deploy.ts
This file
Path
infra/deploy.ts
322 lines · 9.2 KiB · TypeScript
Last changed by
Merge observability into mainoscabrielbefore adoption1985111
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323// Usage: bun run deploy -- --stage <stage>// Runs verify, deploys sandbox, platform and web, checks the push trigger, then// smoke, which also reads the stage's logs since the first upload began.// Refused while `infra/.recording` exists, before any flag is read.// `STAGE_SECRETS_FILE` passes only the items `apps/platform/.env.schema`// declares, to the platform step alone; no value is ever printed.import { BunRuntime, BunServices } from "@effect/platform-bun";import { Config, ConfigProvider, Console, DateTime, Effect, FileSystem, Option, Path, Schema, Stdio,} from "effect";import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { schemaItems } from "./env-schema.ts";import { notRecording } from "./recording.ts";import type { RecordingInProgress } from "./recording.ts";import { customHosts, platformOrigin, repoRoot, stageOf, subdomainFile, WorkersDev,} from "./stages.ts";import type { NoStage, Stage, UnknownStage } from "./stages.ts";
export { RecordingInProgress } from "./recording.ts";
export { NoStage, UnknownStage } from "./stages.ts";
export class StepFailed extends Schema.TaggedError<StepFailed>()("StepFailed", { exitCode: Schema.Int, step: Schema.String,}) { override get message() { return `${this.step} exited ${this.exitCode}, so nothing after it ran`; }}
export class SecretsFileUnreadable extends Schema.TaggedError<SecretsFileUnreadable>()( "SecretsFileUnreadable", { file: Schema.String }) { override get message() { return `STAGE_SECRETS_FILE names ${this.file}, which can't be read`; }}
interface Step { readonly name: string; readonly command: string; readonly args: readonly string[]; readonly cwd: string; readonly env?: Readonly<Record<string, string>>;}
const bin = (app: string, name: string) => `${app}/node_modules/.bin/${name}`;
// A stage on the brand's own domain gets its hostnames and the URL vars that// name them here, never from `wrangler.jsonc` (see `customHosts`).const hostArgs = (stage: Stage) => Option.match(customHosts(stage), { onNone: () => ({ platform: [], web: [] }), onSome: ({ platform, web, webAliases }) => ({ platform: [ "--domain", platform, "--var", `PUBLIC_WEB_URL:https://${web}`, ], web: [ ...[web, ...webAliases].flatMap((host) => ["--domain", host]), "--var", `PUBLIC_PLATFORM_URL:https://${platform}`, ], }), });
const verify: Step = { args: ["run", "verify"], command: "bun", cwd: "", name: "verify",};
// Every step after verify. `since` is when the first upload began: smoke// fails on any error the stage's Workers logged from then on, read with// infra's credentials, so it runs through varlock as bootstrap does.const stepsOf = ( stage: Stage, options: { readonly web: boolean; readonly platformEnv: Readonly<Record<string, string>>; readonly since: DateTime.Utc; }): readonly Step[] => { const hosts = hostArgs(stage);
return [ { args: ["deploy", "--env", stage], command: bin("apps/sandbox", "wrangler"), cwd: "apps/sandbox", name: "sandbox", }, { args: ["deploy", "--env", stage, ...hosts.platform], command: bin("apps/platform", "varlock-wrangler"), cwd: "apps/platform", env: options.platformEnv, name: "platform", }, // The Vite plugin takes the stage from CLOUDFLARE_ENV and writes its deploy // config under `dist/`, so Wrangler gets no --env. NODE_ENV stops a shell's // own value from making a development build, whose `#backend` is the dev world. ...(options.web ? [ { args: ["run", "build"], command: "bun", cwd: "apps/web", env: { CLOUDFLARE_ENV: stage, NODE_ENV: "production" }, name: "web build", }, { args: ["deploy", "--env", stage, ...hosts.web], command: bin("apps/web", "wrangler"), cwd: "apps/web", name: "web", }, ] : []), { args: ["run", "bootstrap", "--stage", stage, "--check-triggers"], command: "bun", cwd: "", name: "triggers", }, { args: [ "run", "--path", "infra/", "--", "bun", "scripts/smoke.ts", "--stage", stage, "--since", DateTime.formatIso(options.since), ], command: "node_modules/.bin/varlock", cwd: "", name: "smoke", }, ];};
const platformSecrets = (root: string) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path;
const file = yield* Config.option(Config.String("STAGE_SECRETS_FILE")).pipe( Effect.orDie );
if (Option.isNone(file)) { return {}; }
const contents = yield* fs .readFileString(file.value) .pipe( Effect.mapError(() => new SecretsFileUnreadable({ file: file.value })) );
const schema = yield* fs .readFileString(path.join(root, "apps/platform/.env.schema")) .pipe(Effect.orDie);
const provider = ConfigProvider.fromDotEnvContents(contents);
const values = yield* Effect.forEach(schemaItems(schema), ({ name }) => Config.option(Config.String(name)) .parse(provider) .pipe( Effect.orDie, Effect.map(Option.map((value) => [name, value] as const)) ) );
return Object.fromEntries(values.flatMap(Option.toArray)); });
const runStep = (root: string, stage: Stage, step: Step) => Effect.gen(function* () { const path = yield* Path.Path; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const shown = [path.basename(step.command), ...step.args].join(" ");
const inherited = yield* Config.option(Config.String("PATH")).pipe( Effect.orDie );
// varlock-wrangler starts `wrangler` by name, and `bun run deploy` puts // only the root's bins on PATH, where no wrangler lives: the step's own // folder's bins come first, as a package runner would put them. const searched = [ path.join(root, step.cwd, "node_modules/.bin"), ...Option.toArray(inherited), ].join(":");
yield* Console.log(`deploy ${stage}: ${step.name}: ${shown}`);
const exitCode = yield* spawner .exitCode( ChildProcess.make( step.command === "bun" ? "bun" : path.join(root, step.command), step.args, { cwd: path.join(root, step.cwd), env: { ...step.env, PATH: searched, WRANGLER_SEND_METRICS: "false", }, extendEnv: true, stderr: "inherit", stdout: "inherit", } ) ) .pipe(Effect.orDie);
return yield* exitCode === 0 ? Effect.void : Effect.fail(new StepFailed({ exitCode, step: step.name })); });
// Mirrors `apps/platform/src/auth/pages.ts`: infra imports no app.const GOOGLE_CALLBACK = "/oauth/google/callback";
const decodeWorkersDev = Schema.decodeUnknownEffect( Schema.fromJsonString(WorkersDev));
const googleRedirectLine = (root: string, stage: Stage) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path;
const recorded = yield* fs .readFileString(path.join(root, subdomainFile)) .pipe(Effect.flatMap(decodeWorkersDev), Effect.option);
return Option.match(recorded, { onNone: () => `deploy ${stage}: to offer Google sign-in, run bun run bootstrap -- --stage ${stage} for the platform's origin, then register <origin>${GOOGLE_CALLBACK} as the Google client's redirect URI (H4)`, onSome: ({ subdomain }) => `deploy ${stage}: to offer Google sign-in, register ${platformOrigin(stage, subdomain)}${GOOGLE_CALLBACK} as the Google client's redirect URI (H4)`, }); });
export const deploy = ( argv: readonly string[]): Effect.Effect< void, | RecordingInProgress | NoStage | UnknownStage | StepFailed | SecretsFileUnreadable, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path> => Effect.gen(function* () { yield* notRecording;
const stage = yield* stageOf(argv); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const root = yield* repoRoot;
const web = yield* fs .exists(path.join(root, "apps/web/wrangler.jsonc")) .pipe(Effect.orDie);
const platformEnv = yield* platformSecrets(root);
yield* runStep(root, stage, verify);
// Smoke reads the logs from here: an error logged while verify ran is // the replaced version's, never this deploy's. const since = yield* DateTime.now;
yield* Effect.forEach( stepsOf(stage, { platformEnv, since, web }), (step) => runStep(root, stage, step), { discard: true } );
yield* Console.log(`deploy ${stage}: deployed, and smoke passed.`); yield* Console.log(yield* googleRedirectLine(root, stage)); });
if (import.meta.main) { BunRuntime.runMain( Effect.gen(function* () { const args = yield* (yield* Stdio.Stdio).args;
return yield* deploy(args); }).pipe(Effect.provide(BunServices.layer)) );}