@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,656 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
+ import { A as StreamsReader, C as ProducerGap, D as StreamGone, E as StreamClosed, F as isValid, I as next, J as ProducerState, K as Offset, M as Storage, N as ZERO_OFFSET, O as StreamNotFound, P as compare, Q as StreamId, S as OffsetMismatch, T as StreamBusy, X as StoredMessage, Y as RecordPatch, _ as InvalidAppendRequest, b as InvalidReadRequest, et as StreamRecord, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, j as StreamsWriter, m as AppendConflict, n as bind, p as CreateResult, q as ProducerId, v as InvalidEpochSeq, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest } from "./streamsy-OjRubIPC.js";
3
+ import { r as attachStorage } from "./owner-BQzMpfC1.js";
4
+ import { t as generateCursor } from "./cursor-generator-CGz1TO_N.js";
5
+ import { Clock, Context, Data, Effect, Layer, Match, Option, Predicate, Random, Schema, Stream } from "effect";
6
+ //#region src/storage/mutation.ts
7
+ const ProducerPrecondition = Schema.Struct({
8
+ producerId: ProducerId,
9
+ expected: Schema.Option(ProducerState),
10
+ next: ProducerState
11
+ });
12
+ const Operation = Schema.Union([
13
+ Schema.TaggedStruct("Create", {
14
+ record: StreamRecord,
15
+ initialMessages: Schema.Array(StoredMessage),
16
+ forkSource: Schema.optionalKey(Schema.Struct({
17
+ id: StreamId,
18
+ liveAtOffset: Offset
19
+ }))
20
+ }),
21
+ Schema.TaggedStruct("Append", {
22
+ streamId: StreamId,
23
+ messages: Schema.Array(StoredMessage),
24
+ patch: RecordPatch,
25
+ expectedOffset: Schema.optionalKey(Offset),
26
+ expectedClosed: Schema.optionalKey(Schema.Boolean),
27
+ producer: Schema.optionalKey(ProducerPrecondition)
28
+ }),
29
+ Schema.TaggedStruct("Delete", {
30
+ streamId: StreamId,
31
+ reason: Schema.Literals(["delete", "expiry"]),
32
+ expectedExpiresAtMs: Schema.optionalKey(Schema.Finite)
33
+ })
34
+ ]);
35
+ const Mutation = Schema.Struct({ operations: Schema.NonEmptyArray(Operation) });
36
+ const OperationResult = Schema.Union([
37
+ Schema.TaggedStruct("Created", { record: StreamRecord }),
38
+ Schema.TaggedStruct("Appended", { record: StreamRecord }),
39
+ Schema.TaggedStruct("Purged", { record: StreamRecord }),
40
+ Schema.TaggedStruct("SoftDeleted", { record: StreamRecord })
41
+ ]);
42
+ /** The success channel of a storage mutation contains only applied operation results. */
43
+ const MutationApplied = Schema.TaggedStruct("Applied", { results: Schema.NonEmptyArray(OperationResult) });
44
+ var MutationRejected = class extends Schema.TaggedError()("MutationRejected", {
45
+ index: Schema.Finite,
46
+ reason: Schema.Literals([
47
+ "offset",
48
+ "closed",
49
+ "producer",
50
+ "exists",
51
+ "not-found",
52
+ "gone",
53
+ "fork-source-gone",
54
+ "expiry-mismatch"
55
+ ]),
56
+ record: Schema.Option(StreamRecord)
57
+ }) {};
58
+ /**
59
+ * Constructors and matchers for the storage values above. They build plain
60
+ * objects and do not validate; storage decodes at its own boundary.
61
+ */
62
+ const Operations = Data.taggedEnum();
63
+ const OperationResults = Data.taggedEnum();
64
+ const Mutations = Data.taggedEnum();
65
+ //#endregion
66
+ //#region src/policy/content-type-matcher.ts
67
+ /**
68
+ * Content type normalization and matching for the durable streams protocol.
69
+ *
70
+ * Responsibilities:
71
+ *
72
+ * - `normalizeContentType` lowercases, strips RFC 7231 parameters (everything
73
+ * after the first `;`), and trims surrounding whitespace.
74
+ * - `contentTypeMatches` compares two content types by equality of their
75
+ * normalized forms.
76
+ *
77
+ * Used by `AppendService` for append content-type conflicts, by
78
+ * `CreateStreamService` via `configMatches` for idempotent create checks, and
79
+ * by `ForkPlanBuilder` for fork content-type compatibility.
80
+ */
81
+ function normalizeContentType(ct) {
82
+ return (ct.toLowerCase().split(";")[0] ?? "").trim();
83
+ }
84
+ function contentTypeMatches(expected, actual) {
85
+ return normalizeContentType(expected) === normalizeContentType(actual);
86
+ }
87
+ //#endregion
88
+ //#region src/policy/create-config-matcher.ts
89
+ function configMatches(existing, options) {
90
+ const contentType = options.contentType ?? existing.config.contentType ?? "application/octet-stream";
91
+ if (!contentTypeMatches(existing.config.contentType, contentType)) return false;
92
+ if ((options.forkedFrom ?? void 0) !== existing.lifecycle.forkedFrom) return false;
93
+ if (options.forkOffset !== void 0 && options.forkOffset !== existing.lifecycle.forkOffset) return false;
94
+ if ((options.forkSubOffset ?? 0) !== (existing.lifecycle.forkSubOffset ?? 0)) return false;
95
+ const inheritedForkExpiry = options.forkedFrom && options.ttlSeconds === void 0 && options.expiresAt === void 0;
96
+ if (existing.config.ttlSeconds !== options.ttlSeconds && !inheritedForkExpiry) return false;
97
+ if (existing.config.expiresAt !== options.expiresAt && !inheritedForkExpiry) return false;
98
+ return existing.lifecycle.closed === (options.closed === true);
99
+ }
100
+ //#endregion
101
+ //#region src/policy/expiry-policy.ts
102
+ /** Pure rules ported from ExpiryPolicy; touch and expiry execution belong to the protocol. */
103
+ function computeExpiresAtMs(config, now) {
104
+ if (config.ttlSeconds !== void 0) return now + config.ttlSeconds * 1e3;
105
+ if (config.expiresAt) return Date.parse(config.expiresAt);
106
+ }
107
+ function isExpired(record, now) {
108
+ const at = record.lifecycle.expiresAtMs;
109
+ return at !== void 0 && at <= now;
110
+ }
111
+ //#endregion
112
+ //#region src/policy/message-framer.ts
113
+ /**
114
+ * Body framing for the durable streams protocol.
115
+ *
116
+ * Responsibilities:
117
+ *
118
+ * - Non-JSON content types pass the original bytes through as a single
119
+ * message.
120
+ * - JSON content types are decoded and re-encoded:
121
+ * - JSON object input becomes one canonical `JSON.stringify(parsed)` message.
122
+ * - JSON array input produces one message per item.
123
+ * - Empty JSON array produces zero messages.
124
+ * - The JSON branch is selected by `contentType.toLowerCase().startsWith("application/json")`,
125
+ * without parameter stripping.
126
+ * - Invalid JSON propagates the underlying `JSON.parse` error.
127
+ *
128
+ * Used by `AppendService`, `CreateStreamService`, and `ForkPlanBuilder` before
129
+ * incoming request bodies are persisted as stored messages.
130
+ */
131
+ function frameMessages(data, contentType) {
132
+ if (!contentType.toLowerCase().startsWith("application/json")) return [data];
133
+ const parsed = JSON.parse(new TextDecoder().decode(data));
134
+ if (Array.isArray(parsed)) return parsed.length === 0 ? [] : parsed.map((item) => new TextEncoder().encode(JSON.stringify(item)));
135
+ return [new TextEncoder().encode(JSON.stringify(parsed))];
136
+ }
137
+ //#endregion
138
+ //#region src/policy/fork-plan-builder.ts
139
+ /** Fork-side validation and plan building. */
140
+ const ForkBuildResult = Data.taggedEnum();
141
+ const ForkPrefix = Data.taggedEnum();
142
+ function resolveForkExpiry(opts, source) {
143
+ if (opts.ttlSeconds !== void 0) return { ttlSeconds: opts.ttlSeconds };
144
+ if (opts.expiresAt) return { expiresAt: opts.expiresAt };
145
+ if (source.config.ttlSeconds !== void 0) return { ttlSeconds: source.config.ttlSeconds };
146
+ if (source.config.expiresAt) return { expiresAt: source.config.expiresAt };
147
+ return {};
148
+ }
149
+ var ForkPlanBuilder = class {
150
+ deps;
151
+ constructor(deps) {
152
+ this.deps = deps;
153
+ }
154
+ build(targetId, sourcePath, source, options, sourceTail) {
155
+ if (!source) return ForkBuildResult.Rejected({ error: new ForkSourceNotFound({
156
+ id: targetId,
157
+ source: sourcePath
158
+ }) });
159
+ if (source.lifecycle.softDeleted) return ForkBuildResult.Rejected({ error: new CreateConflict({
160
+ id: targetId,
161
+ reason: "fork-source-soft-deleted",
162
+ message: `Source stream is soft-deleted: ${sourcePath}`
163
+ }) });
164
+ const forkOffset = options.forkOffset ?? source.currentOffset;
165
+ if (!isValid(forkOffset)) return ForkBuildResult.Rejected({ error: new InvalidForkRequest({
166
+ id: targetId,
167
+ message: "Invalid Stream-Fork-Offset format"
168
+ }) });
169
+ if (compare(forkOffset, ZERO_OFFSET) < 0 || compare(forkOffset, source.currentOffset) > 0) return ForkBuildResult.Rejected({ error: new InvalidForkRequest({
170
+ id: targetId,
171
+ message: "Stream-Fork-Offset exceeds source tail"
172
+ }) });
173
+ let contentType = options.contentType;
174
+ if (!contentType || contentType.trim() === "") contentType = source.config.contentType;
175
+ else if (!contentTypeMatches(contentType, source.config.contentType)) return ForkBuildResult.Rejected({ error: new CreateConflict({
176
+ id: targetId,
177
+ reason: "fork-content-type",
178
+ message: "Fork Content-Type does not match source"
179
+ }) });
180
+ const subOffset = options.forkSubOffset;
181
+ const prefix = this.materializePrefix(subOffset, contentType, sourceTail);
182
+ if (ForkPrefix.$is("Invalid")(prefix)) return ForkBuildResult.Rejected({ error: new InvalidForkRequest({
183
+ id: targetId,
184
+ message: prefix.errorMessage
185
+ }) });
186
+ const expiry = resolveForkExpiry(options, source);
187
+ const fork = {
188
+ forkedFrom: sourcePath,
189
+ forkOffset: Offset.make(forkOffset)
190
+ };
191
+ if (subOffset !== void 0 && subOffset > 0) fork.forkSubOffset = subOffset;
192
+ const baseRecord = this.deps.newRecord(targetId, contentType, {
193
+ ...options,
194
+ ...expiry
195
+ }, fork);
196
+ const initialMessages = this.initialMessages(prefix.messages, options.initialData, contentType, baseRecord.currentOffset);
197
+ const child = this.withInitialTail(baseRecord, initialMessages);
198
+ const plan = Operations.Create({
199
+ record: child,
200
+ initialMessages,
201
+ forkSource: {
202
+ id: sourcePath,
203
+ liveAtOffset: Offset.make(forkOffset)
204
+ }
205
+ });
206
+ return ForkBuildResult.Fork({
207
+ plan,
208
+ toResult: (record) => CreateResult.Created({
209
+ nextOffset: record.currentOffset,
210
+ contentType,
211
+ closed: record.lifecycle.closed
212
+ })
213
+ });
214
+ }
215
+ /**
216
+ * Materialize the partial-message prefix addressed by `forkSubOffset` from the
217
+ * source messages that follow `forkOffset`. `0`/absent yields no prefix. For
218
+ * JSON the sub-offset counts whole flattened messages; for binary/text it
219
+ * counts bytes within the single next source message. Overshoot or an empty
220
+ * source is a 400.
221
+ */
222
+ materializePrefix(subOffset, contentType, sourceTail) {
223
+ if (subOffset === void 0 || subOffset === 0) return ForkPrefix.Prefix({ messages: [] });
224
+ const tail = sourceTail ?? [];
225
+ if (contentType.toLowerCase().startsWith("application/json")) {
226
+ if (subOffset > tail.length) return ForkPrefix.Invalid({ errorMessage: "Stream-Fork-Sub-Offset exceeds source message count" });
227
+ return ForkPrefix.Prefix({ messages: tail.slice(0, subOffset).map((m) => m.data) });
228
+ }
229
+ const first = tail[0];
230
+ if (!first) return ForkPrefix.Invalid({ errorMessage: "Stream-Fork-Sub-Offset has no source message to fork" });
231
+ if (subOffset > first.data.byteLength) return ForkPrefix.Invalid({ errorMessage: "Stream-Fork-Sub-Offset exceeds source message length" });
232
+ return ForkPrefix.Prefix({ messages: [first.data.subarray(0, subOffset)] });
233
+ }
234
+ initialMessages(prefix, initialData, contentType, previousOffset) {
235
+ const framed = [...prefix, ...initialData ? frameMessages(initialData, contentType) : []];
236
+ let offset = previousOffset;
237
+ const now = this.deps.clock.now();
238
+ return framed.map((data) => {
239
+ offset = next(offset);
240
+ return {
241
+ data,
242
+ offset,
243
+ timestamp: now
244
+ };
245
+ });
246
+ }
247
+ withInitialTail(record, initialMessages) {
248
+ const lastMessage = initialMessages[initialMessages.length - 1];
249
+ return {
250
+ id: record.id,
251
+ config: record.config,
252
+ lifecycle: record.lifecycle,
253
+ currentOffset: lastMessage?.offset ?? record.currentOffset
254
+ };
255
+ }
256
+ };
257
+ //#endregion
258
+ //#region src/protocol/expiry.ts
259
+ const expireIfNeeded = Effect.fn("Protocol.expireIfNeeded")(function* (storage, id) {
260
+ const record = yield* storage.record(id);
261
+ const now = yield* Clock.currentTimeMillis;
262
+ if (Option.isSome(record) && !record.value.lifecycle.softDeleted && isExpired(record.value, now)) {
263
+ yield* storage.mutate({ operations: [Operations.Delete({
264
+ streamId: id,
265
+ reason: "expiry",
266
+ expectedExpiresAtMs: record.value.lifecycle.expiresAtMs
267
+ })] }).pipe(Effect.uninterruptible, Effect.catchTag("MutationRejected", () => Effect.void));
268
+ return yield* storage.record(id);
269
+ }
270
+ return record;
271
+ });
272
+ const touch = Effect.fn("Protocol.touch")(function* (storage, record) {
273
+ if (record.config.ttlSeconds === void 0) return;
274
+ const now = yield* Clock.currentTimeMillis;
275
+ yield* storage.mutate({ operations: [Operations.Append({
276
+ streamId: record.id,
277
+ messages: [],
278
+ expectedOffset: record.currentOffset,
279
+ patch: { lifecycle: { expiresAtMs: now + record.config.ttlSeconds * 1e3 } }
280
+ })] }).pipe(Effect.uninterruptible, Effect.catchTag("MutationRejected", () => Effect.void));
281
+ });
282
+ /** One host-triggered sweep; the host owns scheduling and cancellation. */
283
+ const expireDue = Effect.fn("Protocol.expireDue")(function* () {
284
+ const storage = yield* Storage;
285
+ const now = yield* Clock.currentTimeMillis;
286
+ while (true) {
287
+ const deadline = yield* storage.nextExpiry;
288
+ if (Option.isNone(deadline) || deadline.value.at > now) return;
289
+ yield* storage.mutate({ operations: [Operations.Delete({
290
+ streamId: deadline.value.streamId,
291
+ reason: "expiry",
292
+ expectedExpiresAtMs: deadline.value.at
293
+ })] }).pipe(Effect.uninterruptible, Effect.catchTag("MutationRejected", () => Effect.void));
294
+ }
295
+ });
296
+ //#endregion
297
+ //#region src/protocol/create.ts
298
+ function newRecord(id, contentType, options, now, fork) {
299
+ const at = computeExpiresAtMs(options, now);
300
+ const config = {
301
+ contentType,
302
+ createdAt: now
303
+ };
304
+ if (options.ttlSeconds !== void 0) config.ttlSeconds = options.ttlSeconds;
305
+ if (options.expiresAt !== void 0) config.expiresAt = options.expiresAt;
306
+ const lifecycle = {
307
+ closed: options.closed === true,
308
+ softDeleted: false,
309
+ ...fork
310
+ };
311
+ if (options.closed) lifecycle.closedAt = now;
312
+ if (at !== void 0) lifecycle.expiresAtMs = at;
313
+ return {
314
+ id,
315
+ currentOffset: fork?.forkOffset ?? ZERO_OFFSET,
316
+ config,
317
+ lifecycle
318
+ };
319
+ }
320
+ const existingResult = Effect.fn("Protocol.existingResult")(function* (record, options) {
321
+ if (record.lifecycle.softDeleted) return yield* new CreateConflict({
322
+ id: record.id,
323
+ reason: "soft-deleted",
324
+ message: "Stream exists with different configuration"
325
+ });
326
+ if (!configMatches(record, options)) return yield* new CreateConflict({
327
+ id: record.id,
328
+ reason: "config-mismatch",
329
+ message: "Stream exists with different configuration"
330
+ });
331
+ return CreateResult.Exists({
332
+ nextOffset: record.currentOffset,
333
+ contentType: record.config.contentType,
334
+ closed: record.lifecycle.closed
335
+ });
336
+ });
337
+ const create = Effect.fn("Protocol.create")(function* (storage, id, options = {}) {
338
+ if (options.forkedFrom !== void 0 && storage.capabilities.fork === "none") return yield* new NotSupported({
339
+ id,
340
+ feature: "fork"
341
+ });
342
+ const existing = yield* expireIfNeeded(storage, id);
343
+ if (Option.isSome(existing)) return yield* existingResult(existing.value, options);
344
+ const now = yield* Clock.currentTimeMillis;
345
+ let plan;
346
+ if (options.forkedFrom !== void 0) {
347
+ const sourceId = StreamId.make(options.forkedFrom);
348
+ const source = yield* expireIfNeeded(storage, sourceId);
349
+ const after = options.forkOffset;
350
+ const tail = options.forkSubOffset && after && isValid(after) ? [...yield* storage.messages(sourceId, { after: Offset.make(after) })] : void 0;
351
+ const built = new ForkPlanBuilder({
352
+ clock: { now: () => now },
353
+ newRecord: (target, type, opts, fork) => newRecord(target, type, opts, now, fork)
354
+ }).build(id, sourceId, Option.getOrNull(source), options, tail);
355
+ if (Predicate.isTagged(built, "Rejected")) return yield* built.error;
356
+ plan = built.plan;
357
+ if (storage.capabilities.fork === "copy") {
358
+ const prefix = yield* storage.messages(sourceId, { until: plan.record.lifecycle.forkOffset });
359
+ plan = Operations.Create({
360
+ record: plan.record,
361
+ initialMessages: [...prefix, ...plan.initialMessages]
362
+ });
363
+ }
364
+ } else {
365
+ const type = options.contentType ?? "application/octet-stream";
366
+ const record = newRecord(id, type, options, now);
367
+ let offset = record.currentOffset;
368
+ const initialMessages = (options.initialData ? frameMessages(options.initialData, type) : []).map((data) => ({
369
+ data,
370
+ offset: offset = next(offset),
371
+ timestamp: now
372
+ }));
373
+ plan = Operations.Create({
374
+ record: {
375
+ id: record.id,
376
+ config: record.config,
377
+ lifecycle: record.lifecycle,
378
+ currentOffset: offset
379
+ },
380
+ initialMessages
381
+ });
382
+ }
383
+ return yield* storage.mutate({ operations: [plan] }).pipe(Effect.uninterruptible, Effect.map((result) => {
384
+ const record = result.results[0].record;
385
+ return CreateResult.Created({
386
+ nextOffset: record.currentOffset,
387
+ contentType: record.config.contentType,
388
+ closed: record.lifecycle.closed
389
+ });
390
+ }), Effect.catchTag("MutationRejected", (rejection) => {
391
+ if (rejection.reason === "exists" && Option.isSome(rejection.record)) return existingResult(rejection.record.value, options);
392
+ if (options.forkedFrom !== void 0 && rejection.reason === "fork-source-gone") return Effect.fail(new ForkSourceNotFound({
393
+ id,
394
+ source: StreamId.make(options.forkedFrom)
395
+ }));
396
+ return Effect.die(/* @__PURE__ */ new Error(`Unexpected create rejection: ${rejection.reason}`));
397
+ }));
398
+ });
399
+ //#endregion
400
+ //#region src/policy/producer-idempotency-service.ts
401
+ /** Pure producer idempotency decisions. */
402
+ const ProducerValidation = Data.taggedEnum();
403
+ function validateProducer(state, epoch, seq) {
404
+ if (!state) return seq === 0 ? ProducerValidation.Accepted({ proposedState: {
405
+ epoch,
406
+ lastSeq: 0
407
+ } }) : ProducerValidation.Gap({
408
+ expectedSeq: 0,
409
+ receivedSeq: seq
410
+ });
411
+ if (epoch < state.epoch) return ProducerValidation.StaleEpoch({ currentEpoch: state.epoch });
412
+ if (epoch > state.epoch) return seq === 0 ? ProducerValidation.Accepted({ proposedState: {
413
+ epoch,
414
+ lastSeq: 0
415
+ } }) : ProducerValidation.InvalidEpochSeq();
416
+ if (seq <= state.lastSeq) return ProducerValidation.Duplicate({
417
+ lastSeq: state.lastSeq,
418
+ epoch: state.epoch
419
+ });
420
+ if (seq === state.lastSeq + 1) return ProducerValidation.Accepted({ proposedState: {
421
+ epoch,
422
+ lastSeq: seq
423
+ } });
424
+ return ProducerValidation.Gap({
425
+ expectedSeq: state.lastSeq + 1,
426
+ receivedSeq: seq
427
+ });
428
+ }
429
+ function rejectionToAppendError(rejection, id) {
430
+ return Match.valueTags(rejection, {
431
+ StaleEpoch: ({ currentEpoch }) => new StaleEpoch({
432
+ id,
433
+ currentEpoch
434
+ }),
435
+ Gap: ({ expectedSeq, receivedSeq }) => new ProducerGap({
436
+ id,
437
+ expectedSeq,
438
+ receivedSeq
439
+ }),
440
+ InvalidEpochSeq: () => new InvalidEpochSeq({ id })
441
+ });
442
+ }
443
+ const append = Effect.fn("Protocol.append")(function* (storage, id, options) {
444
+ for (let attempt = 0; attempt < 64; attempt++) {
445
+ const found = yield* expireIfNeeded(storage, id);
446
+ if (Option.isNone(found)) return yield* new StreamNotFound({ id });
447
+ const record = found.value;
448
+ if (record.lifecycle.softDeleted) return yield* new StreamGone({ id });
449
+ const producer = options.producer;
450
+ const saved = producer ? yield* storage.producer(id, ProducerId.make(producer.producerId)) : Option.none();
451
+ const validation = producer ? validateProducer(Option.getOrUndefined(saved), producer.producerEpoch, producer.producerSeq) : void 0;
452
+ if (validation && Predicate.isTagged(validation, "Duplicate")) return AppendResult.Duplicate({
453
+ offset: record.currentOffset,
454
+ producerEpoch: validation.epoch,
455
+ producerSeq: validation.lastSeq,
456
+ closed: record.lifecycle.closed
457
+ });
458
+ if (validation && !Predicate.isTagged(validation, "Accepted")) return yield* rejectionToAppendError(validation, id);
459
+ const wantClose = options.close === true;
460
+ const closeOnly = wantClose && options.data.byteLength === 0;
461
+ if (options.data.byteLength === 0 && !closeOnly) return yield* new InvalidAppendRequest({
462
+ id,
463
+ message: "Empty append"
464
+ });
465
+ if (closeOnly && record.lifecycle.closed) return AppendResult.Appended({
466
+ offset: record.currentOffset,
467
+ closed: true
468
+ });
469
+ if (record.lifecycle.closed) return yield* new StreamClosed({
470
+ id,
471
+ offset: record.currentOffset
472
+ });
473
+ if (!closeOnly && !contentTypeMatches(record.config.contentType, options.contentType)) return yield* new AppendConflict({
474
+ id,
475
+ message: "Content-Type mismatch"
476
+ });
477
+ if (!closeOnly && options.seq && record.lifecycle.lastSeq && options.seq <= record.lifecycle.lastSeq) return yield* new AppendConflict({
478
+ id,
479
+ message: "Sequence conflict"
480
+ });
481
+ if (options.expectedOffset !== void 0 && options.expectedOffset !== record.currentOffset) return yield* new OffsetMismatch({
482
+ id,
483
+ expected: options.expectedOffset,
484
+ actual: record.currentOffset
485
+ });
486
+ const now = yield* Clock.currentTimeMillis;
487
+ let offset = record.currentOffset;
488
+ const messages = (closeOnly ? [] : frameMessages(options.data, record.config.contentType)).map((data) => ({
489
+ data,
490
+ offset: offset = next(offset),
491
+ timestamp: now
492
+ }));
493
+ if (messages.length === 0 && !closeOnly) return yield* new InvalidAppendRequest({
494
+ id,
495
+ message: "Empty append"
496
+ });
497
+ const lifecycle = {};
498
+ if (options.seq) lifecycle.lastSeq = options.seq;
499
+ if (wantClose) {
500
+ lifecycle.closed = true;
501
+ lifecycle.closedAt = now;
502
+ }
503
+ if (record.config.ttlSeconds !== void 0) lifecycle.expiresAtMs = now + record.config.ttlSeconds * 1e3;
504
+ const accepted = validation && Predicate.isTagged(validation, "Accepted") ? validation : void 0;
505
+ const operation = Operations.Append({
506
+ streamId: id,
507
+ messages,
508
+ patch: {
509
+ currentOffset: offset,
510
+ lifecycle
511
+ },
512
+ expectedOffset: record.currentOffset,
513
+ expectedClosed: false
514
+ });
515
+ const withProducer = producer && accepted ? Operations.Append({
516
+ ...operation,
517
+ producer: {
518
+ producerId: ProducerId.make(producer.producerId),
519
+ expected: saved,
520
+ next: accepted.proposedState
521
+ }
522
+ }) : operation;
523
+ if (yield* storage.mutate({ operations: [withProducer] }).pipe(Effect.uninterruptible, Effect.as(true), Effect.catchTag("MutationRejected", () => Effect.succeed(false)))) return AppendResult.Appended({
524
+ offset,
525
+ closed: wantClose,
526
+ producerEpoch: accepted?.proposedState.epoch,
527
+ producerSeq: accepted?.proposedState.lastSeq
528
+ });
529
+ }
530
+ return yield* new StreamBusy({ id });
531
+ });
532
+ //#endregion
533
+ //#region src/protocol/read.ts
534
+ const head = Effect.fn("Protocol.head")(function* (storage, id) {
535
+ const found = yield* expireIfNeeded(storage, id);
536
+ if (Option.isNone(found)) return yield* new StreamNotFound({ id });
537
+ const record = found.value;
538
+ if (record.lifecycle.softDeleted) return yield* new StreamGone({ id });
539
+ return {
540
+ contentType: record.config.contentType,
541
+ nextOffset: record.currentOffset,
542
+ ttlSeconds: record.config.ttlSeconds,
543
+ expiresAt: record.config.expiresAt,
544
+ closed: record.lifecycle.closed
545
+ };
546
+ });
547
+ const validateOffset = (id, offset) => offset === void 0 || offset === "-1" || offset === "now" || isValid(offset) ? Effect.void : Effect.fail(new InvalidReadRequest({
548
+ id,
549
+ message: "Invalid offset format"
550
+ }));
551
+ const readRecord = Effect.fn("Protocol.readRecord")(function* (storage, record, options, limit) {
552
+ const from = options.offset === "now" ? record.currentOffset : options.offset;
553
+ const normalized = !from || from === "-1" ? void 0 : from;
554
+ const after = normalized === void 0 ? void 0 : Offset.make(normalized);
555
+ yield* touch(storage, record);
556
+ const messages = yield* storage.messages(record.id, {
557
+ after,
558
+ limit
559
+ });
560
+ const nextOffset = messages.at(-1)?.offset ?? record.currentOffset;
561
+ const upToDate = nextOffset === record.currentOffset;
562
+ return {
563
+ contentType: record.config.contentType,
564
+ messages: messages.map((message) => ({ data: message.data })),
565
+ nextOffset,
566
+ upToDate,
567
+ closed: record.lifecycle.closed && upToDate
568
+ };
569
+ });
570
+ const read = Effect.fn("Protocol.read")(function* (storage, id, options = {}, readLimit = 1e3) {
571
+ yield* validateOffset(id, options.offset);
572
+ const found = yield* expireIfNeeded(storage, id);
573
+ if (Option.isNone(found)) return yield* new StreamNotFound({ id });
574
+ if (found.value.lifecycle.softDeleted) return yield* new StreamGone({ id });
575
+ return yield* readRecord(storage, found.value, options, readLimit);
576
+ });
577
+ function liveResult(result, record, from) {
578
+ const nextOffset = result.messages.length === 0 && from < record.currentOffset ? from : result.nextOffset;
579
+ return {
580
+ ...result,
581
+ nextOffset,
582
+ upToDate: true,
583
+ closed: record.lifecycle.closed && nextOffset === record.currentOffset
584
+ };
585
+ }
586
+ const readNext = Effect.fn("Protocol.readNext")(function* (storage, id, options, timeoutMs) {
587
+ yield* validateOffset(id, options.offset);
588
+ const found = yield* expireIfNeeded(storage, id);
589
+ if (Option.isNone(found)) return yield* new StreamNotFound({ id });
590
+ const record = found.value;
591
+ if (record.lifecycle.softDeleted) return yield* new StreamGone({ id });
592
+ const from = options.offset === "now" ? record.currentOffset : isValid(options.offset) ? options.offset : ZERO_OFFSET;
593
+ const initial = yield* readRecord(storage, record, { offset: from });
594
+ const cursor = Effect.gen(function* () {
595
+ const now = yield* Clock.currentTimeMillis;
596
+ const random = yield* Random.next;
597
+ return generateCursor({ now: () => now }, options.cursor, () => random);
598
+ });
599
+ if (initial.messages.length > 0 || record.lifecycle.closed) return {
600
+ ...initial,
601
+ upToDate: true,
602
+ timedOut: initial.messages.length === 0,
603
+ cursor: yield* cursor
604
+ };
605
+ const waited = yield* storage.changes(id).pipe(Stream.filter((value) => !value.present || value.currentOffset !== record.currentOffset || value.closed !== record.lifecycle.closed || value.softDeleted !== record.lifecycle.softDeleted), Stream.take(1), Stream.runCollect, Effect.timeoutOption(timeoutMs));
606
+ const latest = yield* expireIfNeeded(storage, id);
607
+ if (Option.isNone(latest)) return yield* new StreamNotFound({ id });
608
+ if (latest.value.lifecycle.softDeleted) return yield* new StreamGone({ id });
609
+ const result = yield* readRecord(storage, latest.value, { offset: from });
610
+ return {
611
+ ...liveResult(result, latest.value, from),
612
+ timedOut: result.messages.length === 0 && Option.isNone(waited),
613
+ cursor: yield* cursor
614
+ };
615
+ });
616
+ //#endregion
617
+ //#region src/protocol/layer.ts
618
+ var layer_exports = /* @__PURE__ */ __exportAll({
619
+ bind: () => bind,
620
+ expireDue: () => expireDue,
621
+ layer: () => layer
622
+ });
623
+ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
624
+ const storage = yield* Storage;
625
+ const timeout = options.longPollTimeoutMs ?? 3e4;
626
+ if (!Number.isFinite(timeout) || timeout <= 0) return yield* Effect.die(/* @__PURE__ */ new RangeError("longPollTimeoutMs must be positive"));
627
+ const readLimit = options.readLimit ?? 1e3;
628
+ if (!Number.isSafeInteger(readLimit) || readLimit <= 0) return yield* Effect.die(/* @__PURE__ */ new RangeError("readLimit must be a positive safe integer"));
629
+ const reader = StreamsReader.of({
630
+ head: (id) => head(storage, id),
631
+ read: (id, opts) => read(storage, id, opts, readLimit),
632
+ readNext: (id, opts) => readNext(storage, id, opts, timeout)
633
+ });
634
+ const writer = StreamsWriter.of({
635
+ create: (id, opts) => create(storage, id, opts),
636
+ fork: (id, source, opts) => create(storage, id, {
637
+ ...opts,
638
+ forkedFrom: source
639
+ }),
640
+ append: (id, opts) => append(storage, id, opts),
641
+ remove: Effect.fn("Protocol.remove")(function* (id) {
642
+ yield* expireIfNeeded(storage, id);
643
+ yield* storage.mutate({ operations: [Operations.Delete({
644
+ streamId: id,
645
+ reason: "delete"
646
+ })] }).pipe(Effect.uninterruptible, Effect.catchTag("MutationRejected", (rejection) => {
647
+ if (rejection.reason === "not-found") return Effect.fail(new StreamNotFound({ id }));
648
+ if (rejection.reason === "gone") return Effect.fail(new StreamGone({ id }));
649
+ return Effect.die(/* @__PURE__ */ new Error(`Unexpected delete rejection: ${rejection.reason}`));
650
+ }));
651
+ })
652
+ });
653
+ return Context.make(StreamsReader, attachStorage(reader, storage)).pipe(Context.add(StreamsWriter, attachStorage(writer, storage)));
654
+ }));
655
+ //#endregion
656
+ export { MutationRejected as a, OperationResult as c, ProducerPrecondition as d, MutationApplied as i, OperationResults as l, layer_exports as n, Mutations as o, Mutation as r, Operation as s, layer as t, Operations as u };
@@ -0,0 +1,36 @@
1
+ import { Context, Data, Effect, Predicate } from "effect";
2
+ //#region 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
+ //#endregion
36
+ export { isForeignOwner as a, checkWriteOwner as i, attachOwner as n, ownerOf as o, attachStorage as r, storageOf as s, CurrentOwner as t };