@streamsy/core 0.2.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 Gareth Andrew
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,176 @@
1
+ # @streamsy/core
2
+
3
+ An Effect implementation of the [Durable Streams](https://durablestreams.com)
4
+ protocol. Typed stream declarations, stream services, an in-process memory Layer, an
5
+ HTTP app, and a client for remote hosts. Version 0.4.0 requires
6
+ `effect@4.0.5`.
7
+
8
+ ```sh
9
+ bun add @streamsy/core effect
10
+ ```
11
+
12
+ ```ts
13
+ import { Effect, Schema, Stream } from "effect";
14
+ import { MemoryStorage, Streamsy } from "@streamsy/core";
15
+
16
+ class Events extends Streamsy.json<Events>()("Readme/Events", "events", {
17
+ params: {},
18
+ schema: Schema.String,
19
+ }) {}
20
+
21
+ const program = Effect.gen(function* () {
22
+ const events = yield* Events;
23
+ yield* events.create({});
24
+ yield* events.append({}, ["hello"]);
25
+
26
+ return yield* events.read({}).pipe(Stream.runCollect);
27
+ });
28
+
29
+ await Effect.runPromise(program.pipe(Effect.provide(MemoryStorage.layer(Streamsy.group(Events)))));
30
+ ```
31
+
32
+ Compiled source: [packages/core/examples/readme.ts](https://github.com/gingerhendrix/streamsy/blob/effect-first-live-perimeter/packages/core/examples/readme.ts).
33
+
34
+ ## What you get
35
+
36
+ - `StreamAddress` names a stream with its content type and schema, including
37
+ `StreamAddress.state(id, { collections })` for a Durable State stream. One address
38
+ declares several collections keyed by their wire `type`. Its items are the
39
+ changes of those collections and the State control messages `snapshot-start`,
40
+ `snapshot-end` and `reset`. `Streamsy` declares a named stream service from an
41
+ id template.
42
+ - Stream services create, append, read, follow, and remove streams. Create and
43
+ append return `_tag` variants such as `Created` / `Exists` and
44
+ `Appended` / `Duplicate`. Protocol failures are tagged errors
45
+ (`StreamNotFound`, `StreamGone`, `OffsetMismatch`, `AppendConflict`) for
46
+ `Effect.catchTag`.
47
+ - `Streams.follow(address, { offset, retry })` catches up and then waits for new
48
+ items. When a read fails with a `TransportFault` or `StorageFault`, it tries
49
+ that read again from the same offset, so a server restart or network drop
50
+ yields each item once. The default `retry` schedule starts at 200 ms, adds
51
+ jitter, stops growing at 30 s and never gives up. Other failures end the
52
+ stream. One-shot reads are not retried.
53
+ - `Producer.Position` describes a producer tuple. `Producer.next` advances its sequence after acknowledgement.
54
+ - `Streamsy` and storage layers that take a group bind each stream to its backend.
55
+
56
+ ### Producer restarts
57
+
58
+ The protocol does not allocate producer epochs. If a producer cannot recompute
59
+ a payload after restart, persist the payload together with its `producerId`,
60
+ `producerEpoch`, and `producerSeq` before appending. Re-send that same tuple and
61
+ payload after a restart; `Duplicate` then means the earlier send landed.
62
+
63
+ ## Entries
64
+
65
+ | Entry | Contents |
66
+ | ------------------------- | ----------------------------------------------------------------------------------------- |
67
+ | `@streamsy/core` | Streamsy, MemoryStorage, StreamAddress, DurableState, Producer, storage contracts, errors |
68
+ | `@streamsy/core/remote` | `RemoteStreams.layer(streams, { baseUrl })`: the same stream services over HTTP |
69
+ | `@streamsy/core/http` | `Http.routes`, `Http.app`, `Http.read`, and `securityHeaders` |
70
+ | `@streamsy/core/protocol` | StreamsReader, StreamsWriter, Streams, Protocol, StreamRoute, and raw routes |
71
+ | `@streamsy/core/testing` | Vitest contract tests and fault injection for backends |
72
+
73
+ ## Storage and hosts
74
+
75
+ The memory Layer is process-local and not persistent. Its commit boundary copies
76
+ the whole store for each mutation, so one append costs linear time in the number
77
+ of stored messages. It is a development host; for anything that grows, use
78
+ SQLite from [`@streamsy/storage`](https://www.npmjs.com/package/@streamsy/storage),
79
+ on Bun or in a Durable Object.
80
+ Serve `Http.routes` with Effect’s `HttpRouter.serve` or `HttpRouter.toWebHandler`.
81
+ `Http.read(id, options)` reads a resolved stream id; `securityHeaders` supplies the
82
+ shared response headers. [`@streamsy/serve`](https://www.npmjs.com/package/@streamsy/serve)
83
+ provides output routes and host glue.
84
+
85
+ Browsers use the official `@durable-streams/client` and
86
+ `@durable-streams/state` packages directly against any Streamsy host.
87
+
88
+ `MemoryStorage.layer(streams, { readLimit: 1000 })` sets the server catch-up page size.
89
+ Protocol adapters can use `Protocol.layer({ readLimit })` from `@streamsy/core/protocol`. The default is
90
+ 1000 messages; `readNext` returns the whole available tail. Remote clients send
91
+ only an offset and accept the remote server’s page size. Both direct read
92
+ methods reject malformed offsets with `InvalidReadRequest`; accepted offsets
93
+ are canonical tokens, `-1`, and `now` (or an omitted catch-up offset).
94
+
95
+ Producer options and `Producer.Position` use
96
+ `{ producerId, producerEpoch, producerSeq }`. Append results carry
97
+ `producerEpoch` and `producerSeq` when the acknowledgement includes producer
98
+ state. A close-only producer write uses HTTP 204 and decodes as `Duplicate`
99
+ when that state is present. A close on an already closed stream with a fresh
100
+ tuple returns `Appended` without producer state, including retries of that
101
+ unpersisted tuple.
102
+
103
+ `Http.routes(streams, { access: "read", sseDeadlineMs })`, `Http.app`, and `Http.read` accept an SSE lifetime in
104
+ milliseconds. It defaults to 60,000 and closes the body normally at the
105
+ deadline. Each connection draws its own deadline from 90 to 110 percent of
106
+ this value, so connections opened together do not all close together. Each SSE
107
+ batch goes out as one chunk, so the body ends only after a whole batch and its
108
+ control event. Host-forced interruption and client cancellation remain owned by
109
+ the host. Read results include `contentType`; a remote long poll returning 204
110
+ without Content-Type resolves it with HEAD.
111
+
112
+ ## Row changes
113
+
114
+ `DurableState` is exported from `@streamsy/core`. Direct writers and projection
115
+ outputs use it to make row changes for `Streamsy.state` routes.
116
+
117
+ | Change | Call |
118
+ | ------ | --------------------------------------------------------------------- |
119
+ | Upsert | `DurableState.upsert("card", row)` |
120
+ | Delete | `DurableState.remove("card", key)` |
121
+ | Delete | `DurableState.remove("card", key, { oldValue })` (writes `old_value`) |
122
+
123
+ `DurableState.Change<Collections>` checks the collection and row types. Each
124
+ change has a `_tag` of `"Upsert"` or `"Delete"`.
125
+ `DurableState.changes(address, { offset }, changes)` makes the wire events. With
126
+ an `offset`, each event gets that offset and a default `txid`. Projection outputs
127
+ have no source offset. The route's collection names and key fields define the
128
+ Durable State wire events.
129
+
130
+ ## Control messages
131
+
132
+ A State stream can also hold the control messages of the Durable State
133
+ protocol. A control has `headers.control` and an optional `headers.offset`. It
134
+ has no `type` or `key`.
135
+
136
+ | Control | Make it with | A reader should |
137
+ | ---------------- | ------------------------------- | ------------------------------------------------------------- |
138
+ | `reset` | `StreamAddress.reset()` | Clear its rows, then apply the items after it |
139
+ | `snapshot-start` | `StreamAddress.snapshotStart()` | Treat the changes up to `snapshot-end` as a complete snapshot |
140
+ | `snapshot-end` | `StreamAddress.snapshotEnd()` | Close the snapshot |
141
+
142
+ Each constructor takes `{ offset }`. Items of a State address have the type
143
+ `StreamAddress.CollectionsEvent<Collections>`. Narrow an item with
144
+ `StreamAddress.isChange` or `StreamAddress.isControl` before you read `type`,
145
+ `key` or `headers.operation`:
146
+
147
+ ```ts
148
+ for (const item of batch.items) {
149
+ if (StreamAddress.isControl(item)) {
150
+ if (item.headers.control === "reset") rows.clear();
151
+ } else if ("value" in item) rows.set(item.key, item.value);
152
+ else rows.delete(item.key);
153
+ }
154
+ ```
155
+
156
+ `DurableState.changes` and projection outputs accept a control beside row
157
+ changes and write it unchanged. With an `offset`, a control that has no offset
158
+ gets that offset. `Serve.state` serves stored controls as they are. It still
159
+ refuses the `x-streamsy-state-reset: snapshot` request header, because the
160
+ server does not make snapshots.
161
+
162
+ ## Documentation
163
+
164
+ - [Declare streams](https://streamsy.dev/docs/streams/declare)
165
+ - [Layers and storage](https://streamsy.dev/docs/hosting)
166
+ - [Protocol routes](https://streamsy.dev/docs/http/routes)
167
+ - [Remote client](https://streamsy.dev/docs/http/remote)
168
+ - [Write a storage adapter](https://streamsy.dev/docs/hosting/storage-adapter)
169
+
170
+ Source: https://github.com/gingerhendrix/streamsy
171
+
172
+ ## License
173
+
174
+ MIT
175
+
176
+ An address names one stream. It holds no data. It is not an Effect `Ref`.
@@ -0,0 +1,12 @@
1
+ import { DateTime } from "effect";
2
+ // src/policy/cursor-generator.ts
3
+ const CURSOR_EPOCH_MS = DateTime.toEpochMillis(DateTime.makeUnsafe("2024-10-09T00:00:00.000Z"));
4
+ const CURSOR_INTERVAL_MS = 2e4;
5
+ function generateCursor(clock, previous, random = Math.random) {
6
+ const currentInterval = Math.floor((clock.now() - CURSOR_EPOCH_MS) / CURSOR_INTERVAL_MS);
7
+ if (!previous) return String(currentInterval);
8
+ const previousInterval = parseInt(previous, 10);
9
+ if (Number.isNaN(previousInterval) || previousInterval < currentInterval) return String(currentInterval);
10
+ return String(previousInterval + Math.max(1, Math.floor(random() * 180)));
11
+ }
12
+ export { generateCursor as t };
@@ -0,0 +1,2 @@
1
+ import { H as HttpOptions, U as app, V as streamPath, a as securityHeaders, c as read, d as routes, i as layerShutdownSignal, l as Access, n as ShutdownSignal, o as ReadOptions, r as ShutdownSignalService, s as checkReadOptions, u as RoutesOptions } from "../index-C26ncp7Y.js";
2
+ export { type Access, type HttpOptions, type ReadOptions, type RoutesOptions, ShutdownSignal, type ShutdownSignalService, app, checkReadOptions, layerShutdownSignal, read, routes, securityHeaders, streamPath };
@@ -0,0 +1,3 @@
1
+ import { a as ShutdownSignal, c as streamPath, l as securityHeaders, n as checkReadOptions, o as layerShutdownSignal, r as read, t as app } from "../program-DXUjw5B2.js";
2
+ import { n as routes } from "../http-x2IjDHvw.js";
3
+ export { ShutdownSignal, app, checkReadOptions, layerShutdownSignal, read, routes, securityHeaders, streamPath };
@@ -0,0 +1,67 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { A as StreamsReader, i as checkStreams, j as StreamsWriter } from "./streamsy-DJMArv09.js";
3
+ import { a as ShutdownSignal, c as streamPath, i as requestUrl, l as securityHeaders, n as checkReadOptions, o as layerShutdownSignal, r as read, s as discardRequestBody, t as app } from "./program-DXUjw5B2.js";
4
+ import { Array, Effect, Option } from "effect";
5
+ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
6
+ // src/http/routes.ts
7
+ /** The `allow` header for each access level. */
8
+ const allowedMethods = {
9
+ read: "GET, HEAD, OPTIONS",
10
+ append: "GET, HEAD, POST, OPTIONS",
11
+ full: "GET, HEAD, PUT, POST, DELETE, OPTIONS"
12
+ };
13
+ function routes(group, options) {
14
+ const entries = Array.map(group.streams, (stream) => ({
15
+ stream,
16
+ access: typeof options.access === "function" ? options.access(stream) : options.access
17
+ }));
18
+ const settings = options;
19
+ const prefix = settings.prefix?.replace(/\/$/, "") || "/";
20
+ if (!prefix.startsWith("/") || /[?:#*]/.test(prefix) || prefix.includes("//")) throw new RangeError("HTTP prefix must be an absolute literal path");
21
+ const path = streamPath(prefix);
22
+ const program = app({
23
+ ...settings,
24
+ pathPrefix: prefix
25
+ });
26
+ checkStreams(Array.map(entries, (entry) => entry.stream));
27
+ const handler = Effect.gen(function* () {
28
+ const request = yield* HttpServerRequest.HttpServerRequest;
29
+ const url = requestUrl(request);
30
+ const id = url === void 0 ? void 0 : path.strip(url.pathname);
31
+ const entry = Option.getOrUndefined(Array.findFirst(entries, ({ stream }) => id !== void 0 && stream.match(id)));
32
+ if (entry === void 0) {
33
+ yield* discardRequestBody(request);
34
+ return HttpServerResponse.empty({
35
+ status: 404,
36
+ headers: securityHeaders
37
+ });
38
+ }
39
+ const allow = allowedMethods[entry.access];
40
+ if (entry.access !== "full" && !allow.split(", ").includes(request.method)) {
41
+ yield* discardRequestBody(request);
42
+ return HttpServerResponse.empty({
43
+ status: 405,
44
+ headers: {
45
+ ...securityHeaders,
46
+ allow
47
+ }
48
+ });
49
+ }
50
+ const service = yield* entry.stream;
51
+ const response = yield* program.pipe(Effect.provideService(StreamsReader, service.wire), Effect.provideService(StreamsWriter, service.wire));
52
+ return request.method === "OPTIONS" && entry.access !== "full" ? HttpServerResponse.setHeader(response, "access-control-allow-methods", allow) : response;
53
+ });
54
+ return HttpRouter.add("*", prefix === "/" ? "/*" : `/${prefix.slice(1)}/*`, handler);
55
+ }
56
+ // src/http/index.ts
57
+ var http_exports = /* @__PURE__ */ __exportAll({
58
+ ShutdownSignal: () => ShutdownSignal,
59
+ app: () => app,
60
+ checkReadOptions: () => checkReadOptions,
61
+ layerShutdownSignal: () => layerShutdownSignal,
62
+ read: () => read,
63
+ routes: () => routes,
64
+ securityHeaders: () => securityHeaders,
65
+ streamPath: () => streamPath
66
+ });
67
+ export { routes as n, http_exports as t };