From 6a46de5559dbe8e9968f86ffed2af4435d93925b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 20:48:15 +0000 Subject: [PATCH] UF2: the D1 database from Terraform, the schema through db-migrate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The monitor state's database, provisioned and migrated by Orun before the Worker that binds it deploys: - infra/terraform/cloudflare-d1 (turso-starter's root): one D1 database per deployed environment, named for the product, its id and name lease-published as the WIRING_CLOUDFLARE_D1 document the Worker's config renders from; `terraform validate` passes. - packages/db: the control migration and 010_monitor_state — upstream's init.sql under the table name monitor_state — with turso-starter's runner over D1's REST API; infra/db-migrate runs it, after the D1 apply (enforced on main, advisory on a pull request). - apps/web waits on both: one convergence runs cloudflare-d1 → db-migrate → web per environment. init.sql and `db:init:local` give way to `db:migrate:local`, which applies the same migrations to wrangler's local D1. - tests/db: the migrations through the runner into real SQLite — the checker's own upsert and read on the schema, a second apply applying nothing, the lock, the checksum guard; tests/web holds the table its SQLite stand-in creates to the migration's. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_019PcpNVpFBcbeiX3EHdXfmn --- apps/web/.env.example | 2 +- apps/web/README.md | 2 +- apps/web/component.yaml | 17 +- apps/web/init.sql | 6 - apps/web/package.json | 2 +- infra/db-migrate/component.yaml | 69 ++++++ infra/terraform/cloudflare-d1/component.yaml | 53 +++++ .../cloudflare-d1/terraform/adopt.tf | 43 ++++ .../cloudflare-d1/terraform/backend.tf | 5 + .../terraform/cloudflare-d1/terraform/main.tf | 138 +++++++++++ .../cloudflare-d1/terraform/outputs.tf | 2 + .../cloudflare-d1/terraform/variables.tf | 2 + packages/db/component.yaml | 25 ++ packages/db/eslint.config.js | 2 + packages/db/package.json | 30 +++ packages/db/src/index.ts | 3 + packages/db/src/manifest.ts | 30 +++ packages/db/src/migrations/000_control/up.sql | 12 + .../src/migrations/010_monitor_state/up.sql | 10 + packages/db/src/runner/cli.ts | 119 ++++++++++ packages/db/src/runner/d1-api-adapter.ts | 224 ++++++++++++++++++ packages/db/src/runner/index.ts | 5 + packages/db/src/runner/runner.ts | 140 +++++++++++ packages/db/src/runner/secrets.ts | 58 +++++ packages/db/src/runner/types.ts | 41 ++++ packages/db/src/types.ts | 20 ++ packages/db/tsconfig.build.json | 7 + packages/db/tsconfig.json | 10 + pnpm-lock.yaml | 36 +++ .../uptimeflare/IMPLEMENTATION-STATUS.md | 4 +- specs/epics/uptimeflare/README.md | 2 +- tests/db/component.yaml | 23 ++ tests/db/eslint.config.js | 2 + tests/db/package.json | 20 ++ tests/db/src/migrations.test.ts | 218 +++++++++++++++++ tests/db/tsconfig.json | 11 + tests/db/vitest.config.ts | 8 + tests/web/src/config.test.ts | 14 ++ 38 files changed, 1399 insertions(+), 16 deletions(-) delete mode 100644 apps/web/init.sql create mode 100644 infra/db-migrate/component.yaml create mode 100644 infra/terraform/cloudflare-d1/component.yaml create mode 100644 infra/terraform/cloudflare-d1/terraform/adopt.tf create mode 100644 infra/terraform/cloudflare-d1/terraform/backend.tf create mode 100644 infra/terraform/cloudflare-d1/terraform/main.tf create mode 100644 infra/terraform/cloudflare-d1/terraform/outputs.tf create mode 100644 infra/terraform/cloudflare-d1/terraform/variables.tf create mode 100644 packages/db/component.yaml create mode 100644 packages/db/eslint.config.js create mode 100644 packages/db/package.json create mode 100644 packages/db/src/index.ts create mode 100644 packages/db/src/manifest.ts create mode 100644 packages/db/src/migrations/000_control/up.sql create mode 100644 packages/db/src/migrations/010_monitor_state/up.sql create mode 100644 packages/db/src/runner/cli.ts create mode 100644 packages/db/src/runner/d1-api-adapter.ts create mode 100644 packages/db/src/runner/index.ts create mode 100644 packages/db/src/runner/runner.ts create mode 100644 packages/db/src/runner/secrets.ts create mode 100644 packages/db/src/runner/types.ts create mode 100644 packages/db/src/types.ts create mode 100644 packages/db/tsconfig.build.json create mode 100644 packages/db/tsconfig.json create mode 100644 tests/db/component.yaml create mode 100644 tests/db/eslint.config.js create mode 100644 tests/db/package.json create mode 100644 tests/db/src/migrations.test.ts create mode 100644 tests/db/tsconfig.json create mode 100644 tests/db/vitest.config.ts diff --git a/apps/web/.env.example b/apps/web/.env.example index 96804f8..4450ce8 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -1,4 +1,4 @@ # Nothing to set for the data path: the monitor state lives in the D1 database # bound as DB in wrangler.jsonc (the committed fixture render — wrangler keeps -# a local SQLite behind it; `pnpm db:init:local` creates the table there — and, +# a local SQLite behind it; `pnpm db:migrate:local` applies the migrations there — and, # on deploy, rendered from the cloudflare-d1 root's wiring document). diff --git a/apps/web/README.md b/apps/web/README.md index c68049b..912e700 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -18,7 +18,7 @@ checker (`monitor/`, upstream's `worker/src`) on the Worker's Cron Trigger. ```bash pnpm run wire:fixture # render wrangler.jsonc from the fixture (committed) -pnpm db:init:local # create the monitor_state table in wrangler's local D1 +pnpm db:migrate:local # apply packages/db's migrations to wrangler's local D1 pnpm build # next build + opennextjs-cloudflare build pnpm exec wrangler dev --test-scheduled curl 'http://localhost:8787/__scheduled?cron=*+*+*+*+*' # run the checker once diff --git a/apps/web/component.yaml b/apps/web/component.yaml index 5006031..a471962 100644 --- a/apps/web/component.yaml +++ b/apps/web/component.yaml @@ -16,10 +16,13 @@ spec: lane: isolated # INFRA BEFORE APP. The Worker binds the D1 database by id, and the id is # rendered into its config during the build from the wiring document the - # cloudflare-d1 root lease-publishes after its apply. A job resolves its - # secrets when it STARTS, so on a merge to main this deploy waits for that - # environment's apply (enforced) and the document is there; a pull request - # deploys nothing, so nothing on one waits (advisory). + # cloudflare-d1 root lease-publishes after its apply; and the checker writes + # and the page reads the `monitor_state` table, which db-migrate creates in + # that database. A job resolves its secrets when it STARTS, so on a merge to + # main this deploy waits for both (enforced) — one convergence runs + # cloudflare-d1 → db-migrate → web per environment, and the document and the + # schema are there. A pull request deploys nothing, so nothing on one waits + # (advisory). dependsOn: - component: cloudflare-d1 mode: enforced @@ -27,6 +30,12 @@ spec: - mode: advisory when: triggerRef: github-pull-request + - component: db-migrate + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request secretEnv: WIRING_CLOUDFLARE_D1_STAGE: "secret://uptimeflare/uptimeflare/stage/WIRING_CLOUDFLARE_D1" WIRING_CLOUDFLARE_D1_PROD: "secret://uptimeflare/uptimeflare/prod/WIRING_CLOUDFLARE_D1" diff --git a/apps/web/init.sql b/apps/web/init.sql deleted file mode 100644 index 90565b9..0000000 --- a/apps/web/init.sql +++ /dev/null @@ -1,6 +0,0 @@ --- The monitor state's one table, for wrangler's LOCAL D1 (`pnpm db:init:local`): --- upstream's init.sql under the table name monitor_state. -CREATE TABLE IF NOT EXISTS monitor_state ( - key VARCHAR(255) PRIMARY KEY, - value BLOB NOT NULL -); diff --git a/apps/web/package.json b/apps/web/package.json index b7c5113..c8dd471 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -7,7 +7,7 @@ "build": "next build && opennextjs-cloudflare build --skipBuild --skipWranglerConfigCheck && opennextjs-cloudflare populateCache local", "start": "next start -p 3000", "preview": "opennextjs-cloudflare preview", - "db:init:local": "wrangler d1 execute DB --local --config wrangler.jsonc --file init.sql", + "db:migrate:local": "node ../../tooling/migrations/local.mjs", "typecheck": "tsc --noEmit", "lint": "eslint .", "wire:fixture": "node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json --env stage" diff --git a/infra/db-migrate/component.yaml b/infra/db-migrate/component.yaml new file mode 100644 index 0000000..7c4950b --- /dev/null +++ b/infra/db-migrate/component.yaml @@ -0,0 +1,69 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-migrate + description: Applies the monitor state's schema (packages/db's migrations) to the stage and prod Cloudflare D1 databases + labels: + domain: infra + scope: database + team: platform + layer: data + +spec: + type: db-migrate + lifecycle: production + owner: platform + domain: infra + + # THE SCHEMA BETWEEN THE DATABASE AND THE APP. Migrations target the + # database the `cloudflare-d1` component creates, and find it through the + # wiring document that component lease-publishes after its apply — and a + # job resolves its secrets when it STARTS, so on a merge to main this waits + # for that environment's apply (enforced). apps/web waits on this the same + # way, so one convergence runs cloudflare-d1 → db-migrate → web per + # environment. A pull request applies nothing (this plans offline there), so + # nothing on one waits (advisory). `db` is the package this builds and runs; + # a change to it re-plans this. + dependsOn: + - component: db + - component: cloudflare-d1 + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + + path: packages/db/src/migrations + + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + owner: sourceplane + repo: uptimeflare + + # Everything the runner needs to reach D1 over the REST API, all resolved + # from orun secrets: the provider credential is minted fresh per run from the + # Cloudflare integration's d1-edit template (the workers-deploy token cannot + # touch D1), the account id is a non-secret connection fact, and the + # database id arrives in the wiring document the cloudflare-d1 component + # lease-publishes. + secretEnv: + CLOUDFLARE_API_TOKEN: "secret://uptimeflare/uptimeflare/{{ .environment }}/CLOUDFLARE_D1_TOKEN" + CLOUDFLARE_ACCOUNT_ID: "secret://uptimeflare/uptimeflare/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + WIRING_CLOUDFLARE_D1: "secret://uptimeflare/uptimeflare/{{ .environment }}/WIRING_CLOUDFLARE_D1" + + subscribe: + environments: + - name: stage + profile: plan + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/cloudflare-d1/component.yaml b/infra/terraform/cloudflare-d1/component.yaml new file mode 100644 index 0000000..b423241 --- /dev/null +++ b/infra/terraform/cloudflare-d1/component.yaml @@ -0,0 +1,53 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: cloudflare-d1 + description: Provisions the Cloudflare D1 database the monitor state lives in, for stage and prod + labels: + domain: infra + scope: runtime-database + +spec: + type: terraform + lifecycle: production + owner: platform + domain: infra + + parameters: + orgName: sourceplane + stackName: cloudflare-d1 + terraformDir: terraform + terraformVersion: "1.15.3" + repo: uptimeflare + # SEC-JOB: the wiring document (database id/name) is lease-published + # post-apply; worker deploys read it back as WIRING_CLOUDFLARE_D1_, + # and db-migrate reads it to find the database it migrates. + secretOutputs: "WIRING_CLOUDFLARE_D1=wiring" + + # The Cloudflare Terraform provider authenticates via the CLOUDFLARE_API_TOKEN + # env var, resolved by orun from the project-rung brokered secret — minted + # fresh per run from the d1-edit template (D1 Write; the workers-deploy token + # deliberately cannot touch D1). Declared at component level because + # plan-only lanes refresh against the live Cloudflare API too, not just apply. + secretEnv: + CLOUDFLARE_API_TOKEN: "secret://uptimeflare/uptimeflare/{{ .environment }}/CLOUDFLARE_D1_TOKEN" + # Non-secret connection fact (account-id template). + CLOUDFLARE_ACCOUNT_ID: "secret://uptimeflare/uptimeflare/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + TF_VAR_cloudflare_account_id: "secret://uptimeflare/uptimeflare/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + + subscribe: + environments: + - name: stage + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/cloudflare-d1/terraform/adopt.tf b/infra/terraform/cloudflare-d1/terraform/adopt.tf new file mode 100644 index 0000000..08407cd --- /dev/null +++ b/infra/terraform/cloudflare-d1/terraform/adopt.tf @@ -0,0 +1,43 @@ +# --- Self-healing adoption --- +# +# When the platform state does not yet track the database but Cloudflare +# already has one under this name (a re-bootstrap after a torn-down workspace, +# or state recovered onto a fresh backend), the create would collide with the +# duplicate-name guard. Instead: look the database up at plan time with the +# job's brokered credentials and import it. Fresh products resolve to id = "" +# and create normally, and a resource already tracked in state short-circuits +# the lookup — so this block is inert everywhere except the one case it exists +# for. Both lookups run inside the job: process env carries the brokered +# CLOUDFLARE_API_TOKEN/CLOUDFLARE_ACCOUNT_ID and the TF_HTTP_* state +# credentials, so no extra secrets are needed. + +data "external" "adopt_platform_database" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + name="$(jq -r .name)" + state_file="$(mktemp)" + trap 'rm -f "$state_file"' EXIT + code="$(curl -s -o "$state_file" -w '%%{http_code}' \ + -u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)" + if [ "$code" = "200" ] && jq -e \ + '[.resources[]? | select(.type == "cloudflare_d1_database" and .name == "platform")] | length > 0' \ + "$state_file" >/dev/null 2>&1; then + jq -n '{id: ""}' + exit 0 + fi + resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/d1/database?per_page=100")" + printf '%s' "$resp" | jq -c --arg n "$name" \ + '{id: ([.result[] | select(.name == $n) | .uuid] | first // "")}' + EOT + ] + query = { + name = local.database_name + } +} + +import { + for_each = toset(compact([data.external.adopt_platform_database.result.id])) + to = cloudflare_d1_database.platform + id = "${var.cloudflare_account_id}/${each.value}" +} diff --git a/infra/terraform/cloudflare-d1/terraform/backend.tf b/infra/terraform/cloudflare-d1/terraform/backend.tf new file mode 100644 index 0000000..ff89f5f --- /dev/null +++ b/infra/terraform/cloudflare-d1/terraform/backend.tf @@ -0,0 +1,5 @@ +# Terraform backend configuration is provided by Orun at runtime +# through environment variables and automatic backend initialization. +# +# S3 backend details are set via CLI args in the Orun runner. +# Local placeholder file for clarity. diff --git a/infra/terraform/cloudflare-d1/terraform/main.tf b/infra/terraform/cloudflare-d1/terraform/main.tf new file mode 100644 index 0000000..52af76a --- /dev/null +++ b/infra/terraform/cloudflare-d1/terraform/main.tf @@ -0,0 +1,138 @@ +terraform { + required_version = ">= 1.15.0" + + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job, so + # this block stays empty — no S3 bucket, no AWS role, no workspaces. + backend "http" {} + + required_providers { + cloudflare = { + source = "cloudflare/cloudflare" + version = "~> 4.30" + } + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } +} + +# --- Providers --- + +# Authenticates via the CLOUDFLARE_API_TOKEN env var (provider-native): the +# token is an orun-managed secret resolved into the job env at run time, so it +# never transits Terraform variables. +provider "cloudflare" {} + +# --- Variables (standard Orun parameters) --- + +variable "cloudflare_account_id" { + type = string + sensitive = true + default = "" + description = "Cloudflare account ID (from CLOUDFLARE_ACCOUNT_ID env var)" +} + +variable "orgName" { + type = string + default = "sourceplane" +} + +variable "owner" { + type = string + default = "sourceplane" +} + +variable "repo" { + type = string + default = "uptimeflare" +} + +variable "namespace" { + type = string + default = "sourceplane" +} + +variable "namespacePrefix" { + type = string + default = "" +} + +variable "lane" { + type = string + default = "verify" +} + +variable "environment" { + type = string + default = "stage" +} + +variable "component" { + type = string + default = "cloudflare-d1" +} + +variable "stackName" { + type = string + default = "cloudflare-d1" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# --- The monitor state's database --- +# +# One D1 database per deployed environment (stage, prod), bound by apps/web as +# DB. Its schema is not Terraform's: packages/db's migrations create the +# `monitor_state` table, applied by the db-migrate component after this apply and +# before the Worker deploys. + +locals { + # Built on var.repo (the product's repository slug) so the name is unique per + # product. D1 database names are unique per account, and two products may + # share an account. The Worker binds this database by ID through the wiring + # secret, so the name is free to change. + database_name = "${var.namespacePrefix}${var.repo}-${var.environment}" +} + +resource "cloudflare_d1_database" "platform" { + account_id = var.cloudflare_account_id + name = local.database_name +} + +# --- Wiring manifest (BF5, via orun secrets) --- +# +# The consumable outputs are published by the composition's wire-secrets step +# as the WIRING_CLOUDFLARE_D1 secret on the project/{{env}} rung; worker +# deploys read it back as WIRING_CLOUDFLARE_D1_ secretEnv and render the +# committed @@wiring(...)@@ tokens from it (BF6). The `db-migrate` component +# reads the same document (WIRING_CLOUDFLARE_D1) to find the database it +# migrates. + +output "wiring" { + description = "Wiring document for downstream deploy-time binding resolution (pushed to orun secrets)" + value = jsonencode({ + d1_database_id = cloudflare_d1_database.platform.id + d1_database_name = cloudflare_d1_database.platform.name + }) +} + +# --- Outputs (non-secret) --- + +output "d1_database_id" { + description = "Cloudflare D1 database ID (the Workers binding's database_id)" + value = cloudflare_d1_database.platform.id +} + +output "d1_database_name" { + description = "Cloudflare D1 database name (human-readable identifier)" + value = cloudflare_d1_database.platform.name +} diff --git a/infra/terraform/cloudflare-d1/terraform/outputs.tf b/infra/terraform/cloudflare-d1/terraform/outputs.tf new file mode 100644 index 0000000..9653334 --- /dev/null +++ b/infra/terraform/cloudflare-d1/terraform/outputs.tf @@ -0,0 +1,2 @@ +# Output definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-d1/terraform/variables.tf b/infra/terraform/cloudflare-d1/terraform/variables.tf new file mode 100644 index 0000000..9c92c69 --- /dev/null +++ b/infra/terraform/cloudflare-d1/terraform/variables.tf @@ -0,0 +1,2 @@ +# Variable definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/packages/db/component.yaml b/packages/db/component.yaml new file mode 100644 index 0000000..4885cd4 --- /dev/null +++ b/packages/db/component.yaml @@ -0,0 +1,25 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db + description: The monitor state's schema as migrations, and the runner that applies them to D1 (built by the db-migrate component before it plans or applies) +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: data + # Verified where the code is checked — on dev, by every pull request. On a + # merge the db-migrate component builds this package itself in its own job + # before it applies, so stage and prod need no job of their own here. + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: data diff --git a/packages/db/eslint.config.js b/packages/db/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/db/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/db/package.json b/packages/db/package.json new file mode 100644 index 0000000..82cabc8 --- /dev/null +++ b/packages/db/package.json @@ -0,0 +1,30 @@ +{ + "name": "@saas/db", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "The monitor state's schema as migrations, and the runner that applies them to Cloudflare D1 (the db-migrate composition builds this package and runs dist/runner/cli.js plan|apply)", + "exports": { + ".": "./src/index.ts", + "./manifest": "./src/manifest.ts", + "./types": "./src/types.ts", + "./runner": "./src/runner/index.ts" + }, + "bin": { + "db-migrate": "./dist/runner/cli.js" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json && cp -r src/migrations dist/", + "typecheck": "tsc --noEmit", + "lint": "eslint src", + "manifest:check": "node ../../tooling/migrations/manifest.mjs check", + "manifest:fix": "node ../../tooling/migrations/manifest.mjs fix", + "migrate:plan": "node dist/runner/cli.js plan --env stage" + }, + "devDependencies": { + "@app/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@types/node": "^22.9.0", + "typescript": "^5.8.3" + } +} diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts new file mode 100644 index 0000000..9b5ee07 --- /dev/null +++ b/packages/db/src/index.ts @@ -0,0 +1,3 @@ +export { manifest } from "./manifest.js"; +export type { MigrationEntry, MigrationManifest, BoundedContext } from "./types.js"; +export { BOUNDED_CONTEXTS } from "./types.js"; diff --git a/packages/db/src/manifest.ts b/packages/db/src/manifest.ts new file mode 100644 index 0000000..dab5c2e --- /dev/null +++ b/packages/db/src/manifest.ts @@ -0,0 +1,30 @@ +import type { MigrationManifest } from "./types.js"; + +// Every migration the runner applies, in order, with the sha256 of its file. +// `pnpm --filter @saas/db run manifest:check` verifies the checksums; +// `manifest:fix` rewrites them after a migration file changes (only ever +// before that migration has been applied anywhere — an applied migration's +// checksum is immutable). +export const manifest: MigrationManifest = { + version: 1, + migrations: [ + { + id: "000_control_baseline", + context: "control", + path: "000_control/up.sql", + checksum: + "c7f11499fa82d6fd2baa1af7fc75eeb73cd7be252af2e56841509c66001d638b", + description: + "Baseline control migration — creates the migration tracking schema", + }, + { + id: "010_monitor_state", + context: "app", + path: "010_monitor_state/up.sql", + checksum: + "5cf8e28cb73b4a05ac12776ff20a6aed4741a45256062aa4046ffa49bd673d8b", + description: + "The monitor_state table — key VARCHAR(255) PRIMARY KEY, value BLOB NOT NULL — upstream's init.sql, under a name that survives a rebrand", + }, + ], +}; diff --git a/packages/db/src/migrations/000_control/up.sql b/packages/db/src/migrations/000_control/up.sql new file mode 100644 index 0000000..e5cce04 --- /dev/null +++ b/packages/db/src/migrations/000_control/up.sql @@ -0,0 +1,12 @@ +-- Baseline control migration +-- Creates the migration tracking schema used by the migration runner. +-- Owner: control bounded context +CREATE TABLE IF NOT EXISTS _migrations_applied ( + id TEXT PRIMARY KEY, + context TEXT NOT NULL, + checksum TEXT NOT NULL, + applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + applied_by TEXT NOT NULL DEFAULT 'migration-runner' +); + +-- table _migrations_applied: Tracks which migrations have been applied to the database. diff --git a/packages/db/src/migrations/010_monitor_state/up.sql b/packages/db/src/migrations/010_monitor_state/up.sql new file mode 100644 index 0000000..631a36a --- /dev/null +++ b/packages/db/src/migrations/010_monitor_state/up.sql @@ -0,0 +1,10 @@ +-- The monitor state's one table: upstream's init.sql (`key` the state's name, +-- `value` the compacted state the checker writes every few minutes), named +-- monitor_state rather than after the project, and applied by db-migrate +-- before the Worker deploys. IF NOT EXISTS, so a database whose table an +-- earlier hand-run init created takes this migration as a no-op. +-- Owner: app +CREATE TABLE IF NOT EXISTS monitor_state ( + key VARCHAR(255) PRIMARY KEY, + value BLOB NOT NULL +); diff --git a/packages/db/src/runner/cli.ts b/packages/db/src/runner/cli.ts new file mode 100644 index 0000000..86c256c --- /dev/null +++ b/packages/db/src/runner/cli.ts @@ -0,0 +1,119 @@ +#!/usr/bin/env node +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest } from "../manifest.js"; +import { runMigrations } from "./runner.js"; +import { loadD1CredentialsFromEnv } from "./secrets.js"; +import { D1ApiAdapter } from "./d1-api-adapter.js"; +import type { MigrationAdapter, RunMode } from "./types.js"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_DIR = resolve(__dirname, "../migrations"); + +function usage(): never { + process.stderr.write( + `Usage: db-migrate --env \n` + + `\n` + + `Modes:\n` + + ` plan — report pending migrations without mutating the database\n` + + ` apply — apply pending migrations against the environment's D1 database\n` + + `\n` + + `Options:\n` + + ` --env target environment (required)\n` + + `\n` + + `Environment (apply mode; all wired from orun secrets):\n` + + ` CLOUDFLARE_ACCOUNT_ID Cloudflare account owning the D1 database\n` + + ` CLOUDFLARE_API_TOKEN account token with D1 edit permission\n` + + ` WIRING_CLOUDFLARE_D1 wiring document from the cloudflare-d1 component\n` + + ` (or D1_DATABASE_ID to name the database directly)\n` + + ` CLOUDFLARE_API_BASE_URL optional: the API base (wrangler's override; default\n` + + ` https://api.cloudflare.com/client/v4)\n`, + ); + process.exit(1); +} + +interface ParsedArgs { + mode: RunMode; + env: string; +} + +function parseArgs(argv: string[]): ParsedArgs { + const args = argv.slice(2); + + const mode = args[0] as RunMode | undefined; + if (mode !== "plan" && mode !== "apply") { + usage(); + } + + let env: string | undefined; + + for (let i = 1; i < args.length; i++) { + if (args[i] === "--env" && args[i + 1]) { + env = args[++i]; + } + } + + if (!env) { + const envFromEnv = process.env["MIGRATION_ENV"]; + if (envFromEnv) { + env = envFromEnv; + } + } + + if (!env || !["stage", "prod"].includes(env)) { + process.stderr.write("Error: --env must be 'stage' or 'prod'\n"); + process.exit(1); + } + + return { mode, env }; +} + +// The environment is not a parameter here: orun resolves each environment's +// secrets into the job env, so the D1 database this run targets is whichever +// one the lane was given. `--env` names the lane for the log and the output. +async function resolveAdapter(mode: RunMode): Promise { + if (mode === "plan") { + return null; + } + + process.stderr.write(`Loading credentials from the wired environment (orun secrets)\n`); + const credentials = loadD1CredentialsFromEnv(); + + return new D1ApiAdapter(credentials.accountId, credentials.databaseId, credentials.apiToken); +} + +async function main(): Promise { + const { mode, env } = parseArgs(process.argv); + + process.stderr.write(`db-migrate: mode=${mode} env=${env}\n`); + + const adapter = await resolveAdapter(mode); + + const result = await runMigrations(manifest, { + mode, + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + if (result.failed) { + process.stderr.write( + `FAILED: migration ${result.failed.id} — ${result.failed.error}\n`, + ); + process.exit(1); + } + + const output = { + mode, + env, + applied: result.applied, + skipped: result.skipped, + }; + + process.stdout.write(JSON.stringify(output, null, 2) + "\n"); +} + +main().catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + process.stderr.write(`db-migrate: fatal error — ${message}\n`); + process.exit(1); +}); diff --git a/packages/db/src/runner/d1-api-adapter.ts b/packages/db/src/runner/d1-api-adapter.ts new file mode 100644 index 0000000..e21c514 --- /dev/null +++ b/packages/db/src/runner/d1-api-adapter.ts @@ -0,0 +1,224 @@ +import type { MigrationEntry } from "../types.js"; +import type { AppliedMigration, MigrationAdapter } from "./types.js"; + +// The Cloudflare API's base. `CLOUDFLARE_API_BASE_URL` is wrangler's own +// override of the same thing (a regional or proxied endpoint, or a stand-in +// API offline); unset, it is the public API. +const DEFAULT_CLOUDFLARE_API = "https://api.cloudflare.com/client/v4"; +function cloudflareApi(): string { + return (process.env["CLOUDFLARE_API_BASE_URL"]?.trim() || DEFAULT_CLOUDFLARE_API).replace(/\/+$/, ""); +} + +/** How long a lock row may sit before a later runner reclaims it. A migration + * lane that outlives this was killed mid-flight; the ledger makes the retry + * safe. */ +const LOCK_STALE_MS = 15 * 60 * 1000; + +interface D1QueryResponse { + success?: boolean; + errors?: Array<{ code?: number; message?: string }>; + result?: Array<{ results?: Array>; success?: boolean }>; +} + +/** + * Applies migrations to a Cloudflare D1 database over the REST API. + * + * The CI lane has no Workers binding — it is a Node process — so it speaks to + * D1 the way any external tool does: `POST /accounts/{account}/d1/database/ + * {database}/query`, authorized by an account API token scoped to D1 edit. + * + * Statements are sent one at a time on purpose: the failing statement is then + * named exactly in the error, which is the difference between a five-second + * fix and a bisect through a 200-line migration. + */ +export class D1ApiAdapter implements MigrationAdapter { + private readonly accountId: string; + private readonly databaseId: string; + private readonly apiToken: string; + private readonly fetchImpl: typeof fetch; + private lockId: string | null = null; + + constructor( + accountId: string, + databaseId: string, + apiToken: string, + fetchImpl: typeof fetch = fetch, + ) { + this.accountId = accountId; + this.databaseId = databaseId; + this.apiToken = apiToken; + this.fetchImpl = fetchImpl; + } + + private async query( + sql: string, + params: unknown[] = [], + ): Promise>> { + const url = `${cloudflareApi()}/accounts/${this.accountId}/d1/database/${this.databaseId}/query`; + const res = await this.fetchImpl(url, { + method: "POST", + headers: { + authorization: `Bearer ${this.apiToken}`, + "content-type": "application/json", + }, + body: JSON.stringify({ sql, params }), + }); + + let body: D1QueryResponse; + try { + body = (await res.json()) as D1QueryResponse; + } catch { + throw new Error(`D1 API returned ${res.status} with a non-JSON body`); + } + + if (!res.ok || body.success === false) { + const detail = (body.errors ?? []) + .map((e) => `${e.code ?? ""} ${e.message ?? ""}`.trim()) + .filter(Boolean) + .join("; "); + throw new Error(`D1 API error (${res.status}): ${detail || "unknown error"}`); + } + + return body.result?.[0]?.results ?? []; + } + + /** Split a migration file into statements on top-level semicolons, leaving + * semicolons inside string literals and `--` comments alone. */ + static splitStatements(sql: string): string[] { + const out: string[] = []; + let buf = ""; + let inString = false; + let inComment = false; + for (let i = 0; i < sql.length; i += 1) { + const ch = sql[i]!; + const next = sql[i + 1]; + if (inComment) { + buf += ch; + if (ch === "\n") inComment = false; + continue; + } + if (!inString && ch === "-" && next === "-") { + inComment = true; + buf += ch; + continue; + } + if (ch === "'") { + inString = !inString; + buf += ch; + continue; + } + if (ch === ";" && !inString) { + if (buf.trim()) out.push(buf.trim()); + buf = ""; + continue; + } + buf += ch; + } + if (buf.trim()) out.push(buf.trim()); + // Drop chunks that are only comments/whitespace. + return out.filter((s) => + s.split("\n").some((line) => line.trim() && !line.trim().startsWith("--")), + ); + } + + async connect(): Promise { + // The ledger and the lock table are the runner's own bookkeeping, created + // before the first migration so an empty database is not a special case. + await this.query( + `CREATE TABLE IF NOT EXISTS _migrations_applied ( + id TEXT PRIMARY KEY, + context TEXT NOT NULL, + checksum TEXT NOT NULL, + applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + applied_by TEXT NOT NULL DEFAULT 'migration-runner' + )`, + ); + await this.query( + `CREATE TABLE IF NOT EXISTS _migrations_lock ( + id TEXT PRIMARY KEY, + acquired_at TEXT NOT NULL + )`, + ); + } + + async disconnect(): Promise { + // Stateless HTTP — nothing to close. + } + + /** + * D1 has no advisory locks, so the mutex is a row: the winner is whoever + * inserts it. A row older than LOCK_STALE_MS belongs to a runner that died, + * and is reclaimed — the applied-ledger makes that safe, since a reclaiming + * runner re-reads what actually landed rather than assuming. + */ + async acquireAdvisoryLock(lockId: number): Promise { + const id = `migrate-${lockId}`; + const stale = new Date(Date.now() - LOCK_STALE_MS).toISOString(); + await this.query(`DELETE FROM _migrations_lock WHERE id = ? AND acquired_at < ?`, [ + id, + stale, + ]); + try { + await this.query(`INSERT INTO _migrations_lock (id, acquired_at) VALUES (?, ?)`, [ + id, + new Date().toISOString(), + ]); + } catch (err) { + if (/(UNIQUE|PRIMARY KEY) constraint failed/i.test(String(err))) return false; + throw err; + } + this.lockId = id; + return true; + } + + async releaseAdvisoryLock(lockId: number): Promise { + const id = this.lockId ?? `migrate-${lockId}`; + await this.query(`DELETE FROM _migrations_lock WHERE id = ?`, [id]); + this.lockId = null; + } + + async getAppliedMigrations(): Promise { + const rows = await this.query( + `SELECT id, context, checksum, applied_at FROM _migrations_applied ORDER BY id`, + ); + return rows.map((r) => ({ + id: String(r.id), + context: String(r.context), + checksum: String(r.checksum), + applied_at: String(r.applied_at), + })); + } + + // D1 exposes no interactive transaction over the REST API: a migration is + // applied statement by statement and a failure part-way leaves the earlier + // statements in place. That is survivable here — and only here — because + // every migration is written idempotently (IF NOT EXISTS) and the ledger row + // is written last, so a failed migration is simply re-attempted in full on + // the next run. The no-ops keep the MigrationAdapter contract honest rather + // than pretending a rollback happened. + async beginTransaction(): Promise {} + async commitTransaction(): Promise {} + async rollbackTransaction(): Promise {} + + async executeSql(sql: string): Promise { + const statements = D1ApiAdapter.splitStatements(sql); + for (const statement of statements) { + try { + await this.query(statement); + } catch (err) { + const head = statement.split("\n").slice(0, 3).join(" ").slice(0, 200); + throw new Error(`${err instanceof Error ? err.message : String(err)} — at: ${head}`); + } + } + } + + async recordMigration(entry: MigrationEntry): Promise { + await this.query( + `INSERT INTO _migrations_applied (id, context, checksum, applied_at, applied_by) + VALUES (?, ?, ?, ?, 'db-migrate') + ON CONFLICT (id) DO UPDATE SET checksum = excluded.checksum, + applied_at = excluded.applied_at`, + [entry.id, entry.context, entry.checksum, new Date().toISOString()], + ); + } +} diff --git a/packages/db/src/runner/index.ts b/packages/db/src/runner/index.ts new file mode 100644 index 0000000..b6f53c6 --- /dev/null +++ b/packages/db/src/runner/index.ts @@ -0,0 +1,5 @@ +export type { MigrationAdapter, AppliedMigration, RunnerConfig, RunMode, MigrationPlan, MigrationResult } from "./types.js"; +export { runMigrations, buildPlan } from "./runner.js"; +export { D1ApiAdapter } from "./d1-api-adapter.js"; +export { loadD1CredentialsFromEnv } from "./secrets.js"; +export type { D1Credentials } from "./secrets.js"; diff --git a/packages/db/src/runner/runner.ts b/packages/db/src/runner/runner.ts new file mode 100644 index 0000000..9574ca9 --- /dev/null +++ b/packages/db/src/runner/runner.ts @@ -0,0 +1,140 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { MigrationEntry, MigrationManifest } from "../types.js"; +import type { + MigrationPlan, + MigrationResult, + RunnerConfig, +} from "./types.js"; + +const ADVISORY_LOCK_ID = 839_201_008; + +function computeChecksum(filePath: string): string { + const content = readFileSync(filePath); + return createHash("sha256").update(content).digest("hex"); +} + +export function buildPlan( + manifest: MigrationManifest, + appliedMap: Map, + migrationsDir: string, +): MigrationPlan { + const alreadyApplied: string[] = []; + const pending: MigrationEntry[] = []; + const checksumMismatches: MigrationPlan["checksumMismatches"] = []; + + for (const entry of manifest.migrations) { + const appliedChecksum = appliedMap.get(entry.id); + + if (appliedChecksum !== undefined) { + alreadyApplied.push(entry.id); + + const fileChecksum = computeChecksum( + resolve(migrationsDir, entry.path), + ); + + if (appliedChecksum !== fileChecksum || appliedChecksum !== entry.checksum) { + checksumMismatches.push({ + id: entry.id, + expected: appliedChecksum, + actual: fileChecksum, + }); + } + } else { + pending.push(entry); + } + } + + return { alreadyApplied, pending, checksumMismatches }; +} + +export async function runMigrations( + manifest: MigrationManifest, + config: RunnerConfig, +): Promise { + const { adapter, mode, migrationsDir } = config; + const result: MigrationResult = { applied: [], skipped: [], failed: null }; + + // Offline plan: verify checksums then report all migrations as pending. + if (mode === "plan" && adapter === null) { + for (const entry of manifest.migrations) { + const filePath = resolve(migrationsDir, entry.path); + const fileChecksum = computeChecksum(filePath); + if (fileChecksum !== entry.checksum) { + throw new Error( + `Checksum mismatch for ${entry.id}: manifest says ${entry.checksum}, file has ${fileChecksum}`, + ); + } + } + result.applied = manifest.migrations.map((m) => m.id); + return result; + } + + if (!adapter) { + throw new Error("adapter is required for apply mode"); + } + + await adapter.connect(); + + try { + const locked = await adapter.acquireAdvisoryLock(ADVISORY_LOCK_ID); + if (!locked) { + throw new Error( + "Could not acquire migration advisory lock — another runner may be active", + ); + } + + try { + const appliedRows = await adapter.getAppliedMigrations(); + const appliedMap = new Map(appliedRows.map((r) => [r.id, r.checksum])); + + const plan = buildPlan(manifest, appliedMap, migrationsDir); + + if (plan.checksumMismatches.length > 0) { + const ids = plan.checksumMismatches.map((m) => m.id).join(", "); + throw new Error( + `Checksum mismatch for already-applied migrations: ${ids}`, + ); + } + + result.skipped = plan.alreadyApplied; + + if (mode === "plan") { + result.applied = plan.pending.map((m) => m.id); + return result; + } + + for (const entry of plan.pending) { + const sqlPath = resolve(migrationsDir, entry.path); + const sql = readFileSync(sqlPath, "utf-8"); + const fileChecksum = computeChecksum(sqlPath); + + if (fileChecksum !== entry.checksum) { + throw new Error( + `Checksum mismatch for ${entry.id}: manifest says ${entry.checksum}, file has ${fileChecksum}`, + ); + } + + await adapter.beginTransaction(); + try { + await adapter.executeSql(sql); + await adapter.recordMigration(entry); + await adapter.commitTransaction(); + result.applied.push(entry.id); + } catch (err: unknown) { + await adapter.rollbackTransaction(); + const message = err instanceof Error ? err.message : String(err); + result.failed = { id: entry.id, error: message }; + return result; + } + } + } finally { + await adapter.releaseAdvisoryLock(ADVISORY_LOCK_ID); + } + } finally { + await adapter.disconnect(); + } + + return result; +} diff --git a/packages/db/src/runner/secrets.ts b/packages/db/src/runner/secrets.ts new file mode 100644 index 0000000..1d7698a --- /dev/null +++ b/packages/db/src/runner/secrets.ts @@ -0,0 +1,58 @@ +// D1 credentials from the ENVIRONMENT. +// +// The `cloudflare-d1` terraform component publishes its outputs to the +// workspace's project/env secret rung (the composition's wire-secrets step), +// and orun resolves the keys this runner declares in its component `secretEnv` +// into the job env. Nothing is read from a file, a cloud secret store, or an +// ambient CI value. +// +// Two shapes are accepted for the database id, because the wiring layer speaks +// documents and an operator running this by hand speaks variables: +// - WIRING_CLOUDFLARE_D1 — the component's JSON wiring document +// - D1_DATABASE_ID — the flat override + +export interface D1Credentials { + accountId: string; + databaseId: string; + apiToken: string; +} + +function requireEnv(name: string): string { + const value = process.env[name]?.trim(); + if (!value) { + throw new Error( + `${name} is not set — declare it in the component's secretEnv ` + + `(wired from the cloudflare-d1 component's outputs)`, + ); + } + return value; +} + +/** Pull the database id out of the wiring document, if one is present. */ +function databaseIdFromWiring(): string | null { + const raw = process.env["WIRING_CLOUDFLARE_D1"]?.trim(); + if (!raw) return null; + let doc: Record; + try { + doc = JSON.parse(raw) as Record; + } catch { + throw new Error("WIRING_CLOUDFLARE_D1 is set but is not valid JSON"); + } + const id = doc["d1_database_id"]; + return typeof id === "string" && id.length > 0 ? id : null; +} + +export function loadD1CredentialsFromEnv(): D1Credentials { + const databaseId = process.env["D1_DATABASE_ID"]?.trim() || databaseIdFromWiring(); + if (!databaseId) { + throw new Error( + "No D1 database id — set D1_DATABASE_ID, or wire WIRING_CLOUDFLARE_D1 " + + "from the cloudflare-d1 component", + ); + } + return { + accountId: requireEnv("CLOUDFLARE_ACCOUNT_ID"), + databaseId, + apiToken: requireEnv("CLOUDFLARE_API_TOKEN"), + }; +} diff --git a/packages/db/src/runner/types.ts b/packages/db/src/runner/types.ts new file mode 100644 index 0000000..849d74a --- /dev/null +++ b/packages/db/src/runner/types.ts @@ -0,0 +1,41 @@ +import type { MigrationEntry } from "../types.js"; + +export interface AppliedMigration { + id: string; + context: string; + checksum: string; + applied_at: string; +} + +export interface MigrationAdapter { + connect(): Promise; + disconnect(): Promise; + acquireAdvisoryLock(lockId: number): Promise; + releaseAdvisoryLock(lockId: number): Promise; + getAppliedMigrations(): Promise; + beginTransaction(): Promise; + commitTransaction(): Promise; + rollbackTransaction(): Promise; + executeSql(sql: string): Promise; + recordMigration(entry: MigrationEntry): Promise; +} + +export type RunMode = "plan" | "apply"; + +export interface RunnerConfig { + mode: RunMode; + migrationsDir: string; + adapter: MigrationAdapter | null; +} + +export interface MigrationPlan { + alreadyApplied: string[]; + pending: MigrationEntry[]; + checksumMismatches: Array<{ id: string; expected: string; actual: string }>; +} + +export interface MigrationResult { + applied: string[]; + skipped: string[]; + failed: { id: string; error: string } | null; +} diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts new file mode 100644 index 0000000..1d7c212 --- /dev/null +++ b/packages/db/src/types.ts @@ -0,0 +1,20 @@ +// The migration manifest's shape. A "context" names the slice of the schema +// a migration belongs to: `control` is the runner's own tracking schema, +// `app` is the status page's. Add contexts here when the product grows bounded +// contexts of its own. +export const BOUNDED_CONTEXTS = ["control", "app"] as const; + +export type BoundedContext = (typeof BOUNDED_CONTEXTS)[number]; + +export interface MigrationEntry { + id: string; + context: BoundedContext; + path: string; + checksum: string; + description: string; +} + +export interface MigrationManifest { + version: 1; + migrations: MigrationEntry[]; +} diff --git a/packages/db/tsconfig.build.json b/packages/db/tsconfig.build.json new file mode 100644 index 0000000..c6fb252 --- /dev/null +++ b/packages/db/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + } +} diff --git a/packages/db/tsconfig.json b/packages/db/tsconfig.json new file mode 100644 index 0000000..5a609a8 --- /dev/null +++ b/packages/db/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 32621eb..de0bcfd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -118,6 +118,42 @@ importers: specifier: ^4.151.0 version: 4.155.0(@cloudflare/workers-types@4.20260702.1)(@types/node@22.20.5) + packages/db: + devDependencies: + '@app/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@app/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/node': + specifier: ^22.9.0 + version: 22.20.5 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + tests/db: + devDependencies: + '@app/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@app/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@saas/db': + specifier: workspace:* + version: link:../../packages/db + '@types/node': + specifier: ^22.9.0 + version: 22.20.5 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.7(@types/node@22.20.5)(sugarss@5.0.2(postcss@8.5.32))(terser@5.36.0)(yaml@2.9.1) + tests/web: devDependencies: '@app/eslint-config': diff --git a/specs/epics/uptimeflare/IMPLEMENTATION-STATUS.md b/specs/epics/uptimeflare/IMPLEMENTATION-STATUS.md index 8eedaa1..0bf0ef6 100644 --- a/specs/epics/uptimeflare/IMPLEMENTATION-STATUS.md +++ b/specs/epics/uptimeflare/IMPLEMENTATION-STATUS.md @@ -5,7 +5,7 @@ As built, kept apart from the plan. | Milestone | State | Pull request | |---|---|---| | UF0 — the spec | ✅ shipped | [#1](https://github.com/sourceplane/uptimeflare/pull/1) | -| UF1 — the monitor on Workers | ✅ this pull request | UF1 | -| UF2 — the D1 database and its schema | planned | — | +| UF1 — the monitor on Workers | ✅ shipped | [#2](https://github.com/sourceplane/uptimeflare/pull/2) | +| UF2 — the D1 database and its schema | ✅ this pull request | UF2 | | UF3 — ready to instantiate | planned | — | | UF4 — a baseline | planned | — | diff --git a/specs/epics/uptimeflare/README.md b/specs/epics/uptimeflare/README.md index 66592bc..05d3a12 100644 --- a/specs/epics/uptimeflare/README.md +++ b/specs/epics/uptimeflare/README.md @@ -8,7 +8,7 @@ The port keeps the status page, the incident history, the latency charts, the ba | Field | Value | |-------|-------| -| Status | UF0 shipped (#1); UF1 in review | +| Status | UF0–UF1 shipped (#1, #2); UF2 in review | | Cluster | **UF** (UF0–UF4) | | Owner(s) | `apps/web` (the status page, `worker.ts`, `monitor/`, `uptime.config.ts`) · `tests/web` · `infra/terraform/cloudflare-d1` · `packages/db` + `infra/db-migrate` · `tests/db` | | Builds on | `cron-starter` (one OpenNext Worker with a `scheduled` handler on its own Cron Trigger), `turso-starter` (the `cloudflare-d1` root, the D1 migration runner and `db-migrate`), `cirrus-baseline` (the `@@wiring(...)@@` deploy-time render) | diff --git a/tests/db/component.yaml b/tests/db/component.yaml new file mode 100644 index 0000000..3a21f2b --- /dev/null +++ b/tests/db/component.yaml @@ -0,0 +1,23 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-tests + description: The monitor state migrations' tests (each migration applied through the runner into a real SQLite), run on every pull request +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: tests + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: test diff --git a/tests/db/eslint.config.js b/tests/db/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/tests/db/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/tests/db/package.json b/tests/db/package.json new file mode 100644 index 0000000..95ebe5b --- /dev/null +++ b/tests/db/package.json @@ -0,0 +1,20 @@ +{ + "name": "@app/db-tests", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "tsc --noEmit", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "lint": "eslint src" + }, + "devDependencies": { + "@app/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@saas/db": "workspace:*", + "@types/node": "^22.9.0", + "typescript": "^5.8.3", + "vitest": "^3.2.4" + } +} diff --git a/tests/db/src/migrations.test.ts b/tests/db/src/migrations.test.ts new file mode 100644 index 0000000..b6a3d4f --- /dev/null +++ b/tests/db/src/migrations.test.ts @@ -0,0 +1,218 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import * as path from "node:path"; +import { manifest } from "@saas/db/manifest"; +import { D1ApiAdapter, loadD1CredentialsFromEnv, runMigrations } from "@saas/db/runner"; +import type { MigrationManifest } from "@saas/db/types"; + +const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations"); + +// node:sqlite is real SQLite — D1's engine — so the migrations run here +// against the database semantics they meet in production. Loaded through +// require: it is newer than the bundler's list of Node built-ins. +type Row = Record; +interface Sqlite { + prepare(sql: string): { all(...params: unknown[]): Row[] }; +} +const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite") as { + DatabaseSync: new (file: string) => Sqlite; +}; + +// A stand-in for D1's REST API (`POST …/d1/database/{id}/query`, one statement +// per call, `{ sql, params }` in, `{ success, result: [{ results }] }` out), +// over a real SQLite database: the adapter is exercised through the same +// request and response shapes the db-migrate lane sends to Cloudflare. +function fakeD1(db: Sqlite) { + const requests: { url: string; auth: string | null; sql: string }[] = []; + const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => { + const { sql, params } = JSON.parse(String(init?.body)) as { sql: string; params: unknown[] }; + requests.push({ url: String(input), auth: new Headers(init?.headers).get("authorization"), sql }); + try { + const results = db.prepare(sql).all(...params); + return new Response(JSON.stringify({ success: true, result: [{ results, success: true }] }), { status: 200 }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + return new Response(JSON.stringify({ success: false, errors: [{ code: 7500, message }] }), { status: 400 }); + } + }) as typeof fetch; + return { fetchImpl, requests }; +} + +function tables(db: Sqlite): string[] { + return db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name") + .all() + .map((r) => String(r.name)); +} + +describe("the migration manifest (packages/db)", () => { + it("starts with the control migration, in id order, and names every file with its checksum", () => { + const ids = manifest.migrations.map((m) => m.id); + expect(ids[0]).toBe("000_control_baseline"); + expect([...ids].sort()).toEqual(ids); + expect(new Set(ids).size).toBe(ids.length); + for (const entry of manifest.migrations) { + const file = readFileSync(path.join(migrationsDir, entry.path)); + expect(createHash("sha256").update(file).digest("hex"), entry.id).toBe(entry.checksum); + } + }); + + it("creates upstream's key/value table, under its own name, idempotently", () => { + const sql = readFileSync(path.join(migrationsDir, "010_monitor_state/up.sql"), "utf8"); + expect(sql.replace(/\s+/g, " ")).toContain( + "CREATE TABLE IF NOT EXISTS monitor_state ( key VARCHAR(255) PRIMARY KEY, value BLOB NOT NULL );", + ); + }); + + it("plans every migration as pending offline (a pull request's plan profile)", async () => { + const result = await runMigrations(manifest, { mode: "plan", migrationsDir, adapter: null }); + expect(result.failed).toBeNull(); + expect(result.applied).toEqual(manifest.migrations.map((m) => m.id)); + }); + + it("refuses a file that no longer matches its checksum, even offline", async () => { + const tampered: MigrationManifest = { + version: 1, + migrations: manifest.migrations.map((m, i) => (i === 1 ? { ...m, checksum: "0".repeat(64) } : m)), + }; + await expect(runMigrations(tampered, { mode: "plan", migrationsDir, adapter: null })).rejects.toThrow( + /Checksum mismatch for 010_monitor_state/, + ); + }); +}); + +describe("db-migrate apply, over the D1 REST API, into real SQLite", () => { + let db: Sqlite; + beforeEach(() => { + db = new DatabaseSync(":memory:"); + }); + + it("creates the schema the page reads and writes, and records what it applied", async () => { + const { fetchImpl, requests } = fakeD1(db); + const adapter = new D1ApiAdapter("acct", "db-id", "token", fetchImpl); + const result = await runMigrations(manifest, { mode: "apply", migrationsDir, adapter }); + expect(result.failed).toBeNull(); + expect(result.applied).toEqual(["000_control_baseline", "010_monitor_state"]); + expect(tables(db)).toEqual(["_migrations_applied", "_migrations_lock", "monitor_state"]); + expect(db.prepare("SELECT id FROM _migrations_applied ORDER BY id").all().map((r) => r.id)).toEqual([ + "000_control_baseline", + "010_monitor_state", + ]); + // The lock is released, and every call was the account's database with the token. + expect(db.prepare("SELECT * FROM _migrations_lock").all()).toEqual([]); + expect(new Set(requests.map((r) => r.url))).toEqual( + new Set(["https://api.cloudflare.com/client/v4/accounts/acct/d1/database/db-id/query"]), + ); + expect(new Set(requests.map((r) => r.auth))).toEqual(new Set(["Bearer token"])); + + // The checker's and the page's own statements (apps/web/monitor/store.ts) + // on that schema: the upsert the checker writes the state with, twice, and + // the read the page and the API make. + const upsert = + "INSERT INTO monitor_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value;"; + db.prepare(upsert).all("state", '{"lastUpdate":1}'); + db.prepare(upsert).all("state", '{"lastUpdate":2}'); + expect(db.prepare("SELECT value FROM monitor_state WHERE key = ?").all("state").map((r) => r.value)).toEqual([ + '{"lastUpdate":2}', + ]); + }); + + it("applies nothing twice: a second run skips what the ledger recorded", async () => { + const { fetchImpl } = fakeD1(db); + const adapter = new D1ApiAdapter("acct", "db-id", "token", fetchImpl); + await runMigrations(manifest, { mode: "apply", migrationsDir, adapter }); + db.prepare("INSERT INTO monitor_state (key, value) VALUES (?, ?)").all("state", "kept"); + const again = await runMigrations(manifest, { mode: "apply", migrationsDir, adapter }); + expect(again.applied).toEqual([]); + expect(again.skipped).toEqual(["000_control_baseline", "010_monitor_state"]); + expect(db.prepare("SELECT value FROM monitor_state").all().map((r) => r.value)).toEqual(["kept"]); + }); + + it("takes a table a hand-run init (the app's old init.sql) created as already there", async () => { + db.prepare("CREATE TABLE monitor_state (key VARCHAR(255) PRIMARY KEY, value BLOB NOT NULL)").all(); + db.prepare("INSERT INTO monitor_state (key, value) VALUES (?, ?)").all("state", "from before"); + const { fetchImpl } = fakeD1(db); + const result = await runMigrations(manifest, { + mode: "apply", + migrationsDir, + adapter: new D1ApiAdapter("acct", "db-id", "token", fetchImpl), + }); + expect(result.failed).toBeNull(); + expect(db.prepare("SELECT value FROM monitor_state").all().map((r) => r.value)).toEqual(["from before"]); + }); + + it("refuses to run while another runner holds the lock", async () => { + const { fetchImpl } = fakeD1(db); + const adapter = new D1ApiAdapter("acct", "db-id", "token", fetchImpl); + await adapter.connect(); + db.prepare("INSERT INTO _migrations_lock (id, acquired_at) VALUES (?, ?)").all( + "migrate-839201008", + new Date().toISOString(), + ); + await expect(runMigrations(manifest, { mode: "apply", migrationsDir, adapter })).rejects.toThrow( + /advisory lock/, + ); + expect(tables(db)).not.toContain("monitor_state"); + }); + + it("refuses an applied migration whose file has since changed", async () => { + const { fetchImpl } = fakeD1(db); + const adapter = new D1ApiAdapter("acct", "db-id", "token", fetchImpl); + await runMigrations(manifest, { mode: "apply", migrationsDir, adapter }); + db.prepare("UPDATE _migrations_applied SET checksum = ? WHERE id = ?").all("f".repeat(64), "010_monitor_state"); + await expect(runMigrations(manifest, { mode: "apply", migrationsDir, adapter })).rejects.toThrow( + /Checksum mismatch for already-applied migrations: 010_monitor_state/, + ); + }); + + it("names the statement D1 refused", async () => { + const { fetchImpl } = fakeD1(db); + const adapter = new D1ApiAdapter("acct", "db-id", "token", fetchImpl); + await adapter.connect(); + await expect(adapter.executeSql("CREATE TABLE ok(x);\nINSERT INTO nope VALUES (1);")).rejects.toThrow( + /no such table: nope — at: INSERT INTO nope/, + ); + }); +}); + +describe("D1ApiAdapter.splitStatements", () => { + it("splits on top-level semicolons only, and drops comment-only chunks", () => { + const sql = "-- a comment; with a semicolon\nCREATE TABLE a(x TEXT DEFAULT 'a;b');\n-- trailing; note\nINSERT INTO a VALUES ('it''s');\n"; + expect(D1ApiAdapter.splitStatements(sql)).toEqual([ + "-- a comment; with a semicolon\nCREATE TABLE a(x TEXT DEFAULT 'a;b')", + "-- trailing; note\nINSERT INTO a VALUES ('it''s')", + ]); + }); +}); + +describe("the runner's environment (what the component's secretEnv resolves)", () => { + const saved = { ...process.env }; + afterEach(() => { + process.env = { ...saved }; + }); + + it("reads the database id from the cloudflare-d1 wiring document", () => { + process.env.CLOUDFLARE_ACCOUNT_ID = "acct"; + process.env.CLOUDFLARE_API_TOKEN = "token"; + delete process.env.D1_DATABASE_ID; + process.env.WIRING_CLOUDFLARE_D1 = JSON.stringify({ d1_database_id: "uuid-1", d1_database_name: "stg-x-stage" }); + expect(loadD1CredentialsFromEnv()).toEqual({ accountId: "acct", databaseId: "uuid-1", apiToken: "token" }); + }); + + it("refuses to guess without a database id", () => { + process.env.CLOUDFLARE_ACCOUNT_ID = "acct"; + process.env.CLOUDFLARE_API_TOKEN = "token"; + delete process.env.D1_DATABASE_ID; + delete process.env.WIRING_CLOUDFLARE_D1; + expect(() => loadD1CredentialsFromEnv()).toThrow(/No D1 database id/); + }); + + it("sends to CLOUDFLARE_API_BASE_URL when it is set, as wrangler does", async () => { + process.env.CLOUDFLARE_API_BASE_URL = "http://127.0.0.1:9/client/v4/"; + const { fetchImpl, requests } = fakeD1(new DatabaseSync(":memory:")); + await new D1ApiAdapter("acct", "db-id", "token", fetchImpl).connect(); + expect(requests[0]?.url).toBe("http://127.0.0.1:9/client/v4/accounts/acct/d1/database/db-id/query"); + }); +}); diff --git a/tests/db/tsconfig.json b/tests/db/tsconfig.json new file mode 100644 index 0000000..47d9ecc --- /dev/null +++ b/tests/db/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "composite": false, + "declaration": false, + "declarationMap": false, + "noEmit": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/tests/db/vitest.config.ts b/tests/db/vitest.config.ts new file mode 100644 index 0000000..ce36a74 --- /dev/null +++ b/tests/db/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["src/**/*.test.ts"], + environment: "node", + }, +}); diff --git a/tests/web/src/config.test.ts b/tests/web/src/config.test.ts index 428d42e..a1d6e58 100644 --- a/tests/web/src/config.test.ts +++ b/tests/web/src/config.test.ts @@ -47,6 +47,20 @@ describe("CVE-2026-29779: the page hands the browser only what it shows", () => }); }); +describe("the schema the checker and the page share", () => { + it("is the table the migrations create (packages/db, 010_monitor_state)", async () => { + const { MONITOR_STATE_DDL } = await import("./d1"); + const sql = readFileSync(path.resolve(app, "../../packages/db/src/migrations/010_monitor_state/up.sql"), "utf8") + .replace(/^--.*$/gm, "") + .replace(/\s+/g, " ") + .replace(/\( /g, "(") + .replace(/ \)/g, ")") + .replace(/;\s*$/, "") + .trim(); + expect(sql).toBe(MONITOR_STATE_DDL); + }); +}); + describe("one Worker: the page and the checker", () => { it("enters through worker.ts, which adds the checker's scheduled handler to OpenNext's fetch", () => { const tpl = jsonc(read("wrangler.template.jsonc"));