bootstrap.test.ts
This file
Path
packages/config/test/bootstrap.test.ts
585 lines · 18.0 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 { Effect, FileSystem, Path, Result, Schema } from "effect";45import {6 bucketsFrom,7 checkTriggers,8 CloudflareRefused,9 d1From,10 kvFrom,11 MissingSecrets,12 missingSecrets,13 plan,14 planLines,15 secretNames,16 Step,17 TriggerMismatch,18 TriggersResponse,19 WranglerFailed,20 writeIds,21} from "../../../infra/bootstrap.ts";22import type { Existing } from "../../../infra/bootstrap.ts";23import { schemaItems } from "../../../infra/env-schema.ts";24import { blankJsonc } from "../../../infra/jsonc.ts";25import { resources, stages } from "../../../infra/stages.ts";26import { repoRoot } from "./root.ts";2728const rootText = (file: string) =>29 Effect.gen(function* () {30 const fs = yield* FileSystem.FileSystem;31 const path = yield* Path.Path;3233 return yield* fs.readFileString(path.join(yield* repoRoot, file));34 }).pipe(Effect.provide(NodeServices.layer));3536const PlatformStage = Schema.Struct({37 analytics_engine_datasets: Schema.Tuple([38 Schema.Struct({ dataset: Schema.String }),39 ]),40 artifacts: Schema.Array(41 Schema.Struct({ binding: Schema.String, namespace: Schema.String })42 ),43 d1_databases: Schema.Tuple([44 Schema.Struct({ binding: Schema.String, database_name: Schema.String }),45 ]),46 r2_buckets: Schema.Array(47 Schema.Struct({ binding: Schema.String, bucket_name: Schema.String })48 ),49 services: Schema.Tuple([Schema.Struct({ service: Schema.String })]),50 triggers: Schema.Struct({51 events: Schema.Tuple([52 Schema.Struct({53 filter: Schema.Struct({ namespace: Schema.String }),54 targets: Schema.Tuple([55 Schema.Struct({ workflow_name: Schema.String }),56 ]),57 }),58 ]),59 }),60 vars: Schema.Struct({ STAGE: Schema.String }),61 workflows: Schema.Array(62 Schema.Struct({ binding: Schema.String, name: Schema.String })63 ),64});6566const Wrangler = <S extends Schema.Top>(stage: S) =>67 Schema.fromJsonString(68 Schema.Struct({69 env: Schema.Record(Schema.String, stage),70 name: Schema.String,71 })72 );7374const wrangler = <S extends Schema.Top & { readonly DecodingServices: never }>(75 app: string,76 stage: S77) =>78 rootText(`apps/${app}/wrangler.jsonc`).pipe(79 Effect.map(blankJsonc),80 Effect.flatMap(Schema.decodeUnknownEffect(Wrangler(stage)))81 );8283const nothing: Existing = { d1: [], kv: [], namespaces: [], r2: [] };8485const everything: Existing = {86 d1: [87 {88 id: "11111111-1111-4111-8111-111111111111",89 name: "front-page-dev-oscabriel",90 },91 { id: "22222222-2222-4222-8222-222222222222", name: "front-page-prod" },92 ],93 kv: [94 { id: "33333333333333333333333333333333", title: "oauth-dev-oscabriel" },95 { id: "44444444444444444444444444444444", title: "oauth-prod" },96 ],97 namespaces: [98 "projects-dev-oscabriel",99 "layers-dev-oscabriel",100 "projects-prod",101 "layers-prod",102 ],103 r2: [104 "evidence-dev-oscabriel",105 "evidence-prod",106 "releases-dev-oscabriel",107 "releases-prod",108 "code-cache-dev-oscabriel",109 "code-cache-prod",110 ],111};112113describe("the stage table", () => {114 it.effect(115 "names every stage the platform's wrangler.jsonc declares, and each resource its block uses",116 () =>117 Effect.gen(function* () {118 const platform = yield* wrangler("platform", PlatformStage);119120 expect(platform.name).toBe("platform");121 expect(Object.keys(platform.env)).toStrictEqual([...stages]);122123 const named = stages.map((stage) => {124 const names = resources(stage);125126 return {127 frontPage: names.frontPage,128 metrics: names.metrics,129 namespaces: [names.projects, names.layers],130 onPush: [names.onPush, names.onPush],131 platform: names.platform,132 projects: [names.projects, names.projects],133 sandbox: names.sandbox,134 stage,135 workflows: [names.answer, names.onPush],136 };137 });138139 const declared = stages.map((stage) => {140 const block = platform.env[stage];141142 return {143 frontPage: block?.d1_databases[0].database_name,144 metrics: block?.analytics_engine_datasets[0].dataset,145 namespaces: block?.artifacts.map(({ namespace }) => namespace),146 onPush: [147 block?.triggers.events[0].targets[0].workflow_name,148 block?.workflows.find(({ binding }) => binding === "ON_PUSH")149 ?.name,150 ],151 // Wrangler names a stage's Worker `<name>-<env>`.152 platform: `${platform.name}-${stage}`,153 projects: [154 block?.artifacts.find(({ binding }) => binding === "ARTIFACTS")155 ?.namespace,156 block?.triggers.events[0].filter.namespace,157 ],158 sandbox: block?.services[0].service,159 stage: block?.vars.STAGE,160 workflows: block?.workflows.map(({ name }) => name),161 };162 });163164 expect(declared).toStrictEqual(named);165 expect(166 stages.map((stage) =>167 Object.fromEntries(168 (platform.env[stage]?.r2_buckets ?? []).map(169 ({ binding, bucket_name }) => [binding, bucket_name]170 )171 )172 )173 ).toStrictEqual(174 stages.map((stage) => ({175 CODE_CACHE: resources(stage).codeCache,176 EVIDENCE: resources(stage).evidence,177 RELEASES: resources(stage).releases,178 }))179 );180 })181 );182183 it.effect("names every stage the sandbox's wrangler.jsonc declares", () =>184 Effect.gen(function* () {185 const sandbox = yield* wrangler("sandbox", Schema.Unknown);186187 expect(sandbox.name).toBe("sandbox");188 expect(Object.keys(sandbox.env)).toStrictEqual([...stages]);189 })190 );191});192193describe("the bootstrap plan", () => {194 it("creates every resource of a stage that has none", () => {195 expect(plan("dev-oscabriel", nothing)).toStrictEqual([196 Step.CreateNamespace({ name: "projects-dev-oscabriel" }),197 Step.CreateNamespace({ name: "layers-dev-oscabriel" }),198 Step.CreateD1({ name: "front-page-dev-oscabriel" }),199 Step.CreateKv({ title: "oauth-dev-oscabriel" }),200 Step.CreateR2({ name: "evidence-dev-oscabriel" }),201 Step.CreateR2({ name: "releases-dev-oscabriel" }),202 Step.CreateR2({ name: "code-cache-dev-oscabriel" }),203 ]);204 });205206 it("creates nothing on a second run", () => {207 expect(plan("dev-oscabriel", everything)).toStrictEqual([]);208 expect(plan("prod", everything)).toStrictEqual([]);209 });210211 it("creates only what is missing, and never counts another stage's", () => {212 const prodOnly: Existing = {213 d1: [214 { id: "22222222-2222-4222-8222-222222222222", name: "front-page-prod" },215 ],216 kv: [217 {218 id: "33333333333333333333333333333333",219 title: "oauth-dev-oscabriel",220 },221 ],222 namespaces: ["projects-prod", "layers-prod", "layers-dev-oscabriel"],223 r2: ["evidence-dev-oscabriel", "releases-prod", "code-cache-prod"],224 };225226 expect(plan("dev-oscabriel", prodOnly)).toStrictEqual([227 Step.CreateNamespace({ name: "projects-dev-oscabriel" }),228 Step.CreateD1({ name: "front-page-dev-oscabriel" }),229 Step.CreateR2({ name: "releases-dev-oscabriel" }),230 Step.CreateR2({ name: "code-cache-dev-oscabriel" }),231 ]);232 });233});234235describe("a dry run", () => {236 it("lists each step the plan would take, the private namespace among them, and says nothing changed", () => {237 expect(planLines("prod", plan("prod", nothing))).toStrictEqual([238 "bootstrap prod (dry run): create Artifacts namespace projects-prod",239 "bootstrap prod (dry run): create Artifacts namespace layers-prod",240 "bootstrap prod (dry run): create D1 front-page-prod",241 "bootstrap prod (dry run): create KV oauth-prod",242 "bootstrap prod (dry run): create R2 evidence-prod",243 "bootstrap prod (dry run): create R2 releases-prod",244 "bootstrap prod (dry run): create R2 code-cache-prod",245 "bootstrap prod (dry run): would create 7; nothing was changed",246 ]);247 expect(planLines("prod", [])).toStrictEqual([248 "bootstrap prod (dry run): would create 0; nothing was changed",249 ]);250 });251});252253const changed = (before: string, after: string) => {254 const old = before.split("\n");255256 return after257 .split("\n")258 .flatMap((line, index) =>259 line === old[index] ? [] : [`${index + 1}: ${line.trim()}`]260 );261};262263describe("writing ids into wrangler.jsonc", () => {264 const ids = {265 frontPage: "11111111-1111-4111-8111-111111111111",266 oauth: "33333333333333333333333333333333",267 };268269 it.effect(270 "rewrites only the stage's D1 and KV ids, keeping every other line and comment",271 () =>272 Effect.gen(function* () {273 const text = yield* rootText("apps/platform/wrangler.jsonc");274 const lines = text.split("\n");275 const written = writeIds(text, "dev-oscabriel", ids);276277 const devBlock = lines.findIndex((line) =>278 line.includes('"dev-oscabriel": {')279 );280281 const prodBlock = lines.findIndex((line) => line.includes('"prod": {'));282283 const lineOf = (needle: string) =>284 lines.findIndex(285 (line, index) =>286 index > devBlock && index < prodBlock && line.includes(needle)287 ) + 1;288289 expect(written.split("\n")).toHaveLength(lines.length);290 expect(changed(text, written)).toStrictEqual([291 `${lineOf('"database_id"')}: "database_id": "${ids.frontPage}",`,292 `${lineOf('"OAUTH_KV"')}: { "binding": "OAUTH_KV", "id": "${ids.oauth}" },`,293 ]);294 })295 );296297 it.effect("changes nothing when the ids are already written", () =>298 Effect.gen(function* () {299 const text = yield* rootText("apps/platform/wrangler.jsonc");300 const written = writeIds(text, "prod", ids);301302 expect(writeIds(written, "prod", ids)).toBe(written);303 expect(writeIds(text, "prod", {})).toBe(text);304 })305 );306307 it.effect("writes only the id it is given", () =>308 Effect.gen(function* () {309 const text = yield* rootText("apps/platform/wrangler.jsonc");310311 const written = writeIds(text, "prod", { oauth: ids.oauth });312313 expect(changed(text, written)).toHaveLength(1);314 expect(written).toContain(`"id": "${ids.oauth}"`);315 })316 );317318 it("keeps a comment that sits inside the stage's binding", () => {319 const text = [320 "{",321 ' "env": {',322 ' "prod": {',323 " // the KV namespace `oauth-prod`, {braces} and all",324 ' "kv_namespaces": [{ "binding": "OAUTH_KV", /* new */ "id": "0", },],',325 " },",326 " },",327 "}",328 ].join("\n");329330 expect(writeIds(text, "prod", { oauth: "abc" })).toBe(331 text.replace('"id": "0"', '"id": "abc"')332 );333 });334});335336describe("the push-event trigger, read back", () => {337 const fixture = rootText("infra/fixtures/triggers.json").pipe(338 Effect.flatMap(339 Schema.decodeUnknownEffect(Schema.fromJsonString(TriggersResponse))340 )341 );342343 it.effect(344 "accepts S1's shape, whose targets carry script_name, for its stage",345 () =>346 Effect.gen(function* () {347 const live = yield* fixture;348349 expect(350 Result.isSuccess(checkTriggers("dev-oscabriel", live))351 ).toBeTruthy();352 })353 );354355 it.effect("refuses a stage whose trigger is missing", () =>356 Effect.gen(function* () {357 const live = yield* fixture;358359 const without = {360 ...live,361 result: {362 ...live.result,363 triggers: live.result.triggers.filter(364 ({ filter }) => filter.namespace !== "projects-dev-oscabriel"365 ),366 },367 };368369 expect(checkTriggers("dev-oscabriel", without)).toStrictEqual(370 Result.fail(371 new TriggerMismatch({372 found: [373 "cf.artifacts.repo.forked on layers-dev-oscabriel → platform-dev-oscabriel/on-push-dev-oscabriel",374 "cf.artifacts.repo.pushed on layers-dev-oscabriel → platform-dev-oscabriel/on-push-dev-oscabriel",375 ],376 namespace: "projects-dev-oscabriel",377 script: "platform-dev-oscabriel",378 workflow: "on-push-dev-oscabriel",379 })380 )381 );382 })383 );384385 it.effect("refuses another stage's triggers", () =>386 Effect.gen(function* () {387 const live = yield* fixture;388389 expect(Result.isFailure(checkTriggers("prod", live))).toBeTruthy();390 })391 );392393 it("refuses a target without script_name when it decodes", () => {394 const asConfigured = {395 result: {396 script_name: "platform-dev-oscabriel",397 triggers: [398 {399 filter: { namespace: "projects-dev-oscabriel" },400 targets: [401 { type: "workflow", workflow_name: "on-push-dev-oscabriel" },402 ],403 type: "cf.artifacts.repo.pushed",404 },405 ],406 },407 success: true,408 };409410 expect(411 Result.isFailure(412 Schema.decodeUnknownResult(TriggersResponse)(asConfigured)413 )414 ).toBeTruthy();415 });416});417418describe("what bootstrap reads from Wrangler", () => {419 it.effect("reads D1 databases from `d1 list --json`", () =>420 Effect.gen(function* () {421 expect(422 yield* d1From(423 JSON.stringify([424 {425 created_at: "2026-10-07T00:00:00.000Z",426 name: "front-page-dev-oscabriel",427 uuid: "11111111-1111-4111-8111-111111111111",428 },429 ])430 )431 ).toStrictEqual([432 {433 id: "11111111-1111-4111-8111-111111111111",434 name: "front-page-dev-oscabriel",435 },436 ]);437 })438 );439440 it.effect(441 "reads KV namespaces from `kv namespace list`, past a warning line",442 () =>443 Effect.gen(function* () {444 expect(445 yield* kvFrom(446 [447 "▲ [WARNING] a newer wrangler is out",448 JSON.stringify([449 {450 id: "33333333333333333333333333333333",451 supports_url_encoding: true,452 title: "oauth-dev-oscabriel",453 },454 ]),455 ].join("\n")456 )457 ).toStrictEqual([458 {459 id: "33333333333333333333333333333333",460 title: "oauth-dev-oscabriel",461 },462 ]);463 })464 );465466 it("reads bucket names from `r2 bucket list`'s labelled output", () => {467 const output = [468 " ⛅️ wrangler 4.147.0",469 "───────────────────",470 "Listing buckets...",471 "name: evidence-dev-oscabriel",472 "creation_date: 2026-10-07T00:00:00.000Z",473 "",474 "name: witness",475 "creation_date: 2026-09-01T00:00:00.000Z",476 ].join("\n");477478 expect(bucketsFrom(output)).toStrictEqual([479 "evidence-dev-oscabriel",480 "witness",481 ]);482 });483});484485describe("secrets, by name only", () => {486 it.effect("takes the required names from the platform's .env.schema", () =>487 Effect.gen(function* () {488 const schema = yield* rootText("apps/platform/.env.schema");489490 expect(schemaItems(schema)).toStrictEqual([491 { name: "OPERATOR_TOKEN", required: true },492 { name: "SESSION_TOKENS", required: false },493 { name: "COOKIE_KEY", required: true },494 { name: "PASSWORD_PEPPER", required: true },495 { name: "GOOGLE_CLIENT_ID", required: false },496 { name: "GOOGLE_CLIENT_SECRET", required: false },497 { name: "MASTER_KEY", required: true },498 ]);499 })500 );501502 it("infers a required item from a value when the header says infer", () => {503 const schema = [504 "# @defaultRequired=infer",505 "# ---",506 "",507 "# @sensitive",508 "TOKEN=",509 "",510 "LEVEL=info",511 "",512 "# @required=forEnv(production)",513 "LATER=",514 ].join("\n");515516 expect(schemaItems(schema)).toStrictEqual([517 { name: "TOKEN", required: false },518 { name: "LEVEL", required: true },519 { name: "LATER", required: false },520 ]);521 });522523 it.effect("reads only names from `secret list`", () =>524 Effect.gen(function* () {525 expect(526 yield* secretNames(527 JSON.stringify([{ name: "OPERATOR_TOKEN", type: "secret_text" }])528 )529 ).toStrictEqual(["OPERATOR_TOKEN"]);530 })531 );532533 it("names the required secrets a deployed Worker lacks", () => {534 const items = [535 { name: "OPERATOR_TOKEN", required: true },536 { name: "SESSION_TOKENS", required: false },537 ];538539 expect(missingSecrets(items, ["SESSION_TOKENS"])).toStrictEqual([540 "OPERATOR_TOKEN",541 ]);542 expect(missingSecrets(items, ["OPERATOR_TOKEN"])).toStrictEqual([]);543 });544});545546describe("what a failed bootstrap prints", () => {547 // `runMain` prints a failure as its tag and its message, and nothing else.548 it.effect("names the triggers it found instead of the stage's", () =>549 Effect.gen(function* () {550 const live = yield* rootText("infra/fixtures/triggers.json").pipe(551 Effect.flatMap(552 Schema.decodeUnknownEffect(Schema.fromJsonString(TriggersResponse))553 )554 );555556 const verdict = checkTriggers("dev-oscabriel", {557 ...live,558 result: { ...live.result, triggers: live.result.triggers.slice(0, 1) },559 });560561 expect(Result.isFailure(verdict) ? verdict.failure.message : "").toBe(562 "platform-dev-oscabriel has no cf.artifacts.repo.pushed trigger on projects-dev-oscabriel starting on-push-dev-oscabriel; it has: cf.artifacts.repo.forked on layers-dev-oscabriel → platform-dev-oscabriel/on-push-dev-oscabriel"563 );564 })565 );566567 it("names the secrets a deployed platform lacks, and the calls that failed", () => {568 expect(569 new MissingSecrets({570 names: ["OPERATOR_TOKEN", "COOKIE_KEY"],571 stage: "prod",572 }).message573 ).toBe(574 "prod's platform lacks OPERATOR_TOKEN, COOKIE_KEY: set them by name, from the stage's secrets file (STAGE_SECRETS_FILE)"575 );576 expect(577 new CloudflareRefused({ route: "/workers/subdomain", status: 403 })578 .message579 ).toBe("the Cloudflare API answered /workers/subdomain with 403");580 expect(581 new WranglerFailed({ command: "wrangler d1 list --json", exitCode: 1 })582 .message583 ).toBe("wrangler d1 list --json exited 1");584 });585});