@chimp-labs/keel-streams 0.0.0-stage → 0.1.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,1042 @@
1
+ import { Clock, Context, Duration, Effect, Layer, Option, Schema, Semaphore, Stream, } from "effect";
2
+ import { CurrentTenant, EventBus, EventStore, EventTransportError, KeelBindSym, KeelDefaultLayerSym, KeelEnsureSym, KeelErrorMetaSym, KeelInfraSym, KeelKindSym, KeelMetaSym, KeelTenantLifecycleSym, TenantContextMissingError, matchSubject, } from "@chimp-labs/keel";
3
+ export const recordByteLength = (rec) => {
4
+ let bytes = rec.body ? Buffer.byteLength(rec.body, "utf8") : 0;
5
+ if (rec.headers) {
6
+ for (const [k, v] of rec.headers) {
7
+ bytes += Buffer.byteLength(k, "utf8") + Buffer.byteLength(v, "utf8");
8
+ }
9
+ }
10
+ return bytes;
11
+ };
12
+ const byteLengthOf = recordByteLength;
13
+ // =============================================================================
14
+ // Tagged Errors
15
+ // =============================================================================
16
+ export class DurableStreamError extends Schema.TaggedError()("DurableStreamError", {
17
+ stream: Schema.String,
18
+ operation: Schema.String,
19
+ message: Schema.String,
20
+ cause: Schema.optional(Schema.Unknown),
21
+ }) {
22
+ static [KeelErrorMetaSym] = {
23
+ httpStatus: 500,
24
+ category: "internal",
25
+ retryable: true,
26
+ };
27
+ }
28
+ export class DurableStreamSchemaError extends Schema.TaggedError()("DurableStreamSchemaError", {
29
+ stream: Schema.String,
30
+ direction: Schema.Literals(["encode", "decode"]),
31
+ message: Schema.String,
32
+ cause: Schema.optional(Schema.Unknown),
33
+ }) {
34
+ static [KeelErrorMetaSym] = {
35
+ httpStatus: 400,
36
+ category: "invalid",
37
+ retryable: false,
38
+ };
39
+ }
40
+ export class DurableStreamBadRequestError extends Schema.TaggedError()("DurableStreamBadRequestError", {
41
+ code: Schema.String,
42
+ message: Schema.String,
43
+ }) {
44
+ static [KeelErrorMetaSym] = {
45
+ httpStatus: 400,
46
+ category: "invalid",
47
+ retryable: false,
48
+ };
49
+ }
50
+ export class DurableStreamForbiddenError extends Schema.TaggedError()("DurableStreamForbiddenError", {
51
+ code: Schema.String,
52
+ message: Schema.String,
53
+ }) {
54
+ static [KeelErrorMetaSym] = {
55
+ httpStatus: 403,
56
+ category: "forbidden",
57
+ retryable: false,
58
+ };
59
+ }
60
+ export class DurableStreamNotFoundError extends Schema.TaggedError()("DurableStreamNotFoundError", {
61
+ code: Schema.String,
62
+ message: Schema.String,
63
+ resource: Schema.String,
64
+ }) {
65
+ static [KeelErrorMetaSym] = {
66
+ httpStatus: 404,
67
+ category: "not_found",
68
+ retryable: false,
69
+ };
70
+ }
71
+ export class DurableStreamConflictError extends Schema.TaggedError()("DurableStreamConflictError", {
72
+ code: Schema.String,
73
+ message: Schema.String,
74
+ resource: Schema.String,
75
+ }) {
76
+ static [KeelErrorMetaSym] = {
77
+ httpStatus: 409,
78
+ category: "conflict",
79
+ retryable: false,
80
+ };
81
+ }
82
+ export class DurableStreamPreconditionFailedError extends Schema.TaggedError()("DurableStreamPreconditionFailedError", {
83
+ code: Schema.Literals(["seq_num_mismatch", "fencing_token_mismatch"]),
84
+ message: Schema.String,
85
+ seq_num_mismatch: Schema.optional(Schema.Number),
86
+ fencing_token_mismatch: Schema.optional(Schema.String),
87
+ }) {
88
+ static [KeelErrorMetaSym] = {
89
+ httpStatus: 412,
90
+ category: "conflict",
91
+ retryable: false,
92
+ };
93
+ }
94
+ export class DurableStreamRangeNotSatisfiableError extends Schema.TaggedError()("DurableStreamRangeNotSatisfiableError", {
95
+ code: Schema.String,
96
+ message: Schema.String,
97
+ tail: Schema.Struct({
98
+ seq_num: Schema.Number,
99
+ timestamp: Schema.Number,
100
+ }),
101
+ trim_seq_num: Schema.optional(Schema.Number),
102
+ }) {
103
+ static [KeelErrorMetaSym] = {
104
+ httpStatus: 416,
105
+ category: "invalid",
106
+ retryable: false,
107
+ };
108
+ }
109
+ export const isDurableStreamFailure = (err) => err instanceof DurableStreamError ||
110
+ err instanceof DurableStreamSchemaError ||
111
+ err instanceof DurableStreamBadRequestError ||
112
+ err instanceof DurableStreamForbiddenError ||
113
+ err instanceof DurableStreamNotFoundError ||
114
+ err instanceof DurableStreamConflictError ||
115
+ err instanceof DurableStreamPreconditionFailedError ||
116
+ err instanceof DurableStreamRangeNotSatisfiableError ||
117
+ err instanceof TenantContextMissingError;
118
+ export const toDurableStreamError = (stream, operation) => (err) => isDurableStreamFailure(err)
119
+ ? err
120
+ : new DurableStreamError({
121
+ stream,
122
+ operation,
123
+ message: err instanceof Error ? err.message : String(err),
124
+ cause: err,
125
+ });
126
+ export class DurableStreamBackend extends Context.Service()("@chimp-labs/keel/DurableStreamBackend") {
127
+ }
128
+ // =============================================================================
129
+ // Shared Command & Basin Helpers
130
+ // =============================================================================
131
+ const MAX_BATCH_SIZE = 1000;
132
+ export const sanitizeBasinName = (name) => {
133
+ const clean = name
134
+ .toLowerCase()
135
+ .replace(/[^a-z0-9-]+/g, "-")
136
+ .replace(/^-+|-+$/g, "");
137
+ if (clean.length >= 3)
138
+ return clean.slice(0, 48);
139
+ return `keel-${clean || "stream"}`.slice(0, 48);
140
+ };
141
+ export const isCommandHeaders = (headers) => headers !== undefined && headers.length === 1 && headers[0][0] === "";
142
+ export const getCommandName = (headers) => (isCommandHeaders(headers) ? headers[0][1] : undefined);
143
+ const toRetentionPolicy = (input, defaultPolicy = { age: 604800 }) => {
144
+ if (input === "infinite")
145
+ return { infinite: {} };
146
+ if (input === undefined)
147
+ return defaultPolicy;
148
+ const ms = Duration.toMillis(Duration.fromInputUnsafe(input));
149
+ return { age: Math.max(1, Math.floor(ms / 1000)) };
150
+ };
151
+ const makeBasinConfig = (retention, storageClass) => ({
152
+ create_stream_on_append: true,
153
+ create_stream_on_read: true,
154
+ default_stream_config: {
155
+ storage_class: storageClass,
156
+ retention_policy: retention,
157
+ timestamping: { mode: "client-prefer", uncapped: false },
158
+ delete_on_empty: { min_age_secs: 0 },
159
+ },
160
+ });
161
+ export const makeDurableStreamMemoryBackend = () => {
162
+ const basins = new Map();
163
+ const getOrCreateBasin = (basin, config) => {
164
+ let b = basins.get(basin);
165
+ if (!b) {
166
+ b = {
167
+ config: config ?? {
168
+ create_stream_on_append: true,
169
+ create_stream_on_read: true,
170
+ },
171
+ streams: new Map(),
172
+ };
173
+ basins.set(basin, b);
174
+ }
175
+ else if (config) {
176
+ b.config = config;
177
+ }
178
+ return b;
179
+ };
180
+ const getOrCreateStream = (basin, stream, autoCreate) => {
181
+ const b = getOrCreateBasin(basin);
182
+ let s = b.streams.get(stream);
183
+ if (!s && autoCreate) {
184
+ s = {
185
+ name: stream,
186
+ createdAt: new Date().toISOString(),
187
+ records: [],
188
+ nextSeqNum: 0,
189
+ lastTimestamp: 0,
190
+ trimSeqNum: 0,
191
+ fencingToken: "",
192
+ deleted: false,
193
+ waiters: new Set(),
194
+ };
195
+ b.streams.set(stream, s);
196
+ }
197
+ return s;
198
+ };
199
+ const notifyWaiters = (s) => {
200
+ if (s.waiters.size === 0)
201
+ return;
202
+ const snapshot = [...s.waiters];
203
+ s.waiters.clear();
204
+ for (const wake of snapshot)
205
+ wake();
206
+ };
207
+ const resolveStartSeq = (s, options) => {
208
+ if (options?.seqNum !== undefined) {
209
+ return Math.max(0, Math.floor(options.seqNum));
210
+ }
211
+ if (options?.tailOffset !== undefined) {
212
+ return Math.max(s.trimSeqNum, s.nextSeqNum - Math.max(0, Math.floor(options.tailOffset)));
213
+ }
214
+ if (options?.timestamp !== undefined) {
215
+ const found = s.records.find((r) => r.timestamp >= options.timestamp);
216
+ return found ? found.seq_num : s.nextSeqNum;
217
+ }
218
+ return s.trimSeqNum;
219
+ };
220
+ const sliceRecords = (s, startSeq, options) => {
221
+ const out = [];
222
+ let usedBytes = 0;
223
+ for (const rec of s.records) {
224
+ if (rec.seq_num < startSeq)
225
+ continue;
226
+ if (options?.until !== undefined && rec.timestamp >= options.until)
227
+ break;
228
+ const sz = byteLengthOf(rec);
229
+ if (options?.bytes !== undefined &&
230
+ out.length > 0 &&
231
+ usedBytes + sz > options.bytes) {
232
+ break;
233
+ }
234
+ out.push(rec);
235
+ usedBytes += sz;
236
+ if (options?.count !== undefined && out.length >= options.count)
237
+ break;
238
+ }
239
+ return out;
240
+ };
241
+ const waitForUpdate = (s, timeoutMs) => new Promise((resolve) => {
242
+ let settled = false;
243
+ let timer;
244
+ const done = () => {
245
+ if (settled)
246
+ return;
247
+ settled = true;
248
+ s.waiters.delete(done);
249
+ if (timer !== undefined)
250
+ clearTimeout(timer);
251
+ resolve();
252
+ };
253
+ s.waiters.add(done);
254
+ if (timeoutMs !== undefined && timeoutMs >= 0) {
255
+ timer = setTimeout(done, timeoutMs);
256
+ if (typeof timer === "object" && "unref" in timer) {
257
+ timer.unref();
258
+ }
259
+ }
260
+ });
261
+ return DurableStreamBackend.of({
262
+ ensureBasin: (basin, config) => Effect.sync(() => {
263
+ getOrCreateBasin(basin, config);
264
+ }),
265
+ append: (basin, stream, records, options) => Effect.gen(function* () {
266
+ if (records.length === 0) {
267
+ return yield* new DurableStreamBadRequestError({
268
+ code: "empty_append",
269
+ message: "Append batch must contain at least one record",
270
+ });
271
+ }
272
+ const b = getOrCreateBasin(basin);
273
+ const allowCreate = b.config.create_stream_on_append ?? true;
274
+ const s = getOrCreateStream(basin, stream, allowCreate);
275
+ if (!s) {
276
+ return yield* new DurableStreamNotFoundError({
277
+ code: "stream_not_found",
278
+ message: `Stream "${stream}" not found in basin "${basin}"`,
279
+ resource: stream,
280
+ });
281
+ }
282
+ if (options?.matchSeqNum !== undefined &&
283
+ s.nextSeqNum !== options.matchSeqNum) {
284
+ return yield* new DurableStreamPreconditionFailedError({
285
+ code: "seq_num_mismatch",
286
+ message: `Expected seq_num=${options.matchSeqNum}, actual=${s.nextSeqNum}`,
287
+ seq_num_mismatch: s.nextSeqNum,
288
+ });
289
+ }
290
+ const expectedFence = s.fencingToken;
291
+ if ((expectedFence !== "" && options?.fencingToken !== expectedFence) ||
292
+ (options?.fencingToken !== undefined &&
293
+ options.fencingToken !== expectedFence)) {
294
+ return yield* new DurableStreamPreconditionFailedError({
295
+ code: "fencing_token_mismatch",
296
+ message: `Fencing token mismatch on stream "${stream}"`,
297
+ fencing_token_mismatch: expectedFence,
298
+ });
299
+ }
300
+ const now = yield* Clock.currentTimeMillis;
301
+ const tsMode = b.config.default_stream_config?.timestamping?.mode ?? "client-prefer";
302
+ const startSeq = s.nextSeqNum;
303
+ let firstTs = now;
304
+ let lastTs = now;
305
+ for (let i = 0; i < records.length; i++) {
306
+ const input = records[i];
307
+ const rawTs = tsMode === "arrival"
308
+ ? now
309
+ : input.timestamp !== undefined
310
+ ? input.timestamp
311
+ : now;
312
+ const ts = Math.max(s.lastTimestamp, rawTs);
313
+ if (i === 0)
314
+ firstTs = ts;
315
+ lastTs = ts;
316
+ s.lastTimestamp = ts;
317
+ const seq = s.nextSeqNum++;
318
+ const stored = {
319
+ seq_num: seq,
320
+ timestamp: ts,
321
+ body: input.body,
322
+ ...(input.headers && input.headers.length > 0
323
+ ? { headers: input.headers.map(([k, v]) => [k, v]) }
324
+ : {}),
325
+ };
326
+ s.records.push(stored);
327
+ const cmd = getCommandName(input.headers);
328
+ if (cmd === "fence") {
329
+ s.fencingToken = input.body ?? "";
330
+ }
331
+ else if (cmd === "trim") {
332
+ const parsed = Number(input.body ?? "0");
333
+ if (Number.isFinite(parsed) && parsed > s.trimSeqNum) {
334
+ s.trimSeqNum = Math.min(Math.floor(parsed), s.nextSeqNum);
335
+ s.records = s.records.filter((r) => r.seq_num >= s.trimSeqNum);
336
+ }
337
+ }
338
+ }
339
+ notifyWaiters(s);
340
+ const tailPos = {
341
+ seq_num: s.nextSeqNum,
342
+ timestamp: lastTs,
343
+ };
344
+ return {
345
+ start: { seq_num: startSeq, timestamp: firstTs },
346
+ end: { seq_num: s.nextSeqNum, timestamp: lastTs },
347
+ tail: tailPos,
348
+ };
349
+ }),
350
+ checkTail: (basin, stream) => Effect.gen(function* () {
351
+ const b = getOrCreateBasin(basin);
352
+ const allowCreate = b.config.create_stream_on_read ?? true;
353
+ const s = getOrCreateStream(basin, stream, allowCreate);
354
+ if (!s) {
355
+ return yield* new DurableStreamNotFoundError({
356
+ code: "stream_not_found",
357
+ message: `Stream "${stream}" not found in basin "${basin}"`,
358
+ resource: stream,
359
+ });
360
+ }
361
+ return {
362
+ seq_num: s.nextSeqNum,
363
+ timestamp: s.lastTimestamp,
364
+ };
365
+ }),
366
+ read: (basin, stream, options) => Effect.gen(function* () {
367
+ const b = getOrCreateBasin(basin);
368
+ const allowCreate = b.config.create_stream_on_read ?? true;
369
+ const s = getOrCreateStream(basin, stream, allowCreate);
370
+ if (!s) {
371
+ return yield* new DurableStreamNotFoundError({
372
+ code: "stream_not_found",
373
+ message: `Stream "${stream}" not found in basin "${basin}"`,
374
+ resource: stream,
375
+ });
376
+ }
377
+ let startSeq = resolveStartSeq(s, options);
378
+ const tail = {
379
+ seq_num: s.nextSeqNum,
380
+ timestamp: s.lastTimestamp,
381
+ };
382
+ if (startSeq < s.trimSeqNum) {
383
+ if (options?.clamp) {
384
+ startSeq = s.trimSeqNum;
385
+ }
386
+ else {
387
+ return yield* new DurableStreamRangeNotSatisfiableError({
388
+ code: "range_not_satisfiable",
389
+ message: `Requested seq_num=${startSeq} is below trim point ${s.trimSeqNum}`,
390
+ tail,
391
+ trim_seq_num: s.trimSeqNum,
392
+ });
393
+ }
394
+ }
395
+ if (startSeq > s.nextSeqNum) {
396
+ if (options?.clamp) {
397
+ startSeq = s.nextSeqNum;
398
+ }
399
+ else {
400
+ return yield* new DurableStreamRangeNotSatisfiableError({
401
+ code: "range_not_satisfiable",
402
+ message: `Requested seq_num=${startSeq} is beyond tail ${s.nextSeqNum}`,
403
+ tail,
404
+ trim_seq_num: s.trimSeqNum,
405
+ });
406
+ }
407
+ }
408
+ if (startSeq >= s.nextSeqNum && options?.wait && options.wait > 0) {
409
+ const deadline = Date.now() + Math.min(60, options.wait) * 1000;
410
+ while (s.nextSeqNum <= startSeq && !s.deleted) {
411
+ const remaining = deadline - Date.now();
412
+ if (remaining <= 0)
413
+ break;
414
+ yield* Effect.promise(() => waitForUpdate(s, remaining));
415
+ }
416
+ }
417
+ const currentTail = {
418
+ seq_num: s.nextSeqNum,
419
+ timestamp: s.lastTimestamp,
420
+ };
421
+ if (startSeq >= s.nextSeqNum && !options?.clamp && !(options?.wait && options.wait > 0)) {
422
+ return {
423
+ records: [],
424
+ tail: currentTail,
425
+ };
426
+ }
427
+ const records = sliceRecords(s, startSeq, options);
428
+ return {
429
+ records,
430
+ tail: currentTail,
431
+ };
432
+ }),
433
+ tail: (basin, stream, options) => Stream.unwrap(Effect.gen(function* () {
434
+ const b = getOrCreateBasin(basin);
435
+ const allowCreate = b.config.create_stream_on_read ?? true;
436
+ const s = getOrCreateStream(basin, stream, allowCreate);
437
+ if (!s) {
438
+ return yield* new DurableStreamNotFoundError({
439
+ code: "stream_not_found",
440
+ message: `Stream "${stream}" not found in basin "${basin}"`,
441
+ resource: stream,
442
+ });
443
+ }
444
+ let cursor = resolveStartSeq(s, options);
445
+ if (cursor < s.trimSeqNum) {
446
+ if (options?.clamp) {
447
+ cursor = s.trimSeqNum;
448
+ }
449
+ else {
450
+ return yield* new DurableStreamRangeNotSatisfiableError({
451
+ code: "range_not_satisfiable",
452
+ message: `Requested seq_num=${cursor} is below trim point ${s.trimSeqNum}`,
453
+ tail: { seq_num: s.nextSeqNum, timestamp: s.lastTimestamp },
454
+ trim_seq_num: s.trimSeqNum,
455
+ });
456
+ }
457
+ }
458
+ if (cursor > s.nextSeqNum) {
459
+ if (options?.clamp) {
460
+ cursor = s.nextSeqNum;
461
+ }
462
+ else {
463
+ return yield* new DurableStreamRangeNotSatisfiableError({
464
+ code: "range_not_satisfiable",
465
+ message: `Requested seq_num=${cursor} is beyond tail ${s.nextSeqNum}`,
466
+ tail: { seq_num: s.nextSeqNum, timestamp: s.lastTimestamp },
467
+ trim_seq_num: s.trimSeqNum,
468
+ });
469
+ }
470
+ }
471
+ const maxCount = options?.count;
472
+ const maxBytes = options?.bytes;
473
+ const until = options?.until;
474
+ return Stream.fromAsyncIterable((async function* () {
475
+ let emittedCount = 0;
476
+ let emittedBytes = 0;
477
+ let activeWake;
478
+ try {
479
+ while (!s.deleted) {
480
+ if (cursor < s.trimSeqNum)
481
+ cursor = s.trimSeqNum;
482
+ const remainingCount = maxCount !== undefined ? maxCount - emittedCount : undefined;
483
+ if (remainingCount !== undefined && remainingCount <= 0)
484
+ break;
485
+ const remainingBytes = maxBytes !== undefined ? maxBytes - emittedBytes : undefined;
486
+ if (remainingBytes !== undefined && remainingBytes <= 0)
487
+ break;
488
+ const batchRecords = sliceRecords(s, cursor, {
489
+ ...(remainingCount !== undefined ? { count: remainingCount } : {}),
490
+ ...(remainingBytes !== undefined ? { bytes: remainingBytes } : {}),
491
+ ...(until !== undefined ? { until } : {}),
492
+ });
493
+ if (batchRecords.length > 0) {
494
+ const lastRec = batchRecords[batchRecords.length - 1];
495
+ cursor = lastRec.seq_num + 1;
496
+ for (const r of batchRecords) {
497
+ if (!isCommandHeaders(r.headers)) {
498
+ emittedCount++;
499
+ emittedBytes += byteLengthOf(r);
500
+ }
501
+ }
502
+ yield {
503
+ records: batchRecords,
504
+ tail: {
505
+ seq_num: s.nextSeqNum,
506
+ timestamp: s.lastTimestamp,
507
+ },
508
+ };
509
+ if ((maxCount !== undefined && emittedCount >= maxCount) ||
510
+ (maxBytes !== undefined && emittedBytes >= maxBytes)) {
511
+ break;
512
+ }
513
+ if (until !== undefined && lastRec.timestamp >= until) {
514
+ break;
515
+ }
516
+ continue;
517
+ }
518
+ if (until !== undefined &&
519
+ s.lastTimestamp >= until &&
520
+ s.nextSeqNum > cursor) {
521
+ break;
522
+ }
523
+ await new Promise((resolve) => {
524
+ activeWake = () => {
525
+ activeWake = undefined;
526
+ resolve();
527
+ };
528
+ s.waiters.add(activeWake);
529
+ });
530
+ }
531
+ }
532
+ finally {
533
+ if (activeWake) {
534
+ s.waiters.delete(activeWake);
535
+ }
536
+ }
537
+ })(), toDurableStreamError(stream, "tail"));
538
+ })),
539
+ listStreams: (basin, options) => Effect.sync(() => {
540
+ const b = basins.get(basin);
541
+ if (!b)
542
+ return { streams: [], hasMore: false };
543
+ const prefix = options?.prefix ?? "";
544
+ const startAfter = options?.startAfter;
545
+ const limit = options?.limit ?? 1000;
546
+ const all = [...b.streams.values()]
547
+ .filter((s) => !s.deleted)
548
+ .filter((s) => (prefix ? s.name.startsWith(prefix) : true))
549
+ .filter((s) => (startAfter !== undefined ? s.name > startAfter : true))
550
+ .sort((a, c) => (a.name < c.name ? -1 : a.name > c.name ? 1 : 0));
551
+ const page = all.slice(0, limit);
552
+ return {
553
+ streams: page.map((s) => ({ name: s.name, createdAt: s.createdAt })),
554
+ hasMore: all.length > limit,
555
+ };
556
+ }),
557
+ deleteStream: (basin, stream) => Effect.sync(() => {
558
+ const b = basins.get(basin);
559
+ if (!b)
560
+ return;
561
+ const s = b.streams.get(stream);
562
+ if (!s)
563
+ return;
564
+ s.deleted = true;
565
+ notifyWaiters(s);
566
+ b.streams.delete(stream);
567
+ }),
568
+ });
569
+ };
570
+ /**
571
+ * Pure in-memory `DurableStreamBackend` Layer (zero external dependencies,
572
+ * zero database/circularity, instant unit & integration tests).
573
+ */
574
+ export const DurableStreamMemoryLive = Layer.effect(DurableStreamBackend, Effect.sync(() => makeDurableStreamMemoryBackend()));
575
+ // =============================================================================
576
+ // Internal Helpers: Key Tenant Scoping & Schema Codec
577
+ // =============================================================================
578
+ const resolveTenantPrefix = (def, operation) => Effect.gen(function* () {
579
+ if (!def.tenantScoped)
580
+ return "";
581
+ const tenantOpt = yield* CurrentTenant;
582
+ if (Option.isNone(tenantOpt)) {
583
+ return yield* new TenantContextMissingError({
584
+ resourceKind: "table",
585
+ resourceName: def.durableStreamName,
586
+ operation,
587
+ message: `DurableStream "${def.durableStreamName}" requires CurrentTenant context for "${operation}"`,
588
+ });
589
+ }
590
+ return `${tenantOpt.value.tenantId}/`;
591
+ });
592
+ const encodeRecordValue = (def, value) => {
593
+ const codec = def.schema;
594
+ return Schema.encodeUnknownEffect(codec)(value).pipe(Effect.map((encoded) => JSON.stringify(encoded)), Effect.mapError((cause) => new DurableStreamSchemaError({
595
+ stream: def.durableStreamName,
596
+ direction: "encode",
597
+ message: `Failed to encode record for DurableStream "${def.durableStreamName}"`,
598
+ cause,
599
+ })));
600
+ };
601
+ const decodeBatchRecords = (def, batch) => Effect.gen(function* () {
602
+ const codec = def.schema;
603
+ const out = [];
604
+ for (const rec of batch.records) {
605
+ if (isCommandHeaders(rec.headers))
606
+ continue;
607
+ const parsedJson = yield* Effect.try({
608
+ try: () => JSON.parse(rec.body ?? "null"),
609
+ catch: (cause) => new DurableStreamSchemaError({
610
+ stream: def.durableStreamName,
611
+ direction: "decode",
612
+ message: `Invalid JSON body at seq_num=${rec.seq_num}`,
613
+ cause,
614
+ }),
615
+ });
616
+ const value = yield* Schema.decodeUnknownEffect(codec)(parsedJson).pipe(Effect.mapError((cause) => new DurableStreamSchemaError({
617
+ stream: def.durableStreamName,
618
+ direction: "decode",
619
+ message: `Schema validation failed at seq_num=${rec.seq_num}`,
620
+ cause,
621
+ })));
622
+ out.push({
623
+ seqNum: rec.seq_num,
624
+ timestamp: rec.timestamp,
625
+ value,
626
+ ...(rec.headers && rec.headers.length > 0 ? { headers: rec.headers } : {}),
627
+ });
628
+ }
629
+ return out;
630
+ });
631
+ // =============================================================================
632
+ // Public Typed Operations
633
+ // =============================================================================
634
+ export const ensureDurableStream = (def) => Effect.gen(function* () {
635
+ const backend = yield* DurableStreamBackend;
636
+ return yield* backend.ensureBasin(def.basinName, def.basinConfig);
637
+ });
638
+ export const appendStream = (def, key, values, options) => Effect.gen(function* () {
639
+ const backend = yield* DurableStreamBackend;
640
+ const prefix = yield* resolveTenantPrefix(def, "appendStream");
641
+ const physicalKey = `${prefix}${key}`;
642
+ const encoded = [];
643
+ for (const v of values) {
644
+ const body = yield* encodeRecordValue(def, v);
645
+ encoded.push({
646
+ body,
647
+ ...(options?.headers ? { headers: options.headers } : {}),
648
+ ...(options?.timestamp !== undefined ? { timestamp: options.timestamp } : {}),
649
+ });
650
+ }
651
+ return yield* backend.append(def.basinName, physicalKey, encoded, {
652
+ ...(options?.matchSeqNum !== undefined
653
+ ? { matchSeqNum: options.matchSeqNum }
654
+ : {}),
655
+ ...(options?.fencingToken !== undefined
656
+ ? { fencingToken: options.fencingToken }
657
+ : {}),
658
+ });
659
+ });
660
+ export const fenceStream = (def, key, fencingToken, options) => Effect.gen(function* () {
661
+ const backend = yield* DurableStreamBackend;
662
+ const prefix = yield* resolveTenantPrefix(def, "fenceStream");
663
+ return yield* backend.append(def.basinName, `${prefix}${key}`, [{ headers: [["", "fence"]], body: fencingToken }], {
664
+ ...(options?.matchSeqNum !== undefined
665
+ ? { matchSeqNum: options.matchSeqNum }
666
+ : {}),
667
+ ...(options?.currentFencingToken !== undefined
668
+ ? { fencingToken: options.currentFencingToken }
669
+ : {}),
670
+ });
671
+ });
672
+ export const trimStream = (def, key, trimSeqNum, options) => Effect.gen(function* () {
673
+ const backend = yield* DurableStreamBackend;
674
+ const prefix = yield* resolveTenantPrefix(def, "trimStream");
675
+ return yield* backend.append(def.basinName, `${prefix}${key}`, [{ headers: [["", "trim"]], body: String(trimSeqNum) }], {
676
+ ...(options?.matchSeqNum !== undefined
677
+ ? { matchSeqNum: options.matchSeqNum }
678
+ : {}),
679
+ ...(options?.fencingToken !== undefined
680
+ ? { fencingToken: options.fencingToken }
681
+ : {}),
682
+ });
683
+ });
684
+ export const checkStreamTail = (def, key) => Effect.gen(function* () {
685
+ const backend = yield* DurableStreamBackend;
686
+ const prefix = yield* resolveTenantPrefix(def, "checkStreamTail");
687
+ return yield* backend.checkTail(def.basinName, `${prefix}${key}`);
688
+ });
689
+ export const readStream = (def, key, options) => Effect.gen(function* () {
690
+ const backend = yield* DurableStreamBackend;
691
+ const prefix = yield* resolveTenantPrefix(def, "readStream");
692
+ const batch = yield* backend.read(def.basinName, `${prefix}${key}`, options);
693
+ const records = yield* decodeBatchRecords(def, batch);
694
+ return {
695
+ records,
696
+ tail: batch.tail ?? { seq_num: 0, timestamp: 0 },
697
+ };
698
+ });
699
+ export const tailStream = (def, key, options) => Stream.unwrap(Effect.gen(function* () {
700
+ const backend = yield* DurableStreamBackend;
701
+ const prefix = yield* resolveTenantPrefix(def, "tailStream");
702
+ return backend.tail(def.basinName, `${prefix}${key}`, options).pipe(Stream.mapEffect((batch) => decodeBatchRecords(def, batch)), Stream.flatMap((records) => Stream.fromIterable(records)));
703
+ }));
704
+ export const listDurableStreams = (def, options) => Effect.gen(function* () {
705
+ const backend = yield* DurableStreamBackend;
706
+ const prefix = yield* resolveTenantPrefix(def, "listDurableStreams");
707
+ const res = yield* backend.listStreams(def.basinName, {
708
+ ...(prefix || options?.prefix
709
+ ? { prefix: `${prefix}${options?.prefix ?? ""}` }
710
+ : {}),
711
+ ...(options?.startAfter !== undefined
712
+ ? { startAfter: `${prefix}${options.startAfter}` }
713
+ : {}),
714
+ ...(options?.limit !== undefined ? { limit: options.limit } : {}),
715
+ });
716
+ return {
717
+ streams: res.streams.map((s) => ({
718
+ key: prefix.length > 0 && s.name.startsWith(prefix)
719
+ ? s.name.slice(prefix.length)
720
+ : s.name,
721
+ createdAt: s.createdAt,
722
+ })),
723
+ hasMore: res.hasMore,
724
+ };
725
+ });
726
+ export const deleteDurableStream = (def, key) => Effect.gen(function* () {
727
+ const backend = yield* DurableStreamBackend;
728
+ const prefix = yield* resolveTenantPrefix(def, "deleteDurableStream");
729
+ return yield* backend.deleteStream(def.basinName, `${prefix}${key}`);
730
+ });
731
+ export const bindDurableStream = (runner, def) => ({
732
+ ensure: () => runner.run(ensureDurableStream(def)),
733
+ append: (key, values, options) => runner.run(appendStream(def, key, values, options)),
734
+ fence: (key, fencingToken, options) => runner.run(fenceStream(def, key, fencingToken, options)),
735
+ trim: (key, trimSeqNum, options) => runner.run(trimStream(def, key, trimSeqNum, options)),
736
+ checkTail: (key) => runner.run(checkStreamTail(def, key)),
737
+ read: (key, options) => runner.run(readStream(def, key, options)),
738
+ tail: (key, options) => runner.stream(tailStream(def, key, options)),
739
+ list: (options) => runner.run(listDurableStreams(def, options)),
740
+ delete: (key) => runner.run(deleteDurableStream(def, key)),
741
+ });
742
+ // =============================================================================
743
+ // Primitive Factory: `DurableStream(name, config)`
744
+ // =============================================================================
745
+ /**
746
+ * Declares a typed, durable, append-only stream primitive with monotonic
747
+ * `seqNum`, optimistic `matchSeqNum` CAS, pessimistic `fencingToken`, `trim`,
748
+ * `?wait` long-polling, live tailing, and optional `CurrentTenant` isolation.
749
+ *
750
+ * Swappable across any `DurableStreamBackend`:
751
+ * - `DurableStreamMemoryLive` (zero-dependency in-memory dev & tests)
752
+ * - `DurableStreamS2Live` (**`s2-lite`** Docker or **s2.dev Cloud**)
753
+ * - `DurableStreamNatsLive` (**NATS JetStream** / Synadia Cloud)
754
+ */
755
+ export function DurableStream(name, config) {
756
+ const basinName = config.basin ?? sanitizeBasinName(name);
757
+ const retentionPolicy = toRetentionPolicy(config.retention);
758
+ const deleteOnEmptySecs = config.deleteOnEmptyAfter
759
+ ? Math.max(1, Math.floor(Duration.toMillis(Duration.fromInputUnsafe(config.deleteOnEmptyAfter)) /
760
+ 1000))
761
+ : 0;
762
+ const basinConfig = {
763
+ create_stream_on_append: true,
764
+ create_stream_on_read: config.createOnRead ?? true,
765
+ default_stream_config: {
766
+ storage_class: config.storageClass ?? "express",
767
+ retention_policy: retentionPolicy,
768
+ timestamping: {
769
+ mode: config.timestamping ?? "client-prefer",
770
+ uncapped: false,
771
+ },
772
+ delete_on_empty: {
773
+ min_age_secs: deleteOnEmptySecs,
774
+ },
775
+ },
776
+ };
777
+ const tenantScoped = Boolean(config.tenantScoped);
778
+ class DurableStreamClass {
779
+ static durableStreamName = name;
780
+ static basinName = basinName;
781
+ static schema = config.schema;
782
+ static basinConfig = basinConfig;
783
+ static tenantScoped = tenantScoped;
784
+ static [KeelKindSym] = "ext:durable-stream";
785
+ static [KeelMetaSym] = {
786
+ kind: "ext:durable-stream",
787
+ name,
788
+ basinName,
789
+ tenantScoped,
790
+ };
791
+ static [KeelInfraSym] = () => ({
792
+ extensions: {
793
+ durableStreams: {
794
+ name,
795
+ basinName,
796
+ tenantScoped,
797
+ storageClass: config.storageClass ?? "express",
798
+ },
799
+ },
800
+ });
801
+ static [KeelDefaultLayerSym] = () => DurableStreamMemoryLive;
802
+ static [KeelEnsureSym] = () => ensureDurableStream(DurableStreamClass);
803
+ static [KeelTenantLifecycleSym] = () => ({
804
+ exportCategory: "durableStreams",
805
+ resourceKey: name,
806
+ exportTenantRecords: (tenantId) => Effect.gen(function* () {
807
+ const maybeBackend = yield* Effect.serviceOption(DurableStreamBackend);
808
+ if (Option.isNone(maybeBackend))
809
+ return [];
810
+ const listed = yield* maybeBackend.value.listStreams(basinName, {
811
+ prefix: `${tenantId}/`,
812
+ });
813
+ const exported = [];
814
+ for (const s of listed.streams) {
815
+ const batch = yield* maybeBackend.value
816
+ .read(basinName, s.name, { clamp: true })
817
+ .pipe(Effect.catch(() => Effect.succeed({ records: [] })));
818
+ exported.push({
819
+ key: s.name.slice(`${tenantId}/`.length),
820
+ records: batch.records,
821
+ });
822
+ }
823
+ return exported;
824
+ }),
825
+ eraseTenantRecords: (tenantId) => Effect.gen(function* () {
826
+ const maybeBackend = yield* Effect.serviceOption(DurableStreamBackend);
827
+ if (Option.isNone(maybeBackend))
828
+ return 0;
829
+ const listed = yield* maybeBackend.value.listStreams(basinName, {
830
+ prefix: `${tenantId}/`,
831
+ });
832
+ let deleted = 0;
833
+ for (const s of listed.streams) {
834
+ yield* maybeBackend.value
835
+ .deleteStream(basinName, s.name)
836
+ .pipe(Effect.ignore);
837
+ deleted++;
838
+ }
839
+ return deleted;
840
+ }),
841
+ });
842
+ static [KeelBindSym] = (runner) => bindDurableStream(runner, DurableStreamClass);
843
+ }
844
+ return DurableStreamClass;
845
+ }
846
+ // =============================================================================
847
+ // Swappable Streaming Layers for `Topic` & `EventStore`
848
+ // =============================================================================
849
+ const makeBasinEnsurer = (backend, basinConfig) => {
850
+ const ensured = new Set();
851
+ const sem = Semaphore.makeUnsafe(1);
852
+ return (basin) => Effect.suspend(() => {
853
+ if (ensured.has(basin))
854
+ return Effect.void;
855
+ return sem.withPermits(1)(Effect.gen(function* () {
856
+ if (ensured.has(basin))
857
+ return;
858
+ yield* backend.ensureBasin(basin, basinConfig);
859
+ ensured.add(basin);
860
+ }));
861
+ });
862
+ };
863
+ const readFiniteRange = (backend, basin, streamKey, startSeqNum, endExclusiveSeqNum, maxRecords) => Effect.gen(function* () {
864
+ if (maxRecords !== undefined && maxRecords <= 0)
865
+ return [];
866
+ let endSeq = endExclusiveSeqNum;
867
+ if (endSeq === undefined) {
868
+ const tail = yield* backend.checkTail(basin, streamKey).pipe(Effect.catch((err) => err instanceof DurableStreamNotFoundError
869
+ ? Effect.succeed({ seq_num: 0, timestamp: 0 })
870
+ : Effect.fail(err)));
871
+ endSeq = tail.seq_num;
872
+ }
873
+ if (startSeqNum >= endSeq)
874
+ return [];
875
+ const collected = [];
876
+ let cursor = startSeqNum;
877
+ while (cursor < endSeq) {
878
+ const remainingRange = endSeq - cursor;
879
+ const remainingLimit = maxRecords !== undefined ? maxRecords - collected.length : undefined;
880
+ if (remainingLimit !== undefined && remainingLimit <= 0)
881
+ break;
882
+ const count = Math.min(MAX_BATCH_SIZE, remainingRange, remainingLimit ?? MAX_BATCH_SIZE);
883
+ const batch = yield* backend
884
+ .read(basin, streamKey, {
885
+ seqNum: cursor,
886
+ count,
887
+ clamp: true,
888
+ })
889
+ .pipe(Effect.catch((err) => err instanceof DurableStreamNotFoundError ||
890
+ err instanceof DurableStreamRangeNotSatisfiableError
891
+ ? Effect.succeed({
892
+ records: [],
893
+ tail: { seq_num: endSeq, timestamp: 0 },
894
+ })
895
+ : Effect.fail(err)));
896
+ if (batch.records.length === 0)
897
+ break;
898
+ let lastSeq = cursor - 1;
899
+ for (const rec of batch.records) {
900
+ lastSeq = rec.seq_num;
901
+ if (rec.seq_num >= endSeq)
902
+ break;
903
+ if (isCommandHeaders(rec.headers))
904
+ continue;
905
+ collected.push(rec);
906
+ if (maxRecords !== undefined && collected.length >= maxRecords)
907
+ break;
908
+ }
909
+ if (lastSeq < cursor)
910
+ break;
911
+ cursor = lastSeq + 1;
912
+ }
913
+ return collected;
914
+ });
915
+ const decodeTopicRecord = (rec, fallbackSubject) => Effect.try({
916
+ try: () => {
917
+ const parsed = JSON.parse(rec.body ?? "{}");
918
+ return {
919
+ subject: parsed.subject,
920
+ sequence: rec.seq_num + 1,
921
+ timestamp: rec.timestamp,
922
+ data: parsed.data,
923
+ ...(parsed.key !== undefined ? { key: parsed.key } : {}),
924
+ ...(parsed.partition !== undefined
925
+ ? { partition: parsed.partition }
926
+ : {}),
927
+ ...(parsed.headers !== undefined ? { headers: parsed.headers } : {}),
928
+ };
929
+ },
930
+ catch: (cause) => new EventTransportError({ subject: fallbackSubject, cause }),
931
+ });
932
+ const encodeTopicEntry = (subject, data, options, timestamp) => {
933
+ const payload = {
934
+ subject,
935
+ data,
936
+ ...(options?.key !== undefined ? { key: options.key } : {}),
937
+ ...(options?.partition !== undefined
938
+ ? { partition: options.partition }
939
+ : {}),
940
+ ...(options?.headers !== undefined ? { headers: options.headers } : {}),
941
+ };
942
+ return {
943
+ body: JSON.stringify(payload),
944
+ timestamp,
945
+ };
946
+ };
947
+ /**
948
+ * Swappable `EventBus | EventStore` (`EventLog`) layer backed by `DurableStreamBackend`.
949
+ *
950
+ * Powers `Topic`, `View` (RYOW), `Projection`, `Policy`, `Outbox`,
951
+ * `EventPipeline`, `EventAggregator`, `EventSource`, and `EventSink` over any
952
+ * `DurableStreamBackend` (`Memory`, `S2 / s2-lite`, or `NATS JetStream`).
953
+ */
954
+ export const TopicDurableStreamLive = (options) => Layer.effectContext(Effect.gen(function* () {
955
+ const backend = yield* DurableStreamBackend;
956
+ const basin = sanitizeBasinName(options?.basin ?? "keel-topics");
957
+ const streamKey = options?.streamKey ?? "_events";
958
+ const basinConfig = makeBasinConfig(toRetentionPolicy(options?.retention, { age: 604800 }), options?.storageClass ?? "express");
959
+ const ensureReady = makeBasinEnsurer(backend, basinConfig);
960
+ const publishEntries = (entries) => Effect.gen(function* () {
961
+ if (entries.length === 0)
962
+ return [];
963
+ yield* ensureReady(basin).pipe(Effect.mapError((cause) => new EventTransportError({
964
+ subject: entries[0].subject,
965
+ cause,
966
+ })));
967
+ const nowMs = yield* Clock.currentTimeMillis;
968
+ const results = [];
969
+ for (let offset = 0; offset < entries.length; offset += MAX_BATCH_SIZE) {
970
+ const chunk = entries.slice(offset, offset + MAX_BATCH_SIZE);
971
+ const rawRecords = chunk.map((e) => encodeTopicEntry(e.subject, e.data, e.options, nowMs));
972
+ const ack = yield* backend
973
+ .append(basin, streamKey, rawRecords)
974
+ .pipe(Effect.mapError((cause) => new EventTransportError({
975
+ subject: chunk[0].subject,
976
+ cause,
977
+ })));
978
+ for (let i = 0; i < chunk.length; i++) {
979
+ const entry = chunk[i];
980
+ results.push({
981
+ subject: entry.subject,
982
+ sequence: ack.start.seq_num + 1 + i,
983
+ timestamp: ack.start.timestamp,
984
+ data: entry.data,
985
+ ...(entry.options?.key !== undefined
986
+ ? { key: entry.options.key }
987
+ : {}),
988
+ ...(entry.options?.partition !== undefined
989
+ ? { partition: entry.options.partition }
990
+ : {}),
991
+ ...(entry.options?.headers !== undefined
992
+ ? { headers: entry.options.headers }
993
+ : {}),
994
+ });
995
+ }
996
+ }
997
+ return results;
998
+ });
999
+ const tailFiltered = (pattern, startSeqNum) => backend
1000
+ .tail(basin, streamKey, { seqNum: startSeqNum, clamp: true })
1001
+ .pipe(Stream.mapError((cause) => new EventTransportError({ subject: pattern, cause })), Stream.flatMap((batch) => Stream.fromIterable(batch.records.filter((r) => !isCommandHeaders(r.headers)))), Stream.mapEffect((rec) => decodeTopicRecord(rec, pattern)), Stream.filter((env) => matchSubject(env.subject, pattern)));
1002
+ const bus = EventBus.of({
1003
+ publish: (subject, data, pubOptions) => publishEntries([
1004
+ {
1005
+ subject,
1006
+ data,
1007
+ ...(pubOptions !== undefined ? { options: pubOptions } : {}),
1008
+ },
1009
+ ]).pipe(Effect.map((arr) => arr[0])),
1010
+ publishBatch: (entries) => publishEntries(entries),
1011
+ subscribe: (pattern) => Stream.unwrap(Effect.gen(function* () {
1012
+ yield* ensureReady(basin).pipe(Effect.mapError((cause) => new EventTransportError({ subject: pattern, cause })));
1013
+ const tail = yield* backend.checkTail(basin, streamKey).pipe(Effect.catch((err) => err instanceof DurableStreamNotFoundError
1014
+ ? Effect.succeed({ seq_num: 0, timestamp: 0 })
1015
+ : Effect.fail(err)), Effect.mapError((cause) => new EventTransportError({ subject: pattern, cause })));
1016
+ return tailFiltered(pattern, tail.seq_num);
1017
+ })),
1018
+ });
1019
+ const store = EventStore.of({
1020
+ read: (pattern, readOptions) => Stream.unwrap(Effect.gen(function* () {
1021
+ yield* ensureReady(basin).pipe(Effect.mapError((cause) => new EventTransportError({ subject: pattern, cause })));
1022
+ const startSeqNum = Math.max(0, Math.floor(readOptions?.after ?? 0));
1023
+ if (readOptions?.live) {
1024
+ return tailFiltered(pattern, startSeqNum);
1025
+ }
1026
+ const records = yield* readFiniteRange(backend, basin, streamKey, startSeqNum).pipe(Effect.mapError((cause) => new EventTransportError({ subject: pattern, cause })));
1027
+ return Stream.fromIterable(records).pipe(Stream.mapEffect((rec) => decodeTopicRecord(rec, pattern)), Stream.filter((env) => matchSubject(env.subject, pattern)));
1028
+ })),
1029
+ });
1030
+ return Context.make(EventBus, bus).pipe(Context.add(EventStore, store));
1031
+ }));
1032
+ /**
1033
+ * Composes `DurableStreamBackend` + `TopicDurableStreamLive` on top of any
1034
+ * provided `DurableStreamBackend` Layer.
1035
+ */
1036
+ export const makeKeelDurableStreamingLive = (backendLayer, options) => TopicDurableStreamLive(options?.topic).pipe(Layer.provideMerge(backendLayer));
1037
+ /**
1038
+ * One-line in-memory DurableStream bundle providing `DurableStreamBackend`,
1039
+ * `EventBus`, and `EventStore` with zero external services.
1040
+ */
1041
+ export const KeelMemoryDurableStreamingLive = (options) => makeKeelDurableStreamingLive(DurableStreamMemoryLive, options);
1042
+ //# sourceMappingURL=durable-stream.js.map