Bounded outbox delivery
Run one bounded delivery pass with explicit sink outcomes and fenced settlement.
A delivery worker claims one batch of committed protected-write events and invokes a sink you
supply. It runs once and returns; it starts no daemon, scheduler or network service. The sink runs
after the claim has released its database transaction and connection. Delivery is at least once:
the sink must deduplicate effects by (environmentId, eventId), including after cancellation or an
uncertain acknowledgement.
Use createPostgresProtectedWriteDeliveryWorker or createSqliteProtectedWriteDeliveryWorker
with the same executor, journal prefix and environment as the protected-write adapter. Apply its
explicit protected-write migrations first, including operator history. Authenticate and authorize
worker/operator access in your application. The optional { type, id } operator is copied at
construction as application-attested attribution; omitting it records null, never an invented actor.
Explicit sink policy
import { createPostgresProtectedWriteDeliveryWorker, type ParameterizedSqlExecutor } from "@rolebook/sharing-postgres";
import type { OutboxDeliveryEvent } from "@rolebook/sharing";
declare const executor: ParameterizedSqlExecutor;
// Your sink implements deduplication and decides whether an outcome is known.
declare function send(event: OutboxDeliveryEvent, signal: AbortSignal): Promise<"accepted" | "try-later" | "rejected" | "unknown">;
const worker = createPostgresProtectedWriteDeliveryWorker({
executor,
tablePrefix: "app_authorization",
environmentId: "production",
operator: { type: "service", id: "audit-delivery" },
batchSize: 8,
leaseMs: 30_000,
deliveryTimeoutMs: 10_000,
async deliver(event, { signal }) {
const outcome = await send(event, signal);
if (outcome === "accepted") return { status: "delivered" };
if (outcome === "try-later") return { status: "retry", delayMs: 5_000 };
if (outcome === "rejected") return { status: "quarantine", reason: "sink-rejected-event" };
return { status: "unresolved" };
},
});
const report = await worker.runOnce(); The worker never guesses retry/quarantine policy. A thrown sink exception, malformed result or
explicit unresolved result causes no ACK, retry or quarantine. You may catch a sink error inside
deliver and explicitly classify it if your application can establish the appropriate outcome.
Only delivered permits ACK. A successful quarantine writes the existing durable operator history;
ordinary ACK and retry do not fabricate operator-action records. No payload or receipt is rewritten.
For local SQLite, the facade and contract are the same on Bun SQLite and local libSQL:
import { createSqliteProtectedWriteDeliveryWorker, type ParameterizedSqliteExecutor } from "@rolebook/sharing-sqlite";
import type { OutboxDeliverySink } from "@rolebook/sharing";
declare const executor: ParameterizedSqliteExecutor;
declare const deliver: OutboxDeliverySink;
const worker = createSqliteProtectedWriteDeliveryWorker({
executor, tablePrefix: "app_authorization", environmentId: "production",
batchSize: 4, leaseMs: 30_000, deliveryTimeoutMs: 10_000, deliver,
});
const cancellation = new AbortController();
const report = await worker.runOnce({ signal: cancellation.signal }); Bounds and outcomes
batchSize is an integer 1–32, leaseMs is 1–300000, and deliveryTimeoutMs is 1–leaseMs.
All options and callback/port function references are captured at construction. Each pass makes
one claim call, admits at most batchSize concurrent sink calls, and returns outcomes in claim
order. There is no refill, prefetch or lease renewal. Retry delay is an integer 0–300000; quarantine
reason is a nonblank string of at most 1024 characters without NUL. Results must be plain data.
Sink calls are concurrent; database settlements are serialized within the pass to avoid the
worker’s own SQLite transactions contending. Queue time contributes to lease age. Every settlement
uses the original exact lease token once. A stale/expired token reports stale; no automatic retry
follows a database failure. Separate worker instances need an application-wide concurrency policy.
The frozen report contains stopped and bounded outcomes. Each outcome includes environment,
event ID and original generation, plus acknowledged, retried, quarantined, stale, or
unresolved. Unresolved reasons distinguish sink-error, invalid-result, sink-unresolved,
aborted, timeout and settlement-error. Reports contain no raw exceptions or payloads, and the
worker logs nothing. Claim failure throws a generic reconciliation error: leases may have committed
before the response failed. An ambiguous ACK likewise reports uncertainty even if storage committed.
Do not infer either delivery or rollback from missing evidence.
Cancellation and late effects
Pass an AbortSignal to runOnce. A pre-aborted call claims nothing. Abort during claim waits for
the database call to finish, then starts no sinks. During delivery, abort or a callback timeout
signals cooperative cancellation and prevents new sink starts and future queued settlements.
An already-submitted database settlement is still observed and reported; cancellation does not
undo it. Database operations remain subject to the executor’s own limits, not the sink timeout.
The pass can return while an uncooperative sink still runs. Late fulfillment/rejection is observed, but cannot cause a later settlement. The same worker remains busy until every started sink and submitted settlement actually finishes, and rejects overlapping runs before claiming. A permanently unsettled sink leaves that worker busy permanently. The helper cannot forcibly cancel an external effect. Unreconciled claims can become replayable after lease expiry; sink deduplication is essential.
Worker diagnostics
Every delivery worker, from createOutboxDeliveryWorker or either SQL facade, has diagnostics(), a frozen snapshot of
that worker instance: whether it is idle, running or draining (a returned pass left a sink
running, so new runs are refused), how its last run ended, cumulative counts per outcome and
unresolved reason, and the state of an optional observer. It is local evidence, not backlog,
database, sink or global production health, and it contains no identifiers or text.
import { createOutboxDeliveryWorker, type OutboxDeliveryPort, type OutboxDeliverySink } from "@rolebook/sharing";
declare const outbox: OutboxDeliveryPort;
declare const deliver: OutboxDeliverySink;
declare const metrics: { count(name: string, value: number): void };
const worker = createOutboxDeliveryWorker({
outbox, deliver, batchSize: 8, leaseMs: 30_000, deliveryTimeoutMs: 10_000,
diagnostics: {
// Enums and counts only; called after the run, one call at a time.
observe(run) {
metrics.count(`outbox.run.${run.result}`, 1);
metrics.count("outbox.unresolved", run.unresolved);
},
queueLimit: 64,
observerTimeoutMs: 1_000,
},
});
await worker.runOnce();
const { worker: state, delivery, observation } = worker.diagnostics(); The observer receives only the observation and is called as a plain function, so bind a class
method yourself. It never runs inside runOnce, and its return value does not control a run’s
outcome, admission or settlement; runOnce resolves and rejects exactly as it would without
diagnostics. A throw, a rejection or a call that outlives observerTimeoutMs is counted; a
synchronous call that overruns is counted once when it returns, because no timer can fire during it. The timeout only reports: there is no cancellation signal, and a
timed-out call keeps the single observer slot until it settles, while new observations wait in a
queue of queueLimit (oldest dropped and counted). A stuck observer therefore shows as
observation.status: "stalled" while delivery keeps running. Return or yield promptly (hand the
counts to a buffer and return): code in the same process cannot preempt synchronous CPU work, so a
CPU-bound observer delays everything on its event loop, delivery included.
delivery: "attention" means the last local run ended other than completed, or any claimed event
was retried, quarantined, stale or unresolved. clear means the last run completed with every claimed
event acknowledged, including an empty run; it does not establish global health.
observation.dropped, failed and timedOut are lifetime totals that never reset; status
returns to healthy after the next prompt, successful call. Option objects accept only observe,
queueLimit and observerTimeoutMs; null and unknown keys throw at construction.
The defaults (64 observations, 1,000 ms) are configuration choices, not
performance claims. createPostgresProtectedWriteDeliveryWorker and
createSqliteProtectedWriteDeliveryWorker accept the same diagnostics option and forward it
unchanged.
The shared createOutboxDeliveryWorker accepts an equivalent trusted storage port for composition.
Its port must return immutable claim payloads and release claim transactions before resolving. The
first-party facades meet that contract. This helper provides no tenant-user route, administrative UI,
retention/deletion policy or durable log of failed sink attempts.