flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/services/deployments/src/cloudflare.ts

229 lines10,007 bytesCodeBlame
1/**
2 * Cloudflare's API, behind the calls deployments need: open an upload of
3 * an app's files, put the app in the dispatch namespace, take it down, and
4 * count what each app used.
5 *
6 * The token is the service's own, scoped to Workers scripts and analytics on
7 * g1t's account. It never leaves this Worker: a sandbox only ever gets an
8 * upload session's key, which can upload one manifest's files and nothing
9 * else.
10 */
11
12const API = "https://api.cloudflare.com/client/v4";
13
14export type Manifest = Record<string, { hash: string; size: number }>;
15
16/** A module of a Worker, as the sandbox sends it. */
17export type Module = { name: string; contentBase64: string; contentType: string };
18
19/** What the sandbox built: the Worker's code and settings. */
20export type BuiltWorker = {
21 mainModule?: string;
22 modules?: Module[];
23 compatibilityDate?: string;
24 compatibilityFlags?: string[];
25 vars?: Record<string, unknown>;
26 assetsBinding?: string | null;
27 htmlHandling?: string | null;
28 notFoundHandling?: string | null;
29 _headers?: string;
30 _redirects?: string;
31};
32
33/** Serves the site's files, for an app that brings no code of its own. */
34const ASSETS_ONLY = `export default { fetch(request, env) { return env.ASSETS.fetch(request); } };\n`;
35
36/** What an app answers between being taken down and being gone. */
37const TAKEN_DOWN = `export default {
38 fetch() {
39 return new Response("<!doctype html><meta charset=utf-8><meta name=robots content=noindex><title>Not up</title><body style='font:16px system-ui;background:#121214;color:#ececf1;display:grid;place-items:center;min-height:100vh;margin:0'><main><h1>This app is not up</h1><p style='color:#9a9aa6'>It was taken down. Deploying it again brings it back.</p></main>", { status: 404, headers: { "content-type": "text/html; charset=utf-8", "x-robots-tag": "noindex", "cache-control": "no-store" } });
40 },
41};
42`;
43
44const HTML_HANDLING =["auto-trailing-slash", "force-trailing-slash", "drop-trailing-slash", "none"];
45const NOT_FOUND_HANDLING = ["single-page-application", "404-page", "none"];
46
47export class Cloudflare {
48 constructor(
49 private readonly token: string,
50 private readonly account: string,
51 readonly namespace: string,
52 ) {}
53
54 private async call<T>(method: string, path: string, body?: BodyInit, contentType?: string): Promise<T> {
55 const headers: Record<string, string> = { authorization: `Bearer ${this.token}` };
56 if (contentType) headers["content-type"] = contentType;
57 const response = await fetch(`${API}${path}`, { method, headers, body });
58 const answer = (await response.json().catch(() => null)) as {
59 success?: boolean;
60 result?: T;
61 errors?: { code: number; message: string }[];
62 } | null;
63 if (!response.ok || !answer?.success) {
64 const why = answer?.errors?.map((error) => `${error.message} (${error.code})`).join("; ");
65 throw new Error(`Cloudflare answered ${response.status}: ${why || "no reason given"}`);
66 }
67 return answer.result as T;
68 }
69
70 private scriptPath(script: string): string {
71 return `/accounts/${this.account}/workers/dispatch/namespaces/${this.namespace}/scripts/${encodeURIComponent(script)}`;
72 }
73
74 /** Where a sandbox sends the files an upload session asks for. */
75 get uploadUrl(): string {
76 return `${API}/accounts/${this.account}/workers/assets/upload?base64=true`;
77 }
78
79 /**
80 * Opens an upload of exactly these files. Cloudflare answers with a key
81 * that can upload only them, and the files it does not already have, in
82 * buckets; with no buckets, the key itself completes the upload.
83 */
84 async openUpload(script: string, manifest: Manifest): Promise<{ jwt: string; buckets: string[][] }> {
85 const result = await this.call<{ jwt: string; buckets?: string[][] }>(
86 "POST",
87 `${this.scriptPath(script)}/assets-upload-session`,
88 JSON.stringify({ manifest }),
89 "application/json",
90 );
91 return { jwt: result.jwt, buckets: result.buckets ?? [] };
92 }
93
94 /** Puts an app in the namespace, replacing what was there. */
95 async putScript(
96 script: string,
97 worker: BuiltWorker,
98 completionJwt: string | null,
99 tags: string[],
100 /** The repository's entries for running apps, over the project's own `vars`. */
101 runtime: { secrets: Record<string, string>; variables: Record<string, string> } = { secrets: {}, variables: {} },
102 ): Promise<void> {
103 const form = new FormData();
104 const modules = worker.modules?.length ? worker.modules : null;
105 const assetsBinding = worker.assetsBinding || "ASSETS";
106 const vars: Record<string, unknown> = { ...(worker.vars ?? {}), ...runtime.variables };
107 for (const name of Object.keys(runtime.secrets)) delete vars[name];
108 const bindings: object[] = Object.entries(vars).map(([name, value]) =>
109 typeof value === "string"
110 ? { type: "plain_text", name, text: value }
111 : { type: "json", name, json: value },
112 );
113 for (const [name, text] of Object.entries(runtime.secrets)) bindings.push({ type: "secret_text", name, text });
114 if (completionJwt) bindings.push({ type: "assets", name: assetsBinding });
115 const assetsConfig: Record<string, string> = {};
116 if (worker.htmlHandling && HTML_HANDLING.includes(worker.htmlHandling)) {
117 assetsConfig.html_handling = worker.htmlHandling;
118 }
119 if (worker.notFoundHandling && NOT_FOUND_HANDLING.includes(worker.notFoundHandling)) {
120 assetsConfig.not_found_handling = worker.notFoundHandling;
121 }
122 if (worker._headers) assetsConfig._headers = worker._headers;
123 if (worker._redirects) assetsConfig._redirects = worker._redirects;
124 const mainModule = modules ? worker.mainModule ?? modules[0].name : "index.js";
125 form.append(
126 "metadata",
127 JSON.stringify({
128 main_module: mainModule,
129 compatibility_date: worker.compatibilityDate ?? "2026-09-26",
130 compatibility_flags: worker.compatibilityFlags ?? [],
131 bindings,
132 tags,
133 ...(completionJwt ? { assets: { jwt: completionJwt, config: assetsConfig } } : {}),
134 }),
135 );
136 if (modules) {
137 for (const module of modules) {
138 const bytes = Uint8Array.from(atob(module.contentBase64), (c) => c.charCodeAt(0));
139 form.append(module.name, new File([bytes], module.name, { type: module.contentType }));
140 }
141 } else {
142 if (!completionJwt) throw new Error("The build produced neither code nor files to serve.");
143 form.append(
144 "index.js",
145 new File([ASSETS_ONLY], "index.js", { type: "application/javascript+module" }),
146 );
147 }
148 await this.call("PUT", this.scriptPath(script), form);
149 }
150
151 /** Every app in the namespace, with when it was last changed. */
152 async listScripts(): Promise<{ id: string; modified_on: string }[]> {
153 return this.call<{ id: string; modified_on: string }[]>(
154 "GET",
155 `/accounts/${this.account}/workers/dispatch/namespaces/${this.namespace}/scripts`,
156 );
157 }
158
159 /**
160 * Takes an app down. Already gone is fine.
161 *
162 * A deleted app can keep answering for a while where Cloudflare still has
163 * it warm. So it is first replaced by a notice that it is down, which
164 * reaches the edge as fast as any deploy, and deleted after.
165 */
166 async deleteScript(script: string): Promise<void> {
167 const form = new FormData();
168 form.append(
169 "metadata",
170 JSON.stringify({ main_module: "index.js", compatibility_date: "2026-09-26", bindings: [], tags: ["taken-down"] }),
171 );
172 form.append("index.js", new File([TAKEN_DOWN], "index.js", { type: "application/javascript+module" }));
173 await this.call("PUT", this.scriptPath(script), form).catch(() => undefined);
174 try {
175 await this.call("DELETE", `${this.scriptPath(script)}?force=true`);
176 } catch (error) {
177 if (!/404|not found|10007/i.test(String(error))) throw error;
178 }
179 }
180
181 /**
182 * Requests and CPU time per app over a period, from Workers analytics.
183 * Apps with no traffic are absent.
184 */
185 async usage(
186 scripts: string[],
187 since: string,
188 until: string,
189 ): Promise<Map<string, { requests: number; cpuMs: number }>> {
190 const totals = new Map<string, { requests: number; cpuMs: number }>();
191 if (scripts.length === 0) return totals;
192 const query = (withCpu: boolean) => `query ($account: string!, $since: Time!, $until: Time!, $scripts: [string!]) {
193 viewer { accounts(filter: { accountTag: $account }) {
194 workersInvocationsAdaptive(limit: 10000, filter: { datetime_geq: $since, datetime_lt: $until, scriptName_in: $scripts }) {
195 sum { requests${withCpu ? " cpuTimeUs" : ""} }
196 dimensions { scriptName }
197 }
198 } }
199 }`;
200 type Row = { sum: { requests: number; cpuTimeUs?: number }; dimensions: { scriptName: string } };
201 const ask = async (withCpu: boolean) => {
202 const response = await fetch(`${API}/graphql`, {
203 method: "POST",
204 headers: { authorization: `Bearer ${this.token}`, "content-type": "application/json" },
205 body: JSON.stringify({
206 query: query(withCpu),
207 variables: { account: this.account, since, until, scripts },
208 }),
209 });
210 return (await response.json()) as {
211 data?: { viewer: { accounts: { workersInvocationsAdaptive: Row[] }[] } };
212 errors?: { message: string }[] | null;
213 };
214 };
215 let answer = await ask(true);
216 // CPU time is counted where analytics offers it; requests always.
217 if (answer.errors?.length) answer = await ask(false);
218 if (answer.errors?.length || !answer.data) {
219 throw new Error(`Workers analytics refused: ${answer.errors?.map((e) => e.message).join("; ")}`);
220 }
221 for (const row of answer.data.viewer.accounts[0]?.workersInvocationsAdaptive ?? []) {
222 const seen = totals.get(row.dimensions.scriptName) ?? { requests: 0, cpuMs: 0 };
223 seen.requests += row.sum.requests;
224 seen.cpuMs += Math.ceil((row.sum.cpuTimeUs ?? 0) / 1000);
225 totals.set(row.dimensions.scriptName, seen);
226 }
227 return totals;
228 }
229}