Skip to content
Myr

bootstrap.ts

This file

Path

infra/bootstrap.ts

655 lines · 18.6 KiB · TypeScript

Last changed by

Merge observability into mainoscabrielbefore adoption1985111

History of this file

Take it

1// Usage: bun run bootstrap -- --stage <stage> [--dry-run | --check-triggers]2// Idempotent: creates only what is missing, and never deletes. Either run3// ends by printing the stage's alerts, which a person makes by hand.4import { BunRuntime, BunServices } from "@effect/platform-bun";5import {6  Config,7  Console,8  Data,9  Effect,10  FileSystem,11  Option,12  Path,13  Result,14  Schema,15  Stdio,16  Stream,17} from "effect";18import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";19import { ChildProcess, ChildProcessSpawner } from "effect/process";2021import { alertLines, alerts } from "./alerts.ts";22import { schemaItems } from "./env-schema.ts";23import type { SchemaItem } from "./env-schema.ts";24import { blankJsonc, pathKey, valueSpans } from "./jsonc.ts";25import type { JsonPath, Span } from "./jsonc.ts";26import {27  repoRoot,28  resources,29  stageOf,30  subdomainFile,31  WorkersDev,32} from "./stages.ts";33import type { Stage } from "./stages.ts";3435export interface Existing {36  readonly namespaces: readonly string[];37  readonly d1: readonly { readonly name: string; readonly id: string }[];38  readonly kv: readonly { readonly title: string; readonly id: string }[];39  readonly r2: readonly string[];40}4142export type Step = Data.TaggedEnum<{43  CreateNamespace: { readonly name: string };44  CreateD1: { readonly name: string };45  CreateKv: { readonly title: string };46  CreateR2: { readonly name: string };47}>;4849export const Step = Data.taggedEnum<Step>();5051export const plan = (stage: Stage, existing: Existing): readonly Step[] => {52  const names = resources(stage);5354  return [55    ...[names.projects, names.layers].flatMap((name) =>56      existing.namespaces.includes(name) ? [] : [Step.CreateNamespace({ name })]57    ),58    ...(existing.d1.some(({ name }) => name === names.frontPage)59      ? []60      : [Step.CreateD1({ name: names.frontPage })]),61    ...(existing.kv.some(({ title }) => title === names.oauth)62      ? []63      : [Step.CreateKv({ title: names.oauth })]),64    ...[names.evidence, names.releases, names.codeCache].flatMap((name) =>65      existing.r2.includes(name) ? [] : [Step.CreateR2({ name })]66    ),67  ];68};6970export interface Ids {71  readonly frontPage?: string | undefined;72  readonly oauth?: string | undefined;73}7475const spanOf = (76  json: string,77  spans: ReadonlyMap<string, Span>,78  place: {79    readonly stage: Stage;80    readonly list: string;81    readonly binding: string;82    readonly key: string;83  }84): Option.Option<Span> => {85  const base: JsonPath = ["env", place.stage, place.list];86  const at = (path: JsonPath) => Option.fromNullishOr(spans.get(pathKey(path)));8788  for (let index = 0; Option.isSome(at([...base, index])); index += 1) {89    const named = Option.exists(90      at([...base, index, "binding"]),91      ({ end, start }) =>92        json.slice(start, end) === JSON.stringify(place.binding)93    );9495    if (named) {96      return at([...base, index, place.key]);97    }98  }99100  return Option.none();101};102103// Only those two values change: every comment, comma and line stays.104export const writeIds = (text: string, stage: Stage, ids: Ids): string => {105  const json = blankJsonc(text);106  const spans = valueSpans(json);107108  const edits = [109    {110      binding: "FRONT_PAGE",111      id: ids.frontPage,112      key: "database_id",113      list: "d1_databases",114    },115    { binding: "OAUTH_KV", id: ids.oauth, key: "id", list: "kv_namespaces" },116  ].flatMap(({ id, ...place }) =>117    id === undefined118      ? []119      : Option.toArray(120          Option.map(spanOf(json, spans, { ...place, stage }), (span) => ({121            span,122            value: JSON.stringify(id),123          }))124        )125  );126127  let written = text;128129  // From the last edit back, so each span still points where it did.130  for (const { span, value } of edits.toSorted(131    (a, b) => b.span.start - a.span.start132  )) {133    written = `${written.slice(0, span.start)}${value}${written.slice(span.end)}`;134  }135136  return written;137};138139const Target = Schema.Struct({140  script_name: Schema.String,141  type: Schema.String,142  workflow_name: Schema.optionalKey(Schema.String),143});144145const Trigger = Schema.Struct({146  filter: Schema.Struct({ namespace: Schema.optionalKey(Schema.String) }),147  targets: Schema.Array(Target),148  type: Schema.String,149});150151export const TriggersResponse = Schema.Struct({152  result: Schema.Struct({153    script_name: Schema.String,154    triggers: Schema.Array(Trigger),155  }),156  success: Schema.Boolean,157});158159const PUSHED = "cf.artifacts.repo.pushed";160161export class TriggerMismatch extends Schema.TaggedError<TriggerMismatch>()(162  "TriggerMismatch",163  {164    found: Schema.Array(Schema.String),165    namespace: Schema.String,166    script: Schema.String,167    workflow: Schema.String,168  }169) {170  override get message() {171    const found = this.found.length === 0 ? "none" : this.found.join("; ");172173    return `${this.script} has no ${PUSHED} trigger on ${this.namespace} starting ${this.workflow}; it has: ${found}`;174  }175}176177const held: Result.Result<void> = Result.flip(Result.failVoid);178179export const checkTriggers = (180  stage: Stage,181  live: typeof TriggersResponse.Type182): Result.Result<void, TriggerMismatch> => {183  const names = resources(stage);184  const { script_name: script, triggers } = live.result;185186  const holds =187    live.success &&188    script === names.platform &&189    triggers.some(190      ({ filter, targets, type }) =>191        type === PUSHED &&192        filter.namespace === names.projects &&193        targets.some(194          (target) =>195            target.type === "workflow" &&196            target.script_name === names.platform &&197            target.workflow_name === names.onPush198        )199    );200201  return holds202    ? held203    : Result.fail(204        new TriggerMismatch({205          found: triggers.flatMap(({ filter, targets, type }) =>206            targets.map(207              (target) =>208                `${type} on ${filter.namespace ?? "*"} → ${target.script_name}/${target.workflow_name ?? target.type}`209            )210          ),211          namespace: names.projects,212          script: names.platform,213          workflow: names.onPush,214        })215      );216};217218const jsonIn = (stdout: string) => {219  const start = stdout.search(/^[[{]/mu);220221  return start === -1 ? stdout : stdout.slice(start);222};223224const decodeD1 = Schema.decodeEffect(225  Schema.fromJsonString(226    Schema.Array(Schema.Struct({ name: Schema.String, uuid: Schema.String }))227  )228);229230const decodeKv = Schema.decodeEffect(231  Schema.fromJsonString(232    Schema.Array(Schema.Struct({ id: Schema.String, title: Schema.String }))233  )234);235236const decodeSecrets = Schema.decodeEffect(237  Schema.fromJsonString(Schema.Array(Schema.Struct({ name: Schema.String })))238);239240export const d1From = (stdout: string) =>241  decodeD1(jsonIn(stdout)).pipe(242    Effect.map((databases) =>243      databases.map(({ name, uuid }) => ({ id: uuid, name }))244    )245  );246247export const kvFrom = (stdout: string) =>248  decodeKv(jsonIn(stdout)).pipe(249    Effect.map((namespaces) =>250      namespaces.map(({ id, title }) => ({ id, title }))251    )252  );253254export const bucketsFrom = (stdout: string): readonly string[] =>255  stdout256    .split("\n")257    .flatMap((line) =>258      Option.toArray(259        Option.fromNullishOr(260          /^name:\s+(?<name>\S+)\s*$/u.exec(line)?.groups?.name261        )262      )263    );264265export const secretNames = (stdout: string) =>266  decodeSecrets(jsonIn(stdout)).pipe(267    Effect.map((secrets) => secrets.map(({ name }) => name))268  );269270export const missingSecrets = (271  items: readonly SchemaItem[],272  listed: readonly string[]273): readonly string[] =>274  items.flatMap(({ name, required }) =>275    required && !listed.includes(name) ? [name] : []276  );277278export class CloudflareRefused extends Schema.TaggedError<CloudflareRefused>()(279  "CloudflareRefused",280  { route: Schema.String, status: Schema.Int }281) {282  override get message() {283    return `the Cloudflare API answered ${this.route} with ${this.status}`;284  }285}286287export class WranglerFailed extends Schema.TaggedError<WranglerFailed>()(288  "WranglerFailed",289  { command: Schema.String, exitCode: Schema.Int }290) {291  override get message() {292    return `${this.command} exited ${this.exitCode}`;293  }294}295296export class MissingSecrets extends Schema.TaggedError<MissingSecrets>()(297  "MissingSecrets",298  { names: Schema.Array(Schema.String), stage: Schema.String }299) {300  override get message() {301    return `${this.stage}'s platform lacks ${this.names.join(", ")}: set them by name, from the stage's secrets file (STAGE_SECRETS_FILE)`;302  }303}304305const API = "https://api.cloudflare.com/client/v4";306307const Credentials = Config.all({308  accountId: Config.String("CLOUDFLARE_ACCOUNT_ID"),309  token: Config.Redacted("CLOUDFLARE_API_TOKEN"),310});311312type Credentials =313  typeof Credentials extends Config.Config<infer A> ? A : never;314315const call = (316  credentials: Credentials,317  route: string,318  body?: Readonly<Record<string, string>>319) =>320  Effect.gen(function* () {321    const client = yield* HttpClient.HttpClient;322    const url = `${API}/accounts/${credentials.accountId}${route}`;323324    const request = (325      body === undefined326        ? HttpClientRequest.get(url)327        : HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(url), body)328    ).pipe(HttpClientRequest.bearerToken(credentials.token));329330    const response = yield* client.execute(request);331332    return { status: response.status, text: yield* response.text };333  });334335const ok = (credentials: Credentials, route: string) =>336  call(credentials, route).pipe(337    Effect.flatMap(({ status, text }) =>338      status === 200339        ? Effect.succeed(text)340        : Effect.fail(new CloudflareRefused({ route, status }))341    )342  );343344const decodeTriggers = Schema.decodeEffect(345  Schema.fromJsonString(TriggersResponse)346);347348const decodeSubdomain = Schema.decodeEffect(349  Schema.fromJsonString(Schema.Struct({ result: WorkersDev }))350);351352const exists = (credentials: Credentials, route: string) =>353  call(credentials, route).pipe(354    Effect.flatMap(({ status }) =>355      status === 200 || status === 404356        ? Effect.succeed(status === 200)357        : Effect.fail(new CloudflareRefused({ route, status }))358    )359  );360361const wrangler = (root: string, args: readonly string[]) =>362  Effect.gen(function* () {363    const path = yield* Path.Path;364    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;365    const app = path.join(root, "apps/platform");366367    const handle = yield* spawner.spawn(368      ChildProcess.make(path.join(app, "node_modules/.bin/wrangler"), args, {369        cwd: app,370        // Writes outside Artifacts go through `wrangler login`, never the371        // read-mostly infra token.372        env: {373          CLOUDFLARE_API_TOKEN: undefined,374          WRANGLER_SEND_METRICS: "false",375        },376        extendEnv: true,377        stderr: "inherit",378      })379    );380381    const [stdout, exitCode] = yield* Effect.all(382      [Stream.mkString(Stream.decodeText(handle.stdout)), handle.exitCode],383      { concurrency: "unbounded" }384    );385386    return exitCode === 0387      ? stdout388      : yield* new WranglerFailed({389          command: `wrangler ${args.join(" ")}`,390          exitCode,391        });392  }).pipe(Effect.scoped, Effect.catchTag("PlatformError", Effect.die));393394const readExisting = (root: string, credentials: Credentials, stage: Stage) =>395  Effect.gen(function* () {396    const { layers, projects } = resources(stage);397398    const namespaces = yield* Effect.filter([projects, layers], (name) =>399      exists(credentials, `/artifacts/namespaces/${name}`)400    );401402    return {403      d1: yield* wrangler(root, ["d1", "list", "--json"]).pipe(404        Effect.flatMap(d1From)405      ),406      kv: yield* wrangler(root, ["kv", "namespace", "list"]).pipe(407        Effect.flatMap(kvFrom)408      ),409      namespaces,410      r2: bucketsFrom(yield* wrangler(root, ["r2", "bucket", "list"])),411    } satisfies Existing;412  });413414const describe = (step: Step) =>415  Step.$match(step, {416    CreateD1: ({ name }) => `create D1 ${name}`,417    CreateKv: ({ title }) => `create KV ${title}`,418    CreateNamespace: ({ name }) => `create Artifacts namespace ${name}`,419    CreateR2: ({ name }) => `create R2 ${name}`,420  });421422export const planLines = (423  stage: Stage,424  steps: readonly Step[]425): readonly string[] => [426  ...steps.map((step) => `bootstrap ${stage} (dry run): ${describe(step)}`),427  `bootstrap ${stage} (dry run): would create ${steps.length}; nothing was changed`,428];429430// Bootstrap writes the stage's block itself, not Wrangler's top-level binding.431const NO_CONFIG_EDIT = "--update-config=false";432433const create = (root: string, credentials: Credentials, step: Step) =>434  Step.$match(step, {435    CreateD1: ({ name }) =>436      wrangler(root, ["d1", "create", name, NO_CONFIG_EDIT]),437    CreateKv: ({ title }) =>438      wrangler(root, ["kv", "namespace", "create", title, NO_CONFIG_EDIT]),439    CreateNamespace: ({ name }) => {440      const route = "/artifacts/namespaces";441442      // `unrestricted` is cf's default jurisdiction, and the probes'.443      return call(credentials, route, {444        jurisdiction: "unrestricted",445        namespace: name,446      }).pipe(447        Effect.flatMap(({ status }) =>448          status === 200 || status === 201449            ? Effect.void450            : Effect.fail(new CloudflareRefused({ route, status }))451        )452      );453    },454    CreateR2: ({ name }) =>455      wrangler(root, ["r2", "bucket", "create", name, NO_CONFIG_EDIT]),456  }).pipe(Effect.asVoid);457458const rewrite = (root: string, file: string, edit: (text: string) => string) =>459  Effect.gen(function* () {460    const fs = yield* FileSystem.FileSystem;461    const path = yield* Path.Path;462    const at = path.join(root, file);463464    const text = yield* fs465      .exists(at)466      .pipe(467        Effect.flatMap((present) =>468          present ? fs.readFileString(at) : Effect.succeed("")469        )470      );471472    const written = edit(text);473474    if (written !== text) {475      yield* fs.writeFileString(at, written);476      yield* Console.log(`bootstrap: wrote ${file}`);477    }478  }).pipe(Effect.orDie);479480const triggers = (credentials: Credentials, stage: Stage) =>481  Effect.gen(function* () {482    const { platform, projects } = resources(stage);483484    const live = yield* ok(credentials, `/triggers/${platform}`).pipe(485      Effect.flatMap(decodeTriggers)486    );487488    const verdict = checkTriggers(stage, live);489490    return yield* Result.isFailure(verdict)491      ? Effect.fail(verdict.failure)492      : Console.log(493          `bootstrap ${stage}: ${platform} hears pushes to ${projects}.`494        );495  });496497const secrets = (root: string, credentials: Credentials, stage: Stage) =>498  Effect.gen(function* () {499    const fs = yield* FileSystem.FileSystem;500    const path = yield* Path.Path;501    const { platform } = resources(stage);502503    const items = schemaItems(504      yield* fs505        .readFileString(path.join(root, "apps/platform/.env.schema"))506        .pipe(Effect.orDie)507    );508509    const required = items.flatMap(({ name, required: needed }) =>510      needed ? [name] : []511    );512513    // A script's settings answer 404 until its first deploy.514    const deployed = yield* exists(515      credentials,516      `/workers/scripts/${platform}/settings`517    );518519    const listed = deployed520      ? yield* wrangler(root, [521          "secret",522          "list",523          "--env",524          stage,525          "--format",526          "json",527        ]).pipe(Effect.flatMap(secretNames))528      : [];529530    const missing = missingSecrets(items, listed);531532    if (!deployed) {533      return yield* Console.log(534        `bootstrap ${stage}: ${platform} is not deployed yet, so its first deploy must carry ${required.join(", ")} through varlock, from the stage's secrets file (STAGE_SECRETS_FILE).`535      );536    }537538    return yield* missing.length === 0539      ? Console.log(540          `bootstrap ${stage}: ${platform} holds every required secret.`541        )542      : Effect.fail(new MissingSecrets({ names: missing, stage }));543  });544545// Where the alerts are sent, by name: `alertLines` never shows the address.546const Destination = Config.option(Config.String("ALERT_EMAIL"));547548const alertPlan = (credentials: Credentials, stage: Stage) =>549  Effect.gen(function* () {550    const destination = yield* Destination.pipe(Effect.orDie);551552    yield* Console.log(553      alertLines(554        stage,555        alerts(stage, credentials.accountId),556        Option.isSome(destination)557      ).join("\n")558    );559  });560561const dryRun = (root: string, credentials: Credentials, stage: Stage) =>562  Effect.gen(function* () {563    const steps = plan(stage, yield* readExisting(root, credentials, stage));564565    yield* Console.log(planLines(stage, steps).join("\n"));566    yield* alertPlan(credentials, stage);567  });568569const make = (root: string, credentials: Credentials, stage: Stage) =>570  Effect.gen(function* () {571    const fs = yield* FileSystem.FileSystem;572    const path = yield* Path.Path;573    const names = resources(stage);574    const before = yield* readExisting(root, credentials, stage);575    const steps = plan(stage, before);576577    yield* Effect.forEach(578      steps,579      (step) =>580        Console.log(`bootstrap ${stage}: ${describe(step)}`).pipe(581          Effect.andThen(create(root, credentials, step))582        ),583      { discard: true }584    );585586    const after =587      steps.length === 0588        ? before589        : yield* readExisting(root, credentials, stage);590591    yield* rewrite(root, "apps/platform/wrangler.jsonc", (text) =>592      writeIds(text, stage, {593        frontPage: after.d1.find(({ name }) => name === names.frontPage)?.id,594        oauth: after.kv.find(({ title }) => title === names.oauth)?.id,595      })596    );597598    const migrations = yield* fs599      .exists(path.join(root, "apps/platform/migrations"))600      .pipe(Effect.orDie);601602    if (migrations) {603      yield* wrangler(root, [604        "d1",605        "migrations",606        "apply",607        names.frontPage,608        "--remote",609        "--env",610        stage,611      ]);612    }613614    const { result } = yield* ok(credentials, "/workers/subdomain").pipe(615      Effect.flatMap(decodeSubdomain)616    );617618    yield* rewrite(619      root,620      subdomainFile,621      () => `${JSON.stringify(result, null, 2)}\n`622    );623624    yield* secrets(root, credentials, stage);625    yield* alertPlan(credentials, stage);626627    yield* Console.log(628      `bootstrap ${stage}: created ${steps.length}; next: bun run deploy -- --stage ${stage}`629    );630  });631632export const bootstrap = (argv: readonly string[]) =>633  Effect.gen(function* () {634    const stage = yield* stageOf(argv);635    const credentials = yield* Credentials;636    const root = yield* repoRoot;637638    if (argv.includes("--check-triggers")) {639      return yield* triggers(credentials, stage);640    }641642    return yield* argv.includes("--dry-run")643      ? dryRun(root, credentials, stage)644      : make(root, credentials, stage);645  });646647if (import.meta.main) {648  BunRuntime.runMain(649    Effect.gen(function* () {650      const args = yield* (yield* Stdio.Stdio).args;651652      return yield* bootstrap(args);653    }).pipe(Effect.provide([FetchHttpClient.layer, BunServices.layer]))654  );655}