From f37faf6d2133f3bc5b289ef169e97abb3950959c Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 11 Nov 2026 03:40:28 +0000 Subject: [PATCH] Add bounded Fly Machines API client --- packages/api/src/fly-machines-client.ts | 183 ++++++++++++++++++ packages/api/test/fly-machines-client.test.ts | 178 +++++++++++++++++ 2 files changed, 361 insertions(+) create mode 100644 packages/api/src/fly-machines-client.ts create mode 100644 packages/api/test/fly-machines-client.test.ts diff --git a/packages/api/src/fly-machines-client.ts b/packages/api/src/fly-machines-client.ts new file mode 100644 index 00000000..a7139e37 --- /dev/null +++ b/packages/api/src/fly-machines-client.ts @@ -0,0 +1,183 @@ +/** A small, bounded adapter for Fly's documented Machines v1 API. */ + +export type FlyMachine = { + id: string; + name?: string; + state?: string; + config?: { metadata?: Record; [key: string]: unknown }; + [key: string]: unknown; +}; + +export type FlyMachineConfig = Record & { + metadata?: Record; +}; + +export type FlyClientErrorKind = "timeout" | "network" | "auth" | "rate_limit" | "server" | "http" | "invalid_response" | "ambiguous_create"; + +/** Error messages intentionally contain no URL, response body, or credential. */ +export class FlyClientError extends Error { + constructor( + message: string, + readonly kind: FlyClientErrorKind, + readonly status?: number, + options?: ErrorOptions, + ) { + super(message, options); + this.name = "FlyClientError"; + } +} + +export type FlyMachinesClientOptions = { + token: string; + /** Origin override is intended for local API tests. */ + apiOrigin?: string; + timeoutMs?: number; + maxRetries?: number; + fetch?: typeof fetch; + wait?: (milliseconds: number) => Promise; +}; + +const DEFAULT_ORIGIN = "https://api.machines.dev"; +const DEFAULT_TIMEOUT_MS = 5_000; +const DEFAULT_MAX_RETRIES = 2; +const OPERATION_METADATA_KEY = "factorize_operation_id"; + +function segment(value: string, name: string): string { + if (!value || value.includes("/") || value === "." || value === "..") { + throw new TypeError(`${name} must be a non-empty path segment`); + } + return encodeURIComponent(value); +} + +function errorFromStatus(status: number): FlyClientError { + if (status === 401 || status === 403) return new FlyClientError("Fly authentication failed", "auth", status); + if (status === 429) return new FlyClientError("Fly rate limit exceeded", "rate_limit", status); + if (status >= 500) return new FlyClientError("Fly service failed", "server", status); + if (status === 404) return new FlyClientError("Fly Machine was not found", "http", status); + return new FlyClientError("Fly request failed", "http", status); +} + +function isRetryable(error: unknown): boolean { + return error instanceof FlyClientError && ["timeout", "network", "server", "rate_limit"].includes(error.kind); +} + +/** + * The client never retries machine creation. A create is reconciled by a stable + * metadata operation id, so a repeated caller or ambiguous network result + * discovers the already-created Machine instead of creating a duplicate. + */ +export function createFlyMachinesClient(options: FlyMachinesClientOptions) { + if (!options.token) throw new TypeError("Fly token is required"); + const origin = (options.apiOrigin ?? DEFAULT_ORIGIN).replace(/\/$/, ""); + const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES; + if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new TypeError("timeoutMs must be a positive integer"); + if (!Number.isInteger(maxRetries) || maxRetries < 0 || maxRetries > 5) throw new TypeError("maxRetries must be between 0 and 5"); + const fetchImpl = options.fetch ?? fetch; + const wait = options.wait ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + + async function request(path: string, init: RequestInit, retrySafe: boolean): Promise { + let retries = 0; + while (true) { + let response: Response; + try { + response = await fetchImpl(`${origin}/v1${path}`, { + ...init, + headers: { authorization: `Bearer ${options.token}`, accept: "application/json", ...init.headers }, + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (cause) { + const kind = cause instanceof Error && cause.name === "TimeoutError" ? "timeout" : "network"; + const error = new FlyClientError(kind === "timeout" ? "Fly request timed out" : "Fly network request failed", kind, undefined, { cause }); + if (retrySafe && retries < maxRetries && isRetryable(error)) { + await wait(100 * (2 ** retries++)); + continue; + } + throw error; + } + if (!response.ok) { + await response.body?.cancel().catch(() => undefined); + const error = errorFromStatus(response.status); + if (retrySafe && retries < maxRetries && isRetryable(error)) { + await wait(100 * (2 ** retries++)); + continue; + } + throw error; + } + if (response.status === 204) return undefined as T; + try { + return await response.json() as T; + } catch (cause) { + const kind = cause instanceof Error && cause.name === "TimeoutError" ? "timeout" : "invalid_response"; + const error = new FlyClientError(kind === "timeout" ? "Fly request timed out" : "Fly returned an invalid response", kind, response.status, { cause }); + if (retrySafe && retries < maxRetries && isRetryable(error)) { + await wait(100 * (2 ** retries++)); + continue; + } + throw error; + } + } + } + + const appPath = (app: string) => `/apps/${segment(app, "app")}`; + const machinePath = (app: string, machine: string) => `${appPath(app)}/machines/${segment(machine, "machine id")}`; + + async function findByOperationId(app: string, operationId: string): Promise { + const machines = await request(`${appPath(app)}/machines`, { method: "GET" }, true); + if (!Array.isArray(machines)) throw new FlyClientError("Fly returned an invalid Machine list", "invalid_response"); + return machines.find((machine) => machine.config?.metadata?.[OPERATION_METADATA_KEY] === operationId); + } + + return { + async createMachine(app: string, config: FlyMachineConfig, operationId: string): Promise { + if (!operationId || operationId.length > 200) throw new TypeError("operationId must contain 1 to 200 characters"); + const existing = await findByOperationId(app, operationId); + if (existing) return existing; + const body = { + config: { + ...config, + metadata: { ...config.metadata, [OPERATION_METADATA_KEY]: operationId }, + }, + }; + try { + const created = await request(`${appPath(app)}/machines`, { + method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), + }, false); + if (!created || typeof created.id !== "string" || !created.id) { + throw new FlyClientError("Fly returned an invalid created Machine", "invalid_response"); + } + return created; + } catch (cause) { + // A 409 duplicate or a timeout/server/network failure may mean the + // provider committed the create. Reconcile exactly once before failing. + const ambiguous = cause instanceof FlyClientError && + (["timeout", "network", "server"].includes(cause.kind) || (cause.kind === "http" && cause.status === 409)); + if (!ambiguous) throw cause; + try { + const reconciled = await findByOperationId(app, operationId); + if (reconciled) return reconciled; + } catch { + // Keep the original sanitized create error as the useful diagnosis. + } + throw new FlyClientError("Fly Machine creation outcome is ambiguous; retry with the same operationId", "ambiguous_create", undefined, { cause }); + } + }, + inspectMachine(app: string, machine: string): Promise { + return request(machinePath(app, machine), { method: "GET" }, true); + }, + startMachine(app: string, machine: string): Promise { + return request(`${machinePath(app, machine)}/start`, { method: "POST" }, false); + }, + stopMachine(app: string, machine: string): Promise { + return request(`${machinePath(app, machine)}/stop`, { method: "POST" }, false); + }, + destroyMachine(app: string, machine: string): Promise { + return request(machinePath(app, machine), { method: "DELETE" }, true); + }, + updateMachineConfig(app: string, machine: string, config: FlyMachineConfig): Promise { + return request(machinePath(app, machine), { + method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ config }), + }, true); + }, + }; +} diff --git a/packages/api/test/fly-machines-client.test.ts b/packages/api/test/fly-machines-client.test.ts new file mode 100644 index 00000000..94bb73d2 --- /dev/null +++ b/packages/api/test/fly-machines-client.test.ts @@ -0,0 +1,178 @@ +import { createServer, type Server } from "node:http"; +import { once } from "node:events"; +import { afterEach, describe, expect, it } from "vitest"; +import { createFlyMachinesClient, FlyClientError, type FlyMachine } from "../src/fly-machines-client.js"; + +const token = "test-fly-secret-do-not-leak"; +const servers: Server[] = []; + +async function fakeFly(handler: (request: any, response: any) => void | Promise) { + const server = createServer((request, response) => { void handler(request, response); }); + servers.push(server); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Fake Fly server did not bind a TCP port"); + return `http://127.0.0.1:${address.port}`; +} + +function json(response: any, status: number, body: unknown) { + response.writeHead(status, { "content-type": "application/json" }); + response.end(JSON.stringify(body)); +} + +afterEach(async () => { + await Promise.all(servers.splice(0).map(async (server) => { + server.closeAllConnections(); + if (server.listening) { + server.close(); + await once(server, "close"); + } + })); +}); + +describe("bounded Fly Machines client", () => { + it("creates, inspects, starts, stops, updates config, and destroys with documented paths", async () => { + const calls: Array<{ method: string; path: string; auth: string | undefined }> = []; + const machine: FlyMachine = { id: "m-1", state: "created" }; + const origin = await fakeFly(async (req, res) => { + calls.push({ method: req.method, path: req.url, auth: req.headers.authorization }); + if (req.method === "GET" && req.url === "/v1/apps/app-a/machines") return json(res, 200, []); + if (req.method === "POST" && req.url === "/v1/apps/app-a/machines") { + let raw = ""; for await (const chunk of req) raw += chunk; + const body = JSON.parse(raw); + expect(body.config.metadata.factorize_operation_id).toBe("op-1"); + return json(res, 200, machine); + } + if (req.method === "GET" && req.url === "/v1/apps/app-a/machines/m-1") return json(res, 200, machine); + if (req.method === "POST" && ["/v1/apps/app-a/machines/m-1/start", "/v1/apps/app-a/machines/m-1/stop"].includes(req.url)) { + res.writeHead(204); return res.end(); + } + if (req.method === "POST" && req.url === "/v1/apps/app-a/machines/m-1") return json(res, 200, machine); + if (req.method === "DELETE" && req.url === "/v1/apps/app-a/machines/m-1") { res.writeHead(204); return res.end(); } + json(res, 404, { error: "not found" }); + }); + const client = createFlyMachinesClient({ token, apiOrigin: origin, wait: async () => undefined }); + const created = await client.createMachine("app-a", { image: "example/image", metadata: { keep: "yes" } }, "op-1"); + expect(created.id).toBe("m-1"); + expect((await client.inspectMachine("app-a", "m-1")).id).toBe("m-1"); + await client.startMachine("app-a", "m-1"); + await client.stopMachine("app-a", "m-1"); + expect((await client.updateMachineConfig("app-a", "m-1", { image: "example/new" })).id).toBe("m-1"); + await client.destroyMachine("app-a", "m-1"); + expect(calls.every((call) => call.auth === `Bearer ${token}`)).toBe(true); + expect(calls.map(({ method, path }) => `${method} ${path}`)).toEqual([ + "GET /v1/apps/app-a/machines", "POST /v1/apps/app-a/machines", "GET /v1/apps/app-a/machines/m-1", + "POST /v1/apps/app-a/machines/m-1/start", "POST /v1/apps/app-a/machines/m-1/stop", + "POST /v1/apps/app-a/machines/m-1", "DELETE /v1/apps/app-a/machines/m-1", + ]); + }); + + it("returns typed auth errors without exposing credentials or provider bodies", async () => { + const origin = await fakeFly((_req, res) => json(res, 401, { detail: token })); + const client = createFlyMachinesClient({ token, apiOrigin: origin }); + await expect(client.inspectMachine("app", "machine")).rejects.toMatchObject({ kind: "auth", status: 401 }); + try { await client.inspectMachine("app", "machine"); } catch (error) { + expect(String(error)).not.toContain(token); + expect(String(error)).not.toContain("detail"); + } + }); + + it("bounds a stalled response body and reports a secret-safe timeout", async () => { + let count = 0; + const origin = await fakeFly((_req, res) => { + count++; + res.writeHead(200, { "content-type": "application/json" }); + res.flushHeaders(); + // Deliberately leave the body open until the client deadline aborts it. + }); + const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 30, maxRetries: 0 }); + await expect(client.inspectMachine("app", "machine")).rejects.toMatchObject({ kind: "timeout" }); + expect(count).toBe(1); + }); + + it("retries a safe read only within the configured request bound for 429 and 5xx", async () => { + for (const status of [429, 503]) { + let count = 0; + const origin = await fakeFly((_req, res) => { + count++; + if (count < 3) return json(res, status, { secret: token }); + json(res, 200, { id: "m-1" }); + }); + const client = createFlyMachinesClient({ token, apiOrigin: origin, maxRetries: 2, wait: async () => undefined }); + expect((await client.inspectMachine("app", "m-1")).id).toBe("m-1"); + expect(count).toBe(3); + } + }); + + it("times out a stalled response and reconciles an ambiguous create by operation id", async () => { + const machines: FlyMachine[] = []; + let createCount = 0; + const origin = await fakeFly(async (req, res) => { + if (req.method === "GET") return json(res, 200, machines); + if (req.method === "POST") { + createCount++; + let raw = ""; for await (const chunk of req) raw += chunk; + const body = JSON.parse(raw); + const machine = { id: "m-created", config: body.config }; + machines.push(machine); + // Commit the resource but leave the response stalled past the client's deadline. + res.writeHead(200, { "content-type": "application/json" }); + } + }); + const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 30, maxRetries: 0 }); + const created = await client.createMachine("app", { image: "image" }, "op-ambiguous"); + expect(created.id).toBe("m-created"); + expect(createCount).toBe(1); + }); + + it("reconciles a duplicate invocation before POST and never creates a second Machine", async () => { + const machines: FlyMachine[] = []; + let createCount = 0; + const origin = await fakeFly(async (req, res) => { + if (req.method === "GET") return json(res, 200, machines); + createCount++; + let raw = ""; for await (const chunk of req) raw += chunk; + const body = JSON.parse(raw); + const machine = { id: `m-${createCount}`, config: body.config }; + machines.push(machine); + json(res, 200, machine); + }); + const client = createFlyMachinesClient({ token, apiOrigin: origin }); + expect((await client.createMachine("app", { image: "image" }, "stable-op")).id).toBe("m-1"); + expect((await client.createMachine("app", { image: "image" }, "stable-op")).id).toBe("m-1"); + expect(createCount).toBe(1); + }); + + it("reconciles a provider duplicate response using the stable operation id", async () => { + let machine: FlyMachine | undefined; + let gets = 0; + let posts = 0; + const origin = await fakeFly(async (req, res) => { + if (req.method === "GET") { + gets++; + return json(res, 200, machine ? [machine] : []); + } + posts++; + let raw = ""; for await (const chunk of req) raw += chunk; + machine = { id: "created-by-concurrent-request", config: JSON.parse(raw).config }; + return json(res, 409, { detail: "duplicate create" }); + }); + const client = createFlyMachinesClient({ token, apiOrigin: origin }); + expect((await client.createMachine("app", { image: "image" }, "concurrent-op")).id).toBe("created-by-concurrent-request"); + expect(gets).toBe(2); + expect(posts).toBe(1); + }); + + it("does not retry create after an ambiguous outcome that cannot be reconciled", async () => { + let count = 0; + const origin = await fakeFly((req, res) => { + if (req.method === "GET") return json(res, 200, []); + count++; + res.writeHead(503, { "content-type": "application/json" }); res.end(JSON.stringify({ detail: token })); + }); + const client = createFlyMachinesClient({ token, apiOrigin: origin, wait: async () => undefined }); + await expect(client.createMachine("app", { image: "image" }, "op-fail")).rejects.toMatchObject({ kind: "ambiguous_create" }); + expect(count).toBe(1); + }); +});