@ultimat3/cli 31.48.0 → 31.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +30 -23
- package/README.md +96 -4
- package/package.json +30 -30
- package/src/api-registration.ts +45 -14
- package/src/api-routes.ts +1 -0
- package/src/app-load.ts +7 -3
- package/src/app-openapi.ts +7 -1
- package/src/app-root.ts +7 -1
- package/src/budgets.ts +2 -1
- package/src/clean-services.ts +142 -0
- package/src/cmd-auth.ts +3 -0
- package/src/cmd-clean-spec.ts +10 -3
- package/src/cmd-clean.ts +23 -9
- package/src/cmd-db-backfill.ts +6 -0
- package/src/cmd-db-branch.ts +10 -4
- package/src/cmd-db-recount.ts +5 -12
- package/src/cmd-db-rollback.ts +77 -0
- package/src/cmd-db-spec.ts +18 -2
- package/src/cmd-db-status.ts +5 -10
- package/src/cmd-db.ts +105 -33
- package/src/cmd-deploy-verify.ts +14 -6
- package/src/cmd-docs-topic.ts +94 -0
- package/src/cmd-docs.ts +15 -1
- package/src/cmd-doctor.ts +109 -41
- package/src/cmd-drill.ts +80 -18
- package/src/cmd-env.ts +30 -8
- package/src/cmd-errors-app.ts +63 -0
- package/src/cmd-errors.ts +50 -14
- package/src/cmd-generate.ts +17 -4
- package/src/cmd-heavy-spec.ts +9 -1
- package/src/cmd-heavy.ts +111 -27
- package/src/cmd-i18n.ts +33 -1
- package/src/cmd-jobs.ts +27 -1
- package/src/cmd-merge-driver-spec.ts +12 -0
- package/src/cmd-merge-driver.ts +95 -0
- package/src/cmd-new.ts +23 -3
- package/src/cmd-policy-spec.ts +9 -1
- package/src/cmd-policy.ts +72 -17
- package/src/cmd-stop.ts +18 -4
- package/src/cmd-tasks-run.ts +87 -0
- package/src/cmd-tasks-spec.ts +10 -3
- package/src/cmd-tasks.ts +8 -5
- package/src/cmd-test.ts +2 -1
- package/src/cmd-upgrade-spec.ts +8 -1
- package/src/cmd-upgrade.ts +15 -1
- package/src/cmd-verify.ts +9 -41
- package/src/codemods/agents-doc-row.ts +73 -0
- package/src/codemods/define-error-leaf.ts +37 -12
- package/src/codemods/docs-many-agents.ts +11 -15
- package/src/codemods/docs-worker-commands.ts +26 -0
- package/src/codemods/engine-fs.ts +9 -2
- package/src/codemods/index.ts +4 -0
- package/src/codemods/merge-drivers.ts +147 -0
- package/src/command.ts +3 -0
- package/src/db-applied-edits.ts +117 -0
- package/src/db-dev-wire.ts +18 -0
- package/src/db-diagnostics.ts +5 -10
- package/src/db-generate.ts +82 -7
- package/src/db-migrate-pass.ts +51 -0
- package/src/db-migrate-through-dev.ts +209 -0
- package/src/db-rollback-consent.ts +128 -0
- package/src/db-rollback-pass.ts +76 -0
- package/src/db-seed-generate.ts +5 -1
- package/src/db-seed.ts +7 -1
- package/src/deploy-verify-findings.ts +3 -0
- package/src/deploy-verify-grade.ts +3 -0
- package/src/deploy-verify-processes.ts +32 -0
- package/src/dev-boot.ts +3 -0
- package/src/dev-db-migrate.ts +155 -0
- package/src/dev-db-rollback.ts +33 -0
- package/src/dev-db-settled.ts +22 -0
- package/src/dev-lock-errors.ts +78 -0
- package/src/dev-lock-holder-dir.ts +64 -0
- package/src/dev-lock-live.ts +44 -0
- package/src/dev-lock.ts +59 -84
- package/src/dev-policy.ts +11 -8
- package/src/dev-rebuild-schema.ts +116 -13
- package/src/dev-rebuild.ts +13 -4
- package/src/dev-route-table.ts +7 -0
- package/src/dispatch.ts +21 -1
- package/src/doctor-api-listing.ts +114 -0
- package/src/doctor-guarded.ts +41 -0
- package/src/doctor-port.ts +90 -17
- package/src/doctor-probe.ts +36 -5
- package/src/doctor-processes-probe.ts +127 -0
- package/src/doctor-processes.ts +136 -0
- package/src/doctor-warnings.ts +17 -0
- package/src/error-codes-agents.ts +35 -0
- package/src/error-codes-processes.ts +30 -0
- package/src/error-codes-tooling.ts +2 -0
- package/src/error-codes.ts +12 -13
- package/src/errors-suite.ts +27 -0
- package/src/errors.ts +18 -22
- package/src/exercise-registration.ts +4 -3
- package/src/exercise-services.ts +13 -3
- package/src/framework-env.ts +7 -3
- package/src/framework-schema.ts +15 -5
- package/src/generate-files.ts +1 -0
- package/src/generate-grant-findings.ts +7 -5
- package/src/generate-grants.ts +9 -8
- package/src/generate-kinds.ts +30 -6
- package/src/generate-roles-file.ts +30 -0
- package/src/generate-slice-policy.ts +3 -3
- package/src/guard-sources.ts +1 -2
- package/src/guards.ts +2 -2
- package/src/heavy-env.ts +2 -0
- package/src/heavy-errors.ts +18 -0
- package/src/heavy-holders.ts +78 -0
- package/src/heavy-ledger.ts +56 -14
- package/src/heavy-pressure.ts +104 -0
- package/src/heavy.ts +31 -13
- package/src/i18n-registration.ts +22 -2
- package/src/island-harness.ts +2 -2
- package/src/job-budget.ts +4 -2
- package/src/job-registration.ts +64 -8
- package/src/jobs-queue-known.ts +43 -0
- package/src/mcp-errors-agents.ts +20 -0
- package/src/mcp-errors-doctor.ts +27 -0
- package/src/mcp-errors-processes.ts +23 -0
- package/src/mcp-errors.ts +15 -29
- package/src/mcp-host.ts +2 -2
- package/src/merge-driver-catalog.ts +58 -0
- package/src/merge-driver-config.ts +43 -0
- package/src/merge-driver-lines.ts +140 -0
- package/src/merge-state.ts +105 -0
- package/src/messages-db.ts +22 -1
- package/src/messages-processes.ts +13 -0
- package/src/messages-upgrade.ts +10 -0
- package/src/messages.ts +54 -4
- package/src/output-findings.ts +48 -21
- package/src/page-navigation.ts +5 -2
- package/src/parse.ts +37 -6
- package/src/policy-facts.ts +38 -21
- package/src/policy-row.ts +99 -0
- package/src/port-pair-free.ts +28 -0
- package/src/pwa-artifacts.ts +1 -1
- package/src/registry-lines.ts +110 -0
- package/src/registry.ts +2 -0
- package/src/retain-sweep.ts +1 -1
- package/src/retained-assets-boot.ts +1 -1
- package/src/role-replicator.ts +4 -1
- package/src/role-select.ts +86 -0
- package/src/role-start.ts +13 -55
- package/src/role-sync.ts +10 -5
- package/src/runtime-assets-site.ts +2 -2
- package/src/runtime-assets.ts +1 -1
- package/src/runtime-cache-frame.ts +46 -0
- package/src/runtime-cache-ttl.ts +23 -0
- package/src/runtime-cache.ts +33 -16
- package/src/runtime-database-ssl.ts +84 -0
- package/src/runtime-idempotency-scope.ts +16 -2
- package/src/runtime-jobs-share.ts +52 -0
- package/src/runtime-jobs.ts +43 -12
- package/src/runtime-queue.ts +18 -3
- package/src/runtime-render-document.ts +1 -2
- package/src/runtime-services.ts +8 -1
- package/src/schema-drift.ts +19 -2
- package/src/schema-dump-drift.ts +4 -1
- package/src/serve-boot-probe.ts +30 -2
- package/src/serve-boot.ts +11 -1
- package/src/serve-env.ts +39 -3
- package/src/serve.ts +61 -10
- package/src/site-asset-routes.ts +2 -2
- package/src/site-assets.ts +5 -158
- package/src/stop-run-start.ts +12 -0
- package/src/supervise-boot.ts +61 -0
- package/src/supervise-cgroup.ts +84 -0
- package/src/supervise-child.ts +206 -0
- package/src/supervise-count.ts +244 -0
- package/src/supervise-errors.ts +83 -0
- package/src/supervise-facts.ts +40 -0
- package/src/supervise-messages.ts +84 -0
- package/src/supervise-policy.ts +46 -0
- package/src/supervise-pool.ts +10 -0
- package/src/supervise-probe.ts +158 -0
- package/src/supervise-run.ts +54 -0
- package/src/supervise.ts +383 -0
- package/src/sw-precache-plan.ts +1 -1
- package/src/templates/generate-purge.ts +6 -6
- package/src/templates/guard-animated-layout-property.ts +2 -2
- package/src/templates/guard-bare-error.ts +1 -1
- package/src/templates/guard-error-declared.ts +2 -2
- package/src/templates/guard-focus-visible.ts +1 -1
- package/src/templates/guard-image-dimensions.ts +2 -2
- package/src/templates/guard-island-mount-clears.ts +1 -1
- package/src/templates/guard-native-confirm.ts +1 -1
- package/src/templates/guard-raw-breakpoint.ts +2 -2
- package/src/templates/guard-raw-colour.ts +2 -2
- package/src/templates/guard-raw-fetch.ts +1 -1
- package/src/templates/guard-raw-interval.ts +1 -1
- package/src/templates/guard-raw-length.ts +3 -3
- package/src/templates/guard-raw-motion.ts +97 -1
- package/src/templates/guard-raw-shadow.ts +1 -1
- package/src/templates/guard-raw-z-index.ts +1 -1
- package/src/templates/guard-released-forms.ts +58 -9
- package/src/templates/guard-repo-await-in-loop.ts +1 -1
- package/src/templates/guard-repo-raw-sql.ts +4 -4
- package/src/templates/guard-repo-unbounded.ts +1 -1
- package/src/templates/guard-runtime-pin.ts +1 -1
- package/src/templates/guard-semantic-interactive.ts +2 -2
- package/src/templates/guard-unbounded-fanout.ts +1 -1
- package/src/templates/guard-undeclared-custom-property.ts +3 -3
- package/src/templates/guard-undefined-style-class.ts +3 -3
- package/src/templates/guard-unzoned-date.ts +3 -3
- package/src/templates/query-slice.ts +82 -0
- package/src/templates/query.ts +76 -30
- package/src/templates/resource-page.ts +3 -2
- package/src/templates/scaffold-bin.ts +2 -0
- package/src/templates/scaffold-claude-commands.ts +6 -0
- package/src/templates/scaffold-claude.ts +4 -4
- package/src/templates/scaffold-container-compose.ts +47 -7
- package/src/templates/scaffold-docs.ts +7 -3
- package/src/templates/scaffold-gitattributes.ts +18 -1
- package/src/templates/scaffold-helm-templates.ts +9 -0
- package/src/templates/scaffold-repo.ts +5 -2
- package/src/templates/scaffold-test-services.ts +33 -11
- package/src/templates/shapes/offline.ts +0 -7
- package/src/templates/shapes/realtime.ts +2 -6
- package/src/templates/sign-in-action-tests.ts +6 -4
- package/src/templates/sign-in-challenge.ts +62 -0
- package/src/templates/sign-in-oidc-mfa.ts +31 -0
- package/src/templates/sign-in-oidc.ts +11 -3
- package/src/templates/sign-in-password.ts +18 -56
- package/src/test-only-shipped.ts +29 -2
- package/src/test-shards.ts +134 -42
- package/src/test-verdict.ts +79 -0
- package/src/test-workers.ts +15 -0
- package/src/upgrade-coverage-ratchet.ts +95 -0
- package/src/upgrade-gate-codemods.ts +5 -3
- package/src/upgrade-gate.ts +42 -4
- package/src/upgrade-merge-drivers.ts +25 -0
- package/src/upgrade-report.ts +32 -4
- package/src/upgrade-scope.ts +62 -0
- package/src/verify-checks.ts +2 -8
- package/src/verify-coverage-run.ts +4 -1
- package/src/verify-e2e.ts +21 -3
- package/src/verify-live.ts +38 -14
- package/src/verify-only.ts +67 -0
- package/src/verify-progress.ts +7 -3
- package/src/verify-run.ts +20 -2
- package/src/verify-services-stack.ts +165 -0
- package/src/verify-services.ts +84 -2
- package/src/verify-test-run.ts +6 -7
- package/src/verify-tests.ts +8 -2
- package/src/verify-typecheck.ts +25 -2
- package/src/workspace-checks.ts +4 -1
- package/wiki/Actions.md +66 -3
- package/wiki/Admin-Dashboard.md +2 -2
- package/wiki/Agents.md +5 -5
- package/wiki/Auth.md +20 -6
- package/wiki/Bare-VM.md +1 -1
- package/wiki/CI-Parallel-Gate.md +2 -1
- package/wiki/CLI-Reference.md +115 -42
- package/wiki/Caching-And-Invalidation.md +1 -1
- package/wiki/Client-Navigation.md +35 -5
- package/wiki/Configuration.md +12 -10
- package/wiki/Deployment.md +44 -4
- package/wiki/Entities-And-Migrations.md +17 -3
- package/wiki/FAQ.md +1 -1
- package/wiki/Getting-Started.md +2 -2
- package/wiki/Home.md +3 -3
- package/wiki/I18n.md +6 -4
- package/wiki/Installation.md +12 -11
- package/wiki/Interface-Rules.md +3 -1
- package/wiki/Jobs-And-Workflows.md +24 -4
- package/wiki/Known-Gaps.md +2 -2
- package/wiki/MCP-And-AI.md +48 -13
- package/wiki/Many-Agents.md +69 -2
- package/wiki/Migrations-And-Backfills.md +18 -0
- package/wiki/Notify.md +5 -3
- package/wiki/Observability.md +13 -0
- package/wiki/Outbound-HTTP.md +53 -2
- package/wiki/Policies-And-Authz.md +1 -1
- package/wiki/Queries-And-Live-Queries.md +2 -2
- package/wiki/Realtime.md +24 -7
- package/wiki/Routes-And-Render-Modes.md +2 -2
- package/wiki/Scheduled-Tasks.md +4 -1
- package/wiki/Static-Assets.md +5 -3
- package/wiki/Testing.md +64 -7
- package/wiki/Theming.md +6 -3
- package/wiki/Timezones-And-Dates.md +5 -1
- package/wiki/Troubleshooting.md +1 -0
- package/wiki/Tutorial-01-First-App.md +3 -3
- package/wiki/Tutorial-02-First-Feature.md +1 -1
- package/wiki/Tutorial-03-Auth-And-Admin.md +7 -6
- package/wiki/UI-Components.md +1 -0
- package/wiki/Upgrading.md +38 -0
package/src/db-generate.ts
CHANGED
|
@@ -4,15 +4,22 @@
|
|
|
4
4
|
|
|
5
5
|
// why: `node:path` — Bun ships no path joiner of its own, and these paths are built, not opened.
|
|
6
6
|
import { join } from 'node:path';
|
|
7
|
-
import type {
|
|
7
|
+
import type {
|
|
8
|
+
GeneratedMigration,
|
|
9
|
+
Migration,
|
|
10
|
+
SchemaDescription,
|
|
11
|
+
UnrenderedDeclaration,
|
|
12
|
+
} from '@ultimat3/db';
|
|
8
13
|
import {
|
|
9
14
|
DESTRUCTIVE_MARKER,
|
|
10
15
|
declaredSchema,
|
|
11
16
|
generateMigration,
|
|
17
|
+
migrationForked,
|
|
12
18
|
migrationSnapshotMissing,
|
|
13
19
|
ROLLING_UNSAFE_MARKER,
|
|
14
20
|
snapshotJson,
|
|
15
21
|
} from '@ultimat3/db';
|
|
22
|
+
import { migrationFork } from '@ultimat3/db/schema-dump';
|
|
16
23
|
import { registeredEntities } from '@ultimat3/entity';
|
|
17
24
|
import { describeQueries } from '@ultimat3/query';
|
|
18
25
|
import { loadApp } from './app-load';
|
|
@@ -35,16 +42,27 @@ export interface GenerateMigrationOptions {
|
|
|
35
42
|
* concurrently. Never a default; once dropped, a plain run does not rebuild it.
|
|
36
43
|
*/
|
|
37
44
|
readonly dropRedundant?: boolean | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* `x db gen --merge-fork`, the fix `X_MIGRATION_FORKED` prints. Rewrites the newest sidecar to what
|
|
47
|
+
* the merged chain builds, and goes on as any run does from there. No `.sql` is touched.
|
|
48
|
+
*/
|
|
49
|
+
readonly mergeFork?: boolean | undefined;
|
|
38
50
|
/** `database.rowSecurity` and the tenant columns. The app's own unless a test injects one. */
|
|
39
51
|
readonly rowSecurity?: RowSecurityWanted | undefined;
|
|
40
52
|
}
|
|
41
53
|
|
|
42
54
|
/**
|
|
43
|
-
* What this run actually did —
|
|
55
|
+
* What this run actually did — five different things, and `--json` has to tell them apart. A
|
|
44
56
|
* `hash-recorded` run wrote a file and generated no migration; reporting it as `generated` would
|
|
45
57
|
* claim a migration nobody can apply, and reporting it as `unchanged` would hide the one write.
|
|
58
|
+
* `fork-merged` is the same honesty for `--merge-fork`: a sidecar moved and no migration exists.
|
|
46
59
|
*/
|
|
47
|
-
export type GenerateOutcome =
|
|
60
|
+
export type GenerateOutcome =
|
|
61
|
+
| 'generated'
|
|
62
|
+
| 'hash-recorded'
|
|
63
|
+
| 'fork-merged'
|
|
64
|
+
| 'unchanged'
|
|
65
|
+
| 'blocked';
|
|
48
66
|
|
|
49
67
|
export interface GeneratedFiles {
|
|
50
68
|
readonly outcome: GenerateOutcome;
|
|
@@ -52,6 +70,12 @@ export interface GeneratedFiles {
|
|
|
52
70
|
readonly migration?: GeneratedMigration | undefined;
|
|
53
71
|
/** App-root-relative paths written, in write order. Empty when there was nothing to write. */
|
|
54
72
|
readonly files: readonly string[];
|
|
73
|
+
/** The tables `migration` creates, changes or drops, so a shared checkout can see whose they are. */
|
|
74
|
+
readonly tables?: readonly string[] | undefined;
|
|
75
|
+
/** The newest migration on disk once this run ended: what an empty diff was measured against. */
|
|
76
|
+
readonly newest?: string | undefined;
|
|
77
|
+
/** How many objects `--merge-fork` put right in the newest sidecar. Absent when it merged none. */
|
|
78
|
+
readonly forkRepairs?: number | undefined;
|
|
55
79
|
/** What the source hashes to, whenever this run was in a position to record it. */
|
|
56
80
|
readonly schemaHash?: string | undefined;
|
|
57
81
|
/**
|
|
@@ -91,6 +115,47 @@ export function migrationSql(migration: GeneratedMigration): string {
|
|
|
91
115
|
].join('\n');
|
|
92
116
|
}
|
|
93
117
|
|
|
118
|
+
/** Every table whose recorded shape differs between two snapshots, in name order. */
|
|
119
|
+
function tablesBetween(before: SchemaDescription, after: SchemaDescription): readonly string[] {
|
|
120
|
+
const shape = (schema: SchemaDescription): Map<string, string> =>
|
|
121
|
+
new Map(schema.tables.map((table) => [table.name, JSON.stringify(table)]));
|
|
122
|
+
const was = shape(before);
|
|
123
|
+
const now = shape(after);
|
|
124
|
+
return [...new Set([...was.keys(), ...now.keys()])]
|
|
125
|
+
.filter((name) => was.get(name) !== now.get(name))
|
|
126
|
+
.sort();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
interface SettledChain {
|
|
130
|
+
readonly migrations: readonly Migration[];
|
|
131
|
+
readonly files: readonly string[];
|
|
132
|
+
readonly repairs: number;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Before any diff: against a forked chain the diff is wrong in both directions, asking for a second
|
|
137
|
+
* `create table` the replay refuses. Merging only rewrites a sidecar, which no checksum covers; a
|
|
138
|
+
* collision has no such repair, so it is refused even under `--merge-fork`.
|
|
139
|
+
*/
|
|
140
|
+
async function settleFork(
|
|
141
|
+
root: string,
|
|
142
|
+
migrations: readonly Migration[],
|
|
143
|
+
mergeFork: boolean,
|
|
144
|
+
): Promise<SettledChain> {
|
|
145
|
+
const fork = migrationFork(migrations);
|
|
146
|
+
if (fork === undefined) return { migrations, files: [], repairs: 0 };
|
|
147
|
+
if (!mergeFork || fork.collisions.length > 0) throw migrationForked(fork);
|
|
148
|
+
const file = `${MIGRATIONS_DIR}/${snapshotFileName(fork.newest)}`;
|
|
149
|
+
await Bun.write(join(root, file), snapshotJson(fork.merged));
|
|
150
|
+
return {
|
|
151
|
+
migrations: migrations.map((migration) =>
|
|
152
|
+
migration.id === fork.newest ? { ...migration, snapshot: fork.merged } : migration,
|
|
153
|
+
),
|
|
154
|
+
files: [file],
|
|
155
|
+
repairs: fork.lost.length + fork.stale.length,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
94
159
|
/**
|
|
95
160
|
* Generation reads source and writes files; it never opens a database. The previous migration's
|
|
96
161
|
* snapshot is what it diffs against (`declaredSchema`), so `x db gen` answers the same in CI, on a
|
|
@@ -109,7 +174,10 @@ export async function generateAppMigration(
|
|
|
109
174
|
return { outcome: 'blocked', files: [], findings: app.findings, unrendered: [] };
|
|
110
175
|
}
|
|
111
176
|
|
|
112
|
-
const
|
|
177
|
+
const onDisk = await readMigrations(root);
|
|
178
|
+
const settled = await settleFork(root, onDisk, options.mergeFork === true);
|
|
179
|
+
const migrations = settled.migrations;
|
|
180
|
+
const forkFields = settled.repairs === 0 ? {} : { forkRepairs: settled.repairs };
|
|
113
181
|
const current = declaredSchema(migrations);
|
|
114
182
|
// Refused, never defaulted to the empty schema: with nothing to diff against, every table the
|
|
115
183
|
// database already holds looks new and the generated `up` is `create table` for all of them.
|
|
@@ -166,10 +234,14 @@ export async function generateAppMigration(
|
|
|
166
234
|
return { outcome: 'unchanged', files: [], findings: [], unrendered: migration.unrendered };
|
|
167
235
|
}
|
|
168
236
|
const reconciled = await reconcileSchemaHash(root, newest.id);
|
|
237
|
+
const hashFiles = reconciled.written ? [`${MIGRATIONS_DIR}/${hashFileName(newest.id)}`] : [];
|
|
238
|
+
const quietOutcome = reconciled.written ? 'hash-recorded' : 'unchanged';
|
|
169
239
|
return {
|
|
170
|
-
outcome:
|
|
240
|
+
outcome: settled.repairs > 0 ? 'fork-merged' : quietOutcome,
|
|
171
241
|
schemaHash: reconciled.hash,
|
|
172
|
-
files:
|
|
242
|
+
files: [...settled.files, ...hashFiles],
|
|
243
|
+
newest: newest.id,
|
|
244
|
+
...forkFields,
|
|
173
245
|
findings: [],
|
|
174
246
|
unrendered: migration.unrendered,
|
|
175
247
|
};
|
|
@@ -180,7 +252,7 @@ export async function generateAppMigration(
|
|
|
180
252
|
// after this one. Each file is a ledger row of its own; see `@ultimat3/db`'s `generate-steps.ts`.
|
|
181
253
|
const steps = [migration, ...(migration.followUp === undefined ? [] : [migration.followUp])];
|
|
182
254
|
const dir = join(root, MIGRATIONS_DIR);
|
|
183
|
-
const files: string[] = [];
|
|
255
|
+
const files: string[] = [...settled.files];
|
|
184
256
|
let schemaHash = '';
|
|
185
257
|
for (const step of steps) {
|
|
186
258
|
const sql = `${step.id}.sql`;
|
|
@@ -200,6 +272,9 @@ export async function generateAppMigration(
|
|
|
200
272
|
migration,
|
|
201
273
|
schemaHash,
|
|
202
274
|
files,
|
|
275
|
+
tables: tablesBetween(current, steps[steps.length - 1]?.snapshot ?? migration.snapshot),
|
|
276
|
+
newest: steps[steps.length - 1]?.id ?? migration.id,
|
|
277
|
+
...forkFields,
|
|
203
278
|
findings: [],
|
|
204
279
|
unrendered: migration.unrendered,
|
|
205
280
|
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// One `x db migrate` pass and who applies it: this process through `serve.ts`'s `runMigrations`,
|
|
2
|
+
// or — beside a live `x dev` holding the embedded database — that process, asked over `/_x`.
|
|
3
|
+
// PGlite takes no lock of its own: a second opener's tables are gone at the holder's next write.
|
|
4
|
+
|
|
5
|
+
import type { DriftDifference, DriftReport } from '@ultimat3/db';
|
|
6
|
+
import type { CatalogDescription } from '@ultimat3/db/schema-dump';
|
|
7
|
+
import { unexpectedObjects } from '@ultimat3/db/schema-dump';
|
|
8
|
+
import { migrateThroughDev } from './db-migrate-through-dev';
|
|
9
|
+
import { liveObjectDrift } from './db-object-drift';
|
|
10
|
+
import { liveDevLockChecked } from './dev-lock-live';
|
|
11
|
+
import { resolveServices } from './runtime-bindings';
|
|
12
|
+
import { runMigrations } from './serve';
|
|
13
|
+
|
|
14
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
15
|
+
|
|
16
|
+
export interface MigratePass {
|
|
17
|
+
readonly applied: readonly string[];
|
|
18
|
+
readonly skipped: number;
|
|
19
|
+
readonly appVersion: string;
|
|
20
|
+
readonly durationMs: number;
|
|
21
|
+
/** The live schema against the ledger, after the apply. */
|
|
22
|
+
readonly drift: DriftReport;
|
|
23
|
+
/** What the live database holds that `expected` (the replayed migrations) does not create. */
|
|
24
|
+
objects(expected: CatalogDescription): Promise<readonly DriftDifference[]>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function migratePass(root: string, env: Env): Promise<MigratePass> {
|
|
28
|
+
const services = resolveServices(root, env);
|
|
29
|
+
const holder =
|
|
30
|
+
services.db.mode === 'embedded' ? await liveDevLockChecked(services.stateDir) : undefined;
|
|
31
|
+
if (holder !== undefined) {
|
|
32
|
+
const { drift, catalog, storage, ...report } = await migrateThroughDev(
|
|
33
|
+
holder,
|
|
34
|
+
services.stateDir,
|
|
35
|
+
);
|
|
36
|
+
return {
|
|
37
|
+
...report,
|
|
38
|
+
drift: { ok: drift.length === 0, differences: drift },
|
|
39
|
+
objects: async (expected) => [...unexpectedObjects(catalog, expected), ...storage],
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
const { report, drift } = await runMigrations({ root, env });
|
|
43
|
+
return {
|
|
44
|
+
applied: report.applied.map((entry) => entry.id),
|
|
45
|
+
skipped: report.skipped.length,
|
|
46
|
+
appVersion: report.appVersion,
|
|
47
|
+
durationMs: report.durationMs,
|
|
48
|
+
drift,
|
|
49
|
+
objects: (expected) => liveObjectDrift(root, env, expected),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// `x db migrate` beside a live `x dev` on the embedded database: the pass is asked of the process
|
|
2
|
+
// that holds `.x/pgdata` (`dev-db-migrate.ts`'s POST), never applied by a second opener. A holder
|
|
3
|
+
// that cannot answer is `X_DEV_ALREADY_RUNNING`, its fix the stop, migrate, start that does work.
|
|
4
|
+
|
|
5
|
+
import { renderThrowable, stringField, UltimateError } from '@ultimat3/core';
|
|
6
|
+
import { t } from '@ultimat3/schema';
|
|
7
|
+
import { DEV_MIGRATE_PATH } from './db-dev-wire';
|
|
8
|
+
import type { DevMigrateData } from './dev-db-migrate';
|
|
9
|
+
import { DevAlreadyRunningError, type DevLock } from './dev-lock';
|
|
10
|
+
import { liveDevLockChecked } from './dev-lock-live';
|
|
11
|
+
|
|
12
|
+
const DIFFERENCE = t.object({
|
|
13
|
+
kind: t.string,
|
|
14
|
+
table: t.string.min(0),
|
|
15
|
+
column: t.nullable(t.string),
|
|
16
|
+
cause: t.string,
|
|
17
|
+
fix: t.string,
|
|
18
|
+
});
|
|
19
|
+
const DATA = t.object({
|
|
20
|
+
applied: t.array(t.string),
|
|
21
|
+
skipped: t.number,
|
|
22
|
+
appVersion: t.string,
|
|
23
|
+
durationMs: t.number,
|
|
24
|
+
drift: t.array(DIFFERENCE),
|
|
25
|
+
catalog: t.object({ schema: t.string, tables: t.array(t.json()) }),
|
|
26
|
+
storage: t.array(DIFFERENCE),
|
|
27
|
+
});
|
|
28
|
+
const PAYLOAD = t.object({
|
|
29
|
+
ok: t.boolean,
|
|
30
|
+
data: t.optional(t.json()),
|
|
31
|
+
error: t.optional(t.object({ code: t.string, cause: t.string, fix: t.string })),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
/** One POST to the dev server, answered as parsed JSON. A seam so a test needs no server. */
|
|
35
|
+
export type PostJson = (url: string) => Promise<unknown>;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* `Sec-Fetch-Site: same-origin`, as a browser on the app's own origin sends it: the app's CSRF
|
|
39
|
+
* check runs before any route, and a POST carrying neither that nor an `Origin` is
|
|
40
|
+
* `X_CSRF_BLOCKED` on every app with the check on — which read here as "not a route of that x dev"
|
|
41
|
+
* (measured, two processes). A page on another site cannot forge the header; `/_x`'s own doors
|
|
42
|
+
* (loopback Host and peer) still decide who may ask.
|
|
43
|
+
*/
|
|
44
|
+
export const postJson: PostJson = async (url) =>
|
|
45
|
+
(await (
|
|
46
|
+
await fetch(url, {
|
|
47
|
+
method: 'POST',
|
|
48
|
+
headers: { accept: 'application/json', 'sec-fetch-site': 'same-origin' },
|
|
49
|
+
// A pass is every pending migration; a wedged server must not hold the command for ever.
|
|
50
|
+
signal: AbortSignal.timeout(120_000),
|
|
51
|
+
// `x dev --tls` serves its own development certificate, and this dials loopback only.
|
|
52
|
+
tls: { rejectUnauthorized: false },
|
|
53
|
+
})
|
|
54
|
+
).json()) as unknown;
|
|
55
|
+
|
|
56
|
+
/** The holder through loopback, whatever interface it bound: `/_x` answers that Host only. */
|
|
57
|
+
function devUrl(lock: DevLock, path: string): string {
|
|
58
|
+
const scheme = URL.parse(lock.url)?.protocol === 'https:' ? 'https' : 'http';
|
|
59
|
+
return `${scheme}://localhost:${lock.port}${path}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** One question for the holder: where it is asked, and how its `data` is read. */
|
|
63
|
+
export interface DevAsk<T> {
|
|
64
|
+
/** Under `/_x/db`, query included. */
|
|
65
|
+
readonly path: string;
|
|
66
|
+
/** The command as typed (`['db', 'migrate']`): what the fix runs between `x stop` and `x dev`. */
|
|
67
|
+
readonly resume: readonly string[];
|
|
68
|
+
/**
|
|
69
|
+
* For a request that must not run twice (a rollback): the read-only command that says whether it
|
|
70
|
+
* ran. A request SENT whose answer was lost then refuses with that read as its fix, never `resume`.
|
|
71
|
+
*/
|
|
72
|
+
readonly settle?: readonly string[];
|
|
73
|
+
/** `data` as this CLI reads it, or the reason it cannot. */
|
|
74
|
+
readonly read: (data: unknown) => { readonly value: T } | { readonly unreadable: string };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** How long a booting holder is waited for: a large app's `x dev` boots in about half a minute. */
|
|
78
|
+
export const BOOT_WAIT_MS = 120_000;
|
|
79
|
+
/** How long the lock may be absent — one child gone, the supervisor's next not yet claimed. */
|
|
80
|
+
export const LOCK_GAP_MS = 10_000;
|
|
81
|
+
const BOOT_POLL_MS = 500;
|
|
82
|
+
|
|
83
|
+
/** The seams of the wait: a test moves the clock and hands the lock each re-read finds. */
|
|
84
|
+
export interface DevWait {
|
|
85
|
+
readonly now: () => number;
|
|
86
|
+
readonly sleep: (ms: number) => Promise<void>;
|
|
87
|
+
/** The live lock as it is now: a restarted child wrote a new one. */
|
|
88
|
+
readonly relock: () => Promise<DevLock | undefined>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const waitFor = (stateDir: string): DevWait => ({
|
|
92
|
+
now: Date.now,
|
|
93
|
+
sleep: (ms) => Bun.sleep(ms),
|
|
94
|
+
relock: () => liveDevLockChecked(stateDir),
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Only a connection the kernel refused: the request was never sent, so asking again cannot run a
|
|
99
|
+
* pass twice. Anything else (a socket closed mid-answer, a timeout) may have reached the holder,
|
|
100
|
+
* and a rollback asked twice reverses two migrations.
|
|
101
|
+
*/
|
|
102
|
+
const neverSent = (error: unknown): boolean => {
|
|
103
|
+
const code = stringField(error, 'code');
|
|
104
|
+
return code === 'ECONNREFUSED' || code === 'ConnectionRefused';
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Asked of the holder, and answered by it. Its own refusal (a failed migration, a forked ledger)
|
|
109
|
+
* is re-thrown under its own code; anything that is not this route's answer — an `x dev` with no
|
|
110
|
+
* web role, an older CLI's server, a closed port — refuses with the fix that needs no holder.
|
|
111
|
+
*
|
|
112
|
+
* A holder that is BOOTING is waited for: its lock is claimed before its port is bound, and a save
|
|
113
|
+
* that restarts the child (an entity edit — the very edit this command follows) leaves exactly
|
|
114
|
+
* that for the length of a boot. Told apart from a server with no listener by the lock itself: a
|
|
115
|
+
* new pid, or a claim stamped inside the wait. Polled, since a boot announces nothing to wait on.
|
|
116
|
+
*/
|
|
117
|
+
export async function askDev<T>(
|
|
118
|
+
lock: DevLock,
|
|
119
|
+
stateDir: string,
|
|
120
|
+
ask: DevAsk<T>,
|
|
121
|
+
post: PostJson = postJson,
|
|
122
|
+
wait: DevWait = waitFor(stateDir),
|
|
123
|
+
): Promise<T> {
|
|
124
|
+
let holder = lock;
|
|
125
|
+
const alone = (unanswered: string, sent = false): DevAlreadyRunningError =>
|
|
126
|
+
new DevAlreadyRunningError({
|
|
127
|
+
lock: holder,
|
|
128
|
+
stateDir,
|
|
129
|
+
embeddedDb: true,
|
|
130
|
+
resume: ask.resume,
|
|
131
|
+
unanswered,
|
|
132
|
+
...(sent && ask.settle !== undefined ? { settle: ask.settle } : {}),
|
|
133
|
+
});
|
|
134
|
+
const started = wait.now();
|
|
135
|
+
let goneSince: number | undefined;
|
|
136
|
+
let answer: unknown;
|
|
137
|
+
for (;;) {
|
|
138
|
+
const url = devUrl(holder, ask.path);
|
|
139
|
+
try {
|
|
140
|
+
answer = await post(url);
|
|
141
|
+
break;
|
|
142
|
+
} catch (error) {
|
|
143
|
+
const unanswered = `${url} did not answer: ${renderThrowable(error)}`;
|
|
144
|
+
if (!neverSent(error)) throw alone(unanswered, true);
|
|
145
|
+
if (wait.now() - started >= BOOT_WAIT_MS) throw alone(unanswered);
|
|
146
|
+
const now = await wait.relock();
|
|
147
|
+
if (now === undefined) {
|
|
148
|
+
goneSince ??= wait.now();
|
|
149
|
+
if (wait.now() - goneSince >= LOCK_GAP_MS) {
|
|
150
|
+
throw alone(`${unanswered}; and that x dev exited while this command waited for it`);
|
|
151
|
+
}
|
|
152
|
+
} else {
|
|
153
|
+
goneSince = undefined;
|
|
154
|
+
const claimedAgo = wait.now() - Date.parse(now.startedAt);
|
|
155
|
+
// `NaN` for a lock with no stamp: not fresh, so not booting.
|
|
156
|
+
if (now.pid === holder.pid && !(claimedAgo < BOOT_WAIT_MS)) throw alone(unanswered);
|
|
157
|
+
holder = now;
|
|
158
|
+
}
|
|
159
|
+
await wait.sleep(BOOT_POLL_MS);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const url = devUrl(holder, ask.path);
|
|
163
|
+
const payload = PAYLOAD.safeParse(answer);
|
|
164
|
+
if (payload.issues !== undefined) {
|
|
165
|
+
throw alone(`${url} is not a route of that x dev (an older CLI, or no web role)`);
|
|
166
|
+
}
|
|
167
|
+
const { ok, data, error } = payload.value;
|
|
168
|
+
if (!ok && error !== undefined) throw new UltimateError(error);
|
|
169
|
+
const read = ok ? ask.read(data) : { unreadable: 'ok: false' };
|
|
170
|
+
if ('unreadable' in read) {
|
|
171
|
+
// The route itself answered: whatever it did is done, so this is a sent request's verdict.
|
|
172
|
+
throw alone(`${url} answered a pass this CLI cannot read (${read.unreadable})`, true);
|
|
173
|
+
}
|
|
174
|
+
return read.value;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The first issue of a failed parse, as `askDev`'s `unreadable` names it. */
|
|
178
|
+
export function unreadable(
|
|
179
|
+
issues: readonly { readonly path?: readonly unknown[] | undefined; readonly message: string }[],
|
|
180
|
+
): { readonly unreadable: string } {
|
|
181
|
+
const [issue] = issues;
|
|
182
|
+
return {
|
|
183
|
+
unreadable: issue === undefined ? 'ok: false' : `${issue.path?.join('.')}: ${issue.message}`,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** `x db migrate`'s pass, applied by the holder (`dev-db-migrate.ts`). */
|
|
188
|
+
export function migrateThroughDev(
|
|
189
|
+
lock: DevLock,
|
|
190
|
+
stateDir: string,
|
|
191
|
+
post: PostJson = postJson,
|
|
192
|
+
): Promise<DevMigrateData> {
|
|
193
|
+
return askDev(
|
|
194
|
+
lock,
|
|
195
|
+
stateDir,
|
|
196
|
+
{
|
|
197
|
+
path: DEV_MIGRATE_PATH,
|
|
198
|
+
resume: ['db', 'migrate'],
|
|
199
|
+
read: (data) => {
|
|
200
|
+
const parsed = DATA.safeParse(data);
|
|
201
|
+
if (parsed.issues !== undefined) return unreadable(parsed.issues);
|
|
202
|
+
// Narrowed, not re-validated field by field: both ends are this package on one machine,
|
|
203
|
+
// and the catalog is `introspectCatalog`'s own output — `kind` is db's closed set.
|
|
204
|
+
return { value: data as unknown as DevMigrateData };
|
|
205
|
+
},
|
|
206
|
+
},
|
|
207
|
+
post,
|
|
208
|
+
);
|
|
209
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// What `x db rollback` asks before the first `down` runs, under the migrate lock, of the exact rows
|
|
2
|
+
// about to be reversed: every one has a `-- down` half on disk, and on a deploy — or a database on
|
|
3
|
+
// another machine — the operator named each id in `ROLLBACK_ALLOW_DESTRUCTIVE`.
|
|
4
|
+
|
|
5
|
+
// why: Bun exposes no path-join primitive.
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
import { renderFixShellArg, tryResolveEnvironment } from '@ultimat3/core';
|
|
9
|
+
import type { LedgerRow, Migration } from '@ultimat3/db';
|
|
10
|
+
import { DbError, migrationIrreversible, ROLLBACK_ALLOW_DESTRUCTIVE_ENV } from '@ultimat3/db';
|
|
11
|
+
import { namedDeployed } from './framework-env';
|
|
12
|
+
import { isLoopbackHostname } from './loopback-host';
|
|
13
|
+
import { MIGRATIONS_DIR, parseMigrationSql } from './migrations';
|
|
14
|
+
import type { ServiceBinding } from './runtime-bindings';
|
|
15
|
+
|
|
16
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
17
|
+
|
|
18
|
+
/** The database the rollback runs against: `resolveServices(root, env).db`. */
|
|
19
|
+
export type RollbackDatabase = Pick<ServiceBinding, 'mode' | 'url'>;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Is `url` a Postgres on another machine? A local socket (no host, or a `host=` that is a path) and
|
|
23
|
+
* a loopback name are this machine's; a URL that does not parse is another's — fail closed.
|
|
24
|
+
*/
|
|
25
|
+
function remoteDatabase(url: string): boolean {
|
|
26
|
+
let parsed: URL;
|
|
27
|
+
try {
|
|
28
|
+
parsed = new URL(url);
|
|
29
|
+
} catch {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
const host = parsed.hostname || (parsed.searchParams.get('host') ?? '');
|
|
33
|
+
if (host === '' || host.startsWith('/')) return false;
|
|
34
|
+
return !isLoopbackHostname(host);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Who needs the names. A NAMED deploy — `namedDeployed`, framework-env's own predicate: staging
|
|
39
|
+
* included, which exists to fail the way production fails — and an `ULTIMATE_ENV` that is no
|
|
40
|
+
* environment: a typo must not read as "not production". And, whatever the environment resolves
|
|
41
|
+
* to, an external database on another machine: `DATABASE_URL=<prod> x db rollback` from a shell
|
|
42
|
+
* that names nothing resolves development, and reversed production unasked. A developer's own
|
|
43
|
+
* database (embedded, loopback, a local socket) reverses freely.
|
|
44
|
+
*/
|
|
45
|
+
export function rollbackNeedsConsent(env: Env, database?: RollbackDatabase): boolean {
|
|
46
|
+
if (namedDeployed(env) || tryResolveEnvironment({ env }) === undefined) return true;
|
|
47
|
+
return database?.mode === 'external' && remoteDatabase(database.url);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const namedIn = (allow: string | undefined): ReadonlySet<string> =>
|
|
51
|
+
new Set(
|
|
52
|
+
(allow ?? '')
|
|
53
|
+
.split(',')
|
|
54
|
+
.map((id) => id.trim())
|
|
55
|
+
.filter((id) => id !== ''),
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* A `down` is the destructive half by construction — reversing `add column` drops it, with every
|
|
60
|
+
* value written since — and the build still serving reads what it removes. So every id is named,
|
|
61
|
+
* not only those whose `up` was destructive: the consent `ledgerAheadOfBuild` takes for an older
|
|
62
|
+
* image over a newer schema, asked here of the schema change itself.
|
|
63
|
+
*/
|
|
64
|
+
function assertNamed(
|
|
65
|
+
targets: readonly LedgerRow[],
|
|
66
|
+
env: Env,
|
|
67
|
+
steps: number,
|
|
68
|
+
database: RollbackDatabase | undefined,
|
|
69
|
+
): void {
|
|
70
|
+
if (!rollbackNeedsConsent(env, database)) return;
|
|
71
|
+
const named = namedIn(env[ROLLBACK_ALLOW_DESTRUCTIVE_ENV]);
|
|
72
|
+
const unnamed = targets.filter((row) => !named.has(row.id)).map((row) => row.id);
|
|
73
|
+
if (unnamed.length === 0) return;
|
|
74
|
+
const all = targets.map((row) => row.id).join(',');
|
|
75
|
+
throw new DbError({
|
|
76
|
+
code: 'X_MIGRATION_ROLLBACK_DESTRUCTIVE',
|
|
77
|
+
cause: `x db rollback would reverse ${String(targets.length)} applied migration(s) on a deployed or remote database, and ${ROLLBACK_ALLOW_DESTRUCTIVE_ENV} does not name ${unnamed.join(', ')} — a down drops what its up added, rows included, under a build that still reads it`,
|
|
78
|
+
fix: `${ROLLBACK_ALLOW_DESTRUCTIVE_ENV}=${renderFixShellArg(all, '<migration id>')} x db rollback --steps ${String(steps)} --json # names each migration it reverses; first deploy a build that no longer reads what they added`,
|
|
79
|
+
meta: { refused: unnamed, steps },
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The migrations whose file carries no `-- down` marker at all. An EMPTY down under the marker is a
|
|
85
|
+
* reversal that needs no statement — `x db gen` writes one for a deferred `validate constraint` —
|
|
86
|
+
* so the two are told apart by the one reader of the marker: with none, `up` is the whole file.
|
|
87
|
+
*/
|
|
88
|
+
export async function withoutDown(
|
|
89
|
+
root: string,
|
|
90
|
+
migrations: readonly Migration[],
|
|
91
|
+
): Promise<ReadonlySet<string>> {
|
|
92
|
+
const unmarked = new Set<string>();
|
|
93
|
+
for (const migration of migrations) {
|
|
94
|
+
if (migration.down.trim() !== '') continue;
|
|
95
|
+
const text = await Bun.file(join(root, MIGRATIONS_DIR, `${migration.id}.sql`)).text();
|
|
96
|
+
if (parseMigrationSql(migration.id, text).up === text.trim()) unmarked.add(migration.id);
|
|
97
|
+
}
|
|
98
|
+
return unmarked;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A hand-written migration with no `-- down` half: unrecording it would reverse nothing. */
|
|
102
|
+
function assertReversible(targets: readonly LedgerRow[], unmarked: ReadonlySet<string>): void {
|
|
103
|
+
for (const row of targets) {
|
|
104
|
+
// Not on disk at all is `rollback()`'s own refusal (`X_MIGRATION_CONFLICT`), with its fix.
|
|
105
|
+
if (!unmarked.has(row.id)) continue;
|
|
106
|
+
const file = `${MIGRATIONS_DIR}/${renderFixShellArg(row.id, '<id>')}.sql`;
|
|
107
|
+
throw migrationIrreversible(
|
|
108
|
+
`migration "${row.id}" has no "-- down" half, so rolling it back would delete its ledger row and reverse nothing`,
|
|
109
|
+
`edit ${file} — add a line "-- down" and, below it, the SQL that reverses the statements above; then x db rollback`,
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* `rollback()`'s `confirm`: reversibility first (it is true in every environment), then consent.
|
|
116
|
+
* `database` is the binding the pass runs against; absent, only the environment is asked.
|
|
117
|
+
*/
|
|
118
|
+
export function rollbackConfirm(
|
|
119
|
+
unmarked: ReadonlySet<string>,
|
|
120
|
+
env: Env,
|
|
121
|
+
steps: number,
|
|
122
|
+
database?: RollbackDatabase,
|
|
123
|
+
): (targets: readonly LedgerRow[]) => void {
|
|
124
|
+
return (targets) => {
|
|
125
|
+
assertReversible(targets, unmarked);
|
|
126
|
+
assertNamed(targets, env, steps, database);
|
|
127
|
+
};
|
|
128
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// One `x db rollback` pass and who runs it: this process, on the boot `x db migrate` uses, or —
|
|
2
|
+
// beside a live `x dev` holding the embedded database — that process, asked over `/_x`
|
|
3
|
+
// (`dev-db-rollback.ts`). The rule `db-migrate-pass.ts` states: PGlite takes one opener.
|
|
4
|
+
|
|
5
|
+
import { rollback } from '@ultimat3/db';
|
|
6
|
+
import { t } from '@ultimat3/schema';
|
|
7
|
+
import { DEV_ROLLBACK_PATH } from './db-dev-wire';
|
|
8
|
+
import { askDev, type PostJson, unreadable } from './db-migrate-through-dev';
|
|
9
|
+
import { rollbackConfirm, withoutDown } from './db-rollback-consent';
|
|
10
|
+
import { liveDevLockChecked } from './dev-lock-live';
|
|
11
|
+
import { readMigrations } from './migrations';
|
|
12
|
+
import { resolveServices } from './runtime-bindings';
|
|
13
|
+
import { startQueue } from './runtime-queue';
|
|
14
|
+
|
|
15
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
16
|
+
|
|
17
|
+
const REVERTED = t.object({ reverted: t.array(t.string) });
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `rollback()` over the ambient client, with this command's two questions asked under the lock.
|
|
21
|
+
* Shared by the command and the dev route, so the holder cannot reverse what the command refuses.
|
|
22
|
+
*/
|
|
23
|
+
export async function reverseApplied(
|
|
24
|
+
root: string,
|
|
25
|
+
env: Env,
|
|
26
|
+
steps: number,
|
|
27
|
+
): Promise<readonly string[]> {
|
|
28
|
+
const migrations = await readMigrations(root);
|
|
29
|
+
// The binding, so a database on another machine needs the names whatever the environment says.
|
|
30
|
+
const database = resolveServices(root, env).db;
|
|
31
|
+
const confirm = rollbackConfirm(await withoutDown(root, migrations), env, steps, database);
|
|
32
|
+
return rollback({ migrations, steps, confirm });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The ids reversed, most recently applied first. */
|
|
36
|
+
export async function rollbackPass(
|
|
37
|
+
root: string,
|
|
38
|
+
env: Env,
|
|
39
|
+
steps: number,
|
|
40
|
+
post?: PostJson,
|
|
41
|
+
): Promise<readonly string[]> {
|
|
42
|
+
const services = resolveServices(root, env);
|
|
43
|
+
const holder =
|
|
44
|
+
services.db.mode === 'embedded' ? await liveDevLockChecked(services.stateDir) : undefined;
|
|
45
|
+
if (holder !== undefined) {
|
|
46
|
+
return askDev(
|
|
47
|
+
holder,
|
|
48
|
+
services.stateDir,
|
|
49
|
+
{
|
|
50
|
+
path: `${DEV_ROLLBACK_PATH}?steps=${String(steps)}`,
|
|
51
|
+
resume: ['db', 'rollback', '--steps', String(steps)],
|
|
52
|
+
// Not idempotent: a lost answer is read off the ledger, never asked again.
|
|
53
|
+
settle: ['db', 'status'],
|
|
54
|
+
read: (data) => {
|
|
55
|
+
const parsed = REVERTED.safeParse(data);
|
|
56
|
+
return parsed.issues === undefined
|
|
57
|
+
? { value: parsed.value.reverted }
|
|
58
|
+
: unreadable(parsed.issues);
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
post,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
// `runMigrations`' boot (`serve.ts`), for its reasons: the step that takes the migrate lock needs
|
|
65
|
+
// a session, and on PGlite with `database.rowSecurity` the DDL runs as `x_migrator`.
|
|
66
|
+
const queue = await startQueue(services, undefined, env, 'apply');
|
|
67
|
+
try {
|
|
68
|
+
const release =
|
|
69
|
+
services.db.mode === 'embedded'
|
|
70
|
+
? await (await import('./row-security-boot')).migrateAsMigrator(root)
|
|
71
|
+
: undefined;
|
|
72
|
+
return await reverseApplied(root, env, steps).finally(() => release?.());
|
|
73
|
+
} finally {
|
|
74
|
+
await queue.stop();
|
|
75
|
+
}
|
|
76
|
+
}
|
package/src/db-seed-generate.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { loadApp } from './app-load';
|
|
|
14
14
|
import type { CommandContext } from './command';
|
|
15
15
|
import type { SeedPassRow } from './db-seed';
|
|
16
16
|
import { parseSeedTierFlag, renderSeedTable, seedPassToJson } from './db-seed';
|
|
17
|
+
import { refuseEmbeddedWriteBesideDev } from './dev-lock-live';
|
|
17
18
|
import { readIntFlag } from './flag-number';
|
|
18
19
|
import { withJobDriver } from './jobs-driver';
|
|
19
20
|
import { msg } from './messages';
|
|
@@ -158,7 +159,10 @@ export async function runGeneratedSeed(ctx: CommandContext, root: string): Promi
|
|
|
158
159
|
dryRun,
|
|
159
160
|
transaction: (work) => withTransaction(() => work()),
|
|
160
161
|
}).then((row) => generatedResult(row, dryRun, findings));
|
|
161
|
-
|
|
162
|
+
if (dryRun) return write();
|
|
163
|
+
// The second PGlite writer `x db seed` refuses to be, on the same rule (`dev-lock-live.ts`).
|
|
164
|
+
await refuseEmbeddedWriteBesideDev(root, ctx.env, ['db', 'seed', '--generate']);
|
|
165
|
+
return withJobDriver(root, ctx, write);
|
|
162
166
|
}
|
|
163
167
|
|
|
164
168
|
function generatedResult(
|
package/src/db-seed.ts
CHANGED
|
@@ -103,6 +103,7 @@ export async function discoverSeeds(root: string): Promise<SeedDiscovery> {
|
|
|
103
103
|
const seeds: DiscoveredSeed[] = [];
|
|
104
104
|
const findings: Finding[] = [];
|
|
105
105
|
const seen = new Set<string>();
|
|
106
|
+
const declared = new Set<unknown>();
|
|
106
107
|
for (const pattern of SEED_GLOBS) {
|
|
107
108
|
for await (const absolute of new Bun.Glob(pattern).scan({ cwd: root, absolute: true })) {
|
|
108
109
|
const file = posixRelative(root, absolute);
|
|
@@ -118,7 +119,12 @@ export async function discoverSeeds(root: string): Promise<SeedDiscovery> {
|
|
|
118
119
|
continue;
|
|
119
120
|
}
|
|
120
121
|
for (const value of Object.values(module)) {
|
|
121
|
-
|
|
122
|
+
// One seed, however many modules export it: a `seeds.ts` barrel re-exporting `dev` is the
|
|
123
|
+
// same object, and counted twice it ran twice — or `x db seed dev` named two seeds. The
|
|
124
|
+
// `seeds/` glob is walked first, so the declaring file is the one kept.
|
|
125
|
+
if (!isSeed(value) || declared.has(value)) continue;
|
|
126
|
+
declared.add(value);
|
|
127
|
+
seeds.push({ seed: value, file });
|
|
122
128
|
}
|
|
123
129
|
}
|
|
124
130
|
}
|