Run on celld, the open-source Workers runtime, as well as Cloudflare
Diffinery keeps wrangler.jsonc as the one config and gains a second target:
celld, the open-source Workers and Durable Objects runtime from the Deno team,
now part of Cloudflare. An instance can then leave Cloudflare without a fork.
- scripts/celld-config.mjs renders wrangler.celld.jsonc: it drops the keys celld
refuses (routes, send_email, ratelimits, version_metadata, ...), adds the module
rules, copies secrets from the environment into vars and refuses EGRESS=web.
- git-upload-pack streams through RepoDO.fetch instead of an RPC return value:
celld can't return a stream from RPC ("RPC streams cannot cross isolate
boundaries yet"), which broke git clone there.
- Image codecs import plain .wasm paths instead of .wasm?module.
- test/unit/celld.test.ts keeps it that way: config keys, optional bindings
(CELLD_ABSENT_BINDINGS, type-checked in env.ts), built-in imports, no streams
from Durable Object RPC, and handlers.
- Docs: Run on celld (self-hosting/celld), linked from self-hosting, configuration,
architecture and the README; the rule in AGENTS.md and CONTRIBUTING.md.
Tested on a one-node celld 0.6.3 fleet (Azurite bucket) and on wrangler dev:
the same 14 smoke checks pass on both (git push, clone, shallow clone and fetch,
REST, GraphQL, MCP, issues, pull requests and merge, archives, avatars,
workflow runs). Hosted runners on celld containers are not tested.19 files changed+415−19
Files (19)
- .gitignore+2−0
- AGENTS.md+5−0
- CONTRIBUTING.md+4−0
- README.md+2−0
- apps/diffinery/docs/nav.json+1−0
- apps/diffinery/docs/self-hosting.md+5−1
- apps/diffinery/docs/self-hosting/architecture.md+1−1
- apps/diffinery/docs/self-hosting/celld.md+118−0
- apps/diffinery/docs/self-hosting/configuration.md+1−0
- apps/diffinery/src/env.ts+9−0
- apps/diffinery/src/git/protocol.ts+2−0
- apps/diffinery/src/http/git.ts+4−3
- apps/diffinery/src/lib/image.ts+6−6
- apps/diffinery/src/repo/RepoDO.ts+5−1
- apps/diffinery/src/text-modules.d.ts+14−2
- apps/diffinery/test/unit/celld.test.ts+95−0
- apps/diffinery/test/unit/image.test.ts+2−2
- apps/diffinery/vitest.config.ts+3−3
- scripts/celld-config.mjs+136−0
modified.gitignore+2−0View file
| @@ -7,3 +7,5 @@ | ||
| 7 | 7 | coverage/ |
| 8 | 8 | .DS_Store |
| 9 | 9 | wrangler.deploy.jsonc |
| 10 | +wrangler.celld.jsonc | |
| 11 | +.celld/ |
modifiedAGENTS.md+5−0View file
| @@ -55,6 +55,11 @@ | ||
| 55 | 55 | - **Follow GitHub where GitHub has an API, event or workflow feature**, so git, `gh`, |
| 56 | 56 | Octokit and actions keep working. Document any difference in |
| 57 | 57 | `apps/diffinery/docs/actions/compatibility.md` or the relevant page. |
| 58 | +- **Keep it running on celld**, the open-source Workers runtime | |
| 59 | + (`apps/diffinery/docs/self-hosting/celld.md`). Make a binding celld lacks optional (and list it in | |
| 60 | + `CELLD_ABSENT_BINDINGS`), map any new `wrangler.jsonc` key in `scripts/celld-config.mjs`, and import only | |
| 61 | + `cloudflare:workers`, `cloudflare:workflows` and the `node:` modules celld has. Never return a stream or a | |
| 62 | + `Response` from a Durable Object RPC method: stream through its `fetch()`. `test/unit/celld.test.ts` checks it. | |
| 58 | 63 | - **D1 migrations** live in `apps/diffinery/migrations`. Use the next free number and never |
| 59 | 64 | edit a migration that has shipped. |
| 60 | 65 | - **Security:** guardrails for agents are enforced on the server for git, REST, MCP and the |
modifiedCONTRIBUTING.md+4−0View file
| @@ -75,6 +75,10 @@ | ||
| 75 | 75 | - **GitHub compatibility.** Where GitHub has an API, a workflow feature or an event, |
| 76 | 76 | Diffinery follows it, so existing tools (git, `gh`, Octokit, actions) work unchanged. |
| 77 | 77 | When Diffinery has to differ, say so in the docs. |
| 78 | +- **Open-source runtime.** Diffinery also runs on [celld](https://celld.dev), the open-source | |
| 79 | + Workers runtime. A Cloudflare feature celld lacks must be optional, a new `wrangler.jsonc` | |
| 80 | + key must be mapped in `scripts/celld-config.mjs`, and the unit test `celld.test.ts` checks | |
| 81 | + both. See [Run on celld](https://diffinery.com/docs/self-hosting/celld). | |
| 78 | 82 | - **Database migrations.** D1 migrations live in `apps/diffinery/migrations`. Use the next |
| 79 | 83 | free number and never edit a migration that has shipped. |
| 80 | 84 | - **Security first.** Agents never get a bypass: guardrails are enforced on the server for |
modifiedREADME.md+2−0View file
| @@ -210,6 +210,8 @@ | ||
| 210 | 210 | |
| 211 | 211 | You can also deploy from CI with the included [Deploy workflow](.github/workflows/deploy.yml) on Diffinery or GitHub Actions. The full guide, including email sending, DNS, Access and troubleshooting, is [Deploy your own Diffinery](https://diffinery.com/docs/self-hosting/deploy), and every setting is described in [Configuration](https://diffinery.com/docs/self-hosting/configuration). |
| 212 | 212 | |
| 213 | +Diffinery also targets [celld](https://celld.dev), the open-source Workers and Durable Objects runtime, so the same repository can run on your own machines if you leave Cloudflare. See [Run on celld](https://diffinery.com/docs/self-hosting/celld). | |
| 214 | + | |
| 213 | 215 | ## How it runs on Cloudflare |
| 214 | 216 | |
| 215 | 217 | | Piece | Cloudflare product | |
modifiedapps/diffinery/docs/self-hosting.md+5−1View file
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: Self-hosting |
| 3 | 3 | description: Diffinery is open source (Apache-2.0) and runs on your own Cloudflare account. What an instance needs, what it costs, the steps to deploy one, and where to go next. |
| 4 | -updated: 2026-10-25 | |
| 4 | +updated: 2026-10-30 | |
| 5 | 5 | --- |
| 6 | 6 | |
| 7 | 7 | Diffinery is open-source software under the Apache License 2.0, and the way to use it is to run your own instance on your own Cloudflare account and domain. There's no hosted service to sign up for: diffinery.com is the project's own instance. This page is the overview; [Deploy your own Diffinery](/docs/self-hosting/deploy) is the step-by-step guide. |
| @@ -59,6 +59,10 @@ | ||
| 59 | 59 | - **Your team's tools.** The CLI, the Claude Code and Codex plugins, the MCP server and the editor extensions all work with your instance. People install the CLI from it and run `diffinery setup` with its URL, which signs them in and points git, gh, the Claude Code plugins and Codex at it: `curl -fsSL https://git.example.com/install | bash`, then `diffinery setup --url https://git.example.com`. AI apps connect to `https://git.example.com/mcp`. See [Claude Code](/docs/connect/claude-code#self-hosted-diffinery), [Codex](/docs/connect/codex#self-hosted-diffinery), [Clone in your editor](/docs/repositories/clone-in-your-editor) and [Clone in JetBrains IDEs](/docs/repositories/clone-in-jetbrains-ides). |
| 60 | 60 | - **How it fits together.** [Architecture](/docs/self-hosting/architecture) maps each part of Diffinery to the Cloudflare product that runs it. |
| 61 | 61 | |
| 62 | +## Without Cloudflare | |
| 63 | + | |
| 64 | +The same repository also targets [celld](https://celld.dev), the open-source Workers and Durable Objects runtime, which runs on your own machines with an object storage bucket. `scripts/celld-config.mjs` turns `wrangler.jsonc` into a configuration celld accepts, and the unit tests keep Diffinery inside what celld supports. celld is beta and a few things work differently there, such as email and rate limits; see [Run on celld](/docs/self-hosting/celld). | |
| 65 | + | |
| 62 | 66 | ## Get help and contribute |
| 63 | 67 | |
| 64 | 68 | Report bugs and send pull requests on [the GitHub mirror](https://github.com/codician-team/diffinery) or [the Diffinery repository](https://diffinery.com/codician/diffinery). Report security problems privately with the [report form](https://diffinery.com/security/report); see [Vulnerability disclosure](/docs/security/disclosure). |
modifiedapps/diffinery/docs/self-hosting/architecture.md+1−1View file
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | description: How Diffinery maps onto Cloudflare products, how a git push and a workflow run flow through them, and where each kind of data is stored. |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | -Diffinery is one Cloudflare Worker plus the Cloudflare products it binds to. There are no servers or databases to run yourself. This page explains which product does what, how a git push and a workflow run move through the system, how the code is organized, and where each kind of data lives. Read it before you deploy or operate your own instance, or when you need to reason about consistency and failure modes. | |
| 6 | +Diffinery is one Cloudflare Worker plus the Cloudflare products it binds to. There are no servers or databases to run yourself. This page explains which product does what, how a git push and a workflow run move through the system, how the code is organized, and where each kind of data lives. Read it before you deploy or operate your own instance, or when you need to reason about consistency and failure modes. The same code also runs on celld, the open-source Workers runtime; [Run on celld](/docs/self-hosting/celld) maps each product to its celld equivalent. | |
| 7 | 7 | |
| 8 | 8 | ## Overview |
| 9 | 9 |
addedapps/diffinery/docs/self-hosting/celld.md+118−0View file
| @@ -1,0 +1,118 @@ | ||
| 1 | +--- | |
| 2 | +title: Run on celld | |
| 3 | +description: Run Diffinery outside Cloudflare on celld, the open-source Workers and Durable Objects runtime. What runs, what is left out, the gaps to know, and the commands to deploy a fleet. | |
| 4 | +updated: 2026-10-31 | |
| 5 | +--- | |
| 6 | + | |
| 7 | +Diffinery is built for Cloudflare, and the same code also targets [celld](https://celld.dev), the open-source (Apache-2.0) implementation of Workers and Durable Objects that the Deno team built and that is now part of Cloudflare. celld runs a Worker on your own machines, with an S3, Google Cloud Storage or Azure Blob bucket as its only outside dependency. If you ever need to leave Cloudflare, or run Diffinery where Cloudflare isn't an option, you keep the same repository, the same `wrangler.jsonc` and the same data model. | |
| 8 | + | |
| 9 | +> **Status.** celld is beta and its Containers support is experimental. On October 31, 2026, Diffinery ran on a one-node celld 0.6.3 fleet: it applied the D1 migrations and served the web UI, docs, REST, GraphQL and MCP. git push (with a 6 MB object), clone, shallow clone and fetch worked, as did issues, pull requests and squash merge, archives, profile pictures and the event queues, and pushes started workflow runs. Hosted runners and sandboxes, which need celld's containers, were not tested, and the end-to-end test suite doesn't run on celld yet. The unit tests check on every run that Diffinery stays inside what celld supports (see [How compatibility is kept](#how-compatibility-is-kept)). | |
| 10 | + | |
| 11 | +## What runs on celld | |
| 12 | + | |
| 13 | +| Diffinery uses | On Cloudflare | On celld | | |
| 14 | +| --- | --- | --- | | |
| 15 | +| The Worker: web UI, REST and GraphQL APIs, git over HTTPS, MCP server | Workers | Workers, with `nodejs_compat` | | |
| 16 | +| One Durable Object per repository, with SQLite, alarms and hibernating WebSockets (`REPO`, `PROJECT`, `SCHEDULER`, `COMPOSE`) | Durable Objects | Cells, distributed across the fleet | | |
| 17 | +| Accounts, organizations, tokens (`DB`) | D1 | D1, one cell per database, no read replicas | | |
| 18 | +| Git objects, LFS, logs, caches, artifacts, release assets (`BUCKET`) | R2 | R2, stored under `r2/diffinery-data/` in the fleet bucket | | |
| 19 | +| Webhooks, notifications and email jobs (`EVENTS`, `MAIL`) | Queues | Queues, with retries and dead-letter queues | | |
| 20 | +| Workflow runs, imports, account exports (`RUN_WORKFLOW`, `IMPORT_WORKFLOW`, `ACCOUNT_WORKFLOW`) | Workflows | Workflows | | |
| 21 | +| Housekeeping every 5 minutes | Cron Triggers | Cron Triggers, one run per occurrence across the fleet | | |
| 22 | +| Hosted runners, sandboxes and the import container | Containers | Containers (experimental), on Docker or Podman on each node | | |
| 23 | + | |
| 24 | +## What is left out | |
| 25 | + | |
| 26 | +`celld deploy` stops on a `wrangler.jsonc` key it doesn't know. `scripts/celld-config.mjs` writes `apps/diffinery/wrangler.celld.jsonc` from `wrangler.jsonc` without these keys, and Diffinery runs without each of them: | |
| 27 | + | |
| 28 | +| `wrangler.jsonc` key | Binding | What happens on celld | | |
| 29 | +| --- | --- | --- | | |
| 30 | +| `routes`, `workers_dev` | | celld has no managed ingress. Put a reverse proxy that terminates TLS in front of the fleet. | | |
| 31 | +| `send_email` | `EMAIL` | Emails are logged as skipped, not sent. **Settings → Email** (`/settings/admin/email`) shows "not configured (no EMAIL binding)". Invitation links are still shown to the person who invites, with a copy button. | | |
| 32 | +| `ratelimits` | `RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL` | Requests are not rate limited. Limit them in your proxy. | | |
| 33 | +| `version_metadata` | `CF_VERSION_METADATA` | IndexNow hashes the site's pages at every check instead of once per deployed version. | | |
| 34 | +| `observability`, `upload_source_maps`, `limits` | | Logs go to each node's output, and stack traces point into the bundle. | | |
| 35 | + | |
| 36 | +The script also drops the container keys celld doesn't take (`image_build_context`, `rollout_active_grace_period`, `rollout_step_percentage`); celld builds the runner image in the Dockerfile's directory, `containers/runner`, which is the same context. | |
| 37 | + | |
| 38 | +## Gaps to know | |
| 39 | + | |
| 40 | +- **The first administrator.** The first sign-in is at `/auth/access` through Cloudflare Access, or through open sign-up's emailed code. On celld there is no email, so either put the fleet behind a [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/) with an Access application on `/auth/access` and set `ACCESS_TEAM_DOMAIN` and `ACCESS_AUD`, or wait for a non-Cloudflare email transport. After that, the administrator invites people and sends them the link shown under "Invite created for …"; passkey sign-in needs neither Access nor email. | |
| 41 | +- **Client IP addresses.** Diffinery reads the client's address from the `CF-Connecting-IP` header. Cloudflare sets it; on celld your proxy must set it, and must replace any value the client sent, or a client can pick its own address. | |
| 42 | +- **Request location.** Requests carry no Cloudflare location, so the CLI sign-in page can't compare countries, and `Server-Timing` has no location. | |
| 43 | +- **`EGRESS=web`.** Limiting hosted jobs to HTTP and HTTPS needs Cloudflare Containers' outbound interception, which celld doesn't have. `scripts/celld-config.mjs` refuses `EGRESS=web`. Note that celld's own network fence blocks containers from the node, private ranges and link-local addresses. | |
| 44 | +- **Containers.** Each node that runs jobs needs Docker or Podman, and the `celld-fence` container that celld starts. celld doesn't enforce disk sizes, and moving a cell to another node stops its container. | |
| 45 | +- **Platforms.** celld runs on Linux x86-64, Linux ARM64 and Apple Silicon, not Windows. | |
| 46 | + | |
| 47 | +## Deploy a fleet | |
| 48 | + | |
| 49 | +You need the celld binary ([install](https://celld.dev)) on every node, a bucket, and Node.js 22 and pnpm 10 on the machine you deploy from. `celld deploy` bundles the Worker with esbuild, which `pnpm install` puts in `apps/diffinery/node_modules/.bin`. | |
| 50 | + | |
| 51 | +1. Build what the Worker imports (web islands and docs): | |
| 52 | + | |
| 53 | + ```sh | |
| 54 | + pnpm install | |
| 55 | + pnpm -r build | |
| 56 | + ``` | |
| 57 | + | |
| 58 | +2. Create the Worker's secrets once and keep them. `celld deploy` has no secret store, so `scripts/celld-config.mjs` copies `MASTER_KEY`, `MASTER_KEY_PREV`, `OIDC_PRIVATE_KEY`, `MAIL_EVENTS_SECRET`, `TURNSTILE_SECRET`, `GITHUB_OAUTH_CLIENT_SECRET` and `SANDBOX_POOL_SECRET` from the environment into the Worker's variables. Never change `MASTER_KEY` once it is in use. | |
| 59 | + | |
| 60 | + ```sh | |
| 61 | + export MASTER_KEY="$(openssl rand -base64 32)" | |
| 62 | + export OIDC_PRIVATE_KEY="$(node --input-type=module -e ' | |
| 63 | + const k = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]); | |
| 64 | + const jwk = await crypto.subtle.exportKey("jwk", k.privateKey); | |
| 65 | + jwk.kid = "diffinery-" + new Date().toISOString().slice(0, 10); | |
| 66 | + process.stdout.write(JSON.stringify(jwk));')" | |
| 67 | + ``` | |
| 68 | + | |
| 69 | +3. Write the celld configuration for your hostname: | |
| 70 | + | |
| 71 | + ```sh | |
| 72 | + node scripts/celld-config.mjs --public-url https://git.example.com --var BOOTSTRAP_ADMINS=[email protected] | |
| 73 | + ``` | |
| 74 | + | |
| 75 | + It writes `apps/diffinery/wrangler.celld.jsonc`, readable by you only and ignored by git, and lists what it left out. `--var NAME=VALUE` sets any [Worker variable](/docs/self-hosting/configuration#worker-variables); repeat it. Set `RUNNER_IMAGE` to an image already in a registry to skip building the runner image. | |
| 76 | + | |
| 77 | +4. Deploy, start the nodes, then apply the D1 migrations, which need a live node: | |
| 78 | + | |
| 79 | + ```sh | |
| 80 | + cd apps/diffinery | |
| 81 | + PATH="$PWD/node_modules/.bin:$PATH" celld deploy wrangler.celld.jsonc --bucket s3://your-bucket | |
| 82 | + celld --bucket s3://your-bucket --listen 0.0.0.0:8080 --internal-listen 10.0.0.5:8081 --advertise 10.0.0.5:8081 | |
| 83 | + celld d1 migrations apply diffinery wrangler.celld.jsonc --bucket s3://your-bucket | |
| 84 | + ``` | |
| 85 | + | |
| 86 | + Run the second command on every node, with that node's private address. Put your proxy in front of the `--listen` ports. The deployment, including the variables, lives in the bucket, so give its credentials to fleet administrators only. | |
| 87 | + | |
| 88 | +To update, pull the repository, run steps 1, 3 and 4 again with the same secrets, and apply new migrations. | |
| 89 | + | |
| 90 | +## Try it locally | |
| 91 | + | |
| 92 | +`celld dev` serves a Worker from local storage, but the `celld d1` commands need a real bucket, so `celld dev` can't apply Diffinery's D1 migrations. To try Diffinery, run a one-node fleet on [Azurite](https://github.com/Azure/Azurite), Microsoft's Azure Blob Storage emulator, which celld supports for development. Render the `dev` environment, which has no containers and signs everyone in as `[email protected]`, with `PUBLIC_URL` set to the address you'll open: | |
| 93 | + | |
| 94 | +```sh | |
| 95 | +docker run -d --name azurite -p 10000:10000 mcr.microsoft.com/azure-storage/azurite azurite-blob --blobHost 0.0.0.0 --disableProductStyleUrl | |
| 96 | +az storage container create --name fleet --connection-string "UseDevelopmentStorage=true" | |
| 97 | +export AZURE_STORAGE_USE_EMULATOR=true AZURITE_BLOB_STORAGE_URL=http://127.0.0.1:10000 | |
| 98 | +pnpm -r build | |
| 99 | +MASTER_KEY="$(openssl rand -base64 32)" node scripts/celld-config.mjs --env dev --var PUBLIC_URL=http://localhost:8080 | |
| 100 | +cd apps/diffinery | |
| 101 | +PATH="$PWD/node_modules/.bin:$PATH" celld deploy wrangler.celld.jsonc --bucket az://fleet | |
| 102 | +celld --bucket az://fleet --listen 127.0.0.1:8080 --internal-listen 127.0.0.1:8081 --advertise 127.0.0.1:8081 & | |
| 103 | +celld d1 migrations apply diffinery-dev wrangler.celld.jsonc --bucket az://fleet | |
| 104 | +``` | |
| 105 | + | |
| 106 | +Then open `http://localhost:8080`. The dev sign-in works only while `PUBLIC_URL` and the request are on your own machine. celld doesn't qualify Azurite for a production fleet. | |
| 107 | + | |
| 108 | +## How compatibility is kept | |
| 109 | + | |
| 110 | +`apps/diffinery/test/unit/celld.test.ts` runs with the unit tests on every pull request. It fails when: | |
| 111 | + | |
| 112 | +- `wrangler.jsonc` gets a key that `scripts/celld-config.mjs` doesn't map, so a new Cloudflare-only setting must say what happens on celld; | |
| 113 | +- a binding the script leaves out isn't optional in the Worker's `Env` (`CELLD_ABSENT_BINDINGS` in `src/env.ts`, checked by the typecheck); | |
| 114 | +- the Worker's code imports a built-in module celld doesn't provide (only `cloudflare:workers`, `cloudflare:workflows` and celld's `node:` modules), or a path with a query such as `x.wasm?module`; | |
| 115 | +- a Durable Object's RPC method returns a stream or a `Response` (celld: "RPC streams cannot cross isolate boundaries yet"); stream through the object's `fetch()` instead, as `RepoDO` does for `git-upload-pack`; | |
| 116 | +- the Worker exports a handler celld doesn't call, such as `email` or `tail`. | |
| 117 | + | |
| 118 | +If a change needs a Cloudflare feature celld lacks, make the binding optional and document what happens without it on this page. |
modifiedapps/diffinery/docs/self-hosting/configuration.md+1−0View file
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | | `apps/diffinery/wrangler.deploy.jsonc` | `wrangler.jsonc` without the `dev` environment, plus the real D1 database ID, `ACCESS_TEAM_DOMAIN`, `ACCESS_AUD`, `TURNSTILE_SITE_KEY`, and the route, `PUBLIC_URL` and `MAIL_FROM` for your hostname. Written by `scripts/render-config.mjs` on every deploy and ignored by git. | No. It is regenerated on each deploy. | |
| 14 | 14 | | Worker secrets | `MASTER_KEY` and `OIDC_PRIVATE_KEY`, created by `scripts/ensure-secrets.sh`; `TURNSTILE_SECRET`, set by the deploy from its Turnstile widget; and optionally `GITHUB_OAUTH_CLIENT_SECRET`, which you set yourself. | Only to restore them, or to add the optional one. Never change `MASTER_KEY`. | |
| 15 | 15 | | Repository secrets and variables | Cloudflare credentials and options for the Deploy workflow, and a token for the live test. | Yes, in your forge's repository settings. | |
| 16 | +| `apps/diffinery/wrangler.celld.jsonc` | `wrangler.jsonc` as [celld](/docs/self-hosting/celld) takes it, with the Cloudflare-only keys left out and the secrets in `vars`. Written by `scripts/celld-config.mjs` and ignored by git. | No. Render it again after changing `wrangler.jsonc`. | | |
| 16 | 17 | | `apps/diffinery/.dev.vars` | Local secrets for `wrangler dev`, such as `MASTER_KEY`. Ignored by git. | Yes, for local development only. | |
| 17 | 18 | |
| 18 | 19 | ## Worker variables |
modifiedapps/diffinery/src/env.ts+9−0View file
| @@ -142,3 +142,12 @@ | ||
| 142 | 142 | /** Optional GitHub Enterprise host (e.g. github.example.com) the importer may download release assets from. */ |
| 143 | 143 | IMPORT_GHE_HOST?: string; |
| 144 | 144 | } |
| 145 | + | |
| 146 | +type OptionalKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? K : never }[keyof T]; | |
| 147 | + | |
| 148 | +/** | |
| 149 | + * Bindings celld (the open-source Workers runtime, docs/self-hosting/celld.md) has no equivalent for: | |
| 150 | + * scripts/celld-config.mjs leaves them out, so each must stay optional here and the Worker must run | |
| 151 | + * without it. The celld unit test checks this list against what the script leaves out. | |
| 152 | + */ | |
| 153 | +export const CELLD_ABSENT_BINDINGS = ["EMAIL", "RL_AUTH", "RL_ANON", "RL_ACCOUNT", "RL_CREATE", "RL_MODEL", "CF_VERSION_METADATA"] as const satisfies ReadonlyArray<OptionalKeys<Env>>; |
modifiedapps/diffinery/src/git/protocol.ts+2−0View file
| @@ -2,6 +2,8 @@ | ||
| 2 | 2 | import type { RawObject } from "../repo/objects.js"; |
| 3 | 3 | |
| 4 | 4 | export const AGENT = "diffinery/0.1"; |
| 5 | +/** The RepoDO.fetch path the Worker posts a git fetch request to (http/git.ts); the response is the streamed pack. */ | |
| 6 | +export const UPLOAD_PACK_PATH = "/git-upload-pack"; | |
| 5 | 7 | |
| 6 | 8 | export type RefEntry = { |
| 7 | 9 | name: string; |
modifiedapps/diffinery/src/http/git.ts+4−3View file
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | import { importPushAllowed } from "../imports/service.js"; |
| 8 | 8 | import { loadRepo, repoStub } from "./common.js"; |
| 9 | 9 | import type { Caller } from "../repo/types.js"; |
| 10 | -import { resetByDeploy } from "../git/protocol.js"; | |
| 10 | +import { resetByDeploy, UPLOAD_PACK_PATH } from "../git/protocol.js"; | |
| 11 | 11 | |
| 12 | 12 | /** |
| 13 | 13 | * Git smart HTTP (protocol v2 for fetch/clone, v0 for push) and the Git LFS |
| @@ -39,8 +39,9 @@ | ||
| 39 | 39 | git.post("/:owner/:repo/git-upload-pack", async (c) => { |
| 40 | 40 | const { stub } = await loadRepo(c, c.req.param("owner"), c.req.param("repo"), "read", { readOnlyPost: true, follow: true }); |
| 41 | 41 | const body = await readBody(c.req.raw, MAX_UPLOAD_PACK_REQUEST, "fetch request exceeds 16 MB"); |
| 42 | - const out = await stub.gitUploadPack(body); | |
| 43 | - return new Response(out, { headers: { "content-type": "application/x-git-upload-pack-result", ...noCache } }); | |
| 42 | + // Through RepoDO.fetch rather than RPC, so the pack streams on celld too. | |
| 43 | + const out = await stub.fetch(`https://repo${UPLOAD_PACK_PATH}`, { method: "POST", body }); | |
| 44 | + return new Response(out.body, { headers: { "content-type": "application/x-git-upload-pack-result", ...noCache } }); | |
| 44 | 45 | }); |
| 45 | 46 | |
| 46 | 47 | git.post("/:owner/:repo/git-receive-pack", async (c) => { |
modifiedapps/diffinery/src/lib/image.ts+6−6View file
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Profile pictures: check an uploaded JPEG, PNG or WebP and turn it into small square WebPs. |
| 3 | 3 | * |
| 4 | - * Everything runs in the Worker on jSquash's WASM codecs. Wrangler bundles each `*.wasm` import | |
| 4 | + * Everything runs in the Worker on jSquash's WASM codecs. Wrangler (and celld) bundles each `*.wasm` import | |
| 5 | 5 | * as a compiled WebAssembly.Module (its default CompiledWasm rule), and each codec gets its module |
| 6 | 6 | * through `init(module)`, so nothing is fetched at runtime. |
| 7 | 7 | * |
| @@ -15,12 +15,12 @@ | ||
| 15 | 15 | import decodeWebp, { init as initWebpDecode } from "@jsquash/webp/decode.js"; |
| 16 | 16 | import encodeWebp, { init as initWebpEncode } from "@jsquash/webp/encode.js"; |
| 17 | 17 | import resize, { initResize } from "@jsquash/resize"; |
| 18 | -import JPEG_DEC_WASM from "@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm?module"; | |
| 19 | -import PNG_DEC_WASM from "@jsquash/png/codec/pkg/squoosh_png_bg.wasm?module"; | |
| 20 | -import WEBP_DEC_WASM from "@jsquash/webp/codec/dec/webp_dec.wasm?module"; | |
| 18 | +import JPEG_DEC_WASM from "@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm"; | |
| 19 | +import PNG_DEC_WASM from "@jsquash/png/codec/pkg/squoosh_png_bg.wasm"; | |
| 20 | +import WEBP_DEC_WASM from "@jsquash/webp/codec/dec/webp_dec.wasm"; | |
| 21 | 21 | // @jsquash/webp's encoder picks its SIMD build when the runtime supports WASM SIMD, which V8 (workerd, Node) does. |
| 22 | -import WEBP_ENC_WASM from "@jsquash/webp/codec/enc/webp_enc_simd.wasm?module"; | |
| 23 | -import RESIZE_WASM from "@jsquash/resize/lib/resize/pkg/squoosh_resize_bg.wasm?module"; | |
| 22 | +import WEBP_ENC_WASM from "@jsquash/webp/codec/enc/webp_enc_simd.wasm"; | |
| 23 | +import RESIZE_WASM from "@jsquash/resize/lib/resize/pkg/squoosh_resize_bg.wasm"; | |
| 24 | 24 | import { HttpError } from "./util.js"; |
| 25 | 25 | |
| 26 | 26 | /** Square sizes we store, in pixels: 2× the 20, 40 (`.av.lg`) and 96 (`.av.xl`, rounded up) CSS pixel avatars. */ |
modifiedapps/diffinery/src/repo/RepoDO.ts+5−1View file
| @@ -47,6 +47,7 @@ | ||
| 47 | 47 | type ReceiveRequest, |
| 48 | 48 | resetByDeploy, |
| 49 | 49 | unpackFailure, |
| 50 | + UPLOAD_PACK_PATH, | |
| 50 | 51 | type RefEntry, |
| 51 | 52 | type RefResult, |
| 52 | 53 | } from "../git/protocol.js"; |
| @@ -623,7 +624,7 @@ | ||
| 623 | 624 | } |
| 624 | 625 | |
| 625 | 626 | /** The response streams: the pack is read and sent one object at a time, as the client takes it. */ |
| 626 | - async gitUploadPack(body: Uint8Array): Promise<ReadableStream<Uint8Array>> { | |
| 627 | + private async gitUploadPack(body: Uint8Array): Promise<ReadableStream<Uint8Array>> { | |
| 627 | 628 | const { readable, writable } = new IdentityTransformStream(); |
| 628 | 629 | const writer = writable.getWriter(); |
| 629 | 630 | let started = false; |
| @@ -2161,6 +2162,9 @@ | ||
| 2161 | 2162 | // ---------------------------------------------------------------- live updates (WebSockets with hibernation) |
| 2162 | 2163 | |
| 2163 | 2164 | override async fetch(request: Request): Promise<Response> { |
| 2165 | + // The pack streams back through fetch, not RPC: celld can't return a stream from an RPC call | |
| 2166 | + // ("RPC streams cannot cross isolate boundaries yet"), and a fetch body streams on both runtimes. | |
| 2167 | + if (request.method === "POST" && new URL(request.url).pathname === UPLOAD_PACK_PATH) return new Response(await this.gitUploadPack(new Uint8Array(await request.arrayBuffer()))); | |
| 2164 | 2168 | if (request.headers.get("Upgrade") !== "websocket") return new Response("expected websocket", { status: 426 }); |
| 2165 | 2169 | const topics = (new URL(request.url).searchParams.get("topics") ?? "repo").split(",").filter((t) => /^[a-z]+(:[A-Za-z0-9_-]+)?$/.test(t)).slice(0, 10); |
| 2166 | 2170 | const pair = new WebSocketPair(); |
modifiedapps/diffinery/src/text-modules.d.ts+14−2View file
| @@ -4,8 +4,9 @@ | ||
| 4 | 4 | export default text; |
| 5 | 5 | } |
| 6 | 6 | |
| 7 | -// Compiled WebAssembly modules (wrangler's default CompiledWasm rule; the wasm plugin in vitest.config.ts under tests). | |
| 8 | -declare module "*.wasm?module" { | |
| 7 | +// Compiled WebAssembly modules (wrangler's default CompiledWasm rule, and celld's for every .wasm import; the wasm | |
| 8 | +// plugin in vitest.config.ts under tests). A plain .wasm path: celld documents .wasm?module only for unbundled Workers. | |
| 9 | +declare module "*.wasm" { | |
| 9 | 10 | const module: WebAssembly.Module; |
| 10 | 11 | export default module; |
| 11 | 12 | } |
| @@ -15,3 +16,14 @@ | ||
| 15 | 16 | const data: ArrayBuffer; |
| 16 | 17 | export default data; |
| 17 | 18 | } |
| 19 | + | |
| 20 | +// These two packages ship wasm-bindgen typings beside the file (`*.wasm.d.ts`, the module's exports), which | |
| 21 | +// would win over the pattern above; an exact name wins over both. | |
| 22 | +declare module "@jsquash/png/codec/pkg/squoosh_png_bg.wasm" { | |
| 23 | + const module: WebAssembly.Module; | |
| 24 | + export default module; | |
| 25 | +} | |
| 26 | +declare module "@jsquash/resize/lib/resize/pkg/squoosh_resize_bg.wasm" { | |
| 27 | + const module: WebAssembly.Module; | |
| 28 | + export default module; | |
| 29 | +} |
addedapps/diffinery/test/unit/celld.test.ts+95−0View file
| @@ -1,0 +1,95 @@ | ||
| 1 | +import { readdirSync, readFileSync, statSync } from "node:fs"; | |
| 2 | +import { join } from "node:path"; | |
| 3 | +import { fileURLToPath } from "node:url"; | |
| 4 | +import { describe, expect, it } from "vitest"; | |
| 5 | +import { CELLD_ABSENT_BINDINGS } from "../../src/env.js"; | |
| 6 | +import { CELLD_KEYS, SECRETS, celldConfig } from "../../../../scripts/celld-config.mjs"; | |
| 7 | +import { parseJsonc } from "../../../../scripts/jsonc.mjs"; | |
| 8 | + | |
| 9 | +/** | |
| 10 | + * Diffinery runs on Cloudflare and on celld, the open-source Workers runtime (docs/self-hosting/celld.md). | |
| 11 | + * These checks keep it that way: wrangler.jsonc renders to a config celld accepts, the bindings celld | |
| 12 | + * lacks are optional in Env, and the Worker's own code uses only modules and handlers celld provides. | |
| 13 | + */ | |
| 14 | + | |
| 15 | +const repo = fileURLToPath(new URL("../../../../", import.meta.url)); | |
| 16 | +const wrangler = parseJsonc(readFileSync(join(repo, "apps/diffinery/wrangler.jsonc"), "utf8")); | |
| 17 | + | |
| 18 | +describe("wrangler.jsonc for celld", () => { | |
| 19 | + it("renders with only keys celld accepts", () => { | |
| 20 | + for (const env of [undefined, "dev"]) { | |
| 21 | + const { config } = celldConfig(wrangler, { env }); | |
| 22 | + for (const key of Object.keys(config)) expect(CELLD_KEYS.has(key), `${env ?? "production"}: ${key}`).toBe(true); | |
| 23 | + for (const c of config.containers ?? []) expect(Object.keys(c).every((k) => ["class_name", "image", "name", "instance_type", "max_instances", "runtime"].includes(k))).toBe(true); | |
| 24 | + expect(config.rules).toEqual(expect.arrayContaining([{ type: "Text", globs: ["**/*.txt"] }, { type: "Data", globs: ["**/*.bin"] }])); | |
| 25 | + } | |
| 26 | + expect(celldConfig(wrangler, { env: "dev" }).config.name).toBe("diffinery-dev"); | |
| 27 | + }); | |
| 28 | + | |
| 29 | + it("leaves out exactly the bindings the Worker runs without", () => { | |
| 30 | + // CELLD_ABSENT_BINDINGS is type-checked to be optional in Env; this ties it to what the script drops. | |
| 31 | + const { absent } = celldConfig(wrangler); | |
| 32 | + expect(new Set(absent)).toEqual(new Set(CELLD_ABSENT_BINDINGS)); | |
| 33 | + }); | |
| 34 | + | |
| 35 | + it("stops on a key it doesn't know, a nested key celld refuses, and EGRESS=web", () => { | |
| 36 | + expect(() => celldConfig({ ...wrangler, tail_consumers: [{ service: "x" }] })).toThrow(/"tail_consumers" is not supported by celld/); | |
| 37 | + expect(() => celldConfig({ ...wrangler, r2_buckets: [{ binding: "BUCKET", bucket_name: "b", jurisdiction: "eu" }] })).toThrow(/r2_buckets: celld doesn't support jurisdiction/); | |
| 38 | + expect(() => celldConfig({ ...wrangler, migrations: [{ tag: "v9", renamed_classes: [] }] })).toThrow(/renamed_classes/); | |
| 39 | + expect(() => celldConfig(wrangler, { vars: { EGRESS: "web" } })).toThrow(/EGRESS=web/); | |
| 40 | + }); | |
| 41 | + | |
| 42 | + it("takes secrets and variables into vars, and a registry image for every container", () => { | |
| 43 | + const { config } = celldConfig(wrangler, { vars: { SIGNUP: "open" }, secrets: { MASTER_KEY: "k" }, runnerImage: "registry.example.com/runner:1" }); | |
| 44 | + expect(config.vars).toMatchObject({ SIGNUP: "open", MASTER_KEY: "k", PUBLIC_URL: wrangler.vars.PUBLIC_URL }); | |
| 45 | + expect(config.containers.every((c: { image: string }) => c.image === "registry.example.com/runner:1")).toBe(true); | |
| 46 | + expect(SECRETS).toContain("OIDC_PRIVATE_KEY"); | |
| 47 | + }); | |
| 48 | +}); | |
| 49 | + | |
| 50 | +/** Built-in modules celld implements (its docs/cloudflare-compat.md); node:crypto and node:zlib only in part. */ | |
| 51 | +const CELLD_MODULES = new Set(["cloudflare:workers", "cloudflare:workflows", ...["assert", "async_hooks", "buffer", "crypto", "diagnostics_channel", "events", "fs", "os", "path", "stream", "timers/promises", "util", "zlib"].map((m) => `node:${m}`)]); | |
| 52 | + | |
| 53 | +function sources(dir: string): string[] { | |
| 54 | + return readdirSync(dir).flatMap((f) => { | |
| 55 | + const p = join(dir, f); | |
| 56 | + if (statSync(p).isDirectory()) return sources(p); | |
| 57 | + return /\.tsx?$/.test(f) && !f.endsWith(".d.ts") ? [p] : []; | |
| 58 | + }); | |
| 59 | +} | |
| 60 | + | |
| 61 | +describe("Worker code celld runs", () => { | |
| 62 | + const files = ["apps/diffinery/src", "packages/git-core/src", "packages/shared/src", "packages/workflow-yaml/src"].flatMap((d) => sources(join(repo, d))); | |
| 63 | + | |
| 64 | + it("imports only runtime modules celld provides, and no query-suffixed paths", () => { | |
| 65 | + const bad: string[] = []; | |
| 66 | + for (const file of files) { | |
| 67 | + // Static imports and re-exports (`from "x"`, `import "x"`) and dynamic `import("x")`. | |
| 68 | + for (const [, a, b] of readFileSync(file, "utf8").matchAll(/^\s*(?:import|export)\b[^;]*?(?:\bfrom\s*|import\s+)"([^"\n]+)"|\bimport\(\s*"([^"\n]+)"\s*\)/gm)) { | |
| 69 | + const spec = a ?? b; | |
| 70 | + const builtin = /^(?:node|cloudflare):/.test(spec); | |
| 71 | + // `x.wasm?module` and the like: celld's esbuild picks a loader by extension only. | |
| 72 | + if ((builtin && !CELLD_MODULES.has(spec)) || spec.includes("?")) bad.push(`${file.slice(repo.length)}: ${spec}`); | |
| 73 | + } | |
| 74 | + } | |
| 75 | + expect(bad).toEqual([]); | |
| 76 | + }); | |
| 77 | + | |
| 78 | + it("returns no stream from a Durable Object's RPC methods", () => { | |
| 79 | + // celld: "RPC streams cannot cross isolate boundaries yet". A streamed answer goes through the object's | |
| 80 | + // fetch() instead, as git-upload-pack does (RepoDO.fetch). | |
| 81 | + const bad: string[] = []; | |
| 82 | + for (const file of files.filter((f) => /extends (?:DurableObject|Container)\b/.test(readFileSync(f, "utf8")))) { | |
| 83 | + for (const [m] of readFileSync(file, "utf8").matchAll(/^ {2}(?!private |protected |static |override async fetch\b|async fetch\b)(?:override )?(?:async )?\w+\([^)]*\)\s*:\s*Promise<(?:ReadableStream|Response|R2ObjectBody)\b[^\n]*/gm)) bad.push(`${file.slice(repo.length)}: ${m.trim()}`); | |
| 84 | + } | |
| 85 | + expect(bad).toEqual([]); | |
| 86 | + }); | |
| 87 | + | |
| 88 | + it("exports only the handlers celld calls", () => { | |
| 89 | + // celld has no email or tail handlers. | |
| 90 | + const handlers = readFileSync(join(repo, "apps/diffinery/src/index.ts"), "utf8").match(/export default \{([^}]*)\}/)?.[1]; | |
| 91 | + const names = (handlers ?? "").split(",").map((h) => h.split(":")[0].trim()).filter(Boolean); | |
| 92 | + expect(names.length).toBeGreaterThan(0); | |
| 93 | + for (const n of names) expect(["fetch", "queue", "scheduled", "alarm"]).toContain(n); | |
| 94 | + }); | |
| 95 | +}); |
modifiedapps/diffinery/test/unit/image.test.ts+2−2View file
| @@ -3,8 +3,8 @@ | ||
| 3 | 3 | import encodeJpeg, { init as initJpegEncode } from "@jsquash/jpeg/encode.js"; |
| 4 | 4 | import decodeWebpWasm, { init as initWebpDecode } from "@jsquash/webp/decode.js"; |
| 5 | 5 | import encodeWebp from "@jsquash/webp/encode.js"; |
| 6 | -import JPEG_ENC_WASM from "@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm?module"; | |
| 7 | -import WEBP_DEC_WASM from "@jsquash/webp/codec/dec/webp_dec.wasm?module"; | |
| 6 | +import JPEG_ENC_WASM from "@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm"; | |
| 7 | +import WEBP_DEC_WASM from "@jsquash/webp/codec/dec/webp_dec.wasm"; | |
| 8 | 8 | import { AVATAR_SIZES, MAX_AVATAR_BYTES, cropAndShrink, imageSize, jpegOrientation, makeAvatarImages, orientSquare, shrinkFactor, sniffImage, squareCrop, type Pixels } from "../../src/lib/image.js"; |
| 9 | 9 | import { HttpError } from "../../src/lib/util.js"; |
| 10 | 10 |
modifiedapps/diffinery/vitest.config.ts+3−3View file
| @@ -26,12 +26,12 @@ | ||
| 26 | 26 | }, |
| 27 | 27 | }, |
| 28 | 28 | { |
| 29 | - // `import mod from "x.wasm?module"` gives a compiled WebAssembly.Module, like wrangler's CompiledWasm rule in the Worker. | |
| 29 | + // `import mod from "x.wasm"` gives a compiled WebAssembly.Module, like wrangler's CompiledWasm rule in the Worker. | |
| 30 | 30 | name: "diffinery:wasm-module", |
| 31 | 31 | enforce: "pre", |
| 32 | 32 | async resolveId(source, importer) { |
| 33 | - if (!source.endsWith(".wasm?module")) return null; | |
| 34 | - const file = await this.resolve(source.slice(0, -"?module".length), importer, { skipSelf: true }); | |
| 33 | + if (!source.endsWith(".wasm")) return null; | |
| 34 | + const file = await this.resolve(source, importer, { skipSelf: true }); | |
| 35 | 35 | return file ? PREFIX + Buffer.from(file.id).toString("base64url") : null; |
| 36 | 36 | }, |
| 37 | 37 | load(id) { |
addedscripts/celld-config.mjs+136−0View file
| @@ -1,0 +1,136 @@ | ||
| 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). | |
| 16 | +import { chmodSync, readFileSync, writeFileSync } from "node:fs"; | |
| 17 | +import { dirname, join, resolve } from "node:path"; | |
| 18 | +import { fileURLToPath, pathToFileURL } from "node:url"; | |
| 19 | +import { parseArgs } from "node:util"; | |
| 20 | +import { parseJsonc } from "./jsonc.mjs"; | |
| 21 | + | |
| 22 | +/** Top-level keys `celld deploy` accepts (celld's docs/cloudflare-compat.md); any other stops the deploy. */ | |
| 23 | +export 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. */ | |
| 26 | +const 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 | + */ | |
| 39 | +export 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. */ | |
| 51 | +const 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`. */ | |
| 54 | +export 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 | + */ | |
| 60 | +export 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 | + | |
| 107 | +function 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 | + | |
| 112 | +if (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 | +} |