feat(events): schema, CRUD and the core action registry (Phase 1)
All checks were successful
PR Checks / client-build (pull_request) Successful in 26s
PR Checks / bot-tests (pull_request) Successful in 29s
PR Checks / server-tests (pull_request) Successful in 13m24s

EVENTS_PLAN.md Phase 1. Six of the nine core tables — the ones that do not
depend on the module contract — plus definitions CRUD, publish, archive, and
the action registry with core as its first registrant.

**Nothing dispatches.** There is no runner until Phase 2, so a run row is
created and stays `scheduled`. That is this phase's correct answer and the
surface renders it verbatim rather than hiding it.

Schema (`db/schema.sql`, append-only):
  event_series, event_definitions, event_versions, event_runs,
  event_run_steps, event_run_log. The four that need a writer —
  event_action_settings, event_run_budget, event_run_resources,
  event_run_participants — arrive with the phases that give them one.

Registry (`modules/registries.js` + `config/coreEventActions.js`):
  registerEventActions staging and commit, with its own id namespace, the
  closed risk and reversibility sets, revert() required iff and only iff
  reversible: 'ledger', a bounded budgetMs and a param shape whose every
  entry needs a type and an example. perform/revert/cost are stripped from
  everything the catalog serves. Core declares core.announce, core.wait and
  core.cue through the same staging area a module will use.

  It is reachable ONLY by registerCore(): loader.js builds its own api facade
  and has no method that delegates here, so no module can call it and
  MODULE_API_VERSION is untouched. Phase 7 adds the facade and the bump.

Surface (13 routes under /api/v1/admin/events):
  Reads staff-wide; publish, archive and run creation admin-only from this
  phase per EVENTS.md §N2, even though the switchboard they will consult does
  not exist yet — a button that is admin-only later and open now is a gate
  nobody notices was missing. The live run controls and `verify` are absent
  rather than stubbed, because nothing is in flight yet.

Four things the build settled, all recorded in docs:
  - event_definitions gained a `spec` column. A draft's working copy cannot
    be an event_versions row: that table is immutable and a run pins one.
  - The spec validator must accept its own output. It added `actionVersion`
    and `dormant` and then refused them as unknown keys, which would have made
    the second save of any definition — and publish's re-validation —
    impossible. A test caught it; both are now accepted and recomputed.
  - A param's `example` is required, optional params included, matching
    registerEventTriggers. It is the authoring form's placeholder.
  - Two routes the §API-surface table did not name: GET /admin/events/:id and
    GET /admin/events/series.

Core's three perform() bodies answer { ok: false, retry: false } rather than
{ ok: true }: `ok: true` on an action that did nothing is a recorded world
change that did not occur, which is the exact mistake §F's failure default
exists to prevent.

`conditions.checkLiteral` is exported and reused for step-param type checking
— one switch over the six types, so "is this a datetime" has one answer.

Verified: 44 new tests, whole server suite, `npm run check:modules`, routes
manifest and swagger regenerated (the manifest diff is +13 routes, zero moved).

Docs: RunicGateway/docs#209

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-01 23:29:07 -05:00
parent 6331b36c45
commit 8e03497eb3
23 changed files with 4714 additions and 1 deletions

View File

@@ -0,0 +1,134 @@
// ── 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),
}
// `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.
const SELECT_LIST = `
SELECT d.*, s.name AS series_name, s.slug AS series_slug,
v.version AS current_version
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, 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,
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 = ?,
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,
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],
)
/**
* 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,
slugTaken,
insert,
update,
markReady,
archive,
}

View File

@@ -0,0 +1,270 @@
// ── Event definitions — the save path ──────────────────────────────────────
//
// EVENTS.md §D and "Versioning, and editing a live event". A definition is
// operator-authored data, and this file is the boundary that decides whether a
// version of it may exist. The authoring UI (Phase 3, then Phase 13) will
// re-check some of this for the sake of a good inline error; that second copy is
// expected to drift, so this one is the one that decides, and a definition
// arriving by any other route gets the same answer.
//
// **The three rules with teeth, and each is a rule about time rather than about
// shape:**
//
// 1. Publishing SNAPSHOTS. It copies the working spec into an immutable
// `event_versions` row and points `current_version_id` at it. Editing
// afterwards is free and does not touch the row a live run pinned.
// 2. A dormant step blocks a PUBLISH and never a SAVE. An uninstalled module
// must not make an author's work uneditable, and it must not let a version be
// published that names a verb nobody can perform.
// 3. Archiving is what "delete" means here. `event_runs.version_id` RESTRICTs, so
// a hard delete of a definition that has ever run is refused by the database
// anyway — and the row's history is the thing an audit reads.
const db = require('./eventDefinitions.db')
const versionsDb = require('./eventVersions.db')
const runsDb = require('./eventRuns.db')
const seriesDb = require('./eventSeries.db')
const spec = require('../../events/spec')
const { slugify, uniqueSlug } = require('../teams/teamSlug')
const { cleanBody } = require('../../utils/sanitizeHtml')
const MAX_TITLE = 200
const MAX_SUMMARY = 500
const MAX_URL = 500
const MAX_CONCURRENCY_KEY = 190
// A day either side of §D's default. Below a minute the grace window cannot
// survive a single slow boot; above a day a "missed" occurrence would start
// silently the following afternoon, which is the exact behaviour §E forbids.
const MIN_GRACE_SECONDS = 60
const MAX_GRACE_SECONDS = 86_400
/**
* IANA zone names, checked against the platform's own database rather than a
* list. `Intl.DateTimeFormat` throws `RangeError` on an unknown zone, and Node
* ships the full tzdata — so this is the same check Phase 4's occurrence
* arithmetic will make, asked one screen earlier where an operator can fix it.
*/
function isTimezone(tz) {
try {
Intl.DateTimeFormat(undefined, { timeZone: tz })
return true
} catch {
return false
}
}
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
const trimOrNull = (v, max) => {
if (v === undefined || v === null) return null
const s = String(v).trim()
return s === '' ? null : s.slice(0, max)
}
/**
* Validate an incoming definition against the registries and the schema.
*
* `{ ok: true, definition }` with a normalised row ready for insert/update, or
* `{ ok: false, errors }` listing every problem rather than the first.
*
* `existing` is the row being edited, or null on a create. It is what lets a
* dormant step survive: the ids already in the saved spec widen what the spec
* validator will accept, so an uninstall is never destructive after the fact.
*/
async function validate(input, { existing = null } = {}) {
const errors = []
const body = isPlainObject(input) ? input : {}
const title = trimOrNull(body.title, MAX_TITLE)
if (!title) errors.push('title is required')
const summary = trimOrNull(body.summary, MAX_SUMMARY)
const imageUrl = trimOrNull(body.imageUrl, MAX_URL)
const concurrencyKey = trimOrNull(body.concurrencyKey, MAX_CONCURRENCY_KEY)
// The storyline. Sanitized on write, exactly as a wiki page and a forum post
// are: it is author-supplied HTML that ends up on a public page.
const storyline = body.body === undefined || body.body === null ? null : cleanBody(String(body.body))
const timezone = trimOrNull(body.timezone, 64) || existing?.timezone || 'UTC'
if (!isTimezone(timezone)) errors.push(`timezone: "${timezone}" is not an IANA zone name`)
const graceRaw = body.graceSeconds === undefined ? (existing?.grace_seconds ?? 900) : body.graceSeconds
const graceSeconds = Number(graceRaw)
if (
!Number.isInteger(graceSeconds) ||
graceSeconds < MIN_GRACE_SECONDS ||
graceSeconds > MAX_GRACE_SECONDS
) {
errors.push(`graceSeconds must be an integer ${MIN_GRACE_SECONDS}..${MAX_GRACE_SECONDS}`)
}
let seriesId = null
if (body.seriesId !== undefined && body.seriesId !== null && body.seriesId !== '') {
seriesId = Number(body.seriesId)
if (!Number.isInteger(seriesId) || seriesId < 1) {
errors.push('seriesId must be an integer')
seriesId = null
} else if (!(await seriesDb.exists(seriesId))) {
// Checked here as well as by the foreign key, because a 1452 reaching a
// controller is a 500 and this is a 400 an author can act on.
errors.push(`seriesId ${seriesId} does not exist`)
seriesId = null
}
} else if (existing) {
seriesId = existing.series_id
}
const seriesOrderRaw = body.seriesOrder === undefined ? (existing?.series_order ?? 0) : body.seriesOrder
const seriesOrder = Number(seriesOrderRaw)
if (!Number.isInteger(seriesOrder)) errors.push('seriesOrder must be an integer')
// ── the spec ──
const rawSpec = body.spec === undefined ? existing?.spec ?? spec.emptySpec() : body.spec
const known = existing?.spec ? spec.actionIdsIn(existing.spec) : []
const checked = spec.validate(rawSpec, { knownActionIds: known })
if (!checked.ok) errors.push(...checked.errors)
// ── the slug ──
//
// Derived from the title on create and FROZEN afterwards, like a Team's: the
// public event page lives at it, and a retitle must not break a link somebody
// posted in Discord. An author who genuinely needs a different address makes a
// new definition.
let slug = existing?.slug || null
if (!slug) {
const stem = slugify(title || '') || 'event'
const taken = (await db.list()).map((d) => d.slug)
slug = uniqueSlug(stem, taken, { fallback: 'event' })
}
if (errors.length) return { ok: false, errors }
return {
ok: true,
definition: {
title,
slug,
summary,
body: storyline,
image_url: imageUrl,
owner_module: existing?.owner_module ?? null,
series_id: seriesId,
series_order: seriesOrder,
concurrency_key: concurrencyKey,
grace_seconds: graceSeconds,
timezone,
spec: checked.spec,
},
}
}
/** Create a draft. */
async function create(input, userId) {
const result = await validate(input)
if (!result.ok) return result
const id = await db.insert({ ...result.definition, created_by: userId })
return { ok: true, id, definition: await db.getById(id) }
}
/**
* Edit a definition.
*
* An `archived` definition is not editable. That is the one state check here,
* and it is a real one rather than a formality: archiving is how a definition is
* retired, and a retired definition that can still be edited is a definition
* somebody will edit and then wonder why it never runs.
*/
async function save(id, input, userId) {
const existing = await db.getById(id)
if (!existing) return { ok: false, status: 404, errors: ['no such event definition'] }
if (existing.state === 'archived') {
return { ok: false, status: 409, errors: ['an archived definition cannot be edited'] }
}
const result = await validate(input, { existing })
if (!result.ok) return result
await db.update(id, { ...result.definition, updated_by: userId })
return { ok: true, id, definition: await db.getById(id) }
}
/**
* Publish: snapshot the working spec into an immutable version and go `ready`.
*
* The spec is re-validated here against the registries as they stand RIGHT NOW,
* not trusted from the save that wrote it. A module uninstalled between the two
* is the whole reason: the save was legitimate, and publishing a version whose
* steps name a verb nobody can perform would be a run that fails at dispatch
* with the world half-changed.
*/
async function publish(id, userId) {
const existing = await db.getById(id)
if (!existing) return { ok: false, status: 404, errors: ['no such event definition'] }
if (existing.state === 'archived') {
return { ok: false, status: 409, errors: ['an archived definition cannot be published'] }
}
const checked = spec.validate(existing.spec, {
knownActionIds: spec.actionIdsIn(existing.spec),
})
if (!checked.ok) return { ok: false, status: 400, errors: checked.errors }
const publishable = spec.publishable(checked.spec)
if (!publishable.ok) {
return {
ok: false,
status: 409,
errors: [
`cannot publish: no module registers ${publishable.dormant.join(', ')}`,
],
}
}
if (!checked.spec.phases.some((p) => p.steps.length)) {
// An empty event publishes cleanly and then does nothing, which looks like a
// broken run rather than an empty one. Refusing costs an author one click and
// saves an operator a diagnosis.
return { ok: false, status: 400, errors: ['cannot publish: no phase has any steps'] }
}
const version = await versionsDb.nextVersion(id)
const versionId = await versionsDb.insert(id, version, checked.spec, userId)
await db.markReady(id, versionId, userId)
return { ok: true, versionId, version, definition: await db.getById(id) }
}
/**
* Archive.
*
* Refused while a run of this definition is still in flight — not because the
* database would object (it would not; archiving is an UPDATE), but because the
* screen the run is on reads its title and state from here, and retiring a
* definition mid-run makes the console describe something that is no longer
* supposed to exist. Cancel the run, then archive.
*/
async function archive(id, userId) {
const existing = await db.getById(id)
if (!existing) return { ok: false, status: 404, errors: ['no such event definition'] }
if (existing.state === 'archived') return { ok: true, definition: existing }
const active = await runsDb.countActiveForDefinition(id)
if (active > 0) {
return {
ok: false,
status: 409,
errors: [`cannot archive: ${active} run(s) of this definition are still in flight`],
}
}
await db.archive(id, userId)
return { ok: true, definition: await db.getById(id) }
}
module.exports = {
validate,
create,
save,
publish,
archive,
isTimezone,
MIN_GRACE_SECONDS,
MAX_GRACE_SECONDS,
}

View File

@@ -0,0 +1,23 @@
// ── One JSON reader for the whole events model ─────────────────────────────
//
// JSON columns come back from the driver already parsed on some MariaDB/driver
// combinations and as a string on others — it depends on whether the column is a
// real JSON type or the LONGTEXT + CHECK alias MariaDB implements it as. Every
// read in this directory goes through this, so no caller has to know which it
// got.
//
// Lifted from `engagementRules.db.js`, which learned it first, and hoisted into
// its own file here rather than copied into six: six copies of a fallback is six
// chances for one of them to fall back to `{}` where the reader expects `[]`.
function parseJson(value, fallback) {
if (value === null || value === undefined) return fallback
if (typeof value !== 'string') return value
try {
return JSON.parse(value)
} catch {
return fallback
}
}
module.exports = { parseJson }

View File

@@ -0,0 +1,67 @@
// ── event_run_log — SQL only ───────────────────────────────────────────────
//
// EVENTS.md § Observability. "Why didn't phase 3 start?" must be a query, and
// `activity_log.detail` is TEXT and unqueryable, which is why this table exists
// beside the audit log rather than instead of it. Both are written: the audit of
// WHO published WHAT goes to `activity_log`, the diagnosis goes here.
//
// **`kind` is a closed set enforced here rather than an ENUM in the DDL.** The
// set grows with almost every later phase — conditions in Phase 5, cap draws in
// Phase 6, ledger movements in Phase 8 — and an ENUM change is a table alter
// this project has no migration system for. A constant in a file is the same
// guarantee with a cheaper hinge.
const log = require('../../utils/logger')('events')
const { query } = require('../../utils/db')
const { parseJson } = require('./eventJson')
// Phase 1's kinds. Later phases append; nothing here is ever renamed, because a
// stored row would then name a kind no reader knows.
const KINDS = [
'run.created', // an occurrence was materialised
'run.status', // a status transition, with from/to
'phase.entered', // a phase's steps were materialised
'step.status', // a step transition, with the module's answer
'note', // a human action taken from the admin surface
]
const hydrate = (row) => row && { ...row, detail: parseJson(row.detail, null) }
const listForRun = async (runId, { limit = 500 } = {}) => {
const n = Math.min(Math.max(Number(limit) || 500, 1), 2000)
return (
await query(`SELECT * FROM event_run_log WHERE run_id = ? ORDER BY at DESC, id DESC LIMIT ${n}`, [
runId,
])
).map(hydrate)
}
/**
* Write one line. **Never throws.**
*
* The diagnostic log is what an operator reads when something has already gone
* wrong, so a failure to write it must not become a second failure on top of the
* first — a runner that aborted a run because it could not record why would be
* the worst possible reading of "observability". The same posture
* `uoLinkClient.js` takes: answer, do not throw.
*/
async function write({ runId, stepId = null, kind, phase = null, detail = null }) {
if (!KINDS.includes(kind)) {
// A programming error, not an operational one, and it is louder than a
// silent drop for exactly that reason.
log.warn('event run log: unknown kind', { kind, runId })
return false
}
try {
await query(
'INSERT INTO event_run_log (run_id, step_id, kind, phase, detail) VALUES (?, ?, ?, ?, ?)',
[runId, stepId, kind, phase, detail === null ? null : JSON.stringify(detail)],
)
return true
} catch (err) {
log.error('event run log write failed', { runId, kind, message: err.message })
return false
}
}
module.exports = { KINDS, listForRun, write }

View File

@@ -0,0 +1,95 @@
// ── event_run_steps — SQL only ─────────────────────────────────────────────
//
// EVENTS.md §D and §E. Phase 1 materialises a run's steps and reads them back
// for the run console. **Draining them is Phase 2's**: the CAS claim, the lease,
// the attempt counter and the classification of a module's answer are the
// runner, and none of them is stubbed here.
//
// The one runtime property Phase 1 does have to get right is the idempotency key
// (§E). Core mints it ONCE, at materialisation, and it does NOT vary by attempt —
// a retry re-sends the same key so the game side can recognise the repeat. That
// makes it a property of the INSERT below rather than of the dispatch, which is
// the only reason it can be stable at all.
const crypto = require('crypto')
const { query } = require('../../utils/db')
const { parseJson } = require('./eventJson')
const hydrate = (row) => row && { ...row, params: parseJson(row.params, {}) }
/**
* `sha256(runId | stepId)`, truncated to 40 hex — the shape `shardEvents.dedupeKey`
* already uses, so the two dedupe keys on this codebase read alike.
*
* The step id is not known until the row exists, so materialisation inserts with
* a provisional key and stamps the real one immediately afterwards. That is one
* extra statement per step and it buys the property the whole retry story rests
* on: the key is a function of identity, never of attempt or of clock.
*/
const idempotencyKey = (runId, stepId) =>
crypto.createHash('sha256').update(`${runId}|${stepId}`).digest('hex').slice(0, 40)
const listForRun = async (runId) =>
(
await query(
'SELECT * FROM event_run_steps WHERE run_id = ? ORDER BY phase, seq, id',
[runId],
)
).map(hydrate)
const getById = async (id) => {
const [row] = await query('SELECT * FROM event_run_steps WHERE id = ?', [id])
return hydrate(row)
}
/**
* Materialise one phase's steps.
*
* `INSERT IGNORE` against `UNIQUE (run_id, phase, seq)`, so a tick that overran
* into the next one cannot double-materialise a phase — the same argument the
* occurrence key makes one table up, at the other end of the run.
*
* Returns the rows as they now stand, created or pre-existing, so a caller that
* lost the race still gets the step ids.
*/
const materialisePhase = async (runId, phase, steps) => {
for (let i = 0; i < steps.length; i++) {
const step = steps[i]
const result = await query(
`INSERT IGNORE INTO event_run_steps
(run_id, phase, seq, action_id, params, action_version, on_failure, idempotency_key)
VALUES (?, ?, ?, ?, ?, ?, ?, '')`,
[
runId,
phase,
i,
step.actionId,
JSON.stringify(step.params || {}),
step.actionVersion || 1,
step.onFailure || 'pause',
],
)
if (Number(result?.affectedRows || 0) === 1) {
// Stamped in a second statement because the key is a function of the row's
// own id. Scoped by the empty key so a re-run of this loop over an existing
// phase can never overwrite a key a dispatch has already sent.
await query(
"UPDATE event_run_steps SET idempotency_key = ? WHERE id = ? AND idempotency_key = ''",
[idempotencyKey(runId, result.insertId), result.insertId],
)
}
}
return listForRun(runId)
}
/** The run console's summary line: how many steps sit in each status. */
const statusCounts = async (runId) => {
const rows = await query(
'SELECT status, COUNT(*) AS n FROM event_run_steps WHERE run_id = ? GROUP BY status',
[runId],
)
return Object.fromEntries(rows.map((r) => [r.status, Number(r.n)]))
}
module.exports = { listForRun, getById, materialisePhase, statusCounts, idempotencyKey }

View File

@@ -0,0 +1,105 @@
// ── event_runs — SQL only ──────────────────────────────────────────────────
//
// EVENTS.md §D and §E. Phase 1 writes exactly one kind of row — a `scheduled`
// occurrence — and reads them back for the admin surface. **The claim, the CAS
// transitions and the lease reclaim are Phase 2's** and are deliberately not
// stubbed here: a half-written claim is worse than no claim, because it reads as
// protection.
//
// What Phase 1 does own is the INSERT, and it owns the important half of it:
// materialisation is `INSERT IGNORE` against `UNIQUE (definition_id, scope,
// scheduled_for)`, so a second attempt at one occurrence writes nothing and
// answers honestly rather than raising a duplicate-key error a caller has to
// interpret.
const { query } = require('../../utils/db')
const { parseJson } = require('./eventJson')
const hydrate = (row) => row && { ...row, params: parseJson(row.params, null), rehearsal: Boolean(row.rehearsal) }
const SELECT_LIST = `
SELECT r.*, d.title AS definition_title, d.slug AS definition_slug, v.version AS version_number
FROM event_runs r
JOIN event_definitions d ON d.id = r.definition_id
JOIN event_versions v ON v.id = r.version_id
`
/**
* The admin run list. Newest occurrence first, across every definition.
*
* `limit` is interpolated after an integer coercion rather than bound, because
* MariaDB will not take a placeholder in LIMIT on a prepared statement. It never
* reaches SQL as anything but a number.
*/
const list = async ({ definitionId = null, status = null, limit = 100 } = {}) => {
const where = []
const args = []
if (definitionId) {
where.push('r.definition_id = ?')
args.push(definitionId)
}
if (status) {
where.push('r.status = ?')
args.push(status)
}
const clause = where.length ? `WHERE ${where.join(' AND ')}` : ''
const n = Math.min(Math.max(Number(limit) || 100, 1), 500)
const rows = await query(
`${SELECT_LIST} ${clause} ORDER BY r.scheduled_for DESC, r.id DESC LIMIT ${n}`,
args,
)
return rows.map(hydrate)
}
const getById = async (id) => {
const [row] = await query(`${SELECT_LIST} WHERE r.id = ?`, [id])
return hydrate(row)
}
/**
* Materialise one occurrence. Answers the row id, or `null` when one already
* existed — which is not an error and is the ordinary answer under a tick that
* overran into the next one.
*/
const materialise = async (run) => {
const result = await query(
`INSERT IGNORE INTO event_runs
(definition_id, version_id, scope, scheduled_for, timezone, concurrency_key,
params, rehearsal, started_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
run.definition_id,
run.version_id,
run.scope || '',
run.scheduled_for,
run.timezone || 'UTC',
run.concurrency_key,
run.params === null || run.params === undefined ? null : JSON.stringify(run.params),
run.rehearsal ? 1 : 0,
run.started_by,
],
)
return Number(result?.affectedRows || 0) === 1 ? result.insertId : null
}
/** The occurrence the unique key names, whether or not this call created it. */
const findOccurrence = async (definitionId, scope, scheduledFor) => {
const [row] = await query(
`${SELECT_LIST} WHERE r.definition_id = ? AND r.scope = ? AND r.scheduled_for = ?`,
[definitionId, scope || '', scheduledFor],
)
return hydrate(row)
}
/** Is anything of this definition not yet terminal? The archive pre-check. */
const countActiveForDefinition = async (definitionId) => {
const [row] = await query(
`SELECT COUNT(*) AS n FROM event_runs
WHERE definition_id = ?
AND status IN ('scheduled','starting','running','paused','ending')`,
[definitionId],
)
return Number(row?.n || 0)
}
module.exports = { list, getById, materialise, findOccurrence, countActiveForDefinition }

View File

@@ -0,0 +1,134 @@
// ── Event runs — creating an occurrence ────────────────────────────────────
//
// EVENTS.md §E. Phase 1 creates a run row and materialises the first phase's
// steps. **It does not start anything**: there is no runner until Phase 2, so a
// row created here sits at `scheduled` indefinitely. That is the correct
// behaviour for this phase and it has to be VISIBLE as such rather than looking
// broken, which is why `create()` answers with the row and the admin surface
// renders the status verbatim.
//
// Two properties this file owns, both of which are the reason it exists before
// the runner rather than with it:
//
// - **Materialisation is `INSERT IGNORE` against the occurrence key.** Two
// attempts at one occurrence produce one row and an honest answer, not a
// duplicate-key error a caller has to interpret. The unique index — not a
// claim — is what makes "one run per occurrence per scope" true (§E).
// - **The idempotency key is minted with the step row and never varies by
// attempt.** It is a function of identity, so it can only be stable if it is
// stamped where the identity is created.
const db = require('./eventRuns.db')
const stepsDb = require('./eventRunSteps.db')
const logDb = require('./eventRunLog.db')
const definitionsDb = require('./eventDefinitions.db')
const versionsDb = require('./eventVersions.db')
const MAX_SCOPE = 190
/**
* Render a definition's `concurrency_key` template against a run's params.
*
* `invasion:{region}` with `{ region: 'Yew' }` becomes `invasion:Yew` (§E). A
* placeholder with no matching param is left standing rather than replaced with
* an empty string: `invasion:` would collide with every other unrendered key on
* the deployment, which is the opposite of what a concurrency key is for, and a
* literal `invasion:{region}` in the column is a visible mistake.
*/
function renderConcurrencyKey(template, params) {
if (!template) return null
return String(template)
.replace(/\{([a-zA-Z][a-zA-Z0-9_]*)\}/g, (whole, name) => {
const value = params && params[name]
return value === undefined || value === null || value === '' ? whole : String(value)
})
.slice(0, MAX_SCOPE)
}
/**
* Create one occurrence of a definition and materialise its first phase.
*
* `scheduledFor` defaults to now — "start now" is an occurrence whose instant is
* the present, not a separate concept, which is what keeps the runner's one
* materialise/advance path honest when Phase 4 adds recurrence on top.
*/
async function create(definitionId, { scope = '', scheduledFor = null, rehearsal = false, params = null } = {}, userId) {
const definition = await definitionsDb.getById(definitionId)
if (!definition) return { ok: false, status: 404, errors: ['no such event definition'] }
if (definition.state !== 'ready') {
return {
ok: false,
status: 409,
errors: [`a ${definition.state} definition has no published version to run`],
}
}
if (!definition.current_version_id) {
return { ok: false, status: 409, errors: ['this definition has no published version'] }
}
const version = await versionsDb.getById(definition.current_version_id)
if (!version?.spec?.phases?.length) {
return { ok: false, status: 409, errors: ['the published version has no phases'] }
}
const scopeValue = String(scope || '').slice(0, MAX_SCOPE)
const when = scheduledFor ? new Date(scheduledFor) : new Date()
if (Number.isNaN(when.getTime())) {
return { ok: false, status: 400, errors: ['scheduledFor is not a date'] }
}
const runId = await db.materialise({
definition_id: definitionId,
version_id: version.id,
scope: scopeValue,
// Stored as UTC. The definition's zone is what an occurrence is COMPUTED in
// (Phase 4); what is stored is the instant.
scheduled_for: when,
timezone: definition.timezone,
concurrency_key: renderConcurrencyKey(definition.concurrency_key, params),
params,
rehearsal,
started_by: userId,
})
if (runId === null) {
// The occurrence already existed. Not an error — it is what the unique index
// is for — so the existing row is the answer.
const existing = await db.findOccurrence(definitionId, scopeValue, when)
return { ok: true, created: false, run: existing }
}
await logDb.write({
runId,
kind: 'run.created',
detail: {
definitionId,
versionId: version.id,
version: version.version,
scope: scopeValue,
rehearsal: Boolean(rehearsal),
by: userId,
},
})
// The first phase's steps, materialised at creation rather than at start.
// Phase 2 materialises each LATER phase as the run enters it; doing the first
// one here is what makes a Phase 1 run row inspectable — an operator can see
// the steps that would run, with their params and their idempotency keys,
// before there is anything to run them.
const first = version.spec.phases[0]
await stepsDb.materialisePhase(runId, first.key, first.steps || [])
await logDb.write({ runId, kind: 'phase.entered', phase: first.key, detail: { steps: (first.steps || []).length } })
return { ok: true, created: true, run: await db.getById(runId) }
}
/** A run, its steps and its status counts — what the run console reads. */
async function detail(runId) {
const run = await db.getById(runId)
if (!run) return null
const [steps, counts] = await Promise.all([stepsDb.listForRun(runId), stepsDb.statusCounts(runId)])
return { run, steps, counts }
}
module.exports = { create, detail, renderConcurrencyKey }

View File

@@ -0,0 +1,23 @@
// ── event_series — SQL only ────────────────────────────────────────────────
//
// EVENTS.md §D. The arc a definition may belong to. Phase 1 needs the reads —
// `event_definitions.series_id` is a foreign key and the definition save path
// has to check it resolves — and creating one is Phase 4's, where the calendar
// is what makes an arc visible.
const { query } = require('../../utils/db')
const list = async () =>
query('SELECT * FROM event_series ORDER BY ordering, name, id')
const getById = async (id) => {
const [row] = await query('SELECT * FROM event_series WHERE id = ?', [id])
return row || null
}
const exists = async (id) => {
const [row] = await query('SELECT id FROM event_series WHERE id = ?', [id])
return Boolean(row)
}
module.exports = { list, getById, exists }

View File

@@ -0,0 +1,54 @@
// ── event_versions — SQL only ──────────────────────────────────────────────
//
// EVENTS.md §D. Immutable: there is an insert and there are reads, and there is
// deliberately no update and no delete. A run pins a version, and that pin is
// what makes the run reproducible and an audit answerable after the definition
// has been edited underneath it.
const { query } = require('../../utils/db')
const { parseJson } = require('./eventJson')
const hydrate = (row) => row && { ...row, spec: parseJson(row.spec, null) }
const listForDefinition = async (definitionId) =>
(
await query(
`SELECT v.id, v.definition_id, v.version, v.published_at, v.published_by, u.username AS published_by_username
FROM event_versions v
LEFT JOIN users u ON u.id = v.published_by
WHERE v.definition_id = ?
ORDER BY v.version DESC`,
[definitionId],
)
).map((row) => row)
const getById = async (id) => {
const [row] = await query('SELECT * FROM event_versions WHERE id = ?', [id])
return hydrate(row)
}
/**
* The next version number for a definition.
*
* Read separately and then INSERTed, which is a read-then-write — and it is safe
* only because `UNIQUE (definition_id, version)` is behind it. Two publishes
* racing for version 4 is one 1062 the caller reports, not two rows called 4.
* The unique index is the mechanism; this query is the ergonomics.
*/
const nextVersion = async (definitionId) => {
const [row] = await query(
'SELECT COALESCE(MAX(version), 0) + 1 AS next FROM event_versions WHERE definition_id = ?',
[definitionId],
)
return Number(row?.next || 1)
}
const insert = async (definitionId, version, spec, userId) => {
const result = await query(
'INSERT INTO event_versions (definition_id, version, spec, published_by) VALUES (?, ?, ?, ?)',
[definitionId, version, JSON.stringify(spec), userId],
)
return result.insertId
}
module.exports = { listForDefinition, getById, nextVersion, insert }