ai-resumable-stream 3.3.0 → 3.4.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/README.md CHANGED
@@ -196,6 +196,17 @@ async function resumeMessage(chatId: string) {
196
196
  }
197
197
  ```
198
198
 
199
+ Pass the `signal` of the incoming request. If the client goes away, the resume ends at once and frees its resources, also while it still waits for the first chunk of the producer. The signal applies to the full resume, until the stream ends. Before `resumeStream` returns, the promise rejects with the reason of the signal. After that, the returned stream errors with it.
200
+
201
+ ```ts
202
+ // GET /chat/:chatId/stream
203
+ export async function resume(chatId: string, request: Request) {
204
+ const stream = await context.resumeStream({ streamId: chatId, signal: request.signal });
205
+
206
+ return stream ?? new Response(null, { status: 204 });
207
+ }
208
+ ```
209
+
199
210
  The result is `null` in three cases. The library does not tell you which case applies:
200
211
 
201
212
  - no stream was started with that id
@@ -296,13 +307,15 @@ const context = createResumableUIMessageStream({
296
307
  });
297
308
  ```
298
309
 
299
- | Option | Type | Required | Description |
300
- | -------------- | ------------- | -------- | ---------------------------------------------------------------------------------------------------------- |
301
- | `publisher` | `RedisClient` | Yes | Client that sends commands and publishes messages |
302
- | `subscriber` | `RedisClient` | Yes | Client for subscriptions. Must be a separate client, because a subscribed connection cannot send commands |
303
- | `keyPrefix` | `string` | No | Prefix for all keys and channels. Defaults to `ai-resumable-stream` |
304
- | `ackTimeoutMs` | `number` | No | How long a resume waits for the producer to answer before it returns `null`. Defaults to `1000` |
305
- | `ttlSeconds` | `number` | No | How long a stream stays resumable. Must be longer than your longest stream. Defaults to `86400` (24 hours) |
310
+ | Option | Type | Required | Description |
311
+ | ------------------ | ------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
312
+ | `publisher` | `RedisClient` | Yes | Client that sends commands and publishes messages |
313
+ | `subscriber` | `RedisClient` | Yes | Client for subscriptions. Must be a separate client, because a subscribed connection cannot send commands |
314
+ | `keyPrefix` | `string` | No | Prefix for all keys and channels. Defaults to `ai-resumable-stream` |
315
+ | `ackTimeoutMs` | `number` | No | How long a resume waits for the producer to answer before it returns `null`. Defaults to `1000` |
316
+ | `expireAfterMs` | `number` | No | When the pointer of a stream id expires. Must be longer than your longest stream. Defaults to `86400000` (24 hours) |
317
+ | `commandTimeoutMs` | `number` | No | How long a call waits for Redis before it rejects with a `CommandTimeoutError` (its `name` is `TimeoutError`). Defaults to no limit |
318
+ | `heartbeatMs` | `number` | No | How often a producer renews the mark that its stream is running. The mark expires after three intervals, so a dead producer is detected after three intervals. Defaults to `30000` (30 s, detection after 90 s) |
306
319
 
307
320
  > [!IMPORTANT]
308
321
  > **A stream is only resumable while its producer is alive.**
@@ -361,7 +374,7 @@ const adapter: StreamAdapter = {
361
374
  ```
362
375
 
363
376
  - **`createStream`** runs when a stream starts. It receives the stream id, the generation id and a `ReadableStream<string>` of encoded chunks. First, it discards any state left over from an earlier stream with the same id, so a reused id never replays old chunks. Then it makes `generationId` the current generation of the stream id and consumes the chunks in the background until the stream ends. The chunks stream also ends without an error when the source stream fails. The returned promise resolves as soon as the stream can be resumed, not when it is complete.
364
- - **`resumeStream`** runs when a client reconnects. It returns every chunk produced so far, in the original order, and then continues with the new chunks until the stream ends. With a `generationId`, it resumes that generation. Without one, it resumes the current generation of the stream id. It returns `null` when the id is unknown, the stream has already finished, or its data has expired.
377
+ - **`resumeStream`** runs when a client reconnects. It returns every chunk produced so far, in the original order, and then continues with the new chunks until the stream ends. With a `generationId`, it resumes that generation. Without one, it resumes the current generation of the stream id. It returns `null` when the id is unknown, the stream has already finished, or its data has expired. The library cancels the returned stream when the `signal` of the caller aborts. An adapter can also use `signal` to free a subscription or a wait sooner.
365
378
  - **`requestStop`** runs in the process that wants to stop a stream. With a `generationId`, it stops that generation. Without one, it stops the current generation of the stream id. It must not fail when the stream is unknown or already finished, and it should store the request if the generation does not listen yet.
366
379
  - **`onStopRequested`** runs in the producing process when a stream starts. It registers a listener for one generation that calls `onStop` when a stop signal arrives. If a stop request was stored before the listener was registered, the listener also calls `onStop` for that request. It returns a function that removes only this listener.
367
380
 
@@ -418,6 +431,20 @@ import { waitUntil } from "@vercel/functions";
418
431
  const context = createResumableUIMessageStream({ adapter, waitUntil });
419
432
  ```
420
433
 
434
+ The library gives `waitUntil` a promise for each task that runs after the response: reading the source, the teardown of the adapter, and the stop listener. None of these promises rejects. If you close your store clients, for example the Redis clients, collect the promises and wait for them first. Otherwise the teardown can fail and leave the stream marked as running:
435
+
436
+ ```ts
437
+ const pending: Array<Promise<unknown>> = [];
438
+ const context = createResumableUIMessageStream({
439
+ adapter,
440
+ waitUntil: (promise) => pending.push(promise),
441
+ });
442
+
443
+ // Before shutdown
444
+ await Promise.all(pending);
445
+ await Promise.all([publisher.quit(), subscriber.quit()]);
446
+ ```
447
+
421
448
  ### Finish
422
449
 
423
450
  The library calls `onFinish` after the source stream has ended and the adapter stream has closed. Use it for cleanup, for example to remove the active stream id from the database. The library catches and ignores errors from `onFinish`.
@@ -542,6 +569,7 @@ type StartStreamResult<CHUNK> = {
542
569
  type ResumeStreamOptions = {
543
570
  streamId: string;
544
571
  generationId?: string;
572
+ signal?: AbortSignal;
545
573
  };
546
574
 
547
575
  type StopStreamOptions = {
@@ -554,7 +582,7 @@ type StopStreamOptions = {
554
582
  | ------------ | -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
555
583
  | `adapter` | `StreamAdapter` | Yes | Stores the chunks and transports stop requests |
556
584
  | `codec` | `StreamCodec<CHUNK>` | Yes | Converts chunks to strings for the adapter, and back |
557
- | `waitUntil` | `(promise) => void` | No | Keeps the process alive until all chunks are stored. Only needed on serverless runtimes |
585
+ | `waitUntil` | `(promise) => void` | No | Receives a promise for each task after the response. Keeps a serverless function alive, and lets you wait before you close the clients |
558
586
  | `generateId` | `() => string` | No | Generates the stream id and the generation id when you do not pass them to `startStream`. Must return a new id on each call. Defaults to `crypto.randomUUID` |
559
587
 
560
588
  ### `createResumableUIMessageStream`
@@ -580,6 +608,7 @@ type StreamAdapter = {
580
608
  resumeStream(options: {
581
609
  streamId: string;
582
610
  generationId?: string;
611
+ signal?: AbortSignal;
583
612
  }): Promise<ReadableStream<string> | null>;
584
613
  requestStop(options: { streamId: string; generationId?: string }): Promise<void>;
585
614
  onStopRequested(options: {
@@ -43,6 +43,12 @@ type StreamAdapter = {
43
43
  resumeStream(options: {
44
44
  streamId: string;
45
45
  generationId?: string;
46
+ /**
47
+ * Aborts when the caller gives up on the resume. The caller enforces it already: it
48
+ * stops waiting, and it cancels the stream when the adapter returns it later. An
49
+ * adapter can also use it to free a subscription or a wait sooner.
50
+ */
51
+ signal?: AbortSignal;
46
52
  }): Promise<ReadableStream<string> | null>;
47
53
  /**
48
54
  * Signals the process that owns a generation of the stream to stop producing.
@@ -1,4 +1,4 @@
1
- import { t as StreamAdapter } from "../../adapter-BwSsPtDm.mjs";
1
+ import { t as StreamAdapter } from "../../adapter-DZmSMkrn.mjs";
2
2
  //#region src/adapters/redis/adapter.d.ts
3
3
  /**
4
4
  * A Redis client, described by the commands this adapter actually calls rather than by
@@ -18,7 +18,7 @@ type Redis = {
18
18
  get(key: string): Promise<string | null>;
19
19
  set(key: string, value: string, options?: {
20
20
  expiration?: {
21
- type: `EX`;
21
+ type: `EX` | `PX`;
22
22
  value: number;
23
23
  };
24
24
  }): Promise<unknown>;
@@ -50,13 +50,47 @@ type CreateRedisAdapterOptions = {
50
50
  */
51
51
  ackTimeoutMs?: number;
52
52
  /**
53
- * How long a stream stays resumable, in seconds. Must be longer than your longest
54
- * stream, because a resume finds nothing after this time, even while the producer still
55
- * runs. A shorter value ends sooner the wait of each resume for a producer that died.
56
- * Defaults to 24 hours.
53
+ * When the Redis keys of a stream expire, in milliseconds: the pointer of the stream id
54
+ * and the mark of a finished stream. Must be longer than your longest stream, because a
55
+ * resume without a generation id finds nothing after the pointer expired, even while the
56
+ * producer still runs. The stream of a producer that died is gone sooner, because its
57
+ * producer no longer renews it. Defaults to 24 hours.
58
+ */
59
+ expireAfterMs?: number;
60
+ /**
61
+ * The same as `expireAfterMs`, in seconds. Ignored when `expireAfterMs` is set.
62
+ *
63
+ * @deprecated Use `expireAfterMs`.
57
64
  */
58
65
  ttlSeconds?: number;
66
+ /**
67
+ * How long the adapter waits for Redis when it connects, registers a stream, reads the
68
+ * pointer, or sends and listens for a stop. After this time, the call rejects with a
69
+ * `CommandTimeoutError`. Use it when Redis can become unreachable: the client does not
70
+ * get an answer from a dead peer, and the timeout and the abort signal of the client no
71
+ * longer apply once a command is written. The command can still be pending in the client.
72
+ * Defaults to no limit.
73
+ */
74
+ commandTimeoutMs?: number;
75
+ /**
76
+ * How often a producer renews the mark that its stream is running. The mark expires
77
+ * after three intervals without a renewal, so the stream of a producer that died is
78
+ * gone after three intervals. Each renewal is one Redis command per running stream.
79
+ * Defaults to 30 s, so a dead producer is detected after 90 s.
80
+ */
81
+ heartbeatMs?: number;
59
82
  };
83
+ /**
84
+ * Raised when Redis does not answer a call of the adapter within `commandTimeoutMs`.
85
+ *
86
+ * Its name is `TimeoutError`, the name of the error that `AbortSignal.timeout()` gives, so
87
+ * a check of `error.name === "TimeoutError"` finds both. A plain `Error` and not a
88
+ * `DOMException`, because a `DOMException` takes its name only from its constructor, and a
89
+ * subclass of it is unusual.
90
+ */
91
+ declare class CommandTimeoutError extends Error {
92
+ constructor(timeoutMs: number);
93
+ }
60
94
  /**
61
95
  * Stores streams in Redis, with a runtime derived from `resumable-stream`.
62
96
  *
@@ -66,4 +100,4 @@ type CreateRedisAdapterOptions = {
66
100
  */
67
101
  declare function createRedisAdapter(options: CreateRedisAdapterOptions): StreamAdapter;
68
102
  //#endregion
69
- export { type CreateRedisAdapterOptions, createRedisAdapter };
103
+ export { CommandTimeoutError, type CreateRedisAdapterOptions, createRedisAdapter };
@@ -40,6 +40,16 @@ const DONE_MESSAGE = `\n\n\nDONE_SENTINEL_hasdfasudfyge374%$%^$EDSATRTYFtydryrte
40
40
  const DONE_VALUE = `DONE`;
41
41
  const DEFAULT_ACK_TIMEOUT_MS = 1e3;
42
42
  const DEFAULT_DONE_WATCHDOG_INTERVAL_MS = 1e4;
43
+ /**
44
+ * Long enough to keep the commands few, one SET per running stream every 30 s, and short
45
+ * enough that the stream of a producer that died is gone in about 1.5 minutes.
46
+ */
47
+ const DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
48
+ /**
49
+ * The running sentinel lives this many heartbeat intervals, so two renewals in a row can
50
+ * fail, for example during a reconnect, before it expires.
51
+ */
52
+ const HEARTBEATS_PER_SENTINEL_TTL = 3;
43
53
  function noop() {}
44
54
  function createRuntime(options) {
45
55
  const ctx = {
@@ -48,8 +58,9 @@ function createRuntime(options) {
48
58
  subscriber: options.subscriber,
49
59
  waitUntil: options.waitUntil ?? noop,
50
60
  ackTimeoutMs: options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS,
51
- ttlSeconds: options.ttlSeconds,
52
- doneWatchdogIntervalMs: options.doneWatchdogIntervalMs ?? DEFAULT_DONE_WATCHDOG_INTERVAL_MS
61
+ expireAfterMs: options.expireAfterMs,
62
+ doneWatchdogIntervalMs: options.doneWatchdogIntervalMs ?? DEFAULT_DONE_WATCHDOG_INTERVAL_MS,
63
+ heartbeatIntervalMs: options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS
53
64
  };
54
65
  return {
55
66
  createNewResumableStream: (streamId, makeStream) => createNewResumableStream(ctx, streamId, makeStream),
@@ -66,9 +77,13 @@ async function createNewResumableStream(ctx, streamId, makeStream) {
66
77
  const requestChannel = `${ctx.keyPrefix}:request:${streamId}`;
67
78
  const sentinelKey = `${ctx.keyPrefix}:sentinel:${streamId}`;
68
79
  const chunkChannel = (listenerId) => `${ctx.keyPrefix}:chunk:${listenerId}`;
69
- const sentinelExpiration = { expiration: {
70
- type: `EX`,
71
- value: ctx.ttlSeconds
80
+ const runningExpiration = { expiration: {
81
+ type: `PX`,
82
+ value: ctx.heartbeatIntervalMs * HEARTBEATS_PER_SENTINEL_TTL
83
+ } };
84
+ const doneExpiration = { expiration: {
85
+ type: `PX`,
86
+ value: ctx.expireAfterMs
72
87
  } };
73
88
  const chunks = [];
74
89
  const listenerIds = [];
@@ -131,7 +146,7 @@ async function createNewResumableStream(ctx, streamId, makeStream) {
131
146
  try {
132
147
  await ctx.subscriber.subscribe(requestChannel, onRequest);
133
148
  try {
134
- await ctx.publisher.set(sentinelKey, `1`, sentinelExpiration);
149
+ await ctx.publisher.set(sentinelKey, `1`, runningExpiration);
135
150
  } catch (error) {
136
151
  await ctx.subscriber.unsubscribe(requestChannel, onRequest).catch(noop);
137
152
  throw error;
@@ -141,6 +156,23 @@ async function createNewResumableStream(ctx, streamId, makeStream) {
141
156
  throw error;
142
157
  }
143
158
  /**
159
+ * Renews the running sentinel while the producer is alive. A producer that died stops
160
+ * the renewals, so its sentinel expires: a new resume then finds no stream at once, and
161
+ * the watchdog of an attached consumer closes its stream. A failed renewal is retried at
162
+ * the next interval. The renewal is a plain SET, so it also restores a sentinel that
163
+ * expired while Redis was unreachable. The teardown stops the renewals before it sends
164
+ * DONE, and one connection keeps the order of its commands, so a renewal never
165
+ * overwrites DONE.
166
+ *
167
+ * Differs from upstream: upstream sets the running sentinel once, for 24 hours, so a
168
+ * consumer waits for the ack timeout on every resume of a stream whose producer died.
169
+ */
170
+ const heartbeat = setInterval(() => {
171
+ ctx.publisher.set(sentinelKey, `1`, runningExpiration).catch(noop);
172
+ }, ctx.heartbeatIntervalMs);
173
+ /** A long-lived process can still exit while a stream runs */
174
+ heartbeat.unref?.();
175
+ /**
144
176
  * Marks the stream done, tells the consumers and stops to answer requests.
145
177
  *
146
178
  * Differs from upstream:
@@ -155,16 +187,18 @@ async function createNewResumableStream(ctx, streamId, makeStream) {
155
187
  * - Waits for the chunk publishes still in flight, so a runtime that freezes the process
156
188
  * after `waitUntil` does not lose them.
157
189
  *
158
- * If the DONE write fails, the sentinel stays "1" until it expires. A consumer then gets
190
+ * If the DONE write fails, the sentinel stays "1" until it expires, which is three
191
+ * heartbeat intervals after the teardown stopped the renewals. A consumer then gets
159
192
  * no answer and fails with the ack timeout.
160
193
  */
161
194
  let finishing;
162
195
  const finish = () => {
163
196
  finishing ??= (async () => {
164
197
  isDone = true;
198
+ clearInterval(heartbeat);
165
199
  for (const listenerId of listenerIds) publish(chunkChannel(listenerId), DONE_MESSAGE);
166
200
  await Promise.allSettled([
167
- ctx.publisher.set(sentinelKey, DONE_VALUE, sentinelExpiration),
201
+ ctx.publisher.set(sentinelKey, DONE_VALUE, doneExpiration),
168
202
  ctx.subscriber.unsubscribe(requestChannel, onRequest),
169
203
  ...inFlight
170
204
  ]);
@@ -398,11 +432,25 @@ function sseToChunks() {
398
432
  }
399
433
  //#endregion
400
434
  //#region src/adapters/redis/adapter.ts
435
+ /**
436
+ * Raised when Redis does not answer a call of the adapter within `commandTimeoutMs`.
437
+ *
438
+ * Its name is `TimeoutError`, the name of the error that `AbortSignal.timeout()` gives, so
439
+ * a check of `error.name === "TimeoutError"` finds both. A plain `Error` and not a
440
+ * `DOMException`, because a `DOMException` takes its name only from its constructor, and a
441
+ * subclass of it is unusual.
442
+ */
443
+ var CommandTimeoutError = class extends Error {
444
+ constructor(timeoutMs) {
445
+ super(`Redis did not answer within ${timeoutMs} ms`);
446
+ this.name = `TimeoutError`;
447
+ }
448
+ };
401
449
  const DEFAULT_KEY_PREFIX = `ai-resumable-stream`;
402
450
  /**
403
451
  * The fixed lifetime of the original `resumable-stream`, long enough for any chat turn.
404
452
  */
405
- const DEFAULT_TTL_SECONDS = 1440 * 60;
453
+ const DEFAULT_EXPIRE_AFTER_MS = 1440 * 60 * 1e3;
406
454
  /**
407
455
  * Deletes a key only while it still holds the expected value. One script, so no other
408
456
  * client can write the key between the comparison and the deletion.
@@ -422,7 +470,28 @@ const STOP_TTL_SECONDS = 3600;
422
470
  * durable adapter when a stream must outlive the process that started it.
423
471
  */
424
472
  function createRedisAdapter(options) {
425
- const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX, ackTimeoutMs, ttlSeconds = DEFAULT_TTL_SECONDS } = options;
473
+ const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX, ackTimeoutMs, ttlSeconds, commandTimeoutMs, heartbeatMs } = options;
474
+ if (heartbeatMs !== void 0 && !(heartbeatMs > 0)) throw new RangeError(`heartbeatMs must be greater than 0, got ${heartbeatMs}`);
475
+ const expireAfterMs = options.expireAfterMs ?? (ttlSeconds === void 0 ? DEFAULT_EXPIRE_AFTER_MS : ttlSeconds * 1e3);
476
+ /**
477
+ * Rejects with a `CommandTimeoutError` when the call takes longer than
478
+ * `commandTimeoutMs`. A late failure of the call is handled, so it is not an unhandled
479
+ * rejection.
480
+ */
481
+ function limit(call) {
482
+ if (commandTimeoutMs === void 0) return call;
483
+ const timeoutMs = commandTimeoutMs;
484
+ return new Promise((resolve, reject) => {
485
+ const timer = setTimeout(() => reject(new CommandTimeoutError(timeoutMs)), timeoutMs);
486
+ call.then((value) => {
487
+ clearTimeout(timer);
488
+ resolve(value);
489
+ }, (error) => {
490
+ clearTimeout(timer);
491
+ reject(error);
492
+ });
493
+ });
494
+ }
426
495
  /**
427
496
  * The name of one generation of a stream id. The generation id is encoded, so it holds
428
497
  * no colon and the name splits one way only: stream `a` with generation `b:c` never
@@ -450,7 +519,7 @@ function createRedisAdapter(options) {
450
519
  */
451
520
  const pointerKey = (streamId) => `${keyPrefix}:generation:${streamId}`;
452
521
  async function connect() {
453
- await Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]);
522
+ await limit(Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]));
454
523
  }
455
524
  function createContext(waitUntil) {
456
525
  return createRuntime({
@@ -459,18 +528,19 @@ function createRedisAdapter(options) {
459
528
  subscriber,
460
529
  keyPrefix,
461
530
  ackTimeoutMs,
462
- ttlSeconds
531
+ expireAfterMs,
532
+ heartbeatIntervalMs: heartbeatMs
463
533
  });
464
534
  }
465
535
  async function readPointer(streamId) {
466
- return publisher.get(pointerKey(streamId));
536
+ return limit(publisher.get(pointerKey(streamId)));
467
537
  }
468
538
  /**
469
539
  * Drops the stop kept for a generation once it is over, so nothing outlives the
470
540
  * generation it was meant for.
471
541
  */
472
542
  async function clearStop(streamId, generationId) {
473
- await publisher.del(stopKey(streamId, generationId));
543
+ await limit(publisher.del(stopKey(streamId, generationId)));
474
544
  }
475
545
  /**
476
546
  * Retires the generation, but only while it is still the current one, so a slow
@@ -478,10 +548,10 @@ function createRedisAdapter(options) {
478
548
  * successor may repoint the id at any moment, including between the two.
479
549
  */
480
550
  async function clearPointer(streamId, generationId) {
481
- await publisher.eval(DELETE_IF_EQUAL_SCRIPT, {
551
+ await limit(publisher.eval(DELETE_IF_EQUAL_SCRIPT, {
482
552
  keys: [pointerKey(streamId)],
483
553
  arguments: [generationId]
484
- });
554
+ }));
485
555
  }
486
556
  return {
487
557
  async createStream({ streamId, generationId: runId, chunks, waitUntil }) {
@@ -498,23 +568,37 @@ function createRedisAdapter(options) {
498
568
  * died before it could clean up. A pointer that lives longer than its sentinel only
499
569
  * leads to a stream that the runtime does not know.
500
570
  */
501
- await publisher.set(pointerKey(streamId), generationId, { expiration: {
502
- type: `EX`,
503
- value: ttlSeconds
504
- } });
571
+ await limit(publisher.set(pointerKey(streamId), generationId, { expiration: {
572
+ type: `PX`,
573
+ value: expireAfterMs
574
+ } }));
505
575
  /**
506
576
  * The pointer is dropped as soon as the source ends, so a resume that arrives
507
577
  * during teardown is told there is nothing to resume rather than racing it. The
508
578
  * stop goes with it: a generation that is over has nothing left to stop.
509
579
  */
510
- const sse = chunks.pipeThrough(chunksToSSE()).pipeThrough(new TransformStream({ async flush() {
580
+ const abandon = new AbortController();
581
+ const sse = chunks.pipeThrough(chunksToSSE(), { signal: abandon.signal }).pipeThrough(new TransformStream({ async flush() {
511
582
  await Promise.all([clearPointer(streamId, generationId), clearStop(streamId, runId)]).catch(() => {
512
583
  /** Both expire on their own */
513
584
  });
514
585
  } }));
515
- await createContext(waitUntil).createNewResumableStream(generationId, () => sse);
586
+ /**
587
+ * A registration that times out is abandoned. The runtime can still finish its setup
588
+ * later, so the pipe is aborted: the runtime then sees a failed source and tears the
589
+ * stream down, and the source is cancelled.
590
+ */
591
+ try {
592
+ await limit(createContext(waitUntil).createNewResumableStream(generationId, () => sse));
593
+ } catch (error) {
594
+ abandon.abort(error);
595
+ await clearPointer(streamId, generationId).catch(() => {
596
+ /** It expires on its own */
597
+ });
598
+ throw error;
599
+ }
516
600
  },
517
- async resumeStream({ streamId, generationId: runId }) {
601
+ async resumeStream({ streamId, generationId: runId, signal }) {
518
602
  await connect();
519
603
  /**
520
604
  * A named generation is followed without the pointer, so it can be resumed after a
@@ -544,12 +628,21 @@ function createRedisAdapter(options) {
544
628
  * not yet emitted anything waits for its first chunk.
545
629
  */
546
630
  let first;
631
+ /**
632
+ * A producer that never sends its first chunk would hold this read, and with it the
633
+ * subscription, forever. The abort cancels the read, which removes the subscription.
634
+ */
635
+ const onAbort = () => void reader.cancel(signal?.reason).catch(() => void 0);
636
+ signal?.addEventListener(`abort`, onAbort, { once: true });
547
637
  try {
638
+ if (signal?.aborted) onAbort();
548
639
  first = await reader.read();
549
640
  } catch (error) {
550
641
  reader.releaseLock();
551
642
  if (error instanceof AckTimeoutError) return null;
552
643
  throw error;
644
+ } finally {
645
+ signal?.removeEventListener(`abort`, onAbort);
553
646
  }
554
647
  if (first.done) {
555
648
  reader.releaseLock();
@@ -588,26 +681,26 @@ function createRedisAdapter(options) {
588
681
  * Kept before it is published. A producer subscribes before it reads, so it either
589
682
  * receives the message or finds the key.
590
683
  */
591
- await publisher.set(stopKey(streamId, runId), `1`, { expiration: {
684
+ await limit(publisher.set(stopKey(streamId, runId), `1`, { expiration: {
592
685
  type: `EX`,
593
686
  value: STOP_TTL_SECONDS
594
- } });
595
- await publisher.publish(stopChannel(streamId, runId), `stop`);
687
+ } }));
688
+ await limit(publisher.publish(stopChannel(streamId, runId), `stop`));
596
689
  },
597
690
  async onStopRequested({ streamId, generationId, onStop }) {
598
691
  await connect();
599
692
  const channel = stopChannel(streamId, generationId);
600
693
  const listener = () => onStop();
601
- await subscriber.subscribe(channel, listener);
694
+ await limit(subscriber.subscribe(channel, listener));
602
695
  const unsubscribe = async () => {
603
- await subscriber.unsubscribe(channel, listener);
696
+ await limit(subscriber.unsubscribe(channel, listener));
604
697
  };
605
698
  /**
606
699
  * Read only once subscribed. Reading first, or both at once, leaves a window in
607
700
  * which a stop is neither kept yet nor delivered.
608
701
  */
609
702
  try {
610
- if (await publisher.get(stopKey(streamId, generationId)) !== null) onStop();
703
+ if (await limit(publisher.get(stopKey(streamId, generationId))) !== null) onStop();
611
704
  } catch (error) {
612
705
  await unsubscribe().catch(() => {
613
706
  /** The subscription is gone with the connection */
@@ -619,4 +712,4 @@ function createRedisAdapter(options) {
619
712
  };
620
713
  }
621
714
  //#endregion
622
- export { createRedisAdapter };
715
+ export { CommandTimeoutError, createRedisAdapter };
@@ -1,4 +1,4 @@
1
- import { t as StreamAdapter } from "../../adapter-BwSsPtDm.mjs";
1
+ import { t as StreamAdapter } from "../../adapter-DZmSMkrn.mjs";
2
2
  import { S3Client } from "@aws-sdk/client-s3";
3
3
  //#region src/adapters/s3-express/adapter.d.ts
4
4
  type S3ExpressAdapterOptions = {
@@ -1,5 +1,5 @@
1
- import { n as StreamCodec } from "../adapter-BwSsPtDm.mjs";
2
- import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-t_PoYw_Z.mjs";
1
+ import { n as StreamCodec } from "../adapter-DZmSMkrn.mjs";
2
+ import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-CHVIveYo.mjs";
3
3
  import { UIMessageChunk } from "ai";
4
4
  //#region src/ai-sdk/index.d.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { t as createResumableStream } from "../core-2FBKiKXe.mjs";
1
+ import { t as createResumableStream } from "../core-DfQuMgU1.mjs";
2
2
  import { asSchema, uiMessageChunkSchema } from "ai";
3
3
  //#region src/ai-sdk/index.ts
4
4
  const schema = asSchema(uiMessageChunkSchema);
@@ -1,4 +1,4 @@
1
- import { n as StreamCodec, t as StreamAdapter } from "./adapter-BwSsPtDm.mjs";
1
+ import { n as StreamCodec, t as StreamAdapter } from "./adapter-DZmSMkrn.mjs";
2
2
  import { AsyncIterableStream } from "ai-stream-utils";
3
3
  //#region src/core.d.ts
4
4
  type StartStreamOptions = {
@@ -65,6 +65,14 @@ type ResumeStreamOptions = {
65
65
  * The generation to resume. Defaults to the one the stream id currently points at.
66
66
  */
67
67
  generationId?: string;
68
+ /**
69
+ * Ends the resume when it aborts, at any time until the stream ends. Before
70
+ * `resumeStream` returns, the promise rejects with the reason of the signal. After that,
71
+ * the returned stream errors with it, and the adapter stream is cancelled. Pass the
72
+ * signal of the incoming request, so a client that goes away frees the resume at once,
73
+ * also while the resume still waits for the first chunk.
74
+ */
75
+ signal?: AbortSignal;
68
76
  };
69
77
  type StopStreamOptions = {
70
78
  /**
@@ -96,7 +104,13 @@ type CreateResumableStreamOptions<CHUNK> = {
96
104
  adapter: StreamAdapter;
97
105
  codec: StreamCodec<CHUNK>;
98
106
  /**
99
- * Keeps the host process alive until persistence finishes. Omit on long-lived servers.
107
+ * Receives each promise of the work that runs after the stream is returned: reading the
108
+ * source, the teardown of the adapter, and the stop listener. All of them have settled
109
+ * when that work is done, and none of them rejects.
110
+ *
111
+ * On a serverless runtime, pass the `waitUntil` of the platform, so the work is not
112
+ * suspended. To close the store clients safely, collect the promises and wait for them
113
+ * before you close the clients.
100
114
  */
101
115
  waitUntil?: (promise: Promise<unknown>) => void;
102
116
  /**
@@ -19,6 +19,29 @@ async function ignoreErrors(fn) {
19
19
  } catch {}
20
20
  }
21
21
  /**
22
+ * Settles with the resume of the adapter, or rejects with the reason of the signal if it
23
+ * aborts first. A stream that the adapter returns after the abort is cancelled, so its
24
+ * subscription or its polling does not outlive the resume.
25
+ */
26
+ function abortable(pending, signal) {
27
+ return new Promise((resolve, reject) => {
28
+ const onAbort = () => {
29
+ reject(signal.reason);
30
+ pending.then((stream) => stream?.cancel(signal.reason)).catch(() => {
31
+ /** The resume failed on its own, so there is nothing to cancel */
32
+ });
33
+ };
34
+ signal.addEventListener(`abort`, onAbort, { once: true });
35
+ pending.then((stream) => {
36
+ signal.removeEventListener(`abort`, onAbort);
37
+ resolve(stream);
38
+ }, (error) => {
39
+ signal.removeEventListener(`abort`, onAbort);
40
+ reject(error);
41
+ });
42
+ });
43
+ }
44
+ /**
22
45
  * Creates a resumable stream context bound to a storage adapter and a chunk codec.
23
46
  *
24
47
  * The returned stream is drained once and fanned out to two consumers: the client
@@ -124,9 +147,11 @@ function createResumableStream(options) {
124
147
  * neither delays the client nor fails the stream. A stop requested in the meantime is
125
148
  * not lost where the adapter keeps it until the listener asks. Started only once the
126
149
  * generation is registered, so a start that is refused never touches the stop listeners
127
- * of the generation it collided with.
150
+ * of the generation it collided with. Given to `waitUntil`, because a listener that
151
+ * registers after the source ended is removed here, and the clients must stay open
152
+ * until that is done.
128
153
  */
129
- (async () => {
154
+ const listening = (async () => {
130
155
  try {
131
156
  const remove = await adapter.onStopRequested({
132
157
  streamId,
@@ -142,6 +167,7 @@ function createResumableStream(options) {
142
167
  await ignoreErrors(() => onStopSubscriptionError?.(error));
143
168
  }
144
169
  })();
170
+ waitUntil?.(listening);
145
171
  const drained = (async () => {
146
172
  try {
147
173
  while (true) {
@@ -190,16 +216,19 @@ function createResumableStream(options) {
190
216
  * the current one.
191
217
  */
192
218
  async function resumeStream(options) {
193
- const { streamId, generationId } = options;
194
- const encoded = await adapter.resumeStream(generationId === void 0 ? { streamId } : {
219
+ const { streamId, generationId, signal } = options;
220
+ signal?.throwIfAborted();
221
+ const pending = adapter.resumeStream({
195
222
  streamId,
196
- generationId
223
+ ...generationId === void 0 ? {} : { generationId },
224
+ ...signal === void 0 ? {} : { signal }
197
225
  });
226
+ const encoded = signal ? await abortable(pending, signal) : await pending;
198
227
  if (!encoded) return null;
199
228
  return createAsyncIterableStream(encoded.pipeThrough(new TransformStream({ async transform(data, controller) {
200
229
  const chunk = await codec.decode(data);
201
230
  if (chunk !== void 0) controller.enqueue(chunk);
202
- } })));
231
+ } }), signal === void 0 ? {} : { signal }));
203
232
  }
204
233
  /**
205
234
  * Asks the process producing a generation of the stream to stop: the one named by
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { n as StreamCodec, t as StreamAdapter } from "./adapter-BwSsPtDm.mjs";
2
- import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-t_PoYw_Z.mjs";
1
+ import { n as StreamCodec, t as StreamAdapter } from "./adapter-DZmSMkrn.mjs";
2
+ import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-CHVIveYo.mjs";
3
3
  export { CreateResumableStreamOptions, ResumeStreamOptions, StartStreamOptions, StartStreamResult, StopStreamOptions, type StreamAdapter, type StreamCodec, createResumableStream };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { t as createResumableStream } from "./core-2FBKiKXe.mjs";
1
+ import { t as createResumableStream } from "./core-DfQuMgU1.mjs";
2
2
  export { createResumableStream };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-resumable-stream",
3
- "version": "3.3.0",
3
+ "version": "3.4.0",
4
4
  "description": "Resume and stop AI SDK streams, backed by S3, Redis, or any store you provide",
5
5
  "keywords": [
6
6
  "ai",