|
| 1 | +import { AuthenticatedEnvironment } from "../apiAuth.server"; |
| 2 | +import { logger } from "../logger.server"; |
| 3 | +import { StreamIngestor, StreamResponder } from "./types"; |
| 4 | +import { LineTransformStream } from "./utils.server"; |
| 5 | +import { v1RealtimeStreams } from "./v1StreamsGlobal.server"; |
| 6 | +import { singleton } from "~/utils/singleton"; |
| 7 | + |
| 8 | +export type RelayRealtimeStreamsOptions = { |
| 9 | + ttl: number; |
| 10 | + fallbackIngestor: StreamIngestor; |
| 11 | + fallbackResponder: StreamResponder; |
| 12 | + waitForBufferTimeout?: number; // Time to wait for buffer in ms (default: 500ms) |
| 13 | + waitForBufferInterval?: number; // Polling interval in ms (default: 50ms) |
| 14 | +}; |
| 15 | + |
| 16 | +interface RelayedStreamRecord { |
| 17 | + stream: ReadableStream<Uint8Array>; |
| 18 | + createdAt: number; |
| 19 | + lastAccessed: number; |
| 20 | + finalized: boolean; |
| 21 | +} |
| 22 | + |
| 23 | +export class RelayRealtimeStreams implements StreamIngestor, StreamResponder { |
| 24 | + private _buffers: Map<string, RelayedStreamRecord> = new Map(); |
| 25 | + private cleanupInterval: NodeJS.Timeout; |
| 26 | + private waitForBufferTimeout: number; |
| 27 | + private waitForBufferInterval: number; |
| 28 | + |
| 29 | + constructor(private options: RelayRealtimeStreamsOptions) { |
| 30 | + this.waitForBufferTimeout = options.waitForBufferTimeout ?? 5000; |
| 31 | + this.waitForBufferInterval = options.waitForBufferInterval ?? 50; |
| 32 | + |
| 33 | + // Periodic cleanup |
| 34 | + this.cleanupInterval = setInterval(() => { |
| 35 | + this.cleanup(); |
| 36 | + }, this.options.ttl).unref(); |
| 37 | + } |
| 38 | + |
| 39 | + async streamResponse( |
| 40 | + request: Request, |
| 41 | + runId: string, |
| 42 | + streamId: string, |
| 43 | + environment: AuthenticatedEnvironment, |
| 44 | + signal: AbortSignal |
| 45 | + ): Promise<Response> { |
| 46 | + let record = this._buffers.get(`${runId}:${streamId}`); |
| 47 | + |
| 48 | + if (!record) { |
| 49 | + logger.debug( |
| 50 | + "[RelayRealtimeStreams][streamResponse] No ephemeral record found, waiting to see if one becomes available", |
| 51 | + { |
| 52 | + streamId, |
| 53 | + runId, |
| 54 | + } |
| 55 | + ); |
| 56 | + |
| 57 | + record = await this.waitForBuffer(`${runId}:${streamId}`); |
| 58 | + |
| 59 | + if (!record) { |
| 60 | + logger.debug( |
| 61 | + "[RelayRealtimeStreams][streamResponse] No ephemeral record found, using fallback", |
| 62 | + { |
| 63 | + streamId, |
| 64 | + runId, |
| 65 | + } |
| 66 | + ); |
| 67 | + |
| 68 | + // No ephemeral record, use fallback |
| 69 | + return this.options.fallbackResponder.streamResponse( |
| 70 | + request, |
| 71 | + runId, |
| 72 | + streamId, |
| 73 | + environment, |
| 74 | + signal |
| 75 | + ); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + record.lastAccessed = Date.now(); |
| 80 | + |
| 81 | + logger.debug("[RelayRealtimeStreams][streamResponse] Streaming from ephemeral record", { |
| 82 | + streamId, |
| 83 | + runId, |
| 84 | + }); |
| 85 | + |
| 86 | + // Create a streaming response from the buffered data |
| 87 | + const stream = record.stream |
| 88 | + .pipeThrough(new TextDecoderStream()) |
| 89 | + .pipeThrough(new LineTransformStream()) |
| 90 | + .pipeThrough( |
| 91 | + new TransformStream({ |
| 92 | + transform(chunk, controller) { |
| 93 | + for (const line of chunk) { |
| 94 | + controller.enqueue(`data: ${line}\n\n`); |
| 95 | + } |
| 96 | + }, |
| 97 | + }) |
| 98 | + ) |
| 99 | + .pipeThrough(new TextEncoderStream()); |
| 100 | + |
| 101 | + // Once we start streaming, consider deleting the buffer when done. |
| 102 | + // For a simple approach, we can rely on finalized and no more reads. |
| 103 | + // Or we can let TTL cleanup handle it if multiple readers might come in. |
| 104 | + return new Response(stream, { |
| 105 | + headers: { |
| 106 | + "Content-Type": "text/event-stream", |
| 107 | + "Cache-Control": "no-cache", |
| 108 | + Connection: "keep-alive", |
| 109 | + }, |
| 110 | + }); |
| 111 | + } |
| 112 | + |
| 113 | + async ingestData( |
| 114 | + stream: ReadableStream<Uint8Array>, |
| 115 | + runId: string, |
| 116 | + streamId: string |
| 117 | + ): Promise<Response> { |
| 118 | + const [localStream, fallbackStream] = stream.tee(); |
| 119 | + |
| 120 | + logger.debug("[RelayRealtimeStreams][ingestData] Ingesting data", { runId, streamId }); |
| 121 | + |
| 122 | + // Handle local buffering asynchronously and catch errors |
| 123 | + this.handleLocalIngestion(localStream, runId, streamId).catch((err) => { |
| 124 | + logger.error("[RelayRealtimeStreams][ingestData] Error in local ingestion:", { err }); |
| 125 | + }); |
| 126 | + |
| 127 | + // Forward to the fallback ingestor asynchronously and catch errors |
| 128 | + return this.options.fallbackIngestor.ingestData(fallbackStream, runId, streamId); |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Handles local buffering of the stream data. |
| 133 | + * @param stream The readable stream to buffer. |
| 134 | + * @param streamId The unique identifier for the stream. |
| 135 | + */ |
| 136 | + private async handleLocalIngestion( |
| 137 | + stream: ReadableStream<Uint8Array>, |
| 138 | + runId: string, |
| 139 | + streamId: string |
| 140 | + ) { |
| 141 | + this.createOrUpdateRelayedStream(`${runId}:${streamId}`, stream); |
| 142 | + } |
| 143 | + |
| 144 | + /** |
| 145 | + * Retrieves an existing buffer or creates a new one for the given streamId. |
| 146 | + * @param streamId The unique identifier for the stream. |
| 147 | + */ |
| 148 | + private createOrUpdateRelayedStream( |
| 149 | + bufferKey: string, |
| 150 | + stream: ReadableStream<Uint8Array> |
| 151 | + ): RelayedStreamRecord { |
| 152 | + let record = this._buffers.get(bufferKey); |
| 153 | + if (!record) { |
| 154 | + record = { |
| 155 | + stream, |
| 156 | + createdAt: Date.now(), |
| 157 | + lastAccessed: Date.now(), |
| 158 | + finalized: false, |
| 159 | + }; |
| 160 | + this._buffers.set(bufferKey, record); |
| 161 | + } else { |
| 162 | + record.lastAccessed = Date.now(); |
| 163 | + } |
| 164 | + return record; |
| 165 | + } |
| 166 | + |
| 167 | + private cleanup() { |
| 168 | + const now = Date.now(); |
| 169 | + for (const [key, record] of this._buffers.entries()) { |
| 170 | + // If last accessed is older than ttl, clean up |
| 171 | + if (now - record.lastAccessed > this.options.ttl) { |
| 172 | + this.deleteBuffer(key); |
| 173 | + } |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + private deleteBuffer(bufferKey: string) { |
| 178 | + this._buffers.delete(bufferKey); |
| 179 | + } |
| 180 | + |
| 181 | + /** |
| 182 | + * Waits for a buffer to be created within a specified timeout. |
| 183 | + * @param streamId The unique identifier for the stream. |
| 184 | + * @returns A promise that resolves to true if the buffer was created, false otherwise. |
| 185 | + */ |
| 186 | + private async waitForBuffer(bufferKey: string): Promise<RelayedStreamRecord | undefined> { |
| 187 | + const timeout = this.waitForBufferTimeout; |
| 188 | + const interval = this.waitForBufferInterval; |
| 189 | + const maxAttempts = Math.ceil(timeout / interval); |
| 190 | + let attempts = 0; |
| 191 | + |
| 192 | + return new Promise<RelayedStreamRecord | undefined>((resolve) => { |
| 193 | + const checkBuffer = () => { |
| 194 | + attempts++; |
| 195 | + if (this._buffers.has(bufferKey)) { |
| 196 | + resolve(this._buffers.get(bufferKey)); |
| 197 | + return; |
| 198 | + } |
| 199 | + if (attempts >= maxAttempts) { |
| 200 | + resolve(undefined); |
| 201 | + return; |
| 202 | + } |
| 203 | + setTimeout(checkBuffer, interval); |
| 204 | + }; |
| 205 | + checkBuffer(); |
| 206 | + }); |
| 207 | + } |
| 208 | + |
| 209 | + // Don't forget to clear interval on shutdown if needed |
| 210 | + close() { |
| 211 | + clearInterval(this.cleanupInterval); |
| 212 | + } |
| 213 | +} |
| 214 | + |
| 215 | +function initializeRelayRealtimeStreams() { |
| 216 | + return new RelayRealtimeStreams({ |
| 217 | + ttl: 1000 * 60 * 5, // 5 minutes |
| 218 | + fallbackIngestor: v1RealtimeStreams, |
| 219 | + fallbackResponder: v1RealtimeStreams, |
| 220 | + }); |
| 221 | +} |
| 222 | + |
| 223 | +export const relayRealtimeStreams = singleton( |
| 224 | + "relayRealtimeStreams", |
| 225 | + initializeRelayRealtimeStreams |
| 226 | +); |
0 commit comments