@streamsy/projection 0.12.0 → 0.14.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 +66 -31
- package/dist/checkpoint-store-BE0zelau.js +459 -0
- package/dist/{checkpoint-store-DCfrS4Fd.d.ts → checkpoint-store-Cy5myzCL.d.ts} +42 -7
- package/dist/checkpoint.d.ts +2 -2
- package/dist/checkpoint.js +1 -1
- package/dist/index.d.ts +253 -66
- package/dist/index.js +817 -188
- package/package.json +4 -4
- package/dist/checkpoint-store--bWf1qeP.js +0 -296
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@streamsy/projection",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.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.14.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.1.2",
|
|
48
48
|
"@effect/sql-sqlite-do": "4.1.2",
|
|
49
49
|
"@effect/vitest": "4.1.2",
|
|
50
|
-
"@streamsy/serve": "0.
|
|
51
|
-
"@streamsy/storage": "0.
|
|
50
|
+
"@streamsy/serve": "0.14.0",
|
|
51
|
+
"@streamsy/storage": "0.14.0",
|
|
52
52
|
"@types/bun": "^1.4.3",
|
|
53
53
|
"effect": "4.1.2",
|
|
54
54
|
"miniflare": "4.20260730.0",
|
|
@@ -1,296 +0,0 @@
|
|
|
1
|
-
import { Array, Context, Effect, Layer, Option, Order, Record, Schema, Semaphore } from "effect";
|
|
2
|
-
import { CommitBoundary, ZERO_OFFSET, isStreamsFault } from "@streamsy/core";
|
|
3
|
-
import { OwnerRecords, attachOwner, ownerOf } from "@streamsy/core/internal";
|
|
4
|
-
// src/fault.ts
|
|
5
|
-
/** No live runner for this declaration exists in the selected registry. */
|
|
6
|
-
var NotAttached = class extends Schema.TaggedError()("NotAttached", { projection: Schema.String }) {};
|
|
7
|
-
/** Encoded params do not round-trip through the attached declaration's codecs. */
|
|
8
|
-
var InvalidBinding = class extends Schema.TaggedError()("InvalidBinding", {
|
|
9
|
-
projection: Schema.String,
|
|
10
|
-
params: Schema.Record(Schema.String, Schema.String)
|
|
11
|
-
}) {};
|
|
12
|
-
/** Phase says where the run stopped; a `checkpoint` failure means processing already completed. */
|
|
13
|
-
var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
|
|
14
|
-
phase: Schema.Literals([
|
|
15
|
-
"load",
|
|
16
|
-
"read",
|
|
17
|
-
"pin",
|
|
18
|
-
"process",
|
|
19
|
-
"checkpoint"
|
|
20
|
-
]),
|
|
21
|
-
reason: Schema.Literals([
|
|
22
|
-
"history-unavailable",
|
|
23
|
-
"identity-mismatch",
|
|
24
|
-
"invalid-record",
|
|
25
|
-
"invalid-source",
|
|
26
|
-
"invalid-options",
|
|
27
|
-
"invalid-output",
|
|
28
|
-
"token-conflict",
|
|
29
|
-
"output-busy",
|
|
30
|
-
"range-unreproducible",
|
|
31
|
-
"stale-epoch",
|
|
32
|
-
"storage-failure",
|
|
33
|
-
"unsupported-composition"
|
|
34
|
-
]),
|
|
35
|
-
input: Schema.optionalKey(Schema.String),
|
|
36
|
-
message: Schema.String,
|
|
37
|
-
cause: Schema.optionalKey(Schema.Defect())
|
|
38
|
-
}) {
|
|
39
|
-
get retryable() {
|
|
40
|
-
switch (this.reason) {
|
|
41
|
-
case "storage-failure": return !isStreamsFault(this.cause) || this.cause.retryable;
|
|
42
|
-
case "token-conflict":
|
|
43
|
-
case "output-busy": return true;
|
|
44
|
-
case "history-unavailable":
|
|
45
|
-
case "identity-mismatch":
|
|
46
|
-
case "invalid-record":
|
|
47
|
-
case "invalid-source":
|
|
48
|
-
case "invalid-options":
|
|
49
|
-
case "invalid-output":
|
|
50
|
-
case "range-unreproducible":
|
|
51
|
-
case "stale-epoch":
|
|
52
|
-
case "unsupported-composition": return false;
|
|
53
|
-
}
|
|
54
|
-
return false;
|
|
55
|
-
}
|
|
56
|
-
};
|
|
57
|
-
// src/unit.ts
|
|
58
|
-
/** Length-safe encoding of inert string components; no persistence decoding here. */
|
|
59
|
-
const encodeKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
|
|
60
|
-
const Counter = Schema.Finite.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0));
|
|
61
|
-
const terminal = {
|
|
62
|
-
closed: Schema.optionalKey(Schema.Boolean),
|
|
63
|
-
gone: Schema.optionalKey(Schema.Literal(true))
|
|
64
|
-
};
|
|
65
|
-
Schema.Struct({
|
|
66
|
-
from: Schema.String,
|
|
67
|
-
nextOffset: Schema.String,
|
|
68
|
-
...terminal
|
|
69
|
-
});
|
|
70
|
-
/** A range with the item count a retry must reproduce exactly. */
|
|
71
|
-
const PinnedRange = Schema.Struct({
|
|
72
|
-
from: Schema.String,
|
|
73
|
-
nextOffset: Schema.String,
|
|
74
|
-
count: Counter,
|
|
75
|
-
upToDate: Schema.optionalKey(Schema.Boolean),
|
|
76
|
-
...terminal
|
|
77
|
-
});
|
|
78
|
-
/** A unit pinned before its handler or append; settled by the next pass. */
|
|
79
|
-
const PendingUnit = Schema.Struct({
|
|
80
|
-
ranges: Schema.Record(Schema.String, PinnedRange),
|
|
81
|
-
/** Recorded wake time, preserved across retries. */
|
|
82
|
-
due: Schema.optionalKey(Counter),
|
|
83
|
-
seqs: Schema.optionalKey(Schema.Record(Schema.String, Counter))
|
|
84
|
-
});
|
|
85
|
-
/** Deterministic JSON: keys sorted, so equal maps always encode identically. */
|
|
86
|
-
const canonicalParams = (params) => JSON.stringify(Record.fromEntries(Array.map(Array.sort(Record.keys(params), Order.String), (k) => [k, params[k]])));
|
|
87
|
-
const terminalOf = (source) => {
|
|
88
|
-
const keys = {};
|
|
89
|
-
if (source.closed === true) keys.closed = true;
|
|
90
|
-
if (source.gone === true) keys.gone = true;
|
|
91
|
-
return keys;
|
|
92
|
-
};
|
|
93
|
-
const canonicalRanges = (ranges) => JSON.stringify(Record.fromEntries(Array.map(Array.sort(Record.keys(ranges), Order.String), (k) => {
|
|
94
|
-
const range = ranges[k];
|
|
95
|
-
return [k, {
|
|
96
|
-
from: range?.from,
|
|
97
|
-
nextOffset: range?.nextOffset,
|
|
98
|
-
...terminalOf(range ?? {})
|
|
99
|
-
}];
|
|
100
|
-
})));
|
|
101
|
-
/** The key is stable across producer retries; transaction retries may read a longer tail. */
|
|
102
|
-
const unitOf = (projectionId, version, generation, params, ranges, due) => ({
|
|
103
|
-
projectionId,
|
|
104
|
-
version,
|
|
105
|
-
generation,
|
|
106
|
-
params,
|
|
107
|
-
ranges,
|
|
108
|
-
due: Option.fromUndefinedOr(due),
|
|
109
|
-
key: encodeKey([
|
|
110
|
-
projectionId,
|
|
111
|
-
String(generation),
|
|
112
|
-
canonicalParams(params),
|
|
113
|
-
canonicalRanges(ranges),
|
|
114
|
-
...due === void 0 ? [] : [String(due)]
|
|
115
|
-
])
|
|
116
|
-
});
|
|
117
|
-
/** The handler view of a kernel unit, with the decoded params. */
|
|
118
|
-
const withParams = (unit, params) => ({
|
|
119
|
-
...unit,
|
|
120
|
-
params
|
|
121
|
-
});
|
|
122
|
-
// src/checkpoint-store.ts
|
|
123
|
-
const CheckpointRecord = Schema.Struct({
|
|
124
|
-
identity: Schema.Struct({ inputs: Schema.Record(Schema.String, Schema.String) }),
|
|
125
|
-
/** Input key to accepted offset; the next pass reads after these. */
|
|
126
|
-
inputs: Schema.Record(Schema.String, Schema.String),
|
|
127
|
-
pending: Schema.optionalKey(PendingUnit),
|
|
128
|
-
/** Next process wake, in epoch milliseconds. Absent means no timer. */
|
|
129
|
-
wakeAt: Schema.optionalKey(Counter),
|
|
130
|
-
/** Inputs whose terminal close has already been processed. */
|
|
131
|
-
closed: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)),
|
|
132
|
-
/** The final gone unit committed; only forgetting remains. */
|
|
133
|
-
ended: Schema.optionalKey(Schema.Literal(true)),
|
|
134
|
-
state: Schema.optionalKey(Schema.String),
|
|
135
|
-
adapters: Schema.Struct({ outputs: Schema.optionalKey(Schema.Record(Schema.String, Schema.Struct({
|
|
136
|
-
epoch: Counter,
|
|
137
|
-
nextSeq: Counter
|
|
138
|
-
}))) })
|
|
139
|
-
});
|
|
140
|
-
/** Stored value. The version is the compare-and-set token exposed as a string. */
|
|
141
|
-
const Envelope = Schema.Struct({
|
|
142
|
-
version: Counter,
|
|
143
|
-
record: CheckpointRecord
|
|
144
|
-
});
|
|
145
|
-
const EnvelopeJson = Schema.fromJsonString(Envelope);
|
|
146
|
-
const recordKey = (key) => encodeKey([
|
|
147
|
-
"streamsy.projection.v1",
|
|
148
|
-
key.id,
|
|
149
|
-
String(key.version),
|
|
150
|
-
String(key.generation),
|
|
151
|
-
canonicalParams(key.params)
|
|
152
|
-
]);
|
|
153
|
-
/** Token "0" means no record is stored yet. */
|
|
154
|
-
const ABSENT_TOKEN = "0";
|
|
155
|
-
const storageFailure = (phase, message) => (cause) => new ProjectionFault({
|
|
156
|
-
phase,
|
|
157
|
-
reason: "storage-failure",
|
|
158
|
-
message,
|
|
159
|
-
cause
|
|
160
|
-
});
|
|
161
|
-
/**
|
|
162
|
-
* SQL storage fails a write with this operation when the transaction read the key as
|
|
163
|
-
* absent and a concurrent save created it first. That save won the compare-and-set.
|
|
164
|
-
*/
|
|
165
|
-
const OWNER_RECORD_CONFLICT = "records.conflict";
|
|
166
|
-
/** Stores each projection's offsets and encoded state in one compare-and-set record. */
|
|
167
|
-
var CheckpointStore = class extends Context.Service()("@streamsy/projection/CheckpointStore") {
|
|
168
|
-
/**
|
|
169
|
-
* Checkpoints on the storage owner, in its transaction. Works over every Streamsy
|
|
170
|
-
* storage host, so checkpoints and streams always share one owner.
|
|
171
|
-
*/
|
|
172
|
-
static layer = Layer.effect(this, Effect.gen(function* () {
|
|
173
|
-
const boundary = yield* CommitBoundary;
|
|
174
|
-
const records = yield* OwnerRecords;
|
|
175
|
-
const checkpoints = fromStore({
|
|
176
|
-
read: (key) => records.read(key).pipe(Effect.mapError(storageFailure("load", "Cannot read a checkpoint"))),
|
|
177
|
-
write: (key, value) => records.write(key, value).pipe(Effect.mapError((cause) => cause.operation === OWNER_RECORD_CONFLICT ? new ProjectionFault({
|
|
178
|
-
phase: "checkpoint",
|
|
179
|
-
reason: "token-conflict",
|
|
180
|
-
message: "A second writer on the same key likely created the checkpoint first. Use one writer per key: the follower or one run at a time.",
|
|
181
|
-
cause
|
|
182
|
-
}) : storageFailure("checkpoint", "Cannot write a checkpoint")(cause))),
|
|
183
|
-
remove: (key) => records.remove(key).pipe(Effect.mapError(storageFailure("checkpoint", "Cannot delete a checkpoint"))),
|
|
184
|
-
withTransaction: (body) => boundary.withTransaction(body).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(new ProjectionFault({
|
|
185
|
-
phase: "checkpoint",
|
|
186
|
-
reason: "storage-failure",
|
|
187
|
-
message: "The owner transaction failed",
|
|
188
|
-
cause
|
|
189
|
-
}))))
|
|
190
|
-
});
|
|
191
|
-
attachOwner(checkpoints.load, ownerOf(boundary));
|
|
192
|
-
return checkpoints;
|
|
193
|
-
}));
|
|
194
|
-
/** An independent store for rebuilt values and tests. It shares no owner with streams. */
|
|
195
|
-
static layerMemory = Layer.effect(this, Effect.gen(function* () {
|
|
196
|
-
const records = /* @__PURE__ */ new Map();
|
|
197
|
-
const lock = yield* Semaphore.make(1);
|
|
198
|
-
return fromStore({
|
|
199
|
-
read: (key) => Effect.sync(() => Option.fromUndefinedOr(records.get(key))),
|
|
200
|
-
write: (key, value) => Effect.sync(() => {
|
|
201
|
-
records.set(key, value);
|
|
202
|
-
}),
|
|
203
|
-
remove: (key) => lock.withPermits(1)(Effect.sync(() => {
|
|
204
|
-
records.delete(key);
|
|
205
|
-
})),
|
|
206
|
-
withTransaction: lock.withPermits(1)
|
|
207
|
-
});
|
|
208
|
-
}));
|
|
209
|
-
};
|
|
210
|
-
const fromStore = (store) => {
|
|
211
|
-
const load = Effect.fn("Projection.CheckpointStore.load")(function* (key) {
|
|
212
|
-
const encoded = yield* store.read(recordKey(key));
|
|
213
|
-
if (Option.isNone(encoded)) return {
|
|
214
|
-
record: Option.none(),
|
|
215
|
-
token: ABSENT_TOKEN
|
|
216
|
-
};
|
|
217
|
-
const envelope = yield* Schema.decodeEffect(EnvelopeJson)(encoded.value).pipe(Effect.mapError(() => new ProjectionFault({
|
|
218
|
-
phase: "load",
|
|
219
|
-
reason: "invalid-record",
|
|
220
|
-
message: `Invalid stored record for ${key.id}`
|
|
221
|
-
})));
|
|
222
|
-
return {
|
|
223
|
-
record: Option.some(envelope.record),
|
|
224
|
-
token: String(envelope.version)
|
|
225
|
-
};
|
|
226
|
-
});
|
|
227
|
-
return {
|
|
228
|
-
load,
|
|
229
|
-
compareAndSet: Effect.fn("Projection.CheckpointStore.compareAndSet")(function* (key, ifToken, record) {
|
|
230
|
-
return yield* store.withTransaction(Effect.gen(function* () {
|
|
231
|
-
const current = yield* load(key);
|
|
232
|
-
if (current.token !== ifToken) return yield* new ProjectionFault({
|
|
233
|
-
phase: "checkpoint",
|
|
234
|
-
reason: "token-conflict",
|
|
235
|
-
message: `Record for ${key.id} changed: expected token ${ifToken}, found ${current.token}. A second writer on the same key is the likely cause. Use one writer per key: the follower or one run at a time.`
|
|
236
|
-
});
|
|
237
|
-
const version = Number(ifToken) + 1;
|
|
238
|
-
const encoded = yield* Schema.encodeEffect(EnvelopeJson)({
|
|
239
|
-
version,
|
|
240
|
-
record
|
|
241
|
-
}).pipe(Effect.mapError(() => new ProjectionFault({
|
|
242
|
-
phase: "checkpoint",
|
|
243
|
-
reason: "invalid-record",
|
|
244
|
-
message: `Cannot encode record for ${key.id}`
|
|
245
|
-
})));
|
|
246
|
-
yield* store.write(recordKey(key), encoded);
|
|
247
|
-
return String(version);
|
|
248
|
-
}));
|
|
249
|
-
}),
|
|
250
|
-
remove: (key) => store.remove(recordKey(key))
|
|
251
|
-
};
|
|
252
|
-
};
|
|
253
|
-
const identityOf = (inputs) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, address]) => [name, encodeKey([address.id, address.contentType])]));
|
|
254
|
-
const sameIdentity = (a, b) => {
|
|
255
|
-
const keys = Record.keys(a);
|
|
256
|
-
return keys.length === Record.keys(b).length && Array.every(keys, (k) => a[k] === b[k]);
|
|
257
|
-
};
|
|
258
|
-
/** The stored record, or the unstored initial record for a fresh key. */
|
|
259
|
-
const restore = Effect.fn("Projection.restore")(function* (projection, owner) {
|
|
260
|
-
const loaded = yield* owner.load(projection);
|
|
261
|
-
const identity = { inputs: identityOf(projection.inputs) };
|
|
262
|
-
if (Option.isNone(loaded.record)) return {
|
|
263
|
-
record: {
|
|
264
|
-
identity,
|
|
265
|
-
inputs: Record.fromEntries(Array.map(Record.keys(projection.inputs), (name) => [name, ZERO_OFFSET])),
|
|
266
|
-
adapters: {}
|
|
267
|
-
},
|
|
268
|
-
token: loaded.token,
|
|
269
|
-
loaded
|
|
270
|
-
};
|
|
271
|
-
if (!sameIdentity(loaded.record.value.identity.inputs, identity.inputs)) return yield* new ProjectionFault({
|
|
272
|
-
phase: "load",
|
|
273
|
-
reason: "identity-mismatch",
|
|
274
|
-
message: `Stored inputs differ from the declaration of ${projection.id}`
|
|
275
|
-
});
|
|
276
|
-
for (const name of Record.keys(projection.inputs)) if (loaded.record.value.inputs[name] === void 0) return yield* new ProjectionFault({
|
|
277
|
-
phase: "load",
|
|
278
|
-
reason: "invalid-record",
|
|
279
|
-
input: name,
|
|
280
|
-
message: `Stored record of ${projection.id} has no offset for ${name}`
|
|
281
|
-
});
|
|
282
|
-
return {
|
|
283
|
-
record: loaded.record.value,
|
|
284
|
-
token: loaded.token,
|
|
285
|
-
loaded
|
|
286
|
-
};
|
|
287
|
-
});
|
|
288
|
-
/** Accepted offsets after a unit: every read input moves to its `nextOffset`. */
|
|
289
|
-
const advance = (inputs, ranges) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, offset]) => [name, ranges[name]?.nextOffset ?? offset]));
|
|
290
|
-
/** Items and terminal outcomes contribute ranges, including zero-length terminal ranges. */
|
|
291
|
-
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, {
|
|
292
|
-
from: slice.from,
|
|
293
|
-
nextOffset: slice.nextOffset,
|
|
294
|
-
...terminalOf(slice)
|
|
295
|
-
}]));
|
|
296
|
-
export { rangesOf as a, canonicalParams as c, unitOf as d, withParams as f, ProjectionFault as h, fromStore as i, encodeKey as l, NotAttached as m, CheckpointStore as n, recordKey as o, InvalidBinding as p, advance as r, restore as s, CheckpointRecord as t, terminalOf as u };
|