-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathmetadataStream.ts
More file actions
185 lines (156 loc) · 4.79 KB
/
metadataStream.ts
File metadata and controls
185 lines (156 loc) · 4.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import { request as httpsRequest } from "node:https";
import { request as httpRequest } from "node:http";
import { URL } from "node:url";
export type MetadataOptions<T> = {
baseUrl: string;
runId: string;
key: string;
source: AsyncIterable<T>;
headers?: Record<string, string>;
signal?: AbortSignal;
version?: "v1" | "v2";
target?: "self" | "parent" | "root";
maxRetries?: number;
};
export class MetadataStream<T> {
private controller = new AbortController();
private serverStream: ReadableStream<T>;
private consumerStream: ReadableStream<T>;
private streamPromise: Promise<void>;
private retryCount = 0;
private readonly maxRetries: number;
private currentChunkIndex = 0;
constructor(private options: MetadataOptions<T>) {
const [serverStream, consumerStream] = this.createTeeStreams();
this.serverStream = serverStream;
this.consumerStream = consumerStream;
this.maxRetries = options.maxRetries ?? 10;
this.streamPromise = this.initializeServerStream();
}
private createTeeStreams() {
const readableSource = new ReadableStream<T>({
start: async (controller) => {
try {
for await (const value of this.options.source) {
controller.enqueue(value);
}
controller.close();
} catch (error) {
controller.error(error);
}
},
});
return readableSource.tee();
}
private async makeRequest(startFromChunk: number = 0): Promise<void> {
const reader = this.serverStream.getReader();
return new Promise((resolve, reject) => {
const url = new URL(this.buildUrl());
const timeout = 15 * 60 * 1000; // 15 minutes
const requestFn = url.protocol === "https:" ? httpsRequest : httpRequest;
const req = requestFn({
method: "POST",
hostname: url.hostname,
port: url.port || (url.protocol === "https:" ? 443 : 80),
path: url.pathname + url.search,
headers: {
...this.options.headers,
"Content-Type": "application/json",
"X-Resume-From-Chunk": startFromChunk.toString(),
},
timeout,
});
req.on("error", (error) => {
safeReleaseLock(reader);
reject(error);
});
req.on("timeout", () => {
safeReleaseLock(reader);
req.destroy(new Error("Request timed out"));
});
req.on("response", (res) => {
if (res.statusCode === 408) {
safeReleaseLock(reader);
if (this.retryCount < this.maxRetries) {
this.retryCount++;
resolve(this.makeRequest(this.currentChunkIndex));
return;
}
reject(new Error(`Max retries (${this.maxRetries}) exceeded after timeout`));
return;
}
if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
const error = new Error(`HTTP error! status: ${res.statusCode}`);
reject(error);
return;
}
res.on("end", () => {
resolve();
});
res.resume();
});
if (this.options.signal) {
this.options.signal.addEventListener("abort", () => {
req.destroy(new Error("Request aborted"));
});
}
const processStream = async () => {
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
req.end();
break;
}
const stringified = JSON.stringify(value) + "\n";
req.write(stringified);
this.currentChunkIndex++;
}
} catch (error) {
reject(error);
}
};
processStream().catch((error) => {
reject(error);
});
});
}
private async initializeServerStream(): Promise<void> {
await this.makeRequest(0);
}
public async wait(): Promise<void> {
return this.streamPromise;
}
public [Symbol.asyncIterator]() {
return streamToAsyncIterator(this.consumerStream);
}
private buildUrl(): string {
switch (this.options.version ?? "v1") {
case "v1": {
return `${this.options.baseUrl}/realtime/v1/streams/${this.options.runId}/${
this.options.target ?? "self"
}/${this.options.key}`;
}
case "v2": {
return `${this.options.baseUrl}/realtime/v2/streams/${this.options.runId}/${this.options.key}`;
}
}
}
}
async function* streamToAsyncIterator<T>(stream: ReadableStream<T>): AsyncIterableIterator<T> {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) return;
yield value;
}
} finally {
safeReleaseLock(reader);
}
}
function safeReleaseLock(reader: ReadableStreamDefaultReader<any>) {
try {
reader.releaseLock();
} catch (error) {}
}