@streamsy/core 0.2.0 → 0.4.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.
@@ -0,0 +1,757 @@
1
+ import { I as next, M as Storage, N as ZERO_OFFSET, Q as StreamId, q as ProducerId, z as StorageFault } from "../streamsy-OjRubIPC.js";
2
+ import { n as CommitBoundary, t as layer } from "../layer-D8ybaCL2.js";
3
+ import { a as MutationRejected, t as layer$1 } from "../layer-KvknRFUT.js";
4
+ import { t as OwnerRecords } from "../owner-records-CX6yU28i.js";
5
+ import { Cause, Context, Deferred, Effect, Exit, Fiber, Layer, Match, Option, Predicate, Queue, Ref, Stream } from "effect";
6
+ import { describe, expect, it } from "vitest";
7
+ import { TestClock } from "effect/testing";
8
+ //#region src/testing/storage-contract.ts
9
+ /** Executable Bun edge: a fresh scoped Layer and virtual clock for every case. */
10
+ const id = StreamId.make("s");
11
+ const child = StreamId.make("child");
12
+ const producerId = ProducerId.make("p");
13
+ const one = next(ZERO_OFFSET);
14
+ const two = next(one);
15
+ const encode = (text) => new TextEncoder().encode(text);
16
+ const record = (streamId = id) => ({
17
+ id: streamId,
18
+ config: {
19
+ contentType: "text/plain",
20
+ createdAt: 0
21
+ },
22
+ lifecycle: {
23
+ closed: false,
24
+ softDeleted: false
25
+ },
26
+ currentOffset: ZERO_OFFSET
27
+ });
28
+ const create = (value = record()) => ({
29
+ _tag: "Create",
30
+ record: value,
31
+ initialMessages: []
32
+ });
33
+ const append = (extra = {}) => ({
34
+ _tag: "Append",
35
+ streamId: id,
36
+ messages: [{
37
+ offset: one,
38
+ data: encode("a"),
39
+ timestamp: 0
40
+ }],
41
+ patch: { currentOffset: one },
42
+ ...extra
43
+ });
44
+ const remove = (streamId = id) => ({
45
+ _tag: "Delete",
46
+ streamId,
47
+ reason: "delete"
48
+ });
49
+ const mutate = Effect.fn("Contract.mutate")(function* (operation) {
50
+ return yield* (yield* Storage).mutate({ operations: [operation] });
51
+ });
52
+ function applied(out, tag) {
53
+ expect(out).toMatchObject({ _tag: "Applied" });
54
+ expect(out.results[0]).toMatchObject({ _tag: tag });
55
+ }
56
+ function rejected(out, reason) {
57
+ expect(out).toBeInstanceOf(MutationRejected);
58
+ expect(out).toMatchObject({
59
+ _tag: "MutationRejected",
60
+ reason
61
+ });
62
+ }
63
+ const current = Effect.gen(function* () {
64
+ const storage = yield* Storage;
65
+ return Option.getOrThrow(yield* storage.record(id));
66
+ });
67
+ const fork = Effect.fn("Contract.fork")(function* (sourceId = id, childId = child, boundary) {
68
+ const storage = yield* Storage;
69
+ const source = Option.getOrThrow(yield* storage.record(sourceId));
70
+ const forkOffset = boundary ?? source.currentOffset;
71
+ const messages = storage.capabilities.fork === "copy" ? yield* storage.messages(sourceId, { until: forkOffset }) : [];
72
+ const operation = {
73
+ _tag: "Create",
74
+ record: {
75
+ ...record(childId),
76
+ currentOffset: forkOffset,
77
+ lifecycle: {
78
+ closed: false,
79
+ softDeleted: false,
80
+ forkedFrom: sourceId,
81
+ forkOffset
82
+ }
83
+ },
84
+ initialMessages: messages
85
+ };
86
+ return yield* mutate(storage.capabilities.fork === "chain" ? {
87
+ ...operation,
88
+ forkSource: {
89
+ id: sourceId,
90
+ liveAtOffset: forkOffset
91
+ }
92
+ } : operation);
93
+ });
94
+ const observe = Effect.gen(function* () {
95
+ const storage = yield* Storage;
96
+ const queue = yield* Queue.unbounded();
97
+ const ready = yield* Deferred.make();
98
+ const fiber = yield* storage.changes(id).pipe(Stream.runForEach((value) => Effect.gen(function* () {
99
+ yield* Queue.offer(queue, value);
100
+ yield* Deferred.succeed(ready, void 0);
101
+ })), Effect.forkScoped);
102
+ yield* Deferred.await(ready);
103
+ return {
104
+ queue,
105
+ fiber,
106
+ initial: yield* Queue.take(queue)
107
+ };
108
+ });
109
+ const tick = TestClock.adjust(25);
110
+ const StorageContract = {
111
+ run(options) {
112
+ describe(options.name, () => {
113
+ const test = (name, body, enabled = true, reason = "capability unavailable") => {
114
+ if (!enabled) {
115
+ it.skip(`${name} — ${reason}`, () => {});
116
+ return;
117
+ }
118
+ it(name, () => expect(Effect.gen(function* () {
119
+ const context = yield* Layer.build(options.layer.pipe(Layer.provideMerge(TestClock.layer())));
120
+ const storage = Context.get(context, Storage);
121
+ expect(storage.capabilities).toEqual(options.expected);
122
+ yield* body.pipe(Effect.provide(context));
123
+ }).pipe(Effect.scoped, Effect.runPromiseExit)).resolves.toMatchObject({ _tag: "Success" }));
124
+ };
125
+ const recordsTest = (name, body) => {
126
+ if (options.ownerRecords !== true) {
127
+ it.skip(`${name} — owner records not provided`, () => {});
128
+ return;
129
+ }
130
+ it(name, () => expect(Effect.gen(function* () {
131
+ const context = yield* Layer.build(options.layer);
132
+ yield* body({
133
+ boundary: Option.getOrThrow(Context.getOption(context, CommitBoundary)),
134
+ records: Option.getOrThrow(Context.getOption(context, OwnerRecords))
135
+ }).pipe(Effect.provide(context));
136
+ }).pipe(Effect.scoped, Effect.runPromiseExit)).resolves.toMatchObject({ _tag: "Success" }));
137
+ };
138
+ recordsTest("R1 owner records write, overwrite, read and remove by key", ({ records }) => Effect.gen(function* () {
139
+ expect(yield* records.read("a")).toEqual(Option.none());
140
+ yield* records.write("a", "1");
141
+ yield* records.write("b", "2");
142
+ yield* records.write("a", "3");
143
+ expect(yield* records.read("a")).toEqual(Option.some("3"));
144
+ expect(yield* records.read("b")).toEqual(Option.some("2"));
145
+ yield* records.remove("a");
146
+ yield* records.remove("absent");
147
+ expect(yield* records.read("a")).toEqual(Option.none());
148
+ expect(yield* records.read("b")).toEqual(Option.some("2"));
149
+ }));
150
+ recordsTest("R2 owner records and stream writes commit or roll back together", ({ boundary, records }) => Effect.gen(function* () {
151
+ const storage = yield* Storage;
152
+ const both = boundary.withTransaction(Effect.gen(function* () {
153
+ yield* mutate(create());
154
+ yield* records.write("checkpoint", "1");
155
+ expect(yield* records.read("checkpoint")).toEqual(Option.some("1"));
156
+ }));
157
+ const failed = yield* Effect.exit(boundary.withTransaction(Effect.andThen(both, Effect.fail("rollback"))));
158
+ expect(Exit.isFailure(failed)).toBe(true);
159
+ expect(yield* records.read("checkpoint")).toEqual(Option.none());
160
+ expect(yield* storage.record(id)).toEqual(Option.none());
161
+ yield* both;
162
+ expect(yield* records.read("checkpoint")).toEqual(Option.some("1"));
163
+ expect(Option.isSome(yield* storage.record(id))).toBe(true);
164
+ }));
165
+ test("01 Append advances tail and folds close atomically", Effect.gen(function* () {
166
+ yield* mutate(create());
167
+ applied(yield* mutate(append({ patch: {
168
+ currentOffset: one,
169
+ lifecycle: {
170
+ closed: true,
171
+ closedAt: 7
172
+ }
173
+ } })), "Appended");
174
+ expect(yield* current).toMatchObject({
175
+ currentOffset: one,
176
+ lifecycle: {
177
+ closed: true,
178
+ closedAt: 7
179
+ }
180
+ });
181
+ const storage = yield* Storage;
182
+ expect((yield* storage.messages(id, {})).length).toBe(1);
183
+ }));
184
+ for (const [number, reason] of [
185
+ ["02", "offset"],
186
+ ["03", "closed"],
187
+ ["04", "producer"],
188
+ ["05", "absent producer"]
189
+ ]) test(`${number} rejects ${reason} precondition without writes`, Effect.gen(function* () {
190
+ yield* mutate(create());
191
+ yield* mutate(append({ producer: {
192
+ producerId,
193
+ expected: Option.none(),
194
+ next: {
195
+ epoch: 1,
196
+ lastSeq: 0
197
+ }
198
+ } }));
199
+ const before = yield* current;
200
+ const out = yield* Effect.flip(mutate(append({
201
+ messages: [{
202
+ offset: two,
203
+ data: encode("b"),
204
+ timestamp: 1
205
+ }],
206
+ patch: {
207
+ currentOffset: two,
208
+ lifecycle: { closed: true }
209
+ },
210
+ expectedOffset: reason === "offset" ? ZERO_OFFSET : one,
211
+ expectedClosed: reason === "closed",
212
+ producer: {
213
+ producerId,
214
+ expected: reason === "absent producer" ? Option.none() : Option.some({
215
+ epoch: 9,
216
+ lastSeq: 9
217
+ }),
218
+ next: {
219
+ epoch: 2,
220
+ lastSeq: 0
221
+ }
222
+ }
223
+ })));
224
+ rejected(out, reason === "absent producer" ? "producer" : reason);
225
+ expect(yield* current).toEqual(before);
226
+ const storage = yield* Storage;
227
+ expect((yield* storage.messages(id, {})).length).toBe(1);
228
+ expect(yield* storage.producer(id, producerId)).toEqual(Option.some({
229
+ epoch: 1,
230
+ lastSeq: 0
231
+ }));
232
+ if (Predicate.isTagged(out, "MutationRejected")) expect(out.record).toEqual(Option.some(before));
233
+ }));
234
+ test("06 lifecycle-only TTL touch preserves tail", Effect.gen(function* () {
235
+ yield* mutate(create());
236
+ applied(yield* mutate(append({
237
+ messages: [],
238
+ patch: { lifecycle: { expiresAtMs: 100 } }
239
+ })), "Appended");
240
+ expect(yield* current).toMatchObject({
241
+ currentOffset: ZERO_OFFSET,
242
+ lifecycle: { expiresAtMs: 100 }
243
+ });
244
+ }));
245
+ test("07 exclusive after, inclusive until, lexical order and limit", Effect.gen(function* () {
246
+ yield* mutate(create());
247
+ const three = next(two), four = next(three);
248
+ yield* mutate(append({
249
+ messages: [
250
+ four,
251
+ one,
252
+ three,
253
+ two
254
+ ].map((offset) => ({
255
+ offset,
256
+ data: encode(offset),
257
+ timestamp: 0
258
+ })),
259
+ patch: { currentOffset: four }
260
+ }));
261
+ const storage = yield* Storage;
262
+ expect((yield* storage.messages(id, {})).map((m) => m.offset)).toEqual([
263
+ one,
264
+ two,
265
+ three,
266
+ four
267
+ ]);
268
+ expect((yield* storage.messages(id, {
269
+ after: one,
270
+ until: three
271
+ })).map((m) => m.offset)).toEqual([two, three]);
272
+ expect((yield* storage.messages(id, {
273
+ after: one,
274
+ until: four,
275
+ limit: 1
276
+ })).map((m) => m.offset)).toEqual([two]);
277
+ expect(yield* storage.messages(id, { limit: 0 })).toEqual([]);
278
+ }));
279
+ test("08 first changes element differs from stale observed offset", Effect.gen(function* () {
280
+ yield* mutate(create());
281
+ yield* mutate(append());
282
+ const { initial } = yield* observe;
283
+ expect(initial.currentOffset).toBe(one);
284
+ }));
285
+ test("09 timeout returns no changed value and consumer re-reads fresh snapshot", Effect.gen(function* () {
286
+ yield* mutate(create());
287
+ const { queue, initial } = yield* observe;
288
+ const pending = yield* Stream.fromQueue(queue).pipe(Stream.filter((s) => s.currentOffset !== initial.currentOffset || s.closed !== initial.closed || s.present !== initial.present), Stream.take(1), Stream.runCollect, Effect.timeoutOption(100), Effect.forkScoped);
289
+ yield* TestClock.adjust(100);
290
+ expect(yield* Fiber.join(pending)).toEqual(Option.none());
291
+ const storage = yield* Storage;
292
+ expect(Option.getOrThrow(yield* storage.record(id)).currentOffset).toBe(initial.currentOffset);
293
+ }));
294
+ for (const [number, action] of [
295
+ ["10", "append"],
296
+ ["11", "close"],
297
+ ["12", "soft delete"],
298
+ ["13", "purge"]
299
+ ]) test(`${number} parked changes subscriber wakes on ${action}`, Effect.gen(function* () {
300
+ yield* mutate(create());
301
+ if (action === "soft delete") yield* fork();
302
+ const { queue } = yield* observe;
303
+ yield* mutate(Match.value(action).pipe(Match.when("append", () => append()), Match.when("close", () => append({
304
+ messages: [],
305
+ patch: { lifecycle: { closed: true } }
306
+ })), Match.orElse(() => remove())));
307
+ yield* tick;
308
+ const value = yield* Queue.take(queue);
309
+ if (action === "append") expect(value.currentOffset).toBe(one);
310
+ if (action === "close") expect(value.closed).toBe(true);
311
+ if (action === "soft delete") expect(value.softDeleted).toBe(true);
312
+ if (action === "purge") expect(value.present).toBe(false);
313
+ }), action !== "soft delete" || options.expected.fork === "chain", "soft deletion requires chain fork");
314
+ test("14 purge then re-create lower offset is a change", Effect.gen(function* () {
315
+ yield* mutate(create());
316
+ yield* mutate(append());
317
+ const { queue } = yield* observe;
318
+ yield* mutate(remove());
319
+ yield* mutate(create());
320
+ yield* tick;
321
+ const values = yield* (yield* Storage).changes(id).pipe(Stream.take(1), Stream.runCollect);
322
+ expect(values[0]).toMatchObject({
323
+ present: true,
324
+ currentOffset: ZERO_OFFSET
325
+ });
326
+ expect((yield* Queue.take(queue)).currentOffset).not.toBe(one);
327
+ }));
328
+ test("15 commit before subscription survives lost-notify race", Effect.gen(function* () {
329
+ yield* mutate(create());
330
+ yield* mutate(append());
331
+ const { initial } = yield* observe;
332
+ expect(initial).toEqual({
333
+ present: true,
334
+ currentOffset: one,
335
+ closed: false,
336
+ softDeleted: false
337
+ });
338
+ }));
339
+ test("16 consumer ignores a non-advancing wake then observes advance", Effect.gen(function* () {
340
+ yield* mutate(create());
341
+ const { queue } = yield* observe;
342
+ const unchanged = yield* Deferred.make();
343
+ const result = yield* Stream.fromQueue(queue).pipe(Stream.tap((s) => s.currentOffset === ZERO_OFFSET ? Deferred.succeed(unchanged, void 0) : Effect.void), Stream.filter((s) => s.currentOffset !== ZERO_OFFSET), Stream.take(1), Stream.runCollect, Effect.forkScoped);
344
+ yield* mutate(append({
345
+ messages: [],
346
+ patch: { lifecycle: { expiresAtMs: 100 } }
347
+ }));
348
+ yield* tick;
349
+ yield* Deferred.await(unchanged);
350
+ expect(result.pollUnsafe()).toBeUndefined();
351
+ yield* mutate(append());
352
+ yield* tick;
353
+ expect((yield* Fiber.join(result))[0]?.currentOffset).toBe(one);
354
+ }));
355
+ test("17 repeated Create rejects exists with original record", Effect.gen(function* () {
356
+ yield* mutate(create());
357
+ const out = yield* Effect.flip(mutate(create()));
358
+ rejected(out, "exists");
359
+ if (Predicate.isTagged(out, "MutationRejected")) expect(out.record).toEqual(Option.some(record()));
360
+ }));
361
+ test("18 Create persists an already-closed record", Effect.gen(function* () {
362
+ yield* mutate(create({
363
+ ...record(),
364
+ lifecycle: {
365
+ closed: true,
366
+ closedAt: 9,
367
+ softDeleted: false
368
+ }
369
+ }));
370
+ expect((yield* current).lifecycle.closedAt).toBe(9);
371
+ }));
372
+ test("19 fork capability is an explicit value", Effect.gen(function* () {
373
+ const storage = yield* Storage;
374
+ expect([
375
+ "none",
376
+ "copy",
377
+ "chain"
378
+ ]).toContain(storage.capabilities.fork);
379
+ expect(storage.capabilities.fork).toBe(options.expected.fork);
380
+ }));
381
+ test("20 fork Create is idempotent and missing source rejects", Effect.gen(function* () {
382
+ yield* mutate(create());
383
+ yield* mutate(append());
384
+ applied(yield* fork(), "Created");
385
+ const exists = yield* Effect.flip(fork());
386
+ rejected(exists, "exists");
387
+ if (Predicate.isTagged(exists, "MutationRejected")) expect(exists.record).toEqual(yield* (yield* Storage).record(child));
388
+ rejected(yield* Effect.flip(mutate({
389
+ _tag: "Create",
390
+ record: record(StreamId.make("other")),
391
+ initialMessages: [],
392
+ forkSource: {
393
+ id: StreamId.make("missing"),
394
+ liveAtOffset: ZERO_OFFSET
395
+ }
396
+ })), "fork-source-gone");
397
+ }), options.expected.fork !== "none", "fork unavailable");
398
+ test("21 delete purges record, messages and producers", Effect.gen(function* () {
399
+ yield* mutate(create());
400
+ yield* mutate(append({ producer: {
401
+ producerId,
402
+ expected: Option.none(),
403
+ next: {
404
+ epoch: 0,
405
+ lastSeq: 0
406
+ }
407
+ } }));
408
+ applied(yield* mutate(remove()), "Purged");
409
+ const storage = yield* Storage;
410
+ expect(yield* storage.record(id)).toEqual(Option.none());
411
+ expect(yield* storage.messages(id, {})).toEqual([]);
412
+ expect(yield* storage.producer(id, producerId)).toEqual(Option.none());
413
+ }));
414
+ test("22 delete missing or soft-deleted rejects not-found or gone", Effect.gen(function* () {
415
+ rejected(yield* Effect.flip(mutate(remove())), "not-found");
416
+ yield* mutate(create({
417
+ ...record(),
418
+ lifecycle: {
419
+ closed: false,
420
+ softDeleted: true
421
+ }
422
+ }));
423
+ rejected(yield* Effect.flip(mutate(remove())), "gone");
424
+ rejected(yield* Effect.flip(mutate({
425
+ _tag: "Delete",
426
+ streamId: id,
427
+ reason: "expiry",
428
+ expectedExpiresAtMs: 3
429
+ })), "gone");
430
+ }));
431
+ test("23 stale expiry deletion leaves renewed deadline intact", Effect.gen(function* () {
432
+ yield* mutate(create({
433
+ ...record(),
434
+ lifecycle: {
435
+ closed: false,
436
+ softDeleted: false,
437
+ expiresAtMs: 100
438
+ }
439
+ }));
440
+ rejected(yield* Effect.flip(mutate({
441
+ _tag: "Delete",
442
+ streamId: id,
443
+ reason: "expiry",
444
+ expectedExpiresAtMs: 99
445
+ })), "expiry-mismatch");
446
+ expect((yield* current).lifecycle.expiresAtMs).toBe(100);
447
+ applied(yield* mutate({
448
+ _tag: "Delete",
449
+ streamId: id,
450
+ reason: "expiry",
451
+ expectedExpiresAtMs: 100
452
+ }), "Purged");
453
+ }));
454
+ test(`24 ${options.expected.fork === "chain" ? "soft-delete ancestor then cascade purge" : "purging copied source leaves child readable"}`, Effect.gen(function* () {
455
+ yield* mutate(create());
456
+ yield* mutate(append());
457
+ yield* fork();
458
+ applied(yield* mutate(remove()), options.expected.fork === "chain" ? "SoftDeleted" : "Purged");
459
+ const storage = yield* Storage;
460
+ expect((yield* storage.messages(child, {})).map((m) => new TextDecoder().decode(m.data))).toEqual(["a"]);
461
+ if (options.expected.fork === "chain") rejected(yield* Effect.flip(mutate(remove())), "gone");
462
+ yield* mutate(remove(child));
463
+ expect(yield* storage.record(id)).toEqual(Option.none());
464
+ expect(yield* storage.record(child)).toEqual(Option.none());
465
+ }), options.expected.fork !== "none", "fork unavailable");
466
+ test("25 interruption ends parked subscriber without fault and runs finalizer", Effect.gen(function* () {
467
+ yield* mutate(create());
468
+ const storage = yield* Storage;
469
+ const ready = yield* Deferred.make();
470
+ const done = yield* Deferred.make();
471
+ const fiber = yield* storage.changes(id).pipe(Stream.tap(() => Deferred.succeed(ready, void 0)), Stream.runDrain, Effect.ensuring(Deferred.succeed(done, void 0)), Effect.forkScoped);
472
+ yield* Deferred.await(ready);
473
+ yield* Fiber.interrupt(fiber);
474
+ yield* Deferred.await(done);
475
+ const exit = yield* Fiber.await(fiber);
476
+ expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
477
+ yield* mutate(append());
478
+ expect((yield* observe).initial.currentOffset).toBe(one);
479
+ }));
480
+ test("26 store mutation is all or nothing with first failure index", Effect.gen(function* () {
481
+ yield* mutate(create());
482
+ const storage = yield* Storage;
483
+ const out = yield* Effect.flip(storage.mutate({ operations: [create(record(child)), append({ expectedOffset: one })] }));
484
+ rejected(out, "offset");
485
+ if (Predicate.isTagged(out, "MutationRejected")) expect(out.index).toBe(1);
486
+ expect(yield* storage.record(child)).toEqual(Option.none());
487
+ expect((yield* current).currentOffset).toBe(ZERO_OFFSET);
488
+ const success = yield* storage.mutate({ operations: [create(record(child)), append()] });
489
+ expect(success).toMatchObject({ _tag: "Applied" });
490
+ expect(Option.isSome(yield* storage.record(child))).toBe(true);
491
+ }), options.expected.atomicScope === "store", "requires store atomic scope");
492
+ test("27 stream mutation rejects multiple targets as a defect", Effect.gen(function* () {
493
+ const storage = yield* Storage;
494
+ const exit = yield* Effect.exit(storage.mutate({ operations: [create(), create(record(child))] }));
495
+ expect(Exit.isFailure(exit) && Cause.hasDies(exit.cause)).toBe(true);
496
+ expect(yield* storage.record(id)).toEqual(Option.none());
497
+ }), options.expected.atomicScope === "stream", "requires stream atomic scope");
498
+ test("28 polling observes mutation within one virtual tick", Effect.gen(function* () {
499
+ yield* mutate(create());
500
+ const { queue } = yield* observe;
501
+ yield* mutate(append());
502
+ yield* tick;
503
+ expect((yield* Queue.take(queue)).currentOffset).toBe(one);
504
+ }), options.expected.wake === "poll", "requires polling wake");
505
+ test("29 lazy index is None; indexed returns and updates earliest deadline", Effect.gen(function* () {
506
+ const storage = yield* Storage;
507
+ yield* mutate(create({
508
+ ...record(),
509
+ lifecycle: {
510
+ closed: false,
511
+ softDeleted: false,
512
+ expiresAtMs: 200
513
+ }
514
+ }));
515
+ yield* mutate(create({
516
+ ...record(child),
517
+ lifecycle: {
518
+ closed: false,
519
+ softDeleted: false,
520
+ expiresAtMs: 100
521
+ }
522
+ }));
523
+ expect(yield* storage.nextExpiry).toEqual(options.expected.expiryIndex === "indexed" ? Option.some({
524
+ at: 100,
525
+ streamId: child
526
+ }) : Option.none());
527
+ yield* mutate(remove(child));
528
+ expect(yield* storage.nextExpiry).toEqual(options.expected.expiryIndex === "indexed" ? Option.some({
529
+ at: 200,
530
+ streamId: id
531
+ }) : Option.none());
532
+ yield* mutate(append({
533
+ messages: [],
534
+ patch: { clear: ["expiresAtMs"] }
535
+ }));
536
+ expect(yield* storage.nextExpiry).toEqual(Option.none());
537
+ }));
538
+ test("30 records and byte arrays do not alias input or returned values", Effect.gen(function* () {
539
+ const input = {
540
+ ...record(),
541
+ config: {
542
+ contentType: "text/plain",
543
+ createdAt: 0
544
+ }
545
+ };
546
+ const bytes = encode("a");
547
+ const storage = yield* Storage;
548
+ const outcome = yield* mutate({
549
+ _tag: "Create",
550
+ record: input,
551
+ initialMessages: [{
552
+ offset: one,
553
+ data: bytes,
554
+ timestamp: 0
555
+ }]
556
+ });
557
+ const created = Option.getOrThrow(Option.fromUndefinedOr(Predicate.isTagged(outcome, "Applied") ? outcome.results[0]?.record : void 0));
558
+ expect(created).not.toBe(input);
559
+ expect(created.config).not.toBe(input.config);
560
+ expect(created.lifecycle).not.toBe(input.lifecycle);
561
+ input.config.contentType = "changed";
562
+ const mutableCreated = created;
563
+ mutableCreated.config.contentType = "result-changed";
564
+ mutableCreated.lifecycle.closed = true;
565
+ bytes[0] = 98;
566
+ (yield* storage.messages(id, {}))[0]?.data.fill(99);
567
+ expect((yield* current).config.contentType).toBe("text/plain");
568
+ expect((yield* current).lifecycle.closed).toBe(false);
569
+ expect(new TextDecoder().decode((yield* storage.messages(id, {}))[0]?.data)).toBe("a");
570
+ const first = yield* current, second = yield* current;
571
+ expect(first).not.toBe(second);
572
+ expect(first.config).not.toBe(second.config);
573
+ expect(first.lifecycle).not.toBe(second.lifecycle);
574
+ }));
575
+ test("31 duplicate stream targets are a defect in every mode", Effect.gen(function* () {
576
+ const storage = yield* Storage;
577
+ const exit = yield* Effect.exit(storage.mutate({ operations: [create(), create()] }));
578
+ expect(Exit.isFailure(exit) && Cause.hasDies(exit.cause)).toBe(true);
579
+ expect(yield* storage.record(id)).toEqual(Option.none());
580
+ }));
581
+ test("32 patch clears optional fields and preserves unrelated values", Effect.gen(function* () {
582
+ yield* mutate(create({
583
+ ...record(),
584
+ config: {
585
+ contentType: "text/plain",
586
+ createdAt: 0,
587
+ ttlSeconds: 1,
588
+ expiresAt: "date"
589
+ },
590
+ lifecycle: {
591
+ closed: false,
592
+ softDeleted: false,
593
+ lastSeq: "x",
594
+ expiresAtMs: 100
595
+ }
596
+ }));
597
+ yield* mutate(append({
598
+ messages: [],
599
+ patch: { clear: [
600
+ "ttlSeconds",
601
+ "expiresAt",
602
+ "lastSeq",
603
+ "expiresAtMs"
604
+ ] }
605
+ }));
606
+ expect(yield* current).toEqual(record());
607
+ }));
608
+ test("33 nested fork boundaries and siblings survive until the last dependent is purged", Effect.gen(function* () {
609
+ const storage = yield* Storage;
610
+ const grandchild = StreamId.make("grandchild");
611
+ const sibling = StreamId.make("sibling");
612
+ yield* mutate(create());
613
+ yield* mutate(append());
614
+ yield* mutate(append({
615
+ messages: [{
616
+ offset: two,
617
+ data: encode("excluded"),
618
+ timestamp: 1
619
+ }],
620
+ patch: { currentOffset: two }
621
+ }));
622
+ applied(yield* fork(id, child, one), "Created");
623
+ yield* mutate(append({
624
+ streamId: child,
625
+ messages: [{
626
+ offset: two,
627
+ data: encode("child"),
628
+ timestamp: 2
629
+ }],
630
+ patch: { currentOffset: two }
631
+ }));
632
+ applied(yield* fork(child, grandchild), "Created");
633
+ applied(yield* fork(id, sibling, one), "Created");
634
+ const texts = (streamId) => storage.messages(streamId, {}).pipe(Effect.map((messages) => messages.map((m) => new TextDecoder().decode(m.data))));
635
+ expect(yield* texts(grandchild)).toEqual(["a", "child"]);
636
+ expect(yield* texts(sibling)).toEqual(["a"]);
637
+ const deletion = options.expected.fork === "chain" ? "SoftDeleted" : "Purged";
638
+ applied(yield* mutate(remove()), deletion);
639
+ applied(yield* mutate(remove(child)), deletion);
640
+ expect(yield* texts(grandchild)).toEqual(["a", "child"]);
641
+ applied(yield* mutate(remove(grandchild)), "Purged");
642
+ expect(yield* storage.record(child)).toEqual(Option.none());
643
+ expect(Option.isSome(yield* storage.record(id))).toBe(options.expected.fork === "chain");
644
+ expect(yield* texts(sibling)).toEqual(["a"]);
645
+ applied(yield* mutate(remove(sibling)), "Purged");
646
+ for (const streamId of [
647
+ id,
648
+ child,
649
+ grandchild,
650
+ sibling
651
+ ]) {
652
+ expect(yield* storage.record(streamId)).toEqual(Option.none());
653
+ expect(yield* storage.messages(streamId, {})).toEqual([]);
654
+ }
655
+ }), options.expected.fork !== "none", "fork unavailable");
656
+ test("34 atomic fork and source deletion retain lineage in either operation order", Effect.gen(function* () {
657
+ const storage = yield* Storage;
658
+ for (const deleteFirst of [false, true]) {
659
+ yield* mutate(create());
660
+ yield* mutate(append());
661
+ const creation = {
662
+ _tag: "Create",
663
+ initialMessages: [],
664
+ record: {
665
+ ...record(child),
666
+ currentOffset: one,
667
+ lifecycle: {
668
+ closed: false,
669
+ softDeleted: false,
670
+ forkedFrom: id,
671
+ forkOffset: one
672
+ }
673
+ },
674
+ forkSource: {
675
+ id,
676
+ liveAtOffset: one
677
+ }
678
+ };
679
+ const outcome = yield* storage.mutate({ operations: deleteFirst ? [remove(), creation] : [creation, remove()] });
680
+ expect(outcome).toMatchObject({ _tag: "Applied" });
681
+ if (Predicate.isTagged(outcome, "Applied")) expect(outcome.results.map(({ _tag: tag }) => tag)).toEqual(deleteFirst ? ["SoftDeleted", "Created"] : ["Created", "SoftDeleted"]);
682
+ expect((yield* current).lifecycle.softDeleted).toBe(true);
683
+ expect((yield* storage.messages(child, {})).map((m) => m.offset)).toEqual([one]);
684
+ yield* mutate(remove(child));
685
+ expect(yield* storage.record(id)).toEqual(Option.none());
686
+ }
687
+ }), options.expected.fork === "chain" && options.expected.atomicScope === "store", "requires chain fork and store atomic scope");
688
+ });
689
+ },
690
+ /** The configured memory suite must exercise each shipped capability value. */
691
+ assertModes(configurations) {
692
+ it("configured contract runs cover both shipped capability modes", () => {
693
+ for (const [key, expected] of Object.entries({
694
+ fork: ["chain", "copy"],
695
+ atomicScope: ["store", "stream"],
696
+ wake: ["push", "poll"],
697
+ expiryIndex: ["indexed", "lazy"]
698
+ })) expect(new Set(configurations.map((c) => Object.entries(c).find(([k]) => k === key)?.[1]))).toEqual(new Set(expected));
699
+ });
700
+ }
701
+ };
702
+ //#endregion
703
+ //#region src/testing/fault-injection.ts
704
+ /** One selected attempt per decorator; "after" injects only if that mutation applies. */
705
+ function faultyStorage(source, options) {
706
+ return Layer.effect(Storage, Effect.gen(function* () {
707
+ const storage = yield* Storage;
708
+ if (!Number.isInteger(options.failOn) || options.failOn < 1) return yield* Effect.die(/* @__PURE__ */ new RangeError("failOn must be a positive integer"));
709
+ let calls = 0;
710
+ return Storage.of({
711
+ ...storage,
712
+ mutate: Effect.fn("Testing.faultyStorage.mutate")(function* (mutation) {
713
+ const fail = ++calls === options.failOn;
714
+ const fault = new StorageFault({
715
+ operation: "mutate",
716
+ message: `Injected ${options.when} mutation failure`,
717
+ retryable: true
718
+ });
719
+ if (fail && options.when === "before") return yield* fault;
720
+ const result = yield* storage.mutate(mutation);
721
+ if (fail && options.when === "after") return yield* fault;
722
+ return result;
723
+ })
724
+ });
725
+ })).pipe(Layer.provide(source));
726
+ }
727
+ //#endregion
728
+ //#region src/testing/streams-test.ts
729
+ var StreamsTest = class extends Context.Service()("@streamsy/core/StreamsTest") {};
730
+ /** Real protocol and memory, with deterministic observation at the scoped changes boundary. */
731
+ const layerTest = (options = {}) => Layer.effectContext(Effect.gen(function* () {
732
+ const storage = yield* Storage;
733
+ const count = yield* Ref.make(0);
734
+ const snapshots = yield* Effect.acquireRelease(Queue.unbounded(), Queue.shutdown);
735
+ const observed = Storage.of({
736
+ ...storage,
737
+ changes: (id) => Stream.unwrap(Effect.gen(function* () {
738
+ yield* Effect.acquireRelease(Ref.update(count, (n) => n + 1), () => Ref.update(count, (n) => n - 1));
739
+ return storage.changes(id).pipe(Stream.tap((value) => Queue.offer(snapshots, {
740
+ id,
741
+ value
742
+ })));
743
+ }))
744
+ });
745
+ const context = yield* Layer.build(layer$1(options).pipe(Layer.provide(Layer.succeed(Storage, observed))));
746
+ return Context.add(context, StreamsTest, StreamsTest.of({
747
+ storage: observed,
748
+ subscribers: Ref.get(count),
749
+ snapshot: Queue.take(snapshots)
750
+ }));
751
+ })).pipe(Layer.provide(layer(options)));
752
+ //#endregion
753
+ //#region src/testing/expect-failure-tag.ts
754
+ /** An unexpected success stays a failure so the enclosing test cannot pass. */
755
+ const expectFailureTag = (effect, tag) => effect.pipe(Effect.flip, Effect.tap((error) => Effect.sync(() => expect(error._tag).toBe(tag))));
756
+ //#endregion
757
+ export { StorageContract, StreamsTest, expectFailureTag, faultyStorage, layerTest };