|
| 1 | +// The inbound claim (#2308): one message event, one holder, one result. |
| 2 | +// |
| 3 | +// An inbound event used to be marked `seen` the moment it was handed to this host's |
| 4 | +// executor, so a second poll loop over the same server inbox — or a restart between the |
| 5 | +// delivery and the settings write — could answer it again, and a delivery that failed |
| 6 | +// after the mark left no fact behind. This module is the state machine that fixes that: |
| 7 | +// a caller takes a lease before it delivers, submits the result when the turn was handed |
| 8 | +// off, and records a failure instead of only moving the cursor. The record is plain JSON |
| 9 | +// the caller owns and persists; this module does no I/O, reads no clock (`now` is passed |
| 10 | +// in), and knows nothing about the transport, a Bot Social server or `settings`. |
| 11 | +// |
| 12 | +// The shape follows `claimQueued` / `expireLeases` in tasks.js on purpose: one holder, a |
| 13 | +// lease with an expiry, compare-and-set by lease id, and a transition that cannot run |
| 14 | +// twice. A settled record never hands out a lease again, so a late submit from a holder |
| 15 | +// whose lease expired is refused rather than rewriting a terminal result. |
| 16 | +// |
| 17 | +// pending → claimed → replied | failed | needs-human |
| 18 | +// ↑ | |
| 19 | +// └── expired (attempts + 1, or `failed` at ATTEMPTS_MAX) |
| 20 | +// |
| 21 | +// `replied`, `failed` and `needs-human` are terminal. The first slice keeps the claim on |
| 22 | +// one host: cross-host claiming (the server cursor) is the second slice, and the caller's |
| 23 | +// record is the seam it will use. |
| 24 | + |
| 25 | +import { randomUUID } from 'node:crypto' |
| 26 | + |
| 27 | +// A delivery that keeps failing stops being retried after this many attempts; the record |
| 28 | +// then says `failed`, a fact an operator can read, instead of a cursor that silently moved. |
| 29 | +export const ATTEMPTS_MAX = 3 |
| 30 | +// Long enough for a slow executor hand-off, short enough that a host that died mid-delivery |
| 31 | +// offers the event again on its next poll. |
| 32 | +export const LEASE_TTL_MS = 5 * 60 * 1000 |
| 33 | + |
| 34 | +const TERMINAL = new Set(['replied', 'failed', 'needs-human']) |
| 35 | +const ERROR_MAX = 300 |
| 36 | + |
| 37 | +const invalid = message => Object.assign(new Error(message), { code: 'inbox/invalid' }) |
| 38 | +const at = value => (Number.isFinite(value) ? value : Date.now()) |
| 39 | +const oneLine = value => String(value ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim() |
| 40 | +const bounded = (value, max = ERROR_MAX) => oneLine(value).slice(0, max) |
| 41 | + |
| 42 | +export const isTerminal = record => TERMINAL.has(record?.status) |
| 43 | + |
| 44 | +// A fresh record for one event id. `eventId` is the caller's key (Bot Social's `event_id`); |
| 45 | +// the module only requires it to be a non-empty string so `view()` and errors can name it. |
| 46 | +export function createRecord(eventId, { now = Date.now() } = {}) { |
| 47 | + const id = oneLine(eventId) |
| 48 | + if (id === '') throw invalid('a record needs an event id') |
| 49 | + const stamp = at(now) |
| 50 | + return { |
| 51 | + eventId: id, |
| 52 | + status: 'pending', |
| 53 | + attempts: 0, |
| 54 | + lease: null, |
| 55 | + resultKey: undefined, |
| 56 | + result: undefined, |
| 57 | + error: undefined, |
| 58 | + reason: undefined, |
| 59 | + settled: undefined, |
| 60 | + createdAt: stamp, |
| 61 | + updatedAt: stamp, |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +// Take the event for `holder`. The read of the lease and the write of the new one happen in |
| 66 | +// one synchronous call, so two callers over the same record cannot both see `pending`: |
| 67 | +// the first gets `claimed`, the second `held` (the caller persists the record and the next |
| 68 | +// caller reads the lease). `outcome` is one of: |
| 69 | +// claimed — the lease is yours; deliver, then submit or fail |
| 70 | +// held — a live lease belongs to someone else; do not deliver, do not move a cursor |
| 71 | +// exhausted — the attempt budget was already spent; the record is `failed` |
| 72 | +// settled — a terminal record; never deliver again |
| 73 | +export function claim(record, { holder, now = Date.now(), ttlMs = LEASE_TTL_MS } = {}) { |
| 74 | + const who = oneLine(holder) |
| 75 | + if (who === '') throw invalid('claim needs a holder') |
| 76 | + const stamp = at(now) |
| 77 | + const ttl = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : LEASE_TTL_MS |
| 78 | + if (TERMINAL.has(record.status)) return { outcome: 'settled', status: record.status, record } |
| 79 | + if (record.status === 'claimed') { |
| 80 | + const lease = record.lease |
| 81 | + if (lease !== null && typeof lease === 'object' && Number.isFinite(lease.expiresAt) && lease.expiresAt > stamp) { |
| 82 | + return { outcome: 'held', heldBy: lease.holder, until: lease.expiresAt, lease, record } |
| 83 | + } |
| 84 | + // The holder is gone or stalled: count the attempt before offering the event again. |
| 85 | + // This is the one place the count moves on expiry, so a read cannot both requeue and |
| 86 | + // hand out two leases (the shape of tasks.js `expireLeases`). |
| 87 | + retire(record, stamp, 'the lease expired before the delivery reported a result') |
| 88 | + if (record.status === 'failed') return { outcome: 'exhausted', status: record.status, record } |
| 89 | + } |
| 90 | + if ((record.attempts ?? 0) >= ATTEMPTS_MAX) { |
| 91 | + record.status = 'failed' |
| 92 | + record.error ??= 'the delivery used every attempt' |
| 93 | + record.updatedAt = stamp |
| 94 | + return { outcome: 'exhausted', status: record.status, record } |
| 95 | + } |
| 96 | + const lease = { id: randomUUID(), holder: who, takenAt: stamp, expiresAt: stamp + ttl } |
| 97 | + record.status = 'claimed' |
| 98 | + record.lease = lease |
| 99 | + record.updatedAt = stamp |
| 100 | + return { outcome: 'claimed', lease, record } |
| 101 | +} |
| 102 | + |
| 103 | +// Push a live lease's expiry out. A holder that is still working renews rather than letting |
| 104 | +// the event be offered to a second poll loop. A stale lease id, another holder or an expired |
| 105 | +// lease is refused; it never resurrects the claim. |
| 106 | +export function renew(record, { holder, leaseId, now = Date.now(), ttlMs = LEASE_TTL_MS } = {}) { |
| 107 | + const who = oneLine(holder) |
| 108 | + const stamp = at(now) |
| 109 | + const ttl = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : LEASE_TTL_MS |
| 110 | + if (record.status !== 'claimed') return { ok: false, reason: record.status === 'pending' ? 'not-claimed' : 'settled', record } |
| 111 | + const lease = record.lease |
| 112 | + if (lease === null || typeof lease !== 'object' || lease.id !== leaseId || lease.holder !== who) { |
| 113 | + return { ok: false, reason: 'stale-holder', record } |
| 114 | + } |
| 115 | + if (!Number.isFinite(lease.expiresAt) || lease.expiresAt <= stamp) return { ok: false, reason: 'expired', record } |
| 116 | + lease.expiresAt = stamp + ttl |
| 117 | + record.updatedAt = stamp |
| 118 | + return { ok: true, lease, record } |
| 119 | +} |
| 120 | + |
| 121 | +// The turn was handed off: the event is answered. The first submit wins; the same holder |
| 122 | +// submitting the same result key again is a duplicate answer, not a second write. A submit |
| 123 | +// under a lease that is no longer current is refused and leaves the record alone, so a |
| 124 | +// holder that lost its lease cannot overwrite the new holder's result. |
| 125 | +export function submit(record, { holder, leaseId, resultKey, result, now = Date.now() } = {}) { |
| 126 | + const who = oneLine(holder) |
| 127 | + const stamp = at(now) |
| 128 | + if (record.status === 'replied' && record.settled?.leaseId === leaseId && record.resultKey === resultKey) { |
| 129 | + return { ok: true, duplicate: true, record } |
| 130 | + } |
| 131 | + if (TERMINAL.has(record.status)) return { ok: false, reason: 'settled', record } |
| 132 | + if (record.status !== 'claimed') return { ok: false, reason: 'not-claimed', record } |
| 133 | + const lease = record.lease |
| 134 | + if (lease === null || typeof lease !== 'object' || lease.id !== leaseId || lease.holder !== who) { |
| 135 | + return { ok: false, reason: 'stale-holder', record } |
| 136 | + } |
| 137 | + if (!Number.isFinite(lease.expiresAt) || lease.expiresAt <= stamp) return { ok: false, reason: 'expired', record } |
| 138 | + record.status = 'replied' |
| 139 | + record.resultKey = resultKey |
| 140 | + record.result = result |
| 141 | + record.error = undefined |
| 142 | + record.settled = { leaseId: lease.id, holder: who, at: stamp } |
| 143 | + record.lease = null |
| 144 | + record.updatedAt = stamp |
| 145 | + return { ok: true, duplicate: false, record } |
| 146 | +} |
| 147 | + |
| 148 | +// The delivery failed while the lease was ours. The attempt is spent; at the budget the |
| 149 | +// record turns terminal instead of being retried forever. The holder is named in the error |
| 150 | +// only in the caller's text — the record carries the reason, not a stack. |
| 151 | +export function fail(record, { holder, leaseId, error, now = Date.now() } = {}) { |
| 152 | + const who = oneLine(holder) |
| 153 | + const stamp = at(now) |
| 154 | + if (TERMINAL.has(record.status)) return { ok: false, reason: 'settled', record } |
| 155 | + if (record.status === 'claimed') { |
| 156 | + const lease = record.lease |
| 157 | + if (lease === null || typeof lease !== 'object' || lease.id !== leaseId || lease.holder !== who) { |
| 158 | + return { ok: false, reason: 'stale-holder', record } |
| 159 | + } |
| 160 | + if (!Number.isFinite(lease.expiresAt) || lease.expiresAt <= stamp) return { ok: false, reason: 'expired', record } |
| 161 | + } |
| 162 | + record.attempts = (record.attempts ?? 0) + 1 |
| 163 | + record.lease = null |
| 164 | + record.error = bounded(error?.message ?? error) |
| 165 | + record.status = record.attempts >= ATTEMPTS_MAX ? 'failed' : 'pending' |
| 166 | + record.updatedAt = stamp |
| 167 | + return { ok: true, status: record.status, attempts: record.attempts, record } |
| 168 | +} |
| 169 | + |
| 170 | +// A person has to decide: no further attempt is spent automatically, and the reason is kept |
| 171 | +// for the surface that reads it. Terminal, like `failed`. |
| 172 | +export function needsHuman(record, { reason, now = Date.now() } = {}) { |
| 173 | + const stamp = at(now) |
| 174 | + if (TERMINAL.has(record.status)) return { ok: false, reason: 'settled', record } |
| 175 | + record.reason = bounded(reason) |
| 176 | + record.error = undefined |
| 177 | + record.lease = null |
| 178 | + record.status = 'needs-human' |
| 179 | + record.updatedAt = stamp |
| 180 | + return { ok: true, record } |
| 181 | +} |
| 182 | + |
| 183 | +// A poll that finds a lease past its expiry offers the event again (or ends it at the budget). |
| 184 | +// Idempotent: a second call at the same time sees `pending`, not a second attempt. |
| 185 | +export function expire(record, { now = Date.now() } = {}) { |
| 186 | + const stamp = at(now) |
| 187 | + if (record.status !== 'claimed') return { expired: false, record } |
| 188 | + const lease = record.lease |
| 189 | + if (lease !== null && typeof lease === 'object' && Number.isFinite(lease.expiresAt) && lease.expiresAt > stamp) { |
| 190 | + return { expired: false, record } |
| 191 | + } |
| 192 | + retire(record, stamp, 'the lease expired before the delivery reported a result') |
| 193 | + return { expired: true, status: record.status, attempts: record.attempts, record } |
| 194 | +} |
| 195 | + |
| 196 | +// The read-only shape a surface (or a test) gets: no lease ids to guess with, the holder and |
| 197 | +// the deadline named, and the terminal facts (`resultKey`, `result`, `error`, `reason`). |
| 198 | +export function view(record, { now = Date.now() } = {}) { |
| 199 | + if (record === undefined || record === null) return undefined |
| 200 | + const stamp = at(now) |
| 201 | + const lease = record.lease !== null && typeof record.lease === 'object' ? record.lease : undefined |
| 202 | + const live = lease !== undefined && Number.isFinite(lease.expiresAt) && lease.expiresAt > stamp |
| 203 | + return { |
| 204 | + id: record.eventId, |
| 205 | + status: record.status, |
| 206 | + attempts: record.attempts ?? 0, |
| 207 | + ...(live ? { heldBy: lease.holder, until: lease.expiresAt } : {}), |
| 208 | + ...(record.resultKey === undefined ? {} : { resultKey: record.resultKey }), |
| 209 | + ...(record.result === undefined ? {} : { result: record.result }), |
| 210 | + ...(record.error === undefined ? {} : { error: record.error }), |
| 211 | + ...(record.reason === undefined ? {} : { reason: record.reason }), |
| 212 | + ...(record.settled === undefined ? {} : { settled: record.settled }), |
| 213 | + updatedAt: record.updatedAt, |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +// One attempt spent on an expiry: clear the lease, count it, and end the record at the budget. |
| 218 | +function retire(record, stamp, why) { |
| 219 | + record.lease = null |
| 220 | + record.attempts = (record.attempts ?? 0) + 1 |
| 221 | + record.error = record.error ?? bounded(why) |
| 222 | + record.status = record.attempts >= ATTEMPTS_MAX ? 'failed' : 'pending' |
| 223 | + record.updatedAt = stamp |
| 224 | +} |
0 commit comments