iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / scripts / cloud-rehearsal / rules.tsmain at aacbc74

// rules.ts — what a fake Cloudflare is made of: THE WORLD a rehearsal holds (world.json in the
// run's folder) and THE RULES that answer a call from it. README.md says how the pieces fit.
//
// A world holds no durations that a rule has to add up at each call. When something starts a
// wait (a consent, a purchase, a deploy), the rule that takes it writes the instant the wait ends
// into the world. Every later answer is then a comparison of that instant with the clock.
//
// The world is a schema, and world.json is parsed with it at every read (fake-cloudflare.ts). Each
// part is a loose object: a run's own rule may keep state of its own beside the fields below, and a
// read keeps it.
import { z } from "zod";

const Card = z.looseObject({ brand: z.string(), last4: z.string(), addedAt: z.string() });
export type Card = z.infer<typeof Card>;

export const Account = z.looseObject({
  name: z.string(),
  createdOn: z.string(),
  billing: z.looseObject({
    /** The instant from which Cloudflare's billing page takes a card. null: not known yet, the
     *  consent sets it. */
    opensAt: z.string().nullable(),
    /** How long after the consent the billing page opens, for an account made minutes ago. */
    opensSecondsAfterConsent: z.number(),
    card: Card.nullable(),
  }),
  /** `showsAt`: the instant from which the API says that the plan is on. */
  workersPaid: z.looseObject({ boughtAt: z.string().nullable(), showsAt: z.string().nullable() }),
  r2: z.looseObject({ enabledAt: z.string().nullable() }),
  /** Whether Cloudflare holds a registrant contact, so that the API can buy a domain. */
  hasRegistrant: z.boolean(),
  workersSubdomain: z.string().nullable(),
});
export type Account = z.infer<typeof Account>;

export const World = z.looseObject({
  id: z.string(),
  /** What this rehearsal tests, in the words of whoever asked for it. */
  scenario: z.string(),
  startedAt: z.string(),
  person: z.looseObject({ email: z.string(), firstName: z.string(), lastName: z.string() }),
  consent: z.looseObject({
    status: z.enum(["none", "approved", "refused"]),
    at: z.string().nullable(),
    /** Whether Cloudflare refuses a consent without "Account API Tokens Write". */
    needsTokensTick: z.boolean(),
  }),
  accounts: z.record(z.string(), Account),
  registrar: z.looseObject({
    taken: z.array(z.string()),
    /** A name whose first label has at most this many letters is taken. */
    takenUpToLetters: z.number(),
    /** US dollars a year by top-level domain; "*" is every other one. */
    prices: z.record(z.string(), z.number()),
  }),
  domains: z.record(
    z.string(),
    z.looseObject({
      account: z.string(),
      boughtAt: z.string(),
      registeredAt: z.string(),
      zoneActiveAt: z.string(),
    }),
  ),
  deploys: z.record(
    z.string(),
    z.looseObject({
      kind: z.enum(["first", "attach"]),
      account: z.string(),
      domain: z.string().nullable(),
      startedAt: z.string(),
      endsAt: z.string(),
    }),
  ),
  /** How long each wait takes in this rehearsal, in seconds. A rule turns one into an instant. */
  waits: z.looseObject({
    /** After `POST /accounts` made an account, until its billing page takes a card. */
    newAccountBillingOpens: z.number(),
    workersPaidShows: z.number(),
    domainRegisters: z.number(),
    zoneActive: z.number(),
    firstDeploy: z.number(),
    attachDeploy: z.number(),
  }),
  /** Anything the fake's author wants to remember about this run. */
  notes: z.array(z.string()),
});
export type World = z.infer<typeof World>;

export type Answer = {
  status: number;
  json?: unknown;
  html?: string;
  text?: string;
  /** A path of the fake to send the browser to, after a form. */
  redirect?: string;
};

export type Call = {
  method: string;
  path: string;
  /** What the route's `:name` and `*name` parts matched. */
  params: Record<string, string>;
  query: URLSearchParams;
  /** A JSON body or a form's fields. */
  // `any`: a caller's body is any JSON; each rule reads the fields it knows
  body: Record<string, any>;
  /** The world, for the rule to read and to change. The server keeps what the rule changed. */
  world: World;
  /** The clock, in ms since the epoch. */
  now: number;
  /** The fake's own address, for links: https://fake-cf-123.example.com */
  base: string;
  /** Cloudflare's envelope around a result. */
  ok: (result: unknown, more?: Record<string, unknown>) => Answer;
  /** Cloudflare's envelope around one error. */
  fail: (status: number, code: number, message: string) => Answer;
  /** A page of the fake dashboard. */
  page: (title: string, bodyHtml: string) => Answer;
  /** Whether `instant` has come. A null instant has not. */
  reached: (instant: string | null) => boolean;
  /** The instant `seconds` from now. */
  instantIn: (seconds: number) => string;
};

/** One rule: a route such as "GET /client/v4/accounts/:account/r2/buckets" (the method may be
 *  ANY, and a last part "*rest" takes what is left), and what it answers. An answer of
 *  `undefined` passes the call on to the next rule. */
export type Rule = { route: string; answer: (call: Call) => Answer | undefined };

/** What `route` matched in `method path`, or null. */
export function matchRoute(route: string, method: string, path: string) {
  const [routeMethod = "", routePath = ""] = route.split(" ");
  if (routeMethod !== "ANY" && routeMethod !== method) return null;
  const want = routePath.split("/").filter(Boolean);
  const have = path.split("/").filter(Boolean);
  const params: Record<string, string> = {};
  for (const [index, part] of want.entries()) {
    if (part.startsWith("*")) {
      params[part.slice(1)] = have.slice(index).join("/");
      return params;
    }
    const segment = have[index];
    if (!segment) return null;
    if (part.startsWith(":")) params[part.slice(1)] = decodeURIComponent(segment);
    else if (part !== segment) return null;
  }
  return want.length === have.length ? params : null;
}

export const escapeHtml = (text: string) =>
  text.replace(
    /[&<>"]/g,
    (character) =>
      ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[character] || character,
  );

/** The helpers every call carries, so that a run's own rules.mjs needs no import. */
export function helpersAt(now: number) {
  return {
    ok: (result: unknown, more: Record<string, unknown> = {}): Answer => ({
      status: 200,
      json: { success: true, errors: [], messages: [], result, ...more },
    }),
    fail: (status: number, code: number, message: string): Answer => ({
      status,
      json: { success: false, errors: [{ code, message }], messages: [], result: null },
    }),
    page: (title: string, bodyHtml: string): Answer => ({
      status: 200,
      html: `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)} · Fake Cloudflare</title>
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:40rem;margin:3rem auto;padding:0 1rem;color:#222}button{font:inherit;padding:.6rem 1rem;border-radius:.4rem;border:1px solid #888;background:#f6821f22;cursor:pointer}.note{color:#666}.bar{background:#fff3cd;padding:.4rem .7rem;border-radius:.4rem}pre{background:#f4f4f4;padding:.7rem;overflow:auto;font-size:13px}</style>
<p class="bar">Fake Cloudflare, for a rehearsal. Not Cloudflare: no card, no money, nothing real.</p><h1>${escapeHtml(title)}</h1>${bodyHtml}`,
    }),
    reached: (instant: string | null) => (instant ? Date.parse(instant) <= now : false),
    instantIn: (seconds: number) => new Date(now + seconds * 1000).toISOString(),
  };
}

/** The old account's id, which a new world names twice: on the account and on its domain. */
const OLD_ACCOUNT = "a11d0000000000000000000000000001";

/** The world a rehearsal starts from unless its scenario says otherwise: one person with an old
 *  account that has a card and Workers Paid, and a fresh account, "iterate", that has nothing and
 *  takes no card for its first two minutes. */
export function startingWorld(input: {
  id: string;
  scenario: string;
  now: number;
  person: World["person"];
}): World {
  const startedAt = new Date(input.now).toISOString();
  const longAgo = "2019-03-04T10:00:00.000Z";
  const oldBlog = `${input.person.firstName.toLowerCase()}-old-blog.com`;
  return {
    id: input.id,
    scenario: input.scenario,
    startedAt,
    person: input.person,
    consent: { status: "none", at: null, needsTokensTick: true },
    accounts: {
      [OLD_ACCOUNT]: {
        name: `${input.person.firstName}'s Account`,
        createdOn: longAgo,
        billing: {
          opensAt: longAgo,
          opensSecondsAfterConsent: 0,
          card: { brand: "visa", last4: "4242", addedAt: longAgo },
        },
        workersPaid: { boughtAt: longAgo, showsAt: longAgo },
        r2: { enabledAt: null },
        hasRegistrant: true,
        workersSubdomain: "old-account",
      },
      f4e50000000000000000000000000002: {
        name: "iterate",
        createdOn: startedAt,
        billing: { opensAt: null, opensSecondsAfterConsent: 120, card: null },
        workersPaid: { boughtAt: null, showsAt: null },
        r2: { enabledAt: null },
        hasRegistrant: false,
        workersSubdomain: null,
      },
    },
    registrar: {
      taken: ["iterate.com", "google.com", "cloudflare.com", "example.com"],
      takenUpToLetters: 5,
      prices: { com: 10.44, dev: 12.18, app: 14.18, net: 11.84, "*": 9.99 },
    },
    domains: {
      [oldBlog]: {
        account: OLD_ACCOUNT,
        boughtAt: longAgo,
        registeredAt: longAgo,
        zoneActiveAt: longAgo,
      },
    },
    deploys: {},
    waits: {
      newAccountBillingOpens: 120,
      workersPaidShows: 70,
      domainRegisters: 25,
      zoneActive: 45,
      firstDeploy: 150,
      attachDeploy: 20,
    },
    notes: [],
  };
}