ai-resumable-stream 3.0.0 → 3.2.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.
@@ -1,6 +1,10 @@
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
+ /**
4
8
  * Ignores teardown failures so they never mask the original outcome.
5
9
  */
6
10
  async function ignoreErrors(fn) {
@@ -18,11 +22,8 @@ async function ignoreErrors(fn) {
18
22
  function createResumableStream(options) {
19
23
  const { adapter, codec, waitUntil, generateId = () => crypto.randomUUID() } = options;
20
24
  async function startStream(source, startOptions = {}) {
21
- const { streamId = generateId(), abortController = new AbortController(), onFinish } = startOptions;
22
- const unsubscribe = await adapter.onStopRequested({
23
- streamId,
24
- onStop: () => abortController.abort()
25
- });
25
+ const { streamId = generateId(), generationId = generateId(), abortController: suppliedController, stopTimeoutMs = suppliedController ? 1e3 : 0, onFinish, onStopSubscriptionError } = startOptions;
26
+ const abortController = suppliedController ?? new AbortController();
26
27
  /**
27
28
  * Chunks for the client, exactly as produced. Cancelling stops the client fan-out
28
29
  * but leaves the drain loop running so the adapter still receives every chunk.
@@ -48,26 +49,80 @@ function createResumableStream(options) {
48
49
  * Acquired before registration so a locked source fails before any state is written.
49
50
  */
50
51
  const reader = source.getReader();
52
+ /**
53
+ * Cancelling the source resolves any pending read as done, which ends the drain
54
+ * loop, and propagates upstream so the producer stops doing work. Deferred by
55
+ * `stopTimeoutMs`, so a producer that observes the signal can end its stream first and
56
+ * the chunks that report the stop are still drained. Registered before anything can
57
+ * request a stop, so an early stop is not missed.
58
+ */
59
+ let cancelTimer;
60
+ const cancelSource = () => {
61
+ reader.cancel().catch(() => {
62
+ /** The source is already gone */
63
+ });
64
+ };
65
+ const onAbort = () => {
66
+ if (stopTimeoutMs <= 0) {
67
+ cancelSource();
68
+ return;
69
+ }
70
+ if (stopTimeoutMs > MAX_TIMEOUT_MS) return;
71
+ cancelTimer = setTimeout(cancelSource, stopTimeoutMs);
72
+ };
73
+ abortController.signal.addEventListener(`abort`, onAbort, { once: true });
74
+ /**
75
+ * Set once the source has ended, after which a stop has nothing left to abort and a
76
+ * subscription has nothing left to guard.
77
+ */
78
+ let finished = false;
79
+ let unsubscribe;
80
+ /**
81
+ * Stops listening, now or as soon as the listener is registered.
82
+ */
83
+ async function finish() {
84
+ finished = true;
85
+ clearTimeout(cancelTimer);
86
+ abortController.signal.removeEventListener(`abort`, onAbort);
87
+ const remove = unsubscribe;
88
+ unsubscribe = void 0;
89
+ if (remove) await ignoreErrors(remove);
90
+ }
51
91
  try {
52
92
  await adapter.createStream({
53
93
  streamId,
94
+ generationId,
54
95
  chunks: adapterStream,
55
96
  waitUntil
56
97
  });
57
98
  } catch (error) {
58
99
  reader.releaseLock();
59
- await ignoreErrors(unsubscribe);
100
+ await finish();
60
101
  throw error;
61
102
  }
62
103
  /**
63
- * Cancelling the source resolves any pending read as done, which ends the drain
64
- * loop, and propagates upstream so the producer stops doing work.
104
+ * Listening for stops is best effort and never awaited, so a slow or failing store
105
+ * neither delays the client nor fails the stream. A stop requested in the meantime is
106
+ * not lost where the adapter keeps it until the listener asks. Started only once the
107
+ * generation is registered, so a start that is refused never touches the stop listeners
108
+ * of the generation it collided with.
65
109
  */
66
- abortController.signal.addEventListener(`abort`, () => {
67
- reader.cancel().catch(() => {
68
- /** The source is already gone */
69
- });
70
- }, { once: true });
110
+ (async () => {
111
+ try {
112
+ const remove = await adapter.onStopRequested({
113
+ streamId,
114
+ generationId,
115
+ onStop: () => {
116
+ if (!finished) abortController.abort();
117
+ }
118
+ });
119
+ /** The source ended first, so the listener must not outlive it. */
120
+ if (finished) await ignoreErrors(remove);
121
+ else unsubscribe = remove;
122
+ } catch (error) {
123
+ await ignoreErrors(() => onStopSubscriptionError?.(error));
124
+ }
125
+ })();
71
126
  const drained = (async () => {
72
127
  try {
73
128
  while (true) {
@@ -84,7 +139,7 @@ function createResumableStream(options) {
84
139
  if (!clientCancelled) clientController.error(error);
85
140
  } finally {
86
141
  reader.releaseLock();
87
- await ignoreErrors(unsubscribe);
142
+ await finish();
88
143
  await ignoreErrors(() => adapterController.close());
89
144
  await ignoreErrors(() => onFinish?.());
90
145
  }
@@ -92,15 +147,21 @@ function createResumableStream(options) {
92
147
  waitUntil?.(drained);
93
148
  return {
94
149
  streamId,
150
+ generationId,
95
151
  stream: createAsyncIterableStream(clientStream)
96
152
  };
97
153
  }
98
154
  /**
99
155
  * Returns the chunks of an in-flight stream, starting from the first one it produced,
100
- * or `null` when there is nothing to resume.
156
+ * or `null` when there is nothing to resume: the generation named by `generationId`, or
157
+ * the current one.
101
158
  */
102
159
  async function resumeStream(options) {
103
- const encoded = await adapter.resumeStream({ streamId: options.streamId });
160
+ const { streamId, generationId } = options;
161
+ const encoded = await adapter.resumeStream(generationId === void 0 ? { streamId } : {
162
+ streamId,
163
+ generationId
164
+ });
104
165
  if (!encoded) return null;
105
166
  return createAsyncIterableStream(encoded.pipeThrough(new TransformStream({ async transform(data, controller) {
106
167
  const chunk = await codec.decode(data);
@@ -108,11 +169,16 @@ function createResumableStream(options) {
108
169
  } })));
109
170
  }
110
171
  /**
111
- * Asks the process producing the stream to stop. Resolves once the request is
112
- * recorded, which may be before the producer has observed it.
172
+ * Asks the process producing a generation of the stream to stop: the one named by
173
+ * `generationId`, or the current one. Resolves once the request is recorded, which may
174
+ * be before the producer has observed it.
113
175
  */
114
176
  async function stopStream(options) {
115
- await adapter.requestStop({ streamId: options.streamId });
177
+ const { streamId, generationId } = options;
178
+ await adapter.requestStop(generationId === void 0 ? { streamId } : {
179
+ streamId,
180
+ generationId
181
+ });
116
182
  }
117
183
  return {
118
184
  startStream,
@@ -1,4 +1,4 @@
1
- import { n as StreamCodec, t as StreamAdapter } from "./adapter-D9qrs60B.mjs";
1
+ import { n as StreamCodec, t as StreamAdapter } from "./adapter-CTz0z2k0.mjs";
2
2
  import { AsyncIterableStream } from "ai-stream-utils";
3
3
  //#region src/core.d.ts
4
4
  type StartStreamOptions = {
@@ -10,6 +10,15 @@ type StartStreamOptions = {
10
10
  * to track a separate pointer. Reusing an id discards the previous stream's chunks.
11
11
  */
12
12
  streamId?: string;
13
+ /**
14
+ * Identifies this generation of the stream id, so it can be resumed and stopped on its
15
+ * own, even after a newer generation of the same stream id has started. Defaults to a
16
+ * generated id, returned as `generationId`.
17
+ *
18
+ * Names exactly one generation, so an id is never used for a second generation of the
19
+ * same stream id: a resume or a stop kept for it reaches the generation that holds it.
20
+ */
21
+ generationId?: string;
13
22
  /**
14
23
  * The controller aborted when the stream is stopped. Created if not supplied, so a
15
24
  * stream is always stoppable.
@@ -19,6 +28,28 @@ type StartStreamOptions = {
19
28
  * of relying on stream cancellation propagating upstream.
20
29
  */
21
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;
48
+ /**
49
+ * Called when listening for stop requests fails. The stream is unaffected, but it
50
+ * cannot be stopped. Errors thrown by the callback are ignored.
51
+ */
52
+ onStopSubscriptionError?: (error: unknown) => void;
22
53
  /**
23
54
  * Called once the source has ended and the adapter has been told the stream is
24
55
  * complete. Runs on every exit path, including errors and stops. Errors are ignored.
@@ -30,12 +61,20 @@ type ResumeStreamOptions = {
30
61
  * The id the stream was started under.
31
62
  */
32
63
  streamId: string;
64
+ /**
65
+ * The generation to resume. Defaults to the one the stream id currently points at.
66
+ */
67
+ generationId?: string;
33
68
  };
34
69
  type StopStreamOptions = {
35
70
  /**
36
71
  * The id of the stream to stop.
37
72
  */
38
73
  streamId: string;
74
+ /**
75
+ * The generation to stop. Defaults to the one the stream id currently points at.
76
+ */
77
+ generationId?: string;
39
78
  };
40
79
  type StartStreamResult<CHUNK> = {
41
80
  /**
@@ -43,7 +82,12 @@ type StartStreamResult<CHUNK> = {
43
82
  */
44
83
  streamId: string;
45
84
  /**
46
- * The chunks, for the client that started the stream. Cancelling it does not stop
85
+ * The id of this generation, whether supplied or generated. Pass it to `resumeStream` or
86
+ * `stopStream` to address this generation and no other.
87
+ */
88
+ generationId: string;
89
+ /**
90
+ * The chunks, for the client that started it. Cancelling it does not stop
47
91
  * persistence, so a disconnected client can still resume.
48
92
  */
49
93
  stream: AsyncIterableStream<CHUNK>;
@@ -56,7 +100,11 @@ type CreateResumableStreamOptions<CHUNK> = {
56
100
  */
57
101
  waitUntil?: (promise: Promise<unknown>) => void;
58
102
  /**
59
- * Generates a stream id when `startStream` is not given one.
103
+ * Generates a stream id or a generation id when `startStream` is not given one.
104
+ * Defaults to `crypto.randomUUID`.
105
+ *
106
+ * Must return an id that has not been used before: two generations of a stream id can
107
+ * never share a generation id.
60
108
  */
61
109
  generateId?: () => string;
62
110
  };
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { n as StreamCodec, t as StreamAdapter } from "./adapter-D9qrs60B.mjs";
2
- import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-CE_FvT5z.mjs";
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";
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-BteCDwPY.mjs";
1
+ import { t as createResumableStream } from "./core-DLalFjGA.mjs";
2
2
  export { createResumableStream };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-resumable-stream",
3
- "version": "3.0.0",
3
+ "version": "3.2.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",