ai-resumable-stream 1.4.0 → 3.0.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,61 @@
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
+ createStream(options: {
17
+ streamId: string;
18
+ chunks: ReadableStream<string>;
19
+ /**
20
+ * Keeps the host process alive until the promise settles.
21
+ * Relevant for serverless runtimes where work after the response is suspended.
22
+ */
23
+ waitUntil?: (promise: Promise<unknown>) => void;
24
+ }): Promise<void>;
25
+ /**
26
+ * Returns the chunks of an in-flight stream: those already produced, followed by
27
+ * those still to come, ending when the stream ends.
28
+ *
29
+ * Resolves `null` when the stream is unknown, already finished, or expired.
30
+ */
31
+ resumeStream(options: {
32
+ streamId: string;
33
+ }): Promise<ReadableStream<string> | null>;
34
+ /**
35
+ * Signals whichever process owns the stream to stop producing.
36
+ * Safe to call for an unknown or finished stream.
37
+ */
38
+ requestStop(options: {
39
+ streamId: string;
40
+ }): Promise<void>;
41
+ /**
42
+ * Registers a producer-side listener for stop requests. Returns a function that
43
+ * removes the listener.
44
+ */
45
+ onStopRequested(options: {
46
+ streamId: string;
47
+ onStop: () => void;
48
+ }): Promise<() => void>;
49
+ };
50
+ /**
51
+ * Translates between chunks and the strings an adapter stores.
52
+ *
53
+ * `decode` returns `undefined` to drop a chunk that cannot be represented,
54
+ * so a single corrupt chunk never fails an entire resume.
55
+ */
56
+ type StreamCodec<CHUNK> = {
57
+ encode(chunk: CHUNK): string;
58
+ decode(data: string): CHUNK | undefined | Promise<CHUNK | undefined>;
59
+ };
60
+ //#endregion
61
+ export { StreamCodec as n, StreamAdapter as t };
@@ -0,0 +1,48 @@
1
+ import { t as StreamAdapter } from "../../adapter-D9qrs60B.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
11
+ * is narrower than what `resumable-stream` describes for its own use.
12
+ */
13
+ type Redis = Omit<Publisher, `get` | `set`> & Subscriber & {
14
+ isOpen: boolean;
15
+ get(key: string): Promise<string | null>;
16
+ set(key: string, value: string, options?: {
17
+ expiration?: {
18
+ type: `EX`;
19
+ value: number;
20
+ };
21
+ }): Promise<unknown>;
22
+ del(key: string): Promise<unknown>;
23
+ };
24
+ type CreateRedisAdapterOptions = {
25
+ /**
26
+ * A client from the `redis` package, used to publish chunks and stop requests.
27
+ * Connected on first use and never disconnected, so it stays reusable across streams.
28
+ */
29
+ publisher: Redis;
30
+ /**
31
+ * A second client, required because a subscribed connection cannot issue commands.
32
+ */
33
+ subscriber: Redis;
34
+ /**
35
+ * Namespace for every key and channel this adapter touches.
36
+ */
37
+ keyPrefix?: string;
38
+ };
39
+ /**
40
+ * Stores streams in Redis via `resumable-stream`.
41
+ *
42
+ * Chunks live in the memory of the producing process and reach late subscribers over
43
+ * Redis pub/sub, so a stream is only resumable while its producer is alive. Use a
44
+ * durable adapter when a stream must outlive the process that started it.
45
+ */
46
+ declare function createRedisAdapter(options: CreateRedisAdapterOptions): StreamAdapter;
47
+ //#endregion
48
+ export { type CreateRedisAdapterOptions, createRedisAdapter };
@@ -0,0 +1,177 @@
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
+ * Raised by `resumable-stream` when a producer stops answering resume requests.
55
+ */
56
+ const ACK_TIMEOUT_MESSAGE = `Timeout waiting for ack`;
57
+ function isAckTimeout(error) {
58
+ return (error instanceof Error ? error.message : String(error)).includes(ACK_TIMEOUT_MESSAGE);
59
+ }
60
+ /**
61
+ * Stores streams in Redis via `resumable-stream`.
62
+ *
63
+ * Chunks live in the memory of the producing process and reach late subscribers over
64
+ * Redis pub/sub, so a stream is only resumable while its producer is alive. Use a
65
+ * durable adapter when a stream must outlive the process that started it.
66
+ */
67
+ function createRedisAdapter(options) {
68
+ const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX } = options;
69
+ const stopChannel = (streamId) => `${keyPrefix}:stop:${streamId}`;
70
+ /**
71
+ * Points a caller's stream id at its current generation.
72
+ *
73
+ * A generation is one run of a stream id, and each gets a fresh id because a
74
+ * producer's teardown is asynchronous: it marks its stream done and drops its
75
+ * subscriptions well after the source has ended. Were a reused id to address the same
76
+ * underlying stream, a late teardown would tear down the generation that replaced it.
77
+ */
78
+ const generationKey = (streamId) => `${keyPrefix}:generation:${streamId}`;
79
+ async function connect() {
80
+ await Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]);
81
+ }
82
+ function createContext(waitUntil) {
83
+ return createResumableStreamContext({
84
+ waitUntil: waitUntil ?? null,
85
+ publisher,
86
+ subscriber,
87
+ keyPrefix
88
+ });
89
+ }
90
+ async function readGenerationId(streamId) {
91
+ return publisher.get(generationKey(streamId));
92
+ }
93
+ /**
94
+ * Retires the generation, but only while it is still the current one, so a slow
95
+ * teardown never retires its successor.
96
+ */
97
+ async function clearGenerationId(streamId, generationId) {
98
+ if (await readGenerationId(streamId) === generationId) await publisher.del(generationKey(streamId));
99
+ }
100
+ return {
101
+ async createStream({ streamId, chunks, waitUntil }) {
102
+ await connect();
103
+ const generationId = `${streamId}:${crypto.randomUUID()}`;
104
+ await publisher.set(generationKey(streamId), generationId, { expiration: {
105
+ type: `EX`,
106
+ value: GENERATION_TTL_SECONDS
107
+ } });
108
+ /**
109
+ * The pointer is dropped as soon as the source ends, so a resume that arrives
110
+ * during teardown is told there is nothing to resume rather than racing it.
111
+ */
112
+ const sse = chunks.pipeThrough(chunksToSSE()).pipeThrough(new TransformStream({ async flush() {
113
+ await clearGenerationId(streamId, generationId).catch(() => {
114
+ /** Expires on its own */
115
+ });
116
+ } }));
117
+ await createContext(waitUntil).createNewResumableStream(generationId, () => sse);
118
+ },
119
+ async resumeStream({ streamId }) {
120
+ await connect();
121
+ const generationId = await readGenerationId(streamId);
122
+ if (!generationId) return null;
123
+ const sse = await createContext().resumeExistingStream(generationId);
124
+ if (!sse) return null;
125
+ const reader = sse.pipeThrough(sseToChunks()).getReader();
126
+ /**
127
+ * The first chunk is read here rather than by the caller because a resume that
128
+ * races the producer's teardown only fails once it is read. Reporting that as
129
+ * "nothing to resume" makes it indistinguishable from a stream that already
130
+ * finished, which is what it is. The cost is that resuming a producer which has
131
+ * not yet emitted anything waits for its first chunk.
132
+ */
133
+ let first;
134
+ try {
135
+ first = await reader.read();
136
+ } catch (error) {
137
+ reader.releaseLock();
138
+ if (isAckTimeout(error)) return null;
139
+ throw error;
140
+ }
141
+ if (first.done) {
142
+ reader.releaseLock();
143
+ return null;
144
+ }
145
+ return new ReadableStream({
146
+ start(controller) {
147
+ controller.enqueue(first.value);
148
+ },
149
+ async pull(controller) {
150
+ const { done, value } = await reader.read();
151
+ if (done) {
152
+ controller.close();
153
+ return;
154
+ }
155
+ controller.enqueue(value);
156
+ },
157
+ cancel(reason) {
158
+ return reader.cancel(reason);
159
+ }
160
+ });
161
+ },
162
+ async requestStop({ streamId }) {
163
+ await connect();
164
+ await publisher.publish(stopChannel(streamId), `stop`);
165
+ },
166
+ async onStopRequested({ streamId, onStop }) {
167
+ await connect();
168
+ const channel = stopChannel(streamId);
169
+ await subscriber.subscribe(channel, () => onStop());
170
+ return async () => {
171
+ await subscriber.unsubscribe(channel);
172
+ };
173
+ }
174
+ };
175
+ }
176
+ //#endregion
177
+ export { createRedisAdapter };
@@ -0,0 +1,65 @@
1
+ import { t as StreamAdapter } from "../../adapter-D9qrs60B.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 };