Skip to main content

Built and signed on GitHub Actions

Works with
This package works with DenoIt is unknown whether this package works with Cloudflare Workers, Node.js, Bun, Browsers
It is unknown whether this package works with Cloudflare Workers
It is unknown whether this package works with Node.js
This package works with Deno
It is unknown whether this package works with Bun
It is unknown whether this package works with Browsers
•JSR Score100%•
License
Apache-2.0
•
Downloads410/wk
•
Publisheda day ago (0.0.10)

The Durable Streams protocol plugin for NetScript: one install wires an ephemeral streaming service, stream CLI commands, and Aspire orchestration — with file storage as an explicit opt-in.

@netscript/plugin-streams

JSR CI Docs

The Durable Streams protocol plugin for NetScript: one install wires an ephemeral streaming service, stream CLI commands, and Aspire orchestration — with file storage as an explicit opt-in.

Every real app grows event flows — workers publish executions, auth publishes sessions, your own code publishes domain changes — and someone has to run the pipe they all flow through. @netscript/plugin-streams ships that pipe as one declarative manifest: netscript plugin install stream scaffolds the Durable Streams service into your workspace and adds it to your Aspire AppHost. Memory storage supports replay only during the current service process. It loses every stream on restart; the protocol name does not promise persistent storage.

The plugin is deliberately self-contained: it needs neither Postgres nor Deno KV, so it installs without provisioning any database.

Durability is opt-in. The scaffolded service reads STREAMS_DATA_DIR. When it is unset — which is the default the scaffold installs — the service stores events in memory only, so they do not survive a restart. Set STREAMS_DATA_DIR=<path> to switch to file-backed storage. The service logs a warning at startup whenever it comes up ephemeral. File mode requires an existing, writable directory and a successful startup write/read probe; a bad opt-in fails startup.

Note also that the framework prepends /v1/stream/netscript to the configured streamPath: streamPath: '/workers/executions' resolves to <base>/v1/stream/netscript/workers/executions. Calling the configured path verbatim returns 404. The producer and schema primitives live in @netscript/plugin-streams-core — this package wires the streams service into a NetScript host.

Host-owned startup

Import startStreamsService from @netscript/plugin-streams/service to choose native auth, CORS and listener options. This singular import is inert. Required auth is validated before runtime I/O; guarded raw stream routes need native authn.protect: ['/'] or the intended stream prefix. Supply cors.origin for an exact allowlist, or omit it for NETSCRIPT_CORS_ORIGINS. The factory retains stream protocol headers/methods and returns a native RunningService; stop() drains its front listener and stops its owned upstream. Host serve.port, including zero, takes precedence over PORT and STREAMS_PORT; serve.hostname, TLS and signal options remain native.

The plural @netscript/plugin-streams/services entrypoint retains its existing start-on-import public/wildcard policy and delegates to the same factory. The full typed recipe and adoption boundary are in Host workers and streams services.

Storage contract and operations

The runtime manifest records metadata.storage.defaultMode = "memory", ephemeral = true, and the file opt-in environment key. The installer manifest description declares the ephemeral default and the STREAMS_DATA_DIR opt-in. /health includes a checks entry named streams-storage with storage.mode (memory or file), durable, and probe (not-applicable or passed). Healthy memory mode means the service is reachable; it explicitly reports durable: false. Local directory paths are omitted from health.

The generated AppHost can provision storage explicitly. Add DataDirectories to the existing NetScript.Plugins.streams entry in appsettings.json, then run netscript generate aspire:

{
  "DataDirectories": {
    "STREAMS_DATA_DIR": ".netscript/data/streams"
  }
}

On AppHost start, the generated registration creates the directory (including missing parents) and passes its absolute path through STREAMS_DATA_DIR before streams starts. Relative paths resolve from the resource's Workdir (the project root for the default streams resource). Add .netscript/data/ to .gitignore. Existing contents are retained across resource and AppHost restarts. There is no directory provisioning or file-storage binding when DataDirectories is omitted. Directory bindings override a conflicting Environment value. Directory-creation failure (for example, a file at the target or an unwritable parent) aborts AppHost composition. If an existing directory cannot pass the streams startup write/read probe, the streams service fails startup before health can claim file mode.

Programmatic hosts can declare the same opt-in using new StreamsAspireContribution({ dataDir: '.netscript/data/streams' }) from @netscript/plugin-streams/aspire. Its service spec carries dataDirectories and the environment binding for the host's Aspire builder; the contribution itself does no filesystem I/O.

The existing Environment.STREAMS_DATA_DIR setting still forwards a manually provisioned directory without creating it. In deployments, mount persistent writable storage separately: creating a folder in a disposable container filesystem is not a persistence guarantee. Removing both the DataDirectories binding and any manual environment opt-in restores ephemeral storage on the next AppHost generation/start; retained files are not deleted. Do not share a directory between AppHosts.

The process-boundary acceptance test in services/src/tests/storage-restart_test.ts uses DurableStreamProducer upserts and a delete, flushes, stops the service process, restarts it on the same directory, and compares all HTTP events. Its memory control gets 404 after restart. This proves orderly process restart, not power-loss durability, concurrent writers, replication, or automatic backup. Only one service process may own a data directory.

Retention is unbounded unless an explicit stream expiry/deletion policy is configured. A producer entity delete appends a tombstone; it does not compact retained history. Protocol TTL is a sliding inactivity window renewed by reads/appends; absolute expiry is fixed. Either expires the whole stream, not individual records. Use absolute expiry or scheduled whole-stream/day-segment deletion under a background service identity for a hard bound, and monitor disk capacity. Automatic log compaction and archival are not provided.

In file mode, sliding TTL reads renew immediately for live expiry checks. The companion releases a successful GET or SSE delivery only after LMDB has committed the renewal or a later access to that stream. This applies to SSE reads on wakeup, including heartbeat controls. On restart after a process kill on the same boot, the recovered access time for a completed read has zero staleness from coalescing. A read still waiting for persistence when the process exits may need to be retried.

Read renewals use a 25 ms batching interval and keep one pending access per stream. An in-flight batch, scheduler delays and disk I/O can add to read latency. The append's own metadata transaction records its access time. A bare close, including a repeated close, renews in the native close write. A duplicate append that performs no data write uses its own metadata renewal. Append acknowledgements do not wait for the read renewal queue. HEAD and same-stream PUT leave the deadline as it was. Absolute expiry uses the original deadline.

Clean shutdown flushes outstanding renewals. The companion logs and retries renewal failures. A failed batch can fail a pending GET or end its SSE response so a client can retry. Shutdown reports a failed final flush.

Recovery preserves complete native frames and discards an incomplete final frame; truncated writes can lose the final event. Missing segment files can read empty and corrupt LMDB metadata can prevent startup: the startup probe checks directory I/O, not the integrity of every historical record. Do not interpret it as a corruption repair or data-loss guarantee. Restore a known-good backup when recovery fails; preserve a copy of the damaged directory for investigation.

For backup, stop producers and gracefully stop streams, then copy the entire data directory (LMDB metadata and native segment files together). Restore that complete copy into an existing, writable directory with the service stopped, keep the same storage/protocol versions, and verify HTTP replay before resuming producers. Live file copies are not a supported consistent backup. Durable-by-default provisioning and migration remain separate work in #2114.

Durable recovery reads native frame headers through a reusable 64 KiB window. Tail reads seek from recent verified frame boundaries and allocate only the requested complete messages. The recent boundary cache has fixed capacity (32 segments, 128 checkpoints per segment), so retained history does not increase recovery or idle-tail memory. Responses still require memory for the payloads requested by the caller; cold historical offsets may scan earlier framing headers. Partial final headers, payloads, or trailers stop at the last complete native offset, including fork bases.

The service composes the native LMDB store with a local bounded I/O adapter. It preserves the append log format, producer state, fork stitching and JSON response formatting. The adapter checks the upstream storage hooks at construction and scopes them to its subclass and owned store. Upstream tracking: durable-streams/durable-streams#420. Contributors can start at services/src/bounded-file-store.ts; framing and the large-log RSS regression sit beside it.

Why teams use it

  • One manifest, whole capability — streamsPlugin declares the Durable Streams service, contract versions, and Aspire resources as typed contribution axes the host turns into a running process.
  • Explicit storage choice — memory is ephemeral; the opt-in file backend is proven to replay real producer writes after an orderly service process restart.
  • Typed topic definitions — defineStreamTopic describes manifest topics; @netscript/plugin-streams-core defines typed collections and publishes their entity state.
  • An operations CLI — list-topics, inspect, stats, subscribe, add-schema, add-producer, and clear cover inspecting and operating the stream surface.
  • Zero extra infrastructure — no migrations, no KV, no external broker; the service is a standalone utility process Aspire starts with the rest of your app.

Architecture

flowchart LR
    M["streamsPlugin manifest"] --> H["NetScript host<br/>(plugin install + sync)"]
    H --> S["Durable Streams service"]
    P1["workers · sagas · triggers · auth"] -- publish --> S
    P2["Your app code"] -- publish / subscribe --> S
    S --> C["Consumers<br/>(replay + catch-up)"]

Install

From the root of a NetScript project:

netscript plugin install stream --name streams

The plugin owns its setup — the CLI ships no embedded templates. The scaffolder wires the Durable Streams service and Aspire resources into your workspace, then pins the matching @netscript/* versions. No database is provisioned: streams is a self-contained utility.

To consume the plugin programmatically (custom hosts, tests, tooling), add it as a library:

deno add jsr:@netscript/plugin-streams@<version>

The standalone plugin CLI is also directly runnable:

deno x -A jsr:@netscript/plugin-streams@<version>/cli list-topics

Pin <version> to match your installed CLI; bare jsr:@netscript/* specifiers do not resolve on the pre-release line.

Quick example

Install the plugin, then list the topics it serves — the install scaffolds a default notifications stream, so discovery finds it immediately:

$ netscript plugin install stream --name streams
Installed stream plugin "streams" on port <allocated-port>.
Created 2 plugin files.
Regenerated 12 Aspire helper files.

$ deno x -A jsr:@netscript/plugin-streams@<version>/cli list-topics
1 stream topic(s) discovered.
{
  "topics": [
    {
      "name": "/v1/streams/notifications/events",
      "streamPath": "/v1/streams/notifications/events",
      "producerId": "notifications-producer",
      "producerFile": "streams/notifications-stream.ts",
      "collections": []
    }
  ]
}

Breaking migration in 0.0.8

The root no longer exports defineStreamProducer, defineStreamConsumer, StreamProducerHandle, StreamConsumerHandle, StreamUnsupportedOperationError, or unsupportedStreamOperation. defineStreamTopic remains a frozen manifest definition with no IO.

Replace producer imports with defineStreamSchema and createDurableStream (or createServiceStreamProducer for backend services) from @netscript/plugin-streams-core. Convert each topic payload into a collection with a primary key; replace publish(payload) with upsert(collection, payload) or delete(collection, key), then flush and close on shutdown. This publishes entity state, so model generic messages as entities with stable ids if appropriate.

This example requires zod as an installed dependency; defineStreamSchema accepts any Standard Schema validator, so you can use your existing validator instead.

import { createDurableStream, defineStreamSchema } from '@netscript/plugin-streams-core';
import { z } from 'zod';

const schema = defineStreamSchema({
  order: {
    schema: z.object({ orderId: z.string(), total: z.number() }),
    type: 'order',
    primaryKey: 'orderId',
  },
});

const producer = createDurableStream({
  streamPath: '/orders/placed',
  schema,
  producerId: 'orders-service',
});
producer.upsert('order', { orderId: 'order-1', total: 42 });
await producer.flush();
await producer.close();

Replace consumer subscribe(handler) with HTTP/SSE reads of the same stream path. Resolve the URL with buildStreamUrl / getStreamsUrl from @netscript/plugin-streams-core; browser clients can use bindStreamEventSourceV1 from @netscript/fresh/streams to validate named SSE events. Dispose the binding on teardown. There is no in-process topic subscription replacement. See the streams migration guide.

Public surface

Entry What it gives you
. streamsPlugin, defineStreamTopic, topic/schema types, and the manifest type vocabulary
./cli The streams command group (list-topics, inspect, stats, subscribe, …)
./services The Durable Streams service composition
./aspire The streams Aspire contribution for the AppHost
./scaffold The plugin-owned scaffolder netscript plugin install stream executes

The always-current symbol list is deno doc jsr:@netscript/plugin-streams@<version> (pin <version> on the pre-release line, as above).

Docs

Compatibility

The Durable Streams service and CLI require Deno 2.9+. The manifest and topic definitions are plain data and can be imported anywhere TypeScript runs.

License

Apache-2.0 — see LICENSE. Published to JSR with cryptographically verified provenance.

Examples

Load the plugin manifest

import { streamsPlugin } from "@netscript/plugin-streams";

console.log(streamsPlugin.name);
Built and signed on
GitHub Actions

Add Package

deno add jsr:@netscript/plugin-streams

Import symbol

import * as plugin_streams from "@netscript/plugin-streams";
or

Import directly with a jsr specifier

import * as plugin_streams from "jsr:@netscript/plugin-streams@^0.0.10";