From 0a03282d1b599b47aa344947b3c515f42b065ec7 Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:09 +0100 Subject: [PATCH 01/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- backend/src/services/pushChannel.ts | 222 ++++++++++++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 backend/src/services/pushChannel.ts diff --git a/backend/src/services/pushChannel.ts b/backend/src/services/pushChannel.ts new file mode 100644 index 00000000..d2ccf173 --- /dev/null +++ b/backend/src/services/pushChannel.ts @@ -0,0 +1,222 @@ +/** + * Push-first notification delivery with a silent-retry policy. + * + * Push is tried first for a user's registered devices. Transient transport failures are + * retried in the background with capped exponential backoff, and the user sees nothing + * until the final outcome is known. Permanent and unregistered failures are never retried. + * A token the provider reports as unregistered is removed from the device registry. A + * permanent failure keeps the token, because it may be a bug on our side rather than a dead device. + * + * The caller decides what happens after a failed push, for example falling back to email. + * This module reports `no_devices` separately from `failed` so that a user with no devices + * is not treated as a delivery error. + */ + +import { logger } from '../utils/logger.js'; + +export interface PushMessage { + title: string; + body: string; + /** Extra string data delivered with the push. Must be JSON-serialisable strings. */ + data?: Record; +} + +export type PushFailureKind = 'transient' | 'permanent' | 'unregistered'; + +/** Thrown by a `PushTransport` to classify a failed attempt. */ +export class PushTransportError extends Error { + constructor( + readonly kind: PushFailureKind, + message: string, + /** Server-requested wait before the next attempt, in milliseconds. */ + readonly retryAfterMs?: number, + ) { + super(message); + this.name = 'PushTransportError'; + } +} + +/** Sends one message to one device token. Implementations throw `PushTransportError`. */ +export interface PushTransport { + send(token: string, message: PushMessage): Promise; +} + +export interface PushDeviceRegistry { + tokensFor(userId: string): Promise; + removeToken(userId: string, token: string): Promise; +} + +export interface PushRetryPolicy { + /** Total attempts per device token, including the first. */ + maxAttempts: number; + baseDelayMs: number; + maxDelayMs: number; +} + +export const DEFAULT_PUSH_RETRY_POLICY: PushRetryPolicy = { + maxAttempts: 4, + baseDelayMs: 500, + maxDelayMs: 30_000, +}; + +/** Observability events. Tokens are never included; only a short fingerprint is. */ +export type PushEvent = + | { type: 'attempt_failed'; userId: string; tokenHint: string; attempt: number; kind: PushFailureKind; delayMs?: number } + | { type: 'token_removed'; userId: string; tokenHint: string; reason: PushFailureKind } + | { type: 'delivered'; userId: string; devices: number; attemptsTotal: number } + | { type: 'failed'; userId: string; devices: number; attemptsTotal: number }; + +export interface PushChannelOptions { + transport: PushTransport; + devices: PushDeviceRegistry; + policy?: Partial; + /** Injectable for tests. Defaults to a real timer. */ + sleep?: (ms: number) => Promise; + /** Injectable for tests. Defaults to Math.random. */ + random?: () => number; + /** Metrics and log hook. Defaults to structured logs through the shared logger. */ + observe?: (event: PushEvent) => void; +} + +export type PushResult = + | { status: 'delivered'; devices: number; deliveredTo: number; attemptsTotal: number } + | { status: 'no_devices'; devices: 0; deliveredTo: 0; attemptsTotal: 0 } + | { status: 'failed'; devices: number; deliveredTo: 0; attemptsTotal: number }; + +/** A short, non-reversible hint for logs. Never the token itself. */ +export function tokenHint(token: string): string { + let hash = 0; + for (let i = 0; i < token.length; i += 1) { + hash = (hash * 31 + token.charCodeAt(i)) >>> 0; + } + return `tok_${hash.toString(16).padStart(8, '0')}`; +} + +/** + * Delay before retry number `attempt` (1 for the first retry). Exponential, capped, with + * "equal" jitter so devices do not retry in lockstep. A server-supplied wait is honoured but + * still capped. + */ +export function pushRetryDelayMs( + attempt: number, + policy: PushRetryPolicy, + retryAfterMs: number | undefined, + random: () => number = Math.random, +): number { + if (retryAfterMs !== undefined && Number.isFinite(retryAfterMs) && retryAfterMs >= 0) { + return Math.min(retryAfterMs, policy.maxDelayMs); + } + const exponent = Math.min(Math.max(attempt - 1, 0), 30); + const ceiling = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** exponent); + const half = ceiling / 2; + return Math.floor(half + random() * half); +} + +function defaultSleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function defaultObserve(event: PushEvent): void { + if (event.type === 'failed') { + logger.warn({ ...event }, 'push notification failed for all devices'); + } else if (event.type === 'token_removed') { + logger.info({ ...event }, 'push device token removed'); + } +} + +export class PushChannel { + private readonly transport: PushTransport; + private readonly devices: PushDeviceRegistry; + private readonly policy: PushRetryPolicy; + private readonly sleep: (ms: number) => Promise; + private readonly random: () => number; + private readonly observe: (event: PushEvent) => void; + + constructor(options: PushChannelOptions) { + this.transport = options.transport; + this.devices = options.devices; + this.policy = { ...DEFAULT_PUSH_RETRY_POLICY, ...options.policy }; + if (!Number.isInteger(this.policy.maxAttempts) || this.policy.maxAttempts < 1) { + throw new RangeError('maxAttempts must be a positive integer'); + } + this.sleep = options.sleep ?? defaultSleep; + this.random = options.random ?? Math.random; + this.observe = options.observe ?? defaultObserve; + } + + /** + * Pushes to every registered device of a user. Devices are tried independently, so one + * dead token does not stop delivery to the others. Never throws for transport failures. + */ + async send(userId: string, message: PushMessage): Promise { + const tokens = await this.devices.tokensFor(userId); + if (tokens.length === 0) { + return { status: 'no_devices', devices: 0, deliveredTo: 0, attemptsTotal: 0 }; + } + + let deliveredTo = 0; + let attemptsTotal = 0; + for (const token of tokens) { + const outcome = await this.deliverToDevice(userId, token, message); + attemptsTotal += outcome.attempts; + if (outcome.delivered) deliveredTo += 1; + } + + if (deliveredTo > 0) { + this.observe({ type: 'delivered', userId, devices: tokens.length, attemptsTotal }); + return { status: 'delivered', devices: tokens.length, deliveredTo, attemptsTotal }; + } + this.observe({ type: 'failed', userId, devices: tokens.length, attemptsTotal }); + return { status: 'failed', devices: tokens.length, deliveredTo: 0, attemptsTotal }; + } + + private async deliverToDevice( + userId: string, + token: string, + message: PushMessage, + ): Promise<{ delivered: boolean; attempts: number }> { + const hint = tokenHint(token); + for (let attempt = 1; attempt <= this.policy.maxAttempts; attempt += 1) { + try { + await this.transport.send(token, message); + return { delivered: true, attempts: attempt }; + } catch (error) { + const failure = this.classify(error); + if (failure.kind !== 'transient') { + this.observe({ type: 'attempt_failed', userId, tokenHint: hint, attempt, kind: failure.kind }); + await this.removeDeadToken(userId, token, hint, failure.kind); + return { delivered: false, attempts: attempt }; + } + if (attempt >= this.policy.maxAttempts) { + this.observe({ type: 'attempt_failed', userId, tokenHint: hint, attempt, kind: 'transient' }); + return { delivered: false, attempts: attempt }; + } + // Silent retry: the user is not told about this attempt. + const delayMs = pushRetryDelayMs(attempt, this.policy, failure.retryAfterMs, this.random); + this.observe({ type: 'attempt_failed', userId, tokenHint: hint, attempt, kind: 'transient', delayMs }); + await this.sleep(delayMs); + } + } + return { delivered: false, attempts: this.policy.maxAttempts }; + } + + private classify(error: unknown): { kind: PushFailureKind; retryAfterMs?: number } { + if (error instanceof PushTransportError) { + return { kind: error.kind, retryAfterMs: error.retryAfterMs }; + } + // Anything the transport did not classify is treated as permanent, so unknown bugs are + // not retried blindly and tokens are not deleted for them. + return { kind: 'permanent' }; + } + + private async removeDeadToken( + userId: string, + token: string, + hint: string, + reason: PushFailureKind, + ): Promise { + if (reason !== 'unregistered') return; + await this.devices.removeToken(userId, token); + this.observe({ type: 'token_removed', userId, tokenHint: hint, reason }); + } +} From b2c676478e497bfe35073d12b7cfcc3dfb9d0954 Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:13 +0100 Subject: [PATCH 02/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- backend/src/services/pushChannel.test.ts | 184 +++++++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 backend/src/services/pushChannel.test.ts diff --git a/backend/src/services/pushChannel.test.ts b/backend/src/services/pushChannel.test.ts new file mode 100644 index 00000000..b564eb63 --- /dev/null +++ b/backend/src/services/pushChannel.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + PushChannel, + PushEvent, + PushMessage, + PushTransport, + PushTransportError, + pushRetryDelayMs, + tokenHint, +} from './pushChannel.js'; + +const MESSAGE: PushMessage = { title: 'Invoice paid', body: 'Thanks!' }; + +function devices(map: Record) { + const removed: Array<{ userId: string; token: string }> = []; + return { + removed, + registry: { + tokensFor: vi.fn(async (userId: string) => [...(map[userId] ?? [])]), + removeToken: vi.fn(async (userId: string, token: string) => { + removed.push({ userId, token }); + map[userId] = (map[userId] ?? []).filter((t) => t !== token); + }), + }, + }; +} + +function channel( + transport: PushTransport, + registry: ReturnType['registry'], + overrides: { events?: PushEvent[]; sleep?: (ms: number) => Promise; maxAttempts?: number } = {}, +) { + const events = overrides.events ?? []; + // One shared mock, so the test inspects the same sleep the channel calls. + const sleep = overrides.sleep ?? vi.fn(async () => undefined); + return { + events, + sleep, + channel: new PushChannel({ + transport, + devices: registry, + policy: { maxAttempts: overrides.maxAttempts ?? 3, baseDelayMs: 100, maxDelayMs: 1_000 }, + sleep, + random: () => 0, + observe: (event) => events.push(event), + }), + }; +} + +describe('PushChannel.send', () => { + it('returns no_devices without calling the transport when the user has none', async () => { + const transport = { send: vi.fn(async () => undefined) }; + const { registry } = devices({}); + const { channel: push } = channel(transport, registry); + + await expect(push.send('u1', MESSAGE)).resolves.toMatchObject({ status: 'no_devices', devices: 0 }); + expect(transport.send).not.toHaveBeenCalled(); + }); + + it('delivers to every registered device', async () => { + const transport = { send: vi.fn(async () => undefined) }; + const { registry } = devices({ u1: ['a', 'b'] }); + const { channel: push } = channel(transport, registry); + + await expect(push.send('u1', MESSAGE)).resolves.toEqual({ + status: 'delivered', + devices: 2, + deliveredTo: 2, + attemptsTotal: 2, + }); + expect(transport.send).toHaveBeenCalledTimes(2); + }); + + it('retries a transient failure silently and then succeeds', async () => { + const transport = { + send: vi + .fn() + .mockRejectedValueOnce(new PushTransportError('transient', 'timeout')) + .mockResolvedValueOnce(undefined), + }; + const { registry } = devices({ u1: ['a'] }); + const events: PushEvent[] = []; + const { channel: push, sleep } = channel(transport, registry, { events }); + + const result = await push.send('u1', MESSAGE); + + expect(result).toMatchObject({ status: 'delivered', attemptsTotal: 2 }); + expect(sleep).toHaveBeenCalledTimes(1); + expect(events).toContainEqual(expect.objectContaining({ type: 'attempt_failed', kind: 'transient', attempt: 1 })); + }); + + it('gives up after maxAttempts transient failures and reports failed', async () => { + const transport = { send: vi.fn(async () => { throw new PushTransportError('transient', 'down'); }) }; + const { registry } = devices({ u1: ['a'] }); + const events: PushEvent[] = []; + const { channel: push } = channel(transport, registry, { events, maxAttempts: 3 }); + + await expect(push.send('u1', MESSAGE)).resolves.toMatchObject({ status: 'failed', attemptsTotal: 3 }); + expect(transport.send).toHaveBeenCalledTimes(3); + expect(events.at(-1)).toMatchObject({ type: 'failed', userId: 'u1' }); + }); + + it('removes an unregistered token, does not retry it, and still delivers to other devices', async () => { + const transport = { + send: vi.fn(async (token: string) => { + if (token === 'dead') throw new PushTransportError('unregistered', 'gone'); + }), + }; + const map = { u1: ['dead', 'live'] }; + const { registry, removed } = devices(map); + const { channel: push } = channel(transport, registry); + + await expect(push.send('u1', MESSAGE)).resolves.toMatchObject({ status: 'delivered', deliveredTo: 1 }); + expect(transport.send.mock.calls.filter(([t]) => t === 'dead')).toHaveLength(1); + expect(removed).toEqual([{ userId: 'u1', token: 'dead' }]); + expect(map.u1).toEqual(['live']); + }); + + it('does not retry or remove a token on a permanent failure', async () => { + const transport = { + send: vi.fn(async () => { + throw new PushTransportError('permanent', 'bad payload'); + }), + }; + const map = { u1: ['a'] }; + const { registry, removed } = devices(map); + const { channel: push, sleep } = channel(transport, registry); + + await expect(push.send('u1', MESSAGE)).resolves.toMatchObject({ status: 'failed', attemptsTotal: 1 }); + expect(sleep).not.toHaveBeenCalled(); + expect(removed).toEqual([]); + }); + + it('treats an unclassified error as permanent', async () => { + const transport = { send: vi.fn(async () => { throw new Error('boom'); }) }; + const { registry } = devices({ u1: ['a'] }); + const { channel: push } = channel(transport, registry); + + await expect(push.send('u1', MESSAGE)).resolves.toMatchObject({ status: 'failed', attemptsTotal: 1 }); + expect(transport.send).toHaveBeenCalledTimes(1); + }); + + it('never puts the raw token into observability events', async () => { + const transport = { send: vi.fn(async () => { throw new PushTransportError('transient', 'x'); }) }; + const { registry } = devices({ u1: ['SECRET-DEVICE-TOKEN'] }); + const events: PushEvent[] = []; + const { channel: push } = channel(transport, registry, { events, maxAttempts: 2 }); + + await push.send('u1', MESSAGE); + expect(JSON.stringify(events)).not.toContain('SECRET-DEVICE-TOKEN'); + }); + + it('rejects an invalid retry policy', () => { + const { registry } = devices({}); + expect( + () => new PushChannel({ transport: { send: async () => undefined }, devices: registry, policy: { maxAttempts: 0 } }), + ).toThrow(RangeError); + }); +}); + +describe('pushRetryDelayMs', () => { + const policy = { maxAttempts: 5, baseDelayMs: 100, maxDelayMs: 1_000 }; + + it('grows exponentially and is capped', () => { + // random() = 0 gives the lower half of the ceiling, so the ceiling is easy to read off. + expect(pushRetryDelayMs(1, policy, undefined, () => 0)).toBe(50); + expect(pushRetryDelayMs(2, policy, undefined, () => 0)).toBe(100); + expect(pushRetryDelayMs(3, policy, undefined, () => 0)).toBe(200); + expect(pushRetryDelayMs(20, policy, undefined, () => 0)).toBe(500); + }); + + it('honours a server Retry-After but never beyond maxDelayMs', () => { + expect(pushRetryDelayMs(1, policy, 300, () => 0)).toBe(300); + expect(pushRetryDelayMs(1, policy, 60_000, () => 0)).toBe(1_000); + }); +}); + +describe('tokenHint', () => { + it('is stable and does not contain the token', () => { + expect(tokenHint('abc')).toBe(tokenHint('abc')); + expect(tokenHint('abc')).not.toContain('abc'); + expect(tokenHint('abc')).toMatch(/^tok_[0-9a-f]{8}$/); + }); +}); From ad7a677dc1a464e4cbda1427ea08398ee1743297 Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:16 +0100 Subject: [PATCH 03/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- backend/src/services/quotaLedger.ts | 195 ++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 backend/src/services/quotaLedger.ts diff --git a/backend/src/services/quotaLedger.ts b/backend/src/services/quotaLedger.ts new file mode 100644 index 00000000..66af1206 --- /dev/null +++ b/backend/src/services/quotaLedger.ts @@ -0,0 +1,195 @@ +/** + * Consumption-based API quota ledger with weekly caps. + * + * Each key is charged in units (for example one unit per API call, or per token). A key may + * use up to `weeklyCap` units in a calendar week. Weeks run Monday 00:00 UTC to the next + * Monday 00:00 UTC. + * + * Rules: + * - A consumption that would exceed the cap is rejected and charges nothing. There is no + * partial charge. + * - Each consumption carries an idempotency key. Replaying the same key returns the original + * result and does not charge again, so a retried request cannot double-count. + * - The check and the write are one atomic store operation (`commit`). A store backed by a + * database must implement it as a conditional insert, not as a read followed by a write. + */ + +export const QUOTA_WEEK_MS = 7 * 24 * 60 * 60 * 1000; + +export class QuotaError extends Error { + constructor( + readonly code: 'invalid_units' | 'invalid_idempotency_key' | 'invalid_cap', + message: string, + ) { + super(message); + this.name = 'QuotaError'; + } +} + +export interface LedgerEntry { + idempotencyKey: string; + keyId: string; + units: number; + /** Start of the week the entry is charged to, as an ISO timestamp. */ + weekStart: string; + at: string; +} + +export type CommitOutcome = + | { status: 'applied'; usedAfter: number } + | { status: 'duplicate'; entry: LedgerEntry; usedAfter: number } + | { status: 'exceeded'; usedBefore: number }; + +export interface QuotaStore { + /** + * Atomically: return the existing entry for `entry.idempotencyKey` if there is one; otherwise + * append `entry` only when `usedThisWeek + entry.units <= cap`, and report the result. + */ + commit(entry: LedgerEntry, cap: number): Promise; + usedThisWeek(keyId: string, weekStart: string): Promise; +} + +/** Process-local store. Correct for one process only, which is how tests and dev use it. */ +export class InMemoryQuotaStore implements QuotaStore { + private readonly entries = new Map(); + private readonly usage = new Map(); + + async commit(entry: LedgerEntry, cap: number): Promise { + // No await between the read and the write, so this is atomic within one process. + const existing = this.entries.get(entry.idempotencyKey); + if (existing) { + return { status: 'duplicate', entry: existing, usedAfter: this.usedSync(existing.keyId, existing.weekStart) }; + } + const usedBefore = this.usedSync(entry.keyId, entry.weekStart); + if (usedBefore + entry.units > cap) { + return { status: 'exceeded', usedBefore }; + } + this.entries.set(entry.idempotencyKey, entry); + const usedAfter = usedBefore + entry.units; + this.usage.set(this.usageKey(entry.keyId, entry.weekStart), usedAfter); + return { status: 'applied', usedAfter }; + } + + async usedThisWeek(keyId: string, weekStart: string): Promise { + return this.usedSync(keyId, weekStart); + } + + private usedSync(keyId: string, weekStart: string): number { + return this.usage.get(this.usageKey(keyId, weekStart)) ?? 0; + } + + private usageKey(keyId: string, weekStart: string): string { + return `${keyId}\u0000${weekStart}`; + } +} + +export interface QuotaUsage { + keyId: string; + weekStart: string; + resetsAt: string; + cap: number; + used: number; + remaining: number; +} + +export type ConsumeResult = + | { status: 'applied'; usage: QuotaUsage; idempotencyKey: string } + | { status: 'duplicate'; usage: QuotaUsage; idempotencyKey: string; originalAt: string } + | { status: 'exceeded'; usage: QuotaUsage; requestedUnits: number }; + +export interface QuotaLedgerOptions { + store: QuotaStore; + /** Weekly cap in units for a key. Resolved on each call so plan changes apply at once. */ + weeklyCap: (keyId: string) => number | Promise; + now?: () => Date; + /** Metrics and log hook. Receives no identifiers beyond the key id. */ + observe?: (event: { type: 'consumed' | 'exceeded' | 'duplicate'; keyId: string; units: number }) => void; +} + +/** Start (Monday 00:00 UTC) of the ISO week containing `at`. */ +export function weekStartUtc(at: Date): Date { + const day = at.getUTCDay(); // 0 = Sunday + const daysSinceMonday = (day + 6) % 7; + return new Date(Date.UTC(at.getUTCFullYear(), at.getUTCMonth(), at.getUTCDate() - daysSinceMonday)); +} + +function assertPositiveInteger(value: number, code: QuotaError['code'], label: string): void { + if (!Number.isSafeInteger(value) || value <= 0) { + throw new QuotaError(code, `${label} must be a positive integer`); + } +} + +export class QuotaLedger { + private readonly store: QuotaStore; + private readonly weeklyCap: (keyId: string) => number | Promise; + private readonly now: () => Date; + private readonly observe: NonNullable; + + constructor(options: QuotaLedgerOptions) { + this.store = options.store; + this.weeklyCap = options.weeklyCap; + this.now = options.now ?? (() => new Date()); + this.observe = options.observe ?? (() => undefined); + } + + /** Charges `units` to `keyId` for this week unless that would exceed the cap. */ + async consume(keyId: string, units: number, idempotencyKey: string): Promise { + assertPositiveInteger(units, 'invalid_units', 'units'); + if (typeof idempotencyKey !== 'string' || idempotencyKey.trim() === '') { + throw new QuotaError('invalid_idempotency_key', 'idempotencyKey is required'); + } + const cap = await this.resolveCap(keyId); + const at = this.now(); + const weekStart = weekStartUtc(at).toISOString(); + const outcome = await this.store.commit( + { idempotencyKey, keyId, units, weekStart, at: at.toISOString() }, + cap, + ); + + if (outcome.status === 'applied') { + this.observe({ type: 'consumed', keyId, units }); + return { + status: 'applied', + idempotencyKey, + usage: this.usageFrom(keyId, weekStart, cap, outcome.usedAfter), + }; + } + if (outcome.status === 'duplicate') { + this.observe({ type: 'duplicate', keyId, units }); + // Usage is reported for the current week, not the week of the original entry. + const used = await this.store.usedThisWeek(keyId, weekStart); + return { + status: 'duplicate', + idempotencyKey, + originalAt: outcome.entry.at, + usage: this.usageFrom(keyId, weekStart, cap, used), + }; + } + this.observe({ type: 'exceeded', keyId, units }); + return { + status: 'exceeded', + requestedUnits: units, + usage: this.usageFrom(keyId, weekStart, cap, outcome.usedBefore), + }; + } + + /** Current week's usage for a key, without charging anything. */ + async usage(keyId: string): Promise { + const at = this.now(); + const weekStart = weekStartUtc(at).toISOString(); + const cap = await this.resolveCap(keyId); + const used = await this.store.usedThisWeek(keyId, weekStart); + return this.usageFrom(keyId, weekStart, cap, used); + } + + private async resolveCap(keyId: string): Promise { + const cap = await this.weeklyCap(keyId); + assertPositiveInteger(cap, 'invalid_cap', 'weekly cap'); + return cap; + } + + private usageFrom(keyId: string, weekStart: string, cap: number, used: number): QuotaUsage { + const resetsAt = new Date(new Date(weekStart).getTime() + QUOTA_WEEK_MS).toISOString(); + return { keyId, weekStart, resetsAt, cap, used, remaining: Math.max(0, cap - used) }; + } +} From c358a5b242e1a91f62553f694310498b20b56fd6 Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:20 +0100 Subject: [PATCH 04/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- backend/src/services/quotaLedger.test.ts | 155 +++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 backend/src/services/quotaLedger.test.ts diff --git a/backend/src/services/quotaLedger.test.ts b/backend/src/services/quotaLedger.test.ts new file mode 100644 index 00000000..dcb268f6 --- /dev/null +++ b/backend/src/services/quotaLedger.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, it } from 'vitest'; +import { + InMemoryQuotaStore, + QuotaError, + QuotaLedger, + weekStartUtc, +} from './quotaLedger.js'; + +/** A clock the test can move between weeks. */ +function clock(iso: string) { + let current = new Date(iso); + return { + now: () => new Date(current), + set: (next: string) => { + current = new Date(next); + }, + }; +} + +function ledger(cap: number, at: string) { + const time = clock(at); + const store = new InMemoryQuotaStore(); + const quota = new QuotaLedger({ store, weeklyCap: () => cap, now: time.now }); + return { quota, store, time }; +} + +describe('weekStartUtc', () => { + it('starts the week on Monday 00:00 UTC', () => { + // 2026-02-04 is a Wednesday; its week starts Monday 2026-02-02. + expect(weekStartUtc(new Date('2026-02-04T15:30:00.000Z')).toISOString()).toBe('2026-02-02T00:00:00.000Z'); + }); + + it('puts a Sunday in the week that started the previous Monday', () => { + // 2026-02-08 is a Sunday. + expect(weekStartUtc(new Date('2026-02-08T23:59:00.000Z')).toISOString()).toBe('2026-02-02T00:00:00.000Z'); + }); + + it('puts Monday 00:00 UTC in the new week', () => { + expect(weekStartUtc(new Date('2026-02-09T00:00:00.000Z')).toISOString()).toBe('2026-02-09T00:00:00.000Z'); + }); +}); + +describe('QuotaLedger.consume', () => { + it('applies a consumption and reports what remains', async () => { + const { quota } = ledger(10, '2026-02-04T12:00:00.000Z'); + + const result = await quota.consume('key-1', 3, 'req-1'); + + expect(result).toMatchObject({ status: 'applied', usage: { used: 3, remaining: 7, cap: 10 } }); + }); + + it('accepts a consumption that reaches the cap exactly', async () => { + const { quota } = ledger(5, '2026-02-04T12:00:00.000Z'); + await quota.consume('key-1', 4, 'a'); + + await expect(quota.consume('key-1', 1, 'b')).resolves.toMatchObject({ status: 'applied', usage: { remaining: 0 } }); + }); + + it('rejects a consumption over the cap and charges nothing', async () => { + const { quota } = ledger(5, '2026-02-04T12:00:00.000Z'); + await quota.consume('key-1', 4, 'a'); + + const result = await quota.consume('key-1', 2, 'b'); + + expect(result).toMatchObject({ status: 'exceeded', requestedUnits: 2, usage: { used: 4, remaining: 1 } }); + // The rejected request left no charge behind, so a smaller one still fits. + await expect(quota.consume('key-1', 1, 'c')).resolves.toMatchObject({ status: 'applied', usage: { used: 5 } }); + }); + + it('treats a replayed idempotency key as a duplicate and does not charge twice', async () => { + const { quota } = ledger(10, '2026-02-04T12:00:00.000Z'); + await quota.consume('key-1', 3, 'same-request'); + + const replay = await quota.consume('key-1', 3, 'same-request'); + + expect(replay).toMatchObject({ status: 'duplicate', usage: { used: 3, remaining: 7 } }); + expect(replay).toHaveProperty('originalAt'); + }); + + it('resets usage when a new week starts', async () => { + const { quota, time } = ledger(5, '2026-02-08T23:00:00.000Z'); + await quota.consume('key-1', 5, 'sunday'); + expect((await quota.consume('key-1', 1, 'sunday-2')).status).toBe('exceeded'); + + time.set('2026-02-09T00:30:00.000Z'); + + await expect(quota.consume('key-1', 5, 'monday')).resolves.toMatchObject({ + status: 'applied', + usage: { used: 5, remaining: 0, weekStart: '2026-02-09T00:00:00.000Z' }, + }); + }); + + it('keeps keys independent', async () => { + const { quota } = ledger(2, '2026-02-04T12:00:00.000Z'); + await quota.consume('a', 2, 'a-1'); + + await expect(quota.consume('b', 2, 'b-1')).resolves.toMatchObject({ status: 'applied' }); + }); + + it('applies a cap change immediately', async () => { + let cap = 2; + const store = new InMemoryQuotaStore(); + const quota = new QuotaLedger({ + store, + weeklyCap: () => cap, + now: () => new Date('2026-02-04T12:00:00.000Z'), + }); + await quota.consume('key-1', 2, 'a'); + expect((await quota.consume('key-1', 1, 'b')).status).toBe('exceeded'); + + cap = 10; + + await expect(quota.consume('key-1', 1, 'c')).resolves.toMatchObject({ status: 'applied', usage: { cap: 10 } }); + }); + + it('never lets concurrent consumptions exceed the cap', async () => { + const { quota } = ledger(3, '2026-02-04T12:00:00.000Z'); + + const results = await Promise.all( + Array.from({ length: 5 }, (_, i) => quota.consume('key-1', 1, `c-${i}`)), + ); + + expect(results.filter((r) => r.status === 'applied')).toHaveLength(3); + expect(results.filter((r) => r.status === 'exceeded')).toHaveLength(2); + expect((await quota.usage('key-1')).used).toBe(3); + }); + + it('rejects invalid units, keys and caps with a QuotaError', async () => { + const { quota } = ledger(10, '2026-02-04T12:00:00.000Z'); + + await expect(quota.consume('k', 0, 'x')).rejects.toMatchObject({ code: 'invalid_units' }); + await expect(quota.consume('k', 1.5, 'x')).rejects.toBeInstanceOf(QuotaError); + await expect(quota.consume('k', 1, ' ')).rejects.toMatchObject({ code: 'invalid_idempotency_key' }); + + const broken = new QuotaLedger({ store: new InMemoryQuotaStore(), weeklyCap: () => 0 }); + await expect(broken.consume('k', 1, 'x')).rejects.toMatchObject({ code: 'invalid_cap' }); + }); +}); + +describe('QuotaLedger.usage', () => { + it('reports usage and the reset time without charging anything', async () => { + const { quota } = ledger(10, '2026-02-04T12:00:00.000Z'); + await quota.consume('key-1', 4, 'a'); + + const usage = await quota.usage('key-1'); + + expect(usage).toMatchObject({ + used: 4, + remaining: 6, + weekStart: '2026-02-02T00:00:00.000Z', + resetsAt: '2026-02-09T00:00:00.000Z', + }); + expect((await quota.usage('key-1')).used).toBe(4); + }); +}); From b11e953e91861c18b81095da2925d6b63c959d61 Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:26 +0100 Subject: [PATCH 05/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- backend/src/services/recurringInvoices.ts | 255 ++++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 backend/src/services/recurringInvoices.ts diff --git a/backend/src/services/recurringInvoices.ts b/backend/src/services/recurringInvoices.ts new file mode 100644 index 00000000..c858f494 --- /dev/null +++ b/backend/src/services/recurringInvoices.ts @@ -0,0 +1,255 @@ +/** + * Recurring invoice generation with FX-adjusted amounts. + * + * A template defines an amount in its own currency and a cadence. For every period that has + * come due, the generator issues one invoice in the invoice currency, converted at the rate + * for that issue date. The rate and its date are stored on the invoice, so the amount can be + * audited later. + * + * Rules: + * - Idempotent: each period has the key `:`. Running the generator + * again, including after a crash, cannot issue the same period twice. The store must + * enforce uniqueness on that key. + * - Fail closed on FX: if no usable rate is available, that period is not issued and is + * reported as failed. It is picked up by the next run. It is never issued at a guessed or + * zero rate. + * - Money is rounded once, at the end, to the currency's minor units. + * + * Dates are calendar dates (YYYY-MM-DD) interpreted in UTC. + */ + +import { roundMoney } from './billing/money.js'; + +export type Cadence = 'weekly' | 'monthly'; + +export interface RecurringTemplate { + id: string; + customerId: string; + description: string; + /** Amount in `sourceCurrency`, in major units (e.g. 49.99 USD). */ + amount: number; + sourceCurrency: string; + invoiceCurrency: string; + cadence: Cadence; + /** First issue date, YYYY-MM-DD. */ + startDate: string; + /** Last issue date allowed, YYYY-MM-DD. Omit for no end. */ + endDate?: string; + /** Spread added to the converted amount, in basis points (100 = 1%). Must be >= 0. */ + fxSpreadBps?: number; + active?: boolean; +} + +/** Units of `quote` per one unit of `base`, on the given calendar date. */ +export interface RateProvider { + rate(base: string, quote: string, onDate: string): Promise; +} + +export interface GeneratedInvoice { + key: string; + templateId: string; + customerId: string; + description: string; + issueDate: string; + currency: string; + amount: number; + sourceCurrency: string; + sourceAmount: number; + rate: number; + rateDate: string; + fxSpreadBps: number; +} + +export interface InvoiceStore { + /** Returns true when inserted, false when the key already exists. Must be atomic. */ + insert(invoice: GeneratedInvoice): Promise; +} + +export interface RunReport { + created: GeneratedInvoice[]; + duplicates: string[]; + failed: Array<{ key: string; reason: string }>; +} + +export interface RecurringInvoiceOptions { + store: InvoiceStore; + rates: RateProvider; + /** Cap on invoices produced in one run, so a long-dormant template cannot flood the store. */ + maxInvoicesPerRun?: number; + now?: () => Date; +} + +const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/; +/** Currencies with no minor unit. Everything else uses two decimals. */ +const ZERO_DECIMAL_CURRENCIES = new Set(['JPY', 'KRW']); +const MAX_PERIODS_PER_TEMPLATE = 1200; + +export function minorUnitDecimals(currency: string): number { + return ZERO_DECIMAL_CURRENCIES.has(currency.toUpperCase()) ? 0 : 2; +} + +function parseIsoDate(value: string): Date | null { + if (typeof value !== 'string' || !ISO_DATE.test(value)) return null; + const date = new Date(`${value}T00:00:00.000Z`); + if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) return null; + return date; +} + +function daysInMonthUtc(year: number, monthIndex: number): number { + return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate(); +} + +/** + * The `n`th period after `startDate`. Monthly periods keep the start day where possible and + * clamp to the last day of shorter months (Jan 31 -> Feb 28/29 -> Mar 31). + */ +export function addPeriod(startDate: string, cadence: Cadence, n: number): string { + const start = parseIsoDate(startDate); + if (!start) throw new RangeError(`invalid date: ${startDate}`); + if (cadence === 'weekly') { + return new Date(start.getTime() + n * 7 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10); + } + const year = start.getUTCFullYear(); + const monthIndex = start.getUTCMonth() + n; + const targetYear = year + Math.floor(monthIndex / 12); + const targetMonth = ((monthIndex % 12) + 12) % 12; + const day = Math.min(start.getUTCDate(), daysInMonthUtc(targetYear, targetMonth)); + return new Date(Date.UTC(targetYear, targetMonth, day)).toISOString().slice(0, 10); +} + +/** Issue dates for a template that have come due on or before `asOf` (both inclusive). */ +export function dueIssueDates(template: RecurringTemplate, asOf: string): string[] { + const start = parseIsoDate(template.startDate); + const asOfDate = parseIsoDate(asOf); + if (!start || !asOfDate) return []; + const end = template.endDate ? parseIsoDate(template.endDate) : null; + const limit = end && end < asOfDate ? end : asOfDate; + const dates: string[] = []; + for (let n = 0; n < MAX_PERIODS_PER_TEMPLATE; n += 1) { + const date = addPeriod(template.startDate, template.cadence, n); + if (parseIsoDate(date)!.getTime() > limit.getTime()) break; + dates.push(date); + } + return dates; +} + +/** + * Converts `sourceAmount` at `rate`, adds the spread, and rounds to the invoice currency. + * Throws when the inputs cannot produce a meaningful amount. + */ +export function fxAdjustedAmount( + sourceAmount: number, + rate: number, + spreadBps: number, + invoiceCurrency: string, +): number { + if (!Number.isFinite(sourceAmount) || sourceAmount <= 0) { + throw new RangeError('sourceAmount must be a positive number'); + } + if (!Number.isFinite(rate) || rate <= 0) { + throw new RangeError('rate must be a positive number'); + } + if (!Number.isFinite(spreadBps) || spreadBps < 0) { + throw new RangeError('fxSpreadBps must be zero or positive'); + } + const converted = sourceAmount * rate * (1 + spreadBps / 10_000); + return roundMoney(converted, minorUnitDecimals(invoiceCurrency)); +} + +function validateTemplate(template: RecurringTemplate): string | null { + if (!template.id || !template.customerId) return 'missing id or customerId'; + if (!(template.amount > 0)) return 'amount must be positive'; + if (!/^[A-Z]{3}$/.test(template.sourceCurrency) || !/^[A-Z]{3}$/.test(template.invoiceCurrency)) { + return 'currencies must be ISO 4217 codes'; + } + if (template.cadence !== 'weekly' && template.cadence !== 'monthly') return 'unknown cadence'; + if (!parseIsoDate(template.startDate)) return 'startDate must be YYYY-MM-DD'; + if (template.endDate !== undefined && !parseIsoDate(template.endDate)) return 'endDate must be YYYY-MM-DD'; + if (template.fxSpreadBps !== undefined && !(template.fxSpreadBps >= 0)) return 'fxSpreadBps must be zero or positive'; + return null; +} + +export class RecurringInvoiceGenerator { + private readonly store: InvoiceStore; + private readonly rates: RateProvider; + private readonly maxInvoicesPerRun: number; + private readonly now: () => Date; + + constructor(options: RecurringInvoiceOptions) { + this.store = options.store; + this.rates = options.rates; + this.maxInvoicesPerRun = options.maxInvoicesPerRun ?? 500; + this.now = options.now ?? (() => new Date()); + } + + /** Issues every due period of every active template, as of `asOf` (default: today, UTC). */ + async run(templates: RecurringTemplate[], asOf?: string): Promise { + const today = asOf ?? this.now().toISOString().slice(0, 10); + const report: RunReport = { created: [], duplicates: [], failed: [] }; + let issued = 0; + + for (const template of templates) { + if (template.active === false) continue; + const invalid = validateTemplate(template); + if (invalid) { + report.failed.push({ key: `${template.id}:*`, reason: `invalid_template: ${invalid}` }); + continue; + } + for (const issueDate of dueIssueDates(template, today)) { + if (issued >= this.maxInvoicesPerRun) return report; + const key = `${template.id}:${issueDate}`; + const outcome = await this.issueOne(template, issueDate, key); + if (outcome.kind === 'created') { + report.created.push(outcome.invoice); + issued += 1; + } else if (outcome.kind === 'duplicate') { + report.duplicates.push(key); + } else { + report.failed.push({ key, reason: outcome.reason }); + } + } + } + return report; + } + + private async issueOne( + template: RecurringTemplate, + issueDate: string, + key: string, + ): Promise< + | { kind: 'created'; invoice: GeneratedInvoice } + | { kind: 'duplicate' } + | { kind: 'failed'; reason: string } + > { + let rate: number; + try { + rate = await this.rates.rate(template.sourceCurrency, template.invoiceCurrency, issueDate); + } catch { + return { kind: 'failed', reason: 'fx_rate_unavailable' }; + } + const spread = template.fxSpreadBps ?? 0; + let amount: number; + try { + amount = fxAdjustedAmount(template.amount, rate, spread, template.invoiceCurrency); + } catch { + return { kind: 'failed', reason: 'fx_rate_invalid' }; + } + + const invoice: GeneratedInvoice = { + key, + templateId: template.id, + customerId: template.customerId, + description: template.description, + issueDate, + currency: template.invoiceCurrency, + amount, + sourceCurrency: template.sourceCurrency, + sourceAmount: template.amount, + rate, + rateDate: issueDate, + fxSpreadBps: spread, + }; + const inserted = await this.store.insert(invoice); + return inserted ? { kind: 'created', invoice } : { kind: 'duplicate' }; + } +} From 9eba48b7ca9f5680307ede94840b2c9129dc27a9 Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:30 +0100 Subject: [PATCH 06/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- .../src/services/recurringInvoices.test.ts | 194 ++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 backend/src/services/recurringInvoices.test.ts diff --git a/backend/src/services/recurringInvoices.test.ts b/backend/src/services/recurringInvoices.test.ts new file mode 100644 index 00000000..8367e4fa --- /dev/null +++ b/backend/src/services/recurringInvoices.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + addPeriod, + dueIssueDates, + fxAdjustedAmount, + GeneratedInvoice, + InvoiceStore, + RateProvider, + RecurringInvoiceGenerator, + RecurringTemplate, +} from './recurringInvoices.js'; + +const TEMPLATE: RecurringTemplate = { + id: 'tpl-1', + customerId: 'cust-9', + description: 'Hosting', + amount: 49.99, + sourceCurrency: 'USD', + invoiceCurrency: 'EUR', + cadence: 'monthly', + startDate: '2026-01-15', + fxSpreadBps: 150, +}; + +/** Store that enforces key uniqueness, the way a unique index would. */ +function memoryStore(): InvoiceStore & { invoices: GeneratedInvoice[] } { + const invoices: GeneratedInvoice[] = []; + const keys = new Set(); + return { + invoices, + async insert(invoice) { + if (keys.has(invoice.key)) return false; + keys.add(invoice.key); + invoices.push(invoice); + return true; + }, + }; +} + +function fixedRates(rate = 0.92): RateProvider & { rate: ReturnType } { + return { rate: vi.fn(async () => rate) } as RateProvider & { rate: ReturnType }; +} + +describe('addPeriod', () => { + it('adds monthly periods and clamps to the end of a shorter month', () => { + expect(addPeriod('2027-01-31', 'monthly', 1)).toBe('2027-02-28'); + expect(addPeriod('2027-01-31', 'monthly', 2)).toBe('2027-03-31'); + }); + + it('handles leap years', () => { + expect(addPeriod('2028-01-31', 'monthly', 1)).toBe('2028-02-29'); + }); + + it('rolls over the year', () => { + expect(addPeriod('2026-11-15', 'monthly', 2)).toBe('2027-01-15'); + }); + + it('adds weekly periods of seven days', () => { + expect(addPeriod('2026-01-01', 'weekly', 2)).toBe('2026-01-15'); + }); + + it('rejects a malformed start date', () => { + expect(() => addPeriod('2026-02-30', 'monthly', 1)).toThrow(RangeError); + }); +}); + +describe('dueIssueDates', () => { + it('lists every period up to and including asOf', () => { + expect(dueIssueDates(TEMPLATE, '2026-03-15')).toEqual(['2026-01-15', '2026-02-15', '2026-03-15']); + }); + + it('stops at the end date', () => { + expect(dueIssueDates({ ...TEMPLATE, endDate: '2026-02-20' }, '2026-06-01')).toEqual([ + '2026-01-15', + '2026-02-15', + ]); + }); + + it('returns nothing before the first period', () => { + expect(dueIssueDates(TEMPLATE, '2026-01-14')).toEqual([]); + }); +}); + +describe('fxAdjustedAmount', () => { + it('converts, adds the spread and rounds to minor units', () => { + // 49.99 * 0.92 = 45.9908; * 1.015 = 46.67 after rounding. + expect(fxAdjustedAmount(49.99, 0.92, 150, 'EUR')).toBe(46.67); + }); + + it('uses zero decimals for zero-decimal currencies', () => { + expect(fxAdjustedAmount(10, 150.5, 0, 'JPY')).toBe(1505); + }); + + it('refuses a zero or non-finite rate instead of producing an amount', () => { + expect(() => fxAdjustedAmount(10, 0, 0, 'EUR')).toThrow(RangeError); + expect(() => fxAdjustedAmount(10, Number.NaN, 0, 'EUR')).toThrow(RangeError); + }); + + it('refuses a negative spread', () => { + expect(() => fxAdjustedAmount(10, 1, -1, 'EUR')).toThrow(RangeError); + }); +}); + +describe('RecurringInvoiceGenerator.run', () => { + it('issues one invoice per due period, with the rate and its date recorded', async () => { + const store = memoryStore(); + const rates = fixedRates(); + const generator = new RecurringInvoiceGenerator({ store, rates }); + + const report = await generator.run([TEMPLATE], '2026-02-20'); + + expect(report.created.map((i) => i.issueDate)).toEqual(['2026-01-15', '2026-02-15']); + expect(report.created[0]).toMatchObject({ + key: 'tpl-1:2026-01-15', + currency: 'EUR', + sourceCurrency: 'USD', + sourceAmount: 49.99, + rate: 0.92, + rateDate: '2026-01-15', + fxSpreadBps: 150, + amount: 46.67, + }); + expect(rates.rate).toHaveBeenCalledWith('USD', 'EUR', '2026-01-15'); + }); + + it('does not issue the same period twice when run again', async () => { + const store = memoryStore(); + const generator = new RecurringInvoiceGenerator({ store, rates: fixedRates() }); + + await generator.run([TEMPLATE], '2026-02-20'); + const second = await generator.run([TEMPLATE], '2026-02-20'); + + expect(second.created).toEqual([]); + expect(second.duplicates).toEqual(['tpl-1:2026-01-15', 'tpl-1:2026-02-15']); + expect(store.invoices).toHaveLength(2); + }); + + it('leaves a period un-issued when the FX rate is unavailable, and issues it on a later run', async () => { + const store = memoryStore(); + const rates = { + rate: vi.fn().mockRejectedValueOnce(new Error('feed down')).mockResolvedValue(0.92), + } as unknown as RateProvider; + const generator = new RecurringInvoiceGenerator({ store, rates }); + + const first = await generator.run([TEMPLATE], '2026-01-15'); + expect(first.created).toEqual([]); + expect(first.failed).toEqual([{ key: 'tpl-1:2026-01-15', reason: 'fx_rate_unavailable' }]); + expect(store.invoices).toEqual([]); + + const second = await generator.run([TEMPLATE], '2026-01-15'); + expect(second.created.map((i) => i.key)).toEqual(['tpl-1:2026-01-15']); + }); + + it('never issues at a zero or NaN rate', async () => { + const store = memoryStore(); + const generator = new RecurringInvoiceGenerator({ store, rates: fixedRates(0) }); + + const report = await generator.run([TEMPLATE], '2026-01-15'); + + expect(report.created).toEqual([]); + expect(report.failed[0].reason).toBe('fx_rate_invalid'); + expect(store.invoices).toEqual([]); + }); + + it('skips inactive templates', async () => { + const store = memoryStore(); + const generator = new RecurringInvoiceGenerator({ store, rates: fixedRates() }); + + const report = await generator.run([{ ...TEMPLATE, active: false }], '2026-02-20'); + + expect(report).toEqual({ created: [], duplicates: [], failed: [] }); + }); + + it('reports an invalid template without throwing or affecting other templates', async () => { + const store = memoryStore(); + const generator = new RecurringInvoiceGenerator({ store, rates: fixedRates() }); + const bad = { ...TEMPLATE, id: 'bad', amount: -1 }; + + const report = await generator.run([bad, { ...TEMPLATE, id: 'good' }], '2026-01-15'); + + expect(report.failed).toEqual([{ key: 'bad:*', reason: 'invalid_template: amount must be positive' }]); + expect(report.created.map((i) => i.templateId)).toEqual(['good']); + }); + + it('stops at maxInvoicesPerRun', async () => { + const store = memoryStore(); + const generator = new RecurringInvoiceGenerator({ store, rates: fixedRates(), maxInvoicesPerRun: 2 }); + + const report = await generator.run([{ ...TEMPLATE, cadence: 'weekly', startDate: '2026-01-01' }], '2026-03-01'); + + expect(report.created).toHaveLength(2); + expect(store.invoices).toHaveLength(2); + }); +}); From 75bd544b47c8ced578e44ed734339b6d59bc9bbf Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:33 +0100 Subject: [PATCH 07/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- infra/dr/README.md | 68 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 infra/dr/README.md diff --git a/infra/dr/README.md b/infra/dr/README.md new file mode 100644 index 00000000..f505648a --- /dev/null +++ b/infra/dr/README.md @@ -0,0 +1,68 @@ +# Warm-standby disaster recovery + +This directory covers the warm-standby replica and the promotion drill. The restore-from-backup +drill is separate; see [docs/DISASTER_RECOVERY.md](../../docs/DISASTER_RECOVERY.md). + +## Topology + +- **Primary** takes all writes. +- **Warm standby** is a PostgreSQL streaming replica. It is in recovery, follows the primary, + and serves no writes. Its replay lag is the data at risk if the primary is lost. +- **Promotion** turns the standby into a writable primary. It is one-way: a promoted standby no + longer follows the old primary, so the old primary must be rebuilt as a standby afterwards. + +## Objectives + +- Lag budget: `DRILL_MAX_LAG_SECONDS` (default 30s). A standby over budget is not promoted in a drill. +- Promotion time budget: `DRILL_RTO_BUDGET_SECONDS` (default 300s). + +These are drill thresholds, not guarantees. Record measured values in the drill evidence. + +## Configuration + +Copy `replica.env.example` to a file outside the repository and fill it in. Never commit real +URLs or credentials. The example holds variable names and defaults only. + +## Running the drill + +The drill never touches the primary. It checks the standby, and only with `--execute` promotes it. + +Check only (safe; prints the plan): + +```powershell +$env:DRILL_PRIMARY_URL = "" +$env:DRILL_STANDBY_URL = "" +bash scripts/dr-drill.sh +``` + +Promote (destructive to the drill replica): + +```powershell +$env:DR_DRILL_CONFIRM = "promote-drill-replica" +bash scripts/dr-drill.sh --execute +``` + +Run promotion only against a disposable drill replica. Confirm the URL points at the drill +host before setting `DR_DRILL_CONFIRM`. + +## What the drill checks + +1. The two URLs name different databases. +2. The standby reports `pg_is_in_recovery() = true`. A non-replica is refused. +3. Replay lag is within budget. +4. With `--execute`: `pg_promote()` succeeds, the node leaves recovery, a write to a canary table + succeeds, and elapsed time is within the RTO budget. + +## Evidence to keep + +For each drill, record the date, the measured lag before promotion, the promotion time, the +canary write result, and who ran it. Attach the script output to the drill ticket. + +## Known limits + +- The drill does not measure data loss against the primary's last commit. Lag is replay lag as + seen by the standby. +- It does not reroute application traffic. DNS or connection-string failover is a separate + runbook step and is not exercised here. +- It has not been run against a live Postgres in this change. The guard behaviour is covered by + `scripts/dr-drill.test.mjs`; the promotion path needs a drill run before it is relied on. From 8b27bbc704cf36bea16df269f38b60130f922e24 Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:37 +0100 Subject: [PATCH 08/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- infra/dr/replica.env.example | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 infra/dr/replica.env.example diff --git a/infra/dr/replica.env.example b/infra/dr/replica.env.example new file mode 100644 index 00000000..b373acba --- /dev/null +++ b/infra/dr/replica.env.example @@ -0,0 +1,18 @@ +# Warm-standby promotion drill settings. Copy outside the repository and fill in. +# Never commit real URLs or credentials. + +# Primary database. Used only to confirm the standby is a different database. +DRILL_PRIMARY_URL=postgres://:@:5432/ + +# Standby to check and, with --execute, promote. Must be a disposable drill replica. +DRILL_STANDBY_URL=postgres://:@:5432/ + +# Maximum replay lag, in seconds, before the drill refuses to run. +DRILL_MAX_LAG_SECONDS=30 + +# Maximum promotion time, in seconds, before the drill reports failure. +DRILL_RTO_BUDGET_SECONDS=300 + +# Required for --execute. Set it per run, on the command line, not in this file, so a copied +# file can never promote a replica by accident. Value: promote-drill-replica +# DR_DRILL_CONFIRM= From eded1ed70e59bda52bcb97fd872646fd54e302f6 Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:42 +0100 Subject: [PATCH 09/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- scripts/dr-drill.sh | 101 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 scripts/dr-drill.sh diff --git a/scripts/dr-drill.sh b/scripts/dr-drill.sh new file mode 100644 index 00000000..2b18e8ce --- /dev/null +++ b/scripts/dr-drill.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# Warm-standby promotion drill. +# +# Checks that a streaming replica is in recovery and caught up within a lag budget. With +# --execute it promotes the replica, checks that it accepts writes, and checks the elapsed +# time against an RTO budget. Without --execute it only checks, and prints the plan. +# +# Promotion is one-way: a promoted replica no longer follows the primary. Run this only +# against a disposable drill replica, never against the live standby. See infra/dr/README.md. +# +# The restore-from-backup drill is separate: scripts/disaster-recovery-drill.sh. + +set -euo pipefail + +usage() { + cat >&2 <<'USAGE' +usage: DRILL_PRIMARY_URL=... DRILL_STANDBY_URL=... [DR_DRILL_CONFIRM=promote-drill-replica] \ + scripts/dr-drill.sh [--execute] + + DRILL_PRIMARY_URL primary database URL (used only to confirm it is a different database) + DRILL_STANDBY_URL standby database URL to check and, with --execute, promote + DRILL_MAX_LAG_SECONDS maximum replay lag allowed before the drill refuses (default 30) + DRILL_RTO_BUDGET_SECONDS maximum promotion time allowed (default 300) + DR_DRILL_CONFIRM must be exactly "promote-drill-replica" for --execute +USAGE +} + +EXECUTE=0 +case "${1:-}" in + "") ;; + --execute) EXECUTE=1 ;; + -h | --help) usage; exit 0 ;; + *) usage; exit 2 ;; +esac + +PRIMARY_URL="${DRILL_PRIMARY_URL:?DRILL_PRIMARY_URL is required}" +STANDBY_URL="${DRILL_STANDBY_URL:?DRILL_STANDBY_URL is required}" +MAX_LAG_SECONDS="${DRILL_MAX_LAG_SECONDS:-30}" +RTO_BUDGET_SECONDS="${DRILL_RTO_BUDGET_SECONDS:-300}" + +if [ "$PRIMARY_URL" = "$STANDBY_URL" ]; then + echo "Refusing promotion drill: primary and standby are the same database" >&2 + exit 1 +fi + +if [ "$EXECUTE" -eq 1 ] && [ "${DR_DRILL_CONFIRM:-}" != "promote-drill-replica" ]; then + echo "Refusing --execute: set DR_DRILL_CONFIRM=promote-drill-replica to confirm the standby is disposable" >&2 + exit 1 +fi + +if ! command -v psql >/dev/null 2>&1; then + echo "psql is required" >&2 + exit 1 +fi + +in_recovery=$(psql "$STANDBY_URL" -v ON_ERROR_STOP=1 -Atc "SELECT pg_is_in_recovery()") +if [ "$in_recovery" != "t" ]; then + echo "Standby is not in recovery, so it is not a replica. Refusing to continue." >&2 + exit 1 +fi + +# pg_last_xact_replay_timestamp() is NULL before any transaction has been replayed. An idle +# replica with no history therefore reports zero lag. +lag_seconds=$(psql "$STANDBY_URL" -v ON_ERROR_STOP=1 -Atc \ + "SELECT COALESCE(FLOOR(EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp()))::int, 0)") +if [ "$lag_seconds" -gt "$MAX_LAG_SECONDS" ]; then + echo "Replay lag is ${lag_seconds}s, above the ${MAX_LAG_SECONDS}s budget. Refusing the drill." >&2 + exit 1 +fi +echo "Standby is in recovery with replay lag ${lag_seconds}s (budget ${MAX_LAG_SECONDS}s)." + +if [ "$EXECUTE" -eq 0 ]; then + echo "Plan (not executed): promote the standby, confirm it accepts writes, and check the time against ${RTO_BUDGET_SECONDS}s." + echo "Re-run with --execute and DR_DRILL_CONFIRM=promote-drill-replica to perform it." + exit 0 +fi + +started=$(date +%s) +promoted=$(psql "$STANDBY_URL" -v ON_ERROR_STOP=1 -Atc "SELECT pg_promote(wait => true, wait_seconds => 60)") +if [ "$promoted" != "t" ]; then + echo "pg_promote did not report success" >&2 + exit 1 +fi + +still_in_recovery=$(psql "$STANDBY_URL" -v ON_ERROR_STOP=1 -Atc "SELECT pg_is_in_recovery()") +if [ "$still_in_recovery" != "f" ]; then + echo "Standby is still in recovery after promotion" >&2 + exit 1 +fi + +# Write probe: a promoted standby must accept writes. The table lives in the drill replica only. +psql "$STANDBY_URL" -v ON_ERROR_STOP=1 -q -c \ + "CREATE TABLE IF NOT EXISTS dr_drill_canary (id bigserial PRIMARY KEY, drilled_at timestamptz NOT NULL DEFAULT now()); INSERT INTO dr_drill_canary DEFAULT VALUES;" + +elapsed=$(( $(date +%s) - started )) +if [ "$elapsed" -gt "$RTO_BUDGET_SECONDS" ]; then + echo "Promotion took ${elapsed}s, above the ${RTO_BUDGET_SECONDS}s RTO budget" >&2 + exit 1 +fi + +echo "Promotion drill passed: standby promoted and writable in ${elapsed}s (budget ${RTO_BUDGET_SECONDS}s)." From 2c23f14f617766988284349b261425ef2dc99eee Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:46 +0100 Subject: [PATCH 10/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- scripts/dr-drill.test.mjs | 58 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 scripts/dr-drill.test.mjs diff --git a/scripts/dr-drill.test.mjs b/scripts/dr-drill.test.mjs new file mode 100644 index 00000000..4d1ed75f --- /dev/null +++ b/scripts/dr-drill.test.mjs @@ -0,0 +1,58 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { dirname, resolve } from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; + +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const script = resolve(repositoryRoot, 'scripts/dr-drill.sh'); + +/** + * Runs the drill with a clean environment. Every case here is a guard that refuses before any + * database call, so no Postgres is needed. + */ +function drill(args, env = {}) { + const result = spawnSync('bash', [script, ...args], { + cwd: repositoryRoot, + encoding: 'utf8', + env: { PATH: process.env.PATH, HOME: process.env.HOME ?? '', ...env }, + }); + return { status: result.status, stderr: result.stderr ?? '', stdout: result.stdout ?? '' }; +} + +const PRIMARY = 'postgres://primary.example.test/app'; +const STANDBY = 'postgres://drill-standby.example.test/app'; + +test('requires the primary and standby URLs', () => { + const result = drill([], { DRILL_STANDBY_URL: STANDBY }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /DRILL_PRIMARY_URL is required/); +}); + +test('refuses when the standby is the same database as the primary', () => { + const result = drill([], { DRILL_PRIMARY_URL: PRIMARY, DRILL_STANDBY_URL: PRIMARY }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /primary and standby are the same database/); +}); + +test('refuses --execute without the explicit confirmation', () => { + const result = drill(['--execute'], { DRILL_PRIMARY_URL: PRIMARY, DRILL_STANDBY_URL: STANDBY }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /DR_DRILL_CONFIRM=promote-drill-replica/); +}); + +test('refuses --execute when the confirmation value is wrong', () => { + const result = drill(['--execute'], { + DRILL_PRIMARY_URL: PRIMARY, + DRILL_STANDBY_URL: STANDBY, + DR_DRILL_CONFIRM: 'yes', + }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /DR_DRILL_CONFIRM=promote-drill-replica/); +}); + +test('rejects an unknown argument with usage and exit code 2', () => { + const result = drill(['--promote-now'], { DRILL_PRIMARY_URL: PRIMARY, DRILL_STANDBY_URL: STANDBY }); + assert.equal(result.status, 2); + assert.match(result.stderr, /usage:/); +}); From 934bfad9d075db65f3ad749234b1c8a6d63af74f Mon Sep 17 00:00:00 2001 From: kingdiggydoe-lab Date: Tue, 24 Nov 2026 14:49:49 +0100 Subject: [PATCH 11/11] Push notification channel, API quota ledger, recurring invoices and DR promotion drill Closes #1344 #1346 #1340 #1348 --- docs/DISASTER_RECOVERY.md | 134 ++++++++++++++++++++------------------ 1 file changed, 70 insertions(+), 64 deletions(-) diff --git a/docs/DISASTER_RECOVERY.md b/docs/DISASTER_RECOVERY.md index f725a175..e97c2d06 100644 --- a/docs/DISASTER_RECOVERY.md +++ b/docs/DISASTER_RECOVERY.md @@ -1,64 +1,70 @@ -# Disaster recovery runbook - -This runbook defines the recovery process for the AgenticPay PostgreSQL data -plane. The objectives are an RPO of one hour and an RTO of four hours. Incident -commanders must record actual recovery times and data loss in the incident log. - -## Preparation and ownership - -- Primary owner: on-call platform engineer. -- Approver for production restore: incident commander plus database owner. -- Full backups run daily; incremental backups run every six hours. Production - deployments should use WAL archiving to meet the one-hour RPO. -- Backups require SHA-256 verification before upload or restore. -- Quarterly restore drills must target an isolated database and preserve the - workflow artifact/log as evidence. - -## Incident procedure - -1. Declare the incident, freeze database migrations and payment writes, and - record the suspected corruption time. -2. Confirm whether the primary can be recovered in place. Prefer failover to a - healthy replica for infrastructure-only failures. -3. List and verify restore candidates: - - ```bash - BACKUP_DIR=/var/backups/agenticpay bash scripts/backup.sh verify - ``` - -4. Select the newest verified full backup before the incident, then either: - - ```bash - DATABASE_URL="$RECOVERY_DATABASE_URL" bash scripts/backup.sh restore /path/to/full_backup.sql.gz - DATABASE_URL="$RECOVERY_DATABASE_URL" bash scripts/backup.sh pitr '2026-09-25 10:00:00' - ``` - -5. Validate migrations, table counts, a read-only payment query, queue health, - and reconciliation totals before directing traffic to the recovered system. -6. Rotate credentials exposed during response, re-enable writes gradually, and - monitor payment failures, lag, and reconciliation mismatches. -7. Publish the achieved RPO/RTO, missing transactions, and follow-up actions. - -## Automated restore drill - -The drill refuses to run when source and target URLs are identical: - -```bash -DATABASE_URL="$SOURCE_DATABASE_URL" \ -DRILL_DATABASE_URL="$ISOLATED_DATABASE_URL" \ -BACKUP_DIR=/tmp/agenticpay-drill \ -bash scripts/disaster-recovery-drill.sh -``` - -Use the `Database Backup` workflow's `drill` dispatch option for CI evidence. -The target database is disposable; never use a production connection string as -`DRILL_DATABASE_URL`. - -## Recovery verification checklist - -- [ ] Backup gzip and SHA-256 validation passed. -- [ ] Restore used an isolated target first. -- [ ] Schema and migration state match the release being recovered. -- [ ] Payment totals reconcile against ledger/provider records. -- [ ] Background queues and webhook delivery resume without duplication. -- [ ] RPO and RTO measurements are attached to the incident. +# Disaster recovery runbook + +This runbook defines the recovery process for the AgenticPay PostgreSQL data +plane. The objectives are an RPO of one hour and an RTO of four hours. Incident +commanders must record actual recovery times and data loss in the incident log. + +## Preparation and ownership + +- Primary owner: on-call platform engineer. +- Approver for production restore: incident commander plus database owner. +- Full backups run daily; incremental backups run every six hours. Production + deployments should use WAL archiving to meet the one-hour RPO. +- Backups require SHA-256 verification before upload or restore. +- Quarterly restore drills must target an isolated database and preserve the + workflow artifact/log as evidence. + +## Incident procedure + +1. Declare the incident, freeze database migrations and payment writes, and + record the suspected corruption time. +2. Confirm whether the primary can be recovered in place. Prefer failover to a + healthy replica for infrastructure-only failures. +3. List and verify restore candidates: + + ```bash + BACKUP_DIR=/var/backups/agenticpay bash scripts/backup.sh verify + ``` + +4. Select the newest verified full backup before the incident, then either: + + ```bash + DATABASE_URL="$RECOVERY_DATABASE_URL" bash scripts/backup.sh restore /path/to/full_backup.sql.gz + DATABASE_URL="$RECOVERY_DATABASE_URL" bash scripts/backup.sh pitr '2026-09-25 10:00:00' + ``` + +5. Validate migrations, table counts, a read-only payment query, queue health, + and reconciliation totals before directing traffic to the recovered system. +6. Rotate credentials exposed during response, re-enable writes gradually, and + monitor payment failures, lag, and reconciliation mismatches. +7. Publish the achieved RPO/RTO, missing transactions, and follow-up actions. + +## Automated restore drill + +The drill refuses to run when source and target URLs are identical: + +```bash +DATABASE_URL="$SOURCE_DATABASE_URL" \ +DRILL_DATABASE_URL="$ISOLATED_DATABASE_URL" \ +BACKUP_DIR=/tmp/agenticpay-drill \ +bash scripts/disaster-recovery-drill.sh +``` + +Use the `Database Backup` workflow's `drill` dispatch option for CI evidence. +The target database is disposable; never use a production connection string as +`DRILL_DATABASE_URL`. + +## Warm-standby promotion drill + +Promotion of a streaming replica is a separate drill, covering replay lag and +time to writable. See [infra/dr/README.md](../infra/dr/README.md) and +`scripts/dr-drill.sh`. It promotes only a disposable drill replica. + +## Recovery verification checklist + +- [ ] Backup gzip and SHA-256 validation passed. +- [ ] Restore used an isolated target first. +- [ ] Schema and migration state match the release being recovered. +- [ ] Payment totals reconcile against ledger/provider records. +- [ ] Background queues and webhook delivery resume without duplication. +- [ ] RPO and RTO measurements are attached to the incident.