Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(local-installation): stabilize region probing and fall back on slow downloads

Dongdong Chen84f9362aa0aa
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md
index 03d62f20..6b900b95 100644
--- a/packages/local-installation/AGENTS.md
+++ b/packages/local-installation/AGENTS.md
@@ -171,8 +171,10 @@ leave PostgreSQL holding `postmaster.pid` against every retry.
Every download offered by both a global host and a mainland-China mirror
goes through `downloadInRegion` (`region.ts`), which tries the home's
download region first and never drops a source; the region is
-`SIMPLEX_REGION`, else `<home>/runtime/region.json` (7 days), else the npm
-registry probe, and a fallback to the other region rewrites the file. The
+`SIMPLEX_REGION`, else `<home>/runtime/region.json` (24 hours), else a
+best-of-three npm registry probe (up to 1 MiB per round, fastest wins). When
+the preferred region fails or transfers slowly while a mirror in the other
+region proves faster, the transfer resumes there and rewrites the file. The
resolved region reaches every `localmodels` child and native service as
`SIMPLEX_REGION`. The contract is in `scripts/installs/README.md`.
diff --git a/packages/local-installation/src/download.test.ts b/packages/local-installation/src/download.test.ts
index fe7019cb..aa809a58 100644
--- a/packages/local-installation/src/download.test.ts
+++ b/packages/local-installation/src/download.test.ts
@@ -451,3 +451,317 @@ it("keeps a resumable partial file for the next call", async () => {
expect(await readFile(output)).toEqual(bytes);
expect(await readdir(root)).toEqual(["bundle.tgz"]);
});
+
+it("moves to a faster mirror when the first host is slow with substantial work left", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "linger-download-"));
+ roots.push(root);
+ const bytes = Buffer.alloc(64 * 1024, 0x7a);
+ const requests: string[] = [];
+ const output = path.join(root, "go.tgz");
+ const served = await downloadVerified(
+ {
+ url: "https://primary.example/go.tgz",
+ mirrors: ["https://mirror.example/go.tgz"],
+ output,
+ digest: createHash("sha256").update(bytes).digest("hex"),
+ algorithm: "sha256",
+ maxBytes: bytes.length,
+ signal: new AbortController().signal,
+ },
+ async (url, init) => {
+ const host = new URL(url as URL).host;
+ const range = new Headers(init?.headers).get("range");
+ requests.push(`${host} ${range}`);
+ const start = range ? Number(/^bytes=(\d+)-$/.exec(range)?.[1] ?? 0) : 0;
+ const slice = bytes.subarray(start);
+ const headers: Record<string, string> = {
+ "content-length": String(slice.length),
+ ...(start > 0
+ ? {
+ "content-range": `bytes ${start}-${bytes.length - 1}/${bytes.length}`,
+ }
+ : {}),
+ };
+ if (host === "primary.example") {
+ return new Response(
+ new ReadableStream<Uint8Array>({
+ async start(controller) {
+ for (let offset = 0; offset < slice.length; offset += 2048) {
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ try {
+ controller.enqueue(slice.subarray(offset, offset + 2048));
+ } catch {
+ return;
+ }
+ }
+ try {
+ controller.close();
+ } catch {
+ // Cancelled when switching to the mirror.
+ }
+ },
+ }),
+ { status: start > 0 ? 206 : 200, headers },
+ );
+ }
+ return new Response(slice, { status: start > 0 ? 206 : 200, headers });
+ },
+ {
+ attempts: 2,
+ retryDelayMs: 60_000,
+ idleTimeoutMs: 5_000,
+ slowCheckAfterMs: 100,
+ minBytesPerSecond: 200_000,
+ minRemainingMs: 300,
+ },
+ );
+ expect(served).toBe("https://mirror.example/go.tgz");
+ expect(requests).toHaveLength(2);
+ expect(requests[0]).toBe("primary.example null");
+ expect(requests[1]).toMatch(/^mirror\.example bytes=\d+-$/);
+ expect(await readFile(output)).toEqual(bytes);
+});
+
+it("keeps downloading from a slow primary when the remaining time is short", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "linger-download-"));
+ roots.push(root);
+ const bytes = Buffer.alloc(16 * 1024, 0x79);
+ const hosts: string[] = [];
+ const output = path.join(root, "small.tgz");
+ const served = await downloadVerified(
+ {
+ url: "https://primary.example/small.tgz",
+ mirrors: ["https://mirror.example/small.tgz"],
+ output,
+ digest: createHash("sha256").update(bytes).digest("hex"),
+ algorithm: "sha256",
+ maxBytes: bytes.length,
+ signal: new AbortController().signal,
+ },
+ async (url) => {
+ hosts.push(new URL(url as URL).host);
+ return new Response(
+ new ReadableStream<Uint8Array>({
+ async start(controller) {
+ for (let offset = 0; offset < bytes.length; offset += 4096) {
+ await new Promise((resolve) => setTimeout(resolve, 35));
+ controller.enqueue(bytes.subarray(offset, offset + 4096));
+ }
+ controller.close();
+ },
+ }),
+ { headers: { "content-length": String(bytes.length) } },
+ );
+ },
+ {
+ attempts: 2,
+ retryDelayMs: 0,
+ idleTimeoutMs: 5_000,
+ slowCheckAfterMs: 80,
+ minBytesPerSecond: 500_000,
+ minRemainingMs: 5_000,
+ },
+ );
+ expect(served).toBe("https://primary.example/small.tgz");
+ expect(hosts).toEqual(["primary.example"]);
+ expect(await readFile(output)).toEqual(bytes);
+});
+
+it("finishes on the primary without error when every host is equally slow", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "linger-download-"));
+ roots.push(root);
+ const bytes = Buffer.alloc(40 * 1024, 0x78);
+ const hosts: string[] = [];
+ const output = path.join(root, "slow-both.tgz");
+ const served = await downloadVerified(
+ {
+ url: "https://primary.example/slow-both.tgz",
+ mirrors: ["https://mirror.example/slow-both.tgz"],
+ output,
+ digest: createHash("sha256").update(bytes).digest("hex"),
+ algorithm: "sha256",
+ maxBytes: bytes.length,
+ signal: new AbortController().signal,
+ },
+ async (url, init) => {
+ hosts.push(new URL(url as URL).host);
+ const range = new Headers(init?.headers).get("range");
+ const start = range ? Number(/^bytes=(\d+)-$/.exec(range)?.[1] ?? 0) : 0;
+ const slice = bytes.subarray(start);
+ const headers: Record<string, string> = {
+ "content-length": String(slice.length),
+ ...(start > 0
+ ? {
+ "content-range": `bytes ${start}-${bytes.length - 1}/${bytes.length}`,
+ }
+ : {}),
+ };
+ return new Response(
+ new ReadableStream<Uint8Array>({
+ async start(controller) {
+ for (let offset = 0; offset < slice.length; offset += 2048) {
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ try {
+ controller.enqueue(slice.subarray(offset, offset + 2048));
+ } catch {
+ return;
+ }
+ }
+ try {
+ controller.close();
+ } catch {
+ // Cancelled during round 0 comparison.
+ }
+ },
+ }),
+ { status: start > 0 ? 206 : 200, headers },
+ );
+ },
+ {
+ attempts: 2,
+ retryDelayMs: 60_000,
+ idleTimeoutMs: 5_000,
+ slowCheckAfterMs: 80,
+ minBytesPerSecond: 300_000,
+ minRemainingMs: 150,
+ },
+ );
+ expect(served).toBe("https://primary.example/slow-both.tgz");
+ expect(hosts).toEqual([
+ "primary.example",
+ "mirror.example",
+ "primary.example",
+ ]);
+ expect(await readFile(output)).toEqual(bytes);
+});
+
+it("moves past a hung primary at slowCheckAfterMs instead of waiting for idleTimeoutMs", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "linger-download-"));
+ roots.push(root);
+ const bytes = Buffer.from("served by mirror quickly");
+ const hosts: string[] = [];
+ const output = path.join(root, "kit.tgz");
+ const startedAt = Date.now();
+ const served = await downloadVerified(
+ {
+ url: "https://primary.example/kit.tgz",
+ mirrors: ["https://mirror.example/kit.tgz"],
+ output,
+ digest: createHash("sha256").update(bytes).digest("hex"),
+ algorithm: "sha256",
+ maxBytes: bytes.length,
+ signal: new AbortController().signal,
+ },
+ async (url, init) => {
+ const host = new URL(url as URL).host;
+ hosts.push(host);
+ if (host === "primary.example") {
+ return new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () =>
+ reject(new DOMException("aborted", "AbortError")),
+ );
+ });
+ }
+ return new Response(bytes);
+ },
+ {
+ attempts: 2,
+ retryDelayMs: 0,
+ idleTimeoutMs: 5_000,
+ slowCheckAfterMs: 80,
+ minBytesPerSecond: 100_000,
+ minRemainingMs: 200,
+ },
+ );
+ expect(served).toBe("https://mirror.example/kit.tgz");
+ expect(hosts).toEqual(["primary.example", "mirror.example"]);
+ expect(Date.now() - startedAt).toBeLessThan(1_000);
+ expect(await readFile(output)).toEqual(bytes);
+});
+
+it("promotes the fastest mirror when the first host hangs and the last mirror is slower", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "linger-download-"));
+ roots.push(root);
+ const bytes = Buffer.alloc(64 * 1024, 0x77);
+ const hosts: string[] = [];
+ const output = path.join(root, "kit.tgz");
+ const throttled = (
+ slice: Uint8Array,
+ chunkBytes: number,
+ intervalMs: number,
+ ) =>
+ new ReadableStream<Uint8Array>({
+ async start(controller) {
+ for (let offset = 0; offset < slice.length; offset += chunkBytes) {
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
+ try {
+ controller.enqueue(slice.subarray(offset, offset + chunkBytes));
+ } catch {
+ return;
+ }
+ }
+ try {
+ controller.close();
+ } catch {
+ // Cancelled during round 0 comparison.
+ }
+ },
+ });
+ const served = await downloadVerified(
+ {
+ url: "https://hung.example/kit.tgz",
+ mirrors: [
+ "https://medium.example/kit.tgz",
+ "https://crawl.example/kit.tgz",
+ ],
+ output,
+ digest: createHash("sha256").update(bytes).digest("hex"),
+ algorithm: "sha256",
+ maxBytes: bytes.length,
+ signal: new AbortController().signal,
+ },
+ async (url, init) => {
+ const host = new URL(url as URL).host;
+ hosts.push(host);
+ if (host === "hung.example") {
+ return new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () =>
+ reject(new DOMException("aborted", "AbortError")),
+ );
+ });
+ }
+ const range = new Headers(init?.headers).get("range");
+ const start = range ? Number(/^bytes=(\d+)-$/.exec(range)?.[1] ?? 0) : 0;
+ const slice = bytes.subarray(start);
+ const headers: Record<string, string> = {
+ "content-length": String(slice.length),
+ ...(start > 0
+ ? {
+ "content-range": `bytes ${start}-${bytes.length - 1}/${bytes.length}`,
+ }
+ : {}),
+ };
+ const chunkBytes = host === "medium.example" ? 4096 : 1024;
+ return new Response(throttled(slice, chunkBytes, 30), {
+ status: start > 0 ? 206 : 200,
+ headers,
+ });
+ },
+ {
+ attempts: 2,
+ retryDelayMs: 60_000,
+ idleTimeoutMs: 5_000,
+ slowCheckAfterMs: 90,
+ minBytesPerSecond: 300_000,
+ minRemainingMs: 200,
+ },
+ );
+ expect(served).toBe("https://medium.example/kit.tgz");
+ expect(hosts).toEqual([
+ "hung.example",
+ "medium.example",
+ "crawl.example",
+ "medium.example",
+ ]);
+ expect(await readFile(output)).toEqual(bytes);
+});
diff --git a/packages/local-installation/src/download.ts b/packages/local-installation/src/download.ts
index 0b34bde1..9b12a283 100644
--- a/packages/local-installation/src/download.ts
+++ b/packages/local-installation/src/download.ts
@@ -15,12 +15,39 @@ export interface DownloadTiming {
retryDelayMs: number;
/** An attempt that receives no bytes for this long starts again. */
idleTimeoutMs: number;
+ /**
+ * When mirrors exist, check throughput on this interval during the first
+ * round so a slow host yields to a faster mirror. Disabled when unset or <= 0.
+ */
+ slowCheckAfterMs?: number;
+ /** Throughput below which the first host checks alternate mirrors. */
+ minBytesPerSecond?: number;
+ /** Only check alternate mirrors when at least this much transfer time remains. */
+ minRemainingMs?: number;
}
const defaultTiming: DownloadTiming = {
attempts: 4,
retryDelayMs: 2_000,
idleTimeoutMs: 60_000,
+ slowCheckAfterMs: 6_000,
+ minBytesPerSecond: 1024 * 1024,
+ minRemainingMs: 25_000,
};
+// A mirror replaces a slow primary only when it delivers a meaningful speedup,
+// preventing oscillation when both regions have similar bandwidth.
+const SLOW_SWITCH_RATIO = 1.5;
+
+interface SlowLimit {
+ afterMs: number;
+ minBytesPerSecond: number;
+ minRemainingMs: number;
+}
+
+interface AttemptOutcome {
+ status: "done" | "retry" | "next" | "slow";
+ bytes: number;
+ bytesPerSecond: number;
+}
function publicUrl(value: string) {
const url = new URL(value);
@@ -86,16 +113,55 @@ export async function downloadVerified(
let failure = "no connection";
// One request: "done" when the body ended, "retry" after a transient
- // failure, "next" when this host cannot serve the file.
- const attempt = async (url: URL): Promise<"done" | "retry" | "next"> => {
+ // failure, "next" when this host cannot serve the file, "slow" when it
+ // yielded so another mirror can be compared.
+ const attempt = async (
+ url: URL,
+ slowLimit?: SlowLimit,
+ ): Promise<AttemptOutcome> => {
const stalled = new AbortController();
const signal = AbortSignal.any([options.signal, stalled.signal]);
let idle: NodeJS.Timeout | undefined;
+ let slowTimer: NodeJS.Timeout | undefined;
+ let received = 0;
+ let windowBytes = 0;
+ let windowStartedAt = performance.now();
+ let slowAborted = false;
+ let slowRate = 0;
const watch = () => {
clearTimeout(idle);
idle = setTimeout(() => stalled.abort(), timing.idleTimeoutMs);
};
+ const scheduleSlowCheck = () => {
+ if (!slowLimit) return;
+ slowTimer = setTimeout(() => {
+ const elapsedSec = Math.max(
+ (performance.now() - windowStartedAt) / 1000,
+ 0.001,
+ );
+ const rate = windowBytes / elapsedSec;
+ const remaining =
+ size !== undefined ? Math.max(0, size - completed) : undefined;
+ const remainingMs =
+ remaining !== undefined && rate > 0
+ ? (remaining / rate) * 1000
+ : Number.POSITIVE_INFINITY;
+ if (
+ rate < slowLimit.minBytesPerSecond &&
+ remainingMs > slowLimit.minRemainingMs
+ ) {
+ slowAborted = true;
+ slowRate = rate;
+ stalled.abort();
+ return;
+ }
+ windowBytes = 0;
+ windowStartedAt = performance.now();
+ scheduleSlowCheck();
+ }, slowLimit.afterMs);
+ };
watch();
+ scheduleSlowCheck();
try {
let response: Response;
try {
@@ -106,8 +172,12 @@ export async function downloadVerified(
});
} catch {
options.signal.throwIfAborted();
+ if (slowAborted) {
+ failure = "slow";
+ return { status: "slow", bytes: 0, bytesPerSecond: 0 };
+ }
failure = stalled.signal.aborted ? "no response" : "no connection";
- return "retry";
+ return { status: "retry", bytes: 0, bytesPerSecond: 0 };
}
if (
completed &&
@@ -118,12 +188,12 @@ export async function downloadVerified(
) {
await response.body?.cancel();
failure = "invalid range response";
- return "next";
+ return { status: "next", bytes: 0, bytesPerSecond: 0 };
}
// The previous call received every byte; the checksum decides.
if (completed && response.status === 416) {
await response.body?.cancel();
- return "done";
+ return { status: "done", bytes: 0, bytesPerSecond: 0 };
}
if (completed && response.status === 200) {
// The host ignored the range, so this response starts over.
@@ -135,11 +205,16 @@ export async function downloadVerified(
await response.body?.cancel();
failure = `HTTP ${response.status}`;
// A missing or forbidden file stays so on this host.
- return response.status >= 400 &&
- response.status < 500 &&
- ![408, 429].includes(response.status)
- ? "next"
- : "retry";
+ return {
+ status:
+ response.status >= 400 &&
+ response.status < 500 &&
+ ![408, 429].includes(response.status)
+ ? "next"
+ : "retry",
+ bytes: 0,
+ bytesPerSecond: 0,
+ };
}
const length = Number(response.headers.get("content-length")) || 0;
size = length ? completed + length : undefined;
@@ -163,12 +238,23 @@ export async function downloadVerified(
chunk = await Promise.race([reader.read(), interrupted]);
} catch {
options.signal.throwIfAborted();
+ if (slowAborted) {
+ failure = "slow";
+ return {
+ status: "slow",
+ bytes: received,
+ bytesPerSecond: slowRate,
+ };
+ }
failure = stalled.signal.aborted ? "stalled" : "interrupted";
- return "retry";
+ return { status: "retry", bytes: received, bytesPerSecond: 0 };
}
const { done, value } = chunk;
- if (done) return "done";
+ if (done)
+ return { status: "done", bytes: received, bytesPerSecond: 0 };
watch();
+ received += value.byteLength;
+ windowBytes += value.byteLength;
completed += value.byteLength;
if (completed > options.maxBytes)
throw new Error("Download size exceeds limit.");
@@ -185,26 +271,94 @@ export async function downloadVerified(
}
} finally {
clearTimeout(idle);
+ clearTimeout(slowTimer);
}
};
let published = false;
let served = urls[0]!;
try {
- let result: "done" | "retry" | "next" = "next";
+ let result: AttemptOutcome["status"] = "next";
// Hosts that cannot serve the file leave the rotation.
let active = urls;
+ const slowAfterMs = timing.slowCheckAfterMs ?? 0;
+ const slowFloor = timing.minBytesPerSecond ?? 0;
+ const slowRemainingMs = timing.minRemainingMs ?? 0;
+ const slowEnabled = slowAfterMs > 0 && slowFloor > 0 && timing.attempts > 1;
+ let skipNextDelay = false;
rounds: for (let round = 0; round < timing.attempts; round += 1) {
if (!active.length) break;
- if (round > 0)
+ if (round > 0 && !skipNextDelay)
await delay(timing.retryDelayMs * 2 ** (round - 1), undefined, {
signal: options.signal,
});
- for (const url of active) {
- result = await attempt(url);
+ skipNextDelay = false;
+ let bestSlowRate: number | undefined;
+ const measured = new Map<URL, number>();
+ let anySlowProgress = false;
+ for (let index = 0; index < active.length; index += 1) {
+ const url = active[index]!;
+ const remainingHosts = active.length - 1 - index;
+ let slowLimit: SlowLimit | undefined;
+ if (round === 0 && slowEnabled && active.length > 1) {
+ if (bestSlowRate === undefined) {
+ if (remainingHosts > 0) {
+ slowLimit = {
+ afterMs: slowAfterMs,
+ minBytesPerSecond: slowFloor,
+ minRemainingMs: slowRemainingMs,
+ };
+ }
+ } else {
+ const targetRate =
+ remainingHosts > 0
+ ? Math.max(slowFloor, bestSlowRate * SLOW_SWITCH_RATIO)
+ : bestSlowRate * SLOW_SWITCH_RATIO;
+ if (targetRate > 0) {
+ slowLimit = {
+ afterMs: slowAfterMs,
+ minBytesPerSecond: targetRate,
+ minRemainingMs: 0,
+ };
+ }
+ }
+ }
+ const outcome = await attempt(url, slowLimit);
+ result = outcome.status;
served = url;
- if (result === "done") break rounds;
- if (result === "next") active = active.filter((item) => item !== url);
+ if (outcome.status === "done") break rounds;
+ if (outcome.status === "next") {
+ active = active.filter((item) => item !== url);
+ index -= 1;
+ continue;
+ }
+ if (outcome.status === "slow") {
+ measured.set(url, outcome.bytesPerSecond);
+ if (outcome.bytes > 0) anySlowProgress = true;
+ bestSlowRate =
+ bestSlowRate === undefined
+ ? outcome.bytesPerSecond
+ : Math.max(bestSlowRate, outcome.bytesPerSecond);
+ }
+ }
+ if (round === 0 && measured.size > 0) {
+ const primary = active[0];
+ const baseRate = primary ? (measured.get(primary) ?? 0) : 0;
+ let bestUrl = primary;
+ let bestRate = baseRate;
+ for (const [url, rate] of measured) {
+ if (
+ rate > bestRate &&
+ (baseRate === 0 ? rate > 0 : rate >= baseRate * SLOW_SWITCH_RATIO)
+ ) {
+ bestUrl = url;
+ bestRate = rate;
+ }
+ }
+ if (bestUrl && bestUrl !== primary) {
+ active = [bestUrl, ...active.filter((item) => item !== bestUrl)];
+ }
+ if (anySlowProgress) skipNextDelay = true;
}
}
if (result !== "done")
diff --git a/packages/local-installation/src/native-dependencies.test.ts b/packages/local-installation/src/native-dependencies.test.ts
index e98327dc..b826b2f1 100644
--- a/packages/local-installation/src/native-dependencies.test.ts
+++ b/packages/local-installation/src/native-dependencies.test.ts
@@ -685,6 +685,47 @@ it("prepares real executable launchers and reuses verified warm dependencies ent
})
).env.GOPROXY,
).toBe("https://proxy.example");
+ // When downloading Go falls back to the China mirror, GOPROXY and the
+ // package registry order switch to cn in the same preparation.
+ vi.stubEnv("GOPROXY", "");
+ const fallbackHome = path.join(root, "home-fallback");
+ await mkdir(path.dirname(regionFile(fallbackHome)), { recursive: true });
+ await writeFile(
+ regionFile(fallbackHome),
+ JSON.stringify({
+ schema: REGION_SCHEMA,
+ region: "global",
+ resolved_at: new Date().toISOString(),
+ method: "probe",
+ }),
+ );
+ download.mockClear();
+ download.mockImplementation(async (options) => {
+ const name = options.url.includes("/go")
+ ? "go"
+ : options.url.includes("/pnpm/")
+ ? "pnpm"
+ : options.url.includes("/npm/")
+ ? "npm"
+ : "postgres";
+ await writeFile(options.output, await readFile(archives[name]!));
+ return name === "go" ? (options.mirrors?.[0] ?? options.url) : options.url;
+ });
+ const fallenBack = await prepareNativeDependencies({
+ repo,
+ home: fallbackHome,
+ signal: new AbortController().signal,
+ });
+ expect(fallenBack.registries).toEqual([
+ "https://registry.npmmirror.com/",
+ "https://registry.npmjs.org/",
+ ]);
+ expect(fallenBack.env.pnpm_config_registry).toBe(
+ "https://registry.npmmirror.com/",
+ );
+ expect(fallenBack.env.GOPROXY).toBe(
+ "https://goproxy.cn|https://proxy.golang.org|direct",
+ );
}, 15000);
describe("native voice tools", () => {
const voice = {
diff --git a/packages/local-installation/src/native-dependencies.ts b/packages/local-installation/src/native-dependencies.ts
index 7102b201..c570d5ef 100644
--- a/packages/local-installation/src/native-dependencies.ts
+++ b/packages/local-installation/src/native-dependencies.ts
@@ -579,23 +579,10 @@ export async function prepareNativeDependencies(options: {
const configuredRegistry = configuredNpmRegistry();
// Only downloads resolve the region: a checkout that brings its services
// and TeamHub binaries prepares offline.
- const region =
- withGo || withPackages
- ? await resolveRegion(options.home, {
- signal: options.signal,
- fetcher: options.fetcher,
- })
- : undefined;
- const registries = !withPackages
- ? []
- : configuredRegistry
- ? [configuredRegistry]
- : orderByRegion(region!, [npmRegistry, npmMirrorRegistry]);
- if (registries[0])
- options.onEvent?.({
- kind: "log",
- stage: "release",
- message: `Using package registry ${new URL(registries[0]).host}.\n`,
+ if (withGo || withPackages)
+ await resolveRegion(options.home, {
+ signal: options.signal,
+ fetcher: options.fetcher,
});
const component = async (name: string, artifact: Artifact) => {
const startedAt = Date.now();
@@ -647,6 +634,26 @@ export async function prepareNativeDependencies(options: {
maxBytes: 32 * 1024 ** 2,
});
}
+ // Re-read after toolchain downloads so GOPROXY and package registries pick
+ // up any region fallback recorded during those downloads.
+ const region =
+ withGo || withPackages
+ ? await resolveRegion(options.home, {
+ signal: options.signal,
+ fetcher: options.fetcher,
+ })
+ : undefined;
+ const registries = !withPackages
+ ? []
+ : configuredRegistry
+ ? [configuredRegistry]
+ : orderByRegion(region!, [npmRegistry, npmMirrorRegistry]);
+ if (registries[0])
+ options.onEvent?.({
+ kind: "log",
+ stage: "release",
+ message: `Using package registry ${new URL(registries[0]).host}.\n`,
+ });
const pg = await component(
`PostgreSQL ${postgres.postgresVersion} / pgvector ${postgres.pgvectorVersion}`,
{
diff --git a/packages/local-installation/src/npm-registry.test.ts b/packages/local-installation/src/npm-registry.test.ts
index 60316223..68a85e5b 100644
--- a/packages/local-installation/src/npm-registry.test.ts
+++ b/packages/local-installation/src/npm-registry.test.ts
@@ -1,3 +1,4 @@
+import { setTimeout as delay } from "node:timers/promises";
import { afterEach, expect, it, vi } from "vitest";
import {
configuredNpmRegistry,
@@ -17,6 +18,32 @@ const slow = (bytes: number) =>
}),
);
+const timed = (totalBytes: number, durationMs: number, chunks = 4) =>
+ new Response(
+ new ReadableStream<Uint8Array>({
+ async start(controller) {
+ const chunkSize = Math.ceil(totalBytes / chunks);
+ let sent = 0;
+ const stepMs = durationMs / chunks;
+ for (let i = 0; i < chunks && sent < totalBytes; i += 1) {
+ await delay(stepMs);
+ const size = Math.min(chunkSize, totalBytes - sent);
+ sent += size;
+ try {
+ controller.enqueue(new Uint8Array(size));
+ } catch {
+ return;
+ }
+ }
+ try {
+ controller.close();
+ } catch {
+ // Reader already cancelled when the round ended early.
+ }
+ },
+ }),
+ );
+
it("puts the registry that delivers more of the probe first", async () => {
const requested: string[] = [];
const order = await probeNpmRegistries(
@@ -30,7 +57,7 @@ it("puts the registry that delivers more of the probe first", async () => {
},
50,
);
- expect(order).toEqual([
+ expect(order).toMatchObject([
{ registry: "https://registry.npmmirror.com/", bytes: 4096 },
{ registry: "https://registry.npmjs.org/", bytes: 16 },
]);
@@ -40,6 +67,54 @@ it("puts the registry that delivers more of the probe first", async () => {
]);
});
+it("prefers the faster registry when both finish the full tarball within the probe window", async () => {
+ const order = await probeNpmRegistries(
+ new AbortController().signal,
+ async (url) =>
+ (url as URL | string).toString().includes("npmmirror")
+ ? timed(32 * 1024, 15)
+ : timed(32 * 1024, 140),
+ 400,
+ );
+ expect(order[0]?.registry).toBe("https://registry.npmmirror.com/");
+ expect(order[1]?.registry).toBe("https://registry.npmjs.org/");
+});
+
+it("stops a probe round early once one registry delivers the probe target", async () => {
+ const target = 1024 * 1024;
+ const startedAt = Date.now();
+ const order = await probeNpmRegistries(
+ new AbortController().signal,
+ async (url) => {
+ if ((url as URL | string).toString().includes("npmmirror"))
+ return new Response(new Uint8Array(target * 2));
+ return new Response(
+ new ReadableStream({ pull: () => new Promise(() => {}) }),
+ );
+ },
+ 4_000,
+ );
+ expect(order[0]?.registry).toBe("https://registry.npmmirror.com/");
+ expect(Date.now() - startedAt).toBeLessThan(1_000);
+});
+
+it("recovers from a single-round hiccup through best-of-three confirmation", async () => {
+ let mirrorCalls = 0;
+ const order = await probeNpmRegistries(
+ new AbortController().signal,
+ async (url) => {
+ if ((url as URL | string).toString().includes("npmmirror")) {
+ mirrorCalls += 1;
+ return mirrorCalls === 1 ? timed(32 * 1024, 160) : timed(32 * 1024, 15);
+ }
+ return timed(32 * 1024, 90);
+ },
+ 400,
+ );
+ expect(mirrorCalls).toBe(3);
+ expect(order[0]?.registry).toBe("https://registry.npmmirror.com/");
+});
+
it("measures nothing when neither registry answers", async () => {
expect(
await probeNpmRegistries(
@@ -49,7 +124,7 @@ it("measures nothing when neither registry answers", async () => {
},
50,
),
- ).toEqual([
+ ).toMatchObject([
{ registry: "https://registry.npmjs.org/", bytes: 0 },
{ registry: "https://registry.npmmirror.com/", bytes: 0 },
]);
diff --git a/packages/local-installation/src/npm-registry.ts b/packages/local-installation/src/npm-registry.ts
index b809a2ca..60f594b2 100644
--- a/packages/local-installation/src/npm-registry.ts
+++ b/packages/local-installation/src/npm-registry.ts
@@ -35,53 +35,153 @@ export function configuredNpmRegistry() {
);
}
-/**
- * Measures how many bytes of the same tarball the public registry and its
- * China mirror each deliver within the probe window, most first; -1 when a
- * registry refused. region.ts decides the download region from it.
- */
-export async function probeNpmRegistries(
+export interface NpmRegistryProbe {
+ registry: string;
+ bytes: number;
+ elapsedMs: number;
+}
+
+// 1 MiB measures real body throughput without waiting the full window on a fast
+// host, and avoids tying when both registries finish the full 4.5 MiB tarball.
+const PROBE_TARGET_BYTES = 1024 * 1024;
+const DECISIVE_RATIO = 2;
+const MAX_PROBE_ROUNDS = 3;
+
+function compareProbe(left: NpmRegistryProbe, right: NpmRegistryProbe): number {
+ if (left.bytes > 0 !== right.bytes > 0) return left.bytes > 0 ? -1 : 1;
+ if (left.bytes <= 0) return 0;
+ return right.bytes - left.bytes || left.elapsedMs - right.elapsedMs;
+}
+
+function roundRatio(first: NpmRegistryProbe, second: NpmRegistryProbe): number {
+ if (first.bytes <= 0) return 0;
+ if (second.bytes <= 0) return Number.POSITIVE_INFINITY;
+ const firstRate = first.bytes / Math.max(first.elapsedMs, 1);
+ const secondRate = second.bytes / Math.max(second.elapsedMs, 1);
+ return firstRate / secondRate;
+}
+
+async function probeOnce(
signal: AbortSignal,
- fetcher: typeof fetch = fetch,
- probeMs = 4_000,
-): Promise<{ registry: string; bytes: number }[]> {
+ fetcher: typeof fetch,
+ probeMs: number,
+): Promise<{ results: NpmRegistryProbe[]; timedOut: boolean }> {
+ signal.throwIfAborted();
const registries = [npmRegistry, npmMirrorRegistry];
- const window = AbortSignal.any([signal, AbortSignal.timeout(probeMs)]);
- // A body that ignores the signal still stops counting when the window ends.
+ const round = new AbortController();
+ let timedOut = false;
+ const onParentAbort = () => round.abort();
+ signal.addEventListener("abort", onParentAbort, { once: true });
+ const timer = setTimeout(() => {
+ timedOut = true;
+ round.abort();
+ }, probeMs);
+ // A body that ignores the signal still stops counting when the round ends.
const closed = new Promise<never>((_resolve, reject) =>
- window.addEventListener("abort", () => reject(new Error())),
+ round.signal.addEventListener("abort", () => reject(new Error()), {
+ once: true,
+ }),
);
closed.catch(() => {});
- const received = await Promise.all(
- registries.map(async (registry) => {
- let bytes = 0;
- try {
- const response = await fetcher(
- npmTarballUrl(registry, "pnpm", "11.7.0"),
- { redirect: "error", signal: window },
- );
- if (!response.ok || !response.body) {
- await response.body?.cancel();
- return -1;
- }
- const reader = response.body.getReader();
+ const startedAt = performance.now();
+ try {
+ const measured = await Promise.all(
+ registries.map(async (registry): Promise<NpmRegistryProbe> => {
+ let bytes = 0;
+ let elapsedMs = 0;
try {
- for (;;) {
- const { done, value } = await Promise.race([reader.read(), closed]);
- if (done) break;
- bytes += value.byteLength;
+ const response = await fetcher(
+ npmTarballUrl(registry, "pnpm", "11.7.0"),
+ { redirect: "error", signal: round.signal },
+ );
+ if (!response.ok || !response.body) {
+ elapsedMs = performance.now() - startedAt;
+ await response.body?.cancel();
+ return { registry, bytes: -1, elapsedMs };
+ }
+ const reader = response.body.getReader();
+ try {
+ for (;;) {
+ const { done, value } = await Promise.race([
+ reader.read(),
+ closed,
+ ]);
+ if (done) break;
+ bytes = Math.min(bytes + value.byteLength, PROBE_TARGET_BYTES);
+ if (bytes >= PROBE_TARGET_BYTES) {
+ elapsedMs = performance.now() - startedAt;
+ round.abort();
+ break;
+ }
+ }
+ if (!elapsedMs) elapsedMs = performance.now() - startedAt;
+ } finally {
+ await reader.cancel().catch(() => {});
}
- } finally {
- await reader.cancel().catch(() => {});
+ } catch {
+ // The round ending mid-body still measured progress.
+ if (!elapsedMs) elapsedMs = performance.now() - startedAt;
}
- } catch {
- // The probe window ending mid-body still measured progress.
- }
- return bytes;
- }),
+ return { registry, bytes, elapsedMs };
+ }),
+ );
+ signal.throwIfAborted();
+ return { results: measured.sort(compareProbe), timedOut };
+ } finally {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", onParentAbort);
+ }
+}
+
+/**
+ * Races the public registry and its China mirror on the same tarball (up to
+ * 1 MiB per round, fastest first; -1 when a registry refused). Confirms in a
+ * best-of-three sequence unless neither answers or a full-window round already
+ * shows a clear margin. region.ts decides the download region from it.
+ */
+export async function probeNpmRegistries(
+ signal: AbortSignal,
+ fetcher: typeof fetch = fetch,
+ probeMs = 4_000,
+): Promise<NpmRegistryProbe[]> {
+ const samples = new Map<string, NpmRegistryProbe[]>(
+ [npmRegistry, npmMirrorRegistry].map((registry) => [registry, []]),
);
- signal.throwIfAborted();
- return registries
- .map((registry, index) => ({ registry, bytes: received[index]! }))
- .sort((left, right) => right.bytes - left.bytes);
+ const wins = new Map<string, number>();
+ let lastRound: NpmRegistryProbe[] = [];
+ for (let attempt = 0; attempt < MAX_PROBE_ROUNDS; attempt += 1) {
+ const { results, timedOut } = await probeOnce(signal, fetcher, probeMs);
+ lastRound = results;
+ for (const entry of results) samples.get(entry.registry)?.push(entry);
+ const [first, second] = results;
+ if (!first || first.bytes <= 0) {
+ if (attempt === 0) return results;
+ continue;
+ }
+ wins.set(first.registry, (wins.get(first.registry) ?? 0) + 1);
+ // A full-window probe with a clear lead already measured sustained speed.
+ if (
+ attempt === 0 &&
+ timedOut &&
+ second &&
+ roundRatio(first, second) >= DECISIVE_RATIO
+ )
+ return results;
+ if ((wins.get(first.registry) ?? 0) >= 2) break;
+ }
+ if ((samples.get(npmRegistry)?.length ?? 0) <= 1) return lastRound;
+ return [npmRegistry, npmMirrorRegistry]
+ .map((registry) => {
+ const entries = [...(samples.get(registry) ?? [])].sort(compareProbe);
+ // Lower-median sample resists a single outlier across 2 or 3 rounds.
+ const median = entries[Math.floor((entries.length - 1) / 2)]!;
+ return { median, wins: wins.get(registry) ?? 0 };
+ })
+ .sort((left, right) => {
+ if (left.median.bytes > 0 !== right.median.bytes > 0)
+ return left.median.bytes > 0 ? -1 : 1;
+ if (left.median.bytes <= 0) return 0;
+ return right.wins - left.wins || compareProbe(left.median, right.median);
+ })
+ .map((item) => item.median);
}
diff --git a/packages/local-installation/src/region.test.ts b/packages/local-installation/src/region.test.ts
index d3aa9b77..d697c9f1 100644
--- a/packages/local-installation/src/region.test.ts
+++ b/packages/local-installation/src/region.test.ts
@@ -54,7 +54,7 @@ function probe(mirror: number, global: number) {
: new Response(new Uint8Array(bytes));
}) as unknown as typeof fetch & ReturnType<typeof vi.fn>;
}
-const day = 24 * 60 * 60_000;
+const hour = 60 * 60_000;
it("takes SIMPLEX_REGION over a saved region and records it", async () => {
const directory = await home();
@@ -79,12 +79,12 @@ it("treats auto and unset as not forced and refuses anything else", () => {
);
});
-it("reuses a region saved within 7 days without probing", async () => {
+it("reuses a region saved within 24 hours without probing", async () => {
const directory = await home();
await saved(directory, {
region: "cn",
method: "fallback",
- resolved_at: new Date(Date.now() - 6 * day).toISOString(),
+ resolved_at: new Date(Date.now() - 20 * hour).toISOString(),
});
const fetcher = probe(1, 10);
expect(await resolveRegion(directory, { fetcher })).toBe("cn");
@@ -95,7 +95,7 @@ it("probes again once the saved region is stale or unreadable", async () => {
for (const contents of [
{
region: "global",
- resolved_at: new Date(Date.now() - 8 * day).toISOString(),
+ resolved_at: new Date(Date.now() - 25 * hour).toISOString(),
},
{ region: "mars" },
] as const) {
@@ -103,7 +103,7 @@ it("probes again once the saved region is stale or unreadable", async () => {
await saved(directory, contents as Pick<RegionRecord, "region">);
const fetcher = probe(4096, 16);
expect(await resolveRegion(directory, { fetcher })).toBe("cn");
- expect(fetcher).toHaveBeenCalledTimes(2);
+ expect(fetcher).toHaveBeenCalled();
const record = await read(directory);
expect(record).toMatchObject({ region: "cn", method: "probe" });
expect(Date.now() - Date.parse(record.resolved_at)).toBeLessThan(60_000);
@@ -118,8 +118,10 @@ it("resolves once per process and home", async () => {
resolveRegion(directory, { fetcher }),
]);
expect([first, second]).toEqual(["global", "global"]);
+ const callsAfterFirstResolution = fetcher.mock.calls.length;
+ expect(callsAfterFirstResolution).toBeGreaterThan(0);
expect(await resolveRegion(directory, { fetcher })).toBe("global");
- expect(fetcher).toHaveBeenCalledTimes(2);
+ expect(fetcher).toHaveBeenCalledTimes(callsAfterFirstResolution);
expect(await read(directory)).toMatchObject({
region: "global",
method: "probe",
@@ -222,3 +224,166 @@ it("keeps a forced region when a download falls back", async () => {
await recordRegionFallback(directory, "global");
expect(await resolveRegion(directory)).toBe("cn");
});
+
+it("switches to a faster mirror on a slow transfer and records the fallback region", async () => {
+ const directory = await home();
+ await saved(directory, { region: "global" });
+ const payload = Buffer.alloc(64 * 1024, 0x62);
+ const payloadDigest = createHash("sha256").update(payload).digest("hex");
+ const hosts: string[] = [];
+ const fetcher = (async (
+ input: string | URL | Request,
+ init?: RequestInit,
+ ) => {
+ const url = new URL(requestUrlText(input));
+ hosts.push(url.host);
+ const range = new Headers(init?.headers).get("range");
+ const start = range ? Number(/^bytes=(\d+)-$/.exec(range)?.[1] ?? 0) : 0;
+ const slice = payload.subarray(start);
+ const headers: Record<string, string> = {
+ "content-length": String(slice.length),
+ ...(start > 0
+ ? {
+ "content-range": `bytes ${start}-${payload.length - 1}/${payload.length}`,
+ }
+ : {}),
+ };
+ if (url.host === "nodejs.org") {
+ // Dribbles 2 KiB every 40 ms (~50 KB/s), far below the slow threshold.
+ return new Response(
+ new ReadableStream<Uint8Array>({
+ async start(controller) {
+ for (let offset = 0; offset < slice.length; offset += 2048) {
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ try {
+ controller.enqueue(slice.subarray(offset, offset + 2048));
+ } catch {
+ return;
+ }
+ }
+ try {
+ controller.close();
+ } catch {
+ // Cancelled when switching to the mirror.
+ }
+ },
+ }),
+ { status: start > 0 ? 206 : 200, headers },
+ );
+ }
+ return new Response(slice, { status: start > 0 ? 206 : 200, headers });
+ }) as typeof fetch;
+
+ const served = await downloadInRegion(
+ directory,
+ {
+ ...sources,
+ output: path.join(directory, "node.tgz"),
+ algorithm: "sha256",
+ digest: payloadDigest,
+ maxBytes: payload.length,
+ signal: new AbortController().signal,
+ },
+ fetcher,
+ {
+ attempts: 2,
+ retryDelayMs: 0,
+ idleTimeoutMs: 5_000,
+ slowCheckAfterMs: 100,
+ minBytesPerSecond: 200_000,
+ minRemainingMs: 300,
+ },
+ );
+ expect(served).toContain("cdn.npmmirror.com");
+ expect(hosts).toEqual(["nodejs.org", "cdn.npmmirror.com"]);
+ expect(await read(directory)).toMatchObject({
+ region: "cn",
+ method: "fallback",
+ });
+ expect(await resolveRegion(directory)).toBe("cn");
+});
+
+it("keeps the saved region when a slow primary is still faster than the mirror", async () => {
+ const directory = await home();
+ await saved(directory, { region: "cn" });
+ const payload = Buffer.alloc(64 * 1024, 0x63);
+ const payloadDigest = createHash("sha256").update(payload).digest("hex");
+ const hosts: string[] = [];
+ const throttled = (
+ slice: Uint8Array,
+ chunkBytes: number,
+ intervalMs: number,
+ ) =>
+ new ReadableStream<Uint8Array>({
+ async start(controller) {
+ for (let offset = 0; offset < slice.length; offset += chunkBytes) {
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
+ try {
+ controller.enqueue(slice.subarray(offset, offset + chunkBytes));
+ } catch {
+ return;
+ }
+ }
+ try {
+ controller.close();
+ } catch {
+ // Cancelled when comparing mirrors.
+ }
+ },
+ });
+ const fetcher = (async (
+ input: string | URL | Request,
+ init?: RequestInit,
+ ) => {
+ const url = new URL(requestUrlText(input));
+ hosts.push(url.host);
+ const range = new Headers(init?.headers).get("range");
+ const start = range ? Number(/^bytes=(\d+)-$/.exec(range)?.[1] ?? 0) : 0;
+ const slice = payload.subarray(start);
+ const headers: Record<string, string> = {
+ "content-length": String(slice.length),
+ ...(start > 0
+ ? {
+ "content-range": `bytes ${start}-${payload.length - 1}/${payload.length}`,
+ }
+ : {}),
+ };
+ // Mirror (nodejs.org) is slightly slower than primary (cdn.npmmirror.com).
+ const chunkBytes = url.host === "cdn.npmmirror.com" ? 4096 : 2048;
+ return new Response(throttled(slice, chunkBytes, 30), {
+ status: start > 0 ? 206 : 200,
+ headers,
+ });
+ }) as typeof fetch;
+
+ const served = await downloadInRegion(
+ directory,
+ {
+ ...sources,
+ output: path.join(directory, "node.tgz"),
+ algorithm: "sha256",
+ digest: payloadDigest,
+ maxBytes: payload.length,
+ signal: new AbortController().signal,
+ },
+ fetcher,
+ {
+ attempts: 2,
+ retryDelayMs: 0,
+ idleTimeoutMs: 5_000,
+ slowCheckAfterMs: 100,
+ minBytesPerSecond: 300_000,
+ minRemainingMs: 250,
+ },
+ );
+ expect(served).toContain("cdn.npmmirror.com");
+ expect(hosts).toEqual([
+ "cdn.npmmirror.com",
+ "nodejs.org",
+ "cdn.npmmirror.com",
+ ]);
+ expect(await read(directory)).toMatchObject({
+ region: "cn",
+ method: "probe",
+ });
+});
diff --git a/packages/local-installation/src/region.ts b/packages/local-installation/src/region.ts
index 32f52600..2862cecb 100644
--- a/packages/local-installation/src/region.ts
+++ b/packages/local-installation/src/region.ts
@@ -9,7 +9,7 @@ export type { Region };
// The record localmodels shares: see scripts/installs/README.md.
export const REGION_SCHEMA = "simplex.region/v1";
-const STALE_MS = 7 * 24 * 60 * 60_000;
+const STALE_MS = 24 * 60 * 60_000;
export interface RegionRecord {
schema: typeof REGION_SCHEMA;
region: Region;
@@ -106,8 +106,8 @@ async function resolve(
/**
* The download region of `home`: SIMPLEX_REGION when it names one, else a
- * region.json resolved within the last 7 days, else the npm registry probe
- * (cn when the China mirror delivers more). Resolved once per process.
+ * region.json resolved within the last 24 hours, else the npm registry probe
+ * (cn when the China mirror wins). Resolved once per process.
*/
export function resolveRegion(
home: string,
diff --git a/scripts/installs/README.md b/scripts/installs/README.md
index 374e1357..96ed77d6 100644
--- a/scripts/installs/README.md
+++ b/scripts/installs/README.md
@@ -120,10 +120,12 @@ The installer resolves the region once per process, in this order:
1. `SIMPLEX_REGION`: `cn` or `global` forces that region; `auto` or unset
does not. Any other value is an error.
2. `<LINGER_HOME>/runtime/region.json` when it was resolved within the last
- 7 days.
-3. A probe: the pinned pnpm tarball from `registry.npmjs.org` and from
- `cdn.npmmirror.com` for 4 seconds; `cn` when the China mirror delivers
- more. A probe that reaches neither uses `global` and is not saved.
+ 24 hours.
+3. A probe: up to three rounds racing the first 1 MiB of the pinned pnpm
+ tarball from `registry.npmjs.org` and `cdn.npmmirror.com` (4 seconds per
+ round), stopping once one registry wins two rounds or leads clearly over a
+ full window; `cn` when the China mirror wins. A probe that reaches neither
+ uses `global` and is not saved.
```json
{
@@ -134,9 +136,10 @@ The installer resolves the region once per process, in this order:
}
```
-`method` is `env`, `probe` or `fallback`. When every source of the preferred
-region fails and the other region serves the download, the file is rewritten
-with that region and `fallback`, and later downloads start there (unless
+`method` is `env`, `probe` or `fallback`. When the preferred region fails or
+downloads slowly with substantial work left and a source in the other region
+proves faster and finishes the download, the file is rewritten with that
+region and `fallback`, and later downloads start there (unless
`SIMPLEX_REGION` forces a region).
| Download | global first | cn first |