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.
package/README.md CHANGED
@@ -9,17 +9,17 @@
9
9
 
10
10
  </div>
11
11
 
12
- This library provides resumable streaming for UI message streams created by [`streamText()`](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text) in the AI SDK. Chunks are persisted as they are produced, allowing clients to resume interrupted streams or stop active streams from anywhere.
12
+ This library provides resumable streaming for UI message streams created by [`streamText()`](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text) in the AI SDK. The library stores chunks as they are produced. Clients can then resume an interrupted stream, and any request can stop an active stream.
13
13
 
14
- Where the chunks go is your choice. Two adapters ship; a third is four methods.
14
+ You choose where the chunks are stored. The library includes adapters for Redis and S3 Express. You can also write your own adapter by implementing four methods.
15
15
 
16
16
  **Why?**
17
17
 
18
- Streams are ephemeral. Once data flows through, it is gone. That creates two hard problems.
18
+ A stream does not keep its data. After a chunk is sent, it is gone. This causes two problems.
19
19
 
20
- **Resume is hard** because the server does not track what it has sent. A client that disconnects (network drop, page reload, tab switch) loses everything that arrived while it was away, while the stream keeps running on the server. When reconnecting, there's no way to replay missed chunks without persisting them somewhere.
20
+ **Resume:** The server does not record which chunks it has sent. When a client disconnects (network drop, page reload, tab switch), the stream continues on the server, but the client misses the chunks that are sent during that time. The server can only replay the missed chunks if they are stored somewhere.
21
21
 
22
- **Stop is hard** because the client requesting "stop" is not the request that started the stream. The user clicks "Stop generating", which fires a new HTTP request, but the original stream is running in a different request/process. Without a central coordination point, you can't signal across requests.
22
+ **Stop:** The request that stops a stream is not the request that started it. When the user clicks "Stop generating", the client sends a new HTTP request, but the stream runs in a different request or process. The two requests need a shared place to pass the stop signal.
23
23
 
24
24
  ## Install
25
25
 
@@ -27,7 +27,7 @@ Streams are ephemeral. Once data flows through, it is gone. That creates two har
27
27
  npm install ai-resumable-stream
28
28
  ```
29
29
 
30
- Optional peer dependencies, one per feature you use:
30
+ Install the optional peer dependencies for the features you use:
31
31
 
32
32
  | Package | Needed for |
33
33
  | -------------------- | ----------------------------------------- |
@@ -39,7 +39,7 @@ Optional peer dependencies, one per feature you use:
39
39
  > Version compatibility:
40
40
  >
41
41
  > - Use [`ai-resumable-stream@1.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v1.x) for AI SDK v6
42
- > - Use [`ai-resumable-stream@2.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v2.x) and later for AI SDK v7
42
+ > - Use [`ai-resumable-stream@2.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v2.x) or [`ai-resumable-stream@3.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v3.x) and later for AI SDK v7
43
43
 
44
44
  ## Quick start
45
45
 
@@ -62,28 +62,47 @@ const context = createResumableUIMessageStream({
62
62
  });
63
63
  ```
64
64
 
65
- Then wire three routes.
65
+ Then use the context in your three routes:
66
66
 
67
67
  ```ts
68
+ import { streamText, toUIMessageStream, type UIMessage } from "ai";
69
+
68
70
  // POST /chat/:chatId
69
- const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
70
- streamId: chatId,
71
- });
72
- return stream;
71
+ export async function send(chatId: string, messages: Array<UIMessage>) {
72
+ const abortController = new AbortController();
73
+
74
+ const result = streamText({
75
+ model: openai(`gpt-4o`),
76
+ messages,
77
+ abortSignal: abortController.signal,
78
+ });
79
+
80
+ const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
81
+ streamId: chatId,
82
+ abortController,
83
+ });
84
+
85
+ return stream;
86
+ }
73
87
 
74
88
  // GET /chat/:chatId/stream
75
- const stream = await context.resumeStream({ streamId: chatId });
76
- return stream ?? new Response(null, { status: 204 });
89
+ export async function resume(chatId: string) {
90
+ const stream = await context.resumeStream({ streamId: chatId });
91
+
92
+ return stream ?? new Response(null, { status: 204 });
93
+ }
77
94
 
78
95
  // POST /chat/:chatId/stop
79
- await context.stopStream({ streamId: chatId });
96
+ export async function stop(chatId: string) {
97
+ await context.stopStream({ streamId: chatId });
98
+ }
80
99
  ```
81
100
 
82
101
  ## Usage
83
102
 
84
103
  ### `startStream`
85
104
 
86
- Starts a stream and persists chunks as they are produced. Returns the stream for the client that started it, plus the id it was registered under.
105
+ Starts a stream and stores the chunks as they are produced. Returns the stream for the client, the stream id and the generation id.
87
106
 
88
107
  > [!TIP]
89
108
  > The returned stream is both a `ReadableStream` and an async iterable, so `return stream` and `yield* stream` both work.
@@ -92,7 +111,7 @@ Starts a stream and persists chunks as they are produced. Returns the stream for
92
111
  import { streamText, toUIMessageStream } from "ai";
93
112
 
94
113
  async function sendMessage(chatId: string, messages: UIMessage[]) {
95
- // Optional: lets `streamText` see the stop signal
114
+ // Optional: `streamText` sees the stop signal and aborts the HTTP request
96
115
  const abortController = new AbortController();
97
116
 
98
117
  const result = streamText({
@@ -112,15 +131,55 @@ async function sendMessage(chatId: string, messages: UIMessage[]) {
112
131
  }
113
132
  ```
114
133
 
115
- | Option | Type | Description |
116
- | ----------------- | ----------------------------- | ------------------------------------------------------------------------------------------------- |
117
- | `streamId` | `string` | Defaults to a generated id, returned as `streamId` |
118
- | `abortController` | `AbortController` | Created if not supplied, so a stream is always stoppable |
119
- | `onFinish` | `() => void \| Promise<void>` | Runs once the source has ended, on every exit path including errors and stops. Errors are ignored |
134
+ | Option | Type | Description |
135
+ | ------------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
136
+ | `streamId` | `string` | Id of the stream. Use it to resume or stop the stream. Defaults to a generated id, returned as `streamId` |
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
+ | `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 |
140
+ | `onStopSubscriptionError` | `(error: unknown) => void` | Called when the subscription to stop requests fails. The stream continues, but it cannot be stopped |
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 |
142
+
143
+ #### Abort controller
144
+
145
+ You can always stop a stream. If you do not pass an `abortController`, the library creates one.
146
+
147
+ ```ts
148
+ // Without an abortController: a stop cancels the source stream
149
+ await context.startStream(toUIMessageStream({ stream: result.stream }), { streamId });
150
+
151
+ // With abortController: `streamText` sees the signal and aborts the HTTP request
152
+ const abortController = new AbortController();
153
+ const result = streamText({ model, messages, abortSignal: abortController.signal });
154
+ await context.startStream(toUIMessageStream({ stream: result.stream }), {
155
+ streamId,
156
+ abortController,
157
+ });
158
+ ```
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`.
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
+ ```
120
179
 
121
180
  ### `resumeStream`
122
181
 
123
- Resume an existing stream and replays every chunk produced so far, then follows the rest live. Returns `null` when there is nothing to resume.
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.
124
183
 
125
184
  ```ts
126
185
  async function resumeMessage(chatId: string) {
@@ -137,69 +196,94 @@ async function resumeMessage(chatId: string) {
137
196
  }
138
197
  ```
139
198
 
140
- The stream is `null` in three cases that are deliberately indistinguishable:
199
+ The result is `null` in three cases. The library does not tell you which case applies:
141
200
 
142
- - no stream was ever started under that id
143
- - the stream already completed
144
- - the producer died or was stopped part way through
201
+ - no stream was started with that id
202
+ - the stream has already completed
203
+ - the producer died or was stopped before the stream completed
145
204
 
146
- If your application needs to tell a truncated stream from a complete one, record that next to the message you persist.
205
+ If your application must know whether a stream completed or was cut off, store that information together with the message.
147
206
 
148
207
  ### `stopStream`
149
208
 
150
- Stop an active stream.
209
+ Stops a running stream. Pass `generationId` to stop a specific generation. Omit it to stop the current generation of the stream id.
151
210
 
152
211
  ```ts
153
- async function stopMessage(chatId: string) {
154
- await streams.stopStream({ streamId: chatId });
212
+ async function stopMessage(chatId: string, messageId?: string) {
213
+ await context.stopStream({ streamId: chatId, generationId: messageId });
155
214
  }
156
215
  ```
157
216
 
158
- ## Stream IDs
217
+ A stop request with a generation id can arrive before that generation listens for stop requests, or before it starts. Both included adapters store the request, and the generation stops as soon as it starts to listen. A stop request without a generation id applies to the generation that is current at the time of the request. If there is no current generation, the request is not stored and has no effect.
159
218
 
160
- A stream is addressed by one `streamId` that you choose, and that id is a pointer rather than the stream itself. Each call to `startStream` creates a generation, which is one run of that id, and repoints the id at it. `resumeStream({ streamId })` resolves the pointer and follows the generation it names, and `stopStream({ streamId })` reaches whichever producer holds the id at the time. There is no second key to store or clear.
219
+ See [Identifiers](#identifiers) for details about stream ids and generation ids.
161
220
 
162
- The indirection is what makes an id safe to reuse. Starting a new stream under an id that is already in use repoints it, so a resume gets the new stream and none of the old one's chunks, and a producer that is still shutting down cannot tear down the generation that replaced it.
221
+ ## Identifiers
163
222
 
164
- - **Pass the chat id** in most applications. It encodes "at most one active stream per chat", and a reconnecting client needs nothing else to call `resumeStream({ streamId: chatId })`.
165
- - **Pass the assistant message id** when you need to address one specific stream.
166
- - **Omit it** and one is generated. `startStream` returns it.
223
+ A stream has two ids. If you do not pass an id, `startStream` generates it and returns both ids.
167
224
 
168
- ## Stopping
225
+ - **`streamId`** identifies the stream. A stream can run more than once. Each run is a generation.
226
+ - **`generationId`** identifies one generation of the stream.
169
227
 
170
- Stopping is always possible, because a controller is always available. This works even if you didn't pass an `abortController` directly to `startStream(..., { abortController })`, because one is created automatically if not supplied, ensuring that a stream is always stoppable.
228
+ Each call to `startStream` creates a new generation. The generation that started last is the current generation of the stream id.
171
229
 
172
- ```ts
173
- // Without an abortController: stopping cancels the source, which propagates upstream
174
- await streams.startStream(toUIMessageStream({ stream: result.stream }), { streamId });
230
+ > [!TIP]
231
+ > Most applications only need the stream id. Use an id that the client already knows, for example the chat id or the session id. A client that reconnects can then call `resumeStream({ streamId: chatId })` without any other id.
232
+
233
+ ### Stream ID
234
+
235
+ With only a stream id, `resumeStream` and `stopStream` apply to the current generation.
175
236
 
176
- // With abortController: `streamText` sees the signal
177
- const abortController = new AbortController();
178
- const result = streamText({ model, messages, abortSignal: abortController.signal });
179
- await streams.startStream(toUIMessageStream({ stream: result.stream }), {
180
- streamId,
181
- abortController,
182
- });
183
237
  ```
238
+ startStream({ streamId: "chat-1" }) ──▶ generation A
239
+ startStream({ streamId: "chat-1" }) ──▶ generation B (current)
240
+
241
+ resumeStream({ streamId: "chat-1" }) ──▶ generation B
242
+ stopStream({ streamId: "chat-1" }) ──▶ generation B
243
+ ```
244
+
245
+ If you start a stream with a stream id that is already in use, the new generation becomes the current generation. A resume then returns only the chunks of the new generation. Generation A continues to run until its source stream ends, but the stream id alone no longer reaches it. When generation A ends, its cleanup does not affect generation B.
246
+
247
+ ### Generation ID
248
+
249
+ With a stream id and a generation id, `resumeStream` and `stopStream` apply only to that generation, also after a newer generation has started.
250
+
251
+ ```
252
+ startStream({ streamId: "chat-1", generationId: "msg-1" }) ──▶ generation msg-1
253
+ startStream({ streamId: "chat-1", generationId: "msg-2" }) ──▶ generation msg-2 (current)
254
+
255
+ resumeStream({ streamId: "chat-1" }) ──▶ generation msg-2
256
+ resumeStream({ streamId: "chat-1", generationId: "msg-1" }) ──▶ generation msg-1
257
+ stopStream({ streamId: "chat-1", generationId: "msg-1" }) ──▶ generation msg-1
258
+ ```
259
+
260
+ Use a generation id when generations of the same stream id can overlap. Example: a client stops a generation while a new generation with the same stream id starts. The stop request must stop only the old generation, not the new one.
184
261
 
185
- It's recommended to always pass your own `abortController`. Handing the signal to `streamText` aborts the provider request directly and lets the AI SDK emit its `abort` chunk and run `onAbort`, instead of relying on cancellation travelling back up the pipe.
262
+ Use an id that the client already knows, for example the id of the user message that it sent. The client can then resume or stop that generation without a server-generated id.
263
+
264
+ > [!WARNING]
265
+ > A generation id must be unique within its stream id. Do not use it again, for example when you retry the same message. The library does not check this, and resume and stop do not work correctly for a generation id that is used twice.
186
266
 
187
267
  ## Adapters
188
268
 
189
- | Import | Store |
190
- | ----------------------------------------- | --------------------------------------------------------------------------- |
191
- | `ai-resumable-stream/adapters/redis` | Redis, via [`resumable-stream`](https://github.com/vercel/resumable-stream) |
192
- | `ai-resumable-stream/adapters/s3-express` | One appendable object per stream, in an S3 Express One Zone bucket |
269
+ | Adapter | Import | Where chunks live | Resume needs a live producer | Cost model |
270
+ | ------------------------- | ----------------------------------------- | ----------------------------------- | ---------------------------- | -------------------------------- |
271
+ | [Redis](#redis) | `ai-resumable-stream/adapters/redis` | Memory of the producing process | Yes | Your Redis instance |
272
+ | [S3 Express](#s3-express) | `ai-resumable-stream/adapters/s3-express` | One appendable object in the bucket | No | One billed `PutObject` per flush |
193
273
 
194
274
  ### Redis
195
275
 
196
- This adapter requires two Redis clients (pub/sub needs separate connections). Both `redis` v5 and v6 are supported. The clients will be connected automatically, if not already connected, but the library won't disconnect them afterwards. That means you can manage the connection lifecycle in your application and reuse clients across multiple streams.
276
+ This adapter requires two Redis clients, because pub/sub needs a separate connection. The library connects the clients if they are not connected yet, but it never disconnects them. You manage the connection lifecycle in your application and can reuse the clients for all streams.
277
+
278
+ > [!NOTE]
279
+ > You need to install `redis` to use this adapter. Both v5 and v6 are supported.
197
280
 
198
281
  ```ts
199
282
  import { createClient } from "redis";
200
283
  import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
201
284
  import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
202
285
 
286
+ // Important: publisher and subscriber must be separate clients
203
287
  const publisher = createClient({ url: process.env.REDIS_URL });
204
288
  const subscriber = createClient({ url: process.env.REDIS_URL });
205
289
 
@@ -210,64 +294,25 @@ const context = createResumableUIMessageStream({
210
294
  });
211
295
  ```
212
296
 
213
- | Option | Type | Required | Description |
214
- | ------------ | ------------- | -------- | ------------------------------------------------------------------- |
215
- | `publisher` | `RedisClient` | Yes | Issues commands |
216
- | `subscriber` | `RedisClient` | Yes | Must be separate: a subscribed connection cannot issue commands |
217
- | `keyPrefix` | `string` | No | Namespaces every key and channel. Defaults to `ai-resumable-stream` |
218
-
219
- #### How it works
220
-
221
- This adapter is built on [`resumable-stream`](https://github.com/vercel/resumable-stream). Chunks are never stored in Redis itself. They live in the memory of the process that produces them and reach late subscribers over pub/sub, so Redis carries the signalling and a small pointer per stream, not the messages. There is no chunk retention to configure.
222
-
223
- Each stream id points at a generation, which is one run of that id. That pointer is the only key the adapter writes, and it carries a 24 hour expiry so a producer that dies without cleaning up leaves nothing behind for long. Starting a new stream under an id that is already in use moves the pointer to a fresh generation, so a producer that is still shutting down cannot tear down the stream that replaced it. The pointer is deleted as soon as the source ends, which is why a resume request arriving during teardown is told there is nothing to resume instead of racing it.
224
-
225
- Stop requests travel on a separate pub/sub channel. A producer subscribes to the channel for its stream id when the stream starts, and aborts its controller when a message arrives, no matter which process published it.
297
+ | Option | Type | Required | Description |
298
+ | ------------ | ------------- | -------- | --------------------------------------------------------------------------------------------------------- |
299
+ | `publisher` | `RedisClient` | Yes | Client that sends commands and publishes messages |
300
+ | `subscriber` | `RedisClient` | Yes | Client for subscriptions. Must be a separate client, because a subscribed connection cannot send commands |
301
+ | `keyPrefix` | `string` | No | Prefix for all keys and channels. Defaults to `ai-resumable-stream` |
226
302
 
227
303
  > [!IMPORTANT]
228
304
  > **A stream is only resumable while its producer is alive.**
229
305
 
230
- ```mermaid
231
- sequenceDiagram
232
- participant Client
233
- participant Server
234
- participant Redis
235
-
236
- rect rgb(240, 248, 255)
237
- Note over Client,Redis: startStream
238
- Client->>Server: POST /chat
239
- Server->>Redis: SUBSCRIBE stop channel
240
- Server->>Redis: SET generation pointer
241
- Server->>Server: streamText()
242
- Server->>Redis: PUBLISH chunks
243
- Server-->>Client: stream chunks
244
- end
245
-
246
- rect rgb(240, 255, 240)
247
- Note over Client,Redis: resumeStream
248
- Client->>Server: GET /chat/:chatId/stream
249
- Server->>Redis: GET generation pointer
250
- Server->>Redis: SUBSCRIBE stream channel
251
- Redis-->>Server: replay from the producer's buffer
252
- Server-->>Client: past chunks
253
- Redis-->>Server: new chunks
254
- Server-->>Client: live chunks
255
- end
256
-
257
- rect rgb(255, 248, 240)
258
- Note over Client,Redis: stopStream
259
- Client->>Server: POST /chat/:chatId/stop
260
- Server->>Redis: PUBLISH stop
261
- Redis-->>Server: deliver to the producer
262
- Server->>Server: abortController.abort()
263
- end
264
- ```
306
+ See [docs/adapter-redis.md](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-redis.md) for how it works, a sequence diagram and a full example.
265
307
 
266
308
  ### S3 Express
267
309
 
268
- This adapter requires an [S3 Express One Zone](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-one-zone.html) directory bucket and an `S3Client` that you build yourself, so credentials, region and retry behaviour stay with your application.
310
+ This adapter requires an [S3 Express One Zone](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-one-zone.html) directory bucket and an `S3Client`. You create the client, so you control the credentials, the region and the retry behaviour.
269
311
 
270
- Chunks are held in the bucket rather than in the memory of the process producing them. A resume is served by reading the object, so it does not depend on the producing process answering, and any instance with access to the bucket can serve it.
312
+ The chunks are stored in the bucket, not in the memory of the producing process. A resume reads the chunks from the bucket. It does not need a response from the producing process, and any instance with access to the bucket can serve it.
313
+
314
+ > [!NOTE]
315
+ > You need to install `@aws-sdk/client-s3` to use this adapter.
271
316
 
272
317
  ```ts
273
318
  import { S3Client } from "@aws-sdk/client-s3";
@@ -279,143 +324,71 @@ const adapter = createS3ExpressAdapter({
279
324
  });
280
325
  ```
281
326
 
282
- | Option | Type | Default | Description |
283
- | ---------------------- | ---------- | --------------------- | ----------------------------------------------------------------------------- |
284
- | `client` | `S3Client` | | Built and configured by you |
285
- | `bucket` | `string` | | A directory bucket in an Availability Zone |
286
- | `prefix` | `string` | `ai-resumable-stream` | Namespaces every key. Point the lifecycle rule at it |
287
- | `flushIntervalMs` | `number` | `250` | How long chunks may sit in memory before being written |
288
- | `batchSize` | `number` | `50` | Forces a write once this many chunks are buffered |
289
- | `resumePollIntervalMs` | `number` | `500` | How often a resuming reader looks for new bytes |
290
- | `stopPollIntervalMs` | `number` | `1000` | How often a producer checks for a stop request |
291
- | `heartbeatMs` | `number` | `5000` | How often an idle producer records that it is alive |
292
- | `deadAfterMs` | `number` | `30000` | Silence after which a producer is presumed dead. At least twice `heartbeatMs` |
293
-
294
- #### How it works
295
-
296
- A stream is one object in the bucket, appended to as chunks are produced. Chunks are buffered in memory and written once `batchSize` of them have collected or `flushIntervalMs` has passed, whichever comes first, so a stream costs one request per flush rather than one per chunk.
297
-
298
- Each stream id points at a generation, which is one run of that id, and the pointer is a small object next to the log. Every key the adapter writes sits under the generation, the stop marker included. A producer that has been superseded therefore cannot append into the log of the stream that replaced it, and a stop request cannot reach a generation other than the one it was resolved against.
299
-
300
- Stop requests are an object too. `stopStream` writes a marker under the current generation, and the producer checks for it every `stopPollIntervalMs` and aborts its controller when it appears.
301
-
302
- > [!IMPORTANT]
303
- > The bucket must be an [S3 Express One Zone](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-one-zone.html) directory bucket in an Availability Zone. Appends exist nowhere else in S3, and they are what make a stream one object rather than one object per batch.
304
-
305
- **How a stream is stored.** One appendable object, holding chunks, liveness and completion in the same log. A resuming reader replays the whole backlog in a single ranged read, then follows the tail at one request per poll.
306
-
307
- ```
308
- {prefix}/{streamId}/current pointer to the current generation
309
- {prefix}/{streamId}/{generationId}/0 the log
310
- {prefix}/{streamId}/{generationId}/stop stop marker
311
- ```
312
-
313
- ```mermaid
314
- sequenceDiagram
315
- participant Client
316
- participant Server
317
- participant S3 as S3 Express
318
-
319
- rect rgb(240, 248, 255)
320
- Note over Client,S3: startStream
321
- Client->>Server: POST /chat
322
- Server->>S3: PutObject log (format version)
323
- Server->>S3: PutObject pointer
324
- Server->>Server: streamText()
325
- par write the log
326
- loop every flushIntervalMs
327
- Server->>S3: PutObject append (chunks)
328
- end
329
- and watch for a stop
330
- loop every stopPollIntervalMs
331
- Server->>S3: HeadObject stop marker
332
- end
333
- end
334
- Server-->>Client: stream chunks
335
- end
336
-
337
- rect rgb(240, 255, 240)
338
- Note over Client,S3: resumeStream
339
- Client->>Server: GET /chat/:chatId/stream
340
- Server->>S3: GetObject pointer
341
- Server->>S3: GetObject Range bytes=0-
342
- S3-->>Server: the whole backlog, one request
343
- Server-->>Client: past chunks
344
- loop every resumePollIntervalMs
345
- Server->>S3: GetObject Range bytes=N-
346
- S3-->>Server: new records, or 416 for none
347
- Server-->>Client: live chunks
348
- end
349
- end
350
-
351
- rect rgb(255, 248, 240)
352
- Note over Client,S3: stopStream
353
- Client->>Server: POST /chat/:chatId/stop
354
- Server->>S3: GetObject pointer
355
- Server->>S3: PutObject stop marker
356
- S3-->>Server: the producer's next poll finds it
357
- Server->>Server: abortController.abort()
358
- end
359
- ```
360
-
361
- Every flush is one billed `PutObject`, and that is where the cost of a stream sits. Raising `flushIntervalMs` reduces the number of writes in proportion, and adds the same amount to how far behind a resuming reader runs. Reads are charged at a much lower rate. Run the producer in the same Availability Zone as the bucket, since AWS documents access from another zone as slower.
362
-
363
- A producer with nothing to write records a heartbeat every `heartbeatMs`, and both ends judge liveness on S3's clock rather than the caller's. A log that has not been written to for `deadAfterMs` is treated as having a dead producer, so `resumeStream` returns `null` and a reader already following it ends.
364
-
365
- Nothing is deleted when a stream finishes, because a reader may still be draining it. Set a [lifecycle expiration rule](https://docs.aws.amazon.com/AmazonS3/latest/userguide/directory-buckets-objects-lifecycle.html) on the bucket covering `prefix`.
327
+ | Option | Type | Default | Description |
328
+ | ---------------------- | ---------- | --------------------- | --------------------------------------------------------------------------------------------------- |
329
+ | `client` | `S3Client` | | The S3 client. You create and configure it |
330
+ | `bucket` | `string` | | A directory bucket in an Availability Zone |
331
+ | `prefix` | `string` | `ai-resumable-stream` | Prefix for all keys. Use it as the filter of the lifecycle rule |
332
+ | `flushIntervalMs` | `number` | `250` | Maximum time that chunks stay in memory before they are written |
333
+ | `batchSize` | `number` | `50` | Number of buffered chunks that triggers a write |
334
+ | `resumePollIntervalMs` | `number` | `500` | Interval at which a resumed stream checks for new chunks |
335
+ | `stopPollIntervalMs` | `number` | `1000` | Interval at which a producer checks for a stop request |
336
+ | `heartbeatMs` | `number` | `5000` | Interval at which an idle producer records that it is alive |
337
+ | `deadAfterMs` | `number` | `30000` | Time without writes after which a producer is considered dead. Must be at least twice `heartbeatMs` |
366
338
 
367
339
  > [!WARNING]
368
- > Lifecycle on a directory bucket does nothing unless the bucket policy grants `s3express:CreateSession` with `ReadWrite` to `lifecycle.s3.amazonaws.com`. Without it, objects accumulate silently.
369
-
370
- No local emulator implements appends, so the tests run against an in-memory bucket. To check that model against the real thing:
340
+ > The adapter does not delete objects when a stream finishes. Set a lifecycle expiration rule on the bucket with `prefix` as the filter, and grant `s3express:CreateSession` with `ReadWrite` to `lifecycle.s3.amazonaws.com` in the bucket policy. Without this grant, the rule does nothing and the objects are never deleted. See [Cleanup](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-s3-express.md#cleanup).
371
341
 
372
- ```sh
373
- S3_EXPRESS_BUCKET=my-streams--use1-az4--x-s3 AWS_REGION=us-east-1 pnpm test integration
374
- ```
342
+ See [docs/adapter-s3-express.md](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-s3-express.md) for how it works, the storage layout, a sequence diagram, cost and liveness details, and a full example.
375
343
 
376
344
  ### Custom `StreamAdapter`
377
345
 
378
- A `StreamAdapter` is four methods. Implement them against the store you want and pass the object as `adapter`.
346
+ Implement the `StreamAdapter` interface against the store you want and pass the object as `adapter`.
379
347
 
380
348
  ```ts
381
349
  import type { StreamAdapter } from "ai-resumable-stream";
382
350
 
383
351
  const adapter: StreamAdapter = {
384
- createStream({ streamId, chunks, waitUntil }) { ... },
385
- resumeStream({ streamId }) { ... },
386
- requestStop({ streamId }) { ... },
387
- onStopRequested({ streamId, onStop }) { ... },
352
+ createStream({ streamId, generationId, chunks, waitUntil }) { ... },
353
+ resumeStream({ streamId, generationId }) { ... },
354
+ requestStop({ streamId, generationId }) { ... },
355
+ onStopRequested({ streamId, generationId, onStop }) { ... },
388
356
  };
389
357
  ```
390
358
 
391
- | Method | Contract |
392
- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
393
- | `createStream` | Discards any state left from a previous stream with the same id, registers the id, consumes `chunks` in the background. Resolves once resumable, not once complete |
394
- | `resumeStream` | Chunks already produced, then those still to come. `null` when unknown, finished, or expired |
395
- | `requestStop` | Safe to call for an unknown or finished stream |
396
- | `onStopRequested` | Producer-side listener. Returns a function that removes it |
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.
360
+ - **`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
+ - **`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
+ - **`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.
363
+
364
+ The adapter must treat the chunks as opaque strings. If your store needs a special format, for example escaping or a length prefix, the adapter adds it on write and removes it on read.
397
365
 
398
- `createStream` receives a `ReadableStream<string>` of encoded chunks. It has to consume that stream in the background until it ends, and `resumeStream` has to return the same strings in the same order, followed by the ones still to come. The strings are opaque, so any framing they need to survive your store is the adapter's own concern.
366
+ `requestStop` and `onStopRequested` usually run in different processes, so the stop signal must also go through the store, for example by a subscription or a poll. Store the stop signal per generation, so that a stop never reaches a different generation of the same stream id. `startStream` does not await `onStopRequested`. If `onStopRequested` rejects, the only effect is that the generation cannot be stopped.
399
367
 
400
- `requestStop` and `onStopRequested` usually run in different processes, so the stop signal has to travel through the store as well, by a subscription, a poll, or whatever the backend offers.
368
+ The tests in [`src/__tests__/conformance-suite.ts`](./src/__tests__/conformance-suite.ts) run against both included adapters. They cover the behaviour that an adapter must have:
401
369
 
402
- The tests in [`src/__tests__/conformance-suite.ts`](./src/__tests__/conformance-suite.ts) run against both shipped adapters and cover what an adapter has to get right: replay followed by live chunks on resume, persistence that continues after the client disconnects, a reused id that discards the previous stream's chunks, and a stop that reaches a reader who resumed.
370
+ - a resume replays the past chunks and then continues with the new chunks
371
+ - chunks are still stored after the client disconnects
372
+ - a reused stream id does not replay the chunks of the previous stream
373
+ - a stop also ends the stream of a client that resumed
374
+ - a stop with a generation id only stops that generation, also when it was requested before that generation started
375
+ - an older generation can be resumed while a newer generation is current
403
376
 
404
377
  ## Advanced
405
378
 
406
379
  ### Chunk types
407
380
 
408
- The root export is generic over the chunk type and has no dependency on `ai`. The `ai-sdk` subpath binds it to the AI SDK:
381
+ The root export works with any chunk type and does not depend on `ai`. The `ai-sdk` subpath export is preconfigured for the `UIMessageChunk` type of the AI SDK:
409
382
 
410
383
  ```ts
411
384
  import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
412
385
 
413
- const streams = createResumableUIMessageStream({ adapter });
386
+ const context = createResumableUIMessageStream({ adapter });
414
387
  ```
415
388
 
416
- That is exactly `createResumableStream({ adapter, codec: uiMessageChunkCodec })`. Chunks are validated on the way back, so one written by an older version of your application is dropped rather than failing the resume.
389
+ This is the same as `createResumableStream({ adapter, codec: uiMessageChunkCodec })`. The codec validates each chunk when it is read. An invalid chunk, for example one written by an older version of your application, is dropped and does not fail the resume.
417
390
 
418
- For anything else, supply a `StreamCodec`:
391
+ For other chunk types, pass your own `StreamCodec`:
419
392
 
420
393
  ```ts
421
394
  import { createResumableStream, type StreamCodec } from "ai-resumable-stream";
@@ -425,27 +398,27 @@ const codec: StreamCodec<MyChunk> = {
425
398
  decode: (data) => JSON.parse(data) as MyChunk,
426
399
  };
427
400
 
428
- const streams = createResumableStream({ adapter, codec });
401
+ const context = createResumableStream({ adapter, codec });
429
402
  ```
430
403
 
431
- `decode` may return `undefined` to drop a chunk it cannot represent, so one bad chunk never fails an entire resume.
404
+ `decode` can return `undefined` to drop a chunk that it cannot decode. One invalid chunk then does not fail the full resume.
432
405
 
433
406
  ### Serverless
434
407
 
435
- Persistence outlives the response, so the runtime has to be told to wait for it:
408
+ The library continues to store chunks after the response has been sent. On serverless runtimes, pass `waitUntil` so that the runtime keeps the function alive until all chunks are stored:
436
409
 
437
410
  ```ts
438
411
  import { waitUntil } from "@vercel/functions";
439
412
 
440
- const streams = createResumableUIMessageStream({ adapter, waitUntil });
413
+ const context = createResumableUIMessageStream({ adapter, waitUntil });
441
414
  ```
442
415
 
443
416
  ### Finish
444
417
 
445
- The `onFinish` callback is invoked after the source stream has ended and the adapter stream was closed. Use it for cleanup tasks like removing the active stream ID from the database. Errors thrown by `onFinish` are silently caught.
418
+ The `onFinish` callback is invoked after the source stream has ended and the adapter stream was closed. Use it for cleanup tasks like removing the active stream ID from the database. Errors thrown by `onFinish` are caught and ignored.
446
419
 
447
420
  ```typescript
448
- const stream = await context.startStream(toUIMessageStream({ stream: result.stream }), {
421
+ const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
449
422
  onFinish: async () => {
450
423
  await saveChat({ chatId, activeStreamId: null });
451
424
  },
@@ -454,16 +427,16 @@ const stream = await context.startStream(toUIMessageStream({ stream: result.stre
454
427
 
455
428
  ## Examples
456
429
 
457
- Two runnable demos live in [`examples/`](./examples), one per adapter. Each starts a stream, disconnects the client part way through, resumes it by id, and then stops a second stream from elsewhere.
430
+ The [`examples/`](./examples) folder contains one runnable example for each adapter. Each example starts a stream, disconnects the client before the stream ends, resumes the stream by its id, and then stops a second stream with `stopStream`.
458
431
 
459
432
  ```sh
460
- pnpm example:redis # a throwaway Redis, started for you
461
- pnpm example:s3-express # an in-memory bucket, since no emulator implements appends
433
+ pnpm example:redis # starts a temporary Redis server
434
+ pnpm example:s3-express # uses an in-memory bucket
462
435
  ```
463
436
 
464
437
  ### tRPC
465
438
 
466
- Server-side procedures for sending, resuming, and stopping. The chat id is the stream id, so no active-stream pointer has to be stored or cleared.
439
+ Server-side procedures to send, resume and stop. The chat id is used as the stream id, so you do not have to store a separate stream id.
467
440
 
468
441
  ```ts
469
442
  // server/router.ts
@@ -477,7 +450,7 @@ import { publicProcedure, router } from "./trpc";
477
450
  const publisher = createClient({ url: process.env.REDIS_URL });
478
451
  const subscriber = createClient({ url: process.env.REDIS_URL });
479
452
 
480
- const streams = createResumableUIMessageStream({
453
+ const context = createResumableUIMessageStream({
481
454
  adapter: createRedisAdapter({ publisher, subscriber }),
482
455
  });
483
456
 
@@ -495,7 +468,7 @@ export const appRouter = router({
495
468
  abortSignal: abortController.signal,
496
469
  });
497
470
 
498
- const { stream } = await streams.startStream(toUIMessageStream({ stream: result.stream }), {
471
+ const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
499
472
  streamId: chatId,
500
473
  abortController,
501
474
  onFinish: async () => {
@@ -509,7 +482,7 @@ export const appRouter = router({
509
482
  resumeMessage: publicProcedure.input(z.object({ chatId: z.string() })).mutation(async function* ({
510
483
  input,
511
484
  }): AsyncGenerator<UIMessageChunk> {
512
- const stream = await streams.resumeStream({ streamId: input.chatId });
485
+ const stream = await context.resumeStream({ streamId: input.chatId });
513
486
  if (!stream) return;
514
487
 
515
488
  yield* stream;
@@ -518,7 +491,7 @@ export const appRouter = router({
518
491
  stopMessage: publicProcedure
519
492
  .input(z.object({ chatId: z.string() }))
520
493
  .mutation(async ({ input }) => {
521
- await streams.stopStream({ streamId: input.chatId });
494
+ await context.stopStream({ streamId: input.chatId });
522
495
 
523
496
  return { success: true };
524
497
  }),
@@ -534,7 +507,7 @@ function createResumableStream<CHUNK>(options: CreateResumableStreamOptions<CHUN
534
507
  startStream: (
535
508
  source: ReadableStream<CHUNK>,
536
509
  options?: StartStreamOptions,
537
- ) => Promise<{ streamId: string; stream: AsyncIterableStream<CHUNK> }>;
510
+ ) => Promise<StartStreamResult<CHUNK>>;
538
511
  resumeStream: (options: ResumeStreamOptions) => Promise<AsyncIterableStream<CHUNK> | null>;
539
512
  stopStream: (options: StopStreamOptions) => Promise<void>;
540
513
  };
@@ -548,29 +521,40 @@ type CreateResumableStreamOptions<CHUNK> = {
548
521
 
549
522
  type StartStreamOptions = {
550
523
  streamId?: string;
524
+ generationId?: string;
551
525
  abortController?: AbortController;
526
+ stopTimeoutMs?: number;
527
+ onStopSubscriptionError?: (error: unknown) => void;
552
528
  onFinish?: () => void | Promise<void>;
553
529
  };
554
530
 
531
+ type StartStreamResult<CHUNK> = {
532
+ streamId: string;
533
+ generationId: string;
534
+ stream: AsyncIterableStream<CHUNK>;
535
+ };
536
+
555
537
  type ResumeStreamOptions = {
556
538
  streamId: string;
539
+ generationId?: string;
557
540
  };
558
541
 
559
542
  type StopStreamOptions = {
560
543
  streamId: string;
544
+ generationId?: string;
561
545
  };
562
546
  ```
563
547
 
564
- | Option | Type | Required | Description |
565
- | ------------ | -------------------- | -------- | ----------------------------------------------------------------------------------- |
566
- | `adapter` | `StreamAdapter` | Yes | Where chunks are stored and how stop requests travel |
567
- | `codec` | `StreamCodec<CHUNK>` | Yes | Translates between chunks and the strings an adapter stores |
568
- | `waitUntil` | `(promise) => void` | No | Keeps the host process alive until persistence finishes. Omit on long-lived servers |
569
- | `generateId` | `() => string` | No | Generates a stream id when `startStream` is not given one |
548
+ | Option | Type | Required | Description |
549
+ | ------------ | -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
550
+ | `adapter` | `StreamAdapter` | Yes | Stores the chunks and transports stop requests |
551
+ | `codec` | `StreamCodec<CHUNK>` | Yes | Converts chunks to strings for the adapter, and back |
552
+ | `waitUntil` | `(promise) => void` | No | Keeps the process alive until all chunks are stored. Only needed on serverless runtimes |
553
+ | `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` |
570
554
 
571
555
  ### `createResumableUIMessageStream`
572
556
 
573
- The same, with `codec` fixed to `uiMessageChunkCodec`.
557
+ Same as `createResumableStream`, with `codec` set to `uiMessageChunkCodec`.
574
558
 
575
559
  ```ts
576
560
  function createResumableUIMessageStream(
@@ -584,12 +568,20 @@ function createResumableUIMessageStream(
584
568
  type StreamAdapter = {
585
569
  createStream(options: {
586
570
  streamId: string;
571
+ generationId: string;
587
572
  chunks: ReadableStream<string>;
588
573
  waitUntil?: (promise: Promise<unknown>) => void;
589
574
  }): Promise<void>;
590
- resumeStream(options: { streamId: string }): Promise<ReadableStream<string> | null>;
591
- requestStop(options: { streamId: string }): Promise<void>;
592
- onStopRequested(options: { streamId: string; onStop: () => void }): Promise<() => void>;
575
+ resumeStream(options: {
576
+ streamId: string;
577
+ generationId?: string;
578
+ }): Promise<ReadableStream<string> | null>;
579
+ requestStop(options: { streamId: string; generationId?: string }): Promise<void>;
580
+ onStopRequested(options: {
581
+ streamId: string;
582
+ generationId: string;
583
+ onStop: () => void;
584
+ }): Promise<() => void>;
593
585
  };
594
586
  ```
595
587