ai-resumable-stream 3.1.0 → 3.2.1

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
@@ -136,6 +136,7 @@ async function sendMessage(chatId: string, messages: UIMessage[]) {
136
136
  | `streamId` | `string` | Id of the stream. Use it to resume or stop the stream. Defaults to a generated id, returned as `streamId` |
137
137
  | `generationId` | `string` | Id of this generation. Use it to resume or stop only this generation. Must be unique within the stream id. Defaults to a generated id, returned as `generationId` |
138
138
  | `abortController` | `AbortController` | Aborted when the stream is stopped. Created by the library if you do not pass one |
139
+ | `stopTimeoutMs` | `number` | Time that a stop waits for the source to end before it cancels the source. Defaults to `1000` with a supplied `abortController`, `0` without one |
139
140
  | `onStopSubscriptionError` | `(error: unknown) => void` | Called when the subscription to stop requests fails. The stream continues, but it cannot be stopped |
140
141
  | `onFinish` | `() => void \| Promise<void>` | Called after the source stream has ended, also after an error or a stop. Errors thrown by the callback are ignored |
141
142
 
@@ -158,6 +159,24 @@ await context.startStream(toUIMessageStream({ stream: result.stream }), {
158
159
 
159
160
  We recommend that you pass your own `abortController` and give its signal to `streamText`. A stop then aborts the request to the provider directly, and the AI SDK emits its `abort` chunk and calls `onAbort`. Without it, a stop only cancels the source stream, and the cancellation must propagate back to `streamText`.
160
161
 
162
+ #### Stop timeout
163
+
164
+ A stop aborts the `abortController` and waits up to `stopTimeoutMs` for the source to end. This lets `streamText` emit its `abort` chunk, so `onEnd` and `onFinish` get `isAborted: true`. A source that does not end in time is cancelled.
165
+
166
+ With `stopTimeoutMs: 0`, or without an `abortController`, a stop cancels the source immediately and `isAborted` is `false`.
167
+
168
+ ```ts
169
+ const abortController = new AbortController();
170
+ const result = streamText({ model, messages, abortSignal: abortController.signal });
171
+ const source = toUIMessageStream({
172
+ stream: result.stream,
173
+ onFinish: ({ isAborted, responseMessage }) => {
174
+ // `isAborted` is `true` after a stop
175
+ },
176
+ });
177
+ await context.startStream(source, { streamId, abortController });
178
+ ```
179
+
161
180
  ### `resumeStream`
162
181
 
163
182
  Resumes an existing stream. The returned stream first replays all chunks produced so far and then continues with the new chunks. Pass `generationId` to resume a specific generation. Omit it to resume the current generation of the stream id. Returns `null` when there is nothing to resume.
@@ -181,9 +200,11 @@ The result is `null` in three cases. The library does not tell you which case ap
181
200
 
182
201
  - no stream was started with that id
183
202
  - the stream has already completed
184
- - the producer died or was stopped before the stream completed
203
+ - the source stream failed, the producer died, or the stream was stopped before it completed
204
+
205
+ If the source stream fails, only the client that started the stream receives the error. A client that resumes while the stream is running receives the chunks produced before the failure, and then its stream ends without an error. After that, a resume returns `null`, the same as for a completed stream.
185
206
 
186
- If your application must know whether a stream completed or was cut off, store that information together with the message.
207
+ If your application must know whether a stream completed, failed or was cut off, store that information together with the message.
187
208
 
188
209
  ### `stopStream`
189
210
 
@@ -337,7 +358,7 @@ const adapter: StreamAdapter = {
337
358
  };
338
359
  ```
339
360
 
340
- - **`createStream`** is called 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 returned promise resolves as soon as the stream can be resumed, not when it is complete.
361
+ - **`createStream`** is called 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.
341
362
  - **`resumeStream`** is called 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.
342
363
  - **`requestStop`** is called by 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.
343
364
  - **`onStopRequested`** is called by 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.
@@ -354,6 +375,7 @@ The tests in [`src/__tests__/conformance-suite.ts`](./src/__tests__/conformance-
354
375
  - a stop also ends the stream of a client that resumed
355
376
  - a stop with a generation id only stops that generation, also when it was requested before that generation started
356
377
  - an older generation can be resumed while a newer generation is current
378
+ - when the source stream fails, a client that resumed receives the chunks produced before the failure and then a clean end, and a later resume returns `null`
357
379
 
358
380
  ## Advanced
359
381
 
@@ -504,6 +526,7 @@ type StartStreamOptions = {
504
526
  streamId?: string;
505
527
  generationId?: string;
506
528
  abortController?: AbortController;
529
+ stopTimeoutMs?: number;
507
530
  onStopSubscriptionError?: (error: unknown) => void;
508
531
  onFinish?: () => void | Promise<void>;
509
532
  };
@@ -8,7 +8,8 @@
8
8
  type StreamAdapter = {
9
9
  /**
10
10
  * Discards any state left over from a previous stream with the same id, registers
11
- * the id, and begins consuming `chunks` in the background.
11
+ * the id, and begins consuming `chunks` in the background. `chunks` ends cleanly
12
+ * also when the source fails: a failed stream is over like a completed one.
12
13
  *
13
14
  * Resolves once the stream is registered and resumable, not once it is complete.
14
15
  * A stream id may be reused, so implementations must not replay stale chunks.
@@ -1,4 +1,4 @@
1
- import { t as StreamAdapter } from "../../adapter-CTz0z2k0.mjs";
1
+ import { t as StreamAdapter } from "../../adapter-BwSsPtDm.mjs";
2
2
  import { Publisher, Subscriber } from "resumable-stream";
3
3
  //#region src/adapters/redis/adapter.d.ts
4
4
  /**
@@ -63,6 +63,9 @@ const DELETE_IF_EQUAL_SCRIPT = `if redis.call("GET", KEYS[1]) == ARGV[1] then re
63
63
  const STOP_TTL_SECONDS = 3600;
64
64
  /**
65
65
  * Raised by `resumable-stream` when a producer stops answering resume requests.
66
+ *
67
+ * TODO(#21): the timer that raises it can end without settling the resume, so a resume
68
+ * of a dead producer can wait forever instead of failing with this message.
66
69
  */
67
70
  const ACK_TIMEOUT_MESSAGE = `Timeout waiting for ack`;
68
71
  function isAckTimeout(error) {
@@ -152,6 +155,11 @@ function createRedisAdapter(options) {
152
155
  * The pointer is dropped as soon as the source ends, so a resume that arrives
153
156
  * during teardown is told there is nothing to resume rather than racing it. The
154
157
  * stop goes with it: a generation that is over has nothing left to stop.
158
+ *
159
+ * `chunks` ends cleanly also when the source fails. This matters here, because
160
+ * `resumable-stream` reads its source without a rejection handler: a failed stream
161
+ * would be an unhandled rejection, which ends a Node process, and the generation
162
+ * would never be marked done.
155
163
  */
156
164
  const sse = chunks.pipeThrough(chunksToSSE()).pipeThrough(new TransformStream({ async flush() {
157
165
  await Promise.all([clearPointer(streamId, generationId), clearStop(streamId, runId)]).catch(() => {
@@ -169,7 +177,20 @@ function createRedisAdapter(options) {
169
177
  */
170
178
  const generationId = runId === void 0 ? await readPointer(streamId) : generationName(streamId, runId);
171
179
  if (!generationId) return null;
172
- const sse = await createContext().resumeExistingStream(generationId);
180
+ /**
181
+ * A producer that died without marking its generation done never answers, and
182
+ * `resumable-stream` rejects after waiting for it. There is nothing to resume.
183
+ *
184
+ * TODO(#21): bound this call with a time limit of our own, because the upstream
185
+ * timeout does not always settle.
186
+ */
187
+ let sse;
188
+ try {
189
+ sse = await createContext().resumeExistingStream(generationId);
190
+ } catch (error) {
191
+ if (isAckTimeout(error)) return null;
192
+ throw error;
193
+ }
173
194
  if (!sse) return null;
174
195
  const reader = sse.pipeThrough(sseToChunks()).getReader();
175
196
  /**
@@ -1,4 +1,4 @@
1
- import { t as StreamAdapter } from "../../adapter-CTz0z2k0.mjs";
1
+ import { t as StreamAdapter } from "../../adapter-BwSsPtDm.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-CTz0z2k0.mjs";
2
- import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-DmhblcmG.mjs";
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";
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-DAlVpiTc.mjs";
1
+ import { t as createResumableStream } from "../core-2FBKiKXe.mjs";
2
2
  import { asSchema, uiMessageChunkSchema } from "ai";
3
3
  //#region src/ai-sdk/index.ts
4
4
  const schema = asSchema(uiMessageChunkSchema);
@@ -1,6 +1,16 @@
1
1
  import { createAsyncIterableStream } from "ai-stream-utils";
2
2
  //#region src/core.ts
3
3
  /**
4
+ * The longest delay a timer accepts. A longer one fires almost immediately instead.
5
+ */
6
+ const MAX_TIMEOUT_MS = 2147483647;
7
+ /**
8
+ * The queue size at which the client stream asks for no more chunks. Set explicitly
9
+ * because it also tells whether chunks are still queued: the desired size is below it
10
+ * exactly while the queue holds a chunk.
11
+ */
12
+ const CLIENT_HIGH_WATER_MARK = 1;
13
+ /**
4
14
  * Ignores teardown failures so they never mask the original outcome.
5
15
  */
6
16
  async function ignoreErrors(fn) {
@@ -18,21 +28,35 @@ async function ignoreErrors(fn) {
18
28
  function createResumableStream(options) {
19
29
  const { adapter, codec, waitUntil, generateId = () => crypto.randomUUID() } = options;
20
30
  async function startStream(source, startOptions = {}) {
21
- const { streamId = generateId(), generationId = generateId(), abortController = new AbortController(), onFinish, onStopSubscriptionError } = startOptions;
31
+ const { streamId = generateId(), generationId = generateId(), abortController: suppliedController, stopTimeoutMs = suppliedController ? 1e3 : 0, onFinish, onStopSubscriptionError } = startOptions;
32
+ const abortController = suppliedController ?? new AbortController();
22
33
  /**
23
34
  * Chunks for the client, exactly as produced. Cancelling stops the client fan-out
24
35
  * but leaves the drain loop running so the adapter still receives every chunk.
25
36
  */
26
37
  let clientCancelled = false;
27
38
  let clientController;
39
+ /**
40
+ * A source failure held back until the client has read the chunks before it, because
41
+ * erroring a stream discards the chunks still queued in it. Reported on the next pull,
42
+ * which only happens once the queue is empty.
43
+ */
44
+ let pendingError;
45
+ const failClient = (error) => {
46
+ if ((clientController.desiredSize ?? 0) < CLIENT_HIGH_WATER_MARK) pendingError = { error };
47
+ else clientController.error(error);
48
+ };
28
49
  const clientStream = new ReadableStream({
29
50
  start(controller) {
30
51
  clientController = controller;
31
52
  },
53
+ pull(controller) {
54
+ if (pendingError) controller.error(pendingError.error);
55
+ },
32
56
  cancel() {
33
57
  clientCancelled = true;
34
58
  }
35
- });
59
+ }, { highWaterMark: CLIENT_HIGH_WATER_MARK });
36
60
  /**
37
61
  * Serialized chunks for the adapter.
38
62
  */
@@ -46,14 +70,25 @@ function createResumableStream(options) {
46
70
  const reader = source.getReader();
47
71
  /**
48
72
  * Cancelling the source resolves any pending read as done, which ends the drain
49
- * loop, and propagates upstream so the producer stops doing work. Registered before
50
- * anything can request a stop, so an early stop is not missed.
73
+ * loop, and propagates upstream so the producer stops doing work. Deferred by
74
+ * `stopTimeoutMs`, so a producer that observes the signal can end its stream first and
75
+ * the chunks that report the stop are still drained. Registered before anything can
76
+ * request a stop, so an early stop is not missed.
51
77
  */
52
- const onAbort = () => {
78
+ let cancelTimer;
79
+ const cancelSource = () => {
53
80
  reader.cancel().catch(() => {
54
81
  /** The source is already gone */
55
82
  });
56
83
  };
84
+ const onAbort = () => {
85
+ if (stopTimeoutMs <= 0) {
86
+ cancelSource();
87
+ return;
88
+ }
89
+ if (stopTimeoutMs > MAX_TIMEOUT_MS) return;
90
+ cancelTimer = setTimeout(cancelSource, stopTimeoutMs);
91
+ };
57
92
  abortController.signal.addEventListener(`abort`, onAbort, { once: true });
58
93
  /**
59
94
  * Set once the source has ended, after which a stop has nothing left to abort and a
@@ -66,6 +101,7 @@ function createResumableStream(options) {
66
101
  */
67
102
  async function finish() {
68
103
  finished = true;
104
+ clearTimeout(cancelTimer);
69
105
  abortController.signal.removeEventListener(`abort`, onAbort);
70
106
  const remove = unsubscribe;
71
107
  unsubscribe = void 0;
@@ -118,12 +154,26 @@ function createResumableStream(options) {
118
154
  if (!clientCancelled) clientController.enqueue(value);
119
155
  }
120
156
  } catch (error) {
121
- adapterController.error(error);
122
- if (!clientCancelled) clientController.error(error);
157
+ /**
158
+ * Only the client that started the stream is told about the failure. The adapter
159
+ * sees a clean end, so it marks the generation finished exactly as it does for a
160
+ * completed or stopped one: a resumer gets the chunks produced so far, and nothing
161
+ * once the generation is over, instead of a generation left marked as running.
162
+ * Adapters rely on this: one that hands its chunks to a library which cannot handle
163
+ * a failed stream would otherwise leave an unhandled rejection, which ends a Node
164
+ * process.
165
+ */
166
+ if (!clientCancelled) failClient(error);
123
167
  } finally {
124
168
  reader.releaseLock();
125
- await finish();
169
+ /**
170
+ * The adapter is told the stream is over before the stop listener is removed, so
171
+ * a store that is slow to unsubscribe cannot keep the generation marked running.
172
+ * Stops are ignored from here on, because the source has ended.
173
+ */
174
+ const finishing = finish();
126
175
  await ignoreErrors(() => adapterController.close());
176
+ await finishing;
127
177
  await ignoreErrors(() => onFinish?.());
128
178
  }
129
179
  })();
@@ -1,4 +1,4 @@
1
- import { n as StreamCodec, t as StreamAdapter } from "./adapter-CTz0z2k0.mjs";
1
+ import { n as StreamCodec, t as StreamAdapter } from "./adapter-BwSsPtDm.mjs";
2
2
  import { AsyncIterableStream } from "ai-stream-utils";
3
3
  //#region src/core.d.ts
4
4
  type StartStreamOptions = {
@@ -28,6 +28,23 @@ type StartStreamOptions = {
28
28
  * of relying on stream cancellation propagating upstream.
29
29
  */
30
30
  abortController?: AbortController;
31
+ /**
32
+ * How long a stop waits for the source to end on its own before it cancels the source.
33
+ * Defaults to `1_000` when an `abortController` is supplied, and to `0` otherwise, since
34
+ * a controller created here has no other listener that could end the source.
35
+ *
36
+ * A producer that observes the signal ends its stream itself, and the chunks it emits
37
+ * while doing so still reach the client and the adapter. For `streamText` that is the
38
+ * `abort` chunk, which is what makes `isAborted` true in the UI message stream's
39
+ * `onEnd`/`onFinish`: cancelling first ends that stream before the chunk arrives. A
40
+ * source that ignores the signal, or hangs, is cancelled once the time runs out, so it
41
+ * may produce chunks for that long after the stop. `0` cancels the source immediately.
42
+ *
43
+ * Must be longer than the work a producer does before it ends its stream, for `streamText`
44
+ * the `onAbort` callbacks it awaits before it emits the `abort` chunk. Values longer than a
45
+ * timer can hold, such as `Infinity`, never cancel the source.
46
+ */
47
+ stopTimeoutMs?: number;
31
48
  /**
32
49
  * Called when listening for stop requests fails. The stream is unaffected, but it
33
50
  * cannot be stopped. Errors thrown by the callback are ignored.
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { n as StreamCodec, t as StreamAdapter } from "./adapter-CTz0z2k0.mjs";
2
- import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-DmhblcmG.mjs";
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";
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-DAlVpiTc.mjs";
1
+ import { t as createResumableStream } from "./core-2FBKiKXe.mjs";
2
2
  export { createResumableStream };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-resumable-stream",
3
- "version": "3.1.0",
3
+ "version": "3.2.1",
4
4
  "description": "Resume and stop AI SDK streams, backed by S3, Redis, or any store you provide",
5
5
  "keywords": [
6
6
  "ai",