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
2 changes: 2 additions & 0 deletions cli/src/lib/updater-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ export const UpdaterConfig = {
timeoutsMs: {
automatic: 900,
manual: 10_000,
// Covers the full release binary body (~100 MB), not just the response headers.
download: 300_000,
},
intervalsMs: UpdaterIntervalsMs,
automaticCheckSkipCommands: ['completion', 'doctor', 'update', 'upgrade'],
Expand Down
104 changes: 102 additions & 2 deletions cli/src/lib/updater.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ import {
resolveCommandSelection,
} from '@/lib/command-parser.ts';
import { configFile, kvSet } from '@/lib/config.ts';
import { ConfigurationError } from '@/lib/errors.ts';
import {
ConfigurationError,
EXIT_NETWORK,
NetworkError,
TimeoutError,
} from '@/lib/errors.ts';
import { resolveProcessExecutablePath } from '@/lib/executable-path.ts';
import { createCliRuntime } from '@/lib/runtime.ts';
import { UpdaterConfig } from '@/lib/updater-config.ts';
Expand Down Expand Up @@ -122,10 +127,34 @@ function githubBinaryFetch(options: {
binary: string;
checksum: string;
version?: string;
binaryDelayMs?: number;
binaryError?: unknown;
}): typeof fetch {
const version = options.version ?? UPDATE_TEST_VERSION;
return (async (url: string | URL | Request) => {
return (async (url: string | URL | Request, init?: RequestInit) => {
const requestedUrl = fetchInputUrl(url);
if (
requestedUrl === LINUX_X64_DOWNLOAD_URL &&
(options.binaryDelayMs !== undefined || options.binaryError !== undefined)
) {
const signal = init?.signal ?? undefined;
const body = new ReadableStream<Uint8Array>({
async start(controller) {
await new Promise(done =>
setTimeout(done, options.binaryDelayMs ?? 0)
);
if (options.binaryError !== undefined) {
controller.error(options.binaryError);
} else if (signal?.aborted) {
controller.error(signal.reason);
} else {
controller.enqueue(new TextEncoder().encode(options.binary));
controller.close();
}
},
});
return new Response(body, { status: 200 });
}
if (requestedUrl.includes(`/releases/tags/v${version}`)) {
return new Response(JSON.stringify(githubReleaseMetadata(version)), {
status: 200,
Expand Down Expand Up @@ -529,6 +558,77 @@ describe('binary self-update', () => {
expect(readFileSync(targetPath, 'utf8')).toBe(newBinary);
});

test('downloads a GitHub binary with a longer timeout than metadata requests', async () => {
const targetPath = join(testHome, 'altertable');
const newBinary = `#!/bin/sh\necho ${UPDATE_TEST_VERSION}\n`;
writeFileSync(targetPath, '#!/bin/sh\necho 1.0.0\n', { mode: 0o755 });

const result = await installGitHubBinaryRelease(UPDATE_TEST_VERSION, {
targetPath,
platform: 'linux-x64',
timeoutMs: 20,
downloadTimeoutMs: 5_000,
fetchImpl: githubBinaryFetch({
binary: newBinary,
checksum: sha256(newBinary),
binaryDelayMs: 60,
}),
});

expect(result.verified_version).toBe(UPDATE_TEST_VERSION);
expect(readFileSync(targetPath, 'utf8')).toBe(newBinary);
});

test('reports a GitHub binary download timeout with its cause', async () => {
const targetPath = join(testHome, 'altertable');
const originalBinary = '#!/bin/sh\necho 1.0.0\n';
writeFileSync(targetPath, originalBinary, { mode: 0o755 });

try {
await installGitHubBinaryRelease(UPDATE_TEST_VERSION, {
targetPath,
platform: 'linux-x64',
downloadTimeoutMs: 20,
fetchImpl: githubBinaryFetch({
binary: 'unused',
checksum: '0'.repeat(64),
binaryDelayMs: 60,
}),
});
throw new Error('Expected download to time out.');
} catch (error) {
expect(error).toBeInstanceOf(TimeoutError);
expect((error as TimeoutError).message).toBe(
`Timed out downloading ${LINUX_X64_ASSET} after 0.02s.`
);
expect((error as TimeoutError).exitCode).toBe(EXIT_NETWORK);
}
expect(readFileSync(targetPath, 'utf8')).toBe(originalBinary);
});

test('reports GitHub binary download network failures with their cause', async () => {
const targetPath = join(testHome, 'altertable');
writeFileSync(targetPath, '#!/bin/sh\necho 1.0.0\n', { mode: 0o755 });

try {
await installGitHubBinaryRelease(UPDATE_TEST_VERSION, {
targetPath,
platform: 'linux-x64',
fetchImpl: githubBinaryFetch({
binary: 'unused',
checksum: '0'.repeat(64),
binaryError: new Error('connection reset by peer'),
}),
});
throw new Error('Expected download to fail.');
} catch (error) {
expect(error).toBeInstanceOf(NetworkError);
expect((error as NetworkError).message).toBe(
`Unable to download ${LINUX_X64_ASSET}: connection reset by peer`
);
}
});

test('rejects GitHub binary install on checksum mismatch without replacing target', async () => {
const targetPath = join(testHome, 'altertable');
const originalBinary = '#!/bin/sh\necho 1.0.0\n';
Expand Down
68 changes: 61 additions & 7 deletions cli/src/lib/updater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ import type { CliContext } from '@/context.ts';
import { isJsonOutput } from '@/context.ts';
import { configDir, configGetGlobal } from '@/lib/config.ts';
import { copyProcessEnv, readEnv, readEnvFrom } from '@/lib/env.ts';
import { CliError, HttpError, NetworkError } from '@/lib/errors.ts';
import {
CliError,
HttpError,
NetworkError,
TimeoutError,
} from '@/lib/errors.ts';
import { resolveProcessExecutablePath } from '@/lib/executable-path.ts';
import { hasObjectKey } from '@/lib/object.ts';
import type { OutputSink } from '@/lib/runtime.ts';
Expand Down Expand Up @@ -127,6 +132,8 @@ type InstallCliUpdateOptions = {
targetPath?: string;
platform?: ReleasePlatform;
timeoutMs?: number;
/** Timeout for the whole release binary download, body included. */
downloadTimeoutMs?: number;
fetchImpl?: typeof fetch;
spawnImpl?: SpawnSyncImpl;
stdio?: 'inherit' | 'pipe';
Expand Down Expand Up @@ -529,13 +536,55 @@ async function fetchText(
return await response.text();
}

function isTimeoutAbort(error: unknown): boolean {
return (
error instanceof Error &&
(error.name === 'TimeoutError' || error.name === 'AbortError')
);
}

function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}

function downloadError(
label: string,
timeoutMs: number,
error: unknown
): NetworkError {
if (isTimeoutAbort(error)) {
return new TimeoutError(
`Timed out downloading ${label} after ${timeoutMs / 1000}s.`,
{ cause: error }
);
}
return new NetworkError(
`Unable to download ${label}: ${errorMessage(error)}`,
{ cause: error }
);
}

/** Downloads a release asset; the timeout covers headers and body. */
async function fetchBytes(
url: string,
label: string,
timeoutMs: number,
fetchImpl: typeof fetch
): Promise<Uint8Array> {
const response = await fetchResponse(url, timeoutMs, fetchImpl);
return new Uint8Array(await response.arrayBuffer());
let response: Response;
try {
response = await fetchResponse(url, timeoutMs, fetchImpl);
} catch (error) {
if (error instanceof NetworkError) {
throw downloadError(label, timeoutMs, error.cause);
}
throw error;
}
try {
return new Uint8Array(await response.arrayBuffer());
} catch (error) {
throw downloadError(label, timeoutMs, error);
}
}

function readStringProperty(data: unknown, key: string): string {
Expand Down Expand Up @@ -938,13 +987,15 @@ async function writeVerifiedGitHubBinaryDownload(options: {
release: GitHubBinaryRelease;
targetPath: string;
timeoutMs: number;
downloadTimeoutMs: number;
fetchImpl: typeof fetch;
}): Promise<string> {
const tempPath = tempSiblingPath(options.targetPath, 'download');
try {
const bytes = await fetchBytes(
options.release.assetDownloadUrl,
options.timeoutMs,
options.release.assetName,
options.downloadTimeoutMs,
options.fetchImpl
);
writeFileSync(tempPath, bytes, { mode: 0o755 });
Expand Down Expand Up @@ -973,9 +1024,10 @@ async function writeVerifiedGitHubBinaryDownload(options: {
if (error instanceof CliError) {
throw error;
}
throw new CliError('Unable to install GitHub release binary.', {
cause: error,
});
throw new CliError(
`Unable to install GitHub release binary: ${errorMessage(error)}`,
{ cause: error }
);
}
}

Expand All @@ -996,6 +1048,8 @@ export async function installGitHubBinaryRelease(
release,
targetPath,
timeoutMs,
downloadTimeoutMs:
options.downloadTimeoutMs ?? UpdaterConfig.timeoutsMs.download,
fetchImpl,
});
try {
Expand Down
Loading