From 267b483db450717a75e731ba8688d77e92db0870 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:04:08 +0000 Subject: [PATCH 1/6] fix(updates): a stalled release download retries and resumes A stalled GitHub release download failed the whole update, and each retry started again from byte 0. On a slow link the 183 MB archive never finished. The server now treats a stall as transient and resumes from the bytes it already holds with a Range request. The Linux desktop updater's patched download does the same, retrying idle timeouts and net::ERR_TIMED_OUT, and verifies the full file's digest after a resume. Co-Authored-By: Claude Haiku 5.5 --- .../src/electron/ElectronHttpExecutor.test.ts | 142 ++++++++++++++++++ apps/server/src/cloud/pinnedRuntime.test.ts | 63 ++++++-- apps/server/src/cloud/pinnedRuntime.ts | 49 +++++- patches/electron-updater@6.8.9.patch | 139 ++++++++++++++++- pnpm-lock.yaml | 6 +- 5 files changed, 373 insertions(+), 26 deletions(-) diff --git a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts index 0a37f621dd601..48bd80f7ee905 100644 --- a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts +++ b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts @@ -1,8 +1,18 @@ // @effect-diagnostics nodeBuiltinImport:off -- Fake Electron net request and response emitters. +import * as NodeCrypto from "node:crypto"; import * as NodeEvents from "node:events"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeStream from "node:stream"; import { ElectronHttpExecutor } from "electron-updater/out/electronHttpExecutor.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +type DownloadOptions = Parameters[2]; +type FakeRequest = NodeEvents.EventEmitter & { abort: () => void }; + +const RELEASE = "hello world"; + function startRequest() { const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn() }); const response = new NodeEvents.EventEmitter(); @@ -14,6 +24,74 @@ function startRequest() { return { request, response, reject }; } +// The temp update file already holds `onDisk`, as if an earlier attempt had written it. +function startDownload(onDisk: string) { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "electron-http-executor-")); + const destination = NodePath.join(dir, "update.AppImage"); + NodeFS.writeFileSync(destination, onDisk); + const created = new NodeEvents.EventEmitter(); + let requestCount = 0; + const executor = new ElectronHttpExecutor(); + executor.createRequest = (options: { headers: Record }, callback) => { + const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn(), end: vi.fn() }); + request.on("response", callback); + requestCount++; + created.emit("request", { request, headers: options.headers }); + return request as unknown as Electron.ClientRequest; + }; + const cancellationToken = { + cancelled: false, + createPromise: ( + callback: ( + resolve: (value: unknown) => void, + reject: (error: Error) => void, + onCancel: () => void, + ) => void, + ) => new Promise((resolve, reject) => callback(resolve, reject, () => {})), + } as unknown as DownloadOptions["cancellationToken"]; + const first = NodeEvents.EventEmitter.once(created, "request"); + const result = executor.download(new URL("https://example.com/update.AppImage"), destination, { + cancellationToken, + sha512: NodeCrypto.createHash("sha512").update(RELEASE).digest("base64"), + }); + // A download that settles instead of sending another request fails the wait with its error. + const settled = result.then(() => { + throw new Error("The download finished without another request"); + }); + settled.catch(() => {}); + const nextRequest = async () => { + const [request] = await Promise.race([ + NodeEvents.EventEmitter.once(created, "request"), + settled, + ]); + return request as { request: FakeRequest; headers: Record }; + }; + return { + destination, + first, + nextRequest, + result, + requestCount: () => requestCount, + read: () => NodeFS.readFileSync(destination, "utf8"), + [Symbol.dispose]: () => NodeFS.rmSync(dir, { recursive: true, force: true }), + }; +} + +function respond( + request: FakeRequest, + statusCode: number, + headers: Record, + body: string, +) { + const response = Object.assign(new NodeStream.PassThrough(), { + statusCode, + statusMessage: "", + headers: { "content-length": String(body.length), ...headers }, + }); + request.emit("response", response); + response.end(body); +} + describe("ElectronHttpExecutor idle timeout", () => { beforeEach(() => { vi.useFakeTimers(); @@ -56,4 +134,68 @@ describe("ElectronHttpExecutor idle timeout", () => { expect(request.abort).not.toHaveBeenCalled(); expect(reject).not.toHaveBeenCalled(); }); + + it("resumes a stalled download from the bytes already written", async () => { + using download = startDownload("hello "); + const retry = download.nextRequest(); + + await vi.advanceTimersByTimeAsync(60_000 + 2_000); + const { request, headers } = await retry; + expect(headers.Range).toBe("bytes=6-"); + respond(request, 206, { "content-range": "bytes 6-10/11" }, "world"); + + await expect(download.result).resolves.toBe(download.destination); + expect(download.read()).toBe(RELEASE); + }); + + it("starts over when the server ignores the range", async () => { + using download = startDownload("HELLO "); + const [{ request: first }] = await download.first; + const retry = download.nextRequest(); + + first.emit("error", new Error("net::ERR_TIMED_OUT")); + await vi.advanceTimersByTimeAsync(2_000); + const { request, headers } = await retry; + expect(headers.Range).toBe("bytes=6-"); + respond(request, 200, {}, RELEASE); + + await expect(download.result).resolves.toBe(download.destination); + expect(download.read()).toBe(RELEASE); + }); + + it("fails a resumed download whose earlier bytes do not match the release", async () => { + using download = startDownload("HELLO "); + const retry = download.nextRequest(); + + await vi.advanceTimersByTimeAsync(60_000 + 2_000); + const { request } = await retry; + respond(request, 206, { "content-range": "bytes 6-10/11" }, "world"); + + await expect(download.result).rejects.toMatchObject({ code: "ERR_CHECKSUM_MISMATCH" }); + }); + + it("gives up after three retries", async () => { + using download = startDownload(""); + for (const backoff of [2_000, 4_000, 8_000]) { + const retry = download.nextRequest(); + await vi.advanceTimersByTimeAsync(60_000 + backoff); + await retry; + } + const outcome = expect(download.result).rejects.toThrow("Request timed out"); + + await vi.advanceTimersByTimeAsync(60_000); + await outcome; + expect(download.requestCount()).toBe(4); + }); + + it("does not retry a request that fails for another reason", async () => { + using download = startDownload("hello "); + const [{ request }] = await download.first; + const outcome = expect(download.result).rejects.toThrow("net::ERR_CONNECTION_REFUSED"); + + request.emit("error", new Error("net::ERR_CONNECTION_REFUSED")); + await outcome; + await vi.advanceTimersByTimeAsync(120_000); + expect(download.requestCount()).toBe(1); + }); }); diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 0c016a504c9b4..91416dc91eb06 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -236,14 +236,21 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { }), ); - it.effect("retries a release archive whose body fails after the host answered", () => + it.effect.each([ + { name: "body fails after the host answered", first: "body fails", honorsRange: true }, + { name: "body stalls", first: "body stalls", honorsRange: true }, + { name: "body stalls on a host that ignores Range", first: "body stalls", honorsRange: false }, + { name: "response headers stall", first: "headers stall", honorsRange: true }, + ] as const)("resumes a release archive download when its $name", ({ first, honorsRange }) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-body-" }); const checksums = yield* validChecksums; - let archiveRequests = 0; + const ranges: Array = []; + const progress: PinnedRuntimeProgress[] = []; const archiveRequested = yield* Deferred.make(); + const total = archiveBytes.length; const install = yield* ensurePinnedRuntimeInstalled({ baseDir, version, @@ -252,21 +259,41 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { platform: "linux", arch: "x64", httpClient: HttpClient.make((request) => { - const isChecksums = request.url.endsWith("/SHA256SUMS"); + if (request.url.endsWith("/SHA256SUMS")) { + return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(checksums))); + } + const range = request.headers["range"]; + ranges.push(range); + if (ranges.length > 1) { + const start = honorsRange ? Number(/^bytes=(\d+)-$/.exec(range ?? "")?.[1] ?? 0) : 0; + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + start > 0 + ? new Response(archiveBytes.slice(start), { + status: 206, + headers: { "content-range": `bytes ${start}-${total - 1}/${total}` }, + }) + : new Response(archiveBytes, { headers: { "content-length": `${total}` } }), + ), + ); + } + Deferred.doneUnsafe(archiveRequested, Effect.void); + if (first === "headers stall") return Effect.never; const response = HttpClientResponse.fromWeb( request, - new Response(isChecksums ? checksums : archiveBytes), + new Response(archiveBytes, { headers: { "content-length": `${total}` } }), ); - if (isChecksums || ++archiveRequests > 1) return Effect.succeed(response); const failingBody = Stream.concat( Stream.make(archiveBytes.slice(0, 4)), - Stream.fail( - new HttpClientError.HttpClientError({ - reason: new HttpClientError.DecodeError({ request, response }), - }), - ), + first === "body stalls" + ? Stream.never + : Stream.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.DecodeError({ request, response }), + }), + ), ); - Deferred.doneUnsafe(archiveRequested, Effect.void); // TestClock follows the work a woken sleep starts, so one adjust reaches the retry wait. return Effect.sleep("1 second").pipe( Effect.as( @@ -276,12 +303,22 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { }), runner: extractingRunner(fs, path), validate: () => Effect.void, + onProgress: (event) => progress.push(event), }).pipe(Effect.forkScoped); yield* Deferred.await(archiveRequested); - yield* TestClock.adjust(Duration.seconds(3)); + // The one-minute stall bound, then the first two-second retry backoff. + yield* TestClock.adjust(Duration.seconds(first === "body fails" ? 3 : 63)); const paths = yield* Fiber.join(install); assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`); - assert.equal(archiveRequests, 2); + assert.deepEqual(ranges, [undefined, first === "headers stall" ? undefined : "bytes=4-"]); + assert.deepEqual( + progress.findLast((event) => event.stage === "download"), + { + stage: "download", + received: total, + total, + }, + ); }), ); diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index 09c8145a4a615..0f43261f1e078 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -126,43 +126,76 @@ const DOWNLOAD_RETRY = { times: 3, schedule: Schedule.exponential("2 seconds") } const isTransientDownloadFailure = ( error: HttpClientError.HttpClientError | Cause.TimeoutError, ): boolean => { - // No answer or a stall means the host cannot reach the release source; retrying only delays that. - if (error._tag === "TimeoutError") return false; + // A slow link stalls past the bound and then recovers; the retry resumes from the bytes held. + if (error._tag === "TimeoutError") return true; // Body bytes are read raw, so a DecodeError is a body that failed after the host answered. if (error.reason._tag === "DecodeError") return true; const status = error.response?.status; return status !== undefined && (status >= 500 || status === 429 || status === 408); }; +const CONTENT_RANGE = /^bytes (\d+)-\d+\/(\d+|\*)$/; + const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* ( httpClient: HttpClient.HttpClient, url: string, step: string, onProgress?: (progress: PinnedRuntimeProgress) => void, ) { + // Bytes from earlier attempts outlive the retry so a stalled download resumes with Range. + let chunks: Array = []; + let received = 0; // Bound stalls while holding the install lock, but allow transfers that keep // receiving bytes to finish regardless of their total duration. - return yield* httpClient.execute(HttpClientRequest.get(url)).pipe( + return yield* Effect.suspend(() => + httpClient.execute( + received > 0 + ? HttpClientRequest.get(url).pipe( + HttpClientRequest.setHeader("range", `bytes=${received}-`), + ) + : HttpClientRequest.get(url), + ), + ).pipe( Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.timeout(PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT), Effect.flatMap( Effect.fn(function* (response) { - const length = Number(response.headers["content-length"]); + const contentRange = + response.status === 206 + ? CONTENT_RANGE.exec(response.headers["content-range"] ?? "") + : null; + if (response.status === 206 && Number(contentRange?.[1]) !== received) { + chunks = []; + received = 0; + return yield* new HttpClientError.HttpClientError({ + reason: new HttpClientError.DecodeError({ + request: response.request, + response, + description: "partial content does not resume the bytes already received", + }), + }); + } + if (contentRange === null) { + chunks = []; + received = 0; + } + const length = Number( + contentRange === null ? response.headers["content-length"] : contentRange[2], + ); const total = Number.isFinite(length) && length > 0 ? length : undefined; - let received = 0; onProgress?.({ stage: "download", received, total }); - const chunks = yield* response.stream.pipe( + yield* response.stream.pipe( Stream.timeoutOrElse({ duration: PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT, orElse: () => Stream.fail(new Cause.TimeoutError()), }), - Stream.tap((chunk) => + Stream.runForEach((chunk) => Effect.sync(() => { + chunks.push(chunk); received += chunk.byteLength; onProgress?.({ stage: "download", received, total }); }), ), - Stream.runCollect, ); if (total === undefined && received > 0) { onProgress?.({ stage: "download", received, total: received }); diff --git a/patches/electron-updater@6.8.9.patch b/patches/electron-updater@6.8.9.patch index 1e343589cb509..9088aab128445 100644 --- a/patches/electron-updater@6.8.9.patch +++ b/patches/electron-updater@6.8.9.patch @@ -1,8 +1,143 @@ diff --git a/out/electronHttpExecutor.js b/out/electronHttpExecutor.js -index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..c298ffe7808c421c29e16f1e2ba8510f0cd31142 100644 +index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..be9823826c29855e73326984962df7cb5432edb5 100644 --- a/out/electronHttpExecutor.js +++ b/out/electronHttpExecutor.js -@@ -61,6 +61,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { +@@ -3,7 +3,21 @@ Object.defineProperty(exports, "__esModule", { value: true }); + exports.ElectronHttpExecutor = exports.NET_SESSION_NAME = void 0; + exports.getNetSession = getNetSession; + const builder_util_runtime_1 = require("builder-util-runtime"); ++const fs_1 = require("fs"); ++const stream_1 = require("stream"); + exports.NET_SESSION_NAME = "electron-updater"; ++// A stall on a slow link is retried, resuming from the bytes already in the file. ++const DOWNLOAD_STALL_RETRIES = 3; ++function isDownloadStall(error) { ++ return error != null && (error.message === "Request timed out" || error.message === "net::ERR_TIMED_OUT"); ++} ++function createDigest(options) { ++ const sha512 = options.sha512; ++ if (sha512 != null) { ++ return new builder_util_runtime_1.DigestTransform(sha512, "sha512", sha512.length === 128 && !sha512.includes("+") && !sha512.includes("Z") && !sha512.includes("=") ? "hex" : "base64"); ++ } ++ return options.sha2 == null ? null : new builder_util_runtime_1.DigestTransform(options.sha2, "sha256", "hex"); ++} + function getNetSession() { + return require("electron").session.fromPartition(exports.NET_SESSION_NAME, { + cache: false, +@@ -16,26 +30,104 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { + this.cachedSession = null; + } + async download(url, destination, options) { +- return await options.cancellationToken.createPromise((resolve, reject, onCancel) => { ++ for (let attempt = 0;; attempt++) { ++ const offset = attempt === 0 ? 0 : await fs_1.promises.stat(destination).then(it => it.size, () => 0); ++ try { ++ return await this.downloadFrom(url, destination, options, offset); ++ } ++ catch (e) { ++ if (attempt >= DOWNLOAD_STALL_RETRIES || !isDownloadStall(e)) { ++ throw e; ++ } ++ } ++ await options.cancellationToken.createPromise((resolve, reject, onCancel) => { ++ const timer = setTimeout(resolve, 2000 * 2 ** attempt); ++ onCancel(() => clearTimeout(timer)); ++ }); ++ } ++ } ++ // Appends from `offset` when the server answers the Range with 206, then checks the digest over ++ // the whole file so the bytes from earlier attempts are verified too. A 200 starts over. ++ downloadFrom(url, destination, options, offset) { ++ return options.cancellationToken.createPromise((resolve, reject, onCancel) => { + const requestOptions = { +- headers: options.headers || undefined, ++ headers: offset > 0 ? { ...options.headers, Range: `bytes=${offset}-` } : options.headers || undefined, + redirect: "manual", + }; + (0, builder_util_runtime_1.configureRequestUrl)(url, requestOptions); + (0, builder_util_runtime_1.configureRequestOptions)(requestOptions); ++ let fileOut = null; ++ let upstream = null; ++ let settled = false; ++ const callback = error => { ++ if (settled) { ++ return; ++ } ++ settled = true; ++ const settle = () => (error == null ? resolve(destination) : reject(error)); ++ if (fileOut == null || fileOut.closed) { ++ settle(); ++ return; ++ } ++ // Let the bytes already handed to the file land, so a retry resumes after them. ++ fileOut.once("close", settle); ++ upstream.unpipe(fileOut); ++ if (!fileOut.destroyed && !fileOut.writableEnded) { ++ fileOut.end(); ++ } ++ }; + this.doDownload(requestOptions, { + destination, + options, + onCancel, +- callback: error => { +- if (error == null) { +- resolve(destination); ++ callback, ++ responseHandler: response => { ++ const resumed = offset > 0 && response.statusCode === 206; ++ const contentRange = (0, builder_util_runtime_1.safeGetHeader)(response, "content-range"); ++ if (resumed && (contentRange == null || !contentRange.startsWith(`bytes ${offset}-`))) { ++ callback(new Error(`Cannot resume download at byte ${offset}, got Content-Range ${contentRange}`)); ++ return; ++ } ++ const sha2Header = (0, builder_util_runtime_1.safeGetHeader)(response, "X-Checksum-Sha2"); ++ if (sha2Header != null && options.sha2 != null && sha2Header !== options.sha2) { ++ callback(new Error(`checksum mismatch: expected ${options.sha2} but got ${sha2Header} (X-Checksum-Sha2 header)`)); ++ return; ++ } ++ const streams = []; ++ const contentLength = (0, builder_util_runtime_1.safeGetHeader)(response, "content-length"); ++ if (options.onProgress != null && contentLength != null) { ++ const progress = new builder_util_runtime_1.ProgressCallbackTransform((resumed ? offset : 0) + parseInt(contentLength, 10), options.cancellationToken, options.onProgress); ++ progress.transferred = resumed ? offset : 0; ++ streams.push(progress); ++ } ++ const digest = resumed ? null : createDigest(options); ++ if (digest != null) { ++ streams.push(digest); + } +- else { +- reject(error); ++ fileOut = (0, fs_1.createWriteStream)(destination, { flags: resumed ? "a" : "w" }); ++ upstream = response; ++ for (const stream of streams) { ++ stream.on("error", callback); ++ upstream = upstream.pipe(stream); + } ++ fileOut.on("error", callback); ++ upstream.pipe(fileOut); ++ fileOut.on("finish", () => { ++ if (settled) { ++ return; ++ } ++ fileOut.once("close", () => { ++ const fileDigest = resumed ? createDigest(options) : null; ++ if (fileDigest == null) { ++ callback(null); ++ return; ++ } ++ stream_1.promises ++ .pipeline((0, fs_1.createReadStream)(destination), fileDigest, new stream_1.Writable({ write: (chunk, encoding, next) => next() })) ++ .then(() => callback(null), callback); ++ }); ++ }); + }, +- responseHandler: null, + }, 0); + }); + } +@@ -61,6 +153,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { } return request; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 70431202c4b61..b0fefece8ad52 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -379,7 +379,7 @@ patchedDependencies: alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 - electron-updater@6.8.9: 5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e + electron-updater@6.8.9: f9a64456ab8ea37f471e8479405f839823a57a277d8fa9dcd48ecdc84a749b6c expo-audio@58.0.11: 93691f7f59edb30a3bb2c23b489e605e7ea35506b1212d4a2ebbd1fd79079483 expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 expo-network@58.0.4: 159c2d760d1cd5102e95df51c20600111e7a72096ef0daea8215d50cae48bd98 @@ -469,7 +469,7 @@ importers: version: 8.2.0 electron-updater: specifier: 6.8.9 - version: 6.8.9(patch_hash=5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e)(supports-color@8.1.1) + version: 6.8.9(patch_hash=f9a64456ab8ea37f471e8479405f839823a57a277d8fa9dcd48ecdc84a749b6c)(supports-color@8.1.1) electron-webauthn: specifier: 'catalog:' version: 1.3.1(typescript@6.0.3) @@ -19084,7 +19084,7 @@ snapshots: electron-to-chromium@1.5.430: {} - electron-updater@6.8.9(patch_hash=5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e)(supports-color@8.1.1): + electron-updater@6.8.9(patch_hash=f9a64456ab8ea37f471e8479405f839823a57a277d8fa9dcd48ecdc84a749b6c)(supports-color@8.1.1): dependencies: builder-util-runtime: 9.7.0(supports-color@8.1.1) fs-extra: 10.1.0 From b13b4c95c1c3c8665811ef20488f7ece6d48a7f5 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:58:39 +0000 Subject: [PATCH 2/6] fix(updates): a resume past the end accepts the file once its digest matches A stall after the last byte made the retry ask for bytes past the end of the release, which the host answers with 416. That failed the update even though the file on disk was complete. A 416 on a resume now accepts the held bytes only after the full-file digest matches, so a wrong file still fails. Co-Authored-By: Claude Haiku 5.5 --- .../src/electron/ElectronHttpExecutor.test.ts | 86 +++++++++++++++---- apps/server/src/cloud/pinnedRuntime.test.ts | 57 +++++++++--- apps/server/src/cloud/pinnedRuntime.ts | 26 ++++-- patches/electron-updater@6.8.9.patch | 33 ++++--- pnpm-lock.yaml | 6 +- 5 files changed, 159 insertions(+), 49 deletions(-) diff --git a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts index 48bd80f7ee905..39e77dd788a05 100644 --- a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts +++ b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts @@ -2,6 +2,7 @@ import * as NodeCrypto from "node:crypto"; import * as NodeEvents from "node:events"; import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeStream from "node:stream"; @@ -11,7 +12,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test" type DownloadOptions = Parameters[2]; type FakeRequest = NodeEvents.EventEmitter & { abort: () => void }; +// electron-updater is CommonJS, so a spy goes on the module object its require() returns. +const fsModule = NodeModule.createRequire(import.meta.url)("node:fs") as typeof NodeFS; const RELEASE = "hello world"; +// Larger than a file stream's buffer, so its "drain" marks a write of it as committed to disk. +const PREFIX = "a".repeat(1 << 20); +const LARGE_RELEASE = `${PREFIX}world`; function startRequest() { const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn() }); @@ -25,10 +31,11 @@ function startRequest() { } // The temp update file already holds `onDisk`, as if an earlier attempt had written it. -function startDownload(onDisk: string) { +function startDownload(onDisk: string, release = RELEASE) { const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "electron-http-executor-")); const destination = NodePath.join(dir, "update.AppImage"); NodeFS.writeFileSync(destination, onDisk); + const createWriteStream = vi.spyOn(fsModule, "createWriteStream"); const created = new NodeEvents.EventEmitter(); let requestCount = 0; const executor = new ElectronHttpExecutor(); @@ -52,7 +59,7 @@ function startDownload(onDisk: string) { const first = NodeEvents.EventEmitter.once(created, "request"); const result = executor.download(new URL("https://example.com/update.AppImage"), destination, { cancellationToken, - sha512: NodeCrypto.createHash("sha512").update(RELEASE).digest("base64"), + sha512: NodeCrypto.createHash("sha512").update(release).digest("base64"), }); // A download that settles instead of sending another request fails the wait with its error. const settled = result.then(() => { @@ -66,30 +73,55 @@ function startDownload(onDisk: string) { ]); return request as { request: FakeRequest; headers: Record }; }; + // The first request answers 200 and writes `body` to the file, then stalls before the end. + const stallAfterWriting = async (body: string) => { + const [{ request }] = await first; + const response = startResponse(request, 200, { "content-length": String(release.length) }); + const fileOut = createWriteStream.mock.results[0]!.value as NodeFS.WriteStream; + const committed = NodeEvents.EventEmitter.once(fileOut, "drain"); + response.write(body); + await committed; + const closed = NodeEvents.EventEmitter.once(fileOut, "close"); + const retry = nextRequest(); + await vi.advanceTimersByTimeAsync(60_000); + await closed; + await vi.advanceTimersByTimeAsync(2_000); + return retry; + }; return { destination, first, nextRequest, + stallAfterWriting, result, requestCount: () => requestCount, read: () => NodeFS.readFileSync(destination, "utf8"), - [Symbol.dispose]: () => NodeFS.rmSync(dir, { recursive: true, force: true }), + [Symbol.dispose]: () => { + createWriteStream.mockRestore(); + NodeFS.rmSync(dir, { recursive: true, force: true }); + }, }; } +function startResponse(request: FakeRequest, statusCode: number, headers: Record) { + const response = Object.assign(new NodeStream.PassThrough(), { + statusCode, + statusMessage: "", + headers, + }); + request.emit("response", response); + return response; +} + function respond( request: FakeRequest, statusCode: number, headers: Record, body: string, ) { - const response = Object.assign(new NodeStream.PassThrough(), { - statusCode, - statusMessage: "", - headers: { "content-length": String(body.length), ...headers }, - }); - request.emit("response", response); - response.end(body); + startResponse(request, statusCode, { "content-length": String(body.length), ...headers }).end( + body, + ); } describe("ElectronHttpExecutor idle timeout", () => { @@ -136,16 +168,36 @@ describe("ElectronHttpExecutor idle timeout", () => { }); it("resumes a stalled download from the bytes already written", async () => { - using download = startDownload("hello "); - const retry = download.nextRequest(); + using download = startDownload("", LARGE_RELEASE); - await vi.advanceTimersByTimeAsync(60_000 + 2_000); - const { request, headers } = await retry; - expect(headers.Range).toBe("bytes=6-"); - respond(request, 206, { "content-range": "bytes 6-10/11" }, "world"); + const { request, headers } = await download.stallAfterWriting(PREFIX); + expect(headers.Range).toBe(`bytes=${PREFIX.length}-`); + const range = `bytes ${PREFIX.length}-${LARGE_RELEASE.length - 1}/${LARGE_RELEASE.length}`; + respond(request, 206, { "content-range": range }, "world"); await expect(download.result).resolves.toBe(download.destination); - expect(download.read()).toBe(RELEASE); + expect(download.read()).toBe(LARGE_RELEASE); + }); + + it("accepts a file that already holds every byte when the retry is past the end", async () => { + using download = startDownload("", LARGE_RELEASE); + + const { request, headers } = await download.stallAfterWriting(LARGE_RELEASE); + expect(headers.Range).toBe(`bytes=${LARGE_RELEASE.length}-`); + respond(request, 416, { "content-range": `bytes */${LARGE_RELEASE.length}` }, ""); + + await expect(download.result).resolves.toBe(download.destination); + expect(download.read()).toBe(LARGE_RELEASE); + }); + + it("fails a file past the end of the release whose bytes do not match it", async () => { + using download = startDownload("", LARGE_RELEASE); + + const { request } = await download.stallAfterWriting(`b${LARGE_RELEASE.slice(1)}`); + respond(request, 416, { "content-range": `bytes */${LARGE_RELEASE.length}` }, ""); + + await expect(download.result).rejects.toMatchObject({ code: "ERR_CHECKSUM_MISMATCH" }); + expect(download.requestCount()).toBe(2); }); it("starts over when the server ignores the range", async () => { diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 91416dc91eb06..2f087c33ea32f 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -241,8 +241,22 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { { name: "body stalls", first: "body stalls", honorsRange: true }, { name: "body stalls on a host that ignores Range", first: "body stalls", honorsRange: false }, { name: "response headers stall", first: "headers stall", honorsRange: true }, - ] as const)("resumes a release archive download when its $name", ({ first, honorsRange }) => + { + name: "whole body arrives and then stalls", + first: "body stalls", + honorsRange: true, + held: "whole", + }, + { + name: "whole but wrong body arrives and then fails", + first: "body fails", + honorsRange: true, + held: "wrong", + }, + ] as const)("resumes a release archive download when its $name", (row) => Effect.gen(function* () { + const { first, honorsRange } = row; + const held = "held" in row ? row.held : "prefix"; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-body-" }); @@ -251,6 +265,12 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { const progress: PinnedRuntimeProgress[] = []; const archiveRequested = yield* Deferred.make(); const total = archiveBytes.length; + const heldBytes = + held === "prefix" + ? archiveBytes.slice(0, 4) + : held === "whole" + ? archiveBytes + : archiveBytes.map((byte) => byte ^ 1); const install = yield* ensurePinnedRuntimeInstalled({ baseDir, version, @@ -269,12 +289,17 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { return Effect.succeed( HttpClientResponse.fromWeb( request, - start > 0 - ? new Response(archiveBytes.slice(start), { - status: 206, - headers: { "content-range": `bytes ${start}-${total - 1}/${total}` }, + start >= total + ? new Response("", { + status: 416, + headers: { "content-range": `bytes */${total}` }, }) - : new Response(archiveBytes, { headers: { "content-length": `${total}` } }), + : start > 0 + ? new Response(archiveBytes.slice(start), { + status: 206, + headers: { "content-range": `bytes ${start}-${total - 1}/${total}` }, + }) + : new Response(archiveBytes, { headers: { "content-length": `${total}` } }), ), ); } @@ -285,7 +310,7 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { new Response(archiveBytes, { headers: { "content-length": `${total}` } }), ); const failingBody = Stream.concat( - Stream.make(archiveBytes.slice(0, 4)), + Stream.make(heldBytes), first === "body stalls" ? Stream.never : Stream.fail( @@ -308,9 +333,21 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { yield* Deferred.await(archiveRequested); // The one-minute stall bound, then the first two-second retry backoff. yield* TestClock.adjust(Duration.seconds(first === "body fails" ? 3 : 63)); - const paths = yield* Fiber.join(install); - assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`); - assert.deepEqual(ranges, [undefined, first === "headers stall" ? undefined : "bytes=4-"]); + const result = yield* Fiber.join(install).pipe(Effect.result); + assert.deepEqual(ranges, [ + undefined, + first === "headers stall" ? undefined : `bytes=${heldBytes.length}-`, + ]); + if (held === "wrong") { + assert.equal(result._tag, "Failure"); + if (result._tag !== "Failure") return; + assert.instanceOf(result.failure, PinnedRuntimeInstallError); + assert.equal(result.failure.step, "verifying the t3 release archive checksum"); + return; + } + assert.equal(result._tag, "Success"); + if (result._tag !== "Success") return; + assert.equal(yield* fs.readFileString(result.success.sentinelPath), `${version}\n`); assert.deepEqual( progress.findLast((event) => event.stage === "download"), { diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index 0f43261f1e078..24455a4b68810 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -136,6 +136,16 @@ const isTransientDownloadFailure = ( const CONTENT_RANGE = /^bytes (\d+)-\d+\/(\d+|\*)$/; +const concatChunks = (chunks: ReadonlyArray, length: number): Uint8Array => { + const bytes = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return bytes; +}; + const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* ( httpClient: HttpClient.HttpClient, url: string, @@ -156,10 +166,16 @@ const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")( : HttpClientRequest.get(url), ), ).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), + // A resume answered 416 asked past the end, so the held bytes are the whole file; + // the archive checksum still rejects a wrong one. + Effect.filterOrElse( + (response) => received > 0 && response.status === 416, + HttpClientResponse.filterStatusOk, + ), Effect.timeout(PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT), Effect.flatMap( Effect.fn(function* (response) { + if (response.status === 416) return concatChunks(chunks, received); const contentRange = response.status === 206 ? CONTENT_RANGE.exec(response.headers["content-range"] ?? "") @@ -200,13 +216,7 @@ const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")( if (total === undefined && received > 0) { onProgress?.({ stage: "download", received, total: received }); } - const bytes = new Uint8Array(received); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; - } - return bytes; + return concatChunks(chunks, received); }), ), Effect.retry({ ...DOWNLOAD_RETRY, while: isTransientDownloadFailure }), diff --git a/patches/electron-updater@6.8.9.patch b/patches/electron-updater@6.8.9.patch index 9088aab128445..48e300582b468 100644 --- a/patches/electron-updater@6.8.9.patch +++ b/patches/electron-updater@6.8.9.patch @@ -1,8 +1,8 @@ diff --git a/out/electronHttpExecutor.js b/out/electronHttpExecutor.js -index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..be9823826c29855e73326984962df7cb5432edb5 100644 +index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..107ad84e11134deb49712b87f54cde706ebd7d48 100644 --- a/out/electronHttpExecutor.js +++ b/out/electronHttpExecutor.js -@@ -3,7 +3,21 @@ Object.defineProperty(exports, "__esModule", { value: true }); +@@ -3,7 +3,28 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.ElectronHttpExecutor = exports.NET_SESSION_NAME = void 0; exports.getNetSession = getNetSession; const builder_util_runtime_1 = require("builder-util-runtime"); @@ -14,17 +14,24 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..be9823826c29855e73326984962df7cb +function isDownloadStall(error) { + return error != null && (error.message === "Request timed out" || error.message === "net::ERR_TIMED_OUT"); +} ++// doDownload turns any status >= 400 into this error before a response handler sees it. ++function isRangeNotSatisfiable(error) { ++ return error != null && /", status 416: /.test(error.message); ++} +function createDigest(options) { + const sha512 = options.sha512; + if (sha512 != null) { + return new builder_util_runtime_1.DigestTransform(sha512, "sha512", sha512.length === 128 && !sha512.includes("+") && !sha512.includes("Z") && !sha512.includes("=") ? "hex" : "base64"); + } + return options.sha2 == null ? null : new builder_util_runtime_1.DigestTransform(options.sha2, "sha256", "hex"); ++} ++function verifyFile(destination, digest) { ++ return stream_1.promises.pipeline((0, fs_1.createReadStream)(destination), digest, new stream_1.Writable({ write: (chunk, encoding, next) => next() })); +} function getNetSession() { return require("electron").session.fromPartition(exports.NET_SESSION_NAME, { cache: false, -@@ -16,26 +30,104 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { +@@ -16,26 +37,108 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { this.cachedSession = null; } async download(url, destination, options) { @@ -35,6 +42,12 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..be9823826c29855e73326984962df7cb + return await this.downloadFrom(url, destination, options, offset); + } + catch (e) { ++ // A 416 means the file already reaches the end of the release, so its digest decides. ++ const digest = offset > 0 && isRangeNotSatisfiable(e) ? createDigest(options) : null; ++ if (digest != null) { ++ await verifyFile(destination, digest); ++ return destination; ++ } + if (attempt >= DOWNLOAD_STALL_RETRIES || !isDownloadStall(e)) { + throw e; + } @@ -102,19 +115,19 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..be9823826c29855e73326984962df7cb + const progress = new builder_util_runtime_1.ProgressCallbackTransform((resumed ? offset : 0) + parseInt(contentLength, 10), options.cancellationToken, options.onProgress); + progress.transferred = resumed ? offset : 0; + streams.push(progress); -+ } + } +- else { +- reject(error); + const digest = resumed ? null : createDigest(options); + if (digest != null) { + streams.push(digest); } -- else { -- reject(error); + fileOut = (0, fs_1.createWriteStream)(destination, { flags: resumed ? "a" : "w" }); + upstream = response; + for (const stream of streams) { + stream.on("error", callback); + upstream = upstream.pipe(stream); - } ++ } + fileOut.on("error", callback); + upstream.pipe(fileOut); + fileOut.on("finish", () => { @@ -127,9 +140,7 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..be9823826c29855e73326984962df7cb + callback(null); + return; + } -+ stream_1.promises -+ .pipeline((0, fs_1.createReadStream)(destination), fileDigest, new stream_1.Writable({ write: (chunk, encoding, next) => next() })) -+ .then(() => callback(null), callback); ++ verifyFile(destination, fileDigest).then(() => callback(null), callback); + }); + }); }, @@ -137,7 +148,7 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..be9823826c29855e73326984962df7cb }, 0); }); } -@@ -61,6 +153,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { +@@ -61,6 +164,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { } return request; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b0fefece8ad52..8b20673dc9824 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -379,7 +379,7 @@ patchedDependencies: alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 - electron-updater@6.8.9: f9a64456ab8ea37f471e8479405f839823a57a277d8fa9dcd48ecdc84a749b6c + electron-updater@6.8.9: 1eba5af25f72cb57b26810d051dcaf3c2fb243cd6b88d874bcd4da876010c59f expo-audio@58.0.11: 93691f7f59edb30a3bb2c23b489e605e7ea35506b1212d4a2ebbd1fd79079483 expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 expo-network@58.0.4: 159c2d760d1cd5102e95df51c20600111e7a72096ef0daea8215d50cae48bd98 @@ -469,7 +469,7 @@ importers: version: 8.2.0 electron-updater: specifier: 6.8.9 - version: 6.8.9(patch_hash=f9a64456ab8ea37f471e8479405f839823a57a277d8fa9dcd48ecdc84a749b6c)(supports-color@8.1.1) + version: 6.8.9(patch_hash=1eba5af25f72cb57b26810d051dcaf3c2fb243cd6b88d874bcd4da876010c59f)(supports-color@8.1.1) electron-webauthn: specifier: 'catalog:' version: 1.3.1(typescript@6.0.3) @@ -19084,7 +19084,7 @@ snapshots: electron-to-chromium@1.5.430: {} - electron-updater@6.8.9(patch_hash=f9a64456ab8ea37f471e8479405f839823a57a277d8fa9dcd48ecdc84a749b6c)(supports-color@8.1.1): + electron-updater@6.8.9(patch_hash=1eba5af25f72cb57b26810d051dcaf3c2fb243cd6b88d874bcd4da876010c59f)(supports-color@8.1.1): dependencies: builder-util-runtime: 9.7.0(supports-color@8.1.1) fs-extra: 10.1.0 From 67bdb58ead96c3b9c5abfd65dcce9bd68c548ac4 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:22:29 +0000 Subject: [PATCH 3/6] fix(updates): a cancelled digest check on a resumed download fails The digest check that accepts a complete file after a 416 read the file outside the download's cancellation token, so a cancel during the check still returned success. The check now runs inside the token and aborts its read when the download is cancelled. Co-Authored-By: Claude Haiku 5.5 --- .../src/electron/ElectronHttpExecutor.test.ts | 43 ++++++++++++++----- patches/electron-updater@6.8.9.patch | 22 ++++++---- pnpm-lock.yaml | 6 +-- 3 files changed, 50 insertions(+), 21 deletions(-) diff --git a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts index 39e77dd788a05..90873c88cb57d 100644 --- a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts +++ b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts @@ -14,6 +14,14 @@ type FakeRequest = NodeEvents.EventEmitter & { abort: () => void }; // electron-updater is CommonJS, so a spy goes on the module object its require() returns. const fsModule = NodeModule.createRequire(import.meta.url)("node:fs") as typeof NodeFS; +const openForReading = fsModule.createReadStream; +// electron-updater's own dependency, which apps/desktop does not declare. +const { CancellationToken, CancellationError } = NodeModule.createRequire( + NodeModule.createRequire(import.meta.url).resolve("electron-updater"), +)("builder-util-runtime") as { + CancellationToken: new () => DownloadOptions["cancellationToken"]; + CancellationError: new () => Error; +}; const RELEASE = "hello world"; // Larger than a file stream's buffer, so its "drain" marks a write of it as committed to disk. const PREFIX = "a".repeat(1 << 20); @@ -36,6 +44,7 @@ function startDownload(onDisk: string, release = RELEASE) { const destination = NodePath.join(dir, "update.AppImage"); NodeFS.writeFileSync(destination, onDisk); const createWriteStream = vi.spyOn(fsModule, "createWriteStream"); + const createReadStream = vi.spyOn(fsModule, "createReadStream"); const created = new NodeEvents.EventEmitter(); let requestCount = 0; const executor = new ElectronHttpExecutor(); @@ -46,16 +55,7 @@ function startDownload(onDisk: string, release = RELEASE) { created.emit("request", { request, headers: options.headers }); return request as unknown as Electron.ClientRequest; }; - const cancellationToken = { - cancelled: false, - createPromise: ( - callback: ( - resolve: (value: unknown) => void, - reject: (error: Error) => void, - onCancel: () => void, - ) => void, - ) => new Promise((resolve, reject) => callback(resolve, reject, () => {})), - } as unknown as DownloadOptions["cancellationToken"]; + const cancellationToken = new CancellationToken(); const first = NodeEvents.EventEmitter.once(created, "request"); const result = executor.download(new URL("https://example.com/update.AppImage"), destination, { cancellationToken, @@ -94,10 +94,21 @@ function startDownload(onDisk: string, release = RELEASE) { nextRequest, stallAfterWriting, result, + cancel: () => cancellationToken.cancel(), + // Resolves once the file is open for its digest check, before any of it is read. + readOpened: () => + new Promise((resolve) => { + createReadStream.mockImplementationOnce((...args) => { + const stream = openForReading(...args); + stream.once("open", () => resolve()); + return stream; + }); + }), requestCount: () => requestCount, read: () => NodeFS.readFileSync(destination, "utf8"), [Symbol.dispose]: () => { createWriteStream.mockRestore(); + createReadStream.mockRestore(); NodeFS.rmSync(dir, { recursive: true, force: true }); }, }; @@ -190,6 +201,18 @@ describe("ElectronHttpExecutor idle timeout", () => { expect(download.read()).toBe(LARGE_RELEASE); }); + it("fails a file past the end of the release when the caller cancels its digest check", async () => { + using download = startDownload("", LARGE_RELEASE); + + const { request } = await download.stallAfterWriting(LARGE_RELEASE); + const opened = download.readOpened(); + respond(request, 416, { "content-range": `bytes */${LARGE_RELEASE.length}` }, ""); + await opened; + download.cancel(); + + await expect(download.result).rejects.toBeInstanceOf(CancellationError); + }); + it("fails a file past the end of the release whose bytes do not match it", async () => { using download = startDownload("", LARGE_RELEASE); diff --git a/patches/electron-updater@6.8.9.patch b/patches/electron-updater@6.8.9.patch index 48e300582b468..754b5c6a91009 100644 --- a/patches/electron-updater@6.8.9.patch +++ b/patches/electron-updater@6.8.9.patch @@ -1,8 +1,8 @@ diff --git a/out/electronHttpExecutor.js b/out/electronHttpExecutor.js -index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..107ad84e11134deb49712b87f54cde706ebd7d48 100644 +index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..559c2dbd7e2744905a99905e4cc450295651e055 100644 --- a/out/electronHttpExecutor.js +++ b/out/electronHttpExecutor.js -@@ -3,7 +3,28 @@ Object.defineProperty(exports, "__esModule", { value: true }); +@@ -3,7 +3,34 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.ElectronHttpExecutor = exports.NET_SESSION_NAME = void 0; exports.getNetSession = getNetSession; const builder_util_runtime_1 = require("builder-util-runtime"); @@ -25,13 +25,19 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..107ad84e11134deb49712b87f54cde70 + } + return options.sha2 == null ? null : new builder_util_runtime_1.DigestTransform(options.sha2, "sha256", "hex"); +} -+function verifyFile(destination, digest) { -+ return stream_1.promises.pipeline((0, fs_1.createReadStream)(destination), digest, new stream_1.Writable({ write: (chunk, encoding, next) => next() })); ++function verifyFile(destination, digest, cancellationToken) { ++ return cancellationToken.createPromise((resolve, reject, onCancel) => { ++ const controller = new AbortController(); ++ onCancel(() => controller.abort()); ++ stream_1.promises ++ .pipeline((0, fs_1.createReadStream)(destination, { signal: controller.signal }), digest, new stream_1.Writable({ write: (chunk, encoding, next) => next() })) ++ .then(() => resolve(), reject); ++ }); +} function getNetSession() { return require("electron").session.fromPartition(exports.NET_SESSION_NAME, { cache: false, -@@ -16,26 +37,108 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { +@@ -16,26 +43,108 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { this.cachedSession = null; } async download(url, destination, options) { @@ -45,7 +51,7 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..107ad84e11134deb49712b87f54cde70 + // A 416 means the file already reaches the end of the release, so its digest decides. + const digest = offset > 0 && isRangeNotSatisfiable(e) ? createDigest(options) : null; + if (digest != null) { -+ await verifyFile(destination, digest); ++ await verifyFile(destination, digest, options.cancellationToken); + return destination; + } + if (attempt >= DOWNLOAD_STALL_RETRIES || !isDownloadStall(e)) { @@ -140,7 +146,7 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..107ad84e11134deb49712b87f54cde70 + callback(null); + return; + } -+ verifyFile(destination, fileDigest).then(() => callback(null), callback); ++ verifyFile(destination, fileDigest, options.cancellationToken).then(() => callback(null), callback); + }); + }); }, @@ -148,7 +154,7 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..107ad84e11134deb49712b87f54cde70 }, 0); }); } -@@ -61,6 +164,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { +@@ -61,6 +170,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { } return request; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8b20673dc9824..f30cbeaa3b1e3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -379,7 +379,7 @@ patchedDependencies: alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 - electron-updater@6.8.9: 1eba5af25f72cb57b26810d051dcaf3c2fb243cd6b88d874bcd4da876010c59f + electron-updater@6.8.9: 6833557896e0f83fac33ad17d8c6bb3bab59f18778cb672e6431e969ad2a4c95 expo-audio@58.0.11: 93691f7f59edb30a3bb2c23b489e605e7ea35506b1212d4a2ebbd1fd79079483 expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 expo-network@58.0.4: 159c2d760d1cd5102e95df51c20600111e7a72096ef0daea8215d50cae48bd98 @@ -469,7 +469,7 @@ importers: version: 8.2.0 electron-updater: specifier: 6.8.9 - version: 6.8.9(patch_hash=1eba5af25f72cb57b26810d051dcaf3c2fb243cd6b88d874bcd4da876010c59f)(supports-color@8.1.1) + version: 6.8.9(patch_hash=6833557896e0f83fac33ad17d8c6bb3bab59f18778cb672e6431e969ad2a4c95)(supports-color@8.1.1) electron-webauthn: specifier: 'catalog:' version: 1.3.1(typescript@6.0.3) @@ -19084,7 +19084,7 @@ snapshots: electron-to-chromium@1.5.430: {} - electron-updater@6.8.9(patch_hash=1eba5af25f72cb57b26810d051dcaf3c2fb243cd6b88d874bcd4da876010c59f)(supports-color@8.1.1): + electron-updater@6.8.9(patch_hash=6833557896e0f83fac33ad17d8c6bb3bab59f18778cb672e6431e969ad2a4c95)(supports-color@8.1.1): dependencies: builder-util-runtime: 9.7.0(supports-color@8.1.1) fs-extra: 10.1.0 From f4564e73d6a14a9fb389dc833a07f6884ed4ab6f Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:58:40 +0000 Subject: [PATCH 4/6] fix(updates): resume only bytes this download wrote The desktop retry resumed from whatever file was at the destination, so the differential downloader's leftover output could poison the full download after a stall before headers. It now tracks the bytes its own writers closed with, keeps that count across header-only failures, settles a cancel only after its writer closes, and never writes a response that arrives after settling. The server's SHA256SUMS fetch restarts at byte 0 on retry; only the archive, which its checksum verifies, resumes with Range or accepts 416. Co-Authored-By: Claude Opus 5.5 --- .../src/electron/ElectronHttpExecutor.test.ts | 81 +++++----- apps/server/src/cloud/pinnedRuntime.test.ts | 24 ++- apps/server/src/cloud/pinnedRuntime.ts | 20 ++- patches/electron-updater@6.8.9.patch | 151 +++++++++++------- pnpm-lock.yaml | 6 +- 5 files changed, 171 insertions(+), 111 deletions(-) diff --git a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts index 90873c88cb57d..fb7e947019bb4 100644 --- a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts +++ b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts @@ -26,6 +26,7 @@ const RELEASE = "hello world"; // Larger than a file stream's buffer, so its "drain" marks a write of it as committed to disk. const PREFIX = "a".repeat(1 << 20); const LARGE_RELEASE = `${PREFIX}world`; +const RESUMED_RANGE = `bytes ${PREFIX.length}-${LARGE_RELEASE.length - 1}/${LARGE_RELEASE.length}`; function startRequest() { const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn() }); @@ -38,7 +39,7 @@ function startRequest() { return { request, response, reject }; } -// The temp update file already holds `onDisk`, as if an earlier attempt had written it. +// The temp update file already holds `onDisk`, as the differential downloader's output can. function startDownload(onDisk: string, release = RELEASE) { const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "electron-http-executor-")); const destination = NodePath.join(dir, "update.AppImage"); @@ -178,24 +179,38 @@ describe("ElectronHttpExecutor idle timeout", () => { expect(reject).not.toHaveBeenCalled(); }); - it("resumes a stalled download from the bytes already written", async () => { - using download = startDownload("", LARGE_RELEASE); - - const { request, headers } = await download.stallAfterWriting(PREFIX); - expect(headers.Range).toBe(`bytes=${PREFIX.length}-`); - const range = `bytes ${PREFIX.length}-${LARGE_RELEASE.length - 1}/${LARGE_RELEASE.length}`; - respond(request, 206, { "content-range": range }, "world"); - - await expect(download.result).resolves.toBe(download.destination); - expect(download.read()).toBe(LARGE_RELEASE); - }); - - it("accepts a file that already holds every byte when the retry is past the end", async () => { + it.each([ + { + name: "resumes a stalled download from the bytes already written", + written: PREFIX, + retry: { status: 206, headers: { "content-range": RESUMED_RANGE }, body: "world" }, + }, + { + name: "accepts a file that already holds every byte when the retry is past the end", + written: LARGE_RELEASE, + retry: { + status: 416, + headers: { "content-range": `bytes */${LARGE_RELEASE.length}` }, + body: "", + }, + }, + { + name: "starts over when the server ignores the range", + written: PREFIX, + retry: { status: 200, headers: {}, body: LARGE_RELEASE }, + }, + ])("$name", async ({ written, retry: { status, headers, body } }) => { using download = startDownload("", LARGE_RELEASE); - const { request, headers } = await download.stallAfterWriting(LARGE_RELEASE); - expect(headers.Range).toBe(`bytes=${LARGE_RELEASE.length}-`); - respond(request, 416, { "content-range": `bytes */${LARGE_RELEASE.length}` }, ""); + const { request: unanswered, headers: first } = await download.stallAfterWriting(written); + expect(first.Range).toBe(`bytes=${written.length}-`); + // A retry that fails before any response still resumes after the bytes the first one wrote. + const retry = download.nextRequest(); + unanswered.emit("error", new Error("net::ERR_TIMED_OUT")); + await vi.advanceTimersByTimeAsync(4_000); + const { request, headers: second } = await retry; + expect(second.Range).toBe(`bytes=${written.length}-`); + respond(request, status, headers, body); await expect(download.result).resolves.toBe(download.destination); expect(download.read()).toBe(LARGE_RELEASE); @@ -223,38 +238,21 @@ describe("ElectronHttpExecutor idle timeout", () => { expect(download.requestCount()).toBe(2); }); - it("starts over when the server ignores the range", async () => { - using download = startDownload("HELLO "); - const [{ request: first }] = await download.first; - const retry = download.nextRequest(); - - first.emit("error", new Error("net::ERR_TIMED_OUT")); - await vi.advanceTimersByTimeAsync(2_000); - const { request, headers } = await retry; - expect(headers.Range).toBe("bytes=6-"); - respond(request, 200, {}, RELEASE); - - await expect(download.result).resolves.toBe(download.destination); - expect(download.read()).toBe(RELEASE); - }); - it("fails a resumed download whose earlier bytes do not match the release", async () => { - using download = startDownload("HELLO "); - const retry = download.nextRequest(); + using download = startDownload("", LARGE_RELEASE); - await vi.advanceTimersByTimeAsync(60_000 + 2_000); - const { request } = await retry; - respond(request, 206, { "content-range": "bytes 6-10/11" }, "world"); + const { request } = await download.stallAfterWriting(`b${PREFIX.slice(1)}`); + respond(request, 206, { "content-range": RESUMED_RANGE }, "world"); await expect(download.result).rejects.toMatchObject({ code: "ERR_CHECKSUM_MISMATCH" }); }); - it("gives up after three retries", async () => { - using download = startDownload(""); + it("gives up after three retries without resuming from a file it did not write", async () => { + using download = startDownload("differential output"); for (const backoff of [2_000, 4_000, 8_000]) { const retry = download.nextRequest(); await vi.advanceTimersByTimeAsync(60_000 + backoff); - await retry; + expect((await retry).headers.Range).toBeUndefined(); } const outcome = expect(download.result).rejects.toThrow("Request timed out"); @@ -264,13 +262,12 @@ describe("ElectronHttpExecutor idle timeout", () => { }); it("does not retry a request that fails for another reason", async () => { - using download = startDownload("hello "); + using download = startDownload(""); const [{ request }] = await download.first; const outcome = expect(download.result).rejects.toThrow("net::ERR_CONNECTION_REFUSED"); request.emit("error", new Error("net::ERR_CONNECTION_REFUSED")); await outcome; - await vi.advanceTimersByTimeAsync(120_000); expect(download.requestCount()).toBe(1); }); }); diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 2f087c33ea32f..bc888066f4a9b 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -262,7 +262,9 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-body-" }); const checksums = yield* validChecksums; const ranges: Array = []; + const checksumRanges: Array = []; const progress: PinnedRuntimeProgress[] = []; + const checksumsRequested = yield* Deferred.make(); const archiveRequested = yield* Deferred.make(); const total = archiveBytes.length; const heldBytes = @@ -280,7 +282,24 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { arch: "x64", httpClient: HttpClient.make((request) => { if (request.url.endsWith("/SHA256SUMS")) { - return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(checksums))); + checksumRanges.push(request.headers["range"]); + const response = HttpClientResponse.fromWeb(request, new Response(checksums)); + if (checksumRanges.length > 1) return Effect.succeed(response); + Deferred.doneUnsafe(checksumsRequested, Effect.void); + // The checksums fail once after a prefix, which their retry must not resume from. + const failingBody = Stream.concat( + Stream.make(new TextEncoder().encode(checksums).slice(0, 8)), + Stream.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.DecodeError({ request, response }), + }), + ), + ); + return Effect.sleep("1 second").pipe( + Effect.as( + Object.create(response, { stream: { value: failingBody } }), + ), + ); } const range = request.headers["range"]; ranges.push(range); @@ -330,10 +349,13 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { validate: () => Effect.void, onProgress: (event) => progress.push(event), }).pipe(Effect.forkScoped); + yield* Deferred.await(checksumsRequested); + yield* TestClock.adjust(Duration.seconds(3)); yield* Deferred.await(archiveRequested); // The one-minute stall bound, then the first two-second retry backoff. yield* TestClock.adjust(Duration.seconds(first === "body fails" ? 3 : 63)); const result = yield* Fiber.join(install).pipe(Effect.result); + assert.deepEqual(checksumRanges, [undefined, undefined]); assert.deepEqual(ranges, [ undefined, first === "headers stall" ? undefined : `bytes=${heldBytes.length}-`, diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index 24455a4b68810..0e8ba573512aa 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -150,6 +150,8 @@ const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")( httpClient: HttpClient.HttpClient, url: string, step: string, + // Only a digest-checked asset resumes; anything else restarts at byte 0 on each retry. + resume: boolean, onProgress?: (progress: PinnedRuntimeProgress) => void, ) { // Bytes from earlier attempts outlive the retry so a stalled download resumes with Range. @@ -157,17 +159,21 @@ const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")( let received = 0; // Bound stalls while holding the install lock, but allow transfers that keep // receiving bytes to finish regardless of their total duration. - return yield* Effect.suspend(() => - httpClient.execute( + return yield* Effect.suspend(() => { + if (!resume) { + chunks = []; + received = 0; + } + return httpClient.execute( received > 0 ? HttpClientRequest.get(url).pipe( HttpClientRequest.setHeader("range", `bytes=${received}-`), ) : HttpClientRequest.get(url), - ), - ).pipe( - // A resume answered 416 asked past the end, so the held bytes are the whole file; - // the archive checksum still rejects a wrong one. + ); + }).pipe( + // A resume answered 416 has nothing after the held bytes to send; the archive + // checksum decides whether they are the whole file. Effect.filterOrElse( (response) => received > 0 && response.status === 416, HttpClientResponse.filterStatusOk, @@ -255,6 +261,7 @@ const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(fun httpClient, cliReleaseAssetUrl(input.version, fileName, input.releaseBaseUrl), "downloading the t3 release archive", + true, input.onProgress, ); input.onProgress?.({ stage: "verify" }); @@ -314,6 +321,7 @@ const publishedArchive = Effect.fn("cloud.pinned_runtime.published_archive")(fun input.httpClient, cliReleaseAssetUrl(input.version, CLI_RELEASE_CHECKSUMS_FILE, input.releaseBaseUrl), "downloading the t3 release checksums", + false, ), ), ); diff --git a/patches/electron-updater@6.8.9.patch b/patches/electron-updater@6.8.9.patch index 754b5c6a91009..74ada590655b9 100644 --- a/patches/electron-updater@6.8.9.patch +++ b/patches/electron-updater@6.8.9.patch @@ -1,5 +1,5 @@ diff --git a/out/electronHttpExecutor.js b/out/electronHttpExecutor.js -index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..559c2dbd7e2744905a99905e4cc450295651e055 100644 +index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..e6fb0b8aafda6ae0797d3127b5aa661b0d202ca5 100644 --- a/out/electronHttpExecutor.js +++ b/out/electronHttpExecutor.js @@ -3,7 +3,34 @@ Object.defineProperty(exports, "__esModule", { value: true }); @@ -9,7 +9,7 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..559c2dbd7e2744905a99905e4cc45029 +const fs_1 = require("fs"); +const stream_1 = require("stream"); exports.NET_SESSION_NAME = "electron-updater"; -+// A stall on a slow link is retried, resuming from the bytes already in the file. ++// A stall on a slow link is retried, resuming after the bytes earlier attempts wrote. +const DOWNLOAD_STALL_RETRIES = 3; +function isDownloadStall(error) { + return error != null && (error.message === "Request timed out" || error.message === "net::ERR_TIMED_OUT"); @@ -37,18 +37,21 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..559c2dbd7e2744905a99905e4cc45029 function getNetSession() { return require("electron").session.fromPartition(exports.NET_SESSION_NAME, { cache: false, -@@ -16,26 +43,108 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { +@@ -16,27 +43,133 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { this.cachedSession = null; } async download(url, destination, options) { - return await options.cancellationToken.createPromise((resolve, reject, onCancel) => { ++ // Only bytes this call wrote are resumed: the differential downloader leaves its own output ++ // at the same destination, and an attempt that fails before headers keeps the last count. ++ const held = { bytes: 0 }; + for (let attempt = 0;; attempt++) { -+ const offset = attempt === 0 ? 0 : await fs_1.promises.stat(destination).then(it => it.size, () => 0); ++ const offset = held.bytes; + try { -+ return await this.downloadFrom(url, destination, options, offset); ++ return await this.downloadFrom(url, destination, options, held); + } + catch (e) { -+ // A 416 means the file already reaches the end of the release, so its digest decides. ++ // A 416 refuses the range; the digest decides whether the file already holds the release. + const digest = offset > 0 && isRangeNotSatisfiable(e) ? createDigest(options) : null; + if (digest != null) { + await verifyFile(destination, digest, options.cancellationToken); @@ -66,8 +69,10 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..559c2dbd7e2744905a99905e4cc45029 + } + // Appends from `offset` when the server answers the Range with 206, then checks the digest over + // the whole file so the bytes from earlier attempts are verified too. A 200 starts over. -+ downloadFrom(url, destination, options, offset) { -+ return options.cancellationToken.createPromise((resolve, reject, onCancel) => { ++ downloadFrom(url, destination, options, held) { ++ const offset = held.bytes; ++ const cancellationToken = options.cancellationToken; ++ return new Promise((resolve, reject) => { const requestOptions = { - headers: options.headers || undefined, + headers: offset > 0 ? { ...options.headers, Range: `bytes=${offset}-` } : options.headers || undefined, @@ -75,6 +80,20 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..559c2dbd7e2744905a99905e4cc45029 }; (0, builder_util_runtime_1.configureRequestUrl)(url, requestOptions); (0, builder_util_runtime_1.configureRequestOptions)(requestOptions); +- this.doDownload(requestOptions, { +- destination, +- options, +- onCancel, +- callback: error => { +- if (error == null) { +- resolve(destination); +- } +- else { +- reject(error); +- } +- }, +- responseHandler: null, +- }, 0); + let fileOut = null; + let upstream = null; + let settled = false; @@ -83,6 +102,7 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..559c2dbd7e2744905a99905e4cc45029 + return; + } + settled = true; ++ cancellationToken.removeListener("cancel", cancel); + const settle = () => (error == null ? resolve(destination) : reject(error)); + if (fileOut == null || fileOut.closed) { + settle(); @@ -95,66 +115,79 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..559c2dbd7e2744905a99905e4cc45029 + fileOut.end(); + } + }; - this.doDownload(requestOptions, { - destination, - options, - onCancel, -- callback: error => { -- if (error == null) { -- resolve(destination); -+ callback, -+ responseHandler: response => { -+ const resumed = offset > 0 && response.statusCode === 206; -+ const contentRange = (0, builder_util_runtime_1.safeGetHeader)(response, "content-range"); -+ if (resumed && (contentRange == null || !contentRange.startsWith(`bytes ${offset}-`))) { -+ callback(new Error(`Cannot resume download at byte ${offset}, got Content-Range ${contentRange}`)); -+ return; -+ } -+ const sha2Header = (0, builder_util_runtime_1.safeGetHeader)(response, "X-Checksum-Sha2"); -+ if (sha2Header != null && options.sha2 != null && sha2Header !== options.sha2) { -+ callback(new Error(`checksum mismatch: expected ${options.sha2} but got ${sha2Header} (X-Checksum-Sha2 header)`)); -+ return; -+ } -+ const streams = []; -+ const contentLength = (0, builder_util_runtime_1.safeGetHeader)(response, "content-length"); -+ if (options.onProgress != null && contentLength != null) { -+ const progress = new builder_util_runtime_1.ProgressCallbackTransform((resumed ? offset : 0) + parseInt(contentLength, 10), options.cancellationToken, options.onProgress); -+ progress.transferred = resumed ? offset : 0; -+ streams.push(progress); - } -- else { -- reject(error); -+ const digest = resumed ? null : createDigest(options); -+ if (digest != null) { -+ streams.push(digest); - } -+ fileOut = (0, fs_1.createWriteStream)(destination, { flags: resumed ? "a" : "w" }); -+ upstream = response; -+ for (const stream of streams) { -+ stream.on("error", callback); -+ upstream = upstream.pipe(stream); -+ } -+ fileOut.on("error", callback); -+ upstream.pipe(fileOut); -+ fileOut.on("finish", () => { ++ // doDownload never calls onCancel, so a cancel settles here once the file is closed, and a ++ // response that arrives after it is not written. The request runs on until its idle timeout. ++ const cancel = () => callback(new builder_util_runtime_1.CancellationError()); ++ cancellationToken.onCancel(cancel); ++ if (settled) { ++ return; ++ } ++ try { ++ this.doDownload(requestOptions, { ++ destination, ++ options, ++ callback, ++ responseHandler: response => { + if (settled) { + return; + } ++ const resumed = offset > 0 && response.statusCode === 206; ++ const contentRange = (0, builder_util_runtime_1.safeGetHeader)(response, "content-range"); ++ if (resumed && (contentRange == null || !contentRange.startsWith(`bytes ${offset}-`))) { ++ callback(new Error(`Cannot resume download at byte ${offset}, got Content-Range ${contentRange}`)); ++ return; ++ } ++ const sha2Header = (0, builder_util_runtime_1.safeGetHeader)(response, "X-Checksum-Sha2"); ++ if (sha2Header != null && options.sha2 != null && sha2Header !== options.sha2) { ++ callback(new Error(`checksum mismatch: expected ${options.sha2} but got ${sha2Header} (X-Checksum-Sha2 header)`)); ++ return; ++ } ++ const start = resumed ? offset : 0; ++ const streams = []; ++ const contentLength = (0, builder_util_runtime_1.safeGetHeader)(response, "content-length"); ++ if (options.onProgress != null && contentLength != null) { ++ const progress = new builder_util_runtime_1.ProgressCallbackTransform(start + parseInt(contentLength, 10), options.cancellationToken, options.onProgress); ++ progress.transferred = start; ++ streams.push(progress); ++ } ++ const digest = resumed ? null : createDigest(options); ++ if (digest != null) { ++ streams.push(digest); ++ } ++ fileOut = (0, fs_1.createWriteStream)(destination, { flags: resumed ? "a" : "w" }); + fileOut.once("close", () => { -+ const fileDigest = resumed ? createDigest(options) : null; -+ if (fileDigest == null) { -+ callback(null); ++ held.bytes = start + fileOut.bytesWritten; ++ }); ++ upstream = response; ++ for (const stream of streams) { ++ stream.on("error", callback); ++ upstream = upstream.pipe(stream); ++ } ++ fileOut.on("error", callback); ++ upstream.pipe(fileOut); ++ fileOut.on("finish", () => { ++ if (settled) { + return; + } -+ verifyFile(destination, fileDigest, options.cancellationToken).then(() => callback(null), callback); ++ fileOut.once("close", () => { ++ const fileDigest = resumed ? createDigest(options) : null; ++ if (fileDigest == null) { ++ callback(null); ++ return; ++ } ++ verifyFile(destination, fileDigest, options.cancellationToken).then(() => callback(null), callback); ++ }); + }); -+ }); - }, -- responseHandler: null, - }, 0); ++ }, ++ }, 0); ++ } ++ catch (error) { ++ callback(error); ++ } }); } -@@ -61,6 +170,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { + createRequest(options, callback) { +@@ -61,6 +194,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { } return request; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 31772a976e1e2..e111de9504438 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -378,7 +378,7 @@ patchedDependencies: alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 - electron-updater@6.8.9: 6833557896e0f83fac33ad17d8c6bb3bab59f18778cb672e6431e969ad2a4c95 + electron-updater@6.8.9: 91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155 expo-audio@58.0.11: 93691f7f59edb30a3bb2c23b489e605e7ea35506b1212d4a2ebbd1fd79079483 expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 expo-network@58.0.4: 159c2d760d1cd5102e95df51c20600111e7a72096ef0daea8215d50cae48bd98 @@ -468,7 +468,7 @@ importers: version: 8.2.0 electron-updater: specifier: 6.8.9 - version: 6.8.9(patch_hash=6833557896e0f83fac33ad17d8c6bb3bab59f18778cb672e6431e969ad2a4c95)(supports-color@8.1.1) + version: 6.8.9(patch_hash=91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155)(supports-color@8.1.1) electron-webauthn: specifier: 'catalog:' version: 1.3.1(typescript@6.0.3) @@ -19098,7 +19098,7 @@ snapshots: electron-to-chromium@1.5.430: {} - electron-updater@6.8.9(patch_hash=6833557896e0f83fac33ad17d8c6bb3bab59f18778cb672e6431e969ad2a4c95)(supports-color@8.1.1): + electron-updater@6.8.9(patch_hash=91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155)(supports-color@8.1.1): dependencies: builder-util-runtime: 9.7.0(supports-color@8.1.1) fs-extra: 10.1.0 From 0c7e72df5a74774c66a2a6624678319b89154f00 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:42:46 +0000 Subject: [PATCH 5/6] fix(server): a resumed archive download that ends early is retried A server may answer a resume with a 206 that ends before the total its Content-Range declares. The bytes it sent are kept and the retry asks for the rest, so the checksum sees the whole archive. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/cloud/pinnedRuntime.test.ts | 50 +++++++++++++++------ apps/server/src/cloud/pinnedRuntime.ts | 17 +++++++ 2 files changed, 53 insertions(+), 14 deletions(-) diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index bc888066f4a9b..c885a5dfaea5a 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -238,7 +238,12 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { it.effect.each([ { name: "body fails after the host answered", first: "body fails", honorsRange: true }, - { name: "body stalls", first: "body stalls", honorsRange: true }, + { + name: "body stalls and its resume ends early", + first: "body stalls", + honorsRange: true, + shortResume: true, + }, { name: "body stalls on a host that ignores Range", first: "body stalls", honorsRange: false }, { name: "response headers stall", first: "headers stall", honorsRange: true }, { @@ -257,6 +262,7 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { Effect.gen(function* () { const { first, honorsRange } = row; const held = "held" in row ? row.held : "prefix"; + const shortResume = "shortResume" in row; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-body-" }); @@ -266,6 +272,7 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { const progress: PinnedRuntimeProgress[] = []; const checksumsRequested = yield* Deferred.make(); const archiveRequested = yield* Deferred.make(); + const shortResumeRequested = yield* Deferred.make(); const total = archiveBytes.length; const heldBytes = held === "prefix" @@ -305,20 +312,29 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { ranges.push(range); if (ranges.length > 1) { const start = honorsRange ? Number(/^bytes=(\d+)-$/.exec(range ?? "")?.[1] ?? 0) : 0; - return Effect.succeed( - HttpClientResponse.fromWeb( - request, - start >= total - ? new Response("", { - status: 416, - headers: { "content-range": `bytes */${total}` }, + // A short resume stops one byte early; the next retry asks for that byte. + const end = shortResume && ranges.length === 2 ? total - 1 : total; + const response = HttpClientResponse.fromWeb( + request, + start >= total + ? new Response("", { + status: 416, + headers: { "content-range": `bytes */${total}` }, + }) + : start > 0 + ? new Response(archiveBytes.slice(start, end), { + status: 206, + headers: { "content-range": `bytes ${start}-${end - 1}/${total}` }, }) - : start > 0 - ? new Response(archiveBytes.slice(start), { - status: 206, - headers: { "content-range": `bytes ${start}-${total - 1}/${total}` }, - }) - : new Response(archiveBytes, { headers: { "content-length": `${total}` } }), + : new Response(archiveBytes, { headers: { "content-length": `${total}` } }), + ); + if (end === total) return Effect.succeed(response); + Deferred.doneUnsafe(shortResumeRequested, Effect.void); + // An Effect stream keeps the body, and so the retry wait after it, on the test clock. + const body = Stream.make(archiveBytes.slice(start, end)); + return Effect.sleep("1 second").pipe( + Effect.as( + Object.create(response, { stream: { value: body } }), ), ); } @@ -354,11 +370,17 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { yield* Deferred.await(archiveRequested); // The one-minute stall bound, then the first two-second retry backoff. yield* TestClock.adjust(Duration.seconds(first === "body fails" ? 3 : 63)); + if (shortResume) { + yield* Deferred.await(shortResumeRequested); + // Its one-second delay, then the second, four-second backoff. + yield* TestClock.adjust(Duration.seconds(5)); + } const result = yield* Fiber.join(install).pipe(Effect.result); assert.deepEqual(checksumRanges, [undefined, undefined]); assert.deepEqual(ranges, [ undefined, first === "headers stall" ? undefined : `bytes=${heldBytes.length}-`, + ...(shortResume ? [`bytes=${total - 1}-`] : []), ]); if (held === "wrong") { assert.equal(result._tag, "Failure"); diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index 0e8ba573512aa..08180f80a67ab 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -206,6 +206,7 @@ const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")( ); const total = Number.isFinite(length) && length > 0 ? length : undefined; onProgress?.({ stage: "download", received, total }); + const attemptStart = received; yield* response.stream.pipe( Stream.timeoutOrElse({ duration: PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT, @@ -219,6 +220,22 @@ const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")( }), ), ); + // A server may end a 206 before the declared total; a retry asks for the rest. + if ( + resume && + contentRange !== null && + total !== undefined && + received > attemptStart && + received < total + ) { + return yield* new HttpClientError.HttpClientError({ + reason: new HttpClientError.DecodeError({ + request: response.request, + response, + description: "partial content ended before the declared total", + }), + }); + } if (total === undefined && received > 0) { onProgress?.({ stage: "download", received, total: received }); } From 6b81914187e81981245341b3113cedb43484effc Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:42:22 +0000 Subject: [PATCH 6/6] test(server): remove overlapping updater checksum case Cover HTTP 416 recovery and archive checksum failures separately. The installer verifies the checksum after every successful download. --- apps/server/src/cloud/pinnedRuntime.test.ts | 29 +++------------------ 1 file changed, 4 insertions(+), 25 deletions(-) diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index c885a5dfaea5a..7e4d69482eebf 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -250,18 +250,11 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { name: "whole body arrives and then stalls", first: "body stalls", honorsRange: true, - held: "whole", - }, - { - name: "whole but wrong body arrives and then fails", - first: "body fails", - honorsRange: true, - held: "wrong", + wholeArchive: true, }, ] as const)("resumes a release archive download when its $name", (row) => Effect.gen(function* () { const { first, honorsRange } = row; - const held = "held" in row ? row.held : "prefix"; const shortResume = "shortResume" in row; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -274,12 +267,7 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { const archiveRequested = yield* Deferred.make(); const shortResumeRequested = yield* Deferred.make(); const total = archiveBytes.length; - const heldBytes = - held === "prefix" - ? archiveBytes.slice(0, 4) - : held === "whole" - ? archiveBytes - : archiveBytes.map((byte) => byte ^ 1); + const heldBytes = "wholeArchive" in row ? archiveBytes : archiveBytes.slice(0, 4); const install = yield* ensurePinnedRuntimeInstalled({ baseDir, version, @@ -375,23 +363,14 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { // Its one-second delay, then the second, four-second backoff. yield* TestClock.adjust(Duration.seconds(5)); } - const result = yield* Fiber.join(install).pipe(Effect.result); + const paths = yield* Fiber.join(install); assert.deepEqual(checksumRanges, [undefined, undefined]); assert.deepEqual(ranges, [ undefined, first === "headers stall" ? undefined : `bytes=${heldBytes.length}-`, ...(shortResume ? [`bytes=${total - 1}-`] : []), ]); - if (held === "wrong") { - assert.equal(result._tag, "Failure"); - if (result._tag !== "Failure") return; - assert.instanceOf(result.failure, PinnedRuntimeInstallError); - assert.equal(result.failure.step, "verifying the t3 release archive checksum"); - return; - } - assert.equal(result._tag, "Success"); - if (result._tag !== "Success") return; - assert.equal(yield* fs.readFileString(result.success.sentinelPath), `${version}\n`); + assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`); assert.deepEqual( progress.findLast((event) => event.stage === "download"), {