@streamsy/projection 0.5.0 → 0.7.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,62 @@ 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
+ By default `Projection.attach` keeps the set of bindings with work in memory.
215
+ If the process stops after a commit and before the run, the binding is late
216
+ until its source gets its next write. The next run catches up from the
217
+ checkpoint while the source history remains available. Removal before that run
218
+ uses the final gone unit instead. A commit by another process on the same SQL
219
+ file does not show.
220
+
221
+ Pass `durable: true` to close that gap. Each commit then also writes a pending
222
+ mark for each binding it touches, in the same transaction, to
223
+ `streamsy_projection_pending`. A binding that catches up deletes its mark,
224
+ unless a write during the run marked it again. When the layer starts, it runs
225
+ the bindings that still have marks, up to `batch` (default 25) per pass. A
226
+ binding that fails waits alone, from 1 s doubling to 1 hour, and its
227
+ neighbours keep running. Durable mode needs a local memory or SQL storage
228
+ layer.
229
+
230
+ On Cloudflare, acquire a wakeup in the object's layer scope. Local commits
231
+ fill the same runner's pending set; `next` answers "now" while it has work,
232
+ and each alarm drains one pass (100 units per binding by default).
233
+ `ProjectionWakeup.attach` is durable by default, because Cloudflare evicts idle
234
+ objects. After an eviction or a deploy, the object's acquire reads the marks
235
+ and arms the alarm. Pass `durable: false` for the in-memory set only.
236
+
237
+ ```ts
238
+ StreamsyObject.make({
239
+ app,
240
+ layer,
241
+ wakeups: [ProjectionWakeup.attach(filesWake)],
242
+ });
243
+ ```
244
+
245
+ Both forms accept `retry: Schedule.Schedule<unknown>`. Bun applies it with
246
+ `Effect.retry` to a drain pass; the alarm host uses its delays to re-arm instead
247
+ of sleeping inside an alarm. The default is capped, jittered exponential backoff.
248
+ A finite schedule stops retries when exhausted.
249
+
134
250
  SQL hosts keep checkpoints in `streamsy_owner_records`. Older projection tables
135
251
  are not migrated or read; projections rebuild from zero.
136
252
  Layer authors use `EncodedStore` and `fromStore` from `@streamsy/projection/checkpoint`.
@@ -138,12 +254,31 @@ Layer authors use `EncodedStore` and `fromStore` from `@streamsy/projection/chec
138
254
  ## Run and recover
139
255
 
140
256
  `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`.
257
+ until caught up, closed, or its optional unit limit. `follow` returns a `Stream`
258
+ that runs to caught up, then waits for changes, with a default repair interval of
259
+ 30 seconds. Remote inputs work with `follow` and `run`.
260
+
261
+ `run` and each `follow` element give a `Progress`: the `state` and `offsets` that
262
+ the last pass left, plus `status`, `units`, and `items`. The stream
263
+ emits after the first cycle, after each cycle that commits a unit or reaches
264
+ `limit`, and after the last cycle when every input is closed; then it ends. A wake
265
+ that finds no input emits nothing. Invalid options fail the stream at its first pull.
266
+
267
+ ```ts
268
+ // Forks the follower into the caller's scope; closing the scope stops it.
269
+ const follower = Projection.follow(bound).pipe(Stream.runDrain, Effect.forkScoped);
270
+ ```
271
+
272
+ The stream is pull based: the next cycle runs only when the consumer pulls, so a
273
+ slow consumer gets one element for all the input that arrived meanwhile. The
274
+ consumer's pace sets the follower's pace; add
275
+ `Stream.buffer({ capacity: 1, strategy: "sliding" })` to decouple them. A consumer
276
+ failure or interruption stops the follower. `Stream.share` fans one follower out to
277
+ several consumers and stops it after the last one exits; to keep a projection up
278
+ with no consumer, drain it and publish each element to a `SubscriptionRef`.
144
279
 
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
280
+ Use one writer per projection key: one running `follow` stream, or one `run` at a
281
+ 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
282
  moved checkpoint token fails with `token-conflict`. External handlers may have
148
283
  already run. Any number of `current` and `decide` calls can run beside the
149
284
  follower, including inside a caller transaction. Table and stateless output
@@ -36,15 +36,22 @@ var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
36
36
  /** Length-safe encoding of inert string components; no persistence decoding here. */
37
37
  const encodeKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
38
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
+ };
39
43
  Schema.Struct({
40
44
  from: Schema.String,
41
- nextOffset: Schema.String
45
+ nextOffset: Schema.String,
46
+ ...terminal
42
47
  });
43
48
  /** A range with the item count a retry must reproduce exactly. */
44
49
  const PinnedRange = Schema.Struct({
45
50
  from: Schema.String,
46
51
  nextOffset: Schema.String,
47
- count: Counter
52
+ count: Counter,
53
+ upToDate: Schema.optionalKey(Schema.Boolean),
54
+ ...terminal
48
55
  });
49
56
  /** An outputs unit that was pinned before its append; settled by the next pass. */
50
57
  const PendingUnit = Schema.Struct({
@@ -53,10 +60,20 @@ const PendingUnit = Schema.Struct({
53
60
  });
54
61
  /** Deterministic JSON: keys sorted, so equal maps always encode identically. */
55
62
  const canonicalParams = (params) => JSON.stringify(Record.fromEntries(Array.map(Array.sort(Record.keys(params), Order.String), (k) => [k, params[k]])));
56
- const canonicalRanges = (ranges) => JSON.stringify(Record.fromEntries(Array.map(Array.sort(Record.keys(ranges), Order.String), (k) => [k, {
57
- from: ranges[k]?.from,
58
- nextOffset: ranges[k]?.nextOffset
59
- }])));
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
+ })));
60
77
  /** The key is stable across producer retries; transaction retries may read a longer tail. */
61
78
  const unitOf = (projectionId, version, generation, params, ranges) => ({
62
79
  projectionId,
@@ -82,6 +99,10 @@ const CheckpointRecord = Schema.Struct({
82
99
  /** Input key to accepted offset; the next pass reads after these. */
83
100
  inputs: Schema.Record(Schema.String, Schema.String),
84
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)),
85
106
  state: Schema.optionalKey(Schema.String),
86
107
  adapters: Schema.Struct({ outputs: Schema.optionalKey(Schema.Record(Schema.String, Schema.Struct({
87
108
  epoch: Counter,
@@ -238,9 +259,10 @@ const restore = Effect.fn("Projection.restore")(function* (projection, owner) {
238
259
  });
239
260
  /** Accepted offsets after a unit: every read input moves to its `nextOffset`. */
240
261
  const advance = (inputs, ranges) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, offset]) => [name, ranges[name]?.nextOffset ?? offset]));
241
- /** Only the inputs that contributed items; the unit key and any pin come from these. */
242
- const rangesOf = (slices) => Record.fromEntries(Array.map(Array.filter(Record.toEntries(slices), ([, slice]) => slice.items.length > 0), ([name, slice]) => [name, {
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, {
243
264
  from: slice.from,
244
- nextOffset: slice.nextOffset
265
+ nextOffset: slice.nextOffset,
266
+ ...terminalOf(slice)
245
267
  }]));
246
- 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 };
@@ -11,6 +11,8 @@ interface Slice<A> {
11
11
  readonly nextOffset: string;
12
12
  readonly upToDate: boolean;
13
13
  readonly closed: boolean;
14
+ /** The input is gone. This final unit is followed by forgetting the binding. */
15
+ readonly gone?: boolean;
14
16
  }
15
17
  type Slices<Inputs extends InputMap> = { readonly [K in keyof Inputs]: Slice<ItemOf<Inputs[K]>>; };
16
18
  /** One item tagged with its input; `index` is its position in the whole unit. */
@@ -32,6 +34,8 @@ declare class ProjectionFault extends ProjectionFault_base {
32
34
  get retryable(): boolean;
33
35
  }
34
36
  declare const Range: Schema.Struct<{
37
+ readonly closed: Schema.optionalKey<Schema.Boolean>;
38
+ readonly gone: Schema.optionalKey<Schema.Literal<true>>;
35
39
  readonly from: Schema.String;
36
40
  readonly nextOffset: Schema.String;
37
41
  }>;
@@ -43,7 +47,7 @@ interface Unit<P = Record<string, string>> {
43
47
  readonly version: number;
44
48
  readonly generation: number;
45
49
  readonly params: P;
46
- /** Only the inputs that contributed items; a retry reproduces exactly these. */
50
+ /** The inputs that contributed items or a terminal outcome; retries reproduce these. */
47
51
  readonly ranges: Record<string, Range>;
48
52
  readonly key: string;
49
53
  }
@@ -55,12 +59,19 @@ declare const CheckpointRecord: Schema.Struct<{
55
59
  readonly inputs: Schema.$Record<Schema.String, Schema.String>;
56
60
  readonly pending: Schema.optionalKey<Schema.Struct<{
57
61
  readonly ranges: Schema.$Record<Schema.String, Schema.Struct<{
62
+ readonly closed: Schema.optionalKey<Schema.Boolean>;
63
+ readonly gone: Schema.optionalKey<Schema.Literal<true>>;
58
64
  readonly from: Schema.String;
59
65
  readonly nextOffset: Schema.String;
60
66
  readonly count: Schema.Finite;
67
+ readonly upToDate: Schema.optionalKey<Schema.Boolean>;
61
68
  }>>;
62
69
  readonly seqs: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Finite>>;
63
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>>;
64
75
  readonly state: Schema.optionalKey<Schema.String>;
65
76
  readonly adapters: Schema.Struct<{
66
77
  readonly outputs: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
@@ -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-C8KxieX5.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-CoDWYNbd.js";
1
+ export { t as CheckpointRecord, n as CheckpointStore, i as fromStore, o as recordKey } from "./checkpoint-store-Bm8z-f-l.js";
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { _ as Slice, a as Identity, d as Unit, f as ProjectionFault, g as ItemOf, h as InputServices, m as InputMap, n as CheckpointStore, o as Loaded, p as Entry, r as CheckpointStoreApi, s as ProjectionKey, t as CheckpointRecord, u as Range, v as Slices } from "./checkpoint-store-C8KxieX5.js";
2
- import { Cause, Context, Data, Effect, Fiber, Layer, Option, Pipeable, Schedule, Schema, Scope } from "effect";
3
- import { CommitBoundary, Decided, Decision, DurableState, OffsetMismatch, StreamAddress, Streamsy } from "@streamsy/core";
1
+ import { _ as Slice, a as Identity, d as Unit, f as ProjectionFault, g as ItemOf, h as InputServices, m as InputMap, n as CheckpointStore, o as Loaded, p as Entry, r as CheckpointStoreApi, s as ProjectionKey, t as CheckpointRecord, u as Range, v as Slices } from "./checkpoint-store-D1saxIIM.js";
2
+ import { Cause, Context, Data, Effect, Layer, Option, Pipeable, Schedule, Schema, Stream } from "effect";
3
+ import { CommitBoundary, Decided, Decision, DurableState, OffsetMismatch, Storage, StreamAddress, StreamId, Streamsy } from "@streamsy/core";
4
4
  import { StreamRoute } from "@streamsy/core/protocol";
5
5
  import { SqlClient } from "effect/sql";
6
6
  interface RunOptions {
@@ -132,6 +132,7 @@ type Invalid<C extends StreamRoute.ParamCodecs, P> = { readonly [Name in keyof P
132
132
  type InvalidInput<C extends StreamRoute.ParamCodecs, X> = X extends StreamDeclaration ? Invalid<C, DeclaredParams<X>> : never;
133
133
  /** Every declaration's params must be projection params with the same type. */
134
134
  type Within<C extends StreamRoute.ParamCodecs, I extends Inputs> = { readonly [K in keyof I]: InvalidInput<C, I[K]> extends never ? I[K] : never; };
135
+ type OneWithin<C extends StreamRoute.ParamCodecs, X> = InvalidInput<C, X> extends never ? X : never;
135
136
  type OutputsWithin<C extends StreamRoute.ParamCodecs, D extends RoutedMap> = Within<C, D>;
136
137
  /** Inert: `at` binds the params and returns the value runners take. */
137
138
  interface Declaration<Codecs extends StreamRoute.ParamCodecs, Bound> {
@@ -139,6 +140,8 @@ interface Declaration<Codecs extends StreamRoute.ParamCodecs, Bound> {
139
140
  readonly version: number;
140
141
  readonly generation: number;
141
142
  readonly params: Codecs;
143
+ /** The declared inputs, before `at` binds them. */
144
+ readonly inputs: Inputs;
142
145
  /** Throws a RangeError when a param does not encode. */
143
146
  readonly at: (params: StreamRoute.Params<Codecs>) => Bound;
144
147
  /** Tries declaration inputs in order. Shared inputs return only their declared subset. */
@@ -210,26 +213,41 @@ interface Snapshot<S, Inputs extends InputMap> {
210
213
  readonly offsets: Offsets<Inputs>;
211
214
  }
212
215
  type StateValue<S> = [S] extends [never] ? undefined : S;
216
+ /** Internal: what `read` needs from a bound projection. */
217
+ type Readable<Inputs extends InputMap, S, Q> = Identity & {
218
+ readonly inputs: Inputs;
219
+ readonly state?: BoundState<S>;
220
+ readonly commit: Pick<Commit<never, never, Q>, "load">;
221
+ };
213
222
  /**
214
223
  * Reads the state and offsets from one checkpoint record, so the state
215
224
  * always matches the offsets. Before the first unit, the state is the declared initial
216
225
  * value and every offset is the start of its input.
217
226
  */
218
- declare const read: <Inputs extends InputMap, S = never, Q = never>(projection: Identity & {
219
- readonly inputs: Inputs;
220
- readonly state?: BoundState<S>;
221
- readonly commit: Pick<Commit<never, never, Q>, "load">;
222
- }) => Effect.Effect<Snapshot<StateValue<S>, Inputs>, ProjectionFault, Q>;
223
- interface Progress<Inputs extends InputMap = InputMap> {
224
- readonly status: "progress" | "caught-up" | "source-closed" | "limit-reached";
227
+ declare const read: <Inputs extends InputMap, S = never, Q = never>(projection: Readable<Inputs, S, Q>) => Effect.Effect<Snapshot<StateValue<S>, Inputs>, ProjectionFault, Q>;
228
+ /** The result of one `pass`: one committed unit (`progress`), or no input to commit. */
229
+ interface PassResult<Inputs extends InputMap = InputMap> {
230
+ readonly status: "progress" | "caught-up" | "source-closed";
225
231
  readonly units: number;
226
232
  readonly items: number;
227
233
  readonly offsets: Offsets<Inputs>;
228
234
  }
235
+ /** One runner cycle: the committed state and offsets, plus the work that the cycle did. */
236
+ interface Progress<S, Inputs extends InputMap = InputMap> extends Snapshot<S, Inputs> {
237
+ readonly status: "caught-up" | "limit-reached" | "source-closed";
238
+ /** Units that this cycle committed. */
239
+ readonly units: number;
240
+ /** Input items in those units. */
241
+ readonly items: number;
242
+ }
229
243
  /** Restore and adapt one input unit; the Commit owns every write. */
230
- declare const pass: <Inputs extends InputMap, E, R, Q, Result, P, OR = never>(projection: Executable<Inputs, E, R, Q, Result, P, unknown, OR>) => Effect.Effect<Progress<Inputs>, E | ProjectionFault, OR | Q | InputServices<Inputs> | Exclude<R, P>>;
231
- /** Repeats pass until caught up, closed, or limited. Use one writer per key. */
232
- declare const run: <Inputs extends InputMap, E, R, Q, Result, P, OR = never>(projection: Executable<Inputs, E, R, Q, Result, P, unknown, OR>, options?: RunOptions | undefined) => Effect.Effect<Progress<Inputs>, E | ProjectionFault, OR | Q | InputServices<Inputs> | Exclude<R, P>>;
244
+ declare const pass: <Inputs extends InputMap, E, R, Q, Result, P, OR = never>(projection: Executable<Inputs, E, R, Q, Result, P, unknown, OR>) => Effect.Effect<PassResult<Inputs>, E | ProjectionFault, Exclude<R, P> | Q | OR | InputServices<Inputs>>;
245
+ /**
246
+ * Repeats pass until caught up, closed, or limited, then decodes the state of the last
247
+ * pass once. After a gone input, the result holds the state that the final unit
248
+ * committed, although the kernel then deletes the record. Use one writer per key.
249
+ */
250
+ declare const run: <Inputs extends InputMap, E, R, Q, Result, P, S = never, OR = never>(projection: Executable<Inputs, E, R, Q, Result, P, S, OR>, options?: RunOptions | undefined) => Effect.Effect<Progress<StateValue<S>, Inputs>, E | ProjectionFault, OR | Q | InputServices<Inputs> | Exclude<R, P>>;
233
251
  interface FollowOptions extends RunOptions {
234
252
  /** Upper bound on one wake wait; default 30000. */
235
253
  readonly repairIntervalMs?: number;
@@ -237,12 +255,69 @@ interface FollowOptions extends RunOptions {
237
255
  readonly retry?: Schedule.Schedule<unknown>;
238
256
  }
239
257
  /**
240
- * Runs to caught-up, then waits for the first input to hint at a change and runs
241
- * again. The caller's scope owns the fiber and every parked wait; joining exposes
242
- * the terminal close or a typed failure. On HTTP backends a parked hint is cancelled
243
- * and replaced once per `repairIntervalMs` until an input changes.
258
+ * Follows a projection as a pull stream. Each element is one committed cycle: the
259
+ * state and offsets that the last pass left, plus the units and items of the cycle.
260
+ *
261
+ * To run the stream is to be the writer, so run one `follow` stream per key. The next
262
+ * cycle runs only when the consumer pulls, so a slow consumer gets one element that
263
+ * covers all the input that arrived meanwhile. The stream emits after the first cycle,
264
+ * after each cycle that commits a unit or reaches `limit`, and after the last cycle
265
+ * when every input is closed or an input is gone; then it ends. After a gone input, the
266
+ * last element holds the state that the final unit committed, and the kernel then
267
+ * deletes the record. A wake that finds no input emits nothing.
268
+ * Options are checked at the first pull. On HTTP backends a parked hint is cancelled
269
+ * and replaced once per `repairIntervalMs` until an input changes. One
270
+ * `Projection.follow` span covers the whole stream.
244
271
  */
245
- declare const follow: <Inputs extends InputMap, E, R, Q, Result, P, OR = never>(projection: Executable<Inputs, E, R, Q, Result, P, unknown, OR>, options?: FollowOptions | undefined) => Effect.Effect<Fiber.Fiber<Progress<Inputs>, E | ProjectionFault>, ProjectionFault, OR | Q | Scope.Scope | InputServices<Inputs> | Exclude<R, P>>;
272
+ declare const follow: <Inputs extends InputMap, E, R, Q, Result, P, S = never, OR = never>(projection: Executable<Inputs, E, R, Q, Result, P, S, OR>, options?: FollowOptions) => Stream.Stream<Progress<StateValue<S>, Inputs>, E | ProjectionFault, Exclude<R, P> | Q | OR | InputServices<Inputs>>;
273
+ /** The part of a projection declaration that the attach runner reads. */
274
+ interface Attachable<B> {
275
+ readonly id: string;
276
+ readonly params: StreamRoute.ParamCodecs;
277
+ readonly inputs: Inputs;
278
+ at(params: Readonly<Record<string, unknown>>): B;
279
+ }
280
+ interface AttachOptions {
281
+ /** Units for each binding in one run. Default 100. */
282
+ readonly limit?: number;
283
+ /** Retry a failed drain pass. Defaults to capped, jittered exponential backoff. */
284
+ readonly retry?: Schedule.Schedule<unknown>;
285
+ /**
286
+ * Keep a pending mark for each binding in the storage owner, written in the
287
+ * transaction of the commit that needs the run. After a restart or an
288
+ * eviction, the runner finds the marks and runs those bindings. A binding
289
+ * that fails waits alone, 1 s doubling to 1 hour, and its neighbours run.
290
+ * Needs a local memory or SQL storage layer.
291
+ *
292
+ * Default: false for `Projection.attach`, true for `ProjectionWakeup.attach`.
293
+ */
294
+ readonly durable?: boolean;
295
+ /** With `durable`, the due marks that one drain pass reads. Default 25. */
296
+ readonly batch?: number;
297
+ }
298
+ /**
299
+ * Run a projection whenever a local commit writes one of its inputs. The layer
300
+ * subscribes to `Storage.committed` when it is built, so build it with the
301
+ * storage layer and before the app writes. For each written id, the input's
302
+ * `parse` gives the params, and the runner runs `projection.at(params)`.
303
+ *
304
+ * Use it on long-lived hosts (Bun, Node). On a Cloudflare object, use
305
+ * `ProjectionWakeup.attach(projection)`.
306
+ *
307
+ * By default the set of bindings with work lives in memory. A crash after a
308
+ * commit and before the run leaves that binding late until its source gets its
309
+ * next write. With `durable: true`, a pending mark in storage covers that
310
+ * window, and the layer runs due marks when it starts.
311
+ * Inputs on another owner never commit here, so they never trigger. Do not run
312
+ * an attached binding under `Projection.follow` too: use one writer per key.
313
+ *
314
+ * ```ts
315
+ * const app = Layer.mergeAll(Api, Projection.attach(filesWake)).pipe(
316
+ * Layer.provideMerge(BunStorage.layer(streams, { path })),
317
+ * );
318
+ * ```
319
+ */
320
+ declare const attach$1: <I extends InputMap, E, R, Q, Result, P, OR = never>(projection: Attachable<Executable<I, E, R, Q, Result, P, unknown, OR>>, options?: AttachOptions) => Layer.Layer<never, never, Storage | Exclude<R, P> | Q | OR | InputServices<I>>;
246
321
  /** A bound value projection. Output items from its adapter are discarded. */
247
322
  interface CurrentProjection<Inputs extends InputMap, S, E, R, Q> extends Identity {
248
323
  readonly inputs: Inputs;
@@ -296,12 +371,72 @@ declare class LostRace {
296
371
  declare const forget: <R>(projection: ProjectionKey & {
297
372
  readonly commit: Pick<Commit<never, never, R>, "remove">;
298
373
  }) => Effect.Effect<void, ProjectionFault, R>;
374
+ /** A State declaration with the wake collections. */
375
+ type WakeOutput = StreamDeclaration & StreamRoute.StateRoute<any, Streamsy.WakeCollections>;
376
+ interface WakeDefinition<C extends StreamRoute.ParamCodecs, I extends Input, O> {
377
+ readonly id: string;
378
+ readonly version?: number;
379
+ readonly generation?: number;
380
+ readonly params: C;
381
+ /** The one source stream. Its params must be projection params. */
382
+ readonly input: I & OneWithin<C, I>;
383
+ /** The State declaration with wake collections that gets the row. Its params must be projection params. */
384
+ readonly output: O & OneWithin<C, O>;
385
+ }
386
+ type WakeDeclaration<C extends StreamRoute.ParamCodecs, I extends Input, O extends Input> = AccumulatingDeclaration<C, {
387
+ readonly source: I;
388
+ }, {
389
+ readonly wake: O;
390
+ }, null, never, never, never, CheckpointStore>;
391
+ /**
392
+ * A wake projection: one source stream gives one keyed row in one wake stream.
393
+ * Each unit appends one upsert `{ stream, offset, closed? }` with
394
+ * `Commit.producer`, so several source writes in one unit fold into one row,
395
+ * and a retry answers `Duplicate`. The producer creates a missing wake stream
396
+ * on its own owner. A wake stream on another owner must exist before the first
397
+ * append: its owner creates it at start. When the source is removed or
398
+ * expires, the binding appends a State delete for its row and forgets itself.
399
+ *
400
+ * ```ts
401
+ * const filesWake = Projection.wake({
402
+ * id: "files-wake",
403
+ * params: { user: UserKey, folderId: FolderKey },
404
+ * input: Files,
405
+ * output: UserWake,
406
+ * });
407
+ * ```
408
+ */
409
+ declare function wake<C extends StreamRoute.ParamCodecs, const I extends Input, const O extends WakeOutput>(definition: WakeDefinition<C, I, O>): WakeDeclaration<C, I, O>;
299
410
  declare namespace projection_d_exports {
300
- export { current, decide, each, emit, fold, follow, forget, items, key, mapAccum, mapAccumBatch, pass, process, read, run };
411
+ export { attach$1 as attach, current, decide, each, emit, fold, follow, forget, items, key, mapAccum, mapAccumBatch, pass, process, read, run, wake };
301
412
  }
302
413
  declare const key: (projection: Identity) => ProjectionKey;
303
414
  /** Runs each tagged entry in order and discards its success value. */
304
415
  declare const each: <Inputs extends InputMap, E, R, P = Record<string, string>>(handle: (entry: Entry<Inputs>, unit: Unit<P>) => Effect.Effect<unknown, E, R>) => ((batch: Slices<Inputs>, unit: Unit<P>) => Effect.Effect<void, E, R>);
305
- /** Default storage-failure retry for follow; an explicit options.retry takes precedence. */
416
+ /** Default retry for following and attached runners; an explicit options.retry takes precedence. */
306
417
  export declare const ProjectionRetry: Context.Reference<Schedule.Schedule<unknown, unknown, never, never>>;
307
- export { type Accumulated, CheckpointRecord, CheckpointStore, type CheckpointStoreApi, commit_d_exports as Commit, type CurrentProjection, type DecideSpec, type Declaration, type Emits, type Emitted, type Entry, type Folded, type FollowOptions, type Identity, type Initial, type InputMap, type ItemOf, type Loaded, type Offsets, type OutputBatch, type Progress, projection_d_exports as Projection, ProjectionFault, type ProjectionKey, type Range, type RunOptions, type Slice, type Slices, type Snapshot, type StateDefinition, type StateSchema, type Step, type Unit };
418
+ /**
419
+ * Local commits choose bindings; each alarm drains the same runner used by
420
+ * Projection.attach. Acquire it in the object layer's scope, before any
421
+ * request writes.
422
+ *
423
+ * Durable by default: each commit writes a pending mark for its bindings in
424
+ * the same transaction, so an eviction or a deploy between the commit and the
425
+ * alarm loses no work. The host's acquire reconcile reads the marks and arms
426
+ * the alarm. Pass `durable: false` for the in-memory set only.
427
+ */
428
+ declare const attach: <I extends InputMap, E, R, Q, Result, P, OR = never>(projection: Attachable<Executable<I, E, R, Q, Result, P, unknown, OR>>, options?: AttachOptions) => Effect.Effect<{
429
+ name: string;
430
+ next: Effect.Effect<import("effect/Option").Option<number>, import("@streamsy/core").StorageFault, never>;
431
+ run: Effect.Effect<{
432
+ more: boolean;
433
+ } | {
434
+ more: boolean;
435
+ }, E | ProjectionFault | import("@streamsy/core").StorageFault, OR | Q | InputServices<I> | Exclude<R, P>>;
436
+ retry: import("effect/Schedule").Schedule<unknown, unknown, never, never>;
437
+ deferred: Effect.Effect<number, import("@streamsy/core").StorageFault, never>;
438
+ }, never, import("effect/Scope").Scope | import("@streamsy/core").Storage>;
439
+ export declare const ProjectionWakeup: {
440
+ attach: typeof attach;
441
+ };
442
+ export { type Accumulated, type AttachOptions, type Attachable, CheckpointRecord, CheckpointStore, type CheckpointStoreApi, commit_d_exports as Commit, type CurrentProjection, type DecideSpec, type Declaration, type Emits, type Emitted, type Entry, type Folded, type FollowOptions, type Identity, type Initial, type InputMap, type ItemOf, type Loaded, type Offsets, type OutputBatch, type PassResult, type Progress, projection_d_exports as Projection, ProjectionFault, type ProjectionKey, type Range, type RunOptions, type Slice, type Slices, type Snapshot, type StateDefinition, type StateSchema, type Step, type Unit };