The best way to control Claude Code, Codex and more from any computer or phone

main
ts 273 lines 10.6 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off -- Fake Electron net request and response emitters.
2 import * as NodeCrypto from "node:crypto";
3 import * as NodeEvents from "node:events";
4 import * as NodeFS from "node:fs";
5 import * as NodeModule from "node:module";
6 import * as NodeOS from "node:os";
7 import * as NodePath from "node:path";
8 import * as NodeStream from "node:stream";
9 import { ElectronHttpExecutor } from "electron-updater/out/electronHttpExecutor.js";
10 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
11
12 type DownloadOptions = Parameters<ElectronHttpExecutor["download"]>[2];
13 type FakeRequest = NodeEvents.EventEmitter & { abort: () => void };
14
15 // electron-updater is CommonJS, so a spy goes on the module object its require() returns.
16 const fsModule = NodeModule.createRequire(import.meta.url)("node:fs") as typeof NodeFS;
17 const openForReading = fsModule.createReadStream;
18 // electron-updater's own dependency, which apps/desktop does not declare.
19 const { CancellationToken, CancellationError } = NodeModule.createRequire(
20 NodeModule.createRequire(import.meta.url).resolve("electron-updater"),
21 )("builder-util-runtime") as {
22 CancellationToken: new () => DownloadOptions["cancellationToken"];
23 CancellationError: new () => Error;
24 };
25 const RELEASE = "hello world";
26 // Larger than a file stream's buffer, so its "drain" marks a write of it as committed to disk.
27 const PREFIX = "a".repeat(1 << 20);
28 const LARGE_RELEASE = `${PREFIX}world`;
29 const RESUMED_RANGE = `bytes ${PREFIX.length}-${LARGE_RELEASE.length - 1}/${LARGE_RELEASE.length}`;
30
31 function startRequest() {
32 const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn() });
33 const response = new NodeEvents.EventEmitter();
34 const reject = vi.fn();
35 new ElectronHttpExecutor().addErrorAndTimeoutHandlers(request, reject);
36 // Electron's net.ClientRequest emits these as soon as the request body is sent, before any response.
37 request.emit("finish");
38 request.emit("close");
39 return { request, response, reject };
40 }
41
42 // The temp update file already holds `onDisk`, as the differential downloader's output can.
43 function startDownload(onDisk: string, release = RELEASE) {
44 const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "electron-http-executor-"));
45 const destination = NodePath.join(dir, "update.AppImage");
46 NodeFS.writeFileSync(destination, onDisk);
47 const createWriteStream = vi.spyOn(fsModule, "createWriteStream");
48 const createReadStream = vi.spyOn(fsModule, "createReadStream");
49 const created = new NodeEvents.EventEmitter();
50 let requestCount = 0;
51 const executor = new ElectronHttpExecutor();
52 executor.createRequest = (options: { headers: Record<string, string> }, callback) => {
53 const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn(), end: vi.fn() });
54 request.on("response", callback);
55 requestCount++;
56 created.emit("request", { request, headers: options.headers });
57 return request as unknown as Electron.ClientRequest;
58 };
59 const cancellationToken = new CancellationToken();
60 const first = NodeEvents.EventEmitter.once(created, "request");
61 const result = executor.download(new URL("https://example.com/update.AppImage"), destination, {
62 cancellationToken,
63 sha512: NodeCrypto.createHash("sha512").update(release).digest("base64"),
64 });
65 // A download that settles instead of sending another request fails the wait with its error.
66 const settled = result.then(() => {
67 throw new Error("The download finished without another request");
68 });
69 settled.catch(() => {});
70 const nextRequest = async () => {
71 const [request] = await Promise.race([
72 NodeEvents.EventEmitter.once(created, "request"),
73 settled,
74 ]);
75 return request as { request: FakeRequest; headers: Record<string, string> };
76 };
77 // The first request answers 200 and writes `body` to the file, then stalls before the end.
78 const stallAfterWriting = async (body: string) => {
79 const [{ request }] = await first;
80 const response = startResponse(request, 200, { "content-length": String(release.length) });
81 const fileOut = createWriteStream.mock.results[0]!.value as NodeFS.WriteStream;
82 const committed = NodeEvents.EventEmitter.once(fileOut, "drain");
83 response.write(body);
84 await committed;
85 const closed = NodeEvents.EventEmitter.once(fileOut, "close");
86 const retry = nextRequest();
87 await vi.advanceTimersByTimeAsync(60_000);
88 await closed;
89 await vi.advanceTimersByTimeAsync(2_000);
90 return retry;
91 };
92 return {
93 destination,
94 first,
95 nextRequest,
96 stallAfterWriting,
97 result,
98 cancel: () => cancellationToken.cancel(),
99 // Resolves once the file is open for its digest check, before any of it is read.
100 readOpened: () =>
101 new Promise<void>((resolve) => {
102 createReadStream.mockImplementationOnce((...args) => {
103 const stream = openForReading(...args);
104 stream.once("open", () => resolve());
105 return stream;
106 });
107 }),
108 requestCount: () => requestCount,
109 read: () => NodeFS.readFileSync(destination, "utf8"),
110 [Symbol.dispose]: () => {
111 createWriteStream.mockRestore();
112 createReadStream.mockRestore();
113 NodeFS.rmSync(dir, { recursive: true, force: true });
114 },
115 };
116 }
117
118 function startResponse(request: FakeRequest, statusCode: number, headers: Record<string, string>) {
119 const response = Object.assign(new NodeStream.PassThrough(), {
120 statusCode,
121 statusMessage: "",
122 headers,
123 });
124 request.emit("response", response);
125 return response;
126 }
127
128 function respond(
129 request: FakeRequest,
130 statusCode: number,
131 headers: Record<string, string>,
132 body: string,
133 ) {
134 startResponse(request, statusCode, { "content-length": String(body.length), ...headers }).end(
135 body,
136 );
137 }
138
139 describe("ElectronHttpExecutor idle timeout", () => {
140 beforeEach(() => {
141 vi.useFakeTimers();
142 });
143 afterEach(() => {
144 vi.useRealTimers();
145 });
146
147 it("aborts a request that receives no response for 60 seconds", () => {
148 const { request, reject } = startRequest();
149
150 vi.advanceTimersByTime(59_999);
151 expect(reject).not.toHaveBeenCalled();
152 vi.advanceTimersByTime(1);
153
154 expect(request.abort).toHaveBeenCalledOnce();
155 expect(reject).toHaveBeenCalledWith(new Error("Request timed out"));
156 });
157
158 it("keeps a slow download alive while data keeps arriving", () => {
159 const { request, response, reject } = startRequest();
160 request.emit("response", response);
161
162 for (let elapsed = 0; elapsed < 180_000; elapsed += 30_000) {
163 vi.advanceTimersByTime(30_000);
164 response.emit("data", Buffer.alloc(1));
165 }
166
167 expect(request.abort).not.toHaveBeenCalled();
168 expect(reject).not.toHaveBeenCalled();
169 });
170
171 it("stops the timer once the response ends", () => {
172 const { request, response, reject } = startRequest();
173 request.emit("response", response);
174
175 response.emit("end");
176 vi.advanceTimersByTime(600_000);
177
178 expect(request.abort).not.toHaveBeenCalled();
179 expect(reject).not.toHaveBeenCalled();
180 });
181
182 it.each([
183 {
184 name: "resumes a stalled download from the bytes already written",
185 written: PREFIX,
186 retry: { status: 206, headers: { "content-range": RESUMED_RANGE }, body: "world" },
187 },
188 {
189 name: "accepts a file that already holds every byte when the retry is past the end",
190 written: LARGE_RELEASE,
191 retry: {
192 status: 416,
193 headers: { "content-range": `bytes */${LARGE_RELEASE.length}` },
194 body: "",
195 },
196 },
197 {
198 name: "starts over when the server ignores the range",
199 written: PREFIX,
200 retry: { status: 200, headers: {}, body: LARGE_RELEASE },
201 },
202 ])("$name", async ({ written, retry: { status, headers, body } }) => {
203 using download = startDownload("", LARGE_RELEASE);
204
205 const { request: unanswered, headers: first } = await download.stallAfterWriting(written);
206 expect(first.Range).toBe(`bytes=${written.length}-`);
207 // A retry that fails before any response still resumes after the bytes the first one wrote.
208 const retry = download.nextRequest();
209 unanswered.emit("error", new Error("net::ERR_TIMED_OUT"));
210 await vi.advanceTimersByTimeAsync(4_000);
211 const { request, headers: second } = await retry;
212 expect(second.Range).toBe(`bytes=${written.length}-`);
213 respond(request, status, headers, body);
214
215 await expect(download.result).resolves.toBe(download.destination);
216 expect(download.read()).toBe(LARGE_RELEASE);
217 });
218
219 it("fails a file past the end of the release when the caller cancels its digest check", async () => {
220 using download = startDownload("", LARGE_RELEASE);
221
222 const { request } = await download.stallAfterWriting(LARGE_RELEASE);
223 const opened = download.readOpened();
224 respond(request, 416, { "content-range": `bytes */${LARGE_RELEASE.length}` }, "");
225 await opened;
226 download.cancel();
227
228 await expect(download.result).rejects.toBeInstanceOf(CancellationError);
229 });
230
231 it("fails a file past the end of the release whose bytes do not match it", async () => {
232 using download = startDownload("", LARGE_RELEASE);
233
234 const { request } = await download.stallAfterWriting(`b${LARGE_RELEASE.slice(1)}`);
235 respond(request, 416, { "content-range": `bytes */${LARGE_RELEASE.length}` }, "");
236
237 await expect(download.result).rejects.toMatchObject({ code: "ERR_CHECKSUM_MISMATCH" });
238 expect(download.requestCount()).toBe(2);
239 });
240
241 it("fails a resumed download whose earlier bytes do not match the release", async () => {
242 using download = startDownload("", LARGE_RELEASE);
243
244 const { request } = await download.stallAfterWriting(`b${PREFIX.slice(1)}`);
245 respond(request, 206, { "content-range": RESUMED_RANGE }, "world");
246
247 await expect(download.result).rejects.toMatchObject({ code: "ERR_CHECKSUM_MISMATCH" });
248 });
249
250 it("gives up after three retries without resuming from a file it did not write", async () => {
251 using download = startDownload("differential output");
252 for (const backoff of [2_000, 4_000, 8_000]) {
253 const retry = download.nextRequest();
254 await vi.advanceTimersByTimeAsync(60_000 + backoff);
255 expect((await retry).headers.Range).toBeUndefined();
256 }
257 const outcome = expect(download.result).rejects.toThrow("Request timed out");
258
259 await vi.advanceTimersByTimeAsync(60_000);
260 await outcome;
261 expect(download.requestCount()).toBe(4);
262 });
263
264 it("does not retry a request that fails for another reason", async () => {
265 using download = startDownload("");
266 const [{ request }] = await download.first;
267 const outcome = expect(download.result).rejects.toThrow("net::ERR_CONNECTION_REFUSED");
268
269 request.emit("error", new Error("net::ERR_CONNECTION_REFUSED"));
270 await outcome;
271 expect(download.requestCount()).toBe(1);
272 });
273 });