返回 CodeWhale
source-selection.test.js
根目录 / npm / codewhale / test / source-selection.test.js
1 const assert = require("node:assert/strict");
2 const crypto = require("node:crypto");
3 const fs = require("node:fs");
4 const http = require("node:http");
5 const os = require("node:os");
6 const path = require("node:path");
7 const test = require("node:test");
8
9 const {
10 CHECKSUM_MANIFEST,
11 cnbReleaseBaseUrl,
12 explicitReleaseBase,
13 firstPartyReleaseSources,
14 githubReleaseBaseUrl,
15 hasExplicitReleaseBase,
16 shouldRaceFirstPartyMirrors,
17 transportOptions,
18 } = require("../scripts/artifacts");
19 const { run, _internal } = require("../scripts/install");
20
21 const VERSION = "0.9.10";
22 const REPO = "codewhale-hq/CodeWhale";
23 const CODEWHALE_ASSET = "codewhale-linux-x64";
24 const CODEW_ASSET = "codew-linux-x64";
25 const REQUIRED_ASSETS = [CODEWHALE_ASSET, CODEW_ASSET];
26
27 function sha256(content) {
28 return crypto.createHash("sha256").update(content).digest("hex");
29 }
30
31 function hasExactHostname(value, expectedHostname) {
32 return new URL(value).hostname === expectedHostname;
33 }
34
35 function manifestFor(files) {
36 return Object.entries(files)
37 .map(([name, body]) => `${sha256(body)} ${name}`)
38 .join("\n");
39 }
40
41 function abortError() {
42 const err = new Error("The operation was aborted");
43 err.name = "AbortError";
44 err.code = "ABORT_ERR";
45 err.nonRetryable = true;
46 return err;
47 }
48
49 function hangUntilAbort(signal) {
50 return new Promise((_, reject) => {
51 const fail = () => reject(abortError());
52 if (!signal) {
53 return;
54 }
55 if (signal.aborted) {
56 fail();
57 return;
58 }
59 signal.addEventListener("abort", fail, { once: true });
60 });
61 }
62
63 function deferred() {
64 let resolve;
65 let reject;
66 const promise = new Promise((resolvePromise, rejectPromise) => {
67 resolve = resolvePromise;
68 reject = rejectPromise;
69 });
70 return { promise, reject, resolve };
71 }
72
73 async function makeTempDir(t) {
74 const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codewhale-source-"));
75 t.after(() => fs.promises.rm(dir, { force: true, recursive: true }));
76 return dir;
77 }
78
79 function linuxSelectOptions(overrides = {}) {
80 return {
81 version: VERSION,
82 repo: REPO,
83 requiredAssets: REQUIRED_ASSETS,
84 context: "runtime",
85 env: {},
86 platform: "linux",
87 arch: "x64",
88 ...overrides,
89 };
90 }
91
92 async function withoutForcedDownload(callback) {
93 const previousCodewhale = process.env.CODEWHALE_FORCE_DOWNLOAD;
94 const previousTui = process.env.DEEPSEEK_TUI_FORCE_DOWNLOAD;
95 const previousLegacy = process.env.DEEPSEEK_FORCE_DOWNLOAD;
96 delete process.env.CODEWHALE_FORCE_DOWNLOAD;
97 delete process.env.DEEPSEEK_TUI_FORCE_DOWNLOAD;
98 delete process.env.DEEPSEEK_FORCE_DOWNLOAD;
99 try {
100 return await callback();
101 } finally {
102 if (previousCodewhale === undefined) {
103 delete process.env.CODEWHALE_FORCE_DOWNLOAD;
104 } else {
105 process.env.CODEWHALE_FORCE_DOWNLOAD = previousCodewhale;
106 }
107 if (previousTui === undefined) {
108 delete process.env.DEEPSEEK_TUI_FORCE_DOWNLOAD;
109 } else {
110 process.env.DEEPSEEK_TUI_FORCE_DOWNLOAD = previousTui;
111 }
112 if (previousLegacy === undefined) {
113 delete process.env.DEEPSEEK_FORCE_DOWNLOAD;
114 } else {
115 process.env.DEEPSEEK_FORCE_DOWNLOAD = previousLegacy;
116 }
117 }
118 }
119
120 test("Linux x64 races first-party sources unless an explicit override is set", () => {
121 assert.equal(shouldRaceFirstPartyMirrors({}, "linux", "x64"), true);
122 // The CNB mirror publishes Linux assets only, and native HarmonyOS resolves to
123 // its own asset family; it must not be handed a Linux x64 URL.
124 assert.equal(shouldRaceFirstPartyMirrors({}, "openharmony", "x64"), false);
125 assert.equal(shouldRaceFirstPartyMirrors({}, "linux", "arm64"), false);
126 assert.equal(shouldRaceFirstPartyMirrors({}, "darwin", "arm64"), false);
127 assert.equal(
128 shouldRaceFirstPartyMirrors({ CODEWHALE_USE_CNB_MIRROR: "1" }, "linux", "x64"),
129 false,
130 );
131 assert.equal(
132 shouldRaceFirstPartyMirrors({ CODEWHALE_USE_CNB_MIRROR: "0" }, "linux", "x64"),
133 true,
134 );
135 assert.equal(
136 shouldRaceFirstPartyMirrors(
137 { CODEWHALE_RELEASE_BASE_URL: "https://mirror.example/v0.9.10/" },
138 "linux",
139 "x64",
140 ),
141 false,
142 );
143 assert.equal(
144 hasExplicitReleaseBase({ DEEPSEEK_TUI_RELEASE_BASE_URL: "https://legacy.example/" }),
145 true,
146 );
147 assert.equal(
148 hasExplicitReleaseBase({
149 CODEWHALE_RELEASE_BASE_URL: " ",
150 DEEPSEEK_TUI_RELEASE_BASE_URL: "https://legacy.example/",
151 }),
152 true,
153 );
154 assert.equal(
155 explicitReleaseBase({
156 CODEWHALE_RELEASE_BASE_URL: " ",
157 DEEPSEEK_TUI_RELEASE_BASE_URL: "https://legacy.example/releases",
158 }),
159 "https://legacy.example/releases/",
160 );
161 });
162
163 test("first-party source URLs stay pinned to the exact package version", () => {
164 assert.deepEqual(firstPartyReleaseSources(VERSION, REPO), [
165 {
166 id: "github",
167 label: "GitHub Releases",
168 baseUrl: githubReleaseBaseUrl(VERSION, REPO),
169 },
170 {
171 id: "cnb",
172 label: "CNB first-party mirror",
173 baseUrl: cnbReleaseBaseUrl(VERSION),
174 },
175 ]);
176 assert.equal(
177 githubReleaseBaseUrl(VERSION, REPO),
178 `https://github.com/${REPO}/releases/download/v${VERSION}/`,
179 );
180 assert.equal(
181 cnbReleaseBaseUrl(VERSION),
182 `https://cnb.cool/codewhale.net/codewhale/-/releases/download/v${VERSION}/`,
183 );
184 });
185
186 test("CNB wins when its checksum manifest validates first", async () => {
187 const githubBody = Buffer.from("github-codewhale");
188 const cnbBody = Buffer.from("cnb-codewhale");
189 const fetched = [];
190 let githubSignal;
191
192 const source = await _internal.selectReleaseSource(
193 linuxSelectOptions({
194 fetchText: async (url, opts) => {
195 fetched.push(url);
196 if (hasExactHostname(url, "github.com")) {
197 githubSignal = opts && opts.signal;
198 return hangUntilAbort(opts && opts.signal);
199 }
200 return manifestFor({
201 [CODEWHALE_ASSET]: cnbBody,
202 [CODEW_ASSET]: Buffer.from("cnb-codew"),
203 });
204 },
205 }),
206 );
207
208 assert.equal(source.id, "cnb");
209 assert.match(source.label, /CNB first-party mirror/);
210 assert.equal(source.baseUrl, cnbReleaseBaseUrl(VERSION));
211 assert.equal(source.checksums.get(CODEWHALE_ASSET), sha256(cnbBody));
212 assert.notEqual(source.checksums.get(CODEWHALE_ASSET), sha256(githubBody));
213 assert.equal(githubSignal && githubSignal.aborted, true);
214 assert.ok(fetched.some((url) => hasExactHostname(url, "cnb.cool")));
215 assert.ok(fetched.some((url) => hasExactHostname(url, "github.com")));
216 assert.ok(fetched.every((url) => url.endsWith(CHECKSUM_MANIFEST)));
217 });
218
219 test("GitHub wins when its checksum manifest validates first", async () => {
220 const githubBody = Buffer.from("github-codewhale");
221 let cnbSignal;
222
223 const source = await _internal.selectReleaseSource(
224 linuxSelectOptions({
225 fetchText: async (url, opts) => {
226 if (hasExactHostname(url, "cnb.cool")) {
227 cnbSignal = opts && opts.signal;
228 return hangUntilAbort(opts && opts.signal);
229 }
230 return manifestFor({
231 [CODEWHALE_ASSET]: githubBody,
232 [CODEW_ASSET]: Buffer.from("github-codew"),
233 });
234 },
235 }),
236 );
237
238 assert.equal(source.id, "github");
239 assert.equal(source.baseUrl, githubReleaseBaseUrl(VERSION, REPO));
240 assert.equal(source.checksums.get(CODEWHALE_ASSET), sha256(githubBody));
241 assert.equal(cnbSignal && cnbSignal.aborted, true);
242 });
243
244 test("one unavailable first-party source does not block the valid source", async () => {
245 const githubBody = Buffer.from("github-only");
246 const fetched = [];
247
248 const source = await _internal.selectReleaseSource(
249 linuxSelectOptions({
250 fetchText: async (url) => {
251 fetched.push(url);
252 if (hasExactHostname(url, "cnb.cool")) {
253 const err = new Error("Request failed with status 404: " + url);
254 err.name = "HttpStatusError";
255 err.status = 404;
256 err.nonRetryable = true;
257 throw err;
258 }
259 return manifestFor({
260 [CODEWHALE_ASSET]: githubBody,
261 [CODEW_ASSET]: Buffer.from("github-codew"),
262 });
263 },
264 }),
265 );
266
267 assert.equal(source.id, "github");
268 assert.equal(source.checksums.get(CODEWHALE_ASSET), sha256(githubBody));
269 assert.equal(fetched.length, 2);
270 });
271
272 test("both invalid manifests fail closed", async () => {
273 await assert.rejects(
274 () =>
275 _internal.selectReleaseSource(
276 linuxSelectOptions({
277 fetchText: async () => "not-a-checksum-manifest",
278 }),
279 ),
280 (err) => {
281 assert.match(String(err.message), /No usable first-party release source/);
282 assert.match(String(err.message), /GitHub Releases/);
283 assert.match(String(err.message), /CNB first-party mirror/);
284 assert.equal(err.nonRetryable, true);
285 return true;
286 },
287 );
288 });
289
290 test("aggregate source failure preserves retryable optional-install behavior", async () => {
291 let failure;
292 try {
293 await _internal.selectReleaseSource(
294 linuxSelectOptions({
295 fetchText: async (url) => {
296 const error = new Error(`getaddrinfo ENOTFOUND ${new URL(url).hostname}`);
297 error.code = "ENOTFOUND";
298 throw error;
299 },
300 }),
301 );
302 } catch (error) {
303 failure = error;
304 }
305
306 assert.ok(failure);
307 assert.equal(failure.retryable, true);
308 assert.equal(failure.nonRetryable, undefined);
309 assert.equal(
310 _internal.shouldIgnoreInstallFailure(
311 "install",
312 failure,
313 ["--optional"],
314 {},
315 ),
316 true,
317 );
318 });
319
320 test("explicit release base and CNB override take precedence over the race", async () => {
321 const overrideBase = "https://mirror.example/v0.9.10/";
322 const overrideBody = Buffer.from("override-binary");
323 const fetched = [];
324
325 const overrideSource = await _internal.selectReleaseSource(
326 linuxSelectOptions({
327 env: {
328 CODEWHALE_RELEASE_BASE_URL: overrideBase,
329 CODEWHALE_USE_CNB_MIRROR: "1",
330 },
331 fetchText: async (url) => {
332 fetched.push(url);
333 if (!url.startsWith(overrideBase)) {
334 throw new Error(`unexpected fetch ${url}`);
335 }
336 return manifestFor({
337 [CODEWHALE_ASSET]: overrideBody,
338 [CODEW_ASSET]: Buffer.from("override-codew"),
339 });
340 },
341 }),
342 );
343
344 assert.equal(overrideSource.id, "override");
345 assert.equal(overrideSource.baseUrl, overrideBase);
346 assert.deepEqual(fetched, [`${overrideBase}${CHECKSUM_MANIFEST}`]);
347
348 fetched.length = 0;
349 const cnbSource = await _internal.selectReleaseSource(
350 linuxSelectOptions({
351 env: { CODEWHALE_USE_CNB_MIRROR: "1" },
352 fetchText: async (url) => {
353 fetched.push(url);
354 if (!url.startsWith(cnbReleaseBaseUrl(VERSION))) {
355 throw new Error(`unexpected fetch ${url}`);
356 }
357 return manifestFor({
358 [CODEWHALE_ASSET]: Buffer.from("cnb-forced"),
359 [CODEW_ASSET]: Buffer.from("cnb-forced-codew"),
360 });
361 },
362 }),
363 );
364
365 assert.equal(cnbSource.id, "cnb");
366 assert.deepEqual(fetched, [`${cnbReleaseBaseUrl(VERSION)}${CHECKSUM_MANIFEST}`]);
367 });
368
369 test("locked source downloads each required binary once from the winner", async (t) => {
370 const dir = await makeTempDir(t);
371 const cnbWhale = Buffer.from("cnb-codewhale-bytes");
372 const cnbCodew = Buffer.from("cnb-codew-bytes");
373 const githubWhale = Buffer.from("github-codewhale-bytes");
374 const githubCodew = Buffer.from("github-codew-bytes");
375 const binaryDownloads = [];
376 const manifestFetches = [];
377
378 const source = await _internal.selectReleaseSource(
379 linuxSelectOptions({
380 fetchText: async (url, opts) => {
381 manifestFetches.push(url);
382 if (hasExactHostname(url, "github.com")) {
383 return hangUntilAbort(opts && opts.signal);
384 }
385 return manifestFor({
386 [CODEWHALE_ASSET]: cnbWhale,
387 [CODEW_ASSET]: cnbCodew,
388 });
389 },
390 }),
391 );
392
393 assert.equal(source.id, "cnb");
394
395 const fakeDownload = async (url, destination) => {
396 binaryDownloads.push(url);
397 const body = url.endsWith(CODEW_ASSET) ? cnbCodew : cnbWhale;
398 await fs.promises.mkdir(path.dirname(destination), { recursive: true });
399 await fs.promises.writeFile(destination, body);
400 };
401
402 await withoutForcedDownload(async () => {
403 await _internal.ensureBinary(
404 path.join(dir, "codewhale"),
405 CODEWHALE_ASSET,
406 VERSION,
407 REPO,
408 async () => source.checksums,
409 {
410 baseUrl: source.baseUrl,
411 sourceId: source.id,
412 sourceLabel: source.label,
413 download: fakeDownload,
414 },
415 );
416 await _internal.ensureBinary(
417 path.join(dir, "codew"),
418 CODEW_ASSET,
419 VERSION,
420 REPO,
421 async () => source.checksums,
422 {
423 baseUrl: source.baseUrl,
424 sourceId: source.id,
425 sourceLabel: source.label,
426 download: fakeDownload,
427 },
428 );
429 });
430
431 assert.deepEqual(binaryDownloads, [
432 `${cnbReleaseBaseUrl(VERSION)}${CODEWHALE_ASSET}`,
433 `${cnbReleaseBaseUrl(VERSION)}${CODEW_ASSET}`,
434 ]);
435 assert.ok(manifestFetches.every((url) => url.endsWith(CHECKSUM_MANIFEST)));
436 assert.ok(!binaryDownloads.some((url) => hasExactHostname(url, "github.com")));
437 assert.equal(await fs.promises.readFile(path.join(dir, "codewhale"), "utf8"), cnbWhale.toString());
438 assert.equal(
439 await fs.promises.readFile(path.join(dir, "codewhale.source"), "utf8"),
440 [
441 `source=${source.id}`,
442 `label=${source.label}`,
443 `base=${source.baseUrl}`,
444 `version=${VERSION}`,
445 "",
446 ].join("\n"),
447 );
448 });
449
450 test("run locks both binaries to the first valid manifest source", async (t) => {
451 const dir = await makeTempDir(t);
452 const cnbWhale = Buffer.from("run-cnb-codewhale");
453 const cnbCodew = Buffer.from("run-cnb-codew");
454 const bothStarted = deferred();
455 const releaseCnbManifest = deferred();
456 const binaryDownloads = [];
457 let manifestStarts = 0;
458 let githubSignal;
459
460 const sources = [
461 {
462 id: "github",
463 label: "GitHub Releases",
464 baseUrl: "https://github.invalid/releases/download/v0.9.10/",
465 },
466 {
467 id: "cnb",
468 label: "CNB first-party mirror",
469 baseUrl: "https://cnb.invalid/releases/download/v0.9.10/",
470 },
471 ];
472 const paths = {
473 codewhale: {
474 asset: CODEWHALE_ASSET,
475 target: path.join(dir, "codewhale"),
476 },
477 codew: {
478 asset: CODEW_ASSET,
479 target: path.join(dir, "codew"),
480 },
481 };
482
483 const install = run({
484 context: "runtime",
485 env: {
486 CODEWHALE_FORCE_DOWNLOAD: "1",
487 CODEWHALE_QUIET_INSTALL: "1",
488 CODEWHALE_VERSION: VERSION,
489 },
490 platform: "linux",
491 arch: "x64",
492 paths,
493 releaseDir: dir,
494 sources,
495 fetchText: (url, options) => {
496 manifestStarts += 1;
497 if (manifestStarts === sources.length) {
498 bothStarted.resolve();
499 }
500 if (url.startsWith(sources[0].baseUrl)) {
501 githubSignal = options.signal;
502 return hangUntilAbort(options.signal);
503 }
504 return releaseCnbManifest.promise;
505 },
506 download: async (url, destination) => {
507 binaryDownloads.push(url);
508 const body = url.endsWith(CODEW_ASSET) ? cnbCodew : cnbWhale;
509 await fs.promises.writeFile(destination, body);
510 },
511 });
512
513 await bothStarted.promise;
514 releaseCnbManifest.resolve(
515 manifestFor({
516 [CODEWHALE_ASSET]: cnbWhale,
517 [CODEW_ASSET]: cnbCodew,
518 }),
519 );
520 await install;
521
522 assert.equal(githubSignal.aborted, true);
523 assert.deepEqual(binaryDownloads.sort(), [
524 `${sources[1].baseUrl}${CODEW_ASSET}`,
525 `${sources[1].baseUrl}${CODEWHALE_ASSET}`,
526 ]);
527 assert.equal(
528 await fs.promises.readFile(`${paths.codewhale.target}.source`, "utf8"),
529 [
530 "source=cnb",
531 "label=CNB first-party mirror",
532 `base=${sources[1].baseUrl}`,
533 `version=${VERSION}`,
534 "",
535 ].join("\n"),
536 );
537 assert.equal(
538 await fs.promises.readFile(`${paths.codew.target}.source`, "utf8"),
539 await fs.promises.readFile(`${paths.codewhale.target}.source`, "utf8"),
540 );
541 });
542
543 test("run fails before binary download when neither manifest validates", async (t) => {
544 const dir = await makeTempDir(t);
545 const binaryDownloads = [];
546
547 await assert.rejects(
548 () =>
549 run({
550 context: "runtime",
551 env: {
552 CODEWHALE_FORCE_DOWNLOAD: "1",
553 CODEWHALE_QUIET_INSTALL: "1",
554 CODEWHALE_VERSION: VERSION,
555 },
556 platform: "linux",
557 arch: "x64",
558 releaseDir: dir,
559 paths: {
560 codewhale: {
561 asset: CODEWHALE_ASSET,
562 target: path.join(dir, "codewhale"),
563 },
564 codew: {
565 asset: CODEW_ASSET,
566 target: path.join(dir, "codew"),
567 },
568 },
569 fetchText: async () => "invalid manifest",
570 download: async (url) => {
571 binaryDownloads.push(url);
572 },
573 }),
574 /No usable first-party release source/,
575 );
576
577 assert.deepEqual(binaryDownloads, []);
578 assert.equal(
579 await fs.promises.access(path.join(dir, "codewhale")).then(() => true, () => false),
580 false,
581 );
582 assert.equal(
583 await fs.promises.access(path.join(dir, "codew")).then(() => true, () => false),
584 false,
585 );
586 });
587
588 test("run sends manifest and binaries only to an explicit release base", async (t) => {
589 const dir = await makeTempDir(t);
590 const baseUrl = "https://mirror.invalid/releases/download/v0.9.10/";
591 const codewhaleBody = Buffer.from("override-codewhale");
592 const codewBody = Buffer.from("override-codew");
593 const manifestFetches = [];
594 const binaryDownloads = [];
595
596 await run({
597 context: "runtime",
598 env: {
599 CODEWHALE_FORCE_DOWNLOAD: "1",
600 CODEWHALE_QUIET_INSTALL: "1",
601 CODEWHALE_RELEASE_BASE_URL: baseUrl,
602 CODEWHALE_USE_CNB_MIRROR: "1",
603 CODEWHALE_VERSION: VERSION,
604 },
605 platform: "linux",
606 arch: "x64",
607 releaseDir: dir,
608 paths: {
609 codewhale: {
610 asset: CODEWHALE_ASSET,
611 target: path.join(dir, "codewhale"),
612 },
613 codew: {
614 asset: CODEW_ASSET,
615 target: path.join(dir, "codew"),
616 },
617 },
618 fetchText: async (url) => {
619 manifestFetches.push(url);
620 return manifestFor({
621 [CODEWHALE_ASSET]: codewhaleBody,
622 [CODEW_ASSET]: codewBody,
623 });
624 },
625 download: async (url, destination) => {
626 binaryDownloads.push(url);
627 await fs.promises.writeFile(
628 destination,
629 url.endsWith(CODEW_ASSET) ? codewBody : codewhaleBody,
630 );
631 },
632 });
633
634 assert.deepEqual(manifestFetches, [`${baseUrl}${CHECKSUM_MANIFEST}`]);
635 assert.deepEqual(binaryDownloads.sort(), [
636 `${baseUrl}${CODEW_ASSET}`,
637 `${baseUrl}${CODEWHALE_ASSET}`,
638 ]);
639 });
640
641 test("checksum mismatch against the locked source fails closed", async (t) => {
642 const dir = await makeTempDir(t);
643 const expected = Buffer.from("expected-cnb-bytes");
644 const actual = Buffer.from("tampered-cnb-bytes");
645 const downloads = [];
646 const source = {
647 id: "cnb",
648 label: "CNB first-party mirror",
649 baseUrl: cnbReleaseBaseUrl(VERSION),
650 checksums: new Map([[CODEWHALE_ASSET, sha256(expected)]]),
651 };
652
653 await assert.rejects(
654 () =>
655 _internal.ensureBinary(
656 path.join(dir, "codewhale"),
657 CODEWHALE_ASSET,
658 VERSION,
659 REPO,
660 async () => source.checksums,
661 {
662 baseUrl: source.baseUrl,
663 sourceId: source.id,
664 sourceLabel: source.label,
665 download: async (url, destination) => {
666 downloads.push(url);
667 await fs.promises.mkdir(path.dirname(destination), { recursive: true });
668 await fs.promises.writeFile(destination, actual);
669 },
670 },
671 ),
672 /Checksum mismatch for codewhale-linux-x64 from CNB first-party mirror/,
673 );
674 assert.deepEqual(downloads, [`${cnbReleaseBaseUrl(VERSION)}${CODEWHALE_ASSET}`]);
675 assert.equal(await fs.promises.access(path.join(dir, "codewhale")).then(() => true, () => false), false);
676 });
677
678 test("source selection is visible in progress output", async () => {
679 const previousWrite = process.stderr.write;
680 const previousQuiet = process.env.DEEPSEEK_TUI_QUIET_INSTALL;
681 let stderr = "";
682 process.stderr.write = (chunk) => {
683 stderr += String(chunk);
684 return true;
685 };
686 delete process.env.DEEPSEEK_TUI_QUIET_INSTALL;
687
688 try {
689 await _internal.selectReleaseSource(
690 linuxSelectOptions({
691 fetchText: async (url, opts) => {
692 if (hasExactHostname(url, "github.com")) {
693 return hangUntilAbort(opts && opts.signal);
694 }
695 return manifestFor({
696 [CODEWHALE_ASSET]: Buffer.from("cnb"),
697 [CODEW_ASSET]: Buffer.from("cnb-codew"),
698 });
699 },
700 }),
701 );
702 assert.match(stderr, /probing GitHub Releases and CNB first-party mirror/);
703 assert.match(stderr, /selected CNB first-party mirror/);
704 } finally {
705 process.stderr.write = previousWrite;
706 if (previousQuiet === undefined) {
707 delete process.env.DEEPSEEK_TUI_QUIET_INSTALL;
708 } else {
709 process.env.DEEPSEEK_TUI_QUIET_INSTALL = previousQuiet;
710 }
711 }
712 });
713
714 function allowLoopbackHttp(t) {
715 const previous = transportOptions.allowLoopbackHttp;
716 transportOptions.allowLoopbackHttp = true;
717 t.after(() => {
718 transportOptions.allowLoopbackHttp = previous;
719 });
720 }
721
722 test("aborting a losing manifest probe closes a body already in progress", async (t) => {
723 allowLoopbackHttp(t);
724 const responseStarted = deferred();
725 const responseClosed = deferred();
726 const server = http.createServer((_req, res) => {
727 res.on("close", () => responseClosed.resolve());
728 res.writeHead(200, { "Content-Type": "text/plain" });
729 res.write(`${"a".repeat(64)} ${CODEWHALE_ASSET}\n`);
730 responseStarted.resolve();
731 });
732 await new Promise((resolve, reject) => {
733 server.listen(0, "127.0.0.1", resolve);
734 server.once("error", reject);
735 });
736 t.after(
737 () =>
738 new Promise((resolve) => {
739 server.close(() => resolve());
740 }),
741 );
742
743 const address = server.address();
744 const controller = new AbortController();
745 const fetching = _internal.downloadText(
746 `http://127.0.0.1:${address.port}/${CHECKSUM_MANIFEST}`,
747 {
748 signal: controller.signal,
749 stallMs: 10_000,
750 totalTimeoutMs: 10_000,
751 },
752 );
753 await responseStarted.promise;
754 controller.abort();
755
756 await assert.rejects(fetching, (error) => {
757 assert.equal(error.name, "AbortError");
758 assert.equal(error.code, "ABORT_ERR");
759 return true;
760 });
761 await responseClosed.promise;
762 });
763
764 test("HTTP fixture never starts the losing source's full binary download", async (t) => {
765 allowLoopbackHttp(t);
766 const dir = await makeTempDir(t);
767 const cnbWhale = Buffer.from("fixture-cnb-whale");
768 const cnbCodew = Buffer.from("fixture-cnb-codew");
769 const githubWhale = Buffer.from("fixture-github-whale");
770 const githubCodew = Buffer.from("fixture-github-codew");
771 const hits = { githubManifest: 0, githubBinary: 0, cnbManifest: 0, cnbBinary: 0 };
772
773 const github = await listenFixture({
774 manifest: manifestFor({
775 [CODEWHALE_ASSET]: githubWhale,
776 [CODEW_ASSET]: githubCodew,
777 }),
778 files: {
779 [CODEWHALE_ASSET]: githubWhale,
780 [CODEW_ASSET]: githubCodew,
781 },
782 onManifest: () => {
783 hits.githubManifest += 1;
784 },
785 onBinary: () => {
786 hits.githubBinary += 1;
787 },
788 });
789 const cnb = await listenFixture({
790 manifest: manifestFor({
791 [CODEWHALE_ASSET]: cnbWhale,
792 [CODEW_ASSET]: cnbCodew,
793 }),
794 files: {
795 [CODEWHALE_ASSET]: cnbWhale,
796 [CODEW_ASSET]: cnbCodew,
797 },
798 onManifest: () => {
799 hits.cnbManifest += 1;
800 },
801 onBinary: () => {
802 hits.cnbBinary += 1;
803 },
804 });
805 t.after(() => github.close());
806 t.after(() => cnb.close());
807
808 const source = await _internal.selectReleaseSource(
809 linuxSelectOptions({
810 sources: [
811 {
812 id: "github",
813 label: "GitHub Releases",
814 baseUrl: github.baseUrl,
815 },
816 {
817 id: "cnb",
818 label: "CNB first-party mirror",
819 baseUrl: cnb.baseUrl,
820 },
821 ],
822 fetchText: (url, opts) =>
823 url.startsWith(github.baseUrl)
824 ? hangUntilAbort(opts && opts.signal)
825 : _internal.downloadText(url, opts),
826 }),
827 );
828
829 assert.equal(source.id, "cnb");
830 await withoutForcedDownload(() =>
831 _internal.ensureBinary(
832 path.join(dir, "codewhale"),
833 CODEWHALE_ASSET,
834 VERSION,
835 REPO,
836 async () => source.checksums,
837 { baseUrl: source.baseUrl, sourceId: source.id, sourceLabel: source.label },
838 ),
839 );
840
841 assert.equal(hits.githubBinary, 0);
842 assert.equal(hits.cnbBinary, 1);
843 assert.equal(hits.cnbManifest, 1);
844 assert.equal(await fs.promises.readFile(path.join(dir, "codewhale"), "utf8"), cnbWhale.toString());
845 });
846
847 function listenFixture(spec) {
848 return new Promise((resolve, reject) => {
849 const server = http.createServer((req, res) => {
850 const urlPath = String(req.url || "").split("?")[0];
851 const name = path.posix.basename(urlPath);
852 if (name === CHECKSUM_MANIFEST) {
853 if (spec.onManifest) spec.onManifest();
854 res.writeHead(200, { "Content-Type": "text/plain" });
855 res.end(spec.manifest);
856 return;
857 }
858 if (spec.files[name]) {
859 if (spec.onBinary) spec.onBinary();
860 res.writeHead(200, { "Content-Type": "application/octet-stream" });
861 res.end(spec.files[name]);
862 return;
863 }
864 res.writeHead(404);
865 res.end("missing");
866 });
867 server.listen(0, "127.0.0.1", () => {
868 const address = server.address();
869 resolve({
870 baseUrl: `http://127.0.0.1:${address.port}/releases/download/v${VERSION}/`,
871 close: () =>
872 new Promise((done) => {
873 server.close(() => done());
874 }),
875 });
876 });
877 server.once("error", reject);
878 });
879 }
880
880 lines JAVASCRIPT