ai-resumable-stream 3.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.
@@ -18,11 +18,7 @@ async function ignoreErrors(fn) {
18
18
  function createResumableStream(options) {
19
19
  const { adapter, codec, waitUntil, generateId = () => crypto.randomUUID() } = options;
20
20
  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
- });
21
+ const { streamId = generateId(), generationId = generateId(), abortController = new AbortController(), onFinish, onStopSubscriptionError } = startOptions;
26
22
  /**
27
23
  * Chunks for the client, exactly as produced. Cancelling stops the client fan-out
28
24
  * but leaves the drain loop running so the adapter still receives every chunk.
@@ -48,26 +44,68 @@ function createResumableStream(options) {
48
44
  * Acquired before registration so a locked source fails before any state is written.
49
45
  */
50
46
  const reader = source.getReader();
47
+ /**
48
+ * 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.
51
+ */
52
+ const onAbort = () => {
53
+ reader.cancel().catch(() => {
54
+ /** The source is already gone */
55
+ });
56
+ };
57
+ abortController.signal.addEventListener(`abort`, onAbort, { once: true });
58
+ /**
59
+ * Set once the source has ended, after which a stop has nothing left to abort and a
60
+ * subscription has nothing left to guard.
61
+ */
62
+ let finished = false;
63
+ let unsubscribe;
64
+ /**
65
+ * Stops listening, now or as soon as the listener is registered.
66
+ */
67
+ async function finish() {
68
+ finished = true;
69
+ abortController.signal.removeEventListener(`abort`, onAbort);
70
+ const remove = unsubscribe;
71
+ unsubscribe = void 0;
72
+ if (remove) await ignoreErrors(remove);
73
+ }
51
74
  try {
52
75
  await adapter.createStream({
53
76
  streamId,
77
+ generationId,
54
78
  chunks: adapterStream,
55
79
  waitUntil
56
80
  });
57
81
  } catch (error) {
58
82
  reader.releaseLock();
59
- await ignoreErrors(unsubscribe);
83
+ await finish();
60
84
  throw error;
61
85
  }
62
86
  /**
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.
87
+ * Listening for stops is best effort and never awaited, so a slow or failing store
88
+ * neither delays the client nor fails the stream. A stop requested in the meantime is
89
+ * not lost where the adapter keeps it until the listener asks. Started only once the
90
+ * generation is registered, so a start that is refused never touches the stop listeners
91
+ * of the generation it collided with.
65
92
  */
66
- abortController.signal.addEventListener(`abort`, () => {
67
- reader.cancel().catch(() => {
68
- /** The source is already gone */
69
- });
70
- }, { once: true });
93
+ (async () => {
94
+ try {
95
+ const remove = await adapter.onStopRequested({
96
+ streamId,
97
+ generationId,
98
+ onStop: () => {
99
+ if (!finished) abortController.abort();
100
+ }
101
+ });
102
+ /** The source ended first, so the listener must not outlive it. */
103
+ if (finished) await ignoreErrors(remove);
104
+ else unsubscribe = remove;
105
+ } catch (error) {
106
+ await ignoreErrors(() => onStopSubscriptionError?.(error));
107
+ }
108
+ })();
71
109
  const drained = (async () => {
72
110
  try {
73
111
  while (true) {
@@ -84,7 +122,7 @@ function createResumableStream(options) {
84
122
  if (!clientCancelled) clientController.error(error);
85
123
  } finally {
86
124
  reader.releaseLock();
87
- await ignoreErrors(unsubscribe);
125
+ await finish();
88
126
  await ignoreErrors(() => adapterController.close());
89
127
  await ignoreErrors(() => onFinish?.());
90
128
  }
@@ -92,15 +130,21 @@ function createResumableStream(options) {
92
130
  waitUntil?.(drained);
93
131
  return {
94
132
  streamId,
133
+ generationId,
95
134
  stream: createAsyncIterableStream(clientStream)
96
135
  };
97
136
  }
98
137
  /**
99
138
  * Returns the chunks of an in-flight stream, starting from the first one it produced,
100
- * or `null` when there is nothing to resume.
139
+ * or `null` when there is nothing to resume: the generation named by `generationId`, or
140
+ * the current one.
101
141
  */
102
142
  async function resumeStream(options) {
103
- const encoded = await adapter.resumeStream({ streamId: options.streamId });
143
+ const { streamId, generationId } = options;
144
+ const encoded = await adapter.resumeStream(generationId === void 0 ? { streamId } : {
145
+ streamId,
146
+ generationId
147
+ });
104
148
  if (!encoded) return null;
105
149
  return createAsyncIterableStream(encoded.pipeThrough(new TransformStream({ async transform(data, controller) {
106
150
  const chunk = await codec.decode(data);
@@ -108,11 +152,16 @@ function createResumableStream(options) {
108
152
  } })));
109
153
  }
110
154
  /**
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.
155
+ * Asks the process producing a generation of the stream to stop: the one named by
156
+ * `generationId`, or the current one. Resolves once the request is recorded, which may
157
+ * be before the producer has observed it.
113
158
  */
114
159
  async function stopStream(options) {
115
- await adapter.requestStop({ streamId: options.streamId });
160
+ const { streamId, generationId } = options;
161
+ await adapter.requestStop(generationId === void 0 ? { streamId } : {
162
+ streamId,
163
+ generationId
164
+ });
116
165
  }
117
166
  return {
118
167
  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,11 @@ type StartStreamOptions = {
19
28
  * of relying on stream cancellation propagating upstream.
20
29
  */
21
30
  abortController?: AbortController;
31
+ /**
32
+ * Called when listening for stop requests fails. The stream is unaffected, but it
33
+ * cannot be stopped. Errors thrown by the callback are ignored.
34
+ */
35
+ onStopSubscriptionError?: (error: unknown) => void;
22
36
  /**
23
37
  * Called once the source has ended and the adapter has been told the stream is
24
38
  * complete. Runs on every exit path, including errors and stops. Errors are ignored.
@@ -30,12 +44,20 @@ type ResumeStreamOptions = {
30
44
  * The id the stream was started under.
31
45
  */
32
46
  streamId: string;
47
+ /**
48
+ * The generation to resume. Defaults to the one the stream id currently points at.
49
+ */
50
+ generationId?: string;
33
51
  };
34
52
  type StopStreamOptions = {
35
53
  /**
36
54
  * The id of the stream to stop.
37
55
  */
38
56
  streamId: string;
57
+ /**
58
+ * The generation to stop. Defaults to the one the stream id currently points at.
59
+ */
60
+ generationId?: string;
39
61
  };
40
62
  type StartStreamResult<CHUNK> = {
41
63
  /**
@@ -43,7 +65,12 @@ type StartStreamResult<CHUNK> = {
43
65
  */
44
66
  streamId: string;
45
67
  /**
46
- * The chunks, for the client that started the stream. Cancelling it does not stop
68
+ * The id of this generation, whether supplied or generated. Pass it to `resumeStream` or
69
+ * `stopStream` to address this generation and no other.
70
+ */
71
+ generationId: string;
72
+ /**
73
+ * The chunks, for the client that started it. Cancelling it does not stop
47
74
  * persistence, so a disconnected client can still resume.
48
75
  */
49
76
  stream: AsyncIterableStream<CHUNK>;
@@ -56,7 +83,11 @@ type CreateResumableStreamOptions<CHUNK> = {
56
83
  */
57
84
  waitUntil?: (promise: Promise<unknown>) => void;
58
85
  /**
59
- * Generates a stream id when `startStream` is not given one.
86
+ * Generates a stream id or a generation id when `startStream` is not given one.
87
+ * Defaults to `crypto.randomUUID`.
88
+ *
89
+ * Must return an id that has not been used before: two generations of a stream id can
90
+ * never share a generation id.
60
91
  */
61
92
  generateId?: () => string;
62
93
  };
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-DmhblcmG.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-DAlVpiTc.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.1.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",