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
The walk stopped after 200 commits: lines older than 10c8b54 point at it.
Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
lines 1–2why, one step back1// Usage: bun run deploy -- --stage <stage>2// Runs verify, deploys sandbox, platform and web, checks the push trigger, thenMerge observability into mainoscabrielbefore adoption1985111
lines 3–4why, one step back3// smoke, which also reads the stage's logs since the first upload began.4// Refused while `infra/.recording` exists, before any flag is read.Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
lines 5–6why, one step back5// `STAGE_SECRETS_FILE` passes only the items `apps/platform/.env.schema`6// declares, to the platform step alone; no value is ever printed.Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
lines 7–11why, one step back7import { BunRuntime, BunServices } from "@effect/platform-bun";8import {9 Config,10 ConfigProvider,11 Console,Merge observability into mainoscabrielbefore adoption1985111
line 12why, one step back12 DateTime,Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
lines 13–25why, one step back13 Effect,14 FileSystem,15 Option,16 Path,17 Schema,18 Stdio,19} from "effect";20import { ChildProcess, ChildProcessSpawner } from "effect/process";2122import { schemaItems } from "./env-schema.ts";23import { notRecording } from "./recording.ts";24import type { RecordingInProgress } from "./recording.ts";25import {Add a prod stage served on the brand's own domainoscabrielbefore adoption78a5062
line 26why, one step back26 customHosts,Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
lines 27–66why, one step back27 platformOrigin,28 repoRoot,29 stageOf,30 subdomainFile,31 WorkersDev,32} from "./stages.ts";33import type { NoStage, Stage, UnknownStage } from "./stages.ts";3435export { RecordingInProgress } from "./recording.ts";3637export { NoStage, UnknownStage } from "./stages.ts";3839export class StepFailed extends Schema.TaggedError<StepFailed>()("StepFailed", {40 exitCode: Schema.Int,41 step: Schema.String,42}) {43 override get message() {44 return `${this.step} exited ${this.exitCode}, so nothing after it ran`;45 }46}4748export class SecretsFileUnreadable extends Schema.TaggedError<SecretsFileUnreadable>()(49 "SecretsFileUnreadable",50 { file: Schema.String }51) {52 override get message() {53 return `STAGE_SECRETS_FILE names ${this.file}, which can't be read`;54 }55}5657interface Step {58 readonly name: string;59 readonly command: string;60 readonly args: readonly string[];61 readonly cwd: string;62 readonly env?: Readonly<Record<string, string>>;63}6465const bin = (app: string, name: string) => `${app}/node_modules/.bin/${name}`;66Add a prod stage served on the brand's own domainoscabrielbefore adoption78a5062
lines 67–71why, one step back67// A stage on the brand's own domain gets its hostnames and the URL vars that68// name them here, never from `wrangler.jsonc` (see `customHosts`).69const hostArgs = (stage: Stage) =>70 Option.match(customHosts(stage), {71 onNone: () => ({ platform: [], web: [] }),Serve the web's www host as a redirect to its bare hostoscabrielbefore adoption05cecd1
line 72why, one step back72 onSome: ({ platform, web, webAliases }) => ({Add a prod stage served on the brand's own domainoscabrielbefore adoption78a5062
lines 73–79why, one step back73 platform: [74 "--domain",75 platform,76 "--var",77 `PUBLIC_WEB_URL:https://${web}`,78 ],79 web: [Serve the web's www host as a redirect to its bare hostoscabrielbefore adoption05cecd1
line 80why, one step back80 ...[web, ...webAliases].flatMap((host) => ["--domain", host]),Add a prod stage served on the brand's own domainoscabrielbefore adoption78a5062
lines 81–86why, one step back81 "--var",82 `PUBLIC_PLATFORM_URL:https://${platform}`,83 ],84 }),85 });86Merge observability into mainoscabrielbefore adoption1985111
lines 87–96why, one step back87const verify: Step = {88 args: ["run", "verify"],89 command: "bun",90 cwd: "",91 name: "verify",92};9394// Every step after verify. `since` is when the first upload began: smoke95// fails on any error the stage's Workers logged from then on, read with96// infra's credentials, so it runs through varlock as bootstrap does.Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
lines 97–101why, one step back97const stepsOf = (98 stage: Stage,99 options: {100 readonly web: boolean;101 readonly platformEnv: Readonly<Record<string, string>>;Merge observability into mainoscabrielbefore adoption1985111
line 102why, one step back102 readonly since: DateTime.Utc;Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
line 103why, one step back103 }Add a prod stage served on the brand's own domainoscabrielbefore adoption78a5062
lines 104–147why, one step back104): readonly Step[] => {105 const hosts = hostArgs(stage);106107 return [108 {109 args: ["deploy", "--env", stage],110 command: bin("apps/sandbox", "wrangler"),111 cwd: "apps/sandbox",112 name: "sandbox",113 },114 {115 args: ["deploy", "--env", stage, ...hosts.platform],116 command: bin("apps/platform", "varlock-wrangler"),117 cwd: "apps/platform",118 env: options.platformEnv,119 name: "platform",120 },121 // The Vite plugin takes the stage from CLOUDFLARE_ENV and writes its deploy122 // config under `dist/`, so Wrangler gets no --env. NODE_ENV stops a shell's123 // own value from making a development build, whose `#backend` is the dev world.124 ...(options.web125 ? [126 {127 args: ["run", "build"],128 command: "bun",129 cwd: "apps/web",130 env: { CLOUDFLARE_ENV: stage, NODE_ENV: "production" },131 name: "web build",132 },133 {134 args: ["deploy", "--env", stage, ...hosts.web],135 command: bin("apps/web", "wrangler"),136 cwd: "apps/web",137 name: "web",138 },139 ]140 : []),141 {142 args: ["run", "bootstrap", "--stage", stage, "--check-triggers"],143 command: "bun",144 cwd: "",145 name: "triggers",146 },147 {Merge observability into mainoscabrielbefore adoption1985111
lines 148–160why, one step back148 args: [149 "run",150 "--path",151 "infra/",152 "--",153 "bun",154 "scripts/smoke.ts",155 "--stage",156 stage,157 "--since",158 DateTime.formatIso(options.since),159 ],160 command: "node_modules/.bin/varlock",Add a prod stage served on the brand's own domainoscabrielbefore adoption78a5062
lines 161–165why, one step back161 cwd: "",162 name: "smoke",163 },164 ];165};Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
lines 166–248why, one step back166167const platformSecrets = (root: string) =>168 Effect.gen(function* () {169 const fs = yield* FileSystem.FileSystem;170 const path = yield* Path.Path;171172 const file = yield* Config.option(Config.String("STAGE_SECRETS_FILE")).pipe(173 Effect.orDie174 );175176 if (Option.isNone(file)) {177 return {};178 }179180 const contents = yield* fs181 .readFileString(file.value)182 .pipe(183 Effect.mapError(() => new SecretsFileUnreadable({ file: file.value }))184 );185186 const schema = yield* fs187 .readFileString(path.join(root, "apps/platform/.env.schema"))188 .pipe(Effect.orDie);189190 const provider = ConfigProvider.fromDotEnvContents(contents);191192 const values = yield* Effect.forEach(schemaItems(schema), ({ name }) =>193 Config.option(Config.String(name))194 .parse(provider)195 .pipe(196 Effect.orDie,197 Effect.map(Option.map((value) => [name, value] as const))198 )199 );200201 return Object.fromEntries(values.flatMap(Option.toArray));202 });203204const runStep = (root: string, stage: Stage, step: Step) =>205 Effect.gen(function* () {206 const path = yield* Path.Path;207 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;208 const shown = [path.basename(step.command), ...step.args].join(" ");209210 const inherited = yield* Config.option(Config.String("PATH")).pipe(211 Effect.orDie212 );213214 // varlock-wrangler starts `wrangler` by name, and `bun run deploy` puts215 // only the root's bins on PATH, where no wrangler lives: the step's own216 // folder's bins come first, as a package runner would put them.217 const searched = [218 path.join(root, step.cwd, "node_modules/.bin"),219 ...Option.toArray(inherited),220 ].join(":");221222 yield* Console.log(`deploy ${stage}: ${step.name}: ${shown}`);223224 const exitCode = yield* spawner225 .exitCode(226 ChildProcess.make(227 step.command === "bun" ? "bun" : path.join(root, step.command),228 step.args,229 {230 cwd: path.join(root, step.cwd),231 env: {232 ...step.env,233 PATH: searched,234 WRANGLER_SEND_METRICS: "false",235 },236 extendEnv: true,237 stderr: "inherit",238 stdout: "inherit",239 }240 )241 )242 .pipe(Effect.orDie);243244 return yield* exitCode === 0245 ? Effect.void246 : Effect.fail(new StepFailed({ exitCode, step: step.name }));247 });248Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 249why, one step back249// Mirrors `apps/platform/src/auth/pages.ts`: infra imports no app.Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
lines 250–297why, one step back250const GOOGLE_CALLBACK = "/oauth/google/callback";251252const decodeWorkersDev = Schema.decodeUnknownEffect(253 Schema.fromJsonString(WorkersDev)254);255256const googleRedirectLine = (root: string, stage: Stage) =>257 Effect.gen(function* () {258 const fs = yield* FileSystem.FileSystem;259 const path = yield* Path.Path;260261 const recorded = yield* fs262 .readFileString(path.join(root, subdomainFile))263 .pipe(Effect.flatMap(decodeWorkersDev), Effect.option);264265 return Option.match(recorded, {266 onNone: () =>267 `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)`,268 onSome: ({ subdomain }) =>269 `deploy ${stage}: to offer Google sign-in, register ${platformOrigin(stage, subdomain)}${GOOGLE_CALLBACK} as the Google client's redirect URI (H4)`,270 });271 });272273export const deploy = (274 argv: readonly string[]275): Effect.Effect<276 void,277 | RecordingInProgress278 | NoStage279 | UnknownStage280 | StepFailed281 | SecretsFileUnreadable,282 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path283> =>284 Effect.gen(function* () {285 yield* notRecording;286287 const stage = yield* stageOf(argv);288 const fs = yield* FileSystem.FileSystem;289 const path = yield* Path.Path;290 const root = yield* repoRoot;291292 const web = yield* fs293 .exists(path.join(root, "apps/web/wrangler.jsonc"))294 .pipe(Effect.orDie);295296 const platformEnv = yield* platformSecrets(root);297Merge observability into mainoscabrielbefore adoption1985111
lines 298–303why, one step back298 yield* runStep(root, stage, verify);299300 // Smoke reads the logs from here: an error logged while verify ran is301 // the replaced version's, never this deploy's.302 const since = yield* DateTime.now;303Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
line 304why, one step back304 yield* Effect.forEach(Merge observability into mainoscabrielbefore adoption1985111
line 305why, one step back305 stepsOf(stage, { platformEnv, since, web }),Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
lines 306–322why, one step back306 (step) => runStep(root, stage, step),307 { discard: true }308 );309310 yield* Console.log(`deploy ${stage}: deployed, and smoke passed.`);311 yield* Console.log(yield* googleRedirectLine(root, stage));312 });313314if (import.meta.main) {315 BunRuntime.runMain(316 Effect.gen(function* () {317 const args = yield* (yield* Stdio.Stdio).args;318319 return yield* deploy(args);320 }).pipe(Effect.provide(BunServices.layer))321 );322}