ai-resumable-stream 2.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ //#region src/adapter.d.ts
2
+ /**
3
+ * Storage and signalling backend for resumable streams.
4
+ *
5
+ * Chunks are transported as opaque strings and their order must be preserved. Any
6
+ * framing needed to make a chunk survive the transport is the adapter's own concern.
7
+ */
8
+ type StreamAdapter = {
9
+ /**
10
+ * Discards any state left over from a previous stream with the same id, registers
11
+ * the id, and begins consuming `chunks` in the background.
12
+ *
13
+ * Resolves once the stream is registered and resumable, not once it is complete.
14
+ * A stream id may be reused, so implementations must not replay stale chunks.
15
+ *
16
+ * A generation id names one generation and is never reused: what an implementation does
17
+ * with a reused one is its own business, and no implementation has to make it work.
18
+ */
19
+ createStream(options: {
20
+ streamId: string;
21
+ /**
22
+ * Identifies this generation of the stream id, so it can be resumed and stopped on its
23
+ * own. The stream id is repointed at it.
24
+ */
25
+ generationId: string;
26
+ chunks: ReadableStream<string>;
27
+ /**
28
+ * Keeps the host process alive until the promise settles.
29
+ * Relevant for serverless runtimes where work after the response is suspended.
30
+ */
31
+ waitUntil?: (promise: Promise<unknown>) => void;
32
+ }): Promise<void>;
33
+ /**
34
+ * Returns the chunks of an in-flight stream: those already produced, followed by
35
+ * those still to come, ending when the stream ends.
36
+ *
37
+ * With `generationId`, follows that generation even when a newer one of the stream id is
38
+ * current. Without it, follows the generation the stream id currently points at.
39
+ *
40
+ * Resolves `null` when the stream is unknown, already finished, or expired.
41
+ */
42
+ resumeStream(options: {
43
+ streamId: string;
44
+ generationId?: string;
45
+ }): Promise<ReadableStream<string> | null>;
46
+ /**
47
+ * Signals the process that owns a generation of the stream to stop producing.
48
+ *
49
+ * With `generationId`, only that generation is stopped, including one that has not
50
+ * started yet if the store can keep the request until it does. Without it, the generation
51
+ * the stream id currently points at is stopped, and there is nothing to stop when it
52
+ * points at none. Safe to call for an unknown or finished stream.
53
+ */
54
+ requestStop(options: {
55
+ streamId: string;
56
+ generationId?: string;
57
+ }): Promise<void>;
58
+ /**
59
+ * Registers a producer-side listener for stop requests addressed to one generation. Returns
60
+ * a function that removes the listener, and only that listener.
61
+ *
62
+ * A stop requested for the generation before the listener was registered should still be
63
+ * reported, where the store can keep it.
64
+ */
65
+ onStopRequested(options: {
66
+ streamId: string;
67
+ generationId: string;
68
+ onStop: () => void;
69
+ }): Promise<() => void>;
70
+ };
71
+ /**
72
+ * Translates between chunks and the strings an adapter stores.
73
+ *
74
+ * `decode` returns `undefined` to drop a chunk that cannot be represented,
75
+ * so a single corrupt chunk never fails an entire resume.
76
+ */
77
+ type StreamCodec<CHUNK> = {
78
+ encode(chunk: CHUNK): string;
79
+ decode(data: string): CHUNK | undefined | Promise<CHUNK | undefined>;
80
+ };
81
+ //#endregion
82
+ export { StreamCodec as n, StreamAdapter as t };
@@ -0,0 +1,54 @@
1
+ import { t as StreamAdapter } from "../../adapter-CTz0z2k0.mjs";
2
+ import { Publisher, Subscriber } from "resumable-stream";
3
+ //#region src/adapters/redis/adapter.d.ts
4
+ /**
5
+ * A Redis client, described by the commands this adapter actually calls rather than by
6
+ * the client type of a specific `redis` release. The generic parameters of
7
+ * `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal
8
+ * type would pin consumers to one of them.
9
+ *
10
+ * `get` and `set` are redeclared because the pointer is a string with an expiry, which is
11
+ * narrower than what `resumable-stream` describes for its own use. `unsubscribe` is
12
+ * redeclared because a listener removes itself alone, never every listener of its channel.
13
+ */
14
+ type Redis = Omit<Publisher, `get` | `set`> & Omit<Subscriber, `unsubscribe`> & {
15
+ isOpen: boolean;
16
+ get(key: string): Promise<string | null>;
17
+ set(key: string, value: string, options?: {
18
+ expiration?: {
19
+ type: `EX`;
20
+ value: number;
21
+ };
22
+ }): Promise<unknown>;
23
+ unsubscribe(channel: string, listener?: (message: string) => void): Promise<unknown>;
24
+ del(key: string): Promise<unknown>;
25
+ eval(script: string, options?: {
26
+ keys?: Array<string>;
27
+ arguments?: Array<string>;
28
+ }): Promise<unknown>;
29
+ };
30
+ type CreateRedisAdapterOptions = {
31
+ /**
32
+ * A client from the `redis` package, used to publish chunks and stop requests.
33
+ * Connected on first use and never disconnected, so it stays reusable across streams.
34
+ */
35
+ publisher: Redis;
36
+ /**
37
+ * A second client, required because a subscribed connection cannot issue commands.
38
+ */
39
+ subscriber: Redis;
40
+ /**
41
+ * Namespace for every key and channel this adapter touches.
42
+ */
43
+ keyPrefix?: string;
44
+ };
45
+ /**
46
+ * Stores streams in Redis via `resumable-stream`.
47
+ *
48
+ * Chunks live in the memory of the producing process and reach late subscribers over
49
+ * Redis pub/sub, so a stream is only resumable while its producer is alive. Use a
50
+ * durable adapter when a stream must outlive the process that started it.
51
+ */
52
+ declare function createRedisAdapter(options: CreateRedisAdapterOptions): StreamAdapter;
53
+ //#endregion
54
+ export { type CreateRedisAdapterOptions, createRedisAdapter };
@@ -0,0 +1,258 @@
1
+ import { createResumableStreamContext } from "resumable-stream";
2
+ //#region src/adapters/redis/sse.ts
3
+ /**
4
+ * `resumable-stream` transports a stream of strings that it is free to concatenate and
5
+ * re-slice, so chunks have to carry their own boundaries. SSE framing supplies them:
6
+ * chunks are JSON, which never contains a raw newline, so a blank line always ends one.
7
+ */
8
+ const DATA_PREFIX = `data: `;
9
+ const CHUNK_SEPARATOR = `\n\n`;
10
+ const DONE = `[DONE]`;
11
+ /**
12
+ * Frames each chunk as an SSE event and terminates the stream with a done event.
13
+ */
14
+ function chunksToSSE() {
15
+ return new TransformStream({
16
+ transform(chunk, controller) {
17
+ controller.enqueue(`${DATA_PREFIX}${chunk}${CHUNK_SEPARATOR}`);
18
+ },
19
+ flush(controller) {
20
+ controller.enqueue(`${DATA_PREFIX}${DONE}${CHUNK_SEPARATOR}`);
21
+ }
22
+ });
23
+ }
24
+ /**
25
+ * Recovers chunks from SSE framing, tolerating arbitrary chunk boundaries.
26
+ */
27
+ function sseToChunks() {
28
+ let buffer = ``;
29
+ return new TransformStream({ transform(chunk, controller) {
30
+ buffer += chunk;
31
+ while (true) {
32
+ const end = buffer.indexOf(CHUNK_SEPARATOR);
33
+ if (end === -1) break;
34
+ const event = buffer.slice(0, end);
35
+ buffer = buffer.slice(end + CHUNK_SEPARATOR.length);
36
+ if (!event.startsWith(DATA_PREFIX)) continue;
37
+ const data = event.slice(DATA_PREFIX.length);
38
+ if (data === DONE) continue;
39
+ controller.enqueue(data);
40
+ }
41
+ } });
42
+ }
43
+ //#endregion
44
+ //#region src/adapters/redis/adapter.ts
45
+ const DEFAULT_KEY_PREFIX = `ai-resumable-stream`;
46
+ /**
47
+ * Matches the lifetime `resumable-stream` gives its own keys. The pointer is deleted as
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.
51
+ */
52
+ const GENERATION_TTL_SECONDS = 1440 * 60;
53
+ /**
54
+ * Deletes a key only while it still holds the expected value. One script, so no other
55
+ * client can write the key between the comparison and the deletion.
56
+ */
57
+ const DELETE_IF_EQUAL_SCRIPT = `if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) end return 0`;
58
+ /**
59
+ * How long a stop request is kept for a generation that has not observed it yet. A
60
+ * generation drops its own stop key when it ends, so this only bounds a stop that was
61
+ * requested for a generation which never ran, or which died before it could clean up.
62
+ */
63
+ const STOP_TTL_SECONDS = 3600;
64
+ /**
65
+ * Raised by `resumable-stream` when a producer stops answering resume requests.
66
+ */
67
+ const ACK_TIMEOUT_MESSAGE = `Timeout waiting for ack`;
68
+ function isAckTimeout(error) {
69
+ return (error instanceof Error ? error.message : String(error)).includes(ACK_TIMEOUT_MESSAGE);
70
+ }
71
+ /**
72
+ * Stores streams in Redis via `resumable-stream`.
73
+ *
74
+ * Chunks live in the memory of the producing process and reach late subscribers over
75
+ * Redis pub/sub, so a stream is only resumable while its producer is alive. Use a
76
+ * durable adapter when a stream must outlive the process that started it.
77
+ */
78
+ function createRedisAdapter(options) {
79
+ const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX } = options;
80
+ /**
81
+ * The name of one generation of a stream id. The generation id is encoded, so it holds
82
+ * no colon and the name splits one way only: stream `a` with generation `b:c` never
83
+ * shares a name with stream `a:b` with generation `c`. A generated id is left unchanged.
84
+ */
85
+ const generationName = (streamId, generationId) => `${streamId}:${encodeURIComponent(generationId)}`;
86
+ /**
87
+ * One channel per generation, so a stop reaches that generation alone, and removing the
88
+ * listener of one never removes the listener of another on the shared subscriber.
89
+ */
90
+ const stopChannel = (streamId, generationId) => `${keyPrefix}:stop:${generationName(streamId, generationId)}`;
91
+ /**
92
+ * A stop kept for a generation, because pub/sub has no retention and a stop published
93
+ * before its producer subscribed would otherwise be lost. Keyed by generation, so it
94
+ * can never reach a different generation of the same stream id.
95
+ */
96
+ const stopKey = (streamId, generationId) => `${keyPrefix}:stop:${generationName(streamId, generationId)}`;
97
+ /**
98
+ * Holds the generation a caller's stream id currently points at.
99
+ *
100
+ * A generation is one run of a stream id, and each gets a fresh id because a
101
+ * producer's teardown is asynchronous: it marks its stream done and drops its
102
+ * subscriptions well after the source has ended. Were a reused id to address the same
103
+ * underlying stream, a late teardown would tear down the generation that replaced it.
104
+ */
105
+ const pointerKey = (streamId) => `${keyPrefix}:generation:${streamId}`;
106
+ async function connect() {
107
+ await Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]);
108
+ }
109
+ function createContext(waitUntil) {
110
+ return createResumableStreamContext({
111
+ waitUntil: waitUntil ?? null,
112
+ publisher,
113
+ subscriber,
114
+ keyPrefix
115
+ });
116
+ }
117
+ async function readPointer(streamId) {
118
+ return publisher.get(pointerKey(streamId));
119
+ }
120
+ /**
121
+ * Drops the stop kept for a generation once it is over, so nothing outlives the
122
+ * generation it was meant for.
123
+ */
124
+ async function clearStop(streamId, generationId) {
125
+ await publisher.del(stopKey(streamId, generationId));
126
+ }
127
+ /**
128
+ * Retires the generation, but only while it is still the current one, so a slow
129
+ * teardown never retires its successor. The comparison and the deletion are atomic: a
130
+ * successor may repoint the id at any moment, including between the two.
131
+ */
132
+ async function clearPointer(streamId, generationId) {
133
+ await publisher.eval(DELETE_IF_EQUAL_SCRIPT, {
134
+ keys: [pointerKey(streamId)],
135
+ arguments: [generationId]
136
+ });
137
+ }
138
+ return {
139
+ async createStream({ streamId, generationId: runId, chunks, waitUntil }) {
140
+ await connect();
141
+ /**
142
+ * The pointer holds the full name, which is also the id `resumable-stream` knows
143
+ * the generation by, so two stream ids with the same generation id never share
144
+ * state.
145
+ */
146
+ const generationId = generationName(streamId, runId);
147
+ await publisher.set(pointerKey(streamId), generationId, { expiration: {
148
+ type: `EX`,
149
+ value: GENERATION_TTL_SECONDS
150
+ } });
151
+ /**
152
+ * The pointer is dropped as soon as the source ends, so a resume that arrives
153
+ * during teardown is told there is nothing to resume rather than racing it. The
154
+ * stop goes with it: a generation that is over has nothing left to stop.
155
+ */
156
+ const sse = chunks.pipeThrough(chunksToSSE()).pipeThrough(new TransformStream({ async flush() {
157
+ await Promise.all([clearPointer(streamId, generationId), clearStop(streamId, runId)]).catch(() => {
158
+ /** Both expire on their own */
159
+ });
160
+ } }));
161
+ await createContext(waitUntil).createNewResumableStream(generationId, () => sse);
162
+ },
163
+ async resumeStream({ streamId, generationId: runId }) {
164
+ await connect();
165
+ /**
166
+ * A named generation is followed without the pointer, so it can be resumed after a
167
+ * newer generation took the stream id. Whether its producer is still alive is then only
168
+ * known from `resumable-stream` itself.
169
+ */
170
+ const generationId = runId === void 0 ? await readPointer(streamId) : generationName(streamId, runId);
171
+ if (!generationId) return null;
172
+ const sse = await createContext().resumeExistingStream(generationId);
173
+ if (!sse) return null;
174
+ const reader = sse.pipeThrough(sseToChunks()).getReader();
175
+ /**
176
+ * The first chunk is read here rather than by the caller because a resume that
177
+ * races the producer's teardown only fails once it is read. Reporting that as
178
+ * "nothing to resume" makes it indistinguishable from a stream that already
179
+ * finished, which is what it is. The cost is that resuming a producer which has
180
+ * not yet emitted anything waits for its first chunk.
181
+ */
182
+ let first;
183
+ try {
184
+ first = await reader.read();
185
+ } catch (error) {
186
+ reader.releaseLock();
187
+ if (isAckTimeout(error)) return null;
188
+ throw error;
189
+ }
190
+ if (first.done) {
191
+ reader.releaseLock();
192
+ return null;
193
+ }
194
+ return new ReadableStream({
195
+ start(controller) {
196
+ controller.enqueue(first.value);
197
+ },
198
+ async pull(controller) {
199
+ const { done, value } = await reader.read();
200
+ if (done) {
201
+ controller.close();
202
+ return;
203
+ }
204
+ controller.enqueue(value);
205
+ },
206
+ cancel(reason) {
207
+ return reader.cancel(reason);
208
+ }
209
+ });
210
+ },
211
+ async requestStop({ streamId, generationId }) {
212
+ await connect();
213
+ /**
214
+ * Without a generation id, the stop is for the generation the pointer names at this
215
+ * moment. With the pointer naming none, there is nothing to keep the request under.
216
+ */
217
+ let runId = generationId;
218
+ if (runId === void 0) {
219
+ const current = await readPointer(streamId);
220
+ if (!current?.startsWith(`${streamId}:`)) return;
221
+ runId = decodeURIComponent(current.slice(streamId.length + 1));
222
+ }
223
+ /**
224
+ * Kept before it is published. A producer subscribes before it reads, so it either
225
+ * receives the message or finds the key.
226
+ */
227
+ await publisher.set(stopKey(streamId, runId), `1`, { expiration: {
228
+ type: `EX`,
229
+ value: STOP_TTL_SECONDS
230
+ } });
231
+ await publisher.publish(stopChannel(streamId, runId), `stop`);
232
+ },
233
+ async onStopRequested({ streamId, generationId, onStop }) {
234
+ await connect();
235
+ const channel = stopChannel(streamId, generationId);
236
+ const listener = () => onStop();
237
+ await subscriber.subscribe(channel, listener);
238
+ const unsubscribe = async () => {
239
+ await subscriber.unsubscribe(channel, listener);
240
+ };
241
+ /**
242
+ * Read only once subscribed. Reading first, or both at once, leaves a window in
243
+ * which a stop is neither kept yet nor delivered.
244
+ */
245
+ try {
246
+ if (await publisher.get(stopKey(streamId, generationId)) !== null) onStop();
247
+ } catch (error) {
248
+ await unsubscribe().catch(() => {
249
+ /** The subscription is gone with the connection */
250
+ });
251
+ throw error;
252
+ }
253
+ return unsubscribe;
254
+ }
255
+ };
256
+ }
257
+ //#endregion
258
+ export { createRedisAdapter };
@@ -0,0 +1,65 @@
1
+ import { t as StreamAdapter } from "../../adapter-CTz0z2k0.mjs";
2
+ import { S3Client } from "@aws-sdk/client-s3";
3
+ //#region src/adapters/s3-express/adapter.d.ts
4
+ type S3ExpressAdapterOptions = {
5
+ /**
6
+ * Namespace for every key this adapter writes. Point a lifecycle expiration rule at it.
7
+ */
8
+ prefix?: string;
9
+ /**
10
+ * How long chunks may sit in memory before being written. Defaults to 250ms.
11
+ *
12
+ * This is the cost dial. Every flush is one billed PUT, so doubling it roughly halves
13
+ * what a stream costs, and adds that much to how far a resuming reader lags.
14
+ */
15
+ flushIntervalMs?: number;
16
+ /**
17
+ * Forces a write once this many chunks are buffered, whatever the interval.
18
+ */
19
+ batchSize?: number;
20
+ /**
21
+ * How often a resuming reader looks for new bytes. Defaults to 500ms.
22
+ */
23
+ resumePollIntervalMs?: number;
24
+ /**
25
+ * How often a producer checks for a stop request. Defaults to 1s.
26
+ */
27
+ stopPollIntervalMs?: number;
28
+ /**
29
+ * How often a producer that has nothing to write records that it is alive.
30
+ * Defaults to 5s.
31
+ */
32
+ heartbeatMs?: number;
33
+ /**
34
+ * How long a log may go unwritten before its producer is presumed dead. Defaults to 30s.
35
+ *
36
+ * Keep it a healthy multiple of `heartbeatMs`: a missed beat means a busy event loop far
37
+ * more often than a dead process, and declaring death early truncates a live stream.
38
+ */
39
+ deadAfterMs?: number;
40
+ };
41
+ type CreateS3ExpressAdapterOptions = S3ExpressAdapterOptions & {
42
+ /**
43
+ * A client from `@aws-sdk/client-s3`, built and configured by the caller.
44
+ */
45
+ client: S3Client;
46
+ /**
47
+ * An S3 Express One Zone directory bucket in an Availability Zone. Appends exist
48
+ * nowhere else, and they are what makes a stream one object rather than thousands.
49
+ */
50
+ bucket: string;
51
+ };
52
+ /**
53
+ * Stores streams as one appendable object each, in an S3 Express One Zone bucket.
54
+ *
55
+ * Chunks, liveness and completion all live in the same log, so a reader following a
56
+ * stream costs one request per poll. Nothing is ever listed: every key is either derived
57
+ * from the stream id or named by the log itself.
58
+ *
59
+ * A stream stops being resumable when its producer stops, which is `deadAfterMs` at the
60
+ * outside. How long the objects then sit in the bucket is a lifecycle expiration rule
61
+ * rather than anything this can enforce, so nothing here is deleted.
62
+ */
63
+ declare function createS3ExpressAdapter(options: CreateS3ExpressAdapterOptions): StreamAdapter;
64
+ //#endregion
65
+ export { type CreateS3ExpressAdapterOptions, type S3ExpressAdapterOptions, createS3ExpressAdapter };