@streamsy/core 0.4.0 → 0.6.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
@@ -2,8 +2,8 @@
2
2
 
3
3
  An Effect implementation of the [Durable Streams](https://durablestreams.com)
4
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.1`.
5
+ HTTP app, and a client for remote hosts. Requires
6
+ `effect@4.0.5`.
7
7
 
8
8
  ```sh
9
9
  bun add @streamsy/core effect
@@ -17,12 +17,15 @@ class Events extends Streamsy.json<Events>()("Readme/Events", "events", {
17
17
  params: {},
18
18
  schema: Schema.String,
19
19
  }) {}
20
+
20
21
  const program = Effect.gen(function* () {
21
22
  const events = yield* Events;
22
23
  yield* events.create({});
23
24
  yield* events.append({}, ["hello"]);
25
+
24
26
  return yield* events.read({}).pipe(Stream.runCollect);
25
27
  });
28
+
26
29
  await Effect.runPromise(program.pipe(Effect.provide(MemoryStorage.layer(Streamsy.group(Events)))));
27
30
  ```
28
31
 
@@ -32,8 +35,10 @@ Compiled source: [packages/core/examples/readme.ts](https://github.com/gingerhen
32
35
 
33
36
  - `StreamAddress` names a stream with its content type and schema, including
34
37
  `StreamAddress.state(id, { collections })` for a Durable State stream. One address
35
- declares several collections keyed by their wire `type`. `Streamsy` declares
36
- a named stream service from an id template.
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.
37
42
  - Stream services create, append, read, follow, and remove streams. Create and
38
43
  append return `_tag` variants such as `Created` / `Exists` and
39
44
  `Appended` / `Duplicate`. Protocol failures are tagged errors
@@ -122,6 +127,159 @@ an `offset`, each event gets that offset and a default `txid`. Projection output
122
127
  have no source offset. The route's collection names and key fields define the
123
128
  Durable State wire events.
124
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` opts its output into creation on the first append, including
210
+ on another owner. The owner can call the normal State service's `create` to
211
+ make an empty stream available before that 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
+
125
283
  ## Documentation
126
284
 
127
285
  - [Declare streams](https://streamsy.dev/docs/streams/declare)
@@ -1,5 +1,5 @@
1
1
  import { DateTime } from "effect";
2
- //#region src/policy/cursor-generator.ts
2
+ // src/policy/cursor-generator.ts
3
3
  const CURSOR_EPOCH_MS = DateTime.toEpochMillis(DateTime.makeUnsafe("2024-10-09T00:00:00.000Z"));
4
4
  const CURSOR_INTERVAL_MS = 2e4;
5
5
  function generateCursor(clock, previous, random = Math.random) {
@@ -9,5 +9,4 @@ function generateCursor(clock, previous, random = Math.random) {
9
9
  if (Number.isNaN(previousInterval) || previousInterval < currentInterval) return String(currentInterval);
10
10
  return String(previousInterval + Math.max(1, Math.floor(random() * 180)));
11
11
  }
12
- //#endregion
13
12
  export { generateCursor as t };
@@ -1,2 +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-CFv8vZvy.js";
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-p68har8W.js";
2
2
  export { type Access, type HttpOptions, type ReadOptions, type RoutesOptions, ShutdownSignal, type ShutdownSignalService, app, checkReadOptions, layerShutdownSignal, read, routes, securityHeaders, streamPath };
@@ -1,3 +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-DJ8NpHIf.js";
2
- import { n as routes } from "../http-EnNOUsIK.js";
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-CYtMjdvD.js";
2
+ import { n as routes } from "../http-B10ao6xE.js";
3
3
  export { ShutdownSignal, app, checkReadOptions, layerShutdownSignal, read, routes, securityHeaders, streamPath };
@@ -1,9 +1,9 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { A as StreamsReader, i as checkStreams, j as StreamsWriter } from "./streamsy-OjRubIPC.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-DJ8NpHIf.js";
4
- import { Effect } from "effect";
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { F as StreamsWriter, P as StreamsReader, i as checkStreams } from "./streamsy-D9OCCdw0.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-CYtMjdvD.js";
4
+ import { Array, Effect, Option } from "effect";
5
5
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
6
- //#region src/http/routes.ts
6
+ // src/http/routes.ts
7
7
  /** The `allow` header for each access level. */
8
8
  const allowedMethods = {
9
9
  read: "GET, HEAD, OPTIONS",
@@ -11,7 +11,7 @@ const allowedMethods = {
11
11
  full: "GET, HEAD, PUT, POST, DELETE, OPTIONS"
12
12
  };
13
13
  function routes(group, options) {
14
- const entries = group.streams.map((stream) => ({
14
+ const entries = Array.map(group.streams, (stream) => ({
15
15
  stream,
16
16
  access: typeof options.access === "function" ? options.access(stream) : options.access
17
17
  }));
@@ -23,12 +23,12 @@ function routes(group, options) {
23
23
  ...settings,
24
24
  pathPrefix: prefix
25
25
  });
26
- checkStreams(entries.map((entry) => entry.stream));
26
+ checkStreams(Array.map(entries, (entry) => entry.stream));
27
27
  const handler = Effect.gen(function* () {
28
28
  const request = yield* HttpServerRequest.HttpServerRequest;
29
29
  const url = requestUrl(request);
30
30
  const id = url === void 0 ? void 0 : path.strip(url.pathname);
31
- const entry = entries.find(({ stream }) => id !== void 0 && stream.match(id));
31
+ const entry = Option.getOrUndefined(Array.findFirst(entries, ({ stream }) => id !== void 0 && stream.match(id)));
32
32
  if (entry === void 0) {
33
33
  yield* discardRequestBody(request);
34
34
  return HttpServerResponse.empty({
@@ -53,8 +53,7 @@ function routes(group, options) {
53
53
  });
54
54
  return HttpRouter.add("*", prefix === "/" ? "/*" : `/${prefix.slice(1)}/*`, handler);
55
55
  }
56
- //#endregion
57
- //#region src/http/index.ts
56
+ // src/http/index.ts
58
57
  var http_exports = /* @__PURE__ */ __exportAll({
59
58
  ShutdownSignal: () => ShutdownSignal,
60
59
  app: () => app,
@@ -65,5 +64,4 @@ var http_exports = /* @__PURE__ */ __exportAll({
65
64
  securityHeaders: () => securityHeaders,
66
65
  streamPath: () => streamPath
67
66
  });
68
- //#endregion
69
67
  export { routes as n, http_exports as t };