Skip to main content
NetScriptdocs Search docs ⌘K v0.0.9
Browse documentation
View as Markdown

Orchestration with Aspire

This page explains why a NetScript app needs an orchestrator, how Aspire generates the resource graph from your plugins instead of having you hand-wire it, and what one aspire start stands up. With that model, you can reason about the running system instead of treating it as a black box.

Resource graph
orders plugin
starts
starts
starts
starts
starts
database connection
database connection
database connection
KV cache connection
KV cache connection
KV cache connection
observes
observes
observes
observes
observes
Postgres
resource
Redis cache
resource
(default --cache-backend)
HTTP API service
worker
(background processor)
saga-runner
(background processor)
Aspire AppHost
(declares & starts resource graph)
Aspire Dashboard
(telemetry / logs / traces)
One aspire start derives a coherent resource graph from your plugins, resolves the wiring between resources, and surfaces the whole thing in a dashboard.

Why an orchestrator

Running a multi-plugin NetScript project locally means running a small fleet, not one server:

  • An example oRPC service (defineService) on its assigned port.
  • A Fresh dashboard app.
  • Each runtime plugin's HTTP API: workers-api, sagas-api, triggers-api, and auth-api on their assigned high-range ports, plus the durable-streams runtime on its assigned port.
  • Each plugin's isolated background processors: the workers and sagas runners and the triggers processor. They run as separate executables, not as threads inside the API.
  • The infrastructure they all depend on: a database (Postgres is the recommended engine; mysql, mssql, or sqlite via --db) and a shared cache (redis by default, or garnet or deno-kv via --cache-backend).

Standing that up by hand is the integration tax. You start each process in dependency order, hand each one its connection strings, tell each one where its neighbours live, and tear it all down afterwards. Get it wrong and you meet the usual distributed-dev failures: a service that starts before its database, a processor pointed at the wrong cache, a plugin that cannot find the sibling it calls. The framework adopts an orchestrator to remove that tax.

The unit of a NetScript app is the resource graph, not the process. Each plugin brings an HTTP service, its own isolated background workers, and its infrastructure needs. Aspire lets you declare that graph once and boot it as a whole. Aspire computes the wiring (the database URL the users service needs, the cache endpoint the workers runtime needs, the cross-reference one plugin holds to another) and injects it as environment variables, so no process has to discover its neighbours at runtime.

The generated AppHost

The AppHost is a small TypeScript/Node program scaffolded at aspire/apphost.mts, and it is the entry point aspire start executes. It builds an Aspire builder, hands it your project's appsettings.json, and runs the resulting graph.

TypeScript
aspire/apphost.mts (generated)TypeScript
// aspire/apphost.mts (generated by `netscript init`)
import { createBuilder } from './.aspire/modules/aspire.mts';
import { createNetScriptAppHost } from './.helpers/index.mts';

// 1. Build an Aspire builder (SDK modules restored by `aspire restore`).
const builder = await createBuilder();

// 2. Translate appsettings.json + plugin contributions into a resource
//    graph: db, cache, services, plugin APIs, background processors, apps.
await createNetScriptAppHost(builder, '../appsettings.json');

// 3. Build the graph and run it (dashboard + every resource).
await builder.build().run();

aspire/aspire.config.json (generated)JSON
{
  "appHost": {
    "path": "apphost.mts",
    "language": "typescript/nodejs"
  },
  "sdk": {
    "version": "13.5.3"
  },
  "profiles": {
    "https": {
      "applicationUrl": "https://localhost:0;http://localhost:0",
      "environmentVariables": {
        "ASPIRE_DASHBOARD_OTLP_HTTP_ENDPOINT_URL": "http://localhost:0",
        "ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true",
        "ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS": "true",
        "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:0"
      }
    }
  },
  "packages": {
    "Aspire.Hosting.PostgreSQL": "13.5.3",
    "Aspire.Hosting.Redis": "13.5.3",
    "Aspire.Hosting.Browsers": "13.5.3-preview.1.26425.3"
  }
}

Two facts about the AppHost contradict what people expect from Aspire's .NET AppHost:

  • It uses an isolated TypeScript/Node runtime. aspire.config.json declares language: "typescript/nodejs" and appHost.path: "apphost.mts". The AppHost runs on its own Node.js runtime inside aspire/, with its own package.json and .aspire/ SDK modules, so the Node dependency graph never leaks into the Deno workspace at the project root. You author NetScript in Deno and write no C#.
  • The graph is derived, not hand-written. You do not edit apphost.mts to add a service. You declare infrastructure, services, plugins, and processors in appsettings.json, and each plugin contributes its own resources programmatically. createNetScriptAppHost reads the config, runs the contributions, and registers each resulting resource.

Plugin contributions

You never list processes by hand. A NetScript plugin can declare an Aspire contribution, and the AppHost asks every installed plugin to contribute its own slice of the graph. The contract lives in @netscript/aspire and is deliberately small.

A plugin's contribution extends AspireNSPluginContribution. It names itself and, given a builder and a context, returns the resources it wants in the graph:

TypeScript
// plugins/<name>/src/aspire-contribution.ts (conceptual shape)
import { AspireNSPluginContribution } from "@netscript/aspire/public";
import type { AspireBuilder, AspireResource, ContributionContext } from "@netscript/aspire/application";

class WorkersContribution extends AspireNSPluginContribution {
  readonly pluginName = "@netscript/plugin-workers";

  // Push this plugin's API + background processor into the builder.
  contribute(builder: AspireBuilder, ctx: ContributionContext): readonly AspireResource[] {
    // ... register a deno-service (the API) and a deno-background (the processor)
    return [/* AspireResource[] */];
  }

  // Optional: extra environment this contribution needs.
  declareEnv(ctx: ContributionContext) { return {}; }
}

Health probes come from scaffold capability and healthEndpoint metadata; the child health contract defines the vocabulary.

On the host side, composeAppHost({ builder, context, plugins }) walks the plugin manifests, finds the ones that declare an aspire contribution, instantiates each, and returns the collected resources together with a ContributionRegistry keyed by pluginName. A duplicate plugin name throws DuplicateContributionError, so the graph is checked for duplicates.

Use @netscript/aspire/application when you author focused composition modules. When an application or plugin prefers one entrypoint for all configuration, composition, type, and testing exports, @netscript/aspire/public is the supported production aggregate (import { composeAppHost } from "@netscript/aspire/public"). The root export @netscript/aspire is reserved for diagnostics (inspectAspire). @netscript/aspire/schema also generates a JSON Schema for editor validation of appsettings.json; see the Aspire reference.

Every resource a contribution returns has one of a small, closed set of kinds:

AspireResource — what a plugin contribution returns
Name · TypeDescription
namestring Resource name in the AppHost graph (the label you see in the dashboard).
kindAspireResourceKind One of: deno-service, deno-background, container, database, cache. The closed set keeps the graph easy to reason about.
portnumber? TCP port the resource exposes, when applicable (services and plugin APIs; containers and processors may omit it).
metadataRecord<string, unknown>? Adapter-specific extras the builder backend understands.

So the AppHost is generated in a strong sense: the graph is assembled at boot from the plugins you installed. Add the sagas plugin and its sagas-api and supervisor processor appear; remove it and they disappear, with no edit to apphost.mts. The scaffold writes a thin register-*.mts helper layer (register-infrastructure.mts, register-services.mts, register-plugins.mts, register-background.mts, register-apps.mts, register-tools.mts) so that each resource class goes through the same builder.addExecutable(...) path, with permissions, working directory, HTTP endpoint, and OTEL environment resolved from config. The content of the graph still comes from your plugin set. This is the orchestration side of the plugin system: the plugin that registers routes, a schema slice, and background work also declares how it appears in the resource graph.

Service discovery

Resources also need wiring. A plugin API may call a sibling plugin's HTTP endpoint, a service may depend on another service, and a processor may need the database and the cache. NetScript expresses those needs as references on the config entry, and Aspire resolves them into injected environment variables, so each process starts with its neighbours' addresses already set. @netscript/aspire extracts these dependencies from each entry:

Reference fields on a resource entry (resolved at compose time)
Name · TypeDescription
ServiceReferencesstring[] Other services this resource calls. extractServiceReferences deduplicates repeated entries.
PluginReferencesstring[] Plugin APIs this resource calls. extractPluginReferences returns them for endpoint wiring (e.g. workers-api → sagas-api).
RequiresDbboolean Whether the resource needs the Postgres connection. extractDependencies normalizes it (default false).
RequiresKvboolean Whether the resource needs the Redis/KV connection. Normalized the same way (default false).

Endpoints only exist once resources are created, so the wiring happens in two passes. The first pass creates every resource; the second resolves each reference against the now-known graph and injects it. In the generated builder, that resolution is the equivalent of getEndpoint('http') plus withEnvironment(...) for cross-references, and the database and cache connection strings for the RequiresDb and RequiresKv flags. By the time a process's entry point runs, the URLs it needs are in Deno.env. It never discovers anything at runtime, which is why your handler code has no service-registry client.

Plain text
                          aspire start  (from aspire/)
                                 │
                                 ▼
              ┌──────────────────────────────────────────┐
              │  createNetScriptAppHost(appsettings.json) │
              │  + composeAppHost(plugin contributions)   │
              └──────────────────────────────────────────┘
                                 │  pass 1: create every resource
   ┌─────────────────────────────┼─────────────────────────────────────┐
   ▼                             ▼                                       ▼
(1) dashboard OTLP        (2) infrastructure                   (4) services
    allocated endpoints           ├─ postgres  (Container)           └─ users (service)
                              └─ redis     (Container, cache)
                                 │
                                 ▼  pass 2: resolve references → inject env
    ┌──────────────────────────────────────────────────────────────────────────────┐
    │ (5) plugin APIs  workers-api        sagas-api        triggers-api               │
    │     auth-api         streams (port)                                             │
    │ (6) background processors: workers/runtime.ts, sagas/runtime.ts;                    │
    │     triggers/runtime.ts                                 │
    │ (7) apps:  dashboard (Fresh)        (8) tools                                   │
    └──────────────────────────────────────────────────────────────────────────────┘

Infrastructure comes up first because everything else depends on it, and references resolve only after the resources they point at exist. The full port map for every runtime resource is in the Aspire reference; treat it as canonical and this page as orientation.

The resource graph a single aspire start brings up
Name · TypeDescription
aspire (dashboard)the URL Aspire prints The Aspire dashboard. The generated local profile allows anonymous dashboard access. Live resource list, logs, structured traces, and the OTLP collector (the OTLP URL Aspire prints) surface here.
postgresContainer Provisioned via Docker. The recommended engine is Postgres (swap to mysql / mssql — also Containers — or file-backed sqlite, which has no container, via --db), persistent (DataPath .data/postgres). The database that netscript db commands target — reachable only once Aspire is up.
redisContainer (cache) Redis cache — the default --cache-backend; Redis-compatible. Backs KV/queue workloads for the runtime plugins. Swap to garnet (also a Container) or app-level deno-kv via --cache-backend.
usersassigned port Example oRPC service (defineService). Routes /api/v1/users/* and the RPC surface at /api/rpc/*.
workers-apiassigned port Workers plugin API. /api/v1/workers/{jobs,executions,tasks,seed}; trigger via POST /api/v1/workers/jobs/{id}/trigger.
sagas-apiassigned port Sagas plugin API. /api/v1/sagas/{sagas,instances,publish} plus liveness at /health/live.
triggers-apiassigned port Triggers plugin API: typed oRPC management with raw HMAC webhook ingress. POST /api/v1/webhooks/inbound/generic, GET /api/v1/events.
auth-apiassigned port Auth plugin oRPC service. /api/v1/auth/{signin,callback,signout,sessions/revoke,session,me} with one active backend (NETSCRIPT_AUTH_BACKEND).
streamsassigned port Durable-streams producer runtime. Served as its own Aspire Deno service; workers/auth/sagas mirror execution state into it.
workers / sagas / triggersbackground processors Separate from the APIs: the scaffold emits workers/runtime.ts, sagas/runtime.ts and triggers/runtime.ts. Declared under appsettings BackgroundProcessors.

Customizing the AppHost

Once the graph runs, the recurring question is which change needs which action. The register-*.mts helper layer is generated from netscript.config.ts and appsettings.json, so most edits are a config change plus a regenerate, not a hand-edit of the AppHost. The regenerate command is netscript service generate; it rewrites only the Aspire helper files, never your service code.

Which change needs which action
Name · TypeDescription
Handler / service / app codehot or restart resource Apps and background processors scaffold with Deno watch mode, so they reload on save. A plain service restarts from the dashboard. No regenerate, no AppHost restart.
Env / Permissions / Port / Workdir on a resourcegenerate + restart AppHost Edit the resource's section in netscript.config.ts, run netscript service generate to rewrite the register-*.mts layer, then restart aspire start.
A reference: ServiceReferences / pluginReferences / dependsOngenerate + restart AppHost Same flow. Pass 2 only re-resolves and re-injects services____http__0 on the next aspire start — a declared-but-not-generated reference does nothing.
Add / remove a plugin, or a new appsettings resourcegenerate + restart AppHost netscript plugin install/remove (or a hand-added resource) changes the graph; the resource only joins on the next generate + aspire start.
An injected env value Aspire owns (OTEL_*, a connection string)restart the resource Environment is read once at process start, so bounce the affected resource for the new value to take effect.

Launch permissions for native drivers

A resource's permission flags are set at launch. They are separate from the per-task permissions you tighten inside a worker, which Restrict worker task permissions covers. Launch permissions matter when a plugin loads a native (FFI) database driver, such as the native libSQL/Turso client the workers runtime can use for per-channel storage. Without FFI access the process crashes at import with NotCapable: Requires ffi access, so the workers background processor launches with an explicit permission set that includes --allow-ffi and --allow-sys:

plugins/workers/src/aspire/workers-contribution.tsTypeScript
// plugins/workers/src/aspire/workers-contribution.ts — the background launch set
const WORKERS_BACKGROUND_PERMISSIONS = [
  '--unstable-kv',
  '--allow-net',
  '--allow-env',
  '--allow-read',
  '--allow-write',
  '--allow-run',
  '--allow-sys',
  '--allow-ffi', // native FFI drivers (e.g. libSQL/Turso) load here
] as const;

If your plugin or service pulls in a native driver, give its resource the matching --allow-ffi (and any --allow-sys) flag through its contribution's launch permissions. A missing flag shows up only at runtime as an FFI capability crash, not at generate time.

The dashboard

When aspire start finishes booting, open the dashboard at the URL it prints. The dashboard covers the whole running graph:

  • Resources: every container and executable above, with status, endpoints, and environment.
  • Console logs: stdout and stderr per resource, so a failing background processor is one click away instead of buried in a terminal.
  • Structured logs and traces: Aspire starts an OTLP collector at the OTLP URL Aspire prints. The spans and structured logs your handlers emit land here, correlated by traceparent, so a request that fans out across services is one trace instead of scattered log lines.

Aspire already knows the topology, every resource and its OTEL environment, so it can attach telemetry to that topology. Each resource starts with its OTEL_SERVICE_NAME and an OTEL_EXPORTER_OTLP_ENDPOINT pointed at the dashboard collector (the OTLP URL Aspire prints, http/protobuf). Job dispatch, job execution, scheduler runs, and subprocess task continuation therefore emit OpenTelemetry spans that appear here with no extra wiring, and the trace context reaches worker subprocesses over W3C traceparent. Inside a handler, the scaffold's createJobTools(ctx) helpers add events, progress, and child spans to the active job trace. Observability covers the full framework-and-handler trace path.

HTTP/2 and TLS

NetScript service listeners serve plaintext HTTP/1.1 by default. HTTP/2 is opt-in through TLS: Deno.serve negotiates h2 over ALPN as soon as the listener has a certificate and key, so you get HTTP/2 by giving the service TLS material. Both ways below switch the listener banner from http to https:

TypeScript
Inline TLS on serve()TypeScript
// Pass cert/key PEM material as ServeOptions.tls. Deno then negotiates HTTP/2
// over ALPN for clients that support it (HTTP/1.1 stays available as fallback).
import { createService } from '@netscript/service';
import type { ServiceTlsOptions } from '@netscript/service';

const tls: ServiceTlsOptions = {
  cert: await Deno.readTextFile('cert.pem'), // PEM certificate chain
  key: await Deno.readTextFile('key.pem'),   // PEM private key
};

await createService(router, { name: 'users' })
  .withHealth()
  .serve({ port: 3001, tls }); // note: your scaffold's port will differ

Env pair (no code change)Shell
# When ServeOptions.tls is absent, the listener falls back to this env pair.
# BOTH must be set — one alone is ignored and the service stays plaintext.
NETSCRIPT_TLS_CERT_FILE=cert.pem \
NETSCRIPT_TLS_KEY_FILE=key.pem \
  deno run --allow-net --allow-read --allow-env services/users/main.ts

# With both present the service serves HTTPS + HTTP/2 — confirmed with `curl --http2`.

The --no-aspire escape hatch

Aspire is the default and recommended local path, but it is not mandatory. netscript init takes a --no-aspire flag (netscript init my-app --no-aspire) that skips the orchestration layer entirely: no aspire/ folder, no AppHost to provision infrastructure, and no dashboard. You start the generated Deno processes yourself and provide your own infrastructure connection strings.

Shell
Default — with AspireShell
netscript init my-app --db postgres --service --service-name users --yes

# Step 2: orchestration brings up Postgres + Redis + every process.
cd aspire && aspire restore   # once
aspire start                    # dashboard at the URL Aspire prints

# Step 3: database commands now work (provisioned through Aspire).
netscript db init --name init

Escape hatch — --no-aspireShell
# Scaffold WITHOUT the orchestration layer. No aspire/ folder is created.
netscript init my-app --db postgres --no-aspire --yes

# There is no `aspire start`. Start processes yourself:
deno task --cwd apps/dashboard dev

# You now own infrastructure: bring your own Postgres + cache and supply
# connection strings to each process. `netscript db` has no AppHost to
# provision through, so manage migrations against your own database URL.

When to opt out

  • A deploy target that does its own orchestration. Kubernetes, Nomad, a managed PaaS, or a Docker Compose file you already maintain owns process lifecycle and service discovery, so a second orchestrator on top is redundant. This is the main production case.
  • A constrained or air-gapped environment. No Docker daemon, or a policy against running the Node AppHost runtime. You run Deno processes directly against externally managed infrastructure.
  • A single-purpose slice. You only want the Fresh app, or one service, with no database or cache, and the full graph would be overhead.

For local development of a full multi-plugin app, opting out is almost always the wrong trade: you would rebuild by hand the wiring the contributions generate.

Aspire in production

Aspire is the local-development orchestrator. Its job is to turn git clone → aspire start into a complete, observable, correctly wired stack on one machine. It is deliberately not:

  • A production deployment system. The AppHost provisions Postgres and Redis as local Docker containers for development. They are not your production database or cache, and the AppHost is not a cluster scheduler. In production, point processes at managed or clustered infrastructure and let your platform own lifecycle and scaling.
  • A replacement for your orchestrator of record. Under Kubernetes or a PaaS that already handles discovery, health, and restarts, the same resource model is redundant. That is why --no-aspire is a first-class exit.

The default path has three more trade-offs:

  • A second runtime in the tree. The AppHost is Node/TypeScript while your app is Deno. The isolation keeps the two dependency graphs apart, at the cost of two answers to "what runtime is this?" in one repo.
  • Docker is a hard dependency of the happy path. Without a Docker daemon the default workflow does not start; that is when --no-aspire plus your own infrastructure earns its place.
  • Remote Docker daemons are unsupported. plugin doctor exits with an error when the daemon is remote: published loopback ports belong to the daemon host, while the AppHost probes its own localhost. Use a local daemon or run the AppHost on the Docker host. Aspire's AppHost:ContainerHostname controls container-to-host discovery, not access to remote loopback-published ports.
  • The wiring is implicit. The two-pass reference resolution is invisible at authoring time, so inspect the generated environment variables and the resource graph when you debug service discovery.

Next: Deploy locally with Aspire walks through the full local flow step by step.

Search all documentation

Type a term to search the documentation.