GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Merge origin/main into t3/1211-cancelling-a-transcription-model-downloa · pingdotgg/t3code@6cd4df4

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps
    • desktop/src/electron
      • ElectronHttpExecutor.test.ts
    • server/src
      • cloud
        • pinnedRuntime.test.ts
        • pinnedRuntime.ts
      • orchestration-v2
        • ProjectionStore.test.ts
        • ProjectionStore.ts
        • deferredCommandMessage.ts
      • persistence
        • Migrations.ts
        • Migrations
          • 100_TurnStartReadIndexes.ts
        • reconcileV2PreviewMigration.test.ts
    • web/src
      • components/chat
        • MessagesTimeline.logic.test.ts
        • MessagesTimeline.logic.ts
      • filePathDisplay.test.ts
      • filePathDisplay.ts
      • workspaceBasenameLookup.test.ts
  • packages/client-runtime/src
    • workspaceBasenameLookup.ts
  • patches
    • [email protected]
  • pnpm-lock.yaml
  • scripts/scenarios
    • citation-finds-file-in-overlapping-projects.e2e.ts
    • home-path-tool-rows-show-as-written.e2e.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/desktop/src/electron/ElectronHttpExecutor.test.ts‎

Copy file name to clipboardExpand all lines: apps/desktop/src/electron/ElectronHttpExecutor.test.ts
+214Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,33 @@
11
// @effect-diagnostics nodeBuiltinImport:off -- Fake Electron net request and response emitters.
2+
import * as NodeCrypto from "node:crypto";
23
import * as NodeEvents from "node:events";
4+
import * as NodeFS from "node:fs";
5+
import * as NodeModule from "node:module";
6+
import * as NodeOS from "node:os";
7+
import * as NodePath from "node:path";
8+
import * as NodeStream from "node:stream";
39
import { ElectronHttpExecutor } from "electron-updater/out/electronHttpExecutor.js";
410
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
511

12+
type DownloadOptions = Parameters<ElectronHttpExecutor["download"]>[2];
13+
type FakeRequest = NodeEvents.EventEmitter & { abort: () => void };
14+
15+
// electron-updater is CommonJS, so a spy goes on the module object its require() returns.
16+
const fsModule = NodeModule.createRequire(import.meta.url)("node:fs") as typeof NodeFS;
17+
const openForReading = fsModule.createReadStream;
18+
// electron-updater's own dependency, which apps/desktop does not declare.
19+
const { CancellationToken, CancellationError } = NodeModule.createRequire(
20+
NodeModule.createRequire(import.meta.url).resolve("electron-updater"),
21+
)("builder-util-runtime") as {
22+
CancellationToken: new () => DownloadOptions["cancellationToken"];
23+
CancellationError: new () => Error;
24+
};
25+
const RELEASE = "hello world";
26+
// Larger than a file stream's buffer, so its "drain" marks a write of it as committed to disk.
27+
const PREFIX = "a".repeat(1 << 20);
28+
const LARGE_RELEASE = `${PREFIX}world`;
29+
const RESUMED_RANGE = `bytes ${PREFIX.length}-${LARGE_RELEASE.length - 1}/${LARGE_RELEASE.length}`;
30+
631
function startRequest() {
732
const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn() });
833
const response = new NodeEvents.EventEmitter();
@@ -14,6 +39,103 @@ function startRequest() {
1439
return { request, response, reject };
1540
}
1641

42+
// The temp update file already holds `onDisk`, as the differential downloader's output can.
43+
function startDownload(onDisk: string, release = RELEASE) {
44+
const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "electron-http-executor-"));
45+
const destination = NodePath.join(dir, "update.AppImage");
46+
NodeFS.writeFileSync(destination, onDisk);
47+
const createWriteStream = vi.spyOn(fsModule, "createWriteStream");
48+
const createReadStream = vi.spyOn(fsModule, "createReadStream");
49+
const created = new NodeEvents.EventEmitter();
50+
let requestCount = 0;
51+
const executor = new ElectronHttpExecutor();
52+
executor.createRequest = (options: { headers: Record<string, string> }, callback) => {
53+
const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn(), end: vi.fn() });
54+
request.on("response", callback);
55+
requestCount++;
56+
created.emit("request", { request, headers: options.headers });
57+
return request as unknown as Electron.ClientRequest;
58+
};
59+
const cancellationToken = new CancellationToken();
60+
const first = NodeEvents.EventEmitter.once(created, "request");
61+
const result = executor.download(new URL("https://example.com/update.AppImage"), destination, {
62+
cancellationToken,
63+
sha512: NodeCrypto.createHash("sha512").update(release).digest("base64"),
64+
});
65+
// A download that settles instead of sending another request fails the wait with its error.
66+
const settled = result.then(() => {
67+
throw new Error("The download finished without another request");
68+
});
69+
settled.catch(() => {});
70+
const nextRequest = async () => {
71+
const [request] = await Promise.race([
72+
NodeEvents.EventEmitter.once(created, "request"),
73+
settled,
74+
]);
75+
return request as { request: FakeRequest; headers: Record<string, string> };
76+
};
77+
// The first request answers 200 and writes `body` to the file, then stalls before the end.
78+
const stallAfterWriting = async (body: string) => {
79+
const [{ request }] = await first;
80+
const response = startResponse(request, 200, { "content-length": String(release.length) });
81+
const fileOut = createWriteStream.mock.results[0]!.value as NodeFS.WriteStream;
82+
const committed = NodeEvents.EventEmitter.once(fileOut, "drain");
83+
response.write(body);
84+
await committed;
85+
const closed = NodeEvents.EventEmitter.once(fileOut, "close");
86+
const retry = nextRequest();
87+
await vi.advanceTimersByTimeAsync(60_000);
88+
await closed;
89+
await vi.advanceTimersByTimeAsync(2_000);
90+
return retry;
91+
};
92+
return {
93+
destination,
94+
first,
95+
nextRequest,
96+
stallAfterWriting,
97+
result,
98+
cancel: () => cancellationToken.cancel(),
99+
// Resolves once the file is open for its digest check, before any of it is read.
100+
readOpened: () =>
101+
new Promise<void>((resolve) => {
102+
createReadStream.mockImplementationOnce((...args) => {
103+
const stream = openForReading(...args);
104+
stream.once("open", () => resolve());
105+
return stream;
106+
});
107+
}),
108+
requestCount: () => requestCount,
109+
read: () => NodeFS.readFileSync(destination, "utf8"),
110+
[Symbol.dispose]: () => {
111+
createWriteStream.mockRestore();
112+
createReadStream.mockRestore();
113+
NodeFS.rmSync(dir, { recursive: true, force: true });
114+
},
115+
};
116+
}
117+
118+
function startResponse(request: FakeRequest, statusCode: number, headers: Record<string, string>) {
119+
const response = Object.assign(new NodeStream.PassThrough(), {
120+
statusCode,
121+
statusMessage: "",
122+
headers,
123+
});
124+
request.emit("response", response);
125+
return response;
126+
}
127+
128+
function respond(
129+
request: FakeRequest,
130+
statusCode: number,
131+
headers: Record<string, string>,
132+
body: string,
133+
) {
134+
startResponse(request, statusCode, { "content-length": String(body.length), ...headers }).end(
135+
body,
136+
);
137+
}
138+
17139
describe("ElectronHttpExecutor idle timeout", () => {
18140
beforeEach(() => {
19141
vi.useFakeTimers();
@@ -56,4 +178,96 @@ describe("ElectronHttpExecutor idle timeout", () => {
56178
expect(request.abort).not.toHaveBeenCalled();
57179
expect(reject).not.toHaveBeenCalled();
58180
});
181+
182+
it.each([
183+
{
184+
name: "resumes a stalled download from the bytes already written",
185+
written: PREFIX,
186+
retry: { status: 206, headers: { "content-range": RESUMED_RANGE }, body: "world" },
187+
},
188+
{
189+
name: "accepts a file that already holds every byte when the retry is past the end",
190+
written: LARGE_RELEASE,
191+
retry: {
192+
status: 416,
193+
headers: { "content-range": `bytes */${LARGE_RELEASE.length}` },
194+
body: "",
195+
},
196+
},
197+
{
198+
name: "starts over when the server ignores the range",
199+
written: PREFIX,
200+
retry: { status: 200, headers: {}, body: LARGE_RELEASE },
201+
},
202+
])("$name", async ({ written, retry: { status, headers, body } }) => {
203+
using download = startDownload("", LARGE_RELEASE);
204+
205+
const { request: unanswered, headers: first } = await download.stallAfterWriting(written);
206+
expect(first.Range).toBe(`bytes=${written.length}-`);
207+
// A retry that fails before any response still resumes after the bytes the first one wrote.
208+
const retry = download.nextRequest();
209+
unanswered.emit("error", new Error("net::ERR_TIMED_OUT"));
210+
await vi.advanceTimersByTimeAsync(4_000);
211+
const { request, headers: second } = await retry;
212+
expect(second.Range).toBe(`bytes=${written.length}-`);
213+
respond(request, status, headers, body);
214+
215+
await expect(download.result).resolves.toBe(download.destination);
216+
expect(download.read()).toBe(LARGE_RELEASE);
217+
});
218+
219+
it("fails a file past the end of the release when the caller cancels its digest check", async () => {
220+
using download = startDownload("", LARGE_RELEASE);
221+
222+
const { request } = await download.stallAfterWriting(LARGE_RELEASE);
223+
const opened = download.readOpened();
224+
respond(request, 416, { "content-range": `bytes */${LARGE_RELEASE.length}` }, "");
225+
await opened;
226+
download.cancel();
227+
228+
await expect(download.result).rejects.toBeInstanceOf(CancellationError);
229+
});
230+
231+
it("fails a file past the end of the release whose bytes do not match it", async () => {
232+
using download = startDownload("", LARGE_RELEASE);
233+
234+
const { request } = await download.stallAfterWriting(`b${LARGE_RELEASE.slice(1)}`);
235+
respond(request, 416, { "content-range": `bytes */${LARGE_RELEASE.length}` }, "");
236+
237+
await expect(download.result).rejects.toMatchObject({ code: "ERR_CHECKSUM_MISMATCH" });
238+
expect(download.requestCount()).toBe(2);
239+
});
240+
241+
it("fails a resumed download whose earlier bytes do not match the release", async () => {
242+
using download = startDownload("", LARGE_RELEASE);
243+
244+
const { request } = await download.stallAfterWriting(`b${PREFIX.slice(1)}`);
245+
respond(request, 206, { "content-range": RESUMED_RANGE }, "world");
246+
247+
await expect(download.result).rejects.toMatchObject({ code: "ERR_CHECKSUM_MISMATCH" });
248+
});
249+
250+
it("gives up after three retries without resuming from a file it did not write", async () => {
251+
using download = startDownload("differential output");
252+
for (const backoff of [2_000, 4_000, 8_000]) {
253+
const retry = download.nextRequest();
254+
await vi.advanceTimersByTimeAsync(60_000 + backoff);
255+
expect((await retry).headers.Range).toBeUndefined();
256+
}
257+
const outcome = expect(download.result).rejects.toThrow("Request timed out");
258+
259+
await vi.advanceTimersByTimeAsync(60_000);
260+
await outcome;
261+
expect(download.requestCount()).toBe(4);
262+
});
263+
264+
it("does not retry a request that fails for another reason", async () => {
265+
using download = startDownload("");
266+
const [{ request }] = await download.first;
267+
const outcome = expect(download.result).rejects.toThrow("net::ERR_CONNECTION_REFUSED");
268+
269+
request.emit("error", new Error("net::ERR_CONNECTION_REFUSED"));
270+
await outcome;
271+
expect(download.requestCount()).toBe(1);
272+
});
59273
});
Collapse file

‎apps/server/src/cloud/pinnedRuntime.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/cloud/pinnedRuntime.test.ts
+111-14Lines changed: 111 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -236,14 +236,38 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
236236
}),
237237
);
238238

239-
it.effect("retries a release archive whose body fails after the host answered", () =>
239+
it.effect.each([
240+
{ name: "body fails after the host answered", first: "body fails", honorsRange: true },
241+
{
242+
name: "body stalls and its resume ends early",
243+
first: "body stalls",
244+
honorsRange: true,
245+
shortResume: true,
246+
},
247+
{ name: "body stalls on a host that ignores Range", first: "body stalls", honorsRange: false },
248+
{ name: "response headers stall", first: "headers stall", honorsRange: true },
249+
{
250+
name: "whole body arrives and then stalls",
251+
first: "body stalls",
252+
honorsRange: true,
253+
wholeArchive: true,
254+
},
255+
] as const)("resumes a release archive download when its $name", (row) =>
240256
Effect.gen(function* () {
257+
const { first, honorsRange } = row;
258+
const shortResume = "shortResume" in row;
241259
const fs = yield* FileSystem.FileSystem;
242260
const path = yield* Path.Path;
243261
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-body-" });
244262
const checksums = yield* validChecksums;
245-
let archiveRequests = 0;
263+
const ranges: Array<string | undefined> = [];
264+
const checksumRanges: Array<string | undefined> = [];
265+
const progress: PinnedRuntimeProgress[] = [];
266+
const checksumsRequested = yield* Deferred.make<void>();
246267
const archiveRequested = yield* Deferred.make<void>();
268+
const shortResumeRequested = yield* Deferred.make<void>();
269+
const total = archiveBytes.length;
270+
const heldBytes = "wholeArchive" in row ? archiveBytes : archiveBytes.slice(0, 4);
247271
const install = yield* ensurePinnedRuntimeInstalled({
248272
baseDir,
249273
version,
@@ -252,21 +276,72 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
252276
platform: "linux",
253277
arch: "x64",
254278
httpClient: HttpClient.make((request) => {
255-
const isChecksums = request.url.endsWith("/SHA256SUMS");
279+
if (request.url.endsWith("/SHA256SUMS")) {
280+
checksumRanges.push(request.headers["range"]);
281+
const response = HttpClientResponse.fromWeb(request, new Response(checksums));
282+
if (checksumRanges.length > 1) return Effect.succeed(response);
283+
Deferred.doneUnsafe(checksumsRequested, Effect.void);
284+
// The checksums fail once after a prefix, which their retry must not resume from.
285+
const failingBody = Stream.concat(
286+
Stream.make(new TextEncoder().encode(checksums).slice(0, 8)),
287+
Stream.fail(
288+
new HttpClientError.HttpClientError({
289+
reason: new HttpClientError.DecodeError({ request, response }),
290+
}),
291+
),
292+
);
293+
return Effect.sleep("1 second").pipe(
294+
Effect.as<HttpClientResponse.HttpClientResponse>(
295+
Object.create(response, { stream: { value: failingBody } }),
296+
),
297+
);
298+
}
299+
const range = request.headers["range"];
300+
ranges.push(range);
301+
if (ranges.length > 1) {
302+
const start = honorsRange ? Number(/^bytes=(\d+)-$/.exec(range ?? "")?.[1] ?? 0) : 0;
303+
// A short resume stops one byte early; the next retry asks for that byte.
304+
const end = shortResume && ranges.length === 2 ? total - 1 : total;
305+
const response = HttpClientResponse.fromWeb(
306+
request,
307+
start >= total
308+
? new Response("", {
309+
status: 416,
310+
headers: { "content-range": `bytes */${total}` },
311+
})
312+
: start > 0
313+
? new Response(archiveBytes.slice(start, end), {
314+
status: 206,
315+
headers: { "content-range": `bytes ${start}-${end - 1}/${total}` },
316+
})
317+
: new Response(archiveBytes, { headers: { "content-length": `${total}` } }),
318+
);
319+
if (end === total) return Effect.succeed(response);
320+
Deferred.doneUnsafe(shortResumeRequested, Effect.void);
321+
// An Effect stream keeps the body, and so the retry wait after it, on the test clock.
322+
const body = Stream.make(archiveBytes.slice(start, end));
323+
return Effect.sleep("1 second").pipe(
324+
Effect.as<HttpClientResponse.HttpClientResponse>(
325+
Object.create(response, { stream: { value: body } }),
326+
),
327+
);
328+
}
329+
Deferred.doneUnsafe(archiveRequested, Effect.void);
330+
if (first === "headers stall") return Effect.never;
256331
const response = HttpClientResponse.fromWeb(
257332
request,
258-
new Response(isChecksums ? checksums : archiveBytes),
333+
new Response(archiveBytes, { headers: { "content-length": `${total}` } }),
259334
);
260-
if (isChecksums || ++archiveRequests > 1) return Effect.succeed(response);
261335
const failingBody = Stream.concat(
262-
Stream.make(archiveBytes.slice(0, 4)),
263-
Stream.fail(
264-
new HttpClientError.HttpClientError({
265-
reason: new HttpClientError.DecodeError({ request, response }),
266-
}),
267-
),
336+
Stream.make(heldBytes),
337+
first === "body stalls"
338+
? Stream.never
339+
: Stream.fail(
340+
new HttpClientError.HttpClientError({
341+
reason: new HttpClientError.DecodeError({ request, response }),
342+
}),
343+
),
268344
);
269-
Deferred.doneUnsafe(archiveRequested, Effect.void);
270345
// TestClock follows the work a woken sleep starts, so one adjust reaches the retry wait.
271346
return Effect.sleep("1 second").pipe(
272347
Effect.as<HttpClientResponse.HttpClientResponse>(
@@ -276,12 +351,34 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
276351
}),
277352
runner: extractingRunner(fs, path),
278353
validate: () => Effect.void,
354+
onProgress: (event) => progress.push(event),
279355
}).pipe(Effect.forkScoped);
280-
yield* Deferred.await(archiveRequested);
356+
yield* Deferred.await(checksumsRequested);
281357
yield* TestClock.adjust(Duration.seconds(3));
358+
yield* Deferred.await(archiveRequested);
359+
// The one-minute stall bound, then the first two-second retry backoff.
360+
yield* TestClock.adjust(Duration.seconds(first === "body fails" ? 3 : 63));
361+
if (shortResume) {
362+
yield* Deferred.await(shortResumeRequested);
363+
// Its one-second delay, then the second, four-second backoff.
364+
yield* TestClock.adjust(Duration.seconds(5));
365+
}
282366
const paths = yield* Fiber.join(install);
367+
assert.deepEqual(checksumRanges, [undefined, undefined]);
368+
assert.deepEqual(ranges, [
369+
undefined,
370+
first === "headers stall" ? undefined : `bytes=${heldBytes.length}-`,
371+
...(shortResume ? [`bytes=${total - 1}-`] : []),
372+
]);
283373
assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`);
284-
assert.equal(archiveRequests, 2);
374+
assert.deepEqual(
375+
progress.findLast((event) => event.stage === "download"),
376+
{
377+
stage: "download",
378+
received: total,
379+
total,
380+
},
381+
);
285382
}),
286383
);
287384

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.