ai-resumable-stream 3.3.0 → 3.5.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 -13
- package/dist/{adapter-BwSsPtDm.d.mts → adapter-DZmSMkrn.d.mts} +6 -0
- package/dist/adapters/redis/index.d.mts +72 -16
- package/dist/adapters/redis/index.mjs +294 -30
- 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 +4 -2
package/README.md
CHANGED
|
@@ -65,7 +65,7 @@ const context = createResumableUIMessageStream({
|
|
|
65
65
|
Then use the context in your three routes:
|
|
66
66
|
|
|
67
67
|
```ts
|
|
68
|
-
import { streamText, toUIMessageStream, type UIMessage } from "ai";
|
|
68
|
+
import { createUIMessageStreamResponse, streamText, toUIMessageStream, type UIMessage } from "ai";
|
|
69
69
|
|
|
70
70
|
// POST /chat/:chatId
|
|
71
71
|
export async function send(chatId: string, messages: Array<UIMessage>) {
|
|
@@ -82,14 +82,15 @@ export async function send(chatId: string, messages: Array<UIMessage>) {
|
|
|
82
82
|
abortController,
|
|
83
83
|
});
|
|
84
84
|
|
|
85
|
-
return stream;
|
|
85
|
+
return createUIMessageStreamResponse({ stream });
|
|
86
86
|
}
|
|
87
87
|
|
|
88
88
|
// GET /chat/:chatId/stream
|
|
89
89
|
export async function resume(chatId: string) {
|
|
90
90
|
const stream = await context.resumeStream({ streamId: chatId });
|
|
91
|
+
if (!stream) return new Response(null, { status: 204 });
|
|
91
92
|
|
|
92
|
-
return
|
|
93
|
+
return createUIMessageStreamResponse({ stream });
|
|
93
94
|
}
|
|
94
95
|
|
|
95
96
|
// POST /chat/:chatId/stop
|
|
@@ -196,6 +197,20 @@ async function resumeMessage(chatId: string) {
|
|
|
196
197
|
}
|
|
197
198
|
```
|
|
198
199
|
|
|
200
|
+
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.
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
import { createUIMessageStreamResponse } from "ai";
|
|
204
|
+
|
|
205
|
+
// GET /chat/:chatId/stream
|
|
206
|
+
export async function resume(chatId: string, request: Request) {
|
|
207
|
+
const stream = await context.resumeStream({ streamId: chatId, signal: request.signal });
|
|
208
|
+
if (!stream) return new Response(null, { status: 204 });
|
|
209
|
+
|
|
210
|
+
return createUIMessageStreamResponse({ stream });
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
199
214
|
The result is `null` in three cases. The library does not tell you which case applies:
|
|
200
215
|
|
|
201
216
|
- no stream was started with that id
|
|
@@ -278,7 +293,7 @@ Use an id that the client already knows, for example the id of the user message
|
|
|
278
293
|
This adapter requires two Redis clients, because pub/sub needs a separate connection. The library connects the clients if they are not connected yet, but it never disconnects them. You manage the connection lifecycle in your application and can reuse the clients for all streams.
|
|
279
294
|
|
|
280
295
|
> [!NOTE]
|
|
281
|
-
>
|
|
296
|
+
> This adapter needs a Redis client. Supported clients are `redis` v5 and v6 and the client built into Bun. See [Installation](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-redis.md#installation).
|
|
282
297
|
|
|
283
298
|
```ts
|
|
284
299
|
import { createClient } from "redis";
|
|
@@ -296,13 +311,15 @@ const context = createResumableUIMessageStream({
|
|
|
296
311
|
});
|
|
297
312
|
```
|
|
298
313
|
|
|
299
|
-
| Option
|
|
300
|
-
|
|
|
301
|
-
| `publisher`
|
|
302
|
-
| `subscriber`
|
|
303
|
-
| `keyPrefix`
|
|
304
|
-
| `ackTimeoutMs`
|
|
305
|
-
| `
|
|
314
|
+
| Option | Type | Required | Description |
|
|
315
|
+
| ------------------ | ------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
316
|
+
| `publisher` | `RedisClient` | Yes | Client that sends commands and publishes messages |
|
|
317
|
+
| `subscriber` | `RedisClient` | Yes | Client for subscriptions. Must be a separate client, because a subscribed connection cannot send commands |
|
|
318
|
+
| `keyPrefix` | `string` | No | Prefix for all keys and channels. Defaults to `ai-resumable-stream` |
|
|
319
|
+
| `ackTimeoutMs` | `number` | No | How long a resume waits for the producer to answer before it returns `null`. Defaults to `1000` |
|
|
320
|
+
| `expireAfterMs` | `number` | No | When the pointer of a stream id expires. Must be longer than your longest stream. Defaults to `86400000` (24 hours) |
|
|
321
|
+
| `commandTimeoutMs` | `number` | No | How long a call waits for Redis before it rejects with a `CommandTimeoutError` (its `name` is `TimeoutError`). Defaults to no limit |
|
|
322
|
+
| `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) |
|
|
306
323
|
|
|
307
324
|
> [!IMPORTANT]
|
|
308
325
|
> **A stream is only resumable while its producer is alive.**
|
|
@@ -361,7 +378,7 @@ const adapter: StreamAdapter = {
|
|
|
361
378
|
```
|
|
362
379
|
|
|
363
380
|
- **`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.
|
|
381
|
+
- **`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.
|
|
365
382
|
- **`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
383
|
- **`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.
|
|
367
384
|
|
|
@@ -418,6 +435,20 @@ import { waitUntil } from "@vercel/functions";
|
|
|
418
435
|
const context = createResumableUIMessageStream({ adapter, waitUntil });
|
|
419
436
|
```
|
|
420
437
|
|
|
438
|
+
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:
|
|
439
|
+
|
|
440
|
+
```ts
|
|
441
|
+
const pending: Array<Promise<unknown>> = [];
|
|
442
|
+
const context = createResumableUIMessageStream({
|
|
443
|
+
adapter,
|
|
444
|
+
waitUntil: (promise) => pending.push(promise),
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
// Before shutdown
|
|
448
|
+
await Promise.all(pending);
|
|
449
|
+
await Promise.all([publisher.quit(), subscriber.quit()]);
|
|
450
|
+
```
|
|
451
|
+
|
|
421
452
|
### Finish
|
|
422
453
|
|
|
423
454
|
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`.
|
|
@@ -542,6 +573,7 @@ type StartStreamResult<CHUNK> = {
|
|
|
542
573
|
type ResumeStreamOptions = {
|
|
543
574
|
streamId: string;
|
|
544
575
|
generationId?: string;
|
|
576
|
+
signal?: AbortSignal;
|
|
545
577
|
};
|
|
546
578
|
|
|
547
579
|
type StopStreamOptions = {
|
|
@@ -554,7 +586,7 @@ type StopStreamOptions = {
|
|
|
554
586
|
| ------------ | -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
555
587
|
| `adapter` | `StreamAdapter` | Yes | Stores the chunks and transports stop requests |
|
|
556
588
|
| `codec` | `StreamCodec<CHUNK>` | Yes | Converts chunks to strings for the adapter, and back |
|
|
557
|
-
| `waitUntil` | `(promise) => void` | No |
|
|
589
|
+
| `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 |
|
|
558
590
|
| `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` |
|
|
559
591
|
|
|
560
592
|
### `createResumableUIMessageStream`
|
|
@@ -580,6 +612,7 @@ type StreamAdapter = {
|
|
|
580
612
|
resumeStream(options: {
|
|
581
613
|
streamId: string;
|
|
582
614
|
generationId?: string;
|
|
615
|
+
signal?: AbortSignal;
|
|
583
616
|
}): Promise<ReadableStream<string> | null>;
|
|
584
617
|
requestStop(options: { streamId: string; generationId?: string }): Promise<void>;
|
|
585
618
|
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,15 +1,15 @@
|
|
|
1
|
-
import { t as StreamAdapter } from "../../adapter-
|
|
2
|
-
//#region src/adapters/redis/
|
|
1
|
+
import { t as StreamAdapter } from "../../adapter-DZmSMkrn.mjs";
|
|
2
|
+
//#region src/adapters/redis/client.d.ts
|
|
3
3
|
/**
|
|
4
|
-
* A
|
|
5
|
-
* the client type of a specific `redis` release. The generic parameters of
|
|
6
|
-
* `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal
|
|
7
|
-
*
|
|
4
|
+
* A client from the `redis` package, described by the commands the adapter actually calls
|
|
5
|
+
* rather than by the client type of a specific `redis` release. The generic parameters of
|
|
6
|
+
* `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal type
|
|
7
|
+
* would pin consumers to one of them.
|
|
8
8
|
*
|
|
9
9
|
* `unsubscribe` takes the listener because a listener removes itself alone, never every
|
|
10
10
|
* listener of its channel.
|
|
11
11
|
*/
|
|
12
|
-
type
|
|
12
|
+
type NodeRedis = {
|
|
13
13
|
isOpen: boolean;
|
|
14
14
|
connect(): Promise<unknown>;
|
|
15
15
|
publish(channel: string, message: string): Promise<unknown>;
|
|
@@ -18,7 +18,7 @@ type Redis = {
|
|
|
18
18
|
get(key: string): Promise<string | null>;
|
|
19
19
|
set(key: string, value: string, options?: {
|
|
20
20
|
expiration?: {
|
|
21
|
-
type: `EX`;
|
|
21
|
+
type: `EX` | `PX`;
|
|
22
22
|
value: number;
|
|
23
23
|
};
|
|
24
24
|
}): Promise<unknown>;
|
|
@@ -28,16 +28,38 @@ type Redis = {
|
|
|
28
28
|
arguments?: Array<string>;
|
|
29
29
|
}): Promise<unknown>;
|
|
30
30
|
};
|
|
31
|
+
/**
|
|
32
|
+
* The client built into Bun (`Bun.RedisClient`), described by the commands the adapter
|
|
33
|
+
* calls, so that a consumer on Node does not need the types of Bun.
|
|
34
|
+
*/
|
|
35
|
+
type BunRedis = {
|
|
36
|
+
readonly connected: boolean;
|
|
37
|
+
onconnect: (() => void) | null;
|
|
38
|
+
connect(): Promise<unknown>;
|
|
39
|
+
send(command: string, args: Array<string>): Promise<unknown>;
|
|
40
|
+
publish(channel: string, message: string): Promise<unknown>;
|
|
41
|
+
subscribe(channel: string, listener: BunListener): Promise<unknown>;
|
|
42
|
+
unsubscribe(channel: string, listener: BunListener): Promise<unknown>;
|
|
43
|
+
get(key: string): Promise<string | null>;
|
|
44
|
+
set(key: string, value: string): Promise<unknown>;
|
|
45
|
+
set(key: string, value: string, type: `EX` | `PX`, duration: number): Promise<unknown>;
|
|
46
|
+
del(key: string): Promise<unknown>;
|
|
47
|
+
};
|
|
48
|
+
type BunListener = (message: string, channel: string) => void;
|
|
49
|
+
type RedisClient = NodeRedis | BunRedis;
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/adapters/redis/adapter.d.ts
|
|
31
52
|
type CreateRedisAdapterOptions = {
|
|
32
53
|
/**
|
|
33
|
-
* A client from the `redis` package
|
|
54
|
+
* A client from the `redis` package or the client built into Bun (`Bun.RedisClient`),
|
|
55
|
+
* used to publish chunks and stop requests.
|
|
34
56
|
* Connected on first use and never disconnected, so it stays reusable across streams.
|
|
35
57
|
*/
|
|
36
|
-
publisher:
|
|
58
|
+
publisher: RedisClient;
|
|
37
59
|
/**
|
|
38
60
|
* A second client, required because a subscribed connection cannot issue commands.
|
|
39
61
|
*/
|
|
40
|
-
subscriber:
|
|
62
|
+
subscriber: RedisClient;
|
|
41
63
|
/**
|
|
42
64
|
* Namespace for every key and channel this adapter touches.
|
|
43
65
|
*/
|
|
@@ -50,13 +72,47 @@ type CreateRedisAdapterOptions = {
|
|
|
50
72
|
*/
|
|
51
73
|
ackTimeoutMs?: number;
|
|
52
74
|
/**
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
75
|
+
* When the Redis keys of a stream expire, in milliseconds: the pointer of the stream id
|
|
76
|
+
* and the mark of a finished stream. Must be longer than your longest stream, because a
|
|
77
|
+
* resume without a generation id finds nothing after the pointer expired, even while the
|
|
78
|
+
* producer still runs. The stream of a producer that died is gone sooner, because its
|
|
79
|
+
* producer no longer renews it. Defaults to 24 hours.
|
|
80
|
+
*/
|
|
81
|
+
expireAfterMs?: number;
|
|
82
|
+
/**
|
|
83
|
+
* The same as `expireAfterMs`, in seconds. Ignored when `expireAfterMs` is set.
|
|
84
|
+
*
|
|
85
|
+
* @deprecated Use `expireAfterMs`.
|
|
57
86
|
*/
|
|
58
87
|
ttlSeconds?: number;
|
|
88
|
+
/**
|
|
89
|
+
* How long the adapter waits for Redis when it connects, registers a stream, reads the
|
|
90
|
+
* pointer, or sends and listens for a stop. After this time, the call rejects with a
|
|
91
|
+
* `CommandTimeoutError`. Use it when Redis can become unreachable: the client does not
|
|
92
|
+
* get an answer from a dead peer, and the timeout and the abort signal of the client no
|
|
93
|
+
* longer apply once a command is written. The command can still be pending in the client.
|
|
94
|
+
* Defaults to no limit.
|
|
95
|
+
*/
|
|
96
|
+
commandTimeoutMs?: number;
|
|
97
|
+
/**
|
|
98
|
+
* How often a producer renews the mark that its stream is running. The mark expires
|
|
99
|
+
* after three intervals without a renewal, so the stream of a producer that died is
|
|
100
|
+
* gone after three intervals. Each renewal is one Redis command per running stream.
|
|
101
|
+
* Defaults to 30 s, so a dead producer is detected after 90 s.
|
|
102
|
+
*/
|
|
103
|
+
heartbeatMs?: number;
|
|
59
104
|
};
|
|
105
|
+
/**
|
|
106
|
+
* Raised when Redis does not answer a call of the adapter within `commandTimeoutMs`.
|
|
107
|
+
*
|
|
108
|
+
* Its name is `TimeoutError`, the name of the error that `AbortSignal.timeout()` gives, so
|
|
109
|
+
* a check of `error.name === "TimeoutError"` finds both. A plain `Error` and not a
|
|
110
|
+
* `DOMException`, because a `DOMException` takes its name only from its constructor, and a
|
|
111
|
+
* subclass of it is unusual.
|
|
112
|
+
*/
|
|
113
|
+
declare class CommandTimeoutError extends Error {
|
|
114
|
+
constructor(timeoutMs: number);
|
|
115
|
+
}
|
|
60
116
|
/**
|
|
61
117
|
* Stores streams in Redis, with a runtime derived from `resumable-stream`.
|
|
62
118
|
*
|
|
@@ -66,4 +122,4 @@ type CreateRedisAdapterOptions = {
|
|
|
66
122
|
*/
|
|
67
123
|
declare function createRedisAdapter(options: CreateRedisAdapterOptions): StreamAdapter;
|
|
68
124
|
//#endregion
|
|
69
|
-
export { type CreateRedisAdapterOptions, createRedisAdapter };
|
|
125
|
+
export { CommandTimeoutError, type CreateRedisAdapterOptions, createRedisAdapter };
|
|
@@ -40,6 +40,16 @@ const DONE_MESSAGE = `\n\n\nDONE_SENTINEL_hasdfasudfyge374%$%^$EDSATRTYFtydryrte
|
|
|
40
40
|
const DONE_VALUE = `DONE`;
|
|
41
41
|
const DEFAULT_ACK_TIMEOUT_MS = 1e3;
|
|
42
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;
|
|
43
53
|
function noop() {}
|
|
44
54
|
function createRuntime(options) {
|
|
45
55
|
const ctx = {
|
|
@@ -48,8 +58,9 @@ function createRuntime(options) {
|
|
|
48
58
|
subscriber: options.subscriber,
|
|
49
59
|
waitUntil: options.waitUntil ?? noop,
|
|
50
60
|
ackTimeoutMs: options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS,
|
|
51
|
-
|
|
52
|
-
doneWatchdogIntervalMs: options.doneWatchdogIntervalMs ?? DEFAULT_DONE_WATCHDOG_INTERVAL_MS
|
|
61
|
+
expireAfterMs: options.expireAfterMs,
|
|
62
|
+
doneWatchdogIntervalMs: options.doneWatchdogIntervalMs ?? DEFAULT_DONE_WATCHDOG_INTERVAL_MS,
|
|
63
|
+
heartbeatIntervalMs: options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS
|
|
53
64
|
};
|
|
54
65
|
return {
|
|
55
66
|
createNewResumableStream: (streamId, makeStream) => createNewResumableStream(ctx, streamId, makeStream),
|
|
@@ -66,9 +77,13 @@ async function createNewResumableStream(ctx, streamId, makeStream) {
|
|
|
66
77
|
const requestChannel = `${ctx.keyPrefix}:request:${streamId}`;
|
|
67
78
|
const sentinelKey = `${ctx.keyPrefix}:sentinel:${streamId}`;
|
|
68
79
|
const chunkChannel = (listenerId) => `${ctx.keyPrefix}:chunk:${listenerId}`;
|
|
69
|
-
const
|
|
70
|
-
type: `
|
|
71
|
-
value: ctx.
|
|
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
|
|
72
87
|
} };
|
|
73
88
|
const chunks = [];
|
|
74
89
|
const listenerIds = [];
|
|
@@ -131,7 +146,7 @@ async function createNewResumableStream(ctx, streamId, makeStream) {
|
|
|
131
146
|
try {
|
|
132
147
|
await ctx.subscriber.subscribe(requestChannel, onRequest);
|
|
133
148
|
try {
|
|
134
|
-
await ctx.publisher.set(sentinelKey, `1`,
|
|
149
|
+
await ctx.publisher.set(sentinelKey, `1`, runningExpiration);
|
|
135
150
|
} catch (error) {
|
|
136
151
|
await ctx.subscriber.unsubscribe(requestChannel, onRequest).catch(noop);
|
|
137
152
|
throw error;
|
|
@@ -141,6 +156,23 @@ async function createNewResumableStream(ctx, streamId, makeStream) {
|
|
|
141
156
|
throw error;
|
|
142
157
|
}
|
|
143
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
|
+
/**
|
|
144
176
|
* Marks the stream done, tells the consumers and stops to answer requests.
|
|
145
177
|
*
|
|
146
178
|
* Differs from upstream:
|
|
@@ -155,16 +187,18 @@ async function createNewResumableStream(ctx, streamId, makeStream) {
|
|
|
155
187
|
* - Waits for the chunk publishes still in flight, so a runtime that freezes the process
|
|
156
188
|
* after `waitUntil` does not lose them.
|
|
157
189
|
*
|
|
158
|
-
* If the DONE write fails, the sentinel stays "1" until it expires
|
|
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
|
|
159
192
|
* no answer and fails with the ack timeout.
|
|
160
193
|
*/
|
|
161
194
|
let finishing;
|
|
162
195
|
const finish = () => {
|
|
163
196
|
finishing ??= (async () => {
|
|
164
197
|
isDone = true;
|
|
198
|
+
clearInterval(heartbeat);
|
|
165
199
|
for (const listenerId of listenerIds) publish(chunkChannel(listenerId), DONE_MESSAGE);
|
|
166
200
|
await Promise.allSettled([
|
|
167
|
-
ctx.publisher.set(sentinelKey, DONE_VALUE,
|
|
201
|
+
ctx.publisher.set(sentinelKey, DONE_VALUE, doneExpiration),
|
|
168
202
|
ctx.subscriber.unsubscribe(requestChannel, onRequest),
|
|
169
203
|
...inFlight
|
|
170
204
|
]);
|
|
@@ -355,6 +389,175 @@ function resumeStream(ctx, streamId) {
|
|
|
355
389
|
});
|
|
356
390
|
}
|
|
357
391
|
//#endregion
|
|
392
|
+
//#region src/adapters/redis/client.ts
|
|
393
|
+
/**
|
|
394
|
+
* The Bun client has `connected` in place of `isOpen`. The `isOpen` check comes first, so a
|
|
395
|
+
* `redis` client is never taken for a Bun client.
|
|
396
|
+
*/
|
|
397
|
+
function isBunRedis(client) {
|
|
398
|
+
return !(`isOpen` in client) && `connected` in client && typeof client.send === `function`;
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* One wrapper per client, because a wrapper keeps the subscriptions of its client and
|
|
402
|
+
* hooks into its reconnects. A new adapter on the same clients must not add a second hook.
|
|
403
|
+
*/
|
|
404
|
+
const bunWrappers = /* @__PURE__ */ new WeakMap();
|
|
405
|
+
/**
|
|
406
|
+
* Gives a client the commands of a `redis` client. A `redis` client is returned unchanged.
|
|
407
|
+
*/
|
|
408
|
+
function toNodeRedis(client) {
|
|
409
|
+
if (!isBunRedis(client)) return client;
|
|
410
|
+
let wrapper = bunWrappers.get(client);
|
|
411
|
+
if (!wrapper) {
|
|
412
|
+
wrapper = wrapBunRedis(client);
|
|
413
|
+
bunWrappers.set(client, wrapper);
|
|
414
|
+
}
|
|
415
|
+
return wrapper;
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Bun rejects an unsubscribe when the client is not in subscriber mode, sometimes with a
|
|
419
|
+
* synchronous throw. Then there is nothing to remove, as with a `redis` client.
|
|
420
|
+
*/
|
|
421
|
+
async function unsubscribeQuietly({ client, channel, listener }) {
|
|
422
|
+
try {
|
|
423
|
+
await client.unsubscribe(channel, listener);
|
|
424
|
+
} catch (error) {
|
|
425
|
+
if (error?.code !== `ERR_REDIS_INVALID_STATE`) throw error;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Gives the expiry of `set` as positional arguments and sends `EVAL` through `send`.
|
|
430
|
+
*
|
|
431
|
+
* Subscriptions need more. After a reconnect, Bun keeps its listeners but does not
|
|
432
|
+
* subscribe again on the server, so no message arrives. And Bun keeps a list, not a set, of
|
|
433
|
+
* listeners: a second subscribe with the same listener calls it twice. So the wrapper keeps
|
|
434
|
+
* the listeners of each channel itself and gives Bun one listener for all channels. After
|
|
435
|
+
* each reconnect, it unsubscribes and subscribes that listener again for each channel that
|
|
436
|
+
* has listeners, also for a channel whose last subscribe failed.
|
|
437
|
+
*
|
|
438
|
+
* The calls for one channel run one after the other, and each call makes Bun match the
|
|
439
|
+
* listeners that the channel has at that time. So a subscribe and an unsubscribe that
|
|
440
|
+
* overlap, or a reconnect between them, cannot leave the channel in the wrong state.
|
|
441
|
+
*/
|
|
442
|
+
function wrapBunRedis(client) {
|
|
443
|
+
const channels = /* @__PURE__ */ new Map();
|
|
444
|
+
const dispatch = (message, channel) => {
|
|
445
|
+
for (const listener of channels.get(channel)?.listeners ?? []) listener(message);
|
|
446
|
+
};
|
|
447
|
+
const reconcile = async ({ name, channel }) => {
|
|
448
|
+
if (channel.stale) {
|
|
449
|
+
await unsubscribeQuietly({
|
|
450
|
+
client,
|
|
451
|
+
channel: name,
|
|
452
|
+
listener: dispatch
|
|
453
|
+
});
|
|
454
|
+
channel.registered = false;
|
|
455
|
+
channel.stale = false;
|
|
456
|
+
}
|
|
457
|
+
if (channel.listeners.size > 0 && !channel.registered) {
|
|
458
|
+
await client.subscribe(name, dispatch);
|
|
459
|
+
channel.registered = true;
|
|
460
|
+
} else if (channel.listeners.size === 0 && channel.registered) {
|
|
461
|
+
await unsubscribeQuietly({
|
|
462
|
+
client,
|
|
463
|
+
channel: name,
|
|
464
|
+
listener: dispatch
|
|
465
|
+
});
|
|
466
|
+
channel.registered = false;
|
|
467
|
+
}
|
|
468
|
+
forgetIfUnused({
|
|
469
|
+
name,
|
|
470
|
+
channel
|
|
471
|
+
});
|
|
472
|
+
};
|
|
473
|
+
const forgetIfUnused = ({ name, channel }) => {
|
|
474
|
+
if (channel.listeners.size === 0 && !channel.registered && channels.get(name) === channel) channels.delete(name);
|
|
475
|
+
};
|
|
476
|
+
const enqueue = ({ name, channel }) => {
|
|
477
|
+
const result = channel.queue.then(() => reconcile({
|
|
478
|
+
name,
|
|
479
|
+
channel
|
|
480
|
+
}));
|
|
481
|
+
channel.queue = result.catch(() => {});
|
|
482
|
+
return result;
|
|
483
|
+
};
|
|
484
|
+
const channelOf = (name) => {
|
|
485
|
+
let channel = channels.get(name);
|
|
486
|
+
if (!channel) {
|
|
487
|
+
channel = {
|
|
488
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
489
|
+
registered: false,
|
|
490
|
+
stale: false,
|
|
491
|
+
queue: Promise.resolve()
|
|
492
|
+
};
|
|
493
|
+
channels.set(name, channel);
|
|
494
|
+
}
|
|
495
|
+
return channel;
|
|
496
|
+
};
|
|
497
|
+
/**
|
|
498
|
+
* Restores before it calls the handler that was there before, so a handler that throws
|
|
499
|
+
* cannot stop the restore. On the first connect, no channel is registered yet, so there
|
|
500
|
+
* is nothing to restore.
|
|
501
|
+
*/
|
|
502
|
+
const previous = client.onconnect;
|
|
503
|
+
client.onconnect = function() {
|
|
504
|
+
for (const [name, channel] of channels) {
|
|
505
|
+
if (channel.listeners.size === 0 && !channel.registered) continue;
|
|
506
|
+
channel.stale = true;
|
|
507
|
+
enqueue({
|
|
508
|
+
name,
|
|
509
|
+
channel
|
|
510
|
+
}).catch(() => {});
|
|
511
|
+
}
|
|
512
|
+
previous?.call(this);
|
|
513
|
+
};
|
|
514
|
+
return {
|
|
515
|
+
get isOpen() {
|
|
516
|
+
return client.connected;
|
|
517
|
+
},
|
|
518
|
+
connect: () => client.connect(),
|
|
519
|
+
publish: (channel, message) => client.publish(channel, message),
|
|
520
|
+
subscribe: (name, listener) => {
|
|
521
|
+
const channel = channelOf(name);
|
|
522
|
+
channel.listeners.add(listener);
|
|
523
|
+
/**
|
|
524
|
+
* A failed subscribe registers nothing, as with a `redis` client, so the caller does
|
|
525
|
+
* not have to unsubscribe the listener.
|
|
526
|
+
*/
|
|
527
|
+
return enqueue({
|
|
528
|
+
name,
|
|
529
|
+
channel
|
|
530
|
+
}).catch((error) => {
|
|
531
|
+
channel.listeners.delete(listener);
|
|
532
|
+
forgetIfUnused({
|
|
533
|
+
name,
|
|
534
|
+
channel
|
|
535
|
+
});
|
|
536
|
+
throw error;
|
|
537
|
+
});
|
|
538
|
+
},
|
|
539
|
+
unsubscribe: (name, listener) => {
|
|
540
|
+
const channel = channels.get(name);
|
|
541
|
+
if (!channel) return Promise.resolve();
|
|
542
|
+
if (listener) channel.listeners.delete(listener);
|
|
543
|
+
else channel.listeners.clear();
|
|
544
|
+
return enqueue({
|
|
545
|
+
name,
|
|
546
|
+
channel
|
|
547
|
+
});
|
|
548
|
+
},
|
|
549
|
+
get: (key) => client.get(key),
|
|
550
|
+
set: (key, value, options) => options?.expiration ? client.set(key, value, options.expiration.type, options.expiration.value) : client.set(key, value),
|
|
551
|
+
del: (key) => client.del(key),
|
|
552
|
+
eval: (script, { keys = [], arguments: args = [] } = {}) => client.send(`EVAL`, [
|
|
553
|
+
script,
|
|
554
|
+
String(keys.length),
|
|
555
|
+
...keys,
|
|
556
|
+
...args
|
|
557
|
+
])
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
//#endregion
|
|
358
561
|
//#region src/adapters/redis/sse.ts
|
|
359
562
|
/**
|
|
360
563
|
* The runtime transports a stream of strings that it is free to concatenate and
|
|
@@ -398,11 +601,25 @@ function sseToChunks() {
|
|
|
398
601
|
}
|
|
399
602
|
//#endregion
|
|
400
603
|
//#region src/adapters/redis/adapter.ts
|
|
604
|
+
/**
|
|
605
|
+
* Raised when Redis does not answer a call of the adapter within `commandTimeoutMs`.
|
|
606
|
+
*
|
|
607
|
+
* Its name is `TimeoutError`, the name of the error that `AbortSignal.timeout()` gives, so
|
|
608
|
+
* a check of `error.name === "TimeoutError"` finds both. A plain `Error` and not a
|
|
609
|
+
* `DOMException`, because a `DOMException` takes its name only from its constructor, and a
|
|
610
|
+
* subclass of it is unusual.
|
|
611
|
+
*/
|
|
612
|
+
var CommandTimeoutError = class extends Error {
|
|
613
|
+
constructor(timeoutMs) {
|
|
614
|
+
super(`Redis did not answer within ${timeoutMs} ms`);
|
|
615
|
+
this.name = `TimeoutError`;
|
|
616
|
+
}
|
|
617
|
+
};
|
|
401
618
|
const DEFAULT_KEY_PREFIX = `ai-resumable-stream`;
|
|
402
619
|
/**
|
|
403
620
|
* The fixed lifetime of the original `resumable-stream`, long enough for any chat turn.
|
|
404
621
|
*/
|
|
405
|
-
const
|
|
622
|
+
const DEFAULT_EXPIRE_AFTER_MS = 1440 * 60 * 1e3;
|
|
406
623
|
/**
|
|
407
624
|
* Deletes a key only while it still holds the expected value. One script, so no other
|
|
408
625
|
* client can write the key between the comparison and the deletion.
|
|
@@ -422,7 +639,30 @@ const STOP_TTL_SECONDS = 3600;
|
|
|
422
639
|
* durable adapter when a stream must outlive the process that started it.
|
|
423
640
|
*/
|
|
424
641
|
function createRedisAdapter(options) {
|
|
425
|
-
const {
|
|
642
|
+
const { keyPrefix = DEFAULT_KEY_PREFIX, ackTimeoutMs, ttlSeconds, commandTimeoutMs, heartbeatMs } = options;
|
|
643
|
+
if (heartbeatMs !== void 0 && !(heartbeatMs > 0)) throw new RangeError(`heartbeatMs must be greater than 0, got ${heartbeatMs}`);
|
|
644
|
+
const expireAfterMs = options.expireAfterMs ?? (ttlSeconds === void 0 ? DEFAULT_EXPIRE_AFTER_MS : ttlSeconds * 1e3);
|
|
645
|
+
const publisher = toNodeRedis(options.publisher);
|
|
646
|
+
const subscriber = toNodeRedis(options.subscriber);
|
|
647
|
+
/**
|
|
648
|
+
* Rejects with a `CommandTimeoutError` when the call takes longer than
|
|
649
|
+
* `commandTimeoutMs`. A late failure of the call is handled, so it is not an unhandled
|
|
650
|
+
* rejection.
|
|
651
|
+
*/
|
|
652
|
+
function limit(call) {
|
|
653
|
+
if (commandTimeoutMs === void 0) return call;
|
|
654
|
+
const timeoutMs = commandTimeoutMs;
|
|
655
|
+
return new Promise((resolve, reject) => {
|
|
656
|
+
const timer = setTimeout(() => reject(new CommandTimeoutError(timeoutMs)), timeoutMs);
|
|
657
|
+
call.then((value) => {
|
|
658
|
+
clearTimeout(timer);
|
|
659
|
+
resolve(value);
|
|
660
|
+
}, (error) => {
|
|
661
|
+
clearTimeout(timer);
|
|
662
|
+
reject(error);
|
|
663
|
+
});
|
|
664
|
+
});
|
|
665
|
+
}
|
|
426
666
|
/**
|
|
427
667
|
* The name of one generation of a stream id. The generation id is encoded, so it holds
|
|
428
668
|
* no colon and the name splits one way only: stream `a` with generation `b:c` never
|
|
@@ -450,7 +690,7 @@ function createRedisAdapter(options) {
|
|
|
450
690
|
*/
|
|
451
691
|
const pointerKey = (streamId) => `${keyPrefix}:generation:${streamId}`;
|
|
452
692
|
async function connect() {
|
|
453
|
-
await Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]);
|
|
693
|
+
await limit(Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]));
|
|
454
694
|
}
|
|
455
695
|
function createContext(waitUntil) {
|
|
456
696
|
return createRuntime({
|
|
@@ -459,18 +699,19 @@ function createRedisAdapter(options) {
|
|
|
459
699
|
subscriber,
|
|
460
700
|
keyPrefix,
|
|
461
701
|
ackTimeoutMs,
|
|
462
|
-
|
|
702
|
+
expireAfterMs,
|
|
703
|
+
heartbeatIntervalMs: heartbeatMs
|
|
463
704
|
});
|
|
464
705
|
}
|
|
465
706
|
async function readPointer(streamId) {
|
|
466
|
-
return publisher.get(pointerKey(streamId));
|
|
707
|
+
return limit(publisher.get(pointerKey(streamId)));
|
|
467
708
|
}
|
|
468
709
|
/**
|
|
469
710
|
* Drops the stop kept for a generation once it is over, so nothing outlives the
|
|
470
711
|
* generation it was meant for.
|
|
471
712
|
*/
|
|
472
713
|
async function clearStop(streamId, generationId) {
|
|
473
|
-
await publisher.del(stopKey(streamId, generationId));
|
|
714
|
+
await limit(publisher.del(stopKey(streamId, generationId)));
|
|
474
715
|
}
|
|
475
716
|
/**
|
|
476
717
|
* Retires the generation, but only while it is still the current one, so a slow
|
|
@@ -478,10 +719,10 @@ function createRedisAdapter(options) {
|
|
|
478
719
|
* successor may repoint the id at any moment, including between the two.
|
|
479
720
|
*/
|
|
480
721
|
async function clearPointer(streamId, generationId) {
|
|
481
|
-
await publisher.eval(DELETE_IF_EQUAL_SCRIPT, {
|
|
722
|
+
await limit(publisher.eval(DELETE_IF_EQUAL_SCRIPT, {
|
|
482
723
|
keys: [pointerKey(streamId)],
|
|
483
724
|
arguments: [generationId]
|
|
484
|
-
});
|
|
725
|
+
}));
|
|
485
726
|
}
|
|
486
727
|
return {
|
|
487
728
|
async createStream({ streamId, generationId: runId, chunks, waitUntil }) {
|
|
@@ -498,23 +739,37 @@ function createRedisAdapter(options) {
|
|
|
498
739
|
* died before it could clean up. A pointer that lives longer than its sentinel only
|
|
499
740
|
* leads to a stream that the runtime does not know.
|
|
500
741
|
*/
|
|
501
|
-
await publisher.set(pointerKey(streamId), generationId, { expiration: {
|
|
502
|
-
type: `
|
|
503
|
-
value:
|
|
504
|
-
} });
|
|
742
|
+
await limit(publisher.set(pointerKey(streamId), generationId, { expiration: {
|
|
743
|
+
type: `PX`,
|
|
744
|
+
value: expireAfterMs
|
|
745
|
+
} }));
|
|
505
746
|
/**
|
|
506
747
|
* The pointer is dropped as soon as the source ends, so a resume that arrives
|
|
507
748
|
* during teardown is told there is nothing to resume rather than racing it. The
|
|
508
749
|
* stop goes with it: a generation that is over has nothing left to stop.
|
|
509
750
|
*/
|
|
510
|
-
const
|
|
751
|
+
const abandon = new AbortController();
|
|
752
|
+
const sse = chunks.pipeThrough(chunksToSSE(), { signal: abandon.signal }).pipeThrough(new TransformStream({ async flush() {
|
|
511
753
|
await Promise.all([clearPointer(streamId, generationId), clearStop(streamId, runId)]).catch(() => {
|
|
512
754
|
/** Both expire on their own */
|
|
513
755
|
});
|
|
514
756
|
} }));
|
|
515
|
-
|
|
757
|
+
/**
|
|
758
|
+
* A registration that times out is abandoned. The runtime can still finish its setup
|
|
759
|
+
* later, so the pipe is aborted: the runtime then sees a failed source and tears the
|
|
760
|
+
* stream down, and the source is cancelled.
|
|
761
|
+
*/
|
|
762
|
+
try {
|
|
763
|
+
await limit(createContext(waitUntil).createNewResumableStream(generationId, () => sse));
|
|
764
|
+
} catch (error) {
|
|
765
|
+
abandon.abort(error);
|
|
766
|
+
await clearPointer(streamId, generationId).catch(() => {
|
|
767
|
+
/** It expires on its own */
|
|
768
|
+
});
|
|
769
|
+
throw error;
|
|
770
|
+
}
|
|
516
771
|
},
|
|
517
|
-
async resumeStream({ streamId, generationId: runId }) {
|
|
772
|
+
async resumeStream({ streamId, generationId: runId, signal }) {
|
|
518
773
|
await connect();
|
|
519
774
|
/**
|
|
520
775
|
* A named generation is followed without the pointer, so it can be resumed after a
|
|
@@ -544,12 +799,21 @@ function createRedisAdapter(options) {
|
|
|
544
799
|
* not yet emitted anything waits for its first chunk.
|
|
545
800
|
*/
|
|
546
801
|
let first;
|
|
802
|
+
/**
|
|
803
|
+
* A producer that never sends its first chunk would hold this read, and with it the
|
|
804
|
+
* subscription, forever. The abort cancels the read, which removes the subscription.
|
|
805
|
+
*/
|
|
806
|
+
const onAbort = () => void reader.cancel(signal?.reason).catch(() => void 0);
|
|
807
|
+
signal?.addEventListener(`abort`, onAbort, { once: true });
|
|
547
808
|
try {
|
|
809
|
+
if (signal?.aborted) onAbort();
|
|
548
810
|
first = await reader.read();
|
|
549
811
|
} catch (error) {
|
|
550
812
|
reader.releaseLock();
|
|
551
813
|
if (error instanceof AckTimeoutError) return null;
|
|
552
814
|
throw error;
|
|
815
|
+
} finally {
|
|
816
|
+
signal?.removeEventListener(`abort`, onAbort);
|
|
553
817
|
}
|
|
554
818
|
if (first.done) {
|
|
555
819
|
reader.releaseLock();
|
|
@@ -588,26 +852,26 @@ function createRedisAdapter(options) {
|
|
|
588
852
|
* Kept before it is published. A producer subscribes before it reads, so it either
|
|
589
853
|
* receives the message or finds the key.
|
|
590
854
|
*/
|
|
591
|
-
await publisher.set(stopKey(streamId, runId), `1`, { expiration: {
|
|
855
|
+
await limit(publisher.set(stopKey(streamId, runId), `1`, { expiration: {
|
|
592
856
|
type: `EX`,
|
|
593
857
|
value: STOP_TTL_SECONDS
|
|
594
|
-
} });
|
|
595
|
-
await publisher.publish(stopChannel(streamId, runId), `stop`);
|
|
858
|
+
} }));
|
|
859
|
+
await limit(publisher.publish(stopChannel(streamId, runId), `stop`));
|
|
596
860
|
},
|
|
597
861
|
async onStopRequested({ streamId, generationId, onStop }) {
|
|
598
862
|
await connect();
|
|
599
863
|
const channel = stopChannel(streamId, generationId);
|
|
600
864
|
const listener = () => onStop();
|
|
601
|
-
await subscriber.subscribe(channel, listener);
|
|
865
|
+
await limit(subscriber.subscribe(channel, listener));
|
|
602
866
|
const unsubscribe = async () => {
|
|
603
|
-
await subscriber.unsubscribe(channel, listener);
|
|
867
|
+
await limit(subscriber.unsubscribe(channel, listener));
|
|
604
868
|
};
|
|
605
869
|
/**
|
|
606
870
|
* Read only once subscribed. Reading first, or both at once, leaves a window in
|
|
607
871
|
* which a stop is neither kept yet nor delivered.
|
|
608
872
|
*/
|
|
609
873
|
try {
|
|
610
|
-
if (await publisher.get(stopKey(streamId, generationId)) !== null) onStop();
|
|
874
|
+
if (await limit(publisher.get(stopKey(streamId, generationId))) !== null) onStop();
|
|
611
875
|
} catch (error) {
|
|
612
876
|
await unsubscribe().catch(() => {
|
|
613
877
|
/** The subscription is gone with the connection */
|
|
@@ -619,4 +883,4 @@ function createRedisAdapter(options) {
|
|
|
619
883
|
};
|
|
620
884
|
}
|
|
621
885
|
//#endregion
|
|
622
|
-
export { createRedisAdapter };
|
|
886
|
+
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.5.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",
|
|
@@ -37,6 +37,7 @@
|
|
|
37
37
|
"@arethetypeswrong/cli": "^0.18.5",
|
|
38
38
|
"@aws-sdk/client-s3": "^3.1131.0",
|
|
39
39
|
"@total-typescript/tsconfig": "^1.0.4",
|
|
40
|
+
"@types/bun": "^1.4.5",
|
|
40
41
|
"@types/node": "^26.1.1",
|
|
41
42
|
"@vitest/coverage-v8": "^4.1.10",
|
|
42
43
|
"ai": "^7.0.22",
|
|
@@ -85,8 +86,9 @@
|
|
|
85
86
|
"scripts": {
|
|
86
87
|
"build": "tsdown",
|
|
87
88
|
"test": "vitest run",
|
|
89
|
+
"test:bun": "bun test ./src/adapters/redis/compat.bun.test.ts",
|
|
88
90
|
"test:watch": "vitest",
|
|
89
|
-
"typecheck": "tsc --noEmit",
|
|
91
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.bun.json",
|
|
90
92
|
"example:redis": "tsx examples/redis.ts",
|
|
91
93
|
"example:s3-express": "tsx examples/s3-express.ts",
|
|
92
94
|
"lint": "oxlint --fix",
|