@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.
package/dist/nats.js ADDED
@@ -0,0 +1,712 @@
1
+ import { createHash } from "node:crypto";
2
+ import { connect, credsAuthenticator, nkeyAuthenticator, } from "@nats-io/transport-node";
3
+ import { DeliverPolicy, JetStreamApiCodes, JetStreamApiError, StorageType, jetstream, jetstreamManager, } from "@nats-io/jetstream";
4
+ import { Kvm } from "@nats-io/kv";
5
+ import { Clock, Effect, Layer, Stream } from "effect";
6
+ import { DurableStreamBackend, DurableStreamBadRequestError, DurableStreamNotFoundError, DurableStreamPreconditionFailedError, DurableStreamRangeNotSatisfiableError, getCommandName, isCommandHeaders, makeKeelDurableStreamingLive, recordByteLength as byteLengthOf, toDurableStreamError, } from "./durable-stream.js";
7
+ const sanitizeNatsToken = (raw, maxLen = 32) => {
8
+ const clean = raw
9
+ .toLowerCase()
10
+ .replace(/[^a-z0-9_-]+/g, "_")
11
+ .replace(/^_+|_+$/g, "");
12
+ return (clean || "default").slice(0, maxLen);
13
+ };
14
+ const hashKey = (key) => createHash("sha256").update(key).digest("hex").slice(0, 16);
15
+ const encodeKvKey = (streamKey) => Buffer.from(streamKey, "utf8").toString("base64url");
16
+ const isStreamNotFoundErr = (err) => {
17
+ if (err instanceof JetStreamApiError) {
18
+ return (err.apiError()?.err_code === JetStreamApiCodes.StreamNotFound ||
19
+ err.code === 404);
20
+ }
21
+ const code = err?.api_error?.err_code ?? err?.code;
22
+ return code === JetStreamApiCodes.StreamNotFound || code === 404;
23
+ };
24
+ const isWrongLastSequenceErr = (err) => {
25
+ if (err instanceof JetStreamApiError) {
26
+ return (err.apiError()?.err_code === JetStreamApiCodes.StreamWrongLastSequence);
27
+ }
28
+ return (err?.api_error?.err_code ===
29
+ JetStreamApiCodes.StreamWrongLastSequence);
30
+ };
31
+ const retentionToMaxAgeNanos = (basinConfig) => {
32
+ const policy = basinConfig?.default_stream_config?.retention_policy;
33
+ if (!policy || "infinite" in policy)
34
+ return 0;
35
+ return Math.max(1, Math.floor(policy.age)) * 1_000_000_000;
36
+ };
37
+ const decodeWireEnvelope = (data, jsSeq, fallbackTimestamp) => {
38
+ const text = Buffer.from(data).toString("utf8");
39
+ try {
40
+ const parsed = JSON.parse(text);
41
+ return {
42
+ seq_num: jsSeq - 1,
43
+ timestamp: typeof parsed.timestamp === "number"
44
+ ? parsed.timestamp
45
+ : fallbackTimestamp,
46
+ body: typeof parsed.body === "string" ? parsed.body : "",
47
+ ...(parsed.headers && parsed.headers.length > 0
48
+ ? { headers: parsed.headers }
49
+ : {}),
50
+ };
51
+ }
52
+ catch {
53
+ return {
54
+ seq_num: jsSeq - 1,
55
+ timestamp: fallbackTimestamp,
56
+ body: text,
57
+ };
58
+ }
59
+ };
60
+ const makeNatsBackend = (js, jsm, kvm, config) => {
61
+ const streamPrefix = sanitizeNatsToken(config.streamPrefix ?? "keel_ds", 20);
62
+ const subjectPrefix = (config.subjectPrefix ?? "keel.ds").replace(/[^a-zA-Z0-9._-]+/g, "");
63
+ const kvPrefix = sanitizeNatsToken(config.kvPrefix ?? "keel_ds_meta", 24);
64
+ const replicas = config.replicas ?? 1;
65
+ const storage = config.storage === "memory" ? StorageType.Memory : StorageType.File;
66
+ const basinConfigs = new Map();
67
+ const kvCache = new Map();
68
+ const streamLocks = new Map();
69
+ const withStreamLock = async (lockKey, fn) => {
70
+ const prev = streamLocks.get(lockKey) ?? Promise.resolve();
71
+ let release;
72
+ const next = new Promise((r) => {
73
+ release = r;
74
+ });
75
+ const chain = prev.then(() => next);
76
+ streamLocks.set(lockKey, chain);
77
+ await prev;
78
+ try {
79
+ return await fn();
80
+ }
81
+ finally {
82
+ release();
83
+ if (streamLocks.get(lockKey) === chain) {
84
+ streamLocks.delete(lockKey);
85
+ }
86
+ }
87
+ };
88
+ const getKvBucketName = (basin) => `${kvPrefix}_${sanitizeNatsToken(basin, 32)}`;
89
+ const getJsStreamName = (basin, streamKey) => `${streamPrefix}_${sanitizeNatsToken(basin, 24)}_${hashKey(streamKey)}`;
90
+ const getJsSubject = (basin, streamKey) => `${subjectPrefix}.${sanitizeNatsToken(basin, 24)}.${hashKey(streamKey)}`;
91
+ const getOrCreateBasinKv = async (basin) => {
92
+ const cached = kvCache.get(basin);
93
+ if (cached)
94
+ return cached;
95
+ const bucket = getKvBucketName(basin);
96
+ const kv = await kvm.create(bucket, {
97
+ replicas,
98
+ storage,
99
+ });
100
+ kvCache.set(basin, kv);
101
+ return kv;
102
+ };
103
+ const readStreamMeta = async (kv, streamKey) => {
104
+ const entry = await kv.get(encodeKvKey(streamKey));
105
+ if (!entry || entry.operation !== "PUT" || entry.value.length === 0) {
106
+ return undefined;
107
+ }
108
+ return JSON.parse(Buffer.from(entry.value).toString("utf8"));
109
+ };
110
+ const writeStreamMeta = async (kv, streamKey, meta) => {
111
+ await kv.put(encodeKvKey(streamKey), Buffer.from(JSON.stringify(meta), "utf8"));
112
+ };
113
+ const ensurePhysicalStream = async (basin, streamKey, autoCreate) => {
114
+ const kv = await getOrCreateBasinKv(basin);
115
+ const existing = await readStreamMeta(kv, streamKey);
116
+ const jsStream = existing?.jsStream ?? getJsStreamName(basin, streamKey);
117
+ const subject = existing?.subject ?? getJsSubject(basin, streamKey);
118
+ if (existing) {
119
+ // Verify physical stream still exists (e.g. if deleted externally)
120
+ try {
121
+ await jsm.streams.info(jsStream);
122
+ return { kv, meta: existing };
123
+ }
124
+ catch (err) {
125
+ if (!isStreamNotFoundErr(err))
126
+ throw err;
127
+ if (!autoCreate)
128
+ return undefined;
129
+ }
130
+ }
131
+ else if (!autoCreate) {
132
+ return undefined;
133
+ }
134
+ const basinCfg = basinConfigs.get(basin);
135
+ const maxAge = retentionToMaxAgeNanos(basinCfg);
136
+ try {
137
+ await jsm.streams.add({
138
+ name: jsStream,
139
+ subjects: [subject],
140
+ storage,
141
+ num_replicas: replicas,
142
+ allow_direct: true,
143
+ ...(maxAge > 0 ? { max_age: maxAge } : {}),
144
+ ...(config.maxBytes !== undefined ? { max_bytes: config.maxBytes } : {}),
145
+ ...(config.maxMsgs !== undefined ? { max_msgs: config.maxMsgs } : {}),
146
+ });
147
+ }
148
+ catch (err) {
149
+ // Handle race where stream was concurrently created
150
+ try {
151
+ await jsm.streams.info(jsStream);
152
+ }
153
+ catch {
154
+ throw err;
155
+ }
156
+ }
157
+ const meta = existing ?? {
158
+ name: streamKey,
159
+ jsStream,
160
+ subject,
161
+ createdAt: new Date().toISOString(),
162
+ fenceToken: "",
163
+ trimSeqNum: 0,
164
+ };
165
+ await writeStreamMeta(kv, streamKey, meta);
166
+ return { kv, meta };
167
+ };
168
+ const getStreamInfoSafe = async (jsStream) => {
169
+ try {
170
+ return await jsm.streams.info(jsStream);
171
+ }
172
+ catch (err) {
173
+ if (isStreamNotFoundErr(err))
174
+ return undefined;
175
+ throw err;
176
+ }
177
+ };
178
+ const infoToTail = (info) => {
179
+ const ts = info.state.last_ts ? Date.parse(info.state.last_ts) : 0;
180
+ return {
181
+ seq_num: info.state.last_seq,
182
+ timestamp: Number.isFinite(ts) && info.state.last_seq > 0 ? ts : 0,
183
+ };
184
+ };
185
+ const effectiveTrimSeq = (info, meta) => {
186
+ const fromJs = info.state.first_seq > 0 ? info.state.first_seq - 1 : 0;
187
+ return Math.max(meta.trimSeqNum, fromJs);
188
+ };
189
+ const readRangeFromJs = async (jsStream, startSeq, endSeqExclusive, options) => {
190
+ const out = [];
191
+ if (startSeq >= endSeqExclusive)
192
+ return out;
193
+ const maxCount = options?.count ?? 1000;
194
+ let usedBytes = 0;
195
+ // For a single record read (e.g. snapshot tailOffset: 1), direct getMessage is 1 RTT!
196
+ if (endSeqExclusive - startSeq === 1 || maxCount === 1) {
197
+ const msg = await jsm.streams.getMessage(jsStream, { seq: startSeq + 1 });
198
+ if (!msg)
199
+ return out;
200
+ const rec = decodeWireEnvelope(msg.data, msg.seq, msg.time.getTime());
201
+ if (options?.until !== undefined && rec.timestamp >= options.until) {
202
+ return out;
203
+ }
204
+ out.push(rec);
205
+ return out;
206
+ }
207
+ const toFetch = Math.min(endSeqExclusive - startSeq, maxCount);
208
+ const consumer = await js.consumers.get(jsStream, {
209
+ deliver_policy: DeliverPolicy.StartSequence,
210
+ opt_start_seq: startSeq + 1,
211
+ });
212
+ const iter = await consumer.fetch({
213
+ max_messages: toFetch,
214
+ expires: 5000,
215
+ });
216
+ for await (const msg of iter) {
217
+ const rec = decodeWireEnvelope(msg.data, msg.seq, Math.floor(msg.info.timestampNanos / 1_000_000));
218
+ if (rec.seq_num >= endSeqExclusive)
219
+ break;
220
+ if (options?.until !== undefined && rec.timestamp >= options.until)
221
+ break;
222
+ const sz = byteLengthOf(rec);
223
+ if (options?.bytes !== undefined &&
224
+ out.length > 0 &&
225
+ usedBytes + sz > options.bytes) {
226
+ break;
227
+ }
228
+ out.push(rec);
229
+ usedBytes += sz;
230
+ if (out.length >= toFetch)
231
+ break;
232
+ }
233
+ return out;
234
+ };
235
+ return DurableStreamBackend.of({
236
+ ensureBasin: (basin, basinCfg) => Effect.tryPromise({
237
+ try: async () => {
238
+ basinConfigs.set(basin, basinCfg);
239
+ await getOrCreateBasinKv(basin);
240
+ },
241
+ catch: toDurableStreamError(basin, "ensureBasin"),
242
+ }),
243
+ append: (basin, stream, records, options) => Effect.gen(function* () {
244
+ if (records.length === 0) {
245
+ return yield* new DurableStreamBadRequestError({
246
+ code: "empty_append",
247
+ message: "Append batch must contain at least one record",
248
+ });
249
+ }
250
+ const nowMs = yield* Clock.currentTimeMillis;
251
+ const basinCfg = basinConfigs.get(basin);
252
+ const allowCreate = basinCfg?.create_stream_on_append ?? true;
253
+ const tsMode = basinCfg?.default_stream_config?.timestamping?.mode ?? "client-prefer";
254
+ return yield* Effect.tryPromise({
255
+ try: () => withStreamLock(`${basin}\0${stream}`, async () => {
256
+ const resolved = await ensurePhysicalStream(basin, stream, allowCreate);
257
+ if (!resolved) {
258
+ throw new DurableStreamNotFoundError({
259
+ code: "stream_not_found",
260
+ message: `Stream "${stream}" not found in basin "${basin}"`,
261
+ resource: stream,
262
+ });
263
+ }
264
+ const { kv } = resolved;
265
+ let meta = resolved.meta;
266
+ // Re-read latest metadata under lock to validate active fence
267
+ const freshMeta = await readStreamMeta(kv, stream);
268
+ if (freshMeta)
269
+ meta = freshMeta;
270
+ const expectedFence = meta.fenceToken;
271
+ if ((expectedFence !== "" &&
272
+ options?.fencingToken !== expectedFence) ||
273
+ (options?.fencingToken !== undefined &&
274
+ options.fencingToken !== expectedFence)) {
275
+ throw new DurableStreamPreconditionFailedError({
276
+ code: "fencing_token_mismatch",
277
+ message: `Fencing token mismatch on stream "${stream}"`,
278
+ fencing_token_mismatch: expectedFence,
279
+ });
280
+ }
281
+ const preInfo = await jsm.streams.info(meta.jsStream);
282
+ let expectedLastSeq = options?.matchSeqNum !== undefined
283
+ ? options.matchSeqNum
284
+ : preInfo.state.last_seq;
285
+ // Pre-check matchSeqNum against server state before publishing
286
+ if (options?.matchSeqNum !== undefined &&
287
+ preInfo.state.last_seq !== options.matchSeqNum) {
288
+ throw new DurableStreamPreconditionFailedError({
289
+ code: "seq_num_mismatch",
290
+ message: `Expected seq_num=${options.matchSeqNum}, actual=${preInfo.state.last_seq}`,
291
+ seq_num_mismatch: preInfo.state.last_seq,
292
+ });
293
+ }
294
+ let lastTimestamp = infoToTail(preInfo).timestamp;
295
+ let startSeqNum = 0;
296
+ let firstTs = nowMs;
297
+ let lastTs = nowMs;
298
+ let endSeqNum = expectedLastSeq;
299
+ let updatedFence = meta.fenceToken;
300
+ let updatedTrim = meta.trimSeqNum;
301
+ let metaDirty = false;
302
+ for (let i = 0; i < records.length; i++) {
303
+ const input = records[i];
304
+ const rawTs = tsMode === "arrival"
305
+ ? nowMs
306
+ : input.timestamp !== undefined
307
+ ? input.timestamp
308
+ : nowMs;
309
+ const ts = Math.max(lastTimestamp, rawTs);
310
+ if (i === 0)
311
+ firstTs = ts;
312
+ lastTs = ts;
313
+ lastTimestamp = ts;
314
+ const envelope = {
315
+ body: input.body,
316
+ ...(input.headers && input.headers.length > 0
317
+ ? { headers: input.headers }
318
+ : {}),
319
+ timestamp: ts,
320
+ };
321
+ const useCas = i === 0 && options?.matchSeqNum !== undefined;
322
+ let pubAck;
323
+ try {
324
+ pubAck = await js.publish(meta.subject, Buffer.from(JSON.stringify(envelope), "utf8"), useCas
325
+ ? {
326
+ expect: {
327
+ streamName: meta.jsStream,
328
+ lastSequence: expectedLastSeq,
329
+ },
330
+ }
331
+ : { expect: { streamName: meta.jsStream } });
332
+ }
333
+ catch (err) {
334
+ if (isWrongLastSequenceErr(err)) {
335
+ const actualInfo = await jsm.streams.info(meta.jsStream);
336
+ throw new DurableStreamPreconditionFailedError({
337
+ code: "seq_num_mismatch",
338
+ message: `Expected seq_num=${expectedLastSeq}, actual=${actualInfo.state.last_seq}`,
339
+ seq_num_mismatch: actualInfo.state.last_seq,
340
+ });
341
+ }
342
+ throw err;
343
+ }
344
+ if (i === 0)
345
+ startSeqNum = pubAck.seq - 1;
346
+ endSeqNum = pubAck.seq;
347
+ expectedLastSeq = pubAck.seq;
348
+ const cmd = getCommandName(input.headers);
349
+ if (cmd === "fence") {
350
+ updatedFence = input.body ?? "";
351
+ metaDirty = true;
352
+ }
353
+ else if (cmd === "trim") {
354
+ const target = Math.floor(Number(input.body ?? "0"));
355
+ if (Number.isFinite(target) && target > updatedTrim) {
356
+ const clampedTarget = Math.min(target, endSeqNum);
357
+ updatedTrim = clampedTarget;
358
+ metaDirty = true;
359
+ if (clampedTarget > 0) {
360
+ await jsm.streams.purge(meta.jsStream, {
361
+ seq: clampedTarget + 1,
362
+ });
363
+ }
364
+ }
365
+ }
366
+ }
367
+ if (metaDirty) {
368
+ await writeStreamMeta(kv, stream, {
369
+ ...meta,
370
+ fenceToken: updatedFence,
371
+ trimSeqNum: updatedTrim,
372
+ });
373
+ }
374
+ return {
375
+ start: { seq_num: startSeqNum, timestamp: firstTs },
376
+ end: { seq_num: endSeqNum, timestamp: lastTs },
377
+ tail: { seq_num: endSeqNum, timestamp: lastTs },
378
+ };
379
+ }),
380
+ catch: toDurableStreamError(stream, "append"),
381
+ });
382
+ }),
383
+ checkTail: (basin, stream) => Effect.tryPromise({
384
+ try: async () => {
385
+ const basinCfg = basinConfigs.get(basin);
386
+ const allowCreate = basinCfg?.create_stream_on_read ?? true;
387
+ const resolved = await ensurePhysicalStream(basin, stream, allowCreate);
388
+ if (!resolved) {
389
+ throw new DurableStreamNotFoundError({
390
+ code: "stream_not_found",
391
+ message: `Stream "${stream}" not found in basin "${basin}"`,
392
+ resource: stream,
393
+ });
394
+ }
395
+ const info = await jsm.streams.info(resolved.meta.jsStream);
396
+ return infoToTail(info);
397
+ },
398
+ catch: toDurableStreamError(stream, "checkTail"),
399
+ }),
400
+ read: (basin, stream, options) => Effect.tryPromise({
401
+ try: async () => {
402
+ const basinCfg = basinConfigs.get(basin);
403
+ const allowCreate = basinCfg?.create_stream_on_read ?? true;
404
+ const resolved = await ensurePhysicalStream(basin, stream, allowCreate);
405
+ if (!resolved) {
406
+ throw new DurableStreamNotFoundError({
407
+ code: "stream_not_found",
408
+ message: `Stream "${stream}" not found in basin "${basin}"`,
409
+ resource: stream,
410
+ });
411
+ }
412
+ const { meta } = resolved;
413
+ let info = await jsm.streams.info(meta.jsStream);
414
+ let tail = infoToTail(info);
415
+ const trimSeq = effectiveTrimSeq(info, meta);
416
+ let startSeq;
417
+ if (options?.seqNum !== undefined) {
418
+ startSeq = Math.max(0, Math.floor(options.seqNum));
419
+ }
420
+ else if (options?.tailOffset !== undefined) {
421
+ startSeq = Math.max(trimSeq, tail.seq_num - Math.max(0, Math.floor(options.tailOffset)));
422
+ }
423
+ else if (options?.timestamp !== undefined) {
424
+ // Find first message >= timestamp via Ordered Consumer by start time
425
+ const consumer = await js.consumers.get(meta.jsStream, {
426
+ deliver_policy: DeliverPolicy.StartTime,
427
+ opt_start_time: new Date(options.timestamp).toISOString(),
428
+ });
429
+ const iter = await consumer.fetch({ max_messages: 1, expires: 200 });
430
+ let foundSeq = tail.seq_num;
431
+ for await (const msg of iter) {
432
+ foundSeq = msg.seq - 1;
433
+ break;
434
+ }
435
+ startSeq = Math.max(trimSeq, foundSeq);
436
+ }
437
+ else {
438
+ startSeq = trimSeq;
439
+ }
440
+ if (startSeq < trimSeq) {
441
+ if (options?.clamp) {
442
+ startSeq = trimSeq;
443
+ }
444
+ else {
445
+ throw new DurableStreamRangeNotSatisfiableError({
446
+ code: "range_not_satisfiable",
447
+ message: `Requested seq_num=${startSeq} is below trim point ${trimSeq}`,
448
+ tail,
449
+ trim_seq_num: trimSeq,
450
+ });
451
+ }
452
+ }
453
+ if (startSeq > tail.seq_num) {
454
+ if (options?.clamp) {
455
+ startSeq = tail.seq_num;
456
+ }
457
+ else {
458
+ throw new DurableStreamRangeNotSatisfiableError({
459
+ code: "range_not_satisfiable",
460
+ message: `Requested seq_num=${startSeq} is beyond tail ${tail.seq_num}`,
461
+ tail,
462
+ trim_seq_num: trimSeq,
463
+ });
464
+ }
465
+ }
466
+ // Long-poll when at tail and `wait > 0`
467
+ if (startSeq >= tail.seq_num && options?.wait && options.wait > 0) {
468
+ const consumer = await js.consumers.get(meta.jsStream, {
469
+ deliver_policy: DeliverPolicy.StartSequence,
470
+ opt_start_seq: startSeq + 1,
471
+ });
472
+ const waitMs = Math.min(60, options.wait) * 1000;
473
+ const maxMessages = options.count ?? 100;
474
+ const records = [];
475
+ let usedBytes = 0;
476
+ const iter = await consumer.fetch({
477
+ max_messages: maxMessages,
478
+ expires: waitMs,
479
+ });
480
+ for await (const msg of iter) {
481
+ const rec = decodeWireEnvelope(msg.data, msg.seq, Math.floor(msg.info.timestampNanos / 1_000_000));
482
+ if (options.until !== undefined && rec.timestamp >= options.until) {
483
+ break;
484
+ }
485
+ const sz = byteLengthOf(rec);
486
+ if (options.bytes !== undefined &&
487
+ records.length > 0 &&
488
+ usedBytes + sz > options.bytes) {
489
+ break;
490
+ }
491
+ records.push(rec);
492
+ usedBytes += sz;
493
+ break; // return promptly once newly appended batch arrives
494
+ }
495
+ info = await jsm.streams.info(meta.jsStream);
496
+ tail = infoToTail(info);
497
+ return { records, tail };
498
+ }
499
+ if (startSeq >= tail.seq_num) {
500
+ return { records: [], tail };
501
+ }
502
+ const records = await readRangeFromJs(meta.jsStream, startSeq, tail.seq_num, options);
503
+ return { records, tail };
504
+ },
505
+ catch: toDurableStreamError(stream, "read"),
506
+ }),
507
+ tail: (basin, stream, options) => Stream.unwrap(Effect.tryPromise({
508
+ try: async () => {
509
+ const basinCfg = basinConfigs.get(basin);
510
+ const allowCreate = basinCfg?.create_stream_on_read ?? true;
511
+ const resolved = await ensurePhysicalStream(basin, stream, allowCreate);
512
+ if (!resolved) {
513
+ throw new DurableStreamNotFoundError({
514
+ code: "stream_not_found",
515
+ message: `Stream "${stream}" not found in basin "${basin}"`,
516
+ resource: stream,
517
+ });
518
+ }
519
+ const { meta } = resolved;
520
+ const info = await jsm.streams.info(meta.jsStream);
521
+ const tail = infoToTail(info);
522
+ const trimSeq = effectiveTrimSeq(info, meta);
523
+ let startSeq;
524
+ if (options?.seqNum !== undefined) {
525
+ startSeq = Math.max(0, Math.floor(options.seqNum));
526
+ }
527
+ else if (options?.tailOffset !== undefined) {
528
+ startSeq = Math.max(trimSeq, tail.seq_num - Math.max(0, Math.floor(options.tailOffset)));
529
+ }
530
+ else {
531
+ startSeq = trimSeq;
532
+ }
533
+ if (startSeq < trimSeq) {
534
+ if (options?.clamp)
535
+ startSeq = trimSeq;
536
+ else {
537
+ throw new DurableStreamRangeNotSatisfiableError({
538
+ code: "range_not_satisfiable",
539
+ message: `Requested seq_num=${startSeq} is below trim point ${trimSeq}`,
540
+ tail,
541
+ trim_seq_num: trimSeq,
542
+ });
543
+ }
544
+ }
545
+ if (startSeq > tail.seq_num) {
546
+ if (options?.clamp)
547
+ startSeq = tail.seq_num;
548
+ else {
549
+ throw new DurableStreamRangeNotSatisfiableError({
550
+ code: "range_not_satisfiable",
551
+ message: `Requested seq_num=${startSeq} is beyond tail ${tail.seq_num}`,
552
+ tail,
553
+ trim_seq_num: trimSeq,
554
+ });
555
+ }
556
+ }
557
+ const maxCount = options?.count;
558
+ const maxBytes = options?.bytes;
559
+ const until = options?.until;
560
+ const useTimestampStart = options?.seqNum === undefined &&
561
+ options?.tailOffset === undefined &&
562
+ options?.timestamp !== undefined;
563
+ return Stream.fromAsyncIterable((async function* () {
564
+ const consumer = await js.consumers.get(meta.jsStream, useTimestampStart
565
+ ? {
566
+ deliver_policy: DeliverPolicy.StartTime,
567
+ opt_start_time: new Date(options.timestamp).toISOString(),
568
+ }
569
+ : {
570
+ deliver_policy: DeliverPolicy.StartSequence,
571
+ opt_start_seq: Math.max(1, startSeq + 1),
572
+ });
573
+ const messages = await consumer.consume({
574
+ max_messages: 64,
575
+ expires: 15_000,
576
+ });
577
+ let emittedCount = 0;
578
+ let emittedBytes = 0;
579
+ try {
580
+ for await (const msg of messages) {
581
+ const rec = decodeWireEnvelope(msg.data, msg.seq, Math.floor(msg.info.timestampNanos / 1_000_000));
582
+ if (until !== undefined && rec.timestamp >= until)
583
+ break;
584
+ const isCmd = isCommandHeaders(rec.headers);
585
+ if (!isCmd) {
586
+ const sz = byteLengthOf(rec);
587
+ if (maxBytes !== undefined &&
588
+ emittedCount > 0 &&
589
+ emittedBytes + sz > maxBytes) {
590
+ break;
591
+ }
592
+ emittedCount++;
593
+ emittedBytes += sz;
594
+ }
595
+ yield {
596
+ records: [rec],
597
+ tail: {
598
+ seq_num: Math.max(tail.seq_num, rec.seq_num + 1),
599
+ timestamp: rec.timestamp,
600
+ },
601
+ };
602
+ if (maxCount !== undefined && emittedCount >= maxCount) {
603
+ break;
604
+ }
605
+ if (maxBytes !== undefined && emittedBytes >= maxBytes) {
606
+ break;
607
+ }
608
+ }
609
+ }
610
+ finally {
611
+ await messages.close().catch(() => { });
612
+ }
613
+ })(), toDurableStreamError(stream, "tail"));
614
+ },
615
+ catch: toDurableStreamError(stream, "tail"),
616
+ })),
617
+ listStreams: (basin, options) => Effect.tryPromise({
618
+ try: async () => {
619
+ const kv = await getOrCreateBasinKv(basin);
620
+ const prefix = options?.prefix ?? "";
621
+ const startAfter = options?.startAfter;
622
+ const limit = options?.limit ?? 1000;
623
+ const items = [];
624
+ const keyIter = await kv.keys();
625
+ for await (const k of keyIter) {
626
+ const entry = await kv.get(k);
627
+ if (!entry || entry.operation !== "PUT" || entry.value.length === 0) {
628
+ continue;
629
+ }
630
+ const meta = JSON.parse(Buffer.from(entry.value).toString("utf8"));
631
+ if (prefix && !meta.name.startsWith(prefix))
632
+ continue;
633
+ if (startAfter !== undefined && meta.name <= startAfter)
634
+ continue;
635
+ items.push({ name: meta.name, createdAt: meta.createdAt });
636
+ }
637
+ items.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
638
+ const page = items.slice(0, limit);
639
+ return {
640
+ streams: page,
641
+ hasMore: items.length > limit,
642
+ };
643
+ },
644
+ catch: toDurableStreamError(basin, "listStreams"),
645
+ }),
646
+ deleteStream: (basin, stream) => Effect.tryPromise({
647
+ try: () => withStreamLock(`${basin}\0${stream}`, async () => {
648
+ const kv = await getOrCreateBasinKv(basin);
649
+ const meta = await readStreamMeta(kv, stream);
650
+ const jsStream = meta?.jsStream ?? getJsStreamName(basin, stream);
651
+ const info = await getStreamInfoSafe(jsStream);
652
+ if (info) {
653
+ await jsm.streams.delete(jsStream);
654
+ }
655
+ await kv.purge(encodeKvKey(stream)).catch(() => { });
656
+ }),
657
+ catch: toDurableStreamError(stream, "deleteStream"),
658
+ }),
659
+ });
660
+ };
661
+ const openNatsConnection = async (config) => {
662
+ const servers = Array.isArray(config.servers)
663
+ ? [...config.servers]
664
+ : [config.servers];
665
+ const opts = {
666
+ ...config.connectionOptions,
667
+ servers,
668
+ name: config.name ?? "keel-durable-stream",
669
+ ...(config.token !== undefined ? { token: config.token } : {}),
670
+ ...(config.user !== undefined ? { user: config.user } : {}),
671
+ ...(config.pass !== undefined ? { pass: config.pass } : {}),
672
+ };
673
+ if (config.creds !== undefined) {
674
+ const bytes = typeof config.creds === "string"
675
+ ? Buffer.from(config.creds, "utf8")
676
+ : config.creds;
677
+ opts.authenticator = credsAuthenticator(bytes);
678
+ }
679
+ else if (config.nkeySeed !== undefined) {
680
+ const bytes = typeof config.nkeySeed === "string"
681
+ ? Buffer.from(config.nkeySeed, "utf8")
682
+ : config.nkeySeed;
683
+ opts.authenticator = nkeyAuthenticator(bytes);
684
+ }
685
+ return await connect(opts);
686
+ };
687
+ /**
688
+ * Scoped `DurableStreamBackend` Layer backed by **NATS JetStream** + **NATS KV**.
689
+ *
690
+ * - 1 JetStream stream per `(basin, streamKey)` → exact 0-based `seq_num` & native
691
+ * `expect.lastSequence` CAS (`412` on conflict)
692
+ * - Per-basin NATS KV bucket → leader fencing (`fenceStream` / `fencingToken`) & `listStreams`
693
+ * - Native `jsm.streams.purge` → `trimStream` (`416` / `clamp`)
694
+ * - JetStream Ordered Consumer → zero-gap replay-to-live `tailStream` & `?wait` long-poll
695
+ * - Automatically drains & closes the NATS connection when the Effect `Scope` exits.
696
+ */
697
+ export const DurableStreamNatsLive = (config) => Layer.effect(DurableStreamBackend, Effect.acquireRelease(Effect.tryPromise({
698
+ try: async () => {
699
+ const nc = await openNatsConnection(config);
700
+ const js = jetstream(nc);
701
+ const jsm = await jetstreamManager(nc);
702
+ const kvm = new Kvm(js);
703
+ return { nc, js, jsm, kvm };
704
+ },
705
+ catch: toDurableStreamError("nats", "connect"),
706
+ }), ({ nc }) => Effect.promise(() => nc.isClosed() ? Promise.resolve() : nc.drain().catch(() => nc.close()))).pipe(Effect.map(({ js, jsm, kvm }) => makeNatsBackend(js, jsm, kvm, config))));
707
+ /**
708
+ * One-line streaming layer providing `DurableStreamBackend`, `EventBus`,
709
+ * and `EventStore` over **NATS JetStream**.
710
+ */
711
+ export const KeelNatsStreamingLive = (config) => makeKeelDurableStreamingLive(DurableStreamNatsLive(config), config);
712
+ //# sourceMappingURL=nats.js.map