ai-resumable-stream 3.2.1 → 3.4.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 +46 -15
- package/dist/{adapter-BwSsPtDm.d.mts → adapter-DZmSMkrn.d.mts} +6 -0
- package/dist/adapters/redis/index.d.mts +59 -10
- package/dist/adapters/redis/index.mjs +491 -55
- package/dist/adapters/s3-express/index.d.mts +1 -1
- package/dist/ai-sdk/index.d.mts +2 -2
- package/dist/ai-sdk/index.mjs +1 -1
- package/dist/{core-t_PoYw_Z.d.mts → core-CHVIveYo.d.mts} +16 -2
- package/dist/{core-2FBKiKXe.mjs → core-DfQuMgU1.mjs} +35 -6
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- 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
|
|
|
@@ -196,6 +196,17 @@ async function resumeMessage(chatId: string) {
|
|
|
196
196
|
}
|
|
197
197
|
```
|
|
198
198
|
|
|
199
|
+
Pass the `signal` of the incoming request. If the client goes away, the resume ends at once and frees its resources, also while it still waits for the first chunk of the producer. The signal applies to the full resume, until the stream ends. Before `resumeStream` returns, the promise rejects with the reason of the signal. After that, the returned stream errors with it.
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
// GET /chat/:chatId/stream
|
|
203
|
+
export async function resume(chatId: string, request: Request) {
|
|
204
|
+
const stream = await context.resumeStream({ streamId: chatId, signal: request.signal });
|
|
205
|
+
|
|
206
|
+
return stream ?? new Response(null, { status: 204 });
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
199
210
|
The result is `null` in three cases. The library does not tell you which case applies:
|
|
200
211
|
|
|
201
212
|
- no stream was started with that id
|
|
@@ -296,11 +307,15 @@ const context = createResumableUIMessageStream({
|
|
|
296
307
|
});
|
|
297
308
|
```
|
|
298
309
|
|
|
299
|
-
| Option
|
|
300
|
-
|
|
|
301
|
-
| `publisher`
|
|
302
|
-
| `subscriber`
|
|
303
|
-
| `keyPrefix`
|
|
310
|
+
| Option | Type | Required | Description |
|
|
311
|
+
| ------------------ | ------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
312
|
+
| `publisher` | `RedisClient` | Yes | Client that sends commands and publishes messages |
|
|
313
|
+
| `subscriber` | `RedisClient` | Yes | Client for subscriptions. Must be a separate client, because a subscribed connection cannot send commands |
|
|
314
|
+
| `keyPrefix` | `string` | No | Prefix for all keys and channels. Defaults to `ai-resumable-stream` |
|
|
315
|
+
| `ackTimeoutMs` | `number` | No | How long a resume waits for the producer to answer before it returns `null`. Defaults to `1000` |
|
|
316
|
+
| `expireAfterMs` | `number` | No | When the pointer of a stream id expires. Must be longer than your longest stream. Defaults to `86400000` (24 hours) |
|
|
317
|
+
| `commandTimeoutMs` | `number` | No | How long a call waits for Redis before it rejects with a `CommandTimeoutError` (its `name` is `TimeoutError`). Defaults to no limit |
|
|
318
|
+
| `heartbeatMs` | `number` | No | How often a producer renews the mark that its stream is running. The mark expires after three intervals, so a dead producer is detected after three intervals. Defaults to `30000` (30 s, detection after 90 s) |
|
|
304
319
|
|
|
305
320
|
> [!IMPORTANT]
|
|
306
321
|
> **A stream is only resumable while its producer is alive.**
|
|
@@ -358,10 +373,10 @@ const adapter: StreamAdapter = {
|
|
|
358
373
|
};
|
|
359
374
|
```
|
|
360
375
|
|
|
361
|
-
- **`createStream`**
|
|
362
|
-
- **`resumeStream`**
|
|
363
|
-
- **`requestStop`**
|
|
364
|
-
- **`onStopRequested`**
|
|
376
|
+
- **`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.
|
|
377
|
+
- **`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. The library cancels the returned stream when the `signal` of the caller aborts. An adapter can also use `signal` to free a subscription or a wait sooner.
|
|
378
|
+
- **`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.
|
|
379
|
+
- **`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
380
|
|
|
366
381
|
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
382
|
|
|
@@ -389,7 +404,7 @@ import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
|
|
|
389
404
|
const context = createResumableUIMessageStream({ adapter });
|
|
390
405
|
```
|
|
391
406
|
|
|
392
|
-
This is the same as `createResumableStream({ adapter, codec: uiMessageChunkCodec })`. The codec validates each chunk when
|
|
407
|
+
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
408
|
|
|
394
409
|
For other chunk types, pass your own `StreamCodec`:
|
|
395
410
|
|
|
@@ -416,9 +431,23 @@ import { waitUntil } from "@vercel/functions";
|
|
|
416
431
|
const context = createResumableUIMessageStream({ adapter, waitUntil });
|
|
417
432
|
```
|
|
418
433
|
|
|
434
|
+
The library gives `waitUntil` a promise for each task that runs after the response: reading the source, the teardown of the adapter, and the stop listener. None of these promises rejects. If you close your store clients, for example the Redis clients, collect the promises and wait for them first. Otherwise the teardown can fail and leave the stream marked as running:
|
|
435
|
+
|
|
436
|
+
```ts
|
|
437
|
+
const pending: Array<Promise<unknown>> = [];
|
|
438
|
+
const context = createResumableUIMessageStream({
|
|
439
|
+
adapter,
|
|
440
|
+
waitUntil: (promise) => pending.push(promise),
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
// Before shutdown
|
|
444
|
+
await Promise.all(pending);
|
|
445
|
+
await Promise.all([publisher.quit(), subscriber.quit()]);
|
|
446
|
+
```
|
|
447
|
+
|
|
419
448
|
### Finish
|
|
420
449
|
|
|
421
|
-
The `onFinish`
|
|
450
|
+
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
451
|
|
|
423
452
|
```typescript
|
|
424
453
|
const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
|
|
@@ -501,7 +530,7 @@ export const appRouter = router({
|
|
|
501
530
|
});
|
|
502
531
|
```
|
|
503
532
|
|
|
504
|
-
## API
|
|
533
|
+
## API reference
|
|
505
534
|
|
|
506
535
|
### `createResumableStream`
|
|
507
536
|
|
|
@@ -540,6 +569,7 @@ type StartStreamResult<CHUNK> = {
|
|
|
540
569
|
type ResumeStreamOptions = {
|
|
541
570
|
streamId: string;
|
|
542
571
|
generationId?: string;
|
|
572
|
+
signal?: AbortSignal;
|
|
543
573
|
};
|
|
544
574
|
|
|
545
575
|
type StopStreamOptions = {
|
|
@@ -552,7 +582,7 @@ type StopStreamOptions = {
|
|
|
552
582
|
| ------------ | -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
553
583
|
| `adapter` | `StreamAdapter` | Yes | Stores the chunks and transports stop requests |
|
|
554
584
|
| `codec` | `StreamCodec<CHUNK>` | Yes | Converts chunks to strings for the adapter, and back |
|
|
555
|
-
| `waitUntil` | `(promise) => void` | No |
|
|
585
|
+
| `waitUntil` | `(promise) => void` | No | Receives a promise for each task after the response. Keeps a serverless function alive, and lets you wait before you close the clients |
|
|
556
586
|
| `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` |
|
|
557
587
|
|
|
558
588
|
### `createResumableUIMessageStream`
|
|
@@ -578,6 +608,7 @@ type StreamAdapter = {
|
|
|
578
608
|
resumeStream(options: {
|
|
579
609
|
streamId: string;
|
|
580
610
|
generationId?: string;
|
|
611
|
+
signal?: AbortSignal;
|
|
581
612
|
}): Promise<ReadableStream<string> | null>;
|
|
582
613
|
requestStop(options: { streamId: string; generationId?: string }): Promise<void>;
|
|
583
614
|
onStopRequested(options: {
|
|
@@ -43,6 +43,12 @@ type StreamAdapter = {
|
|
|
43
43
|
resumeStream(options: {
|
|
44
44
|
streamId: string;
|
|
45
45
|
generationId?: string;
|
|
46
|
+
/**
|
|
47
|
+
* Aborts when the caller gives up on the resume. The caller enforces it already: it
|
|
48
|
+
* stops waiting, and it cancels the stream when the adapter returns it later. An
|
|
49
|
+
* adapter can also use it to free a subscription or a wait sooner.
|
|
50
|
+
*/
|
|
51
|
+
signal?: AbortSignal;
|
|
46
52
|
}): Promise<ReadableStream<string> | null>;
|
|
47
53
|
/**
|
|
48
54
|
* Signals the process that owns a generation of the stream to stop producing.
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { t as StreamAdapter } from "../../adapter-
|
|
2
|
-
import { Publisher, Subscriber } from "resumable-stream";
|
|
1
|
+
import { t as StreamAdapter } from "../../adapter-DZmSMkrn.mjs";
|
|
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,20 +6,22 @@ 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?: {
|
|
19
|
-
type: `EX`;
|
|
21
|
+
type: `EX` | `PX`;
|
|
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,57 @@ 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
|
+
* When the Redis keys of a stream expire, in milliseconds: the pointer of the stream id
|
|
54
|
+
* and the mark of a finished stream. Must be longer than your longest stream, because a
|
|
55
|
+
* resume without a generation id finds nothing after the pointer expired, even while the
|
|
56
|
+
* producer still runs. The stream of a producer that died is gone sooner, because its
|
|
57
|
+
* producer no longer renews it. Defaults to 24 hours.
|
|
58
|
+
*/
|
|
59
|
+
expireAfterMs?: number;
|
|
60
|
+
/**
|
|
61
|
+
* The same as `expireAfterMs`, in seconds. Ignored when `expireAfterMs` is set.
|
|
62
|
+
*
|
|
63
|
+
* @deprecated Use `expireAfterMs`.
|
|
64
|
+
*/
|
|
65
|
+
ttlSeconds?: number;
|
|
66
|
+
/**
|
|
67
|
+
* How long the adapter waits for Redis when it connects, registers a stream, reads the
|
|
68
|
+
* pointer, or sends and listens for a stop. After this time, the call rejects with a
|
|
69
|
+
* `CommandTimeoutError`. Use it when Redis can become unreachable: the client does not
|
|
70
|
+
* get an answer from a dead peer, and the timeout and the abort signal of the client no
|
|
71
|
+
* longer apply once a command is written. The command can still be pending in the client.
|
|
72
|
+
* Defaults to no limit.
|
|
73
|
+
*/
|
|
74
|
+
commandTimeoutMs?: number;
|
|
75
|
+
/**
|
|
76
|
+
* How often a producer renews the mark that its stream is running. The mark expires
|
|
77
|
+
* after three intervals without a renewal, so the stream of a producer that died is
|
|
78
|
+
* gone after three intervals. Each renewal is one Redis command per running stream.
|
|
79
|
+
* Defaults to 30 s, so a dead producer is detected after 90 s.
|
|
80
|
+
*/
|
|
81
|
+
heartbeatMs?: number;
|
|
44
82
|
};
|
|
45
83
|
/**
|
|
46
|
-
*
|
|
84
|
+
* Raised when Redis does not answer a call of the adapter within `commandTimeoutMs`.
|
|
85
|
+
*
|
|
86
|
+
* Its name is `TimeoutError`, the name of the error that `AbortSignal.timeout()` gives, so
|
|
87
|
+
* a check of `error.name === "TimeoutError"` finds both. A plain `Error` and not a
|
|
88
|
+
* `DOMException`, because a `DOMException` takes its name only from its constructor, and a
|
|
89
|
+
* subclass of it is unusual.
|
|
90
|
+
*/
|
|
91
|
+
declare class CommandTimeoutError extends Error {
|
|
92
|
+
constructor(timeoutMs: number);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Stores streams in Redis, with a runtime derived from `resumable-stream`.
|
|
47
96
|
*
|
|
48
97
|
* Chunks live in the memory of the producing process and reach late subscribers over
|
|
49
98
|
* Redis pub/sub, so a stream is only resumable while its producer is alive. Use a
|
|
@@ -51,4 +100,4 @@ type CreateRedisAdapterOptions = {
|
|
|
51
100
|
*/
|
|
52
101
|
declare function createRedisAdapter(options: CreateRedisAdapterOptions): StreamAdapter;
|
|
53
102
|
//#endregion
|
|
54
|
-
export { type CreateRedisAdapterOptions, createRedisAdapter };
|
|
103
|
+
export { CommandTimeoutError, type CreateRedisAdapterOptions, createRedisAdapter };
|
|
@@ -1,7 +1,397 @@
|
|
|
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
|
+
/**
|
|
44
|
+
* Long enough to keep the commands few, one SET per running stream every 30 s, and short
|
|
45
|
+
* enough that the stream of a producer that died is gone in about 1.5 minutes.
|
|
46
|
+
*/
|
|
47
|
+
const DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
|
|
48
|
+
/**
|
|
49
|
+
* The running sentinel lives this many heartbeat intervals, so two renewals in a row can
|
|
50
|
+
* fail, for example during a reconnect, before it expires.
|
|
51
|
+
*/
|
|
52
|
+
const HEARTBEATS_PER_SENTINEL_TTL = 3;
|
|
53
|
+
function noop() {}
|
|
54
|
+
function createRuntime(options) {
|
|
55
|
+
const ctx = {
|
|
56
|
+
keyPrefix: `${options.keyPrefix}:rs`,
|
|
57
|
+
publisher: options.publisher,
|
|
58
|
+
subscriber: options.subscriber,
|
|
59
|
+
waitUntil: options.waitUntil ?? noop,
|
|
60
|
+
ackTimeoutMs: options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS,
|
|
61
|
+
expireAfterMs: options.expireAfterMs,
|
|
62
|
+
doneWatchdogIntervalMs: options.doneWatchdogIntervalMs ?? DEFAULT_DONE_WATCHDOG_INTERVAL_MS,
|
|
63
|
+
heartbeatIntervalMs: options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS
|
|
64
|
+
};
|
|
65
|
+
return {
|
|
66
|
+
createNewResumableStream: (streamId, makeStream) => createNewResumableStream(ctx, streamId, makeStream),
|
|
67
|
+
resumeExistingStream: (streamId) => resumeExistingStream(ctx, streamId)
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
async function resumeExistingStream(ctx, streamId) {
|
|
71
|
+
const state = await ctx.publisher.get(`${ctx.keyPrefix}:sentinel:${streamId}`);
|
|
72
|
+
if (!state) return void 0;
|
|
73
|
+
if (state === DONE_VALUE) return null;
|
|
74
|
+
return resumeStream(ctx, streamId);
|
|
75
|
+
}
|
|
76
|
+
async function createNewResumableStream(ctx, streamId, makeStream) {
|
|
77
|
+
const requestChannel = `${ctx.keyPrefix}:request:${streamId}`;
|
|
78
|
+
const sentinelKey = `${ctx.keyPrefix}:sentinel:${streamId}`;
|
|
79
|
+
const chunkChannel = (listenerId) => `${ctx.keyPrefix}:chunk:${listenerId}`;
|
|
80
|
+
const runningExpiration = { expiration: {
|
|
81
|
+
type: `PX`,
|
|
82
|
+
value: ctx.heartbeatIntervalMs * HEARTBEATS_PER_SENTINEL_TTL
|
|
83
|
+
} };
|
|
84
|
+
const doneExpiration = { expiration: {
|
|
85
|
+
type: `PX`,
|
|
86
|
+
value: ctx.expireAfterMs
|
|
87
|
+
} };
|
|
88
|
+
const chunks = [];
|
|
89
|
+
const listenerIds = [];
|
|
90
|
+
let isDone = false;
|
|
91
|
+
let resolveDone;
|
|
92
|
+
ctx.waitUntil(new Promise((resolve) => {
|
|
93
|
+
resolveDone = resolve;
|
|
94
|
+
}));
|
|
95
|
+
/**
|
|
96
|
+
* Publishes without waiting for the reply, and contains a failure.
|
|
97
|
+
*
|
|
98
|
+
* Differs from upstream in two ways:
|
|
99
|
+
* - Upstream awaits the publishes of each chunk before it reads the next one, so while a
|
|
100
|
+
* consumer is attached, the producer (and its own client) reads one chunk per Redis
|
|
101
|
+
* round trip (https://github.com/vercel/resumable-stream/issues/52). The client sends
|
|
102
|
+
* commands of one connection in the order they are called, so the consumer still
|
|
103
|
+
* gets the chunks in order.
|
|
104
|
+
* - Upstream does not handle a failed publish, so a dropped connection is an unhandled
|
|
105
|
+
* rejection that ends a Node process
|
|
106
|
+
* (https://github.com/vercel/resumable-stream/issues/53). A consumer that misses a
|
|
107
|
+
* chunk this way gets incomplete data, but a dropped connection also ends its own
|
|
108
|
+
* subscription.
|
|
109
|
+
*
|
|
110
|
+
* Publishes still in flight are kept, so the teardown can wait for them.
|
|
111
|
+
*/
|
|
112
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
113
|
+
const publish = (channel, message) => {
|
|
114
|
+
const promise = ctx.publisher.publish(channel, message).then(noop, noop);
|
|
115
|
+
inFlight.add(promise);
|
|
116
|
+
promise.then(() => inFlight.delete(promise));
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Answers a consumer with every chunk so far, and with DONE if the source has ended.
|
|
120
|
+
*
|
|
121
|
+
* Differs from upstream: upstream passes an async listener, whose promise the Redis
|
|
122
|
+
* client ignores. A failed publish was an unhandled rejection, and a message that is no
|
|
123
|
+
* JSON threw inside the client. No upstream issue covers this.
|
|
124
|
+
*/
|
|
125
|
+
const onRequest = (message) => {
|
|
126
|
+
let request;
|
|
127
|
+
try {
|
|
128
|
+
request = JSON.parse(message);
|
|
129
|
+
} catch {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (typeof request?.listenerId !== `string`) return;
|
|
133
|
+
listenerIds.push(request.listenerId);
|
|
134
|
+
const channel = chunkChannel(request.listenerId);
|
|
135
|
+
publish(channel, chunks.join(``).slice(request.skipCharacters ?? 0));
|
|
136
|
+
if (isDone) publish(channel, DONE_MESSAGE);
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Subscribed before the sentinel is set, so a consumer that sees the sentinel always
|
|
140
|
+
* finds the producer listening. From upstream 2.2.13
|
|
141
|
+
* (https://github.com/vercel/resumable-stream/pull/41).
|
|
142
|
+
*
|
|
143
|
+
* Differs from upstream: if this setup fails, the promise given to `waitUntil` still
|
|
144
|
+
* settles, and the subscription is removed again.
|
|
145
|
+
*/
|
|
146
|
+
try {
|
|
147
|
+
await ctx.subscriber.subscribe(requestChannel, onRequest);
|
|
148
|
+
try {
|
|
149
|
+
await ctx.publisher.set(sentinelKey, `1`, runningExpiration);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
await ctx.subscriber.unsubscribe(requestChannel, onRequest).catch(noop);
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
} catch (error) {
|
|
155
|
+
resolveDone();
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Renews the running sentinel while the producer is alive. A producer that died stops
|
|
160
|
+
* the renewals, so its sentinel expires: a new resume then finds no stream at once, and
|
|
161
|
+
* the watchdog of an attached consumer closes its stream. A failed renewal is retried at
|
|
162
|
+
* the next interval. The renewal is a plain SET, so it also restores a sentinel that
|
|
163
|
+
* expired while Redis was unreachable. The teardown stops the renewals before it sends
|
|
164
|
+
* DONE, and one connection keeps the order of its commands, so a renewal never
|
|
165
|
+
* overwrites DONE.
|
|
166
|
+
*
|
|
167
|
+
* Differs from upstream: upstream sets the running sentinel once, for 24 hours, so a
|
|
168
|
+
* consumer waits for the ack timeout on every resume of a stream whose producer died.
|
|
169
|
+
*/
|
|
170
|
+
const heartbeat = setInterval(() => {
|
|
171
|
+
ctx.publisher.set(sentinelKey, `1`, runningExpiration).catch(noop);
|
|
172
|
+
}, ctx.heartbeatIntervalMs);
|
|
173
|
+
/** A long-lived process can still exit while a stream runs */
|
|
174
|
+
heartbeat.unref?.();
|
|
175
|
+
/**
|
|
176
|
+
* Marks the stream done, tells the consumers and stops to answer requests.
|
|
177
|
+
*
|
|
178
|
+
* Differs from upstream:
|
|
179
|
+
* - Runs only once, and it cannot reject. Each command can fail alone, for example when
|
|
180
|
+
* Redis drops the connections, and the promise given to `waitUntil` still settles.
|
|
181
|
+
* Upstream awaits all commands together with no handler, so one failure is an
|
|
182
|
+
* unhandled rejection that ends a Node process, and the teardown never finishes
|
|
183
|
+
* (https://github.com/vercel/resumable-stream/issues/53,
|
|
184
|
+
* https://github.com/vercel/resumable-stream/pull/54).
|
|
185
|
+
* - Removes only its own listener of the request channel. Upstream removes every
|
|
186
|
+
* listener of the channel on the shared subscriber.
|
|
187
|
+
* - Waits for the chunk publishes still in flight, so a runtime that freezes the process
|
|
188
|
+
* after `waitUntil` does not lose them.
|
|
189
|
+
*
|
|
190
|
+
* If the DONE write fails, the sentinel stays "1" until it expires, which is three
|
|
191
|
+
* heartbeat intervals after the teardown stopped the renewals. A consumer then gets
|
|
192
|
+
* no answer and fails with the ack timeout.
|
|
193
|
+
*/
|
|
194
|
+
let finishing;
|
|
195
|
+
const finish = () => {
|
|
196
|
+
finishing ??= (async () => {
|
|
197
|
+
isDone = true;
|
|
198
|
+
clearInterval(heartbeat);
|
|
199
|
+
for (const listenerId of listenerIds) publish(chunkChannel(listenerId), DONE_MESSAGE);
|
|
200
|
+
await Promise.allSettled([
|
|
201
|
+
ctx.publisher.set(sentinelKey, DONE_VALUE, doneExpiration),
|
|
202
|
+
ctx.subscriber.unsubscribe(requestChannel, onRequest),
|
|
203
|
+
...inFlight
|
|
204
|
+
]);
|
|
205
|
+
resolveDone();
|
|
206
|
+
})();
|
|
207
|
+
return finishing;
|
|
208
|
+
};
|
|
209
|
+
return new ReadableStream({ start(controller) {
|
|
210
|
+
/**
|
|
211
|
+
* Reads the whole source, also when nobody reads this stream any more, so the
|
|
212
|
+
* consumers still get every chunk.
|
|
213
|
+
*
|
|
214
|
+
* Differs from upstream: the loop has a rejection handler. A source that errors
|
|
215
|
+
* errors this stream and still runs the teardown. Upstream gives an unhandled
|
|
216
|
+
* rejection, which ends a Node process, and the stream stays resumable until the
|
|
217
|
+
* sentinel expires (https://github.com/vercel/resumable-stream/issues/53).
|
|
218
|
+
*/
|
|
219
|
+
const read = async () => {
|
|
220
|
+
try {
|
|
221
|
+
const reader = makeStream().getReader();
|
|
222
|
+
while (true) {
|
|
223
|
+
const { done, value } = await reader.read();
|
|
224
|
+
if (done) break;
|
|
225
|
+
chunks.push(value);
|
|
226
|
+
try {
|
|
227
|
+
controller.enqueue(value);
|
|
228
|
+
} catch {}
|
|
229
|
+
for (const listenerId of listenerIds) publish(chunkChannel(listenerId), value);
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
controller.close();
|
|
233
|
+
} catch {}
|
|
234
|
+
} catch (error) {
|
|
235
|
+
try {
|
|
236
|
+
controller.error(error);
|
|
237
|
+
} catch {}
|
|
238
|
+
} finally {
|
|
239
|
+
await finish();
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
read();
|
|
243
|
+
} });
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Asks the producer of `streamId` for its chunks and gives them as a stream. Settles with
|
|
247
|
+
* the stream on the first answer, with `null` if the producer has finished, and rejects
|
|
248
|
+
* with an `AckTimeoutError` if no answer comes in time.
|
|
249
|
+
*/
|
|
250
|
+
function resumeStream(ctx, streamId) {
|
|
251
|
+
const listenerId = crypto.randomUUID();
|
|
252
|
+
const chunkChannel = `${ctx.keyPrefix}:chunk:${listenerId}`;
|
|
253
|
+
const sentinelKey = `${ctx.keyPrefix}:sentinel:${streamId}`;
|
|
254
|
+
return new Promise((resolve, reject) => {
|
|
255
|
+
/**
|
|
256
|
+
* Differs from upstream: the promise settles once, also when the timeout and an answer
|
|
257
|
+
* race. Upstream can settle twice, and can also not settle at all
|
|
258
|
+
* (https://github.com/vercel/resumable-stream/issues/50,
|
|
259
|
+
* https://github.com/vercel/resumable-stream/pull/43).
|
|
260
|
+
*/
|
|
261
|
+
let settled = false;
|
|
262
|
+
const settle = (fn) => {
|
|
263
|
+
if (settled) return;
|
|
264
|
+
settled = true;
|
|
265
|
+
fn();
|
|
266
|
+
};
|
|
267
|
+
let ackTimeout;
|
|
268
|
+
let watchdogTimeout;
|
|
269
|
+
let timedOut = false;
|
|
270
|
+
let cleanupPromise;
|
|
271
|
+
let onMessage;
|
|
272
|
+
/**
|
|
273
|
+
* Differs from upstream: cannot reject. Upstream awaits it in the message listener and
|
|
274
|
+
* in the timer, where a failed unsubscribe, for example on a dropped connection, is an
|
|
275
|
+
* unhandled rejection. The subscription is gone with the connection in that case.
|
|
276
|
+
*/
|
|
277
|
+
const cleanup = () => {
|
|
278
|
+
cleanupPromise ??= (async () => {
|
|
279
|
+
clearTimeout(ackTimeout);
|
|
280
|
+
clearTimeout(watchdogTimeout);
|
|
281
|
+
await ctx.subscriber.unsubscribe(chunkChannel, onMessage).catch(noop);
|
|
282
|
+
})();
|
|
283
|
+
return cleanupPromise;
|
|
284
|
+
};
|
|
285
|
+
const readableStream = new ReadableStream({
|
|
286
|
+
async start(controller) {
|
|
287
|
+
const closeStream = () => {
|
|
288
|
+
try {
|
|
289
|
+
controller.close();
|
|
290
|
+
} catch {}
|
|
291
|
+
};
|
|
292
|
+
/**
|
|
293
|
+
* The DONE message travels over pub/sub and can be lost, for example on a
|
|
294
|
+
* reconnect. The sentinel is checked from time to time, and the stream closes
|
|
295
|
+
* after two checks in a row see it done or gone, so that messages still in transit
|
|
296
|
+
* get one interval to arrive. From upstream 2.2.13
|
|
297
|
+
* (https://github.com/vercel/resumable-stream/pull/47).
|
|
298
|
+
*/
|
|
299
|
+
let doneObservations = 0;
|
|
300
|
+
let watchdogStarted = false;
|
|
301
|
+
const scheduleDoneWatchdog = () => {
|
|
302
|
+
if (cleanupPromise) return;
|
|
303
|
+
watchdogTimeout = setTimeout(() => void checkDone(), ctx.doneWatchdogIntervalMs);
|
|
304
|
+
};
|
|
305
|
+
const startDoneWatchdog = () => {
|
|
306
|
+
if (watchdogStarted) return;
|
|
307
|
+
watchdogStarted = true;
|
|
308
|
+
scheduleDoneWatchdog();
|
|
309
|
+
};
|
|
310
|
+
const checkDone = async () => {
|
|
311
|
+
try {
|
|
312
|
+
const state = await ctx.publisher.get(sentinelKey);
|
|
313
|
+
if (state !== DONE_VALUE && state !== null) {
|
|
314
|
+
doneObservations = 0;
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
doneObservations += 1;
|
|
318
|
+
if (doneObservations < 2) return;
|
|
319
|
+
closeStream();
|
|
320
|
+
await cleanup();
|
|
321
|
+
} catch {} finally {
|
|
322
|
+
scheduleDoneWatchdog();
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
/**
|
|
326
|
+
* Differs from upstream:
|
|
327
|
+
* - The wait is configurable (https://github.com/vercel/resumable-stream/issues/42).
|
|
328
|
+
* - The timer always settles the promise: with `null` if the producer has
|
|
329
|
+
* finished, else with an `AckTimeoutError`. Upstream also checks that the wall
|
|
330
|
+
* clock moved on by more than 1000 ms. When the timer fires at exactly 1000 ms,
|
|
331
|
+
* or when the clock goes back, the promise never settles. Upstream also awaits
|
|
332
|
+
* Redis in the timer with no handler, so a failure is an unhandled rejection
|
|
333
|
+
* (https://github.com/vercel/resumable-stream/issues/50,
|
|
334
|
+
* https://github.com/vercel/resumable-stream/pull/43).
|
|
335
|
+
* - An answer that arrives after the timer fired is ignored, so it cannot open a
|
|
336
|
+
* stream that the timer is about to fail.
|
|
337
|
+
*/
|
|
338
|
+
const onAckTimeout = async () => {
|
|
339
|
+
timedOut = true;
|
|
340
|
+
await cleanup();
|
|
341
|
+
if (await ctx.publisher.get(sentinelKey).catch(() => void 0) === DONE_VALUE) {
|
|
342
|
+
closeStream();
|
|
343
|
+
settle(() => resolve(null));
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const error = new AckTimeoutError();
|
|
347
|
+
try {
|
|
348
|
+
controller.error(error);
|
|
349
|
+
} catch {}
|
|
350
|
+
settle(() => reject(error));
|
|
351
|
+
};
|
|
352
|
+
/**
|
|
353
|
+
* Differs from upstream: a plain function. Upstream passes an async listener whose
|
|
354
|
+
* promise the Redis client ignores, so a failed cleanup in it was an unhandled
|
|
355
|
+
* rejection.
|
|
356
|
+
*/
|
|
357
|
+
onMessage = (message) => {
|
|
358
|
+
if (timedOut) return;
|
|
359
|
+
/** The producer always answers, with an empty string if it has no chunk yet */
|
|
360
|
+
clearTimeout(ackTimeout);
|
|
361
|
+
settle(() => resolve(readableStream));
|
|
362
|
+
if (message === DONE_MESSAGE) {
|
|
363
|
+
closeStream();
|
|
364
|
+
cleanup();
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
startDoneWatchdog();
|
|
368
|
+
try {
|
|
369
|
+
controller.enqueue(message);
|
|
370
|
+
} catch {
|
|
371
|
+
/** The client cancelled the stream */
|
|
372
|
+
cleanup();
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
try {
|
|
376
|
+
ackTimeout = setTimeout(() => void onAckTimeout(), ctx.ackTimeoutMs);
|
|
377
|
+
await ctx.subscriber.subscribe(chunkChannel, onMessage);
|
|
378
|
+
const request = { listenerId };
|
|
379
|
+
await ctx.publisher.publish(`${ctx.keyPrefix}:request:${streamId}`, JSON.stringify(request));
|
|
380
|
+
} catch (error) {
|
|
381
|
+
await cleanup();
|
|
382
|
+
settle(() => reject(error));
|
|
383
|
+
}
|
|
384
|
+
},
|
|
385
|
+
async cancel() {
|
|
386
|
+
await cleanup();
|
|
387
|
+
}
|
|
388
|
+
});
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
//#endregion
|
|
2
392
|
//#region src/adapters/redis/sse.ts
|
|
3
393
|
/**
|
|
4
|
-
*
|
|
394
|
+
* The runtime transports a stream of strings that it is free to concatenate and
|
|
5
395
|
* re-slice, so chunks have to carry their own boundaries. SSE framing supplies them:
|
|
6
396
|
* chunks are JSON, which never contains a raw newline, so a blank line always ends one.
|
|
7
397
|
*/
|
|
@@ -42,14 +432,25 @@ function sseToChunks() {
|
|
|
42
432
|
}
|
|
43
433
|
//#endregion
|
|
44
434
|
//#region src/adapters/redis/adapter.ts
|
|
435
|
+
/**
|
|
436
|
+
* Raised when Redis does not answer a call of the adapter within `commandTimeoutMs`.
|
|
437
|
+
*
|
|
438
|
+
* Its name is `TimeoutError`, the name of the error that `AbortSignal.timeout()` gives, so
|
|
439
|
+
* a check of `error.name === "TimeoutError"` finds both. A plain `Error` and not a
|
|
440
|
+
* `DOMException`, because a `DOMException` takes its name only from its constructor, and a
|
|
441
|
+
* subclass of it is unusual.
|
|
442
|
+
*/
|
|
443
|
+
var CommandTimeoutError = class extends Error {
|
|
444
|
+
constructor(timeoutMs) {
|
|
445
|
+
super(`Redis did not answer within ${timeoutMs} ms`);
|
|
446
|
+
this.name = `TimeoutError`;
|
|
447
|
+
}
|
|
448
|
+
};
|
|
45
449
|
const DEFAULT_KEY_PREFIX = `ai-resumable-stream`;
|
|
46
450
|
/**
|
|
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.
|
|
451
|
+
* The fixed lifetime of the original `resumable-stream`, long enough for any chat turn.
|
|
51
452
|
*/
|
|
52
|
-
const
|
|
453
|
+
const DEFAULT_EXPIRE_AFTER_MS = 1440 * 60 * 1e3;
|
|
53
454
|
/**
|
|
54
455
|
* Deletes a key only while it still holds the expected value. One script, so no other
|
|
55
456
|
* client can write the key between the comparison and the deletion.
|
|
@@ -62,24 +463,35 @@ const DELETE_IF_EQUAL_SCRIPT = `if redis.call("GET", KEYS[1]) == ARGV[1] then re
|
|
|
62
463
|
*/
|
|
63
464
|
const STOP_TTL_SECONDS = 3600;
|
|
64
465
|
/**
|
|
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`.
|
|
466
|
+
* Stores streams in Redis, with a runtime derived from `resumable-stream`.
|
|
76
467
|
*
|
|
77
468
|
* Chunks live in the memory of the producing process and reach late subscribers over
|
|
78
469
|
* Redis pub/sub, so a stream is only resumable while its producer is alive. Use a
|
|
79
470
|
* durable adapter when a stream must outlive the process that started it.
|
|
80
471
|
*/
|
|
81
472
|
function createRedisAdapter(options) {
|
|
82
|
-
const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX } = options;
|
|
473
|
+
const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX, ackTimeoutMs, ttlSeconds, commandTimeoutMs, heartbeatMs } = options;
|
|
474
|
+
if (heartbeatMs !== void 0 && !(heartbeatMs > 0)) throw new RangeError(`heartbeatMs must be greater than 0, got ${heartbeatMs}`);
|
|
475
|
+
const expireAfterMs = options.expireAfterMs ?? (ttlSeconds === void 0 ? DEFAULT_EXPIRE_AFTER_MS : ttlSeconds * 1e3);
|
|
476
|
+
/**
|
|
477
|
+
* Rejects with a `CommandTimeoutError` when the call takes longer than
|
|
478
|
+
* `commandTimeoutMs`. A late failure of the call is handled, so it is not an unhandled
|
|
479
|
+
* rejection.
|
|
480
|
+
*/
|
|
481
|
+
function limit(call) {
|
|
482
|
+
if (commandTimeoutMs === void 0) return call;
|
|
483
|
+
const timeoutMs = commandTimeoutMs;
|
|
484
|
+
return new Promise((resolve, reject) => {
|
|
485
|
+
const timer = setTimeout(() => reject(new CommandTimeoutError(timeoutMs)), timeoutMs);
|
|
486
|
+
call.then((value) => {
|
|
487
|
+
clearTimeout(timer);
|
|
488
|
+
resolve(value);
|
|
489
|
+
}, (error) => {
|
|
490
|
+
clearTimeout(timer);
|
|
491
|
+
reject(error);
|
|
492
|
+
});
|
|
493
|
+
});
|
|
494
|
+
}
|
|
83
495
|
/**
|
|
84
496
|
* The name of one generation of a stream id. The generation id is encoded, so it holds
|
|
85
497
|
* no colon and the name splits one way only: stream `a` with generation `b:c` never
|
|
@@ -107,25 +519,28 @@ function createRedisAdapter(options) {
|
|
|
107
519
|
*/
|
|
108
520
|
const pointerKey = (streamId) => `${keyPrefix}:generation:${streamId}`;
|
|
109
521
|
async function connect() {
|
|
110
|
-
await Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]);
|
|
522
|
+
await limit(Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]));
|
|
111
523
|
}
|
|
112
524
|
function createContext(waitUntil) {
|
|
113
|
-
return
|
|
114
|
-
waitUntil
|
|
525
|
+
return createRuntime({
|
|
526
|
+
waitUntil,
|
|
115
527
|
publisher,
|
|
116
528
|
subscriber,
|
|
117
|
-
keyPrefix
|
|
529
|
+
keyPrefix,
|
|
530
|
+
ackTimeoutMs,
|
|
531
|
+
expireAfterMs,
|
|
532
|
+
heartbeatIntervalMs: heartbeatMs
|
|
118
533
|
});
|
|
119
534
|
}
|
|
120
535
|
async function readPointer(streamId) {
|
|
121
|
-
return publisher.get(pointerKey(streamId));
|
|
536
|
+
return limit(publisher.get(pointerKey(streamId)));
|
|
122
537
|
}
|
|
123
538
|
/**
|
|
124
539
|
* Drops the stop kept for a generation once it is over, so nothing outlives the
|
|
125
540
|
* generation it was meant for.
|
|
126
541
|
*/
|
|
127
542
|
async function clearStop(streamId, generationId) {
|
|
128
|
-
await publisher.del(stopKey(streamId, generationId));
|
|
543
|
+
await limit(publisher.del(stopKey(streamId, generationId)));
|
|
129
544
|
}
|
|
130
545
|
/**
|
|
131
546
|
* Retires the generation, but only while it is still the current one, so a slow
|
|
@@ -133,62 +548,74 @@ function createRedisAdapter(options) {
|
|
|
133
548
|
* successor may repoint the id at any moment, including between the two.
|
|
134
549
|
*/
|
|
135
550
|
async function clearPointer(streamId, generationId) {
|
|
136
|
-
await publisher.eval(DELETE_IF_EQUAL_SCRIPT, {
|
|
551
|
+
await limit(publisher.eval(DELETE_IF_EQUAL_SCRIPT, {
|
|
137
552
|
keys: [pointerKey(streamId)],
|
|
138
553
|
arguments: [generationId]
|
|
139
|
-
});
|
|
554
|
+
}));
|
|
140
555
|
}
|
|
141
556
|
return {
|
|
142
557
|
async createStream({ streamId, generationId: runId, chunks, waitUntil }) {
|
|
143
558
|
await connect();
|
|
144
559
|
/**
|
|
145
|
-
* The pointer holds the full name, which is also the id
|
|
560
|
+
* The pointer holds the full name, which is also the id the runtime knows
|
|
146
561
|
* the generation by, so two stream ids with the same generation id never share
|
|
147
562
|
* state.
|
|
148
563
|
*/
|
|
149
564
|
const generationId = generationName(streamId, runId);
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
565
|
+
/**
|
|
566
|
+
* The pointer lives as long as the sentinel of the runtime. The adapter deletes it
|
|
567
|
+
* when the source ends, so the expiry only removes the pointer of a producer that
|
|
568
|
+
* died before it could clean up. A pointer that lives longer than its sentinel only
|
|
569
|
+
* leads to a stream that the runtime does not know.
|
|
570
|
+
*/
|
|
571
|
+
await limit(publisher.set(pointerKey(streamId), generationId, { expiration: {
|
|
572
|
+
type: `PX`,
|
|
573
|
+
value: expireAfterMs
|
|
574
|
+
} }));
|
|
154
575
|
/**
|
|
155
576
|
* The pointer is dropped as soon as the source ends, so a resume that arrives
|
|
156
577
|
* during teardown is told there is nothing to resume rather than racing it. The
|
|
157
578
|
* 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
579
|
*/
|
|
164
|
-
const
|
|
580
|
+
const abandon = new AbortController();
|
|
581
|
+
const sse = chunks.pipeThrough(chunksToSSE(), { signal: abandon.signal }).pipeThrough(new TransformStream({ async flush() {
|
|
165
582
|
await Promise.all([clearPointer(streamId, generationId), clearStop(streamId, runId)]).catch(() => {
|
|
166
583
|
/** Both expire on their own */
|
|
167
584
|
});
|
|
168
585
|
} }));
|
|
169
|
-
|
|
586
|
+
/**
|
|
587
|
+
* A registration that times out is abandoned. The runtime can still finish its setup
|
|
588
|
+
* later, so the pipe is aborted: the runtime then sees a failed source and tears the
|
|
589
|
+
* stream down, and the source is cancelled.
|
|
590
|
+
*/
|
|
591
|
+
try {
|
|
592
|
+
await limit(createContext(waitUntil).createNewResumableStream(generationId, () => sse));
|
|
593
|
+
} catch (error) {
|
|
594
|
+
abandon.abort(error);
|
|
595
|
+
await clearPointer(streamId, generationId).catch(() => {
|
|
596
|
+
/** It expires on its own */
|
|
597
|
+
});
|
|
598
|
+
throw error;
|
|
599
|
+
}
|
|
170
600
|
},
|
|
171
|
-
async resumeStream({ streamId, generationId: runId }) {
|
|
601
|
+
async resumeStream({ streamId, generationId: runId, signal }) {
|
|
172
602
|
await connect();
|
|
173
603
|
/**
|
|
174
604
|
* A named generation is followed without the pointer, so it can be resumed after a
|
|
175
605
|
* newer generation took the stream id. Whether its producer is still alive is then only
|
|
176
|
-
* known from
|
|
606
|
+
* known from the runtime itself.
|
|
177
607
|
*/
|
|
178
608
|
const generationId = runId === void 0 ? await readPointer(streamId) : generationName(streamId, runId);
|
|
179
609
|
if (!generationId) return null;
|
|
180
610
|
/**
|
|
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.
|
|
611
|
+
* A producer that died without marking its generation done never answers, and the
|
|
612
|
+
* runtime rejects after waiting for it. There is nothing to resume.
|
|
186
613
|
*/
|
|
187
614
|
let sse;
|
|
188
615
|
try {
|
|
189
616
|
sse = await createContext().resumeExistingStream(generationId);
|
|
190
617
|
} catch (error) {
|
|
191
|
-
if (
|
|
618
|
+
if (error instanceof AckTimeoutError) return null;
|
|
192
619
|
throw error;
|
|
193
620
|
}
|
|
194
621
|
if (!sse) return null;
|
|
@@ -201,12 +628,21 @@ function createRedisAdapter(options) {
|
|
|
201
628
|
* not yet emitted anything waits for its first chunk.
|
|
202
629
|
*/
|
|
203
630
|
let first;
|
|
631
|
+
/**
|
|
632
|
+
* A producer that never sends its first chunk would hold this read, and with it the
|
|
633
|
+
* subscription, forever. The abort cancels the read, which removes the subscription.
|
|
634
|
+
*/
|
|
635
|
+
const onAbort = () => void reader.cancel(signal?.reason).catch(() => void 0);
|
|
636
|
+
signal?.addEventListener(`abort`, onAbort, { once: true });
|
|
204
637
|
try {
|
|
638
|
+
if (signal?.aborted) onAbort();
|
|
205
639
|
first = await reader.read();
|
|
206
640
|
} catch (error) {
|
|
207
641
|
reader.releaseLock();
|
|
208
|
-
if (
|
|
642
|
+
if (error instanceof AckTimeoutError) return null;
|
|
209
643
|
throw error;
|
|
644
|
+
} finally {
|
|
645
|
+
signal?.removeEventListener(`abort`, onAbort);
|
|
210
646
|
}
|
|
211
647
|
if (first.done) {
|
|
212
648
|
reader.releaseLock();
|
|
@@ -245,26 +681,26 @@ function createRedisAdapter(options) {
|
|
|
245
681
|
* Kept before it is published. A producer subscribes before it reads, so it either
|
|
246
682
|
* receives the message or finds the key.
|
|
247
683
|
*/
|
|
248
|
-
await publisher.set(stopKey(streamId, runId), `1`, { expiration: {
|
|
684
|
+
await limit(publisher.set(stopKey(streamId, runId), `1`, { expiration: {
|
|
249
685
|
type: `EX`,
|
|
250
686
|
value: STOP_TTL_SECONDS
|
|
251
|
-
} });
|
|
252
|
-
await publisher.publish(stopChannel(streamId, runId), `stop`);
|
|
687
|
+
} }));
|
|
688
|
+
await limit(publisher.publish(stopChannel(streamId, runId), `stop`));
|
|
253
689
|
},
|
|
254
690
|
async onStopRequested({ streamId, generationId, onStop }) {
|
|
255
691
|
await connect();
|
|
256
692
|
const channel = stopChannel(streamId, generationId);
|
|
257
693
|
const listener = () => onStop();
|
|
258
|
-
await subscriber.subscribe(channel, listener);
|
|
694
|
+
await limit(subscriber.subscribe(channel, listener));
|
|
259
695
|
const unsubscribe = async () => {
|
|
260
|
-
await subscriber.unsubscribe(channel, listener);
|
|
696
|
+
await limit(subscriber.unsubscribe(channel, listener));
|
|
261
697
|
};
|
|
262
698
|
/**
|
|
263
699
|
* Read only once subscribed. Reading first, or both at once, leaves a window in
|
|
264
700
|
* which a stop is neither kept yet nor delivered.
|
|
265
701
|
*/
|
|
266
702
|
try {
|
|
267
|
-
if (await publisher.get(stopKey(streamId, generationId)) !== null) onStop();
|
|
703
|
+
if (await limit(publisher.get(stopKey(streamId, generationId))) !== null) onStop();
|
|
268
704
|
} catch (error) {
|
|
269
705
|
await unsubscribe().catch(() => {
|
|
270
706
|
/** The subscription is gone with the connection */
|
|
@@ -276,4 +712,4 @@ function createRedisAdapter(options) {
|
|
|
276
712
|
};
|
|
277
713
|
}
|
|
278
714
|
//#endregion
|
|
279
|
-
export { createRedisAdapter };
|
|
715
|
+
export { CommandTimeoutError, createRedisAdapter };
|
package/dist/ai-sdk/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as StreamCodec } from "../adapter-
|
|
2
|
-
import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-
|
|
1
|
+
import { n as StreamCodec } from "../adapter-DZmSMkrn.mjs";
|
|
2
|
+
import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-CHVIveYo.mjs";
|
|
3
3
|
import { UIMessageChunk } from "ai";
|
|
4
4
|
//#region src/ai-sdk/index.d.ts
|
|
5
5
|
/**
|
package/dist/ai-sdk/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as StreamCodec, t as StreamAdapter } from "./adapter-
|
|
1
|
+
import { n as StreamCodec, t as StreamAdapter } from "./adapter-DZmSMkrn.mjs";
|
|
2
2
|
import { AsyncIterableStream } from "ai-stream-utils";
|
|
3
3
|
//#region src/core.d.ts
|
|
4
4
|
type StartStreamOptions = {
|
|
@@ -65,6 +65,14 @@ type ResumeStreamOptions = {
|
|
|
65
65
|
* The generation to resume. Defaults to the one the stream id currently points at.
|
|
66
66
|
*/
|
|
67
67
|
generationId?: string;
|
|
68
|
+
/**
|
|
69
|
+
* Ends the resume when it aborts, at any time until the stream ends. Before
|
|
70
|
+
* `resumeStream` returns, the promise rejects with the reason of the signal. After that,
|
|
71
|
+
* the returned stream errors with it, and the adapter stream is cancelled. Pass the
|
|
72
|
+
* signal of the incoming request, so a client that goes away frees the resume at once,
|
|
73
|
+
* also while the resume still waits for the first chunk.
|
|
74
|
+
*/
|
|
75
|
+
signal?: AbortSignal;
|
|
68
76
|
};
|
|
69
77
|
type StopStreamOptions = {
|
|
70
78
|
/**
|
|
@@ -96,7 +104,13 @@ type CreateResumableStreamOptions<CHUNK> = {
|
|
|
96
104
|
adapter: StreamAdapter;
|
|
97
105
|
codec: StreamCodec<CHUNK>;
|
|
98
106
|
/**
|
|
99
|
-
*
|
|
107
|
+
* Receives each promise of the work that runs after the stream is returned: reading the
|
|
108
|
+
* source, the teardown of the adapter, and the stop listener. All of them have settled
|
|
109
|
+
* when that work is done, and none of them rejects.
|
|
110
|
+
*
|
|
111
|
+
* On a serverless runtime, pass the `waitUntil` of the platform, so the work is not
|
|
112
|
+
* suspended. To close the store clients safely, collect the promises and wait for them
|
|
113
|
+
* before you close the clients.
|
|
100
114
|
*/
|
|
101
115
|
waitUntil?: (promise: Promise<unknown>) => void;
|
|
102
116
|
/**
|
|
@@ -19,6 +19,29 @@ async function ignoreErrors(fn) {
|
|
|
19
19
|
} catch {}
|
|
20
20
|
}
|
|
21
21
|
/**
|
|
22
|
+
* Settles with the resume of the adapter, or rejects with the reason of the signal if it
|
|
23
|
+
* aborts first. A stream that the adapter returns after the abort is cancelled, so its
|
|
24
|
+
* subscription or its polling does not outlive the resume.
|
|
25
|
+
*/
|
|
26
|
+
function abortable(pending, signal) {
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
const onAbort = () => {
|
|
29
|
+
reject(signal.reason);
|
|
30
|
+
pending.then((stream) => stream?.cancel(signal.reason)).catch(() => {
|
|
31
|
+
/** The resume failed on its own, so there is nothing to cancel */
|
|
32
|
+
});
|
|
33
|
+
};
|
|
34
|
+
signal.addEventListener(`abort`, onAbort, { once: true });
|
|
35
|
+
pending.then((stream) => {
|
|
36
|
+
signal.removeEventListener(`abort`, onAbort);
|
|
37
|
+
resolve(stream);
|
|
38
|
+
}, (error) => {
|
|
39
|
+
signal.removeEventListener(`abort`, onAbort);
|
|
40
|
+
reject(error);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
22
45
|
* Creates a resumable stream context bound to a storage adapter and a chunk codec.
|
|
23
46
|
*
|
|
24
47
|
* The returned stream is drained once and fanned out to two consumers: the client
|
|
@@ -124,9 +147,11 @@ function createResumableStream(options) {
|
|
|
124
147
|
* neither delays the client nor fails the stream. A stop requested in the meantime is
|
|
125
148
|
* not lost where the adapter keeps it until the listener asks. Started only once the
|
|
126
149
|
* generation is registered, so a start that is refused never touches the stop listeners
|
|
127
|
-
* of the generation it collided with.
|
|
150
|
+
* of the generation it collided with. Given to `waitUntil`, because a listener that
|
|
151
|
+
* registers after the source ended is removed here, and the clients must stay open
|
|
152
|
+
* until that is done.
|
|
128
153
|
*/
|
|
129
|
-
(async () => {
|
|
154
|
+
const listening = (async () => {
|
|
130
155
|
try {
|
|
131
156
|
const remove = await adapter.onStopRequested({
|
|
132
157
|
streamId,
|
|
@@ -142,6 +167,7 @@ function createResumableStream(options) {
|
|
|
142
167
|
await ignoreErrors(() => onStopSubscriptionError?.(error));
|
|
143
168
|
}
|
|
144
169
|
})();
|
|
170
|
+
waitUntil?.(listening);
|
|
145
171
|
const drained = (async () => {
|
|
146
172
|
try {
|
|
147
173
|
while (true) {
|
|
@@ -190,16 +216,19 @@ function createResumableStream(options) {
|
|
|
190
216
|
* the current one.
|
|
191
217
|
*/
|
|
192
218
|
async function resumeStream(options) {
|
|
193
|
-
const { streamId, generationId } = options;
|
|
194
|
-
|
|
219
|
+
const { streamId, generationId, signal } = options;
|
|
220
|
+
signal?.throwIfAborted();
|
|
221
|
+
const pending = adapter.resumeStream({
|
|
195
222
|
streamId,
|
|
196
|
-
generationId
|
|
223
|
+
...generationId === void 0 ? {} : { generationId },
|
|
224
|
+
...signal === void 0 ? {} : { signal }
|
|
197
225
|
});
|
|
226
|
+
const encoded = signal ? await abortable(pending, signal) : await pending;
|
|
198
227
|
if (!encoded) return null;
|
|
199
228
|
return createAsyncIterableStream(encoded.pipeThrough(new TransformStream({ async transform(data, controller) {
|
|
200
229
|
const chunk = await codec.decode(data);
|
|
201
230
|
if (chunk !== void 0) controller.enqueue(chunk);
|
|
202
|
-
} })));
|
|
231
|
+
} }), signal === void 0 ? {} : { signal }));
|
|
203
232
|
}
|
|
204
233
|
/**
|
|
205
234
|
* Asks the process producing a generation of the stream to stop: the one named by
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as StreamCodec, t as StreamAdapter } from "./adapter-
|
|
2
|
-
import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-
|
|
1
|
+
import { n as StreamCodec, t as StreamAdapter } from "./adapter-DZmSMkrn.mjs";
|
|
2
|
+
import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-CHVIveYo.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-
|
|
1
|
+
import { t as createResumableStream } from "./core-DfQuMgU1.mjs";
|
|
2
2
|
export { createResumableStream };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-resumable-stream",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.4.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",
|