ai-resumable-stream 1.4.0 → 3.0.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,719 @@
1
+ import { GetObjectCommand, HeadObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
2
+ //#region src/adapters/s3-express/client.ts
3
+ /**
4
+ * Raised when an append is rejected because the offset it carried is not the object's
5
+ * current size. Also what a retry of an append that already landed looks like.
6
+ */
7
+ var WriteOffsetMismatchError = class extends Error {
8
+ constructor(key) {
9
+ super(`Append to ${key} did not match the object's current size`);
10
+ this.name = `WriteOffsetMismatchError`;
11
+ }
12
+ };
13
+ /**
14
+ * Raised when a segment has used all of its 10,000 parts.
15
+ */
16
+ var TooManyPartsError = class extends Error {
17
+ constructor(key) {
18
+ super(`Segment ${key} has no parts left`);
19
+ this.name = `TooManyPartsError`;
20
+ }
21
+ };
22
+ function statusOf(error) {
23
+ return error?.$metadata?.httpStatusCode;
24
+ }
25
+ function nameOf(error) {
26
+ return error?.name;
27
+ }
28
+ function isMissing(error) {
29
+ return statusOf(error) === 404 || nameOf(error) === `NoSuchKey` || nameOf(error) === `NotFound`;
30
+ }
31
+ function isUnsatisfiableRange(error) {
32
+ return statusOf(error) === 416 || nameOf(error) === `InvalidRange`;
33
+ }
34
+ /**
35
+ * Records the response's `Date` header, which is S3's own now and the only clock the
36
+ * adapter trusts for deadlines. The SDK does not put it in command output, so it is read
37
+ * from the raw response.
38
+ *
39
+ * The middleware is added to the command rather than to the client, so a caller's client
40
+ * is left exactly as they built it. Only successful responses are read, which is why the
41
+ * adapter falls back to a `HeadObject` when it needs the clock and the range was empty.
42
+ */
43
+ function captureDate(command, sink) {
44
+ command.middlewareStack.add((next) => async (args) => {
45
+ const result = await next(args);
46
+ const headers = result.response?.headers;
47
+ const parsed = headers?.date ? Date.parse(headers.date) : NaN;
48
+ if (!Number.isNaN(parsed)) sink.date = parsed;
49
+ return result;
50
+ }, {
51
+ step: `deserialize`,
52
+ name: `captureResponseDate`
53
+ });
54
+ }
55
+ /**
56
+ * Binds the adapter's S3 calls to a caller-built client and a directory bucket.
57
+ *
58
+ * The bucket must be an S3 Express One Zone directory bucket in an Availability Zone.
59
+ * Appends exist nowhere else, and they are what makes a stream one object instead of
60
+ * thousands.
61
+ */
62
+ function createS3Operations(options) {
63
+ const { client, bucket } = options;
64
+ return {
65
+ async put(key, body) {
66
+ await client.send(new PutObjectCommand({
67
+ Bucket: bucket,
68
+ Key: key,
69
+ Body: body
70
+ }));
71
+ },
72
+ async append(key, offset, body) {
73
+ try {
74
+ await client.send(new PutObjectCommand({
75
+ Bucket: bucket,
76
+ Key: key,
77
+ Body: body,
78
+ WriteOffsetBytes: offset
79
+ }));
80
+ } catch (error) {
81
+ if (nameOf(error) === `InvalidWriteOffset`) throw new WriteOffsetMismatchError(key);
82
+ if (nameOf(error) === `TooManyParts`) throw new TooManyPartsError(key);
83
+ throw error;
84
+ }
85
+ },
86
+ async read(key, offset) {
87
+ const sink = { date: void 0 };
88
+ const command = new GetObjectCommand({
89
+ Bucket: bucket,
90
+ Key: key,
91
+ Range: `bytes=${offset}-`
92
+ });
93
+ captureDate(command, sink);
94
+ try {
95
+ const response = await client.send(command);
96
+ return {
97
+ bytes: await response.Body?.transformToByteArray() ?? /* @__PURE__ */ new Uint8Array(),
98
+ date: sink.date,
99
+ lastModified: response.LastModified?.getTime()
100
+ };
101
+ } catch (error) {
102
+ if (isUnsatisfiableRange(error)) return {
103
+ bytes: /* @__PURE__ */ new Uint8Array(),
104
+ date: void 0,
105
+ lastModified: void 0
106
+ };
107
+ if (isMissing(error)) return void 0;
108
+ throw error;
109
+ }
110
+ },
111
+ async head(key) {
112
+ const sink = { date: void 0 };
113
+ const command = new HeadObjectCommand({
114
+ Bucket: bucket,
115
+ Key: key
116
+ });
117
+ captureDate(command, sink);
118
+ try {
119
+ const response = await client.send(command);
120
+ return {
121
+ size: response.ContentLength ?? 0,
122
+ date: sink.date,
123
+ lastModified: response.LastModified?.getTime()
124
+ };
125
+ } catch (error) {
126
+ if (isMissing(error)) return void 0;
127
+ throw error;
128
+ }
129
+ }
130
+ };
131
+ }
132
+ //#endregion
133
+ //#region src/adapters/s3-express/delay.ts
134
+ /**
135
+ * Sleeps, but gives up as soon as the caller loses interest.
136
+ */
137
+ function delay(ms, signal) {
138
+ if (signal.aborted) return Promise.resolve();
139
+ return new Promise((resolve) => {
140
+ const timer = setTimeout(finish, ms);
141
+ signal.addEventListener(`abort`, finish, { once: true });
142
+ function finish() {
143
+ clearTimeout(timer);
144
+ signal.removeEventListener(`abort`, finish);
145
+ resolve();
146
+ }
147
+ });
148
+ }
149
+ /**
150
+ * The record types a stream log holds. A record is a header line, and for a chunk the
151
+ * exact payload bytes that follow it.
152
+ *
153
+ * V<version>\n the first record of every segment
154
+ * C<byteLength>\n<payload> a chunk
155
+ * B\n the producer is alive but idle
156
+ * E\n the generation ended
157
+ * N<segment key>\n the log continues in another object
158
+ *
159
+ * A chunk is framed by its byte length rather than by a separator, so nothing inside it
160
+ * has to be escaped. The codec already produces JSON, and wrapping that in JSON again
161
+ * costs about 1.4x the bytes and a second parse of every chunk on the way back.
162
+ */
163
+ const RecordType = {
164
+ VERSION: `V`,
165
+ CHUNK: `C`,
166
+ BEAT: `B`,
167
+ END: `E`,
168
+ NEXT: `N`
169
+ };
170
+ /**
171
+ * What a reader should do once it has taken the chunks out of a batch of records.
172
+ */
173
+ const Outcome = {
174
+ MORE: `more`,
175
+ END: `end`,
176
+ NEXT: `next`
177
+ };
178
+ const NEWLINE = 10;
179
+ const encoder$1 = new TextEncoder();
180
+ const decoder$1 = new TextDecoder();
181
+ /**
182
+ * Joins encoded records so a batch of them is written by a single append.
183
+ */
184
+ function joinRecords(parts) {
185
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
186
+ const result = new Uint8Array(total);
187
+ let offset = 0;
188
+ for (const part of parts) {
189
+ result.set(part, offset);
190
+ offset += part.length;
191
+ }
192
+ return result;
193
+ }
194
+ /**
195
+ * Opens a segment. Written when the object is created, so a segment is never empty and a
196
+ * reader always gets bytes, and with them S3's clock, from its very first read.
197
+ */
198
+ function encodeVersion() {
199
+ return encoder$1.encode(`${RecordType.VERSION}1\n`);
200
+ }
201
+ function encodeChunk(data) {
202
+ const payload = encoder$1.encode(data);
203
+ return joinRecords([encoder$1.encode(`${RecordType.CHUNK}${payload.length}\n`), payload]);
204
+ }
205
+ /**
206
+ * A beat carries no payload, but it is still a real record: S3 rejects an append with an
207
+ * empty body.
208
+ */
209
+ function encodeBeat() {
210
+ return encoder$1.encode(`${RecordType.BEAT}\n`);
211
+ }
212
+ /**
213
+ * Written however a generation ends. A stream that failed is reported exactly like one
214
+ * that completed, so the outcome itself is not recorded.
215
+ */
216
+ function encodeEnd() {
217
+ return encoder$1.encode(`${RecordType.END}\n`);
218
+ }
219
+ /**
220
+ * Links a full segment to the one the log continues in. Segments form a chain, and this
221
+ * record is the only thing that holds it together: nothing is ever listed, so a reader
222
+ * finds the next object by being told its key rather than by looking for it.
223
+ */
224
+ function encodeNext(key) {
225
+ return encoder$1.encode(`${RecordType.NEXT}${key}\n`);
226
+ }
227
+ /**
228
+ * Reads whole records from the front of `bytes` and reports how many bytes they used.
229
+ *
230
+ * A trailing record that is not yet complete is left alone and `consumed` stops in front
231
+ * of it, so a reader that starts again from there loses nothing. That matters because AWS
232
+ * does not promise that a reader never sees a partly committed append.
233
+ */
234
+ function decodeRecords(bytes) {
235
+ const records = [];
236
+ let consumed = 0;
237
+ while (consumed < bytes.length) {
238
+ const newline = bytes.indexOf(NEWLINE, consumed);
239
+ if (newline === -1) break;
240
+ const header = decoder$1.decode(bytes.subarray(consumed, newline));
241
+ const rest = header.slice(1);
242
+ if (header[0] === RecordType.CHUNK) {
243
+ const length = Number(rest);
244
+ if (!Number.isInteger(length) || length < 0) throw new Error(`Malformed chunk header in stream log: ${header}`);
245
+ const start = newline + 1;
246
+ const end = start + length;
247
+ /** The payload has not been written in full yet. */
248
+ if (end > bytes.length) break;
249
+ records.push({
250
+ type: RecordType.CHUNK,
251
+ data: decoder$1.decode(bytes.subarray(start, end))
252
+ });
253
+ consumed = end;
254
+ continue;
255
+ }
256
+ if (header[0] === RecordType.VERSION) {
257
+ const version = Number(rest);
258
+ /**
259
+ * Refusing is the point of the marker. A log written by a later version may frame
260
+ * its records differently, and reading it as if it did not would hand the codec
261
+ * nonsense rather than fail.
262
+ */
263
+ if (version !== 1) throw new Error(`Stream log is format ${rest}, which this version cannot read`);
264
+ records.push({
265
+ type: RecordType.VERSION,
266
+ version
267
+ });
268
+ } else if (header[0] === RecordType.BEAT) records.push({ type: RecordType.BEAT });
269
+ else if (header[0] === RecordType.END) records.push({ type: RecordType.END });
270
+ else if (header[0] === RecordType.NEXT) records.push({
271
+ type: RecordType.NEXT,
272
+ key: rest
273
+ });
274
+ else
275
+ /**
276
+ * Nothing can be recovered from here: the offset of every later record is unknown,
277
+ * so the log has to be abandoned rather than silently truncated.
278
+ */
279
+ throw new Error(`Unknown record type in stream log: ${header[0]}`);
280
+ consumed = newline + 1;
281
+ }
282
+ return {
283
+ records,
284
+ consumed
285
+ };
286
+ }
287
+ /**
288
+ * Drains records into `chunks` and reports what the reader should do next. A link to the
289
+ * next segment, like an end record, is always the last thing written to an object, so
290
+ * nothing is skipped by stopping at one.
291
+ */
292
+ function collectChunks(records, chunks) {
293
+ for (const record of records) {
294
+ if (record.type === RecordType.CHUNK) {
295
+ chunks.push(record.data);
296
+ continue;
297
+ }
298
+ if (record.type === RecordType.END) return { outcome: Outcome.END };
299
+ if (record.type === RecordType.NEXT) return {
300
+ outcome: Outcome.NEXT,
301
+ key: record.key
302
+ };
303
+ }
304
+ return { outcome: Outcome.MORE };
305
+ }
306
+ //#endregion
307
+ //#region src/adapters/s3-express/serial.ts
308
+ /**
309
+ * Runs work one piece at a time, in the order it was queued.
310
+ *
311
+ * Appends to a log have to be strictly ordered, because each one carries the offset the
312
+ * last one ended at. Chunks, beats and the end record are written from different timers,
313
+ * so without this they would race for that offset.
314
+ */
315
+ function createSerialQueue() {
316
+ let tail = Promise.resolve();
317
+ return { run(work) {
318
+ /**
319
+ * The next piece of work runs whether or not the one before it succeeded. A write
320
+ * that was refused leaves the store exactly as it was, so what follows is still
321
+ * valid at the same offset; stopping the queue on the first failure would strand
322
+ * every write after it.
323
+ */
324
+ const next = tail.then(work, work);
325
+ tail = next.then(() => {}, () => {});
326
+ return next;
327
+ } };
328
+ }
329
+ //#endregion
330
+ //#region src/adapters/s3-express/stop-watcher.ts
331
+ /**
332
+ * Watches for stop requests on behalf of producers, when the store has no way to push one.
333
+ *
334
+ * Two things make this more than a poll loop. A watcher is asked for before the generation
335
+ * it guards exists, because `core` registers the listener first and the stream second. And
336
+ * a stream id may be reused while its previous producer is still shutting down, so at that
337
+ * moment two watchers of one id are alive at once, each belonging to a different
338
+ * generation. Pairing them first in first out is exact, because the two calls are always
339
+ * made in pairs and in order.
340
+ *
341
+ * Nothing here knows where a stop request is kept. It asks a question and waits.
342
+ */
343
+ function createStopWatchers(options) {
344
+ const { isStopRequested, pollIntervalMs } = options;
345
+ const waiting = /* @__PURE__ */ new Map();
346
+ function createWatcher(streamId, onStop) {
347
+ const abortController = new AbortController();
348
+ const { signal } = abortController;
349
+ let begin = () => {};
350
+ const started = new Promise((resolve) => {
351
+ begin = resolve;
352
+ });
353
+ (async () => {
354
+ const generationId = await started;
355
+ /** Cancelled before it was ever paired with a generation. */
356
+ if (generationId === void 0) return;
357
+ while (!signal.aborted) {
358
+ try {
359
+ if (await isStopRequested(streamId, generationId)) {
360
+ if (!signal.aborted) onStop();
361
+ return;
362
+ }
363
+ } catch {}
364
+ await delay(pollIntervalMs, signal);
365
+ }
366
+ })();
367
+ return {
368
+ begin,
369
+ cancel: () => {
370
+ abortController.abort();
371
+ begin(void 0);
372
+ }
373
+ };
374
+ }
375
+ return {
376
+ watch(streamId, onStop) {
377
+ const watcher = createWatcher(streamId, onStop);
378
+ const queue = waiting.get(streamId) ?? [];
379
+ queue.push(watcher);
380
+ waiting.set(streamId, queue);
381
+ return () => {
382
+ watcher.cancel();
383
+ const queued = waiting.get(streamId);
384
+ if (!queued) return;
385
+ const index = queued.indexOf(watcher);
386
+ if (index !== -1) queued.splice(index, 1);
387
+ if (queued.length === 0) waiting.delete(streamId);
388
+ };
389
+ },
390
+ begin(streamId, generationId) {
391
+ const queue = waiting.get(streamId);
392
+ const watcher = queue?.shift();
393
+ if (queue?.length === 0) waiting.delete(streamId);
394
+ watcher?.begin(generationId);
395
+ }
396
+ };
397
+ }
398
+ //#endregion
399
+ //#region src/adapters/s3-express/adapter.ts
400
+ const DEFAULT_PREFIX = `ai-resumable-stream`;
401
+ const DEFAULT_FLUSH_INTERVAL_MS = 250;
402
+ const DEFAULT_BATCH_SIZE = 50;
403
+ const DEFAULT_RESUME_POLL_INTERVAL_MS = 500;
404
+ const DEFAULT_STOP_POLL_INTERVAL_MS = 1e3;
405
+ const DEFAULT_HEARTBEAT_MS = 5e3;
406
+ const DEFAULT_DEAD_AFTER_MS = 3e4;
407
+ const DEFAULT_MAX_PARTS_PER_SEGMENT = 9e3;
408
+ const encoder = new TextEncoder();
409
+ const decoder = new TextDecoder();
410
+ const VERSION_RECORD = encodeVersion();
411
+ const STOP_MARKER = encoder.encode(`1`);
412
+ function unref(timer) {
413
+ timer.unref?.();
414
+ }
415
+ /**
416
+ * A death threshold that is not comfortably larger than the beat will declare healthy
417
+ * producers dead, which truncates live streams. Refuse the configuration outright rather
418
+ * than let it corrupt streams under load.
419
+ */
420
+ function assertHeartbeatWindow(heartbeatMs, deadAfterMs) {
421
+ if (deadAfterMs < heartbeatMs * 2) throw new Error(`deadAfterMs (${deadAfterMs}) must be at least twice heartbeatMs (${heartbeatMs})`);
422
+ }
423
+ /**
424
+ * Whether a log has been silent long enough for its producer to be presumed dead.
425
+ *
426
+ * Both timestamps come from the same S3 response, so this is a comparison of S3's clock
427
+ * with itself. A producer and its readers run on different hosts, and a check that mixed
428
+ * their clocks would kill healthy streams on the first few seconds of drift.
429
+ */
430
+ function isStale(response, deadAfterMs) {
431
+ const { date, lastModified } = response;
432
+ if (date === void 0 || lastModified === void 0) return false;
433
+ return date - lastModified > deadAfterMs;
434
+ }
435
+ /**
436
+ * Stores streams as one appendable object each, in an S3 Express One Zone bucket.
437
+ *
438
+ * Chunks, liveness and completion all live in the same log, so a reader following a
439
+ * stream costs one request per poll. Nothing is ever listed: every key is either derived
440
+ * from the stream id or named by the log itself.
441
+ *
442
+ * A stream stops being resumable when its producer stops, which is `deadAfterMs` at the
443
+ * outside. How long the objects then sit in the bucket is a lifecycle expiration rule
444
+ * rather than anything this can enforce, so nothing here is deleted.
445
+ */
446
+ function createS3ExpressAdapter(options) {
447
+ const { client, bucket, ...rest } = options;
448
+ return createStreamAdapter(createS3Operations({
449
+ client,
450
+ bucket
451
+ }), rest);
452
+ }
453
+ /**
454
+ * The adapter, bound to storage operations rather than to a client, so the tests can run
455
+ * the whole of it against an in-memory bucket. No local emulator implements appends.
456
+ */
457
+ function createStreamAdapter(s3, options = {}) {
458
+ const { prefix = DEFAULT_PREFIX, flushIntervalMs = DEFAULT_FLUSH_INTERVAL_MS, batchSize = DEFAULT_BATCH_SIZE, resumePollIntervalMs = DEFAULT_RESUME_POLL_INTERVAL_MS, stopPollIntervalMs = DEFAULT_STOP_POLL_INTERVAL_MS, heartbeatMs = DEFAULT_HEARTBEAT_MS, deadAfterMs = DEFAULT_DEAD_AFTER_MS, maxPartsPerSegment = DEFAULT_MAX_PARTS_PER_SEGMENT } = options;
459
+ assertHeartbeatWindow(heartbeatMs, deadAfterMs);
460
+ /**
461
+ * A stream id becomes one path segment, so an id like `tenant:app/session` cannot nest
462
+ * a directory or collide with the keys of another stream.
463
+ */
464
+ const streamPrefix = (streamId) => `${prefix}/${encodeURIComponent(streamId)}`;
465
+ const pointerKey = (streamId) => `${streamPrefix(streamId)}/current`;
466
+ const stopKey = (streamId, generationId) => `${streamPrefix(streamId)}/${generationId}/stop`;
467
+ const segmentKey = (streamId, generationId, index) => `${streamPrefix(streamId)}/${generationId}/${index}`;
468
+ async function readPointer(streamId) {
469
+ const result = await s3.read(pointerKey(streamId), 0);
470
+ if (!result || result.bytes.length === 0) return void 0;
471
+ try {
472
+ return JSON.parse(decoder.decode(result.bytes));
473
+ } catch {
474
+ return;
475
+ }
476
+ }
477
+ /**
478
+ * Stop requests are keyed by generation, so one can never reach the generation that
479
+ * replaced it, and nothing has to be cleaned up when a stream id is reused.
480
+ */
481
+ const stopWatchers = createStopWatchers({
482
+ pollIntervalMs: stopPollIntervalMs,
483
+ isStopRequested: async (streamId, generationId) => await s3.head(stopKey(streamId, generationId)) !== void 0
484
+ });
485
+ return {
486
+ async createStream({ streamId, chunks, waitUntil }) {
487
+ const generationId = crypto.randomUUID();
488
+ const pointer = { generationId };
489
+ /**
490
+ * A segment opens with its format version, so it is never empty and a reader gets
491
+ * bytes, and with them S3's clock, from its very first read. The log is created
492
+ * before the pointer, so a pointer always names a log that exists and a reader never
493
+ * has to treat a missing one as anything but gone.
494
+ */
495
+ const segment = {
496
+ index: 0,
497
+ key: segmentKey(streamId, generationId, 0),
498
+ offset: VERSION_RECORD.length,
499
+ parts: 1
500
+ };
501
+ await s3.put(segment.key, VERSION_RECORD);
502
+ await s3.put(pointerKey(streamId), encoder.encode(JSON.stringify(pointer)));
503
+ stopWatchers.begin(streamId, generationId);
504
+ const writes = createSerialQueue();
505
+ async function appendRecord(body) {
506
+ try {
507
+ await s3.append(segment.key, segment.offset, body);
508
+ } catch (error) {
509
+ if (!(error instanceof WriteOffsetMismatchError)) throw error;
510
+ /**
511
+ * Either the append landed and its response was lost, or the object is not the
512
+ * length this producer thinks it is. The size tells the two apart, and an
513
+ * append is never replayed blindly: it is not idempotent.
514
+ */
515
+ const head = await s3.head(segment.key);
516
+ if (head?.size === segment.offset + body.length) {
517
+ segment.offset = head.size;
518
+ segment.parts += 1;
519
+ return;
520
+ }
521
+ if (head?.size !== segment.offset) throw error;
522
+ await s3.append(segment.key, segment.offset, body);
523
+ }
524
+ segment.offset += body.length;
525
+ segment.parts += 1;
526
+ }
527
+ /**
528
+ * Continues the log in a new object once this one has used its parts, leaving
529
+ * behind a record naming where a reader should carry on.
530
+ */
531
+ async function rollSegment() {
532
+ const next = segmentKey(streamId, generationId, segment.index + 1);
533
+ await appendRecord(encodeNext(next));
534
+ await s3.put(next, VERSION_RECORD);
535
+ segment.index += 1;
536
+ segment.key = next;
537
+ segment.offset = VERSION_RECORD.length;
538
+ segment.parts = 1;
539
+ }
540
+ async function write(body) {
541
+ if (segment.parts >= maxPartsPerSegment) await rollSegment();
542
+ await appendRecord(body);
543
+ }
544
+ let buffer = [];
545
+ let lastFlushAt = Date.now();
546
+ let flushTimer;
547
+ function clearFlushTimer() {
548
+ if (flushTimer === void 0) return;
549
+ clearTimeout(flushTimer);
550
+ flushTimer = void 0;
551
+ }
552
+ async function flush() {
553
+ clearFlushTimer();
554
+ if (buffer.length === 0) return;
555
+ const pending = buffer;
556
+ buffer = [];
557
+ lastFlushAt = Date.now();
558
+ await writes.run(() => write(joinRecords(pending)));
559
+ }
560
+ /**
561
+ * Guarantees that a chunk arriving just after a flush is still written within the
562
+ * interval, rather than waiting for a chunk that may never come.
563
+ */
564
+ function scheduleFlush() {
565
+ if (flushTimer !== void 0) return;
566
+ const due = Math.max(0, lastFlushAt + flushIntervalMs - Date.now());
567
+ flushTimer = setTimeout(() => {
568
+ flushTimer = void 0;
569
+ flush().catch(() => {
570
+ /** The next write reports it */
571
+ });
572
+ }, due);
573
+ }
574
+ /**
575
+ * Beats for as long as the source is being drained, including while it is idle. A
576
+ * beat is a real record because S3 rejects an append with an empty body.
577
+ */
578
+ const heartbeat = setInterval(() => {
579
+ writes.run(async () => {
580
+ if (buffer.length > 0) return;
581
+ await write(encodeBeat());
582
+ }).catch(() => {
583
+ /** Retried on the next beat */
584
+ });
585
+ }, heartbeatMs);
586
+ unref(heartbeat);
587
+ const consumed = (async () => {
588
+ const reader = chunks.getReader();
589
+ try {
590
+ while (true) {
591
+ const { done, value } = await reader.read();
592
+ if (done) break;
593
+ buffer.push(encodeChunk(value));
594
+ if (buffer.length >= batchSize || Date.now() - lastFlushAt >= flushIntervalMs) await flush();
595
+ else scheduleFlush();
596
+ }
597
+ await flush();
598
+ } catch {
599
+ await flush().catch(() => {
600
+ /** The chunks are lost either way */
601
+ });
602
+ } finally {
603
+ clearInterval(heartbeat);
604
+ clearFlushTimer();
605
+ reader.releaseLock();
606
+ /**
607
+ * A stream that failed is reported exactly like one that completed, so the end
608
+ * record says only that the generation is over.
609
+ */
610
+ await writes.run(() => write(encodeEnd())).catch(() => {
611
+ /** Readers fall back to the silence */
612
+ });
613
+ }
614
+ })();
615
+ waitUntil?.(consumed);
616
+ },
617
+ async resumeStream({ streamId }) {
618
+ const pointer = await readPointer(streamId);
619
+ if (!pointer) return null;
620
+ const cursor = {
621
+ key: segmentKey(streamId, pointer.generationId, 0),
622
+ offset: 0
623
+ };
624
+ const replay = [];
625
+ let ended = false;
626
+ let stale = false;
627
+ /**
628
+ * One ranged read returns the whole backlog. A second one happens only when the log
629
+ * has already continued in another object.
630
+ */
631
+ while (true) {
632
+ const result = await s3.read(cursor.key, cursor.offset);
633
+ if (!result) return null;
634
+ stale = isStale(result, deadAfterMs);
635
+ if (result.bytes.length === 0) break;
636
+ const { records, consumed } = decodeRecords(result.bytes);
637
+ cursor.offset += consumed;
638
+ const collected = collectChunks(records, replay);
639
+ if (collected.outcome === Outcome.END) {
640
+ ended = true;
641
+ break;
642
+ }
643
+ if (collected.outcome === Outcome.NEXT) {
644
+ cursor.key = collected.key;
645
+ cursor.offset = 0;
646
+ continue;
647
+ }
648
+ break;
649
+ }
650
+ /**
651
+ * A stream that ended is reported the same way whether it completed or failed, and
652
+ * so is one whose producer died: there is nothing left to follow.
653
+ */
654
+ if (ended || stale) return null;
655
+ const abortController = new AbortController();
656
+ const { signal } = abortController;
657
+ let lastProgressAt = Date.now();
658
+ return new ReadableStream({
659
+ start(controller) {
660
+ for (const data of replay) controller.enqueue(data);
661
+ },
662
+ async pull(controller) {
663
+ while (!signal.aborted) {
664
+ const result = await s3.read(cursor.key, cursor.offset);
665
+ if (!result) {
666
+ controller.close();
667
+ return;
668
+ }
669
+ if (result.bytes.length > 0) {
670
+ lastProgressAt = Date.now();
671
+ const { records, consumed } = decodeRecords(result.bytes);
672
+ cursor.offset += consumed;
673
+ const chunks = [];
674
+ const collected = collectChunks(records, chunks);
675
+ for (const data of chunks) controller.enqueue(data);
676
+ if (collected.outcome === Outcome.END) {
677
+ controller.close();
678
+ return;
679
+ }
680
+ if (collected.outcome === Outcome.NEXT) {
681
+ cursor.key = collected.key;
682
+ cursor.offset = 0;
683
+ }
684
+ if (chunks.length > 0) return;
685
+ continue;
686
+ }
687
+ /**
688
+ * Nothing new. How long the log has been quiet is only worth asking S3 once
689
+ * the reader's own wait suggests something is wrong, and the answer itself is
690
+ * always S3's, never the reader's.
691
+ */
692
+ if (Date.now() - lastProgressAt >= deadAfterMs) {
693
+ const head = await s3.head(cursor.key);
694
+ if (!head || isStale(head, deadAfterMs)) {
695
+ controller.close();
696
+ return;
697
+ }
698
+ lastProgressAt = Date.now();
699
+ }
700
+ await delay(resumePollIntervalMs, signal);
701
+ }
702
+ },
703
+ cancel() {
704
+ abortController.abort();
705
+ }
706
+ });
707
+ },
708
+ async requestStop({ streamId }) {
709
+ const pointer = await readPointer(streamId);
710
+ if (!pointer) return;
711
+ await s3.put(stopKey(streamId, pointer.generationId), STOP_MARKER);
712
+ },
713
+ async onStopRequested({ streamId, onStop }) {
714
+ return stopWatchers.watch(streamId, onStop);
715
+ }
716
+ };
717
+ }
718
+ //#endregion
719
+ export { createS3ExpressAdapter };