-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathfetch-timeout.ts
More file actions
202 lines (192 loc) · 6.03 KB
/
Copy pathfetch-timeout.ts
File metadata and controls
202 lines (192 loc) · 6.03 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Fetch timeout helpers wrap fetch calls with timeout and abort behavior.
import { redactSensitiveUrlLikeString } from "@openclaw/net-policy/redact-sensitive-url";
import { createSubsystemLogger } from "../logging/subsystem.js";
import { resolveSafeTimeoutDelayMs } from "./timer-delay.js";
const log = createSubsystemLogger("fetch-timeout");
const LOG_URL_MAX_CHARS = 500;
const URL_SECRET_SUFFIX_PATTERN = /[?#]/;
type TimeoutAbortSignalParams = {
timeoutMs?: number;
signal?: AbortSignal;
operation?: string;
url?: string;
};
/**
* Relay abort without forwarding the Event argument as the abort reason.
* Using .bind() avoids closure scope capture (memory leak prevention).
*/
function relayAbort(this: AbortController) {
this.abort();
}
/** Returns a bound abort relay for use as an event listener. */
export function bindAbortRelay(controller: AbortController): () => void {
return relayAbort.bind(controller);
}
function sanitizeTimeoutLogUrl(rawUrl: string | undefined): string | undefined {
const trimmed = rawUrl?.trim();
if (!trimmed) {
return undefined;
}
try {
// Strip credentials, query, and fragment before logging; timeout URLs often
// include provider tokens or signed request parameters.
const parsed = new URL(trimmed);
parsed.username = "";
parsed.password = "";
parsed.search = "";
parsed.hash = "";
const value = redactSensitiveUrlLikeString(parsed.toString());
return value.length > LOG_URL_MAX_CHARS ? `${value.slice(0, LOG_URL_MAX_CHARS)}...` : value;
} catch {
const withoutQueryOrHash = trimmed.split(URL_SECRET_SUFFIX_PATTERN, 1)[0] ?? "";
const cleaned = redactSensitiveUrlLikeString(
withoutQueryOrHash
.replace(/[\r\n\u2028\u2029]+/g, " ")
.replace(/\p{Cc}+/gu, " ")
.replace(/\s+/g, " ")
.trim(),
);
if (!cleaned) {
return undefined;
}
return cleaned.length > LOG_URL_MAX_CHARS
? `${cleaned.slice(0, LOG_URL_MAX_CHARS)}...`
: cleaned;
}
}
function abortDueToTimeout(
controller: AbortController,
timeoutMs: number,
startedAtMs: number,
operation?: string,
url?: string,
) {
if (controller.signal.aborted) {
return;
}
const sanitizedUrl = sanitizeTimeoutLogUrl(url);
const elapsedMs = Math.max(0, Date.now() - startedAtMs);
const delayMs = Math.max(0, elapsedMs - timeoutMs);
// A large elapsed/timeout gap means the timer callback itself was starved,
// which is more useful for operators than another plain timeout message.
const eventLoopDelayHint =
delayMs >= Math.max(1000, timeoutMs * 0.5)
? `timer delayed ${delayMs}ms, likely event-loop starvation`
: null;
const consoleMessage = [
`fetch timeout after ${timeoutMs}ms`,
`(elapsed ${elapsedMs}ms)`,
eventLoopDelayHint,
operation ? `operation=${operation}` : null,
sanitizedUrl ? `url=${sanitizedUrl}` : null,
]
.filter((part): part is string => Boolean(part))
.join(" ");
log.warn("fetch timeout reached; aborting operation", {
timeoutMs,
elapsedMs,
...(eventLoopDelayHint ? { timerDelayMs: delayMs, eventLoopDelayHint } : {}),
consoleMessage,
...(operation ? { operation } : {}),
...(sanitizedUrl ? { url: sanitizedUrl } : {}),
});
const error = new Error("request timed out");
error.name = "TimeoutError";
controller.abort(error);
}
/**
* Builds an abort signal that combines an optional parent signal with a timeout.
* Callers must run `cleanup`; `refresh` restarts only the internal timeout timer.
*/
export function buildTimeoutAbortSignal(params: TimeoutAbortSignalParams): {
signal?: AbortSignal;
cleanup: () => void;
refresh: () => void;
} {
const { timeoutMs, signal } = params;
if (!timeoutMs && !signal) {
return { signal: undefined, cleanup: () => {}, refresh: () => {} };
}
if (!timeoutMs) {
return { signal, cleanup: () => {}, refresh: () => {} };
}
const controller = new AbortController();
const normalizedTimeoutMs = resolveSafeTimeoutDelayMs(timeoutMs);
let active = true;
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const scheduleTimeout = () => {
timeoutId = setTimeout(
abortDueToTimeout,
normalizedTimeoutMs,
controller,
normalizedTimeoutMs,
Date.now(),
params.operation,
params.url,
);
};
scheduleTimeout();
const onAbort = bindAbortRelay(controller);
if (signal) {
if (signal.aborted) {
controller.abort();
} else {
signal.addEventListener("abort", onAbort, { once: true });
}
}
return {
signal: controller.signal,
refresh: () => {
if (!active || controller.signal.aborted) {
return;
}
if (timeoutId) {
clearTimeout(timeoutId);
}
scheduleTimeout();
},
cleanup: () => {
active = false;
if (timeoutId) {
clearTimeout(timeoutId);
}
if (signal) {
signal.removeEventListener("abort", onAbort);
}
},
};
}
/**
* Fetch wrapper that adds timeout support via AbortController.
*
* @param url - The URL to fetch
* @param init - RequestInit options (headers, method, body, etc.)
* @param timeoutMs - Timeout in milliseconds
* @param fetchFn - The fetch implementation to use (defaults to global fetch)
* @returns The fetch Response
* @throws AbortError if the request times out
*/
export async function fetchWithTimeout(
url: string,
init: RequestInit,
timeoutMs: number,
fetchFn: typeof fetch = fetch,
): Promise<Response> {
const { signal: timeoutSignal, cleanup } = buildTimeoutAbortSignal({
timeoutMs: Math.max(1, timeoutMs),
operation: "fetchWithTimeout",
url,
});
const callerSignal = init.signal ?? undefined;
// The wrapper timeout ends once fetch returns headers, but the response body
// must keep following caller cancellation (and its reason) after that point.
const signal =
callerSignal && timeoutSignal
? AbortSignal.any([callerSignal, timeoutSignal])
: (callerSignal ?? timeoutSignal);
try {
return await fetchFn(url, { ...init, signal });
} finally {
cleanup();
}
}