cloud / scripts / cloud-rehearsal / RULES.mdmain at aacbc74
# Writing a rule for the fake Cloudflare
`rules.mjs` in a rehearsal's folder is that run's own rules. The server reads the file again at
each call and tries its rules first, then the shared ones (`reference/base-rules.ts`). So a rule
here can answer a new call, or take over a call that a shared rule answers.
```js
// rules.mjs
export const rules = [
{
// METHOD (or ANY) and a path. `:name` takes one part, a last `*name` takes what is left.
route: "GET /client/v4/accounts/:account/pages/projects",
// The answer, from the world at this instant. `undefined` passes the call on to the next rule.
answer: (call) => {
const account = call.world.accounts[call.params.account];
if (!account) return undefined;
return call.ok(account.pagesProjects || []);
},
},
];
```
The file has no imports: everything a rule needs is on `call`.
| On `call` | What it is |
| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `method`, `path`, `params`, `query` | The call. `query` is a `URLSearchParams`. |
| `body` | A JSON body, or a form's fields. `{}` when there is none. |
| `world` | The contents of `world.json`. Change it in place: the server keeps what a rule changed. |
| `now` | The clock, in ms since the epoch. |
| `base` | The fake's own address, for a link in a page or a redirect's target. |
| `ok(result, more)` | Cloudflare's envelope: `{ success: true, errors: [], messages: [], result }`. `more` adds fields beside `result`, such as `result_info`. |
| `fail(status, code, message)` | Cloudflare's envelope around one error. |
| `page(title, bodyHtml)` | A page of the fake dashboard. |
| `reached(instant)` | Whether an ISO instant has come. `null` has not. |
| `instantIn(seconds)` | The ISO instant so many seconds from now. |
An answer is `{ status, json }`, `{ status, html }`, `{ status, text }`, or `{ status: 303, redirect: "/a/path" }`
after a form. `call.ok`, `call.fail` and `call.page` make the first two.
## Waits are instants
A rule never adds a duration up at each call. When something starts a wait, the rule that takes it
writes the instant the wait ends into the world, and every later answer compares that instant with
the clock:
```js
{
// a page's button: the purchase is made now, and the API shows it later
route: "POST /:account/workers/plans",
answer: (call) => {
const account = call.world.accounts[call.params.account];
account.workersPaid = { boughtAt: call.instantIn(0), showsAt: call.instantIn(call.world.waits.workersPaidShows) };
return { status: 303, redirect: `/${call.params.account}/workers/plans` };
},
},
{
route: "GET /client/v4/accounts/:account/subscriptions",
answer: (call) => {
const account = call.world.accounts[call.params.account];
return call.ok(call.reached(account.workersPaid.showsAt) ? [{ rate_plan: { id: "workers_paid" } }] : []);
},
},
```
## What the world holds
`reference/rules.ts` has the schema (`World`) with a comment on each field, and `startingWorld`, the
default start. The server parses world.json with that schema at each call: keep every field that
it names, with its type, or each call gets a 500 until the file is a world again. A new fact goes
where a reader would look for it: on the account it is about, or as a new top-level field with a
plain name; the schema lets such a field through. Durations that a scenario sets are under
`waits`, in seconds.
## A page
```js
{
route: "ANY /:account/domains/transfer",
answer: (call) => {
if (call.method === "POST") {
call.world.notes.push(`${call.body.domain} was asked to transfer at ${call.instantIn(0)}`);
return { status: 303, redirect: `/${call.params.account}/domains/transfer?said=1` };
}
return call.page("Transfer a domain", `<form method="post"><p><input name="domain"> <button>Transfer</button></p></form>`);
},
},
```
A page of the real dashboard asks for cards and passwords. A page here never does: it has a button.
## The deploy
iterate Cloud's agent deploys in two steps. In a rehearsal each is `POST /deploy` with plain JSON, not Cloudflare's envelope:
- `{ account }` is the first deploy, before the domain. It runs on a Free account: it asks for no card, no Workers Paid and no R2.
- `{ account, domain }` is the deploy that attaches the domain. The shared rule refuses it, as the real one fails, while the first deploy still runs, while the account is not on Workers Paid or has no R2, and while the domain is not an active zone of the account.
Both answer `{ job, kind, status }`, and `GET /deploy/<job>` says how it goes. A rule of the run that takes over `POST /deploy` keeps these two shapes.
## The sandbox
iterate Cloud's agent also runs shell commands, in a Linux box of the install. In a rehearsal each
one is `POST /sandbox` with `{ command, timeoutSeconds, background }`, and the answer is plain
JSON, not Cloudflare's envelope:
- a command that ran: `{ status: 200, json: { exitCode, stdout, stderr } }`, with what a real
shell would print;
- with `background: true`: `{ status: 200, json: { job, endsInSeconds, exitCode } }`, where `job` is
a short id of letters and digits. The agent is told when it ends.
One rule matches every command, so a rule for a command tests `call.body.command` and answers
`undefined` for any other:
```js
{
route: "POST /sandbox",
answer: (call) => {
if (!/^\s*node --version/.test(call.body.command)) return undefined;
return { status: 200, json: { exitCode: 0, stdout: "v24.11.0\n", stderr: "" } };
},
},
```
The box has iterate's source at `/root/core`, Node, pnpm, git and curl. A deploy's log is
`/root/cloud/job-<job>.log`, and the shared rules answer `tail` of it.