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