@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.
@@ -1,12 +1,12 @@
1
- import { E as StorageCapabilities, Et as ChangeSnapshot, Pt as StreamId, R as StreamsReader, h as Storage, z as StreamsWriter } from "../projection-marks-DcO_5VNd.js";
2
- import { K as MemoryOptions, q as ProtocolOptions } from "../index-D-n48qXe.js";
1
+ import { G as StreamId, L as ChangeSnapshot, S as StorageOwner, t as StorageShape, w as StorageCapabilities } from "../storage-xTb82JxJ.js";
2
+ import { K as MemoryOptions, nt as StreamsReader, q as ProtocolOptions, rt as StreamsWriter } from "../index-DIx4D2t0.js";
3
3
  import { Context, Effect, Layer } from "effect";
4
4
  interface StorageContractOptions {
5
5
  readonly name: string;
6
- readonly layer: Layer.Layer<Storage>;
6
+ readonly layer: Layer.Layer<StorageOwner>;
7
7
  readonly expected: StorageCapabilities;
8
8
  /**
9
- * The Layer also provides `CommitBoundary`, and the internal owner records,
9
+ * Run the cases for the owner's transaction, and for the internal owner records,
10
10
  * commit hooks and projection marks that projections need.
11
11
  */
12
12
  readonly ownerRecords?: boolean;
@@ -17,12 +17,12 @@ export declare const StorageContract: {
17
17
  assertModes(configurations: ReadonlyArray<StorageCapabilities>): void;
18
18
  };
19
19
  /** One selected attempt per decorator; "after" injects only if that mutation applies. */
20
- export declare function faultyStorage(source: Layer.Layer<Storage>, options: {
20
+ export declare function faultyStorage(source: Layer.Layer<StorageOwner>, options: {
21
21
  readonly failOn: number;
22
22
  readonly when: "before" | "after";
23
- }): Layer.Layer<Storage>;
23
+ }): Layer.Layer<StorageOwner>;
24
24
  declare const StreamsTest_base: Context.ServiceClass<StreamsTest, "@streamsy/core/StreamsTest", {
25
- readonly storage: typeof Storage.Service;
25
+ readonly storage: StorageShape;
26
26
  readonly subscribers: Effect.Effect<number>;
27
27
  readonly snapshot: Effect.Effect<{
28
28
  readonly id: StreamId;
@@ -1,8 +1,7 @@
1
- import { G as ProducerId, L as Storage, R as ZERO_OFFSET, V as next, X as StreamId } from "../streamsy-IBFULoEr.js";
2
- import { _ as StorageFault } from "../read-message-CGHhOCMc.js";
3
- import { a as CommitHooks, c as OwnerRecords, i as ProjectionMarks, p as CommitBoundary } from "../boundary-BTrhL8De.js";
4
- import { a as MutationRejected, t as layer } from "../layer-pomDIajD.js";
5
- import { t as layer$1 } from "../layer-C-8GAL_W.js";
1
+ import { Q as StreamId, U as next, q as ProducerId, z as ZERO_OFFSET } from "../streamsy-DiAjZWlT.js";
2
+ import { N as StorageFault, _ as decorateOwner, b as ownerParts, k as StorageOwner } from "../read-message-DP1UpEFl.js";
3
+ import { a as MutationRejected, t as layer } from "../layer-DTOhxWkw.js";
4
+ import { t as layer$1 } from "../layer-Dv_LBCgD.js";
6
5
  import { Array, Cause, Context, Deferred, Effect, Exit, Fiber, Layer, Match, Option, Order, Predicate, PubSub, Queue, Record, Ref, Scope, Stream } from "effect";
7
6
  import { SqlError } from "effect/sql";
8
7
  import { describe, expect, it } from "vitest";
@@ -14,7 +13,7 @@ const projectionMarksContract = (marks) => Effect.gen(function* () {
14
13
  const projection = "marks-contract";
15
14
  const failure = {
16
15
  at: 123,
17
- reason: Option.some("invalid-record"),
16
+ reason: Option.some("InvalidRecord"),
18
17
  message: "x".repeat(1100)
19
18
  };
20
19
  const savedFailure = {
@@ -43,7 +42,7 @@ const projectionMarksContract = (marks) => Effect.gen(function* () {
43
42
  yield* check(stoppedOnly.stopped === 2 && stoppedOnly.fresh === 0 && stoppedOnly.sleeping === 0 && stoppedOnly.retryDue === 0 && stoppedOnly.backingOff === 0 && Option.isNone(stoppedOnly.nextDueAt), "stopped-only summary");
44
43
  yield* Effect.orDie(marks.mark(projection, ["a-stop"]));
45
44
  const raised = yield* read("a-stop");
46
- yield* check(raised?.seq === 2 && raised.stopped && raised.attempts === 2 && Option.isSome(raised.failure) && raised.failure.value.at === 123 && Option.contains(raised.failure.value.reason, "invalid-record") && raised.failure.value.message === savedFailure.message, "mark preserves stop and truncated failure");
45
+ yield* check(raised?.seq === 2 && raised.stopped && raised.attempts === 2 && Option.isSome(raised.failure) && raised.failure.value.at === 123 && Option.contains(raised.failure.value.reason, "InvalidRecord") && raised.failure.value.message === savedFailure.message, "mark preserves stop and truncated failure");
47
46
  yield* marks.fail(projection, "future", {
48
47
  attempts: 3,
49
48
  failure,
@@ -163,7 +162,7 @@ const projectionMarksContract = (marks) => Effect.gen(function* () {
163
162
  const projectionMarksTransactionContract = (marks, boundary) => Effect.gen(function* () {
164
163
  const failure = {
165
164
  at: 1,
166
- reason: Option.some("invalid-record"),
165
+ reason: Option.some("InvalidRecord"),
167
166
  message: "bad"
168
167
  };
169
168
  yield* marks.fail("rollback-stop", "a", {
@@ -191,6 +190,8 @@ const projectionMarksTransactionContract = (marks, boundary) => Effect.gen(funct
191
190
  });
192
191
  // src/testing/storage-contract.ts
193
192
  /** Executable Bun edge: a fresh scoped Layer and virtual clock for every case. */
193
+ /** The stream storage of the owner in context. */
194
+ const Storage = Effect.map(Effect.service(StorageOwner), (owner) => ownerParts(owner).storage);
194
195
  const id = StreamId.make("s");
195
196
  const child = StreamId.make("child");
196
197
  const producerId = ProducerId.make("p");
@@ -301,7 +302,7 @@ const StorageContract = {
301
302
  }
302
303
  it(name, () => expect(Effect.gen(function* () {
303
304
  const context = yield* Layer.build(options.layer.pipe(Layer.provideMerge(TestClock.layer())));
304
- const storage = Context.get(context, Storage);
305
+ const storage = ownerParts(Context.get(context, StorageOwner)).storage;
305
306
  expect(storage.capabilities).toEqual(options.expected);
306
307
  yield* body.pipe(Effect.provide(context));
307
308
  }).pipe(Effect.scoped, Effect.runPromiseExit)).resolves.toMatchObject({ _tag: "Success" }));
@@ -313,11 +314,13 @@ const StorageContract = {
313
314
  }
314
315
  it(name, () => expect(Effect.gen(function* () {
315
316
  const context = yield* Layer.build(options.layer);
317
+ const boundary = Context.get(context, StorageOwner);
318
+ const { records, hooks, marks } = ownerParts(boundary);
316
319
  yield* body({
317
- boundary: Option.getOrThrow(Context.getOption(context, CommitBoundary)),
318
- records: Option.getOrThrow(Context.getOption(context, OwnerRecords)),
319
- hooks: Option.getOrThrow(Context.getOption(context, CommitHooks)),
320
- marks: Option.getOrThrow(Context.getOption(context, ProjectionMarks))
320
+ boundary,
321
+ records,
322
+ hooks,
323
+ marks
321
324
  }).pipe(Effect.provide(context));
322
325
  }).pipe(Effect.scoped, Effect.runPromiseExit)).resolves.toMatchObject({ _tag: "Success" }));
323
326
  };
@@ -1262,35 +1265,37 @@ const StorageContract = {
1262
1265
  // src/testing/fault-injection.ts
1263
1266
  /** One selected attempt per decorator; "after" injects only if that mutation applies. */
1264
1267
  function faultyStorage(source, options) {
1265
- return Layer.effect(Storage, Effect.gen(function* () {
1266
- const storage = yield* Storage;
1268
+ return Layer.effect(StorageOwner, Effect.gen(function* () {
1269
+ const owner = yield* StorageOwner;
1267
1270
  if (!Number.isInteger(options.failOn) || options.failOn < 1) return yield* Effect.die(/* @__PURE__ */ new RangeError("failOn must be a positive integer"));
1268
1271
  let calls = 0;
1269
- return Storage.of({
1272
+ const storage = ownerParts(owner).storage;
1273
+ return decorateOwner(owner, { storage: {
1270
1274
  ...storage,
1271
1275
  mutate: Effect.fn("Testing.faultyStorage.mutate")(function* (mutation) {
1272
1276
  const fail = ++calls === options.failOn;
1273
1277
  const fault = new StorageFault({
1274
1278
  operation: "mutate",
1275
1279
  message: `Injected ${options.when} mutation failure`,
1276
- retryable: true
1280
+ isRetryable: true
1277
1281
  });
1278
1282
  if (fail && options.when === "before") return yield* fault;
1279
1283
  const result = yield* storage.mutate(mutation);
1280
1284
  if (fail && options.when === "after") return yield* fault;
1281
1285
  return result;
1282
1286
  })
1283
- });
1287
+ } });
1284
1288
  })).pipe(Layer.provide(source));
1285
1289
  }
1286
1290
  // src/testing/streams-test.ts
1287
1291
  var StreamsTest = class extends Context.Service()("@streamsy/core/StreamsTest") {};
1288
1292
  /** Real protocol and memory, with deterministic observation at the scoped changes boundary. */
1289
1293
  const layerTest = (options = {}) => Layer.effectContext(Effect.gen(function* () {
1290
- const storage = yield* Storage;
1294
+ const owner = yield* StorageOwner;
1295
+ const { storage } = ownerParts(owner);
1291
1296
  const count = yield* Ref.make(0);
1292
1297
  const snapshots = yield* Effect.acquireRelease(Queue.unbounded(), Queue.shutdown);
1293
- const observed = Storage.of({
1298
+ const observedOwner = decorateOwner(owner, { storage: {
1294
1299
  ...storage,
1295
1300
  changes: (id) => Stream.unwrap(Effect.gen(function* () {
1296
1301
  yield* Effect.acquireRelease(Ref.update(count, (n) => n + 1), () => Ref.update(count, (n) => n - 1));
@@ -1299,8 +1304,9 @@ const layerTest = (options = {}) => Layer.effectContext(Effect.gen(function* ()
1299
1304
  value
1300
1305
  })));
1301
1306
  }))
1302
- });
1303
- const context = yield* Layer.build(layer(options).pipe(Layer.provide(Layer.succeed(Storage, observed))));
1307
+ } });
1308
+ const observed = ownerParts(observedOwner).storage;
1309
+ const context = yield* Layer.build(layer(options).pipe(Layer.provide(Layer.succeed(StorageOwner, observedOwner))));
1304
1310
  return Context.add(context, StreamsTest, StreamsTest.of({
1305
1311
  storage: observed,
1306
1312
  subscribers: Ref.get(count),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@streamsy/core",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "Effect-first Durable Streams protocol, storage contract, memory layer and toolkit.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -56,14 +56,14 @@
56
56
  "test:unit": "bun --bun vitest run --dir test"
57
57
  },
58
58
  "devDependencies": {
59
- "@effect/vitest": "4.1.5",
59
+ "@effect/vitest": "4.2.0",
60
60
  "@types/bun": "^1.4.3",
61
- "effect": "4.1.5",
61
+ "effect": "4.2.0",
62
62
  "typescript": "^7.0.2",
63
63
  "vitest": "5.0.5"
64
64
  },
65
65
  "peerDependencies": {
66
- "effect": "^4.1.5",
66
+ "effect": "^4.2.0",
67
67
  "vitest": "^5.0.0"
68
68
  },
69
69
  "peerDependenciesMeta": {
@@ -1,371 +0,0 @@
1
- import { l as attachOwner } from "./read-message-CGHhOCMc.js";
2
- import { Array, Cause, Context, Effect, Exit, Option, Order, Schema, Semaphore } from "effect";
3
- // src/storage/commit-boundary.ts
4
- /** The transaction of the storage owner. Every Streamsy storage host provides it. */
5
- var CommitBoundary = class extends Context.Service()("@streamsy/core/CommitBoundary") {};
6
- // src/storage/memory/state.ts
7
- const copyRecord = (record) => ({
8
- id: record.id,
9
- currentOffset: record.currentOffset,
10
- config: { ...record.config },
11
- lifecycle: { ...record.lifecycle }
12
- });
13
- const copyMessage = (message) => ({
14
- offset: message.offset,
15
- timestamp: message.timestamp,
16
- data: new Uint8Array(message.data)
17
- });
18
- function patchRecord(record, patch) {
19
- const config = {
20
- ...record.config,
21
- ...patch.config
22
- };
23
- const lifecycle = {
24
- ...record.lifecycle,
25
- ...patch.lifecycle
26
- };
27
- for (const key of patch.clear ?? []) switch (key) {
28
- case "ttlSeconds":
29
- delete config.ttlSeconds;
30
- break;
31
- case "expiresAt":
32
- delete config.expiresAt;
33
- break;
34
- case "expiresAtMs":
35
- delete lifecycle.expiresAtMs;
36
- break;
37
- case "lastSeq": delete lifecycle.lastSeq;
38
- }
39
- return {
40
- id: record.id,
41
- currentOffset: patch.currentOffset ?? record.currentOffset,
42
- config,
43
- lifecycle
44
- };
45
- }
46
- function indexDeadlines(state) {
47
- state.deadlines = Array.sort(Array.flatMap([...state.entries.values()], ({ record }) => record.lifecycle.softDeleted || record.lifecycle.expiresAtMs === void 0 ? [] : [{
48
- at: record.lifecycle.expiresAtMs,
49
- streamId: record.id
50
- }]), Order.make((a, b) => {
51
- const compared = a.at - b.at || a.streamId.localeCompare(b.streamId);
52
- return compared < 0 ? -1 : compared > 0 ? 1 : 0;
53
- }));
54
- }
55
- /** A private transaction draft; no mutable stream data aliases the committed state. */
56
- const copyState = (state) => ({
57
- entries: new Map(Array.map([...state.entries], ([id, entry]) => [id, {
58
- record: copyRecord(entry.record),
59
- messages: Array.map(entry.messages, copyMessage),
60
- producers: new Map(Array.map([...entry.producers], ([producerId, producer]) => [producerId, {
61
- epoch: producer.epoch,
62
- lastSeq: producer.lastSeq
63
- }]))
64
- }])),
65
- children: new Map(Array.map([...state.children], ([id, children]) => [id, new Set(children)])),
66
- deadlines: Array.map(state.deadlines, (deadline) => ({ ...deadline }))
67
- });
68
- // src/internal/owner-records.ts
69
- /** The `StorageFault.operation` of an owner store that cannot list its records. */
70
- const OWNER_RECORDS_LIST_UNSUPPORTED = "records.list.unsupported";
71
- var OwnerRecords = class extends Context.Service()("@streamsy/core/internal/OwnerRecords") {};
72
- // src/internal/commit-hooks.ts
73
- var CommitHooks = class extends Context.Service()("@streamsy/core/internal/CommitHooks") {};
74
- /** Shared registry for storage boundaries: register in a scope, run in order. */
75
- const commitHookRegistry = () => {
76
- const hooks = /* @__PURE__ */ new Set();
77
- const beforeCommit = (hook) => Effect.acquireRelease(Effect.sync(() => {
78
- const entry = { hook };
79
- hooks.add(entry);
80
- return entry;
81
- }), (entry) => Effect.sync(() => {
82
- hooks.delete(entry);
83
- })).pipe(Effect.asVoid);
84
- const run = (ids) => ids.size === 0 || hooks.size === 0 ? Effect.void : Effect.forEach([...hooks], (entry) => entry.hook(ids), { discard: true });
85
- return {
86
- beforeCommit,
87
- run
88
- };
89
- };
90
- // src/internal/projection-marks.ts
91
- var ProjectionMarks = class extends Context.Service()("@streamsy/core/internal/ProjectionMarks") {};
92
- // src/storage/memory/marks.ts
93
- /** A private transaction draft of the marks. */
94
- const copyMarks = (marks) => new Map(Array.map([...marks], ([projection, rows]) => [projection, new Map(rows)]));
95
- const rowsOf = (marks, projection) => {
96
- const found = marks.get(projection);
97
- if (found !== void 0) return found;
98
- const rows = /* @__PURE__ */ new Map();
99
- marks.set(projection, rows);
100
- return rows;
101
- };
102
- const byDue = Order.mapInput(Order.Tuple([Order.Number, Order.String]), (mark) => [mark.dueAt, mark.params]);
103
- const mark = (marks, projection, params) => {
104
- const rows = rowsOf(marks, projection);
105
- for (const value of params) {
106
- const found = rows.get(value);
107
- rows.set(value, found === void 0 ? {
108
- params: value,
109
- seq: 1,
110
- attempts: 0,
111
- dueAt: 0,
112
- stopped: false,
113
- wakeAt: Option.none(),
114
- failure: Option.none()
115
- } : {
116
- ...found,
117
- seq: found.seq + 1,
118
- dueAt: Option.isSome(found.wakeAt) ? 0 : found.dueAt,
119
- wakeAt: Option.none()
120
- });
121
- }
122
- };
123
- const nextDue = (marks, projection) => {
124
- let earliest;
125
- for (const row of marks.get(projection)?.values() ?? []) if (!row.stopped) earliest = earliest === void 0 ? row.dueAt : Math.min(earliest, row.dueAt);
126
- return Option.fromUndefinedOr(earliest);
127
- };
128
- const due = (marks, projection, now, limit) => Array.sort(Array.filter([...marks.get(projection)?.values() ?? []], (row) => !row.stopped && row.dueAt <= now), byDue).slice(0, limit);
129
- const read = (marks, projection, params) => {
130
- const rows = marks.get(projection);
131
- const found = /* @__PURE__ */ new Map();
132
- for (const value of params) {
133
- const row = rows?.get(value);
134
- if (row !== void 0) found.set(value, row);
135
- }
136
- return found;
137
- };
138
- const clear = (marks, projection, params, seq) => {
139
- const rows = marks.get(projection);
140
- const row = rows?.get(params);
141
- if (rows === void 0 || row === void 0) return;
142
- if (row.seq === seq) rows.delete(params);
143
- else rows.set(params, {
144
- ...row,
145
- attempts: 0,
146
- dueAt: 0,
147
- stopped: false,
148
- wakeAt: Option.none(),
149
- failure: Option.none()
150
- });
151
- };
152
- /** Sleep only the seq that ran; a concurrent write must run before it can sleep. */
153
- const sleep = (marks, projection, params, seq, wakeAt) => {
154
- const rows = rowsOf(marks, projection);
155
- const row = rows.get(params);
156
- const matching = row === void 0 || row.seq === seq;
157
- rows.set(params, {
158
- params,
159
- seq: row?.seq ?? 1,
160
- attempts: 0,
161
- dueAt: matching ? wakeAt : 0,
162
- wakeAt: matching ? Option.some(wakeAt) : Option.none(),
163
- stopped: false,
164
- failure: Option.none()
165
- });
166
- };
167
- const remove = (marks, projection, params) => {
168
- marks.get(projection)?.delete(params);
169
- };
170
- const fail = (marks, projection, params, options) => {
171
- const rows = rowsOf(marks, projection);
172
- const found = rows.get(params);
173
- rows.set(params, {
174
- params,
175
- seq: found?.seq ?? 1,
176
- attempts: options.attempts,
177
- dueAt: Option.getOrElse(options.dueAt, () => 0),
178
- stopped: Option.isNone(options.dueAt),
179
- wakeAt: Option.none(),
180
- failure: Option.some({
181
- ...options.failure,
182
- message: options.failure.message.slice(0, 1e3)
183
- })
184
- });
185
- };
186
- 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);
187
- const resume = (marks, projection) => {
188
- let changed = 0;
189
- const rows = marks.get(projection);
190
- if (rows === void 0) return 0;
191
- for (const [key, row] of rows) {
192
- if (!row.stopped) continue;
193
- rows.set(key, {
194
- ...row,
195
- dueAt: 0,
196
- stopped: false
197
- });
198
- changed += 1;
199
- }
200
- return changed;
201
- };
202
- const retry = (marks, projection, params) => {
203
- let changed = 0;
204
- const rows = marks.get(projection);
205
- if (rows === void 0) return 0;
206
- for (const [key, row] of rows) {
207
- if (!row.stopped && (row.attempts === 0 || row.dueAt === 0) || params !== void 0 && key !== params) continue;
208
- rows.set(key, {
209
- ...row,
210
- dueAt: 0,
211
- stopped: false
212
- });
213
- changed += 1;
214
- }
215
- return changed;
216
- };
217
- /** Classify each row once; a failed row at `now` is due, not backing off. */
218
- const summary = (marks, projection, now) => {
219
- let fresh = 0;
220
- let sleeping = 0;
221
- let retryDue = 0;
222
- let backingOff = 0;
223
- let stopped = 0;
224
- let earliest;
225
- for (const row of marks.get(projection)?.values() ?? []) {
226
- if (row.stopped) {
227
- stopped += 1;
228
- continue;
229
- }
230
- if (Option.isSome(row.wakeAt)) sleeping += 1;
231
- else if (row.attempts === 0) fresh += 1;
232
- else if (row.dueAt <= now) retryDue += 1;
233
- else backingOff += 1;
234
- earliest = earliest === void 0 ? row.dueAt : Math.min(earliest, row.dueAt);
235
- }
236
- return {
237
- fresh,
238
- sleeping,
239
- retryDue,
240
- backingOff,
241
- stopped,
242
- nextDueAt: Option.fromUndefinedOr(earliest)
243
- };
244
- };
245
- /** A new private marks store. Each operation runs synchronously when its Effect executes. */
246
- const memoryProjectionMarks = () => {
247
- const table = /* @__PURE__ */ new Map();
248
- return {
249
- mark: (projection, params) => Effect.sync(() => mark(table, projection, params)),
250
- nextDue: (projection) => Effect.sync(() => nextDue(table, projection)),
251
- summary: (projection, now) => Effect.sync(() => summary(table, projection, now)),
252
- due: (projection, now, limit) => Effect.sync(() => due(table, projection, now, limit)),
253
- read: (projection, params) => Effect.sync(() => read(table, projection, params)),
254
- clear: (projection, params, seq) => Effect.sync(() => clear(table, projection, params, seq)),
255
- sleep: (projection, params, seq, wakeAt) => Effect.sync(() => sleep(table, projection, params, seq, wakeAt)),
256
- remove: (projection, params) => Effect.sync(() => remove(table, projection, params)),
257
- fail: (projection, params, options) => Effect.sync(() => fail(table, projection, params, options)),
258
- retry: (projection, params) => Effect.sync(() => retry(table, projection, params)),
259
- resume: (projection) => Effect.sync(() => resume(table, projection)),
260
- failed: (projection, limit) => Effect.sync(() => failed(table, projection, limit))
261
- };
262
- };
263
- // src/storage/memory/boundary.ts
264
- var ActiveDraft = class extends Context.Service()("@streamsy/core/internal/MemoryActiveDraft") {};
265
- const activeDraft = (owner, reject) => Effect.flatMap(Effect.serviceOption(ActiveDraft), (draft) => Effect.withFiber((fiber) => {
266
- if (Option.isSome(draft) && (draft.value.owner !== owner || !draft.value.active || draft.value.fiberId !== fiber.id)) return reject();
267
- return Effect.succeed(draft);
268
- }));
269
- var MemoryEnlistFault = class extends Schema.TaggedError()("MemoryEnlistFault", { message: Schema.String }) {};
270
- const rejectEnlist = () => Effect.fail(new MemoryEnlistFault({ message: "Enlisting requires the active memory owner fiber" }));
271
- /** Join the memory owner transaction open on this fiber. */
272
- function enlist(owner, participant) {
273
- return Effect.flatMap(activeDraft(owner, rejectEnlist), (draft) => {
274
- if (Option.isNone(draft)) return rejectEnlist();
275
- draft.value.participants.add(participant);
276
- return Effect.void;
277
- });
278
- }
279
- const notifyParticipants = (participants, callback) => {
280
- const defects = [];
281
- for (const participant of participants) try {
282
- participant[callback]();
283
- } catch (defect) {
284
- defects.push(defect);
285
- }
286
- if (defects.length > 0) throw new AggregateError(defects, `Memory participant ${callback} failed`);
287
- };
288
- const makeBoundary = (committed, publish) => Effect.gen(function* () {
289
- const owner = {};
290
- const lock = yield* Semaphore.make(1);
291
- let committedRecords = /* @__PURE__ */ new Map();
292
- let committedMarks = /* @__PURE__ */ new Map();
293
- const hooks = commitHookRegistry();
294
- const current = activeDraft(owner, () => Effect.die(/* @__PURE__ */ new Error("Memory boundary requires the active owner fiber")));
295
- const withTransaction = (body) => Effect.flatMap(current, (ambient) => {
296
- if (Option.isSome(ambient)) return body;
297
- return Effect.withFiber((fiber) => Effect.suspend(() => {
298
- const draft = {
299
- owner,
300
- fiberId: fiber.id,
301
- state: copyState(committed),
302
- records: new Map(committedRecords),
303
- marks: copyMarks(committedMarks),
304
- ids: /* @__PURE__ */ new Set(),
305
- participants: /* @__PURE__ */ new Set(),
306
- active: true,
307
- changed: false
308
- };
309
- const withHooks = body.pipe(Effect.tap(() => Effect.orDie(hooks.run(draft.ids))), Effect.provideService(ActiveDraft, draft));
310
- return Effect.uninterruptibleMask((restore) => Effect.exit(restore(withHooks)).pipe(Effect.flatMap((exit) => {
311
- 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));
312
- return Effect.sync(() => {
313
- Object.assign(committed, draft.state);
314
- committedRecords = draft.records;
315
- committedMarks = draft.marks;
316
- notifyParticipants(draft.participants, "onCommit");
317
- }).pipe(Effect.ensuring(Effect.suspend(() => draft.changed ? publish(draft.ids) : Effect.void)), Effect.as(exit.value));
318
- }), Effect.ensuring(Effect.sync(() => {
319
- draft.active = false;
320
- }))));
321
- }).pipe(Semaphore.withPermit(lock)));
322
- });
323
- const access = (f) => Effect.map(current, (draft) => f(Option.isSome(draft) ? draft.value.state : committed));
324
- const changed = (ids) => Effect.map(current, (draft) => {
325
- if (Option.isNone(draft)) throw new Error("Memory mutation requires an owner");
326
- draft.value.changed = true;
327
- for (const id of ids) draft.value.ids.add(id);
328
- });
329
- const boundary = CommitBoundary.of({ withTransaction });
330
- const records = OwnerRecords.of({
331
- read: (key) => Effect.map(current, (draft) => Option.fromUndefinedOr((Option.isSome(draft) ? draft.value.records : committedRecords).get(key))),
332
- list: (prefix) => Effect.map(current, (draft) => Array.filter(Array.fromIterable(Option.isSome(draft) ? draft.value.records : committedRecords), ([key]) => key.startsWith(prefix))),
333
- remove: (key) => withTransaction(Effect.map(current, (draft) => {
334
- if (Option.isNone(draft)) throw new Error("Memory record delete requires an owner");
335
- draft.value.records.delete(key);
336
- })),
337
- write: (key, encoded) => withTransaction(Effect.map(current, (draft) => {
338
- if (Option.isNone(draft)) throw new Error("Memory record write requires an owner");
339
- draft.value.records.set(key, encoded);
340
- }))
341
- });
342
- const readMarks = (f) => Effect.map(current, (draft) => f(Option.isSome(draft) ? draft.value.marks : committedMarks));
343
- const writeMarks = (f) => withTransaction(Effect.map(current, (draft) => {
344
- if (Option.isNone(draft)) throw new Error("Memory mark write requires an owner");
345
- return f(draft.value.marks);
346
- }));
347
- const marks = ProjectionMarks.of({
348
- mark: (projection, params) => writeMarks((table) => mark(table, projection, params)),
349
- nextDue: (projection) => readMarks((table) => nextDue(table, projection)),
350
- summary: (projection, now) => readMarks((table) => summary(table, projection, now)),
351
- due: (projection, now, limit) => readMarks((table) => due(table, projection, now, limit)),
352
- read: (projection, params) => readMarks((table) => read(table, projection, params)),
353
- clear: (projection, params, seq) => writeMarks((table) => clear(table, projection, params, seq)),
354
- sleep: (projection, params, seq, wakeAt) => writeMarks((table) => sleep(table, projection, params, seq, wakeAt)),
355
- remove: (projection, params) => writeMarks((table) => remove(table, projection, params)),
356
- fail: (projection, params, options) => writeMarks((table) => fail(table, projection, params, options)),
357
- resume: (projection) => writeMarks((table) => resume(table, projection)),
358
- failed: (projection, limit) => readMarks((table) => failed(table, projection, limit)),
359
- retry: (projection, params) => writeMarks((table) => retry(table, projection, params))
360
- });
361
- return {
362
- boundary: attachOwner(boundary, owner),
363
- marks: attachOwner(marks, owner),
364
- records: attachOwner(records, owner),
365
- hooks: attachOwner(CommitHooks.of({ beforeCommit: hooks.beforeCommit }), owner),
366
- withTransaction,
367
- access,
368
- changed
369
- };
370
- });
371
- export { CommitHooks as a, OwnerRecords as c, indexDeadlines as d, patchRecord as f, ProjectionMarks as i, copyMessage as l, makeBoundary as n, commitHookRegistry as o, CommitBoundary as p, memoryProjectionMarks as r, OWNER_RECORDS_LIST_UNSUPPORTED as s, enlist as t, copyRecord as u };