The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
fix(updates): a stalled release download retries and resumes (#38038)
Co-authored-by: Claude Haiku 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
shivam committed
Nov 19, 2026 at 20:27 UTC
b0e469ceb9542bc3cfc2bc3d8345c43b66cd9832
5 files changed
+599
-35
apps/desktop/src/electron/ElectronHttpExecutor.test.ts
+214
@@ -1,8 +1,33 @@
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();
@@ -14,6 +39,103 @@ function startRequest() {
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();
@@ -56,4 +178,96 @@ describe("ElectronHttpExecutor idle timeout", () => {
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
});
apps/server/src/cloud/pinnedRuntime.test.ts
+111
-14
@@ -236,14 +236,38 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
236
}),
237
);
238
239
- it.effect("retries a release archive whose body fails after the host answered", () =>
239
+ it.effect.each([
240
+ { name: "body fails after the host answered", first: "body fails", honorsRange: true },
241
+ {
242
+ name: "body stalls and its resume ends early",
243
+ first: "body stalls",
244
+ honorsRange: true,
245
+ shortResume: true,
246
+ },
247
+ { name: "body stalls on a host that ignores Range", first: "body stalls", honorsRange: false },
248
+ { name: "response headers stall", first: "headers stall", honorsRange: true },
249
+ {
250
+ name: "whole body arrives and then stalls",
251
+ first: "body stalls",
252
+ honorsRange: true,
253
+ wholeArchive: true,
254
+ },
255
+ ] as const)("resumes a release archive download when its $name", (row) =>
256
Effect.gen(function* () {
257
+ const { first, honorsRange } = row;
258
+ const shortResume = "shortResume" in row;
259
const fs = yield* FileSystem.FileSystem;
260
const path = yield* Path.Path;
261
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-body-" });
262
const checksums = yield* validChecksums;
245
- let archiveRequests = 0;
263
+ const ranges: Array<string | undefined> = [];
264
+ const checksumRanges: Array<string | undefined> = [];
265
+ const progress: PinnedRuntimeProgress[] = [];
266
+ const checksumsRequested = yield* Deferred.make<void>();
267
const archiveRequested = yield* Deferred.make<void>();
268
+ const shortResumeRequested = yield* Deferred.make<void>();
269
+ const total = archiveBytes.length;
270
+ const heldBytes = "wholeArchive" in row ? archiveBytes : archiveBytes.slice(0, 4);
271
const install = yield* ensurePinnedRuntimeInstalled({
272
baseDir,
273
version,
@@ -252,21 +276,72 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
276
platform: "linux",
277
arch: "x64",
278
httpClient: HttpClient.make((request) => {
255
- const isChecksums = request.url.endsWith("/SHA256SUMS");
279
+ if (request.url.endsWith("/SHA256SUMS")) {
280
+ checksumRanges.push(request.headers["range"]);
281
+ const response = HttpClientResponse.fromWeb(request, new Response(checksums));
282
+ if (checksumRanges.length > 1) return Effect.succeed(response);
283
+ Deferred.doneUnsafe(checksumsRequested, Effect.void);
284
+ // The checksums fail once after a prefix, which their retry must not resume from.
285
+ const failingBody = Stream.concat(
286
+ Stream.make(new TextEncoder().encode(checksums).slice(0, 8)),
287
+ Stream.fail(
288
+ new HttpClientError.HttpClientError({
289
+ reason: new HttpClientError.DecodeError({ request, response }),
290
+ }),
291
+ ),
292
+ );
293
+ return Effect.sleep("1 second").pipe(
294
+ Effect.as<HttpClientResponse.HttpClientResponse>(
295
+ Object.create(response, { stream: { value: failingBody } }),
296
+ ),
297
+ );
298
+ }
299
+ const range = request.headers["range"];
300
+ ranges.push(range);
301
+ if (ranges.length > 1) {
302
+ const start = honorsRange ? Number(/^bytes=(\d+)-$/.exec(range ?? "")?.[1] ?? 0) : 0;
303
+ // A short resume stops one byte early; the next retry asks for that byte.
304
+ const end = shortResume && ranges.length === 2 ? total - 1 : total;
305
+ const response = HttpClientResponse.fromWeb(
306
+ request,
307
+ start >= total
308
+ ? new Response("", {
309
+ status: 416,
310
+ headers: { "content-range": `bytes */${total}` },
311
+ })
312
+ : start > 0
313
+ ? new Response(archiveBytes.slice(start, end), {
314
+ status: 206,
315
+ headers: { "content-range": `bytes ${start}-${end - 1}/${total}` },
316
+ })
317
+ : new Response(archiveBytes, { headers: { "content-length": `${total}` } }),
318
+ );
319
+ if (end === total) return Effect.succeed(response);
320
+ Deferred.doneUnsafe(shortResumeRequested, Effect.void);
321
+ // An Effect stream keeps the body, and so the retry wait after it, on the test clock.
322
+ const body = Stream.make(archiveBytes.slice(start, end));
323
+ return Effect.sleep("1 second").pipe(
324
+ Effect.as<HttpClientResponse.HttpClientResponse>(
325
+ Object.create(response, { stream: { value: body } }),
326
+ ),
327
+ );
328
+ }
329
+ Deferred.doneUnsafe(archiveRequested, Effect.void);
330
+ if (first === "headers stall") return Effect.never;
331
const response = HttpClientResponse.fromWeb(
332
request,
258
- new Response(isChecksums ? checksums : archiveBytes),
333
+ new Response(archiveBytes, { headers: { "content-length": `${total}` } }),
334
);
260
- if (isChecksums || ++archiveRequests > 1) return Effect.succeed(response);
335
const failingBody = Stream.concat(
262
- Stream.make(archiveBytes.slice(0, 4)),
263
- Stream.fail(
264
- new HttpClientError.HttpClientError({
265
- reason: new HttpClientError.DecodeError({ request, response }),
266
- }),
267
- ),
336
+ Stream.make(heldBytes),
337
+ first === "body stalls"
338
+ ? Stream.never
339
+ : Stream.fail(
340
+ new HttpClientError.HttpClientError({
341
+ reason: new HttpClientError.DecodeError({ request, response }),
342
+ }),
343
+ ),
344
);
269
- Deferred.doneUnsafe(archiveRequested, Effect.void);
345
// TestClock follows the work a woken sleep starts, so one adjust reaches the retry wait.
346
return Effect.sleep("1 second").pipe(
347
Effect.as<HttpClientResponse.HttpClientResponse>(
@@ -276,12 +351,34 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
351
}),
352
runner: extractingRunner(fs, path),
353
validate: () => Effect.void,
354
+ onProgress: (event) => progress.push(event),
355
}).pipe(Effect.forkScoped);
280
- yield* Deferred.await(archiveRequested);
356
+ yield* Deferred.await(checksumsRequested);
357
yield* TestClock.adjust(Duration.seconds(3));
358
+ yield* Deferred.await(archiveRequested);
359
+ // The one-minute stall bound, then the first two-second retry backoff.
360
+ yield* TestClock.adjust(Duration.seconds(first === "body fails" ? 3 : 63));
361
+ if (shortResume) {
362
+ yield* Deferred.await(shortResumeRequested);
363
+ // Its one-second delay, then the second, four-second backoff.
364
+ yield* TestClock.adjust(Duration.seconds(5));
365
+ }
366
const paths = yield* Fiber.join(install);
367
+ assert.deepEqual(checksumRanges, [undefined, undefined]);
368
+ assert.deepEqual(ranges, [
369
+ undefined,
370
+ first === "headers stall" ? undefined : `bytes=${heldBytes.length}-`,
371
+ ...(shortResume ? [`bytes=${total - 1}-`] : []),
372
+ ]);
373
assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`);
284
- assert.equal(archiveRequests, 2);
374
+ assert.deepEqual(
375
+ progress.findLast((event) => event.stage === "download"),
376
+ {
377
+ stage: "download",
378
+ received: total,
379
+ total,
380
+ },
381
+ );
382
}),
383
);
384
apps/server/src/cloud/pinnedRuntime.ts
+84
-16
@@ -126,54 +126,120 @@ const DOWNLOAD_RETRY = { times: 3, schedule: Schedule.exponential("2 seconds") }
126
const isTransientDownloadFailure = (
127
error: HttpClientError.HttpClientError | Cause.TimeoutError,
128
): boolean => {
129
- // No answer or a stall means the host cannot reach the release source; retrying only delays that.
130
- if (error._tag === "TimeoutError") return false;
129
+ // A slow link stalls past the bound and then recovers; the retry resumes from the bytes held.
130
+ if (error._tag === "TimeoutError") return true;
131
// Body bytes are read raw, so a DecodeError is a body that failed after the host answered.
132
if (error.reason._tag === "DecodeError") return true;
133
const status = error.response?.status;
134
return status !== undefined && (status >= 500 || status === 429 || status === 408);
135
};
136
137
+const CONTENT_RANGE = /^bytes (\d+)-\d+\/(\d+|\*)$/;
138
+
139
+const concatChunks = (chunks: ReadonlyArray<Uint8Array>, length: number): Uint8Array => {
140
+ const bytes = new Uint8Array(length);
141
+ let offset = 0;
142
+ for (const chunk of chunks) {
143
+ bytes.set(chunk, offset);
144
+ offset += chunk.byteLength;
145
+ }
146
+ return bytes;
147
+};
148
+
149
const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* (
150
httpClient: HttpClient.HttpClient,
151
url: string,
152
step: string,
153
+ // Only a digest-checked asset resumes; anything else restarts at byte 0 on each retry.
154
+ resume: boolean,
155
onProgress?: (progress: PinnedRuntimeProgress) => void,
156
) {
157
+ // Bytes from earlier attempts outlive the retry so a stalled download resumes with Range.
158
+ let chunks: Array<Uint8Array> = [];
159
+ let received = 0;
160
// Bound stalls while holding the install lock, but allow transfers that keep
161
// receiving bytes to finish regardless of their total duration.
145
- return yield* httpClient.execute(HttpClientRequest.get(url)).pipe(
146
- Effect.flatMap(HttpClientResponse.filterStatusOk),
162
+ return yield* Effect.suspend(() => {
163
+ if (!resume) {
164
+ chunks = [];
165
+ received = 0;
166
+ }
167
+ return httpClient.execute(
168
+ received > 0
169
+ ? HttpClientRequest.get(url).pipe(
170
+ HttpClientRequest.setHeader("range", `bytes=${received}-`),
171
+ )
172
+ : HttpClientRequest.get(url),
173
+ );
174
+ }).pipe(
175
+ // A resume answered 416 has nothing after the held bytes to send; the archive
176
+ // checksum decides whether they are the whole file.
177
+ Effect.filterOrElse(
178
+ (response) => received > 0 && response.status === 416,
179
+ HttpClientResponse.filterStatusOk,
180
+ ),
181
Effect.timeout(PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT),
182
Effect.flatMap(
183
Effect.fn(function* (response) {
150
- const length = Number(response.headers["content-length"]);
184
+ if (response.status === 416) return concatChunks(chunks, received);
185
+ const contentRange =
186
+ response.status === 206
187
+ ? CONTENT_RANGE.exec(response.headers["content-range"] ?? "")
188
+ : null;
189
+ if (response.status === 206 && Number(contentRange?.[1]) !== received) {
190
+ chunks = [];
191
+ received = 0;
192
+ return yield* new HttpClientError.HttpClientError({
193
+ reason: new HttpClientError.DecodeError({
194
+ request: response.request,
195
+ response,
196
+ description: "partial content does not resume the bytes already received",
197
+ }),
198
+ });
199
+ }
200
+ if (contentRange === null) {
201
+ chunks = [];
202
+ received = 0;
203
+ }
204
+ const length = Number(
205
+ contentRange === null ? response.headers["content-length"] : contentRange[2],
206
+ );
207
const total = Number.isFinite(length) && length > 0 ? length : undefined;
152
- let received = 0;
208
onProgress?.({ stage: "download", received, total });
154
- const chunks = yield* response.stream.pipe(
209
+ const attemptStart = received;
210
+ yield* response.stream.pipe(
211
Stream.timeoutOrElse({
212
duration: PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT,
213
orElse: () => Stream.fail(new Cause.TimeoutError()),
214
}),
159
- Stream.tap((chunk) =>
215
+ Stream.runForEach((chunk) =>
216
Effect.sync(() => {
217
+ chunks.push(chunk);
218
received += chunk.byteLength;
219
onProgress?.({ stage: "download", received, total });
220
}),
221
),
165
- Stream.runCollect,
222
);
223
+ // A server may end a 206 before the declared total; a retry asks for the rest.
224
+ if (
225
+ resume &&
226
+ contentRange !== null &&
227
+ total !== undefined &&
228
+ received > attemptStart &&
229
+ received < total
230
+ ) {
231
+ return yield* new HttpClientError.HttpClientError({
232
+ reason: new HttpClientError.DecodeError({
233
+ request: response.request,
234
+ response,
235
+ description: "partial content ended before the declared total",
236
+ }),
237
+ });
238
+ }
239
if (total === undefined && received > 0) {
240
onProgress?.({ stage: "download", received, total: received });
241
}
170
- const bytes = new Uint8Array(received);
171
- let offset = 0;
172
- for (const chunk of chunks) {
173
- bytes.set(chunk, offset);
174
- offset += chunk.byteLength;
175
- }
176
- return bytes;
242
+ return concatChunks(chunks, received);
243
}),
244
),
245
Effect.retry({ ...DOWNLOAD_RETRY, while: isTransientDownloadFailure }),
@@ -212,6 +278,7 @@ const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(fun
278
httpClient,
279
cliReleaseAssetUrl(input.version, fileName, input.releaseBaseUrl),
280
"downloading the t3 release archive",
281
+ true,
282
input.onProgress,
283
);
284
input.onProgress?.({ stage: "verify" });
@@ -271,6 +338,7 @@ const publishedArchive = Effect.fn("cloud.pinned_runtime.published_archive")(fun
338
input.httpClient,
339
cliReleaseAssetUrl(input.version, CLI_RELEASE_CHECKSUMS_FILE, input.releaseBaseUrl),
340
"downloading the t3 release checksums",
341
+ false,
342
),
343
),
344
);
patches/electron-updater@6.8.9.patch
+187
-2
@@ -1,8 +1,193 @@
1
diff --git a/out/electronHttpExecutor.js b/out/electronHttpExecutor.js
2
-index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..c298ffe7808c421c29e16f1e2ba8510f0cd31142 100644
2
+index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..e6fb0b8aafda6ae0797d3127b5aa661b0d202ca5 100644
3
--- a/out/electronHttpExecutor.js
4
+++ b/out/electronHttpExecutor.js
5
-@@ -61,6 +61,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor {
5
+@@ -3,7 +3,34 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ElectronHttpExecutor = exports.NET_SESSION_NAME = void 0;
7
+ exports.getNetSession = getNetSession;
8
+ const builder_util_runtime_1 = require("builder-util-runtime");
9
++const fs_1 = require("fs");
10
++const stream_1 = require("stream");
11
+ exports.NET_SESSION_NAME = "electron-updater";
12
++// A stall on a slow link is retried, resuming after the bytes earlier attempts wrote.
13
++const DOWNLOAD_STALL_RETRIES = 3;
14
++function isDownloadStall(error) {
15
++ return error != null && (error.message === "Request timed out" || error.message === "net::ERR_TIMED_OUT");
16
++}
17
++// doDownload turns any status >= 400 into this error before a response handler sees it.
18
++function isRangeNotSatisfiable(error) {
19
++ return error != null && /", status 416: /.test(error.message);
20
++}
21
++function createDigest(options) {
22
++ const sha512 = options.sha512;
23
++ if (sha512 != null) {
24
++ return new builder_util_runtime_1.DigestTransform(sha512, "sha512", sha512.length === 128 && !sha512.includes("+") && !sha512.includes("Z") && !sha512.includes("=") ? "hex" : "base64");
25
++ }
26
++ return options.sha2 == null ? null : new builder_util_runtime_1.DigestTransform(options.sha2, "sha256", "hex");
27
++}
28
++function verifyFile(destination, digest, cancellationToken) {
29
++ return cancellationToken.createPromise((resolve, reject, onCancel) => {
30
++ const controller = new AbortController();
31
++ onCancel(() => controller.abort());
32
++ stream_1.promises
33
++ .pipeline((0, fs_1.createReadStream)(destination, { signal: controller.signal }), digest, new stream_1.Writable({ write: (chunk, encoding, next) => next() }))
34
++ .then(() => resolve(), reject);
35
++ });
36
++}
37
+ function getNetSession() {
38
+ return require("electron").session.fromPartition(exports.NET_SESSION_NAME, {
39
+ cache: false,
40
+@@ -16,27 +43,133 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor {
41
+ this.cachedSession = null;
42
+ }
43
+ async download(url, destination, options) {
44
+- return await options.cancellationToken.createPromise((resolve, reject, onCancel) => {
45
++ // Only bytes this call wrote are resumed: the differential downloader leaves its own output
46
++ // at the same destination, and an attempt that fails before headers keeps the last count.
47
++ const held = { bytes: 0 };
48
++ for (let attempt = 0;; attempt++) {
49
++ const offset = held.bytes;
50
++ try {
51
++ return await this.downloadFrom(url, destination, options, held);
52
++ }
53
++ catch (e) {
54
++ // A 416 refuses the range; the digest decides whether the file already holds the release.
55
++ const digest = offset > 0 && isRangeNotSatisfiable(e) ? createDigest(options) : null;
56
++ if (digest != null) {
57
++ await verifyFile(destination, digest, options.cancellationToken);
58
++ return destination;
59
++ }
60
++ if (attempt >= DOWNLOAD_STALL_RETRIES || !isDownloadStall(e)) {
61
++ throw e;
62
++ }
63
++ }
64
++ await options.cancellationToken.createPromise((resolve, reject, onCancel) => {
65
++ const timer = setTimeout(resolve, 2000 * 2 ** attempt);
66
++ onCancel(() => clearTimeout(timer));
67
++ });
68
++ }
69
++ }
70
++ // Appends from `offset` when the server answers the Range with 206, then checks the digest over
71
++ // the whole file so the bytes from earlier attempts are verified too. A 200 starts over.
72
++ downloadFrom(url, destination, options, held) {
73
++ const offset = held.bytes;
74
++ const cancellationToken = options.cancellationToken;
75
++ return new Promise((resolve, reject) => {
76
+ const requestOptions = {
77
+- headers: options.headers || undefined,
78
++ headers: offset > 0 ? { ...options.headers, Range: `bytes=${offset}-` } : options.headers || undefined,
79
+ redirect: "manual",
80
+ };
81
+ (0, builder_util_runtime_1.configureRequestUrl)(url, requestOptions);
82
+ (0, builder_util_runtime_1.configureRequestOptions)(requestOptions);
83
+- this.doDownload(requestOptions, {
84
+- destination,
85
+- options,
86
+- onCancel,
87
+- callback: error => {
88
+- if (error == null) {
89
+- resolve(destination);
90
+- }
91
+- else {
92
+- reject(error);
93
+- }
94
+- },
95
+- responseHandler: null,
96
+- }, 0);
97
++ let fileOut = null;
98
++ let upstream = null;
99
++ let settled = false;
100
++ const callback = error => {
101
++ if (settled) {
102
++ return;
103
++ }
104
++ settled = true;
105
++ cancellationToken.removeListener("cancel", cancel);
106
++ const settle = () => (error == null ? resolve(destination) : reject(error));
107
++ if (fileOut == null || fileOut.closed) {
108
++ settle();
109
++ return;
110
++ }
111
++ // Let the bytes already handed to the file land, so a retry resumes after them.
112
++ fileOut.once("close", settle);
113
++ upstream.unpipe(fileOut);
114
++ if (!fileOut.destroyed && !fileOut.writableEnded) {
115
++ fileOut.end();
116
++ }
117
++ };
118
++ // doDownload never calls onCancel, so a cancel settles here once the file is closed, and a
119
++ // response that arrives after it is not written. The request runs on until its idle timeout.
120
++ const cancel = () => callback(new builder_util_runtime_1.CancellationError());
121
++ cancellationToken.onCancel(cancel);
122
++ if (settled) {
123
++ return;
124
++ }
125
++ try {
126
++ this.doDownload(requestOptions, {
127
++ destination,
128
++ options,
129
++ callback,
130
++ responseHandler: response => {
131
++ if (settled) {
132
++ return;
133
++ }
134
++ const resumed = offset > 0 && response.statusCode === 206;
135
++ const contentRange = (0, builder_util_runtime_1.safeGetHeader)(response, "content-range");
136
++ if (resumed && (contentRange == null || !contentRange.startsWith(`bytes ${offset}-`))) {
137
++ callback(new Error(`Cannot resume download at byte ${offset}, got Content-Range ${contentRange}`));
138
++ return;
139
++ }
140
++ const sha2Header = (0, builder_util_runtime_1.safeGetHeader)(response, "X-Checksum-Sha2");
141
++ if (sha2Header != null && options.sha2 != null && sha2Header !== options.sha2) {
142
++ callback(new Error(`checksum mismatch: expected ${options.sha2} but got ${sha2Header} (X-Checksum-Sha2 header)`));
143
++ return;
144
++ }
145
++ const start = resumed ? offset : 0;
146
++ const streams = [];
147
++ const contentLength = (0, builder_util_runtime_1.safeGetHeader)(response, "content-length");
148
++ if (options.onProgress != null && contentLength != null) {
149
++ const progress = new builder_util_runtime_1.ProgressCallbackTransform(start + parseInt(contentLength, 10), options.cancellationToken, options.onProgress);
150
++ progress.transferred = start;
151
++ streams.push(progress);
152
++ }
153
++ const digest = resumed ? null : createDigest(options);
154
++ if (digest != null) {
155
++ streams.push(digest);
156
++ }
157
++ fileOut = (0, fs_1.createWriteStream)(destination, { flags: resumed ? "a" : "w" });
158
++ fileOut.once("close", () => {
159
++ held.bytes = start + fileOut.bytesWritten;
160
++ });
161
++ upstream = response;
162
++ for (const stream of streams) {
163
++ stream.on("error", callback);
164
++ upstream = upstream.pipe(stream);
165
++ }
166
++ fileOut.on("error", callback);
167
++ upstream.pipe(fileOut);
168
++ fileOut.on("finish", () => {
169
++ if (settled) {
170
++ return;
171
++ }
172
++ fileOut.once("close", () => {
173
++ const fileDigest = resumed ? createDigest(options) : null;
174
++ if (fileDigest == null) {
175
++ callback(null);
176
++ return;
177
++ }
178
++ verifyFile(destination, fileDigest, options.cancellationToken).then(() => callback(null), callback);
179
++ });
180
++ });
181
++ },
182
++ }, 0);
183
++ }
184
++ catch (error) {
185
++ callback(error);
186
++ }
187
+ });
188
+ }
189
+ createRequest(options, callback) {
190
+@@ -61,6 +194,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor {
191
}
192
return request;
193
}
pnpm-lock.yaml
+3
-3
@@ -378,7 +378,7 @@ patchedDependencies:
378
alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd
379
app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53
380
dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4
381
- electron-updater@6.8.9: 5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e
381
+ electron-updater@6.8.9: 91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155
382
expo-audio@58.0.11: 93691f7f59edb30a3bb2c23b489e605e7ea35506b1212d4a2ebbd1fd79079483
383
expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7
384
expo-network@58.0.4: 159c2d760d1cd5102e95df51c20600111e7a72096ef0daea8215d50cae48bd98
@@ -468,7 +468,7 @@ importers:
468
version: 8.2.0
469
electron-updater:
470
specifier: 6.8.9
471
- version: 6.8.9(patch_hash=5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e)(supports-color@8.1.1)
471
+ version: 6.8.9(patch_hash=91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155)(supports-color@8.1.1)
472
electron-webauthn:
473
specifier: 'catalog:'
474
version: 1.3.1(typescript@6.0.3)
@@ -19107,7 +19107,7 @@ snapshots:
19107
19108
electron-to-chromium@1.5.430: {}
19109
19110
- electron-updater@6.8.9(patch_hash=5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e)(supports-color@8.1.1):
19110
+ electron-updater@6.8.9(patch_hash=91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155)(supports-color@8.1.1):
19111
dependencies:
19112
builder-util-runtime: 9.7.0(supports-color@8.1.1)
19113
fs-extra: 10.1.0