Repository navigation
Expand file tree
/
Copy pathstream-failover-runtime.ts
More file actions
170 lines (164 loc) · 4.45 KB
/
Copy pathstream-failover-runtime.ts
File metadata and controls
170 lines (164 loc) · 4.45 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
import type { ServerResponse } from "node:http";
import type { RuntimeRotationProxyStatus } from "../runtime/rotation-server-types.js";
export const HOP_BY_HOP_HEADERS = new Set([
"connection",
"content-length",
"expect",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
]);
const PRIVATE_CLIENT_RESPONSE_HEADERS = new Set([
"x-codex-multi-auth-account-index",
"x-codex-multi-auth-account-label",
"x-codex-multi-auth-account-email",
"x-codex-multi-auth-account-id",
]);
const DECODED_UPSTREAM_RESPONSE_HEADERS = new Set([
// Node fetch returns decoded bytes while preserving the upstream encoding header.
"content-encoding",
]);
export function responseHeadersForClient(upstreamHeaders: Headers): Record<string, string> {
const headers: Record<string, string> = {};
for (const [key, value] of upstreamHeaders.entries()) {
const normalizedKey = key.toLowerCase();
if (HOP_BY_HOP_HEADERS.has(normalizedKey)) continue;
if (PRIVATE_CLIENT_RESPONSE_HEADERS.has(normalizedKey)) continue;
if (DECODED_UPSTREAM_RESPONSE_HEADERS.has(normalizedKey)) continue;
headers[key] = value;
}
return headers;
}
export async function withTimeout<T>(
promise: Promise<T>,
timeoutMs: number,
onTimeout: () => void,
message: string,
): Promise<T> {
let timeout: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise,
new Promise<T>((_resolve, reject) => {
timeout = setTimeout(() => {
onTimeout();
reject(new Error(message));
}, Math.max(1, timeoutMs));
}),
]);
} finally {
if (timeout) clearTimeout(timeout);
}
}
export async function readErrorBody(
response: Response,
timeoutMs: number,
maxBytes = 1024 * 1024,
): Promise<string> {
// The outbound fetch's abort timer is cleared once headers arrive, so a
// stalled error body would otherwise hang this handler forever (the success
// path is per-chunk stall-bounded; the error path was not). Read the body via
// a reader, bound it by an idle timeout AND a size cap, and cancel the stream
// on timeout/overflow so the socket is released.
const body = response.body;
if (!body || typeof body.getReader !== "function") {
// Fallback for impls without a streamable body: race text() against a timer.
try {
return await withTimeout(
response.text(),
timeoutMs,
() => undefined,
"error body stalled",
);
} catch {
return "";
}
}
const reader = body.getReader();
const chunks: Uint8Array[] = [];
let total = 0;
try {
for (;;) {
let idleTimer: ReturnType<typeof setTimeout> | undefined;
const idle = new Promise<never>((_resolve, reject) => {
idleTimer = setTimeout(
() => reject(new Error("error body stalled")),
Math.max(1, timeoutMs),
);
});
let result: Awaited<ReturnType<typeof reader.read>>;
try {
result = await Promise.race([reader.read(), idle]);
} finally {
if (idleTimer) clearTimeout(idleTimer);
}
if (result.done) break;
if (result.value) {
total += result.value.byteLength;
if (total > maxBytes) break; // cap: enough for diagnostics, no OOM
chunks.push(result.value);
}
}
} catch {
// stalled or errored — fall through with whatever we have
} finally {
await reader.cancel().catch(() => undefined);
}
try {
return Buffer.concat(chunks).toString("utf8");
} catch {
return "";
}
}
export async function forwardStreamingResponse(
upstream: Response,
res: ServerResponse,
status: RuntimeRotationProxyStatus,
onStreamError: () => void,
streamStallTimeoutMs: number,
): Promise<boolean> {
status.streamsStarted += 1;
res.writeHead(
upstream.status,
responseHeadersForClient(upstream.headers),
);
if (!upstream.body) {
res.end();
return true;
}
const reader = upstream.body.getReader();
res.on("close", () => {
if (!res.writableEnded) {
void reader.cancel().catch(() => undefined);
}
});
try {
while (true) {
const { done, value } = await withTimeout(
reader.read(),
streamStallTimeoutMs,
() => {
void reader.cancel().catch(() => undefined);
},
`upstream stream stalled after ${streamStallTimeoutMs}ms`,
);
if (done) break;
if (value && value.byteLength > 0) {
res.write(Buffer.from(value));
}
}
res.end();
return true;
} catch (error) {
status.lastError = error instanceof Error ? error.message : String(error);
onStreamError();
if (!res.destroyed) {
res.destroy(error instanceof Error ? error : undefined);
}
return false;
}
}