@rackbops/docket-core
v0.32.0
Published
Tracker core: people, tasks, occurrences, schedules, the two lanes, the task-type contract and the ports. No platform code.
Readme
@rackbops/docket-core
The tracker's domain, scheduler, two lanes, task-type contract and ports, with no platform code:
no Hono, no discord.js, no sqlite, no fetch. A host -- the tracker plugin in
Rackbops/rackbops-bot-plugins (plugins/tracker) -- supplies the adapters behind the ports and
gets a tracker; Rackbops/city-hall (upstream: Lepid-Labs/city-hall) only queues and runs its
model Jobs. Design:
Rackbops/Tooling, research/city-hall-task-tracker.md, section 5 (plan rev17).
| Module | What it holds |
|---|---|
| model | the records: users, tasks (config and type state), occurrences, events, task history, recipients, blocks, replies, series, findings, usage |
| ports | Store, Clock, Identity, Notifier, Executor, Fetch, the Store's input shapes, and the errors a Notifier or Executor throws (DeliveryFailedError, ExecutorUnavailableError, JobPendingError) |
| memory-store, store-contract | the Store in memory: the reference semantics and the test fake; STORE_CONTRACT, those semantics as cases a host runs against its own Store |
| schedule, zoned | once, calendar, poll and period schedules, nextDue, periodDate, zone-aware wall-clock arithmetic on Intl alone |
| scheduler, dedupe, tasks | one upcoming occurrence per task through its dedupe key; cancel-and-replace on edit, keeping a snooze's run and a follow-up; createTask |
| dispatch, delivery | the notify and execute lanes (an active task's runs only; tickNotify takes an AbortSignal), DM delivery claimed in the Store before each send, per-recipient outcomes and retries, crash recovery, replies and snooze; a type's outcome recorded, then applied (state stored, series and findings appended, complete ends the task, followUp queues one more run), then delivered, so a failed send is retried without running the type again; a Job the runner has not finished is asked about again each tick, charged once |
| authz, consent | every read takes an identity, the series and findings included; invitations, accept, the decline rule, opt-out, admin lifts |
| when, describe, messages, refs | what the bot says and hears: a person's "when" (parseWhen), cadences and instants in words, the consent DM, the registration disclosure, the /tasks list, and buttons whose reply references route a press back as a reply (replyButtons, replyForRef): a run's done, snooze and decision are the owner's, once per fired run while the task is active (when the host handles a task's replies one at a time), enforced in Lanes.reply on every path; a recipient's copy carries the opt-out and no run actions |
| text | clean: a person's or a model's text made safe for a DM (no mention pings, no masked link, no control characters, capped); the types package re-exports it |
| job-state | where an execute-lane run's Job stands, from its events: its key, whether it is out, PENDING_LIMIT_MS |
| budget | daily ceilings for model runs (plan 5.7, 5.12): DEFAULT_BUDGET (2 USD and 20 calls a person, 10 USD and 100 calls in all), days from midnight Eastern, charge, budgetHold, and the one-time notices; the execute lane charges each run to its owner, holds a person at a ceiling until midnight, stops at the global one, and backs off after a usage limit without charging anyone |
| gift-model, gift-ports, gift-validate, gift-ledger, gift-memory-store, gift-store-contract, gift-rules, gift-groups | the gift organizer's ledger (plan item 158, epic #94), beside the task types and off the scheduler: recipients (a person or a household, never a tracker user), groups, occasions, roster rows, items, purchase lines and allocations, each with a revision and an archived flag, and one change event per write; money in integer minor units with its currency. GiftStore is its own port, so a host without gifts implements nothing new: owner-scoped reads (another owner's row reads as missing), revision-checked updates, idempotency keys, one roster row per occasion and recipient, forgetOwner. GiftLedger is the one write path: it validates every field (an unknown one is refused, not dropped) and refuses an id that is not the same owner's record of the right kind. MemoryGiftStore is the reference; GIFT_STORE_CONTRACT the cases a host runs against its own store. gift-rules derives coverage, allocation fills and per-currency spend from the records; gift-groups previews rosters from groups and reviewed syncs |
| contract, capabilities, job | TaskType, defineTaskType, the grantable capability enum (tier 0 and tier 1 only; tier 2 has no name here), the JobSpec and JobResult a runner speaks |
import { createTask, Lanes, MemoryStore } from "@rackbops/docket-core"
import { TASK_TYPES } from "@rackbops/docket-types"
const store = new MemoryStore()
const lanes = new Lanes({ store, clock: { now: () => new Date() }, types: TASK_TYPES, notifier })
await lanes.recover()
setInterval(() => lanes.tickNotify(AbortSignal.timeout(30_000)), 60_000)A host replaces MemoryStore with its own Store (and proves it by running STORE_CONTRACT
against it), supplies a Notifier that DMs a user, a Fetch
for the plain-code types (the price tracker reads pages through it, via RunContext.ports), and an
Executor that hands Jobs to the runner. The core never calls a model and holds no credential:
every model call runs in the runner, through the Claude Code CLI on roshne's subscription, never an
API key.
Adopting the gift ledger (0.24.0)
Nothing changes for a host that offers no gifts: Store is untouched. A host that does implements
GiftStore with its own storage, runs every GIFT_STORE_CONTRACT case against a fresh one, and
writes only through GiftLedger. Its check-and-write for a revision, an idempotency key and the
roster pair must be one atomic step (one SQLite transaction), which the contract's at-once cases
test. It also implements replay, which the ledger asks first, so a retried write gets its first
result even after the records moved on; store giftRequestKey(request) beside each key, so a
retry whose JSON keys arrive in another order still matches. Lists come back in the order rows were
written, not sorted by createdAt. Archiving hides a record from lists but never breaks a link
to it, so an archived record stays a valid reference; an archived roster row still holds its place
on the occasion, and the owner restores it rather than adding the recipient again.
The ledger's reference checks read before the store writes and are not atomic with it: two writes racing on the same records can both pass them. A host that needs that closed serializes one owner's writes.
gift-rules derives the views from records read back. Pass it every allocation and purchase of
the owner, archived or not, in creation order (a subset moves units between gifts that share a
purchase). giftBuckets fills each live purchase's kept units (ordered, less cancelled and
returned) into its live allocations in that order, so a return or cancellation reopens only the
gift filled last. giftCoverage gives each roster row its status (needs planning, planned,
awaiting, purchased, ready, given, skipped) and whether it is done: the owner's "shopping
complete" call, a skip, a target of 0, or a met target; with no target, a purchase alone never
marks someone done. giftSpend keeps planned, spent, pending refunds, refunded and net apart, one
row per currency; cancelled units were never charged and are out of the total, so a refund
(for returns or a price adjustment) is never recorded for a cancellation, and never exceeds the
line's total. purchaseShares splits a line's total over its units so the parts
sum to it exactly. The ledger refuses a write that would make an allocation hold more units than
its purchase keeps, but a later return or cancellation never locks the gifts already on it.
gift-groups builds rosters. An occasion names its groups (groupIds) and hand overrides
(includeIds, excludeIds); previewRoster lists each person once, with the groups they came
from and the overrides shown. The roster rows are the snapshot: editing a group (editGroupMembers,
then GiftLedger.update) changes no occasion until the owner reviews a sync. previewGroupSync
shows who would be added (a restored row brings its budget back) and removed, with their coverage,
the budget change, and every live gift on the occasion naming someone off the roster, whether their
row goes now or went earlier, so a gift kept on someone off the roster is asked about at every sync.
The roster is the groups plus overrides: a row added by hand without includeIds is offered for
removal. A group is a static list or, with filter: {labels}, a saved rule (docket#98): its members
are the owner's live recipients carrying every one of those labels (trimmed, spaced once and case-folded; a relationship or an
age band is just a label the owner typed, such as cousin or adult), only
labels the owner typed, so a blank or missing label never matches. groupMembers and
resolveGroups resolve one; previewRoster refuses a filter group passed unresolved, and
previewGroupSync takes the owner's recipients to resolve them. A group made before docket#98
has no filter key and reads as a static list. planGroupSync refuses until each such gift has a keep, reassign (to people on the
roster) or unassign decision, and refuses decisions for other gifts. GiftLedger.applyGiftSync
refuses the whole plan if the occasion was archived, it or a group moved since the preview, or a
filter group's matches moved (the roster is resolved again and compared), then
writes the gift changes first and the roster rows after; it is not atomic (a refused write leaves
the earlier ones, and the owner previews again). Retry a plan with the same plan and key: write n
uses <key>/n, so a retry replays what was written; a new preview needs a new key. An archived
occasion is never synced. A static
group's membership is a list of ids and no label decides it; a filter group's is its labels.
gift-rollover sets up next year (docket#99). previewGiftRollover shows the new occasion (its
title's year moved on, its date a year later, 29 February becoming the 28th, or a date and title the
owner gives, its year, if it has one, taken from that date), its roster -- the groups re-resolved
against today's membership and labels, plus the overrides, with each staying person's target and
budget, and who is left off -- and only the ideas the owner picks: unbought, not handed off, for the
people still on. It never carries a purchase or a received, wrapped, ready or given state, and every
person's decision starts again at planning (a carried target of 0 still reads as skipped). Nothing
is written until GiftLedger.applyGiftRollover, which previews again from the store and, before
writing, refuses one whose writes would now differ or whose picked item was archived or rejected,
and refuses an unkeyed repeat of an occasion already made (another live one of the same kind, title,
year and date); the old occasion is never written, archived or not.
gift-duplicates warns before a repeat gift (docket#100). GiftLedger.giftDuplicates (pure:
findGiftDuplicates) reports, for an allocation about to be written, the same product -- the same
item, or the same normalized product key, else the same normalized http or https URL, with the same
variant -- already allocated to one of the same people (a household matching each of its members) on
another live occasion, unless that item was archived or rejected, or in their history (given to
them, or bought for them on an archived occasion with units still kept), as warnings; and the same
product in another variant, the same page (another query, or another product key), or the same title
as possible duplicates only. No warning refuses a write: the owner may accept one, and the
allocation then records the warned ids in its optional repeatOf, which must name the owner's other
allocations. A rollover's carried idea names its source there. Only allocations count, so a watch or
scout having seen a listing is never taken as ownership.
gift-scout joins gifts to the scout (docket#101). GiftLedger.saveFindingAsIdea (pure:
giftIdeaFromFinding) makes one of the owner's findings, of any task type, a new item in the idea
state, linked back by source: { kind: "scout", ref: "<taskId>/<findingId>" }; it is never
selected, bought or allocated, so it covers nobody, and its text is kept only as notes, cleaned.
Another owner's finding is refused, and so is an unkeyed second save of one finding. A finding that
carries eBay data (tagged ebay, or naming an eBay address in its source or text) copies nothing of
the listing, as the eBay watch keeps none: the owner names the gift. An item's optional
watchTaskIds links the owner's price or want-list watches; the gift store cannot see tasks, so set
it with GiftLedger.linkGiftWatches, which checks them (giftWatchProblems). Nothing in the gift
ledger reads or writes a task, so linking, buying or archiving a gift never changes a watch.
giftScoutBrief gives a scout run for a gift only the interests and avoidances the owner picks; no
such run exists yet.
gift-import brings in a list of gifts after review (docket#102). parseGiftImport stages CSV (a
header row; quoted fields, doubled quotes and line breaks inside quotes; a column it does not know
is listed in unknownColumns; a quote that never closes refuses the input) or a pasted list (one
gift a line, | or tab between title, recipients, occasion, quantity, price, link), at most 500
rows, each with its source, line and a key made from its content. A row missing a title, or with a
bad quantity, price (a comma only groups thousands), currency or link, is staged with its problems.
reviewGiftImport matches each row's people and occasion to the owner's live records by name,
case-folded, and marks it ready, new, ambiguous or invalid; both are pure, so nothing is
written before the owner has seen the review, which shows the staged unknownColumns and problems
too. GiftLedger.applyGiftImport writes the approved rows and answers each with its own outcome
(not atomic): it reviews again first and skips an ambiguous or invalid row, or one whose match
moved; it creates a named-only person or a custom occasion for a new name, an item (an idea, or
selected when allocated; the price an estimate, never spend; source import), and, for a row
naming people and an occasion, one unbought gift (one allocation, shared false) giving each of
them the row's quantity, adding them to the roster unless they were taken off it (a row with people
but no occasion makes only its item, and says so). Every write is keyed by the row's content, so
importing the same rows again creates nothing twice; a person or occasion an earlier import made
that has since been archived or renamed, or an imported item (gift idea) the owner archived, stops
the row instead.
gift-digest sends an opt-in gift digest (docket#103). An occasion may carry a shop-by day
(deadline, on or before its date) and the owner's opt-in (digest); both may be left out, as on
occasions from before. decideGiftDigest is pure: from the occasion, its roster, giftBuckets and
the owner's zone and preferred hour, it says whether a digest is due and its text -- who still needs
a gift (not done, and short of their target in gifts bought) and how many gifts are awaiting
arrival, with the days left. It is due at most once a local day, at or after the preferred hour,
only when there is something to say and it changed since the last digest or the shop-by day (or the
date, when there is no shop-by day) is 0 to 3 days away; never without the opt-in, and never after
the date. The text names people and counts only: no price, note or item title. The host stores any
returned state for the next call and claims giftDigestKey(occasionId, day) once before sending;
it runs on the notify lane, with no model call. A rollover carries the digest choice and moves the
shop-by day with the date. Days are counted in the owner's zone.
Adopting 0.18.0
Run now (rackbops-bot-plugins#369). runNowKey(taskId, requestId) keys a run its owner asked for
now: now:<task>:<request>, one per request, so a retried request queues one run. The host creates
it as an ordinary occurrence due now; isOffSchedule is true for it, as for a snooze's run and a
follow-up, so the schedule's next run stays where it was (materialize) and a schedule edit keeps it
(cancelScheduledRuns). Its message goes to the owner and every accepted recipient, as a scheduled
run's does. Nothing else changes, and no Store change is needed. requestId is 1 to 64 letters,
digits, - or _; anything else throws. The host decides which tasks may run now and how often,
and refuses: a one-off (its scheduled run stays queued, so a reminder would go twice and a research
request end early); a renewal (its ask takes its period from the run's dueAt); a paused or ended
task (the run would wait for a resume, or never fire).
Adopting 0.16.0
The fixes for roshne's 2026-10-23 audit (#73, #74, #75) tighten three Store rules and add two calls a
host should make. Run STORE_CONTRACT against the Store: each rule below is a case there, and a
store that skips one fails it.
Store
settleDelivery(o, u, settle, expected?)withexpectedwrites only while the row's status isexpected(UPDATE ... WHERE status = ?) and otherwise changes nothing, returning the row as it stands; a missing row still throws (#47).deleteOccurrence(id, guard?)with aguarddeletes only while the run isqueued, has no record, and has no event afterguard.lastEventId(none at all when it is null); an event id it cannot find refuses too (#55).listSeriesbreaks equal timestamps by insertion order, and alimitbelow 1 returns no points (#48).
Calls
- Pass the task's type as
reschedule's seventh argument, so an edit is checked against the schedule kinds the type takes, ascreateTaskchecks a new task (#50). - Call docket-types'
patternProblemwhen a price watch with a pattern is saved, so the owner hears at once rather than on the third miss (#45).
Removed (#75; unused by the tracker): manualKey and deliveredTo from docket-core, and
listingsFromJsonLd from docket-types.
Adopting 0.5.0
0.5.0 adds what the research type (docket-types, plan 1.2 row 5) needs: a follow-up run, stored
findings, and a Job the runner has not finished yet. A host's Store gains three methods and a
usage column, and its Executor takes a third argument. Run STORE_CONTRACT against the Store:
three new cases cover the changes.
Store
- A
findingstable:id,task_id,owner_id,occurrence_id(nullable),key(nullable, unique when set),type,text,tags(a JSON array of strings),source(nullable),at. Indexfindings(task_id)andfindings(owner_id): one serves the task view, the other forget-me.addFinding(finding)inserts one row. With akeyalready stored it adds nothing and returns the stored row (INSERT ... ON CONFLICT(key) DO NOTHING, then select), exactly likeaddSeriesPoint. The dispatcher keys a finding in one of three ways:<task>:<key>when the type gave a key (a deterministic id, for dedupe and do-not-resurface, plan 5.2);<occurrence>:<index>for a run's other findings;reply:<reply id>:<index>for findings fromonReply.
listFindings({ taskId?, ownerId?, since? })returns rows oldest first byat, ties in insertion order (ORDER BY at, rowid).sinceis inclusive.deleteFindings(ownerId)deletes every finding of the tasks that person owns and returns how many. Forget-me calls it besidedeleteDeliveriesand theusagedelete. A host that erases inside a synchronous transaction runsDELETE FROM findings WHERE owner_id = ?there instead.
usagegains a nullablekeycolumn, unique when set. With a key already stored,addUsageadds nothing and returns the stored row. The execute lane keys each charge by its Job key, so a crash between a charge and its run's record never charges one call twice.- No new occurrence column. A follow-up is an ordinary occurrence whose
dedupeKeyisfollowup:<occurrence>. A run's Job state (its key, whether it is out) is read from its ownstatusevents (job-state.ts), which the host stores already. - Each execute tick reads the events of every due execute-lane run (
hasJobOut), andreschedulereads them for the task's queued runs. That is cheap at the tracker's size, but indexevents(occurrence_id)if the host has not already.
Executor
run(spec, occurrenceId, jobKey)takes a third argument, andspecmay be null. Submit underjobKey, not the occurrence id. It is the occurrence id for a run's first Job and<occurrence id>:<n>after the n-th usage limit, because city-hall answers a known key with that Job's result, and a usage limit's result would otherwise come back for good.runneed not wait for the runner. Submit withPOST /api/execute/jobsandkey = jobKey. While the Job is notdoneorfailed, throwJobPendingError. Then:- The run goes back to the queue, unstarted and uncharged.
- Nothing new is submitted while a Job is out. Each execute tick first asks about every run
whose Job is out, under the same key: resubmit the same key, or
GET /api/execute/jobs/:id. So Jobs really go one at a time (plan 5.3), and the budget check never misses a call in flight. - The run skips the budget check while its Job is out: its call is already made, and holding it would only delay collecting it.
- It writes one
submittedevent for the whole wait, and is charged once, when the result comes back. prepareis not called again. Every later ask passesspec = null: answer the Job already out underjobKey, and never submit anything new. So keep what you need to find it by key (city-hall's job id from the first POST, say) in the plugin's own store. That way apreparethat would now decide differently (edited config, a passed deadline) cannot fire the run without collecting the Job.- Any other error on a Job already out (an HTTP 500, say) is treated like pending: same key, no new Job, up to the same limit. The first Job may still run, so it is never resubmitted under a new key.
- An adapter asked with
spec = nullthat has no record forjobKey(its store lost the city-hall job id, say) should throw: the run is then held like a pending one for up toPENDING_LIMIT_MS, given up and charged one call. So persist the city-hall job id before returning from the first ask. - While a Job out keeps failing, the run writes one
waiting: ...event per distinct reason, not one per tick.
- The wait is bounded, and the lane is held for every owner meanwhile.
- A Job pending past
SLOW_JOB_MS(1 hour, inferred) is reported to the admins once, with oneerrorevent on the run. - A Job still answering pending (or failing)
PENDING_LIMIT_MS(6 hours, inferred) after its submission is given up. The run writes oneerrorevent, and the type'sfinishgets{ kind: "error", detail: "the job did not finish in time" }. That result is charged as one call, since the Job may have run. The lane then moves on. - A Job is given up only on an answer, never during
ExecutorUnavailableError. So a Job that finished while city-hall was unreachable is collected when city-hall is back.
- A Job pending past
- "One Job at a time" holds from the tracker's side. A Job it gave up on may still be running at the runner, and nothing cancels it there.
- A run whose Job is out is never deleted.
rescheduleand a task completing keep it.reschedulereturnsjobOut: trueso the host can tell the owner the run in flight still counts. For aonceschedule, old or new, it throwsScheduleErrorinstead: that run is the task, and the edit would run it twice. It is collected and charged even if its task was paused, completed or archived meanwhile.- For a paused task, the outcome is applied and its sends wait for the resume, as for any fired run.
- For a done or archived task, the outcome is dropped (no DM, no findings, no follow-up) and the charge stays.
ExecutorUnavailableErrorstill means nothing could be asked (city-hall unreachable, no runner). The run is requeued; a Job already out is asked about under its key next time. Any other error from a first submission is not retried by the core. It becomes an uncharged{ kind: "error" }result for the type'sfinish. So throwExecutorUnavailableErrorfor a transport failure that may pass.- A Store error while a pending run goes back to the queue leaves it
running. The next sweep puts it back afterSTALE_RUN_MS, because its Job is on record. A crash between the result and the record re-asks the same key, which gives the same result with no second model call, and the keyed charge is not counted twice.
Types and lanes
A fired run whose outcome completes a paused task does not complete it while it is paused: that would make the task done and send at once, through the pause. The run waits, applied. The first notify tick after the resume completes the task and sends the message. A task archived meanwhile is never turned to done.
"Done" means the same on both paths. A task set done or archived while that completion waits drops its message, as a Job collected after the task ended does: no DM, its sends are dropped, and the findings and the charge already stored stay.
An execute-lane type's
finishalways runs once its run starts. Apreparethat throws, or an Executor that throws (other than pending, unavailable or a usage limit), becomes an unchargederrorresult. So a type can always retry or tell its owner, and aoncetask is never stranded silently.preparemay return{ outcome }instead of a JobSpec when no call is needed (a research request past its deadline). That is the run's outcome: nothing is submitted or charged.Outcome.followUp: { at? }asks for one more run of the same task:- It is due at
at, or when the asking run fired. - It is queued only after the outcome is applied, so it runs on the state that outcome wrote.
- It is off the schedule (
isOffSchedule): materialization never counts it as the next scheduled run, andreschedulenever cancels it. - It waits until the asking run has finished (
isFinishing), and on the execute lane it is budget-checked, charged and limited like any model run. - It is ignored together with
completeand fromonReply. - Past
MAX_FOLLOW_UPS(5; 9 from 0.9.0) in a row the run writes an error event, the task completes, and the owner and admins are told once. A snooze's run in a chain starts a new count.
- It is due at
Outcome.findingsare stored when the outcome is applied, each with the task's owner and type.Finding.keyis optional.visibleFindings(store, actor, taskId, { since? })serves them to the owner, accepted recipients and admins (the series' rule), and returns null for anyone else.visibleTaskandvisibleTasksnow give a recipient the task withoutconfigandstate. Those are the owner's: a research request's draft, including a rejected or unreviewed one, lives instate(ResearchState.draft). Only the owner and admins read it. A host view that showed a recipient a task's config reads it from what the recipient was sent instead.
The research type, in the plugin
- Add
researchto the types the plugin loads (TASK_TYPEShas it) and allow it withnotify.notifyis its only capability, tier 0, so no admin grant is needed;createTaskgives it. - The intake's optional
atbecomes the schedule{ kind: "once", at: at ?? now }. Its optionaldeadlinegoes intoconfig.deadlineas an ISO instant. - Send its DMs with no allowed mentions (
allowed_mentions: { parse: [] }). The type already breaks every mention, masked link and mention-spelling URL in model text, but the Notifier is the last line. - The rejection DM quotes the reviewer's problems, model-written text cleaned and capped like the rest. Every research DM stays at or under 1900 characters.
Adopting 0.4.0
0.4.0 (#18) changes what a host implements. Run
STORE_CONTRACT against the host's Store after each step; every rule below is a case there.
Store
findUserBySubjectis gone, withUser.usrSubject: people live in the host's own store.deleteQueuedOccurrencesis gone too. (Outside the Store:Identity.actorForSubjectand theMemoryport are gone.)deleteOccurrence(id)deletes one row, only while it isqueued, and says whether it did.reschedulecancels through it one row at a time, keeping a snooze's run and any run that has fired.updateOccurrenceIf(id, expected, patch)is a compare-and-set on status: it patches only while the row's status isexpectedand returns null otherwise. It must be atomic (one SQLUPDATE ... WHERE id = ? AND status = ?); the lanes start every run through it.Occurrence.recordis a new nullable JSON column (OccurrencePatch.recordwrites it). A run has fired once its record is stored, whatever its status;startedAtno longer means that.requeueRunningmust setstartedAtback to null, and keeprecord.SeriesPoint.keyis a new nullable, unique-when-set column:addSeriesPointwith a key already stored adds nothing and returns the stored point, so a run applied again never appends twice.- A
deliveriestable, keyed by (occurrenceId,userId), withstatus(pending,claimed,sent,deferred,failed,unconfirmed),messageId,error,attempts,deferrals,retryAt,createdAt,claimedAtandsettledAt. A row is owed whileretryAtis set.planDeliveryinserts apendingrow owed fromat; a no-op returning null when the row exists.claimDeliverytakes an owed row:claimed,claimedAt=at,retryAtnull. Null when the row is missing or not owed. Atomic: two callers never both win (UPDATE ... WHERE retryAt IS NOT NULL).settleDeliverywrites every field ofDeliverySettle, so an absentmessageIdorerrorclears it.listDeliveriesfilters by run, person, status, anddueBefore(owed rows withretryAtat or before it), oldest first.deleteDeliveries(userId)erases a person's rows: forget-me must call it.
UsageSourceis"run"only: there are no recall charges.- The budgets (#17, first released in 0.4.0) add
listUsers,addUsage,listUsageandclaimNotice; a 0.3.0 host needs all four, with theusageand notice rows behind them. - Forget-me erases more than
deleteDeliveries: the person'susagerows and theirbudget:person:<id>:*notices name them too.deleteDeliveriesis async, so a host that erases inside a synchronous database transaction runs the same delete there instead.
Notifier
- It keeps no claim table of its own:
deliverclaims each send in the Store first. - How a send fails decides what happens next, so map Discord's errors carefully:
DeliveryFailedError(message, true)-- the person cannot be messaged at all (DMs closed, left the server, bot blocked): failed for good at once;DeliveryFailedError(message)-- nothing went out this time: retried after 1 minute, then after 2 more, three sends in all;ExecutorUnavailableError-- not now, nothing went out: deferred, no attempt counted, retried after 1, 2, 4 ... minutes (doubling, capped at an hour), eight times in all;- any other error -- it may have gone out:
unconfirmed, never resent.
- A claim left open past
STALE_CLAIM_MS(10 min), or found byrecover()at start, settles asunconfirmed. A fired run leftrunningpastSTALE_RUN_MS(10 min) goes back to be resumed.
Lanes and replies
- Call
recover()once at start. Owed sends go out ontickNotify, nevertickExecute. - A paused task's runs do not start, and its owed sends wait; a run that fired before the pause is still applied, and its sends wait too. Each pause gives its owed rows a fresh round, so pause and resume buy three more sends; that is intended.
- A run is answered once it has finished (
done, orfailed), whatever it still owes anyone; a fired run still finishing (isFinishing) is refused with "still finishing". A host lookup that finds "the latest run" to route a reply to must include runs that still owe a delivery, not only those whose copies all went out. - Serialize per task: a task's replies, its edits (
reschedule) and its runs one at a time. The core guards a run's start and a snooze by compare-and-set, but a schedule edit racing a firing run can leave a run of the old schedule beside the new one.tickNotifywalks every task, so a host either holds one lock around the whole tick and its edits, or (as the tracker plugin does) runs one tick per task with work, under that task's lock, through a Store view that narrows the occurrence and delivery lists to that task and leaves users, usage and notices whole. - The core checks the abort signal between runs; a type whose fetch throws on abort is the host's
to stop, by passing the signal to its
Fetchport. visibleOccurrenceshidesrecordfrom anyone but the owner and admins;visibleDeliveries,visibleRepliesandvisibleHistoryshow a recipient only their own rows, so no recipient learns who else receives a task. A host writingrecipient_*,blockedorblock_liftedhistory startsdetailwith the recipient's id.registrationText(user, { first, notes? })no longer takes or shows a usr link.
