Files
website/server/src/model/events/eventDefinitions.db.js
wtclaude f40dd765c3
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 49s
PR Checks / client-build (pull_request) Successful in 1m4s
PR Checks / server-tests (pull_request) Successful in 6m6s
fix(core): the last fixes' core half (W1 W2 W5 W19)
Stage 4 of docs/modules/rust/PLAN_LAST_FIXES.md, with the org lead's
2026-10-22 decisions.

W19: one module per site at boot, as at install. The first module
directory by name holds the site, whether or not it then loads; every
other is recorded startup_failed at the manifest stage, before a line of
its code is required, with a reason naming the module that holds the
site. Module-uo and Module-Rust side by side used to fail the second
with a slot collision. Loader, lifecycle, schema and event-contract
tests that loaded several fixture modules now load each case alone.

W1: a reconcile files a resource the game no longer has, and that is
past its `until`, as expired rather than orphaned, with the same log
line expired() writes. No MODULE_API bump: `until` and reconcile's
answer are unchanged.

W5: a dry run that passes on the draft is kept with the fingerprint of
the validated spec (three nullable columns on event_definitions).
Publish stamps the new version verified, with that dry run's reviewer
and time, when the spec it freezes has the same fingerprint, and writes
version.verified on the occurrences it re-pins. Verify answers
draftRecorded and publish answers verified; OpenAPI regenerated.

W2: the run console says "Phase p1: steps done, waiting to advance" and
"Why this phase has not advanced", not "has not started".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-10-22 00:38:39 -05:00

252 lines
9.0 KiB
JavaScript

// ── event_definitions — SQL only ───────────────────────────────────────────
//
// EVENTS.md §D. The `.db.js` half of the pair: parameterised SQL and hydration,
// no policy. Everything that decides whether a write is allowed lives in
// `eventDefinitions.model.js`.
const { query } = require('../../utils/db')
const { parseJson } = require('./eventJson')
const hydrate = (row) =>
row && {
...row,
spec: parseJson(row.spec, null),
// TINYINT(1) arrives as 0/1. Every reader of this column asks a yes/no
// question, and the public model's filters compare against a boolean.
listed: Boolean(row.listed),
}
// `current_version` is joined rather than stored: the list screen shows "v3" and
// the column that would hold it is a denormalisation of a row this query already
// has to reach for the publish date anyway.
//
// `current_version_verified_at` rides along for the same reason and answers the
// same kind of question (Phase 6). A `ready` definition whose version has never
// been dry-run will not start on its schedule (§K), and the one place that fact
// is worth saying is the screen its author is already looking at -- the
// alternative is finding out on the Friday it did not run.
const SELECT_LIST = `
SELECT d.*, s.name AS series_name, s.slug AS series_slug,
v.version AS current_version,
v.verified_at AS current_version_verified_at
FROM event_definitions d
LEFT JOIN event_series s ON s.id = d.series_id
LEFT JOIN event_versions v ON v.id = d.current_version_id
`
const list = async ({ state = null } = {}) => {
const rows = state
? await query(`${SELECT_LIST} WHERE d.state = ? ORDER BY d.updated_at DESC, d.id DESC`, [state])
: await query(`${SELECT_LIST} ORDER BY d.updated_at DESC, d.id DESC`)
return rows.map(hydrate)
}
const getById = async (id) => {
const [row] = await query(`${SELECT_LIST} WHERE d.id = ?`, [id])
return hydrate(row)
}
const getBySlug = async (slug) => {
const [row] = await query(`${SELECT_LIST} WHERE d.slug = ?`, [slug])
return hydrate(row)
}
/** Does any OTHER definition hold this slug? The uniqueness pre-check. */
const slugTaken = async (slug, exceptId = null) => {
const rows = exceptId
? await query('SELECT id FROM event_definitions WHERE slug = ? AND id <> ?', [slug, exceptId])
: await query('SELECT id FROM event_definitions WHERE slug = ?', [slug])
return rows.length > 0
}
const insert = async (d) => {
const result = await query(
`INSERT INTO event_definitions
(title, slug, summary, body, image_url, owner_module, series_id, series_order,
concurrency_key, grace_seconds, timezone, listed, spec, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
d.title,
d.slug,
d.summary,
d.body,
d.image_url,
d.owner_module,
d.series_id,
d.series_order,
d.concurrency_key,
d.grace_seconds,
d.timezone,
d.listed ? 1 : 0,
JSON.stringify(d.spec),
d.created_by,
d.created_by,
],
)
return result.insertId
}
const update = (id, d) =>
query(
`UPDATE event_definitions
SET title = ?, slug = ?, summary = ?, body = ?, image_url = ?, series_id = ?,
series_order = ?, concurrency_key = ?, grace_seconds = ?, timezone = ?,
listed = ?, spec = ?, updated_by = ?
WHERE id = ?`,
[
d.title,
d.slug,
d.summary,
d.body,
d.image_url,
d.series_id,
d.series_order,
d.concurrency_key,
d.grace_seconds,
d.timezone,
d.listed ? 1 : 0,
JSON.stringify(d.spec),
d.updated_by,
id,
],
)
/**
* Point a definition at the version it just published, and mark it `ready`.
*
* One statement, because the two halves are the same fact: `ready` means "a
* version has been published and the schedule is live" (§E), so a state without
* a `current_version_id` is a lie the scheduler would act on.
*/
const markReady = (id, versionId, userId) =>
query(
`UPDATE event_definitions
SET state = 'ready', current_version_id = ?, updated_by = ?
WHERE id = ?`,
[versionId, userId, id],
)
/**
* Record a dry run that passed on the draft, with the fingerprint of the spec it
* passed on (W5). Publish reads it back through `getById`'s `d.*`.
*/
const markDraftVerified = (id, { at = new Date(), userId = null, hash }) =>
query(
`UPDATE event_definitions
SET draft_verified_at = ?, draft_verified_by = ?, draft_verified_hash = ?
WHERE id = ?`,
[at, userId, hash, id],
)
/**
* Every definition the runner should expand a recurrence for (Phase 4).
*
* `ready` is the whole gate, and it is deliberately the only one: EVENTS.md §E
* defines `ready` as "a version has been published and the schedule is live", so
* publishing IS the switch and archiving is how an operator turns a recurrence
* off. A separate schedule-enabled flag would be a second answer to a question
* `state` already answers, and the two would eventually disagree.
*
* The VERSION's spec is joined rather than the definition's working copy: the
* draft is what an author is midway through editing, and a half-typed `weekly`
* must never materialise anything. The pinned spec comes back with it, so the
* whole expansion is one round trip.
*
* The series columns are here for the CALENDAR rather than the runner, which
* ignores them: a projected occurrence has to be filterable and labellable by
* its arc exactly as a materialised run is, and a second query to learn the name
* of a row this one already reached would be two round trips for a join.
*/
const findSchedulable = async ({ listedOnly = false } = {}) => {
const rows = await query(
`SELECT d.id, d.title, d.slug, d.summary, d.image_url, d.timezone, d.grace_seconds,
d.concurrency_key, d.current_version_id, d.series_id, v.spec AS version_spec,
s.name AS series_name, s.slug AS series_slug
FROM event_definitions d
JOIN event_versions v ON v.id = d.current_version_id
LEFT JOIN event_series s ON s.id = d.series_id
WHERE d.state = 'ready'${listedOnly ? ' AND d.listed = 1' : ''}
ORDER BY d.id`,
)
return rows.map((row) => ({ ...row, version_spec: parseJson(row.version_spec, null) }))
}
/**
* Every `ready` definition whose PUBLISHED version starts on this trigger
* (Rust PLAN_REDESIGNS §14.3.12, D370). The emit path's question, asked on every
* firing, so it answers in one query and the common answer is no rows.
*
* Read from the version, never the working copy, for the reason the schedule
* expansion is: a start an author is midway through typing must not fire.
* `JSON_EXTRACT` over `$.starts[*].on` is an array, or NULL for a version with
* no starts, and `JSON_CONTAINS` of NULL is not true.
*/
const findStartingOn = async (triggerId) => {
const rows = await query(
`SELECT d.id, d.title, d.grace_seconds, d.current_version_id,
v.spec AS version_spec, v.verified_at AS version_verified_at
FROM event_definitions d
JOIN event_versions v ON v.id = d.current_version_id
WHERE d.state = 'ready'
AND JSON_CONTAINS(JSON_EXTRACT(v.spec, '$.starts[*].on'), JSON_QUOTE(?))
ORDER BY d.id`,
[triggerId],
)
return rows.map((row) => ({ ...row, version_spec: parseJson(row.version_spec, null) }))
}
/**
* One definition by slug, for the PUBLIC event page (Phase 14a).
*
* `ready` and `listed` are both in the WHERE rather than checked by the caller,
* so an unlisted event answers exactly as a nonexistent one does — a 404 that
* cannot be told from "no such slug". A caller that filtered afterwards would
* be one forgotten early-return away from publishing a draft.
*
* An ARCHIVED definition is deliberately absent too. Archiving is what delete
* means on the admin screen, and a page that kept answering afterwards would
* make the only delete this feature has do nothing an operator could see.
*/
const getPublicBySlug = async (slug) => {
const [row] = await query(
`${SELECT_LIST} WHERE d.slug = ? AND d.state = 'ready' AND d.listed = 1`,
[slug],
)
return hydrate(row)
}
/** Every listed, ready definition in one series, in the arc's own order. */
const listPublicBySeries = async (seriesId) => {
const rows = await query(
`${SELECT_LIST}
WHERE d.series_id = ? AND d.state = 'ready' AND d.listed = 1
ORDER BY d.series_order, d.id`,
[seriesId],
)
return rows.map(hydrate)
}
/**
* Archive. Never a hard delete while runs reference it (§ API surface) — and the
* schema would refuse one anyway, because `event_runs.version_id` RESTRICTs.
* Archiving is what "delete" means on this screen, and the row keeps its history.
*/
const archive = (id, userId) =>
query("UPDATE event_definitions SET state = 'archived', updated_by = ? WHERE id = ?", [userId, id])
module.exports = {
list,
getById,
getBySlug,
getPublicBySlug,
listPublicBySeries,
slugTaken,
findSchedulable,
findStartingOn,
insert,
update,
markReady,
markDraftVerified,
archive,
}