Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
214 changes: 214 additions & 0 deletions apps/desktop/src/electron/ElectronHttpExecutor.test.ts
Original file line number Diff line number Diff line change
@@ -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<ElectronHttpExecutor["download"]>[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();
Expand All @@ -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<string, string> }, 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<string, string> };
};
// 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<void>((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<string, string>) {
const response = Object.assign(new NodeStream.PassThrough(), {
statusCode,
statusMessage: "",
headers,
});
request.emit("response", response);
return response;
}

function respond(
request: FakeRequest,
statusCode: number,
headers: Record<string, string>,
body: string,
) {
startResponse(request, statusCode, { "content-length": String(body.length), ...headers }).end(
body,
);
}

describe("ElectronHttpExecutor idle timeout", () => {
beforeEach(() => {
vi.useFakeTimers();
Expand Down Expand Up @@ -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);
});
});
125 changes: 111 additions & 14 deletions apps/server/src/cloud/pinnedRuntime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | undefined> = [];
const checksumRanges: Array<string | undefined> = [];
const progress: PinnedRuntimeProgress[] = [];
const checksumsRequested = yield* Deferred.make<void>();
const archiveRequested = yield* Deferred.make<void>();
const shortResumeRequested = yield* Deferred.make<void>();
const total = archiveBytes.length;
const heldBytes = "wholeArchive" in row ? archiveBytes : archiveBytes.slice(0, 4);
const install = yield* ensurePinnedRuntimeInstalled({
baseDir,
version,
Expand All @@ -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<HttpClientResponse.HttpClientResponse>(
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<HttpClientResponse.HttpClientResponse>(
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<HttpClientResponse.HttpClientResponse>(
Expand All @@ -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,
},
);
}),
);

Expand Down
Loading
Loading