|
| 1 | +import Redis, { RedisOptions } from "ioredis"; |
| 2 | +import { logger } from "./logger.server"; |
| 3 | + |
| 4 | +export type RealtimeStreamsOptions = { |
| 5 | + redis: RedisOptions | undefined; |
| 6 | +}; |
| 7 | + |
| 8 | +export class RealtimeStreams { |
| 9 | + constructor(private options: RealtimeStreamsOptions) {} |
| 10 | + |
| 11 | + async streamResponse(runId: string, streamId: string, signal: AbortSignal): Promise<Response> { |
| 12 | + const redis = new Redis(this.options.redis ?? {}); |
| 13 | + const streamKey = `stream:${runId}:${streamId}`; |
| 14 | + |
| 15 | + const stream = new TransformStream({ |
| 16 | + transform(chunk: string, controller) { |
| 17 | + try { |
| 18 | + const data = JSON.parse(chunk); |
| 19 | + |
| 20 | + if (typeof data === "object" && data !== null && "__end" in data && data.__end === true) { |
| 21 | + controller.terminate(); |
| 22 | + return; |
| 23 | + } |
| 24 | + controller.enqueue(`data: ${chunk}\n\n`); |
| 25 | + } catch (error) { |
| 26 | + console.error("Invalid JSON in stream:", error); |
| 27 | + } |
| 28 | + }, |
| 29 | + }); |
| 30 | + |
| 31 | + const response = new Response(stream.readable, { |
| 32 | + headers: { |
| 33 | + "Content-Type": "text/event-stream", |
| 34 | + "Cache-Control": "no-cache", |
| 35 | + Connection: "keep-alive", |
| 36 | + }, |
| 37 | + }); |
| 38 | + |
| 39 | + let isCleanedUp = false; |
| 40 | + |
| 41 | + async function cleanup() { |
| 42 | + if (isCleanedUp) return; |
| 43 | + isCleanedUp = true; |
| 44 | + await redis.quit(); |
| 45 | + const writer = stream.writable.getWriter(); |
| 46 | + if (writer) await writer.close().catch(() => {}); // Ensure close doesn't error if already closed |
| 47 | + } |
| 48 | + |
| 49 | + signal.addEventListener("abort", cleanup); |
| 50 | + |
| 51 | + (async () => { |
| 52 | + let lastId = "0"; |
| 53 | + let retryCount = 0; |
| 54 | + const maxRetries = 3; |
| 55 | + |
| 56 | + try { |
| 57 | + while (!signal.aborted) { |
| 58 | + try { |
| 59 | + const messages = await redis.xread( |
| 60 | + "COUNT", |
| 61 | + 100, |
| 62 | + "BLOCK", |
| 63 | + 5000, |
| 64 | + "STREAMS", |
| 65 | + streamKey, |
| 66 | + lastId |
| 67 | + ); |
| 68 | + |
| 69 | + retryCount = 0; |
| 70 | + |
| 71 | + if (messages && messages.length > 0) { |
| 72 | + const [_key, entries] = messages[0]; |
| 73 | + |
| 74 | + for (const [id, fields] of entries) { |
| 75 | + lastId = id; |
| 76 | + |
| 77 | + if (fields && fields.length >= 2 && !stream.writable.locked) { |
| 78 | + const writer = stream.writable.getWriter(); |
| 79 | + try { |
| 80 | + await writer.write(fields[1]); |
| 81 | + } finally { |
| 82 | + writer.releaseLock(); |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + } catch (error) { |
| 88 | + console.error("Error reading from Redis stream:", error); |
| 89 | + retryCount++; |
| 90 | + if (retryCount >= maxRetries) throw error; |
| 91 | + await new Promise((resolve) => setTimeout(resolve, 1000 * retryCount)); |
| 92 | + } |
| 93 | + } |
| 94 | + } catch (error) { |
| 95 | + console.error("Fatal error in stream processing:", error); |
| 96 | + } finally { |
| 97 | + await cleanup(); |
| 98 | + } |
| 99 | + })(); |
| 100 | + |
| 101 | + return response; |
| 102 | + } |
| 103 | + |
| 104 | + async ingestData( |
| 105 | + stream: ReadableStream<Uint8Array>, |
| 106 | + runId: string, |
| 107 | + streamId: string |
| 108 | + ): Promise<Response> { |
| 109 | + const redis = new Redis(this.options.redis ?? {}); |
| 110 | + |
| 111 | + const streamKey = `stream:${runId}:${streamId}`; |
| 112 | + |
| 113 | + async function cleanup(stream?: TransformStream) { |
| 114 | + try { |
| 115 | + await redis.quit(); |
| 116 | + if (stream) { |
| 117 | + const writer = stream.writable.getWriter(); |
| 118 | + await writer.close(); // Catch in case the stream is already closed |
| 119 | + } |
| 120 | + } catch (error) { |
| 121 | + logger.error("[RealtimeStreams][ingestData] Error in cleanup:", { error }); |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + try { |
| 126 | + const reader = stream.getReader(); |
| 127 | + const decoder = new TextDecoder(); |
| 128 | + let buffer = ""; |
| 129 | + |
| 130 | + while (true) { |
| 131 | + const { done, value } = await reader.read(); |
| 132 | + |
| 133 | + logger.debug("[RealtimeStreams][ingestData] Reading data", { streamKey, done }); |
| 134 | + |
| 135 | + if (done) { |
| 136 | + if (buffer) { |
| 137 | + const data = JSON.parse(buffer); |
| 138 | + await redis.xadd(streamKey, "*", "data", JSON.stringify(data)); |
| 139 | + } |
| 140 | + break; |
| 141 | + } |
| 142 | + |
| 143 | + buffer += decoder.decode(value, { stream: true }); |
| 144 | + const lines = buffer.split("\n"); |
| 145 | + buffer = lines.pop() || ""; |
| 146 | + |
| 147 | + for (const line of lines) { |
| 148 | + if (line.trim()) { |
| 149 | + const data = JSON.parse(line); |
| 150 | + |
| 151 | + logger.debug("[RealtimeStreams][ingestData] Ingesting data", { streamKey }); |
| 152 | + |
| 153 | + await redis.xadd(streamKey, "*", "data", JSON.stringify(data)); |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + await redis.xadd(streamKey, "*", "data", JSON.stringify({ __end: true })); |
| 159 | + return new Response(null, { status: 200 }); |
| 160 | + } catch (error) { |
| 161 | + console.error("Error in ingestData:", error); |
| 162 | + return new Response(null, { status: 500 }); |
| 163 | + } finally { |
| 164 | + await cleanup(); |
| 165 | + } |
| 166 | + } |
| 167 | +} |
0 commit comments