iterate.com / cloud

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

cloud / scripts / cloud-rehearsal / fake-cloudflare.tsmain at aacbc74

// fake-cloudflare.ts — THE FAKE CLOUDFLARE'S SERVER, for one rehearsal of iterate's sign-up chat.
// It is a thin thing on purpose. It knows nothing about Cloudflare: the run's folder does.
//
//   world.json   the state, with every wait as the instant it ends (rules.ts)
//   rules.mjs    this run's own rules, tried first; then the shared ones (base-rules.ts)
//   run.jsonl    every call, its answer and who gave it; and the world whenever it changed
//
// EVERY CALL STARTS WITH THE RUN'S SECRET, as the first segment of its path: /<secret>/client/v4/…
// The tunnel is public, so a call without it gets a bare 404, before any rule or agent sees it.
// The secret is cut off, and what follows is the call.
//
// A CALL IS ANSWERED IN THIS ORDER:
//   1. the first rule that has an answer;
//   2. Cloudflare's own 404 (code 7003) when the call is under /client/v4 and is no route of
//      Cloudflare's API: nobody invents an answer for a call that the real API refuses;
//   3. a bare 404 when the call is none of: a route of Cloudflare's API, a page under an account
//      (/<account id>/…, as the dashboard's are), or a path that some rule names. Nobody else's
//      call spends an agent's run;
//   4. THE AGENT. Nobody has a rule for this call, so `askAgent` is asked to write one into
//      rules.mjs (and to change world.json if it must). The caller waits up to `missWaitMs`. If
//      the rule is there by then, it answers. If not, the caller gets Cloudflare's "unknown error"
//      (code 10013, a 503), as from a control plane that is busy, and the next call finds the rule.
//      One agent works at a time, and a call that is being worked on (the same method, path and
//      body) is not asked about twice.
//
// Both files are read again at each call, so the agent, or a person, changes a running rehearsal
// by saving a file.
import { appendFileSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { join } from "node:path";
import { z } from "zod";
import { baseRules } from "./base-rules.ts";
import { helpersAt, matchRoute, World, type Answer, type Rule } from "./rules.ts";

/** A call nobody has a rule for, as the agent is told it. */
export type Miss = {
  method: string;
  path: string;
  query: string;
  body: unknown;
  runDir: string;
  /** What Cloudflare's API spec says about the route; empty for a page of the dashboard. */
  aboutTheRoute: string;
};

const UNKNOWN_ERROR: Answer = {
  status: 503,
  json: {
    success: false,
    errors: [
      {
        code: 10013,
        message:
          "An unknown error has occurred. If this error persists, please file a report in workers-sdk (https://github.com/cloudflare/workers-sdk/issues) or reach out to your account team.",
      },
    ],
    messages: [],
    result: null,
  },
};
/** What a browser asks for by itself: never worth a question to the agent. */
const BROWSER_NOISE = /^\/(favicon\.ico|robots\.txt|apple-touch-icon.*|\.well-known\/.*)$/;
/** A page of the dashboard: under an account's id, as dash.cloudflare.com/<account>/… is. */
const ACCOUNT_PAGE = /^\/[0-9a-f]{32}(\/[\w.~-]+)*\/?$/;
const NOT_FOUND: Answer = { status: 404, text: "Not found\n" };

export async function startFakeCloudflare(options: {
  runDir: string;
  /** 0: any free port. */
  port: number;
  /** The first path segment of every call; anything else is a 404 (start.ts makes it). */
  secret: string;
  /** The address people and agents reach the fake at, for the links in its pages. */
  publicUrl: (port: number) => string;
  now: () => number;
  /** Whether `method path` (the path without /client/v4) is a route of Cloudflare's API. */
  isCloudflareRoute: (method: string, path: string) => boolean;
  describeCloudflareRoute: (method: string, path: string) => string;
  askAgent: (miss: Miss) => Promise<void>;
  missWaitMs: number;
  /** How many calls of one run the agent is asked about, at most. */
  maxAgentRuns: number;
}) {
  const worldFile = join(options.runDir, "world.json");
  const rulesFile = join(options.runDir, "rules.mjs");
  const recordFile = join(options.runDir, "run.jsonl");
  const record = (line: Record<string, unknown>) =>
    appendFileSync(
      recordFile,
      `${JSON.stringify({ at: new Date(options.now()).toISOString(), ...line })}\n`,
    );

  let base = "";
  let runRules: Rule[] = [];
  let rulesText: string | undefined;
  /** This run's rules as rules.mjs has them now. A file that does not load keeps the rules from
   *  before, and the record says why. rules.mjs has no imports (a call carries its helpers), so
   *  it is read as text and evaluated: a module import would be cached at its first load. The
   *  text is compared, not the file's time: two writes within one step of the file system's
   *  clock have one time, and the second one's rule would never load. */
  function loadRunRules() {
    const text = readFileSync(rulesFile, "utf8");
    if (text === rulesText) return;
    rulesText = text;
    try {
      const source = text.replace(/^export\s+/gm, "");
      // oxlint-disable-next-line no-new-func -- the run's own rules file, written by the fake's author for this run
      const loaded: unknown = new Function(`${source}\n;return rules;`)();
      if (!Array.isArray(loaded))
        throw new Error("rules.mjs must say `export const rules = [...]`");
      runRules = loaded;
    } catch (error) {
      record({ event: "rules-did-not-load", error: String(error) });
    }
  }

  /** The first rule's answer for a call, with the world it changed kept; null: no rule has one. */
  function answerFromRules(method: string, url: URL, body: Record<string, unknown>) {
    loadRunRules();
    // A world.json that is no world (rules.ts `World`) throws here, as one that is no JSON does:
    // the call gets a 500, and the record says which field is wrong.
    const world = World.parse(JSON.parse(readFileSync(worldFile, "utf8")));
    const before = JSON.stringify(world);
    const now = options.now();
    for (const rule of [...runRules, ...baseRules]) {
      const params = matchRoute(rule.route, method, url.pathname);
      if (!params) continue;
      let answer: Answer | undefined;
      try {
        answer = rule.answer({
          method,
          path: url.pathname,
          params,
          query: url.searchParams,
          body,
          world,
          now,
          base,
          ...helpersAt(now),
        });
      } catch (error) {
        record({ event: "rule-threw", rule: rule.route, error: String(error) });
        return { answer: UNKNOWN_ERROR, by: `rule ${rule.route}, which threw` };
      }
      if (!answer) continue;
      if (JSON.stringify(world) !== before) {
        writeFileSync(`${worldFile}.next`, `${JSON.stringify(world, null, 2)}\n`);
        renameSync(`${worldFile}.next`, worldFile);
        record({ event: "world-changed", by: rule.route, world });
      }
      return { answer, by: `rule ${rule.route}` };
    }
    return null;
  }

  const asking = new Map<string, Promise<void>>();
  let agentQueue = Promise.resolve();
  let agentRuns = 0;
  async function answerOf(
    method: string,
    url: URL,
    body: Record<string, unknown>,
  ): Promise<{ answer: Answer; by: string }> {
    const fromRules = answerFromRules(method, url, body);
    if (fromRules) return fromRules;
    const path = url.pathname;
    const apiPath = path.startsWith("/client/v4/") ? path.slice("/client/v4".length) : null;
    if (apiPath && !options.isCloudflareRoute(method, apiPath))
      return {
        by: "Cloudflare's routes: no such route",
        answer: {
          status: 404,
          json: {
            success: false,
            errors: [
              {
                code: 7003,
                message: `Could not route to ${path}, perhaps your object identifier is invalid?`,
              },
              { code: 7000, message: "No route for that URI" },
            ],
            messages: [],
            result: null,
          },
        },
      };
    if (BROWSER_NOISE.test(path)) return { by: "nobody", answer: NOT_FOUND };
    const known =
      apiPath ||
      ACCOUNT_PAGE.test(path) ||
      [...runRules, ...baseRules].some((rule) => matchRoute(rule.route, method, path));
    if (!known) return { by: "nobody: no route, page or rule has this path", answer: NOT_FOUND };

    // the body is part of the call: two commands to /sandbox are two questions
    const key = `${method} ${path} ${JSON.stringify(body)}`;
    let work = asking.get(key);
    if (!work) {
      if (agentRuns >= options.maxAgentRuns)
        return {
          by: "nobody: the agent has been asked as often as this run allows",
          answer: UNKNOWN_ERROR,
        };
      agentRuns += 1;
      const miss: Miss = {
        method,
        path,
        query: url.search,
        body,
        runDir: options.runDir,
        aboutTheRoute: apiPath ? options.describeCloudflareRoute(method, apiPath) : "",
      };
      record({ event: "agent-asked", method, path });
      work = agentQueue
        .then(() => options.askAgent(miss))
        .catch((error: unknown) =>
          record({ event: "agent-failed", method, path, error: String(error) }),
        );
      agentQueue = work;
      asking.set(key, work);
      void work.finally(() => asking.delete(key));
    }
    const inTime = await within(work, options.missWaitMs);
    const written = inTime ? answerFromRules(method, url, body) : null;
    if (written) return { answer: written.answer, by: "agent" };
    return {
      by: inTime
        ? "nobody: the agent wrote no rule that answers this"
        : "nobody yet: the agent still works on it",
      answer: UNKNOWN_ERROR,
    };
  }

  const server = createServer((request, response) => {
    void handle(request, response).catch((error: unknown) => {
      record({ event: "server-threw", error: String(error) });
      response.writeHead(500, { "content-type": "text/plain" }).end("The fake Cloudflare broke.\n");
    });
  });
  const prefix = `/${options.secret}`;
  async function handle(request: IncomingMessage, response: ServerResponse) {
    const method = request.method || "GET";
    const raw = new URL(request.url || "/", "http://fake-cloudflare");
    if (
      options.secret.length < 16 ||
      (raw.pathname !== prefix && !raw.pathname.startsWith(`${prefix}/`))
    ) {
      request.resume();
      response.writeHead(404, { "content-type": "text/plain" }).end("Not found\n");
      return;
    }
    const url = new URL(raw.pathname.slice(prefix.length) || "/", raw);
    url.search = raw.search;
    const body = await bodyOf(request);
    const { answer, by } = await answerOf(method, url, body);
    const text =
      answer.json !== undefined
        ? JSON.stringify(answer.json, null, 2)
        : answer.html || answer.text || "";
    record({
      method,
      path: url.pathname,
      query: url.search,
      body,
      status: answer.status,
      by,
      answer: answer.html ? "(a page)" : text.slice(0, 2000),
    });
    const type =
      answer.json !== undefined
        ? "application/json"
        : answer.html
          ? "text/html; charset=utf-8"
          : "text/plain; charset=utf-8";
    response.writeHead(answer.status, {
      "content-type": type,
      "cache-control": "no-store",
      ...(answer.redirect && { location: `${base}${answer.redirect}` }),
    });
    response.end(text);
  }

  await new Promise<void>((resolve) => server.listen(options.port, "127.0.0.1", resolve));
  const address = server.address();
  if (!address || typeof address === "string") throw new Error("the fake Cloudflare has no port");
  base = `${options.publicUrl(address.port)}${prefix}`;
  return {
    port: address.port,
    /** Where this process reaches the server, with the secret, whatever its public address is. */
    url: `http://127.0.0.1:${address.port}${prefix}`,
    close: () =>
      new Promise<void>((resolve) => {
        server.close(() => resolve());
        server.closeAllConnections();
      }),
  };
}

const JSONObject = z.record(z.string(), z.unknown());

/** A JSON body or a form's fields; {} for anything else. */
async function bodyOf(request: IncomingMessage): Promise<Record<string, unknown>> {
  const chunks: Buffer[] = [];
  let size = 0;
  for await (const chunk of request) {
    size += chunk.length;
    if (size > 1_000_000) return {};
    chunks.push(chunk);
  }
  const text = Buffer.concat(chunks).toString("utf8");
  if (!text) return {};
  if ((request.headers["content-type"] || "").includes("application/x-www-form-urlencoded"))
    return Object.fromEntries(new URLSearchParams(text));
  try {
    return JSONObject.safeParse(JSON.parse(text)).data || {};
  } catch {
    return {};
  }
}

/** Whether `work` ended within `ms`. */
async function within(work: Promise<void>, ms: number) {
  let timer: NodeJS.Timeout | undefined;
  const late = new Promise<false>((resolve) => {
    timer = setTimeout(() => resolve(false), ms);
  });
  const result = await Promise.race([work.then(() => true as const), late]);
  clearTimeout(timer);
  return result;
}