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
83 changes: 83 additions & 0 deletions src/lib/__tests__/wizard-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,3 +407,86 @@ describe('extractZipArchive', () => {
);
});
});

describe('downloadWithRetry', () => {
const url = 'https://example.com/skill.zip';
const noSleep = () => Promise.resolve();
const okResponse = () =>
Promise.resolve({
ok: true,
status: 200,
statusText: 'OK',
arrayBuffer: () => Promise.resolve(new ArrayBuffer(3)),
});

it('returns the body on first success without sleeping', async () => {
let fetches = 0;

const bytes = await __test.downloadWithRetry(url, {
fetchImpl: (() => {
fetches += 1;
return okResponse();
}) as any,
sleepImpl: () => {
throw new Error('should not sleep');
},
});

expect(fetches).toBe(1);
expect(bytes).toHaveLength(3);
});

it('retries with exponential backoff before succeeding', async () => {
let attempts = 0;
const sleeps: number[] = [];

const bytes = await __test.downloadWithRetry(url, {
fetchImpl: (() => {
attempts += 1;
if (attempts < 3) return Promise.reject(new Error('fetch failed'));
return okResponse();
}) as any,
sleepImpl: (ms: number) => {
sleeps.push(ms);
return Promise.resolve();
},
backoffMs: 500,
});

expect(attempts).toBe(3);
expect(sleeps).toEqual([500, 1000]);
expect(bytes).toHaveLength(3);
});

it('treats a non-ok response as a failure and retries it', async () => {
let attempts = 0;

await expect(
__test.downloadWithRetry(url, {
fetchImpl: (() => {
attempts += 1;
return Promise.resolve({
ok: false,
status: 503,
statusText: 'Service Unavailable',
arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)),
});
}) as any,
sleepImpl: noSleep,
maxAttempts: 2,
}),
).rejects.toThrow(/HTTP 503 Service Unavailable/);

expect(attempts).toBe(2);
});

it('reports every attempt when all retries fail', async () => {
await expect(
__test.downloadWithRetry(url, {
fetchImpl: (() => Promise.reject(new Error('network down'))) as any,
sleepImpl: noSleep,
maxAttempts: 3,
}),
).rejects.toThrow(/attempt 1.*attempt 2.*attempt 3/s);
});
});
52 changes: 47 additions & 5 deletions src/lib/wizard-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,51 @@ function extractZipArchive(zip: Uint8Array, destDir: string): number {
return written;
}

const DOWNLOAD_TIMEOUT_MS = 60000; // per attempt
const DOWNLOAD_MAX_ATTEMPTS = 3;
const DOWNLOAD_BACKOFF_MS = 500; // doubles each retry

function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}

/** Download a URL to a buffer, retrying transient failures with backoff. */
async function downloadWithRetry(
url: string,
opts: {
fetchImpl?: typeof fetch;
sleepImpl?: (ms: number) => Promise<void>;
timeoutMs?: number;
maxAttempts?: number;
backoffMs?: number;
} = {},
): Promise<Uint8Array> {
const {
fetchImpl = fetch,
sleepImpl = sleep,
timeoutMs = DOWNLOAD_TIMEOUT_MS,
maxAttempts = DOWNLOAD_MAX_ATTEMPTS,
backoffMs = DOWNLOAD_BACKOFF_MS,
} = opts;

const failures: string[] = [];
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const resp = await fetchImpl(url, {
signal: AbortSignal.timeout(timeoutMs),
});
if (!resp.ok) throw new Error(`HTTP ${resp.status} ${resp.statusText}`);
return new Uint8Array(await resp.arrayBuffer());
} catch (err: any) {
failures.push(`attempt ${attempt}: ${err.message}`);
if (attempt < maxAttempts) {
await sleepImpl(backoffMs * 2 ** (attempt - 1));
}
}
}
throw new Error(`download failed — ${failures.join('; ')}`);
}

/**
* Download and extract a skill.
* By default installs to `<installDir>/.claude/skills/<id>/`.
Expand All @@ -142,11 +187,7 @@ export async function downloadSkill(

try {
fs.mkdirSync(skillDir, { recursive: true });
const resp = await fetch(skillEntry.downloadUrl, {
signal: AbortSignal.timeout(30000),
});
if (!resp.ok) throw new Error(`download failed with HTTP ${resp.status}`);
const zip = new Uint8Array(await resp.arrayBuffer());
const zip = await downloadWithRetry(skillEntry.downloadUrl);
step = 'extract';
const fileCount = extractZipArchive(zip, skillDir);
fs.writeFileSync(path.join(skillDir, '.posthog-wizard'), '');
Expand Down Expand Up @@ -1244,6 +1285,7 @@ export const WIZARD_TOOL_NAMES = {

export const __test = {
extractZipArchive,
downloadWithRetry,
writeLedgerAtomic,
readLedger,
applyAuditAdditions,
Expand Down
Loading