import http from 'http'; import type { AddressInfo } from 'net'; import Limrun, { GradleSnapshotRequestUnavailableError, NotFoundError } from '../src'; import { isDirectInstanceHttpError } from '../src/internal/direct-instance-errors'; type DaemonCall = { method: string | undefined; path: string | undefined; auth: string | undefined; body: string; }; /** A build daemon that records requests and answers each with the next status and body. */ async function withDaemon( answers: Array<{ status: number; body: string }>, run: (apiUrl: string, calls: DaemonCall[]) => Promise, ) { const calls: DaemonCall[] = []; const server = http.createServer(async (req, res) => { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(Buffer.from(chunk)); calls.push({ method: req.method, path: req.url, auth: req.headers.authorization, body: Buffer.concat(chunks).toString(), }); const answer = answers.shift() ?? { status: 500, body: 'unexpected request' }; res.statusCode = answer.status; res.end(answer.body); }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); try { await run(`http://127.0.0.1:${(server.address() as AddressInfo).port}`, calls); } finally { await new Promise((resolve) => server.close(() => resolve())); } } const encryptionKey = Buffer.alloc(32, 7).toString('base64'); test('a snapshot request sends the names and the key to the build daemon and reads the restore there', async () => { const save = { phase: 'idle' }; const answers = [ { restore: { phase: 'pending' }, save }, { restore: { phase: 'restoring', key: 'myapp-main' }, save }, { restore: { phase: 'restored', key: 'myapp-main', bytes: 2048 }, save }, ].map((report) => ({ status: 200, body: JSON.stringify(report) })); await withDaemon(answers, async (apiUrl, calls) => { const lim = new Limrun({ apiKey: 'management-key' }); const client = await lim.gradleInstances.createClient({ apiUrl, token: 'gradle-token' }); const updates: string[] = []; const result = await client.restoreSnapshot({ key: 'myapp-pr51', restoreKeys: ['myapp-pr51', 'myapp-main'], encryptionKey, onUpdate: (snapshot) => updates.push(snapshot.restore.phase), }); // The daemon's report reads like getSnapshot's: its key is the matched key, and the phase // older images report for the whole restore is the download. expect(result).toEqual({ restore: { phase: 'restored', matchedKey: 'myapp-main', bytes: 2048 }, save, }); expect(updates).toEqual(['pending', 'downloading', 'restored']); const read = { method: 'GET', path: '/snapshot', auth: 'Bearer gradle-token', body: '' }; expect(calls).toEqual([ { method: 'POST', path: '/snapshot', auth: 'Bearer gradle-token', body: JSON.stringify({ key: 'myapp-pr51', restoreKeys: ['myapp-pr51', 'myapp-main'], encryptionKey }), }, read, read, ]); }); }); test("a daemon's refusal carries its status and reason", async () => { await withDaemon( [{ status: 409, body: 'the instance already restores and saves other snapshot keys\n' }], async (apiUrl) => { const lim = new Limrun({ apiKey: 'management-key' }); const client = await lim.gradleInstances.createClient({ apiUrl, token: 'gradle-token' }); const err = await client.restoreSnapshot({ key: 'other', encryptionKey }).catch((e: unknown) => e); expect(isDirectInstanceHttpError(err, 409)).toBe(true); expect((err as Error).message).toBe( 'Disk snapshot request failed: 409 the instance already restores and saves other snapshot keys', ); expect((err as Error).message).not.toContain(encryptionKey); }, ); }); test('a 404 from the daemon is not a gone instance', async () => { await withDaemon([{ status: 404, body: '' }], async (apiUrl) => { const lim = new Limrun({ apiKey: 'management-key' }); const client = await lim.gradleInstances.createClient({ apiUrl, token: 'gradle-token' }); const err = await client.restoreSnapshot({ key: 'app', encryptionKey }).catch((e: unknown) => e); // A CLI would replace an instance it took for gone, so the daemon's 404 must not read as one. expect(err).toBeInstanceOf(GradleSnapshotRequestUnavailableError); expect(err).not.toBeInstanceOf(NotFoundError); }); });