ai-resumable-stream 3.2.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
@@ -200,9 +200,11 @@ The result is `null` in three cases. The library does not tell you which case ap
200
200
 
201
201
  - no stream was started with that id
202
202
  - the stream has already completed
203
- - 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
204
 
205
- If your application must know whether a stream completed or was cut off, store that information together with the message.
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.
206
+
207
+ If your application must know whether a stream completed, failed or was cut off, store that information together with the message.
206
208
 
207
209
  ### `stopStream`
208
210
 
@@ -356,7 +358,7 @@ const adapter: StreamAdapter = {
356
358
  };
357
359
  ```
358
360
 
359
- - **`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.
360
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.
361
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.
362
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.
@@ -373,6 +375,7 @@ The tests in [`src/__tests__/conformance-suite.ts`](./src/__tests__/conformance-
373
375
  - a stop also ends the stream of a client that resumed
374
376
  - a stop with a generation id only stops that generation, also when it was requested before that generation started
375
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`
376
379
 
377
380
  ## Advanced
378
381
 
@@ -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-DaFTnidy.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-DLalFjGA.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);
@@ -5,6 +5,12 @@ import { createAsyncIterableStream } from "ai-stream-utils";
5
5
  */
6
6
  const MAX_TIMEOUT_MS = 2147483647;
7
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
+ /**
8
14
  * Ignores teardown failures so they never mask the original outcome.
9
15
  */
10
16
  async function ignoreErrors(fn) {
@@ -30,14 +36,27 @@ function createResumableStream(options) {
30
36
  */
31
37
  let clientCancelled = false;
32
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
+ };
33
49
  const clientStream = new ReadableStream({
34
50
  start(controller) {
35
51
  clientController = controller;
36
52
  },
53
+ pull(controller) {
54
+ if (pendingError) controller.error(pendingError.error);
55
+ },
37
56
  cancel() {
38
57
  clientCancelled = true;
39
58
  }
40
- });
59
+ }, { highWaterMark: CLIENT_HIGH_WATER_MARK });
41
60
  /**
42
61
  * Serialized chunks for the adapter.
43
62
  */
@@ -135,12 +154,26 @@ function createResumableStream(options) {
135
154
  if (!clientCancelled) clientController.enqueue(value);
136
155
  }
137
156
  } catch (error) {
138
- adapterController.error(error);
139
- 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);
140
167
  } finally {
141
168
  reader.releaseLock();
142
- 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();
143
175
  await ignoreErrors(() => adapterController.close());
176
+ await finishing;
144
177
  await ignoreErrors(() => onFinish?.());
145
178
  }
146
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 = {
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-DaFTnidy.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-DLalFjGA.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.2.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",