|
| 1 | +import { ApiClient } from "../apiClient/index.js"; |
| 2 | +import { AsyncIterableStream } from "../streams/asyncIterableStream.js"; |
| 3 | +import { AnyZodFetchOptions } from "../zodfetch.js"; |
| 4 | +import { StreamsWriterV1 } from "./streamsWriterV1.js"; |
| 5 | +import { StreamsWriterV2 } from "./streamsWriterV2.js"; |
| 6 | +import { StreamsWriter } from "./types.js"; |
| 7 | + |
| 8 | +export type StreamInstanceOptions<T> = { |
| 9 | + apiClient: ApiClient; |
| 10 | + baseUrl: string; |
| 11 | + runId: string; |
| 12 | + key: string; |
| 13 | + source: AsyncIterable<T>; |
| 14 | + headers?: Record<string, string>; |
| 15 | + signal?: AbortSignal; |
| 16 | + requestOptions?: AnyZodFetchOptions; |
| 17 | + target?: "self" | "parent" | "root" | string; |
| 18 | + debug?: boolean; |
| 19 | +}; |
| 20 | + |
| 21 | +type StreamsWriterInstance<T> = StreamsWriterV1<T> | StreamsWriterV2<T>; |
| 22 | + |
| 23 | +export class StreamInstance<T> implements StreamsWriter { |
| 24 | + private streamPromise: Promise<StreamsWriterInstance<T>>; |
| 25 | + |
| 26 | + constructor(private options: StreamInstanceOptions<T>) { |
| 27 | + this.streamPromise = this.initializeWriter(); |
| 28 | + } |
| 29 | + |
| 30 | + private async initializeWriter(): Promise<StreamsWriterInstance<T>> { |
| 31 | + const { version, headers } = await this.options.apiClient.createStream( |
| 32 | + this.options.runId, |
| 33 | + "self", |
| 34 | + this.options.key, |
| 35 | + this.options?.requestOptions |
| 36 | + ); |
| 37 | + |
| 38 | + const parsedResponse = parseCreateStreamResponse(version, headers); |
| 39 | + |
| 40 | + const streamWriter = |
| 41 | + parsedResponse.version === "v1" |
| 42 | + ? new StreamsWriterV1({ |
| 43 | + key: this.options.key, |
| 44 | + runId: this.options.runId, |
| 45 | + source: this.options.source, |
| 46 | + baseUrl: this.options.baseUrl, |
| 47 | + headers: this.options.apiClient.getHeaders(), |
| 48 | + signal: this.options.signal, |
| 49 | + version, |
| 50 | + target: "self", |
| 51 | + }) |
| 52 | + : new StreamsWriterV2({ |
| 53 | + basin: parsedResponse.basin, |
| 54 | + stream: this.options.key, |
| 55 | + accessToken: parsedResponse.accessToken, |
| 56 | + source: this.options.source, |
| 57 | + signal: this.options.signal, |
| 58 | + limiter: (await import("p-limit")).default, |
| 59 | + debug: this.options.debug, |
| 60 | + flushIntervalMs: parsedResponse.flushIntervalMs, |
| 61 | + maxRetries: parsedResponse.maxRetries, |
| 62 | + }); |
| 63 | + |
| 64 | + return streamWriter; |
| 65 | + } |
| 66 | + |
| 67 | + public async wait(): Promise<void> { |
| 68 | + return this.streamPromise.then((writer) => writer.wait()); |
| 69 | + } |
| 70 | + |
| 71 | + public get stream(): AsyncIterableStream<T> { |
| 72 | + const self = this; |
| 73 | + |
| 74 | + return new ReadableStream<T>({ |
| 75 | + async start(controller) { |
| 76 | + const streamWriter = await self.streamPromise; |
| 77 | + |
| 78 | + const iterator = streamWriter[Symbol.asyncIterator](); |
| 79 | + |
| 80 | + while (true) { |
| 81 | + if (self.options.signal?.aborted) { |
| 82 | + break; |
| 83 | + } |
| 84 | + |
| 85 | + const { done, value } = await iterator.next(); |
| 86 | + |
| 87 | + if (done) { |
| 88 | + controller.close(); |
| 89 | + break; |
| 90 | + } |
| 91 | + |
| 92 | + controller.enqueue(value); |
| 93 | + } |
| 94 | + }, |
| 95 | + }); |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +type ParsedStreamResponse = |
| 100 | + | { |
| 101 | + version: "v1"; |
| 102 | + } |
| 103 | + | { |
| 104 | + version: "v2"; |
| 105 | + accessToken: string; |
| 106 | + basin: string; |
| 107 | + flushIntervalMs?: number; |
| 108 | + maxRetries?: number; |
| 109 | + }; |
| 110 | + |
| 111 | +function parseCreateStreamResponse( |
| 112 | + version: string, |
| 113 | + headers: Record<string, string> | undefined |
| 114 | +): ParsedStreamResponse { |
| 115 | + if (version === "v1") { |
| 116 | + return { version: "v1" }; |
| 117 | + } |
| 118 | + |
| 119 | + const accessToken = headers?.["x-s2-access-token"]; |
| 120 | + const basin = headers?.["x-s2-basin"]; |
| 121 | + |
| 122 | + if (!accessToken || !basin) { |
| 123 | + return { version: "v1" }; |
| 124 | + } |
| 125 | + |
| 126 | + const flushIntervalMs = headers?.["x-s2-flush-interval-ms"]; |
| 127 | + const maxRetries = headers?.["x-s2-max-retries"]; |
| 128 | + |
| 129 | + return { |
| 130 | + version: "v2", |
| 131 | + accessToken, |
| 132 | + basin, |
| 133 | + flushIntervalMs: flushIntervalMs ? parseInt(flushIntervalMs) : undefined, |
| 134 | + maxRetries: maxRetries ? parseInt(maxRetries) : undefined, |
| 135 | + }; |
| 136 | +} |
| 137 | + |
| 138 | +async function* streamToAsyncIterator<T>(stream: ReadableStream<T>): AsyncIterableIterator<T> { |
| 139 | + const reader = stream.getReader(); |
| 140 | + try { |
| 141 | + while (true) { |
| 142 | + const { done, value } = await reader.read(); |
| 143 | + if (done) return; |
| 144 | + yield value; |
| 145 | + } |
| 146 | + } finally { |
| 147 | + safeReleaseLock(reader); |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +function safeReleaseLock(reader: ReadableStreamDefaultReader<any>) { |
| 152 | + try { |
| 153 | + reader.releaseLock(); |
| 154 | + } catch (error) {} |
| 155 | +} |
0 commit comments