@streamsy/core 0.15.0 → 0.17.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/README.md CHANGED
@@ -1,297 +1,17 @@
1
1
  # @streamsy/core
2
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. Requires
6
- `effect@4.1.5`.
3
+ An Effect implementation of the [Durable Streams](https://durablestreams.com) protocol. Provides typed stream declarations, Durable State streams, frontier streams, an in-process memory host, HTTP protocol routes, and a remote HTTP/SSE client.
7
4
 
8
5
  ```sh
9
6
  bun add @streamsy/core effect
10
7
  ```
11
8
 
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
- ## Materialize State
163
-
164
- `DurableState.materialize(state, events)` folds State items into one map of rows
165
- for each collection. Start from `DurableState.materialized(address)`. It applies
166
- the State rules: an upsert sets a row, a delete removes it, `reset` clears every
167
- collection, and `snapshot-end` removes each row that the snapshot did not name. A
168
- snapshot can span several calls. The input state does not change.
169
-
170
- ```ts
171
- let state = DurableState.materialized(Board.at({ id }));
172
-
173
- for (const batch of batches) state = DurableState.materialize(state, batch.items);
174
-
175
- state.rows.card; // ReadonlyMap<string, Card>
176
- ```
177
-
178
- ## Wake streams
179
-
180
- A wake stream indexes the writes of a family of streams. It is a State stream
181
- with one row for each source stream: `{ stream, offset, closed? }`, keyed by the
182
- source id. The row holds the source tail after its last write. A client follows
183
- one wake stream and reads only the source streams that moved past its saved
184
- cursors.
185
-
186
- ```ts
187
- class Files extends Streamsy.state<Files>()("App/Files", "folders/:folderId/files", {
188
- params: { folderId: FolderKey },
189
- collections: { file: { schema: FileValue, key: "path" } },
190
- }) {}
191
-
192
- class UserWake extends Streamsy.wake<UserWake>()("App/UserWake", "users/:user/wake", {
193
- params: { user: UserKey },
194
- }) {}
195
-
196
- const streams = Streamsy.group(Files, UserWake);
197
- ```
198
-
199
- A wake declaration names no sources. A projection writes its rows:
200
- `Projection.wake` from `@streamsy/projection` links one source stream to one
201
- wake stream, with params of its own. The source and the wake stream can live on
202
- different storage owners. See the projection README.
203
-
204
- `Streamsy.wake` is a preset for `Streamsy.state` with `wakeCollections`.
205
- It has the normal State service, including `create`, `append`, `remove`,
206
- `read`, `follow`, `fold` and `collect`. Use `DurableState.materialize` to fold
207
- its events into the latest rows.
208
-
209
- `Projection.wake` creates a missing output on its checkpoint owner. On another
210
- owner, the wake stream must already exist. Its owner calls the normal State
211
- service's `create` before the first append. A repeated create answers
212
- `Exists`:
213
-
214
- ```ts
215
- const start = Effect.gen(function* () {
216
- const wake = yield* UserWake;
217
- yield* wake.create({ user });
218
- });
219
- ```
220
-
221
- HTTP access is mount policy. Choose read access for projection outputs on a
222
- public mount and full access on an internal mount where producers create and
223
- append them:
224
-
225
- ```ts
226
- Http.routes(streams, {
227
- prefix: "/streams",
228
- access: (stream) => (stream === UserWake ? "read" : "full"),
229
- });
230
- Http.routes(Streamsy.group(UserWake), { prefix: "/__wake", access: "full" });
231
- ```
232
-
233
- `Streamsy.followWake` turns wake batches into actions:
234
-
235
- ```ts
236
- const actions = Streamsy.followWake(
237
- UserWake,
238
- { user },
239
- {
240
- from: saved.wake,
241
- cursors: saved.cursors,
242
- },
243
- );
244
- // Each batch: { items: WakeItem[], offset }. An item is Dirty, Removed, Reset or Snapshot.
245
- // Save each source cursor first, then save `offset` as the wake cursor.
246
- ```
247
-
248
- A client with its own HTTP reader does not need a `RemoteStreams` stack.
249
- It decodes each page with `Streamsy.WakeMessage` and calls the pure
250
- `Streamsy.wakeActions`, which `followWake` also uses:
251
-
252
- ```ts
253
- const decodePage = Schema.decodeUnknownEffect(Schema.Array(Streamsy.WakeMessage));
254
-
255
- const handle = (page: unknown, snapshot?: ReadonlySet<StreamId>) =>
256
- Effect.map(decodePage(page), (events) =>
257
- Streamsy.wakeActions(events, { cursors: saved.cursors, snapshot }),
258
- );
259
- // { items, snapshot }: items as above. Pass snapshot to the call for the next page.
260
- ```
261
-
262
- A wake row lags its source by one projection pass, on the same owner and on
263
- another one. The client reads each source to its tail, so the lag costs
264
- latency only.
265
-
266
- A wake row relies on append-only streams. The `offset` of a source only goes up,
267
- so a client compares it with its saved cursor. Never reuse a source id: do not
268
- create a stream again under the id of a removed or expired stream. The new
269
- stream starts at a lower offset, and a client with a saved cursor skips its
270
- items. The projection also treats a gone source as removed for good.
271
-
272
- ## Local commit events
273
-
274
- `Storage.committed` is a scoped
275
- `Effect<PubSub.Subscription<ReadonlyArray<StreamId>>>`. The subscription exists
276
- when the effect returns, so a later commit always lands in it. Memory and SQL
277
- storage publish the ids touched by each successful local commit after it
278
- commits. Rolled-back writes publish nothing. Each subscriber gets its own
279
- subscription, which its scope releases. Events are best effort and have no replay; commits from
280
- another process do not appear. `Storage.changes(id)` remains the per-stream
281
- read notification source. Custom storage adapters must provide `committed`.
282
-
283
9
  ## Documentation
284
10
 
285
- - [Declare streams](https://streamsy.dev/docs/streams/declare)
286
- - [Choose storage](https://streamsy.dev/docs/storage)
287
- - [Expose the stream protocol](https://streamsy.dev/docs/servers/protocol)
288
- - [Connect to a remote server](https://streamsy.dev/docs/servers/remote)
289
- - [Write a storage adapter](https://streamsy.dev/docs/storage/adapter)
290
-
291
- Source: https://github.com/gingerhendrix/streamsy
11
+ - [Streams guide](https://streamsy.dev/docs/streams/declare)
12
+ - [API reference](https://streamsy.dev/docs/reference/core/streamsy)
13
+ - [Streamsy docs](https://streamsy.dev)
292
14
 
293
15
  ## License
294
16
 
295
17
  MIT
296
-
297
- An address names one stream. It holds no data. It is not an Effect `Ref`.
@@ -1,4 +1,4 @@
1
- import { S as InvalidCreateRequest } from "./streamsy-HKC10a_V.js";
1
+ import { w as InvalidCreateRequest } from "./streamsy-DiAjZWlT.js";
2
2
  import { Array, DateTime, Effect, Option, Result } from "effect";
3
3
  // src/policy/message-framer.ts
4
4
  /**
@@ -1,2 +1,2 @@
1
- import { $ as streamPath, C as Access, S as read, T as routes, _ as ShutdownSignalService, a as LIVE_SOCKET_PROTOCOL, b as ReadOptions, c as LiveControlFrame, d as controlFrame, et as HttpOptions, f as isLiveUpgrade, g as ShutdownSignal, h as upgradeRequired, i as LIVE_PONG, l as LiveOpenFrame, m as openFrame, n as HttpLiveMode, o as LiveBatch, p as nextCursor, r as LIVE_PING, s as LiveCloseCode, tt as app, u as closeCodeForStatus, v as layerShutdownSignal, w as RoutesOptions, x as checkReadOptions, y as securityHeaders } from "../index-BtVxu6VJ.js";
1
+ import { $ as HttpOptions, C as Access, Q as streamPath, S as read, T as routes, _ as ShutdownSignalService, a as LIVE_SOCKET_PROTOCOL, b as ReadOptions, c as LiveControlFrame, d as controlFrame, et as app, f as isLiveUpgrade, g as ShutdownSignal, h as upgradeRequired, i as LIVE_PONG, l as LiveOpenFrame, m as openFrame, n as HttpLiveMode, o as LiveBatch, p as nextCursor, r as LIVE_PING, s as LiveCloseCode, u as closeCodeForStatus, v as layerShutdownSignal, w as RoutesOptions, x as checkReadOptions, y as securityHeaders } from "../index-DIx4D2t0.js";
2
2
  export { type Access, type HttpLiveMode, type HttpOptions, LIVE_PING, LIVE_PONG, LIVE_SOCKET_PROTOCOL, type LiveBatch, LiveCloseCode, type LiveControlFrame, type LiveOpenFrame, type ReadOptions, type RoutesOptions, ShutdownSignal, type ShutdownSignalService, app, checkReadOptions, closeCodeForStatus, controlFrame, isLiveUpgrade, layerShutdownSignal, nextCursor, openFrame, read, routes, securityHeaders, streamPath, upgradeRequired };
@@ -1,3 +1,3 @@
1
- import { a as LIVE_PING, c as LiveCloseCode, d as isLiveUpgrade, f as nextCursor, g as layerShutdownSignal, h as ShutdownSignal, l as closeCodeForStatus, m as upgradeRequired, n as checkReadOptions, o as LIVE_PONG, p as openFrame, r as read, s as LIVE_SOCKET_PROTOCOL, t as app, u as controlFrame, v as streamPath, y as securityHeaders } from "../program-BlfAJNlD.js";
2
- import { n as routes } from "../http-YoA8cUTN.js";
1
+ import { a as LIVE_PING, c as LiveCloseCode, d as isLiveUpgrade, f as nextCursor, g as layerShutdownSignal, h as ShutdownSignal, l as closeCodeForStatus, m as upgradeRequired, n as checkReadOptions, o as LIVE_PONG, p as openFrame, r as read, s as LIVE_SOCKET_PROTOCOL, t as app, u as controlFrame, v as streamPath, y as securityHeaders } from "../program-gGLU50A1.js";
2
+ import { n as routes } from "../http-aCMEaxro.js";
3
3
  export { LIVE_PING, LIVE_PONG, LIVE_SOCKET_PROTOCOL, LiveCloseCode, ShutdownSignal, app, checkReadOptions, closeCodeForStatus, controlFrame, isLiveUpgrade, layerShutdownSignal, nextCursor, openFrame, read, routes, securityHeaders, streamPath, upgradeRequired };
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { F as StreamsReader, I as StreamsWriter, i as checkStreams } from "./streamsy-HKC10a_V.js";
3
- import { _ as discardRequestBody, a as LIVE_PING, c as LiveCloseCode, d as isLiveUpgrade, f as nextCursor, g as layerShutdownSignal, h as ShutdownSignal, i as requestUrl, l as closeCodeForStatus, m as upgradeRequired, n as checkReadOptions, o as LIVE_PONG, p as openFrame, r as read, s as LIVE_SOCKET_PROTOCOL, t as app, u as controlFrame, v as streamPath, y as securityHeaders } from "./program-BlfAJNlD.js";
2
+ import { L as StreamsReader, R as StreamsWriter, i as checkStreams } from "./streamsy-DiAjZWlT.js";
3
+ import { _ as discardRequestBody, a as LIVE_PING, c as LiveCloseCode, d as isLiveUpgrade, f as nextCursor, g as layerShutdownSignal, h as ShutdownSignal, i as requestUrl, l as closeCodeForStatus, m as upgradeRequired, n as checkReadOptions, o as LIVE_PONG, p as openFrame, r as read, s as LIVE_SOCKET_PROTOCOL, t as app, u as controlFrame, v as streamPath, y as securityHeaders } from "./program-gGLU50A1.js";
4
4
  import { Array, Effect, Option } from "effect";
5
5
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
6
6
  // src/http/routes.ts