feat(modules): replay module schema fragments after core's
All checks were successful
PR Checks / bot-install (pull_request) Successful in 22s
PR Checks / client-build (pull_request) Successful in 28s
PR Checks / server-tests (pull_request) Successful in 10m9s

Phase 2, PR 3 of docs/website/MODULE_SYSTEM.md 2.7. ensureSchema() now replays
every installed module's schema fragment immediately after core's schema.sql,
per MODULE_API.md 2.6.

The work splits across two files on the line of whether a database is needed to
know the answer. loader.js VALIDATES a fragment at load time, before anything is
mounted, because every rule 2.6 states about the SQL is knowable by reading it;
a module that breaks one never mounts (4.4, left column). modules/schema.js
EXECUTES it, so the only failures there are the ones the database alone could
report, and those are post-mount and answer 503 (4.4, right column).

Validation is a leading-verb allowlist -- CREATE, ALTER, INSERT, UPDATE, the
four core's own schema.sql uses -- rather than the DROP denylist 2.6 words it
as. A fragment is replayed on every boot, so TRUNCATE and DELETE would empty a
table at each restart and RENAME would fail at the second one; a denylist only
ever bans what somebody thought of. A CREATE TABLE missing IF NOT EXISTS is
rejected for the same reason: it works once and fails every boot after, which
presents to an operator as a module that broke on restart.

The splitter moves to utils/sqlStatements.js so core's schema and a fragment are
split by literally the same code, which is what 2.6 promises. It is its own file
rather than an export of utils/db.js because the loader validates fragments at
require time and must not drag the mariadb pool into app.js's require chain.

The replay sits outside ensureSchema's wait-for-the-database retry loop: a
fragment that throws is one module's failure, not a signal the database is
coming up, and retrying core's whole schema nine more times over one module's
bad SQL would turn a 503'd module into a two-minute boot.

Found while wiring it: db/seed.js calls ensureSchema() standalone for
`npm run seed`, without ever requiring app.js, so the loader has not scanned and
fragments()'s 7.6 throw would have broken seeding outright. The replay asks
isLoaded() and logs the skip rather than swallowing it -- a booting server
quietly getting no module tables is the thing 7.6 exists to prevent.

Verification:

- 856 server tests pass, 14 new. moduleSchema.test.js injects the query fn, so
  the exact statements and their order are asserted with the pool at a dead port
  like every other suite.
- routes.manifest.json and routes.guards.json diffs are zero lines, 229 routes
  -- the phase 2 exit criterion. swagger-output.json regenerates byte-identical.
- Run for real against the local MariaDB with two fixture modules: a good
  fragment created its table, applied its ALTER and seeded its row; a fragment
  whose SQL passes validation but the server rejects (`id NOTATYPE`) marked only
  that module startup_failed, its route answering 503 while the other answered
  200; a second ensureSchema on the same database was a clean no-op.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-10 16:56:58 -05:00
parent 7780fb033b
commit 2892d01b24
6 changed files with 541 additions and 23 deletions

View File

@@ -18,16 +18,22 @@
// boot (§4.4).
//
// What is deliberately NOT here yet, each landing with the PR that first calls
// it (§2.7): schema-fragment replay (PR 3), the three de-entanglement registries
// (PR 4), boot/shutdown hook dispatch and the `installed_modules` reconcile
// (PR 5), GET /api/v1/public/modules and the client chunk's static mount
// (PRs 6-7). Until PR 5 the state a module carries is in memory only.
// it (§2.7): the three de-entanglement registries (PR 4), boot/shutdown hook
// dispatch and the `installed_modules` reconcile (PR 5), GET
// /api/v1/public/modules and the client chunk's static mount (PRs 6-7). Until
// PR 5 the state a module carries is in memory only.
//
// PR 3 added the fragment half of the schema story: this file VALIDATES a
// fragment (statement by statement, at load time, before anything is mounted)
// and publishes it through `fragments()`. Replaying it needs a database, so it
// belongs to modules/schema.js, which utils/db.js calls after core's schema.
const fs = require('fs')
const path = require('path')
const { MODULE_API_VERSION } = require('./version')
const semver = require('./semver')
const { splitStatements } = require('../utils/sqlStatements')
const log = require('../utils/logger')('modules')
@@ -193,10 +199,52 @@ function coreTableNames() {
return coreTables
}
/** Every table name a schema fragment declares. Throws if the file is unreadable. */
// The only leading verbs a fragment may use — an allowlist, not a DROP denylist.
//
// §2.6 bans `DROP`, but a denylist only ever bans what somebody thought of, and
// core's own schema.sql needs exactly four verbs: CREATE, ALTER, INSERT, UPDATE.
// Anything else in a file that is REPLAYED ON EVERY BOOT is a mistake worth
// failing on — TRUNCATE and DELETE would empty a table every restart, RENAME
// would break on the second one, and GRANT/SET/USE are core's business, not a
// module's. CREATE covers CREATE INDEX as well as CREATE TABLE.
//
// This is a leading-verb check and says so: `ALTER TABLE x DROP COLUMN y` passes
// it. Catching that needs a SQL parser, which is a large dependency to take on
// for a rule whose real job is stopping the obvious foot-gun early.
const ALLOWED_VERBS = new Set(['CREATE', 'ALTER', 'INSERT', 'UPDATE'])
const CREATE_TABLE_ANY = /^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?/i
const CREATE_TABLE_GUARDED = /^CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+/i
/**
* Read and validate a module's schema fragment; return every table it declares.
*
* Validation happens HERE, at load time, and not in modules/schema.js where the
* fragment is replayed, because every rule §2.6 states is knowable by reading
* the file — no database required. Failing at load means a module with a bad
* fragment never mounts at all (§4.4's first column: routes and nav simply
* absent), rather than mounting, 503ing, and leaving whatever its fragment did
* manage to execute behind it.
*
* Throws if the file is unreadable or breaks a rule.
*/
function tablesOf(dir, manifest) {
if (!manifest.schema) return new Set()
const sql = fs.readFileSync(path.join(dir, manifest.schema), 'utf8')
const file = path.join(dir, manifest.schema)
const sql = fs.readFileSync(file, 'utf8')
for (const statement of splitStatements(sql)) {
const verb = (statement.match(/^\w+/) || [''])[0].toUpperCase()
if (!ALLOWED_VERBS.has(verb)) {
throw new Error(`schema fragment statement starts with "${verb}" (allowed: ${[...ALLOWED_VERBS].join(', ')})`)
}
// A bare CREATE TABLE succeeds exactly once and fails every boot after it,
// which presents as a module that worked until the first restart.
if (CREATE_TABLE_ANY.test(statement) && !CREATE_TABLE_GUARDED.test(statement)) {
throw new Error('schema fragment has a CREATE TABLE without IF NOT EXISTS')
}
}
return new Set([...sql.matchAll(CREATE_TABLE)].map((m) => m[1].toLowerCase()))
}
@@ -448,6 +496,18 @@ function assertLoaded(caller) {
if (!loaded) throw new Error(`modules.${caller}() before modules.load()`)
}
/**
* Has load() run in this process?
*
* The one legitimate reason to ask instead of just calling an accessor: a
* process that never required app.js and so has no module list to be wrong
* about. `npm run seed` (db/seed.js) is exactly that — it calls ensureSchema()
* standalone, and the fragment replay has to be able to tell "this is the seed
* script" from "the server booted and something is mis-ordered", which is the
* distinction §7.6's throw exists to preserve everywhere else.
*/
const isLoaded = () => loaded
/**
* Every module found on the volume, loaded or failed, in scan order.
*
@@ -467,7 +527,24 @@ function list() {
}))
}
/**
* Every schema fragment waiting to be replayed, in scan order.
*
* `registered` only: a module that failed validation must not get its tables
* created (it is not going to run), and one already `started` has had them. The
* absolute path is resolved here rather than handed out as a manifest-relative
* name, so the replay never has to know how a module directory is laid out.
*
* @returns {{id: string, file: string}[]}
*/
function fragments() {
assertLoaded('fragments')
return [...modules.values()]
.filter((r) => r.state === 'registered' && r.manifest.schema)
.map((r) => ({ id: r.id, file: path.join(r.dir, r.manifest.schema) }))
}
/** Absolute path of the modules directory. */
const dir = () => MODULES_DIR
module.exports = { load, list, setState, dir }
module.exports = { load, list, setState, fragments, isLoaded, dir }

View File

@@ -0,0 +1,84 @@
// ── Module schema fragment replay ──────────────────────────────────────────
//
// Phase 2, PR 3 of docs/website/MODULE_SYSTEM.md §2.7. Normative contract:
// docs/website/MODULE_API.md §2.6 (fragments) and §4.4 (failure is a state).
//
// utils/db.js calls replayFragments() once, immediately after core's schema.sql
// is in place and before seedDefaults(), so that by the time a module's onBoot
// runs (PR 5) its tables exist.
//
// The split of responsibility with loader.js is worth stating, because it is the
// reason there are two files:
//
// loader.js VALIDATES a fragment — at load time, with no database, before
// anything is mounted. Every rule §2.6 states about the SQL is
// knowable by reading it, so a fragment that breaks one costs the
// module its mount entirely (§4.4, first column).
// schema.js EXECUTES it. Only reachable failures live here: the database
// rejecting a statement it could not have known was bad. Those are
// post-mount, so they 503 (§4.4, second column).
//
// The property this file exists to keep: **a fragment that fails takes down its
// own module and nothing else.** Not core's boot, not another module's tables.
const fs = require('fs')
const { splitStatements } = require('../utils/sqlStatements')
const log = require('../utils/logger')('modules')
/**
* Replay every installed module's schema fragment, in scan order.
*
* Never throws. A module whose fragment fails is moved to `startup_failed` with
* the database's own message as the reason, its routes answer 503 through the
* dispatch guard the loader already mounted, and the next module is replayed as
* if nothing happened.
*
* Partial application is accepted rather than compensated for: MariaDB commits
* each DDL statement implicitly, so a fragment failing at statement three has
* already created the first two tables and no wrapping transaction could undo
* them. Since every statement is required to be idempotent (§2.6), the fix is
* for the operator to correct the fragment and reboot — the surviving tables are
* re-CREATE-IF-NOT-EXISTSed harmlessly and the replay carries on past them.
*
* @param {object} [deps] injection seam for tests — the whole point of this
* function taking arguments at all, since the server suite runs with the pool
* pointed at a dead port.
* @param {(sql: string) => Promise<any>} [deps.query]
* @param {object} [deps.modules] the loader
*/
async function replayFragments({ query, modules } = {}) {
/* eslint-disable global-require */
const run = query || require('../utils/db').query
const loader = modules || require('./loader')
/* eslint-enable global-require */
// Not an error: `npm run seed` calls ensureSchema() without ever requiring
// app.js, so no scan has happened and there is genuinely nothing to replay.
// Logged rather than silently skipped — the one thing that must not happen is
// a booting server quietly getting no module tables (§7.6).
if (!loader.isLoaded()) {
log.info('no module scan in this process — skipping schema fragment replay')
return
}
for (const { id, file } of loader.fragments()) {
try {
const statements = splitStatements(fs.readFileSync(file, 'utf8'))
for (const statement of statements) {
// Serially, and awaited: a fragment's ALTER TABLE routinely depends on
// the CREATE TABLE above it.
await run(statement)
}
log.info(`schema ensured for module "${id}"`, { statements: statements.length })
} catch (err) {
loader.setState(id, 'startup_failed', err.message)
log.error(`module "${id}" schema fragment failed — its routes will answer 503`, {
reason: err.message,
})
}
}
}
module.exports = { replayFragments }