@streamsy/projection 0.5.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 +129 -7
- package/dist/{checkpoint-store-CoDWYNbd.js → checkpoint-store-Bm8z-f-l.js} +32 -10
- package/dist/{checkpoint-store-C8KxieX5.d.ts → checkpoint-store-D1saxIIM.d.ts} +12 -1
- package/dist/checkpoint.d.ts +1 -1
- package/dist/checkpoint.js +1 -1
- package/dist/index.d.ts +134 -21
- package/dist/index.js +401 -79
- package/package.json +4 -4
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.
|
|
69
|
-
|
|
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
|
|
142
|
-
|
|
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
|
|
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
|
|
@@ -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
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
/**
|
|
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,
|
|
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
|
-
/**
|
|
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<{
|
package/dist/checkpoint.d.ts
CHANGED
|
@@ -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-
|
|
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 };
|
package/dist/checkpoint.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as CheckpointRecord, n as CheckpointStore, i as fromStore, o as recordKey } from "./checkpoint-store-
|
|
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-
|
|
2
|
-
import { Cause, Context, Data, 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:
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
readonly
|
|
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<
|
|
231
|
-
/**
|
|
232
|
-
|
|
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,55 @@ interface FollowOptions extends RunOptions {
|
|
|
237
255
|
readonly retry?: Schedule.Schedule<unknown>;
|
|
238
256
|
}
|
|
239
257
|
/**
|
|
240
|
-
*
|
|
241
|
-
*
|
|
242
|
-
*
|
|
243
|
-
*
|
|
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,
|
|
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
|
+
/**
|
|
287
|
+
* Run a projection whenever a local commit writes one of its inputs. The layer
|
|
288
|
+
* subscribes to `Storage.committed` when it is built, so build it with the
|
|
289
|
+
* storage layer and before the app writes. For each written id, the input's
|
|
290
|
+
* `parse` gives the params, and the runner runs `projection.at(params)`.
|
|
291
|
+
*
|
|
292
|
+
* Use it on long-lived hosts (Bun, Node). On a Cloudflare object, use
|
|
293
|
+
* `ProjectionWakeup.attach(projection)`.
|
|
294
|
+
*
|
|
295
|
+
* The set of bindings with work lives in memory. A crash after a commit and
|
|
296
|
+
* before the run leaves that binding late until its source gets its next write.
|
|
297
|
+
* Inputs on another owner never commit here, so they never trigger. Do not run
|
|
298
|
+
* an attached binding under `Projection.follow` too: use one writer per key.
|
|
299
|
+
*
|
|
300
|
+
* ```ts
|
|
301
|
+
* const app = Layer.mergeAll(Api, Projection.attach(filesWake)).pipe(
|
|
302
|
+
* Layer.provideMerge(BunStorage.layer(streams, { path })),
|
|
303
|
+
* );
|
|
304
|
+
* ```
|
|
305
|
+
*/
|
|
306
|
+
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
307
|
/** A bound value projection. Output items from its adapter are discarded. */
|
|
247
308
|
interface CurrentProjection<Inputs extends InputMap, S, E, R, Q> extends Identity {
|
|
248
309
|
readonly inputs: Inputs;
|
|
@@ -296,12 +357,64 @@ declare class LostRace {
|
|
|
296
357
|
declare const forget: <R>(projection: ProjectionKey & {
|
|
297
358
|
readonly commit: Pick<Commit<never, never, R>, "remove">;
|
|
298
359
|
}) => Effect.Effect<void, ProjectionFault, R>;
|
|
360
|
+
/** A State declaration with the wake collections. */
|
|
361
|
+
type WakeOutput = StreamDeclaration & StreamRoute.StateRoute<any, Streamsy.WakeCollections>;
|
|
362
|
+
interface WakeDefinition<C extends StreamRoute.ParamCodecs, I extends Input, O> {
|
|
363
|
+
readonly id: string;
|
|
364
|
+
readonly version?: number;
|
|
365
|
+
readonly generation?: number;
|
|
366
|
+
readonly params: C;
|
|
367
|
+
/** The one source stream. Its params must be projection params. */
|
|
368
|
+
readonly input: I & OneWithin<C, I>;
|
|
369
|
+
/** The State declaration with wake collections that gets the row. Its params must be projection params. */
|
|
370
|
+
readonly output: O & OneWithin<C, O>;
|
|
371
|
+
}
|
|
372
|
+
type WakeDeclaration<C extends StreamRoute.ParamCodecs, I extends Input, O extends Input> = AccumulatingDeclaration<C, {
|
|
373
|
+
readonly source: I;
|
|
374
|
+
}, {
|
|
375
|
+
readonly wake: O;
|
|
376
|
+
}, null, never, never, never, CheckpointStore>;
|
|
377
|
+
/**
|
|
378
|
+
* A wake projection: one source stream gives one keyed row in one wake stream.
|
|
379
|
+
* Each unit appends one upsert `{ stream, offset, closed? }` with
|
|
380
|
+
* `Commit.producer`, so several source writes in one unit fold into one row,
|
|
381
|
+
* and a retry answers `Duplicate`. The producer creates a missing wake stream
|
|
382
|
+
* on its own owner. A wake stream on another owner must exist before the first
|
|
383
|
+
* append: its owner creates it at start. When the source is removed or
|
|
384
|
+
* expires, the binding appends a State delete for its row and forgets itself.
|
|
385
|
+
*
|
|
386
|
+
* ```ts
|
|
387
|
+
* const filesWake = Projection.wake({
|
|
388
|
+
* id: "files-wake",
|
|
389
|
+
* params: { user: UserKey, folderId: FolderKey },
|
|
390
|
+
* input: Files,
|
|
391
|
+
* output: UserWake,
|
|
392
|
+
* });
|
|
393
|
+
* ```
|
|
394
|
+
*/
|
|
395
|
+
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
396
|
declare namespace projection_d_exports {
|
|
300
|
-
export { current, decide, each, emit, fold, follow, forget, items, key, mapAccum, mapAccumBatch, pass, process, read, run };
|
|
397
|
+
export { attach$1 as attach, current, decide, each, emit, fold, follow, forget, items, key, mapAccum, mapAccumBatch, pass, process, read, run, wake };
|
|
301
398
|
}
|
|
302
399
|
declare const key: (projection: Identity) => ProjectionKey;
|
|
303
400
|
/** Runs each tagged entry in order and discards its success value. */
|
|
304
401
|
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
|
|
402
|
+
/** Default retry for following and attached runners; an explicit options.retry takes precedence. */
|
|
306
403
|
export declare const ProjectionRetry: Context.Reference<Schedule.Schedule<unknown, unknown, never, never>>;
|
|
307
|
-
|
|
404
|
+
/**
|
|
405
|
+
* Local commits choose bindings; each alarm drains the same runner used by
|
|
406
|
+
* Projection.attach. Acquire it in the object layer's scope, before any
|
|
407
|
+
* request writes.
|
|
408
|
+
*/
|
|
409
|
+
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<{
|
|
410
|
+
name: string;
|
|
411
|
+
next: Effect.Effect<import("effect/Option").Option<number>, never, never>;
|
|
412
|
+
run: Effect.Effect<{
|
|
413
|
+
more: boolean;
|
|
414
|
+
}, E | ProjectionFault, OR | Q | InputServices<I> | Exclude<R, P>>;
|
|
415
|
+
retry: import("effect/Schedule").Schedule<unknown, unknown, never, never>;
|
|
416
|
+
}, never, import("effect/Scope").Scope | import("@streamsy/core").Storage>;
|
|
417
|
+
export declare const ProjectionWakeup: {
|
|
418
|
+
attach: typeof attach;
|
|
419
|
+
};
|
|
420
|
+
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 };
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
|
-
import { a as rangesOf, c as canonicalParams, d as ProjectionFault, l as
|
|
3
|
-
import { Array, Context, Data, Duration, Effect, Function, Layer, Option, Pipeable, Predicate, Record, Ref, Result, Schedule, Schema } from "effect";
|
|
4
|
-
import { CommitBoundary, DurableState, Offset, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
|
|
2
|
+
import { a as rangesOf, c as canonicalParams, d as withParams, f as ProjectionFault, l as terminalOf, n as CheckpointStore, r as advance, s as restore, t as CheckpointRecord, u as unitOf } from "./checkpoint-store-Bm8z-f-l.js";
|
|
3
|
+
import { Array, Cause, Clock, Context, Data, Duration, Effect, Exit, Function, Layer, Option, Pipeable, Predicate, PubSub, Record, Ref, Result, Schedule, Schema, Stream } from "effect";
|
|
4
|
+
import { CommitBoundary, DurableState, Offset, Storage, StreamId, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
|
|
5
5
|
import { Streams, StreamsWriter } from "@streamsy/core/protocol";
|
|
6
|
-
import { CurrentOwner, isForeignOwner, ownerOf } from "@streamsy/core/internal";
|
|
6
|
+
import { CurrentOwner, compileSegments, isForeignOwner, ownerOf } from "@streamsy/core/internal";
|
|
7
7
|
import { SqlClient } from "effect/sql";
|
|
8
8
|
// src/batch.ts
|
|
9
9
|
/** An input that was skipped this pass: nothing read, nothing known beyond its cursor. */
|
|
@@ -72,6 +72,35 @@ const readSlice = Effect.fn("Projection.readSlice")(function* (input, address, f
|
|
|
72
72
|
closed: result.closed
|
|
73
73
|
} };
|
|
74
74
|
});
|
|
75
|
+
/**
|
|
76
|
+
* A lost history is terminal only when a known input's head confirms it is gone.
|
|
77
|
+
* A pinned unit is replayed with `reproduce` and never takes this path: a
|
|
78
|
+
* removal between a pin and its append is a `range-unreproducible` fault.
|
|
79
|
+
*/
|
|
80
|
+
const readOrGone = Effect.fn("Projection.readOrGone")(function* (input, address, from, read, seen) {
|
|
81
|
+
return yield* read.pipe(Effect.catchTag("ProjectionFault", (fault) => {
|
|
82
|
+
if (!seen || fault.reason !== "history-unavailable") return Effect.fail(fault);
|
|
83
|
+
return Effect.gen(function* () {
|
|
84
|
+
const { wire } = yield* address.stream;
|
|
85
|
+
if (!(yield* wire.head(address.id).pipe(Effect.as(false), Effect.catchTags({
|
|
86
|
+
StreamNotFound: () => Effect.succeed(true),
|
|
87
|
+
StreamGone: () => Effect.succeed(true)
|
|
88
|
+
}), Effect.mapError((cause) => new ProjectionFault({
|
|
89
|
+
phase: "read",
|
|
90
|
+
reason: "storage-failure",
|
|
91
|
+
input,
|
|
92
|
+
message: `Cannot read the head of ${address.id}`,
|
|
93
|
+
cause
|
|
94
|
+
}))))) return yield* fault;
|
|
95
|
+
return { slice: {
|
|
96
|
+
...emptySlice(from),
|
|
97
|
+
upToDate: true,
|
|
98
|
+
closed: true,
|
|
99
|
+
gone: true
|
|
100
|
+
} };
|
|
101
|
+
});
|
|
102
|
+
}));
|
|
103
|
+
});
|
|
75
104
|
/** Decode failure is an input fault: the stored bytes do not match the declared codec. */
|
|
76
105
|
const decodeMessages = (input, address, messages) => Effect.forEach(messages, (message, index) => Schema.decodeEffect(address.codec)(Predicate.isTagged(address, "Json") ? new TextDecoder().decode(message.data) : message.data).pipe(Effect.mapError(() => new ProjectionFault({
|
|
77
106
|
phase: "read",
|
|
@@ -88,6 +117,16 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
|
|
|
88
117
|
input,
|
|
89
118
|
message: `Pinned range of ${address.id} after ${range.from} cannot be reproduced: ${detail}`
|
|
90
119
|
});
|
|
120
|
+
if (range.count === 0) {
|
|
121
|
+
if (range.from !== range.nextOffset || !range.closed && !range.gone) return yield* unreproducible("an empty pin must describe a terminal outcome at the same offset");
|
|
122
|
+
return { slice: {
|
|
123
|
+
...emptySlice(range.from),
|
|
124
|
+
nextOffset: range.nextOffset,
|
|
125
|
+
closed: range.closed === true,
|
|
126
|
+
upToDate: true,
|
|
127
|
+
...terminalOf(range)
|
|
128
|
+
} };
|
|
129
|
+
}
|
|
91
130
|
let messages = [];
|
|
92
131
|
let cursor = range.from;
|
|
93
132
|
let last;
|
|
@@ -134,16 +173,17 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
|
|
|
134
173
|
from: range.from,
|
|
135
174
|
items: yield* decodeMessages(input, address, messages),
|
|
136
175
|
nextOffset: range.nextOffset,
|
|
137
|
-
upToDate: last.upToDate && cursor === range.nextOffset,
|
|
138
|
-
closed:
|
|
176
|
+
upToDate: range.upToDate ?? (last.upToDate && cursor === range.nextOffset),
|
|
177
|
+
closed: range.closed === true
|
|
139
178
|
} };
|
|
140
179
|
});
|
|
141
180
|
/** Read one server page per input in declaration order. */
|
|
142
|
-
const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets) {
|
|
181
|
+
const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets, seen = false) {
|
|
143
182
|
const slices = {};
|
|
144
183
|
let items = 0;
|
|
145
184
|
for (const [name, address] of inputEntries(inputs)) {
|
|
146
|
-
const
|
|
185
|
+
const from = offsets[name] ?? "";
|
|
186
|
+
const read = yield* readOrGone(name, address, from, readSlice(name, address, from), seen);
|
|
147
187
|
slices[name] = read.slice;
|
|
148
188
|
items += read.slice.items.length;
|
|
149
189
|
}
|
|
@@ -363,6 +403,16 @@ const transaction = withPrepare(make({
|
|
|
363
403
|
// src/commit/producer.ts
|
|
364
404
|
/** The pinned tuple identity: the params join the id so two parameterisations never share a sequence. */
|
|
365
405
|
const producerId = (id, version, params) => `${id}/v${version}${Record.keys(params).length === 0 ? "" : `/${canonicalParams(params)}`}`;
|
|
406
|
+
/** The head of one output. A missing output on the checkpoint's owner is created here. */
|
|
407
|
+
const prepareOutput = (output, store) => {
|
|
408
|
+
const { wire, owner: outputOwner } = output.service;
|
|
409
|
+
return wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== ownerOf(store.load) ? Effect.fail(cause) : Streams.create(output.address).pipe(Effect.provideService(StreamsWriter, wire), Effect.andThen(wire.head(output.address.id)))), Effect.mapError((cause) => new ProjectionFault({
|
|
410
|
+
phase: "pin",
|
|
411
|
+
reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
|
|
412
|
+
message: `Cannot prepare output ${output.address.id}`,
|
|
413
|
+
cause
|
|
414
|
+
})));
|
|
415
|
+
};
|
|
366
416
|
/** The pin write is the last save before the append, so its conflict is a pin failure. */
|
|
367
417
|
const asPin = (fault) => fault.phase === "checkpoint" && fault.reason === "token-conflict" ? new ProjectionFault({
|
|
368
418
|
phase: "pin",
|
|
@@ -398,7 +448,6 @@ const producer = pin(make({
|
|
|
398
448
|
};
|
|
399
449
|
const { identity, adapters } = before.record;
|
|
400
450
|
const streams = detailsOf(request).outputs;
|
|
401
|
-
const ranges = request.unit.ranges;
|
|
402
451
|
const positions = { ...adapters.outputs };
|
|
403
452
|
for (const [name, position] of Record.toEntries(positions)) if (position.epoch !== projection.generation) return yield* new ProjectionFault({
|
|
404
453
|
phase: "load",
|
|
@@ -425,13 +474,7 @@ const producer = pin(make({
|
|
|
425
474
|
if (pending === void 0 && Record.keys(seqs).length > 0) {
|
|
426
475
|
for (const [name, output] of Record.toEntries(streams)) {
|
|
427
476
|
if (seqs[name] === void 0) continue;
|
|
428
|
-
|
|
429
|
-
if ((yield* wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== ownerOf(owner.load) ? Effect.fail(cause) : Streams.create(output.address).pipe(Effect.provideService(StreamsWriter, wire), Effect.andThen(wire.head(output.address.id)))), Effect.mapError((cause) => new ProjectionFault({
|
|
430
|
-
phase: "pin",
|
|
431
|
-
reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
|
|
432
|
-
message: `Cannot prepare output ${output.address.id}`,
|
|
433
|
-
cause
|
|
434
|
-
})))).closed) return yield* new ProjectionFault({
|
|
477
|
+
if ((yield* prepareOutput(output, owner)).closed) return yield* new ProjectionFault({
|
|
435
478
|
phase: "pin",
|
|
436
479
|
reason: "invalid-output",
|
|
437
480
|
message: `Output ${output.address.id} is closed`
|
|
@@ -447,13 +490,10 @@ const producer = pin(make({
|
|
|
447
490
|
adapters: { outputs: { ...positions } },
|
|
448
491
|
pending: {
|
|
449
492
|
seqs,
|
|
450
|
-
ranges:
|
|
451
|
-
from: range.from,
|
|
452
|
-
nextOffset: range.nextOffset,
|
|
453
|
-
count: detailsOf(request).ranges[name]?.count ?? 0
|
|
454
|
-
}]))
|
|
493
|
+
ranges: detailsOf(request).ranges
|
|
455
494
|
}
|
|
456
495
|
};
|
|
496
|
+
if (before.record.closed !== void 0) Object.assign(pinned, { closed: before.record.closed });
|
|
457
497
|
if (before.record.state !== void 0) Object.assign(pinned, { state: before.record.state });
|
|
458
498
|
token = yield* owner.compareAndSet(projection, before.token, pinned).pipe(Effect.mapError(asPin));
|
|
459
499
|
}
|
|
@@ -607,6 +647,7 @@ const declare = (definition, bind) => {
|
|
|
607
647
|
version,
|
|
608
648
|
generation,
|
|
609
649
|
params: definition.params,
|
|
650
|
+
inputs: definition.inputs,
|
|
610
651
|
at: (params) => bind({
|
|
611
652
|
id: definition.id,
|
|
612
653
|
version,
|
|
@@ -661,28 +702,61 @@ function mapAccum(definition) {
|
|
|
661
702
|
function mapAccumBatch(definition) {
|
|
662
703
|
return build("mapAccumBatch", definition);
|
|
663
704
|
}
|
|
705
|
+
// src/forget.ts
|
|
706
|
+
/**
|
|
707
|
+
* Deletes the record. Stop the follower first, or use a new generation.
|
|
708
|
+
* Delete stream outputs first, because forgetting restarts their producer sequences.
|
|
709
|
+
*/
|
|
710
|
+
const forget = (projection) => Effect.gen(function* () {
|
|
711
|
+
if (projection.commit.remove === void 0) return yield* new ProjectionFault({
|
|
712
|
+
phase: "checkpoint",
|
|
713
|
+
reason: "unsupported-composition",
|
|
714
|
+
message: "This Commit does not support forgetting"
|
|
715
|
+
});
|
|
716
|
+
yield* projection.commit.remove(projection);
|
|
717
|
+
return yield* Effect.void;
|
|
718
|
+
});
|
|
664
719
|
// src/snapshot.ts
|
|
665
720
|
/** Internal: the offsets of a record, typed by the declared inputs. */
|
|
666
721
|
const offsetsOf = (record) => record.inputs;
|
|
667
722
|
/**
|
|
723
|
+
* Internal: decodes one encoded state field. The result is the declared initial value
|
|
724
|
+
* when no state is stored, and `undefined` when the declaration has no `state:`.
|
|
725
|
+
*/
|
|
726
|
+
const stateOf = Effect.fnUntraced(function* (projection, encoded) {
|
|
727
|
+
const declared = projection.state;
|
|
728
|
+
const stored = declared === void 0 ? Option.none() : yield* decodeState(projection, declared.schema, Option.fromUndefinedOr(encoded));
|
|
729
|
+
return declared === void 0 ? void 0 : Option.getOrElse(stored, declared.initial);
|
|
730
|
+
});
|
|
731
|
+
/**
|
|
668
732
|
* Reads the state and offsets from one checkpoint record, so the state
|
|
669
733
|
* always matches the offsets. Before the first unit, the state is the declared initial
|
|
670
734
|
* value and every offset is the start of its input.
|
|
671
735
|
*/
|
|
672
736
|
const read = Effect.fn("Projection.read")(function* (projection) {
|
|
673
|
-
const declared = projection.state;
|
|
674
737
|
const restored = yield* restore(projection, projection.commit);
|
|
675
|
-
const encoded = Option.fromUndefinedOr(restored.record.state);
|
|
676
|
-
const stored = declared === void 0 ? Option.none() : yield* decodeState(projection, declared.schema, encoded);
|
|
677
738
|
return {
|
|
678
|
-
state:
|
|
739
|
+
state: yield* stateOf(projection, restored.record.state),
|
|
679
740
|
offsets: offsetsOf(restored.record)
|
|
680
741
|
};
|
|
681
742
|
});
|
|
682
743
|
// src/run.ts
|
|
683
|
-
/**
|
|
684
|
-
|
|
744
|
+
/**
|
|
745
|
+
* Internal: one pass that also returns the encoded state it committed, or the stored
|
|
746
|
+
* state when it found no input.
|
|
747
|
+
*/
|
|
748
|
+
const step = Effect.fn("Projection.pass")(function* (projection) {
|
|
685
749
|
const before = yield* restore(projection, projection.commit);
|
|
750
|
+
if (before.record.ended) {
|
|
751
|
+
yield* forget(projection);
|
|
752
|
+
return {
|
|
753
|
+
status: "source-closed",
|
|
754
|
+
units: 0,
|
|
755
|
+
items: 0,
|
|
756
|
+
offsets: offsetsOf(before.record),
|
|
757
|
+
encoded: before.record.state
|
|
758
|
+
};
|
|
759
|
+
}
|
|
686
760
|
const pending = before.record.pending;
|
|
687
761
|
if (pending !== void 0 && !isPinned(projection.commit)) return yield* new ProjectionFault({
|
|
688
762
|
phase: "load",
|
|
@@ -704,30 +778,40 @@ const pass = Effect.fn("Projection.pass")(function* (projection) {
|
|
|
704
778
|
}
|
|
705
779
|
batch = slices;
|
|
706
780
|
} else {
|
|
707
|
-
const read = yield* readInputs(projection.inputs, before.record.inputs);
|
|
781
|
+
const read = yield* readInputs(projection.inputs, before.record.inputs, Option.isSome(before.loaded.record));
|
|
708
782
|
batch = read.slices;
|
|
709
783
|
count = read.items;
|
|
710
|
-
|
|
784
|
+
const terminal = Array.some(Record.toEntries(batch), ([name, slice]) => slice.gone === true || slice.closed && slice.upToDate && !before.record.closed?.[name]);
|
|
785
|
+
if (count === 0 && !terminal) return {
|
|
711
786
|
status: Array.every(Record.values(batch), (slice) => slice.closed) ? "source-closed" : "caught-up",
|
|
712
787
|
units: 0,
|
|
713
788
|
items: 0,
|
|
714
|
-
offsets: offsetsOf(before.record)
|
|
789
|
+
offsets: offsetsOf(before.record),
|
|
790
|
+
encoded: before.record.state
|
|
715
791
|
};
|
|
716
792
|
}
|
|
793
|
+
const gone = Array.some(Record.values(batch), (slice) => slice.gone === true);
|
|
717
794
|
const ranges = pending?.ranges ?? rangesOf(batch);
|
|
718
795
|
const unit = unitOf(projection.id, projection.version, projection.generation, projection.params, ranges);
|
|
719
796
|
const { pending: _pending, ...record } = before.record;
|
|
797
|
+
const closed = { ...record.closed };
|
|
798
|
+
for (const [name, slice] of Record.toEntries(batch)) if (slice.closed && slice.upToDate) closed[name] = true;
|
|
720
799
|
const next = {
|
|
721
800
|
...record,
|
|
722
|
-
inputs: advance(record.inputs, ranges)
|
|
801
|
+
inputs: advance(record.inputs, ranges),
|
|
802
|
+
closed
|
|
723
803
|
};
|
|
804
|
+
if (gone) Object.assign(next, { ended: true });
|
|
724
805
|
const outputs = {};
|
|
725
806
|
for (const [name, address] of Record.toEntries(projection.streams ?? {})) outputs[name] = {
|
|
726
807
|
address,
|
|
727
808
|
service: yield* address.stream
|
|
728
809
|
};
|
|
729
810
|
let prepared;
|
|
730
|
-
|
|
811
|
+
let result;
|
|
812
|
+
const run = Effect.suspend(() => projection.process(batch, unit, before.record.state, prepared)).pipe(Effect.tap((value) => Effect.sync(() => {
|
|
813
|
+
result = value;
|
|
814
|
+
})), Effect.mapError((error) => new HandlerFailed({ error })));
|
|
731
815
|
const prepare = projection.prepare === void 0 ? void 0 : Effect.suspend(() => projection.prepare(batch, unit)).pipe(Effect.tap((value) => Effect.sync(() => {
|
|
732
816
|
prepared = value;
|
|
733
817
|
})), Effect.asVoid, Effect.mapError((error) => new HandlerFailed({ error })));
|
|
@@ -741,46 +825,71 @@ const pass = Effect.fn("Projection.pass")(function* (projection) {
|
|
|
741
825
|
outputs,
|
|
742
826
|
prepare,
|
|
743
827
|
ranges: Record.fromEntries(Array.map(Record.toEntries(ranges), ([name, range]) => [name, {
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
828
|
+
...range,
|
|
829
|
+
count: batch[name]?.items.length ?? 0,
|
|
830
|
+
closed: batch[name]?.closed ?? false,
|
|
831
|
+
upToDate: batch[name]?.upToDate ?? false
|
|
747
832
|
}]))
|
|
748
833
|
});
|
|
749
834
|
yield* projection.commit.apply(request).pipe(Effect.catchTag("HandlerFailed", (failure) => Effect.fail(failure.error)));
|
|
835
|
+
const stored = withState(next, result);
|
|
836
|
+
if (gone) yield* forget(projection);
|
|
750
837
|
return {
|
|
751
|
-
status: "progress",
|
|
838
|
+
status: gone ? "source-closed" : "progress",
|
|
752
839
|
units: 1,
|
|
753
840
|
items: count,
|
|
754
|
-
offsets: offsetsOf(next)
|
|
841
|
+
offsets: offsetsOf(next),
|
|
842
|
+
encoded: stored.state
|
|
755
843
|
};
|
|
756
844
|
});
|
|
757
|
-
/**
|
|
758
|
-
const
|
|
759
|
-
|
|
845
|
+
/** Restore and adapt one input unit; the Commit owns every write. */
|
|
846
|
+
const pass = (projection) => Effect.map(step(projection), ({ encoded: _encoded, ...result }) => result);
|
|
847
|
+
/** Internal: repeats pass until caught up, closed, or limited. The caller validates options. */
|
|
848
|
+
const catchUp = Effect.fnUntraced(function* (projection, options) {
|
|
760
849
|
const cap = options.limit ?? Number.POSITIVE_INFINITY;
|
|
761
850
|
let units = 0;
|
|
762
851
|
let items = 0;
|
|
763
|
-
let
|
|
852
|
+
let offsets;
|
|
853
|
+
let encoded;
|
|
764
854
|
do {
|
|
765
|
-
result = yield*
|
|
855
|
+
const result = yield* step(projection);
|
|
766
856
|
units += result.units;
|
|
767
857
|
items += result.items;
|
|
858
|
+
offsets = result.offsets;
|
|
859
|
+
encoded = result.encoded;
|
|
768
860
|
if (result.status !== "progress") return {
|
|
769
|
-
|
|
861
|
+
status: result.status,
|
|
770
862
|
units,
|
|
771
|
-
items
|
|
863
|
+
items,
|
|
864
|
+
offsets,
|
|
865
|
+
encoded
|
|
772
866
|
};
|
|
773
867
|
} while (units < cap);
|
|
774
868
|
return {
|
|
775
|
-
...result,
|
|
776
869
|
status: "limit-reached",
|
|
777
870
|
units,
|
|
778
|
-
items
|
|
871
|
+
items,
|
|
872
|
+
offsets,
|
|
873
|
+
encoded
|
|
779
874
|
};
|
|
780
875
|
});
|
|
876
|
+
/** Internal: a cycle with its state decoded once. It reads no checkpoint. */
|
|
877
|
+
const progressOf = (projection, { encoded, ...cycle }) => Effect.map(stateOf(projection, encoded), (state) => ({
|
|
878
|
+
...cycle,
|
|
879
|
+
state
|
|
880
|
+
}));
|
|
881
|
+
/**
|
|
882
|
+
* Repeats pass until caught up, closed, or limited, then decodes the state of the last
|
|
883
|
+
* pass once. After a gone input, the result holds the state that the final unit
|
|
884
|
+
* committed, although the kernel then deletes the record. Use one writer per key.
|
|
885
|
+
*/
|
|
886
|
+
const run = Effect.fn("Projection.run")(function* (projection, options = {}) {
|
|
887
|
+
yield* validateOptions(options);
|
|
888
|
+
return yield* progressOf(projection, yield* catchUp(projection, options));
|
|
889
|
+
});
|
|
781
890
|
// src/retry.ts
|
|
782
891
|
const defaultRetry = Schedule.exponential("200 millis").pipe(Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.millis(Math.min(3e4, Duration.toMillis(duration))))), Schedule.jittered, Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.millis(Math.min(3e4, Duration.toMillis(duration))))));
|
|
783
|
-
/** Default
|
|
892
|
+
/** Default retry for following and attached runners; an explicit options.retry takes precedence. */
|
|
784
893
|
const ProjectionRetry = Context.Reference("@streamsy/projection/ProjectionRetry", { defaultValue: () => defaultRetry });
|
|
785
894
|
// src/follow.ts
|
|
786
895
|
/**
|
|
@@ -788,17 +897,12 @@ const ProjectionRetry = Context.Reference("@streamsy/projection/ProjectionRetry"
|
|
|
788
897
|
* authoritative. Only the response cursor is kept, so the next hint on that
|
|
789
898
|
* input echoes it. A closed input answers `readNext` at once, so a closed and
|
|
790
899
|
* drained input parks for the interval instead of waking every cycle; the
|
|
791
|
-
* open inputs, and the interval itself, decide when the next run happens.
|
|
900
|
+
* open inputs, and the interval itself, decide when the next run happens. A
|
|
901
|
+
* gone input wakes the next run so it can end the binding.
|
|
792
902
|
*/
|
|
793
|
-
const hint = Effect.fn("Projection.
|
|
903
|
+
const hint = Effect.fn("Projection.hint")(function* (input, address, offset, interval, cursors) {
|
|
794
904
|
const cursor = (yield* Ref.get(cursors))[input];
|
|
795
905
|
const { wire: reader } = yield* address.stream;
|
|
796
|
-
const historyUnavailable = () => new ProjectionFault({
|
|
797
|
-
phase: "read",
|
|
798
|
-
reason: "history-unavailable",
|
|
799
|
-
input,
|
|
800
|
-
message: `Required history of ${address.id} after ${offset} is unavailable`
|
|
801
|
-
});
|
|
802
906
|
const storageFailure = (cause) => new ProjectionFault({
|
|
803
907
|
phase: "read",
|
|
804
908
|
reason: "storage-failure",
|
|
@@ -820,8 +924,8 @@ const hint = Effect.fn("Projection.wake")(function* (input, address, offset, int
|
|
|
820
924
|
message: cause.message,
|
|
821
925
|
cause
|
|
822
926
|
}),
|
|
823
|
-
StreamNotFound: () =>
|
|
824
|
-
StreamGone: () =>
|
|
927
|
+
StreamNotFound: () => Effect.void,
|
|
928
|
+
StreamGone: () => Effect.void,
|
|
825
929
|
NotSupported: (error) => new ProjectionFault({
|
|
826
930
|
phase: "read",
|
|
827
931
|
reason: "unsupported-composition",
|
|
@@ -833,12 +937,21 @@ const hint = Effect.fn("Projection.wake")(function* (input, address, offset, int
|
|
|
833
937
|
}), Effect.timeoutOption(interval), Effect.asVoid);
|
|
834
938
|
});
|
|
835
939
|
/**
|
|
836
|
-
*
|
|
837
|
-
*
|
|
838
|
-
*
|
|
839
|
-
*
|
|
940
|
+
* Follows a projection as a pull stream. Each element is one committed cycle: the
|
|
941
|
+
* state and offsets that the last pass left, plus the units and items of the cycle.
|
|
942
|
+
*
|
|
943
|
+
* To run the stream is to be the writer, so run one `follow` stream per key. The next
|
|
944
|
+
* cycle runs only when the consumer pulls, so a slow consumer gets one element that
|
|
945
|
+
* covers all the input that arrived meanwhile. The stream emits after the first cycle,
|
|
946
|
+
* after each cycle that commits a unit or reaches `limit`, and after the last cycle
|
|
947
|
+
* when every input is closed or an input is gone; then it ends. After a gone input, the
|
|
948
|
+
* last element holds the state that the final unit committed, and the kernel then
|
|
949
|
+
* deletes the record. A wake that finds no input emits nothing.
|
|
950
|
+
* Options are checked at the first pull. On HTTP backends a parked hint is cancelled
|
|
951
|
+
* and replaced once per `repairIntervalMs` until an input changes. One
|
|
952
|
+
* `Projection.follow` span covers the whole stream.
|
|
840
953
|
*/
|
|
841
|
-
const follow =
|
|
954
|
+
const follow = (projection, options = {}) => Stream.unwrap(Effect.gen(function* () {
|
|
842
955
|
yield* validateOptions(options);
|
|
843
956
|
const interval = options.repairIntervalMs ?? 3e4;
|
|
844
957
|
if (!Number.isSafeInteger(interval) || interval <= 0) return yield* new ProjectionFault({
|
|
@@ -847,12 +960,166 @@ const follow = Effect.fn("Projection.follow")(function* (projection, options = {
|
|
|
847
960
|
message: "repairIntervalMs must be a positive safe integer"
|
|
848
961
|
});
|
|
849
962
|
const cursors = yield* Ref.make({});
|
|
850
|
-
const
|
|
851
|
-
|
|
963
|
+
const schedule = (options.retry ?? (yield* ProjectionRetry)).pipe(Schedule.tap(({ input }) => Schema.is(ProjectionFault)(input) && input.retryable ? Effect.logWarning("Projection.follow retry", input) : Effect.void));
|
|
964
|
+
const retrying = (effect) => Effect.retry(effect, {
|
|
852
965
|
while: (fault) => Schema.is(ProjectionFault)(fault) && fault.retryable,
|
|
853
|
-
schedule
|
|
854
|
-
})
|
|
966
|
+
schedule
|
|
967
|
+
});
|
|
968
|
+
const wake = (offsets) => Effect.raceAllFirst(Array.map(inputEntries(projection.inputs), ([name, address]) => hint(name, address, offsets[name] ?? ZERO_OFFSET, interval, cursors)));
|
|
969
|
+
/**
|
|
970
|
+
* One cycle, retried on a retryable fault. When it follows a caught-up cycle it
|
|
971
|
+
* first waits for a hint; a retry after a failed wait runs at once.
|
|
972
|
+
*/
|
|
973
|
+
const cycle = (previous) => {
|
|
974
|
+
let waiting = previous?.status === "caught-up";
|
|
975
|
+
return retrying(Effect.suspend(() => {
|
|
976
|
+
const parked = waiting && previous !== void 0;
|
|
977
|
+
waiting = false;
|
|
978
|
+
return parked ? wake(previous.offsets).pipe(Effect.andThen(catchUp(projection, options))) : catchUp(projection, options);
|
|
979
|
+
}));
|
|
980
|
+
};
|
|
981
|
+
/** Runs cycles until one must be emitted: the first, a commit, a limit, or the close. */
|
|
982
|
+
const next = Effect.fnUntraced(function* (previous) {
|
|
983
|
+
let result = yield* cycle(previous);
|
|
984
|
+
if (previous === void 0) return result;
|
|
985
|
+
while (result.status === "caught-up" && result.units === 0) result = yield* cycle(result);
|
|
986
|
+
return result;
|
|
987
|
+
});
|
|
988
|
+
return Stream.unfold(void 0, (previous) => Effect.gen(function* () {
|
|
989
|
+
if (previous?.status === "source-closed") return void 0;
|
|
990
|
+
const result = yield* next(previous);
|
|
991
|
+
return [yield* progressOf(projection, result), result];
|
|
992
|
+
}));
|
|
993
|
+
})).pipe(Stream.withSpan("Projection.follow"));
|
|
994
|
+
/**
|
|
995
|
+
* The binding of a written stream id, if the projection reads that id.
|
|
996
|
+
*
|
|
997
|
+
* The rule: each input must give every projection param, so that one id picks
|
|
998
|
+
* one binding. A declaration input with a template is checked here and throws a
|
|
999
|
+
* RangeError. A custom route has no template, so an id whose parse misses a
|
|
1000
|
+
* param is skipped. A fixed address triggers only a projection with no params.
|
|
1001
|
+
*/
|
|
1002
|
+
const matcher = (declaration) => {
|
|
1003
|
+
const names = Record.keys(declaration.params);
|
|
1004
|
+
const inputs = Record.toEntries(declaration.inputs);
|
|
1005
|
+
for (const [name, input] of inputs) {
|
|
1006
|
+
const given = isDeclaration(input) ? input.template.length === 0 ? names : compileSegments(input.template).names : [];
|
|
1007
|
+
const missing = Array.filter(names, (param) => !given.includes(param));
|
|
1008
|
+
if (missing.length > 0) throw new RangeError(`Projection ${declaration.id} cannot attach: input ${name} does not give param ${Array.join(missing, ", ")}`);
|
|
1009
|
+
}
|
|
1010
|
+
const bound = (params) => {
|
|
1011
|
+
const binding = declaration.at(params);
|
|
1012
|
+
return Option.some([canonicalParams(binding.params), binding]);
|
|
1013
|
+
};
|
|
1014
|
+
return (id) => {
|
|
1015
|
+
for (const [, input] of inputs) {
|
|
1016
|
+
if (!isDeclaration(input)) {
|
|
1017
|
+
if (input.id === id) return bound({});
|
|
1018
|
+
continue;
|
|
1019
|
+
}
|
|
1020
|
+
const parsed = input.parse(id);
|
|
1021
|
+
if (Option.isNone(parsed)) continue;
|
|
1022
|
+
const params = parsed.value;
|
|
1023
|
+
if (Array.every(names, (name) => name in params)) return bound(params);
|
|
1024
|
+
}
|
|
1025
|
+
return Option.none();
|
|
1026
|
+
};
|
|
1027
|
+
};
|
|
1028
|
+
/**
|
|
1029
|
+
* A binding that faults with `history-unavailable` on an input whose head is
|
|
1030
|
+
* absent can never run: its source is gone, and an id never returns. With a
|
|
1031
|
+
* checkpoint, `readOrGone` turns this into a `gone` unit, so only a binding
|
|
1032
|
+
* with no checkpoint reaches here. Any other head answer keeps the fault.
|
|
1033
|
+
*/
|
|
1034
|
+
const sourceGone = (inputs, cause) => Effect.gen(function* () {
|
|
1035
|
+
const fault = Cause.findErrorOption(cause).pipe(Option.filter((error) => Schema.is(ProjectionFault)(error) && error.reason === "history-unavailable"));
|
|
1036
|
+
if (Option.isNone(fault) || fault.value.input === void 0) return false;
|
|
1037
|
+
const input = fault.value.input;
|
|
1038
|
+
const address = Array.findFirst(inputEntries(inputs), ([name]) => name === input);
|
|
1039
|
+
if (Option.isNone(address)) return false;
|
|
1040
|
+
const { wire } = yield* address.value[1].stream;
|
|
1041
|
+
return yield* wire.head(address.value[1].id).pipe(Effect.as(false), Effect.catchTags({
|
|
1042
|
+
StreamNotFound: () => Effect.succeed(true),
|
|
1043
|
+
StreamGone: () => Effect.succeed(true)
|
|
1044
|
+
}), Effect.orElseSucceed(() => false));
|
|
855
1045
|
});
|
|
1046
|
+
/**
|
|
1047
|
+
* One scoped commit subscription and pending set, shared by the two host
|
|
1048
|
+
* adapters. The subscription exists when this effect returns, so a commit
|
|
1049
|
+
* after that point always marks its binding.
|
|
1050
|
+
*/
|
|
1051
|
+
const runnerOf = (declaration, limit = 100) => {
|
|
1052
|
+
if (!Number.isSafeInteger(limit) || limit <= 0) throw new RangeError("Projection.attach limit must be a positive safe integer");
|
|
1053
|
+
const match = matcher(declaration);
|
|
1054
|
+
return Effect.gen(function* () {
|
|
1055
|
+
const committed = yield* (yield* Storage).committed;
|
|
1056
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1057
|
+
const add = (ids) => {
|
|
1058
|
+
for (const id of ids) {
|
|
1059
|
+
const found = match(id);
|
|
1060
|
+
if (Option.isSome(found)) pending.set(found.value[0], found.value[1]);
|
|
1061
|
+
}
|
|
1062
|
+
};
|
|
1063
|
+
const absorb = Effect.map(PubSub.takeUpTo(committed, Number.POSITIVE_INFINITY), Array.forEach(add));
|
|
1064
|
+
return {
|
|
1065
|
+
next: Effect.gen(function* () {
|
|
1066
|
+
yield* absorb;
|
|
1067
|
+
return pending.size > 0 ? Option.some(yield* Clock.currentTimeMillis) : Option.none();
|
|
1068
|
+
}),
|
|
1069
|
+
wait: Effect.gen(function* () {
|
|
1070
|
+
yield* absorb;
|
|
1071
|
+
if (pending.size === 0) add(yield* PubSub.take(committed));
|
|
1072
|
+
}),
|
|
1073
|
+
drain: Effect.fn("Projection.drain")(function* () {
|
|
1074
|
+
yield* absorb;
|
|
1075
|
+
let failure;
|
|
1076
|
+
for (const [key, binding] of Array.fromIterable(pending)) {
|
|
1077
|
+
pending.delete(key);
|
|
1078
|
+
const exit = yield* Effect.exit(run(binding, { limit }));
|
|
1079
|
+
if (Exit.isSuccess(exit) && exit.value.status !== "limit-reached") continue;
|
|
1080
|
+
if (Exit.isFailure(exit) && (yield* sourceGone(binding.inputs, exit.cause))) {
|
|
1081
|
+
yield* Effect.logWarning(`Projection ${declaration.id} dropped binding ${key}: its source was removed before its first run`);
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
pending.set(key, binding);
|
|
1085
|
+
if (Exit.isFailure(exit)) failure ??= exit.cause;
|
|
1086
|
+
}
|
|
1087
|
+
yield* absorb;
|
|
1088
|
+
if (failure !== void 0) return yield* Effect.failCause(failure);
|
|
1089
|
+
return { more: pending.size > 0 };
|
|
1090
|
+
})()
|
|
1091
|
+
};
|
|
1092
|
+
});
|
|
1093
|
+
};
|
|
1094
|
+
// src/attach.ts
|
|
1095
|
+
/**
|
|
1096
|
+
* Run a projection whenever a local commit writes one of its inputs. The layer
|
|
1097
|
+
* subscribes to `Storage.committed` when it is built, so build it with the
|
|
1098
|
+
* storage layer and before the app writes. For each written id, the input's
|
|
1099
|
+
* `parse` gives the params, and the runner runs `projection.at(params)`.
|
|
1100
|
+
*
|
|
1101
|
+
* Use it on long-lived hosts (Bun, Node). On a Cloudflare object, use
|
|
1102
|
+
* `ProjectionWakeup.attach(projection)`.
|
|
1103
|
+
*
|
|
1104
|
+
* The set of bindings with work lives in memory. A crash after a commit and
|
|
1105
|
+
* before the run leaves that binding late until its source gets its next write.
|
|
1106
|
+
* Inputs on another owner never commit here, so they never trigger. Do not run
|
|
1107
|
+
* an attached binding under `Projection.follow` too: use one writer per key.
|
|
1108
|
+
*
|
|
1109
|
+
* ```ts
|
|
1110
|
+
* const app = Layer.mergeAll(Api, Projection.attach(filesWake)).pipe(
|
|
1111
|
+
* Layer.provideMerge(BunStorage.layer(streams, { path })),
|
|
1112
|
+
* );
|
|
1113
|
+
* ```
|
|
1114
|
+
*/
|
|
1115
|
+
const attach$1 = (projection, options = {}) => {
|
|
1116
|
+
const runner = runnerOf(projection, options.limit);
|
|
1117
|
+
return Layer.effectDiscard(Effect.gen(function* () {
|
|
1118
|
+
const { wait, drain } = yield* runner;
|
|
1119
|
+
const retry = options.retry ?? (yield* ProjectionRetry);
|
|
1120
|
+
yield* wait.pipe(Effect.andThen(drain.pipe(Effect.tapError((error) => Effect.logError(`Projection.attach ${projection.id} failed`, error)), Effect.retry(retry))), Effect.repeat(Schedule.forever), Effect.withSpan("Projection.attach"), Effect.forkScoped);
|
|
1121
|
+
}));
|
|
1122
|
+
};
|
|
856
1123
|
// src/current.ts
|
|
857
1124
|
/**
|
|
858
1125
|
* Folds the checkpoint and input tail in memory, without locks or writes.
|
|
@@ -929,22 +1196,57 @@ const retryLostRace = Effect.fnUntraced(function* (attempt, schedule) {
|
|
|
929
1196
|
return yield* Effect.fromResult(outcome);
|
|
930
1197
|
});
|
|
931
1198
|
const isOffsetMismatch = (error) => Predicate.isTagged(error, "OffsetMismatch");
|
|
932
|
-
// src/
|
|
1199
|
+
// src/wake.ts
|
|
1200
|
+
const row = (stream, offset, closed) => DurableState.upsert("stream", closed ? {
|
|
1201
|
+
stream,
|
|
1202
|
+
offset: Offset.make(offset),
|
|
1203
|
+
closed: true
|
|
1204
|
+
} : {
|
|
1205
|
+
stream,
|
|
1206
|
+
offset: Offset.make(offset)
|
|
1207
|
+
});
|
|
933
1208
|
/**
|
|
934
|
-
*
|
|
935
|
-
*
|
|
1209
|
+
* A wake projection: one source stream gives one keyed row in one wake stream.
|
|
1210
|
+
* Each unit appends one upsert `{ stream, offset, closed? }` with
|
|
1211
|
+
* `Commit.producer`, so several source writes in one unit fold into one row,
|
|
1212
|
+
* and a retry answers `Duplicate`. The producer creates a missing wake stream
|
|
1213
|
+
* on its own owner. A wake stream on another owner must exist before the first
|
|
1214
|
+
* append: its owner creates it at start. When the source is removed or
|
|
1215
|
+
* expires, the binding appends a State delete for its row and forgets itself.
|
|
1216
|
+
*
|
|
1217
|
+
* ```ts
|
|
1218
|
+
* const filesWake = Projection.wake({
|
|
1219
|
+
* id: "files-wake",
|
|
1220
|
+
* params: { user: UserKey, folderId: FolderKey },
|
|
1221
|
+
* input: Files,
|
|
1222
|
+
* output: UserWake,
|
|
1223
|
+
* });
|
|
1224
|
+
* ```
|
|
936
1225
|
*/
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
1226
|
+
function wake(definition) {
|
|
1227
|
+
const input = definition.input;
|
|
1228
|
+
return build("mapAccumBatch", {
|
|
1229
|
+
id: definition.id,
|
|
1230
|
+
version: definition.version,
|
|
1231
|
+
generation: definition.generation,
|
|
1232
|
+
params: definition.params,
|
|
1233
|
+
commit: producer,
|
|
1234
|
+
inputs: { source: input },
|
|
1235
|
+
outputs: { wake: definition.output },
|
|
1236
|
+
state: {
|
|
1237
|
+
schema: Schema.Null,
|
|
1238
|
+
initial: null
|
|
1239
|
+
},
|
|
1240
|
+
mapAccumBatch: (_state, batch, unit) => {
|
|
1241
|
+
const source = isDeclaration(input) ? input.at(unit.params) : input;
|
|
1242
|
+
const slice = batch.source;
|
|
1243
|
+
return [null, { wake: [slice.gone ? DurableState.remove("stream", StreamId.make(source.id)) : row(StreamId.make(source.id), slice.nextOffset, slice.closed)] }];
|
|
1244
|
+
}
|
|
942
1245
|
});
|
|
943
|
-
|
|
944
|
-
return yield* Effect.void;
|
|
945
|
-
});
|
|
1246
|
+
}
|
|
946
1247
|
// src/projection.ts
|
|
947
1248
|
var projection_exports = /* @__PURE__ */ __exportAll({
|
|
1249
|
+
attach: () => attach$1,
|
|
948
1250
|
current: () => current,
|
|
949
1251
|
decide: () => decide,
|
|
950
1252
|
each: () => each,
|
|
@@ -959,7 +1261,8 @@ var projection_exports = /* @__PURE__ */ __exportAll({
|
|
|
959
1261
|
pass: () => pass,
|
|
960
1262
|
process: () => process,
|
|
961
1263
|
read: () => read,
|
|
962
|
-
run: () => run
|
|
1264
|
+
run: () => run,
|
|
1265
|
+
wake: () => wake
|
|
963
1266
|
});
|
|
964
1267
|
const key = (projection) => ({
|
|
965
1268
|
id: projection.id,
|
|
@@ -969,4 +1272,23 @@ const key = (projection) => ({
|
|
|
969
1272
|
});
|
|
970
1273
|
/** Runs each tagged entry in order and discards its success value. */
|
|
971
1274
|
const each = (handle) => (batch, unit) => Effect.forEach(items(batch), (entry) => handle(entry, unit), { discard: true });
|
|
972
|
-
|
|
1275
|
+
// src/wakeup.ts
|
|
1276
|
+
/**
|
|
1277
|
+
* Local commits choose bindings; each alarm drains the same runner used by
|
|
1278
|
+
* Projection.attach. Acquire it in the object layer's scope, before any
|
|
1279
|
+
* request writes.
|
|
1280
|
+
*/
|
|
1281
|
+
const attach = (projection, options = {}) => {
|
|
1282
|
+
const runner = runnerOf(projection, options.limit);
|
|
1283
|
+
return Effect.gen(function* () {
|
|
1284
|
+
const { next, drain } = yield* runner;
|
|
1285
|
+
return {
|
|
1286
|
+
name: `streamsy/projection/${encodeURIComponent(projection.id)}`,
|
|
1287
|
+
next,
|
|
1288
|
+
run: drain,
|
|
1289
|
+
retry: options.retry ?? (yield* ProjectionRetry)
|
|
1290
|
+
};
|
|
1291
|
+
});
|
|
1292
|
+
};
|
|
1293
|
+
const ProjectionWakeup = { attach };
|
|
1294
|
+
export { CheckpointRecord, CheckpointStore, commit_exports as Commit, HandlerFailed, projection_exports as Projection, ProjectionFault, ProjectionRetry, ProjectionWakeup, Transaction };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@streamsy/projection",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Checkpointed Effect projections over one or more retained streams.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"test:dialects": "bun --bun vitest run test/sql-dialects.test.ts"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@streamsy/core": "^0.
|
|
40
|
+
"@streamsy/core": "^0.6.0"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@cloudflare/workers-types": "4.20251228.0",
|
|
@@ -47,8 +47,8 @@
|
|
|
47
47
|
"@effect/sql-sqlite-bun": "4.0.5",
|
|
48
48
|
"@effect/sql-sqlite-do": "4.0.5",
|
|
49
49
|
"@effect/vitest": "4.0.5",
|
|
50
|
-
"@streamsy/serve": "0.
|
|
51
|
-
"@streamsy/storage": "0.
|
|
50
|
+
"@streamsy/serve": "0.6.0",
|
|
51
|
+
"@streamsy/storage": "0.6.0",
|
|
52
52
|
"@types/bun": "^1.4.3",
|
|
53
53
|
"effect": "4.0.5",
|
|
54
54
|
"miniflare": "4.20260730.0",
|