deploy.test.ts
This file
Path
packages/config/test/deploy.test.ts
494 lines · 15.6 KiB · TypeScript
Last changed by
Merge infra/drop-demo into mainoscabrielbefore adoptionc49b6bf
History of this fileTake it
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import {5 Console,6 ConfigProvider,7 DateTime,8 Effect,9 FileSystem,10 Layer,11 Option,12 Path,13 Ref,14 Result,15 Schema,16 Sink,17 Stream,18} from "effect";19import { ChildProcess, ChildProcessSpawner } from "effect/process";2021import {22 deploy,23 NoStage,24 StepFailed,25 UnknownStage,26} from "../../../infra/deploy.ts";27import { LockFile } from "../../../infra/recording.ts";28import { repoRoot } from "./root.ts";2930interface Spawned {31 readonly command: string;32 readonly args: readonly string[];33 readonly cwd: string;34 readonly env: Readonly<Record<string, string | undefined>>;35 // When it was spawned, in epoch milliseconds.36 readonly at: number;37}3839const recording = (exitOf: (spawned: Spawned) => number) =>40 Effect.gen(function* () {41 const path = yield* Path.Path;42 const root = yield* repoRoot;43 const spawned = yield* Ref.make<readonly Spawned[]>([]);4445 const spawner = ChildProcessSpawner.make((command) =>46 Effect.gen(function* () {47 if (!ChildProcess.isStandardCommand(command)) {48 return yield* Effect.die("the deploy pipes no commands");49 }5051 const call: Spawned = {52 args: command.args,53 at: DateTime.toEpochMillis(yield* DateTime.now),54 command: path.basename(command.command),55 cwd: path.relative(root, command.options.cwd ?? root),56 env: command.options.env ?? {},57 };5859 yield* Ref.update(spawned, (calls) => [...calls, call]);6061 return ChildProcessSpawner.makeHandle({62 all: Stream.empty,63 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitOf(call))),64 getInputFd: () => Sink.drain,65 getOutputFd: () => Stream.empty,66 isRunning: Effect.succeed(false),67 kill: () => Effect.void,68 pid: ChildProcessSpawner.ProcessId(1),69 stderr: Stream.empty,70 stdin: Sink.drain,71 stdout: Stream.empty,72 unref: Effect.succeed(Effect.void),73 });74 })75 );7677 return {78 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),79 spawned: Ref.get(spawned),80 };81 });8283const run = (84 argv: readonly string[],85 options: {86 readonly exitOf?: (spawned: Spawned) => number;87 readonly env?: Readonly<Record<string, string>>;88 } = {}89) =>90 Effect.gen(function* () {91 const fs = yield* FileSystem.FileSystem;92 const path = yield* Path.Path;93 const fake = yield* recording(options.exitOf ?? (() => 0));9495 // A lock nobody wrote, so a local `infra/.recording` never decides these96 // tests; recording.test.ts holds the lock itself.97 const unlocked = path.join(98 yield* fs.makeTempDirectoryScoped({ prefix: "deploy-unlocked-" }),99 ".recording"100 );101102 const result = yield* deploy(argv).pipe(103 Effect.provide(fake.layer),104 Effect.provideService(LockFile, unlocked),105 // Only what the test sets, whatever the shell running the tests has.106 Effect.provideService(107 ConfigProvider.ConfigProvider,108 ConfigProvider.fromEnv({ env: { ...options.env } })109 ),110 Effect.result111 );112113 return { result, spawned: yield* fake.spawned };114 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));115116// The instant smoke reads the logs since is the run's own, so a line shows117// where it goes; "hands smoke the instant…" holds its value.118const line = ({ args, command, cwd }: Spawned) =>119 `${cwd === "" ? "." : cwd}$ ${[120 command,121 ...args.map((arg, index) =>122 args[index - 1] === "--since" ? "<since>" : arg123 ),124 ].join(" ")}`;125126describe("a deploy without a known stage", () => {127 it.live(128 "fails with NoStage and spawns nothing when no --stage is given",129 () =>130 Effect.gen(function* () {131 const { result, spawned } = yield* run([]);132133 expect(result).toStrictEqual(Result.fail(new NoStage()));134 expect(spawned).toStrictEqual([]);135 })136 );137138 it.live("fails with NoStage when --stage has no value", () =>139 Effect.gen(function* () {140 const { result, spawned } = yield* run(["--stage"]);141142 expect(result).toStrictEqual(Result.fail(new NoStage()));143 expect(spawned).toStrictEqual([]);144 })145 );146147 it.live.each(["staging", "dev-", "dev-Alice", "dev-nobody", "local"])(148 "fails with UnknownStage for --stage %s and spawns nothing",149 (stage) =>150 Effect.gen(function* () {151 const { result, spawned } = yield* run(["--stage", stage]);152153 expect(result).toStrictEqual(Result.fail(new UnknownStage({ stage })));154 expect(spawned).toStrictEqual([]);155 })156 );157});158159describe("a deploy to dev-oscabriel", () => {160 it.live(161 "verifies, deploys sandbox, platform and web, checks the trigger, then smoke-tests the stage",162 () =>163 Effect.gen(function* () {164 const { result, spawned } = yield* run(["--stage", "dev-oscabriel"]);165166 expect(Result.isSuccess(result)).toBeTruthy();167 expect(spawned.map(line)).toStrictEqual([168 ".$ bun run verify",169 "apps/sandbox$ wrangler deploy --env dev-oscabriel",170 "apps/platform$ varlock-wrangler deploy --env dev-oscabriel",171 "apps/web$ bun run build",172 "apps/web$ wrangler deploy --env dev-oscabriel",173 ".$ bun run bootstrap --stage dev-oscabriel --check-triggers",174 ".$ varlock run --path infra/ -- bun scripts/smoke.ts --stage dev-oscabriel --since <since>",175 ]);176 })177 );178179 it.live(180 "ends by printing the redirect URI Google sign-in needs registered (H4)",181 () =>182 Effect.gen(function* () {183 const printed: string[] = [];184185 const quiet: Console.Console = {186 ...console,187 log: (...args: readonly unknown[]) => {188 printed.push(args.map(String).join(" "));189 },190 };191192 const { result } = yield* run(["--stage", "dev-oscabriel"]).pipe(193 Effect.provideService(Console.Console, quiet)194 );195196 expect(Result.isSuccess(result)).toBeTruthy();197 expect(printed.at(-1)).toBe(198 "deploy dev-oscabriel: to offer Google sign-in, register https://platform-dev-oscabriel.oscargabriel.workers.dev/oauth/google/callback as the Google client's redirect URI (H4)"199 );200 })201 );202203 it.live("takes --stage=dev-oscabriel as well", () =>204 Effect.gen(function* () {205 const { result, spawned } = yield* run(["--stage=dev-oscabriel"]);206207 expect(Result.isSuccess(result)).toBeTruthy();208 expect(spawned).toHaveLength(7);209 })210 );211212 it.live("stops after a failing verify, and deploys nothing", () =>213 Effect.gen(function* () {214 const { result, spawned } = yield* run(["--stage", "dev-oscabriel"], {215 exitOf: ({ args }) => (args.includes("verify") ? 1 : 0),216 });217218 expect(result).toStrictEqual(219 Result.fail(new StepFailed({ exitCode: 1, step: "verify" }))220 );221 expect(spawned.map(line)).toStrictEqual([".$ bun run verify"]);222 })223 );224225 it.live("stops after a failing sandbox deploy, before the platform's", () =>226 Effect.gen(function* () {227 const { result, spawned } = yield* run(["--stage", "dev-oscabriel"], {228 exitOf: ({ cwd }) => (cwd === "apps/sandbox" ? 2 : 0),229 });230231 expect(result).toStrictEqual(232 Result.fail(new StepFailed({ exitCode: 2, step: "sandbox" }))233 );234 expect(spawned).toHaveLength(2);235 })236 );237238 it.live("fails when smoke fails, after everything else ran", () =>239 Effect.gen(function* () {240 const { result, spawned } = yield* run(["--stage", "dev-oscabriel"], {241 exitOf: ({ args }) => (args.includes("scripts/smoke.ts") ? 1 : 0),242 });243244 expect(result).toStrictEqual(245 Result.fail(new StepFailed({ exitCode: 1, step: "smoke" }))246 );247 expect(spawned).toHaveLength(7);248 })249 );250251 it.live(252 "hands smoke the instant the first upload began, after verify, so an error the replaced version logged during verify never fails it",253 () =>254 Effect.gen(function* () {255 const { result, spawned } = yield* run(["--stage", "dev-oscabriel"]);256 const [verify, sandbox] = spawned;257 const smoke = spawned.at(-1);258259 const since = Option.map(260 Schema.decodeUnknownOption(Schema.DateTimeUtcFromString)(261 smoke?.args.at(-1)262 ),263 DateTime.toEpochMillis264 );265266 expect(Result.isSuccess(result)).toBeTruthy();267 expect({268 flag: smoke?.args.at(-2),269 since: Option.isSome(since),270 verifiedFirst: Option.exists(271 since,272 (at) => (verify?.at ?? Infinity) <= at273 ),274 withTheUpload: Option.exists(275 since,276 (at) => at <= (sandbox?.at ?? -Infinity)277 ),278 }).toStrictEqual({279 flag: "--since",280 since: true,281 verifiedFirst: true,282 withTheUpload: true,283 });284 })285 );286287 it.live("turns Wrangler's metrics off in every command it spawns", () =>288 Effect.gen(function* () {289 const { spawned } = yield* run(["--stage", "dev-oscabriel"]);290291 expect(spawned.map(({ env }) => env.WRANGLER_SEND_METRICS)).toStrictEqual(292 ["false", "false", "false", "false", "false", "false", "false"]293 );294 })295 );296297 it.live(298 "builds the web for the stage, as production, before Wrangler deploys that build",299 () =>300 Effect.gen(function* () {301 const { spawned } = yield* run(["--stage", "dev-oscabriel"]);302303 const web = spawned.filter(({ cwd }) => cwd === "apps/web");304305 // The Vite plugin writes the stage's deploy config at build time, and306 // Wrangler refuses an --env other than the one the build was for. A307 // production build never carries the `development` #backend.308 expect(309 web.map(({ args, env }) => ({310 args,311 stage: env.CLOUDFLARE_ENV,312 vite: env.NODE_ENV,313 }))314 ).toStrictEqual([315 {316 args: ["run", "build"],317 stage: "dev-oscabriel",318 vite: "production",319 },320 {321 args: ["deploy", "--env", "dev-oscabriel"],322 stage: undefined,323 vite: undefined,324 },325 ]);326 })327 );328329 it.live(330 "puts each step's own bins first on PATH, so varlock-wrangler starts the platform's pinned wrangler",331 () =>332 Effect.gen(function* () {333 const path = yield* Path.Path;334 const root = yield* repoRoot;335336 // `bun run deploy` gives the root's bins, where no wrangler lives.337 const inherited = `${path.join(root, "node_modules/.bin")}:/usr/bin`;338339 const { spawned } = yield* run(["--stage", "dev-oscabriel"], {340 env: { PATH: inherited },341 });342343 const first = spawned.map(({ cwd, env }) => ({344 cwd,345 first: env.PATH?.split(":")[0],346 rest: env.PATH?.split(":").slice(1).join(":"),347 }));348349 expect(first[2]).toStrictEqual({350 cwd: "apps/platform",351 first: path.join(root, "apps/platform/node_modules/.bin"),352 rest: inherited,353 });354 expect(first[1]?.first).toBe(355 path.join(root, "apps/sandbox/node_modules/.bin")356 );357 }).pipe(Effect.provide(NodeServices.layer))358 );359360 it.live(361 "hands the platform's deploy the values in STAGE_SECRETS_FILE that its .env.schema names, and no other step any",362 () =>363 Effect.gen(function* () {364 const fs = yield* FileSystem.FileSystem;365 const path = yield* Path.Path;366 const dir = yield* fs.makeTempDirectoryScoped();367 const file = path.join(dir, "dev-oscabriel.secrets");368369 yield* fs.writeFileString(370 file,371 [372 "# generated for dev-oscabriel",373 "OPERATOR_TOKEN=operator-token-that-is-long-enough-000",374 'SESSION_TOKENS={"alice-token-that-is-long-enough-0000":"alice"}',375 "NOT_IN_THE_SCHEMA=dropped",376 ].join("\n")377 );378379 const { result, spawned } = yield* run(["--stage", "dev-oscabriel"], {380 env: { STAGE_SECRETS_FILE: file },381 });382383 expect(Result.isSuccess(result)).toBeTruthy();384385 const carried = spawned.map(({ env }) =>386 Object.keys(env)387 .filter((key) => key !== "PATH" && key !== "WRANGLER_SEND_METRICS")388 .toSorted()389 );390391 expect(carried).toStrictEqual([392 [],393 [],394 ["OPERATOR_TOKEN", "SESSION_TOKENS"],395 ["CLOUDFLARE_ENV", "NODE_ENV"],396 [],397 [],398 [],399 ]);400 expect(spawned[2]?.env.SESSION_TOKENS).toBe(401 '{"alice-token-that-is-long-enough-0000":"alice"}'402 );403 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))404 );405});406407const messageOf = (408 argv: readonly string[],409 options: Parameters<typeof run>[1] = {}410) =>411 run(argv, options).pipe(412 Effect.map(({ result }) =>413 Result.isFailure(result) ? result.failure.message : ""414 )415 );416417describe("what a failed deploy prints", () => {418 it.live("names the stages it knows when it refuses one", () =>419 Effect.gen(function* () {420 expect(yield* messageOf([])).toBe(421 "no --stage: name one of dev-oscabriel, prod"422 );423 expect(yield* messageOf(["--stage", "staging"])).toBe(424 "--stage staging is not a stage infra/stages.ts declares (dev-oscabriel, prod)"425 );426 })427 );428429 it.live("names the step that failed and how", () =>430 Effect.gen(function* () {431 const message = yield* messageOf(["--stage", "dev-oscabriel"], {432 exitOf: ({ cwd }) => (cwd === "apps/platform" ? 3 : 0),433 });434435 expect(message).toBe("platform exited 3, so nothing after it ran");436 })437 );438439 it.live("names the secrets file it could not read", () =>440 Effect.gen(function* () {441 const message = yield* messageOf(["--stage", "dev-oscabriel"], {442 env: { STAGE_SECRETS_FILE: "/nowhere/dev-oscabriel.secrets" },443 });444445 expect(message).toBe(446 "STAGE_SECRETS_FILE names /nowhere/dev-oscabriel.secrets, which can't be read"447 );448 })449 );450});451452describe("a deploy to prod", () => {453 it.live(454 "puts the platform and the web on the brand's own domain, and hands each the other's URL",455 () =>456 Effect.gen(function* () {457 const { result, spawned } = yield* run(["--stage", "prod"]);458 const git = `git.${Brand.domain}`;459460 expect(Result.isSuccess(result)).toBeTruthy();461 expect(spawned.map(line)).toStrictEqual([462 ".$ bun run verify",463 "apps/sandbox$ wrangler deploy --env prod",464 `apps/platform$ varlock-wrangler deploy --env prod --domain ${git} --var PUBLIC_WEB_URL:https://${Brand.domain}`,465 "apps/web$ bun run build",466 `apps/web$ wrangler deploy --env prod --domain ${Brand.domain} --domain www.${Brand.domain} --var PUBLIC_PLATFORM_URL:https://${git}`,467 ".$ bun run bootstrap --stage prod --check-triggers",468 ".$ varlock run --path infra/ -- bun scripts/smoke.ts --stage prod --since <since>",469 ]);470 })471 );472473 it.live("names the Google redirect URI on the platform's own host", () =>474 Effect.gen(function* () {475 const printed: string[] = [];476477 const quiet: Console.Console = {478 ...console,479 log: (...args: readonly unknown[]) => {480 printed.push(args.map(String).join(" "));481 },482 };483484 const { result } = yield* run(["--stage", "prod"]).pipe(485 Effect.provideService(Console.Console, quiet)486 );487488 expect(Result.isSuccess(result)).toBeTruthy();489 expect(printed.at(-1)).toBe(490 `deploy prod: to offer Google sign-in, register https://git.${Brand.domain}/oauth/google/callback as the Google client's redirect URI (H4)`491 );492 })493 );494});