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