feat(events): schema, CRUD and the core action registry (Phase 1)
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:
315
server/src/router/v1/admin/events.controller.js
Normal file
315
server/src/router/v1/admin/events.controller.js
Normal file
@@ -0,0 +1,315 @@
|
||||
// ── Admin: events ──────────────────────────────────────────────────────────
|
||||
//
|
||||
// EVENTS.md § API surface, Phase 1. Definitions CRUD, publish, archive, the
|
||||
// action catalog and the run reads.
|
||||
//
|
||||
// This file reads ids out of URLs and shapes responses; it validates nothing.
|
||||
// Every decision lives in `model/events/*.model.js` and in `events/spec.js`, so
|
||||
// a definition arriving from a future import or a restore gets the same answer
|
||||
// this screen does.
|
||||
//
|
||||
// **What is deliberately absent**: pause, resume, advance, cancel, step
|
||||
// skip/retry/confirm, cleanup and the action switchboard. Each of them acts on a
|
||||
// run in flight, and nothing is in flight until Phase 2 builds the runner. A
|
||||
// control that returns 200 and does nothing is worse than one that is not there.
|
||||
|
||||
const registries = require('../../../modules/registries')
|
||||
const spec = require('../../../events/spec')
|
||||
const definitionsDb = require('../../../model/events/eventDefinitions.db')
|
||||
const definitions = require('../../../model/events/eventDefinitions.model')
|
||||
const versionsDb = require('../../../model/events/eventVersions.db')
|
||||
const seriesDb = require('../../../model/events/eventSeries.db')
|
||||
const runsDb = require('../../../model/events/eventRuns.db')
|
||||
const runs = require('../../../model/events/eventRuns.model')
|
||||
const logDb = require('../../../model/events/eventRunLog.db')
|
||||
const activity = require('../../../model/activity/activity.model')
|
||||
|
||||
const asId = (raw) => {
|
||||
const n = Number(raw)
|
||||
return Number.isInteger(n) && n > 0 ? n : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape a definition takes on the wire.
|
||||
*
|
||||
* Explicit rather than the row, like every other admin surface here: the row
|
||||
* carries `created_by`, `updated_by` and the joined series columns, and a
|
||||
* response that spreads it is a response that gains a column the day somebody
|
||||
* adds one.
|
||||
*/
|
||||
const shapeDefinition = (d) => ({
|
||||
id: d.id,
|
||||
title: d.title,
|
||||
slug: d.slug,
|
||||
summary: d.summary,
|
||||
body: d.body,
|
||||
imageUrl: d.image_url,
|
||||
ownerModule: d.owner_module,
|
||||
state: d.state,
|
||||
currentVersionId: d.current_version_id,
|
||||
currentVersion: d.current_version,
|
||||
seriesId: d.series_id,
|
||||
seriesName: d.series_name,
|
||||
seriesOrder: d.series_order,
|
||||
concurrencyKey: d.concurrency_key,
|
||||
graceSeconds: d.grace_seconds,
|
||||
timezone: d.timezone,
|
||||
spec: d.spec,
|
||||
createdAt: d.created_at,
|
||||
updatedAt: d.updated_at,
|
||||
})
|
||||
|
||||
const shapeRun = (r) => ({
|
||||
id: r.id,
|
||||
definitionId: r.definition_id,
|
||||
definitionTitle: r.definition_title,
|
||||
definitionSlug: r.definition_slug,
|
||||
versionId: r.version_id,
|
||||
version: r.version_number,
|
||||
scope: r.scope,
|
||||
status: r.status,
|
||||
health: r.health,
|
||||
cleanupStatus: r.cleanup_status,
|
||||
currentPhase: r.current_phase,
|
||||
scheduledFor: r.scheduled_for,
|
||||
timezone: r.timezone,
|
||||
concurrencyKey: r.concurrency_key,
|
||||
params: r.params,
|
||||
rehearsal: r.rehearsal,
|
||||
startedAt: r.started_at,
|
||||
endedAt: r.ended_at,
|
||||
lastError: r.last_error,
|
||||
createdAt: r.created_at,
|
||||
})
|
||||
|
||||
const shapeStep = (s) => ({
|
||||
id: s.id,
|
||||
runId: s.run_id,
|
||||
phase: s.phase,
|
||||
seq: s.seq,
|
||||
actionId: s.action_id,
|
||||
params: s.params,
|
||||
actionVersion: s.action_version,
|
||||
status: s.status,
|
||||
dueAt: s.due_at,
|
||||
attempts: s.attempts,
|
||||
onFailure: s.on_failure,
|
||||
idempotencyKey: s.idempotency_key,
|
||||
lastError: s.last_error,
|
||||
startedAt: s.started_at,
|
||||
finishedAt: s.finished_at,
|
||||
})
|
||||
|
||||
/** GET /api/v1/admin/events */
|
||||
exports.list = async (req, res) => {
|
||||
const state = ['draft', 'ready', 'archived'].includes(req.query.state) ? req.query.state : null
|
||||
const rows = await definitionsDb.list({ state })
|
||||
res.json({ events: rows.map(shapeDefinition) })
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/v1/admin/events/catalog
|
||||
*
|
||||
* The registered actions, their param schemas, their risk classes and the
|
||||
* vocabularies over both — served from the registries, so there is no table
|
||||
* behind it and a module that was uninstalled simply stops appearing. Same
|
||||
* argument the engagement trigger catalog makes: the editor offers exactly the
|
||||
* set the save path checks against, so the two cannot drift.
|
||||
*
|
||||
* Budget dimensions are absent, and that is Phase 1 being honest rather than an
|
||||
* omission: `registerEventBudgets` is Phase 7's and nothing declares one yet.
|
||||
*/
|
||||
exports.catalog = (_req, res) => {
|
||||
res.json({
|
||||
actions: registries.allEventActions(),
|
||||
risks: registries.ACTION_RISKS,
|
||||
reversible: registries.ACTION_REVERSIBLE,
|
||||
paramTypes: registries.ACTION_PARAM_TYPES,
|
||||
onFailure: spec.ON_FAILURE,
|
||||
onFailureByRisk: spec.ON_FAILURE_BY_RISK,
|
||||
scheduleKinds: spec.SCHEDULE_KINDS,
|
||||
limits: {
|
||||
maxPhases: spec.MAX_PHASES,
|
||||
maxStepsPerPhase: spec.MAX_STEPS_PER_PHASE,
|
||||
maxSteps: spec.MAX_STEPS,
|
||||
defaultBudgetMs: registries.DEFAULT_BUDGET_MS,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** GET /api/v1/admin/events/series */
|
||||
exports.listSeries = async (_req, res) => {
|
||||
const rows = await seriesDb.list()
|
||||
res.json({
|
||||
series: rows.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
slug: s.slug,
|
||||
description: s.description,
|
||||
ordering: s.ordering,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
/** GET /api/v1/admin/events/runs */
|
||||
exports.listRuns = async (req, res) => {
|
||||
const rows = await runsDb.list({
|
||||
definitionId: asId(req.query.definitionId),
|
||||
status: req.query.status || null,
|
||||
limit: req.query.limit,
|
||||
})
|
||||
res.json({ runs: rows.map(shapeRun) })
|
||||
}
|
||||
|
||||
/** GET /api/v1/admin/events/runs/:runId */
|
||||
exports.getRun = async (req, res) => {
|
||||
const runId = asId(req.params.runId)
|
||||
if (!runId) return res.status(400).json({ error: 'bad run id' })
|
||||
const found = await runs.detail(runId)
|
||||
if (!found) return res.status(404).json({ error: 'no such run' })
|
||||
return res.json({
|
||||
run: shapeRun(found.run),
|
||||
steps: found.steps.map(shapeStep),
|
||||
counts: found.counts,
|
||||
})
|
||||
}
|
||||
|
||||
/** GET /api/v1/admin/events/runs/:runId/log */
|
||||
exports.getRunLog = async (req, res) => {
|
||||
const runId = asId(req.params.runId)
|
||||
if (!runId) return res.status(400).json({ error: 'bad run id' })
|
||||
const run = await runsDb.getById(runId)
|
||||
if (!run) return res.status(404).json({ error: 'no such run' })
|
||||
const lines = await logDb.listForRun(runId, { limit: req.query.limit })
|
||||
return res.json({
|
||||
log: lines.map((l) => ({
|
||||
id: l.id,
|
||||
stepId: l.step_id,
|
||||
kind: l.kind,
|
||||
phase: l.phase,
|
||||
detail: l.detail,
|
||||
at: l.at,
|
||||
})),
|
||||
kinds: logDb.KINDS,
|
||||
})
|
||||
}
|
||||
|
||||
/** GET /api/v1/admin/events/:id */
|
||||
exports.get = async (req, res) => {
|
||||
const id = asId(req.params.id)
|
||||
if (!id) return res.status(400).json({ error: 'bad event id' })
|
||||
const row = await definitionsDb.getById(id)
|
||||
if (!row) return res.status(404).json({ error: 'no such event definition' })
|
||||
return res.json({ event: shapeDefinition(row) })
|
||||
}
|
||||
|
||||
/** GET /api/v1/admin/events/:id/versions */
|
||||
exports.listVersions = async (req, res) => {
|
||||
const id = asId(req.params.id)
|
||||
if (!id) return res.status(400).json({ error: 'bad event id' })
|
||||
const row = await definitionsDb.getById(id)
|
||||
if (!row) return res.status(404).json({ error: 'no such event definition' })
|
||||
const rows = await versionsDb.listForDefinition(id)
|
||||
return res.json({
|
||||
versions: rows.map((v) => ({
|
||||
id: v.id,
|
||||
version: v.version,
|
||||
publishedAt: v.published_at,
|
||||
publishedBy: v.published_by,
|
||||
publishedByUsername: v.published_by_username,
|
||||
current: v.id === row.current_version_id,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
/** POST /api/v1/admin/events */
|
||||
exports.create = async (req, res) => {
|
||||
const result = await definitions.create(req.body, req.user.id)
|
||||
if (!result.ok) return res.status(result.status || 400).json({ errors: result.errors })
|
||||
await activity.log({
|
||||
req,
|
||||
action: 'event.definition.created',
|
||||
detail: { id: result.id, title: result.definition.title },
|
||||
})
|
||||
return res.status(201).json({ event: shapeDefinition(result.definition) })
|
||||
}
|
||||
|
||||
/** PUT /api/v1/admin/events/:id */
|
||||
exports.update = async (req, res) => {
|
||||
const id = asId(req.params.id)
|
||||
if (!id) return res.status(400).json({ error: 'bad event id' })
|
||||
const result = await definitions.save(id, req.body, req.user.id)
|
||||
if (!result.ok) return res.status(result.status || 400).json({ errors: result.errors })
|
||||
await activity.log({
|
||||
req,
|
||||
action: 'event.definition.updated',
|
||||
detail: { id, title: result.definition.title },
|
||||
})
|
||||
return res.json({ event: shapeDefinition(result.definition) })
|
||||
}
|
||||
|
||||
/** POST /api/v1/admin/events/:id/publish */
|
||||
exports.publish = async (req, res) => {
|
||||
const id = asId(req.params.id)
|
||||
if (!id) return res.status(400).json({ error: 'bad event id' })
|
||||
const result = await definitions.publish(id, req.user.id)
|
||||
if (!result.ok) return res.status(result.status || 400).json({ errors: result.errors })
|
||||
await activity.log({
|
||||
req,
|
||||
action: 'event.definition.published',
|
||||
detail: { id, version: result.version, versionId: result.versionId },
|
||||
})
|
||||
return res.json({
|
||||
event: shapeDefinition(result.definition),
|
||||
version: result.version,
|
||||
versionId: result.versionId,
|
||||
})
|
||||
}
|
||||
|
||||
/** DELETE /api/v1/admin/events/:id — archive, never a hard delete */
|
||||
exports.archive = async (req, res) => {
|
||||
const id = asId(req.params.id)
|
||||
if (!id) return res.status(400).json({ error: 'bad event id' })
|
||||
const result = await definitions.archive(id, req.user.id)
|
||||
if (!result.ok) return res.status(result.status || 400).json({ errors: result.errors })
|
||||
await activity.log({ req, action: 'event.definition.archived', detail: { id } })
|
||||
return res.json({ event: shapeDefinition(result.definition) })
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/v1/admin/events/:id/runs
|
||||
*
|
||||
* Creates the occurrence. It stays `scheduled` until Phase 2's runner exists,
|
||||
* and the response says so through `pending: true` rather than by pretending
|
||||
* something started.
|
||||
*/
|
||||
exports.startRun = async (req, res) => {
|
||||
const id = asId(req.params.id)
|
||||
if (!id) return res.status(400).json({ error: 'bad event id' })
|
||||
const result = await runs.create(
|
||||
id,
|
||||
{
|
||||
scope: req.body?.scope,
|
||||
scheduledFor: req.body?.scheduledFor,
|
||||
rehearsal: Boolean(req.body?.rehearsal),
|
||||
params: req.body?.params ?? null,
|
||||
},
|
||||
req.user.id,
|
||||
)
|
||||
if (!result.ok) return res.status(result.status || 400).json({ errors: result.errors })
|
||||
if (result.created) {
|
||||
await activity.log({
|
||||
req,
|
||||
action: 'event.run.created',
|
||||
detail: {
|
||||
definitionId: id,
|
||||
runId: result.run.id,
|
||||
rehearsal: Boolean(req.body?.rehearsal),
|
||||
},
|
||||
})
|
||||
}
|
||||
return res.status(result.created ? 201 : 200).json({
|
||||
run: shapeRun(result.run),
|
||||
created: result.created,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user