@streamsy/core 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{create-validation-C_aJJm5u.js → create-validation-NKP81BC0.js} +1 -1
- package/dist/http/index.d.ts +1 -1
- package/dist/http/index.js +2 -2
- package/dist/{http-BNYNMGuk.js → http-aCMEaxro.js} +2 -2
- package/dist/{index-D-n48qXe.d.ts → index-DIx4D2t0.d.ts} +329 -152
- package/dist/index.d.ts +3 -3
- package/dist/index.js +52 -184
- package/dist/internal/index.d.ts +254 -26
- package/dist/internal/index.js +12 -3
- package/dist/{layer-pomDIajD.js → layer-DTOhxWkw.js} +19 -19
- package/dist/{layer-C-8GAL_W.js → layer-Dv_LBCgD.js} +15 -8
- package/dist/{program-DhW5In9U.js → program-gGLU50A1.js} +11 -9
- package/dist/protocol/index.d.ts +1 -2
- package/dist/protocol/index.js +3 -3
- package/dist/read-message-DP1UpEFl.js +660 -0
- package/dist/remote/index.d.ts +2 -2
- package/dist/remote/index.js +8 -8
- package/dist/{projection-marks-DcO_5VNd.d.ts → storage-xTb82JxJ.d.ts} +301 -462
- package/dist/{streamsy-IBFULoEr.js → streamsy-DiAjZWlT.js} +321 -94
- package/dist/testing/index.d.ts +7 -7
- package/dist/testing/index.js +28 -22
- package/package.json +4 -4
- package/dist/boundary-BTrhL8De.js +0 -371
- package/dist/read-message-CGHhOCMc.js +0 -193
|
@@ -0,0 +1,660 @@
|
|
|
1
|
+
import { Array, Cause, Context, Data, Effect, Exit, Option, Order, Predicate, Record, Schema, SchemaGetter, Semaphore } from "effect";
|
|
2
|
+
// src/fault.ts
|
|
3
|
+
var StorageFault = class extends Schema.TaggedError()("StorageFault", {
|
|
4
|
+
operation: Schema.String,
|
|
5
|
+
message: Schema.String,
|
|
6
|
+
isRetryable: Schema.Boolean,
|
|
7
|
+
cause: Schema.optionalKey(Schema.Defect())
|
|
8
|
+
}) {};
|
|
9
|
+
var EncodeFault = class extends Schema.TaggedError()("EncodeFault", {
|
|
10
|
+
message: Schema.String,
|
|
11
|
+
cause: Schema.optionalKey(Schema.Defect())
|
|
12
|
+
}) {};
|
|
13
|
+
var DecodeFault = class extends Schema.TaggedError()("DecodeFault", {
|
|
14
|
+
message: Schema.String,
|
|
15
|
+
cause: Schema.optionalKey(Schema.Defect())
|
|
16
|
+
}) {};
|
|
17
|
+
/**
|
|
18
|
+
* A stream param value cannot form a stream id, for example a value that contains `/` or is
|
|
19
|
+
* empty. `stream` is the route template and `parameter` names the param.
|
|
20
|
+
*/
|
|
21
|
+
var InvalidStreamParams = class extends Schema.TaggedError()("InvalidStreamParams", {
|
|
22
|
+
stream: Schema.String,
|
|
23
|
+
parameter: Schema.String,
|
|
24
|
+
message: Schema.String
|
|
25
|
+
}) {};
|
|
26
|
+
/** Failures of the remote boundary; protocol rejections have their own typed errors. */
|
|
27
|
+
var TransportFault = class extends Schema.TaggedError()("TransportFault", {
|
|
28
|
+
operation: Schema.String,
|
|
29
|
+
reason: Schema.Literals([
|
|
30
|
+
"request",
|
|
31
|
+
"response",
|
|
32
|
+
"decode",
|
|
33
|
+
"configuration"
|
|
34
|
+
]),
|
|
35
|
+
/** HTTP status of the response, when available. */
|
|
36
|
+
status: Schema.optionalKey(Schema.Int),
|
|
37
|
+
message: Schema.String,
|
|
38
|
+
cause: Schema.optionalKey(Schema.Defect())
|
|
39
|
+
}) {
|
|
40
|
+
/** Failed requests, 429s and 5xx responses can succeed later. */
|
|
41
|
+
get isRetryable() {
|
|
42
|
+
return this.reason === "request" || this.status !== void 0 && (this.status === 429 || this.status >= 500);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const StreamsFault = Schema.Union([StorageFault, TransportFault]);
|
|
46
|
+
/** A storage or transport failure, as opposed to a protocol rejection. */
|
|
47
|
+
const isStreamsFault = Schema.is(StreamsFault);
|
|
48
|
+
/**
|
|
49
|
+
* True for an error that can succeed later: any error with a boolean `isRetryable` that is
|
|
50
|
+
* `true`, such as a `StorageFault`, a `TransportFault` or a `ProjectionFault`.
|
|
51
|
+
*/
|
|
52
|
+
const isRetryableFault = (error) => Predicate.hasProperty(error, "isRetryable") && Predicate.isBoolean(error.isRetryable) && error.isRetryable;
|
|
53
|
+
// src/storage/owner.ts
|
|
54
|
+
/** The storage owner of a local host: its identity, its transaction and its commits. */
|
|
55
|
+
var StorageOwner = class extends Context.Service()("@streamsy/core/StorageOwner") {};
|
|
56
|
+
// src/internal/commit-hooks.ts
|
|
57
|
+
/** Shared registry for storage boundaries: register in a scope, run in order. */
|
|
58
|
+
const commitHookRegistry = () => {
|
|
59
|
+
const hooks = /* @__PURE__ */ new Set();
|
|
60
|
+
const beforeCommit = (hook) => Effect.acquireRelease(Effect.sync(() => {
|
|
61
|
+
const entry = { hook };
|
|
62
|
+
hooks.add(entry);
|
|
63
|
+
return entry;
|
|
64
|
+
}), (entry) => Effect.sync(() => {
|
|
65
|
+
hooks.delete(entry);
|
|
66
|
+
})).pipe(Effect.asVoid);
|
|
67
|
+
const run = (ids) => ids.size === 0 || hooks.size === 0 ? Effect.void : Effect.forEach([...hooks], (entry) => entry.hook(ids), { discard: true });
|
|
68
|
+
return {
|
|
69
|
+
beforeCommit,
|
|
70
|
+
run
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
// src/storage/memory/state.ts
|
|
74
|
+
const copyRecord = (record) => ({
|
|
75
|
+
id: record.id,
|
|
76
|
+
currentOffset: record.currentOffset,
|
|
77
|
+
config: { ...record.config },
|
|
78
|
+
lifecycle: { ...record.lifecycle }
|
|
79
|
+
});
|
|
80
|
+
const copyMessage = (message) => ({
|
|
81
|
+
offset: message.offset,
|
|
82
|
+
timestamp: message.timestamp,
|
|
83
|
+
data: new Uint8Array(message.data)
|
|
84
|
+
});
|
|
85
|
+
function patchRecord(record, patch) {
|
|
86
|
+
const config = {
|
|
87
|
+
...record.config,
|
|
88
|
+
...patch.config
|
|
89
|
+
};
|
|
90
|
+
const lifecycle = {
|
|
91
|
+
...record.lifecycle,
|
|
92
|
+
...patch.lifecycle
|
|
93
|
+
};
|
|
94
|
+
for (const key of patch.clear ?? []) switch (key) {
|
|
95
|
+
case "ttlSeconds":
|
|
96
|
+
delete config.ttlSeconds;
|
|
97
|
+
break;
|
|
98
|
+
case "expiresAt":
|
|
99
|
+
delete config.expiresAt;
|
|
100
|
+
break;
|
|
101
|
+
case "expiresAtMs":
|
|
102
|
+
delete lifecycle.expiresAtMs;
|
|
103
|
+
break;
|
|
104
|
+
case "lastSeq": delete lifecycle.lastSeq;
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
id: record.id,
|
|
108
|
+
currentOffset: patch.currentOffset ?? record.currentOffset,
|
|
109
|
+
config,
|
|
110
|
+
lifecycle
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function indexDeadlines(state) {
|
|
114
|
+
state.deadlines = Array.sort(Array.flatMap([...state.entries.values()], ({ record }) => record.lifecycle.softDeleted || record.lifecycle.expiresAtMs === void 0 ? [] : [{
|
|
115
|
+
at: record.lifecycle.expiresAtMs,
|
|
116
|
+
streamId: record.id
|
|
117
|
+
}]), Order.make((a, b) => {
|
|
118
|
+
const compared = a.at - b.at || a.streamId.localeCompare(b.streamId);
|
|
119
|
+
return compared < 0 ? -1 : compared > 0 ? 1 : 0;
|
|
120
|
+
}));
|
|
121
|
+
}
|
|
122
|
+
/** A private transaction draft; no mutable stream data aliases the committed state. */
|
|
123
|
+
const copyState = (state) => ({
|
|
124
|
+
entries: new Map(Array.map([...state.entries], ([id, entry]) => [id, {
|
|
125
|
+
record: copyRecord(entry.record),
|
|
126
|
+
messages: Array.map(entry.messages, copyMessage),
|
|
127
|
+
producers: new Map(Array.map([...entry.producers], ([producerId, producer]) => [producerId, {
|
|
128
|
+
epoch: producer.epoch,
|
|
129
|
+
lastSeq: producer.lastSeq
|
|
130
|
+
}]))
|
|
131
|
+
}])),
|
|
132
|
+
children: new Map(Array.map([...state.children], ([id, children]) => [id, new Set(children)])),
|
|
133
|
+
deadlines: Array.map(state.deadlines, (deadline) => ({ ...deadline }))
|
|
134
|
+
});
|
|
135
|
+
// src/storage/memory/marks.ts
|
|
136
|
+
/** A private transaction draft of the marks. */
|
|
137
|
+
const copyMarks = (marks) => new Map(Array.map([...marks], ([projection, rows]) => [projection, new Map(rows)]));
|
|
138
|
+
const rowsOf = (marks, projection) => {
|
|
139
|
+
const found = marks.get(projection);
|
|
140
|
+
if (found !== void 0) return found;
|
|
141
|
+
const rows = /* @__PURE__ */ new Map();
|
|
142
|
+
marks.set(projection, rows);
|
|
143
|
+
return rows;
|
|
144
|
+
};
|
|
145
|
+
const byDue = Order.mapInput(Order.Tuple([Order.Number, Order.String]), (mark) => [mark.dueAt, mark.params]);
|
|
146
|
+
const mark = (marks, projection, params) => {
|
|
147
|
+
const rows = rowsOf(marks, projection);
|
|
148
|
+
for (const value of params) {
|
|
149
|
+
const found = rows.get(value);
|
|
150
|
+
rows.set(value, found === void 0 ? {
|
|
151
|
+
params: value,
|
|
152
|
+
seq: 1,
|
|
153
|
+
attempts: 0,
|
|
154
|
+
dueAt: 0,
|
|
155
|
+
stopped: false,
|
|
156
|
+
wakeAt: Option.none(),
|
|
157
|
+
failure: Option.none()
|
|
158
|
+
} : {
|
|
159
|
+
...found,
|
|
160
|
+
seq: found.seq + 1,
|
|
161
|
+
dueAt: Option.isSome(found.wakeAt) ? 0 : found.dueAt,
|
|
162
|
+
wakeAt: Option.none()
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
const nextDue = (marks, projection) => {
|
|
167
|
+
let earliest;
|
|
168
|
+
for (const row of marks.get(projection)?.values() ?? []) if (!row.stopped) earliest = earliest === void 0 ? row.dueAt : Math.min(earliest, row.dueAt);
|
|
169
|
+
return Option.fromUndefinedOr(earliest);
|
|
170
|
+
};
|
|
171
|
+
const due = (marks, projection, now, limit) => Array.sort(Array.filter([...marks.get(projection)?.values() ?? []], (row) => !row.stopped && row.dueAt <= now), byDue).slice(0, limit);
|
|
172
|
+
const read = (marks, projection, params) => {
|
|
173
|
+
const rows = marks.get(projection);
|
|
174
|
+
const found = /* @__PURE__ */ new Map();
|
|
175
|
+
for (const value of params) {
|
|
176
|
+
const row = rows?.get(value);
|
|
177
|
+
if (row !== void 0) found.set(value, row);
|
|
178
|
+
}
|
|
179
|
+
return found;
|
|
180
|
+
};
|
|
181
|
+
const clear = (marks, projection, params, seq) => {
|
|
182
|
+
const rows = marks.get(projection);
|
|
183
|
+
const row = rows?.get(params);
|
|
184
|
+
if (rows === void 0 || row === void 0) return;
|
|
185
|
+
if (row.seq === seq) rows.delete(params);
|
|
186
|
+
else rows.set(params, {
|
|
187
|
+
...row,
|
|
188
|
+
attempts: 0,
|
|
189
|
+
dueAt: 0,
|
|
190
|
+
stopped: false,
|
|
191
|
+
wakeAt: Option.none(),
|
|
192
|
+
failure: Option.none()
|
|
193
|
+
});
|
|
194
|
+
};
|
|
195
|
+
/** Sleep only the seq that ran; a concurrent write must run before it can sleep. */
|
|
196
|
+
const sleep = (marks, projection, params, seq, wakeAt) => {
|
|
197
|
+
const rows = rowsOf(marks, projection);
|
|
198
|
+
const row = rows.get(params);
|
|
199
|
+
const matching = row === void 0 || row.seq === seq;
|
|
200
|
+
rows.set(params, {
|
|
201
|
+
params,
|
|
202
|
+
seq: row?.seq ?? 1,
|
|
203
|
+
attempts: 0,
|
|
204
|
+
dueAt: matching ? wakeAt : 0,
|
|
205
|
+
wakeAt: matching ? Option.some(wakeAt) : Option.none(),
|
|
206
|
+
stopped: false,
|
|
207
|
+
failure: Option.none()
|
|
208
|
+
});
|
|
209
|
+
};
|
|
210
|
+
const remove = (marks, projection, params) => {
|
|
211
|
+
marks.get(projection)?.delete(params);
|
|
212
|
+
};
|
|
213
|
+
const fail = (marks, projection, params, options) => {
|
|
214
|
+
const rows = rowsOf(marks, projection);
|
|
215
|
+
const found = rows.get(params);
|
|
216
|
+
rows.set(params, {
|
|
217
|
+
params,
|
|
218
|
+
seq: found?.seq ?? 1,
|
|
219
|
+
attempts: options.attempts,
|
|
220
|
+
dueAt: Option.getOrElse(options.dueAt, () => 0),
|
|
221
|
+
stopped: Option.isNone(options.dueAt),
|
|
222
|
+
wakeAt: Option.none(),
|
|
223
|
+
failure: Option.some({
|
|
224
|
+
...options.failure,
|
|
225
|
+
message: options.failure.message.slice(0, 1e3)
|
|
226
|
+
})
|
|
227
|
+
});
|
|
228
|
+
};
|
|
229
|
+
const failed = (marks, projection, limit) => Array.sort(Array.filter([...marks.get(projection)?.values() ?? []], (row) => row.attempts > 0), Order.combine(Order.mapInput(Order.Boolean, (row) => !row.stopped), byDue)).slice(0, limit);
|
|
230
|
+
const resume = (marks, projection) => {
|
|
231
|
+
let changed = 0;
|
|
232
|
+
const rows = marks.get(projection);
|
|
233
|
+
if (rows === void 0) return 0;
|
|
234
|
+
for (const [key, row] of rows) {
|
|
235
|
+
if (!row.stopped) continue;
|
|
236
|
+
rows.set(key, {
|
|
237
|
+
...row,
|
|
238
|
+
dueAt: 0,
|
|
239
|
+
stopped: false
|
|
240
|
+
});
|
|
241
|
+
changed += 1;
|
|
242
|
+
}
|
|
243
|
+
return changed;
|
|
244
|
+
};
|
|
245
|
+
const retry = (marks, projection, params) => {
|
|
246
|
+
let changed = 0;
|
|
247
|
+
const rows = marks.get(projection);
|
|
248
|
+
if (rows === void 0) return 0;
|
|
249
|
+
for (const [key, row] of rows) {
|
|
250
|
+
if (!row.stopped && (row.attempts === 0 || row.dueAt === 0) || params !== void 0 && key !== params) continue;
|
|
251
|
+
rows.set(key, {
|
|
252
|
+
...row,
|
|
253
|
+
dueAt: 0,
|
|
254
|
+
stopped: false
|
|
255
|
+
});
|
|
256
|
+
changed += 1;
|
|
257
|
+
}
|
|
258
|
+
return changed;
|
|
259
|
+
};
|
|
260
|
+
/** Classify each row once; a failed row at `now` is due, not backing off. */
|
|
261
|
+
const summary = (marks, projection, now) => {
|
|
262
|
+
let fresh = 0;
|
|
263
|
+
let sleeping = 0;
|
|
264
|
+
let retryDue = 0;
|
|
265
|
+
let backingOff = 0;
|
|
266
|
+
let stopped = 0;
|
|
267
|
+
let earliest;
|
|
268
|
+
for (const row of marks.get(projection)?.values() ?? []) {
|
|
269
|
+
if (row.stopped) {
|
|
270
|
+
stopped += 1;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (Option.isSome(row.wakeAt)) sleeping += 1;
|
|
274
|
+
else if (row.attempts === 0) fresh += 1;
|
|
275
|
+
else if (row.dueAt <= now) retryDue += 1;
|
|
276
|
+
else backingOff += 1;
|
|
277
|
+
earliest = earliest === void 0 ? row.dueAt : Math.min(earliest, row.dueAt);
|
|
278
|
+
}
|
|
279
|
+
return {
|
|
280
|
+
fresh,
|
|
281
|
+
sleeping,
|
|
282
|
+
retryDue,
|
|
283
|
+
backingOff,
|
|
284
|
+
stopped,
|
|
285
|
+
nextDueAt: Option.fromUndefinedOr(earliest)
|
|
286
|
+
};
|
|
287
|
+
};
|
|
288
|
+
/** A new private marks store. Each operation runs synchronously when its Effect executes. */
|
|
289
|
+
const memoryProjectionMarks = () => {
|
|
290
|
+
const table = /* @__PURE__ */ new Map();
|
|
291
|
+
return {
|
|
292
|
+
mark: (projection, params) => Effect.sync(() => mark(table, projection, params)),
|
|
293
|
+
nextDue: (projection) => Effect.sync(() => nextDue(table, projection)),
|
|
294
|
+
summary: (projection, now) => Effect.sync(() => summary(table, projection, now)),
|
|
295
|
+
due: (projection, now, limit) => Effect.sync(() => due(table, projection, now, limit)),
|
|
296
|
+
read: (projection, params) => Effect.sync(() => read(table, projection, params)),
|
|
297
|
+
clear: (projection, params, seq) => Effect.sync(() => clear(table, projection, params, seq)),
|
|
298
|
+
sleep: (projection, params, seq, wakeAt) => Effect.sync(() => sleep(table, projection, params, seq, wakeAt)),
|
|
299
|
+
remove: (projection, params) => Effect.sync(() => remove(table, projection, params)),
|
|
300
|
+
fail: (projection, params, options) => Effect.sync(() => fail(table, projection, params, options)),
|
|
301
|
+
retry: (projection, params) => Effect.sync(() => retry(table, projection, params)),
|
|
302
|
+
resume: (projection) => Effect.sync(() => resume(table, projection)),
|
|
303
|
+
failed: (projection, limit) => Effect.sync(() => failed(table, projection, limit))
|
|
304
|
+
};
|
|
305
|
+
};
|
|
306
|
+
// src/storage/memory/boundary.ts
|
|
307
|
+
var ActiveDraft = class extends Context.Service()("@streamsy/core/internal/MemoryActiveDraft") {};
|
|
308
|
+
const activeDraft = (owner, reject) => Effect.flatMap(Effect.serviceOption(ActiveDraft), (draft) => Effect.withFiber((fiber) => {
|
|
309
|
+
if (Option.isSome(draft) && (draft.value.owner !== owner || !draft.value.active || draft.value.fiberId !== fiber.id)) return reject();
|
|
310
|
+
return Effect.succeed(draft);
|
|
311
|
+
}));
|
|
312
|
+
var MemoryEnlistFault = class extends Schema.TaggedError()("MemoryEnlistFault", { message: Schema.String }) {};
|
|
313
|
+
const rejectEnlist = () => Effect.fail(new MemoryEnlistFault({ message: "Enlisting requires the active memory owner fiber" }));
|
|
314
|
+
/** Join the memory owner transaction open on this fiber. */
|
|
315
|
+
function enlist(owner, participant) {
|
|
316
|
+
return Effect.flatMap(activeDraft(owner, rejectEnlist), (draft) => {
|
|
317
|
+
if (Option.isNone(draft)) return rejectEnlist();
|
|
318
|
+
draft.value.participants.add(participant);
|
|
319
|
+
return Effect.void;
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
const notifyParticipants = (participants, callback) => {
|
|
323
|
+
const defects = [];
|
|
324
|
+
for (const participant of participants) try {
|
|
325
|
+
participant[callback]();
|
|
326
|
+
} catch (defect) {
|
|
327
|
+
defects.push(defect);
|
|
328
|
+
}
|
|
329
|
+
if (defects.length > 0) throw new AggregateError(defects, `Memory participant ${callback} failed`);
|
|
330
|
+
};
|
|
331
|
+
const makeBoundary = (committed, publish) => Effect.gen(function* () {
|
|
332
|
+
const owner = {};
|
|
333
|
+
const lock = yield* Semaphore.make(1);
|
|
334
|
+
let committedRecords = /* @__PURE__ */ new Map();
|
|
335
|
+
let committedMarks = /* @__PURE__ */ new Map();
|
|
336
|
+
const hooks = commitHookRegistry();
|
|
337
|
+
const current = activeDraft(owner, () => Effect.die(/* @__PURE__ */ new Error("Memory boundary requires the active owner fiber")));
|
|
338
|
+
const withTransaction = (body) => Effect.flatMap(current, (ambient) => {
|
|
339
|
+
if (Option.isSome(ambient)) return body;
|
|
340
|
+
return Effect.withFiber((fiber) => Effect.suspend(() => {
|
|
341
|
+
const draft = {
|
|
342
|
+
owner,
|
|
343
|
+
fiberId: fiber.id,
|
|
344
|
+
state: copyState(committed),
|
|
345
|
+
records: new Map(committedRecords),
|
|
346
|
+
marks: copyMarks(committedMarks),
|
|
347
|
+
ids: /* @__PURE__ */ new Set(),
|
|
348
|
+
participants: /* @__PURE__ */ new Set(),
|
|
349
|
+
active: true,
|
|
350
|
+
changed: false
|
|
351
|
+
};
|
|
352
|
+
const withHooks = body.pipe(Effect.tap(() => Effect.orDie(hooks.run(draft.ids))), Effect.provideService(ActiveDraft, draft));
|
|
353
|
+
return Effect.uninterruptibleMask((restore) => Effect.exit(restore(withHooks)).pipe(Effect.flatMap((exit) => {
|
|
354
|
+
if (Exit.isFailure(exit)) return Effect.sync(() => notifyParticipants(Array.reverse(Array.fromIterable(draft.participants)), "onRollback")).pipe(Effect.catchCause((rollback) => Effect.failCause(Cause.combine(exit.cause, rollback))), Effect.andThen(exit));
|
|
355
|
+
return Effect.sync(() => {
|
|
356
|
+
Object.assign(committed, draft.state);
|
|
357
|
+
committedRecords = draft.records;
|
|
358
|
+
committedMarks = draft.marks;
|
|
359
|
+
notifyParticipants(draft.participants, "onCommit");
|
|
360
|
+
}).pipe(Effect.ensuring(Effect.suspend(() => draft.changed ? publish(draft.ids) : Effect.void)), Effect.as(exit.value));
|
|
361
|
+
}), Effect.ensuring(Effect.sync(() => {
|
|
362
|
+
draft.active = false;
|
|
363
|
+
}))));
|
|
364
|
+
}).pipe(Semaphore.withPermit(lock)));
|
|
365
|
+
});
|
|
366
|
+
const access = (f) => Effect.map(current, (draft) => f(Option.isSome(draft) ? draft.value.state : committed));
|
|
367
|
+
const changed = (ids) => Effect.map(current, (draft) => {
|
|
368
|
+
if (Option.isNone(draft)) throw new Error("Memory mutation requires an owner");
|
|
369
|
+
draft.value.changed = true;
|
|
370
|
+
for (const id of ids) draft.value.ids.add(id);
|
|
371
|
+
});
|
|
372
|
+
const records = {
|
|
373
|
+
read: (key) => Effect.map(current, (draft) => Option.fromUndefinedOr((Option.isSome(draft) ? draft.value.records : committedRecords).get(key))),
|
|
374
|
+
list: (prefix) => Effect.map(current, (draft) => Array.filter(Array.fromIterable(Option.isSome(draft) ? draft.value.records : committedRecords), ([key]) => key.startsWith(prefix))),
|
|
375
|
+
remove: (key) => withTransaction(Effect.map(current, (draft) => {
|
|
376
|
+
if (Option.isNone(draft)) throw new Error("Memory record delete requires an owner");
|
|
377
|
+
draft.value.records.delete(key);
|
|
378
|
+
})),
|
|
379
|
+
write: (key, encoded) => withTransaction(Effect.map(current, (draft) => {
|
|
380
|
+
if (Option.isNone(draft)) throw new Error("Memory record write requires an owner");
|
|
381
|
+
draft.value.records.set(key, encoded);
|
|
382
|
+
}))
|
|
383
|
+
};
|
|
384
|
+
const readMarks = (f) => Effect.map(current, (draft) => f(Option.isSome(draft) ? draft.value.marks : committedMarks));
|
|
385
|
+
const writeMarks = (f) => withTransaction(Effect.map(current, (draft) => {
|
|
386
|
+
if (Option.isNone(draft)) throw new Error("Memory mark write requires an owner");
|
|
387
|
+
return f(draft.value.marks);
|
|
388
|
+
}));
|
|
389
|
+
return {
|
|
390
|
+
marks: {
|
|
391
|
+
mark: (projection, params) => writeMarks((table) => mark(table, projection, params)),
|
|
392
|
+
nextDue: (projection) => readMarks((table) => nextDue(table, projection)),
|
|
393
|
+
summary: (projection, now) => readMarks((table) => summary(table, projection, now)),
|
|
394
|
+
due: (projection, now, limit) => readMarks((table) => due(table, projection, now, limit)),
|
|
395
|
+
read: (projection, params) => readMarks((table) => read(table, projection, params)),
|
|
396
|
+
clear: (projection, params, seq) => writeMarks((table) => clear(table, projection, params, seq)),
|
|
397
|
+
sleep: (projection, params, seq, wakeAt) => writeMarks((table) => sleep(table, projection, params, seq, wakeAt)),
|
|
398
|
+
remove: (projection, params) => writeMarks((table) => remove(table, projection, params)),
|
|
399
|
+
fail: (projection, params, options) => writeMarks((table) => fail(table, projection, params, options)),
|
|
400
|
+
resume: (projection) => writeMarks((table) => resume(table, projection)),
|
|
401
|
+
failed: (projection, limit) => readMarks((table) => failed(table, projection, limit)),
|
|
402
|
+
retry: (projection, params) => writeMarks((table) => retry(table, projection, params))
|
|
403
|
+
},
|
|
404
|
+
records,
|
|
405
|
+
hooks: { beforeCommit: hooks.beforeCommit },
|
|
406
|
+
enlist: (participant) => enlist(owner, participant),
|
|
407
|
+
withTransaction,
|
|
408
|
+
access,
|
|
409
|
+
changed
|
|
410
|
+
};
|
|
411
|
+
});
|
|
412
|
+
// src/internal/storage-owner.ts
|
|
413
|
+
const OwnerBackend = Data.taggedEnum();
|
|
414
|
+
/**
|
|
415
|
+
* Join the memory owner's transaction open on this fiber. A SQL owner has no memory
|
|
416
|
+
* transaction, so there it fails as an enlist outside the owner fiber does.
|
|
417
|
+
*/
|
|
418
|
+
const memoryEnlist = (backend) => OwnerBackend.$match(backend, {
|
|
419
|
+
Memory: ({ enlist }) => enlist,
|
|
420
|
+
Sql: () => () => Effect.fail(new MemoryEnlistFault({ message: "Enlisting requires the active memory owner fiber" }))
|
|
421
|
+
});
|
|
422
|
+
/**
|
|
423
|
+
* A key for one value on each owner. Keep the key in a module constant: each owner runs
|
|
424
|
+
* `make` with its own parts once, on first use.
|
|
425
|
+
*/
|
|
426
|
+
var OwnerSlot = class {
|
|
427
|
+
make;
|
|
428
|
+
constructor(make) {
|
|
429
|
+
this.make = make;
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
const PartsKey = Symbol.for("@streamsy/core/internal/StorageOwnerParts");
|
|
433
|
+
/** A fresh owner identity. Each call returns a value no other call returns. */
|
|
434
|
+
const newOwnerId = (label) => `${label}:${crypto.randomUUID()}`;
|
|
435
|
+
/** Build a storage owner from its adapter parts. Each call is a new owner. */
|
|
436
|
+
const buildStorageOwner = (options) => {
|
|
437
|
+
const slots = /* @__PURE__ */ new Map();
|
|
438
|
+
const parts = {
|
|
439
|
+
storage: options.storage,
|
|
440
|
+
records: options.records,
|
|
441
|
+
hooks: options.hooks,
|
|
442
|
+
marks: options.marks,
|
|
443
|
+
backend: options.backend,
|
|
444
|
+
slot: (key) => {
|
|
445
|
+
if (slots.has(key)) return slots.get(key);
|
|
446
|
+
const value = key.make(parts);
|
|
447
|
+
slots.set(key, value);
|
|
448
|
+
return value;
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
const owner = StorageOwner.of({
|
|
452
|
+
id: newOwnerId(options.label),
|
|
453
|
+
capabilities: options.storage.capabilities,
|
|
454
|
+
withTransaction: options.withTransaction,
|
|
455
|
+
committed: options.storage.committed
|
|
456
|
+
});
|
|
457
|
+
return Object.defineProperty(owner, PartsKey, {
|
|
458
|
+
value: parts,
|
|
459
|
+
enumerable: false
|
|
460
|
+
});
|
|
461
|
+
};
|
|
462
|
+
/**
|
|
463
|
+
* The same owner with some parts replaced, for decorators in tests. The id, the backend
|
|
464
|
+
* and the slots stay the owner's own.
|
|
465
|
+
*/
|
|
466
|
+
const decorateOwner = (owner, patch) => {
|
|
467
|
+
const parts = ownerParts(owner);
|
|
468
|
+
const storage = patch.storage ?? parts.storage;
|
|
469
|
+
const decorated = StorageOwner.of({
|
|
470
|
+
id: owner.id,
|
|
471
|
+
capabilities: storage.capabilities,
|
|
472
|
+
withTransaction: patch.withTransaction ?? owner.withTransaction,
|
|
473
|
+
committed: storage.committed
|
|
474
|
+
});
|
|
475
|
+
return Object.defineProperty(decorated, PartsKey, {
|
|
476
|
+
value: {
|
|
477
|
+
...parts,
|
|
478
|
+
storage,
|
|
479
|
+
records: patch.records ?? parts.records,
|
|
480
|
+
hooks: patch.hooks ?? parts.hooks,
|
|
481
|
+
marks: patch.marks ?? parts.marks
|
|
482
|
+
},
|
|
483
|
+
enumerable: false
|
|
484
|
+
});
|
|
485
|
+
};
|
|
486
|
+
/** The adapter parts of `owner`. Dies when `buildStorageOwner` did not build it. */
|
|
487
|
+
const ownerParts = (owner) => {
|
|
488
|
+
const parts = Predicate.hasProperty(owner, PartsKey) ? owner[PartsKey] : void 0;
|
|
489
|
+
if (parts === void 0) throw new TypeError("This StorageOwner was not built with buildStorageOwner");
|
|
490
|
+
return parts;
|
|
491
|
+
};
|
|
492
|
+
// src/internal/owner.ts
|
|
493
|
+
/** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
|
|
494
|
+
const ForeignOwnerType = Symbol.for("@streamsy/core/internal/ForeignOwner");
|
|
495
|
+
var ForeignOwner = class extends Data.TaggedError("ForeignOwner") {
|
|
496
|
+
stream;
|
|
497
|
+
[ForeignOwnerType] = true;
|
|
498
|
+
constructor(stream, knownOwner) {
|
|
499
|
+
super({ message: knownOwner ? `Stream write to ${stream} does not share the checkpoint owner` : `Cannot establish a storage owner for ${stream}; its protocol wires have no StorageOwner` });
|
|
500
|
+
this.stream = stream;
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
const isForeignOwner = (value) => Predicate.hasProperty(value, ForeignOwnerType) && value[ForeignOwnerType] === true;
|
|
504
|
+
const CurrentOwner = Context.Reference("@streamsy/core/internal/CurrentOwner", { defaultValue: () => void 0 });
|
|
505
|
+
const checkWriteOwner = (owner, id, knownOwner) => Effect.flatMap(CurrentOwner, (expected) => expected === void 0 || expected === owner ? Effect.void : Effect.die(new ForeignOwner(id, knownOwner)));
|
|
506
|
+
// src/internal/stream-params.ts
|
|
507
|
+
/**
|
|
508
|
+
* Throw a params failure from a synchronous binding such as `at(params)`. The throw is a
|
|
509
|
+
* `RangeError` whose `cause` is the typed failure, so `resolveParams` can recover it.
|
|
510
|
+
*/
|
|
511
|
+
const throwInvalidStreamParams = (error) => {
|
|
512
|
+
throw new RangeError(error.message, { cause: error });
|
|
513
|
+
};
|
|
514
|
+
const isInvalidStreamParams = Schema.is(InvalidStreamParams);
|
|
515
|
+
/**
|
|
516
|
+
* Run a throwing params binding inside an Effect. A params failure becomes
|
|
517
|
+
* `InvalidStreamParams` in `E`; any other throw is a defect.
|
|
518
|
+
*/
|
|
519
|
+
const resolveParams = (bind) => Effect.suspend(() => {
|
|
520
|
+
try {
|
|
521
|
+
return Effect.succeed(bind());
|
|
522
|
+
} catch (thrown) {
|
|
523
|
+
return Predicate.hasProperty(thrown, "cause") && isInvalidStreamParams(thrown.cause) ? Effect.fail(thrown.cause) : Effect.die(thrown);
|
|
524
|
+
}
|
|
525
|
+
});
|
|
526
|
+
// src/toolkit/route-internal.ts
|
|
527
|
+
/** Ids are canonical relative paths, the same rule the remote Layer enforces. */
|
|
528
|
+
function isCanonicalIdSegment(value) {
|
|
529
|
+
if (value.length === 0 || value === "." || value === "..") return false;
|
|
530
|
+
return !/[%?#/\\]/.test(value);
|
|
531
|
+
}
|
|
532
|
+
function compileSegments(template) {
|
|
533
|
+
if (template.length === 0) throw new RangeError("a stream route template must name at least one segment");
|
|
534
|
+
if (template.startsWith("/")) throw new RangeError("a stream route template is relative and cannot start with a slash");
|
|
535
|
+
if (/[?#*]/.test(template)) throw new RangeError("a stream route template cannot contain a query, fragment, or wildcard");
|
|
536
|
+
const names = [];
|
|
537
|
+
const segments = [];
|
|
538
|
+
for (const part of template.split("/")) {
|
|
539
|
+
if (part.length === 0) throw new RangeError("a stream route template cannot contain an empty segment");
|
|
540
|
+
if (!part.startsWith(":")) {
|
|
541
|
+
if (!isCanonicalIdSegment(part)) throw new RangeError(`a stream route literal segment is not a canonical id segment: ${part}`);
|
|
542
|
+
segments.push({
|
|
543
|
+
kind: "literal",
|
|
544
|
+
value: part
|
|
545
|
+
});
|
|
546
|
+
continue;
|
|
547
|
+
}
|
|
548
|
+
const name = part.slice(1);
|
|
549
|
+
if (name.length === 0) throw new RangeError("a stream route parameter needs a name");
|
|
550
|
+
if (names.includes(name)) throw new RangeError(`duplicate stream route parameter: ${name}`);
|
|
551
|
+
names.push(name);
|
|
552
|
+
segments.push({
|
|
553
|
+
kind: "parameter",
|
|
554
|
+
name
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
return {
|
|
558
|
+
template,
|
|
559
|
+
segments: Object.freeze(segments),
|
|
560
|
+
names: Object.freeze(names)
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* True when two template routes can both match one id.
|
|
565
|
+
*
|
|
566
|
+
* Lengths must agree, and every position must be either an equal literal pair
|
|
567
|
+
* or a parameter on at least one side. A parameter is treated as matching any
|
|
568
|
+
* segment, so a codec-constrained parameter can report an overlap it would
|
|
569
|
+
* never actually match. A custom route carries no template and is never
|
|
570
|
+
* checked; HTTP dispatch uses declaration order and the first match wins.
|
|
571
|
+
*/
|
|
572
|
+
function templatesOverlap(left, right) {
|
|
573
|
+
if (left.length === 0 || right.length === 0) return false;
|
|
574
|
+
const a = compileSegments(left).segments;
|
|
575
|
+
const b = compileSegments(right).segments;
|
|
576
|
+
if (a.length !== b.length) return false;
|
|
577
|
+
for (const [index, segment] of a.entries()) {
|
|
578
|
+
const other = b[index];
|
|
579
|
+
if (!other || segment.kind === "parameter" || other.kind === "parameter") continue;
|
|
580
|
+
if (segment.value !== other.value) return false;
|
|
581
|
+
}
|
|
582
|
+
return true;
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* True when a route is a singleton: a template route whose template names no parameter.
|
|
586
|
+
* A custom route has an empty template and is never a singleton.
|
|
587
|
+
*/
|
|
588
|
+
function isSingletonRoute(route) {
|
|
589
|
+
return route.template.length > 0 && compileSegments(route.template).names.length === 0;
|
|
590
|
+
}
|
|
591
|
+
// src/toolkit/state-wire.ts
|
|
592
|
+
const upsertOperation = Schema.Union([
|
|
593
|
+
Schema.Literal("upsert"),
|
|
594
|
+
Schema.Literal("insert").transform("upsert"),
|
|
595
|
+
Schema.Literal("update").transform("upsert")
|
|
596
|
+
]);
|
|
597
|
+
const headers = {
|
|
598
|
+
offset: Schema.optionalKey(Schema.String),
|
|
599
|
+
txid: Schema.optionalKey(Schema.String),
|
|
600
|
+
timestamp: Schema.optionalKey(Schema.String),
|
|
601
|
+
from: Schema.optionalKey(Schema.String)
|
|
602
|
+
};
|
|
603
|
+
/**
|
|
604
|
+
* A change key. Encoding rejects an empty key, which Durable State clients cannot address, so
|
|
605
|
+
* an append of such a change fails with `EncodeFault`. Decoding accepts any string.
|
|
606
|
+
*/
|
|
607
|
+
const changeKey = (type) => Schema.String.pipe(Schema.decodeTo(Schema.String, {
|
|
608
|
+
decode: SchemaGetter.passthrough(),
|
|
609
|
+
encode: SchemaGetter.checkEffect((key) => Effect.succeed(key.length > 0 || `Invalid state key for type "${type}": must not be null, undefined, or empty`))
|
|
610
|
+
}));
|
|
611
|
+
const wireChangeCodec = (type, value, name = "*") => Schema.Union([Schema.Struct({
|
|
612
|
+
type,
|
|
613
|
+
key: changeKey(name),
|
|
614
|
+
value,
|
|
615
|
+
headers: Schema.Struct({
|
|
616
|
+
operation: upsertOperation,
|
|
617
|
+
...headers
|
|
618
|
+
})
|
|
619
|
+
}), Schema.Struct({
|
|
620
|
+
type,
|
|
621
|
+
key: changeKey(name),
|
|
622
|
+
old_value: Schema.optionalKey(value),
|
|
623
|
+
headers: Schema.Struct({
|
|
624
|
+
operation: Schema.Literal("delete"),
|
|
625
|
+
...headers
|
|
626
|
+
})
|
|
627
|
+
})]);
|
|
628
|
+
const wireControlCodec = Schema.Struct({ headers: Schema.Struct({
|
|
629
|
+
control: Schema.Literals([
|
|
630
|
+
"snapshot-start",
|
|
631
|
+
"snapshot-end",
|
|
632
|
+
"reset"
|
|
633
|
+
]),
|
|
634
|
+
offset: Schema.optionalKey(Schema.String)
|
|
635
|
+
}) });
|
|
636
|
+
const rawChange = wireChangeCodec(Schema.String, Schema.Unknown);
|
|
637
|
+
/** Decode the State envelope while keeping row values in their wire form. */
|
|
638
|
+
const decodeStateWire = Schema.decodeEffect(Schema.fromJsonString(Schema.Union([wireControlCodec, rawChange])));
|
|
639
|
+
// src/toolkit/read-message.ts
|
|
640
|
+
const parseJson = Schema.decodeOption(Schema.fromJsonString(Schema.Unknown));
|
|
641
|
+
const decodeChange = Schema.decodeUnknownOption(rawChange);
|
|
642
|
+
const isUndeclaredChange = (address, json) => {
|
|
643
|
+
if (!("collections" in address) || !Predicate.isObject(address.collections)) return false;
|
|
644
|
+
if ("strict" in address && address.strict === true) return false;
|
|
645
|
+
const parsed = parseJson(json);
|
|
646
|
+
if (Option.isNone(parsed)) return false;
|
|
647
|
+
const value = parsed.value;
|
|
648
|
+
if (Predicate.hasProperty(value, "headers") && Predicate.hasProperty(value.headers, "control")) return false;
|
|
649
|
+
const change = decodeChange(value);
|
|
650
|
+
return Option.isSome(change) && !Record.has(address.collections, change.value.type);
|
|
651
|
+
};
|
|
652
|
+
/** A decoded message, or None for a change outside a non-strict State address's collections. */
|
|
653
|
+
const decodeMessage = (address, message, index) => {
|
|
654
|
+
const wire = Predicate.isTagged(address, "Json") ? new TextDecoder().decode(message.data) : message.data;
|
|
655
|
+
return Schema.decodeEffect(address.codec)(wire).pipe(Effect.asSome, Effect.catch((cause) => Predicate.isString(wire) && isUndeclaredChange(address, wire) ? Effect.succeedNone : Effect.fail(new DecodeFault({
|
|
656
|
+
message: `Cannot decode ${address.id} at read message ${index}`,
|
|
657
|
+
cause
|
|
658
|
+
}))));
|
|
659
|
+
};
|
|
660
|
+
export { DecodeFault as A, memoryProjectionMarks as C, patchRecord as D, indexDeadlines as E, TransportFault as F, isRetryableFault as I, isStreamsFault as L, InvalidStreamParams as M, StorageFault as N, commitHookRegistry as O, StreamsFault as P, makeBoundary as S, copyRecord as T, decorateOwner as _, compileSegments as a, ownerParts as b, templatesOverlap as c, CurrentOwner as d, checkWriteOwner as f, buildStorageOwner as g, OwnerSlot as h, wireControlCodec as i, EncodeFault as j, StorageOwner as k, resolveParams as l, OwnerBackend as m, decodeStateWire as n, isCanonicalIdSegment as o, isForeignOwner as p, wireChangeCodec as r, isSingletonRoute as s, decodeMessage as t, throwInvalidStreamParams as u, memoryEnlist as v, copyMessage as w, MemoryEnlistFault as x, newOwnerId as y };
|
package/dist/remote/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { D as Group, E as Any, O as Identifiers } from "../index-
|
|
1
|
+
import { et as TransportFault } from "../storage-xTb82JxJ.js";
|
|
2
|
+
import { D as Group, E as Any, O as Identifiers, nt as StreamsReader, rt as StreamsWriter } from "../index-DIx4D2t0.js";
|
|
3
3
|
import { Layer } from "effect";
|
|
4
4
|
import { HttpClient, HttpClientRequest } from "effect/http";
|
|
5
5
|
interface Options {
|