ai-resumable-stream 3.2.1 → 3.3.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 +16 -14
- package/dist/adapters/redis/index.d.mts +22 -7
- package/dist/adapters/redis/index.mjs +380 -37
- package/package.json +2 -3
package/README.md
CHANGED
|
@@ -135,10 +135,10 @@ async function sendMessage(chatId: string, messages: UIMessage[]) {
|
|
|
135
135
|
| ------------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
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
|
-
| `abortController` | `AbortController` |
|
|
138
|
+
| `abortController` | `AbortController` | The library aborts it when the stream stops, and creates one if you do not pass one |
|
|
139
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
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.
|
|
141
|
+
| `onFinish` | `() => void \| Promise<void>` | Called after the source stream has ended, also after an error or a stop. The library ignores errors from the callback |
|
|
142
142
|
|
|
143
143
|
#### Abort controller
|
|
144
144
|
|
|
@@ -296,11 +296,13 @@ const context = createResumableUIMessageStream({
|
|
|
296
296
|
});
|
|
297
297
|
```
|
|
298
298
|
|
|
299
|
-
| Option
|
|
300
|
-
|
|
|
301
|
-
| `publisher`
|
|
302
|
-
| `subscriber`
|
|
303
|
-
| `keyPrefix`
|
|
299
|
+
| Option | Type | Required | Description |
|
|
300
|
+
| -------------- | ------------- | -------- | ---------------------------------------------------------------------------------------------------------- |
|
|
301
|
+
| `publisher` | `RedisClient` | Yes | Client that sends commands and publishes messages |
|
|
302
|
+
| `subscriber` | `RedisClient` | Yes | Client for subscriptions. Must be a separate client, because a subscribed connection cannot send commands |
|
|
303
|
+
| `keyPrefix` | `string` | No | Prefix for all keys and channels. Defaults to `ai-resumable-stream` |
|
|
304
|
+
| `ackTimeoutMs` | `number` | No | How long a resume waits for the producer to answer before it returns `null`. Defaults to `1000` |
|
|
305
|
+
| `ttlSeconds` | `number` | No | How long a stream stays resumable. Must be longer than your longest stream. Defaults to `86400` (24 hours) |
|
|
304
306
|
|
|
305
307
|
> [!IMPORTANT]
|
|
306
308
|
> **A stream is only resumable while its producer is alive.**
|
|
@@ -358,10 +360,10 @@ const adapter: StreamAdapter = {
|
|
|
358
360
|
};
|
|
359
361
|
```
|
|
360
362
|
|
|
361
|
-
- **`createStream`**
|
|
362
|
-
- **`resumeStream`**
|
|
363
|
-
- **`requestStop`**
|
|
364
|
-
- **`onStopRequested`**
|
|
363
|
+
- **`createStream`** runs 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.
|
|
364
|
+
- **`resumeStream`** runs 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.
|
|
365
|
+
- **`requestStop`** runs in 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.
|
|
366
|
+
- **`onStopRequested`** runs in 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.
|
|
365
367
|
|
|
366
368
|
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.
|
|
367
369
|
|
|
@@ -389,7 +391,7 @@ import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
|
389
391
|
const context = createResumableUIMessageStream({ adapter });
|
|
390
392
|
```
|
|
391
393
|
|
|
392
|
-
This is the same as `createResumableStream({ adapter, codec: uiMessageChunkCodec })`. The codec validates each chunk when
|
|
394
|
+
This is the same as `createResumableStream({ adapter, codec: uiMessageChunkCodec })`. The codec validates each chunk when the library reads it. The codec drops an invalid chunk, for example one that an older version of your application wrote, and the resume does not fail.
|
|
393
395
|
|
|
394
396
|
For other chunk types, pass your own `StreamCodec`:
|
|
395
397
|
|
|
@@ -418,7 +420,7 @@ const context = createResumableUIMessageStream({ adapter, waitUntil });
|
|
|
418
420
|
|
|
419
421
|
### Finish
|
|
420
422
|
|
|
421
|
-
The `onFinish`
|
|
423
|
+
The library calls `onFinish` after the source stream has ended and the adapter stream has closed. Use it for cleanup, for example to remove the active stream id from the database. The library catches and ignores errors from `onFinish`.
|
|
422
424
|
|
|
423
425
|
```typescript
|
|
424
426
|
const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
@@ -501,7 +503,7 @@ export const appRouter = router({
|
|
|
501
503
|
});
|
|
502
504
|
```
|
|
503
505
|
|
|
504
|
-
## API
|
|
506
|
+
## API reference
|
|
505
507
|
|
|
506
508
|
### `createResumableStream`
|
|
507
509
|
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { t as StreamAdapter } from "../../adapter-BwSsPtDm.mjs";
|
|
2
|
-
import { Publisher, Subscriber } from "resumable-stream";
|
|
3
2
|
//#region src/adapters/redis/adapter.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* A Redis client, described by the commands this adapter actually calls rather than by
|
|
@@ -7,12 +6,15 @@ import { Publisher, Subscriber } from "resumable-stream";
|
|
|
7
6
|
* `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal
|
|
8
7
|
* type would pin consumers to one of them.
|
|
9
8
|
*
|
|
10
|
-
* `
|
|
11
|
-
*
|
|
12
|
-
* redeclared because a listener removes itself alone, never every listener of its channel.
|
|
9
|
+
* `unsubscribe` takes the listener because a listener removes itself alone, never every
|
|
10
|
+
* listener of its channel.
|
|
13
11
|
*/
|
|
14
|
-
type Redis =
|
|
12
|
+
type Redis = {
|
|
15
13
|
isOpen: boolean;
|
|
14
|
+
connect(): Promise<unknown>;
|
|
15
|
+
publish(channel: string, message: string): Promise<unknown>;
|
|
16
|
+
subscribe(channel: string, listener: (message: string) => void): Promise<unknown>;
|
|
17
|
+
unsubscribe(channel: string, listener?: (message: string) => void): Promise<unknown>;
|
|
16
18
|
get(key: string): Promise<string | null>;
|
|
17
19
|
set(key: string, value: string, options?: {
|
|
18
20
|
expiration?: {
|
|
@@ -20,7 +22,6 @@ type Redis = Omit<Publisher, `get` | `set`> & Omit<Subscriber, `unsubscribe`> &
|
|
|
20
22
|
value: number;
|
|
21
23
|
};
|
|
22
24
|
}): Promise<unknown>;
|
|
23
|
-
unsubscribe(channel: string, listener?: (message: string) => void): Promise<unknown>;
|
|
24
25
|
del(key: string): Promise<unknown>;
|
|
25
26
|
eval(script: string, options?: {
|
|
26
27
|
keys?: Array<string>;
|
|
@@ -41,9 +42,23 @@ type CreateRedisAdapterOptions = {
|
|
|
41
42
|
* Namespace for every key and channel this adapter touches.
|
|
42
43
|
*/
|
|
43
44
|
keyPrefix?: string;
|
|
45
|
+
/**
|
|
46
|
+
* How long a resume waits for the producer to answer before it gives up and returns
|
|
47
|
+
* `null`. A producer that died never answers, so every resume of its stream waits this
|
|
48
|
+
* long. A producer that is alive but busy can need more than the default. Defaults to
|
|
49
|
+
* 1000 ms.
|
|
50
|
+
*/
|
|
51
|
+
ackTimeoutMs?: number;
|
|
52
|
+
/**
|
|
53
|
+
* How long a stream stays resumable, in seconds. Must be longer than your longest
|
|
54
|
+
* stream, because a resume finds nothing after this time, even while the producer still
|
|
55
|
+
* runs. A shorter value ends sooner the wait of each resume for a producer that died.
|
|
56
|
+
* Defaults to 24 hours.
|
|
57
|
+
*/
|
|
58
|
+
ttlSeconds?: number;
|
|
44
59
|
};
|
|
45
60
|
/**
|
|
46
|
-
* Stores streams in Redis
|
|
61
|
+
* Stores streams in Redis, with a runtime derived from `resumable-stream`.
|
|
47
62
|
*
|
|
48
63
|
* Chunks live in the memory of the producing process and reach late subscribers over
|
|
49
64
|
* Redis pub/sub, so a stream is only resumable while its producer is alive. Use a
|
|
@@ -1,7 +1,363 @@
|
|
|
1
|
-
|
|
1
|
+
//#region src/adapters/redis/runtime/runtime.ts
|
|
2
|
+
/*! @license
|
|
3
|
+
* This file is derived from resumable-stream 2.2.13 (src/runtime.ts),
|
|
4
|
+
* https://github.com/vercel/resumable-stream
|
|
5
|
+
*
|
|
6
|
+
* Copyright (c) 2025 Vercel, Inc
|
|
7
|
+
*
|
|
8
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
|
|
9
|
+
* software and associated documentation files (the "Software"), to deal in the Software
|
|
10
|
+
* without restriction, including without limitation the rights to use, copy, modify,
|
|
11
|
+
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
|
|
12
|
+
* permit persons to whom the Software is furnished to do so, subject to the following
|
|
13
|
+
* conditions:
|
|
14
|
+
*
|
|
15
|
+
* The above copyright notice and this permission notice shall be included in all copies
|
|
16
|
+
* or substantial portions of the Software.
|
|
17
|
+
*
|
|
18
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
19
|
+
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
|
20
|
+
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
21
|
+
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
|
|
22
|
+
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
|
|
23
|
+
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Raised when the producer does not answer a resume in time, for example because it died
|
|
27
|
+
* before it could mark its stream done.
|
|
28
|
+
*
|
|
29
|
+
* Differs from upstream: upstream raises a plain `Error`, which a caller can only identify
|
|
30
|
+
* by its message.
|
|
31
|
+
*/
|
|
32
|
+
var AckTimeoutError = class extends Error {
|
|
33
|
+
constructor() {
|
|
34
|
+
/** The upstream message, kept for callers that still match on it */
|
|
35
|
+
super(`Timeout waiting for ack`);
|
|
36
|
+
this.name = `AckTimeoutError`;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const DONE_MESSAGE = `\n\n\nDONE_SENTINEL_hasdfasudfyge374%$%^$EDSATRTYFtydryrte\n`;
|
|
40
|
+
const DONE_VALUE = `DONE`;
|
|
41
|
+
const DEFAULT_ACK_TIMEOUT_MS = 1e3;
|
|
42
|
+
const DEFAULT_DONE_WATCHDOG_INTERVAL_MS = 1e4;
|
|
43
|
+
function noop() {}
|
|
44
|
+
function createRuntime(options) {
|
|
45
|
+
const ctx = {
|
|
46
|
+
keyPrefix: `${options.keyPrefix}:rs`,
|
|
47
|
+
publisher: options.publisher,
|
|
48
|
+
subscriber: options.subscriber,
|
|
49
|
+
waitUntil: options.waitUntil ?? noop,
|
|
50
|
+
ackTimeoutMs: options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS,
|
|
51
|
+
ttlSeconds: options.ttlSeconds,
|
|
52
|
+
doneWatchdogIntervalMs: options.doneWatchdogIntervalMs ?? DEFAULT_DONE_WATCHDOG_INTERVAL_MS
|
|
53
|
+
};
|
|
54
|
+
return {
|
|
55
|
+
createNewResumableStream: (streamId, makeStream) => createNewResumableStream(ctx, streamId, makeStream),
|
|
56
|
+
resumeExistingStream: (streamId) => resumeExistingStream(ctx, streamId)
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
async function resumeExistingStream(ctx, streamId) {
|
|
60
|
+
const state = await ctx.publisher.get(`${ctx.keyPrefix}:sentinel:${streamId}`);
|
|
61
|
+
if (!state) return void 0;
|
|
62
|
+
if (state === DONE_VALUE) return null;
|
|
63
|
+
return resumeStream(ctx, streamId);
|
|
64
|
+
}
|
|
65
|
+
async function createNewResumableStream(ctx, streamId, makeStream) {
|
|
66
|
+
const requestChannel = `${ctx.keyPrefix}:request:${streamId}`;
|
|
67
|
+
const sentinelKey = `${ctx.keyPrefix}:sentinel:${streamId}`;
|
|
68
|
+
const chunkChannel = (listenerId) => `${ctx.keyPrefix}:chunk:${listenerId}`;
|
|
69
|
+
const sentinelExpiration = { expiration: {
|
|
70
|
+
type: `EX`,
|
|
71
|
+
value: ctx.ttlSeconds
|
|
72
|
+
} };
|
|
73
|
+
const chunks = [];
|
|
74
|
+
const listenerIds = [];
|
|
75
|
+
let isDone = false;
|
|
76
|
+
let resolveDone;
|
|
77
|
+
ctx.waitUntil(new Promise((resolve) => {
|
|
78
|
+
resolveDone = resolve;
|
|
79
|
+
}));
|
|
80
|
+
/**
|
|
81
|
+
* Publishes without waiting for the reply, and contains a failure.
|
|
82
|
+
*
|
|
83
|
+
* Differs from upstream in two ways:
|
|
84
|
+
* - Upstream awaits the publishes of each chunk before it reads the next one, so while a
|
|
85
|
+
* consumer is attached, the producer (and its own client) reads one chunk per Redis
|
|
86
|
+
* round trip (https://github.com/vercel/resumable-stream/issues/52). The client sends
|
|
87
|
+
* commands of one connection in the order they are called, so the consumer still
|
|
88
|
+
* gets the chunks in order.
|
|
89
|
+
* - Upstream does not handle a failed publish, so a dropped connection is an unhandled
|
|
90
|
+
* rejection that ends a Node process
|
|
91
|
+
* (https://github.com/vercel/resumable-stream/issues/53). A consumer that misses a
|
|
92
|
+
* chunk this way gets incomplete data, but a dropped connection also ends its own
|
|
93
|
+
* subscription.
|
|
94
|
+
*
|
|
95
|
+
* Publishes still in flight are kept, so the teardown can wait for them.
|
|
96
|
+
*/
|
|
97
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
98
|
+
const publish = (channel, message) => {
|
|
99
|
+
const promise = ctx.publisher.publish(channel, message).then(noop, noop);
|
|
100
|
+
inFlight.add(promise);
|
|
101
|
+
promise.then(() => inFlight.delete(promise));
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* Answers a consumer with every chunk so far, and with DONE if the source has ended.
|
|
105
|
+
*
|
|
106
|
+
* Differs from upstream: upstream passes an async listener, whose promise the Redis
|
|
107
|
+
* client ignores. A failed publish was an unhandled rejection, and a message that is no
|
|
108
|
+
* JSON threw inside the client. No upstream issue covers this.
|
|
109
|
+
*/
|
|
110
|
+
const onRequest = (message) => {
|
|
111
|
+
let request;
|
|
112
|
+
try {
|
|
113
|
+
request = JSON.parse(message);
|
|
114
|
+
} catch {
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (typeof request?.listenerId !== `string`) return;
|
|
118
|
+
listenerIds.push(request.listenerId);
|
|
119
|
+
const channel = chunkChannel(request.listenerId);
|
|
120
|
+
publish(channel, chunks.join(``).slice(request.skipCharacters ?? 0));
|
|
121
|
+
if (isDone) publish(channel, DONE_MESSAGE);
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* Subscribed before the sentinel is set, so a consumer that sees the sentinel always
|
|
125
|
+
* finds the producer listening. From upstream 2.2.13
|
|
126
|
+
* (https://github.com/vercel/resumable-stream/pull/41).
|
|
127
|
+
*
|
|
128
|
+
* Differs from upstream: if this setup fails, the promise given to `waitUntil` still
|
|
129
|
+
* settles, and the subscription is removed again.
|
|
130
|
+
*/
|
|
131
|
+
try {
|
|
132
|
+
await ctx.subscriber.subscribe(requestChannel, onRequest);
|
|
133
|
+
try {
|
|
134
|
+
await ctx.publisher.set(sentinelKey, `1`, sentinelExpiration);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
await ctx.subscriber.unsubscribe(requestChannel, onRequest).catch(noop);
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
} catch (error) {
|
|
140
|
+
resolveDone();
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Marks the stream done, tells the consumers and stops to answer requests.
|
|
145
|
+
*
|
|
146
|
+
* Differs from upstream:
|
|
147
|
+
* - Runs only once, and it cannot reject. Each command can fail alone, for example when
|
|
148
|
+
* Redis drops the connections, and the promise given to `waitUntil` still settles.
|
|
149
|
+
* Upstream awaits all commands together with no handler, so one failure is an
|
|
150
|
+
* unhandled rejection that ends a Node process, and the teardown never finishes
|
|
151
|
+
* (https://github.com/vercel/resumable-stream/issues/53,
|
|
152
|
+
* https://github.com/vercel/resumable-stream/pull/54).
|
|
153
|
+
* - Removes only its own listener of the request channel. Upstream removes every
|
|
154
|
+
* listener of the channel on the shared subscriber.
|
|
155
|
+
* - Waits for the chunk publishes still in flight, so a runtime that freezes the process
|
|
156
|
+
* after `waitUntil` does not lose them.
|
|
157
|
+
*
|
|
158
|
+
* If the DONE write fails, the sentinel stays "1" until it expires. A consumer then gets
|
|
159
|
+
* no answer and fails with the ack timeout.
|
|
160
|
+
*/
|
|
161
|
+
let finishing;
|
|
162
|
+
const finish = () => {
|
|
163
|
+
finishing ??= (async () => {
|
|
164
|
+
isDone = true;
|
|
165
|
+
for (const listenerId of listenerIds) publish(chunkChannel(listenerId), DONE_MESSAGE);
|
|
166
|
+
await Promise.allSettled([
|
|
167
|
+
ctx.publisher.set(sentinelKey, DONE_VALUE, sentinelExpiration),
|
|
168
|
+
ctx.subscriber.unsubscribe(requestChannel, onRequest),
|
|
169
|
+
...inFlight
|
|
170
|
+
]);
|
|
171
|
+
resolveDone();
|
|
172
|
+
})();
|
|
173
|
+
return finishing;
|
|
174
|
+
};
|
|
175
|
+
return new ReadableStream({ start(controller) {
|
|
176
|
+
/**
|
|
177
|
+
* Reads the whole source, also when nobody reads this stream any more, so the
|
|
178
|
+
* consumers still get every chunk.
|
|
179
|
+
*
|
|
180
|
+
* Differs from upstream: the loop has a rejection handler. A source that errors
|
|
181
|
+
* errors this stream and still runs the teardown. Upstream gives an unhandled
|
|
182
|
+
* rejection, which ends a Node process, and the stream stays resumable until the
|
|
183
|
+
* sentinel expires (https://github.com/vercel/resumable-stream/issues/53).
|
|
184
|
+
*/
|
|
185
|
+
const read = async () => {
|
|
186
|
+
try {
|
|
187
|
+
const reader = makeStream().getReader();
|
|
188
|
+
while (true) {
|
|
189
|
+
const { done, value } = await reader.read();
|
|
190
|
+
if (done) break;
|
|
191
|
+
chunks.push(value);
|
|
192
|
+
try {
|
|
193
|
+
controller.enqueue(value);
|
|
194
|
+
} catch {}
|
|
195
|
+
for (const listenerId of listenerIds) publish(chunkChannel(listenerId), value);
|
|
196
|
+
}
|
|
197
|
+
try {
|
|
198
|
+
controller.close();
|
|
199
|
+
} catch {}
|
|
200
|
+
} catch (error) {
|
|
201
|
+
try {
|
|
202
|
+
controller.error(error);
|
|
203
|
+
} catch {}
|
|
204
|
+
} finally {
|
|
205
|
+
await finish();
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
read();
|
|
209
|
+
} });
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Asks the producer of `streamId` for its chunks and gives them as a stream. Settles with
|
|
213
|
+
* the stream on the first answer, with `null` if the producer has finished, and rejects
|
|
214
|
+
* with an `AckTimeoutError` if no answer comes in time.
|
|
215
|
+
*/
|
|
216
|
+
function resumeStream(ctx, streamId) {
|
|
217
|
+
const listenerId = crypto.randomUUID();
|
|
218
|
+
const chunkChannel = `${ctx.keyPrefix}:chunk:${listenerId}`;
|
|
219
|
+
const sentinelKey = `${ctx.keyPrefix}:sentinel:${streamId}`;
|
|
220
|
+
return new Promise((resolve, reject) => {
|
|
221
|
+
/**
|
|
222
|
+
* Differs from upstream: the promise settles once, also when the timeout and an answer
|
|
223
|
+
* race. Upstream can settle twice, and can also not settle at all
|
|
224
|
+
* (https://github.com/vercel/resumable-stream/issues/50,
|
|
225
|
+
* https://github.com/vercel/resumable-stream/pull/43).
|
|
226
|
+
*/
|
|
227
|
+
let settled = false;
|
|
228
|
+
const settle = (fn) => {
|
|
229
|
+
if (settled) return;
|
|
230
|
+
settled = true;
|
|
231
|
+
fn();
|
|
232
|
+
};
|
|
233
|
+
let ackTimeout;
|
|
234
|
+
let watchdogTimeout;
|
|
235
|
+
let timedOut = false;
|
|
236
|
+
let cleanupPromise;
|
|
237
|
+
let onMessage;
|
|
238
|
+
/**
|
|
239
|
+
* Differs from upstream: cannot reject. Upstream awaits it in the message listener and
|
|
240
|
+
* in the timer, where a failed unsubscribe, for example on a dropped connection, is an
|
|
241
|
+
* unhandled rejection. The subscription is gone with the connection in that case.
|
|
242
|
+
*/
|
|
243
|
+
const cleanup = () => {
|
|
244
|
+
cleanupPromise ??= (async () => {
|
|
245
|
+
clearTimeout(ackTimeout);
|
|
246
|
+
clearTimeout(watchdogTimeout);
|
|
247
|
+
await ctx.subscriber.unsubscribe(chunkChannel, onMessage).catch(noop);
|
|
248
|
+
})();
|
|
249
|
+
return cleanupPromise;
|
|
250
|
+
};
|
|
251
|
+
const readableStream = new ReadableStream({
|
|
252
|
+
async start(controller) {
|
|
253
|
+
const closeStream = () => {
|
|
254
|
+
try {
|
|
255
|
+
controller.close();
|
|
256
|
+
} catch {}
|
|
257
|
+
};
|
|
258
|
+
/**
|
|
259
|
+
* The DONE message travels over pub/sub and can be lost, for example on a
|
|
260
|
+
* reconnect. The sentinel is checked from time to time, and the stream closes
|
|
261
|
+
* after two checks in a row see it done or gone, so that messages still in transit
|
|
262
|
+
* get one interval to arrive. From upstream 2.2.13
|
|
263
|
+
* (https://github.com/vercel/resumable-stream/pull/47).
|
|
264
|
+
*/
|
|
265
|
+
let doneObservations = 0;
|
|
266
|
+
let watchdogStarted = false;
|
|
267
|
+
const scheduleDoneWatchdog = () => {
|
|
268
|
+
if (cleanupPromise) return;
|
|
269
|
+
watchdogTimeout = setTimeout(() => void checkDone(), ctx.doneWatchdogIntervalMs);
|
|
270
|
+
};
|
|
271
|
+
const startDoneWatchdog = () => {
|
|
272
|
+
if (watchdogStarted) return;
|
|
273
|
+
watchdogStarted = true;
|
|
274
|
+
scheduleDoneWatchdog();
|
|
275
|
+
};
|
|
276
|
+
const checkDone = async () => {
|
|
277
|
+
try {
|
|
278
|
+
const state = await ctx.publisher.get(sentinelKey);
|
|
279
|
+
if (state !== DONE_VALUE && state !== null) {
|
|
280
|
+
doneObservations = 0;
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
doneObservations += 1;
|
|
284
|
+
if (doneObservations < 2) return;
|
|
285
|
+
closeStream();
|
|
286
|
+
await cleanup();
|
|
287
|
+
} catch {} finally {
|
|
288
|
+
scheduleDoneWatchdog();
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
/**
|
|
292
|
+
* Differs from upstream:
|
|
293
|
+
* - The wait is configurable (https://github.com/vercel/resumable-stream/issues/42).
|
|
294
|
+
* - The timer always settles the promise: with `null` if the producer has
|
|
295
|
+
* finished, else with an `AckTimeoutError`. Upstream also checks that the wall
|
|
296
|
+
* clock moved on by more than 1000 ms. When the timer fires at exactly 1000 ms,
|
|
297
|
+
* or when the clock goes back, the promise never settles. Upstream also awaits
|
|
298
|
+
* Redis in the timer with no handler, so a failure is an unhandled rejection
|
|
299
|
+
* (https://github.com/vercel/resumable-stream/issues/50,
|
|
300
|
+
* https://github.com/vercel/resumable-stream/pull/43).
|
|
301
|
+
* - An answer that arrives after the timer fired is ignored, so it cannot open a
|
|
302
|
+
* stream that the timer is about to fail.
|
|
303
|
+
*/
|
|
304
|
+
const onAckTimeout = async () => {
|
|
305
|
+
timedOut = true;
|
|
306
|
+
await cleanup();
|
|
307
|
+
if (await ctx.publisher.get(sentinelKey).catch(() => void 0) === DONE_VALUE) {
|
|
308
|
+
closeStream();
|
|
309
|
+
settle(() => resolve(null));
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
const error = new AckTimeoutError();
|
|
313
|
+
try {
|
|
314
|
+
controller.error(error);
|
|
315
|
+
} catch {}
|
|
316
|
+
settle(() => reject(error));
|
|
317
|
+
};
|
|
318
|
+
/**
|
|
319
|
+
* Differs from upstream: a plain function. Upstream passes an async listener whose
|
|
320
|
+
* promise the Redis client ignores, so a failed cleanup in it was an unhandled
|
|
321
|
+
* rejection.
|
|
322
|
+
*/
|
|
323
|
+
onMessage = (message) => {
|
|
324
|
+
if (timedOut) return;
|
|
325
|
+
/** The producer always answers, with an empty string if it has no chunk yet */
|
|
326
|
+
clearTimeout(ackTimeout);
|
|
327
|
+
settle(() => resolve(readableStream));
|
|
328
|
+
if (message === DONE_MESSAGE) {
|
|
329
|
+
closeStream();
|
|
330
|
+
cleanup();
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
startDoneWatchdog();
|
|
334
|
+
try {
|
|
335
|
+
controller.enqueue(message);
|
|
336
|
+
} catch {
|
|
337
|
+
/** The client cancelled the stream */
|
|
338
|
+
cleanup();
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
try {
|
|
342
|
+
ackTimeout = setTimeout(() => void onAckTimeout(), ctx.ackTimeoutMs);
|
|
343
|
+
await ctx.subscriber.subscribe(chunkChannel, onMessage);
|
|
344
|
+
const request = { listenerId };
|
|
345
|
+
await ctx.publisher.publish(`${ctx.keyPrefix}:request:${streamId}`, JSON.stringify(request));
|
|
346
|
+
} catch (error) {
|
|
347
|
+
await cleanup();
|
|
348
|
+
settle(() => reject(error));
|
|
349
|
+
}
|
|
350
|
+
},
|
|
351
|
+
async cancel() {
|
|
352
|
+
await cleanup();
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
//#endregion
|
|
2
358
|
//#region src/adapters/redis/sse.ts
|
|
3
359
|
/**
|
|
4
|
-
*
|
|
360
|
+
* The runtime transports a stream of strings that it is free to concatenate and
|
|
5
361
|
* re-slice, so chunks have to carry their own boundaries. SSE framing supplies them:
|
|
6
362
|
* chunks are JSON, which never contains a raw newline, so a blank line always ends one.
|
|
7
363
|
*/
|
|
@@ -44,12 +400,9 @@ function sseToChunks() {
|
|
|
44
400
|
//#region src/adapters/redis/adapter.ts
|
|
45
401
|
const DEFAULT_KEY_PREFIX = `ai-resumable-stream`;
|
|
46
402
|
/**
|
|
47
|
-
*
|
|
48
|
-
* soon as the source ends, so this only bounds the leak from a producer that died before
|
|
49
|
-
* it could clean up. There is nothing to gain from expiring sooner than the stream state
|
|
50
|
-
* it points at.
|
|
403
|
+
* The fixed lifetime of the original `resumable-stream`, long enough for any chat turn.
|
|
51
404
|
*/
|
|
52
|
-
const
|
|
405
|
+
const DEFAULT_TTL_SECONDS = 1440 * 60;
|
|
53
406
|
/**
|
|
54
407
|
* Deletes a key only while it still holds the expected value. One script, so no other
|
|
55
408
|
* client can write the key between the comparison and the deletion.
|
|
@@ -62,24 +415,14 @@ const DELETE_IF_EQUAL_SCRIPT = `if redis.call("GET", KEYS[1]) == ARGV[1] then re
|
|
|
62
415
|
*/
|
|
63
416
|
const STOP_TTL_SECONDS = 3600;
|
|
64
417
|
/**
|
|
65
|
-
*
|
|
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.
|
|
69
|
-
*/
|
|
70
|
-
const ACK_TIMEOUT_MESSAGE = `Timeout waiting for ack`;
|
|
71
|
-
function isAckTimeout(error) {
|
|
72
|
-
return (error instanceof Error ? error.message : String(error)).includes(ACK_TIMEOUT_MESSAGE);
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* Stores streams in Redis via `resumable-stream`.
|
|
418
|
+
* Stores streams in Redis, with a runtime derived from `resumable-stream`.
|
|
76
419
|
*
|
|
77
420
|
* Chunks live in the memory of the producing process and reach late subscribers over
|
|
78
421
|
* Redis pub/sub, so a stream is only resumable while its producer is alive. Use a
|
|
79
422
|
* durable adapter when a stream must outlive the process that started it.
|
|
80
423
|
*/
|
|
81
424
|
function createRedisAdapter(options) {
|
|
82
|
-
const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX } = options;
|
|
425
|
+
const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX, ackTimeoutMs, ttlSeconds = DEFAULT_TTL_SECONDS } = options;
|
|
83
426
|
/**
|
|
84
427
|
* The name of one generation of a stream id. The generation id is encoded, so it holds
|
|
85
428
|
* no colon and the name splits one way only: stream `a` with generation `b:c` never
|
|
@@ -110,11 +453,13 @@ function createRedisAdapter(options) {
|
|
|
110
453
|
await Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]);
|
|
111
454
|
}
|
|
112
455
|
function createContext(waitUntil) {
|
|
113
|
-
return
|
|
114
|
-
waitUntil
|
|
456
|
+
return createRuntime({
|
|
457
|
+
waitUntil,
|
|
115
458
|
publisher,
|
|
116
459
|
subscriber,
|
|
117
|
-
keyPrefix
|
|
460
|
+
keyPrefix,
|
|
461
|
+
ackTimeoutMs,
|
|
462
|
+
ttlSeconds
|
|
118
463
|
});
|
|
119
464
|
}
|
|
120
465
|
async function readPointer(streamId) {
|
|
@@ -142,24 +487,25 @@ function createRedisAdapter(options) {
|
|
|
142
487
|
async createStream({ streamId, generationId: runId, chunks, waitUntil }) {
|
|
143
488
|
await connect();
|
|
144
489
|
/**
|
|
145
|
-
* The pointer holds the full name, which is also the id
|
|
490
|
+
* The pointer holds the full name, which is also the id the runtime knows
|
|
146
491
|
* the generation by, so two stream ids with the same generation id never share
|
|
147
492
|
* state.
|
|
148
493
|
*/
|
|
149
494
|
const generationId = generationName(streamId, runId);
|
|
495
|
+
/**
|
|
496
|
+
* The pointer lives as long as the sentinel of the runtime. The adapter deletes it
|
|
497
|
+
* when the source ends, so the expiry only removes the pointer of a producer that
|
|
498
|
+
* died before it could clean up. A pointer that lives longer than its sentinel only
|
|
499
|
+
* leads to a stream that the runtime does not know.
|
|
500
|
+
*/
|
|
150
501
|
await publisher.set(pointerKey(streamId), generationId, { expiration: {
|
|
151
502
|
type: `EX`,
|
|
152
|
-
value:
|
|
503
|
+
value: ttlSeconds
|
|
153
504
|
} });
|
|
154
505
|
/**
|
|
155
506
|
* The pointer is dropped as soon as the source ends, so a resume that arrives
|
|
156
507
|
* during teardown is told there is nothing to resume rather than racing it. The
|
|
157
508
|
* 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.
|
|
163
509
|
*/
|
|
164
510
|
const sse = chunks.pipeThrough(chunksToSSE()).pipeThrough(new TransformStream({ async flush() {
|
|
165
511
|
await Promise.all([clearPointer(streamId, generationId), clearStop(streamId, runId)]).catch(() => {
|
|
@@ -173,22 +519,19 @@ function createRedisAdapter(options) {
|
|
|
173
519
|
/**
|
|
174
520
|
* A named generation is followed without the pointer, so it can be resumed after a
|
|
175
521
|
* newer generation took the stream id. Whether its producer is still alive is then only
|
|
176
|
-
* known from
|
|
522
|
+
* known from the runtime itself.
|
|
177
523
|
*/
|
|
178
524
|
const generationId = runId === void 0 ? await readPointer(streamId) : generationName(streamId, runId);
|
|
179
525
|
if (!generationId) return null;
|
|
180
526
|
/**
|
|
181
|
-
* A producer that died without marking its generation done never answers, and
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
* TODO(#21): bound this call with a time limit of our own, because the upstream
|
|
185
|
-
* timeout does not always settle.
|
|
527
|
+
* A producer that died without marking its generation done never answers, and the
|
|
528
|
+
* runtime rejects after waiting for it. There is nothing to resume.
|
|
186
529
|
*/
|
|
187
530
|
let sse;
|
|
188
531
|
try {
|
|
189
532
|
sse = await createContext().resumeExistingStream(generationId);
|
|
190
533
|
} catch (error) {
|
|
191
|
-
if (
|
|
534
|
+
if (error instanceof AckTimeoutError) return null;
|
|
192
535
|
throw error;
|
|
193
536
|
}
|
|
194
537
|
if (!sse) return null;
|
|
@@ -205,7 +548,7 @@ function createRedisAdapter(options) {
|
|
|
205
548
|
first = await reader.read();
|
|
206
549
|
} catch (error) {
|
|
207
550
|
reader.releaseLock();
|
|
208
|
-
if (
|
|
551
|
+
if (error instanceof AckTimeoutError) return null;
|
|
209
552
|
throw error;
|
|
210
553
|
}
|
|
211
554
|
if (first.done) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-resumable-stream",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.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",
|
|
@@ -30,8 +30,7 @@
|
|
|
30
30
|
"./package.json": "./package.json"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"ai-stream-utils": "^3.1.1"
|
|
34
|
-
"resumable-stream": "^2.2.12"
|
|
33
|
+
"ai-stream-utils": "^3.1.1"
|
|
35
34
|
},
|
|
36
35
|
"devDependencies": {
|
|
37
36
|
"@ai-sdk/provider": "^4.0.3",
|