@streamsy/core 0.5.0 → 0.7.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,24 @@
1
+ import { Context, Effect } from "effect";
2
+ // src/internal/owner-records.ts
3
+ var OwnerRecords = class extends Context.Service()("@streamsy/core/internal/OwnerRecords") {};
4
+ // src/internal/commit-hooks.ts
5
+ var CommitHooks = class extends Context.Service()("@streamsy/core/internal/CommitHooks") {};
6
+ /** Shared registry for storage boundaries: register in a scope, run in order. */
7
+ const commitHookRegistry = () => {
8
+ const hooks = /* @__PURE__ */ new Set();
9
+ const beforeCommit = (hook) => Effect.acquireRelease(Effect.sync(() => {
10
+ const entry = { hook };
11
+ hooks.add(entry);
12
+ return entry;
13
+ }), (entry) => Effect.sync(() => {
14
+ hooks.delete(entry);
15
+ })).pipe(Effect.asVoid);
16
+ const run = (ids) => ids.size === 0 || hooks.size === 0 ? Effect.void : Effect.forEach([...hooks], (entry) => entry.hook(ids), { discard: true });
17
+ return {
18
+ beforeCommit,
19
+ run
20
+ };
21
+ };
22
+ // src/internal/projection-marks.ts
23
+ var ProjectionMarks = class extends Context.Service()("@streamsy/core/internal/ProjectionMarks") {};
24
+ export { OwnerRecords as i, CommitHooks as n, commitHookRegistry as r, ProjectionMarks as t };
@@ -1,5 +1,5 @@
1
- import { _ as StreamsWriter, g as StreamsReader, h as Reader, v as Writer } from "../owner-records-BV5Un5R0.js";
2
- import { D as streams_d_exports, P as layer_d_exports, u as RoutesOptions, z as route_d_exports } from "../index-C26ncp7Y.js";
1
+ import { C as StreamsReader, S as Reader, T as Writer, w as StreamsWriter } from "../projection-marks-28vAwOzM.js";
2
+ import { D as streams_d_exports, P as layer_d_exports, u as RoutesOptions, z as route_d_exports } from "../index-IhF2sua7.js";
3
3
  import { HttpRouter } from "effect/http";
4
4
  /** Raw protocol route for adapters and wire conformance tests. */
5
5
  export declare const routes: (options?: Omit<RoutesOptions, "access">) => import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request<"Requires", StreamsReader> | HttpRouter.Request<"Requires", StreamsWriter>>;
@@ -1,6 +1,6 @@
1
- import { A as StreamsReader, j as StreamsWriter, l as streams_exports, u as route_exports } from "../streamsy-DJMArv09.js";
2
- import { n as layer_exports } from "../layer-DyezIxJT.js";
3
- import { t as app } from "../program-DXUjw5B2.js";
1
+ import { F as StreamsWriter, P as StreamsReader, l as streams_exports, u as route_exports } from "../streamsy-D9OCCdw0.js";
2
+ import { n as layer_exports } from "../layer-8Y1cg6UL.js";
3
+ import { t as app } from "../program-CYtMjdvD.js";
4
4
  import { HttpRouter } from "effect/http";
5
5
  // src/protocol/routes.ts
6
6
  /** Raw protocol route for adapters and wire conformance tests. */
@@ -1,5 +1,5 @@
1
- import { _ as StreamsWriter, g as StreamsReader, vt as TransportFault } from "../owner-records-BV5Un5R0.js";
2
- import { f as Any, m as Identifiers, p as Group } from "../index-C26ncp7Y.js";
1
+ import { C as StreamsReader, Tt as TransportFault, w as StreamsWriter } from "../projection-marks-28vAwOzM.js";
2
+ import { f as Any, m as Identifiers, p as Group } from "../index-IhF2sua7.js";
3
3
  import { Layer } from "effect";
4
4
  import { HttpClient, HttpClientRequest } from "effect/http";
5
5
  interface Options {
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-D8jQpDG7.js";
2
- import { A as StreamsReader, C as ProducerGap, D as StreamGone, E as StreamClosed, O as StreamNotFound, Q as StreamId, S as OffsetMismatch, T as StreamBusy, V as TransportFault, _ as InvalidAppendRequest, b as InvalidReadRequest, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, j as StreamsWriter, m as AppendConflict, n as bind, p as CreateResult, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest } from "../streamsy-DJMArv09.js";
2
+ import { A as StreamClosed, C as InvalidForkRequest, D as ProducerGap, E as OffsetMismatch, F as StreamsWriter, G as TransportFault, M as StreamNotFound, O as StaleEpoch, P as StreamsReader, T as NotSupported, _ as CreateResult, b as ForkSourceNotFound, g as AppendResult, j as StreamGone, k as StreamBusy, n as bind, nt as StreamId, v as AppendConflict, w as InvalidReadRequest, x as InvalidAppendRequest, y as CreateConflict } from "../streamsy-D9OCCdw0.js";
3
3
  import { Array, Context, DateTime, Effect, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";
4
4
  import { HttpClient, HttpClientRequest } from "effect/http";
5
5
  // src/remote/request.ts
@@ -0,0 +1,93 @@
1
+ import { Context, Data, Effect, Predicate } from "effect";
2
+ // src/internal/owner.ts
3
+ /** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
4
+ const ForeignOwnerType = Symbol.for("@streamsy/core/internal/ForeignOwner");
5
+ var ForeignOwner = class extends Data.TaggedError("ForeignOwner") {
6
+ stream;
7
+ [ForeignOwnerType] = true;
8
+ constructor(stream, knownOwner) {
9
+ super({ message: knownOwner ? `Stream write to ${stream} does not share the checkpoint owner` : `Cannot establish a storage owner for ${stream}; the exposed Storage does not own the protocol wires` });
10
+ this.stream = stream;
11
+ }
12
+ };
13
+ const isForeignOwner = (value) => Predicate.hasProperty(value, ForeignOwnerType) && value[ForeignOwnerType] === true;
14
+ const OwnerMetadata = Symbol.for("@streamsy/core/internal/CommitOwner");
15
+ const attachOwner = (value, owner) => Object.defineProperty(value, OwnerMetadata, {
16
+ value: owner,
17
+ enumerable: false
18
+ });
19
+ const ownerOf = (value) => {
20
+ if (!(OwnerMetadata in value)) return value;
21
+ const owner = value[OwnerMetadata];
22
+ return Predicate.isObjectKeyword(owner) ? owner : value;
23
+ };
24
+ const CurrentOwner = Context.Reference("@streamsy/core/internal/CurrentOwner", { defaultValue: () => void 0 });
25
+ const checkWriteOwner = (owner, id, knownOwner) => Effect.flatMap(CurrentOwner, (expected) => expected === void 0 || expected === owner ? Effect.void : Effect.die(new ForeignOwner(id, knownOwner)));
26
+ const Metadata = Symbol.for("@streamsy/core/internal/StorageOwner");
27
+ const attachStorage = (wire, storage) => Object.defineProperty(wire, Metadata, {
28
+ value: storage,
29
+ enumerable: false
30
+ });
31
+ const storageOf = (wire) => {
32
+ if (!(Metadata in wire)) return void 0;
33
+ return wire[Metadata];
34
+ };
35
+ // src/toolkit/route-internal.ts
36
+ /** Ids are canonical relative paths, the same rule the remote Layer enforces. */
37
+ function isCanonicalIdSegment(value) {
38
+ if (value.length === 0 || value === "." || value === "..") return false;
39
+ return !/[%?#/\\]/.test(value);
40
+ }
41
+ function compileSegments(template) {
42
+ if (template.length === 0) throw new RangeError("a stream route template must name at least one segment");
43
+ if (template.startsWith("/")) throw new RangeError("a stream route template is relative and cannot start with a slash");
44
+ if (/[?#*]/.test(template)) throw new RangeError("a stream route template cannot contain a query, fragment, or wildcard");
45
+ const names = [];
46
+ const segments = [];
47
+ for (const part of template.split("/")) {
48
+ if (part.length === 0) throw new RangeError("a stream route template cannot contain an empty segment");
49
+ if (!part.startsWith(":")) {
50
+ if (!isCanonicalIdSegment(part)) throw new RangeError(`a stream route literal segment is not a canonical id segment: ${part}`);
51
+ segments.push({
52
+ kind: "literal",
53
+ value: part
54
+ });
55
+ continue;
56
+ }
57
+ const name = part.slice(1);
58
+ if (name.length === 0) throw new RangeError("a stream route parameter needs a name");
59
+ if (names.includes(name)) throw new RangeError(`duplicate stream route parameter: ${name}`);
60
+ names.push(name);
61
+ segments.push({
62
+ kind: "parameter",
63
+ name
64
+ });
65
+ }
66
+ return {
67
+ template,
68
+ segments: Object.freeze(segments),
69
+ names: Object.freeze(names)
70
+ };
71
+ }
72
+ /**
73
+ * True when two template routes can both match one id.
74
+ *
75
+ * Lengths must agree, and every position must be either an equal literal pair
76
+ * or a parameter on at least one side. A parameter is treated as matching any
77
+ * segment, so a codec-constrained parameter can report an overlap it would
78
+ * never actually match. A custom route carries no template and is never
79
+ * checked; HTTP dispatch uses declaration order and the first match wins.
80
+ */
81
+ function templatesOverlap(left, right) {
82
+ if (left.length === 0 || right.length === 0) return false;
83
+ const a = compileSegments(left).segments;
84
+ const b = compileSegments(right).segments;
85
+ if (a.length !== b.length) return false;
86
+ for (const [index, segment] of a.entries()) {
87
+ const other = b[index];
88
+ if (!other || segment.kind === "parameter" || other.kind === "parameter") continue;
89
+ if (segment.value !== other.value) return false;
90
+ }
91
+ return true;
92
+ }
93
+ export { attachOwner as a, isForeignOwner as c, CurrentOwner as i, ownerOf as l, isCanonicalIdSegment as n, attachStorage as o, templatesOverlap as r, checkWriteOwner as s, compileSegments as t, storageOf as u };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { i as checkWriteOwner, o as ownerOf, s as storageOf } from "./owner-BWQ2KvC_.js";
2
+ import { l as ownerOf, n as isCanonicalIdSegment, r as templatesOverlap, s as checkWriteOwner, t as compileSegments, u as storageOf } from "./route-internal-DNL0oGTN.js";
3
3
  import { Array, Context, Data, Duration, Effect, Layer, Option, Predicate, Record, Result, Schedule, Schema, Stream } from "effect";
4
4
  // src/schema/index.ts
5
5
  const StreamId = Schema.String.pipe(Schema.brand("StreamId"));
@@ -242,69 +242,12 @@ const isProtocolError = (error) => Record.has(protocolErrorTags, error._tag);
242
242
  /** Constructors and matchers for the protocol results above. */
243
243
  const CreateResult = Data.taggedEnum();
244
244
  const AppendResult = Data.taggedEnum();
245
- // src/toolkit/route-internal.ts
246
- /** Ids are canonical relative paths, the same rule the remote Layer enforces. */
247
- function isCanonicalIdSegment(value) {
248
- if (value.length === 0 || value === "." || value === "..") return false;
249
- return !/[%?#/\\]/.test(value);
250
- }
251
- function compileSegments(template) {
252
- if (template.length === 0) throw new RangeError("a stream route template must name at least one segment");
253
- if (template.startsWith("/")) throw new RangeError("a stream route template is relative and cannot start with a slash");
254
- if (/[?#*]/.test(template)) throw new RangeError("a stream route template cannot contain a query, fragment, or wildcard");
255
- const names = [];
256
- const segments = [];
257
- for (const part of template.split("/")) {
258
- if (part.length === 0) throw new RangeError("a stream route template cannot contain an empty segment");
259
- if (!part.startsWith(":")) {
260
- if (!isCanonicalIdSegment(part)) throw new RangeError(`a stream route literal segment is not a canonical id segment: ${part}`);
261
- segments.push({
262
- kind: "literal",
263
- value: part
264
- });
265
- continue;
266
- }
267
- const name = part.slice(1);
268
- if (name.length === 0) throw new RangeError("a stream route parameter needs a name");
269
- if (names.includes(name)) throw new RangeError(`duplicate stream route parameter: ${name}`);
270
- names.push(name);
271
- segments.push({
272
- kind: "parameter",
273
- name
274
- });
275
- }
276
- return {
277
- template,
278
- segments: Object.freeze(segments),
279
- names: Object.freeze(names)
280
- };
281
- }
282
- /**
283
- * True when two template routes can both match one id.
284
- *
285
- * Lengths must agree, and every position must be either an equal literal pair
286
- * or a parameter on at least one side. A parameter is treated as matching any
287
- * segment, so a codec-constrained parameter can report an overlap it would
288
- * never actually match. A custom route carries no template and is never
289
- * checked; HTTP dispatch uses declaration order and the first match wins.
290
- */
291
- function templatesOverlap(left, right) {
292
- if (left.length === 0 || right.length === 0) return false;
293
- const a = compileSegments(left).segments;
294
- const b = compileSegments(right).segments;
295
- if (a.length !== b.length) return false;
296
- for (const [index, segment] of a.entries()) {
297
- const other = b[index];
298
- if (!other || segment.kind === "parameter" || other.kind === "parameter") continue;
299
- if (segment.value !== other.value) return false;
300
- }
301
- return true;
302
- }
303
245
  // src/toolkit/address.ts
304
246
  var address_exports = /* @__PURE__ */ __exportAll({
305
247
  bytes: () => bytes$2,
306
248
  isChange: () => isChange,
307
249
  isControl: () => isControl,
250
+ isUpsert: () => isUpsert,
308
251
  json: () => json$2,
309
252
  reset: () => reset,
310
253
  snapshotEnd: () => snapshotEnd,
@@ -371,6 +314,8 @@ const stateControl = Schema.Struct({ headers: Schema.Struct({
371
314
  const isControl = (event) => Predicate.hasProperty(event.headers, "control");
372
315
  /** True for an upsert or delete change. */
373
316
  const isChange = (event) => !isControl(event);
317
+ /** True for an upsert change, with its value available. */
318
+ const isUpsert = (event) => isChange(event) && event.headers.operation === "upsert";
374
319
  const control = (name, options) => ({ headers: options.offset === void 0 ? { control: name } : {
375
320
  control: name,
376
321
  offset: options.offset
@@ -843,4 +788,4 @@ function group(...keys) {
843
788
  checkStreams(keys);
844
789
  return Object.freeze({ streams: Object.freeze(keys) });
845
790
  }
846
- export { StreamLifecycle as $, StreamsReader as A, StreamsFault as B, ProducerGap as C, StreamGone as D, StreamClosed as E, isValid as F, MessageWindow as G, isRetryableFault as H, next as I, ProducerState as J, Offset as K, DecodeFault as L, Storage as M, ZERO_OFFSET as N, StreamNotFound as O, compare as P, StreamId as Q, EncodeFault as R, OffsetMismatch as S, StreamBusy as T, isStreamsFault as U, TransportFault as V, ChangeSnapshot as W, StoredMessage as X, RecordPatch as Y, StreamConfig as Z, InvalidAppendRequest as _, custom as a, InvalidReadRequest as b, state as c, address_exports as d, StreamRecord as et, AppendResult as f, ForkSourceNotFound as g, CreateConflict as h, checkStreams as i, StreamsWriter as j, isProtocolError as k, streams_exports as l, AppendConflict as m, bind as n, group as o, CreateResult as p, ProducerId as q, bytes as r, json as s, Wildcard as t, route_exports as u, InvalidEpochSeq as v, StaleEpoch as w, NotSupported as x, InvalidForkRequest as y, StorageFault as z };
791
+ export { RecordPatch as $, StreamClosed as A, next as B, InvalidForkRequest as C, ProducerGap as D, OffsetMismatch as E, StreamsWriter as F, TransportFault as G, EncodeFault as H, Storage as I, ChangeSnapshot as J, isRetryableFault as K, ZERO_OFFSET as L, StreamNotFound as M, isProtocolError as N, StaleEpoch as O, StreamsReader as P, ProducerState as Q, compare as R, InvalidEpochSeq as S, NotSupported as T, StorageFault as U, DecodeFault as V, StreamsFault as W, Offset as X, MessageWindow as Y, ProducerId as Z, CreateResult as _, custom as a, ForkSourceNotFound as b, state as c, address_exports as d, StoredMessage as et, isControl as f, AppendResult as g, stateControl as h, checkStreams as i, StreamRecord as it, StreamGone as j, StreamBusy as k, streams_exports as l, stateChange as m, bind as n, StreamId as nt, group as o, isUpsert as p, isStreamsFault as q, bytes as r, StreamLifecycle as rt, json as s, Wildcard as t, StreamConfig as tt, route_exports as u, AppendConflict as v, InvalidReadRequest as w, InvalidAppendRequest as x, CreateConflict as y, isValid as z };
@@ -1,11 +1,14 @@
1
- import { _ as StreamsWriter, dt as StreamId, g as StreamsReader, m as StorageCapabilities, r as Storage, rt as ChangeSnapshot } from "../owner-records-BV5Un5R0.js";
2
- import { M as MemoryOptions, N as ProtocolOptions } from "../index-C26ncp7Y.js";
1
+ import { C as StreamsReader, u as Storage, ut as ChangeSnapshot, vt as StreamId, w as StreamsWriter, x as StorageCapabilities } from "../projection-marks-28vAwOzM.js";
2
+ import { M as MemoryOptions, N as ProtocolOptions } from "../index-IhF2sua7.js";
3
3
  import { Context, Effect, Layer } from "effect";
4
4
  interface StorageContractOptions {
5
5
  readonly name: string;
6
6
  readonly layer: Layer.Layer<Storage>;
7
7
  readonly expected: StorageCapabilities;
8
- /** The Layer also provides `CommitBoundary` and the internal owner records that projections need. */
8
+ /**
9
+ * The Layer also provides `CommitBoundary`, and the internal owner records,
10
+ * commit hooks and projection marks that projections need.
11
+ */
9
12
  readonly ownerRecords?: boolean;
10
13
  }
11
14
  export declare const StorageContract: {
@@ -1,11 +1,13 @@
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";
1
+ import { B as next, I as Storage, L as ZERO_OFFSET, U as StorageFault, Z as ProducerId, nt as StreamId } from "../streamsy-D9OCCdw0.js";
2
+ import { n as CommitBoundary, t as layer } from "../layer-C-QriVBc.js";
3
+ import { a as MutationRejected, t as layer$1 } from "../layer-8Y1cg6UL.js";
4
+ import { i as OwnerRecords, n as CommitHooks, t as ProjectionMarks } from "../projection-marks-RqurLPLA.js";
5
+ import { Array, Cause, Context, Deferred, Effect, Exit, Fiber, Layer, Match, Option, Order, Predicate, PubSub, Queue, Record, Ref, Scope, Stream } from "effect";
6
+ import { SqlError } from "effect/sql";
6
7
  import { describe, expect, it } from "vitest";
7
8
  import { TestClock } from "effect/testing";
8
9
  // src/testing/storage-contract.ts
10
+ /** Executable Bun edge: a fresh scoped Layer and virtual clock for every case. */
9
11
  const id = StreamId.make("s");
10
12
  const child = StreamId.make("child");
11
13
  const producerId = ProducerId.make("p");
@@ -130,7 +132,9 @@ const StorageContract = {
130
132
  const context = yield* Layer.build(options.layer);
131
133
  yield* body({
132
134
  boundary: Option.getOrThrow(Context.getOption(context, CommitBoundary)),
133
- records: Option.getOrThrow(Context.getOption(context, OwnerRecords))
135
+ records: Option.getOrThrow(Context.getOption(context, OwnerRecords)),
136
+ hooks: Option.getOrThrow(Context.getOption(context, CommitHooks)),
137
+ marks: Option.getOrThrow(Context.getOption(context, ProjectionMarks))
134
138
  }).pipe(Effect.provide(context));
135
139
  }).pipe(Effect.scoped, Effect.runPromiseExit)).resolves.toMatchObject({ _tag: "Success" }));
136
140
  };
@@ -161,6 +165,169 @@ const StorageContract = {
161
165
  expect(yield* records.read("checkpoint")).toEqual(Option.some("1"));
162
166
  expect(Option.isSome(yield* storage.record(id))).toBe(true);
163
167
  }));
168
+ recordsTest("R3 committed reports a transaction's ids after its commit and nothing after a rollback", ({ boundary }) => Effect.gen(function* () {
169
+ const storage = yield* Storage;
170
+ const other = StreamId.make("other");
171
+ const committed = yield* storage.committed;
172
+ const failed = yield* Effect.exit(boundary.withTransaction(Effect.andThen(mutate(create()), Effect.fail("rollback"))));
173
+ expect(Exit.isFailure(failed)).toBe(true);
174
+ expect(yield* PubSub.takeUpTo(committed, Infinity)).toEqual([]);
175
+ yield* boundary.withTransaction(Effect.gen(function* () {
176
+ yield* mutate(create());
177
+ yield* mutate(create(record(other)));
178
+ expect(yield* PubSub.takeUpTo(committed, Infinity)).toEqual([]);
179
+ }));
180
+ expect(yield* PubSub.takeUpTo(committed, Infinity)).toEqual([[id, other]]);
181
+ }));
182
+ recordsTest("R4 owner record keys of any length stay distinct, inside and outside a transaction", ({ boundary, records }) => Effect.gen(function* () {
183
+ const shared = "k".repeat(600);
184
+ const first = `${shared}-first`;
185
+ const second = `${shared}-second`;
186
+ yield* records.write(first, "1");
187
+ yield* boundary.withTransaction(Effect.gen(function* () {
188
+ expect(yield* records.read(second)).toEqual(Option.none());
189
+ yield* records.write(second, "2");
190
+ }));
191
+ expect(yield* records.read(first)).toEqual(Option.some("1"));
192
+ expect(yield* records.read(second)).toEqual(Option.some("2"));
193
+ yield* records.remove(first);
194
+ expect(yield* records.read(first)).toEqual(Option.none());
195
+ expect(yield* records.read(second)).toEqual(Option.some("2"));
196
+ }));
197
+ recordsTest("R5 commit hooks see the ids of create, append, delete and expiry before the commit", ({ boundary, hooks, records }) => Effect.gen(function* () {
198
+ const committed = yield* (yield* Storage).committed;
199
+ const seen = [];
200
+ const published = [];
201
+ const expiring = StreamId.make("expiring");
202
+ const scope = yield* Scope.fork(yield* Scope.Scope);
203
+ yield* hooks.beforeCommit((ids) => Effect.gen(function* () {
204
+ published.push(...yield* PubSub.takeUpTo(committed, Infinity));
205
+ expect(published).toHaveLength(seen.length);
206
+ seen.push([...ids]);
207
+ })).pipe(Scope.provide(scope));
208
+ yield* mutate(create());
209
+ yield* mutate(append());
210
+ expect(Exit.isFailure(yield* Effect.exit(mutate(create())))).toBe(true);
211
+ yield* mutate(remove());
212
+ yield* mutate(create({
213
+ ...record(expiring),
214
+ lifecycle: {
215
+ closed: false,
216
+ softDeleted: false,
217
+ expiresAtMs: 100
218
+ }
219
+ }));
220
+ yield* mutate({
221
+ _tag: "Delete",
222
+ streamId: expiring,
223
+ reason: "expiry",
224
+ expectedExpiresAtMs: 100
225
+ });
226
+ yield* boundary.withTransaction(records.write("only-records", "1"));
227
+ expect(seen).toEqual([
228
+ [id],
229
+ [id],
230
+ [id],
231
+ [expiring],
232
+ [expiring]
233
+ ]);
234
+ const other = StreamId.make("other");
235
+ yield* boundary.withTransaction(Effect.andThen(mutate(create(record(other))), mutate(create(record(child)))));
236
+ expect(seen[5]).toEqual([other, child]);
237
+ yield* Scope.close(scope, Exit.void);
238
+ yield* mutate(remove(other));
239
+ expect(seen).toHaveLength(6);
240
+ }));
241
+ recordsTest("R6 a hook's writes join the transaction and a hook failure rolls the write back", ({ hooks, records }) => Effect.gen(function* () {
242
+ const storage = yield* Storage;
243
+ let fail = false;
244
+ yield* hooks.beforeCommit((ids) => fail ? Effect.fail(new SqlError.SqlError({ reason: new SqlError.UnknownError({
245
+ cause: "hook",
246
+ message: "hook failed"
247
+ }) })) : Effect.orDie(records.write("hooked", Array.join([...ids], ","))));
248
+ yield* mutate(create());
249
+ expect(yield* records.read("hooked")).toEqual(Option.some(id));
250
+ fail = true;
251
+ const committed = yield* storage.committed;
252
+ expect(Exit.isFailure(yield* Effect.exit(mutate(append())))).toBe(true);
253
+ expect((yield* current).currentOffset).toBe(ZERO_OFFSET);
254
+ expect(yield* PubSub.takeUpTo(committed, Infinity)).toEqual([]);
255
+ }));
256
+ recordsTest("R7 projection marks raise seq, clear by seq, defer, and list due marks in order", ({ marks }) => Effect.gen(function* () {
257
+ expect(yield* marks.nextDue("p")).toEqual(Option.none());
258
+ yield* Effect.orDie(marks.mark("p", ["a", "b"]));
259
+ yield* Effect.orDie(marks.mark("p", ["a"]));
260
+ yield* Effect.orDie(marks.mark("q", ["a"]));
261
+ const read = yield* marks.read("p", [
262
+ "a",
263
+ "b",
264
+ "absent"
265
+ ]);
266
+ expect(Array.sort([...read.keys()], Order.String)).toEqual(["a", "b"]);
267
+ expect(read.get("a")).toEqual({
268
+ params: "a",
269
+ seq: 2,
270
+ attempts: 0,
271
+ dueAt: 0
272
+ });
273
+ expect(read.get("b")).toEqual({
274
+ params: "b",
275
+ seq: 1,
276
+ attempts: 0,
277
+ dueAt: 0
278
+ });
279
+ expect(yield* marks.nextDue("p")).toEqual(Option.some(0));
280
+ yield* marks.clear("p", "a", 1);
281
+ expect((yield* marks.read("p", ["a"])).get("a")?.seq).toBe(2);
282
+ yield* marks.clear("p", "a", 2);
283
+ expect((yield* marks.read("p", ["a"])).size).toBe(0);
284
+ expect((yield* marks.read("q", ["a"])).get("a")?.seq).toBe(1);
285
+ yield* marks.defer("p", "b", 1, 5e3);
286
+ yield* Effect.orDie(marks.mark("p", ["b"]));
287
+ expect((yield* marks.read("p", ["b"])).get("b")).toEqual({
288
+ params: "b",
289
+ seq: 2,
290
+ attempts: 1,
291
+ dueAt: 5e3
292
+ });
293
+ expect(yield* marks.deferred("p")).toBe(1);
294
+ expect(yield* marks.nextDue("p")).toEqual(Option.some(5e3));
295
+ yield* marks.defer("p", "c", 2, 3e3);
296
+ expect(yield* marks.deferred("p")).toBe(2);
297
+ yield* Effect.orDie(marks.mark("p", ["e", "d"]));
298
+ expect(Array.map(yield* marks.due("p", 4e3, 10), (row) => row.params)).toEqual([
299
+ "d",
300
+ "e",
301
+ "c"
302
+ ]);
303
+ expect(Array.map(yield* marks.due("p", 1e4, 2), (row) => row.params)).toEqual(["d", "e"]);
304
+ expect(Array.map(yield* marks.due("p", 1e4, 10), (row) => row.params)).toEqual([
305
+ "d",
306
+ "e",
307
+ "c",
308
+ "b"
309
+ ]);
310
+ yield* marks.remove("p", "b");
311
+ yield* marks.remove("p", "absent");
312
+ expect(yield* marks.deferred("p")).toBe(1);
313
+ const many = Array.makeBy(150, (index) => `m${String(index).padStart(3, "0")}`);
314
+ yield* Effect.orDie(marks.mark("many", many));
315
+ yield* Effect.orDie(marks.mark("many", many));
316
+ const all = yield* marks.read("many", many);
317
+ expect(all.size).toBe(150);
318
+ expect(Array.every([...all.values()], (row) => row.seq === 2)).toBe(true);
319
+ expect(yield* marks.due("many", 0, 1e3)).toHaveLength(150);
320
+ }));
321
+ recordsTest("R8 marks written by a commit hook commit and roll back with the write", ({ boundary, hooks, marks }) => Effect.gen(function* () {
322
+ yield* hooks.beforeCommit((ids) => marks.mark("p", [...ids]));
323
+ yield* mutate(create());
324
+ expect((yield* marks.read("p", [id])).get(id)?.seq).toBe(1);
325
+ const failed = yield* Effect.exit(boundary.withTransaction(Effect.andThen(mutate(append()), Effect.fail("rollback"))));
326
+ expect(Exit.isFailure(failed)).toBe(true);
327
+ expect((yield* marks.read("p", [id])).get(id)?.seq).toBe(1);
328
+ yield* mutate(append());
329
+ expect((yield* marks.read("p", [id])).get(id)?.seq).toBe(2);
330
+ }));
164
331
  test("01 Append advances tail and folds close atomically", Effect.gen(function* () {
165
332
  yield* mutate(create());
166
333
  applied(yield* mutate(append({ patch: {
@@ -684,6 +851,55 @@ const StorageContract = {
684
851
  expect(yield* storage.record(id)).toEqual(Option.none());
685
852
  }
686
853
  }), options.expected.fork === "chain" && options.expected.atomicScope === "store", "requires chain fork and store atomic scope");
854
+ test("34a committed broadcasts without replay and releases each subscription independently", Effect.gen(function* () {
855
+ const storage = yield* Storage;
856
+ let released = 0;
857
+ const scope = yield* Scope.fork(yield* Scope.Scope);
858
+ const first = yield* storage.committed.pipe(Effect.tap(() => Effect.addFinalizer(() => Effect.sync(() => {
859
+ released += 1;
860
+ }))), Scope.provide(scope));
861
+ yield* mutate(create());
862
+ expect(yield* PubSub.take(first)).toEqual([id]);
863
+ const second = yield* storage.committed;
864
+ expect(yield* PubSub.takeUpTo(second, Infinity)).toEqual([]);
865
+ yield* mutate(append());
866
+ expect(yield* PubSub.take(first)).toEqual([id]);
867
+ expect(yield* PubSub.take(second)).toEqual([id]);
868
+ yield* Scope.close(scope, Exit.void);
869
+ expect(released).toBe(1);
870
+ yield* mutate(remove());
871
+ expect(yield* PubSub.take(second)).toEqual([id]);
872
+ }));
873
+ test("35 committed reports the ids of create, append, delete and expiry after commit", Effect.gen(function* () {
874
+ const storage = yield* Storage;
875
+ const expiring = StreamId.make("expiring");
876
+ const committed = yield* storage.committed;
877
+ yield* mutate(create());
878
+ expect(yield* PubSub.takeUpTo(committed, Infinity)).toEqual([[id]]);
879
+ yield* mutate(append());
880
+ rejected(yield* Effect.flip(mutate(create())), "exists");
881
+ yield* mutate(remove());
882
+ yield* mutate(create({
883
+ ...record(expiring),
884
+ lifecycle: {
885
+ closed: false,
886
+ softDeleted: false,
887
+ expiresAtMs: 100
888
+ }
889
+ }));
890
+ yield* mutate({
891
+ _tag: "Delete",
892
+ streamId: expiring,
893
+ reason: "expiry",
894
+ expectedExpiresAtMs: 100
895
+ });
896
+ expect(yield* PubSub.takeUpTo(committed, Infinity)).toEqual([
897
+ [id],
898
+ [id],
899
+ [expiring],
900
+ [expiring]
901
+ ]);
902
+ }));
687
903
  });
688
904
  },
689
905
  /** The configured memory suite must exercise each shipped capability value. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@streamsy/core",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Effect-first Durable Streams protocol, storage contract, memory layer and toolkit.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,35 +0,0 @@
1
- import { Context, Data, Effect, Predicate } from "effect";
2
- // src/internal/owner.ts
3
- /** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
4
- const ForeignOwnerType = Symbol.for("@streamsy/core/internal/ForeignOwner");
5
- var ForeignOwner = class extends Data.TaggedError("ForeignOwner") {
6
- stream;
7
- [ForeignOwnerType] = true;
8
- constructor(stream, knownOwner) {
9
- super({ message: knownOwner ? `Stream write to ${stream} does not share the checkpoint owner` : `Cannot establish a storage owner for ${stream}; the exposed Storage does not own the protocol wires` });
10
- this.stream = stream;
11
- }
12
- };
13
- const isForeignOwner = (value) => Predicate.hasProperty(value, ForeignOwnerType) && value[ForeignOwnerType] === true;
14
- const OwnerMetadata = Symbol.for("@streamsy/core/internal/CommitOwner");
15
- const attachOwner = (value, owner) => Object.defineProperty(value, OwnerMetadata, {
16
- value: owner,
17
- enumerable: false
18
- });
19
- const ownerOf = (value) => {
20
- if (!(OwnerMetadata in value)) return value;
21
- const owner = value[OwnerMetadata];
22
- return Predicate.isObjectKeyword(owner) ? owner : value;
23
- };
24
- const CurrentOwner = Context.Reference("@streamsy/core/internal/CurrentOwner", { defaultValue: () => void 0 });
25
- const checkWriteOwner = (owner, id, knownOwner) => Effect.flatMap(CurrentOwner, (expected) => expected === void 0 || expected === owner ? Effect.void : Effect.die(new ForeignOwner(id, knownOwner)));
26
- const Metadata = Symbol.for("@streamsy/core/internal/StorageOwner");
27
- const attachStorage = (wire, storage) => Object.defineProperty(wire, Metadata, {
28
- value: storage,
29
- enumerable: false
30
- });
31
- const storageOf = (wire) => {
32
- if (!(Metadata in wire)) return void 0;
33
- return wire[Metadata];
34
- };
35
- export { isForeignOwner as a, checkWriteOwner as i, attachOwner as n, ownerOf as o, attachStorage as r, storageOf as s, CurrentOwner as t };
@@ -1,4 +0,0 @@
1
- import { Context } from "effect";
2
- // src/internal/owner-records.ts
3
- var OwnerRecords = class extends Context.Service()("@streamsy/core/internal/OwnerRecords") {};
4
- export { OwnerRecords as t };