@streamsy/projection 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,480 +1,16 @@
1
1
  # @streamsy/projection
2
2
 
3
- Checkpointed projections over typed Streamsy routes. A constructor defines the
4
- step. Its `commit:` value defines how results and offsets become durable.
3
+ Checkpointed projections over Streamsy streams. Declare folds, processes, and stream-emitting projections with transactional commits, generation-addressed outputs, frontier rows, `StateTable` row stores, and `FoldByKey` read models on SQLite, Postgres, MySQL, or memory.
5
4
 
6
- ## Constructors
7
-
8
- | Constructor | Handler | Result | Commit |
9
- | -------------------------- | ------------------------ | -------------------------- | ------------------------------- |
10
- | `Projection.fold` | `(state, entry, unit)` | Next value | Defaults to `Commit.checkpoint` |
11
- | `Projection.process` | `(batch, unit, context)` | Effect of void or `WakeAt` | Required |
12
- | `Projection.emit` | `(entry, unit)` | Output items | Required |
13
- | `Projection.mapAccum` | `(state, entry, unit)` | `[state, emits]` | Required |
14
- | `Projection.mapAccumBatch` | `(state, batch, unit)` | `[state, emits]` | Required |
15
-
16
- Except for `process`, steps return a value or an Effect. A missing output key
17
- emits nothing. `Projection.each` adapts an entry handler for `process`.
18
- Batch handlers must give the same final rows for any unit size. In per-entry
19
- steps, use `unit` for parameters and unit ranges.
20
-
21
- A local input's `Slice.offsets` holds one storage offset per item, in item order;
22
- its last offset equals `nextOffset` when non-empty. `Entry.offset` carries the
23
- same offset, and a read from `entry.offset` resumes after that entry. Non-empty
24
- HTTP inputs have `offsets` undefined and entries omit `offset`, because HTTP
25
- supplies page boundaries only. Every empty slice has `offsets: []`, including
26
- skipped inputs and timer-only units. Pinned retries retain the entry offsets.
27
-
28
- ```ts
29
- import { Effect, Layer, Schema } from "effect";
30
- import { MemoryStorage, Streamsy } from "@streamsy/core";
31
- import { CheckpointStore, Commit, Projection } from "@streamsy/projection";
32
-
33
- class Numbers extends Streamsy.json<Numbers>()("Example/Numbers", "numbers", {
34
- params: {},
35
- schema: Schema.Finite,
36
- }) {}
37
- class Doubled extends Streamsy.json<Doubled>()("Example/Doubled", "doubled", {
38
- params: {},
39
- schema: Schema.Finite,
40
- }) {}
41
- const doubled = Projection.emit({
42
- id: "doubled",
43
- params: {},
44
- inputs: { input: Numbers },
45
- outputs: { output: Doubled },
46
- commit: Commit.producer,
47
- emit: ({ item }) => ({ output: [item * 2] }),
48
- });
49
- const host = CheckpointStore.layer.pipe(
50
- Layer.provideMerge(MemoryStorage.layer(Streamsy.group(Numbers, Doubled))),
51
- );
52
- const program = Effect.gen(function* () {
53
- const numbers = yield* Numbers;
54
- yield* numbers.create({});
55
- yield* numbers.append({}, [1, 2, 3]);
56
- return yield* Projection.run(doubled.at({}));
57
- });
58
- await Effect.runPromise(program.pipe(Effect.provide(host)));
59
- ```
60
-
61
- ## Commits
62
-
63
- | Commit | Fits | Guarantee | Services |
64
- | ------------- | ----------------------------------- | ----------------------------------------- | -------------------------------- |
65
- | `checkpoint` | `fold` | Exactly once for the saved value | `CheckpointStore` |
66
- | `transaction` | All constructors | Exactly once within the owner transaction | `CheckpointStore`, `Transaction` |
67
- | `producer` | `emit`, `mapAccum`, `mapAccumBatch` | Effectively once for outputs | `CheckpointStore`, output routes |
68
- | `atLeastOnce` | `process` | At least once | `CheckpointStore` |
69
-
70
- `Commit.transaction` commits the unit and checkpoint together on a memory or
71
- SQL storage host. Checkpoints and stream writes must share the transaction owner.
72
- A SQL handler reads the storage owner’s `SqlClient` from context to join the
73
- transaction. External calls are at least once.
74
-
75
- `Commit.producer` pins ranges and producer sequences. Retries append with the
76
- same positions; handlers must be deterministic. A missing output on the
77
- checkpoint's owner is created on the first append. An output on another owner
78
- must already exist: its owner creates it at start. There is no atomicity
79
- across producer outputs. Chain projections for sinks with different guarantees.
80
-
81
- `Commit.atLeastOnce` pins before processing, so retries keep `unit.key`.
82
- `Projection.process` with `Commit.transaction` can
83
- use `prepare(batch, unit)` outside the transaction. It runs at least once and passes its result to
84
- `process`. A retry can read new input and change `unit.key`.
85
-
86
- `Commit.transactionWithCleanup((key) => cleanup)` passes the binding’s
87
- checkpoint key to the cleanup Effect. The Effect reads its services from context.
88
- `Projection.forget` runs cleanup after removing the checkpoint and marking any
89
- route records forgotten. Pass the bound declaration for a routed binding.
90
- `Projection.retire` runs it after the tombstone write and owned output cleanup.
91
- The callback also runs on a repeated retirement. A cleanup failure rolls back
92
- changes in the same transaction, including SQL run with the storage owner’s client.
93
-
94
- `Commit.withCompensation(f)` calls `f(result, cause, unit)` after successful
95
- processing if the commit fails. It is also available as a `.pipe` combinator.
96
- For external delivery, use `Commit.atLeastOnce` with `unit.key` as the idempotency key,
97
- the declaration's [binding retry policy](https://streamsy.dev/docs/reference/projection/runners#binding-retry)
98
- for a retry budget and `onExhausted`, and [`Projection.wakeAt`](https://streamsy.dev/docs/projections/process#timers)
99
- for a deferred retry or a snooze. See the [effects guide](https://streamsy.dev/docs/projections/effects) for the complete pattern.
100
-
101
- To stop a binding on a permanent typed handler error, add
102
- `readonly [NonRetryable] = true` using `NonRetryable` from `@streamsy/projection`.
103
- Attached runners report the failure without stepping the retry schedule or
104
- calling `onExhausted`.
105
-
106
- `Commit.make` defines `load`, `apply`, and optional `remove`. Custom Commits
107
- extend ranges on retry. Never save after a failed handler; compare-and-set on
108
- `loaded.token`; report `checkpoint / token-conflict` for a moved token; return
109
- `"0"` for an absent record; and load stored state. The guarantee must describe
110
- the actual writes. See the [bucket example](https://streamsy.dev/docs/projections/state#custom-commits).
111
-
112
- ## State and output routes
113
-
114
- `fold`, `mapAccum`, and `mapAccumBatch` require `state: { schema, initial }`.
115
- `initial` can depend on decoded parameters. State and offsets share one record.
116
- `Projection.read(bound)` reads through the Commit's `load` and returns
117
- `{ state, offsets }`, using `initial` before the first unit.
118
- `Projection.current(bound)` folds the checkpoint and input tail in memory. It
119
- takes no lock and writes no checkpoint or outputs. It requires `state:` and
120
- returns matching state and offsets, including entries appended before the call.
121
- `mapAccum` and `mapAccumBatch` compute state and discard emitted items.
122
- `Projection.decide(bound, { input, decide })` requires `state:`, calls `current`,
123
- decides, and appends to one input with that input's offset as `expectedOffset`. It
124
- retries on `OffsetMismatch`. See [Read, decide, append](https://streamsy.dev/docs/projections/state#read-decide-append).
125
-
126
- `Serve.value(schema, effect)` serves values computed with `Projection.read`.
127
- Before the first saved unit, reads return the declared initial value.
128
- `Serve.mount(Board, path)` and `Serve.mount(Transitions, path)` mount output routes.
129
-
130
- Outputs accept routes or fixed addresses, like inputs. `Streamsy.json` accepts
131
- items. `Streamsy.state` accepts `DurableState.upsert("card", row)` and
132
- `DurableState.remove("card", key)` from `@streamsy/core`. Each change names its
133
- collection. Two outputs cannot name the same stream or an input.
134
-
135
- ## State tables
136
-
137
- `StateTable.define(State)` declares a projection that keeps the rows of a
138
- `Streamsy.state` stream in SQLite tables beside the stream. Run
139
- `StateTable.migrate(sql)` at host start and attach the table with
140
- `Projection.attach(table, { durable: true })`. A bound table reads rows with
141
- `get`, `getMany` and `list`, each with the offset that the rows reflect.
142
- `StateTable.rebuild` makes the rows again from the stream alone. The types of
143
- a declaration and a bound table are `StateTable.Declaration` and
144
- `StateTable.Bound`.
145
-
146
- `FoldByKey.process(table, spec)` builds a `Projection.process` handler on a SQL
147
- host. Put the State stream in `outputs` to fold records into one collection. Use
148
- `Commit.transaction` and provide the storage owner’s `SqlClient` to the runner.
149
- The fold reads each key’s previous row from the table. `sync` and the fold handler
150
- fail with `ProjectionFault` for every wire, SQL and schema failure,
151
- and the handler adds `FoldByKeyError` for a row with the wrong key. A fold's
152
- identity includes its `id`, `generation` and binding params. See
153
- [State tables](https://streamsy.dev/docs/projections/state-table).
154
-
155
- ## Wake streams
156
-
157
- `Projection.wake` writes a `Streamsy.wake` stream from one source stream. It is
158
- `mapAccumBatch` with `Commit.producer`. Each unit appends one upsert
159
- `{ stream, offset, closed? }`, so several source writes in one unit fold into
160
- one row. It reads committed storage, so every write path counts: toolkit calls,
161
- HTTP, other projections and raw `StreamsWriter` writes.
162
-
163
- ```ts
164
- const filesWake = Projection.wake({
165
- id: "files-wake",
166
- params: { user: UserKey, folderId: FolderKey },
167
- input: Files,
168
- output: UserWake,
169
- });
5
+ ```sh
6
+ bun add @streamsy/projection @streamsy/core effect
170
7
  ```
171
8
 
172
- Here `Files.at` takes `user` and `folderId`, and `UserWake.at` takes
173
- `user`. Each Files id supplies both params for attachment. The wake stream can live
174
- on another owner, where its owner must create it before the first append. The producer
175
- creates a missing output on its checkpoint owner only. A retry answers `Duplicate`, so delivery is effectively
176
- once for each binding. Rows of one source arrive in source order. A reader that
177
- comes before the first append gets 404 unless the owner calls the normal State
178
- service's `create` to make an empty stream available. `Streamsy.wake` is a State
179
- preset with `wakeCollections`; a `Streamsy.state` declaration with those
180
- collections also works as the output.
181
-
182
- | Source event | Wake change |
183
- | ------------------ | --------------------------------------------- |
184
- | Append | Upsert with the new tail, one for each unit |
185
- | Close with a body | Upsert with `closed: true` in the same unit |
186
- | Close, no body | Upsert with `closed: true` at the same offset |
187
- | Remove, TTL expiry | State delete of the source id, then `forget` |
188
- | Create, empty | None until the first append |
189
-
190
- A removed or expired source answers `StreamGone` or `StreamNotFound`. A
191
- binding with a checkpoint then appends the delete with its next producer
192
- sequence and forgets itself. A stream id never returns, so the delete is final.
193
- A binding with no checkpoint keeps the `history-unavailable` fault, because its
194
- source never existed for it. A drained closed source reports `source-closed`.
195
- `Projection.follow` ends when its input closes. Observe a later removal with
196
- `Projection.attach` or another explicit run.
197
-
198
- All projections receive terminal outcomes through their input slices. A close
199
- with no new items still makes one unit with `slice.closed`; the checkpoint
200
- records the close so subsequent runs do not repeat that empty unit. Batch
201
- handlers (`process` and `mapAccumBatch`) can react even when `slice.items` is
202
- empty; per-item handlers have no entries to process.
203
-
204
- When an input with a checkpoint is confirmed gone, the kernel runs a final
205
- unit with `slice.gone: true`, then forgets the binding by default. Lost history
206
- on a live input still fails. Other storage faults fail the pass and remain
207
- available to the normal retry policy.
208
-
209
- A pending unit replays its pinned input ranges. If the input is removed
210
- between the pin and the settle, the replay fails with `range-unreproducible`
211
- and the pin stays. The final gone unit does not run for that binding. Keep
212
- source history until pending units settle, or call `Projection.forget(bound)`
213
- to discard its progress.
214
-
215
- ## Hosts
216
-
217
- | Layer | Provides | Requires |
218
- | ----------------------------- | ---------------------------- | ------------------------------- |
219
- | `CheckpointStore.layer` | `CheckpointStore` | `CommitBoundary`, owner records |
220
- | `Transaction.layer` | `Transaction` | `CommitBoundary` |
221
- | `CheckpointStore.layerMemory` | Standalone `CheckpointStore` | Nothing |
222
-
223
- `CheckpointStore.layer` keeps checkpoints on the owner of the streams. It works
224
- over every Streamsy storage host: `MemoryStorage.layer`, `BunStorage.layer`, and
225
- `DurableObjectStorage.layer`. Add `Transaction.layer` over the same storage host for `Commit.transaction`.
226
- Compose the projection Layers over storage with
227
- `Layer.provideMerge` and retain one Layer graph for the host lifetime:
228
-
229
- ```ts
230
- const host = Layer.mergeAll(CheckpointStore.layer, Transaction.layer).pipe(
231
- Layer.provideMerge(BunStorage.layer(streams, { client: { filename } })),
232
- );
233
- ```
234
-
235
- `CheckpointStore.layerMemory` is standalone. It keeps checkpoints in the
236
- process and does not join the stream owner, so processing is at least once. Use
237
- it for rebuilt values, tests, and a remote host (`RemoteStreams.layer`).
238
-
239
- ### Attached projections
240
-
241
- `Projection.attach(projection)` runs a projection whenever a local commit
242
- writes one of its inputs. The storage reports the stream ids of each commit
243
- through `Storage.committed`. For each id, the input's `parse` gives the params,
244
- and the runner runs `projection.at(params)`. So a new member of a family gets
245
- its binding on its first commit, and the app names no bindings.
246
-
247
- ```ts
248
- const host = Layer.mergeAll(Api, Projection.attach(filesWake)).pipe(
249
- Layer.provideMerge(CheckpointStore.layer),
250
- Layer.provideMerge(BunStorage.layer(streams, { client: { filename: path } })),
251
- );
252
- ```
253
-
254
- Each input must give every projection param, so that one id picks one binding.
255
- `attach` throws a `RangeError` when an input does not. Inputs on another owner
256
- never commit here; use a wake stream in `triggers` to request their bindings. Do not also run an attached binding
257
- under `Projection.follow`.
258
-
259
- Pass fixed-address wake classes with `triggers: [Wake]`. A provided stream service
260
- on another owner makes a trigger remote; a matching owner or absent service
261
- uses local storage. Provide the remote class
262
- at runtime with `Protocol.bind(RemoteStreams.layerProtocol(...), Streamsy.group(Wake))`
263
- or another owner's protocol layer. `Projection.attach` starts a scoped live-read
264
- follower for each remote trigger, so a remote upsert wakes it without a local
265
- commit. `ProjectionWakeup.attach` rejects remote triggers at attach with a
266
- `RangeError` naming the stream; it accepts only its own storage owner's triggers.
267
-
268
- A pass reads local triggers, drains bindings, then reads one page per remote
269
- trigger outside the local transaction. Durable marks and the page's `nextOffset`
270
- commit together locally. Cursors persist in both durability modes; private marks
271
- can be lost after ingestion on restart. Missing or deleted remote streams leave
272
- the cursor unchanged without a fault. Invalid requests, data or page cursors stop
273
- only that trigger with `invalid-source`; `registry.rescan` and projection-level
274
- `registry.retry` clear the stop. Remote transport or storage read failures fail
275
- the pass retryably after all remote triggers are attempted. Local commits during
276
- pass backoff wait until it ends, up to the default 30 s cap. The follower uses its
277
- own `passRetry` steps and never signals a failure. `next` makes no network request.
278
- See [Trigger streams](https://streamsy.dev/docs/projections/run#trigger-streams).
279
-
280
- By default `Projection.attach` keeps pending binding marks, timers and backoff in private memory.
281
- In both modes a retryable failed binding waits alone, by default from 1 s doubling to 1 hour, while
282
- its neighbours run. A non-retryable projection or storage fault stops only the binding that failed.
283
- Handler errors and defects retry. A local commit or trigger row does not shorten backoff or end a stop;
284
- `registry.retry` or `registry.schedule` makes it due now. `registry.failed` lists
285
- failed bindings with their stored cause. A runner start makes stopped marks due once.
286
- If the process stops after a commit and before the run, the binding is late
287
- until its source gets its next write. The next run catches up from the
288
- checkpoint while the source history remains available. Removal before that run
289
- uses the final gone unit instead. A commit by another process on the same SQL
290
- file does not show.
291
-
292
- Pass `durable: true` to close that gap. Each commit then also writes a pending
293
- mark for each binding it touches, in the same transaction, to
294
- `streamsy_projection_pending`. A binding that catches up keeps a sleeping mark
295
- when its checkpoint records a wake; otherwise it deletes its mark, unless a write
296
- during the run marked it again. When the layer starts, it runs
297
- the bindings with due marks, up to `batch` (default 25) per pass. Durable mode needs a local memory or SQL storage layer.
298
-
299
- On Cloudflare, acquire a wakeup in the object's layer scope. Local commits
300
- fill the same runner's pending set; `next` answers "now" while it has work,
301
- and each alarm drains one pass (100 units per binding by default).
302
- `ProjectionWakeup.attach` is durable by default, because Cloudflare evicts idle
303
- objects. After an eviction or a deploy, the object's acquire reads the marks
304
- and arms the alarm, including sleeping timer deadlines. Pass `durable: false` for private memory marks and timers that reset on eviction until the binding's next input.
305
-
306
- ```ts
307
- StreamsyObject.make({
308
- app,
309
- layer,
310
- wakeups: [ProjectionWakeup.attach(filesWake)],
311
- });
312
- ```
313
-
314
- Both attach forms accept `concurrency` (default `1`), the most bindings run at once.
315
- It must be a positive safe integer. Each binding still runs in at most one fiber;
316
- units within that binding run in order.
317
-
318
- | Host | `Commit.transaction` | `Commit.atLeastOnce` |
319
- | --------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------ |
320
- | SQLite (Bun, Node and Deno) | Transaction bodies serialize; reads and `prepare` can overlap another unit's transaction | Handler bodies run in parallel |
321
- | Durable Objects | As SQLite | Handler bodies overlap across awaits |
322
- | Postgres and MySQL | Handler bodies run in parallel up to the pool size, subject to shared output row locks | Handler bodies run in parallel |
323
-
324
- Keep `concurrency` below the pool size: each `Commit.transaction` unit holds one
325
- pooled connection for its whole handler. Both server drivers default to 10 connections;
326
- leave a connection for reads, appends and runner storage operations. Inside the handler, run all SQL on the storage
327
- owner’s `SqlClient` in the handler's fiber. `sql.reserve` or a fiber without the
328
- handler's transaction context waits forever on SQLite, and on a pool once every
329
- connection holds a transaction. Appending to a shared output last keeps its row
330
- lock short: units serialize from that append until commit. Units that lock streams
331
- in opposite orders across separate appends can deadlock on Postgres or MySQL; the
332
- database aborts one transaction and its binding backs off before retrying.
333
-
334
- All five constructors accept `retry: { schedule?, maxAttempts?, onExhausted? }`.
335
- The default binding retry doubles from 1 s to 1 hour without a limit. A finite schedule
336
- or `maxAttempts` stops the binding when exhausted; `registry.failed` includes
337
- `exhausted: true`. `registry.retry` permits one more run. New input during backoff
338
- keeps the attempt count and deadline; success clears them. The runner replays a fresh
339
- schedule for the failure count, so use step-count schedules, without input or elapsed-time
340
- dependence. Stored deadlines survive durable restarts without recomputation.
341
- `onExhausted(unit, failure)` runs at least once before stopping; dedupe with `unit.key`.
342
- It receives decoded params. If no unit formed before the exhausting failure, the hook
343
- is skipped and logged. A failing hook is logged and the binding stops anyway.
344
- Non-retryable faults stop without the hook. Hooks run outside the handler transaction.
345
- A `process` context includes `attempt`, starting at 1 and increasing on failed attached
346
- runs. Direct `run` and `follow` always use 1. See [binding retry](https://streamsy.dev/docs/reference/projection/runners#binding-retry).
347
-
348
- Both forms accept `passRetry: Schedule.Schedule<unknown>`. Timing only: the runner calls
349
- the schedule once per retryable failed pass with no input. Bun waits for its delays; the
350
- alarm host uses them to re-arm. A dying schedule is logged and treated as exhausted. The default is capped, jittered exponential backoff.
351
- An attach call that still passes the removed `retry` option throws a `RangeError` naming `passRetry`.
352
- A finite schedule stops pass retries when exhausted. Binding failures use the declaration's `retry` policy; the pass policy paces failures in marks, cursor or trigger operations.
353
-
354
- SQL hosts keep checkpoints in `streamsy_owner_records`. Older projection tables
355
- are not migrated or read; projections rebuild from zero.
356
- Layer authors use `EncodedStore` and `fromStore` from `@streamsy/projection/checkpoint`.
357
-
358
- `Projection.Registry.layer` exposes attached runners through `status`, `changes`,
359
- `events`, `failed` and `awaitOffset`. `registry.schedule(binding)` also accepts an
360
- array of bindings of one projection and wakes the runner once. Mixed projection
361
- ids die with `RangeError`; empty arrays do nothing and duplicates coalesce. Every
362
- binding is validated before any marks are written. Invalid params fail with
363
- `InvalidBinding`. Marks are written in chunks of 100; a later storage failure can
364
- leave earlier chunks marked, so repeat the request safely. The call returns before
365
- processing finishes. `registry.retry(target)` makes failed work due now.
366
-
367
- After a fold fix, `registry.rescan(projectionOrId, WakeClassOrStreamId)` resets one
368
- trigger cursor to `ZERO_OFFSET`, clears its stop and wakes the runner. It does not
369
- reset binding checkpoints. Raise `generation` to replay those bindings.
370
- A row that still fails to decode stops that stream again. The cursor is stored in
371
- both durability modes and survives restart; ingested marks survive only in durable
372
- mode. An unknown projection fails with `NotAttached`; an unknown trigger dies with
373
- `RangeError`. A first attach already reads a trigger stream from its start, so a new
374
- family needs no rescan. See [runner requests](https://streamsy.dev/docs/projections/run#observe-attached-runners).
375
-
376
- ## Timers
377
-
378
- A `Projection.process` handler can return `Projection.wakeAt(time)`, with epoch
379
- milliseconds or an Effect `DateTime`, under `Commit.atLeastOnce` or
380
- `Commit.transaction` (including compensation wrappers). Returning void clears the
381
- previous timer; new input before the deadline can replace or cancel it. Other
382
- return values are discarded. A custom `Commit<void>` does not fit a timer handler.
383
-
384
- When the recorded time is due, the handler receives `unit.due: Some(time)`. Without
385
- new input, the slices and `unit.ranges` are empty. With new input, one unit carries
386
- both the items and the due time. The key includes the recorded due time, so pinned
387
- retries keep it and distinct deadlines have different keys. Decide what is due
388
- from `unit.due`; read `Clock` only to choose a late policy.
389
-
390
- `run`, `pass` and `follow` handle due timers when they next run. They do not wait
391
- for the deadline; `follow` can discover it on an input change or repair cycle.
392
- A `run` cycle makes at most one due unit without input, even if its handler returns
393
- a time already passed. Return a time after `unit.due` for the next wake.
394
-
395
- `Projection.attach` wakes a sleeping binding at its recorded deadline. Its process
396
- wait re-reads the wall clock at least every 30 seconds while a deadline exists,
397
- so after host suspend a passed wake is discovered within 30 seconds of resume.
398
- `ProjectionWakeup.attach` exposes that deadline to the Durable Object alarm host,
399
- which arms its alarm for the wake time. Wakes can be late; handlers use `unit.due`
400
- to apply their late policy. A wake during backoff waits for backoff to end. A
401
- stopped binding keeps its checkpoint timer and fires late after retry or restart.
402
- With `durable: false`, pending work and timers live in private memory: restart or
403
- eviction loses a timer's wake until the binding's next input. Use durable marks
404
- on persistent storage for restart recovery.
405
-
406
- Return a time after `unit.due` for the next wake. Repeatedly returning a passed
407
- time leaves the mark due immediately and can run the handler at pass speed.
408
-
409
- ## Run and recover
410
-
411
- `declaration.at(params)` binds a projection. `pass` runs one unit; `run` continues
412
- until caught up, closed, or its optional unit limit. `follow` returns a `Stream`
413
- that runs to caught up, then waits for changes, with a default repair interval of
414
- 30 seconds. Remote inputs work with `follow` and `run`.
415
-
416
- `run` and each `follow` element give a `Progress`: the `state` and `offsets` that
417
- the last pass left, plus `status`, `units`, `items`, and `wakeAt: Option<number>`. The stream
418
- emits after the first cycle, after each cycle that commits a unit or reaches
419
- `limit`, and after the last cycle when every input is closed; then it ends. A cycle
420
- that finds no input or due timer emits nothing. Invalid options fail the stream at its first pull.
421
-
422
- ```ts
423
- // Forks the follower into the caller's scope; closing the scope stops it.
424
- const follower = Projection.follow(bound).pipe(Stream.runDrain, Effect.forkScoped);
425
- ```
426
-
427
- The stream is pull based: the next cycle runs only when the consumer pulls, so a
428
- slow consumer gets one element for all the input that arrived meanwhile. The
429
- consumer's pace sets the follower's pace; add
430
- `Stream.buffer({ capacity: 1, strategy: "sliding" })` to decouple them. A consumer
431
- failure or interruption stops the follower. `Stream.share` fans one follower out to
432
- several consumers and stops it after the last one exits; to keep a projection up
433
- with no consumer, drain it and publish each element to a `SubscriptionRef`.
434
-
435
- Use one writer per projection key: one running `follow` stream, or one `run` at a
436
- time. Each run of a `follow` stream value is a new writer. Schedules must not overlap. A second writer is a deployment fault; a
437
- moved checkpoint token fails with `token-conflict`. External handlers may have
438
- already run. Any number of `current` and `decide` calls can run beside the
439
- follower, including inside a caller transaction. Table and stateless output
440
- projections are follow-only; wait on their output to see a command.
441
-
442
- `follow` retries `token-conflict`, `output-busy`, and retryable `storage-failure`: `options.retry` overrides the
443
- `ProjectionRetry` context reference, whose default is jittered exponential
444
- backoff from 200 ms, capped at 30 s. `run` does not retry. Handler errors retain
445
- their types; `ProjectionFault` carries `phase`, `reason`, and `cause`.
446
-
447
- Records are keyed by `id`, `generation` and canonical parameters.
448
- Raise `generation` to start over, including after a change to input identity or
449
- state schema. A new generation replays into fresh `perGeneration` streams.
450
- Unwrapped outputs with `Commit.producer` or `Commit.transaction` receive the
451
- replay after their existing items. To start with an empty output, choose a fresh
452
- address or remove the stream before you start the upgraded process. Attach can
453
- start replay at startup. [Checkpoints and generations](https://streamsy.dev/docs/projections/checkpoints#generations)
454
-
455
- Delete an explicit `version: 1`. If a binding used a different `version`, stop
456
- the old runners and keep the full input history for the new generation. The
457
- migration guide covers reader cutover and retirement. [Migrate a declaration that set `version`](https://streamsy.dev/docs/projections/checkpoints#migrate-a-declaration-that-set-version)
458
-
459
- Stop and drain the binding's runners before calling `Projection.forget(bound)`
460
- to discard progress. Forget keeps the streams. For a routed binding, pass the
461
- value returned by `declaration.at(params)` so `forget` marks its route records.
462
- Passing a bare key leaves them live and allows a replay to append to old data.
463
- Use a store that supports owner-record listing for routed forget on an existing
464
- checkpoint, including automatic forget after a gone input.
465
- With a transaction Commit, forgetting an absent checkpoint fails with a retryable
466
- `token-conflict` if another host commits the binding's first unit meanwhile.
467
-
468
- `Projection.retire` writes a tombstone even if the checkpoint cannot be decoded.
469
- It can remove or close owned streams after a forget when you pass the declaration
470
- with the original routed outputs. The result has `record` and a flat `streams`
471
- array. [Retire a generation](https://streamsy.dev/docs/projections/checkpoints#retire-a-generation)
472
-
473
- Without a follower, each `current` replays from the last checkpoint or from
474
- the start. A continuously growing input can delay it. Fold handlers must be
475
- replayable and give the same result for any page split.
9
+ ## Documentation
476
10
 
477
- Full reference: [streamsy.dev/docs/projections](https://streamsy.dev/docs/projections).
11
+ - [Projections guide](https://streamsy.dev/docs/projections)
12
+ - [API reference](https://streamsy.dev/docs/reference/projection/constructors)
13
+ - [Streamsy docs](https://streamsy.dev)
478
14
 
479
15
  ## License
480
16