diff --git a/README.md b/README.md index 2c1b240e..c5cac1f3 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ export const migrateProd = Op({ overview: "Apply the pending migrations to prod, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-prod", { plan: digest })]), + phase("Approve", [gate("approve-migrate-prod", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply prod --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/docs/approval.md b/docs/approval.md index 6ded3d4d..0b24de5b 100644 --- a/docs/approval.md +++ b/docs/approval.md @@ -27,7 +27,7 @@ export const migrateDev = Op({ overview: "Apply the pending migrations to dev, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-dev", { plan: digest })]), + phase("Approve", [gate("approve-migrate-dev", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply dev --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); @@ -39,8 +39,26 @@ export const migrateDev = Op({ The digest is checked twice: by the gate on every run, against the approval, and by the Apply step under the lock, against the digest the gate passed, so a change between the two (another runner applying first, a table altered out of band) refuses too. +The gate's `resume: true` (chant 0.124.26 or later, [chant#3947](https://github.com/INTENTIUS/chant/issues/3947)) starts the run after an approval at the gate instead of the first phase. A run that stops at the gate stores a checkpoint of the step outputs the later steps read, here the Plan step's digest, and `yodel approve` copies the checkpoint's digest onto the approval. The next `yodel apply` runs the Plan step again, as chant always does for the step a gate's plan names, then carries on from the gate when the plan, the commit and the checkpoint match what was approved (`decideGateResume`, `op/gate-checkpoint.ts:266` in chant 0.124.46). chant prints `[resume] at gate "approve-migrate-dev", from run 's checkpoint `, and `yodel apply --json` reports the same three under `resumed`. The Plan step is the only step before the gate, so the resumed run runs the same steps as a fresh one; what it adds is the record of which gated run it continued. When a check fails, such as a commit landing between the two runs, the run starts at the first phase, says why on a `[resume]` line, and the approval still passes the gate. + `yodel apply` finds the Op by its shape, whatever its name. When there is none it prints this declaration to add; when more than one applies the environment, `--op ` picks one; an Op whose gate is not bound to the Plan step's output is refused. `chant run migrate-dev` run directly (as CI may) needs `yodel` on `PATH`; `yodel apply` puts itself there for the Op it runs. The declarative path's `ApplyOp` carries its own plan-bound gate ([The two workflows](workflows.md)). +### Renaming the gate + +The approvals on `chant/lifecycle` are recorded under the Op's name and the gate's. A gate that is renamed, or moved into another Op, lists its old name in `aliases`, so an approval already given still counts ([chant#3949](https://github.com/INTENTIUS/chant/issues/3949)): + +```ts +phase("Approve", [gate("approve-dev", { plan: digest, resume: true, aliases: [{ gate: "approve-migrate-dev" }] })]), +``` + +Leave `op` out of the alias when the gate stays in its Op, or name the old one: `{ op: "migrate-dev-legacy", gate: "approve" }`. An approval of the old name counts at the renamed gate when it answers the old gate's newest pending fact, that fact has not expired, and the approval is for this run's plan digest. The run then writes it again under the new name, with `carriedFrom` naming the line it came from, and prints a `[carried]` line. `yodel apply --execute` counts the carried line only while the gate still lists that alias, which is how chant's gate reads it (`op/gate.ts:815` in chant 0.124.46, `src/versioned/approval.ts`). A carried approval does not resume the run at the gate, since its approver saw the old gate's checkpoint: the run starts at the first phase and the carried approval passes the gate when it gets there. `yodel approve` always records an approval under the gate's current name. chant's OPS017 refuses an alias that is still a gate in some Op of the build. + +### A quorum at the base commit + +A gate that needs more than one approver declares `identity.gates..quorum` in `chant.workspace.json` (chant#4324). chant reads that entry at the base commit, and its quorum replaces the Op's own `approval.quorum`, so a pull request cannot lower the quorum its own apply needs. `yodel apply --execute` counts the gate the same way, with chant's `tallyGateApprovals` over the rules at base and the roles `.chant/trust.json` at base gives a sealed approver (`src/versioned/approval.ts`). It passes when every rule is met, and otherwise refuses with exit 3 and what is still missing. + +A quorum that only the Op declares, with none at base, is refused: the Op is part of the change being applied, so yodel counts nothing from it. Declare the quorum under `identity.gates` on the base branch, or run `yodel apply` without `--execute` and leave the count to the gate step. An approval `policy` is also refused under `--execute`, since only the gate step evaluates one. The Op runs with no environment, so a rule with `targets` does not cover it, as in chant's gate step. An approval carried from an alias still counts through the alias rule above, but a quorum split between old and new gate names is not added up here; approve under the current name. + ## The plan digest On the versioned path the digest covers what the run would do and the state it would start from: diff --git a/docs/audit.md b/docs/audit.md index d0488d1f..9f12ad11 100644 --- a/docs/audit.md +++ b/docs/audit.md @@ -70,7 +70,7 @@ Cross-check: prod vs staging schema: sha256:4f0c... vs sha256:4f0c... — same build ``` -The component is the project's directory in its repository, or `schema` for a project at the root. A tenant is recorded on its environment's ledger as `/`. The record also names the commit, the CI run, who ran it and, when a gate approved it, who approved it. The apply prints a `release:` line on stderr saying what it recorded. +The component is the project's directory in its repository, or `schema` for a project at the root. A tenant is recorded on its environment's ledger as `/`. The record also names the commit, the CI run, who ran it and, when a gate approved it, who approved it (`approver`) and which resolution did (`admission`: the `op`, the `gate` and when it was resolved, from chant's `admissionOf` in `src/versioned/approval.ts`). An apply made from a chant release, `yodel apply --release ` (or `YODEL_RELEASE`), also writes `releaseDigest`; the checkout must be at the commit the release was cut at, and any other apply writes none. An ungated apply writes no `approver` and no `admission`. Records already on the ledger are never rewritten, and a reader takes each of these fields as optional. The apply prints a `release:` line on stderr saying what it recorded. The schema is already applied when the record is written, so a record that cannot be written is a `release:` line, not a failed run. That happens when the project is not in a git repository, when the `chant/lifecycle` branch cannot be fetched or has forked from the remote's, or when an out-of-order apply leaves the environment at a schema no migration recorded. The history table stays the record of what ran. The release ledger only says which schema each environment reached. diff --git a/docs/configuration.md b/docs/configuration.md index de1c26fa..85308da9 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -10,7 +10,7 @@ type: reference `@intentius/sql-yodeler` is on npm. It needs Node 22.12 or later, and the project also needs chant and the `sql` lexicon, which `chant.config.ts` and the declarations import: ```sh -npm install @intentius/sql-yodeler @intentius/chant@0.124.25 @intentius/chant-lexicon-sql@0.124.25 +npm install @intentius/sql-yodeler @intentius/chant@0.124.48 @intentius/chant-lexicon-sql@0.124.48 npx yodel --version ``` @@ -237,6 +237,7 @@ yodel plan: yodel.config.ts sets environments.dev.topology to cluster:main, but | `YODEL_LOCK_TTL` | `yodel apply`, `yodel init`, `yodel repair` on ClickHouse | the lock's TTL in seconds | | `YODEL_LOCK_WAIT` | `yodel apply` | how long to wait for a lock another apply holds, as `--lock-wait` (`10m`); `yodel apply` hands its `--lock-wait` to the Op's Apply step this way | | `YODEL_STAND_DOWN` | `yodel apply` | `1`: as `--stand-down`, apply nothing and exit 0 when the run's branch has a newer commit on `origin` | +| `YODEL_RELEASE` | `yodel apply` | a chant release's digest or label: as `--release`, the apply is made from that release, and its release record names it (`releaseDigest`) | | `YODEL_LOCK_RETRIES` | `yodel apply` on Postgres | how many more times a statement that hit `lock_timeout` is tried (default 5, the pause doubling from 250 ms) | | `GITHUB_TOKEN`, `GITLAB_TOKEN`, `FORGEJO_TOKEN` (each after `CHANT__TOKEN`; `GH_TOKEN` on GitHub and Forgejo) | `yodel plan --comment`, `yodel drift --issue` | the forge token; see [Approval](approval.md) and [Drift](drift.md#the-tracking-issue) | diff --git a/docs/drift.md b/docs/drift.md index c351d0a7..86ac96e2 100644 --- a/docs/drift.md +++ b/docs/drift.md @@ -93,6 +93,18 @@ Op "watch-dev" completed in 1.8s The starter templates render a scheduled pipeline per watch for each forge (`npm run ci` writes them from `ops/`): a GitHub Actions or Forgejo Actions workflow on the watch's cron, and a GitLab CI job run by a pipeline schedule you create with the cron the file notes (GitLab keeps no cron in the file). The job reads with the reader's credentials and never pushes: its snapshot and run record stay in the job. Its token writes only issues: GitHub's job token gets `issues: write`, Forgejo's can write already, and GitLab uses `GITLAB_TOKEN`, the project access token the plan comment uses. +### When the watch stops running + +A scheduled job can stop with no error anywhere. GitHub turns a scheduled workflow off after 60 days with no activity in the repository, and on GitLab the job runs only from a pipeline schedule someone created. `yodel plan --comment` asks the forge when the environment's watch job last ran, and when the watch's cron has fired at least twice since, the comment carries a warning ([chant#4289](https://github.com/INTENTIUS/chant/issues/4289)), and the job log the same line: + +``` +Warning: Op `watch-dev` is overdue: its schedule `17 * * * *` has fired at least twice and its last run was on 2026-10-18. GitHub turns a scheduled workflow off after 60 days with no activity in the repository. Turn the workflow on again under Actions, or run it by hand. +``` + +The watch is the `WatchOp` whose `env` is the environment, and the job is the file `npm run ci` rendered for it: `.github/workflows/watch-.yml`, `.forgejo/workflows/watch-.yml`, or the job in `.gitlab/yodel-watch.gitlab-ci.yml` whose rules select it (`src/pr/overdue.ts`). A watch with no rendered file is not checked. With no run on record, the count starts at the commit that added the file. chant gives the verdict (`overdueVerdict`, `op/schedule-overdue.ts:107` in chant 0.124.46), so one late or dropped run is not a warning. + +The warning never fails the plan. A forge that does not answer is a line in the job log and no warning. On GitHub the plan job reads the workflow's runs with `actions: read`, which the rendered `yodel-pr.yml` asks for; run `npm run ci` to add it to pipelines rendered before. + ## The tracking issue `yodel drift --issue` keeps one issue for the project and environment on the forge, found again by a marker in its body (``, where `` is the project's directory in its repository, `.` at the root): diff --git a/docs/kubernetes.md b/docs/kubernetes.md index 520889e0..2c046651 100644 --- a/docs/kubernetes.md +++ b/docs/kubernetes.md @@ -49,7 +49,7 @@ spec: volumeMounts: [{ name: project, mountPath: /work }] containers: - name: apply - image: ghcr.io/intentius/sql-yodeler:0.9.0@sha256: + image: ghcr.io/intentius/sql-yodeler:0.10.0@sha256: workingDir: /work command: ["yodel", "apply", "prod", "--lock-wait", "10m"] env: diff --git a/docs/lint.md b/docs/lint.md index be6521be..de669893 100644 --- a/docs/lint.md +++ b/docs/lint.md @@ -115,6 +115,8 @@ SQLCH126 the check's level, silenceable, clickhouse schema check: A GRANT column list names a column the table does not declare SQLCH127 the check's level, silenceable, clickhouse schema check: An expression calls a function the pinned server does not have +SQLCH128 the check's level, silenceable, clickhouse + schema check: An integration engine or table function argument holds a literal credential ``` `fork`, `directory`, `checksum`, `unreadable-object` and `checkpoint` are integrity rules: always errors. `unreadable-object` means an object in a recorded schema, or a step, that the `sql` lexicon cannot read or classify; it is never skipped. `destructive`, `pg-rewrite`, `pg-lock`, `ch-mutation` and `ch-rebuild` come from the classifier's class of each statement or step, and can be silenced one statement at a time. The `pg-` and `ch-` rules apply to their own dialect. diff --git a/docs/migrations.md b/docs/migrations.md index 175d589a..d0fbbdc1 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -46,7 +46,7 @@ No changes: the declared schema matches the newest migration's recorded schema ( (From the Postgres example's run, just after it writes `rename-email`; `run.ts postgres --write` rewrites this quote with the README. The committed-example check in `examples/walkthrough/run.ts` runs `yodel new check` in each example, so a declared schema that drifts from its migrations fails the e2e test.) -It refuses (exit 1) when the directory is not one chain (a fork, a missing parent) or a migration of that id is already there. `yodel new --sql` writes a migration you write yourself ([below](#hand-written-migrations)). `yodel new --backfill` ends the migration with a backfill step written from `backfills/.json` ([Data migrations](steps.md#backfills)), and `--retain ` keeps the old column of a Postgres rename, or the old table of a rebuild, that long after the switch ([Data migrations](steps.md#postgres-postgresmigrationop)). +It refuses (exit 1) when the directory is not one chain (a fork, a missing parent) or a migration of that id is already there. `yodel new --sql` writes a migration you write yourself ([below](#hand-written-migrations)). `yodel new --backfill` ends the migration with a backfill step written from `backfills/.json` ([Data migrations](steps.md#backfills)), `--orm-handoff :` ends the migration with a step that marks an ORM's own migration applied ([Schema from an ORM](orm.md#handing-a-hard-change-to-the-orm)), and `--retain ` keeps the old column of a Postgres rename, or the old table of a rebuild, that long after the switch ([Data migrations](steps.md#postgres-postgresmigrationop)). ## Hand-written migrations diff --git a/docs/orm.md b/docs/orm.md index 884c52d4..b10237ab 100644 --- a/docs/orm.md +++ b/docs/orm.md @@ -88,6 +88,72 @@ yodel plan: each object has one owner, and app.customers is declared twice: by s The same holds when `src/` exports the object under another name: yodel reads each built object's name and refuses the build when a source creates it too. +## Drizzle for queries, chant for the schema + +The sections above read the ORM's schema into declarations. For Drizzle on Postgres the other direction works too: the declarations in `src/` own the schema, and chant writes the Drizzle module the application queries with. A select over it has the row type the declaration gives, and the plan, the approval and the apply stay yodel's. + +```bash +npx chant sql drizzle --output app/db/schema.ts +``` + +The command builds the project as `chant build` does and writes `pgTable`, `pgEnum`, `pgSequence` and view declarations, with the foreign keys, indexes and constraints named as Postgres names them. The file starts with chant's generated-file marker. Commit it, and import it where the application imports its Drizzle schema today. Your app keeps Drizzle and never imports yodel. + +Then stop running Drizzle's migrations: + +- Remove `drizzle-kit push` and `drizzle-kit migrate` from scripts, CI and the deploy. Tables change through `yodel new`, `yodel plan` and `yodel apply`, or through a `PostgresMigrationOp` for a hard change. +- Run `npx chant sql drizzle --check --output app/db/schema.ts` in CI. It exits 1, naming the file, when `src/` declares something the file does not. +- In a chant workspace, list the file as a `generated` entry of the member, so `chant workspace check --generated` fails on a stale file ([In a chant workspace](workspace.md)): + +```json +{ + "name": "db", + "dir": "db", + "kind": "chant", + "generated": [ + { "path": "app/db/schema.ts", "generator": "chant sql drizzle --output app/db/schema.ts", "sources": ["db/src"] } + ] +} +``` + +Use one direction per table. If a Drizzle `drizzle-kit export` source (above) declares `app.orders`, the export of the same table would write what that source already owns, and a table declared in `src/` and by a source is a build error ([One owner per object](#one-owner-per-object)). Pick the source for tables Drizzle owns, and the export for tables `src/` owns. + +The module is checked against drizzle-orm 0.45.4. `bigint` columns are `number` by default, as `drizzle-kit pull` writes them, and `--bigint bigint` reads them as `bigint`. Routines, triggers, extensions, grants and the other objects Drizzle has no declaration for are listed in the file's header and left out; chant's [Drizzle Schema Export](https://intentius.io/chant/lexicons/sql/drizzle/) page has the full list and the mapping. + +## Handing a hard change to the ORM + +An ORM is weakest at the hard change: a column rename that must not break readers, a type change across kinds, a large backfill. For those, run the change as a `PostgresMigrationOp` ([Data migrations](steps.md#postgres-postgresmigrationop)), change the ORM's schema file to the final state, and write the ORM's own migration for the same change. An `orm-handoff` step at the end of the yodel migration then marks that ORM migration as applied, so the ORM does not run it a second time. + +```bash +npx yodel new rename-login --orm-handoff prisma:20261009120000_rename_login +npx yodel new rename-login --orm-handoff rails:20261009120000 +``` + +The step is the migration's last, so it runs after the Op, under the migration's lock and gate. Its options are in the migration's checksum and the plan digest, and its hash is the `statement_sha` of its history row, as for any step (`stepSha` in `src/steps/kinds.ts`). It is for Postgres. `--orm-handoff` and `--backfill` both end a migration, so give one. + +Before the migration's first statement, apply refuses the whole migration, with exit 4 and nothing sent, when: + +- the ORM migration is not in the repository: for Prisma, `prisma/migrations//migration.sql`; for Rails, a file `db/migrate/_*.rb` (`ormMigrationFile` in `src/steps/orm-handoff.ts`); +- the ORM already records it as applied: for Prisma, a row of `_prisma_migrations` with this `migration_name` and `finished_at` set; for Rails, a row of `schema_migrations` with this `version`. + +The check runs first because a refusal after the Op would leave the change made and the ORM about to make it again. A migration that stopped between the ORM's record and yodel's own history row is refused on its rerun by the second check; once you have confirmed the ORM's row, take the step out of `migration.json` and record the edit with `yodel repair --reason ... `. + +| ORM | What the step does | Options | +|---|---|---| +| Prisma | runs `npx --no-install prisma migrate resolve --applied ` in the project directory, then reads `_prisma_migrations` to confirm the row is on this environment's server | `dir` (default `prisma/migrations`), `schema`, `config` (passed as `--schema` and `--config`), `dbSchema` (the schema holding `_prisma_migrations`, default `public`) | +| Rails | creates `schema_migrations` if it is missing, then inserts the version | `dir` (default `db/migrate`), `table` (default `schema_migrations`), `dbSchema` (default `public`) | + +### Why the Prisma CLI and not a row + +Both are possible, because `prisma migrate resolve --applied` writes one row to `_prisma_migrations`. yodel runs the command. The schema engine's `mark_migration_applied` (prisma-engines, `schema-engine/commands/src/commands/mark_migration_applied.rs`) refuses a migration that is not in the migrations directory or is already finished, checks the provider in `migration_lock.toml`, takes the migrations table's lock, and creates the table when the database has none. It records the SHA-256 of `migration.sql` as the row's `checksum` (`schema-connector/src/checksum.rs`), which `migrate deploy` compares on every run. A row yodel wrote itself would have to copy each of those and follow them when Prisma changes them. The cost is that the CLI must be installed in the project and must reach the same database as the environment, through the project's own datasource (`prisma.config.ts` or `DATABASE_URL`). yodel checks that after the command: if `_prisma_migrations` on the environment's server has no finished row for the migration, the step fails and says the datasource points elsewhere. Prisma's reference page for `migrate resolve` says the command is for a failed migration, but the source above also records one that has no row, which is what baselining relies on ([baselining](https://www.prisma.io/docs/orm/prisma-migrate/workflows/baselining)). + +### Why Rails gets a row + +Rails has no command that records a migration without running it: `db:migrate` runs the app's Ruby. What Rails itself writes for a migration it ran is one row, the version as a string in the `version` column (`ActiveRecord::SchemaMigration#create_version`, `activerecord/lib/active_record/schema_migration.rb`), and `db:migrate` skips every version already in the table (`pending_migrations` in `activerecord/lib/active_record/migration.rb`). The file name's leading digits are the version (`MigrationFilenameRegexp`), which is what the `migration` option holds. The table Rails creates has one column, `version`, a string primary key and no `id`. + +### Other ORMs + +The step takes `prisma` and `rails` only; any other `orm` value is refused with the list it does. The marks for the others are `migrate --fake` for Django, `alembic stamp ` for Alembic, and a row in `__drizzle_migrations` for Drizzle. They are not built. + ## Proof The `declarative` claim runs a project whose `yodel.config.ts` has a source whose command prints a Prisma-style DDL file (the claim installs no ORM): the first apply creates the ORM's tables behind the gate, a column added to the model is the one change `yodel plan` shows, the approved apply adds it, and the plan is then empty. Under `BREAK=1` the DDL changes again after the approval, and the column is not applied. diff --git a/docs/workspace.md b/docs/workspace.md index cf2e133e..73defd03 100644 --- a/docs/workspace.md +++ b/docs/workspace.md @@ -15,7 +15,7 @@ This needs chant 0.124.23 or later (INTENTIUS/chant#3931, #3932 and #3941). { "name": "shop", "schema": 1, - "pins": [{ "package": "@intentius/chant-lexicon-sql", "version": "0.124.25" }], + "pins": [{ "package": "@intentius/chant-lexicon-sql", "version": "0.124.48" }], "members": [ { "name": "db", "dir": "db", "kind": "chant" }, { diff --git a/examples/clickhouse/README.md b/examples/clickhouse/README.md index bd438d10..d71a3d74 100644 --- a/examples/clickhouse/README.md +++ b/examples/clickhouse/README.md @@ -302,7 +302,7 @@ export const migrateDev = Op({ overview: "Apply the pending migrations to dev, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-dev", { plan: digest })]), + phase("Approve", [gate("approve-migrate-dev", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply dev --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/examples/clickhouse/ops/migrate-dev.op.ts b/examples/clickhouse/ops/migrate-dev.op.ts index d2fe1484..bcdddfdb 100644 --- a/examples/clickhouse/ops/migrate-dev.op.ts +++ b/examples/clickhouse/ops/migrate-dev.op.ts @@ -12,7 +12,7 @@ export const migrateDev = Op({ overview: "Apply the pending migrations to dev, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-dev", { plan: digest })]), + phase("Approve", [gate("approve-migrate-dev", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply dev --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/examples/clickhouse/package.json b/examples/clickhouse/package.json index 04fa3e0f..eb38337d 100644 --- a/examples/clickhouse/package.json +++ b/examples/clickhouse/package.json @@ -10,8 +10,8 @@ "build": "chant build src --lexicon sql -o dist/schema.json" }, "dependencies": { - "@intentius/chant": "0.124.25", - "@intentius/chant-lexicon-sql": "0.124.25", + "@intentius/chant": "0.124.48", + "@intentius/chant-lexicon-sql": "0.124.48", "@intentius/sql-yodeler": "file:../.." }, "devDependencies": { diff --git a/examples/postgres/README.md b/examples/postgres/README.md index 89b45898..c2cb6eb8 100644 --- a/examples/postgres/README.md +++ b/examples/postgres/README.md @@ -307,7 +307,7 @@ export const migrateDev = Op({ overview: "Apply the pending migrations to dev, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-dev", { plan: digest })]), + phase("Approve", [gate("approve-migrate-dev", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply dev --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/examples/postgres/ops/migrate-dev.op.ts b/examples/postgres/ops/migrate-dev.op.ts index d2fe1484..bcdddfdb 100644 --- a/examples/postgres/ops/migrate-dev.op.ts +++ b/examples/postgres/ops/migrate-dev.op.ts @@ -12,7 +12,7 @@ export const migrateDev = Op({ overview: "Apply the pending migrations to dev, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-dev", { plan: digest })]), + phase("Approve", [gate("approve-migrate-dev", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply dev --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/examples/postgres/package.json b/examples/postgres/package.json index f210957b..9e434cdb 100644 --- a/examples/postgres/package.json +++ b/examples/postgres/package.json @@ -10,8 +10,8 @@ "build": "chant build src --lexicon sql -o dist/schema.json" }, "dependencies": { - "@intentius/chant": "0.124.25", - "@intentius/chant-lexicon-sql": "0.124.25", + "@intentius/chant": "0.124.48", + "@intentius/chant-lexicon-sql": "0.124.48", "@intentius/sql-yodeler": "file:../.." }, "devDependencies": { diff --git a/package-lock.json b/package-lock.json index 389bca9c..c492c6ac 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,19 +1,19 @@ { "name": "@intentius/sql-yodeler", - "version": "0.9.0", + "version": "0.10.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@intentius/sql-yodeler", - "version": "0.9.0", + "version": "0.10.0", "license": "Apache-2.0", "dependencies": { - "@intentius/chant": "^0.124.25", - "@intentius/chant-lexicon-forgejo": "^0.124.25", - "@intentius/chant-lexicon-github": "^0.124.25", - "@intentius/chant-lexicon-gitlab": "^0.124.25", - "@intentius/chant-lexicon-sql": "^0.124.25", + "@intentius/chant": "^0.124.48", + "@intentius/chant-lexicon-forgejo": "^0.124.48", + "@intentius/chant-lexicon-github": "^0.124.48", + "@intentius/chant-lexicon-gitlab": "^0.124.48", + "@intentius/chant-lexicon-sql": "^0.124.48", "tsx": "^4.23.15" }, "bin": { @@ -21,7 +21,7 @@ }, "devDependencies": { "@eslint/js": "^10.0.1", - "@intentius/chant-lexicon-docker": "^0.124.25", + "@intentius/chant-lexicon-docker": "^0.124.48", "@types/node": "^22.20.5", "@types/pg": "^8.23.1", "ajv": "^8.20.0", @@ -647,9 +647,9 @@ } }, "node_modules/@intentius/chant": { - "version": "0.124.25", - "resolved": "https://registry.npmjs.org/@intentius/chant/-/chant-0.124.25.tgz", - "integrity": "sha512-Fm14CmtViUjZEPMSdpNQQztqTyxb7+bqAipuKCTov7WJ3jVqFPepymlg72U8PtaVu05V7vGH21t6heiHxanxlA==", + "version": "0.124.48", + "resolved": "https://registry.npmjs.org/@intentius/chant/-/chant-0.124.48.tgz", + "integrity": "sha512-JhaR35Q9CD5UyxTUOBOVFbadAJtPgCaGU17YoFSnl85fBi3aWNtNsYxZRkc0dNsjcV0/yKOeASd5CrD49iBM+A==", "license": "Apache-2.0", "dependencies": { "@dagrejs/dagre": "^3.0.0", @@ -676,46 +676,46 @@ } }, "node_modules/@intentius/chant-lexicon-docker": { - "version": "0.124.25", - "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-docker/-/chant-lexicon-docker-0.124.25.tgz", - "integrity": "sha512-n6GQ6kAsx+x2C+b4Q2ngISeLtJa48caE9ovdmfjgKqSz6SzF4qIHRqXC7nOcehUPqwOqWsHgOXFekD/JzR/lBQ==", + "version": "0.124.48", + "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-docker/-/chant-lexicon-docker-0.124.48.tgz", + "integrity": "sha512-GQ4+hJ0kAEYYCr7vHOHIiOp9hTJV/3rHLYlZ3Vt3mVDVK6BJgrQMvTrYmpmLHaulfCCM3I1nz9pnrUIKGv9gNw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@intentius/chant-lexicon-otel": "^0.124.25" + "@intentius/chant-lexicon-otel": "^0.124.48" }, "peerDependencies": { - "@intentius/chant": "^0.124.25" + "@intentius/chant": "^0.124.48" } }, "node_modules/@intentius/chant-lexicon-forgejo": { - "version": "0.124.25", - "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-forgejo/-/chant-lexicon-forgejo-0.124.25.tgz", - "integrity": "sha512-Z88ou/G/y/UrplRIDK9zKz96DlS6tgQbLvc36Njsw9/T9N9Phxjjr2qY2dLuMuzYgVx8XErWvz7nvhDbzqt9tQ==", + "version": "0.124.48", + "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-forgejo/-/chant-lexicon-forgejo-0.124.48.tgz", + "integrity": "sha512-LhasDQVv7LwNWHnzE8Y57uPLsj7L6WxvSkyIwGBQWPHEYFCp2Ku5d3m9iVBQNrqh+vri+KC4aCL48ZEe2i1r2g==", "license": "Apache-2.0", "peerDependencies": { - "@intentius/chant": "^0.124.25", - "@intentius/chant-lexicon-github": "^0.124.25", + "@intentius/chant": "^0.124.48", + "@intentius/chant-lexicon-github": "^0.124.48", "zod": "^4.3.6" } }, "node_modules/@intentius/chant-lexicon-github": { - "version": "0.124.25", - "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-github/-/chant-lexicon-github-0.124.25.tgz", - "integrity": "sha512-memhQV++i7DZPwd/HNtA4AuydVJ14STYv+Itoe5Fv81Jcwepk9IYK7LuEOYJtxgLGPpObhkXJdWEPQT8KkmvIg==", + "version": "0.124.48", + "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-github/-/chant-lexicon-github-0.124.48.tgz", + "integrity": "sha512-1pJJ01tm4v70W90fddnIeT21nUJHk+BreT3S3RnkcN1Y4wiXK6XzbQegAsZEEboadWapJxxye2+XlM8keB8+SQ==", "license": "Apache-2.0", "peerDependencies": { - "@intentius/chant": "^0.124.25" + "@intentius/chant": "^0.124.48" } }, "node_modules/@intentius/chant-lexicon-gitlab": { - "version": "0.124.25", - "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-gitlab/-/chant-lexicon-gitlab-0.124.25.tgz", - "integrity": "sha512-OsK3SVjNoB85ZC/HFhZ1ywH3mQQC/hIBpgtvBKf2pEbgQc85/kxvRGLCli+4GERgrB8zq1qryj9p2b9frvzx2w==", + "version": "0.124.48", + "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-gitlab/-/chant-lexicon-gitlab-0.124.48.tgz", + "integrity": "sha512-nQL1J1Qs1AEuqLWwKDBzw4ThuFUuaSPyNQKVbqN8yj4jsogbbzd45cW0bERBYcJ6urAYSHm1zKH6PDCJJCRubQ==", "license": "Apache-2.0", "peerDependencies": { - "@intentius/chant": "^0.124.25", - "@intentius/chant-lexicon-github": "^0.124.25" + "@intentius/chant": "^0.124.48", + "@intentius/chant-lexicon-github": "^0.124.48" }, "peerDependenciesMeta": { "@intentius/chant-lexicon-github": { @@ -724,9 +724,9 @@ } }, "node_modules/@intentius/chant-lexicon-otel": { - "version": "0.124.25", - "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-otel/-/chant-lexicon-otel-0.124.25.tgz", - "integrity": "sha512-CJ0BHv7ZpUs/3Eza/WSVFIqJmjLwBJdK1PnLW8AVpIUM197MhaHDZetF1x0DGcMhPIHiwDkfdUKP4xhusVWZPQ==", + "version": "0.124.48", + "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-otel/-/chant-lexicon-otel-0.124.48.tgz", + "integrity": "sha512-RX/b+Y8VRJypLPmZh2JCWZuC3C0E252jZCbm0hZtY9CBfwPv1yMTeQFflsTqoH9MQco/aescfz8En9VER8kl2Q==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -734,20 +734,20 @@ "zod": "^4.3.6" }, "peerDependencies": { - "@intentius/chant": "^0.124.25" + "@intentius/chant": "^0.124.48" } }, "node_modules/@intentius/chant-lexicon-sql": { - "version": "0.124.25", - "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-sql/-/chant-lexicon-sql-0.124.25.tgz", - "integrity": "sha512-rJKMaajDaFD3gaQOfD8K5q3au4kuxRAhHiXbj/Jm3W9canh8GtCkgxSE88CWIS8i/wXMGDjCEf7ugs6ODJ4uLw==", + "version": "0.124.48", + "resolved": "https://registry.npmjs.org/@intentius/chant-lexicon-sql/-/chant-lexicon-sql-0.124.48.tgz", + "integrity": "sha512-cC+8y5ncfvw7MMLHkfJZo4+V8IOPD9wUPDu0wv2qGfHJNFdUnNtLJCarpZTdBCya8+Z+00ZGMhrj//mbsdcprQ==", "license": "Apache-2.0", "dependencies": { "pg": "^8.23.1", "zod": "^4.3.6" }, "peerDependencies": { - "@intentius/chant": "^0.124.25" + "@intentius/chant": "^0.124.48" } }, "node_modules/@jridgewell/resolve-uri": { diff --git a/package.json b/package.json index 96fb5c57..d9a6a912 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@intentius/sql-yodeler", - "version": "0.9.0", + "version": "0.10.0", "description": "Schema changes for ClickHouse and Postgres, and the ops they imply, on chant's sql lexicon", "keywords": [ "clickhouse", @@ -58,16 +58,16 @@ "grant": "tsx scripts/grant.ts" }, "dependencies": { - "@intentius/chant": "^0.124.25", - "@intentius/chant-lexicon-forgejo": "^0.124.25", - "@intentius/chant-lexicon-github": "^0.124.25", - "@intentius/chant-lexicon-gitlab": "^0.124.25", - "@intentius/chant-lexicon-sql": "^0.124.25", + "@intentius/chant": "^0.124.48", + "@intentius/chant-lexicon-forgejo": "^0.124.48", + "@intentius/chant-lexicon-github": "^0.124.48", + "@intentius/chant-lexicon-gitlab": "^0.124.48", + "@intentius/chant-lexicon-sql": "^0.124.48", "tsx": "^4.23.15" }, "devDependencies": { "@eslint/js": "^10.0.1", - "@intentius/chant-lexicon-docker": "^0.124.25", + "@intentius/chant-lexicon-docker": "^0.124.48", "@types/node": "^22.20.5", "@types/pg": "^8.23.1", "ajv": "^8.20.0", diff --git a/schemas/apply.schema.json b/schemas/apply.schema.json index 6b4a4702..0976bf7c 100644 --- a/schemas/apply.schema.json +++ b/schemas/apply.schema.json @@ -188,6 +188,30 @@ "appliedNow": { "description": "applied: the migrations this run applied.", "$ref": "common.schema.json#/$defs/stringList" + }, + "resumed": { + "description": "applied: the run started at the approved gate (a gate with resume: true, chant#3947) rather than at the first phase.", + "type": "object", + "additionalProperties": false, + "required": [ + "gate", + "run", + "checkpoint" + ], + "properties": { + "gate": { + "description": "The gate the run resumed at.", + "type": "string" + }, + "run": { + "description": "The run that stopped at the gate, whose checkpoint this run read.", + "type": "string" + }, + "checkpoint": { + "description": "The checkpoint's digest, the one the approval copied.", + "type": "string" + } + } } } }, diff --git a/src/chant/apply.ts b/src/chant/apply.ts index 1a60d0da..a2f23dd0 100644 --- a/src/chant/apply.ts +++ b/src/chant/apply.ts @@ -137,6 +137,8 @@ export interface ApplyRun { output: string; /** The exit code of the Op's Apply step (`yodel apply --execute`), when it ran. */ stepExit?: number; + /** The run started at an approved gate (chant#3947): the gate, the run that stopped there, and its checkpoint's digest. */ + resumed?: { gate: string; run: string; checkpoint: string }; } /** What a `chant run` of an ApplyOp says about its outcome. */ @@ -144,7 +146,10 @@ export function readApplyRun(code: number, output: string): ApplyRun { const status: ApplyRunStatus = code === 0 ? "applied" : code === GATED ? "gated" : "failed"; const chantApprove = /^\s*approve\s*:\s*(chant approve .+?)\s*$/m.exec(output)?.[1]; const planDigest = /^\s*plan\s*:\s*(\S+)\s*$/m.exec(output)?.[1]; - return { status, code, ...(chantApprove ? { chantApprove } : {}), ...(planDigest ? { planDigest } : {}), output }; + // chant's renderHuman (op/local-output.ts:33 in 0.124.46) opens a resumed run with this line. + const r = /^\[resume\] at gate "([^"]+)", from run (\S+)'s checkpoint (\S+)\s*$/m.exec(output); + const resumed = r ? { gate: r[1] ?? "", run: r[2] ?? "", checkpoint: r[3] ?? "" } : undefined; + return { status, code, ...(chantApprove ? { chantApprove } : {}), ...(planDigest ? { planDigest } : {}), ...(resumed ? { resumed } : {}), output }; } /** diff --git a/src/check/flyway.ts b/src/check/flyway.ts index 668c8302..8e6b962a 100644 --- a/src/check/flyway.ts +++ b/src/check/flyway.ts @@ -1,5 +1,5 @@ /** - * A Flyway project as `yodel check` reads it (#250): its `flyway.toml` or + * A Flyway project as `yodel check` reads it (#250, #4400): its `flyway.toml` or * `flyway.conf`, the locations it names, read recursively, and the * placeholders it substitutes. * @@ -24,10 +24,19 @@ * Flyway's own run would be. */ -import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; -import { basename, dirname, join, relative, resolve, sep } from "node:path"; +import { basename, isAbsolute, relative, resolve, sep } from "node:path"; +import * as layout from "@intentius/chant/workspace/flyway-layout"; +import { workingTree, type WorkspaceTree } from "@intentius/chant/workspace/tree"; import { YodelError } from "../project.js"; +/* + * The reading itself is chant's `workspace/flyway-layout`, the one the + * workspace's Flyway kind uses (#4400). This file keeps yodel's view of it: + * absolute file system paths in, absolute paths out, and a YodelError where + * chant throws a FlywayPlaceholderError. The tree is rooted at `/`, so a + * location outside the project (`filesystem:../shared`) still reads. + */ + export interface FlywayConfig { /** The configuration file, absolute; undefined with none. */ file?: string; @@ -54,233 +63,82 @@ export interface FlywayConfig { environment?: string; } +const fsRoot = (): WorkspaceTree => workingTree(sep); +const toTree = (abs: string): string => resolve(abs).split(sep).filter(Boolean).join("/"); +const toAbs = (p: string): string => resolve(sep, ...p.split("/")); + +/** chant's configuration for each of ours, to hand back to chant's `substitute`. */ +const layouts = new WeakMap(); + /** The first `flyway.toml`, else `flyway.conf`, in `dir` or a directory above it up to `stopAt`. */ export function findFlywayConfig(dir: string, stopAt?: string): string | undefined { + const at = resolve(dir); const top = stopAt === undefined ? undefined : resolve(stopAt); - let at = resolve(dir); - for (;;) { - for (const name of ["flyway.toml", "flyway.conf"]) { - const f = join(at, name); - if (existsSync(f) && statSync(f).isFile()) return f; - } - const up = dirname(at); - if (at === top || up === at || (top !== undefined && !`${at}${sep}`.startsWith(`${top}${sep}`))) return undefined; - at = up; - } -} - -type Values = Record; - -/** Java-properties `flyway.*` keys, without the `flyway.` prefix. */ -export function parseFlywayConf(text: string): Values { - const out: Values = {}; - const lines = text.split(/\r?\n/); - for (let i = 0; i < lines.length; i++) { - let line = lines[i] ?? ""; - while (/\\$/.test(line) && i + 1 < lines.length) line = line.slice(0, -1) + (lines[++i] ?? "").trimStart(); - const t = line.trim(); - if (t === "" || t.startsWith("#") || t.startsWith("!")) continue; - const m = /^([^=:\s]+)\s*[=:]\s*(.*)$/.exec(t); - if (!m) continue; - const key = m[1] ?? ""; - if (!key.startsWith("flyway.")) continue; - out[key.slice("flyway.".length)] = (m[2] ?? "").trim(); - } - return out; -} - -/** A TOML document, as far as Flyway's configuration uses it: tables, strings, arrays of strings, booleans and numbers. */ -export function parseToml(text: string): Record { - const tables: Record = { "": {} }; - let current = ""; - const lines = text.split(/\r?\n/); - for (let i = 0; i < lines.length; i++) { - const t = stripComment(lines[i] ?? "").trim(); - if (t === "") continue; - const table = /^\[\s*([^\]]+?)\s*\]$/.exec(t); - if (table) { - current = (table[1] ?? "").split(".").map((k) => unquote(k.trim())).join("."); - tables[current] ??= {}; - continue; - } - const kv = /^("[^"]*"|'[^']*'|[A-Za-z0-9_.:-]+)\s*=\s*(.*)$/.exec(t); - if (!kv) continue; - let raw = kv[2] ?? ""; - // A multi-line array runs to its closing bracket. - while (raw.trimStart().startsWith("[") && !balanced(raw) && i + 1 < lines.length) raw += ` ${stripComment(lines[++i] ?? "").trim()}`; - const path = unquote(kv[1] ?? "").split("."); - const key = path.pop() ?? ""; - const where = [current, ...path].filter(Boolean).join("."); - tables[where] ??= {}; - tables[where][key] = tomlValue(raw.trim()); - } - return tables; -} - -function stripComment(line: string): string { - let quote: string | undefined; - for (let i = 0; i < line.length; i++) { - const c = line[i]; - if (quote) { - if (c === "\\" && quote === '"') i++; - else if (c === quote) quote = undefined; - } else if (c === '"' || c === "'") quote = c; - else if (c === "#") return line.slice(0, i); - } - return line; + // A tree reads up to its root, so the project's directory is the root when `dir` is inside it. + const inside = top !== undefined && `${at}${sep}`.startsWith(`${top}${sep}`); + const base = inside ? top : resolve(sep); + const found = layout.findFlywayConfig(workingTree(base), toTreeUnder(base, at)); + return found === undefined ? undefined : resolve(base, ...found.split("/")); } -const balanced = (s: string) => (s.match(/\[/g) ?? []).length <= (s.match(/\]/g) ?? []).length; - -function unquote(s: string): string { - if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) return s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\"); - return s; -} - -function tomlValue(raw: string): string | string[] | boolean { - if (raw === "true" || raw === "false") return raw === "true"; - if (raw.startsWith("[")) { - const inner = raw.replace(/^\[/, "").replace(/\]\s*$/, ""); - return (inner.match(/"(?:[^"\\]|\\.)*"|'[^']*'|[^,\s]+/g) ?? []).map((v) => unquote(v.trim())).filter((v) => v !== ""); - } - return unquote(raw); -} - -const list = (v: string | string[] | boolean | undefined): string[] | undefined => - v === undefined || typeof v === "boolean" ? undefined : Array.isArray(v) ? v : v.split(",").map((s) => s.trim()).filter(Boolean); -const str = (v: string | string[] | boolean | undefined): string | undefined => (typeof v === "string" ? v : Array.isArray(v) ? v.join(",") : undefined); - -/** The database name a JDBC URL names: the path after the host. */ -function databaseOf(url: string | undefined): string | undefined { - const m = url === undefined ? null : /^jdbc:[a-z0-9]+:\/\/[^/]+\/([^?;]+)/i.exec(url); - return m?.[1] ?? undefined; +function toTreeUnder(base: string, abs: string): string { + return relative(base, abs).split(sep).filter(Boolean).join("/"); } /** The configuration `file` holds, or the defaults with `dir` as the one location when there is none. */ export function readFlywayConfig(file: string | undefined, dir: string): FlywayConfig { - let values: Values = {}; - let placeholders: Record = {}; - if (file !== undefined) { - const text = readFileSync(file, "utf8"); - if (file.endsWith(".toml")) { - const t = parseToml(text); - const flyway = t.flyway ?? {}; - const name = str(flyway.environment) ?? "default"; - const env = t[`environments.${name}`] ?? {}; - values = { ...flyway, ...(t[`environments.${name}.flyway`] ?? {}), ...(env.url !== undefined ? { url: env.url } : {}), ...(env.user !== undefined ? { user: env.user } : {}), ...(env.schemas !== undefined ? { schemas: env.schemas } : {}) }; - if (str(flyway.environment) !== undefined) values.environment = name; - placeholders = Object.fromEntries(Object.entries({ ...(t["flyway.placeholders"] ?? {}), ...(t[`environments.${name}.flyway.placeholders`] ?? {}) }).map(([k, v]) => [k, str(v) ?? String(v)])); - } else { - values = parseFlywayConf(text); - placeholders = Object.fromEntries(Object.entries(values).flatMap(([k, v]) => (k.startsWith("placeholders.") ? [[k.slice("placeholders.".length), str(v) ?? ""]] : []))); - } - } - const root = file === undefined ? resolve(dir) : dirname(file); - const named = list(values.locations) ?? []; - const locations: string[] = []; - const codeLocations: string[] = []; - for (const l of named) { - const m = /^(filesystem|classpath):(.*)$/.exec(l); - const kind = m?.[1] ?? "classpath"; - const path = (m?.[2] ?? l).replace(/^\/+/, kind === "classpath" ? "" : "/"); - if (kind === "filesystem") locations.push(resolve(root, path)); - else { - locations.push(join(root, "src", "main", "resources", path)); - codeLocations.push(join(root, "src", "main", "java", path), join(root, "src", "main", "kotlin", path)); - } - } + const c = layout.readFlywayConfig(fsRoot(), file === undefined ? undefined : toTree(file), toTree(dir)); + // Locations chant leaves out as outside the tree: only an absolute `filesystem:` path is one here, as the tree is the whole disk. + const absolute = c.outside.flatMap((l) => { + const m = /^filesystem:(.*)$/.exec(l); + return m?.[1] !== undefined && isAbsolute(m[1]) ? [resolve(m[1])] : []; + }); + const locations = [...c.locations.map(toAbs), ...absolute]; if (locations.length === 0) locations.push(resolve(dir)); - const schemas = list(values.schemas); - const replacement = values.placeholderReplacement; - const defaultSchema = str(values.defaultSchema) ?? schemas?.[0]; - const user = str(values.user); - const database = databaseOf(str(values.url)); - const environment = str(values.environment); - return { - ...(file !== undefined ? { file } : {}), - root, + const { root, codeLocations } = c; + // chant's fields this adapter replaces with absolute paths or leaves out. + const replaced = ["file", "root", "locations", "codeLocations", "outside", "url", "dialect"] as const; + const rest = Object.fromEntries(Object.entries(c).filter(([key]) => !(replaced as readonly string[]).includes(key))) as Omit; + const mine: FlywayConfig = { + ...rest, + ...(file !== undefined ? { file: resolve(file) } : {}), + root: toAbs(root), locations, - codeLocations, - placeholders, - placeholderPrefix: str(values.placeholderPrefix) ?? "${", - placeholderSuffix: str(values.placeholderSuffix) ?? "}", - placeholderReplacement: !(replacement === false || replacement === "false"), - sqlMigrationPrefix: str(values.sqlMigrationPrefix) ?? "V", - repeatableSqlMigrationPrefix: str(values.repeatableSqlMigrationPrefix) ?? "R", - baselineMigrationPrefix: str(values.baselineMigrationPrefix) ?? "B", - undoSqlMigrationPrefix: str(values.undoSqlMigrationPrefix) ?? "U", - sqlMigrationSeparator: str(values.sqlMigrationSeparator) ?? "__", - sqlMigrationSuffixes: list(values.sqlMigrationSuffixes) ?? [".sql"], - ...(defaultSchema !== undefined ? { defaultSchema } : {}), - ...(user !== undefined ? { user } : {}), - ...(database !== undefined ? { database } : {}), - table: str(values.table) ?? "flyway_schema_history", - ...(environment !== undefined ? { environment } : {}), + codeLocations: codeLocations.map(toAbs), }; + layouts.set(mine, c); + return mine; } /** Every file under `dir`, recursively, absolute, sorted; none when it does not exist. */ export function walk(dir: string): string[] { - if (!existsSync(dir) || !statSync(dir).isDirectory()) return []; - const out: string[] = []; - for (const name of readdirSync(dir).sort()) { - const p = join(dir, name); - if (statSync(p).isDirectory()) out.push(...walk(p)); - else out.push(p); - } - return out; + return layout.walk(fsRoot(), toTree(dir)).map(toAbs); } /** A Flyway SQL callback (`beforeMigrate.sql`, `afterEachMigrate__notify.sql`, ...): run around a migrate, not a migration. */ -export const isCallback = (file: string): boolean => /^(before|after)[A-Z][A-Za-z]*(__.*)?\.[A-Za-z]+$/.test(basename(file)); +export const isCallback = (file: string): boolean => layout.isCallback(basename(file)); /** The code migrations (Java, Kotlin) in `config`'s locations, relative to its root. */ export function codeMigrations(config: FlywayConfig): string[] { - const code = /\.(java|kt|class)$/; - const prefixes = [config.sqlMigrationPrefix, config.repeatableSqlMigrationPrefix, config.baselineMigrationPrefix].filter(Boolean); - const migration = (f: string) => code.test(f) && prefixes.some((p) => basename(f).startsWith(p)) && basename(f).includes(config.sqlMigrationSeparator); - return [...new Set([...config.locations, ...config.codeLocations])] - .flatMap((d) => walk(d)) - .filter(migration) - .map((f) => relative(config.root, f).split(sep).join("/")); + const c = layouts.get(config); + if (c === undefined) return []; + // Ours holds the absolute locations (with any absolute `filesystem:` ones), so the tree-relative copy takes them. + const shared: layout.FlywayConfig = { ...c, locations: config.locations.map(toTree), codeLocations: config.codeLocations.map(toTree) }; + return layout.codeMigrations(fsRoot(), shared).map((f) => relative(config.root, toAbs(f)).split(sep).join("/")); } -/** The values Flyway gives its own placeholders, for `file`. */ -function builtins(config: FlywayConfig, file: string, fallback: { defaultSchema?: string | undefined }): Record { - return { - "flyway:defaultSchema": config.defaultSchema ?? fallback.defaultSchema, - "flyway:user": config.user, - "flyway:database": config.database, - "flyway:timestamp": new Date().toISOString().replace("T", " ").replace(/\..*$/, ""), - "flyway:filename": basename(file), - "flyway:workingDirectory": process.cwd(), - "flyway:table": config.table, - "flyway:environment": config.environment, - }; -} - -const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - /** * `text` with its placeholders replaced, line by line so line numbers hold. - * A placeholder with no value is an error naming `file` and the line. + * A placeholder with no value is a YodelError naming `file` and the line. */ export function substitute(text: string, file: string, config: FlywayConfig, fallback: { defaultSchema?: string | undefined } = {}): string { - if (!config.placeholderReplacement) return text; - const values: Record = { ...builtins(config, file, fallback), ...config.placeholders }; - const lower = new Map(Object.entries(values).map(([k, v]) => [k.toLowerCase(), v])); - const pattern = new RegExp(`${escape(config.placeholderPrefix)}([A-Za-z0-9_.:-]+)${escape(config.placeholderSuffix)}`, "g"); - return text - .split("\n") - .map((line, i) => - line.replace(pattern, (whole, name: string) => { - const v = values[name] ?? lower.get(name.toLowerCase()); - if (v === undefined) { - const where = config.file === undefined ? "a flyway.toml or flyway.conf beside the migrations" : relative(process.cwd(), config.file) || config.file; - throw new YodelError(`${file}:${String(i + 1)}: no value for the placeholder ${whole}; set it in ${where} (flyway.placeholders.${name} in flyway.conf, [flyway.placeholders] in flyway.toml)`); - } - return v; - }), - ) - .join("\n"); + const c = layouts.get(config); + if (c === undefined) return text; + try { + return layout.substitute(text, file, c, fallback); + } catch (e) { + if (!(e instanceof layout.FlywayPlaceholderError)) throw e; + const where = config.file === undefined ? "a flyway.toml or flyway.conf beside the migrations" : relative(process.cwd(), config.file) || config.file; + throw new YodelError(`${e.file}:${String(e.line)}: no value for the placeholder ${e.placeholder}; set it in ${where} (flyway.placeholders.${e.name} in flyway.conf, [flyway.placeholders] in flyway.toml)`); + } } diff --git a/src/ci/render.ts b/src/ci/render.ts index 11f0dd1f..221bc6d1 100644 --- a/src/ci/render.ts +++ b/src/ci/render.ts @@ -636,7 +636,8 @@ export function actionsReview(forge: Actions, envs_: Environments): RenderedFile comment: asComment(header), name: "yodel-pr", on: { pull_request: { branches: [MAIN] } }, - permissions: new Permissions({ contents: "read", "pull-requests": "write", ...(clouds.length > 0 ? { "id-token": "write" as const } : {}) }), + // actions: read lets yodel plan --comment ask when the watch workflows last ran (chant#4289). + permissions: new Permissions({ contents: "read", "pull-requests": "write", ...(forge === "github" ? { actions: "read" as const } : {}), ...(clouds.length > 0 ? { "id-token": "write" as const } : {}) }), concurrency: new Concurrency({ group: "yodel-pr-${{ github.event.pull_request.number }}", "cancel-in-progress": true }), jobs, }); @@ -1000,6 +1001,25 @@ export async function applyPipelines(dir: string, envs: Environments): Promise # vX.Y.Z` + * (chant#4403, #4410); the `# vX.Y.Z` is a YAML comment, which parsing drops. + * Each re-emit below puts every one back on the line that names the same + * pinned ref, so the re-emitted text still matches chant's and the files keep + * the release each SHA stands for. + */ +export function withPinComments(original: string, emitted: string): string { + const comments = new Map(); + for (const [, ref, comment] of original.matchAll(/uses: (\S+@[0-9a-f]{40}) (# [^\n]*)$/gm)) { + if (ref !== undefined && comment !== undefined) comments.set(ref, comment); + } + if (comments.size === 0) return emitted; + return emitted.replace(/uses: (\S+@[0-9a-f]{40})$/gm, (line: string, ref: string) => { + const comment = comments.get(ref); + return comment ? `${line} ${comment}` : line; + }); +} + function withWaveReports(forge: Forge, yaml: string, waves: readonly Wave[], tc: Toolchain, envs: Pick = {}): string { // A wide wave's jobs are wave---decide and -share-. const envOf = (job: string) => waves.find((w, i) => new RegExp(`^wave-${String(i + 1)}-${w.env.replace(/[^A-Za-z0-9]/g, "\\$&")}(-decide|-share-\\d+)?$`).test(job))?.env; @@ -1007,7 +1027,7 @@ function withWaveReports(forge: Forge, yaml: string, waves: readonly Wave[], tc: const header = yaml.slice(0, body); const doc = parseYAMLDocument(yaml) as Record; if (forge === "gitlab") { - const emit = (d: Record) => `${header}${Object.entries(d).map(([k, v]) => emitYAMLEntry(k, v)).join("\n\n")}\n`; + const emit = (d: Record) => withPinComments(yaml, `${header}${Object.entries(d).map(([k, v]) => emitYAMLEntry(k, v)).join("\n\n")}\n`); if (emit(doc) !== yaml) throw new Error("gitlab: the apply waves do not emit back to chant's text"); // The merge request job that records the plans a review approves (#48): the waves as after the merge. const record = doc[`${APPLY_PIPELINE}-record-plans`] as { variables?: Record; id_tokens?: unknown; script?: string[] } | undefined; @@ -1043,7 +1063,7 @@ function withWaveReports(forge: Forge, yaml: string, waves: readonly Wave[], tc: if (at < 0) throw new Error(`${forge}: the apply waves have no jobs`); const jobs = doc.jobs as Record> }>; const top = yaml.slice(0, at + 1); - const emitJobs = () => `${emitYAMLEntry("jobs", jobs)}\n`; + const emitJobs = () => withPinComments(yaml, `${emitYAMLEntry("jobs", jobs)}\n`); if (`${top}${emitJobs()}` !== yaml) throw new Error(`${forge}: the apply waves do not emit back to chant's text`); for (const [name, job] of Object.entries(jobs)) { const env = envOf(name); @@ -1070,7 +1090,7 @@ function withPlansReaders(forge: Forge, yaml: string, waves: readonly Wave[], di if (at < 0) throw new Error(`${forge}: the plans workflow has no jobs`); const doc = parseYAMLDocument(yaml) as { jobs: Record> }; const top = yaml.slice(0, at + 1); - const emitJobs = () => `${emitYAMLEntry("jobs", doc.jobs)}\n`; + const emitJobs = () => withPinComments(yaml, `${emitYAMLEntry("jobs", doc.jobs)}\n`); if (`${top}${emitJobs()}` !== yaml) throw new Error(`${forge}: the plans workflow does not emit back to chant's text`); const job = doc.jobs["record-plans"]; if (!job) throw new Error(`${forge}: the plans workflow has no record-plans job`); @@ -1170,7 +1190,7 @@ function withWatchLogin(forge: Actions, yaml: string, env: string, envs: Pick> }> }; const top = yaml.slice(0, at + 1); - const emitJobs = () => `${emitYAMLEntry("jobs", doc.jobs)}\n`; + const emitJobs = () => withPinComments(yaml, `${emitYAMLEntry("jobs", doc.jobs)}\n`); if (`${top}${emitJobs()}` !== yaml) throw new Error(`${forge}: the watch for ${env} does not emit back to chant's text`); const job = doc.jobs[`watch-${env}`]; if (!job) throw new Error(`${forge}: the watch for ${env} has no watch-${env} job`); @@ -1185,7 +1205,7 @@ function withWatchIdTokens(yaml: string, envs: Pick; - const emit = (d: Record) => `${header}${Object.entries(d).map(([k, v]) => emitYAMLEntry(k, v)).join("\n\n")}\n`; + const emit = (d: Record) => withPinComments(yaml, `${header}${Object.entries(d).map(([k, v]) => emitYAMLEntry(k, v)).join("\n\n")}\n`); if (emit(doc) !== yaml) throw new Error("gitlab: the watch file does not emit back to chant's text"); for (const env of envs.names) { const job = doc[`watch-${env}`] as { script?: string[]; variables?: Record } | undefined; diff --git a/src/commands/apply.ts b/src/commands/apply.ts index aeaff178..4655fee8 100644 --- a/src/commands/apply.ts +++ b/src/commands/apply.ts @@ -68,7 +68,7 @@ import { declarativeOverrideSource, judgeDeclarative } from "../declarative/plan import type { StandingOverride } from "@intentius/chant/override-gate"; import { BASELINE_ENV } from "../versioned/op.js"; import { baselineFromEnv, executeBaseline, planBaseline, projectBaseline } from "../init/second.js"; -import { appliedHead, recordReleaseLines } from "../release/index.js"; +import { appliedHead, recordReleaseLines, RELEASE_ENV, releaseToApply, type ReleaseFacts } from "../release/index.js"; /** When the gate's newest approval does not hold: what moved since (or that approval was asked for again), in one line. */ async function movedSinceApproval(project: Project, venv: VersionedEnv, ordered: readonly Migration[], op: MigrateOpRef, digest: string | undefined) { @@ -110,7 +110,7 @@ export type VersionedOutcome = | { status: "stood-down"; stoodDown: string; op?: string } | { status: "gated"; op: string; gate: string; moved?: NonNullable>>["moved"]; approve?: string; chantApprove?: string; gatePlanDigest?: string } | { status: "failed"; op: string; exitCode: number; chantExitCode: number; moved?: NonNullable>>["moved"]; approve?: string; chantApprove?: string } - | { status: "applied"; op: string; appliedNow: string[] }; + | { status: "applied"; op: string; appliedNow: string[]; resumed?: { gate: string; run: string; checkpoint: string } }; /** What a declarative run (the ApplyOp) did; `plan` is the plan before the run. */ export type DeclarativeOutcome = { plan: Record; policy?: RuleResult[] } & ( @@ -135,7 +135,7 @@ export function applyJson(doc: ApplyDoc): Record { return { environment: doc.environment, dialect: doc.dialect, ...(doc.server ? { server: doc.server } : {}), op: doc.op, ...doc.outcome }; } -const usage = "usage: yodel apply [--json] [--dir ] [--op ] [--allow-out-of-order] [--plan] [--lock-wait ] [--stand-down]"; +const usage = "usage: yodel apply [--json] [--dir ] [--op ] [--allow-out-of-order] [--plan] [--lock-wait ] [--stand-down] [--release ]"; const waveModes = ["wave-plan", "wave-apply", "step-sql"] as const; @@ -222,6 +222,11 @@ Options: that commit's own apply applies this environment. Asked before the lock and while waiting for it. Also YODEL_STAND_DOWN=1 + --release the apply is made from a chant release (chant release + cut), named by its digest or label: the checkout must + be at the commit the release was cut at, and the + release record names it (releaseDigest). Also + ${RELEASE_ENV}= -C, --dir the project directory (default: the working directory) The migrations Op runs two steps of its own, not for direct use: @@ -286,6 +291,10 @@ interface ApplyArgs { /** `--step-sql` and the flags with it: one SQL step, as a stage hook runs it (#206). */ stepArgv: string[] | undefined; spec: string; + /** `--release`, else ${"`"}YODEL_RELEASE${"`"}: the chant release the apply is made from, by digest or label. */ + release: string | undefined; + /** The release's digest, once {@link releaseToApply} found it for this checkout. */ + releaseDigest?: string | undefined; /** A tenant of a slot (#56): chant decided the slot, so the decision is checked for it. */ decidedAs?: { target: string; planDigest: string } | undefined; } @@ -307,6 +316,7 @@ function parseApplyArgs(args: string[]): ApplyArgs { execute: { type: "boolean" }, "lock-wait": { type: "string" }, "stand-down": { type: "boolean" }, + release: { type: "string" }, "wave-plan": { type: "string" }, "wave-apply": { type: "string" }, spec: { type: "string" }, @@ -342,6 +352,7 @@ function parseApplyArgs(args: string[]): ApplyArgs { waveApply: str("wave-apply"), stepArgv: str("step-sql") !== undefined ? ["yodel", "apply", ...args] : undefined, spec: str("spec") ?? WAVES_SPEC_FILE, + release: str("release") ?? (process.env[RELEASE_ENV] || undefined), }; } @@ -361,6 +372,8 @@ export const apply: Command = { const writes = !a.plan && !a.digest && a.wavePlan === undefined && a.stepArgv === undefined; const asReader = writes ? readerRefusal(profile, runnable(command, project.dir)) : undefined; if (asReader) throw new YodelError(asReader, EXIT_REFUSED); + // An apply made from a chant release (#277) names it; one at another commit than the release's is refused before anything runs. + if (writes && a.release !== undefined) a.releaseDigest = await releaseToApply(project.dir, a.release); try { return await applyIn(project, a, args, io); } catch (e) { @@ -489,17 +502,17 @@ async function versionedApplyWith(project: Project, env: Environment, a: ApplyAr if (!approved) throw new YodelError(`--execute records a baseline only under the plan its Op's gate approved, and ${APPROVED_PLAN_ENV} is not set; run yodel init --baseline ${env.name}`); const op = await findMigrateOp(project, env, a.op); const ledger = await migrationsLedger(project, env.name, io); - let approver: string | undefined; + let admittedBy: ReleaseFacts = {}; await executeBaseline(project, env, venv, baseline, { approvedDigest: approved, approve: async (digest) => { const by = await verifyApproval(ledger, op, digest); - approver = by.resolvedBy; + admittedBy = { approver: by.approver, admission: by.admission }; io.err(`approval: ${op.name} / ${op.gate} for ${digest}, by ${by.resolvedBy} at ${by.timestamp}\n`); }, log: (l) => { io.err(`${l}\n`); }, }); - await recordApplied(project, env, venv, ordered, io, approver); + await recordApplied(project, env, venv, ordered, io, { ...admittedBy, releaseDigest: a.releaseDigest }); io.out(`Recorded: ${baseline.id}, as ${env.name}'s baseline\n`); return 0; } @@ -515,7 +528,7 @@ async function versionedApplyWith(project: Project, env: Environment, a: ApplyAr if (!approved) throw new YodelError(`--execute reverts only the plan its Op's gate approved, and ${APPROVED_PLAN_ENV} is not set; run yodel revert ${env.name} ${revert.id}`); const op = await findMigrateOp(project, env, a.op); const ledger = await migrationsLedger(project, env.name, io); - let approver: string | undefined; + let admittedBy: ReleaseFacts = {}; // The policy over the revert (#97), as the base commit has it (#73), as yodel revert judged it before the gate. const { policy: basePolicy, note: policyNote } = await policyAtBase(project); if (policyNote) io.err(`${policyNote}\n`); @@ -526,7 +539,7 @@ async function versionedApplyWith(project: Project, env: Environment, a: ApplyAr ...(a.lockWaitMs !== undefined ? { lockWaitMs: a.lockWaitMs } : {}), approve: async (digest) => { const by = await verifyApproval(ledger, op, digest); - approver = by.resolvedBy; + admittedBy = { approver: by.approver, admission: by.admission }; io.err(`approval: ${op.name} / ${op.gate} for ${digest}, by ${by.resolvedBy} at ${by.timestamp}\n`); }, ...(basePolicy @@ -550,7 +563,7 @@ async function versionedApplyWith(project: Project, env: Environment, a: ApplyAr : {}), log: (l) => { io.err(`${l}\n`); }, }); - await recordApplied(project, env, venv, ordered, io, approver); + await recordApplied(project, env, venv, ordered, io, { ...admittedBy, releaseDigest: a.releaseDigest }); io.out(`Reverted: ${plan.migration.id}, back to ${plan.to ?? "an empty schema"}\n`); return 0; } @@ -652,7 +665,7 @@ async function versionedApplyWith(project: Project, env: Environment, a: ApplyAr }); // An apply that changed nothing ran no step, and tells chant so: a step command runs once per apply that changes the schema, not once per push (#206). await hooks.skipped(result.stoodDown ?? "nothing to apply"); - if (result.applied.length > 0) await recordApplied(project, env, venv, ordered, io, wave?.review?.approvers.join(", ")); + if (result.applied.length > 0) await recordApplied(project, env, venv, ordered, io, { approver: wave?.review?.approvers.join(", "), releaseDigest: a.releaseDigest }); if (a.json) io.out(`${JSON.stringify(applyJson({ mode: "execute", environment: env.name, planDigest: planned.migrations, wavePlanDigest: planned.planDigest, result }), null, 2)}\n`); else io.out(result.stoodDown ? `${result.stoodDown}\n` : result.applied.length === 0 ? "Nothing to apply.\n" : `Applied: ${result.applied.join(", ")}\n`); return 0; @@ -669,7 +682,7 @@ async function versionedApplyWith(project: Project, env: Environment, a: ApplyAr const steps = await stepsAtBase(project, env.name); if (steps.note) io.err(`${steps.note}\n`); let before: StepOutcome[] = []; - let approver: string | undefined; + let admittedBy: ReleaseFacts = {}; // The steps (#64) as stage hooks (#206), read at base; the Op's approval, checked under the lock before they run, lets a held one through. const hooksFile = stepsHooksFile(steps.steps, env.name, { approved: true, ...(steps.sha ? { base: steps.sha } : {}) }); const hooks = applyHooks(project, venv, env, () => hooksFile, io); @@ -684,7 +697,7 @@ async function versionedApplyWith(project: Project, env: Environment, a: ApplyAr // Under the lock: every pending migration ran first where this environment requires (exit 4 otherwise). await enforcePromotion(project, env.name, ordered, (await inspect(venv, ordered)).status.pending); const by = await verifyApproval(ledger, op, digest); - approver = by.resolvedBy; + admittedBy = { approver: by.approver, admission: by.admission }; io.err(`approval: ${op.name} / ${op.gate} for ${digest}, by ${by.resolvedBy} at ${by.timestamp}${by.signer !== undefined ? `, sealed by ${by.signer}` : ""}\n`); // The before steps (#64), under the lock: one that fails refuses; a held one is let through by the Op's approval, which every run of it asks for. before = await hooks.before(); @@ -711,7 +724,7 @@ async function versionedApplyWith(project: Project, env: Environment, a: ApplyAr } : {}), }); - if (result.applied.length > 0) await recordApplied(project, env, venv, ordered, io, approver); + if (result.applied.length > 0) await recordApplied(project, env, venv, ordered, io, { ...admittedBy, releaseDigest: a.releaseDigest }); if (a.json) io.out(`${JSON.stringify(applyJson({ mode: "execute", environment: env.name, planDigest: approved, result }), null, 2)}\n`); else io.out(result.stoodDown ? `${result.stoodDown}\n` : result.applied.length === 0 ? "Nothing to apply.\n" : `Applied: ${result.applied.join(", ")}\n`); return 0; @@ -813,6 +826,7 @@ async function versionedApplyWith(project: Project, env: Environment, a: ApplyAr ...process.env, ...(a.lockWaitMs !== undefined ? { [LOCK_WAIT_ENV]: `${String(a.lockWaitMs)}ms` } : {}), ...(a.standDown ? { [STAND_DOWN_ENV]: "1" } : {}), + ...(a.releaseDigest ? { [RELEASE_ENV]: a.releaseDigest } : {}), }; const run = await runMigrateOp(project, op, { allowOutOfOrder: a.allowOutOfOrder, env: childEnv, onOutput: (t) => { io.err(t); } }); if (run.status === "gated") { @@ -855,7 +869,7 @@ async function versionedApplyWith(project: Project, env: Environment, a: ApplyAr return emit({ status: "stood-down", stoodDown: stoodLate, op: op.name }, 0); } if (a.json) { - io.out(`${JSON.stringify(applyJson({ mode: "versioned", report: after, outcome: { status: "applied", op: op.name, appliedNow: report.status.pending.map((p) => p.id) } }), null, 2)}\n`); + io.out(`${JSON.stringify(applyJson({ mode: "versioned", report: after, outcome: { status: "applied", op: op.name, appliedNow: report.status.pending.map((p) => p.id), ...(run.resumed ? { resumed: run.resumed } : {}) } }), null, 2)}\n`); } else { io.out(`\nApplied: ${report.status.pending.map((p) => p.id).join(", ")}.\n`); } @@ -966,9 +980,9 @@ async function declarativeRun( } /** Records the schema `env` holds now on chant's release ledger (#208), told on stderr. */ -async function recordApplied(project: Project, env: Environment, venv: VersionedEnv, ordered: readonly Migration[], io: Io, approver: string | undefined): Promise { +async function recordApplied(project: Project, env: Environment, venv: VersionedEnv, ordered: readonly Migration[], io: Io, facts: ReleaseFacts): Promise { const { status } = await inspect(venv, ordered); - const lines = await recordReleaseLines(project, env, appliedHead(ordered, status)?.document.schema, approver ? { approver } : {}); + const lines = await recordReleaseLines(project, env, appliedHead(ordered, status)?.document.schema, facts); for (const line of lines) io.err(`${line}\n`); } diff --git a/src/commands/new.ts b/src/commands/new.ts index cd78afa2..ec590904 100644 --- a/src/commands/new.ts +++ b/src/commands/new.ts @@ -27,9 +27,9 @@ import { type CreatedMigration, type MigrationCheck, } from "../migrations/index.js"; -import { asBackfill, asForm, BACKFILL_FILE, backfillTemplate, describeForm, describeFormSql, formPath, formProblems, formTemplate, loadBackfill, PG_MIGRATION_OP, REBUILD_OP, TEMPLATE_MARK, type BackfillForm } from "../steps/index.js"; +import { asBackfill, asForm, BACKFILL_FILE, ormHandoffOptions, type OrmHandoffOptions, backfillTemplate, describeForm, describeFormSql, formPath, formProblems, formTemplate, loadBackfill, PG_MIGRATION_OP, REBUILD_OP, TEMPLATE_MARK, type BackfillForm } from "../steps/index.js"; -const usage = "usage: yodel new [--sql | --backfill []] [--retain ] [--check ]... [--replace [--env ]...] [--json] [--dir ]"; +const usage = "usage: yodel new [--sql | --backfill []] [--retain ] [--orm-handoff :] [--check ]... [--replace [--env ]...] [--json] [--dir ]"; const help = `${usage} @@ -90,6 +90,12 @@ Without it a Postgres step drops the old column in the same apply, right after the switch, and a rebuild keeps the old table for 7 days. To add it to a migration you just wrote, run yodel new --replace --retain 7d. +--orm-handoff : ends the migration with an orm-handoff step: +after the Op, apply marks the ORM's own migration applied, so the ORM does +not run it (docs/orm.md). is prisma, with the migration's directory +name (prisma:20261009120000_rename_login), or rails, with its version +(rails:20261009120000). It cannot be combined with --backfill. + --check adds a pre-migration check to migration.json: a read-only query that must return no rows. yodel apply runs it against the environment before the gate and again under the lock just before the migration's first @@ -112,6 +118,9 @@ Options: ${formPath("")} (or ) --retain how long a column rename or a rebuild keeps the old column or table + --orm-handoff : + end the migration with a step that marks the ORM's + migration applied (prisma or rails) --check a pre-migration check that must return no rows (repeatable; ": " names it) --replace redo the newest migration, named @@ -137,6 +146,7 @@ interface NewArgs { /** The file --backfill names; "" for the default form. */ backfill: string | undefined; retain: string | undefined; + ormHandoff: OrmHandoffOptions | undefined; replace: boolean; envs: string[]; checks: MigrationCheck[]; @@ -156,7 +166,7 @@ function parseNewArgs(args: string[]): NewArgs { args: bareBackfill(args), allowPositionals: true, strict: true, - options: { json: { type: "boolean" }, dir: { type: "string", short: "C" }, sql: { type: "boolean" }, backfill: { type: "string" }, retain: { type: "string" }, replace: { type: "boolean" }, env: { type: "string", multiple: true }, check: { type: "string", multiple: true } }, + options: { json: { type: "boolean" }, dir: { type: "string", short: "C" }, sql: { type: "boolean" }, backfill: { type: "string" }, retain: { type: "string" }, "orm-handoff": { type: "string" }, replace: { type: "boolean" }, env: { type: "string", multiple: true }, check: { type: "string", multiple: true } }, }); } catch (e) { throw new YodelError(`${e instanceof Error ? e.message : String(e)}\n${usage}`); @@ -171,8 +181,18 @@ function parseNewArgs(args: string[]): NewArgs { throw new YodelError(`--sql writes a migration you write yourself, so it takes no --backfill, --retain, --check or --replace\n${usage}`); } if (retain !== undefined && !DURATION.test(retain)) throw new YodelError(`--retain takes a duration such as 7d, 12h or 0s, got ${JSON.stringify(retain)}\n${usage}`); + const handoffArg = parsed.values["orm-handoff"]; + let ormHandoff: OrmHandoffOptions | undefined; + if (typeof handoffArg === "string") { + if (sql || parsed.values.backfill !== undefined) throw new YodelError(`--orm-handoff ends a migration the way --backfill does, and --sql writes a migration you write yourself: give one of them\n${usage}`); + const at = handoffArg.indexOf(":"); + const got = ormHandoffOptions({ orm: at < 0 ? handoffArg : handoffArg.slice(0, at), migration: at < 0 ? "" : handoffArg.slice(at + 1) }); + if ("problem" in got) throw new YodelError(`--orm-handoff takes :, such as prisma:20261009120000_rename_login or rails:20261009120000: ${got.problem}\n${usage}`); + ormHandoff = got.options; + } return { name, + ormHandoff, json: parsed.values.json === true, dir: typeof parsed.values.dir === "string" ? parsed.values.dir : process.cwd(), backfill: typeof parsed.values.backfill === "string" ? parsed.values.backfill : undefined, @@ -295,7 +315,7 @@ export const newCommand: Command = { implemented: true, run: (args, io) => guarded("new", io, args, help, async () => { - const { name, json, dir, backfill: backfillArg, retain, replace, envs, checks, sql } = parseNewArgs(args); + const { name, json, dir, backfill: backfillArg, retain, ormHandoff, replace, envs, checks, sql } = parseNewArgs(args); const project = await loadProject(dir); if (sql) return writeHandWritten(io, project, name, json); let backfill: { text: string } | { form: BackfillForm } | undefined; @@ -335,7 +355,7 @@ export const newCommand: Command = { const build = await buildSchema(project); let made: ReturnType; try { - made = createMigration({ name, build: build.output, previous, ...(backfill ? { backfill } : {}), ...(retain !== undefined ? { retain } : {}), ...(checks.length > 0 ? { checks } : {}) }); + made = createMigration({ name, build: build.output, previous, ...(backfill ? { backfill } : {}), ...(retain !== undefined ? { retain } : {}), ...(ormHandoff ? { ormHandoff } : {}), ...(checks.length > 0 ? { checks } : {}) }); } finally { build.dispose(); } diff --git a/src/commands/plan.ts b/src/commands/plan.ts index f29f6e32..28355be5 100644 --- a/src/commands/plan.ts +++ b/src/commands/plan.ts @@ -13,6 +13,7 @@ import { collectDeclarativePlan, declarativePlanExitCode, declarativePlanJson, r import { runnable } from "../chant/runnable.js"; import { decodeSubject } from "../versioned/explain.js"; import { collectVersionedPlan } from "../pr/model.js"; +import { overdueNotes } from "../pr/overdue.js"; import { commentMarker, planJsonVersioned, renderPlanMarkdown, renderPlanText, subjectIn } from "../pr/render.js"; import { planPart } from "../pr/part.js"; import { describeForge, resolveForge, type Forge, type ForgeFlags } from "../pr/forge.js"; @@ -183,6 +184,7 @@ async function declarativePlan(project: Project, env: Environment, a: PlanArgs, const build = await buildSchema(project); try { const result = await collectDeclarativePlan(project, env, build, await planEnvironment(project, env, build), { opName: a.op }); + if (forge) result.notes.push(...(await watchNotes(project, env, forge, io))); if (forge) await postComment(forge, commentMarker(env.name), renderDeclarativeMarkdown(result), io); const doc = declarativePlanJson(result); if (a.format === "json") io.out(`${JSON.stringify(doc, null, 2)}\n`); @@ -210,6 +212,7 @@ async function versionedPlan(project: Project, env: Environment, a: PlanArgs, io const result = await collectVersionedPlan(project, env, { allowOutOfOrder: a.allowOutOfOrder, opName: a.op, previous }); const code = result.refusal?.exitCode ?? 0; + if (forge) result.notes.push(...(await watchNotes(project, env, forge, io))); if (forge) await postComment(forge, marker, renderPlanMarkdown(result), io); if (a.part !== undefined) { const file = resolve(a.part); @@ -229,6 +232,7 @@ async function versionedPlan(project: Project, env: Environment, a: PlanArgs, io async function tenantSetPlan(project: Project, env: Environment, a: PlanArgs, io: Io): Promise { const forge = a.comment ? await resolveForge(a.forge, process.env, "--comment") : undefined; const result = await collectTenantSetPlan(project, env.name, { allowOutOfOrder: a.allowOutOfOrder }); + if (forge) result.notes.push(...(await watchNotes(project, env, forge, io))); if (forge) await postComment(forge, commentMarker(env.name), renderTenantSetMarkdown(result), io); if (a.format === "json") io.out(`${JSON.stringify(tenantSetJson(result), null, 2)}\n`); else if (a.format === "markdown") io.out(renderTenantSetMarkdown(result)); @@ -236,6 +240,11 @@ async function tenantSetPlan(project: Project, env: Environment, a: PlanArgs, io return tenantSetExitCode(result); } +/** A warning per overdue drift watch of the environment (chant#4289), for the comment; the job log gets the same lines. */ +async function watchNotes(project: Project, env: Environment, forge: Forge, io: Io): Promise { + return overdueNotes(project.dir, env.tenant?.env ?? env.name, forge.client, (line) => { io.err(`${line}\n`); }); +} + /** The pull request `--comment` posts on: resolveForge refuses a target without one. */ const prOf = (forge: Forge): number => forge.target.pr ?? 0; diff --git a/src/migrations/create.ts b/src/migrations/create.ts index 6b9eabb5..de01c1eb 100644 --- a/src/migrations/create.ts +++ b/src/migrations/create.ts @@ -14,8 +14,9 @@ import type { BuildOutput } from "../chant/build.js"; import { computeChecksum } from "./checksum.js"; import { MIGRATION_FORMAT, serializeDocument, type MigrationCheck, type MigrationDocument, type MigrationFiles, type MigrationStep } from "./document.js"; import { MIGRATION_NAME, type Migration } from "./directory.js"; -import { asBackfill, BACKFILL_FILE, describeForm, PG_MIGRATION_OP, REBUILD_OP, type BackfillForm } from "../steps/kinds.js"; +import { asBackfill, BACKFILL_FILE, describeForm, PG_MIGRATION_OP, REBUILD_OP, type BackfillForm, type OrmHandoffOptions } from "../steps/kinds.js"; import { backfillFormStep, backfillStep, describeFormSql } from "../steps/backfill.js"; +import { ormHandoffStep } from "../steps/orm-handoff.js"; export interface CreateMigrationOptions { /** The migration's name, the part of its id after the timestamp. */ @@ -39,6 +40,11 @@ export interface CreateMigrationOptions { * With one, a migration is made even when the build has no schema change. */ backfill?: { text: string; file?: string } | { form: BackfillForm }; + /** + * An `orm-handoff` step to end the migration with (#279): it marks the + * ORM's own migration applied after the Op, so the ORM does not run it. + */ + ormHandoff?: OrmHandoffOptions; /** * How long a `PostgresMigrationOp` step keeps the old column, or a * `ClickHouseRebuildOp` step the old table, after the switch: written @@ -159,6 +165,7 @@ export function createMigration(options: CreateMigrationOptions): CreatedMigrati const step = "form" in options.backfill ? backfillFormStep(options.name, options.backfill.form) : backfillStep(options.name, options.backfill.file ?? BACKFILL_FILE); statements = { ...statements, refused: true, steps: [...statements.steps, step as unknown as MigrationStep] }; } + if (options.ormHandoff) statements = { ...statements, refused: true, steps: [...statements.steps, ormHandoffStep(options.name, options.ormHandoff)] }; if (statements.steps.length === 0) return { id: undefined, statements }; const unsigned: MigrationDocument = { diff --git a/src/pr/overdue.ts b/src/pr/overdue.ts new file mode 100644 index 00000000..6d134bf8 --- /dev/null +++ b/src/pr/overdue.ts @@ -0,0 +1,98 @@ +/** + * The plan comment's warning that an environment's drift watch stopped + * running (chant#4289). A scheduled job can stop with no error anywhere: + * GitHub turns a scheduled workflow off after 60 days with no activity in + * the repository, and on GitLab the job runs only from a pipeline schedule + * someone created. The watch cannot report its own absence, so `yodel plan + * --comment` asks the forge when the environment's WatchOp job last ran and + * warns when its cron has fired at least twice since. + * + * chant decides (`overdueVerdict` in `op/schedule-overdue.ts`); yodel says + * which Op and which file. The Op is the WatchOp whose `Env` label is the + * environment (chant's `WatchOp` sets `Watch` and `Env`, + * `op/composites/watch-op.ts:80` in chant 0.124.46). The file is the one + * `yodel ci` renders for it: `.github/workflows/.yml` or + * `.forgejo/workflows/.yml`, and on GitLab {@link GITLAB_WATCH} when its + * rules select the Op. chant's own `checkOverdueOps` reads only root + * `*.gitlab-ci.yml` files, so yodel asks the forge itself. + * + * Nothing here fails the plan. A forge that does not answer is a line in + * the job log and no warning. + */ + +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { OpConfig } from "@intentius/chant/op/types"; +import type { OverdueOp } from "@intentius/chant/op/schedule-overdue"; +import type { PrForge } from "@intentius/chant/pr-forge"; + +/** The GitLab file `yodel ci` renders the watches into (`GITLAB_WATCH_FILE` in ../ci/render.ts). */ +export const GITLAB_WATCH = ".gitlab/yodel-watch.gitlab-ci.yml"; + +/** The environment's scheduled WatchOps, by name. */ +export async function envWatches(ops: Iterable, env: string): Promise<{ op: string; cron: string }[]> { + const { scheduledWatches } = await import("@intentius/chant/op/schedule-overdue"); + return scheduledWatches([...ops].filter((o) => o.labels?.Watch === "true" && o.labels.Env === env)); +} + +/** The file `yodel ci` rendered for `op` on `forge`, relative to the project, when the project has it. */ +export function watchPipelineFile(dir: string, forge: PrForge["kind"], op: string): string | undefined { + if (forge === "gitlab") { + try { + return readFileSync(join(dir, GITLAB_WATCH), "utf8").includes(`$CHANT_SCHEDULED_OP == "${op}"`) ? GITLAB_WATCH : undefined; + } catch { + return undefined; + } + } + const path = `.${forge}/workflows/${op}.yml`; + return existsSync(join(dir, path)) ? path : undefined; +} + +/** + * The environment's overdue watches, each logged with `log`. `ops` are the + * project's discovered Op configs; `dir` is the project, where `yodel ci` + * writes its files. + */ +export async function overdueWatches(input: { + ops: Iterable; + env: string; + dir: string; + forge: Pick; + now: Date; + log: (line: string) => void; +}): Promise { + const { forge } = input; + if (!forge.scheduledRuns) return []; + const { fileAdded, overdueVerdict } = await import("@intentius/chant/op/schedule-overdue"); + const out: OverdueOp[] = []; + for (const watch of await envWatches(input.ops, input.env)) { + const file = watchPipelineFile(input.dir, forge.kind, watch.op); + if (!file) continue; + let runs: Awaited>>; + try { + runs = await forge.scheduledRuns({ op: watch.op, workflow: file.split("/").pop() ?? file }); + } catch (e) { + input.log(`yodel plan: ${forge.kind} did not say when ${watch.op} last ran, so it is not checked: ${(e instanceof Error ? e.message : String(e)).split("\n")[0] ?? ""}`); + continue; + } + const found = overdueVerdict(watch, forge.kind, runs, runs.last ? undefined : fileAdded(input.dir, file), input.now); + if (found) { + input.log(`yodel plan: Warning: ${found.message}`); + out.push(found); + } + } + return out; +} + +/** The notes `yodel plan --comment` adds for the environment's overdue watches: discovers the Ops, never throws. */ +export async function overdueNotes(dir: string, env: string, forge: Pick, log: (line: string) => void, now = new Date()): Promise { + try { + const { discoverOps } = await import("@intentius/chant/op/discover"); + const found = await discoverOps({ cwd: dir }); + const overdue = await overdueWatches({ ops: [...found.ops.values()].map((o) => o.config), env, dir, forge, now, log }); + return overdue.map((o) => `Warning: ${o.message}`); + } catch (e) { + log(`yodel plan: the watch schedule was not checked: ${(e instanceof Error ? e.message : String(e)).split("\n")[0] ?? ""}`); + return []; + } +} diff --git a/src/release/index.ts b/src/release/index.ts index 866eecf5..9246167b 100644 --- a/src/release/index.ts +++ b/src/release/index.ts @@ -18,14 +18,28 @@ * A tenant (#56) is recorded on its environment's ledger as the component * `/`, so a tenant compares with the same tenant of * another environment. + * + * What else a record carries (#277), each only when it is known: + * + * - `approver` and `admission` (`{ op, gate, resolvedAt }`, chant#4020), for + * an apply a gate approved, both from chant's `admissionOf`. An apply no + * approval let through writes neither. + * - `releaseDigest` (chant#4043), for an apply made from a chant release + * (`_releases/.json`): `yodel apply --release `, + * which hands it to the Op's Apply step in `YODEL_RELEASE`. chant writes it + * only when the caller names a release, never inferred, and so does yodel. + * + * Records already on the ledger are never rewritten; a reader takes every + * field above as optional (chant's `reference/workspace-read-contract`). */ import { execFile } from "node:child_process"; import { promisify } from "node:util"; +import type { ReleaseAdmission } from "@intentius/chant/lifecycle/release-ledger"; import type { BuildOutput } from "../chant/build.js"; import type { Migration } from "../migrations/index.js"; import { schemaSha } from "../migrations/checkpoint.js"; -import type { Environment, Project } from "../project.js"; +import { YodelError, type Environment, type Project } from "../project.js"; import type { VersionedStatus } from "../versioned/state.js"; /** What {@link recordRelease} did: the record it appended, or why it appended none. */ @@ -70,13 +84,48 @@ export function appliedHead(ordered: readonly Migration[], status: Pick { + const { resolveRelease } = await import("@intentius/chant/lifecycle/release-store"); + const { getHeadCommit } = await import("@intentius/chant/lifecycle/git"); + const found = await resolveRelease(ref, { cwd }); + if (!found) throw new YodelError(`--release ${ref}: no chant release on the chant/lifecycle branch has that digest or label (chant release cut makes one); nothing was applied`); + let head: string | undefined; + try { + head = await getHeadCommit({ cwd }); + } catch { + head = undefined; + } + if (head !== found.release.commit) { + throw new YodelError( + `--release ${ref}: release ${found.release.releaseDigest} was cut at ${found.release.commit.slice(0, 12)}, and ${cwd} is at ${head ? head.slice(0, 12) : "no commit"}; check out the release's commit to apply from it. Nothing was applied.`, + ); + } + return found.release.releaseDigest; +} + /** * Appends a release record of `schema` for `env` to chant's release ledger * and pushes it. Writes nothing when the project is not in a git * repository, or when the ledger branch could not be fetched or has forked * from the remote's (appending there would drop one side's records). */ -export async function recordRelease(project: Project, env: Environment, schema: BuildOutput, options: { approver?: string } = {}): Promise { +export async function recordRelease(project: Project, env: Environment, schema: BuildOutput, options: ReleaseFacts = {}): Promise { const cwd = project.dir; const base = await releaseComponent(cwd); if (base === undefined) return { recorded: false, reason: `${cwd} is not in a git repository` }; @@ -109,6 +158,8 @@ export async function recordRelease(project: Project, env: Environment, schema: timestamp: new Date().toISOString(), actor, ...(options.approver ? { approver: options.approver } : {}), + ...(options.admission ? { admission: options.admission } : {}), + ...(options.releaseDigest ? { releaseDigest: options.releaseDigest } : {}), }, { cwd }, ); @@ -117,7 +168,7 @@ export async function recordRelease(project: Project, env: Environment, schema: } /** {@link recordRelease}, told in one line (two when the push did not land); a failure to record is a line too, never thrown. */ -export async function recordReleaseLines(project: Project, env: Environment, schema: BuildOutput | undefined, options: { approver?: string } = {}): Promise { +export async function recordReleaseLines(project: Project, env: Environment, schema: BuildOutput | undefined, options: ReleaseFacts = {}): Promise { if (!schema) return [`release: not recorded; ${env.name}'s schema is none a migration recorded (nothing applied, or an out-of-order gap)`]; try { const r = await recordRelease(project, env, schema, options); diff --git a/src/replay/replay.ts b/src/replay/replay.ts index 02504291..da50b9d7 100644 --- a/src/replay/replay.ts +++ b/src/replay/replay.ts @@ -39,7 +39,7 @@ import type { ClassifiedChange } from "@intentius/chant-lexicon-sql/core/classif import type { StatementStep } from "@intentius/chant-lexicon-sql/migration-statements"; import { YodelError, type SqlDialect } from "../project.js"; import { isCheckpoint, isHandWritten, type Migration } from "../migrations/index.js"; -import { asBackfill, describeStep, planStep, type BackfillStep } from "../steps/kinds.js"; +import { asBackfill, asOrmHandoff, describeStep, planStep, type BackfillStep } from "../steps/kinds.js"; import type { RebuildReceiptStore } from "../steps/rebuild.js"; /** Exit code: the target is not fresh and `reset` was not given; nothing was run. */ @@ -159,6 +159,10 @@ export async function replayMigrations(ordered: readonly Migration[], driver: Re done.skipped.push(`step ${String(i)}: ${describeStep(s)} (moves data; the replayed database has none)`); continue; } + if (asOrmHandoff(s)) { + done.skipped.push(`step ${String(i)}: ${describeStep(s)} (records the ORM's own migration; the replayed database has no ORM)`); + continue; + } const plan = planStep(s); const outcome: OpStepOutcome = plan.run === "refused" ? { refused: plan.reason } : await driver.opStep(m, i); if ("refused" in outcome) { diff --git a/src/steps/index.ts b/src/steps/index.ts index 76d5fe2a..8a24d98e 100644 --- a/src/steps/index.ts +++ b/src/steps/index.ts @@ -6,6 +6,7 @@ * runRebuild(...) a ClickHouseRebuildOp step (./rebuild.ts) * runBackfill(...) a backfill step, a form or an Op of effect() batches (./backfill.ts) * runPgMigration(...) a PostgresMigrationOp step (./postgres-migration.ts) + * runOrmHandoff(...) an orm-handoff step (./orm-handoff.ts) * defaultStepRunner what the versioned apply calls for an Op step */ @@ -19,12 +20,14 @@ import { runBackfill, serverReceipts, type PgBackfillServer } from "./backfill.j import type { StepPlan } from "./kinds.js"; import { rebuildChantConfig, runRebuild, type RebuildReceiptStore } from "./rebuild.js"; import { runPgMigration } from "./postgres-migration.js"; +import { runOrmHandoff, type HandoffExec } from "./orm-handoff.js"; export * from "./kinds.js"; export * from "./run.js"; export * from "./rebuild.js"; export * from "./backfill.js"; export * from "./postgres-migration.js"; +export * from "./orm-handoff.js"; /** What running one Op step needs. */ export interface StepContext { @@ -47,6 +50,8 @@ export interface StepContext { receipts?: ReceiptStore | undefined; /** A rebuild's partition receipts; default the sql lexicon's on the server (`chant_receipts.receipts`). `yodel test` keeps each case's apart (#112). */ rebuildReceipts?: RebuildReceiptStore | undefined; + /** An orm-handoff step's CLI runner; default runs the command in the project directory. A test passes its own. */ + exec?: HandoffExec | undefined; /** The tenant the step runs on (#56): what the step names in the template is renamed to the tenant. */ tenant?: TenantOf | undefined; } @@ -83,6 +88,12 @@ export const defaultStepRunner: StepRunner = async (ctx) => { const { summary } = await runRebuild(options, { environment: ctx.environment, projectDir: ctx.projectDir, schema, log: ctx.log, config, ...(ctx.rebuildReceipts ? { receipts: ctx.rebuildReceipts } : {}) }); return { summary }; } + if (ctx.plan.run === "ormHandoff") { + if (!ctx.postgres) throw new YodelError("an orm-handoff step records the ORM's migration on the environment's Postgres server, and this environment has none"); + const options = tenant && ctx.plan.options.dbSchema ? { ...ctx.plan.options, dbSchema: tenant.rename(ctx.plan.options.dbSchema) } : ctx.plan.options; + const { summary } = await runOrmHandoff(options, { projectDir: ctx.projectDir, client: ctx.postgres.client, log: ctx.log, ...(ctx.exec ? { exec: ctx.exec } : {}) }); + return { summary }; + } if (ctx.plan.run === "pgMigration") { const options = tenant ? { ...ctx.plan.options, table: tenant.rename(ctx.plan.options.table) } : ctx.plan.options; const { summary } = await runPgMigration(options, { environment: ctx.environment, projectDir: ctx.projectDir, schema, lockTimeoutMs: ctx.lockTimeoutMs, log: ctx.log, config: tenant?.config }); diff --git a/src/steps/kinds.ts b/src/steps/kinds.ts index 01b08c54..f45f1ade 100644 --- a/src/steps/kinds.ts +++ b/src/steps/kinds.ts @@ -14,7 +14,9 @@ * one batch), or as an Op of `effect()` steps in a module in the * migration's directory (`./backfill.ts`); * - `PostgresMigrationOp`, the step `yodel new` writes for a Postgres column - * rename or type change across kinds (`./postgres-migration.ts`, #13). + * rename or type change across kinds (`./postgres-migration.ts`, #13); + * - `orm-handoff`, the last step of a migration whose change an ORM also owns: + * it marks the ORM's own migration as applied (`./orm-handoff.ts`, #279). * * Everything else (a manual step, a rebuild in app mode) is refused before * anything runs, with exit 2. @@ -30,6 +32,8 @@ export const BACKFILL_OP = "backfill"; export const BACKFILL_FILE = "backfill.ts"; export const REBUILD_OP = "ClickHouseRebuildOp"; export const PG_MIGRATION_OP = "PostgresMigrationOp"; +/** The `op` of an ORM handoff step. */ +export const ORM_HANDOFF_OP = "orm-handoff"; type OpStep = Extract; @@ -92,7 +96,40 @@ export interface PgMigrationOptions { statementTimeoutMs?: number; } +/** + * An `orm-handoff` step's options: the ORM and the id of its own migration. + * Paths are relative to the project directory. + */ +export type OrmHandoffOptions = + | { + orm: "prisma"; + /** The migration's directory name under `dir`, for example `20261009120000_rename_login`. */ + migration: string; + /** Prisma's migrations directory; default `prisma/migrations`. */ + dir?: string; + /** `--schema` for the CLI. */ + schema?: string; + /** `--config` for the CLI. */ + config?: string; + /** The Postgres schema `_prisma_migrations` is in (the datasource URL's `schema`); default `public`. */ + dbSchema?: string; + } + | { + orm: "rails"; + /** The migration's version, the digits that start its file name. */ + migration: string; + /** Rails' migration directory; default `db/migrate`. */ + dir?: string; + /** The schema migrations table; default `schema_migrations`. */ + table?: string; + /** The Postgres schema the table is in; default `public`. */ + dbSchema?: string; + }; + +export const ORM_HANDOFF_ORMS = ["prisma", "rails"] as const; + export type StepPlan = + | { run: "ormHandoff"; options: OrmHandoffOptions } | { run: "statement" } | { run: "rebuild"; options: RebuildOptions } | { run: "pgMigration"; options: PgMigrationOptions } @@ -207,6 +244,7 @@ export function planStep(step: MigrationStep | BackfillStep): StepPlan { return { run: "rebuild", options: { name: o.name, table: o.table, dualWrite: dw as DualWrite, ...(retain ? { retain } : {}) } }; } if (step.op === PG_MIGRATION_OP) return planPgMigration(step); + if ((step.op as string) === ORM_HANDOFF_OP) return planOrmHandoff(step as OpStep); return { run: "refused", reason: `${step.op} for ${step.object} (${step.name}), not SQL: yodel apply does not run that Op` }; } @@ -241,6 +279,36 @@ function planPgMigration(step: OpStep): StepPlan { }; } +/** A path inside the project: relative, `/`-separated, no `..` and no hidden part. */ +const isRelativePath = (v: unknown): v is string => { + if (!isString(v) || v.includes("\\") || v.startsWith("/")) return false; + return v.split("/").every((p) => p !== "" && p !== "." && p !== ".." && !p.startsWith(".")); +}; +const isIdentifier = (v: unknown): v is string => typeof v === "string" && /^[A-Za-z_][A-Za-z0-9_$]*$/.test(v); +const PRISMA_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/; + +/** The step's options as an ORM handoff, or what is wrong with them. */ +export function ormHandoffOptions(o: unknown): { options: OrmHandoffOptions } | { problem: string } { + if (!isRecord(o)) return { problem: "its options are an object" }; + const orm = o.orm; + if (orm !== "prisma" && orm !== "rails") return { problem: `options.orm is ${JSON.stringify(orm)}; yodel hands off to ${ORM_HANDOFF_ORMS.join(" and ")}` }; + const allowed = orm === "prisma" ? ["orm", "migration", "dir", "schema", "config", "dbSchema"] : ["orm", "migration", "dir", "table", "dbSchema"]; + for (const k of Object.keys(o)) if (!allowed.includes(k)) return { problem: `"${k}" is not an option of a ${orm} handoff (${allowed.join(", ")})` }; + if (orm === "prisma" && !(typeof o.migration === "string" && PRISMA_NAME.test(o.migration))) return { problem: `options.migration names a Prisma migration directory, for example "20261009120000_rename_login" (got ${JSON.stringify(o.migration)})` }; + if (orm === "rails" && !(typeof o.migration === "string" && /^[0-9]+$/.test(o.migration))) return { problem: `options.migration is a Rails migration version, the digits that start its file name, as a string (got ${JSON.stringify(o.migration)})` }; + for (const k of ["dir", "schema", "config"] as const) if (o[k] !== undefined && !isRelativePath(o[k])) return { problem: `options.${k} is a path inside the project (got ${JSON.stringify(o[k])})` }; + for (const k of ["table", "dbSchema"] as const) if (o[k] !== undefined && !isIdentifier(o[k])) return { problem: `options.${k} is an unquoted SQL name (got ${JSON.stringify(o[k])})` }; + return { options: o as unknown as OrmHandoffOptions }; +} + +function planOrmHandoff(step: OpStep): StepPlan { + const got = ormHandoffOptions(step.options); + return "problem" in got ? { run: "refused", reason: `${ORM_HANDOFF_OP} for ${step.object} (${step.name}): ${got.problem}` } : { run: "ormHandoff", options: got.options }; +} + +/** The step as an ORM handoff, when it is one. */ +export const asOrmHandoff = (step: MigrationStep | BackfillStep): OpStep | undefined => (step.kind === "op" && (step.op as string) === ORM_HANDOFF_OP ? (step as OpStep) : undefined); + /** One line naming a step, for logs and refusals. */ export function describeStep(step: MigrationStep | BackfillStep): string { if (step.kind === "statement") return `${step.rule} ${step.class}, ${step.name}`; @@ -250,6 +318,11 @@ export function describeStep(step: MigrationStep | BackfillStep): string { const form = asForm(backfill.options); return form ? `backfill of ${describeForm(form)}` : `backfill ${"file" in backfill.options ? backfill.options.file : "(a form yodel does not run)"}`; } + const handoff = asOrmHandoff(step); + if (handoff) { + const got = ormHandoffOptions(handoff.options); + return "options" in got ? `${ORM_HANDOFF_OP}: mark ${got.options.orm} migration ${got.options.migration} applied` : `${ORM_HANDOFF_OP} (${got.problem})`; + } return `${step.op} for ${step.object} (${step.name})`; } diff --git a/src/steps/orm-handoff.ts b/src/steps/orm-handoff.ts new file mode 100644 index 00000000..76c7cee1 --- /dev/null +++ b/src/steps/orm-handoff.ts @@ -0,0 +1,183 @@ +/** + * An `orm-handoff` step (#279): the last step of a migration whose change an + * ORM also owns. A hard change (a staged rename, a type change) runs as a + * `PostgresMigrationOp`; the team writes the ORM's own migration for the same + * change; this step then marks that migration as applied, so the ORM does not + * run it again. + * + * It does what each ORM's own "mark as applied" does, and nothing the ORM + * would not: + * + * - Prisma: `prisma migrate resolve --applied `, the CLI. Yodel runs + * the command and does not write `_prisma_migrations` itself. The CLI + * (schema-engine's `mark_migration_applied`) refuses a migration that is not + * in the migrations directory, refuses one already recorded as finished, + * checks the directory's provider lock file, takes the migrations table's + * advisory lock, and writes the row with the checksum of `migration.sql` + * (SHA-256, hex; `checksum.rs`), which `migrate deploy` and `migrate dev` + * compare on every run. A row written by hand has to copy all of that and + * follow it when a Prisma release changes it. + * - Rails: a row in `schema_migrations`, which is all Rails itself writes for + * a migration it has run (`SchemaMigration#create_version` inserts the + * version string into the `version` column). `rails db:migrate` skips a + * migration whose version is in the table (`pending_migrations` rejects the + * versions already migrated). Rails runs the app's Ruby to do that, so + * yodel inserts the row itself. + * + * Before the migration's first statement, apply asks {@link ormHandoffRefusal} + * whether the handoff can work: the ORM's migration is in the repository and + * is not recorded as applied. A handoff found out only after the Op ran would + * leave the change made and the ORM about to make it again. + */ + +import { execFile } from "node:child_process"; +import { statSync, readdirSync } from "node:fs"; +import { join } from "node:path"; +import type { PgClient } from "../history/postgres/index.js"; +import type { MigrationStep } from "@intentius/chant-lexicon-sql/migration-statements"; +import { ORM_HANDOFF_OP, type OrmHandoffOptions } from "./kinds.js"; + +const PRISMA_DIR = "prisma/migrations"; +const RAILS_DIR = "db/migrate"; +const DEFAULT_SCHEMA = "public"; +/** Rails' migration file name: the version, the name, an optional scope (`MigrationFilenameRegexp`). */ +const RAILS_FILE = /^([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb$/; + +const quote = (s: string) => `"${s.replace(/"/g, '""')}"`; +const str = (s: string) => `'${s.replace(/'/g, "''")}'`; + +/** Runs a command to the end: its stdout and stderr, and its exit code (not a throw). */ +export type HandoffExec = (command: string, args: string[], cwd: string) => Promise<{ code: number; output: string }>; + +export const defaultHandoffExec: HandoffExec = (command, args, cwd) => + new Promise((resolve) => { + execFile(command, args, { cwd, env: process.env, maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) => { + const code = error === null ? 0 : typeof error.code === "number" ? error.code : 1; + resolve({ code, output: `${stdout}${stderr}`.trim() }); + }); + }); + +/** The ORM's own name for it, for messages. */ +const ormName = (o: OrmHandoffOptions) => (o.orm === "prisma" ? "Prisma" : "Rails"); + +/** The file in the repository that proves the ORM migration exists, or `undefined`. */ +export function ormMigrationFile(options: OrmHandoffOptions, projectDir: string): string | undefined { + if (options.orm === "prisma") { + const file = join(projectDir, options.dir ?? PRISMA_DIR, options.migration, "migration.sql"); + return isFile(file) ? file : undefined; + } + const dir = join(projectDir, options.dir ?? RAILS_DIR); + let names: string[]; + try { + names = readdirSync(dir); + } catch { + return undefined; + } + const name = names.find((n) => RAILS_FILE.exec(n)?.[1] === options.migration); + return name !== undefined && isFile(join(dir, name)) ? join(dir, name) : undefined; +} + +function isFile(path: string): boolean { + try { + return statSync(path).isFile(); + } catch { + return false; + } +} + +/** Where the ORM records its migrations, and the query that says whether it recorded this one. */ +function recordedQuery(options: OrmHandoffOptions): { table: string; sql: string } { + const schema = quote(options.dbSchema ?? DEFAULT_SCHEMA); + if (options.orm === "prisma") { + // A row with finished_at set is what schema-engine's mark_migration_applied calls applied; a failed or rolled-back row is not. + return { table: `${schema}._prisma_migrations`, sql: `SELECT 1 AS applied FROM ${schema}._prisma_migrations WHERE migration_name = ${str(options.migration)} AND finished_at IS NOT NULL` }; + } + const table = `${schema}.${quote(options.table ?? "schema_migrations")}`; + return { table, sql: `SELECT 1 AS applied FROM ${table} WHERE version = ${str(options.migration)}` }; +} + +const MISSING_TABLE = /relation "[^"]+" does not exist|schema "[^"]+" does not exist/; + +/** Whether the ORM's table already holds the migration. A table that is not there yet holds nothing. */ +async function isRecorded(options: OrmHandoffOptions, read: (sql: string) => Promise>>): Promise { + try { + return (await read(recordedQuery(options).sql)).length > 0; + } catch (e) { + if (MISSING_TABLE.test(e instanceof Error ? e.message : String(e))) return false; + throw e; + } +} + +/** + * Why the handoff cannot run, or `undefined` when it can: the ORM's migration + * is not in the repository, or the ORM already records it as applied. `read` + * runs a read-only query on the environment's server. + */ +export async function ormHandoffRefusal(options: OrmHandoffOptions, ctx: { projectDir: string; read: (sql: string) => Promise>> }): Promise { + const orm = ormName(options); + if (ormMigrationFile(options, ctx.projectDir) === undefined) { + const where = options.orm === "prisma" ? `${options.dir ?? PRISMA_DIR}/${options.migration}/migration.sql` : `${options.dir ?? RAILS_DIR}/${options.migration}_*.rb`; + return `the ${orm} migration ${options.migration} is not in the repository (looked for ${where}), so there is nothing to mark applied`; + } + if (await isRecorded(options, ctx.read)) { + return `${orm} already records ${options.migration} as applied (${recordedQuery(options).table}), so the Op's change would be made twice or the ORM's migration was run by the ORM; remove the orm-handoff step if the ORM ran it`; + } + return undefined; +} + +export interface OrmHandoffSummary { + op: "orm-handoff"; + orm: "prisma" | "rails"; + migration: string; + /** How it was recorded: the Prisma CLI, or a row yodel inserted. */ + via: "prisma migrate resolve" | "insert"; + table: string; +} + +export interface RunOrmHandoffOptions { + projectDir: string; + /** The environment's Postgres connection. */ + client: PgClient; + log?: (line: string) => void; + exec?: HandoffExec; +} + +/** Runs the handoff to the end. Throws when the ORM's migration is missing or already applied, or the ORM's command fails. */ +export async function runOrmHandoff(options: OrmHandoffOptions, run: RunOrmHandoffOptions): Promise<{ summary: OrmHandoffSummary }> { + const read = (sql: string) => run.client.query(sql); + const why = await ormHandoffRefusal(options, { projectDir: run.projectDir, read }); + if (why) throw new Error(`orm-handoff refused: ${why}`); + const { table } = recordedQuery(options); + if (options.orm === "rails") { + // Rails' own table: `create_table` with a string primary key `version` and no id column. + await run.client.query(`CREATE TABLE IF NOT EXISTS ${table} ("version" character varying NOT NULL PRIMARY KEY)`); + await run.client.query(`INSERT INTO ${table} ("version") VALUES ($1)`, [options.migration]); + run.log?.(`recorded Rails migration ${options.migration} in ${table}`); + return { summary: { op: "orm-handoff", orm: "rails", migration: options.migration, via: "insert", table } }; + } + const args = ["--no-install", "prisma", "migrate", "resolve", "--applied", options.migration, ...(options.schema ? ["--schema", options.schema] : []), ...(options.config ? ["--config", options.config] : [])]; + run.log?.(`npx ${args.join(" ")}`); + const result = await (run.exec ?? defaultHandoffExec)("npx", args, run.projectDir); + if (result.code !== 0) throw new Error(`prisma migrate resolve --applied ${options.migration} exited ${String(result.code)}: ${result.output.split("\n").slice(-6).join("\n")}`); + // The CLI reaches the database through the project's own datasource; confirm it is the environment's. + if (!(await isRecorded(options, read))) { + throw new Error(`prisma migrate resolve --applied ${options.migration} succeeded, but ${table} on this environment's server has no finished row for it: the project's datasource points at another database or schema (set dbSchema if Prisma uses another schema)`); + } + return { summary: { op: "orm-handoff", orm: "prisma", migration: options.migration, via: "prisma migrate resolve", table } }; +} + +/** The step to put at the end of a migration's `steps` in `migration.json`: the options are in the step, so in the migration's checksum and the plan digest. */ +export function ormHandoffStep(migrationName: string, options: OrmHandoffOptions): Extract { + return { + kind: "op", + object: "orm-handoff", + type: "Yodel::OrmHandoff", + name: migrationName, + op: ORM_HANDOFF_OP as never, + importPath: "@intentius/sql-yodeler", + options: options, + declaration: JSON.stringify(options, null, 2), + changes: [], + detail: `marks the ${ormName(options)} migration ${options.migration} as applied, so ${ormName(options)} does not run it again. yodel apply runs it last, after the Op, under the migration's lock and gate.`, + }; +} diff --git a/src/testing/run.ts b/src/testing/run.ts index cb5aecbe..a51d557c 100644 --- a/src/testing/run.ts +++ b/src/testing/run.ts @@ -39,7 +39,7 @@ import { environmentSettings } from "../config/settings.js"; import { isCheckpoint, readMigrations, type Migration } from "../migrations/index.js"; import { migrationsDir } from "../versioned/index.js"; import { httpPort } from "../history/index.js"; -import { asBackfill, defaultStepRunner, planStep, type RebuildReceiptStore, type StepRunner } from "../steps/index.js"; +import { asBackfill, asOrmHandoff, defaultStepRunner, planStep, type RebuildReceiptStore, type StepRunner } from "../steps/index.js"; import type { BackfillStep } from "../steps/kinds.js"; import { NOT_FRESH, openReplay, refuseShared, sharedProfiles, type ReplayDriver } from "../replay/index.js"; import type { Expectation, TestCase } from "./define.js"; @@ -299,6 +299,7 @@ export async function runTests(project: Project, env: Environment, files: readon await runStep({ environment: env.name, projectDir: project.dir, migration: m, index: i, plan, log: (l) => { log(` ${l}`); }, receipts, ...s.backfillContext() }); continue; } + if (asOrmHandoff(st)) continue; // the ORM's own record; a test database has no ORM const plan = planStep(st); if (plan.run === "refused") throw new Error(`${m.id} step ${String(i)} cannot run here: ${plan.reason}`); const outcome = await driver.opStep(m, i, { receipts }); diff --git a/src/versioned/approval.ts b/src/versioned/approval.ts index c59d9be3..a8d55eba 100644 --- a/src/versioned/approval.ts +++ b/src/versioned/approval.ts @@ -16,14 +16,21 @@ * - it is newer than the newest pending fact for the gate, so an approval * from before the gate last asked does not answer it; * - the workspace's approval rule for the gate (`identity.gates`), when one - * applies, accepts it. + * applies, accepts it; + * - one the gate step carried from an alias (`carriedFrom`, chant#3949) + * counts only while the gate still lists that alias, as chant's gate reads + * it (`op/gate.ts:815` in chant 0.124.46). * - * A gate with a quorum or policy (`approval`) is refused here: counting a - * quorum is the gate step's, and `--execute` fails closed rather than - * approximate it. + * A gate with a quorum is counted here by chant's own tally (`tallyGateApprovals`) + * under the quorum the workspace declaration sets at the base commit + * (`identity.gates..quorum`, chant#4324), never the Op's own. A quorum + * only the Op declares, and a policy, are refused: `--execute` fails closed + * rather than count what the change itself can edit or approximate a policy. */ import type { GateLedgerPort } from "@intentius/chant/op/gate"; +import type { GateResolutionRecord } from "@intentius/chant/lifecycle/gate-ledger"; +import type { ReleaseAdmission } from "@intentius/chant/lifecycle/release-ledger"; import { YodelError } from "../project.js"; import type { MigrateOpRef } from "./op.js"; @@ -32,24 +39,85 @@ const EPOCH = new Date(0).toISOString(); /** Exit code of a refusal for want of an approval: the same as a run stopped at the gate. */ export const NOT_APPROVED = 3; -/** Throws unless the ledger holds an approval of `op`'s gate for `digest`. Returns who approved it. */ -export async function verifyApproval(port: GateLedgerPort, op: MigrateOpRef, digest: string): Promise<{ resolvedBy: string; timestamp: string; review?: { pr: number; head: string; approvers: string[] }; signer?: string }> { - if (op.quorum) { - throw new YodelError(`--execute cannot check gate "${op.gate}" of ${op.name}: it declares an approval quorum or policy, which only the gate step counts; run yodel apply without --execute`, NOT_APPROVED); +/** What {@link verifyApproval} found: the approval that counted, and what the release record says of it (#277). */ +export interface VerifiedApproval { + resolvedBy: string; + timestamp: string; + review?: { pr: number; head: string; approvers: string[] }; + signer?: string; + /** Every approver of the plan that counted, comma joined, from chant's `admissionOf`: the release record's `approver`. */ + approver: string; + /** The resolution that admitted the apply (`{ op, gate, resolvedAt }`, chant#4020): the release record's `admission`. */ + admission: ReleaseAdmission; +} + +/** + * Throws unless the ledger holds an approval of `op`'s gate for `digest`. Returns who approved it. + * + * A gate whose workspace declaration at base sets `identity.gates..quorum` + * (chant#4324) is counted by chant's own tally under those rules: distinct + * humans, roles from `.chant/trust.json` at base, none of it from the Op being + * run. A quorum the Op alone declares is refused, since the Op is part of the + * change; so is a policy, which only the gate step evaluates. + */ +export async function verifyApproval(port: GateLedgerPort, op: MigrateOpRef, digest: string): Promise { + if (op.policy) { + throw new YodelError(`--execute cannot check gate "${op.gate}" of ${op.name}: it declares an approval policy, which only the gate step evaluates; run yodel apply without --execute`, NOT_APPROVED); } const { latestPendingGate, latestResolutionForPlan } = await import("@intentius/chant/lifecycle/gate-ledger"); const ledger = await port.read(op.name); const rule = (await port.approvalRule?.(op.gate)) ?? null; - const resolutions = ledger.resolutions.filter((r) => r.gate !== op.gate || rule === null || rule.refuses(r) === null); - const since = latestPendingGate(ledger.pending, op.gate)?.timestamp ?? EPOCH; - const found = latestResolutionForPlan(resolutions, op.gate, since, digest); + // The quorum at base (chant#4324), the only one counted: the Op's own is the change's to edit. + const atBase = rule?.requirement.quorum ?? undefined; + if (op.quorum && atBase === undefined) { + throw new YodelError( + `--execute cannot check gate "${op.gate}" of ${op.name}: its approval quorum is declared only in the Op, which this change can edit, and the workspace declaration at the base commit sets none; ` + + `declare it as identity.gates.${op.gate}.quorum in chant.workspace.json on the base branch, or run yodel apply without --execute`, + NOT_APPROVED, + ); + } + const declared = (from: { op: string; gate: string }) => (op.aliases ?? []).some((a) => a.op === from.op && a.gate === from.gate); + const listed = ledger.resolutions.filter((r) => r.gate !== op.gate || r.carriedFrom === undefined || declared(r.carriedFrom)); + const resolutions = listed.filter((r) => r.gate !== op.gate || rule === null || rule.refuses(r) === null); + const standing = latestPendingGate(ledger.pending, op.gate); + const since = standing?.timestamp ?? EPOCH; + let found: { resolution?: GateResolutionRecord | undefined; mismatched?: GateResolutionRecord | undefined }; + // The approvals that counted toward the gate: one, or the quorum's. + let counted: GateResolutionRecord[]; + let waiting = ""; + if (atBase !== undefined) { + const { tallyGateApprovals, humanQuorumSince } = await import("@intentius/chant/op/gate"); + const { quorumRules, quorumRulesFor, quorumWaiting, UNPROVEN_JUDGE } = await import("@intentius/chant/op/gate-quorum"); + const { samePlanDigest } = await import("@intentius/chant/lifecycle/plan-digest"); + // As chant's gate step reads it: the rules this run takes (the Op runs with no environment, so a rule with `targets` does not cover it), and who an approval proves. + const rules = quorumRulesFor(quorumRules(atBase), []); + const judge = (await port.quorumJudge?.(op.gate)) ?? UNPROVEN_JUDGE; + const humansSince = standing && samePlanDigest(standing.planDigest, digest) ? humanQuorumSince(ledger.pending, standing) : since; + const tally = tallyGateApprovals(resolutions, op.gate, since, digest, { ...(rules.length > 0 ? { quorum: rules } : {}), mode: "log-only" }, humansSince, judge); + found = { resolution: tally.met ? tally.counted[tally.counted.length - 1] : undefined, mismatched: tally.mismatched }; + counted = tally.counted; + waiting = tally.met || !tally.rules ? "" : ` (the quorum at base is not met: ${quorumWaiting(tally.rules)})`; + } else { + found = latestResolutionForPlan(resolutions, op.gate, since, digest); + counted = resolutions.filter((x) => x.gate === op.gate && Date.parse(x.timestamp) >= Date.parse(since)); + } const r = found.resolution; - if (r) return { resolvedBy: r.resolvedBy, timestamp: r.timestamp, ...(r.review ? { review: r.review } : {}), ...(r.seal ? { signer: r.seal.signer } : {}) }; + if (r) { + // The release record's approver and admission come from chant's admissionOf, over the approvals that count here, bound to the digest of the one found. + const { admissionOf } = await import("@intentius/chant/lifecycle/release-ledger"); + const admitted = admissionOf(counted, { op: op.name, gate: op.gate, ...(r.planDigest !== undefined ? { planDigest: r.planDigest } : {}) }) ?? { + approver: r.resolvedBy, + admission: { op: op.name, gate: op.gate, resolvedAt: r.timestamp }, + }; + return { resolvedBy: r.resolvedBy, timestamp: r.timestamp, ...(r.review ? { review: r.review } : {}), ...(r.seal ? { signer: r.seal.signer } : {}), ...admitted }; + } // An approval of this digest the gate's rule does not count (#48: one not sealed by a signer at base), and why. - const uncounted = rule === null ? undefined : latestResolutionForPlan(ledger.resolutions, op.gate, since, digest).resolution; + const uncounted = rule === null ? undefined : latestResolutionForPlan(listed, op.gate, since, digest).resolution; const why = uncounted ? rule?.refuses(uncounted) : null; - const other = why - ? ` (the approval by ${uncounted?.resolvedBy ?? "?"} at ${uncounted?.timestamp ?? "?"} does not count: ${why})` + const other = waiting !== "" + ? waiting + : why + ? ` (the approval by ${uncounted?.resolvedBy ?? "?"} at ${uncounted?.timestamp ?? "?"} does not count: ${why})` : found.mismatched ? ` (the newest approval of that gate is for ${found.mismatched.planDigest ?? "no plan"}, by ${found.mismatched.resolvedBy} at ${found.mismatched.timestamp})` : ""; diff --git a/src/versioned/engine.ts b/src/versioned/engine.ts index d9077b26..7e41b6cb 100644 --- a/src/versioned/engine.ts +++ b/src/versioned/engine.ts @@ -46,7 +46,8 @@ import { PLAN_NEEDS_OP } from "../chant/plan.js"; import type { Migration } from "../migrations/index.js"; import { environmentSettings } from "../config/settings.js"; import type { Topology } from "../topology/render.js"; -import { defaultStepRunner, describeStep, planStep, stepSha, StepOpFailed, type StepRunner } from "../steps/index.js"; +import { defaultStepRunner, describeStep, ormHandoffRefusal, planStep, stepSha, StepOpFailed, type StepRunner } from "../steps/index.js"; +import { renameIdentifier } from "../tenants/target.js"; import type { ReceiptStore } from "@intentius/chant/op/receipt-store"; import { HistoryRecorder, @@ -202,7 +203,7 @@ export function stepRefusal(toApply: readonly PendingMigration[]): YodelError | const lines = toApply.flatMap((p) => p.refusedSteps.map(({ index, reason }) => ` ${p.id} step ${String(index)}: ${reason}`)); if (lines.length === 0) return undefined; return new YodelError( - `refused: a pending migration has a step yodel apply does not run: a person acts on a manual step, and yodel apply runs only ClickHouseRebuildOp (materialized-view mode) and backfill steps on ClickHouse, and PostgresMigrationOp on Postgres. Nothing was applied:\n${lines.join("\n")}`, + `refused: a pending migration has a step yodel apply does not run: a person acts on a manual step, and yodel apply runs only ClickHouseRebuildOp (materialized-view mode) and backfill steps on ClickHouse, PostgresMigrationOp and orm-handoff on Postgres. Nothing was applied:\n${lines.join("\n")}`, PLAN_NEEDS_OP, ); } @@ -436,6 +437,7 @@ async function applyMigration( // The started row's note: the policy overrides the run relied on (#53), the checks' outcomes (#52), and what the run adds (a wave's decision, #87). const noted: Record = { ...(overrides.length > 0 ? { policy: { overrides } } : {}), ...(options.runNote?.() ?? {}) }; let checksNote = Object.keys(noted).length > 0 ? JSON.stringify(noted) : ""; + await handoffPreflight(venv, p, rec, options); if (checksDue(p)) { const outcomes = await runChecks(venv.driver, m); checksNote = JSON.stringify({ ...noted, checks: outcomes }); @@ -489,6 +491,32 @@ async function applyMigration( return after?.error; } +/** + * An orm-handoff step (#279) is the migration's last, so a refusal found + * when it runs would come after the Op made its change. Before the + * migration's first statement, apply reads the repository and the ORM's + * table: a missing or already recorded ORM migration refuses the migration + * with nothing of it sent. + */ +async function handoffPreflight(venv: VersionedEnv, p: PendingMigration, rec: MigrationRecord | undefined, options: ExecuteOptions): Promise { + const m = p.migration; + const where = { defaultDatabase: m.document.defaultDatabase, defaultSchema: m.document.defaultSchema }; + for (const [i, step] of m.document.steps.entries()) { + if (statementDone(rec, i)) continue; + const plan = planStep(step); + if (plan.run !== "ormHandoff") continue; + const tenant = venv.driver.stepContext().tenant; + const rename = (s: string) => (tenant ? renameIdentifier(s, tenant.template, tenant.name) : s); + const handoff = plan.options.dbSchema ? { ...plan.options, dbSchema: rename(plan.options.dbSchema) } : plan.options; + const why = await ormHandoffRefusal(handoff, { projectDir: venv.projectDir ?? process.cwd(), read: (sql) => venv.driver.readCheck(sql, where) }); + if (why) { + const error = `step ${String(i)} (orm-handoff): ${why}`; + options.log(`${m.id}: ${error}`); + throw new YodelError(`refused: ${m.id} ends with an orm-handoff step that cannot run. Nothing of ${m.id} was applied:\n ${error}`, REFUSED); + } + } +} + type RowBase = { migration_id: string; parent: string; checksum: string; silences: string }; /** Runs Op step `i` of `p`, recording its start and outcome. */ diff --git a/src/versioned/op.ts b/src/versioned/op.ts index 525105d7..e2a539b2 100644 --- a/src/versioned/op.ts +++ b/src/versioned/op.ts @@ -6,8 +6,10 @@ * * Plan shell("yodel apply --digest", { id: "plan" }) * prints the digest of the pending migrations and the live schema - * Approve gate(..., { plan: stepOutput(plan, "stdout") }) - * a resolution counts only for that digest (`chant approve --plan `) + * Approve gate(..., { plan: stepOutput(plan, "stdout"), resume: true }) + * a resolution counts only for that digest (`chant approve --plan `); + * with `resume`, the run after the approval starts at the gate + * (chant#3947): it runs the Plan step again and skips nothing else * Apply shell("yodel apply --execute", { env: { YODEL_APPROVED_PLAN: stepOutput(plan, "stdout") } }) * takes the lock, computes the digest again, refuses if it moved, applies * @@ -45,8 +47,15 @@ export interface MigrateOpRef { name: string; filePath: string; gate: string; - /** The gate declares a quorum or policy (`approval`). */ + /** The gate declares an `approval` quorum in the Op. Only a quorum at base counts for `--execute` (chant#4324); this one is the change's to edit. */ quorum: boolean; + /** The gate declares an approval policy, which only the gate step evaluates. */ + policy?: boolean; + /** + * The gate's old names (chant#3949), each with its Op (this Op when the + * alias names none). An approval recorded under one counts for the gate. + */ + aliases?: { op: string; gate: string }[]; } const command = (verb: string) => new RegExp(`^(?:npx\\s+)?yodel\\s+apply\\s+(\\S+)\\s+${verb}(?:\\s|$)`); @@ -62,7 +71,7 @@ function shellCmd(step: StepDefinition): { cmd: string; id?: string } | undefine } /** The parts of a migrations Op for `env`, when `config` is one. */ -export function migrateOpParts(config: OpConfig, env: string): { gate: string | undefined; quorum: boolean } | undefined { +export function migrateOpParts(config: OpConfig, env: string): { gate: string | undefined; quorum: boolean; policy?: boolean; aliases?: { op: string; gate: string }[] } | undefined { const all = steps(config); const plan = all.map(shellCmd).find((s) => s && DIGEST.exec(s.cmd)?.[1] === env); const execute = all.map(shellCmd).find((s) => s && EXECUTE.exec(s.cmd)?.[1] === env); @@ -71,7 +80,9 @@ export function migrateOpParts(config: OpConfig, env: string): { gate: string | if (s.kind !== "gate" || s.plan === undefined || typeof s.plan === "string") return false; return (s.plan as { step?: unknown }).step === plan.id; }); - return gate?.kind === "gate" ? { gate: gate.gate, quorum: gate.approval !== undefined } : { gate: undefined, quorum: false }; + if (gate?.kind !== "gate") return { gate: undefined, quorum: false }; + const aliases = (gate.aliases ?? []).map((a) => ({ op: a.op ?? config.name, gate: a.gate })); + return { gate: gate.gate, quorum: gate.approval !== undefined, ...(gate.approval?.policy !== undefined ? { policy: true } : {}), ...(aliases.length > 0 ? { aliases } : {}) }; } /** How to declare the Op `yodel apply` looks for. */ @@ -88,7 +99,7 @@ export function migrateOpExample(env: string): string { ` overview: "Apply the pending migrations to ${env}, behind an approval bound to their plan digest",`, ` phases: [`, ` phase("Plan", [plan]),`, - ` phase("Approve", [gate("approve-migrate-${env}", { plan: digest })]),`, + ` phase("Approve", [gate("approve-migrate-${env}", { plan: digest, resume: true })]),`, ` phase("Apply", [shell("yodel apply ${env} --execute", { env: { ${APPROVED_PLAN_ENV}: digest }, timeout: "2h" })]),`, ` ],`, `});`, @@ -120,7 +131,7 @@ export function selectMigrateOp( if (!op.parts.gate) { throw new YodelError(`Op "${op.config.name}" (${op.filePath}) has no approval gate bound to its Plan step's digest, and yodel only applies behind one; give it gate(..., { plan: stepOutput(plan, "stdout") })`); } - return { name: op.config.name, filePath: op.filePath, gate: op.parts.gate, quorum: op.parts.quorum }; + return { name: op.config.name, filePath: op.filePath, gate: op.parts.gate, quorum: op.parts.quorum, ...(op.parts.policy ? { policy: true } : {}), ...(op.parts.aliases ? { aliases: op.parts.aliases } : {}) }; } export async function findMigrateOp(project: Project, target: Environment, name?: string): Promise { diff --git a/src/versioned/state.ts b/src/versioned/state.ts index 9fc09cf5..b0070c09 100644 --- a/src/versioned/state.ts +++ b/src/versioned/state.ts @@ -150,6 +150,7 @@ function partWayOf(m: Migration, rec: MigrationRecord, actual: string): { partWa /** Why a step apply runs on one dialect is refused in a migration of the other, or `undefined`. */ function dialectRefusal(run: string, dialect: string): string | undefined { if (run === "rebuild" && dialect !== "clickhouse") return `a ClickHouseRebuildOp step in a ${dialect} migration`; + if (run === "ormHandoff" && dialect !== "postgres") return `an orm-handoff step in a ${dialect} migration`; if (run === "pgMigration" && dialect !== "postgres") return `a PostgresMigrationOp step in a ${dialect} migration`; return undefined; } @@ -163,7 +164,9 @@ export function classifySteps(m: Migration): Pick> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' diff --git a/templates/clickhouse/.forgejo/workflows/watch-prod.yml b/templates/clickhouse/.forgejo/workflows/watch-prod.yml index 8a88fa45..162f7798 100644 --- a/templates/clickhouse/.forgejo/workflows/watch-prod.yml +++ b/templates/clickhouse/.forgejo/workflows/watch-prod.yml @@ -23,7 +23,7 @@ jobs: YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' GITHUB_TOKEN: '${{ github.token }}' steps: - - uses: https://code.forgejo.org/actions/checkout@v7 + - uses: https://code.forgejo.org/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' diff --git a/templates/clickhouse/.forgejo/workflows/yodel-apply.yml b/templates/clickhouse/.forgejo/workflows/yodel-apply.yml index 8db10e55..7d9bba7d 100644 --- a/templates/clickhouse/.forgejo/workflows/yodel-apply.yml +++ b/templates/clickhouse/.forgejo/workflows/yodel-apply.yml @@ -42,7 +42,7 @@ jobs: YODEL_WEBHOOK_URL: '${{ secrets.YODEL_WEBHOOK_URL }}' YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' steps: - - uses: https://code.forgejo.org/actions/checkout@v7 + - uses: https://code.forgejo.org/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - run: npm ci @@ -50,6 +50,13 @@ jobs: - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - name: Plan, gate and apply wave 1 (dev) run: chant run wave --spec yodel-waves.json --wave 1 + - name: Keep the job's outcome + if: always() + uses: https://code.forgejo.org/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3.2.1 + with: + name: yodel-apply-wave-1-dev-outcome + path: .chant/op-waves/yodel-apply/outcomes/outcome-wave-1.json + if-no-files-found: ignore - name: yodel report dev if: always() run: mkdir -p yodel-report; ./node_modules/.bin/yodel report dev --json > yodel-report/dev.json || true; ./node_modules/.bin/yodel report dev --html yodel-report/dev.html || true @@ -64,6 +71,7 @@ jobs: runs-on: docker needs: - wave-1-dev + if: '!cancelled()' container: node:22-bookworm env: YODEL_CREDENTIALS: writer:prod @@ -78,14 +86,25 @@ jobs: DEV_CLICKHOUSE_READER_USER: '${{ secrets.DEV_CLICKHOUSE_READER_USER }}' DEV_CLICKHOUSE_READER_PASSWORD: '${{ secrets.DEV_CLICKHOUSE_READER_PASSWORD }}' steps: - - uses: https://code.forgejo.org/actions/checkout@v7 + - uses: https://code.forgejo.org/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + - name: Download the earlier jobs' outcomes + uses: https://code.forgejo.org/actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2 + with: + path: .chant/op-waves/yodel-apply/outcomes - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - name: Plan, gate and apply wave 2 (prod) run: chant run wave --spec yodel-waves.json --wave 2 + - name: Keep the job's outcome + if: always() + uses: https://code.forgejo.org/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3.2.1 + with: + name: yodel-apply-wave-2-prod-outcome + path: .chant/op-waves/yodel-apply/outcomes/outcome-wave-2.json + if-no-files-found: ignore - name: yodel report prod if: always() run: mkdir -p yodel-report; ./node_modules/.bin/yodel report prod --json > yodel-report/prod.json || true; ./node_modules/.bin/yodel report prod --html yodel-report/prod.html || true diff --git a/templates/clickhouse/.github/workflows/watch-dev.yml b/templates/clickhouse/.github/workflows/watch-dev.yml index 8587e422..ac0e88a4 100644 --- a/templates/clickhouse/.github/workflows/watch-dev.yml +++ b/templates/clickhouse/.github/workflows/watch-dev.yml @@ -27,7 +27,7 @@ jobs: YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' GITHUB_TOKEN: '${{ github.token }}' steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' diff --git a/templates/clickhouse/.github/workflows/watch-prod.yml b/templates/clickhouse/.github/workflows/watch-prod.yml index 6e4b8b4f..24481497 100644 --- a/templates/clickhouse/.github/workflows/watch-prod.yml +++ b/templates/clickhouse/.github/workflows/watch-prod.yml @@ -27,7 +27,7 @@ jobs: YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' GITHUB_TOKEN: '${{ github.token }}' steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' diff --git a/templates/clickhouse/.github/workflows/yodel-apply.yml b/templates/clickhouse/.github/workflows/yodel-apply.yml index 847b5ad9..f64e8ab3 100644 --- a/templates/clickhouse/.github/workflows/yodel-apply.yml +++ b/templates/clickhouse/.github/workflows/yodel-apply.yml @@ -42,7 +42,7 @@ jobs: YODEL_WEBHOOK_URL: '${{ secrets.YODEL_WEBHOOK_URL }}' YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - run: npm ci @@ -50,6 +50,15 @@ jobs: - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - name: Plan, gate and apply wave 1 (dev) run: chant run wave --spec yodel-waves.json --wave 1 + - name: Keep the job's outcome + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: yodel-apply-wave-1-dev-outcome + path: .chant/op-waves/yodel-apply/outcomes/outcome-wave-1.json + if-no-files-found: ignore + include-hidden-files: true + overwrite: true - name: yodel report dev if: always() run: mkdir -p yodel-report; ./node_modules/.bin/yodel report dev --json > yodel-report/dev.json || true; ./node_modules/.bin/yodel report dev --html yodel-report/dev.html || true @@ -64,6 +73,7 @@ jobs: runs-on: ubuntu-latest needs: - wave-1-dev + if: '!cancelled()' container: node:22-bookworm environment: name: prod @@ -80,14 +90,27 @@ jobs: DEV_CLICKHOUSE_READER_USER: '${{ secrets.DEV_CLICKHOUSE_READER_USER }}' DEV_CLICKHOUSE_READER_PASSWORD: '${{ secrets.DEV_CLICKHOUSE_READER_PASSWORD }}' steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + - name: Download the earlier jobs' outcomes + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + path: .chant/op-waves/yodel-apply/outcomes - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - name: Plan, gate and apply wave 2 (prod) run: chant run wave --spec yodel-waves.json --wave 2 + - name: Keep the job's outcome + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: yodel-apply-wave-2-prod-outcome + path: .chant/op-waves/yodel-apply/outcomes/outcome-wave-2.json + if-no-files-found: ignore + include-hidden-files: true + overwrite: true - name: yodel report prod if: always() run: mkdir -p yodel-report; ./node_modules/.bin/yodel report prod --json > yodel-report/prod.json || true; ./node_modules/.bin/yodel report prod --html yodel-report/prod.html || true diff --git a/templates/clickhouse/.github/workflows/yodel-pr.yml b/templates/clickhouse/.github/workflows/yodel-pr.yml index 90d121a2..0cde88f9 100644 --- a/templates/clickhouse/.github/workflows/yodel-pr.yml +++ b/templates/clickhouse/.github/workflows/yodel-pr.yml @@ -17,6 +17,7 @@ on: permissions: contents: read pull-requests: write + actions: read concurrency: group: yodel-pr-${{ github.event.pull_request.number }} diff --git a/templates/clickhouse/.gitlab/yodel-apply.gitlab-ci.yml b/templates/clickhouse/.gitlab/yodel-apply.gitlab-ci.yml index a7e8d68c..971c2fa3 100644 --- a/templates/clickhouse/.gitlab/yodel-apply.gitlab-ci.yml +++ b/templates/clickhouse/.gitlab/yodel-apply.gitlab-ci.yml @@ -13,7 +13,8 @@ # a migration that environment's history does not record as applied. # chant Op waves "yodel-apply": one stage per wave, each needing the one before. # A wave that waits at its gate exits 3 and stops the waves after it; approve the -# digest it prints, then retry the job. +# digest it prints, then retry the job. A job whose runs failed exits 1, an allowed +# failure, and the waves after it run what does not depend on those runs. stages: - wave-1-dev @@ -37,13 +38,16 @@ wave-1-dev: - export PATH="$PWD/node_modules/.bin:$PATH" - git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - chant run wave --spec yodel-waves.json --wave 1 - after_script: - - mkdir -p yodel-report; ./node_modules/.bin/yodel report dev --json > yodel-report/dev.json || true; ./node_modules/.bin/yodel report dev --html yodel-report/dev.html || true + allow_failure: + exit_codes: + - 1 artifacts: name: yodel-report-wave-1-dev when: always paths: - yodel-report/ + after_script: + - mkdir -p yodel-report; ./node_modules/.bin/yodel report dev --json > yodel-report/dev.json || true; ./node_modules/.bin/yodel report dev --html yodel-report/dev.html || true wave-2-prod: stage: wave-2-prod @@ -65,10 +69,13 @@ wave-2-prod: - export PATH="$PWD/node_modules/.bin:$PATH" - git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - chant run wave --spec yodel-waves.json --wave 2 - after_script: - - mkdir -p yodel-report; ./node_modules/.bin/yodel report prod --json > yodel-report/prod.json || true; ./node_modules/.bin/yodel report prod --html yodel-report/prod.html || true + allow_failure: + exit_codes: + - 1 artifacts: name: yodel-report-wave-2-prod when: always paths: - yodel-report/ + after_script: + - mkdir -p yodel-report; ./node_modules/.bin/yodel report prod --json > yodel-report/prod.json || true; ./node_modules/.bin/yodel report prod --html yodel-report/prod.html || true diff --git a/templates/clickhouse/ops/migrate-dev.op.ts b/templates/clickhouse/ops/migrate-dev.op.ts index 77f8bfcd..f1eaa2f2 100644 --- a/templates/clickhouse/ops/migrate-dev.op.ts +++ b/templates/clickhouse/ops/migrate-dev.op.ts @@ -12,7 +12,7 @@ export const migrateDev = Op({ overview: "Apply the pending migrations to dev, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-dev", { plan: digest })]), + phase("Approve", [gate("approve-migrate-dev", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply dev --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/templates/clickhouse/ops/migrate-prod.op.ts b/templates/clickhouse/ops/migrate-prod.op.ts index 767fba72..a503a38d 100644 --- a/templates/clickhouse/ops/migrate-prod.op.ts +++ b/templates/clickhouse/ops/migrate-prod.op.ts @@ -12,7 +12,7 @@ export const migrateProd = Op({ overview: "Apply the pending migrations to prod, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-prod", { plan: digest })]), + phase("Approve", [gate("approve-migrate-prod", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply prod --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/templates/clickhouse/package.json b/templates/clickhouse/package.json index f29d7e5b..245ff7e5 100644 --- a/templates/clickhouse/package.json +++ b/templates/clickhouse/package.json @@ -14,9 +14,9 @@ "replay": "yodel ci --replay" }, "dependencies": { - "@intentius/chant": "0.124.25", - "@intentius/chant-lexicon-sql": "0.124.25", - "@intentius/sql-yodeler": "^0.9.0" + "@intentius/chant": "0.124.48", + "@intentius/chant-lexicon-sql": "0.124.48", + "@intentius/sql-yodeler": "^0.10.0" }, "devDependencies": { "@types/node": "^22.20.5", diff --git a/templates/postgres/.forgejo/workflows/watch-dev.yml b/templates/postgres/.forgejo/workflows/watch-dev.yml index 26f34011..c762794c 100644 --- a/templates/postgres/.forgejo/workflows/watch-dev.yml +++ b/templates/postgres/.forgejo/workflows/watch-dev.yml @@ -23,7 +23,7 @@ jobs: YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' GITHUB_TOKEN: '${{ github.token }}' steps: - - uses: https://code.forgejo.org/actions/checkout@v7 + - uses: https://code.forgejo.org/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' diff --git a/templates/postgres/.forgejo/workflows/watch-prod.yml b/templates/postgres/.forgejo/workflows/watch-prod.yml index b98867a0..9d14d6fb 100644 --- a/templates/postgres/.forgejo/workflows/watch-prod.yml +++ b/templates/postgres/.forgejo/workflows/watch-prod.yml @@ -23,7 +23,7 @@ jobs: YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' GITHUB_TOKEN: '${{ github.token }}' steps: - - uses: https://code.forgejo.org/actions/checkout@v7 + - uses: https://code.forgejo.org/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' diff --git a/templates/postgres/.forgejo/workflows/yodel-apply.yml b/templates/postgres/.forgejo/workflows/yodel-apply.yml index cdf4c91c..5c38d84c 100644 --- a/templates/postgres/.forgejo/workflows/yodel-apply.yml +++ b/templates/postgres/.forgejo/workflows/yodel-apply.yml @@ -42,7 +42,7 @@ jobs: YODEL_WEBHOOK_URL: '${{ secrets.YODEL_WEBHOOK_URL }}' YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' steps: - - uses: https://code.forgejo.org/actions/checkout@v7 + - uses: https://code.forgejo.org/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - run: npm ci @@ -50,6 +50,13 @@ jobs: - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - name: Plan, gate and apply wave 1 (dev) run: chant run wave --spec yodel-waves.json --wave 1 + - name: Keep the job's outcome + if: always() + uses: https://code.forgejo.org/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3.2.1 + with: + name: yodel-apply-wave-1-dev-outcome + path: .chant/op-waves/yodel-apply/outcomes/outcome-wave-1.json + if-no-files-found: ignore - name: yodel report dev if: always() run: mkdir -p yodel-report; ./node_modules/.bin/yodel report dev --json > yodel-report/dev.json || true; ./node_modules/.bin/yodel report dev --html yodel-report/dev.html || true @@ -64,6 +71,7 @@ jobs: runs-on: docker needs: - wave-1-dev + if: '!cancelled()' container: node:22-bookworm env: YODEL_CREDENTIALS: writer:prod @@ -78,14 +86,25 @@ jobs: DEV_POSTGRES_READER_USER: '${{ secrets.DEV_POSTGRES_READER_USER }}' DEV_POSTGRES_READER_PASSWORD: '${{ secrets.DEV_POSTGRES_READER_PASSWORD }}' steps: - - uses: https://code.forgejo.org/actions/checkout@v7 + - uses: https://code.forgejo.org/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + - name: Download the earlier jobs' outcomes + uses: https://code.forgejo.org/actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2 + with: + path: .chant/op-waves/yodel-apply/outcomes - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - name: Plan, gate and apply wave 2 (prod) run: chant run wave --spec yodel-waves.json --wave 2 + - name: Keep the job's outcome + if: always() + uses: https://code.forgejo.org/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3.2.1 + with: + name: yodel-apply-wave-2-prod-outcome + path: .chant/op-waves/yodel-apply/outcomes/outcome-wave-2.json + if-no-files-found: ignore - name: yodel report prod if: always() run: mkdir -p yodel-report; ./node_modules/.bin/yodel report prod --json > yodel-report/prod.json || true; ./node_modules/.bin/yodel report prod --html yodel-report/prod.html || true diff --git a/templates/postgres/.github/workflows/watch-dev.yml b/templates/postgres/.github/workflows/watch-dev.yml index 52da921f..9abb41c0 100644 --- a/templates/postgres/.github/workflows/watch-dev.yml +++ b/templates/postgres/.github/workflows/watch-dev.yml @@ -27,7 +27,7 @@ jobs: YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' GITHUB_TOKEN: '${{ github.token }}' steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' diff --git a/templates/postgres/.github/workflows/watch-prod.yml b/templates/postgres/.github/workflows/watch-prod.yml index 9895816a..27a43cfb 100644 --- a/templates/postgres/.github/workflows/watch-prod.yml +++ b/templates/postgres/.github/workflows/watch-prod.yml @@ -27,7 +27,7 @@ jobs: YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' GITHUB_TOKEN: '${{ github.token }}' steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' diff --git a/templates/postgres/.github/workflows/yodel-apply.yml b/templates/postgres/.github/workflows/yodel-apply.yml index 9d95eb30..ffa184c1 100644 --- a/templates/postgres/.github/workflows/yodel-apply.yml +++ b/templates/postgres/.github/workflows/yodel-apply.yml @@ -42,7 +42,7 @@ jobs: YODEL_WEBHOOK_URL: '${{ secrets.YODEL_WEBHOOK_URL }}' YODEL_WEBHOOK_KEY: '${{ secrets.YODEL_WEBHOOK_KEY }}' steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - run: npm ci @@ -50,6 +50,15 @@ jobs: - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - name: Plan, gate and apply wave 1 (dev) run: chant run wave --spec yodel-waves.json --wave 1 + - name: Keep the job's outcome + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: yodel-apply-wave-1-dev-outcome + path: .chant/op-waves/yodel-apply/outcomes/outcome-wave-1.json + if-no-files-found: ignore + include-hidden-files: true + overwrite: true - name: yodel report dev if: always() run: mkdir -p yodel-report; ./node_modules/.bin/yodel report dev --json > yodel-report/dev.json || true; ./node_modules/.bin/yodel report dev --html yodel-report/dev.html || true @@ -64,6 +73,7 @@ jobs: runs-on: ubuntu-latest needs: - wave-1-dev + if: '!cancelled()' container: node:22-bookworm environment: name: prod @@ -80,14 +90,27 @@ jobs: DEV_POSTGRES_READER_USER: '${{ secrets.DEV_POSTGRES_READER_USER }}' DEV_POSTGRES_READER_PASSWORD: '${{ secrets.DEV_POSTGRES_READER_PASSWORD }}' steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + - name: Download the earlier jobs' outcomes + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + path: .chant/op-waves/yodel-apply/outcomes - run: npm ci - run: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - run: git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - name: Plan, gate and apply wave 2 (prod) run: chant run wave --spec yodel-waves.json --wave 2 + - name: Keep the job's outcome + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: yodel-apply-wave-2-prod-outcome + path: .chant/op-waves/yodel-apply/outcomes/outcome-wave-2.json + if-no-files-found: ignore + include-hidden-files: true + overwrite: true - name: yodel report prod if: always() run: mkdir -p yodel-report; ./node_modules/.bin/yodel report prod --json > yodel-report/prod.json || true; ./node_modules/.bin/yodel report prod --html yodel-report/prod.html || true diff --git a/templates/postgres/.github/workflows/yodel-pr.yml b/templates/postgres/.github/workflows/yodel-pr.yml index ce65f993..b6a2b45e 100644 --- a/templates/postgres/.github/workflows/yodel-pr.yml +++ b/templates/postgres/.github/workflows/yodel-pr.yml @@ -17,6 +17,7 @@ on: permissions: contents: read pull-requests: write + actions: read concurrency: group: yodel-pr-${{ github.event.pull_request.number }} diff --git a/templates/postgres/.gitlab/yodel-apply.gitlab-ci.yml b/templates/postgres/.gitlab/yodel-apply.gitlab-ci.yml index a7e8d68c..971c2fa3 100644 --- a/templates/postgres/.gitlab/yodel-apply.gitlab-ci.yml +++ b/templates/postgres/.gitlab/yodel-apply.gitlab-ci.yml @@ -13,7 +13,8 @@ # a migration that environment's history does not record as applied. # chant Op waves "yodel-apply": one stage per wave, each needing the one before. # A wave that waits at its gate exits 3 and stops the waves after it; approve the -# digest it prints, then retry the job. +# digest it prints, then retry the job. A job whose runs failed exits 1, an allowed +# failure, and the waves after it run what does not depend on those runs. stages: - wave-1-dev @@ -37,13 +38,16 @@ wave-1-dev: - export PATH="$PWD/node_modules/.bin:$PATH" - git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - chant run wave --spec yodel-waves.json --wave 1 - after_script: - - mkdir -p yodel-report; ./node_modules/.bin/yodel report dev --json > yodel-report/dev.json || true; ./node_modules/.bin/yodel report dev --html yodel-report/dev.html || true + allow_failure: + exit_codes: + - 1 artifacts: name: yodel-report-wave-1-dev when: always paths: - yodel-report/ + after_script: + - mkdir -p yodel-report; ./node_modules/.bin/yodel report dev --json > yodel-report/dev.json || true; ./node_modules/.bin/yodel report dev --html yodel-report/dev.html || true wave-2-prod: stage: wave-2-prod @@ -65,10 +69,13 @@ wave-2-prod: - export PATH="$PWD/node_modules/.bin:$PATH" - git fetch --no-tags origin '+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle' && git branch -f chant/lifecycle origin/chant/lifecycle || echo 'no chant/lifecycle branch yet, so nothing is approved' - chant run wave --spec yodel-waves.json --wave 2 - after_script: - - mkdir -p yodel-report; ./node_modules/.bin/yodel report prod --json > yodel-report/prod.json || true; ./node_modules/.bin/yodel report prod --html yodel-report/prod.html || true + allow_failure: + exit_codes: + - 1 artifacts: name: yodel-report-wave-2-prod when: always paths: - yodel-report/ + after_script: + - mkdir -p yodel-report; ./node_modules/.bin/yodel report prod --json > yodel-report/prod.json || true; ./node_modules/.bin/yodel report prod --html yodel-report/prod.html || true diff --git a/templates/postgres/ops/migrate-dev.op.ts b/templates/postgres/ops/migrate-dev.op.ts index 77f8bfcd..f1eaa2f2 100644 --- a/templates/postgres/ops/migrate-dev.op.ts +++ b/templates/postgres/ops/migrate-dev.op.ts @@ -12,7 +12,7 @@ export const migrateDev = Op({ overview: "Apply the pending migrations to dev, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-dev", { plan: digest })]), + phase("Approve", [gate("approve-migrate-dev", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply dev --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/templates/postgres/ops/migrate-prod.op.ts b/templates/postgres/ops/migrate-prod.op.ts index 767fba72..a503a38d 100644 --- a/templates/postgres/ops/migrate-prod.op.ts +++ b/templates/postgres/ops/migrate-prod.op.ts @@ -12,7 +12,7 @@ export const migrateProd = Op({ overview: "Apply the pending migrations to prod, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-prod", { plan: digest })]), + phase("Approve", [gate("approve-migrate-prod", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply prod --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/templates/postgres/package.json b/templates/postgres/package.json index f29d7e5b..245ff7e5 100644 --- a/templates/postgres/package.json +++ b/templates/postgres/package.json @@ -14,9 +14,9 @@ "replay": "yodel ci --replay" }, "dependencies": { - "@intentius/chant": "0.124.25", - "@intentius/chant-lexicon-sql": "0.124.25", - "@intentius/sql-yodeler": "^0.9.0" + "@intentius/chant": "0.124.48", + "@intentius/chant-lexicon-sql": "0.124.48", + "@intentius/sql-yodeler": "^0.10.0" }, "devDependencies": { "@types/node": "^22.20.5", diff --git a/test/credentials.test.ts b/test/credentials.test.ts index ddd838ce..9dae89b6 100644 --- a/test/credentials.test.ts +++ b/test/credentials.test.ts @@ -135,7 +135,7 @@ describe("a project's reader and writer", () => { const pr = yaml(".github/workflows/yodel-pr.yml"); const jobs = pr.jobs as Record; expect(Object.keys(jobs["plan-dev"]?.env ?? {})).toEqual(["DEV_POSTGRES_URL", "DEV_POSTGRES_READER_USER", "YODEL_WEBHOOK_URL", "YODEL_WEBHOOK_KEY"]); - expect(pr.permissions).toEqual({ contents: "read", "pull-requests": "write", "id-token": "write" }); + expect(pr.permissions).toEqual({ contents: "read", "pull-requests": "write", actions: "read", "id-token": "write" }); // Every plan job tries a write first, with each reader it holds. expect(jobs["plan-dev"]?.steps.map((s) => s.run)).toContain("yodel config check dev --write-probe"); const prodSteps = (jobs["plan-prod"]?.steps ?? []).map((s) => s.run); diff --git a/test/e2e/orm-handoff.test.ts b/test/e2e/orm-handoff.test.ts new file mode 100644 index 00000000..295537df --- /dev/null +++ b/test/e2e/orm-handoff.test.ts @@ -0,0 +1,138 @@ +/** + * The ORM handoff end to end against the emulator's Postgres (#279): a + * column rename runs as a PostgresMigrationOp step, then an orm-handoff step + * marks the ORM's own migration applied. + * + * - Prisma: `prisma migrate status` reports the migration as applied and + * `prisma migrate deploy` runs nothing. Needs the prisma CLI in the project + * (the suite installs it with npm into the temporary project) and + * DATABASE_URL pointing at the emulator with ?schema=. + * - Rails: the version is a row in schema_migrations. When `rails` is on the + * PATH, `rails db:migrate:status` is also checked; the row is checked either + * way, because it is the whole of what Rails reads. + * + * Written, not run: the epic's brief is unit tests only. Run it with the + * emulator up: + * + * YODEL_E2E_POSTGRES_URL=postgres://$(ipconfig getifaddr en0):5432/postgres \ + * YODEL_E2E_POSTGRES_USER=postgres YODEL_E2E_POSTGRES_PASSWORD=chant \ + * npx vitest run test/e2e/orm-handoff.test.ts + * + * Objects in schema _orm_handoff, the history in _orm_handoff_history. + */ + +import { execFileSync } from "node:child_process"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { runChant } from "../../src/chant/process.js"; +import type { BuildOutput, BuiltObject } from "../../src/chant/build.js"; +import { createMigration, readMigrations, writeMigration, type Migration } from "../../src/migrations/index.js"; +import type { OrmHandoffOptions } from "../../src/steps/index.js"; +import { json, yodel } from "../helpers/run.js"; +import { postgres, postgresReachable, postgresUrl } from "./emulator.js"; +import { e2eProject, suiteName } from "./names.js"; + +const S = suiteName("orm_handoff"); +const HISTORY = `${S}_history`; + +const schema: BuiltObject = { export: "app", type: "Postgres::Schema", ddl: `CREATE SCHEMA ${S}`, dependsOn: [] }; +const people = (cols: string): BuiltObject => ({ export: "people", type: "Postgres::Table", ddl: `CREATE TABLE ${S}.people (${cols})`, dependsOn: ["app"] }); +const build = (cols: string): BuildOutput => ({ dialect: "postgres", objects: [schema, people(cols)] }); + +const available = (command: string, args: string[]): boolean => { + try { + execFileSync(command, args, { stdio: "ignore", timeout: 120_000 }); + return true; + } catch { + return false; + } +}; + +describe.skipIf(!postgresReachable)("the ORM handoff on postgres", () => { + let dir = ""; + let dispose = (): void => undefined; + const saved = process.env.YODEL_HISTORY_DATABASE; + const migrations = () => join(dir, "migrations"); + const at = (...args: string[]) => [...args, "--dir", dir]; + + const approvedApply = async () => { + const gated = await yodel(at("apply", "e2e", "--json")); + expect(gated.code, gated.err).toBe(3); + const command = (json(gated) as { approve?: string }).approve ?? ""; + const ran = await runChant(command.split(" ").slice(1), { cwd: dir }); + expect(ran.code, ran.stderr).toBe(0); + return yodel(at("apply", "e2e", "--json")); + }; + + /** Makes the first migration (the table with `login`) and applies it; then the rename with the handoff. */ + const rename = (handoff: OrmHandoffOptions, minute: number, to: string): Migration => { + const made = createMigration({ name: "rename-login", build: build(`id bigint PRIMARY KEY,\n ${to} text NOT NULL -- previously: ${to === "handle" ? "login" : "handle"}\n`), previous: readMigrations(migrations()).at(-1), now: new Date(Date.UTC(2026, 9, 23, 13, minute)), ormHandoff: handoff }); + if (made.id === undefined) throw new Error("no change for the rename"); + writeMigration(migrations(), made); + const m = readMigrations(migrations()).find((x) => x.id === made.id); + if (!m) throw new Error("the migration was not written"); + return m; + }; + + beforeAll(async () => { + process.env.YODEL_HISTORY_DATABASE = HISTORY; + await postgres(`DROP SCHEMA IF EXISTS ${S} CASCADE; DROP SCHEMA IF EXISTS ${HISTORY} CASCADE`); + ({ dir, dispose } = e2eProject("postgres-versioned", S)); + const first = createMigration({ name: "people", build: build("id bigint PRIMARY KEY, login text NOT NULL"), now: new Date(Date.UTC(2026, 9, 23, 12, 0)) }); + if (first.id === undefined) throw new Error("no first migration"); + writeMigration(migrations(), first); + const applied = await approvedApply(); + expect(applied.code, applied.err).toBe(0); + await postgres(`INSERT INTO ${S}.people (id, login) SELECT g, 'user' || g FROM generate_series(1, 500) g`); + }); + afterAll(async () => { + dispose(); + if (saved === undefined) delete process.env.YODEL_HISTORY_DATABASE; + else process.env.YODEL_HISTORY_DATABASE = saved; + await postgres(`DROP SCHEMA IF EXISTS ${S} CASCADE; DROP SCHEMA IF EXISTS ${HISTORY} CASCADE`); + }); + + it("Rails: the rename runs, then schema_migrations holds the version", async () => { + const version = "20261023130000"; + mkdirSync(join(dir, "db/migrate"), { recursive: true }); + writeFileSync(join(dir, "db/migrate", `${version}_rename_login.rb`), "class RenameLogin < ActiveRecord::Migration[7.1]\n def change\n rename_column :people, :login, :handle\n end\nend\n"); + const m = rename({ orm: "rails", migration: version, dbSchema: S }, 30, "handle"); + expect(m.document.steps.map((s) => (s.kind === "op" ? s.op : s.kind))).toEqual(["PostgresMigrationOp", "orm-handoff"]); + + const applied = await approvedApply(); + expect(applied.code, applied.err).toBe(0); + expect(applied.err).toMatch(/step 1: orm-handoff: mark rails migration 20261023130000 applied/); + const cols = await postgres<{ c: string }>(`SELECT column_name AS c FROM information_schema.columns WHERE table_schema = '${S}' AND table_name = 'people' ORDER BY ordinal_position`); + expect(cols.map((c) => c.c)).toEqual(["id", "handle"]); + expect(await postgres(`SELECT version FROM ${S}.schema_migrations`)).toEqual([{ version }]); + const step = (await postgres<{ note: string }>(`SELECT note FROM ${HISTORY}.history WHERE migration_id = '${m.id}' AND kind = 'step' AND statement_index = 1 AND status = 'succeeded'`))[0]; + expect(JSON.parse(step?.note ?? "{}")).toMatchObject({ op: "orm-handoff", orm: "rails", via: "insert" }); + }, 600_000); + + it.skipIf(!available("npx", ["--no-install", "prisma", "--version"]))("Prisma: migrate status reports the migration applied and migrate deploy runs nothing", async () => { + const name = "20261023140000_rename_login_again"; + const url = new URL(postgresUrl); + url.username = process.env.YODEL_E2E_POSTGRES_USER ?? "postgres"; + url.password = process.env.YODEL_E2E_POSTGRES_PASSWORD ?? ""; + url.searchParams.set("schema", S); + const env = { ...process.env, DATABASE_URL: url.toString() }; + mkdirSync(join(dir, "prisma/migrations", name), { recursive: true }); + writeFileSync(join(dir, "prisma/migrations", name, "migration.sql"), `ALTER TABLE "${S}"."people" RENAME COLUMN "handle" TO "nick";\n`); + writeFileSync(join(dir, "prisma/migrations/migration_lock.toml"), 'provider = "postgresql"\n'); + writeFileSync(join(dir, "prisma/schema.prisma"), 'datasource db {\n provider = "postgresql"\n url = env("DATABASE_URL")\n}\n\nmodel people {\n id BigInt @id\n nick String\n}\n'); + // The Prisma CLI inherits the process environment, as it does when a person runs yodel apply. + Object.assign(process.env, { DATABASE_URL: env.DATABASE_URL }); + rename({ orm: "prisma", migration: name, dbSchema: S }, 40, "nick"); + + const applied = await approvedApply(); + expect(applied.code, applied.err).toBe(0); + const status = execFileSync("npx", ["--no-install", "prisma", "migrate", "status"], { cwd: dir, env, encoding: "utf8" }); + expect(status).toMatch(/Database schema is up to date|have been applied/); + const deploy = execFileSync("npx", ["--no-install", "prisma", "migrate", "deploy"], { cwd: dir, env, encoding: "utf8" }); + expect(deploy).toMatch(/No pending migrations to apply/); + const row = (await postgres<{ checksum: string; finished: boolean }>(`SELECT checksum, finished_at IS NOT NULL AS finished FROM ${S}._prisma_migrations WHERE migration_name = '${name}'`))[0]; + expect(row?.finished).toBe(true); + expect(row?.checksum).toMatch(/^[0-9a-f]{64}$/); + }, 600_000); +}); diff --git a/test/e2e/postgres-versioned.test.ts b/test/e2e/postgres-versioned.test.ts index 6bce5588..e126e8a6 100644 --- a/test/e2e/postgres-versioned.test.ts +++ b/test/e2e/postgres-versioned.test.ts @@ -165,6 +165,9 @@ describe.skipIf(!postgresReachable)("the versioned path on postgres", () => { const applied = await approvedApply(); expect(applied.code, applied.err).toBe(0); expect((json(applied) as StatusDoc).status).toBe("applied"); + // The gate resumes (chant#3947): the second run starts at it, from the gated run's checkpoint. + expect((json(applied) as StatusDoc & { resumed?: { gate: string } }).resumed?.gate).toBe("approve-migrate-e2e"); + expect(applied.err).toContain(`[resume] at gate "approve-migrate-e2e"`); expect(applied.err).toMatch(/lock: held in Postgres advisory lock/); const after = await status(0); diff --git a/test/e2e/versioned.test.ts b/test/e2e/versioned.test.ts index 10e3471a..55c2a633 100644 --- a/test/e2e/versioned.test.ts +++ b/test/e2e/versioned.test.ts @@ -115,6 +115,9 @@ describe.skipIf(!clickhouseReachable)("the versioned path on clickhouse", () => const applied = await approvedApply(); expect(applied.code, applied.err).toBe(0); expect((json(applied) as StatusDoc).status).toBe("applied"); + // The gate resumes (chant#3947): the second run starts at it, from the gated run's checkpoint. + expect((json(applied) as StatusDoc & { resumed?: { gate: string } }).resumed?.gate).toBe("approve-migrate-e2e"); + expect(applied.err).toContain(`[resume] at gate "approve-migrate-e2e"`); // No Keeper on the emulator: the run says the lock is local. expect(applied.err).toContain("cross-runner locking needs Keeper"); expect(await count(`EXISTS TABLE ${DB}.a`)).toBe(1); diff --git a/test/fixtures/clickhouse-versioned/ops/migrate-e2e.op.ts b/test/fixtures/clickhouse-versioned/ops/migrate-e2e.op.ts index 24ed1f2c..6b6fc7bd 100644 --- a/test/fixtures/clickhouse-versioned/ops/migrate-e2e.op.ts +++ b/test/fixtures/clickhouse-versioned/ops/migrate-e2e.op.ts @@ -8,7 +8,7 @@ export const op = Op({ overview: "Apply the pending migrations to e2e, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-e2e", { plan: digest })]), + phase("Approve", [gate("approve-migrate-e2e", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply e2e --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/test/fixtures/postgres-versioned/ops/migrate-e2e.op.ts b/test/fixtures/postgres-versioned/ops/migrate-e2e.op.ts index 24ed1f2c..6b6fc7bd 100644 --- a/test/fixtures/postgres-versioned/ops/migrate-e2e.op.ts +++ b/test/fixtures/postgres-versioned/ops/migrate-e2e.op.ts @@ -8,7 +8,7 @@ export const op = Op({ overview: "Apply the pending migrations to e2e, behind an approval bound to their plan digest", phases: [ phase("Plan", [plan]), - phase("Approve", [gate("approve-migrate-e2e", { plan: digest })]), + phase("Approve", [gate("approve-migrate-e2e", { plan: digest, resume: true })]), phase("Apply", [shell("yodel apply e2e --execute", { env: { YODEL_APPROVED_PLAN: digest }, timeout: "2h" })]), ], }); diff --git a/test/gate-resume.test.ts b/test/gate-resume.test.ts new file mode 100644 index 00000000..d168d41e --- /dev/null +++ b/test/gate-resume.test.ts @@ -0,0 +1,182 @@ +/** + * The migrations Op's gate on chant 0.124.46: the run after an approval + * resumes at the gate (chant#3947), and a renamed gate keeps its recorded + * approvals through an alias (chant#3949). + * + * These run the real `chant run` and `chant approve` on the starter + * template's Op, in a git repository of its own. The `yodel` on the Op's + * PATH is a stand-in that prints a fixed digest for `--digest` and logs each + * call, so no server is needed. The e2e suite (test/e2e/versioned.test.ts) + * checks the same resume against a server through `yodel apply`. + */ + +import { execFileSync } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { delimiter, join, resolve } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { memoryGateLedgerPort } from "@intentius/chant/op/gate"; +import { GATED, readApplyRun } from "../src/chant/apply.js"; +import { runChant } from "../src/chant/process.js"; +import { chantApproveArgs } from "../src/commands/approve.js"; +import { projectFromConfig } from "../src/project.js"; +import { gitLedger, NOT_APPROVED, verifyApproval } from "../src/versioned/approval.js"; +import { migrateOpParts, selectMigrateOp, type MigrateOpRef } from "../src/versioned/op.js"; + +const ROOT = resolve(import.meta.dirname, ".."); +const TEMPLATE_OP = readFileSync(join(ROOT, "templates/postgres/ops/migrate-dev.op.ts"), "utf8"); +const DIGEST = `jcs1-sha256:${"a".repeat(64)}`; + +const dirs: string[] = []; +afterEach(() => { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); +}); + +/** A git repository holding the template's migrate-dev Op, a stand-in yodel, and the worktree's node_modules. */ +function repo(op = TEMPLATE_OP) { + const dir = mkdtempSync(join(tmpdir(), "yodel-gate-resume-")); + dirs.push(dir); + symlinkSync(join(ROOT, "node_modules"), join(dir, "node_modules")); + mkdirSync(join(dir, "ops")); + mkdirSync(join(dir, "bin")); + const log = join(dir, "yodel.log"); + writeFileSync( + join(dir, "bin", "yodel"), + `#!/bin/sh\necho "$*" >> '${log}'\ncase "$3" in --digest) echo '${DIGEST}';; --execute) echo "applied $YODEL_APPROVED_PLAN";; esac\n`, + ); + chmodSync(join(dir, "bin", "yodel"), 0o755); + writeFileSync(join(dir, ".gitignore"), "node_modules\nyodel.log\n"); + writeFileSync(join(dir, "ops", "migrate-dev.op.ts"), op); + const git = (...args: string[]) => execFileSync("git", ["-c", "user.name=tester", "-c", "user.email=tester@example.com", "-c", "commit.gpgsign=false", ...args], { cwd: dir, stdio: "pipe" }); + git("init", "-q", "-b", "main"); + git("add", "-A"); + git("commit", "-qm", "init"); + const env = { ...process.env, PATH: [join(dir, "bin"), process.env.PATH ?? ""].join(delimiter) }; + const run = async () => { + const r = await runChant(["run", "migrate-dev", "--gated-exit", String(GATED)], { cwd: dir, env }); + return readApplyRun(r.code, `${r.stdout}\n${r.stderr}`); + }; + const approve = async (gate: string) => { + const r = await runChant(chantApproveArgs("migrate-dev", gate, DIGEST, false, { actor: "tester" }), { cwd: dir, env }); + expect(r.code, r.stderr).toBe(0); + return r; + }; + const calls = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : []); + const commit = (file: string, text: string) => { + writeFileSync(join(dir, file), text); + git("add", "-A"); + git("commit", "-qm", `edit ${file}`); + }; + return { dir, run, approve, calls, commit }; +} + +const project = projectFromConfig("/p", "/p/chant.config.ts", { lexicons: ["sql"], sql: { dialect: "postgres" } }); +const dev = { name: "dev", profile: { url: "postgres://x:5432/app" } }; + +/** The project's migrations Op for dev, as yodel apply finds it. */ +async function findOp(dir: string): Promise { + const { discoverOps } = await import("@intentius/chant/op/discover"); + const found = await discoverOps({ cwd: dir }); + return selectMigrateOp(found.ops, project, dev); +} + +describe("the run after yodel approve (chant#3947)", () => { + it("resumes at the template's gate: chant reports the gate it resumed at, the plan runs again, the apply once", async () => { + expect(TEMPLATE_OP).toContain(`gate("approve-migrate-dev", { plan: digest, resume: true })`); + const r = repo(); + + const gated = await r.run(); + expect(gated.status).toBe("gated"); + expect(gated.planDigest).toBe(DIGEST); + expect(gated.output).toMatch(/resume\s*: once approved, the next run starts at this gate \(checkpoint jcs1-sha256:[0-9a-f]{64}\)/); + expect(gated.resumed).toBeUndefined(); + + const approved = await r.approve("approve-migrate-dev"); + expect(approved.stderr).toMatch(/The next run resumes at this gate from run \S+'s checkpoint jcs1-sha256:[0-9a-f]{64}/); + + const second = await r.run(); + expect(second.status, second.output).toBe("applied"); + expect(second.resumed).toMatchObject({ gate: "approve-migrate-dev", checkpoint: expect.stringMatching(/^jcs1-sha256:[0-9a-f]{64}$/) as unknown }); + expect(r.calls()).toEqual(["apply dev --digest", "apply dev --digest", "apply dev --execute"]); + + // --execute's own check reads the same ledger and finds the approval. + await expect(verifyApproval(await gitLedger(r.dir), await findOp(r.dir), DIGEST)).resolves.toMatchObject({ resolvedBy: "tester" }); + }); + + it("starts at the first phase when the Op's commit moved since the gated run, and still applies on the approval", async () => { + const r = repo(); + await r.run(); + await r.approve("approve-migrate-dev"); + r.commit("README.md", "another commit\n"); + const second = await r.run(); + expect(second.status, second.output).toBe("applied"); + expect(second.resumed).toBeUndefined(); + expect(second.output).toMatch(/\[resume\] .*commit/); + }); +}); + +describe("renaming the migrations Op's gate (chant#3949)", () => { + const renamed = (aliases: string) => TEMPLATE_OP.replace(`gate("approve-migrate-dev", { plan: digest, resume: true })`, `gate("approve-dev", { plan: digest${aliases} })`); + + it("keeps the approval recorded under the old name through an alias, and --execute counts the carried line", async () => { + const r = repo(); + expect((await r.run()).status).toBe("gated"); + await r.approve("approve-migrate-dev"); + + r.commit("ops/migrate-dev.op.ts", renamed(`, aliases: [{ gate: "approve-migrate-dev" }]`)); + const op = await findOp(r.dir); + expect(op).toMatchObject({ gate: "approve-dev", aliases: [{ op: "migrate-dev", gate: "approve-migrate-dev" }] }); + + const after = await r.run(); + expect(after.status, after.output).toBe("applied"); + expect(after.output).toContain("[carried] tester's approval of migrate-dev/approve-migrate-dev"); + expect(r.calls().filter((c) => c.endsWith("--execute"))).toHaveLength(1); + + const ledger = await gitLedger(r.dir); + await expect(verifyApproval(ledger, op, DIGEST)).resolves.toMatchObject({ resolvedBy: "tester" }); + // Drop the alias and the carried line stops counting, as it does for chant's gate. + await expect(verifyApproval(ledger, { ...op, aliases: [] }, DIGEST)).rejects.toMatchObject({ exitCode: NOT_APPROVED }); + }); + + it("without the alias, the renamed gate asks for approval again", async () => { + const r = repo(); + await r.run(); + await r.approve("approve-migrate-dev"); + r.commit("ops/migrate-dev.op.ts", renamed("")); + const after = await r.run(); + expect(after.status).toBe("gated"); + expect(r.calls().filter((c) => c.endsWith("--execute"))).toHaveLength(0); + }); +}); + +describe("the gate's parts as yodel reads them", () => { + const plan = { kind: "activity" as const, fn: "shellCmd", id: "plan", args: { cmd: "yodel apply dev --digest" } }; + const execute = { kind: "activity" as const, fn: "shellCmd", args: { cmd: "yodel apply dev --execute", env: {} } }; + const gate = (extra: Record) => ({ kind: "gate" as const, gate: "approve-dev", plan: { kind: "step-output-ref", step: "plan", path: "stdout" }, ...extra }); + const config = (g: unknown) => ({ name: "migrate-dev", overview: "", phases: [{ name: "all", steps: [plan, g, execute] }] }) as never; + + it("names each alias's Op, this one when the alias leaves it out", () => { + expect(migrateOpParts(config(gate({ aliases: [{ gate: "old" }, { op: "migrate-dev-legacy", gate: "approve" }] })), "dev")).toEqual({ + gate: "approve-dev", + quorum: false, + aliases: [{ op: "migrate-dev", gate: "old" }, { op: "migrate-dev-legacy", gate: "approve" }], + }); + expect(migrateOpParts(config(gate({})), "dev")).toEqual({ gate: "approve-dev", quorum: false }); + }); + + it("reads chant's resume line off a run's output", () => { + const out = `[resume] at gate "approve-dev", from run local-1's checkpoint jcs1-sha256:${"c".repeat(64)}\n[phase] Plan\n`; + expect(readApplyRun(0, out).resumed).toEqual({ gate: "approve-dev", run: "local-1", checkpoint: `jcs1-sha256:${"c".repeat(64)}` }); + expect(readApplyRun(0, "[phase] Plan\n").resumed).toBeUndefined(); + }); + + it("counts a carried approval only while the gate lists the alias it came from", async () => { + const op: MigrateOpRef = { name: "migrate-dev", filePath: "/p/ops/migrate-dev.op.ts", gate: "approve-dev", quorum: false, aliases: [{ op: "migrate-dev", gate: "old" }] }; + const carried = (from: string) => + memoryGateLedgerPort({ + resolutions: [{ version: 1, op: op.name, gate: op.gate, resolvedBy: "alice", timestamp: "2026-10-09T12:00:00.000Z", planDigest: DIGEST, carriedFrom: { op: "migrate-dev", gate: from, timestamp: "2026-10-09T11:00:00.000Z" } }], + }); + await expect(verifyApproval(carried("old"), op, DIGEST)).resolves.toMatchObject({ resolvedBy: "alice" }); + await expect(verifyApproval(carried("older"), op, DIGEST)).rejects.toMatchObject({ exitCode: NOT_APPROVED }); + }); +}); diff --git a/test/init-unsupported.test.ts b/test/init-unsupported.test.ts index ccc72e1b..277d123e 100644 --- a/test/init-unsupported.test.ts +++ b/test/init-unsupported.test.ts @@ -12,28 +12,29 @@ import { describeUnsupported } from "../src/init/unsupported.js"; import { renderDrift } from "../src/chant/drift.js"; describe("the kinds yodel refuses", () => { - it("are the ones chant's coverage table refuses: composite types, aggregates and quotas adopt now, operators and foreign tables do not", () => { + it("are the ones chant's coverage table refuses: composite types, aggregates, quotas, operators and publications adopt now, foreign tables and operator classes do not", () => { const status = (dialect: "postgres" | "clickhouse", kind: string) => KIND_COVERAGE[dialect].find((r) => r.kind === kind)?.status; for (const k of ["composite type", "range type", "aggregate", "collation", "cast", "event trigger"]) expect(status("postgres", k), k).toBe("declared"); - for (const k of ["operator", "foreign table", "publication"]) expect(status("postgres", k), k).toBe("refused"); + for (const k of ["operator", "publication", "foreign data wrapper", "foreign server", "extended statistics"]) expect(status("postgres", k), k).toBe("declared"); + for (const k of ["foreign table", "operator class", "subscription"]) expect(status("postgres", k), k).toBe("refused"); for (const k of ["quota", "settings profile"]) expect(status("clickhouse", k), k).toBe("declared"); - expect(status("clickhouse", "named collection")).toBe("refused"); + expect(status("clickhouse", "named collection")).toBe("referenced"); }); it("are described as chant describes them, with the schema when there is one", () => { - expect(describeUnsupported({ kind: "operator", schema: "shop", name: "===(integer,integer)" })).toBe("operator shop.===(integer,integer)"); - expect(describeUnsupported({ kind: "publication", name: "pub" })).toBe("publication pub"); + expect(describeUnsupported({ kind: "operator class", schema: "shop", name: "ops" })).toBe("operator class shop.ops"); + expect(describeUnsupported({ kind: "subscription", name: "sub" })).toBe("subscription sub"); }); }); describe("yodel init --from", () => { - const found = [describeUnsupported({ kind: "operator", schema: "shop", name: "===(integer,integer)" }), describeUnsupported({ kind: "foreign table", schema: "shop", name: "remote" })]; + const found = [describeUnsupported({ kind: "operator class", schema: "shop", name: "ops" }), describeUnsupported({ kind: "foreign table", schema: "shop", name: "remote" })]; it("refuses (exit 4) naming each object, and adopts with --skip-unsupported", () => { const refusal = unsupportedRefusal("prod", found, false); expect(refusal?.exitCode).toBe(4); expect(refusal?.message).toContain("prod holds 2 objects of a kind chant's sql lexicon cannot declare"); - expect(refusal?.message).toContain(" operator shop.===(integer,integer)\n foreign table shop.remote"); + expect(refusal?.message).toContain(" operator class shop.ops\n foreign table shop.remote"); expect(refusal?.message).toContain("--skip-unsupported"); expect(unsupportedRefusal("prod", found, true)).toBeUndefined(); expect(unsupportedRefusal("prod", [], false)).toBeUndefined(); @@ -41,14 +42,14 @@ describe("yodel init --from", () => { it("records what --skip-unsupported left out in the baseline's note", () => { const row = baselineRow({ id: "20261012T0000-baseline", parent: null, checksum: "sha256:x" }, { seq: 1, runId: "r", appliedBy: "a", environment: "prod", skipped: found }); - expect(row.note).toBe("baseline: adopted from the live database by yodel init --from prod; its statements were not run; not adopted, of kinds yodel cannot declare: operator shop.===(integer,integer), foreign table shop.remote"); + expect(row.note).toBe("baseline: adopted from the live database by yodel init --from prod; its statements were not run; not adopted, of kinds yodel cannot declare: operator class shop.ops, foreign table shop.remote"); }); }); describe("yodel drift", () => { it("lists objects of kinds yodel cannot declare as unmanaged, apart from drift", () => { - const text = renderDrift({ environment: "prod", changed: [], missing: [], unobserved: [], unmanaged: ["operator shop.===(integer,integer)"] }); + const text = renderDrift({ environment: "prod", changed: [], missing: [], unobserved: [], unmanaged: ["operator class shop.ops"] }); expect(text).toContain("No drift: every declared object matches the server."); - expect(text).toContain("Unmanaged (a kind yodel cannot declare, so never drift):\n operator shop.===(integer,integer)"); + expect(text).toContain("Unmanaged (a kind yodel cannot declare, so never drift):\n operator class shop.ops"); }); }); diff --git a/test/orm-handoff.test.ts b/test/orm-handoff.test.ts new file mode 100644 index 00000000..e52007c5 --- /dev/null +++ b/test/orm-handoff.test.ts @@ -0,0 +1,255 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import type { MigrationStep } from "@intentius/chant-lexicon-sql/migration-statements"; +import { projectFromConfig } from "../src/project.js"; +import { classifySteps, closeVersioned, currentDigest, executeApply, inspect, openVersioned, selectToApply, type VersionedEnv } from "../src/versioned/index.js"; +import { + asOrmHandoff, + describeStep, + ormHandoffOptions, + ormHandoffRefusal, + ormHandoffStep, + planStep, + runOrmHandoff, + stepSha, + type HandoffExec, + type OrmHandoffOptions, + type StepRunner, +} from "../src/steps/index.js"; +import { FakePgServer } from "./helpers/fake-postgres.js"; +import { migration } from "./helpers/fake-clickhouse.js"; +import { createMigration, type Migration } from "../src/migrations/index.js"; + +const dirs: string[] = []; +afterAll(() => { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); +}); + +/** A project directory holding a Prisma migration and a Rails one. */ +function repo(): string { + const d = mkdtempSync(join(tmpdir(), "yodel-handoff-")); + dirs.push(d); + mkdirSync(join(d, "prisma/migrations/20261009120000_rename_login"), { recursive: true }); + writeFileSync(join(d, "prisma/migrations/20261009120000_rename_login/migration.sql"), 'ALTER TABLE "users" RENAME COLUMN "login" TO "handle";\n'); + mkdirSync(join(d, "db/migrate"), { recursive: true }); + writeFileSync(join(d, "db/migrate/20261009120000_rename_login.rb"), "class RenameLogin < ActiveRecord::Migration[7.1]; end\n"); + return d; +} + +const PRISMA: OrmHandoffOptions = { orm: "prisma", migration: "20261009120000_rename_login", dbSchema: "app" }; +const RAILS: OrmHandoffOptions = { orm: "rails", migration: "20261009120000", dbSchema: "app" }; + +/** A stand-in for the server: the ORM's table holds `recorded` and every query is kept. */ +function fakeServer(recorded: Array> = [], missingTable = false) { + const queries: Array<{ sql: string; params?: readonly unknown[] | undefined }> = []; + const client = { + query(sql: string, params?: readonly unknown[]): Promise { + queries.push({ sql, params }); + if (sql.startsWith("SELECT")) { + if (missingTable) return Promise.reject(new Error(`relation "app._prisma_migrations" does not exist`)); + return Promise.resolve(recorded as T[]); + } + return Promise.resolve([]); + }, + }; + return { client, queries }; +} + +describe("the orm-handoff step's options", () => { + const step = (options: unknown): MigrationStep => ({ ...ormHandoffStep("m", PRISMA), options: options as Record }); + it("plans a Prisma or Rails handoff", () => { + expect(planStep(ormHandoffStep("m", PRISMA))).toEqual({ run: "ormHandoff", options: PRISMA }); + expect(planStep(ormHandoffStep("m", RAILS))).toEqual({ run: "ormHandoff", options: RAILS }); + expect(describeStep(ormHandoffStep("m", RAILS))).toBe("orm-handoff: mark rails migration 20261009120000 applied"); + expect(asOrmHandoff(ormHandoffStep("m", RAILS))).toBeDefined(); + }); + it("refuses an ORM it does not know, a bad name, a path outside the project and a stray option", () => { + const why = (o: unknown) => { + const p = planStep(step(o)); + return p.run === "refused" ? p.reason : p.run; + }; + expect(why({ orm: "django", migration: "0001" })).toMatch(/options.orm is "django"; yodel hands off to prisma and rails/); + expect(why({ orm: "prisma", migration: "../x" })).toMatch(/names a Prisma migration directory/); + expect(why({ orm: "rails", migration: "rename_login" })).toMatch(/Rails migration version/); + expect(why({ orm: "prisma", migration: "a", dir: "../outside" })).toMatch(/options.dir is a path inside the project/); + expect(why({ orm: "rails", migration: "1", table: 'x"; DROP' })).toMatch(/options.table is an unquoted SQL name/); + expect(why({ orm: "rails", migration: "1", schema: "x" })).toMatch(/"schema" is not an option of a rails handoff/); + expect(ormHandoffOptions(null)).toEqual({ problem: "its options are an object" }); + }); +}); + +describe("refusing a handoff that cannot work", () => { + it("refuses when the ORM migration is not in the repository", async () => { + const projectDir = repo(); + const read = () => Promise.resolve([]); + const prisma = await ormHandoffRefusal({ ...PRISMA, migration: "20270101000000_gone" }, { projectDir, read }); + expect(prisma).toMatch(/Prisma migration 20270101000000_gone is not in the repository \(looked for prisma\/migrations\/20270101000000_gone\/migration.sql\)/); + const rails = await ormHandoffRefusal({ ...RAILS, migration: "20270101000000" }, { projectDir, read }); + expect(rails).toMatch(/Rails migration 20270101000000 is not in the repository \(looked for db\/migrate\/20270101000000_\*.rb\)/); + // A directory without migration.sql is not a migration. + mkdirSync(join(projectDir, "prisma/migrations/20270202000000_empty")); + expect(await ormHandoffRefusal({ ...PRISMA, migration: "20270202000000_empty" }, { projectDir, read })).toMatch(/not in the repository/); + }); + + it("refuses when the ORM already records the migration as applied", async () => { + const projectDir = repo(); + const read = (sql: string) => Promise.resolve(sql.includes("_prisma_migrations") || sql.includes("schema_migrations") ? [{ applied: 1 }] : []); + expect(await ormHandoffRefusal(PRISMA, { projectDir, read })).toMatch(/Prisma already records 20261009120000_rename_login as applied \("app"._prisma_migrations\)/); + expect(await ormHandoffRefusal(RAILS, { projectDir, read })).toMatch(/Rails already records 20261009120000 as applied \("app"."schema_migrations"\)/); + }); + + it("counts a Prisma row as applied only when it is finished, and an ORM table that is not there as empty", async () => { + const projectDir = repo(); + const seen: string[] = []; + const read = (sql: string) => { + seen.push(sql); + return Promise.resolve([]); + }; + expect(await ormHandoffRefusal(PRISMA, { projectDir, read })).toBeUndefined(); + expect(seen[0]).toBe(`SELECT 1 AS applied FROM "app"._prisma_migrations WHERE migration_name = '20261009120000_rename_login' AND finished_at IS NOT NULL`); + const none = () => Promise.reject(new Error('relation "app.schema_migrations" does not exist')); + expect(await ormHandoffRefusal(RAILS, { projectDir, read: none })).toBeUndefined(); + const broken = () => Promise.reject(new Error("permission denied for table x")); + await expect(ormHandoffRefusal(RAILS, { projectDir, read: broken })).rejects.toThrow(/permission denied/); + }); +}); + +describe("running the handoff", () => { + it("Rails: creates the table when it is not there and inserts the version", async () => { + const projectDir = repo(); + const { client, queries } = fakeServer(); + const { summary } = await runOrmHandoff(RAILS, { projectDir, client }); + expect(summary).toEqual({ op: "orm-handoff", orm: "rails", migration: "20261009120000", via: "insert", table: '"app"."schema_migrations"' }); + expect(queries.slice(1).map((q) => q.sql)).toEqual([ + `CREATE TABLE IF NOT EXISTS "app"."schema_migrations" ("version" character varying NOT NULL PRIMARY KEY)`, + `INSERT INTO "app"."schema_migrations" ("version") VALUES ($1)`, + ]); + expect(queries[2]?.params).toEqual(["20261009120000"]); + }); + + it("Rails: writes nothing when the migration is missing or recorded", async () => { + const projectDir = repo(); + const recorded = fakeServer([{ applied: 1 }]); + await expect(runOrmHandoff(RAILS, { projectDir, client: recorded.client })).rejects.toThrow(/already records/); + expect(recorded.queries.filter((q) => !q.sql.startsWith("SELECT"))).toEqual([]); + const missing = fakeServer(); + await expect(runOrmHandoff({ ...RAILS, migration: "99" }, { projectDir, client: missing.client })).rejects.toThrow(/not in the repository/); + expect(missing.queries).toEqual([]); + }); + + it("Prisma: runs prisma migrate resolve --applied in the project and checks the row", async () => { + const projectDir = repo(); + const calls: Array<{ command: string; args: string[]; cwd: string }> = []; + const server = fakeServer(); + // The CLI writes the row; the next read finds it. + const exec: HandoffExec = (command, args, cwd) => { + calls.push({ command, args, cwd }); + server.client.query = (sql: string) => Promise.resolve((sql.startsWith("SELECT") ? [{ applied: 1 }] : []) as T[]); + return Promise.resolve({ code: 0, output: "Migration 20261009120000_rename_login marked as applied." }); + }; + const { summary } = await runOrmHandoff({ ...PRISMA, schema: "prisma/schema.prisma" }, { projectDir, client: server.client, exec }); + expect(calls).toEqual([{ command: "npx", args: ["--no-install", "prisma", "migrate", "resolve", "--applied", "20261009120000_rename_login", "--schema", "prisma/schema.prisma"], cwd: projectDir }]); + expect(summary).toMatchObject({ orm: "prisma", via: "prisma migrate resolve", table: '"app"._prisma_migrations' }); + }); + + it("Prisma: does not run the CLI for a missing or recorded migration, and fails on its exit or on another database", async () => { + const projectDir = repo(); + const never: HandoffExec = () => Promise.reject(new Error("the CLI must not run")); + await expect(runOrmHandoff({ ...PRISMA, migration: "20270101000000_gone" }, { projectDir, client: fakeServer().client, exec: never })).rejects.toThrow(/not in the repository/); + await expect(runOrmHandoff(PRISMA, { projectDir, client: fakeServer([{ applied: 1 }]).client, exec: never })).rejects.toThrow(/already records/); + const failing: HandoffExec = () => Promise.resolve({ code: 1, output: "P3008 The migration is already recorded as applied" }); + await expect(runOrmHandoff(PRISMA, { projectDir, client: fakeServer().client, exec: failing })).rejects.toThrow(/exited 1: P3008/); + const ok: HandoffExec = () => Promise.resolve({ code: 0, output: "" }); + await expect(runOrmHandoff(PRISMA, { projectDir, client: fakeServer().client, exec: ok })).rejects.toThrow(/no finished row for it/); + }); +}); + +describe("the step in a migration", () => { + const SCHEMA = "yodel_279_history"; + const handoff = ormHandoffStep("rename-login", { orm: "prisma", migration: "20261009120000_rename_login", dbSchema: "yodel_279" }); + const stmt = (sql: string): MigrationStep => ({ kind: "statement", object: "users", type: "Postgres::Table", name: "yodel_279.users", sql, rule: "SQLPG200", class: "create", transactional: true }); + const pgMigration = (id: string, steps: MigrationStep[], dialect: "postgres" | "clickhouse" = "postgres"): Migration => { + const m = migration(id, null, steps); + return { ...m, document: { ...m.document, dialect } }; + }; + + const setup = async (projectDir: string, recorded: boolean) => { + const server = new FakePgServer(); + const project = projectFromConfig(projectDir, join(projectDir, "chant.config.ts"), { lexicons: ["sql"], sql: { dialect: "postgres", profiles: { e2e: { url: "postgres://pg:5432/db", schemas: ["yodel_279"] } } } }); + const venv = await openVersioned(project, { name: "e2e", profile: { url: "postgres://pg:5432/db" } }, { YODEL_HISTORY_DATABASE: SCHEMA }, undefined, () => server.connect()); + venv.driver.liveFingerprint = () => Promise.resolve("sha256:fake"); + const asked: string[] = []; + venv.driver.readCheck = (sql) => { + asked.push(sql); + return Promise.resolve(recorded ? [{ applied: 1 }] : []); + }; + return { server, venv, asked }; + }; + const apply = async (venv: VersionedEnv, ordered: Migration[], runStep: StepRunner) => { + const { status } = await inspect(venv, ordered); + const digest = await currentDigest(venv, status, selectToApply(status, false)); + return executeApply(venv, ordered, { approvedDigest: digest, allowOutOfOrder: false, approve: () => Promise.resolve(), log: () => undefined, runStep, processEnv: { USER: "tester" } }); + }; + + it("hashes into the history like any step, and changes with its options", async () => { + const m = pgMigration("20261009T1000-rename", [stmt("CREATE TABLE yodel_279.users (id bigint)"), handoff]); + const { server, venv } = await setup(repo(), false); + const ran: number[] = []; + await apply(venv, [m], (ctx) => { + ran.push(ctx.index); + return Promise.resolve({ summary: { op: "orm-handoff", orm: "prisma" } }); + }); + expect(ran).toEqual([1]); + expect(server.sent).toEqual(["CREATE TABLE yodel_279.users (id bigint)"]); + const rows = server.rows.filter((r) => r.kind === "step"); + expect(rows.map((r) => r.status)).toEqual(["started", "succeeded"]); + expect(rows[1]).toMatchObject({ statement_index: 1, statement_sha: stepSha(handoff), note: JSON.stringify({ op: "orm-handoff", orm: "prisma" }) }); + expect(stepSha(handoff)).toMatch(/^sha256:[0-9a-f]{64}$/); + expect(stepSha(handoff)).toBe(stepSha(ormHandoffStep("rename-login", { orm: "prisma", migration: "20261009120000_rename_login", dbSchema: "yodel_279" }))); + expect(stepSha(handoff)).not.toBe(stepSha(ormHandoffStep("rename-login", { orm: "prisma", migration: "20261010000000_other", dbSchema: "yodel_279" }))); + await closeVersioned(venv); + }); + + it("refuses the migration before its first statement when the ORM migration is missing", async () => { + const m = pgMigration("20261009T1000-rename", [stmt("CREATE TABLE yodel_279.users (id bigint)"), ormHandoffStep("rename-login", { orm: "prisma", migration: "20270101000000_gone", dbSchema: "yodel_279" })]); + const { server, venv } = await setup(repo(), false); + const runStep: StepRunner = () => Promise.reject(new Error("no step may run")); + await expect(apply(venv, [m], runStep)).rejects.toMatchObject({ exitCode: 4, message: expect.stringContaining("Nothing of 20261009T1000-rename was applied") as unknown }); + expect(server.sent).toEqual([]); + await closeVersioned(venv); + }); + + it("refuses the migration before its first statement when the ORM already records it", async () => { + const m = pgMigration("20261009T1000-rename", [stmt("CREATE TABLE yodel_279.users (id bigint)"), handoff]); + const { server, venv, asked } = await setup(repo(), true); + await expect(apply(venv, [m], () => Promise.reject(new Error("no step may run")))).rejects.toThrow(/Prisma already records 20261009120000_rename_login as applied/); + expect(asked[0]).toContain(`"yodel_279"._prisma_migrations`); + expect(server.sent).toEqual([]); + await closeVersioned(venv); + }); + + it("is refused when it is not the migration's last step or the migration is not Postgres", () => { + const early = pgMigration("20261009T1000-rename", [handoff, stmt("CREATE TABLE yodel_279.users (id bigint)")]); + expect(classifySteps(early).refusedSteps[0]?.reason).toMatch(/not 20261009T1000-rename's last/); + const last = pgMigration("20261009T1001-rename", [stmt("CREATE TABLE yodel_279.users (id bigint)"), handoff]); + expect(classifySteps(last)).toMatchObject({ opSteps: [{ index: 1 }], refusedSteps: [] }); + const ch = pgMigration("20261009T1002-rename", [handoff], "clickhouse"); + expect(classifySteps(ch).refusedSteps[0]?.reason).toBe("an orm-handoff step in a clickhouse migration"); + }); +}); + +describe("yodel's migration writer", () => { + it("ends a migration with the handoff, in its checksum", () => { + const build = { dialect: "postgres" as const, objects: [{ export: "app", type: "Postgres::Schema", ddl: "CREATE SCHEMA app", dependsOn: [] }] }; + const now = new Date(Date.UTC(2026, 9, 23, 12, 0)); + const made = createMigration({ name: "first", build, now, ormHandoff: PRISMA }); + const plain = createMigration({ name: "first", build, now }); + if (made.id === undefined || plain.id === undefined) throw new Error("expected migrations"); + expect(made.document.steps.at(-1)).toMatchObject({ kind: "op", op: "orm-handoff", options: PRISMA }); + expect(made.document.refused).toBe(true); + expect(made.document.checksum).not.toBe(plain.document.checksum); + expect(made.files.sql).toContain("orm-handoff"); + }); +}); diff --git a/test/overdue.test.ts b/test/overdue.test.ts new file mode 100644 index 00000000..4ee203c1 --- /dev/null +++ b/test/overdue.test.ts @@ -0,0 +1,120 @@ +/** + * src/pr/overdue.ts: `yodel plan --comment` warns when the environment's + * drift watch has not run for two fires of its cron (chant#4289). The + * project is the starter template's ops and rendered pipelines, in a git + * repository of its own; the forge is chant's client over a fake fetch, or + * a stand-in where only the verdict matters. + */ + +import { execFileSync } from "node:child_process"; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import type { ForgeFetch, PrForge } from "@intentius/chant/pr-forge"; +import { GITLAB_WATCH_FILE } from "../src/ci/render.js"; +import { resolveForge } from "../src/pr/forge.js"; +import { GITLAB_WATCH, overdueNotes, watchPipelineFile } from "../src/pr/overdue.js"; +import { commentMarker, renderPlanMarkdown } from "../src/pr/render.js"; + +const ROOT = resolve(import.meta.dirname, ".."); +const TEMPLATE = join(ROOT, "templates/postgres"); +const NOW = new Date("2026-10-23T12:00:00.000Z"); + +const dir = mkdtempSync(join(tmpdir(), "yodel-overdue-")); +afterAll(() => { + rmSync(dir, { recursive: true, force: true }); +}); +symlinkSync(join(ROOT, "node_modules"), join(dir, "node_modules")); +mkdirSync(join(dir, "ops")); +for (const f of ["ops/watch-dev.op.ts", "ops/watch-prod.op.ts", ".github/workflows/watch-dev.yml", ".github/workflows/watch-prod.yml", GITLAB_WATCH]) cpSync(join(TEMPLATE, f), join(dir, f)); +{ + const git = (...args: string[]) => execFileSync("git", ["-c", "user.name=tester", "-c", "user.email=tester@example.com", "-c", "commit.gpgsign=false", ...args], { cwd: dir, stdio: "pipe", env: { ...process.env, GIT_COMMITTER_DATE: "2026-09-01T00:00:00Z", GIT_AUTHOR_DATE: "2026-09-01T00:00:00Z" } }); + execFileSync("sh", ["-c", "printf 'node_modules\\n' > .gitignore"], { cwd: dir }); + git("init", "-q", "-b", "main"); + git("add", "-A"); + git("commit", "-qm", "init"); +} + +/** chant's GitHub client for acme/db#42 over a fake fetch: the watch workflow's state and its newest scheduled run. */ +async function github(state: string, lastRun: string | undefined): Promise<{ client: PrForge; calls: string[] }> { + const calls: string[] = []; + const fetch: ForgeFetch = (url) => { + calls.push(url); + const send = (v: unknown) => Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve(JSON.stringify(v)) }); + if (/\/actions\/workflows\/[^/]+$/.test(url)) return send({ state }); + if (url.includes("/runs?event=schedule") && lastRun) return send({ workflow_runs: [{ created_at: lastRun }] }); + return send({ workflow_runs: [] }); + }; + const env = { GITHUB_ACTIONS: "true", GITHUB_REPOSITORY: "acme/db", GITHUB_REF: "refs/pull/42/merge", GITHUB_TOKEN: "secret" }; + const { client } = await resolveForge({}, env, "--comment", fetch); + return { client, calls }; +} + +describe("the overdue drift watch in the plan comment (chant#4289)", () => { + it("warns when dev's watch last ran two fires of its cron ago, and asks about dev's workflow alone", async () => { + const { client, calls } = await github("active", "2026-10-23T09:17:00Z"); + const log: string[] = []; + const notes = await overdueNotes(dir, "dev", client, (l) => log.push(l), NOW); + expect(notes).toEqual([ + "Warning: Op `watch-dev` is overdue: its schedule `17 * * * *` has fired at least twice and its last run was on 2026-10-23. GitHub turns a scheduled workflow off after 60 days with no activity in the repository. Turn the workflow on again under Actions, or run it by hand.", + ]); + expect(log).toEqual([`yodel plan: ${notes[0] ?? ""}`]); + expect(calls.every((u) => u.includes("/actions/workflows/watch-dev.yml"))).toBe(true); + }); + + it("says nothing when the watch ran since the cron's last fire", async () => { + const { client } = await github("active", "2026-10-23T11:17:00Z"); + expect(await overdueNotes(dir, "dev", client, () => undefined, NOW)).toEqual([]); + }); + + it("names GitHub's reason when it turned the workflow off", async () => { + const { client } = await github("disabled_inactivity", "2026-08-01T00:17:00Z"); + const [note] = await overdueNotes(dir, "prod", client, () => undefined, NOW); + expect(note).toContain("Op `watch-prod` is overdue: its schedule `47 * * * *`"); + expect(note).toContain("GitHub has turned the workflow off (disabled_inactivity)"); + }); + + it("on GitLab reads yodel's watch file, and counts from the commit that added it when no schedule ever ran", async () => { + const asked: string[] = []; + const gitlab: Pick = { + kind: "gitlab", + scheduledRuns: (q) => { + asked.push(`${q.op} ${q.workflow}`); + return Promise.resolve({ noSchedule: true }); + }, + }; + const [note] = await overdueNotes(dir, "dev", gitlab, () => undefined, NOW); + expect(asked).toEqual([`watch-dev ${GITLAB_WATCH.split("/").pop() ?? ""}`]); + expect(note).toContain("no run is on record since its pipeline was added on 2026-09-01"); + expect(note).toContain("No active pipeline schedule sets CHANT_SCHEDULED_OP to watch-dev"); + }); + + it("logs a forge that will not answer, and warns about nothing", async () => { + const refusing: Pick = { kind: "github", scheduledRuns: () => Promise.reject(new Error("403 Resource not accessible by integration")) }; + const log: string[] = []; + expect(await overdueNotes(dir, "dev", refusing, (l) => log.push(l), NOW)).toEqual([]); + expect(log).toEqual(["yodel plan: github did not say when watch-dev last ran, so it is not checked: 403 Resource not accessible by integration"]); + }); + + it("finds the files yodel ci renders, and none for an environment without a watch", async () => { + expect(GITLAB_WATCH).toBe(GITLAB_WATCH_FILE); + expect(watchPipelineFile(dir, "github", "watch-dev")).toBe(".github/workflows/watch-dev.yml"); + expect(watchPipelineFile(dir, "forgejo", "watch-dev")).toBeUndefined(); + expect(watchPipelineFile(dir, "gitlab", "watch-staging")).toBeUndefined(); + const { client } = await github("active", undefined); + expect(await overdueNotes(dir, "staging", client, () => undefined, NOW)).toEqual([]); + }); + + it("is a note in the comment's markdown", () => { + const note = "Warning: Op `watch-dev` is overdue: its schedule `17 * * * *` has fired at least twice and its last run was on 2026-10-01."; + const md = renderPlanMarkdown({ environment: "dev", dialect: "postgres", appliedCount: 0, pending: [], problems: [], notes: [note] } as never); + expect(md.startsWith(commentMarker("dev"))).toBe(true); + expect(md).toContain(`> ${note}`); + }); + + it("the GitHub plan workflow may read Actions, which the check needs", () => { + const pr = readFileSync(join(TEMPLATE, ".github/workflows/yodel-pr.yml"), "utf8"); + expect(pr).toMatch(/^permissions:\n(?: {2}\S.*\n)*? {2}actions: read\n/m); + }); +}); diff --git a/test/quorum-at-base.test.ts b/test/quorum-at-base.test.ts new file mode 100644 index 00000000..fed209b0 --- /dev/null +++ b/test/quorum-at-base.test.ts @@ -0,0 +1,124 @@ +/** + * `yodel apply --execute` counts a gate's quorum (#278, chant#4324) by the + * rules `identity.gates..quorum` sets in chant.workspace.json at the + * base commit, through chant's own tally. A quorum only the Op declares, and + * a change that lowers it, count for nothing. + * + * The port reads its rule from a real git repository: `main` is the base, a + * branch checked out on top is the change being run. + */ + +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import type { GateResolutionRecord } from "@intentius/chant/lifecycle/gate-ledger"; +import { gitGateLedgerPort, memoryGateLedgerPort, type GateLedgerPort } from "@intentius/chant/op/gate"; +import { sealGateApproval } from "@intentius/chant/workspace/trust/seal"; +import { NOT_APPROVED, verifyApproval } from "../src/versioned/approval.js"; +import type { MigrateOpRef } from "../src/versioned/op.js"; + +const DIGEST = `jcs1-sha256:${"a".repeat(64)}`; +const GATE = "approve-migrate-prod"; +const dirs: string[] = []; +afterAll(() => { + for (const d of dirs) rmSync(d, { recursive: true, force: true }); +}); + +const hasSshKeygen = spawnSync("ssh-keygen", ["-Y"], { stdio: "ignore" }).error === undefined; + +const keyDir = mkdtempSync(join(tmpdir(), "yodel-quorum-keys-")); +dirs.push(keyDir); +const key = (name: string) => { + if (!hasSshKeygen) return { file: "", pub: "" }; + const file = join(keyDir, name); + execFileSync("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", name, "-f", file]); + return { file, pub: readFileSync(`${file}.pub`, "utf8").trim().split(" ").slice(0, 2).join(" ") }; +}; +const keys: Record = { alice: key("alice"), bob: key("bob") }; + +/** chant.workspace.json declaring the gate's quorum (none: the gate has no entry). The gate is then sealed-only, as any `identity.gates` gate is. */ +const declaration = (quorum?: unknown) => + `${JSON.stringify({ name: "acme", schema: 1, members: [], identity: { gates: quorum ? { [GATE]: { quorum } } : {} } }, null, 2)}\n`; + +/** A repository whose `main` declares `atBase` as the gate's quorum, signed by alice and bob, checked out on a branch whose own declaration has `inChange`. */ +function repo(atBase: unknown, inChange: unknown = atBase) { + const dir = mkdtempSync(join(tmpdir(), "yodel-quorum-base-")); + dirs.push(dir); + const git = (...args: string[]) => execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.test", "-c", "commit.gpgsign=false", ...args], { cwd: dir, stdio: "pipe" }); + git("init", "-q", "-b", "main"); + mkdirSync(join(dir, ".chant")); + writeFileSync(join(dir, ".chant", "allowed_signers"), Object.entries(keys).map(([n, k]) => `${n} ${k.pub}\n`).join("")); + writeFileSync(join(dir, "chant.workspace.json"), declaration(atBase)); + git("add", "-A"); + git("commit", "-qm", "base"); + git("checkout", "-q", "-b", "change"); + writeFileSync(join(dir, "chant.workspace.json"), declaration(inChange)); + git("commit", "-qam", "the change", "--allow-empty"); + return dir; +} + +const approval = (resolvedBy: string, timestamp: string, sealed: boolean): GateResolutionRecord => { + const a = { op: "migrate-prod", gate: GATE, resolvedBy, timestamp, planDigest: DIGEST, approver: { kind: "human" as const } }; + return { version: 1, ...a, ...(sealed ? { seal: sealGateApproval(keys[resolvedBy]?.file ?? "", a) } : {}) }; +}; + +/** The ledger of `by`, with the gate's rule read from `dir` as chant's gate step reads it (at main). Sealed when the gate is in the declaration. */ +const portFor = (dir: string, sealed: boolean, ...by: string[]): GateLedgerPort => ({ + ...memoryGateLedgerPort({ resolutions: by.map((b, i) => approval(b, `2026-10-10T09:0${String(i)}:00.000Z`, sealed)) }), + approvalRule: (gate, at) => gitGateLedgerPort({ cwd: dir }).approvalRule?.(gate, at) ?? Promise.resolve(null), + quorumJudge: (gate, at) => (gitGateLedgerPort({ cwd: dir }).quorumJudge as NonNullable)(gate, at), +}); + +const op = (quorum: boolean): MigrateOpRef => ({ name: "migrate-prod", filePath: "ops/migrate-prod.op.ts", gate: GATE, quorum }); + +describe.skipIf(!hasSshKeygen)("a quorum at base, counted by --execute", () => { + it("passes when the quorum at base is met, and names every approver", async () => { + const dir = repo({ count: 2 }); + const by = await verifyApproval(portFor(dir, true, "alice", "bob"), op(false), DIGEST); + expect(by.approver.split(", ").sort()).toEqual(["alice", "bob"]); + expect(by).toMatchObject({ resolvedBy: "bob", admission: { op: "migrate-prod", gate: GATE, resolvedAt: "2026-10-10T09:01:00.000Z" } }); + }); + + it("refuses, saying what is missing, when the quorum at base is not met", async () => { + const dir = repo({ count: 2 }); + await expect(verifyApproval(portFor(dir, true, "alice"), op(false), DIGEST)).rejects.toMatchObject({ exitCode: NOT_APPROVED, message: expect.stringMatching(/quorum at base is not met/) as unknown }); + // One person approving twice is one approver. + await expect(verifyApproval(portFor(dir, true, "alice", "alice"), op(false), DIGEST)).rejects.toThrow(/quorum at base is not met/); + }); + + it("counts the quorum at base when a change lowers the Op's own", async () => { + // The Op in the change asks for one approver; the base asks for two. + const dir = repo({ count: 2 }); + await expect(verifyApproval(portFor(dir, true, "alice"), op(true), DIGEST)).rejects.toThrow(/quorum at base is not met/); + await expect(verifyApproval(portFor(dir, true, "alice", "bob"), op(true), DIGEST)).resolves.toMatchObject({ resolvedBy: "bob" }); + }); + + it("counts the quorum at base when the change lowers the declaration itself", async () => { + const dir = repo({ count: 2 }, { count: 1 }); + await expect(verifyApproval(portFor(dir, true, "alice"), op(true), DIGEST)).rejects.toThrow(/quorum at base is not met/); + await expect(verifyApproval(portFor(dir, true, "alice", "bob"), op(true), DIGEST)).resolves.toMatchObject({ resolvedBy: "bob" }); + }); + + it("counts nothing from a quorum declared only in the Op, with none at base", async () => { + const dir = repo(undefined); + await expect(verifyApproval(portFor(dir, false, "alice", "bob"), op(true), DIGEST)).rejects.toMatchObject({ + exitCode: NOT_APPROVED, + message: expect.stringMatching(/declared only in the Op.*identity\.gates\.approve-migrate-prod\.quorum/s) as unknown, + }); + // And one the change adds to the declaration is no quorum at base. + const added = repo(undefined, { count: 1 }); + await expect(verifyApproval(portFor(added, false, "alice"), op(true), DIGEST)).rejects.toThrow(/declared only in the Op/); + }); + + it("still takes one approval for a gate with no quorum anywhere", async () => { + const dir = repo(undefined); + await expect(verifyApproval(portFor(dir, false, "alice"), op(false), DIGEST)).resolves.toMatchObject({ resolvedBy: "alice" }); + }); + + it("refuses a gate policy, which only the gate step evaluates", async () => { + const dir = repo({ count: 1 }); + await expect(verifyApproval(portFor(dir, true, "alice"), { ...op(true), policy: true }, DIGEST)).rejects.toThrow(/policy/); + }); +}); diff --git a/test/release-admission.test.ts b/test/release-admission.test.ts new file mode 100644 index 00000000..a135ab73 --- /dev/null +++ b/test/release-admission.test.ts @@ -0,0 +1,109 @@ +/** + * What a release record carries beyond the schema (#277): the admission and + * approver of a gated apply, the digest of the chant release an apply was + * made from; and readers that take every such field as optional. + */ + +import { execFileSync } from "node:child_process"; +import { afterAll, describe, expect, it } from "vitest"; +import { persistRelease, makeRelease } from "@intentius/chant/lifecycle/release-store"; +import { appendReleaseRecord, readReleaseLedger } from "@intentius/chant/lifecycle/release-ledger"; +import { memoryGateLedgerPort } from "@intentius/chant/op/gate"; +import type { BuildOutput } from "../src/chant/build.js"; +import { loadProject, type Environment, type SqlProfile } from "../src/project.js"; +import { recordRelease, releaseToApply } from "../src/release/index.js"; +import { deriveAudit } from "../src/report/audit.js"; +import { verifyApproval } from "../src/versioned/approval.js"; +import type { MigrateOpRef } from "../src/versioned/op.js"; +import { projectFrom } from "./helpers/run.js"; + +const DIGEST = `jcs1-sha256:${"a".repeat(64)}`; +const op = { name: "migrate-dev", gate: "approve-migrate-dev" } as MigrateOpRef; +const resolution = (resolvedBy: string, timestamp: string, planDigest = DIGEST) => ({ version: 1 as const, op: op.name, gate: op.gate, resolvedBy, timestamp, planDigest }); + +describe("verifyApproval names the admission", () => { + it("gives the approver and the resolution that admitted the apply, from chant's admissionOf", async () => { + const port = memoryGateLedgerPort({ resolutions: [resolution("alice", "2026-10-10T09:00:00.000Z")] }); + expect(await verifyApproval(port, op, DIGEST)).toMatchObject({ + resolvedBy: "alice", + approver: "alice", + admission: { op: "migrate-dev", gate: "approve-migrate-dev", resolvedAt: "2026-10-10T09:00:00.000Z" }, + }); + }); + + it("joins every approver of the plan, and takes the newest resolution's time", async () => { + const port = memoryGateLedgerPort({ resolutions: [resolution("alice", "2026-10-10T09:00:00.000Z"), resolution("bob", "2026-10-10T09:05:00.000Z")] }); + const by = await verifyApproval(port, op, DIGEST); + expect(by.approver.split(", ").sort()).toEqual(["alice", "bob"]); + expect(by.admission.resolvedAt).toBe("2026-10-10T09:05:00.000Z"); + }); +}); + +describe("the release record", () => { + const p = projectFrom("clickhouse-versioned"); + afterAll(() => { + p.dispose(); + }); + const env = (name: string): Environment => ({ name, profile: {} as SqlProfile }); + const schema = { dialect: "clickhouse", objects: { a: 1 } } as unknown as BuildOutput; + const admission = { op: "migrate-dev", gate: "approve-migrate-dev", resolvedAt: "2026-10-10T09:00:00.000Z" }; + + it("carries admission and approver of a gated apply, and releaseDigest of one made from a release; an ungated apply carries none", async () => { + const project = await loadProject(p.dir); + await recordRelease(project, env("plain"), schema); + await recordRelease(project, env("gated"), schema, { approver: "alice", admission }); + await recordRelease(project, env("released"), schema, { approver: "alice", admission, releaseDigest: "sha256:rel" }); + const read = async (e: string) => (await readReleaseLedger(e, { cwd: p.dir })).records[0] as unknown as Record; + const plain = await read("plain"); + expect(plain).not.toHaveProperty("admission"); + expect(plain).not.toHaveProperty("approver"); + expect(plain).not.toHaveProperty("releaseDigest"); + const gated = await read("gated"); + expect(gated).toMatchObject({ approver: "alice", admission }); + expect(gated).not.toHaveProperty("releaseDigest"); + expect(await read("released")).toMatchObject({ approver: "alice", admission, releaseDigest: "sha256:rel" }); + }, 60_000); + + it("reads a ledger of old and new lines mixed, without rewriting the old ones", async () => { + const project = await loadProject(p.dir); + const gitSha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: p.dir, encoding: "utf8" }).trim(); + const old = { component: "schema", env: "mixed", digest: "sha256:old", gitSha, runId: "r0", timestamp: "2026-10-01T00:00:00.000Z", actor: "ci" }; + await appendReleaseRecord({ ...old, unknownFromLater: { x: 1 } } as never, { cwd: p.dir }); + const before = (await readReleaseLedger("mixed", { cwd: p.dir })).records.length; + await recordRelease(project, env("mixed"), schema, { approver: "alice", admission }); + const { records } = await readReleaseLedger("mixed", { cwd: p.dir }); + expect(before).toBe(1); + expect(records).toHaveLength(2); + expect(records[0]).toMatchObject({ digest: "sha256:old", runId: "r0" }); + expect(records[0]).not.toHaveProperty("admission"); + expect(records[1]).toMatchObject({ approver: "alice", admission }); + }, 60_000); + + it("applies from a release only at the commit it was cut at, and refuses a ref no release answers to", async () => { + const gitSha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: p.dir, encoding: "utf8" }).trim(); + await expect(releaseToApply(p.dir, "v9")).rejects.toThrow(/no chant release/); + const here = makeRelease({ member: null, commit: gitSha, artifactDigests: [], targets: [] }); + await persistRelease(here, [], { cwd: p.dir }); + expect(await releaseToApply(p.dir, here.releaseDigest)).toBe(here.releaseDigest); + const elsewhere = makeRelease({ member: null, commit: "0".repeat(40), artifactDigests: [], targets: [] }); + await persistRelease(elsewhere, [], { cwd: p.dir }); + await expect(releaseToApply(p.dir, elsewhere.releaseDigest)).rejects.toThrow(/was cut at 000000000000/); + }, 60_000); +}); + +describe("the audit log over a gate ledger of old and new lines", () => { + it("shows a pending fact without gitSha or runId as it is, ignores unknown keys, and reads the new fields", () => { + const pending = (timestamp: string, extra: Record) => ({ record: { version: 1, kind: "pending", op: op.name, gate: op.gate, expiresAt: "", timestamp, planDigest: DIGEST, ...extra } }); + const lines = [ + pending("2026-10-10T08:00:00.000Z", {}), + pending("2026-10-10T08:30:00.000Z", { gitSha: "abc", runId: "run-9", runOrigin: { forge: "github" }, later: true }), + { record: { ...resolution("alice", "2026-10-10T08:40:00.000Z"), gitSha: "abc", runId: "run-9", carriedFrom: undefined, later: [1] } }, + ]; + const { entries } = deriveAudit({ environment: "dev", history: "h", rows: [], ledger: { op: op.name, gate: op.gate, path: "_gates/migrate-dev.jsonl", lines } }); + const asked = entries.filter((e) => e.kind === "approval-requested"); + expect(asked).toHaveLength(2); + expect(asked[0]?.detail).toBeUndefined(); + expect(asked[1]?.detail).toBe("run run-9"); + expect(entries.filter((e) => e.kind === "approved").map((e) => e.by)).toEqual(["alice"]); + }); +}); diff --git a/test/template.test.ts b/test/template.test.ts index 0706160d..92ced9d2 100644 --- a/test/template.test.ts +++ b/test/template.test.ts @@ -236,7 +236,8 @@ describe.each(DIALECTS)("templates/%s", (dialect) => { expect(job.steps.find((s) => s.run === reportCommand(env))?.if, `${f} ${name}`).toBe("always()"); // On Forgejo, Forgejo's fork: actions/upload-artifact@v4 refuses any server but github.com's. const upload = f.startsWith(".forgejo") ? FORGEJO_UPLOAD_ARTIFACT : "actions/upload-artifact@v4"; - expect(job.steps.find((s) => s.uses === upload)?.with, `${f} ${name}`).toMatchObject({ name: reportArtifact(name), path: REPORT_DIR }); + // A wave job also uploads its outcome file (#4322), so pick the report's upload by name. + expect(job.steps.find((s) => s.uses === upload && s.with?.name === reportArtifact(name))?.with, `${f} ${name}`).toMatchObject({ name: reportArtifact(name), path: REPORT_DIR }); for (const v of WEBHOOK_VARIABLES) expect(job.env?.[v], `${f} ${name}`).toBe(`\${{ secrets.${v} }}`); } } diff --git a/test/versioned.test.ts b/test/versioned.test.ts index 71bd47a7..231fa5c5 100644 --- a/test/versioned.test.ts +++ b/test/versioned.test.ts @@ -255,7 +255,12 @@ describe("the approval --execute checks in chant's gate ledger", () => { it("counts only an approval of this gate, for this digest, newer than the gate's newest pending fact", async () => { const digest = `jcs1-sha256:${"a".repeat(64)}`; const other = `jcs1-sha256:${"b".repeat(64)}`; - await expect(verifyApproval(approvedLedger(digest), OP, digest)).resolves.toEqual({ resolvedBy: "alice", timestamp: "2026-10-09T12:00:00.000Z" }); + await expect(verifyApproval(approvedLedger(digest), OP, digest)).resolves.toEqual({ + resolvedBy: "alice", + timestamp: "2026-10-09T12:00:00.000Z", + approver: "alice", + admission: { op: OP.name, gate: OP.gate, resolvedAt: "2026-10-09T12:00:00.000Z" }, + }); await expect(verifyApproval(approvedLedger(other), OP, digest)).rejects.toThrow(new RegExp(`newest approval of that gate is for ${other}`)); await expect(verifyApproval(approvedLedger(digest), { ...OP, gate: "another-gate" }, digest)).rejects.toMatchObject({ exitCode: NOT_APPROVED }); // The gate asked again after the approval: that approval no longer answers it. @@ -267,7 +272,7 @@ describe("the approval --execute checks in chant's gate ledger", () => { // An approval recorded before plan-bound gates (no digest) never counts. const legacy = memoryGateLedgerPort({ resolutions: [{ version: 1, op: OP.name, gate: OP.gate, resolvedBy: "alice", timestamp: "2026-10-09T12:00:00.000Z" }] }); await expect(verifyApproval(legacy, OP, digest)).rejects.toMatchObject({ exitCode: NOT_APPROVED }); - // A quorum gate is the gate step's to count: refused, never approximated. + // A quorum only the Op declares is the change's to edit: refused (the quorum at base is test/quorum-at-base.test.ts). await expect(verifyApproval(approvedLedger(digest), { ...OP, quorum: true }, digest)).rejects.toThrow(/quorum/); }); });