ai-resumable-stream 3.0.0 → 3.2.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.
@@ -12,9 +12,17 @@ type StreamAdapter = {
12
12
  *
13
13
  * Resolves once the stream is registered and resumable, not once it is complete.
14
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.
15
18
  */
16
19
  createStream(options: {
17
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;
18
26
  chunks: ReadableStream<string>;
19
27
  /**
20
28
  * Keeps the host process alive until the promise settles.
@@ -26,24 +34,37 @@ type StreamAdapter = {
26
34
  * Returns the chunks of an in-flight stream: those already produced, followed by
27
35
  * those still to come, ending when the stream ends.
28
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
+ *
29
40
  * Resolves `null` when the stream is unknown, already finished, or expired.
30
41
  */
31
42
  resumeStream(options: {
32
43
  streamId: string;
44
+ generationId?: string;
33
45
  }): Promise<ReadableStream<string> | null>;
34
46
  /**
35
- * Signals whichever process owns the stream to stop producing.
36
- * Safe to call for an unknown or finished stream.
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.
37
53
  */
38
54
  requestStop(options: {
39
55
  streamId: string;
56
+ generationId?: string;
40
57
  }): Promise<void>;
41
58
  /**
42
- * Registers a producer-side listener for stop requests. Returns a function that
43
- * removes the listener.
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.
44
64
  */
45
65
  onStopRequested(options: {
46
66
  streamId: string;
67
+ generationId: string;
47
68
  onStop: () => void;
48
69
  }): Promise<() => void>;
49
70
  };
@@ -1,4 +1,4 @@
1
- import { t as StreamAdapter } from "../../adapter-D9qrs60B.mjs";
1
+ import { t as StreamAdapter } from "../../adapter-CTz0z2k0.mjs";
2
2
  import { Publisher, Subscriber } from "resumable-stream";
3
3
  //#region src/adapters/redis/adapter.d.ts
4
4
  /**
@@ -7,10 +7,11 @@ import { Publisher, Subscriber } from "resumable-stream";
7
7
  * `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal
8
8
  * type would pin consumers to one of them.
9
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.
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.
12
13
  */
13
- type Redis = Omit<Publisher, `get` | `set`> & Subscriber & {
14
+ type Redis = Omit<Publisher, `get` | `set`> & Omit<Subscriber, `unsubscribe`> & {
14
15
  isOpen: boolean;
15
16
  get(key: string): Promise<string | null>;
16
17
  set(key: string, value: string, options?: {
@@ -19,7 +20,12 @@ type Redis = Omit<Publisher, `get` | `set`> & Subscriber & {
19
20
  value: number;
20
21
  };
21
22
  }): Promise<unknown>;
23
+ unsubscribe(channel: string, listener?: (message: string) => void): Promise<unknown>;
22
24
  del(key: string): Promise<unknown>;
25
+ eval(script: string, options?: {
26
+ keys?: Array<string>;
27
+ arguments?: Array<string>;
28
+ }): Promise<unknown>;
23
29
  };
24
30
  type CreateRedisAdapterOptions = {
25
31
  /**
@@ -51,6 +51,17 @@ const DEFAULT_KEY_PREFIX = `ai-resumable-stream`;
51
51
  */
52
52
  const GENERATION_TTL_SECONDS = 1440 * 60;
53
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
+ /**
54
65
  * Raised by `resumable-stream` when a producer stops answering resume requests.
55
66
  */
56
67
  const ACK_TIMEOUT_MESSAGE = `Timeout waiting for ack`;
@@ -66,16 +77,32 @@ function isAckTimeout(error) {
66
77
  */
67
78
  function createRedisAdapter(options) {
68
79
  const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX } = options;
69
- const stopChannel = (streamId) => `${keyPrefix}:stop:${streamId}`;
70
80
  /**
71
- * Points a caller's stream id at its current generation.
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.
72
99
  *
73
100
  * A generation is one run of a stream id, and each gets a fresh id because a
74
101
  * producer's teardown is asynchronous: it marks its stream done and drops its
75
102
  * subscriptions well after the source has ended. Were a reused id to address the same
76
103
  * underlying stream, a late teardown would tear down the generation that replaced it.
77
104
  */
78
- const generationKey = (streamId) => `${keyPrefix}:generation:${streamId}`;
105
+ const pointerKey = (streamId) => `${keyPrefix}:generation:${streamId}`;
79
106
  async function connect() {
80
107
  await Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]);
81
108
  }
@@ -87,38 +114,60 @@ function createRedisAdapter(options) {
87
114
  keyPrefix
88
115
  });
89
116
  }
90
- async function readGenerationId(streamId) {
91
- return publisher.get(generationKey(streamId));
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));
92
126
  }
93
127
  /**
94
128
  * Retires the generation, but only while it is still the current one, so a slow
95
- * teardown never retires its successor.
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.
96
131
  */
97
- async function clearGenerationId(streamId, generationId) {
98
- if (await readGenerationId(streamId) === generationId) await publisher.del(generationKey(streamId));
132
+ async function clearPointer(streamId, generationId) {
133
+ await publisher.eval(DELETE_IF_EQUAL_SCRIPT, {
134
+ keys: [pointerKey(streamId)],
135
+ arguments: [generationId]
136
+ });
99
137
  }
100
138
  return {
101
- async createStream({ streamId, chunks, waitUntil }) {
139
+ async createStream({ streamId, generationId: runId, chunks, waitUntil }) {
102
140
  await connect();
103
- const generationId = `${streamId}:${crypto.randomUUID()}`;
104
- await publisher.set(generationKey(streamId), generationId, { expiration: {
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: {
105
148
  type: `EX`,
106
149
  value: GENERATION_TTL_SECONDS
107
150
  } });
108
151
  /**
109
152
  * 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.
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.
111
155
  */
112
156
  const sse = chunks.pipeThrough(chunksToSSE()).pipeThrough(new TransformStream({ async flush() {
113
- await clearGenerationId(streamId, generationId).catch(() => {
114
- /** Expires on its own */
157
+ await Promise.all([clearPointer(streamId, generationId), clearStop(streamId, runId)]).catch(() => {
158
+ /** Both expire on their own */
115
159
  });
116
160
  } }));
117
161
  await createContext(waitUntil).createNewResumableStream(generationId, () => sse);
118
162
  },
119
- async resumeStream({ streamId }) {
163
+ async resumeStream({ streamId, generationId: runId }) {
120
164
  await connect();
121
- const generationId = await readGenerationId(streamId);
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);
122
171
  if (!generationId) return null;
123
172
  const sse = await createContext().resumeExistingStream(generationId);
124
173
  if (!sse) return null;
@@ -159,17 +208,49 @@ function createRedisAdapter(options) {
159
208
  }
160
209
  });
161
210
  },
162
- async requestStop({ streamId }) {
211
+ async requestStop({ streamId, generationId }) {
163
212
  await connect();
164
- await publisher.publish(stopChannel(streamId), `stop`);
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`);
165
232
  },
166
- async onStopRequested({ streamId, onStop }) {
233
+ async onStopRequested({ streamId, generationId, onStop }) {
167
234
  await connect();
168
- const channel = stopChannel(streamId);
169
- await subscriber.subscribe(channel, () => onStop());
170
- return async () => {
171
- await subscriber.unsubscribe(channel);
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);
172
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;
173
254
  }
174
255
  };
175
256
  }
@@ -1,4 +1,4 @@
1
- import { t as StreamAdapter } from "../../adapter-D9qrs60B.mjs";
1
+ import { t as StreamAdapter } from "../../adapter-CTz0z2k0.mjs";
2
2
  import { S3Client } from "@aws-sdk/client-s3";
3
3
  //#region src/adapters/s3-express/adapter.d.ts
4
4
  type S3ExpressAdapterOptions = {
@@ -11,6 +11,15 @@ var WriteOffsetMismatchError = class extends Error {
11
11
  }
12
12
  };
13
13
  /**
14
+ * Raised when an object is created under a key that already holds one.
15
+ */
16
+ var ObjectExistsError = class extends Error {
17
+ constructor(key) {
18
+ super(`Object ${key} already exists`);
19
+ this.name = `ObjectExistsError`;
20
+ }
21
+ };
22
+ /**
14
23
  * Raised when a segment has used all of its 10,000 parts.
15
24
  */
16
25
  var TooManyPartsError = class extends Error {
@@ -28,6 +37,14 @@ function nameOf(error) {
28
37
  function isMissing(error) {
29
38
  return statusOf(error) === 404 || nameOf(error) === `NoSuchKey` || nameOf(error) === `NotFound`;
30
39
  }
40
+ /**
41
+ * A conditional write that lost: the object exists (412), or another conditional write
42
+ * to the same key was in flight (409).
43
+ */
44
+ function isConditionFailed(error) {
45
+ const status = statusOf(error);
46
+ return status === 412 || status === 409 || nameOf(error) === `PreconditionFailed` || nameOf(error) === `ConditionalRequestConflict`;
47
+ }
31
48
  function isUnsatisfiableRange(error) {
32
49
  return statusOf(error) === 416 || nameOf(error) === `InvalidRange`;
33
50
  }
@@ -69,6 +86,19 @@ function createS3Operations(options) {
69
86
  Body: body
70
87
  }));
71
88
  },
89
+ async create(key, body) {
90
+ try {
91
+ await client.send(new PutObjectCommand({
92
+ Bucket: bucket,
93
+ Key: key,
94
+ Body: body,
95
+ IfNoneMatch: `*`
96
+ }));
97
+ } catch (error) {
98
+ if (isConditionFailed(error)) throw new ObjectExistsError(key);
99
+ throw error;
100
+ }
101
+ },
72
102
  async append(key, offset, body) {
73
103
  try {
74
104
  await client.send(new PutObjectCommand({
@@ -331,29 +361,18 @@ function createSerialQueue() {
331
361
  /**
332
362
  * Watches for stop requests on behalf of producers, when the store has no way to push one.
333
363
  *
334
- * Two things make this more than a poll loop. A watcher is asked for before the generation
335
- * it guards exists, because `core` registers the listener first and the stream second. And
336
- * a stream id may be reused while its previous producer is still shutting down, so at that
337
- * moment two watchers of one id are alive at once, each belonging to a different
338
- * generation. Pairing them first in first out is exact, because the two calls are always
339
- * made in pairs and in order.
364
+ * A watcher is told the generation it guards, and stop requests are kept per generation,
365
+ * so it may start asking before the generation's log exists and still see a stop that was
366
+ * requested earlier. Two generations of one stream id are watched independently.
340
367
  *
341
368
  * Nothing here knows where a stop request is kept. It asks a question and waits.
342
369
  */
343
370
  function createStopWatchers(options) {
344
371
  const { isStopRequested, pollIntervalMs } = options;
345
- const waiting = /* @__PURE__ */ new Map();
346
- function createWatcher(streamId, onStop) {
372
+ return { watch(streamId, generationId, onStop) {
347
373
  const abortController = new AbortController();
348
374
  const { signal } = abortController;
349
- let begin = () => {};
350
- const started = new Promise((resolve) => {
351
- begin = resolve;
352
- });
353
375
  (async () => {
354
- const generationId = await started;
355
- /** Cancelled before it was ever paired with a generation. */
356
- if (generationId === void 0) return;
357
376
  while (!signal.aborted) {
358
377
  try {
359
378
  if (await isStopRequested(streamId, generationId)) {
@@ -364,36 +383,8 @@ function createStopWatchers(options) {
364
383
  await delay(pollIntervalMs, signal);
365
384
  }
366
385
  })();
367
- return {
368
- begin,
369
- cancel: () => {
370
- abortController.abort();
371
- begin(void 0);
372
- }
373
- };
374
- }
375
- return {
376
- watch(streamId, onStop) {
377
- const watcher = createWatcher(streamId, onStop);
378
- const queue = waiting.get(streamId) ?? [];
379
- queue.push(watcher);
380
- waiting.set(streamId, queue);
381
- return () => {
382
- watcher.cancel();
383
- const queued = waiting.get(streamId);
384
- if (!queued) return;
385
- const index = queued.indexOf(watcher);
386
- if (index !== -1) queued.splice(index, 1);
387
- if (queued.length === 0) waiting.delete(streamId);
388
- };
389
- },
390
- begin(streamId, generationId) {
391
- const queue = waiting.get(streamId);
392
- const watcher = queue?.shift();
393
- if (queue?.length === 0) waiting.delete(streamId);
394
- watcher?.begin(generationId);
395
- }
396
- };
386
+ return () => abortController.abort();
387
+ } };
397
388
  }
398
389
  //#endregion
399
390
  //#region src/adapters/s3-express/adapter.ts
@@ -407,6 +398,20 @@ const DEFAULT_DEAD_AFTER_MS = 3e4;
407
398
  const DEFAULT_MAX_PARTS_PER_SEGMENT = 9e3;
408
399
  const encoder = new TextEncoder();
409
400
  const decoder = new TextDecoder();
401
+ /**
402
+ * The name of the pointer object inside a stream's prefix. A generation id may not take
403
+ * it, or the pointer would sit where that generation's directory has to be.
404
+ */
405
+ const POINTER_NAME = `current`;
406
+ /**
407
+ * Path segments a generation id cannot become: nothing, a relative path, or the pointer.
408
+ */
409
+ const RESERVED_SEGMENTS = /* @__PURE__ */ new Set([
410
+ ``,
411
+ `.`,
412
+ `..`,
413
+ POINTER_NAME
414
+ ]);
410
415
  const VERSION_RECORD = encodeVersion();
411
416
  const STOP_MARKER = encoder.encode(`1`);
412
417
  function unref(timer) {
@@ -462,9 +467,19 @@ function createStreamAdapter(s3, options = {}) {
462
467
  * a directory or collide with the keys of another stream.
463
468
  */
464
469
  const streamPrefix = (streamId) => `${prefix}/${encodeURIComponent(streamId)}`;
465
- const pointerKey = (streamId) => `${streamPrefix(streamId)}/current`;
466
- const stopKey = (streamId, generationId) => `${streamPrefix(streamId)}/${generationId}/stop`;
467
- const segmentKey = (streamId, generationId, index) => `${streamPrefix(streamId)}/${generationId}/${index}`;
470
+ const pointerKey = (streamId) => `${streamPrefix(streamId)}/${POINTER_NAME}`;
471
+ const stopKey = (streamId, generationId) => `${generationPrefix(streamId, generationId)}/stop`;
472
+ const segmentKey = (streamId, generationId, index) => `${generationPrefix(streamId, generationId)}/${index}`;
473
+ /**
474
+ * A generation id becomes one path segment next to the pointer, for the same reason as
475
+ * a stream id. Encoding leaves a generated id unchanged, so the layout is the same
476
+ * whether the caller chose the id or not.
477
+ */
478
+ function generationPrefix(streamId, generationId) {
479
+ const segment = encodeURIComponent(generationId);
480
+ if (RESERVED_SEGMENTS.has(segment)) throw new Error(`generationId must not be empty, "." or "..", nor "${POINTER_NAME}"`);
481
+ return `${streamPrefix(streamId)}/${segment}`;
482
+ }
468
483
  async function readPointer(streamId) {
469
484
  const result = await s3.read(pointerKey(streamId), 0);
470
485
  if (!result || result.bytes.length === 0) return void 0;
@@ -475,16 +490,16 @@ function createStreamAdapter(s3, options = {}) {
475
490
  }
476
491
  }
477
492
  /**
478
- * Stop requests are keyed by generation, so one can never reach the generation that
479
- * replaced it, and nothing has to be cleaned up when a stream id is reused.
493
+ * Stop requests are keyed by generation, so one can never reach another generation of
494
+ * the same stream id, and nothing has to be cleaned up when a stream id is reused. A stop
495
+ * may be written before its generation starts, and is found once it does.
480
496
  */
481
497
  const stopWatchers = createStopWatchers({
482
498
  pollIntervalMs: stopPollIntervalMs,
483
499
  isStopRequested: async (streamId, generationId) => await s3.head(stopKey(streamId, generationId)) !== void 0
484
500
  });
485
501
  return {
486
- async createStream({ streamId, chunks, waitUntil }) {
487
- const generationId = crypto.randomUUID();
502
+ async createStream({ streamId, generationId, chunks, waitUntil }) {
488
503
  const pointer = { generationId };
489
504
  /**
490
505
  * A segment opens with its format version, so it is never empty and a reader gets
@@ -498,9 +513,14 @@ function createStreamAdapter(s3, options = {}) {
498
513
  offset: VERSION_RECORD.length,
499
514
  parts: 1
500
515
  };
501
- await s3.put(segment.key, VERSION_RECORD);
516
+ /**
517
+ * Created rather than written: a generation id that already has a log belongs to
518
+ * another generation, and overwriting it would corrupt that stream and leave its
519
+ * producer appending into an object it no longer agrees with. `ObjectExistsError`
520
+ * says so instead.
521
+ */
522
+ await s3.create(segment.key, VERSION_RECORD);
502
523
  await s3.put(pointerKey(streamId), encoder.encode(JSON.stringify(pointer)));
503
- stopWatchers.begin(streamId, generationId);
504
524
  const writes = createSerialQueue();
505
525
  async function appendRecord(body) {
506
526
  try {
@@ -614,11 +634,21 @@ function createStreamAdapter(s3, options = {}) {
614
634
  })();
615
635
  waitUntil?.(consumed);
616
636
  },
617
- async resumeStream({ streamId }) {
618
- const pointer = await readPointer(streamId);
619
- if (!pointer) return null;
637
+ async resumeStream({ streamId, generationId }) {
638
+ /**
639
+ * A named generation is read directly, so it can be resumed after a newer one took
640
+ * the pointer. An id that cannot name a generation names nothing to resume.
641
+ */
642
+ const target = generationId ?? (await readPointer(streamId))?.generationId;
643
+ if (target === void 0) return null;
644
+ let firstKey;
645
+ try {
646
+ firstKey = segmentKey(streamId, target, 0);
647
+ } catch {
648
+ return null;
649
+ }
620
650
  const cursor = {
621
- key: segmentKey(streamId, pointer.generationId, 0),
651
+ key: firstKey,
622
652
  offset: 0
623
653
  };
624
654
  const replay = [];
@@ -705,13 +735,15 @@ function createStreamAdapter(s3, options = {}) {
705
735
  }
706
736
  });
707
737
  },
708
- async requestStop({ streamId }) {
709
- const pointer = await readPointer(streamId);
710
- if (!pointer) return;
711
- await s3.put(stopKey(streamId, pointer.generationId), STOP_MARKER);
738
+ async requestStop({ streamId, generationId }) {
739
+ const target = generationId ?? (await readPointer(streamId))?.generationId;
740
+ if (target === void 0) return;
741
+ await s3.put(stopKey(streamId, target), STOP_MARKER);
712
742
  },
713
- async onStopRequested({ streamId, onStop }) {
714
- return stopWatchers.watch(streamId, onStop);
743
+ async onStopRequested({ streamId, generationId, onStop }) {
744
+ /** Fails here, rather than on every poll, for an id that cannot name a generation. */
745
+ stopKey(streamId, generationId);
746
+ return stopWatchers.watch(streamId, generationId, onStop);
715
747
  }
716
748
  };
717
749
  }
@@ -1,5 +1,5 @@
1
- import { n as StreamCodec } from "../adapter-D9qrs60B.mjs";
2
- import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-CE_FvT5z.mjs";
1
+ import { n as StreamCodec } from "../adapter-CTz0z2k0.mjs";
2
+ import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-DaFTnidy.mjs";
3
3
  import { UIMessageChunk } from "ai";
4
4
  //#region src/ai-sdk/index.d.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { t as createResumableStream } from "../core-BteCDwPY.mjs";
1
+ import { t as createResumableStream } from "../core-DLalFjGA.mjs";
2
2
  import { asSchema, uiMessageChunkSchema } from "ai";
3
3
  //#region src/ai-sdk/index.ts
4
4
  const schema = asSchema(uiMessageChunkSchema);