@streamsy/core 0.2.1 → 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,22 @@
1
+ import { n as OwnerRecordsApi, t as OwnerRecords } from "../owner-records-QDlssl__.js";
2
+ import { Context, Effect } from "effect";
3
+ //#region src/internal/owner.d.ts
4
+ /** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
5
+ declare const ForeignOwnerType: unique symbol;
6
+ declare const ForeignOwner_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
7
+ readonly _tag: "ForeignOwner";
8
+ } & Readonly<A>;
9
+ declare class ForeignOwner extends ForeignOwner_base<{
10
+ readonly message: string;
11
+ }> {
12
+ readonly stream: string;
13
+ readonly [ForeignOwnerType] = true;
14
+ constructor(stream: string, knownOwner: boolean);
15
+ }
16
+ export declare const isForeignOwner: (value: unknown) => value is ForeignOwner;
17
+ type Owner = object;
18
+ export declare const attachOwner: <A extends object>(value: A, owner: Owner) => A;
19
+ export declare const ownerOf: (value: object) => Owner;
20
+ export declare const CurrentOwner: Context.Reference<object | undefined>;
21
+ //#endregion
22
+ export { OwnerRecords, type OwnerRecordsApi };
@@ -0,0 +1,3 @@
1
+ import { a as isForeignOwner, n as attachOwner, o as ownerOf, t as CurrentOwner } from "../owner-BQzMpfC1.js";
2
+ import { t as OwnerRecords } from "../owner-records-CX6yU28i.js";
3
+ export { CurrentOwner, OwnerRecords, attachOwner, isForeignOwner, ownerOf };
@@ -0,0 +1,340 @@
1
+ import { M as Storage, N as ZERO_OFFSET } from "./streamsy-OjRubIPC.js";
2
+ import { a as MutationRejected, l as OperationResults, o as Mutations, u as Operations } from "./layer-KvknRFUT.js";
3
+ import { n as attachOwner, o as ownerOf } from "./owner-BQzMpfC1.js";
4
+ import { t as OwnerRecords } from "./owner-records-CX6yU28i.js";
5
+ import { Context, Effect, Layer, Option, Predicate, Queue, Schedule, Semaphore, Stream } from "effect";
6
+ //#region src/storage/commit-boundary.ts
7
+ /** The transaction of the storage owner. Every Streamsy storage host provides it. */
8
+ var CommitBoundary = class extends Context.Service()("@streamsy/core/CommitBoundary") {};
9
+ //#endregion
10
+ //#region src/storage/memory/state.ts
11
+ const copyRecord = (record) => ({
12
+ id: record.id,
13
+ currentOffset: record.currentOffset,
14
+ config: { ...record.config },
15
+ lifecycle: { ...record.lifecycle }
16
+ });
17
+ const copyMessage = (message) => ({
18
+ offset: message.offset,
19
+ timestamp: message.timestamp,
20
+ data: new Uint8Array(message.data)
21
+ });
22
+ function patchRecord(record, patch) {
23
+ const config = {
24
+ ...record.config,
25
+ ...patch.config
26
+ };
27
+ const lifecycle = {
28
+ ...record.lifecycle,
29
+ ...patch.lifecycle
30
+ };
31
+ for (const key of patch.clear ?? []) switch (key) {
32
+ case "ttlSeconds":
33
+ delete config.ttlSeconds;
34
+ break;
35
+ case "expiresAt":
36
+ delete config.expiresAt;
37
+ break;
38
+ case "expiresAtMs":
39
+ delete lifecycle.expiresAtMs;
40
+ break;
41
+ case "lastSeq": delete lifecycle.lastSeq;
42
+ }
43
+ return {
44
+ id: record.id,
45
+ currentOffset: patch.currentOffset ?? record.currentOffset,
46
+ config,
47
+ lifecycle
48
+ };
49
+ }
50
+ function indexDeadlines(state) {
51
+ state.deadlines = [...state.entries.values()].flatMap(({ record }) => record.lifecycle.softDeleted || record.lifecycle.expiresAtMs === void 0 ? [] : [{
52
+ at: record.lifecycle.expiresAtMs,
53
+ streamId: record.id
54
+ }]).toSorted((a, b) => a.at - b.at || a.streamId.localeCompare(b.streamId));
55
+ }
56
+ /** A private transaction draft; no mutable stream data aliases the committed state. */
57
+ const copyState = (state) => ({
58
+ entries: new Map([...state.entries].map(([id, entry]) => [id, {
59
+ record: copyRecord(entry.record),
60
+ messages: entry.messages.map(copyMessage),
61
+ producers: new Map([...entry.producers].map(([producerId, producer]) => [producerId, {
62
+ epoch: producer.epoch,
63
+ lastSeq: producer.lastSeq
64
+ }]))
65
+ }])),
66
+ children: new Map([...state.children].map(([id, children]) => [id, new Set(children)])),
67
+ deadlines: state.deadlines.map((deadline) => ({ ...deadline }))
68
+ });
69
+ //#endregion
70
+ //#region src/storage/memory/lineage.ts
71
+ function addEdge(state, parent, child) {
72
+ const children = state.children.get(parent) ?? /* @__PURE__ */ new Set();
73
+ children.add(child);
74
+ state.children.set(parent, children);
75
+ }
76
+ const hasDependents = (state, id) => (state.children.get(id)?.size ?? 0) > 0;
77
+ function purge(state, record, chain, changed) {
78
+ let current = record;
79
+ while (current) {
80
+ const childId = current.id;
81
+ const parentId = chain ? current.lifecycle.forkedFrom : void 0;
82
+ state.entries.delete(childId);
83
+ state.children.delete(childId);
84
+ changed.add(childId);
85
+ if (parentId === void 0) return;
86
+ const children = state.children.get(parentId);
87
+ children?.delete(childId);
88
+ if (children?.size === 0) state.children.delete(parentId);
89
+ const parent = state.entries.get(parentId)?.record;
90
+ if (!parent?.lifecycle.softDeleted || hasDependents(state, parentId)) return;
91
+ current = parent;
92
+ }
93
+ }
94
+ function composeMessages(state, id, chain) {
95
+ const entry = state.entries.get(id);
96
+ if (!entry) return [];
97
+ const { forkedFrom, forkOffset } = entry.record.lifecycle;
98
+ return [...chain && forkedFrom !== void 0 && forkOffset !== void 0 ? composeMessages(state, forkedFrom, true).filter((message) => message.offset <= forkOffset) : [], ...entry.messages].toSorted((a, b) => a.offset < b.offset ? -1 : a.offset > b.offset ? 1 : 0);
99
+ }
100
+ //#endregion
101
+ //#region src/storage/memory/notifier.ts
102
+ /** Private store-wide wakes, with retention isolated to each active subscription. */
103
+ const createNotifier = Effect.gen(function* () {
104
+ const queues = /* @__PURE__ */ new Set();
105
+ const subscriptions = queues;
106
+ let closed = false;
107
+ yield* Effect.addFinalizer(() => Effect.gen(function* () {
108
+ const detached = yield* Effect.sync(() => {
109
+ closed = true;
110
+ const active = [...queues];
111
+ queues.clear();
112
+ return active;
113
+ });
114
+ for (const queue of detached) yield* Queue.shutdown(queue);
115
+ }));
116
+ return {
117
+ queues: subscriptions,
118
+ get closed() {
119
+ return closed;
120
+ },
121
+ subscribe: Effect.acquireRelease(Effect.gen(function* () {
122
+ const queue = yield* Queue.make({
123
+ capacity: 1,
124
+ strategy: "dropping"
125
+ });
126
+ if (!(yield* Effect.sync(() => {
127
+ if (closed) return false;
128
+ queues.add(queue);
129
+ return true;
130
+ }))) {
131
+ yield* Queue.shutdown(queue);
132
+ return yield* Effect.interrupt;
133
+ }
134
+ return queue;
135
+ }), (queue) => Effect.andThen(Effect.sync(() => queues.delete(queue)), Queue.shutdown(queue))),
136
+ publish: Effect.sync(() => {
137
+ for (const queue of queues) Queue.offerUnsafe(queue, void 0);
138
+ })
139
+ };
140
+ });
141
+ //#endregion
142
+ //#region src/storage/memory/boundary.ts
143
+ var ActiveDraft = class extends Context.Service()("@streamsy/core/internal/MemoryActiveDraft") {};
144
+ const makeBoundary = (committed, publish) => Effect.gen(function* () {
145
+ const owner = {};
146
+ const lock = yield* Semaphore.make(1);
147
+ let committedRecords = /* @__PURE__ */ new Map();
148
+ const current = Effect.flatMap(Effect.serviceOption(ActiveDraft), (draft) => Effect.withFiber((fiber) => {
149
+ if (Option.isSome(draft) && (draft.value.owner !== owner || !draft.value.active || draft.value.fiberId !== fiber.id)) return Effect.die(/* @__PURE__ */ new Error("Memory boundary requires the active owner fiber"));
150
+ return Effect.succeed(draft);
151
+ }));
152
+ const withTransaction = (body) => Effect.flatMap(current, (ambient) => {
153
+ if (Option.isSome(ambient)) return body;
154
+ return Effect.withFiber((fiber) => Effect.suspend(() => {
155
+ const draft = {
156
+ owner,
157
+ fiberId: fiber.id,
158
+ state: copyState(committed),
159
+ records: new Map(committedRecords),
160
+ active: true,
161
+ changed: false
162
+ };
163
+ return Effect.uninterruptibleMask((restore) => restore(body.pipe(Effect.provideService(ActiveDraft, draft))).pipe(Effect.tap(() => Effect.sync(() => {
164
+ Object.assign(committed, draft.state);
165
+ committedRecords = draft.records;
166
+ }).pipe(Effect.andThen(Effect.suspend(() => draft.changed ? publish : Effect.void)))), Effect.ensuring(Effect.sync(() => {
167
+ draft.active = false;
168
+ }))));
169
+ }).pipe(Semaphore.withPermit(lock)));
170
+ });
171
+ const access = (f) => Effect.map(current, (draft) => f(Option.isSome(draft) ? draft.value.state : committed));
172
+ const changed = Effect.map(current, (draft) => {
173
+ if (Option.isNone(draft)) throw new Error("Memory mutation requires an owner");
174
+ draft.value.changed = true;
175
+ });
176
+ const boundary = CommitBoundary.of({ withTransaction });
177
+ const records = OwnerRecords.of({
178
+ read: (key) => Effect.map(current, (draft) => Option.fromUndefinedOr((Option.isSome(draft) ? draft.value.records : committedRecords).get(key))),
179
+ remove: (key) => withTransaction(Effect.map(current, (draft) => {
180
+ if (Option.isNone(draft)) throw new Error("Memory record delete requires an owner");
181
+ draft.value.records.delete(key);
182
+ })),
183
+ write: (key, encoded) => withTransaction(Effect.map(current, (draft) => {
184
+ if (Option.isNone(draft)) throw new Error("Memory record write requires an owner");
185
+ draft.value.records.set(key, encoded);
186
+ }))
187
+ });
188
+ return {
189
+ boundary: attachOwner(boundary, owner),
190
+ records: attachOwner(records, owner),
191
+ withTransaction,
192
+ access,
193
+ changed
194
+ };
195
+ });
196
+ //#endregion
197
+ //#region src/storage/memory/changes.ts
198
+ function snapshot(state, id) {
199
+ const record = state.entries.get(id)?.record;
200
+ return {
201
+ present: record !== void 0,
202
+ currentOffset: record?.currentOffset ?? ZERO_OFFSET,
203
+ closed: record?.lifecycle.closed ?? false,
204
+ softDeleted: record?.lifecycle.softDeleted ?? false
205
+ };
206
+ }
207
+ function changes(state, bus, id, push, interval) {
208
+ const read = Effect.sync(() => snapshot(state, id));
209
+ if (!push) return Stream.fromEffect(read).pipe(Stream.repeat(Schedule.spaced(interval)));
210
+ return Stream.unwrap(Effect.gen(function* () {
211
+ const subscription = yield* bus.subscribe;
212
+ return Stream.concat(Stream.fromEffect(read), Stream.fromQueue(subscription).pipe(Stream.mapEffect(() => read)));
213
+ }));
214
+ }
215
+ //#endregion
216
+ //#region src/storage/memory/layer.ts
217
+ function reject(state, operation, index) {
218
+ const id = Predicate.isTagged(operation, "Create") ? operation.record.id : operation.streamId;
219
+ const entry = state.entries.get(id);
220
+ const record = entry?.record;
221
+ const rejected = (reason) => new MutationRejected({
222
+ index,
223
+ reason,
224
+ record: record ? Option.some(copyRecord(record)) : Option.none()
225
+ });
226
+ if (Predicate.isTagged(operation, "Create")) {
227
+ if (record) return rejected("exists");
228
+ if (operation.forkSource) {
229
+ const source = state.entries.get(operation.forkSource.id)?.record;
230
+ if (!source || source.lifecycle.softDeleted || source.currentOffset < operation.forkSource.liveAtOffset) return rejected("fork-source-gone");
231
+ }
232
+ return;
233
+ }
234
+ if (!entry || !record) return rejected("not-found");
235
+ if (record.lifecycle.softDeleted) return rejected("gone");
236
+ if (Predicate.isTagged(operation, "Delete")) {
237
+ if (operation.reason === "expiry" && (operation.expectedExpiresAtMs === void 0 || record.lifecycle.expiresAtMs !== operation.expectedExpiresAtMs)) return rejected("expiry-mismatch");
238
+ return;
239
+ }
240
+ if (operation.expectedOffset !== void 0 && operation.expectedOffset !== record.currentOffset) return rejected("offset");
241
+ if (operation.expectedClosed !== void 0 && operation.expectedClosed !== record.lifecycle.closed) return rejected("closed");
242
+ if (operation.producer) {
243
+ const actual = entry.producers.get(operation.producer.producerId);
244
+ const expected = Option.getOrUndefined(operation.producer.expected);
245
+ if (actual?.epoch !== expected?.epoch || actual?.lastSeq !== expected?.lastSeq) return rejected("producer");
246
+ }
247
+ }
248
+ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
249
+ const chain = !options.constrained;
250
+ const interval = options.pollIntervalMs ?? 25;
251
+ if (!Number.isFinite(interval) || interval <= 0) return yield* Effect.die(/* @__PURE__ */ new RangeError("pollIntervalMs must be positive"));
252
+ const committed = {
253
+ entries: /* @__PURE__ */ new Map(),
254
+ children: /* @__PURE__ */ new Map(),
255
+ deadlines: []
256
+ };
257
+ const bus = yield* createNotifier;
258
+ const owner = yield* makeBoundary(committed, bus.publish);
259
+ const commit = (state, mutation) => {
260
+ const changed = /* @__PURE__ */ new Set();
261
+ for (const [index, operation] of mutation.operations.entries()) {
262
+ const rejection = reject(state, operation, index);
263
+ if (rejection) return rejection;
264
+ }
265
+ const results = [];
266
+ for (const operation of mutation.operations) {
267
+ if (!Predicate.isTagged(operation, "Create")) continue;
268
+ const record = copyRecord(operation.record);
269
+ state.entries.set(record.id, {
270
+ record,
271
+ messages: operation.initialMessages.map(copyMessage),
272
+ producers: /* @__PURE__ */ new Map()
273
+ });
274
+ if (chain && record.lifecycle.forkedFrom !== void 0) addEdge(state, record.lifecycle.forkedFrom, record.id);
275
+ }
276
+ for (const operation of mutation.operations) {
277
+ const id = Predicate.isTagged(operation, "Create") ? operation.record.id : operation.streamId;
278
+ const entry = state.entries.get(id);
279
+ if (!entry) throw new Error("Mutation target disappeared after preflight");
280
+ changed.add(id);
281
+ Operations.$match(operation, {
282
+ Create: () => {
283
+ results.push(OperationResults.Created({ record: copyRecord(entry.record) }));
284
+ },
285
+ Append: (append) => {
286
+ entry.messages.push(...append.messages.map(copyMessage));
287
+ entry.record = patchRecord(entry.record, append.patch);
288
+ if (append.producer) entry.producers.set(append.producer.producerId, { ...append.producer.next });
289
+ results.push(OperationResults.Appended({ record: copyRecord(entry.record) }));
290
+ },
291
+ Delete: () => {
292
+ if (chain && hasDependents(state, id)) {
293
+ entry.record = patchRecord(entry.record, { lifecycle: { softDeleted: true } });
294
+ results.push(OperationResults.SoftDeleted({ record: copyRecord(entry.record) }));
295
+ } else {
296
+ results.push(OperationResults.Purged({ record: copyRecord(entry.record) }));
297
+ purge(state, entry.record, chain, changed);
298
+ }
299
+ }
300
+ });
301
+ }
302
+ if (chain) indexDeadlines(state);
303
+ const [first, ...rest] = results;
304
+ if (!first) throw new Error("Empty mutation");
305
+ return {
306
+ outcome: Mutations.Applied({ results: [first, ...rest] }),
307
+ changed
308
+ };
309
+ };
310
+ const storage = Storage.of({
311
+ capabilities: {
312
+ fork: chain ? "chain" : "copy",
313
+ atomicScope: chain ? "store" : "stream",
314
+ wake: chain ? "push" : "poll",
315
+ expiryIndex: chain ? "indexed" : "lazy"
316
+ },
317
+ record: Effect.fn("Memory.record")((id) => owner.access((state) => Option.fromUndefinedOr(state.entries.get(id)?.record).pipe(Option.map(copyRecord)))),
318
+ messages: Effect.fn("Memory.messages")((id, window) => owner.access((state) => composeMessages(state, id, chain).filter((message) => (window.after === void 0 || message.offset > window.after) && (window.until === void 0 || message.offset <= window.until)).slice(0, window.limit === void 0 ? void 0 : Math.max(0, window.limit)).map(copyMessage))),
319
+ producer: Effect.fn("Memory.producer")((id, producerId) => owner.access((state) => Option.fromUndefinedOr(state.entries.get(id)?.producers.get(producerId)).pipe(Option.map((value) => ({
320
+ epoch: value.epoch,
321
+ lastSeq: value.lastSeq
322
+ }))))),
323
+ mutate: Effect.fn("Memory.mutate")(function* (mutation) {
324
+ const ids = mutation.operations.map((operation) => Predicate.isTagged(operation, "Create") ? operation.record.id : operation.streamId);
325
+ if (ids.length === 0 || new Set(ids).size !== ids.length || !chain && ids.length > 1) return yield* Effect.die(/* @__PURE__ */ new Error("Mutation requires distinct streams within atomicScope"));
326
+ return yield* Effect.gen(function* () {
327
+ const result = yield* owner.access((state) => commit(state, mutation));
328
+ if (Predicate.isTagged(result, "MutationRejected")) return yield* result;
329
+ const { outcome, changed } = result;
330
+ if (changed.size > 0) yield* owner.changed;
331
+ return outcome;
332
+ }).pipe(owner.withTransaction, Effect.uninterruptible);
333
+ }),
334
+ changes: (id) => changes(committed, bus, id, chain, interval),
335
+ nextExpiry: owner.access((state) => Option.fromUndefinedOr(state.deadlines[0]).pipe(Option.map((deadline) => ({ ...deadline }))))
336
+ });
337
+ return Context.make(Storage, attachOwner(storage, ownerOf(owner.boundary))).pipe(Context.add(CommitBoundary, owner.boundary), Context.add(OwnerRecords, owner.records));
338
+ }));
339
+ //#endregion
340
+ export { CommitBoundary as n, layer as t };