Skip to content

Commit 5cb74c8

Browse files
Merge pull request #355 from GenerationSoftware/gen-2845-bounded-fly-client
[GEN-2845] Implement bounded Fly Machines client
2 parents 33fcd8b + f37faf6 commit 5cb74c8

2 files changed

Lines changed: 361 additions & 0 deletions

File tree

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
/** A small, bounded adapter for Fly's documented Machines v1 API. */
2+
3+
export type FlyMachine = {
4+
id: string;
5+
name?: string;
6+
state?: string;
7+
config?: { metadata?: Record<string, string>; [key: string]: unknown };
8+
[key: string]: unknown;
9+
};
10+
11+
export type FlyMachineConfig = Record<string, unknown> & {
12+
metadata?: Record<string, string>;
13+
};
14+
15+
export type FlyClientErrorKind = "timeout" | "network" | "auth" | "rate_limit" | "server" | "http" | "invalid_response" | "ambiguous_create";
16+
17+
/** Error messages intentionally contain no URL, response body, or credential. */
18+
export class FlyClientError extends Error {
19+
constructor(
20+
message: string,
21+
readonly kind: FlyClientErrorKind,
22+
readonly status?: number,
23+
options?: ErrorOptions,
24+
) {
25+
super(message, options);
26+
this.name = "FlyClientError";
27+
}
28+
}
29+
30+
export type FlyMachinesClientOptions = {
31+
token: string;
32+
/** Origin override is intended for local API tests. */
33+
apiOrigin?: string;
34+
timeoutMs?: number;
35+
maxRetries?: number;
36+
fetch?: typeof fetch;
37+
wait?: (milliseconds: number) => Promise<void>;
38+
};
39+
40+
const DEFAULT_ORIGIN = "https://api.machines.dev";
41+
const DEFAULT_TIMEOUT_MS = 5_000;
42+
const DEFAULT_MAX_RETRIES = 2;
43+
const OPERATION_METADATA_KEY = "factorize_operation_id";
44+
45+
function segment(value: string, name: string): string {
46+
if (!value || value.includes("/") || value === "." || value === "..") {
47+
throw new TypeError(`${name} must be a non-empty path segment`);
48+
}
49+
return encodeURIComponent(value);
50+
}
51+
52+
function errorFromStatus(status: number): FlyClientError {
53+
if (status === 401 || status === 403) return new FlyClientError("Fly authentication failed", "auth", status);
54+
if (status === 429) return new FlyClientError("Fly rate limit exceeded", "rate_limit", status);
55+
if (status >= 500) return new FlyClientError("Fly service failed", "server", status);
56+
if (status === 404) return new FlyClientError("Fly Machine was not found", "http", status);
57+
return new FlyClientError("Fly request failed", "http", status);
58+
}
59+
60+
function isRetryable(error: unknown): boolean {
61+
return error instanceof FlyClientError && ["timeout", "network", "server", "rate_limit"].includes(error.kind);
62+
}
63+
64+
/**
65+
* The client never retries machine creation. A create is reconciled by a stable
66+
* metadata operation id, so a repeated caller or ambiguous network result
67+
* discovers the already-created Machine instead of creating a duplicate.
68+
*/
69+
export function createFlyMachinesClient(options: FlyMachinesClientOptions) {
70+
if (!options.token) throw new TypeError("Fly token is required");
71+
const origin = (options.apiOrigin ?? DEFAULT_ORIGIN).replace(/\/$/, "");
72+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
73+
const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
74+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new TypeError("timeoutMs must be a positive integer");
75+
if (!Number.isInteger(maxRetries) || maxRetries < 0 || maxRetries > 5) throw new TypeError("maxRetries must be between 0 and 5");
76+
const fetchImpl = options.fetch ?? fetch;
77+
const wait = options.wait ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
78+
79+
async function request<T>(path: string, init: RequestInit, retrySafe: boolean): Promise<T> {
80+
let retries = 0;
81+
while (true) {
82+
let response: Response;
83+
try {
84+
response = await fetchImpl(`${origin}/v1${path}`, {
85+
...init,
86+
headers: { authorization: `Bearer ${options.token}`, accept: "application/json", ...init.headers },
87+
signal: AbortSignal.timeout(timeoutMs),
88+
});
89+
} catch (cause) {
90+
const kind = cause instanceof Error && cause.name === "TimeoutError" ? "timeout" : "network";
91+
const error = new FlyClientError(kind === "timeout" ? "Fly request timed out" : "Fly network request failed", kind, undefined, { cause });
92+
if (retrySafe && retries < maxRetries && isRetryable(error)) {
93+
await wait(100 * (2 ** retries++));
94+
continue;
95+
}
96+
throw error;
97+
}
98+
if (!response.ok) {
99+
await response.body?.cancel().catch(() => undefined);
100+
const error = errorFromStatus(response.status);
101+
if (retrySafe && retries < maxRetries && isRetryable(error)) {
102+
await wait(100 * (2 ** retries++));
103+
continue;
104+
}
105+
throw error;
106+
}
107+
if (response.status === 204) return undefined as T;
108+
try {
109+
return await response.json() as T;
110+
} catch (cause) {
111+
const kind = cause instanceof Error && cause.name === "TimeoutError" ? "timeout" : "invalid_response";
112+
const error = new FlyClientError(kind === "timeout" ? "Fly request timed out" : "Fly returned an invalid response", kind, response.status, { cause });
113+
if (retrySafe && retries < maxRetries && isRetryable(error)) {
114+
await wait(100 * (2 ** retries++));
115+
continue;
116+
}
117+
throw error;
118+
}
119+
}
120+
}
121+
122+
const appPath = (app: string) => `/apps/${segment(app, "app")}`;
123+
const machinePath = (app: string, machine: string) => `${appPath(app)}/machines/${segment(machine, "machine id")}`;
124+
125+
async function findByOperationId(app: string, operationId: string): Promise<FlyMachine | undefined> {
126+
const machines = await request<FlyMachine[]>(`${appPath(app)}/machines`, { method: "GET" }, true);
127+
if (!Array.isArray(machines)) throw new FlyClientError("Fly returned an invalid Machine list", "invalid_response");
128+
return machines.find((machine) => machine.config?.metadata?.[OPERATION_METADATA_KEY] === operationId);
129+
}
130+
131+
return {
132+
async createMachine(app: string, config: FlyMachineConfig, operationId: string): Promise<FlyMachine> {
133+
if (!operationId || operationId.length > 200) throw new TypeError("operationId must contain 1 to 200 characters");
134+
const existing = await findByOperationId(app, operationId);
135+
if (existing) return existing;
136+
const body = {
137+
config: {
138+
...config,
139+
metadata: { ...config.metadata, [OPERATION_METADATA_KEY]: operationId },
140+
},
141+
};
142+
try {
143+
const created = await request<FlyMachine>(`${appPath(app)}/machines`, {
144+
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
145+
}, false);
146+
if (!created || typeof created.id !== "string" || !created.id) {
147+
throw new FlyClientError("Fly returned an invalid created Machine", "invalid_response");
148+
}
149+
return created;
150+
} catch (cause) {
151+
// A 409 duplicate or a timeout/server/network failure may mean the
152+
// provider committed the create. Reconcile exactly once before failing.
153+
const ambiguous = cause instanceof FlyClientError &&
154+
(["timeout", "network", "server"].includes(cause.kind) || (cause.kind === "http" && cause.status === 409));
155+
if (!ambiguous) throw cause;
156+
try {
157+
const reconciled = await findByOperationId(app, operationId);
158+
if (reconciled) return reconciled;
159+
} catch {
160+
// Keep the original sanitized create error as the useful diagnosis.
161+
}
162+
throw new FlyClientError("Fly Machine creation outcome is ambiguous; retry with the same operationId", "ambiguous_create", undefined, { cause });
163+
}
164+
},
165+
inspectMachine(app: string, machine: string): Promise<FlyMachine> {
166+
return request(machinePath(app, machine), { method: "GET" }, true);
167+
},
168+
startMachine(app: string, machine: string): Promise<void> {
169+
return request(`${machinePath(app, machine)}/start`, { method: "POST" }, false);
170+
},
171+
stopMachine(app: string, machine: string): Promise<void> {
172+
return request(`${machinePath(app, machine)}/stop`, { method: "POST" }, false);
173+
},
174+
destroyMachine(app: string, machine: string): Promise<void> {
175+
return request(machinePath(app, machine), { method: "DELETE" }, true);
176+
},
177+
updateMachineConfig(app: string, machine: string, config: FlyMachineConfig): Promise<FlyMachine> {
178+
return request(machinePath(app, machine), {
179+
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ config }),
180+
}, true);
181+
},
182+
};
183+
}
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
import { createServer, type Server } from "node:http";
2+
import { once } from "node:events";
3+
import { afterEach, describe, expect, it } from "vitest";
4+
import { createFlyMachinesClient, FlyClientError, type FlyMachine } from "../src/fly-machines-client.js";
5+
6+
const token = "test-fly-secret-do-not-leak";
7+
const servers: Server[] = [];
8+
9+
async function fakeFly(handler: (request: any, response: any) => void | Promise<void>) {
10+
const server = createServer((request, response) => { void handler(request, response); });
11+
servers.push(server);
12+
server.listen(0, "127.0.0.1");
13+
await once(server, "listening");
14+
const address = server.address();
15+
if (!address || typeof address === "string") throw new Error("Fake Fly server did not bind a TCP port");
16+
return `http://127.0.0.1:${address.port}`;
17+
}
18+
19+
function json(response: any, status: number, body: unknown) {
20+
response.writeHead(status, { "content-type": "application/json" });
21+
response.end(JSON.stringify(body));
22+
}
23+
24+
afterEach(async () => {
25+
await Promise.all(servers.splice(0).map(async (server) => {
26+
server.closeAllConnections();
27+
if (server.listening) {
28+
server.close();
29+
await once(server, "close");
30+
}
31+
}));
32+
});
33+
34+
describe("bounded Fly Machines client", () => {
35+
it("creates, inspects, starts, stops, updates config, and destroys with documented paths", async () => {
36+
const calls: Array<{ method: string; path: string; auth: string | undefined }> = [];
37+
const machine: FlyMachine = { id: "m-1", state: "created" };
38+
const origin = await fakeFly(async (req, res) => {
39+
calls.push({ method: req.method, path: req.url, auth: req.headers.authorization });
40+
if (req.method === "GET" && req.url === "/v1/apps/app-a/machines") return json(res, 200, []);
41+
if (req.method === "POST" && req.url === "/v1/apps/app-a/machines") {
42+
let raw = ""; for await (const chunk of req) raw += chunk;
43+
const body = JSON.parse(raw);
44+
expect(body.config.metadata.factorize_operation_id).toBe("op-1");
45+
return json(res, 200, machine);
46+
}
47+
if (req.method === "GET" && req.url === "/v1/apps/app-a/machines/m-1") return json(res, 200, machine);
48+
if (req.method === "POST" && ["/v1/apps/app-a/machines/m-1/start", "/v1/apps/app-a/machines/m-1/stop"].includes(req.url)) {
49+
res.writeHead(204); return res.end();
50+
}
51+
if (req.method === "POST" && req.url === "/v1/apps/app-a/machines/m-1") return json(res, 200, machine);
52+
if (req.method === "DELETE" && req.url === "/v1/apps/app-a/machines/m-1") { res.writeHead(204); return res.end(); }
53+
json(res, 404, { error: "not found" });
54+
});
55+
const client = createFlyMachinesClient({ token, apiOrigin: origin, wait: async () => undefined });
56+
const created = await client.createMachine("app-a", { image: "example/image", metadata: { keep: "yes" } }, "op-1");
57+
expect(created.id).toBe("m-1");
58+
expect((await client.inspectMachine("app-a", "m-1")).id).toBe("m-1");
59+
await client.startMachine("app-a", "m-1");
60+
await client.stopMachine("app-a", "m-1");
61+
expect((await client.updateMachineConfig("app-a", "m-1", { image: "example/new" })).id).toBe("m-1");
62+
await client.destroyMachine("app-a", "m-1");
63+
expect(calls.every((call) => call.auth === `Bearer ${token}`)).toBe(true);
64+
expect(calls.map(({ method, path }) => `${method} ${path}`)).toEqual([
65+
"GET /v1/apps/app-a/machines", "POST /v1/apps/app-a/machines", "GET /v1/apps/app-a/machines/m-1",
66+
"POST /v1/apps/app-a/machines/m-1/start", "POST /v1/apps/app-a/machines/m-1/stop",
67+
"POST /v1/apps/app-a/machines/m-1", "DELETE /v1/apps/app-a/machines/m-1",
68+
]);
69+
});
70+
71+
it("returns typed auth errors without exposing credentials or provider bodies", async () => {
72+
const origin = await fakeFly((_req, res) => json(res, 401, { detail: token }));
73+
const client = createFlyMachinesClient({ token, apiOrigin: origin });
74+
await expect(client.inspectMachine("app", "machine")).rejects.toMatchObject({ kind: "auth", status: 401 });
75+
try { await client.inspectMachine("app", "machine"); } catch (error) {
76+
expect(String(error)).not.toContain(token);
77+
expect(String(error)).not.toContain("detail");
78+
}
79+
});
80+
81+
it("bounds a stalled response body and reports a secret-safe timeout", async () => {
82+
let count = 0;
83+
const origin = await fakeFly((_req, res) => {
84+
count++;
85+
res.writeHead(200, { "content-type": "application/json" });
86+
res.flushHeaders();
87+
// Deliberately leave the body open until the client deadline aborts it.
88+
});
89+
const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 30, maxRetries: 0 });
90+
await expect(client.inspectMachine("app", "machine")).rejects.toMatchObject({ kind: "timeout" });
91+
expect(count).toBe(1);
92+
});
93+
94+
it("retries a safe read only within the configured request bound for 429 and 5xx", async () => {
95+
for (const status of [429, 503]) {
96+
let count = 0;
97+
const origin = await fakeFly((_req, res) => {
98+
count++;
99+
if (count < 3) return json(res, status, { secret: token });
100+
json(res, 200, { id: "m-1" });
101+
});
102+
const client = createFlyMachinesClient({ token, apiOrigin: origin, maxRetries: 2, wait: async () => undefined });
103+
expect((await client.inspectMachine("app", "m-1")).id).toBe("m-1");
104+
expect(count).toBe(3);
105+
}
106+
});
107+
108+
it("times out a stalled response and reconciles an ambiguous create by operation id", async () => {
109+
const machines: FlyMachine[] = [];
110+
let createCount = 0;
111+
const origin = await fakeFly(async (req, res) => {
112+
if (req.method === "GET") return json(res, 200, machines);
113+
if (req.method === "POST") {
114+
createCount++;
115+
let raw = ""; for await (const chunk of req) raw += chunk;
116+
const body = JSON.parse(raw);
117+
const machine = { id: "m-created", config: body.config };
118+
machines.push(machine);
119+
// Commit the resource but leave the response stalled past the client's deadline.
120+
res.writeHead(200, { "content-type": "application/json" });
121+
}
122+
});
123+
const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 30, maxRetries: 0 });
124+
const created = await client.createMachine("app", { image: "image" }, "op-ambiguous");
125+
expect(created.id).toBe("m-created");
126+
expect(createCount).toBe(1);
127+
});
128+
129+
it("reconciles a duplicate invocation before POST and never creates a second Machine", async () => {
130+
const machines: FlyMachine[] = [];
131+
let createCount = 0;
132+
const origin = await fakeFly(async (req, res) => {
133+
if (req.method === "GET") return json(res, 200, machines);
134+
createCount++;
135+
let raw = ""; for await (const chunk of req) raw += chunk;
136+
const body = JSON.parse(raw);
137+
const machine = { id: `m-${createCount}`, config: body.config };
138+
machines.push(machine);
139+
json(res, 200, machine);
140+
});
141+
const client = createFlyMachinesClient({ token, apiOrigin: origin });
142+
expect((await client.createMachine("app", { image: "image" }, "stable-op")).id).toBe("m-1");
143+
expect((await client.createMachine("app", { image: "image" }, "stable-op")).id).toBe("m-1");
144+
expect(createCount).toBe(1);
145+
});
146+
147+
it("reconciles a provider duplicate response using the stable operation id", async () => {
148+
let machine: FlyMachine | undefined;
149+
let gets = 0;
150+
let posts = 0;
151+
const origin = await fakeFly(async (req, res) => {
152+
if (req.method === "GET") {
153+
gets++;
154+
return json(res, 200, machine ? [machine] : []);
155+
}
156+
posts++;
157+
let raw = ""; for await (const chunk of req) raw += chunk;
158+
machine = { id: "created-by-concurrent-request", config: JSON.parse(raw).config };
159+
return json(res, 409, { detail: "duplicate create" });
160+
});
161+
const client = createFlyMachinesClient({ token, apiOrigin: origin });
162+
expect((await client.createMachine("app", { image: "image" }, "concurrent-op")).id).toBe("created-by-concurrent-request");
163+
expect(gets).toBe(2);
164+
expect(posts).toBe(1);
165+
});
166+
167+
it("does not retry create after an ambiguous outcome that cannot be reconciled", async () => {
168+
let count = 0;
169+
const origin = await fakeFly((req, res) => {
170+
if (req.method === "GET") return json(res, 200, []);
171+
count++;
172+
res.writeHead(503, { "content-type": "application/json" }); res.end(JSON.stringify({ detail: token }));
173+
});
174+
const client = createFlyMachinesClient({ token, apiOrigin: origin, wait: async () => undefined });
175+
await expect(client.createMachine("app", { image: "image" }, "op-fail")).rejects.toMatchObject({ kind: "ambiguous_create" });
176+
expect(count).toBe(1);
177+
});
178+
});

0 commit comments

Comments
 (0)