@streamsy/projection 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
@@ -65,8 +65,9 @@ and checkpoint commit together. External calls are at least once. Memory hosts
65
65
  provide no `Transaction`.
66
66
 
67
67
  `Commit.producer` pins ranges and producer sequences. Retries append with the
68
- same positions; handlers must be deterministic. Foreign outputs must already
69
- exist. Same-owner outputs can be created automatically. There is no atomicity
68
+ same positions; handlers must be deterministic. A missing output on the
69
+ checkpoint's owner is created on the first append. An output on another owner
70
+ must already exist: its owner creates it at start. There is no atomicity
70
71
  across producer outputs. Chain projections for sinks with different guarantees.
71
72
 
72
73
  `Commit.atLeastOnce` pins before processing, so retries keep `unit.key`.
@@ -107,6 +108,65 @@ items. `Streamsy.state` accepts `DurableState.upsert("card", row)` and
107
108
  `DurableState.remove("card", key)` from `@streamsy/core`. Each change names its
108
109
  collection. Two outputs cannot name the same stream or an input.
109
110
 
111
+ ## Wake streams
112
+
113
+ `Projection.wake` writes a `Streamsy.wake` stream from one source stream. It is
114
+ `mapAccumBatch` with `Commit.producer`. Each unit appends one upsert
115
+ `{ stream, offset, closed? }`, so several source writes in one unit fold into
116
+ one row. It reads committed storage, so every write path counts: toolkit calls,
117
+ HTTP, other projections and raw `StreamsWriter` writes.
118
+
119
+ ```ts
120
+ const filesWake = Projection.wake({
121
+ id: "files-wake",
122
+ params: { user: UserKey, folderId: FolderKey },
123
+ input: Files,
124
+ output: UserWake,
125
+ });
126
+ ```
127
+
128
+ Here `Files.at` takes `user` and `folderId`, and `UserWake.at` takes
129
+ `user`. Each Files id supplies both params for attachment. The wake stream can live on another owner. The producer creates it on
130
+ the first append, and a retry answers `Duplicate`, so delivery is effectively
131
+ once for each binding. Rows of one source arrive in source order. A reader that
132
+ comes before the first append gets 404 unless the owner calls the normal State
133
+ service's `create` to make an empty stream available. `Streamsy.wake` is a State
134
+ preset with `wakeCollections`; a `Streamsy.state` declaration with those
135
+ collections also works as the output.
136
+
137
+ | Source event | Wake change |
138
+ | ------------------ | --------------------------------------------- |
139
+ | Append | Upsert with the new tail, one for each unit |
140
+ | Close with a body | Upsert with `closed: true` in the same unit |
141
+ | Close, no body | Upsert with `closed: true` at the same offset |
142
+ | Remove, TTL expiry | State delete of the source id, then `forget` |
143
+ | Create, empty | None until the first append |
144
+
145
+ A removed or expired source answers `StreamGone` or `StreamNotFound`. A
146
+ binding with a checkpoint then appends the delete with its next producer
147
+ sequence and forgets itself. A stream id never returns, so the delete is final.
148
+ A binding with no checkpoint keeps the `history-unavailable` fault, because its
149
+ source never existed for it. A drained closed source reports `source-closed`.
150
+ `Projection.follow` ends when its input closes. Observe a later removal with
151
+ `Projection.attach` or another explicit run.
152
+
153
+ All projections receive terminal outcomes through their input slices. A close
154
+ with no new items still makes one unit with `slice.closed`; the checkpoint
155
+ records the close so subsequent runs do not repeat that empty unit. Batch
156
+ handlers (`process` and `mapAccumBatch`) can react even when `slice.items` is
157
+ empty; per-item handlers have no entries to process.
158
+
159
+ When an input with a checkpoint is confirmed gone, the kernel runs a final
160
+ unit with `slice.gone: true`, then forgets the binding by default. Lost history
161
+ on a live input still fails. Other storage faults fail the pass and remain
162
+ available to the normal retry policy.
163
+
164
+ A pending unit replays its pinned input ranges. If the input is removed
165
+ between the pin and the settle, the replay fails with `range-unreproducible`
166
+ and the pin stays. The final gone unit does not run for that binding. Keep
167
+ source history until pending units settle, or call `Projection.forget` on the
168
+ binding after you clean up its outputs.
169
+
110
170
  ## Hosts
111
171
 
112
172
  | Layer | Provides | Requires |
@@ -131,6 +191,49 @@ const host = Layer.mergeAll(CheckpointStore.layer, Transaction.layer).pipe(
131
191
  process and does not join the stream owner, so processing is at least once. Use
132
192
  it for rebuilt values, tests, and a remote host (`RemoteStreams.layer`).
133
193
 
194
+ ### Attached projections
195
+
196
+ `Projection.attach(projection)` runs a projection whenever a local commit
197
+ writes one of its inputs. The storage reports the stream ids of each commit
198
+ through `Storage.committed`. For each id, the input's `parse` gives the params,
199
+ and the runner runs `projection.at(params)`. So a new member of a family gets
200
+ its binding on its first commit, and the app names no bindings.
201
+
202
+ ```ts
203
+ const host = Layer.mergeAll(Api, Projection.attach(filesWake)).pipe(
204
+ Layer.provideMerge(CheckpointStore.layer),
205
+ Layer.provideMerge(BunStorage.layer(streams, { path })),
206
+ );
207
+ ```
208
+
209
+ Each input must give every projection param, so that one id picks one binding.
210
+ `attach` throws a `RangeError` when an input does not. Inputs on another owner
211
+ never commit here, so they never trigger. Do not also run an attached binding
212
+ under `Projection.follow`.
213
+
214
+ The set of bindings with work lives in memory. If the process stops after a
215
+ commit and before the run, the binding is late until its source gets its next
216
+ write. The next run catches up from the checkpoint while the source history remains
217
+ available. Removal before that run uses the final gone unit instead. A commit
218
+ by another process on the same SQL file does not show.
219
+
220
+ On Cloudflare, acquire a wakeup in the object's layer scope. Local commits
221
+ fill the same runner's pending set; `next` answers "now" while it has work,
222
+ and each alarm drains one pass (100 units per binding by default).
223
+
224
+ ```ts
225
+ StreamsyObject.make({
226
+ app,
227
+ layer,
228
+ wakeups: [ProjectionWakeup.attach(filesWake)],
229
+ });
230
+ ```
231
+
232
+ Both forms accept `retry: Schedule.Schedule<unknown>`. Bun applies it with
233
+ `Effect.retry` to a drain pass; the alarm host uses its delays to re-arm instead
234
+ of sleeping inside an alarm. The default is capped, jittered exponential backoff.
235
+ A finite schedule stops retries when exhausted.
236
+
134
237
  SQL hosts keep checkpoints in `streamsy_owner_records`. Older projection tables
135
238
  are not migrated or read; projections rebuild from zero.
136
239
  Layer authors use `EncodedStore` and `fromStore` from `@streamsy/projection/checkpoint`.
@@ -138,12 +241,31 @@ Layer authors use `EncodedStore` and `fromStore` from `@streamsy/projection/chec
138
241
  ## Run and recover
139
242
 
140
243
  `declaration.at(params)` binds a projection. `pass` runs one unit; `run` continues
141
- until caught up, closed, or its optional unit limit. `follow` returns a scoped
142
- fiber and waits for changes, with a default repair interval of 30 seconds. Remote inputs
143
- work with `follow` and `run`.
244
+ until caught up, closed, or its optional unit limit. `follow` returns a `Stream`
245
+ that runs to caught up, then waits for changes, with a default repair interval of
246
+ 30 seconds. Remote inputs work with `follow` and `run`.
247
+
248
+ `run` and each `follow` element give a `Progress`: the `state` and `offsets` that
249
+ the last pass left, plus `status`, `units`, and `items`. The stream
250
+ emits after the first cycle, after each cycle that commits a unit or reaches
251
+ `limit`, and after the last cycle when every input is closed; then it ends. A wake
252
+ that finds no input emits nothing. Invalid options fail the stream at its first pull.
253
+
254
+ ```ts
255
+ // Forks the follower into the caller's scope; closing the scope stops it.
256
+ const follower = Projection.follow(bound).pipe(Stream.runDrain, Effect.forkScoped);
257
+ ```
258
+
259
+ The stream is pull based: the next cycle runs only when the consumer pulls, so a
260
+ slow consumer gets one element for all the input that arrived meanwhile. The
261
+ consumer's pace sets the follower's pace; add
262
+ `Stream.buffer({ capacity: 1, strategy: "sliding" })` to decouple them. A consumer
263
+ failure or interruption stops the follower. `Stream.share` fans one follower out to
264
+ several consumers and stops it after the last one exits; to keep a projection up
265
+ with no consumer, drain it and publish each element to a `SubscriptionRef`.
144
266
 
145
- Use one writer per projection key: one `follow`, or one `run` at a
146
- time. Schedules must not overlap. A second writer is a deployment fault; a
267
+ Use one writer per projection key: one running `follow` stream, or one `run` at a
268
+ time. Each run of a `follow` stream value is a new writer. Schedules must not overlap. A second writer is a deployment fault; a
147
269
  moved checkpoint token fails with `token-conflict`. External handlers may have
148
270
  already run. Any number of `current` and `decide` calls can run beside the
149
271
  follower, including inside a caller transaction. Table and stateless output
@@ -1,7 +1,7 @@
1
- import { Context, Effect, Layer, Option, Schema, Semaphore } from "effect";
1
+ import { Array, Context, Effect, Layer, Option, Order, Record, Schema, Semaphore } from "effect";
2
2
  import { CommitBoundary, ZERO_OFFSET, isStreamsFault } from "@streamsy/core";
3
3
  import { OwnerRecords, attachOwner, ownerOf } from "@streamsy/core/internal";
4
- //#region src/fault.ts
4
+ // src/fault.ts
5
5
  /** Phase says where the run stopped; a `checkpoint` failure means processing already completed. */
6
6
  var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
7
7
  phase: Schema.Literals([
@@ -32,20 +32,26 @@ var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
32
32
  return this.reason === "storage-failure" && (!isStreamsFault(this.cause) || this.cause.retryable);
33
33
  }
34
34
  };
35
- //#endregion
36
- //#region src/unit.ts
35
+ // src/unit.ts
37
36
  /** Length-safe encoding of inert string components; no persistence decoding here. */
38
37
  const encodeKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
39
38
  const Counter = Schema.Finite.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0));
39
+ const terminal = {
40
+ closed: Schema.optionalKey(Schema.Boolean),
41
+ gone: Schema.optionalKey(Schema.Literal(true))
42
+ };
40
43
  Schema.Struct({
41
44
  from: Schema.String,
42
- nextOffset: Schema.String
45
+ nextOffset: Schema.String,
46
+ ...terminal
43
47
  });
44
48
  /** A range with the item count a retry must reproduce exactly. */
45
49
  const PinnedRange = Schema.Struct({
46
50
  from: Schema.String,
47
51
  nextOffset: Schema.String,
48
- count: Counter
52
+ count: Counter,
53
+ upToDate: Schema.optionalKey(Schema.Boolean),
54
+ ...terminal
49
55
  });
50
56
  /** An outputs unit that was pinned before its append; settled by the next pass. */
51
57
  const PendingUnit = Schema.Struct({
@@ -53,11 +59,21 @@ const PendingUnit = Schema.Struct({
53
59
  seqs: Schema.optionalKey(Schema.Record(Schema.String, Counter))
54
60
  });
55
61
  /** Deterministic JSON: keys sorted, so equal maps always encode identically. */
56
- const canonicalParams = (params) => JSON.stringify(Object.fromEntries(Object.keys(params).toSorted().map((k) => [k, params[k]])));
57
- const canonicalRanges = (ranges) => JSON.stringify(Object.fromEntries(Object.keys(ranges).toSorted().map((k) => [k, {
58
- from: ranges[k]?.from,
59
- nextOffset: ranges[k]?.nextOffset
60
- }])));
62
+ const canonicalParams = (params) => JSON.stringify(Record.fromEntries(Array.map(Array.sort(Record.keys(params), Order.String), (k) => [k, params[k]])));
63
+ const terminalOf = (source) => {
64
+ const keys = {};
65
+ if (source.closed === true) keys.closed = true;
66
+ if (source.gone === true) keys.gone = true;
67
+ return keys;
68
+ };
69
+ const canonicalRanges = (ranges) => JSON.stringify(Record.fromEntries(Array.map(Array.sort(Record.keys(ranges), Order.String), (k) => {
70
+ const range = ranges[k];
71
+ return [k, {
72
+ from: range?.from,
73
+ nextOffset: range?.nextOffset,
74
+ ...terminalOf(range ?? {})
75
+ }];
76
+ })));
61
77
  /** The key is stable across producer retries; transaction retries may read a longer tail. */
62
78
  const unitOf = (projectionId, version, generation, params, ranges) => ({
63
79
  projectionId,
@@ -77,13 +93,16 @@ const withParams = (unit, params) => ({
77
93
  ...unit,
78
94
  params
79
95
  });
80
- //#endregion
81
- //#region src/checkpoint-store.ts
96
+ // src/checkpoint-store.ts
82
97
  const CheckpointRecord = Schema.Struct({
83
98
  identity: Schema.Struct({ inputs: Schema.Record(Schema.String, Schema.String) }),
84
99
  /** Input key to accepted offset; the next pass reads after these. */
85
100
  inputs: Schema.Record(Schema.String, Schema.String),
86
101
  pending: Schema.optionalKey(PendingUnit),
102
+ /** Inputs whose terminal close has already been processed. */
103
+ closed: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)),
104
+ /** The final gone unit committed; only forgetting remains. */
105
+ ended: Schema.optionalKey(Schema.Literal(true)),
87
106
  state: Schema.optionalKey(Schema.String),
88
107
  adapters: Schema.Struct({ outputs: Schema.optionalKey(Schema.Record(Schema.String, Schema.Struct({
89
108
  epoch: Counter,
@@ -203,10 +222,10 @@ const fromStore = (store) => {
203
222
  remove: (key) => store.remove(recordKey(key))
204
223
  };
205
224
  };
206
- const identityOf = (inputs) => Object.fromEntries(Object.entries(inputs).map(([name, address]) => [name, encodeKey([address.id, address.contentType])]));
225
+ const identityOf = (inputs) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, address]) => [name, encodeKey([address.id, address.contentType])]));
207
226
  const sameIdentity = (a, b) => {
208
- const keys = Object.keys(a);
209
- return keys.length === Object.keys(b).length && keys.every((k) => a[k] === b[k]);
227
+ const keys = Record.keys(a);
228
+ return keys.length === Record.keys(b).length && Array.every(keys, (k) => a[k] === b[k]);
210
229
  };
211
230
  /** The stored record, or the unstored initial record for a fresh key. */
212
231
  const restore = Effect.fn("Projection.restore")(function* (projection, owner) {
@@ -215,7 +234,7 @@ const restore = Effect.fn("Projection.restore")(function* (projection, owner) {
215
234
  if (Option.isNone(loaded.record)) return {
216
235
  record: {
217
236
  identity,
218
- inputs: Object.fromEntries(Object.keys(projection.inputs).map((name) => [name, ZERO_OFFSET])),
237
+ inputs: Record.fromEntries(Array.map(Record.keys(projection.inputs), (name) => [name, ZERO_OFFSET])),
219
238
  adapters: {}
220
239
  },
221
240
  token: loaded.token,
@@ -226,7 +245,7 @@ const restore = Effect.fn("Projection.restore")(function* (projection, owner) {
226
245
  reason: "identity-mismatch",
227
246
  message: `Stored inputs differ from the declaration of ${projection.id}`
228
247
  });
229
- for (const name of Object.keys(projection.inputs)) if (loaded.record.value.inputs[name] === void 0) return yield* new ProjectionFault({
248
+ for (const name of Record.keys(projection.inputs)) if (loaded.record.value.inputs[name] === void 0) return yield* new ProjectionFault({
230
249
  phase: "load",
231
250
  reason: "invalid-record",
232
251
  input: name,
@@ -239,11 +258,11 @@ const restore = Effect.fn("Projection.restore")(function* (projection, owner) {
239
258
  };
240
259
  });
241
260
  /** Accepted offsets after a unit: every read input moves to its `nextOffset`. */
242
- const advance = (inputs, ranges) => Object.fromEntries(Object.entries(inputs).map(([name, offset]) => [name, ranges[name]?.nextOffset ?? offset]));
243
- /** Only the inputs that contributed items; the unit key and any pin come from these. */
244
- const rangesOf = (slices) => Object.fromEntries(Object.entries(slices).filter(([, slice]) => slice.items.length > 0).map(([name, slice]) => [name, {
261
+ const advance = (inputs, ranges) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, offset]) => [name, ranges[name]?.nextOffset ?? offset]));
262
+ /** Items and terminal outcomes contribute ranges, including zero-length terminal ranges. */
263
+ const rangesOf = (slices) => Record.fromEntries(Array.map(Array.filter(Record.toEntries(slices), ([, slice]) => slice.items.length > 0 || slice.closed || slice.gone === true), ([name, slice]) => [name, {
245
264
  from: slice.from,
246
- nextOffset: slice.nextOffset
265
+ nextOffset: slice.nextOffset,
266
+ ...terminalOf(slice)
247
267
  }]));
248
- //#endregion
249
- export { rangesOf as a, canonicalParams as c, ProjectionFault as d, fromStore as i, unitOf as l, CheckpointStore as n, recordKey as o, advance as r, restore as s, CheckpointRecord as t, withParams as u };
268
+ export { rangesOf as a, canonicalParams as c, withParams as d, ProjectionFault as f, fromStore as i, terminalOf as l, CheckpointStore as n, recordKey as o, advance as r, restore as s, CheckpointRecord as t, unitOf as u };
@@ -1,7 +1,6 @@
1
1
  import { Context, Effect, Layer, Option, Schema } from "effect";
2
2
  import { CommitBoundary, StreamAddress, Streamsy } from "@streamsy/core";
3
3
  import { OwnerRecords } from "@streamsy/core/internal";
4
- //#region src/batch.d.ts
5
4
  /** Declaration order of the map is the read and item order of every pass. */
6
5
  type InputMap = Record<string, Streamsy.Address<unknown, unknown>>;
7
6
  type ItemOf<Address> = Address extends StreamAddress.StreamAddress<infer A> ? A : never;
@@ -12,6 +11,8 @@ interface Slice<A> {
12
11
  readonly nextOffset: string;
13
12
  readonly upToDate: boolean;
14
13
  readonly closed: boolean;
14
+ /** The input is gone. This final unit is followed by forgetting the binding. */
15
+ readonly gone?: boolean;
15
16
  }
16
17
  type Slices<Inputs extends InputMap> = { readonly [K in keyof Inputs]: Slice<ItemOf<Inputs[K]>>; };
17
18
  /** One item tagged with its input; `index` is its position in the whole unit. */
@@ -21,8 +22,6 @@ type Entry<Inputs extends InputMap> = { readonly [K in keyof Inputs]: {
21
22
  readonly index: number;
22
23
  }; }[keyof Inputs];
23
24
  type InputServices<Inputs extends InputMap> = Inputs[keyof Inputs]["stream"]["Identifier"];
24
- //#endregion
25
- //#region src/fault.d.ts
26
25
  declare const ProjectionFault_base: Schema.Class<ProjectionFault, Schema.TaggedStruct<"ProjectionFault", {
27
26
  readonly phase: Schema.Literals<readonly ["load", "read", "pin", "process", "checkpoint"]>;
28
27
  readonly reason: Schema.Literals<readonly ["history-unavailable", "identity-mismatch", "invalid-record", "invalid-source", "invalid-options", "invalid-output", "token-conflict", "range-unreproducible", "stale-epoch", "storage-failure", "unsupported-composition"]>;
@@ -34,9 +33,9 @@ declare const ProjectionFault_base: Schema.Class<ProjectionFault, Schema.TaggedS
34
33
  declare class ProjectionFault extends ProjectionFault_base {
35
34
  get retryable(): boolean;
36
35
  }
37
- //#endregion
38
- //#region src/unit.d.ts
39
36
  declare const Range: Schema.Struct<{
37
+ readonly closed: Schema.optionalKey<Schema.Boolean>;
38
+ readonly gone: Schema.optionalKey<Schema.Literal<true>>;
40
39
  readonly from: Schema.String;
41
40
  readonly nextOffset: Schema.String;
42
41
  }>;
@@ -48,12 +47,10 @@ interface Unit<P = Record<string, string>> {
48
47
  readonly version: number;
49
48
  readonly generation: number;
50
49
  readonly params: P;
51
- /** Only the inputs that contributed items; a retry reproduces exactly these. */
50
+ /** The inputs that contributed items or a terminal outcome; retries reproduce these. */
52
51
  readonly ranges: Record<string, Range>;
53
52
  readonly key: string;
54
53
  }
55
- //#endregion
56
- //#region src/checkpoint-store.d.ts
57
54
  declare const CheckpointRecord: Schema.Struct<{
58
55
  readonly identity: Schema.Struct<{
59
56
  readonly inputs: Schema.$Record<Schema.String, Schema.String>;
@@ -62,12 +59,19 @@ declare const CheckpointRecord: Schema.Struct<{
62
59
  readonly inputs: Schema.$Record<Schema.String, Schema.String>;
63
60
  readonly pending: Schema.optionalKey<Schema.Struct<{
64
61
  readonly ranges: Schema.$Record<Schema.String, Schema.Struct<{
62
+ readonly closed: Schema.optionalKey<Schema.Boolean>;
63
+ readonly gone: Schema.optionalKey<Schema.Literal<true>>;
65
64
  readonly from: Schema.String;
66
65
  readonly nextOffset: Schema.String;
67
66
  readonly count: Schema.Finite;
67
+ readonly upToDate: Schema.optionalKey<Schema.Boolean>;
68
68
  }>>;
69
69
  readonly seqs: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Finite>>;
70
70
  }>>;
71
+ /** Inputs whose terminal close has already been processed. */
72
+ readonly closed: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Boolean>>;
73
+ /** The final gone unit committed; only forgetting remains. */
74
+ readonly ended: Schema.optionalKey<Schema.Literal<true>>;
71
75
  readonly state: Schema.optionalKey<Schema.String>;
72
76
  readonly adapters: Schema.Struct<{
73
77
  readonly outputs: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
@@ -122,5 +126,4 @@ interface Identity {
122
126
  readonly params: Record<string, string>;
123
127
  readonly inputs: InputMap;
124
128
  }
125
- //#endregion
126
129
  export { Slice as _, Identity as a, fromStore as c, Unit as d, ProjectionFault as f, ItemOf as g, InputServices as h, EncodedStore as i, recordKey as l, InputMap as m, CheckpointStore as n, Loaded as o, Entry as p, CheckpointStoreApi as r, ProjectionKey as s, CheckpointRecord as t, Range as u, Slices as v };
@@ -1,2 +1,2 @@
1
- import { c as fromStore, i as EncodedStore, l as recordKey, n as CheckpointStore, o as Loaded, r as CheckpointStoreApi, s as ProjectionKey, t as CheckpointRecord } from "./checkpoint-store-yQb6UDAb.js";
1
+ import { c as fromStore, i as EncodedStore, l as recordKey, n as CheckpointStore, o as Loaded, r as CheckpointStoreApi, s as ProjectionKey, t as CheckpointRecord } from "./checkpoint-store-D1saxIIM.js";
2
2
  export { CheckpointRecord, CheckpointStore, type CheckpointStoreApi, type EncodedStore, type Loaded, type ProjectionKey, fromStore, recordKey };
@@ -1 +1 @@
1
- export { t as CheckpointRecord, n as CheckpointStore, i as fromStore, o as recordKey } from "./checkpoint-store-DacqeoMQ.js";
1
+ export { t as CheckpointRecord, n as CheckpointStore, i as fromStore, o as recordKey } from "./checkpoint-store-Bm8z-f-l.js";