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