// DECLARED-EVENT ATTEMPTS (architecture, "What an author writes, and how": the events row; ADR 0036 ยง4). A queued packet // is not evidence its receiver answered: each attempt is claimed under the shared action lock, signed when it is sent on // the receiver's clock (receiverNow: a receiver holds a signature's timestamp to a tolerance against its own clock, // Stripe's libraries to five minutes, so a packet signed at the write, or on a World clock the app does not read, would // be refused), and its outcome recorded as its own row. A failed attempt // holds the delivery for the next one on the vendor's declared schedule; this is not the originating-write outbox. // The attempt is made as the pack declares its vendor makes it: over HTTP, into a socket session the app holds, or as a // request to another twin; with its body rendered again, several events gathered into one request, a timeout, the // attempt's number and the last failure's reason in its headers; and the endpoint turned off when its failures reach // the vendor's bound. No vendor's nouns are here. import { applyTwinWriteAtomic, twinResources } from './serve.ts'; import { receiverNow, worldNow } from './world-clock.ts'; import { attemptRenderer, endpointSecret, fillEnvelope, liveEndpoint, signPacket, type EndpointsDecl, type EventScheme, type EventTransport, type EventWrite } from './events.ts'; import { recordFault, serviceLedger, webhookFault } from './scenario-consume.ts'; import { durationMs } from './placements.ts'; import { sessionsAt, type SocketSession } from './sockets.ts'; import { projectRoot } from './storage.ts'; const ATTEMPT = '_world_event_delivery_attempt'; /** An endpoint's run of outcomes, kept for its kind's `disable` bound: never a vendor resource. */ const HEALTH = '_world_event_endpoint_health'; type Row = Record; /** A packet's transport as it is kept: its request's or frame's template filled from the endpoint at the write. */ type Via = 'http' | { twin: { method: string; body: unknown; headers: Record } } | { socket: string; session: string; frame: unknown }; type Claimed = { attemptId: string; url: string; body: string; headers: Record; via: Via; endpointId: string; timeoutMs: number | null }; /** Why an attempt failed, as the next attempt's `$retryReason` names it. */ type RetryReason = 'http_timeout' | 'http_error' | 'connection_failed'; /** An attempt's own values: its number, the retry's number and the last failure's reason (absent on the first), and * the instant on the receiver's clock. */ function attemptValues(n: number, reason: unknown, ms: number): Record { return { $attempt: n, $retry: n > 1 ? n - 1 : undefined, $retryReason: n > 1 && typeof reason === 'string' ? reason : undefined, '$time.attempt.ms': ms, '$time.attempt.s': Math.floor(ms / 1000), '$time.attempt.iso': new Date(ms).toISOString(), }; } /** The headers an attempt fills itself; a value absent leaves its header out. */ function attemptHeaders(templates: unknown, values: Record): Record { const out: Record = {}; if (!templates || typeof templates !== 'object') return out; for (const [name, template] of Object.entries(templates as Record)) { const value = values[template]; if (value !== undefined && value !== null) out[name] = String(value); } return out; } /** One packet's body at an attempt: as rendered at the write, or, rendered at each attempt, its envelope filled again * with the write's values, the pack's render's `data` when it gave one, and the attempt's values. */ function bodyAt(row: Row, values: Record, endpoint: Row | undefined, data: Record | undefined): string { const render = row.render as { envelope: unknown; values: Record } | undefined; if (!render || typeof render !== 'object' || !render.values || typeof render.values !== 'object') return String(row.body); return JSON.stringify(fillEnvelope(render.envelope, { ...render.values, ...(data ? { $data: data } : {}), ...values }, endpoint)); } /** Packets in the order they were made. */ const made = (a: Row, b: Row): number => Number(a.sent_at) - Number(b.sent_at) || Number(a.seq) - Number(b.seq); /** The packets one attempt sends: itself; a batch's gathered packets; or, at a batched packet's first attempt, it and * the packets for its endpoint not yet sent (queued, or waiting out their window), in the order they were made, at * most its `batch_max`. */ function batchMembers(resources: ReadonlyArray, deliveryType: string, row: Row): Row[] { if (Array.isArray(row.batch_of)) return (row.batch_of as unknown[]).map((id) => resources.find((r) => r.type === deliveryType && r.id === id)).filter((r): r is Row => r !== undefined && r.deleted !== true); const max = Number(row.batch_max); if (!Number.isSafeInteger(max) || max < 1 || Number(row.attempt_count) !== 0) return [row]; const others = resources.filter((r) => r.type === deliveryType && r.id !== row.id && r.deleted !== true && (r.delivery_state === 'queued' || r.delivery_state === 'held') && Number(r.attempt_count) === 0 && r.batch_max !== undefined && !Array.isArray(r.batch_of) && r.endpoint_type === row.endpoint_type && r.endpoint_id === row.endpoint_id) .sort(made); return [row, ...others.slice(0, max - 1)].sort(made); } /** A socket delivery's frame: its template filled with the event, its sequence number and the attempt's values. */ function socketFrame(via: { frame: unknown }, event: string, seq: number, values: Record): string { let parsed: unknown = event; try { parsed = JSON.parse(event); } catch { /* a body that is not JSON is sent as its text */ } const frame = fillEnvelope(via.frame ?? '$event', { $event: parsed, $seq: seq, ...values }); return typeof frame === 'string' ? frame : JSON.stringify(frame); } /** A request to another twin's operation, as the app would call the vendor, routed to that vendor's twin in the World * (vendor-call.ts): its status, or 0 when nothing answered. */ async function twinSend(url: string, method: string, body: string, headers: Record): Promise { const { vendorFetch } = await import('./vendor-call.ts'); try { const res = await vendorFetch(url, { method, headers: { 'content-type': 'application/json', ...headers }, body }); await res.body?.cancel().catch(() => undefined); return res.status; } catch { return 0; } } const TIMEOUT = Symbol('timeout'); /** The work's answer, or TIMEOUT when `ms` (machine time: a request takes real time) pass first. */ async function within(work: Promise, ms: number | null): Promise { if (ms === null) return work; void work.catch(() => undefined); let timer: ReturnType | undefined; const late = new Promise((done) => { timer = setTimeout(() => done(TIMEOUT), ms); }); try { return await Promise.race([work, late]); } finally { clearTimeout(timer); } } /** Make the delivery's next attempt, if it is queued for one: sent, or failed without sending when the World's scenario * drops it (`webhook-drop`, landing on each attempt it is placed over), and recorded. Answers whether the delivery is * now held for a later attempt. Existing attempts and interrupted sending claims never turn into an unrequested send. */ export async function attemptDelivery( service: string, deliveryType: string, deliveryId: string, root: string | undefined, transport: EventTransport, trace: Record, ): Promise { const at = worldNow(); const seen = twinResources(service, root).find((r) => r.type === deliveryType && r.id === deliveryId); if (!seen || seen.deleted === true || seen.delivery_state !== 'queued') return false; // the fault is read before the claim (recording it is a write of its own) and recorded only for an attempt made const ledger = typeof seen.vendor === 'string' ? serviceLedger({ vendor: seen.vendor, service, root, at, recording: true }) : undefined; const drop = ledger ? webhookFault(ledger, String(seen.event_type), ['webhook-drop']) : undefined; // a body rendered at each attempt is rendered by the pack before the claim (its render reads the World), for the // packets the attempt is expected to send; the claim falls back to the write's own data for any other const rendered = new Map>(); const render = attemptRenderer(projectRoot(root)); if (render && seen.render && typeof seen.render === 'object') { const n = Number(seen.attempt_count) + 1; for (const m of batchMembers(twinResources(service, root) as unknown as Row[], deliveryType, seen as unknown as Row)) { const kept = (m.render as { write?: Omit } | undefined)?.write; if (kept) rendered.set(String(m.id), await render({ ...kept, attempt: n }, String(m.event_type))); } } const { value: claim } = await applyTwinWriteAtomic(service, (resources) => { const all = resources as unknown as Row[]; const row = all.find((r) => r.type === deliveryType && r.id === deliveryId); if (!row || row.deleted === true || row.delivery_state !== 'queued') return { kind: 'skip', value: undefined }; const n = Number(row.attempt_count) + 1; const attemptId = `${deliveryType}:${deliveryId}:${n}`; if (!Number.isSafeInteger(n) || all.some((r) => r.type === ATTEMPT && r.id === attemptId)) return { kind: 'skip', value: undefined }; if (row.delivery_protocol !== 2 || typeof row.url !== 'string' || typeof row.body !== 'string' || typeof row.message_id !== 'string' || !row.scheme || typeof row.scheme !== 'object' || !row.endpoint || typeof row.endpoint !== 'object' || !row.headers || typeof row.headers !== 'object' || Array.isArray(row.headers) || Object.values(row.headers).some((v) => typeof v !== 'string')) { throw new Error('A retained declared-event packet is incomplete; it cannot be dispatched.'); } const via = (row.transport ?? 'http') as Via; // signed with the endpoint's secret (and keys) as it is now; an endpoint deleted or disabled since takes no further // attempt, as the vendor stops retrying it (Stripe's "Automatic retries") const kind = row.endpoint as EndpointsDecl, endpointId = String(row.endpoint_id); const endpoint = liveEndpoint(all, kind, endpointId, via === 'http'); const secret = endpointSecret(all, kind, endpointId, via === 'http'); if (endpoint === undefined || secret === undefined) return { kind: 'write', value: 'ended', write: { operation: 'world_event_delivery.end', subjectType: deliveryType, subjectId: deliveryId, fields: { delivery_state: 'ended', due_at: null }, occurredAt: at, actor: { kind: 'system' as const }, } }; const ms = receiverNow(), seconds = Math.floor(ms / 1000); const values = attemptValues(n, row.last_reason, ms); const members = batchMembers(all, deliveryType, row); const bodies = members.map((m) => bodyAt(m, values, endpoint, rendered.get(String(m.id)))); const gathers = row.batch_max !== undefined && !Array.isArray(row.batch_of); const event = row.batch_max !== undefined ? `[${bodies.join(',')}]` : bodies[0]!; const method = typeof via === 'object' && 'twin' in via ? via.twin.method : 'POST'; const signed = signPacket(row.scheme as EventScheme | ReadonlyArray, secret, event, seconds, row.url, row.message_id, { ms, endpoint, method }); // what goes on the wire: the event itself (HTTP), wrapped in the other vendor's request (a twin), or a frame let body = signed.body; if (typeof via === 'object' && 'twin' in via) { let parsed: unknown = body; try { parsed = JSON.parse(body); } catch { /* sent as its text */ } const wrapped = fillEnvelope(via.twin.body ?? '$event', { $event: parsed, '$event.text': body, '$event.base64': Buffer.from(body, 'utf8').toString('base64'), ...values }); body = typeof wrapped === 'string' ? wrapped : JSON.stringify(wrapped); } else if (typeof via === 'object' && 'socket' in via) body = socketFrame(via, body, Number(row.seq), values); const headers = { ...row.headers as Record, ...(typeof via === 'object' && 'twin' in via ? via.twin.headers : {}), ...attemptHeaders(row.attempt_headers, values), ...signed.headers }; return { kind: 'write', value: { attemptId, url: row.url, body, headers, via, endpointId, timeoutMs: typeof row.timeout_ms === 'number' ? row.timeout_ms : null, }, write: { operation: 'world_event_delivery.claim', subjectType: deliveryType, subjectId: deliveryId, fields: { delivery_state: 'sending', attempt_count: n, current_attempt: attemptId, ...(gathers ? { batch_of: members.map((m) => m.id) } : {}) }, projection: { creates: [{ type: ATTEMPT, id: attemptId, fields: { delivery_type: deliveryType, delivery_id: deliveryId, attempt: n, signed_at: seconds, state: 'sending', started_at: Date.parse(at), finished_at: null, transport_status: null, } }], // the packets this attempt gathers are sent in it, and by it alone ...(gathers && members.length > 1 ? { updates: members.filter((m) => m.id !== deliveryId).map((m) => ({ type: deliveryType, id: String(m.id), fields: { delivery_state: 'batched', batch_into: deliveryId, due_at: null } })) } : {}), }, occurredAt: at, actor: { kind: 'system' as const }, } }; }, root); if (claim === undefined || claim === 'ended') return false; let status: number | null = null, timedOut = false, sentToSession = false, noSession = false; if (drop) await recordFault(ledger!, drop, { event: seen.event_type, delivery: deliveryId, attempt: claim.attemptId }); else if (typeof claim.via === 'object' && 'socket' in claim.via) { // into each open session bound to the endpoint; none open fails the attempt (the app is not connected) const via = claim.via; const bound = sessionsAt(service, projectRoot(root), via.socket).filter((s: SocketSession) => String(s.state[via.session]) === claim.endpointId); for (const s of bound) s.send(claim.body); sentToSession = bound.length > 0; noSession = !sentToSession; } else { try { const via = claim.via; const sending = typeof via === 'object' && 'twin' in via ? twinSend(claim.url, via.twin.method, claim.body, { ...claim.headers, ...trace }) : transport(claim.url, claim.body, { ...claim.headers, ...trace }); const answer = await within(sending, claim.timeoutMs); if (answer === TIMEOUT) timedOut = true; else if (typeof answer === 'number' && Number.isInteger(answer) && answer >= 100 && answer <= 599) status = answer; } catch { // A thrown request can have reached the receiver. Preserve uncertainty and // never copy exception strings, response bodies or credentials into history. } } // a dropped attempt failed: the vendor sent nothing the receiver could have taken; one not answered in time failed const state = drop || timedOut || noSession ? 'failed' : sentToSession ? 'succeeded' : status === null ? 'unknown' : status >= 200 && status < 300 ? 'succeeded' : 'failed'; const reason: RetryReason | null = state === 'succeeded' ? null : timedOut ? 'http_timeout' : status !== null ? 'http_error' : 'connection_failed'; const occurredAt = worldNow(), finishedAt = Date.parse(occurredAt); const { value: held } = await applyTwinWriteAtomic(service, (resources) => { const all = resources as unknown as Row[]; const attempt = all.find((r) => r.type === ATTEMPT && r.id === claim.attemptId); if (!attempt || attempt.deleted === true || attempt.state !== 'sending' || attempt.delivery_type !== deliveryType || attempt.delivery_id !== deliveryId) return { kind: 'skip', value: false }; const row = all.find((r) => r.type === deliveryType && r.id === deliveryId); const current = row && row.deleted !== true && row.delivery_state === 'sending' && row.current_attempt === claim.attemptId; // the next attempt falls due after this one's own due time by the schedule's next delay, so a clock moved past // several of them finds each due (a receiver unreachable for the vendor's whole schedule fails for good); a // redelivery by hand is not retried const after = current && state !== 'succeeded' && row.redelivery !== true && Array.isArray(row.retry_ms) ? row.retry_ms[Number(row.attempt_count) - 1] : undefined; const due = typeof after === 'number' ? Number(row!.due_at) + after : undefined; const updates: Array<{ type: string; id: string; fields: Record }> = []; const creates: Array<{ type: string; id: string; fields: Record }> = []; if (current && row) { updates.push({ type: deliveryType, id: deliveryId, fields: { delivery_state: due !== undefined ? 'held' : state, due_at: due ?? null, finished_at: finishedAt, transport_status: status, last_reason: reason, // A later attempt must not erase earlier positive acceptance. accepted_at: state === 'succeeded' ? row.accepted_at ?? finishedAt : row.accepted_at ?? null, } }); // its first acceptance lowers its stored event's count of deliveries not yet accepted (events.ts `pending`) const pending = row.pending as { store?: unknown; field?: unknown } | undefined; if (state === 'succeeded' && (row.accepted_at === null || row.accepted_at === undefined) && typeof pending?.store === 'string' && typeof pending.field === 'string') { const event = all.find((r) => r.type === pending.store && r.id === row.event_id && r.deleted !== true); if (event) updates.push({ type: pending.store, id: String(row.event_id), fields: { [pending.field]: Math.max(0, Number(event[pending.field] ?? 0) - 1) } }); } // the endpoint's run of outcomes against its kind's bound; crossing it writes the vendor's own disabled state const policy = (row.endpoint as EndpointsDecl | undefined)?.disable; if (policy) { const id = `${String(row.endpoint_type)}:${String(row.endpoint_id)}`; const health = all.find((r) => r.type === HEALTH && r.id === id && r.deleted !== true); const failed = state !== 'succeeded'; const consecutive = failed ? Number(health?.consecutive_failures ?? 0) + 1 : 0; const since = failed ? (typeof health?.failing_since === 'number' ? health.failing_since : finishedAt) : null; const keep = policy.successRate?.of ?? 0; const recent = keep > 0 ? [...(Array.isArray(health?.recent) ? health.recent as boolean[] : []), !failed].slice(-keep) : []; const off = failed && ( (policy.failures !== undefined && consecutive >= policy.failures) || (policy.failingFor !== undefined && since !== null && finishedAt - since >= durationMs(policy.failingFor)) || (policy.successRate !== undefined && recent.length >= policy.successRate.of && recent.filter(Boolean).length / recent.length < policy.successRate.below)); // turned off, the run starts again: an endpoint turned on again is held to the bound afresh const fields = off ? { endpoint_type: row.endpoint_type, endpoint_id: row.endpoint_id, consecutive_failures: 0, failing_since: null, recent: [], disabled_at: finishedAt } : { endpoint_type: row.endpoint_type, endpoint_id: row.endpoint_id, consecutive_failures: consecutive, failing_since: since, recent, disabled_at: health?.disabled_at ?? null }; (health ? updates : creates).push({ type: HEALTH, id, fields }); if (off) updates.push({ type: String(row.endpoint_type), id: String(row.endpoint_id), fields: { ...policy.set } }); } } return { kind: 'write', value: due !== undefined, write: { operation: 'world_event_delivery.finish', subjectType: ATTEMPT, subjectId: claim.attemptId, fields: { state, finished_at: finishedAt, transport_status: status, failure_reason: reason, ...(drop ? { dropped: true } : {}) }, ...(updates.length || creates.length ? { projection: { ...(updates.length ? { updates } : {}), ...(creates.length ? { creates } : {}) } } : {}), occurredAt, actor: { kind: 'system' as const }, } }; }, root); return held; } /** A socket session that resumes after the last sequence number it saw is sent every later frame of the endpoint it is * bound to again, in order, whatever became of their attempts (Discord's Gateway resume): the frames as they were * rendered at the write. Answers how many it was sent. */ export function replaySocketDeliveries(service: string, root: string | undefined, session: SocketSession, after: number): number { const rows = (twinResources(service, root) as unknown as Row[]).filter((r) => { const via = r.transport as { socket?: unknown; session?: unknown } | undefined; return r.deleted !== true && via && typeof via === 'object' && via.socket === session.socket && Number(r.seq) > after && String(r.endpoint_id) === String(session.state[String(via.session)]); }).sort((a, b) => Number(a.seq) - Number(b.seq)); const ms = receiverNow(); for (const r of rows) session.send(socketFrame(r.transport as { frame: unknown }, String(r.body), Number(r.seq), attemptValues(Math.max(1, Number(r.attempt_count)), r.last_reason, ms))); return rows.length; }