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:
134
server/src/model/events/eventRuns.model.js
Normal file
134
server/src/model/events/eventRuns.model.js
Normal 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 }
|
||||
Reference in New Issue
Block a user