diff --git a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts index 0a37f621dd601..fb7e947019bb4 100644 --- a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts +++ b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts @@ -1,8 +1,33 @@ // @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 NodeModule from "node:module"; +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 }; + +// 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); +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() }); const response = new NodeEvents.EventEmitter(); @@ -14,6 +39,103 @@ function startRequest() { return { request, response, reject }; } +// 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"); + 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(); + 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 = new 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 }; + }; + // 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, + 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 }); + }, + }; +} + +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, +) { + startResponse(request, statusCode, { "content-length": String(body.length), ...headers }).end( + body, + ); +} + describe("ElectronHttpExecutor idle timeout", () => { beforeEach(() => { vi.useFakeTimers(); @@ -56,4 +178,96 @@ describe("ElectronHttpExecutor idle timeout", () => { expect(request.abort).not.toHaveBeenCalled(); expect(reject).not.toHaveBeenCalled(); }); + + 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: 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); + }); + + 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); + + 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("fails a resumed download whose earlier bytes do not match the release", async () => { + using download = startDownload("", LARGE_RELEASE); + + 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 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); + expect((await retry).headers.Range).toBeUndefined(); + } + 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(""); + 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; + 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..7e4d69482eebf 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -236,14 +236,38 @@ 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 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 }, + { + name: "whole body arrives and then stalls", + first: "body stalls", + honorsRange: true, + wholeArchive: true, + }, + ] as const)("resumes a release archive download when its $name", (row) => Effect.gen(function* () { + const { first, honorsRange } = row; + 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-" }); const checksums = yield* validChecksums; - let archiveRequests = 0; + const ranges: Array = []; + const checksumRanges: Array = []; + const progress: PinnedRuntimeProgress[] = []; + const checksumsRequested = yield* Deferred.make(); const archiveRequested = yield* Deferred.make(); + const shortResumeRequested = yield* Deferred.make(); + const total = archiveBytes.length; + const heldBytes = "wholeArchive" in row ? archiveBytes : archiveBytes.slice(0, 4); const install = yield* ensurePinnedRuntimeInstalled({ baseDir, version, @@ -252,21 +276,72 @@ 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")) { + 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); + if (ranges.length > 1) { + const start = honorsRange ? Number(/^bytes=(\d+)-$/.exec(range ?? "")?.[1] ?? 0) : 0; + // 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}` }, + }) + : 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 } }), + ), + ); + } + 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 }), - }), - ), + Stream.make(heldBytes), + 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 +351,34 @@ 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* 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)); + if (shortResume) { + yield* Deferred.await(shortResumeRequested); + // Its one-second delay, then the second, four-second backoff. + yield* TestClock.adjust(Duration.seconds(5)); + } 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}-`] : []), + ]); assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`); - assert.equal(archiveRequests, 2); + 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..08180f80a67ab 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -126,54 +126,120 @@ 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 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, 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. + 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( - Effect.flatMap(HttpClientResponse.filterStatusOk), + 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 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, + ), Effect.timeout(PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT), Effect.flatMap( Effect.fn(function* (response) { - const length = Number(response.headers["content-length"]); + if (response.status === 416) return concatChunks(chunks, received); + 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( + const attemptStart = received; + 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, ); + // 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 }); } - 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 }), @@ -212,6 +278,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" }); @@ -271,6 +338,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 1e343589cb509..74ada590655b9 100644 --- a/patches/electron-updater@6.8.9.patch +++ b/patches/electron-updater@6.8.9.patch @@ -1,8 +1,193 @@ diff --git a/out/electronHttpExecutor.js b/out/electronHttpExecutor.js -index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..c298ffe7808c421c29e16f1e2ba8510f0cd31142 100644 +index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..e6fb0b8aafda6ae0797d3127b5aa661b0d202ca5 100644 --- a/out/electronHttpExecutor.js +++ b/out/electronHttpExecutor.js -@@ -61,6 +61,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { +@@ -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"); ++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 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"); ++} ++// 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, 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,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 = held.bytes; ++ try { ++ return await this.downloadFrom(url, destination, options, held); ++ } ++ catch (e) { ++ // 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); ++ return destination; ++ } ++ 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, 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, + redirect: "manual", + }; + (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; ++ const callback = error => { ++ if (settled) { ++ return; ++ } ++ settled = true; ++ cancellationToken.removeListener("cancel", cancel); ++ 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(); ++ } ++ }; ++ // 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", () => { ++ 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; ++ } ++ fileOut.once("close", () => { ++ const fileDigest = resumed ? createDigest(options) : null; ++ if (fileDigest == null) { ++ callback(null); ++ return; ++ } ++ verifyFile(destination, fileDigest, options.cancellationToken).then(() => callback(null), callback); ++ }); ++ }); ++ }, ++ }, 0); ++ } ++ catch (error) { ++ callback(error); ++ } + }); + } + 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 f1772ae8410fd..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: 5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e + 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=5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e)(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=5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e)(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