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

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