Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

diffinery/scripts/celld-config.mjs
136 lines · 8.6 KBRaw History
1#!/usr/bin/env node
2// Render apps/diffinery/wrangler.celld.jsonc from wrangler.jsonc, for celld (https://celld.dev), the
3// open-source Workers and Durable Objects runtime. wrangler.jsonc stays the one source of truth: this
4// keeps what celld runs and drops the Cloudflare-network features, whose bindings the Worker treats as
5// optional (CELLD_ABSENT_BINDINGS in src/env.ts). celld stops on a key it doesn't know, so a new
6// key in wrangler.jsonc fails here until it is listed below (docs/self-hosting/celld.md).
7//
8// node scripts/celld-config.mjs [--env dev] [--public-url https://git.example.com] [--var NAME=VALUE ...] [--out <file>]
9//
10// --env applies one of wrangler.jsonc's environments, as `wrangler -e` does (`--env dev` for `celld dev`).
11// --var sets a Worker variable; repeat it. `celld deploy` takes no secrets of its own, so the secrets
12// named in SECRETS are copied from this process's environment into `vars` when set: the rendered file
13// then holds them, is written readable by its owner only and is ignored by git. celld keeps the
14// deployment in the fleet bucket, whose credentials are the fleet's administrator access anyway.
15// From the environment it also takes RUNNER_IMAGE, an image already in a registry (scripts/runner-image.sh).
16import { chmodSync, readFileSync, writeFileSync } from "node:fs";
17import { dirname, join, resolve } from "node:path";
18import { fileURLToPath, pathToFileURL } from "node:url";
19import { parseArgs } from "node:util";
20import { parseJsonc } from "./jsonc.mjs";
21
22/** Top-level keys `celld deploy` accepts (celld's docs/cloudflare-compat.md); any other stops the deploy. */
23export const CELLD_KEYS = new Set(["$schema", "name", "main", "no_bundle", "compatibility_date", "compatibility_flags", "durable_objects", "migrations", "assets", "services", "triggers", "vars", "d1_databases", "kv_namespaces", "queues", "workflows", "r2_buckets", "worker_loaders", "containers", "define", "rules"]);
24
25/** Keys celld accepts inside a list entry; any other stops the deploy. */
26const NESTED = {
27 migrations: ["tag", "new_sqlite_classes"],
28 workflows: ["name", "binding", "class_name", "script_name"],
29 producers: ["binding", "queue", "delivery_delay"],
30 consumers: ["queue", "max_batch_size", "max_batch_timeout", "max_retries", "dead_letter_queue", "max_concurrency", "retry_delay"],
31 d1_databases: ["binding", "database_name", "database_id", "migrations_dir", "migrations_table"],
32 r2_buckets: ["binding", "bucket_name"],
33};
34
35/**
36 * wrangler.jsonc keys celld has no equivalent for, and what the instance does without each. A key
37 * that holds bindings names them, so the guard test can check the Worker runs without them.
38 */
39export const DROPPED = {
40 routes: { why: "celld has no managed ingress: put a TLS-terminating proxy in front of the fleet" },
41 workers_dev: { why: "a workers.dev subdomain only exists on Cloudflare" },
42 observability: { why: "logs go to each celld node's output" },
43 upload_source_maps: { why: "stack traces point into the bundle" },
44 limits: { why: "celld has no per-request CPU limit to raise" },
45 version_metadata: { why: "IndexNow hashes the site's pages at every check instead of once per deployed version", bindings: (v) => [v.binding] },
46 ratelimits: { why: "requests are not rate limited: limit them in the proxy in front of the fleet", bindings: (v) => v.map((r) => r.name) },
47 send_email: { why: "emails are logged as skipped, not sent", bindings: (v) => v.map((e) => e.name) },
48};
49
50/** Container keys celld accepts. The image build context is the Dockerfile's directory, as image_build_context says here. */
51const CONTAINER_KEYS = ["class_name", "image", "name", "instance_type", "max_instances", "runtime"];
52
53/** Secrets (`wrangler secret put` on Cloudflare) copied from the environment into `vars`. */
54export const SECRETS = ["MASTER_KEY", "MASTER_KEY_PREV", "OIDC_PRIVATE_KEY", "MAIL_EVENTS_SECRET", "TURNSTILE_SECRET", "GITHUB_OAUTH_CLIENT_SECRET", "SANDBOX_POOL_SECRET"];
55
56/**
57 * wrangler.jsonc as celld takes it. Returns the config and the bindings left out (`absent`), which
58 * must all be optional in the Worker's Env. Throws on anything celld would refuse or run differently.
59 */
60export function celldConfig(wrangler, { env, vars = {}, secrets = {}, runnerImage } = {}) {
61 let cfg = structuredClone(wrangler);
62 if (env) {
63 const block = cfg.env?.[env];
64 if (!block) throw new Error(`wrangler.jsonc has no environment "${env}"`);
65 cfg = { ...cfg, ...structuredClone(block), name: `${cfg.name}-${env}` };
66 }
67 delete cfg.env;
68
69 const absent = [];
70 const dropped = [];
71 for (const key of Object.keys(cfg)) {
72 if (CELLD_KEYS.has(key)) continue;
73 const d = DROPPED[key];
74 if (!d) throw new Error(`wrangler.jsonc key "${key}" is not supported by celld; handle it in scripts/celld-config.mjs (DROPPED) and docs/self-hosting/celld.md`);
75 absent.push(...(d.bindings?.(cfg[key]) ?? []));
76 dropped.push({ key, why: d.why });
77 delete cfg[key];
78 }
79
80 for (const m of cfg.migrations ?? []) only("migrations", m, NESTED.migrations);
81 for (const w of cfg.workflows ?? []) only("workflows", w, NESTED.workflows);
82 for (const p of cfg.queues?.producers ?? []) only("queues.producers", p, NESTED.producers);
83 for (const c of cfg.queues?.consumers ?? []) only("queues.consumers", c, NESTED.consumers);
84 for (const d of cfg.d1_databases ?? []) only("d1_databases", d, NESTED.d1_databases);
85 for (const r of cfg.r2_buckets ?? []) only("r2_buckets", r, NESTED.r2_buckets);
86 // celld schedules containers itself: no rollout settings, and the build context is the Dockerfile's directory.
87 cfg.containers = (cfg.containers ?? []).map((c) => {
88 if (c.image_build_context && resolve(c.image_build_context) !== dirname(resolve(c.image))) throw new Error(`container ${c.class_name}: celld builds in the Dockerfile's directory, not ${c.image_build_context}`);
89 const out = Object.fromEntries(Object.entries(c).filter(([k]) => CONTAINER_KEYS.includes(k)));
90 if (runnerImage) out.image = runnerImage;
91 return out;
92 });
93 if (!cfg.containers.length) delete cfg.containers;
94
95 // Wrangler's default module rules, which the Worker relies on (src/text-modules.d.ts), stated for celld's esbuild.
96 const rules = cfg.rules ?? [];
97 for (const [type, glob] of [["Text", "**/*.txt"], ["Data", "**/*.bin"]]) if (!rules.some((r) => r.globs?.includes(glob))) rules.push({ type, globs: [glob] });
98 cfg.rules = rules;
99
100 cfg.vars = { ...cfg.vars, ...vars, ...secrets };
101 for (const [k, v] of Object.entries(cfg.vars)) if (typeof v !== "string") throw new Error(`var ${k} must be a string for celld`);
102 // EGRESS=web starts containers without internet and intercepts their HTTPS (lib/egress.ts), which celld refuses.
103 if (cfg.vars.EGRESS === "web") throw new Error("EGRESS=web needs Cloudflare Containers' outbound interception, which celld doesn't have; leave EGRESS unset");
104 return { config: cfg, absent, dropped };
105}
106
107function only(where, entry, keys) {
108 const extra = Object.keys(entry).filter((k) => !keys.includes(k));
109 if (extra.length) throw new Error(`${where}: celld doesn't support ${extra.join(", ")}`);
110}
111
112if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
113 const { values } = parseArgs({ options: { env: { type: "string" }, "public-url": { type: "string" }, var: { type: "string", multiple: true }, out: { type: "string" } } });
114 const appDir = join(dirname(fileURLToPath(import.meta.url)), "..", "apps", "diffinery");
115 const vars = {};
116 for (const v of values.var ?? []) {
117 const i = v.indexOf("=");
118 if (i < 1) throw new Error(`--var takes NAME=VALUE, not ${JSON.stringify(v)}`);
119 vars[v.slice(0, i)] = v.slice(i + 1);
120 }
121 if (values["public-url"]) {
122 const url = new URL(values["public-url"]);
123 if (url.pathname !== "/") throw new Error("--public-url must be an origin, like https://git.example.com");
124 vars.PUBLIC_URL = url.origin;
125 vars.MAIL_FROM ??= `notifications@${url.hostname}`;
126 }
127 const secrets = Object.fromEntries(SECRETS.filter((s) => process.env[s]).map((s) => [s, process.env[s]]));
128 const wrangler = parseJsonc(readFileSync(join(appDir, "wrangler.jsonc"), "utf8"));
129 const { config, dropped } = celldConfig(wrangler, { env: values.env, vars, secrets, runnerImage: process.env.RUNNER_IMAGE });
130 const out = values.out ? resolve(values.out) : join(appDir, "wrangler.celld.jsonc");
131 writeFileSync(out, `// Generated by scripts/celld-config.mjs from wrangler.jsonc; do not edit.\n${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
132 chmodSync(out, 0o600);
133 for (const d of dropped) console.error(`left out ${d.key}: ${d.why}`);
134 if (Object.keys(secrets).length) console.error(`copied ${Object.keys(secrets).join(", ")} into vars; keep ${out} private`);
135 console.log(`wrote ${out}`);
136}