Skip to content

Commit 209816b

Browse files
committed
refactor(cli): use AbortController for HTTP timeout handling
Replace req.destroy() timeout handling with AbortController pattern for cleaner resource cleanup. This ensures proper cleanup of buffered response data on timeout and follows modern Node.js best practices. Changes: - Create AbortController with signal passed to request options - Use setTimeout to trigger abort after timeout period - Clear timeout on successful completion or error - Handle AbortError in error handler for timeout messages
1 parent c349c92 commit 209816b

1 file changed

Lines changed: 15 additions & 7 deletions

File tree

cli/lib/checkup-api.ts

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -157,18 +157,23 @@ async function postRpc<T>(params: {
157157
"Content-Length": Buffer.byteLength(body).toString(),
158158
};
159159

160+
// Use AbortController for clean timeout handling
161+
const controller = new AbortController();
162+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
163+
160164
return new Promise((resolve, reject) => {
161165
const req = https.request(
162166
url,
163167
{
164168
method: "POST",
165169
headers,
166-
timeout: timeoutMs,
170+
signal: controller.signal,
167171
},
168172
(res) => {
169173
let data = "";
170174
res.on("data", (chunk) => (data += chunk));
171175
res.on("end", () => {
176+
clearTimeout(timeoutId);
172177
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
173178
try {
174179
const parsed = JSON.parse(data);
@@ -189,16 +194,19 @@ async function postRpc<T>(params: {
189194
reject(new RpcError({ rpcName, statusCode, payloadText: data, payloadJson }));
190195
}
191196
});
197+
res.on("error", () => {
198+
clearTimeout(timeoutId);
199+
});
192200
}
193201
);
194202

195-
// Handle timeout event
196-
req.on("timeout", () => {
197-
req.destroy();
198-
reject(new Error(`RPC ${rpcName} timed out after ${timeoutMs}ms`));
199-
});
200-
201203
req.on("error", (err: Error) => {
204+
clearTimeout(timeoutId);
205+
// Handle abort as timeout
206+
if (err.name === "AbortError" || (err as any).code === "ABORT_ERR") {
207+
reject(new Error(`RPC ${rpcName} timed out after ${timeoutMs}ms`));
208+
return;
209+
}
202210
// Provide clearer error for common network issues
203211
if ((err as any).code === "ECONNREFUSED") {
204212
reject(new Error(`RPC ${rpcName} failed: connection refused to ${url.host}`));

0 commit comments

Comments
 (0)