From 106e308031e12ab33130392a195c59956ede3f96 Mon Sep 17 00:00:00 2001 From: James Peter Date: Wed, 25 Nov 2026 11:50:31 +1000 Subject: [PATCH] Bound Nectar's minute cron reads and writes whatever history is stored An idle minute tick read 919 rows at six subscriptions and 19,542 at thirty subscriptions with a webhook endpoint (28 million rows a day against Workers Free's 5 million), and wrote 74 to 111 rows a tick (over the 100,000-a-day write limit). Invoice balances scanned every credit note, allocation and collection, the subscription observer walked every subscription twice a minute, the webhook observer re-evaluated every customer's entitlements every minute, and the dispatcher wrote a row per job per run. - Indexes that match the observers' queries (migration 0131), and a partial index so the collection runner reads only collections that can still act. - The subscription observer sweeps on a new local day, hourly, and at most every five minutes on recorded activity; source writes still record their own state in their transaction. - The webhook observer re-evaluates only customers named by new audit subjects or usage events, and sweeps on a new local day or hourly. - The dispatcher records every run but writes a job row only when the job changed something, failed or ran over two seconds, and trims history older than seven days at most a hundred runs an hour. - One read-budget test through the emitted Worker with a metered D1. Co-Authored-By: Claude Opus 5.5 --- API.md | 16 +-- management/integration/deployment-spec.json | 6 ++ .../core/0131_scheduled_read_budget.sql | 25 +++++ sources.lock.json | 18 ++-- src/nectar/automatic-collection-jobs.ts | 2 +- src/nectar/job-runs.ts | 57 +++++++--- src/nectar/observation-gate.ts | 21 ++++ src/nectar/subscription-states.ts | 19 +++- src/nectar/webhook-entitlements.ts | 60 +++++++++-- tests/nectar/cron-budget.mjs | 101 ++++++++++++++++++ tests/nectar/d1-meter.mjs | 31 ++++++ tests/nectar/harness.mjs | 7 +- tests/nectar/isolated-cases.mjs | 1 + tests/nectar/job-runs.mjs | 17 ++- 14 files changed, 333 insertions(+), 48 deletions(-) create mode 100644 migrations/core/0131_scheduled_read_budget.sql create mode 100644 src/nectar/observation-gate.ts create mode 100644 tests/nectar/cron-budget.mjs create mode 100644 tests/nectar/d1-meter.mjs diff --git a/API.md b/API.md index 68517701..d0939b2e 100644 --- a/API.md +++ b/API.md @@ -1137,18 +1137,22 @@ actual start and finish instants, status, sanitized error category and its ordered jobs. Timestamps are Unix milliseconds. Repeated or concurrent invocations of the same scheduled instant retain separate identities. -A job is `not_started` until the dispatcher reaches it, `running` during its -call, then `completed` or `failed`. A thrown failure stops the same downstream -work as before; those job rows retain null start and finish times. A returned +Every invocation is recorded; its jobs are recorded when they matter. A job +appears when it changed something (it wrote a business audit event), failed, or +ran longer than two seconds, so a quiet minute is one invocation with no jobs. +A recorded job is `running` during its call, then `completed` or `failed`. A +thrown failure stops the same downstream work as before; the jobs after it are +recorded as `not_started` with null start and finish times. A returned `status: failed` is recorded without changing the job's existing continuation behavior. Completion means that invocation returned normally: handled per-item payment, delivery or synchronization failures remain in their existing source records and are not a claim of settlement or delivery. +Invocations older than seven days are removed, a hundred at most each hour. -The dispatcher renews a heartbeat each minute and between jobs. On a later +The dispatcher renews a heartbeat each minute. On a later normal tick, an invocation with no heartbeat for thirty minutes becomes -`interrupted`; its running job becomes interrupted and downstream jobs stay -unstarted. This reports an expired execution lease, including a stopped Worker, +`interrupted`; its recorded running job becomes interrupted and downstream jobs +stay unstarted. This reports an expired execution lease, including a stopped Worker, rather than claiming to distinguish every cause of a lost heartbeat. Neither this classification nor reading history retries any work. Ordinary future ticks retain each product job's existing eligibility, authority and once-only diff --git a/management/integration/deployment-spec.json b/management/integration/deployment-spec.json index c93cd62f..33fc9242 100644 --- a/management/integration/deployment-spec.json +++ b/management/integration/deployment-spec.json @@ -816,6 +816,12 @@ "name": "core-0130_invoice_payment_schedules.sql", "sha256": "2e78f8f1939cc281e41226cbb168517b9e0cdc2fc16d1f31e82b37504bdf66af", "sql": "-- Dated instructions carry no background execution authority. The current\n-- owner must explicitly submit the accepted instruction on its exact date.\nALTER TABLE nc_invoice_partial_payments ADD COLUMN payment_kind TEXT NOT NULL DEFAULT 'card' CHECK(payment_kind IN ('card','scheduled_ach'));\nCREATE TABLE nc_invoice_schedule_authority (\n id TEXT PRIMARY KEY REFERENCES nc_invoice_partial_payments(id),\n customer_id TEXT NOT NULL REFERENCES nc_customers(id),\n portal_session_id TEXT NOT NULL REFERENCES nc_portal_sessions(id),\n basis_hash TEXT NOT NULL, accepted_at INTEGER NOT NULL\n);\nCREATE TRIGGER nc_invoice_schedule_kind_immutable BEFORE UPDATE ON nc_invoice_partial_payments\nWHEN OLD.payment_kind IS NOT NEW.payment_kind\n AND NOT EXISTS(SELECT 1 FROM nc_privacy_context)\n AND NOT EXISTS(SELECT 1 FROM rer_portability_state WHERE id=1 AND applying=1)\nBEGIN SELECT RAISE(ABORT,'nectar_immutable'); END;\n" + }, + { + "binding": "DB", + "name": "core-0131_scheduled_read_budget.sql", + "sha256": "1d6f942a12908d1949d852eda556cfbe2c794de2d2b01e18df2d0cdb409d9187", + "sql": "-- Scheduled and polled reads search by invoice and subscription instead of\n-- scanning every credit note, allocation and collection ever stored, and the\n-- observers remember when they last swept so an idle minute reads a few rows.\nCREATE INDEX nc_invoices_subscription_status ON nc_invoices(subscription_id,status,issue_date);\nCREATE INDEX nc_credit_notes_invoice ON nc_credit_notes(invoice_id);\nCREATE INDEX nc_allocations_invoice ON nc_allocations(invoice_id);\nCREATE INDEX nc_usage_credit_applications_invoice ON nc_usage_credit_applications(invoice_id);\nCREATE INDEX nc_processor_reversals_invoice ON nc_processor_reversals(invoice_id);\nCREATE INDEX nc_native_collections_invoice ON nc_native_collections(invoice_id,status);\nCREATE INDEX nc_automatic_collections_invoice ON nc_automatic_collections(invoice_id,status);\nCREATE INDEX nc_subscriptions_customer ON nc_subscriptions(customer_id,created_at);\nCREATE INDEX nc_subscription_lifecycle_subscription ON nc_subscription_lifecycle(subscription_id,seq);\n-- The collection runner reads only collections that can still act.\nCREATE INDEX nc_automatic_collection_open ON nc_automatic_collections(prepared_at,id)\n WHERE status IN ('active','claimed','uncertain','pending_settlement','refused','returned');\n-- clean_at/clean_marker: the last finished sweep. sweep_at/sweep_marker: the sweep in progress.\nALTER TABLE nc_subscription_state_cursor ADD COLUMN clean_at INTEGER;\nALTER TABLE nc_subscription_state_cursor ADD COLUMN clean_marker TEXT;\nALTER TABLE nc_subscription_state_cursor ADD COLUMN sweep_at INTEGER;\nALTER TABLE nc_subscription_state_cursor ADD COLUMN sweep_marker TEXT;\n-- swept_at: the last full pass. audit_seq/usage_rowid: the change feed already examined.\nALTER TABLE nc_webhook_observation_cursor ADD COLUMN swept_at INTEGER;\nALTER TABLE nc_webhook_observation_cursor ADD COLUMN sweep_at INTEGER;\nALTER TABLE nc_webhook_observation_cursor ADD COLUMN audit_seq INTEGER;\nALTER TABLE nc_webhook_observation_cursor ADD COLUMN usage_rowid INTEGER;\n" } ], "compatibilityDate": "2026-09-08", diff --git a/migrations/core/0131_scheduled_read_budget.sql b/migrations/core/0131_scheduled_read_budget.sql new file mode 100644 index 00000000..42902fbf --- /dev/null +++ b/migrations/core/0131_scheduled_read_budget.sql @@ -0,0 +1,25 @@ +-- Scheduled and polled reads search by invoice and subscription instead of +-- scanning every credit note, allocation and collection ever stored, and the +-- observers remember when they last swept so an idle minute reads a few rows. +CREATE INDEX nc_invoices_subscription_status ON nc_invoices(subscription_id,status,issue_date); +CREATE INDEX nc_credit_notes_invoice ON nc_credit_notes(invoice_id); +CREATE INDEX nc_allocations_invoice ON nc_allocations(invoice_id); +CREATE INDEX nc_usage_credit_applications_invoice ON nc_usage_credit_applications(invoice_id); +CREATE INDEX nc_processor_reversals_invoice ON nc_processor_reversals(invoice_id); +CREATE INDEX nc_native_collections_invoice ON nc_native_collections(invoice_id,status); +CREATE INDEX nc_automatic_collections_invoice ON nc_automatic_collections(invoice_id,status); +CREATE INDEX nc_subscriptions_customer ON nc_subscriptions(customer_id,created_at); +CREATE INDEX nc_subscription_lifecycle_subscription ON nc_subscription_lifecycle(subscription_id,seq); +-- The collection runner reads only collections that can still act. +CREATE INDEX nc_automatic_collection_open ON nc_automatic_collections(prepared_at,id) + WHERE status IN ('active','claimed','uncertain','pending_settlement','refused','returned'); +-- clean_at/clean_marker: the last finished sweep. sweep_at/sweep_marker: the sweep in progress. +ALTER TABLE nc_subscription_state_cursor ADD COLUMN clean_at INTEGER; +ALTER TABLE nc_subscription_state_cursor ADD COLUMN clean_marker TEXT; +ALTER TABLE nc_subscription_state_cursor ADD COLUMN sweep_at INTEGER; +ALTER TABLE nc_subscription_state_cursor ADD COLUMN sweep_marker TEXT; +-- swept_at: the last full pass. audit_seq/usage_rowid: the change feed already examined. +ALTER TABLE nc_webhook_observation_cursor ADD COLUMN swept_at INTEGER; +ALTER TABLE nc_webhook_observation_cursor ADD COLUMN sweep_at INTEGER; +ALTER TABLE nc_webhook_observation_cursor ADD COLUMN audit_seq INTEGER; +ALTER TABLE nc_webhook_observation_cursor ADD COLUMN usage_rowid INTEGER; diff --git a/sources.lock.json b/sources.lock.json index c5465103..25c4f2d3 100644 --- a/sources.lock.json +++ b/sources.lock.json @@ -186,7 +186,7 @@ "executable": false }, "API.md": { - "sha256": "f51773668ed0b707053ac10f6961f7fcf21f7518756e4e702037adc1c6cc85e3", + "sha256": "0e2de208114f8f84a69433708d4b655e87aeb2098d1a4eae84f077e2ad5d1bfa", "executable": false }, "base-copies.json": { @@ -382,7 +382,7 @@ "executable": false }, "management/integration/deployment-spec.json": { - "sha256": "c6ea17c8aac9b20426715360c0a256c107d15242bc5faea95eba6a7a59953ca0", + "sha256": "e24c3a68b02bc37d42f9ed3d68bdaebb77247b49f47b044c27736e81e1f21da1", "executable": false }, "migrations/core/0001_owner.sql": { @@ -3946,7 +3946,7 @@ "executable": false }, "src/nectar/automatic-collection-jobs.ts": { - "sha256": "cfe5f29e14e3b18e27b61dd855e493bcc3d71e27d12de94ffb8c2504e0ef2a24", + "sha256": "6a9a98bf81e469c4dd6b1343b84038974ab301b5a71f2d28105949d3d53fbe44", "executable": false }, "src/nectar/automatic-collection-records.ts": { @@ -4402,7 +4402,7 @@ "executable": false }, "src/nectar/job-runs.ts": { - "sha256": "a733a583562770852917ec95a47fd9c340e0e0dcf55dcca34e2a54ca421801fd", + "sha256": "342695ec1dcf7ae926aabc1ee516f82852db5463cc8c71ec68cd76f1b9645573", "executable": false }, "src/nectar/ledger-postings.ts": { @@ -5270,7 +5270,7 @@ "executable": false }, "src/nectar/subscription-states.ts": { - "sha256": "1f5b9992cf3f5da7a84f1e357eb136ee937bd5362aa3cc08ab5d332efdd9cfc1", + "sha256": "e5f398c955c4890ee89f854112ba243f82b9bdff81339e2e3d108785a53e9540", "executable": false }, "src/nectar/subscriptions.ts": { @@ -5698,7 +5698,7 @@ "executable": false }, "src/nectar/webhook-entitlements.ts": { - "sha256": "a3dd49bab3bbf8a635eed68f3f061b365a51ed5508033959624818991166e556", + "sha256": "b491c5b5a60407561a03ca33a10fc8c669101a15a5a3466cd0027de6bb03541b", "executable": false }, "src/nectar/webhook-stripe.ts": { @@ -6166,7 +6166,7 @@ "executable": false }, "tests/nectar/harness.mjs": { - "sha256": "6865663a89d3fb24c6f36f9e9701e1e40035d3b93358bb7b2a5996edfd241e3f", + "sha256": "b46c260b0bf0ae892068f8e744c31e5f00f1637b030289002e7c4f7867ac7fb9", "executable": false }, "tests/nectar/hierarchies.mjs": { @@ -6238,7 +6238,7 @@ "executable": false }, "tests/nectar/isolated-cases.mjs": { - "sha256": "f8162a33d6c2b607e10ad53230c935d1f1d8d2a8a981e0f53680c2c9fa6d6dd6", + "sha256": "10146fa7a0498e0d83785229dd5dc00cd44ed505a40ebb7a1d47beec6401ba2a", "executable": false }, "tests/nectar/isolated.mjs": { @@ -6246,7 +6246,7 @@ "executable": false }, "tests/nectar/job-runs.mjs": { - "sha256": "881c38ab6cb2926f68f9e509a75dad6915f493f80cb77316be66c5e2e8f70862", + "sha256": "575c6cc42aa936839504da5cab49210a20c3d30af26bbee26008ae2a6d630bd1", "executable": false }, "tests/nectar/journey.mjs": { diff --git a/src/nectar/automatic-collection-jobs.ts b/src/nectar/automatic-collection-jobs.ts index 2adaca64..a5913884 100644 --- a/src/nectar/automatic-collection-jobs.ts +++ b/src/nectar/automatic-collection-jobs.ts @@ -131,7 +131,7 @@ export async function collectAutomaticInvoice(env:Bindings,invoice:string){ } } export async function runAutomaticCollections(env:Bindings){ - for(const row of await all(env,"SELECT a.id,a.invoice_id,a.status FROM nc_automatic_collections a JOIN nc_invoices i ON i.id=a.invoice_id JOIN nc_customers c ON c.id=a.customer_id WHERE c.erased_at IS NULL AND i.status='issued' AND (a.status IN ('active','claimed','uncertain','pending_settlement') OR (a.status IN ('refused','returned') AND NOT EXISTS(SELECT 1 FROM nc_retry_series r WHERE r.collection_id=a.id))) ORDER BY a.prepared_at,a.id")){ + for(const row of await all(env,"SELECT a.id,a.invoice_id,a.status FROM nc_automatic_collections a JOIN nc_invoices i ON i.id=a.invoice_id JOIN nc_customers c ON c.id=a.customer_id WHERE c.erased_at IS NULL AND i.status='issued' AND a.status IN ('active','claimed','uncertain','pending_settlement','refused','returned') AND (a.status IN ('active','claimed','uncertain','pending_settlement') OR NOT EXISTS(SELECT 1 FROM nc_retry_series r WHERE r.collection_id=a.id)) ORDER BY a.prepared_at,a.id")){ if(row.status==='active')await collectAutomaticInvoice(env,row.invoice_id) else await reconcileAutomaticCollection(env,row.id) } diff --git a/src/nectar/job-runs.ts b/src/nectar/job-runs.ts index 1cf263cd..3d5f4182 100644 --- a/src/nectar/job-runs.ts +++ b/src/nectar/job-runs.ts @@ -3,10 +3,17 @@ import type { Bindings } from '../auth.server' import { requireOwner, type Actor } from './actor' import { clockInstant } from './clock' -import { newId, stmt, type Row } from './core' +import { newId, one, stmt, type Row } from './core' type Job = { name: string; run: () => Promise } +type Execution = { ordinal: number; job: string; status: string; startedAt: number | null; finishedAt: number | null; errorCode: string | null } const LEASE_MS = 30 * 60_000 +// A job still running after this long is recorded as running, so a hung job is +// visible; faster jobs are recorded only if they changed something or failed. +const SLOW_MS = 2_000 +// Dispatches kept, in minutes of the per-minute schedule (seven days). +const KEEP_DISPATCHES = 7 * 24 * 60 +const PRUNE_PER_RUN = 100 // Error text, provider results and even arbitrary typed error codes may contain // customer data. The operational door publishes only these fixed categories. @@ -16,6 +23,12 @@ function failureCode(error: unknown) { ? 'storage_failure' : 'job_failure' } +const auditMark = async (env: Bindings) => (await one(env, 'SELECT COALESCE(MAX(seq),0) seq FROM nc_audit'))!.seq as number +const record = (env: Bindings, id: string, rows: Execution[]) => rows.map(row => stmt(env, + `INSERT INTO nc_job_executions(dispatch_id,ordinal,job,status,started_at,finished_at,error_code) VALUES(?,?,?,?,?,?,?) + ON CONFLICT(dispatch_id,ordinal) DO UPDATE SET status=excluded.status,started_at=excluded.started_at,finished_at=excluded.finished_at,error_code=excluded.error_code`, + id, row.ordinal, row.job, row.status, row.startedAt, row.finishedAt, row.errorCode)) + export async function runScheduledJobs(env: Bindings, schedule: { cron: string; scheduledTime: number }, jobs: Job[]) { const id = newId(), at = clockInstant(env) // Observation writes deliberately do not create business audit events. A @@ -24,40 +37,58 @@ export async function runScheduledJobs(env: Bindings, schedule: { cron: string; stmt(env, "UPDATE nc_job_executions SET status='interrupted',finished_at=?,error_code='execution_lease_expired' WHERE status='running' AND dispatch_id IN (SELECT id FROM nc_job_dispatches WHERE status='running' AND heartbeat_at<=?)", at, at - LEASE_MS), stmt(env, "UPDATE nc_job_dispatches SET status='interrupted',finished_at=?,error_code='execution_lease_expired' WHERE status='running' AND heartbeat_at<=?", at, at - LEASE_MS), stmt(env, "INSERT INTO nc_job_dispatches(id,cron,scheduled_at,status,started_at,heartbeat_at) VALUES(?,?,?,'running',?,?)", id, schedule.cron, schedule.scheduledTime, at, at), - ...jobs.map((job, index) => stmt(env, "INSERT INTO nc_job_executions(dispatch_id,ordinal,job,status) VALUES(?,?,?,'not_started')", id, index, job.name)), ]) + // Every job's row is kept in memory and written when it matters: the job + // changed something, failed, or has been running long enough to need watching. + const rows: Execution[] = jobs.map((job, ordinal) => ({ ordinal, job: job.name, status: 'not_started', startedAt: null, finishedAt: null, errorCode: null })) + const written = new Set() + const persist = async (only: Execution[], extra: D1PreparedStatement[] = []) => { + only.forEach(row => written.add(row.ordinal)) + await env.DB.batch([...record(env, id, only), ...extra]) + } let heartbeat = Promise.resolve() const timer = setInterval(() => { heartbeat = heartbeat.then(async () => { await stmt(env, "UPDATE nc_job_dispatches SET heartbeat_at=? WHERE id=? AND status='running'", clockInstant(env), id).run() }).catch(() => { /* A missing heartbeat is recovered as an expired lease. */ }) }, 60_000) - let failed = false + let failed = false, mark = await auditMark(env) try { for (const [index, job] of jobs.entries()) { - await env.DB.batch([ - stmt(env, "UPDATE nc_job_executions SET status='running',started_at=? WHERE dispatch_id=? AND ordinal=? AND status='not_started'", clockInstant(env), id, index), - stmt(env, "UPDATE nc_job_dispatches SET heartbeat_at=? WHERE id=? AND status='running'", clockInstant(env), id), - ]) + const row = rows[index] + row.status = 'running'; row.startedAt = clockInstant(env) + let watch: ReturnType | undefined, slow = Promise.resolve() + watch = setTimeout(() => { slow = persist(rows.slice(index)).catch(() => { /* Unwritten rows are recorded when the job ends. */ }) }, SLOW_MS) try { const result = await job.run() + clearTimeout(watch); await slow // Some existing jobs report a handled failure without throwing. Keep // their established continuation behavior and report that failure too. const reportedFailure = result !== null && typeof result === 'object' && 'status' in result && result.status === 'failed' failed ||= reportedFailure - await stmt(env, "UPDATE nc_job_executions SET status=?,finished_at=?,error_code=? WHERE dispatch_id=? AND ordinal=? AND status='running'", - reportedFailure ? 'failed' : 'completed', clockInstant(env), reportedFailure ? 'job_reported_failure' : null, id, index).run() + Object.assign(row, { status: reportedFailure ? 'failed' : 'completed', finishedAt: clockInstant(env), errorCode: reportedFailure ? 'job_reported_failure' : null }) + const next = await auditMark(env), worked = next !== mark + mark = next + if (worked || reportedFailure || written.has(index)) await persist([row]) } catch (error) { + clearTimeout(watch); await slow const code = failureCode(error) - await env.DB.batch([ - stmt(env, "UPDATE nc_job_executions SET status='failed',finished_at=?,error_code=? WHERE dispatch_id=? AND ordinal=? AND status='running'", clockInstant(env), code, id, index), - stmt(env, "UPDATE nc_job_dispatches SET status='failed',finished_at=?,error_code=? WHERE id=? AND status='running'", clockInstant(env), code, id), - ]) + Object.assign(row, { status: 'failed', finishedAt: clockInstant(env), errorCode: code }) + await persist(rows.slice(index), [stmt(env, "UPDATE nc_job_dispatches SET status='failed',finished_at=?,error_code=? WHERE id=? AND status='running'", clockInstant(env), code, id)]) throw error } } await stmt(env, "UPDATE nc_job_dispatches SET status=?,finished_at=?,error_code=? WHERE id=? AND status='running'", failed ? 'failed' : 'completed', clockInstant(env), failed ? 'job_reported_failure' : null, id).run() + // History beyond a week is dropped from the oldest end, a few rows an hour, + // so clearing an old backlog never spends the day's write allowance. + if (new Date(schedule.scheduledTime).getUTCMinutes() === 0) { + const old = "SELECT seq FROM nc_job_dispatches WHERE seq<=(SELECT COALESCE(MAX(seq),0) FROM nc_job_dispatches)-? AND status<>'running' ORDER BY seq LIMIT ?" + await env.DB.batch([ + stmt(env, `DELETE FROM nc_job_executions WHERE dispatch_id IN (SELECT id FROM nc_job_dispatches WHERE seq IN (${old}))`, KEEP_DISPATCHES, PRUNE_PER_RUN), + stmt(env, `DELETE FROM nc_job_dispatches WHERE seq IN (${old})`, KEEP_DISPATCHES, PRUNE_PER_RUN), + ]) + } } finally { clearInterval(timer) await heartbeat diff --git a/src/nectar/observation-gate.ts b/src/nectar/observation-gate.ts new file mode 100644 index 00000000..09a2198f --- /dev/null +++ b/src/nectar/observation-gate.ts @@ -0,0 +1,21 @@ +// Scheduled observers watch dated facts, so most minutes they have nothing to +// learn. These gates keep an idle minute at a handful of rows: a full sweep runs +// only when the business's local day changed, an hour passed, or recorded +// activity suggests a source the commit-time capture does not cover. +import type { Bindings } from '../auth.server' +import { one } from './core' +import { localDate } from './dates' + +export const HOUR_MS = 3_600_000 +export const ACTIVITY_SWEEP_MS = 5 * 60_000 + +/** What the audit trail and usage ledger hold now; unchanged means no recorded change. */ +export async function changeMarker(env: Bindings) { + const row = (await one(env, 'SELECT (SELECT COALESCE(MAX(seq),0) FROM nc_audit) a,(SELECT COALESCE(MAX(rowid),0) FROM nc_usage_events) u'))! + return `${row.a}:${row.u}` +} + +/** True when a sweep that finished at `cleanAt` no longer covers `at`. */ +export function sweepDue(at: number, cleanAt: number | null | undefined, timezone: string) { + return cleanAt == null || at < cleanAt || at - cleanAt >= HOUR_MS || localDate(at, timezone) !== localDate(cleanAt, timezone) +} diff --git a/src/nectar/subscription-states.ts b/src/nectar/subscription-states.ts index 6cf3d6d3..d823e964 100644 --- a/src/nectar/subscription-states.ts +++ b/src/nectar/subscription-states.ts @@ -6,6 +6,7 @@ import { requireBusiness } from './business' import { clockInstant } from './clock' import { today, zonedStart } from './dates' import { entitlementState } from './entitlement-state' +import { ACTIVITY_SWEEP_MS, changeMarker, sweepDue } from './observation-gate' export async function subscriptionState(env: Bindings, sub: Row, day: string) { const input = await entitlementState(env, sub, day) @@ -22,7 +23,17 @@ export async function observeSubscriptionStates(env: Bindings) { const business = await requireBusiness(env).catch(() => null) if (!business) return const at = clockInstant(env) - const cursor = (await one(env, 'SELECT subscription_id FROM nc_subscription_state_cursor WHERE singleton=1'))!.subscription_id + const gate = (await one(env, 'SELECT subscription_id,clean_at,clean_marker,sweep_at,sweep_marker FROM nc_subscription_state_cursor WHERE singleton=1'))! + const cursor = gate.subscription_id as string + let sweepAt = gate.sweep_at as number | null, sweepMarker = gate.sweep_marker as string | null + if (cursor === '') { + // Source writes record their own state in their transaction. A new sweep is + // for dated boundaries (a new local day), the hourly safety net, and + // recorded activity at most every few minutes. + const marker = await changeMarker(env) + if (!sweepDue(at, gate.clean_at, business.timezone) && (marker === gate.clean_marker || at - gate.clean_at < ACTIVITY_SWEEP_MS)) return + sweepAt = at; sweepMarker = marker + } const rows = await all(env, `SELECT s.* FROM nc_subscriptions s JOIN nc_customers c ON c.id=s.customer_id WHERE s.billing_mode='live' AND c.status='active' AND c.erased_at IS NULL AND s.id>? ORDER BY s.id LIMIT 25`, cursor) for (const sub of rows) { @@ -71,10 +82,12 @@ export async function observeSubscriptionStates(env: Bindings) { } catch (error) { if (!(error instanceof NectarError && error.code === 'stale')) throw error // Keep the page pending so a source race is retried on the next tick. + await env.DB.prepare('UPDATE nc_subscription_state_cursor SET clean_at=NULL WHERE singleton=1').run() return } } } - await env.DB.prepare('UPDATE nc_subscription_state_cursor SET subscription_id=? WHERE singleton=1 AND subscription_id=?') - .bind(rows.length === 25 ? rows.at(-1)!.id : '', cursor).run() + const more = rows.length === 25 + await env.DB.prepare(`UPDATE nc_subscription_state_cursor SET subscription_id=?,sweep_at=?,sweep_marker=?,clean_at=${more ? 'clean_at' : '?'},clean_marker=${more ? 'clean_marker' : '?'} WHERE singleton=1 AND subscription_id=?`) + .bind(...[more ? rows.at(-1)!.id : '', sweepAt, sweepMarker, ...(more ? [] : [sweepAt, sweepMarker]), cursor]).run() } diff --git a/src/nectar/webhook-entitlements.ts b/src/nectar/webhook-entitlements.ts index 4e6c8f0f..f69f9959 100644 --- a/src/nectar/webhook-entitlements.ts +++ b/src/nectar/webhook-entitlements.ts @@ -4,6 +4,7 @@ import type { Bindings } from '../auth.server' import type { Actor } from './actor' import { all,commit,fingerprint,guard,NectarError,newId,one,parseJson,stmt,type Row } from './core' import { clockInstant } from './clock' +import { sweepDue } from './observation-gate' import { entitlements } from './entitlements' import { metadataFor,withMetadata } from './metadata' const reader:Actor={id:'system:webhooks',kind:'agent',name:'Webhook state observer',email:'',role:null,sessionId:null,capabilities:new Set(['read'])} @@ -14,17 +15,14 @@ async function eventMetadata(env: Bindings, customer: string, state: Row[]) { const prices=await all(env,'SELECT DISTINCT i.price_id FROM nc_items i JOIN nc_subscriptions s ON s.id=i.subscription_id WHERE s.customer_id=? ORDER BY i.price_id',customer) return [{kind:'customer',id:customer,...await metadataFor(env,'customer',customer)},...subscriptions,{kind:'prices',objects:await withMetadata(env,'price',prices.map(p=>({kind:'price',id:p.price_id})))}] } -export async function observeWebhookEntitlements(env: Bindings) { - if(!await one(env,'SELECT 1 FROM nc_webhook_endpoints WHERE enabled=1'))return - const cursor=(await one(env,'SELECT customer_id FROM nc_webhook_observation_cursor WHERE singleton=1'))!.customer_id - const customers=await all(env,`SELECT c.id FROM nc_customers c WHERE c.id>? AND c.erased_at IS NULL AND c.status='active' AND - (EXISTS(SELECT 1 FROM nc_webhook_entitlement_state old WHERE old.customer_id=c.id) OR EXISTS(SELECT 1 FROM nc_subscriptions s JOIN nc_items i ON i.subscription_id=s.id JOIN nc_prices p ON p.id=i.price_id JOIN nc_features f ON f.product_id=p.product_id WHERE s.customer_id=c.id)) ORDER BY c.id LIMIT 100`,cursor) - for(const customer of customers){ +// Customers whose decisions are observed: those with a stored state or any feature. +const population=`(EXISTS(SELECT 1 FROM nc_webhook_entitlement_state old WHERE old.customer_id=c.id) OR EXISTS(SELECT 1 FROM nc_subscriptions s JOIN nc_items i ON i.subscription_id=s.id JOIN nc_prices p ON p.id=i.price_id JOIN nc_features f ON f.product_id=p.product_id WHERE s.customer_id=c.id))` +async function observeCustomer(env: Bindings, customer: Row) { const generation=(await one(env,'SELECT value FROM nc_privacy_generation WHERE id=1'))!.value const decisions=await entitlements(env,reader,customer.id) const state=decisions.map(f=>({feature:f.feature,allowed:f.allowed,paths:f.paths.map((p:Row)=>({subscription:p.subscription,granted:p.granted,numericLimit:p.numericLimit??null,lifecycle:p.state?.lifecycle??null,paymentState:p.state?.payment?.status??null,warning:p.warning??false,quota:p.quota?{meter:p.quota.meter,limit:p.quota.limit,policy:p.quota.policy,exhausted:p.quota.exhausted,period:p.quota.period}:null,paymentRestricted:p.payment?.restricted??false}))})) const basis=await fingerprint(state),old=await one(env,'SELECT basis,state_json FROM nc_webhook_entitlement_state WHERE customer_id=?',customer.id) - if(old?.basis===basis)continue + if(old?.basis===basis)return const previous=parseJson(old?.state_json,[]),at=clockInstant(env),metadata=await eventMetadata(env,customer.id,state) const add=(type:string,data:unknown)=>stmt(env,'INSERT INTO nc_webhook_events(id,type,customer_id,subject,payload_json,created_at) VALUES(?,?,?,?,?,?)',newId(),type,customer.id,customer.id,JSON.stringify({type,data,metadata}),at) const events=[add('entitlements.updated',{customer_id:customer.id,features:state})] @@ -48,6 +46,52 @@ export async function observeWebhookEntitlements(env: Bindings) { try{ await commit(env,[guard(env,'stale','(SELECT value FROM nc_privacy_generation WHERE id=1)=?',generation),guard(env,'stale','(SELECT basis FROM nc_webhook_entitlement_state WHERE customer_id=?) IS ?',customer.id,old?.basis??null),...events,stmt(env,'INSERT INTO nc_webhook_entitlement_state(customer_id,basis,state_json,updated_at) VALUES(?,?,?,?) ON CONFLICT(customer_id) DO UPDATE SET basis=excluded.basis,state_json=excluded.state_json,updated_at=excluded.updated_at',customer.id,basis,JSON.stringify(state),at)],{actor:'system:webhooks',action:'webhook.entitlement.observe',subject:customer.id,detail:{events:events.length}}) }catch(error){if(!(error instanceof NectarError&&error.status===409))throw error} +} + +// Who changed since the feed position: customers named by an audit subject (the +// customer, one of its subscriptions or invoices) or by a usage event. Subjects +// that name no customer (catalogue and policy edits) wait for the next sweep. +const feedPosition = async (env: Bindings) => (await one(env, 'SELECT COALESCE(MAX(seq),0) a,(SELECT COALESCE(MAX(rowid),0) FROM nc_usage_events) u FROM nc_audit'))! +async function dirtyCustomers(env: Bindings, auditSeq: number, usageRowid: number) { + const audit = await feedPosition(env) + // A position ahead of the ledger means the ledger was restored: examine everyone. + if (audit.a < auditSeq || audit.u < usageRowid) return { audit: audit.a as number, usage: audit.u as number, customers: [] as string[], overflow: true } + if (audit.a === auditSeq && audit.u === usageRowid) return { audit: audit.a as number, usage: audit.u as number, customers: [] as string[], overflow: false } + const named = await all(env, `SELECT DISTINCT COALESCE(c.id,s.customer_id,i.customer_id) id FROM (SELECT DISTINCT subject FROM nc_audit WHERE seq>? AND seq<=? AND actor<>'system:webhooks' LIMIT 200) a + LEFT JOIN nc_customers c ON c.id=a.subject LEFT JOIN nc_subscriptions s ON s.id=a.subject LEFT JOIN nc_invoices i ON i.id=a.subject`, auditSeq, audit.a) + const used = await all(env, 'SELECT DISTINCT customer_id id FROM nc_usage_events WHERE rowid>? AND rowid<=? LIMIT 200', usageRowid, audit.u) + const ids = [...new Set([...named, ...used].map(row => row.id).filter(Boolean))] as string[] + return { audit: audit.a as number, usage: audit.u as number, customers: ids, overflow: ids.length > 100 } +} + +export async function observeWebhookEntitlements(env: Bindings) { + if(!await one(env,'SELECT 1 FROM nc_webhook_endpoints WHERE enabled=1'))return + const at=clockInstant(env),zone=(await one(env,'SELECT timezone FROM nc_business WHERE singleton=1'))?.timezone??'UTC' + const gate=(await one(env,'SELECT customer_id,swept_at,sweep_at,audit_seq,usage_rowid FROM nc_webhook_observation_cursor WHERE singleton=1'))! + const cursor=gate.customer_id as string + let sweepAt=gate.sweep_at as number|null,audit=gate.audit_seq as number|null,usage=gate.usage_rowid as number|null + if(cursor===''){ + // Only dated facts and unattributed edits need a full pass; a change to one + // customer's records re-evaluates that customer in the minute it happens. + let sweep=sweepDue(at,gate.swept_at,zone)||audit==null||usage==null + if(!sweep){ + const feed=await dirtyCustomers(env,audit!,usage!) + if(feed.overflow)sweep=true + else{ + if(feed.customers.length){ + for(const customer of await all(env,`SELECT c.id FROM nc_customers c WHERE c.id IN (SELECT value FROM json_each(?)) AND c.erased_at IS NULL AND c.status='active' AND ${population} ORDER BY c.id`,JSON.stringify(feed.customers)))await observeCustomer(env,customer) + } + if(feed.audit!==audit||feed.usage!==usage)await env.DB.prepare('UPDATE nc_webhook_observation_cursor SET audit_seq=?,usage_rowid=? WHERE singleton=1').bind(feed.audit,feed.usage).run() + return + } + } + // The feed position is taken before the first customer is read, so a change + // that lands during the sweep is examined by the minute after it. + const feed=await feedPosition(env) + sweepAt=at;audit=feed.a;usage=feed.u } - await env.DB.prepare('UPDATE nc_webhook_observation_cursor SET customer_id=? WHERE singleton=1').bind(customers.length===100?customers.at(-1)!.id:'').run() + const customers=await all(env,`SELECT c.id FROM nc_customers c WHERE c.id>? AND c.erased_at IS NULL AND c.status='active' AND ${population} ORDER BY c.id LIMIT 100`,cursor) + for(const customer of customers)await observeCustomer(env,customer) + const more=customers.length===100 + await env.DB.prepare(`UPDATE nc_webhook_observation_cursor SET customer_id=?,sweep_at=?,audit_seq=?,usage_rowid=?,swept_at=${more?'swept_at':'?'} WHERE singleton=1`).bind(...[more?customers.at(-1)!.id:'',sweepAt,audit,usage,...(more?[]:[sweepAt])]).run() } diff --git a/tests/nectar/cron-budget.mjs b/tests/nectar/cron-budget.mjs new file mode 100644 index 00000000..d9fc2b0e --- /dev/null +++ b/tests/nectar/cron-budget.mjs @@ -0,0 +1,101 @@ +// Workers Free gives every tool on an account 5,000,000 D1 rows read and 100,000 rows written a day. +// A small company's Nectar runs the minute cron 1,440 times: a quiet minute, and the hourly sweep of +// dated facts, must cost the same however long the history is. Rows are D1's own meta.rows_read and +// meta.rows_written through the emitted Worker, on thirty subscriptions with two invoices each, a webhook +// endpoint, and thirty days of dispatcher history. Ceilings are generous: a regression is a multiple. +import assert from 'node:assert/strict' +import { totp } from './mfa.mjs' + +const MINUTE = 60_000, DAY = 86_400_000 +const QUIET_READS = 150, QUIET_WRITES = 20 +const SWEEP_READS = 6_000, SWEEP_WRITES = 400 +// A day of the minute cron: 1,440 quiet minutes plus 24 sweeps, against a tenth of the free read allowance and under a third of the write one. +const DAILY_READS = 500_000, DAILY_WRITES = 30_000 + +export const harnessOptions = () => ({ + meter: true, localTime: '2026-10-01T10:00:00Z', + webhookFetch: async () => new Response(null, { status: 204 }), +}) + +const copies = [ + ['nc_customers', ['id', 'external_id', 'billing_email'], "id NOT LIKE '%-copy%'"], + ['nc_subscriptions', ['id', 'customer_id', 'external_id'], "id NOT LIKE '%-copy%'"], + ['nc_items', ['id', 'subscription_id'], "id NOT LIKE '%-copy%'"], + ['nc_invoices', ['id', 'customer_id', 'subscription_id', 'number', 'public_token'], "id NOT LIKE '%-copy%'"], +] + +export async function cronBudgetFlow(h, owner) { + const api = (path, body, status) => h.api(path, owner, body, status) + let instant = Date.parse('2026-10-01T10:00:00Z') + const tick = async (time = instant + 5 * MINUTE) => assert.equal((await h.raw(`/cdn-cgi/local/scheduled?time=${time}&cron=${encodeURIComponent('* * * * *')}`)).status, 200) + const reads = async () => { + const log = await (await h.raw('/__reads?reset=1')).json() + return { read: log.reduce((n, row) => n + row.read, 0), written: log.reduce((n, row) => n + row.written, 0), + top: Object.entries(log.reduce((by, row) => ({ ...by, [row.sql.replace(/\s+/g, ' ').slice(0, 90)]: (by[row.sql.replace(/\s+/g, ' ').slice(0, 90)] ?? 0) + row.read }), {})).sort((a, b) => b[1] - a[1]).slice(0, 3) } + } + await api('business.configure', { ...await api('business'), timezone: 'UTC' }) + const factor = await api('mfa.totp.start', {}) + await api('mfa.totp.confirm', { factor: factor.factor, code: totp(factor.secret, instant) }) + await api('webhook.register', { url: 'https://receiver.nectar-app.com/budget', consent: true }) + const product = (await api('product.create', { code: 'synthetic-nectar-budget-1', name: 'Synthetic budget plan' })).id + const price = (await api('price.create', { product, kind: 'flat', unit_amount: '100', taxable: false })).id + await api('feature.grant', { product, feature: 'synthetic-nectar-budget-feature' }) + const subscriptions = [] + for (let index = 0; index < 3; index++) { + const customer = (await api('customer.create', { external_id: `synthetic-nectar-budget-${index}`, name: `Synthetic budget customer ${index}`, billing_email: `budget-${index}@example.test` })).id + subscriptions.push((await api('subscription.create', { customer, start_date: '2026-09-01', anchor_day: 1, price: [price] })).id) + } + // Thirty days of invoices: September's issued on 1 October, October's on 1 November, through the public doors. + for (const [period, day] of [['2026-09', '2026-10-01'], ['2026-10', '2026-11-01']]) { + if (period === '2026-10') { instant = Date.parse('2026-11-01T10:00:00Z'); await h.advanceClock(new Date(instant).toISOString()); await api('mfa.verify', { code: totp(factor.secret, instant) }) } + const run = await api('billrun.prepare', { period }) + for (const { id } of (await api(`runs/${run.id}`)).invoices) { + await api('invoice.approve', { invoice: id, acknowledge: true }) + await api('invoice.finalise', { invoice: id, issue_date: day }) + } + } + // Ten copies of that book: thirty subscriptions and sixty issued invoices. + await h.db.exec('PRAGMA foreign_keys=OFF') + for (let copy = 1; copy <= 9; copy++) for (const [table, changed, where] of copies) { + const columns = (await h.db.prepare(`SELECT name FROM pragma_table_info('${table}')`).all()).results.map(row => row.name) + const select = columns.map(name => changed.includes(name) ? `${name}||'-copy${copy}'` : name).join(',') + await h.db.prepare(`INSERT INTO ${table}(${columns.join(',')}) SELECT ${select} FROM ${table} WHERE ${where}`).run() + } + assert.equal((await h.db.prepare("SELECT COUNT(*) n FROM nc_subscriptions WHERE billing_mode='live'").first()).n, 30) + assert.equal((await h.db.prepare("SELECT COUNT(*) n FROM nc_invoices WHERE status='issued'").first()).n, 60) + // Thirty days of the dispatcher's own history, as a real installation holds it. + for (let offset = 0; offset < 30 * 1440; offset += 5000) { + const last = Math.min(offset + 4999, 30 * 1440 - 1) + await h.db.prepare(`WITH RECURSIVE s(i) AS (SELECT ${offset} UNION ALL SELECT i+1 FROM s WHERE i<${last}) INSERT INTO nc_job_dispatches(id,cron,scheduled_at,status,started_at,heartbeat_at,finished_at) SELECT 'h'||i,'* * * * *',i*60000,'completed',i*60000,i*60000,i*60000+1 FROM s`).run() + } + // The first minutes settle the book: every subscription's state is observed once, every event delivered. + await tick(); await tick(); await tick() + await reads() + + await tick() + const quiet = await reads() + assert.ok(quiet.read <= QUIET_READS && quiet.written <= QUIET_WRITES, `a quiet minute read ${quiet.read} and wrote ${quiet.written} rows: ${JSON.stringify(quiet.top)}`) + + // An hour later the sweep of dated facts runs once, over every subscription and every customer's entitlements. + instant += 61 * MINUTE; await h.advanceClock(new Date(instant).toISOString()) + await tick() + const sweep = await reads() + assert.ok(sweep.read <= SWEEP_READS && sweep.written <= SWEEP_WRITES, `the hourly sweep read ${sweep.read} and wrote ${sweep.written} rows: ${JSON.stringify(sweep.top)}`) + await tick() + const after = await reads() + assert.ok(after.read <= QUIET_READS, `the minute after a sweep read ${after.read} rows: ${JSON.stringify(after.top)}`) + + const readsPerDay = quiet.read * 1440 + sweep.read * 24, writesPerDay = quiet.written * 1440 + sweep.written * 24 + assert.ok(readsPerDay <= DAILY_READS && writesPerDay <= DAILY_WRITES, `a day of the minute cron reads ${readsPerDay} and writes ${writesPerDay} rows`) + + // The next local day sweeps again; on the hour the clean-up trims the history it keeps, a few rows at a time. + instant = Date.parse('2026-11-02T10:00:00Z'); await h.advanceClock(new Date(instant).toISOString()) + await tick(); await tick(instant + 6 * MINUTE) + assert.ok((await reads()).read <= SWEEP_READS + QUIET_READS, 'the first minutes of a new day stay within the sweep ceiling') + const held = (await h.db.prepare('SELECT COUNT(*) n FROM nc_job_dispatches').first()).n + await tick(instant) + const trim = await reads() + const trimmed = held - (await h.db.prepare('SELECT COUNT(*) n FROM nc_job_dispatches').first()).n + assert.ok(trimmed > 0 && trimmed <= 100 + 1 && trim.read <= 2_000 && trim.written <= 1_000, `the hourly clean-up removed ${trimmed} dispatches, read ${trim.read} and wrote ${trim.written} rows`) + console.log(`cronBudgetFlow: a quiet minute read ${quiet.read} and wrote ${quiet.written} rows, an hourly sweep read ${sweep.read} and wrote ${sweep.written}`) +} diff --git a/tests/nectar/d1-meter.mjs b/tests/nectar/d1-meter.mjs new file mode 100644 index 00000000..0d4ccc4e --- /dev/null +++ b/tests/nectar/d1-meter.mjs @@ -0,0 +1,31 @@ +// Adds up the rows D1 reports reading and writing for every statement the Worker runs, and answers +// GET /__reads (add ?reset=1 to clear). A read-budget test wraps the emitted Worker with this module; +// production code never loads it. Local D1 reports the same meta.rows_read as hosted D1. +export const meterModule = inner => `import inner from './${inner}' +const log = [], real = new WeakMap() +const note = (sql, meta, batch) => log.push({ sql, read: meta?.rows_read ?? 0, written: meta?.rows_written ?? 0, batch }) +function wrap(sql, statement) { + const proxy = new Proxy(statement, { get(target, key) { + if (key === 'bind') return (...values) => wrap(sql, target.bind(...values)) + if (key === 'all' || key === 'run') return async (...args) => { const result = await target[key](...args); note(sql, result.meta); return result } + if (key === 'first') return async column => { const result = await target.all(); note(sql, result.meta); const row = result.results[0] ?? null; return column && row ? row[column] : row } + if (key === 'raw') return async () => { const result = await target.all(); note(sql, result.meta); return result.results.map(row => Object.values(row)) } + const value = Reflect.get(target, key); return typeof value === 'function' ? value.bind(target) : value + } }) + real.set(proxy, { sql, statement }) + return proxy +} +function counting(db) { return new Proxy(db, { get(target, key) { + if (key === 'prepare') return sql => wrap(sql, target.prepare(sql)) + if (key === 'batch') return async statements => { const results = await target.batch(statements.map(s => real.get(s)?.statement ?? s)); results.forEach((result, i) => note(real.get(statements[i])?.sql ?? '?', result.meta, true)); return results } + if (key === 'withSession') return (...args) => counting(target.withSession(...args)) + const value = Reflect.get(target, key); return typeof value === 'function' ? value.bind(target) : value +} }) } +export default { ...inner, + fetch: (request, env, ctx) => { + const url = new URL(request.url) + if (url.pathname === '/__reads') { const out = JSON.stringify(log); if (url.searchParams.get('reset')) log.length = 0; return new Response(out) } + return inner.fetch(request, { ...env, DB: counting(env.DB) }, ctx) + }, + scheduled: (event, env, ctx) => inner.scheduled(event, { ...env, DB: counting(env.DB) }, ctx) } +` diff --git a/tests/nectar/harness.mjs b/tests/nectar/harness.mjs index c2fdcbf4..c0b27338 100644 --- a/tests/nectar/harness.mjs +++ b/tests/nectar/harness.mjs @@ -7,12 +7,13 @@ import { randomBytes } from 'node:crypto' import { readFile, readdir } from 'node:fs/promises' import { createRequire } from 'node:module' import { httpListener } from './http-listener.mjs' +import { meterModule } from './d1-meter.mjs' // Wrangler's own Miniflare and SQL splitter, so the runtime matches `rer build`. const wrangler = createRequire(import.meta.url)('wrangler') const { Miniflare, convertV4MiniflareOptions } = createRequire(createRequire(import.meta.url).resolve('wrangler'))('miniflare') -export async function harness({ assets = false, localTime, wallTime = false, hostname = '127.0.0.1', stripeFetch, stripeSecret, stripeSecondarySecret, stripeWebhookSecret, quickbooksFetch, webhookFetch, persistence, databaseId='nectar', applyMigrations=true, settings={} } = {}) { +export async function harness({ assets = false, localTime, wallTime = false, hostname = '127.0.0.1', stripeFetch, stripeSecret, stripeSecondarySecret, stripeWebhookSecret, quickbooksFetch, webhookFetch, persistence, databaseId='nectar', applyMigrations=true, settings={}, meter=false } = {}) { assert.ok(!wallTime || localTime===undefined&&!('NECTAR_LOCAL_TIME' in settings),'Wall-time journeys refuse a simulated clock') const secret = () => randomBytes(32).toString('base64url') const vars = { AUTH_LOCAL: 'true', OWNER_EMAIL: 'owner@example.test', SESSION_SECRET: secret(), SETUP_TOKEN: secret(), MFA_KEY: secret(), PORTAL_KEY: secret(), MAIL_PROVIDER: 'resend', MAIL_API_KEY: 'test-only-resend-key', MAIL_FROM: 'auth@example.test' } @@ -46,7 +47,7 @@ export async function harness({ assets = false, localTime, wallTime = false, hos vars.AUTH_ORIGIN = origin const options = { // Omitting port lets workerd bind a fresh port 0 on every runtime start. - cf: false, unsafeTriggerHandlers: true, host: '127.0.0.1', modulesRoot: 'dist/server', modules: ['index.js', ...chunks].map(path => ({ type: 'ESModule', path: `dist/server/${path}` })), compatibilityDate: '2026-09-08', compatibilityFlags: ['nodejs_compat'], + cf: false, unsafeTriggerHandlers: true, host: '127.0.0.1', modulesRoot: 'dist/server', modules: [...(meter ? [{ type: 'ESModule', path: 'dist/server/d1-meter-entry.mjs', contents: meterModule('index.js') }] : []), ...['index.js', ...chunks].map(path => ({ type: 'ESModule', path: `dist/server/${path}` }))], compatibilityDate: '2026-09-08', compatibilityFlags: ['nodejs_compat'], d1Databases: { DB: databaseId }, ...(persistence?{resourcePersistencePath:persistence}:{}), bindings: vars, outboundService, ...(assets ? { assets: { directory: 'dist/client', binding: 'ASSETS', run_worker_first: true, routerConfig: { has_user_worker: true, invoke_user_worker_ahead_of_assets: true } } } : {}), } @@ -147,7 +148,7 @@ export async function harness({ assets = false, localTime, wallTime = false, hos await mf.ready db = await mf.getD1Database('DB') } - return { restart,configureMail,origin, vars, raw, api, submit, page, signIn, close, mails, mailResponses,advanceClock,rejectAudit,assertStorageExcludes, dispatch: async request => mf.dispatchFetch(request.url, { redirect: 'manual', method: request.method, headers: Object.fromEntries(request.headers), ...(!['GET','HEAD'].includes(request.method) ? { body: await request.arrayBuffer() } : {}) }) } + return { restart,configureMail,origin, vars, raw, get db() { return db }, api, submit, page, signIn, close, mails, mailResponses,advanceClock,rejectAudit,assertStorageExcludes, dispatch: async request => mf.dispatchFetch(request.url, { redirect: 'manual', method: request.method, headers: Object.fromEntries(request.headers), ...(!['GET','HEAD'].includes(request.method) ? { body: await request.arrayBuffer() } : {}) }) } } export const file = (filename, content, type = 'application/octet-stream') => ({ filename, base64: Buffer.from(content).toString('base64'), type }) diff --git a/tests/nectar/isolated-cases.mjs b/tests/nectar/isolated-cases.mjs index 50d74209..dbb86cf5 100644 --- a/tests/nectar/isolated-cases.mjs +++ b/tests/nectar/isolated-cases.mjs @@ -100,6 +100,7 @@ export const isolatedJourneys = [ { file: 'close-tieout', name: 'closeTieoutFlow', load: () => import('./close-tieout.mjs') }, { file: 'test-mode', name: 'testModeFlow', load: () => import('./test-mode.mjs') }, { file: 'job-runs', name: 'jobRunsFlow', load: () => import('./job-runs.mjs') }, + { file: 'cron-budget', name: 'cronBudgetFlow', load: () => import('./cron-budget.mjs') }, { file: 'collection-diagnosis', name: 'collectionDiagnosisFlow', load: () => import('./collection-diagnosis.mjs') }, { file: 'tax-source-report', name: 'taxSourceReportFlow', load: () => import('./tax-source-report.mjs') }, ] diff --git a/tests/nectar/job-runs.mjs b/tests/nectar/job-runs.mjs index 3a42539f..7b1c8d0f 100644 --- a/tests/nectar/job-runs.mjs +++ b/tests/nectar/job-runs.mjs @@ -85,8 +85,8 @@ export async function jobRunsFlow(h, owner) { assert.equal((await tick()).status, 200) let [first] = await read() assert.equal(first.status, 'completed') - assert.deepEqual(first.jobs.map(job => job.job), ['subscription-states-before', 'webhooks', 'payment-link-expiry', 'automatic-collections', 'payment-retries', 'invoice-automation', 'subscription-states-after-invoices']) - assert.ok(first.jobs.every(job => job.status === 'completed' && job.started_at === instant && job.finished_at === instant && job.error_code === null)) + // A quiet minute is one dispatch row: jobs that changed nothing leave no execution rows. + assert.deepEqual(first.jobs, []) assert.equal(first.cron, '* * * * *'); assert.equal(first.scheduled_at, instant) assert.equal(JSON.stringify([await api('runs'), await api('payments'), await api('audit'), h.mails.length]), before) assert.equal(writes(), 0) @@ -103,7 +103,7 @@ export async function jobRunsFlow(h, owner) { assert.deepEqual(await api('assurance-runs'), []) } finally { await h.rejectAudit() } assert.equal((await tick('0 14 * * *')).status, 200) - assert.equal((await read())[0].jobs.length, 23) + assert.deepEqual((await read())[0].jobs.map(job => [job.job, job.status]), [['assurance', 'completed']], 'only the job that changed something is recorded') assert.equal((await api('assurance-runs'))[0].status, 'completed') await h.rejectAudit('assurance.scan') @@ -112,7 +112,7 @@ export async function jobRunsFlow(h, owner) { const [reported] = await read() assert.equal(reported.status, 'failed'); assert.equal(reported.error_code, 'job_reported_failure') assert.equal(reported.jobs.find(job => job.job === 'assurance').status, 'failed') - assert.equal(reported.jobs.at(-1).status, 'completed') + assert.ok(reported.jobs.every(job => job.status !== 'not_started'), 'the run continued past the reported failure to its end') } finally { await h.rejectAudit() } const customer = (await api('customer.create', { external_id: 'synthetic-nectar-operations-1', name: 'Synthetic private customer', billing_email: email })).id @@ -144,7 +144,14 @@ export async function jobRunsFlow(h, owner) { } const scheduled = tick().catch(() => null) await Promise.race([active.entered.promise, new Promise((_, reject) => setTimeout(() => reject(new Error('collection edge did not pause')), 15000))]) - const [running] = await read() + // A job that outlasts the dispatcher's slow-job mark becomes visible as running. + let running + for (let attempts = 0; ; attempts++) { + [running] = await read() + if (running.jobs.some(job => job.job === 'automatic-collections')) break + assert.ok(attempts < 150, 'a slow job is recorded as running') + await new Promise(resolve => setTimeout(resolve, 100)) + } assert.equal(running.status, 'running') assert.equal(running.jobs.find(job => job.job === 'automatic-collections').status, 'running') assert.ok(running.jobs.slice(4).every(job => job.status === 'not_started'))