diff --git a/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md b/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md index 3c06943..8aadddc 100644 --- a/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md +++ b/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md @@ -1,5 +1,10 @@ # GitHub Release Webhook Plan +The dated phase records below describe the configuration deployed at each +milestone. For the current Mail/cleanup/reconciliation schedules, use +[Worker operations](../worker/README.md) and +[`worker/wrangler.jsonc`](../worker/wrangler.jsonc). + ## Status **Stage:** Phase E activated and first real stable publish observed @@ -57,7 +62,7 @@ webhook, redelivery, recon, and rollback. - Gates: `npm run check`, `npm test` (108 + 1 D1), `npm run build` on `origin/main` before deploy. - Secret: `GITHUB_WEBHOOK_SECRET` installed via Wrangler (not in git/Actions). -- Deploy: Worker version `52d03e76-b69a-42c8-9d63-bcb6316e33f3` on +- Deploy (2026-07-29 configuration): Worker version `52d03e76-b69a-42c8-9d63-bcb6316e33f3` on `pegma.dev/api/*` with crons `* * * * *` and `0 */6 * * *`. - Smoke: operator signed `ping` → 204; unsigned POST → 401; health `githubReleases.ingestionConfigured=true`; `GET /api/releases` schema diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index de6ba63..fa47994 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -184,7 +184,8 @@ Durable rate-limit policies (separate from Identity): - `pegma.admin.role.mutate` (assign / revoke, 30/h per operator) - `pegma.admin.principal.lookup` (directory lookups, 120/h per operator) -All four are swept by the same scheduled maintenance run. +All four are swept by the same rotating cleanup schedule, one policy per +invocation. ## Site pages @@ -198,8 +199,12 @@ All four are swept by the same scheduled maintenance run. ## Maintenance and health -Minute cron runs Support Desk queue repair and inactive projection sweep with -independent cursors, plus Support Desk rate-limit sweeps. Mail send for support +The separate cleanup cron (`1-59 * * * *`) runs one rotating task per +invocation, including Support Desk queue repair, inactive projection sweep, +and each Support/Admin rate-limit policy. Each task runs every 14–15 minutes, +with independent queue cursors and no writes for unchanged bookmarks. +Identity Mail send/reconciliation keeps its own one-minute invocation. +Mail send for support notifications is deferred (templates are defined; create/reply/staff reply omit notification for this host surface). diff --git a/docs/securityscan.md b/docs/securityscan.md index f8adab4..a49fe66 100644 --- a/docs/securityscan.md +++ b/docs/securityscan.md @@ -3,6 +3,12 @@ Point-in-time security review per the `security-scan` skill. Date: 2026-07-29. Read-only review; this report is the only file created. +Schedule descriptions below record the configuration reviewed on that date. +For the current Mail and rotating cleanup schedule, see +[Worker maintenance](../worker/README.md#identity-composition) and +[`worker/wrangler.jsonc`](../worker/wrangler.jsonc). This note does not update +or rerun the historical security assessment. + ## Phase 0 — Recon ### Stack diff --git a/worker/README.md b/worker/README.md index 3289b6e..223304e 100644 --- a/worker/README.md +++ b/worker/README.md @@ -157,11 +157,31 @@ Passkey removal stays disabled until an email-code recovery implementation is live. This deliberately avoids a last-factor lockout in the passkey-only configuration. -The one-minute Cron trigger advances independently persisted cursors for -challenge, email-operation, Mail send, Mail reconciliation, and terminal -retention scans. It also purges expired Sessions and sweeps all four durable -rate-limit policies. Replaying a cursor after a crash is safe because claims -and deletions are conditional. Dead-letter and terminal-unknown Mail remains +The one-minute Cron trigger runs Mail send and reconciliation only. A separate +`1-59 * * * *` trigger runs one cleanup lane per invocation: challenge cleanup, +email-operation repair, Mail retention, expired Sessions, each of the four +Identity rate-limit policies, Support queue repair/inactive sweep, and each of +the four Support/Admin rate-limit policies. The 14 lanes rotate using the +scheduled UTC time, including across hour boundaries, so each runs every +14–15 minutes. This gives cleanup its own invocation CPU budget instead of +combining every task under the Workers Free 10 ms limit. Authentication and +rate-limit checks still enforce expiry on access; cleanup only reclaims or +repairs stored data. + +Each run reads its cursor record once, merges successful lane results into a +single conditional update, and skips unchanged cursors (including empty +pages). Identity and Support retain independent collections and bookmarks. +The D1 adapter retries conditional updates up to three times, re-reading the +current record before merging the changed fields, including when Mail and +cleanup invocations overlap. Cursor-save failures are logged as +`identity.maintenance_failed` or `support.maintenance_failed` with task +`cursors`; the next invocation replays the page from its prior bookmark. +These bookmarks optimize scans rather than commit domain work: Mail leases, +provider idempotency keys, receipts, and conditional cleanup writes remain +durable independently of the cursor save. +Routine per-lane success logs are omitted; invocation logs and error/terminal +Mail logs remain enabled. Replaying a cursor after a crash is safe because +claims and deletions are conditional. Dead-letter and terminal-unknown Mail remains in D1 for operator inspection until explicitly acknowledged. Email delivery must remain disabled until the host also has an authenticated, audited operator acknowledgement workflow; this Worker intentionally exposes no @@ -179,7 +199,7 @@ via AccessContext defaults (not a paid entitlement). Categories: marker: `[PEG-…]`. Tracking pages: `/feedback` and `/feedback/{ticketId}`. Create and reply use durable rate limits `pegma.support.ticket.create` and -`pegma.support.ticket.reply`. Minute maintenance runs queue repair and +`pegma.support.ticket.reply`. Rotating cleanup runs queue repair and inactive projection sweep with independent cursors. Notifications on create/reply are omitted in this slice; Pegma templates are composed for a later mail activation. Health lists Support Desk package detail without @@ -240,11 +260,20 @@ webhook secret in the same maintenance window. `GITHUB_ALLOWED_REPOSITORY_IDS` (comma-separated numeric IDs). Names are display data only; IDs are the allowlist authority. -**Schedules:** `* * * * *` runs Identity maintenance only. `0 */6 * * *` runs +**Schedules:** `* * * * *` runs Identity Mail send/reconciliation. +`1-59 * * * *` runs one rotating Identity or Support cleanup lane. +`0 */6 * * *` runs GitHub release reconciliation only (public `/repos/{owner}/{repo}/releases/latest` with conditional ETags, bounded timeouts/bodies). Reconciliation is also the initial backfill path; it never fabricates `@pegma/webhooks` receipt rows. +After deploying maintenance changes, check invocation CPU times and outcomes +for both mail and cleanup triggers in Workers Observability. Local D1 tests +verify cursor writes and dispatch, but do not enforce Cloudflare's production +CPU limit. A busy mail page or large cleanup page can still require smaller +pages or Workers Paid; reducing cron frequency alone does not raise the +per-invocation allowance. + **Organization webhook (Phase E):** create one org webhook subscribed only to `release` events, payload URL `https://pegma.dev/api/webhooks/github/releases`, content type `application/json`, secret matching the Worker secret. Verify diff --git a/worker/src/identity-maintenance.test.ts b/worker/src/identity-maintenance.test.ts index 49f358e..69fd0bc 100644 --- a/worker/src/identity-maintenance.test.ts +++ b/worker/src/identity-maintenance.test.ts @@ -125,6 +125,166 @@ function fixture() { } describe('Identity maintenance', () => { + it('does no bookmark I/O or failure logging when only disabled mail tasks are selected', async () => { + const value = fixture(); + const collection = vi.spyOn(value.runtime.store, 'collection'); + await runIdentityMaintenance( + { ...value.runtime, mailWorker: null }, + value.logger, + { + tasks: ['mail_send', 'mail_reconcile', 'mail_retention'], + }, + ); + expect(collection).not.toHaveBeenCalled(); + expect(value.logger.log).not.toHaveBeenCalled(); + expect(value.sendPage).not.toHaveBeenCalled(); + expect(value.reconciliationPage).not.toHaveBeenCalled(); + expect(value.mailSweep).not.toHaveBeenCalled(); + }); + + it('logs an invalid limiter selection instead of silently skipping cleanup', async () => { + const value = fixture(); + await runIdentityMaintenance(value.runtime, value.logger, { + tasks: ['rate_limits'], + limiterIndex: 1, + }); + expect(value.limiterSweep).not.toHaveBeenCalled(); + expect(value.logger.log).toHaveBeenCalledExactlyOnceWith( + 'error', + 'identity.maintenance_failed', + { task: 'rate_limits', error: 'RangeError' }, + ); + }); + + it('identifies cursor-save failures and replays from the prior durable bookmark', async () => { + const value = fixture(); + const collection = value.runtime.store.collection; + let fail = true; + vi.spyOn(value.runtime.store, 'collection').mockImplementation( + (definition) => { + const target = collection(definition); + return { + ...target, + update: (...args) => { + if (fail) + return Promise.reject(new Error('cursor write unavailable')); + return target.update(...args); + }, + }; + }, + ); + await runIdentityMaintenance(value.runtime, value.logger, { + tasks: ['mail_send'], + }); + expect(value.logger.log).toHaveBeenCalledWith( + 'error', + 'identity.maintenance_failed', + { task: 'cursors', error: 'Error' }, + ); + fail = false; + await runIdentityMaintenance(value.runtime, value.logger, { + tasks: ['mail_send'], + }); + expect(value.sendPage).toHaveBeenNthCalledWith(2, { limit: 5 }); + await runIdentityMaintenance(value.runtime, value.logger, { + tasks: ['mail_send'], + }); + expect(value.sendPage).toHaveBeenNthCalledWith(3, { + limit: 5, + cursor: 'send-next', + }); + }); + + it('still runs cursor-independent hygiene if the bookmark read fails', async () => { + const value = fixture(); + const collection = value.runtime.store.collection; + vi.spyOn(value.runtime.store, 'collection').mockImplementation( + (definition) => { + const target = collection(definition); + return definition.name === 'pegma-dev-maintenance' + ? { + ...target, + get: async () => { + throw new Error('bookmark unavailable'); + }, + } + : target; + }, + ); + await runIdentityMaintenance(value.runtime, value.logger); + expect(value.limiterSweep).toHaveBeenCalledTimes(1); + expect(value.purgeExpired).toHaveBeenCalledTimes(1); + expect(value.challengeSweep).not.toHaveBeenCalled(); + expect(value.logger.log).toHaveBeenCalledWith( + 'error', + 'identity.maintenance_failed', + { task: 'challenges', error: 'Error' }, + ); + }); + + it('runs only mail on the minute path and does not write idle cursors', async () => { + const value = fixture(); + value.sendPage.mockResolvedValue({ + examined: 0, + results: [], + nextCursor: null, + }); + value.reconciliationPage.mockResolvedValue({ + examined: 0, + results: [], + nextCursor: null, + }); + const collection = value.runtime.store.collection; + const writes = vi.fn(); + const reads = vi.fn(); + vi.spyOn(value.runtime.store, 'collection').mockImplementation( + (definition) => { + const target = collection(definition); + return { + ...target, + get: (...args) => { + reads(); + return target.get(...args); + }, + update: (...args) => { + writes(); + return target.update(...args); + }, + }; + }, + ); + + await runIdentityMaintenance(value.runtime, value.logger, { + tasks: ['mail_send', 'mail_reconcile'], + }); + + expect(reads).toHaveBeenCalledTimes(1); + expect(writes).not.toHaveBeenCalled(); + expect(value.sendPage).toHaveBeenCalledTimes(1); + expect(value.reconciliationPage).toHaveBeenCalledTimes(1); + expect(value.challengeSweep).not.toHaveBeenCalled(); + expect(value.operationSweep).not.toHaveBeenCalled(); + expect(value.mailSweep).not.toHaveBeenCalled(); + expect(value.limiterSweep).not.toHaveBeenCalled(); + expect(value.purgeExpired).not.toHaveBeenCalled(); + expect(value.logger.log).not.toHaveBeenCalled(); + }); + + it('sweeps just the selected rate-limit policy', async () => { + const value = fixture(); + const other = { + ...value.runtime.limiters[0]!, + sweep: vi.fn(async () => ({ scanned: 0, deleted: 0 })), + }; + await runIdentityMaintenance( + { ...value.runtime, limiters: [...value.runtime.limiters, other] }, + value.logger, + { tasks: ['rate_limits'], limiterIndex: 1 }, + ); + expect(value.limiterSweep).not.toHaveBeenCalled(); + expect(other.sweep).toHaveBeenCalledTimes(1); + }); + it('persists independent cursors and runs every hygiene lane', async () => { const value = fixture(); diff --git a/worker/src/identity-maintenance.ts b/worker/src/identity-maintenance.ts index 8053d73..6e4cbcb 100644 --- a/worker/src/identity-maintenance.ts +++ b/worker/src/identity-maintenance.ts @@ -7,6 +7,7 @@ import type { Identity, MailWorker } from '@pegma/identity'; import type { DurableRateLimiter } from '@pegma/rate-limit'; import type { SessionStore } from '@pegma/sessions'; import type { Logger } from '@pegma/spine'; +import { selectMaintenanceLimiters } from './maintenance-limiters'; export interface IdentityMaintenanceRuntime { readonly store: Store; @@ -19,6 +20,23 @@ export interface IdentityMaintenanceRuntime { readonly sessions: SessionStore; } +export const IDENTITY_MAINTENANCE_TASKS = [ + 'challenges', + 'email_operations', + 'rate_limits', + 'sessions', + 'mail_send', + 'mail_reconcile', + 'mail_retention', +] as const; +export type IdentityMaintenanceTask = + (typeof IDENTITY_MAINTENANCE_TASKS)[number]; + +export interface IdentityMaintenanceOptions { + readonly tasks?: readonly IdentityMaintenanceTask[]; + readonly limiterIndex?: number; +} + interface MaintenanceRecord { readonly partition: StoredValue; readonly id: StoredValue; @@ -77,28 +95,29 @@ function emptyRecord(): MaintenanceRecord { }; } -async function readCursor( +async function saveCursors( store: Store, - name: CursorName, -): Promise { - const record = await store.collection(maintenance).get(KEY); - return record === null ? undefined : cursor(record[name]); -} - -async function saveCursor( - store: Store, - name: CursorName, - next: string | null, + changes: Partial>, ): Promise { - await store.collection(maintenance).update(KEY, (current) => ({ - action: 'write', - value: { - ...(current ?? emptyRecord()), - partition: KEY.partition, - id: KEY.id, - [name]: next, - }, - })); + if (Object.keys(changes).length === 0) return; + await store.collection(maintenance).update(KEY, (current) => { + if ( + Object.entries(changes).every( + ([name, next]) => (current?.[name as CursorName] ?? null) === next, + ) + ) { + return { action: 'keep' }; + } + return { + action: 'write', + value: { + ...(current ?? emptyRecord()), + partition: KEY.partition, + id: KEY.id, + ...changes, + }, + }; + }); } async function runTask( @@ -108,7 +127,6 @@ async function runTask( ): Promise { try { await task(); - logger.log('info', 'identity.maintenance_completed', { task: name }); } catch (error) { logger.log('error', 'identity.maintenance_failed', { task: name, @@ -120,90 +138,109 @@ async function runTask( export async function runIdentityMaintenance( runtime: IdentityMaintenanceRuntime, logger: Logger, + options: IdentityMaintenanceOptions = {}, ): Promise { - const tasks: Promise[] = [ - runTask(logger, 'challenges', async () => { - const prior = await readCursor(runtime.store, 'challengeCursor'); - const result = await runtime.identity.sweepChallenges(100, prior); - await saveCursor( - runtime.store, - 'challengeCursor', - result.hasMore ? result.cursor : null, - ); - }), - runTask(logger, 'email_operations', async () => { - const prior = await readCursor(runtime.store, 'emailOperationCursor'); - const result = await runtime.identity.sweepEmailOperations(100, prior); - await saveCursor( - runtime.store, - 'emailOperationCursor', - result.hasMore ? result.cursor : null, + // Read once and merge only successful lanes in one conditional update. The + // former five concurrent writers retried against the same cursor row. + const selected = (options.tasks ?? IDENTITY_MAINTENANCE_TASKS).filter( + (name) => runtime.mailWorker !== null || !name.startsWith('mail_'), + ); + const needsCursor = (name: IdentityMaintenanceTask) => + name !== 'sessions' && name !== 'rate_limits'; + const snapshot = selected.some(needsCursor) + ? await runtime.store + .collection(maintenance) + .get(KEY) + .then( + (value) => ({ ok: true as const, value }), + (error: unknown) => ({ ok: false as const, error }), + ) + : { ok: true as const, value: null }; + const prior = snapshot.ok ? snapshot.value : null; + const changes: Partial> = {}; + const saveCursor = (name: CursorName, next: string | null): void => { + if ((prior?.[name] ?? null) !== next) changes[name] = next; + }; + const tasks: Record Promise> = { + challenges: async () => { + const previous = cursor(prior?.challengeCursor ?? null); + const result = await runtime.identity.sweepChallenges(100, previous); + saveCursor('challengeCursor', result.hasMore ? result.cursor : null); + }, + email_operations: async () => { + const previous = cursor(prior?.emailOperationCursor ?? null); + const result = await runtime.identity.sweepEmailOperations(100, previous); + saveCursor('emailOperationCursor', result.hasMore ? result.cursor : null); + }, + rate_limits: async () => { + const limiters = selectMaintenanceLimiters( + runtime.limiters, + options.limiterIndex, ); - }), - runTask(logger, 'rate_limits', async () => { - await Promise.all(runtime.limiters.map((limiter) => limiter.sweep())); - }), - runTask(logger, 'sessions', async () => { + await Promise.all(limiters.map((limiter) => limiter.sweep())); + }, + sessions: async () => { await runtime.sessions.purgeExpired(); - }), - ]; - - const mailWorker = runtime.mailWorker; - if (mailWorker !== null) { - tasks.push( - runTask(logger, 'mail_send', async () => { - const prior = await readCursor(runtime.store, 'mailSendCursor'); - const result = await mailWorker.runSendPage({ - limit: MAIL_PROVIDER_PAGE_LIMIT, - ...(prior === undefined ? {} : { cursor: prior }), - }); - const terminal = result.results.filter( - (entry) => entry.status === 'dead_letter', - ).length; - if (terminal > 0) { - logger.log('error', 'identity.mail_terminal', { - lane: 'send', - count: terminal, - }); - } - await saveCursor(runtime.store, 'mailSendCursor', result.nextCursor); - }), - runTask(logger, 'mail_reconcile', async () => { - const prior = await readCursor(runtime.store, 'mailReconcileCursor'); - const result = await mailWorker.runReconciliationPage({ - limit: MAIL_PROVIDER_PAGE_LIMIT, - ...(prior === undefined ? {} : { cursor: prior }), + }, + mail_send: async () => { + const mailWorker = runtime.mailWorker; + if (mailWorker === null) return; + const previous = cursor(prior?.mailSendCursor ?? null); + const result = await mailWorker.runSendPage({ + limit: MAIL_PROVIDER_PAGE_LIMIT, + ...(previous === undefined ? {} : { cursor: previous }), + }); + const terminal = result.results.filter( + (entry) => entry.status === 'dead_letter', + ).length; + if (terminal > 0) { + logger.log('error', 'identity.mail_terminal', { + lane: 'send', + count: terminal, }); - const terminal = result.results.filter( - (entry) => - entry.status === 'dead_letter' || - entry.status === 'terminal_unknown', - ).length; - if (terminal > 0) { - logger.log('error', 'identity.mail_terminal', { - lane: 'reconcile', - count: terminal, - }); - } - await saveCursor( - runtime.store, - 'mailReconcileCursor', - result.nextCursor, - ); - }), - runTask(logger, 'mail_retention', async () => { - const prior = await readCursor(runtime.store, 'mailSweepCursor'); - const result = await runtime.identity.sweepMail({ - limit: 100, - ...(prior === undefined ? {} : { cursor: prior }), - terminalBefore: new Date( - Date.now() - 7 * 24 * 60 * 60_000, - ).toISOString(), + } + saveCursor('mailSendCursor', result.nextCursor); + }, + mail_reconcile: async () => { + const mailWorker = runtime.mailWorker; + if (mailWorker === null) return; + const previous = cursor(prior?.mailReconcileCursor ?? null); + const result = await mailWorker.runReconciliationPage({ + limit: MAIL_PROVIDER_PAGE_LIMIT, + ...(previous === undefined ? {} : { cursor: previous }), + }); + const terminal = result.results.filter( + (entry) => + entry.status === 'dead_letter' || entry.status === 'terminal_unknown', + ).length; + if (terminal > 0) { + logger.log('error', 'identity.mail_terminal', { + lane: 'reconcile', + count: terminal, }); - await saveCursor(runtime.store, 'mailSweepCursor', result.nextCursor); + } + saveCursor('mailReconcileCursor', result.nextCursor); + }, + mail_retention: async () => { + if (runtime.mailWorker === null) return; + const previous = cursor(prior?.mailSweepCursor ?? null); + const result = await runtime.identity.sweepMail({ + limit: 100, + ...(previous === undefined ? {} : { cursor: previous }), + terminalBefore: new Date( + Date.now() - 7 * 24 * 60 * 60_000, + ).toISOString(), + }); + saveCursor('mailSweepCursor', result.nextCursor); + }, + }; + await Promise.all( + selected.map((name) => + runTask(logger, name, async () => { + if (needsCursor(name) && !snapshot.ok) throw snapshot.error; + await tasks[name](); }), - ); - } - - await Promise.all(tasks); + ), + ); + await runTask(logger, 'cursors', () => saveCursors(runtime.store, changes)); } diff --git a/worker/src/index.ts b/worker/src/index.ts index 4eb6456..da08c65 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -39,6 +39,7 @@ import { type SupportRuntimeEnv, } from './support-desk'; import { runSupportMaintenance } from './support-maintenance'; +import { MAIL_CRON, CLEANUP_CRON, cleanupLaneAt } from './maintenance-schedule'; import { createPegmaMcpHandler } from './mcp-server'; import type { CatalogFetchEnv } from './mcp-catalog-fetch'; @@ -49,7 +50,10 @@ type AppEnv = Env & SupportRuntimeEnv & CatalogFetchEnv; -function createSupportHandler(env: AppEnv, logger: ReturnType) { +function createSupportHandler( + env: AppEnv, + logger: ReturnType, +) { const identityRuntime = createProductionIdentityRuntime(env, logger); const supportRuntime = createProductionSupportRuntime(env, { sessions: identityRuntime.sessions, @@ -368,8 +372,8 @@ export default { ctx: ExecutionContext, ): void { const logger = createAppLogger(env, (promise) => ctx.waitUntil(promise)); - // Dispatch by cron expression so six-hour release reconciliation stays - // independent of one-minute Identity maintenance. + // Each cron has its own invocation CPU budget. Never combine all cleanup + // with the time-sensitive mail path on Workers Free. if (controller.cron === RELEASE_RECONCILIATION_CRON) { ctx.waitUntil( (async () => { @@ -394,60 +398,88 @@ export default { return; } - ctx.waitUntil( - (async () => { - try { - await runIdentityMaintenance( - createProductionIdentityRuntime(env, logger), - logger, - ); - } catch (error) { - logger.log('error', 'identity.maintenance_unavailable', { - error: error instanceof Error ? error.name : 'unknown', - }); - } - })(), - ); + const cleanup = + controller.cron === CLEANUP_CRON + ? cleanupLaneAt(controller.scheduledTime) + : null; + if (controller.cron !== MAIL_CRON && cleanup === null) { + logger.log('warn', 'maintenance.unknown_cron', { cron: controller.cron }); + return; + } - ctx.waitUntil( - (async () => { - try { - const identityRuntime = createProductionIdentityRuntime(env, logger); - const supportRuntime = createProductionSupportRuntime(env, { - sessions: identityRuntime.sessions, - identity: identityRuntime.identity, - identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, - logger, - }); - await runSupportMaintenance( - { - store: supportRuntime.store, - clock: supportRuntime.clock, - // The admin mutation limiter joins the sweep: without it, - // expired pegma.admin.role.mutate counters would sit in D1 - // forever. - limiters: [ - ...supportRuntime.limiters, - createAdminMutationLimiter( - supportRuntime.store, - supportRuntime.clock, - ), - createAdminLookupLimiter( - supportRuntime.store, - supportRuntime.clock, - ), - ], - terminalRetentionMilliseconds: - supportRuntime.terminalRetentionMilliseconds, - }, - logger, - ); - } catch (error) { - logger.log('error', 'support.maintenance_unavailable', { - error: error instanceof Error ? error.name : 'unknown', - }); - } - })(), - ); + if (cleanup === null || cleanup.kind === 'identity') + ctx.waitUntil( + (async () => { + try { + await runIdentityMaintenance( + createProductionIdentityRuntime(env, logger), + logger, + cleanup === null + ? { tasks: ['mail_send', 'mail_reconcile'] } + : { + tasks: [cleanup.task], + ...(cleanup.limiterIndex === undefined + ? {} + : { limiterIndex: cleanup.limiterIndex }), + }, + ); + } catch (error) { + logger.log('error', 'identity.maintenance_unavailable', { + error: error instanceof Error ? error.name : 'unknown', + }); + } + })(), + ); + + if (cleanup?.kind === 'support') + ctx.waitUntil( + (async () => { + try { + const identityRuntime = createProductionIdentityRuntime( + env, + logger, + ); + const supportRuntime = createProductionSupportRuntime(env, { + sessions: identityRuntime.sessions, + identity: identityRuntime.identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + logger, + }); + await runSupportMaintenance( + { + store: supportRuntime.store, + clock: supportRuntime.clock, + // The admin mutation limiter joins the sweep: without it, + // expired pegma.admin.role.mutate counters would sit in D1 + // forever. + limiters: [ + ...supportRuntime.limiters, + createAdminMutationLimiter( + supportRuntime.store, + supportRuntime.clock, + ), + createAdminLookupLimiter( + supportRuntime.store, + supportRuntime.clock, + ), + ], + terminalRetentionMilliseconds: + supportRuntime.terminalRetentionMilliseconds, + }, + logger, + { + tasks: [cleanup.task], + ...(cleanup.limiterIndex === undefined + ? {} + : { limiterIndex: cleanup.limiterIndex }), + }, + ); + } catch (error) { + logger.log('error', 'support.maintenance_unavailable', { + error: error instanceof Error ? error.name : 'unknown', + }); + } + })(), + ); }, } satisfies ExportedHandler; diff --git a/worker/src/maintenance-cursors.d1.test.ts b/worker/src/maintenance-cursors.d1.test.ts new file mode 100644 index 0000000..7210b0a --- /dev/null +++ b/worker/src/maintenance-cursors.d1.test.ts @@ -0,0 +1,344 @@ +import { env } from 'cloudflare:workers'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { createSessionStore } from '@pegma/sessions'; +import { systemClock, type Logger } from '@pegma/spine'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + runIdentityMaintenance, + type IdentityMaintenanceRuntime, +} from './identity-maintenance'; +import { runSupportMaintenance } from './support-maintenance'; +import { + createIdentityRuntime, + createProductionIdentityRuntime, +} from './identity-runtime'; +import { + createProductionSupportRuntime, + createAdminMutationLimiter, + createAdminLookupLimiter, +} from './support-desk'; +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { cleanupLaneAt } from './maintenance-schedule'; + +const logger: Logger = { log: vi.fn() }; +/** Semantically matches worker/migrations/0001_pegma_storage.sql. */ +const SCHEMA_STATEMENTS = [ + `CREATE TABLE IF NOT EXISTS RECORDS ( + partition_key TEXT NOT NULL, + row_key TEXT NOT NULL, + record_json TEXT, + version INTEGER NOT NULL, + deleted INTEGER NOT NULL CHECK (deleted IN (0, 1)), + PRIMARY KEY (partition_key, row_key) +) STRICT`, + `CREATE TABLE IF NOT EXISTS PEGMA_STORAGE_D1_TX_GUARD ( + reason TEXT NOT NULL +) STRICT`, + `CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_EXISTS +BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD +WHEN NEW.reason = 'exists' +BEGIN + SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_EXISTS'); +END`, + `CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_MISSING +BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD +WHEN NEW.reason = 'missing' +BEGIN + SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_MISSING'); +END`, + `CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_CHANGED +BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD +WHEN NEW.reason = 'changed' +BEGIN + SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_CHANGED'); +END`, +] as const; + +beforeAll(async () => { + for (const statement of SCHEMA_STATEMENTS) { + await env.IDENTITY_DB.prepare(statement).run(); + } +}); +beforeEach(async () => { + vi.clearAllMocks(); + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); + +function fixture() { + const store = createCloudflareD1Store({ + database: env.IDENTITY_DB, + createSchemaIfMissing: false, + }); + const runtime: IdentityMaintenanceRuntime = { + store, + identity: { + sweepChallenges: vi.fn(async () => ({ + inspected: 0, + pulled: 0, + deleted: 0, + rejected: 0, + hasMore: true, + cursor: 'challenge-next', + })), + sweepEmailOperations: vi.fn(async () => ({ + inspected: 0, + repaired: 0, + failed: 0, + rejected: 0, + deleted: 0, + hasMore: true, + cursor: 'operation-next', + })), + sweepMail: vi.fn(async () => ({ + examined: 0, + deleted: 0, + nextCursor: 'retention-next', + more: true, + })), + }, + mailWorker: { + send: vi.fn(), + reconcile: vi.fn(), + runSendPage: vi.fn(async () => ({ + examined: 0, + results: [], + nextCursor: 'send-next', + })), + runReconciliationPage: vi.fn(async () => ({ + examined: 0, + results: [], + nextCursor: 'reconcile-next', + })), + }, + sessions: createSessionStore(store, { logger }), + limiters: [], + }; + return { store, runtime }; +} + +describe('maintenance cursor writes over D1', () => { + it('covers every limiter in the real production compositions', () => { + const identity = createProductionIdentityRuntime( + { + ...env, + IDENTITY_EMAIL_CODE_SECRET_BASE64: btoa( + String.fromCharCode(...new Uint8Array(32).fill(7)), + ), + }, + logger, + ); + const support = createProductionSupportRuntime(env, { + identity: identity.identity, + sessions: identity.sessions, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + logger, + }); + const supportLimiters = [ + ...support.limiters, + createAdminMutationLimiter(support.store), + createAdminLookupLimiter(support.store), + ]; + const lanes = Array.from({ length: 14 }, (_, index) => + cleanupLaneAt(Date.parse('2026-10-15T12:01:00Z') + index * 60_000), + ); + for (const [kind, limiters] of [ + ['identity', identity.limiters], + ['support', supportLimiters], + ] as const) { + const indices = lanes + .filter((lane) => lane.kind === kind && lane.task === 'rate_limits') + .map((lane) => lane.limiterIndex) + .sort(); + expect(indices).toEqual(limiters.map((_, index) => index)); + } + }); + + it('retries an overlapping mail/cleanup CAS conflict and preserves both sets of cursors', async () => { + const { store, runtime } = fixture(); + await runIdentityMaintenance(runtime, logger); + vi.mocked(runtime.identity.sweepChallenges).mockResolvedValue({ + inspected: 0, + pulled: 0, + deleted: 0, + rejected: 0, + hasMore: true, + cursor: 'challenge-after-overlap', + }); + vi.mocked(runtime.mailWorker!.runSendPage).mockResolvedValue({ + examined: 0, + results: [], + nextCursor: 'send-after-overlap', + }); + let decisions = 0; + let release!: () => void; + const ready = new Promise((resolve) => { + release = resolve; + }); + const collection = store.collection; + vi.spyOn(store, 'collection').mockImplementation((definition) => { + const target = collection(definition); + return { + ...target, + update: (key, decide, options) => + target.update( + key, + async (current) => { + decisions++; + if (decisions === 2) release(); + if (decisions <= 2) await ready; + return decide(current); + }, + options, + ), + }; + }); + await Promise.all([ + runIdentityMaintenance(runtime, logger, { + tasks: ['mail_send', 'mail_reconcile'], + }), + runIdentityMaintenance(runtime, logger, { tasks: ['challenges'] }), + ]); + expect(decisions).toBe(3); + const row = await env.IDENTITY_DB.prepare( + "SELECT record_json, version FROM RECORDS WHERE partition_key = 'pegma-dev-maintenance:identity'", + ).first<{ record_json: string; version: number }>(); + expect(row?.version).toBe(3); + expect(JSON.parse(row!.record_json)).toMatchObject({ + mailSendCursor: 'send-after-overlap', + challengeCursor: 'challenge-after-overlap', + mailReconcileCursor: 'reconcile-next', + }); + expect(logger.log).not.toHaveBeenCalledWith( + 'error', + expect.anything(), + expect.anything(), + ); + }); + + it('keeps the real published mail workers idle without writes or provider calls', async () => { + const { store } = fixture(); + const send = vi.fn(async () => { + throw new Error('unexpected send'); + }); + const reconcile = vi.fn(async () => { + throw new Error('unexpected reconciliation'); + }); + const runtime = createIdentityRuntime( + { + store, + emailCodeSecretBase64: btoa( + String.fromCharCode(...new Uint8Array(32).fill(7)), + ), + emailFrom: 'Pegma ', + emailEnabled: true, + mailDelivery: { + provider: { send }, + reconciliation: { reconcile }, + classifyFailure: () => 'unavailable', + }, + }, + logger, + ); + for (let tick = 0; tick < 2; tick++) { + await runIdentityMaintenance(runtime, logger, { + tasks: ['mail_send', 'mail_reconcile'], + }); + } + expect( + await env.IDENTITY_DB.prepare( + 'SELECT COUNT(*) AS count FROM RECORDS', + ).first('count'), + ).toBe(0); + expect(send).not.toHaveBeenCalled(); + expect(reconcile).not.toHaveBeenCalled(); + expect(logger.log).not.toHaveBeenCalled(); + }); + + it('merges five simultaneous lane results in one write and skips unchanged bookmarks', async () => { + const { runtime } = fixture(); + await runIdentityMaintenance(runtime, logger); + const read = () => + env.IDENTITY_DB.prepare( + "SELECT record_json, version FROM RECORDS WHERE partition_key = 'pegma-dev-maintenance:identity'", + ).first<{ record_json: string; version: number }>(); + const first = await read(); + expect(first?.version).toBe(1); + expect(JSON.parse(first!.record_json)).toMatchObject({ + challengeCursor: 'challenge-next', + emailOperationCursor: 'operation-next', + mailSendCursor: 'send-next', + mailReconcileCursor: 'reconcile-next', + mailSweepCursor: 'retention-next', + }); + await runIdentityMaintenance(runtime, logger); + expect(await read()).toEqual(first); + expect(logger.log).not.toHaveBeenCalledWith( + 'error', + expect.anything(), + expect.anything(), + ); + }); + + it('preserves failed and unselected lanes while advancing successful mail cursors', async () => { + const { runtime } = fixture(); + await runIdentityMaintenance(runtime, logger); + vi.mocked(runtime.mailWorker!.runSendPage).mockResolvedValue({ + examined: 0, + results: [], + nextCursor: null, + }); + vi.mocked(runtime.mailWorker!.runReconciliationPage).mockRejectedValue( + new Error('provider unavailable'), + ); + await runIdentityMaintenance(runtime, logger, { + tasks: ['mail_send', 'mail_reconcile'], + }); + const row = await env.IDENTITY_DB.prepare( + "SELECT record_json, version FROM RECORDS WHERE partition_key = 'pegma-dev-maintenance:identity'", + ).first<{ record_json: string; version: number }>(); + expect(row?.version).toBe(2); + expect(JSON.parse(row!.record_json)).toMatchObject({ + mailSendCursor: null, + mailReconcileCursor: 'reconcile-next', + challengeCursor: 'challenge-next', + emailOperationCursor: 'operation-next', + mailSweepCursor: 'retention-next', + }); + }); + + it('does not create or rewrite support bookmarks for empty queue pages', async () => { + const { store } = fixture(); + const run = () => + runSupportMaintenance( + { store, clock: systemClock, limiters: [] }, + logger, + ); + await run(); + expect( + await env.IDENTITY_DB.prepare( + 'SELECT COUNT(*) AS count FROM RECORDS', + ).first('count'), + ).toBe(0); + const record = JSON.stringify({ + partition: 'support-desk', + id: 'maintenance', + queueRepairCursor: null, + queueInactiveSweepCursor: null, + }); + await env.IDENTITY_DB.prepare('INSERT INTO RECORDS VALUES (?, ?, ?, 7, 0)') + .bind('pegma-dev-support-maintenance:support-desk', 'maintenance', record) + .run(); + await run(); + expect( + await env.IDENTITY_DB.prepare('SELECT version FROM RECORDS').first( + 'version', + ), + ).toBe(7); + expect(logger.log).not.toHaveBeenCalledWith( + 'error', + expect.anything(), + expect.anything(), + ); + }); +}); diff --git a/worker/src/maintenance-limiters.test.ts b/worker/src/maintenance-limiters.test.ts new file mode 100644 index 0000000..98d03d6 --- /dev/null +++ b/worker/src/maintenance-limiters.test.ts @@ -0,0 +1,28 @@ +import { createMemoryStore } from '@pegma/storage-core'; +import { createDurableLimiter, defineRateLimitPolicy } from '@pegma/rate-limit'; +import { describe, expect, it } from 'vitest'; +import { selectMaintenanceLimiters } from './maintenance-limiters'; + +const store = createMemoryStore(); +const limiters = [0, 1].map((index) => + createDurableLimiter( + defineRateLimitPolicy({ + name: `maintenance-test-${index}`, + limit: 1, + windowMs: 60_000, + }), + store, + ), +); + +describe('maintenance limiter selection', () => { + it('selects one policy or the full set explicitly', () => { + expect(selectMaintenanceLimiters(limiters, undefined)).toBe(limiters); + expect(selectMaintenanceLimiters(limiters, 1)).toEqual([limiters[1]]); + }); + it.each([-1, 0.5, 2, NaN, Infinity])('rejects invalid index %s', (index) => { + expect(() => selectMaintenanceLimiters(limiters, index)).toThrow( + RangeError, + ); + }); +}); diff --git a/worker/src/maintenance-limiters.ts b/worker/src/maintenance-limiters.ts new file mode 100644 index 0000000..8da7b5f --- /dev/null +++ b/worker/src/maintenance-limiters.ts @@ -0,0 +1,13 @@ +import type { DurableRateLimiter } from '@pegma/rate-limit'; + +/** Reject schedule/runtime drift instead of silently skipping a policy. */ +export function selectMaintenanceLimiters( + limiters: readonly DurableRateLimiter[], + index: number | undefined, +): readonly DurableRateLimiter[] { + if (index === undefined) return limiters; + if (!Number.isInteger(index) || index < 0 || index >= limiters.length) { + throw new RangeError('Maintenance limiter index is out of range.'); + } + return [limiters[index]!]; +} diff --git a/worker/src/maintenance-schedule.test.ts b/worker/src/maintenance-schedule.test.ts new file mode 100644 index 0000000..6676bbe --- /dev/null +++ b/worker/src/maintenance-schedule.test.ts @@ -0,0 +1,150 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { MAIL_CRON, CLEANUP_CRON, cleanupLaneAt } from './maintenance-schedule'; +import { + RELEASE_RECONCILIATION_CRON, + runReleaseReconciliation, +} from './release-reconciliation'; +import { runIdentityMaintenance } from './identity-maintenance'; +import { runSupportMaintenance } from './support-maintenance'; +import worker from './index'; + +vi.mock('./identity-maintenance', () => ({ runIdentityMaintenance: vi.fn() })); +vi.mock('./support-maintenance', () => ({ runSupportMaintenance: vi.fn() })); +vi.mock('./logger', () => ({ createAppLogger: () => ({ log: vi.fn() }) })); +vi.mock('./identity-runtime', () => ({ + createProductionIdentityRuntime: () => ({ sessions: {}, identity: {} }), +})); +vi.mock('./support-desk', () => ({ + createProductionSupportRuntime: () => ({ + store: {}, + clock: {}, + limiters: [{}, {}], + terminalRetentionMilliseconds: 1, + }), + createAdminMutationLimiter: () => ({}), + createAdminLookupLimiter: () => ({}), +})); +vi.mock('./github-release-webhook', () => ({ + createProductionStore: () => ({}), +})); +vi.mock('./releases-api', () => ({ readReleasesConfig: () => ({}) })); +vi.mock('./release-reconciliation', async (original) => ({ + ...(await original()), + runReleaseReconciliation: vi.fn(), +})); + +async function scheduled(cron: string, time: number) { + const pending: Promise[] = []; + worker.scheduled( + { cron, scheduledTime: time, noRetry() {} }, + {} as Parameters[1], + { + waitUntil: (promise: Promise) => { + pending.push(promise); + }, + passThroughOnException() {}, + props: {}, + exports: {}, + } as ExecutionContext, + ); + await Promise.all(pending); +} + +describe('maintenance dispatch', () => { + beforeEach(() => vi.clearAllMocks()); + + it('returns a lane at minute zero and for timestamps around the Unix epoch', () => { + for (const time of [ + -60_000, + 0, + 60_000, + Date.parse('2026-10-15T12:00:00Z'), + ]) { + expect(cleanupLaneAt(time)).toEqual( + expect.objectContaining({ + kind: expect.stringMatching(/^(identity|support)$/), + }), + ); + } + expect(cleanupLaneAt(Date.parse('2026-10-15T12:00:00Z'))).toEqual( + cleanupLaneAt(Date.parse('2026-10-15T11:59:00Z')), + ); + }); + + it('keeps the deployed cron expressions aligned with the dispatcher', () => { + const config = readFileSync( + new URL('../wrangler.jsonc', import.meta.url), + 'utf8', + ); + const crons = JSON.parse(config.match(/"crons":\s*(\[[^\]]*\])/)![1]!); + expect(crons).toEqual([ + MAIL_CRON, + CLEANUP_CRON, + RELEASE_RECONCILIATION_CRON, + ]); + }); + + it('keeps mail minute-by-minute without running cleanup or releases', async () => { + await scheduled(MAIL_CRON, Date.parse('2026-10-15T12:00:00Z')); + expect(runIdentityMaintenance).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.anything(), + { tasks: ['mail_send', 'mail_reconcile'] }, + ); + expect(runSupportMaintenance).not.toHaveBeenCalled(); + expect(runReleaseReconciliation).not.toHaveBeenCalled(); + }); + + it('covers all 14 cleanup lanes once across a UTC day boundary', async () => { + const lanes = []; + const start = Date.parse('2026-10-15T23:53:00Z'); + for (let minute = 0; minute < 15; minute++) { + const time = start + minute * 60_000; + if (new Date(time).getUTCMinutes() === 0) continue; + const lane = cleanupLaneAt(time); + lanes.push(JSON.stringify(lane)); + vi.clearAllMocks(); + await scheduled(CLEANUP_CRON, time); + const selected = + lane.kind === 'identity' + ? runIdentityMaintenance + : runSupportMaintenance; + const other = + lane.kind === 'identity' + ? runSupportMaintenance + : runIdentityMaintenance; + expect(selected).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.anything(), + { + tasks: [lane.task], + ...(lane.limiterIndex === undefined + ? {} + : { limiterIndex: lane.limiterIndex }), + }, + ); + expect(other).not.toHaveBeenCalled(); + expect(runReleaseReconciliation).not.toHaveBeenCalled(); + } + expect(new Set(lanes).size).toBe(14); + for (const kind of ['identity', 'support']) { + for (let limiterIndex = 0; limiterIndex < 4; limiterIndex++) { + expect(lanes).toContain( + JSON.stringify({ kind, task: 'rate_limits', limiterIndex }), + ); + } + } + }); + + it('runs only release reconciliation on its own cron and ignores unknown crons', async () => { + await scheduled( + RELEASE_RECONCILIATION_CRON, + Date.parse('2026-10-15T12:00:00Z'), + ); + await scheduled('unknown', Date.parse('2026-10-15T12:00:00Z')); + expect(runReleaseReconciliation).toHaveBeenCalledTimes(1); + expect(runIdentityMaintenance).not.toHaveBeenCalled(); + expect(runSupportMaintenance).not.toHaveBeenCalled(); + }); +}); diff --git a/worker/src/maintenance-schedule.ts b/worker/src/maintenance-schedule.ts new file mode 100644 index 0000000..a03917f --- /dev/null +++ b/worker/src/maintenance-schedule.ts @@ -0,0 +1,47 @@ +import type { IdentityMaintenanceTask } from './identity-maintenance'; +import type { SupportMaintenanceTask } from './support-maintenance'; + +export const MAIL_CRON = '* * * * *'; +// A separate invocation gives cleanup its own CPU allowance. Skip minute zero +// (also used by release reconciliation), while rotating through 14 small lanes. +export const CLEANUP_CRON = '1-59 * * * *'; + +type CleanupLane = + | { + readonly kind: 'identity'; + readonly task: IdentityMaintenanceTask; + readonly limiterIndex?: number; + } + | { + readonly kind: 'support'; + readonly task: SupportMaintenanceTask; + readonly limiterIndex?: number; + }; + +const CLEANUP_LANES: readonly CleanupLane[] = [ + { kind: 'identity', task: 'challenges' }, + { kind: 'identity', task: 'email_operations' }, + { kind: 'identity', task: 'mail_retention' }, + { kind: 'identity', task: 'sessions' }, + ...[0, 1, 2, 3].map((limiterIndex) => ({ + kind: 'identity' as const, + task: 'rate_limits' as const, + limiterIndex, + })), + { kind: 'support', task: 'queue_repair' }, + { kind: 'support', task: 'queue_inactive_sweep' }, + ...[0, 1, 2, 3].map((limiterIndex) => ({ + kind: 'support' as const, + task: 'rate_limits' as const, + limiterIndex, + })), +]; + +/** Deterministic across cold starts, delayed delivery, and UTC hour boundaries. */ +export function cleanupLaneAt(scheduledTime: number): CleanupLane { + const minute = Math.floor(scheduledTime / 60_000); + // Count only eligible minutes so skipping minute zero never skips a lane. + const tick = minute - Math.floor(minute / 60) - 1; + const length = CLEANUP_LANES.length; + return CLEANUP_LANES[((tick % length) + length) % length]!; +} diff --git a/worker/src/support-api.test.ts b/worker/src/support-api.test.ts index a3b21ac..70640be 100644 --- a/worker/src/support-api.test.ts +++ b/worker/src/support-api.test.ts @@ -488,6 +488,69 @@ describe('support error mapping', () => { }); describe('support maintenance cursors', () => { + it('logs invalid limiter selections and still sweeps policies when bookmark reads fail', async () => { + const { store, runtime } = fixture(); + const log = { log: vi.fn() }; + const sweeps = runtime.limiters.map((limiter) => + vi.spyOn(limiter, 'sweep'), + ); + await runSupportMaintenance( + { store, clock, limiters: runtime.limiters }, + log, + { tasks: ['rate_limits'], limiterIndex: runtime.limiters.length }, + ); + expect(log.log).toHaveBeenCalledExactlyOnceWith( + 'error', + 'support.maintenance_failed', + { task: 'rate_limits', error: 'RangeError' }, + ); + log.log.mockClear(); + const collection = store.collection; + vi.spyOn(store, 'collection').mockImplementation((definition) => { + const target = collection(definition); + return definition.name === 'pegma-dev-support-maintenance' + ? { + ...target, + get: async () => { + throw new Error('bookmark unavailable'); + }, + } + : target; + }); + await runSupportMaintenance( + { store, clock, limiters: runtime.limiters }, + log, + ); + for (const sweep of sweeps) expect(sweep).toHaveBeenCalledTimes(1); + for (const task of ['queue_repair', 'queue_inactive_sweep']) { + expect(log.log).toHaveBeenCalledWith( + 'error', + 'support.maintenance_failed', + { task, error: 'Error' }, + ); + } + }); + + it('sweeps only the selected support policy without reading queue bookmarks', async () => { + const { store, runtime } = fixture(); + const sweeps = runtime.limiters.map((limiter) => + vi.spyOn(limiter, 'sweep'), + ); + const collection = vi.spyOn(store, 'collection'); + await runSupportMaintenance( + { store, clock, limiters: runtime.limiters }, + logger, + { tasks: ['rate_limits'], limiterIndex: 1 }, + ); + expect(sweeps[0]).not.toHaveBeenCalled(); + expect(sweeps[1]).toHaveBeenCalledTimes(1); + expect( + collection.mock.calls.some( + ([definition]) => definition.name === 'pegma-dev-support-maintenance', + ), + ).toBe(false); + }); + it('persists independent queue cursors and runs repair/sweep', async () => { const { store, runtime } = fixture(); await saveSupportCursor(store, 'queueRepairCursor', 'cursor-repair-1'); diff --git a/worker/src/support-cursors.ts b/worker/src/support-cursors.ts index b6d6c45..5598886 100644 --- a/worker/src/support-cursors.ts +++ b/worker/src/support-cursors.ts @@ -13,8 +13,7 @@ import { * bookmarks. */ export type SupportCursorName = - | 'queueRepairCursor' - | 'queueInactiveSweepCursor'; + 'queueRepairCursor' | 'queueInactiveSweepCursor'; interface SupportMaintenanceRecord { readonly partition: StoredValue; @@ -63,18 +62,42 @@ export async function readSupportCursor( return record === null ? undefined : cursor(record[name]); } +export async function readSupportCursors( + store: Store, +): Promise { + return store.collection(maintenance).get(KEY); +} + +export async function saveSupportCursors( + store: Store, + changes: Partial>, +): Promise { + if (Object.keys(changes).length === 0) return; + await store.collection(maintenance).update(KEY, (current) => { + if ( + Object.entries(changes).every( + ([name, next]) => + (current?.[name as SupportCursorName] ?? null) === next, + ) + ) { + return { action: 'keep' }; + } + return { + action: 'write', + value: { + ...(current ?? emptyRecord()), + ...changes, + partition: KEY.partition, + id: KEY.id, + }, + }; + }); +} + export async function saveSupportCursor( store: Store, name: SupportCursorName, next: string | null, ): Promise { - await store.collection(maintenance).update(KEY, (current) => ({ - action: 'write', - value: { - ...(current ?? emptyRecord()), - partition: KEY.partition, - id: KEY.id, - [name]: next, - }, - })); + await saveSupportCursors(store, { [name]: next }); } diff --git a/worker/src/support-maintenance.ts b/worker/src/support-maintenance.ts index 5eb9d22..4263fe2 100644 --- a/worker/src/support-maintenance.ts +++ b/worker/src/support-maintenance.ts @@ -5,8 +5,13 @@ import { import type { DurableRateLimiter } from '@pegma/rate-limit'; import type { Clock, Logger } from '@pegma/spine'; import type { Store } from '@pegma/storage-core'; -import { readSupportCursor, saveSupportCursor } from './support-cursors'; +import { + readSupportCursors, + saveSupportCursors, + type SupportCursorName, +} from './support-cursors'; import { SUPPORT_TERMINAL_RETENTION_MS } from './support-desk'; +import { selectMaintenanceLimiters } from './maintenance-limiters'; export interface SupportMaintenanceRuntime { readonly store: Store; @@ -17,6 +22,17 @@ export interface SupportMaintenanceRuntime { const PAGE_LIMIT = 50; +export const SUPPORT_MAINTENANCE_TASKS = [ + 'queue_repair', + 'queue_inactive_sweep', + 'rate_limits', +] as const; +export type SupportMaintenanceTask = (typeof SUPPORT_MAINTENANCE_TASKS)[number]; +export interface SupportMaintenanceOptions { + readonly tasks?: readonly SupportMaintenanceTask[]; + readonly limiterIndex?: number; +} + async function runTask( logger: Logger, name: string, @@ -24,7 +40,6 @@ async function runTask( ): Promise { try { await task(); - logger.log('info', 'support.maintenance_completed', { task: name }); } catch (error) { logger.log('error', 'support.maintenance_failed', { task: name, @@ -40,48 +55,68 @@ async function runTask( export async function runSupportMaintenance( runtime: SupportMaintenanceRuntime, logger: Logger, + options: SupportMaintenanceOptions = {}, ): Promise { const terminalRetentionMilliseconds = runtime.terminalRetentionMilliseconds ?? SUPPORT_TERMINAL_RETENTION_MS; - const tasks: Promise[] = [ - runTask(logger, 'queue_repair', async () => { - const prior = await readSupportCursor(runtime.store, 'queueRepairCursor'); + const selected = options.tasks ?? SUPPORT_MAINTENANCE_TASKS; + const snapshot = selected.some((name) => name !== 'rate_limits') + ? await readSupportCursors(runtime.store).then( + (value) => ({ ok: true as const, value }), + (error: unknown) => ({ ok: false as const, error }), + ) + : { ok: true as const, value: null }; + const prior = snapshot.ok ? snapshot.value : null; + const changes: Partial> = {}; + const previous = (name: SupportCursorName): string | undefined => + typeof prior?.[name] === 'string' && prior[name].length <= 8_192 + ? prior[name] + : undefined; + const save = (name: SupportCursorName, next: string | null): void => { + if ((prior?.[name] ?? null) !== next) changes[name] = next; + }; + const tasks: Record Promise> = { + queue_repair: async () => { + const cursor = previous('queueRepairCursor'); const result = await repairQueueProjectionPage({ store: runtime.store, clock: runtime.clock, terminalRetentionMilliseconds, limit: PAGE_LIMIT, - ...(prior === undefined ? {} : { cursor: prior }), + ...(cursor === undefined ? {} : { cursor }), }); - await saveSupportCursor( - runtime.store, - 'queueRepairCursor', - result.nextCursor, - ); - }), - runTask(logger, 'queue_inactive_sweep', async () => { - const prior = await readSupportCursor( - runtime.store, - 'queueInactiveSweepCursor', - ); + save('queueRepairCursor', result.nextCursor); + }, + queue_inactive_sweep: async () => { + const cursor = previous('queueInactiveSweepCursor'); const result = await sweepInactiveQueueProjections({ store: runtime.store, clock: runtime.clock, terminalRetentionMilliseconds, limit: PAGE_LIMIT, - ...(prior === undefined ? {} : { cursor: prior }), + ...(cursor === undefined ? {} : { cursor }), }); - await saveSupportCursor( - runtime.store, - 'queueInactiveSweepCursor', - result.nextCursor, + save('queueInactiveSweepCursor', result.nextCursor); + }, + rate_limits: async () => { + const limiters = selectMaintenanceLimiters( + runtime.limiters, + options.limiterIndex, ); - }), - runTask(logger, 'rate_limits', async () => { - await Promise.all(runtime.limiters.map((limiter) => limiter.sweep())); - }), - ]; + await Promise.all(limiters.map((limiter) => limiter.sweep())); + }, + }; - await Promise.all(tasks); + await Promise.all( + selected.map((name) => + runTask(logger, name, async () => { + if (name !== 'rate_limits' && !snapshot.ok) throw snapshot.error; + await tasks[name](); + }), + ), + ); + await runTask(logger, 'cursors', () => + saveSupportCursors(runtime.store, changes), + ); } diff --git a/worker/worker-configuration.d.ts b/worker/worker-configuration.d.ts index 416f64c..b6c0128 100644 --- a/worker/worker-configuration.d.ts +++ b/worker/worker-configuration.d.ts @@ -1,10 +1,12 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types --config=worker/wrangler.jsonc worker/worker-configuration.d.ts` (hash: 75d6aad1ee166f4faa6212c745e3d48e) +// Generated by Wrangler by running `wrangler types --config=worker/wrangler.jsonc worker/worker-configuration.d.ts` (hash: 077dc894d6ddafa61f2fb71a1426732c) // Runtime types generated with workerd@1.20260722.1 2026-07-28 nodejs_compat interface __BaseEnv_Env { IDENTITY_DB: D1Database; IDENTITY_EMAIL_FROM: "Pegma "; IDENTITY_EMAIL_ENABLED: "true"; + GITHUB_ORGANIZATION_ID: "309286193"; + GITHUB_ALLOWED_REPOSITORY_IDS: "1312512520,1312519623,1312811498,1312961609,1312942188,1313911960,1313917945,1314116350,1314093835,1313927900,1314239450,1314421283,1313936481"; } declare namespace Cloudflare { interface GlobalProps { @@ -17,7 +19,7 @@ type StringifyValues> = { [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; }; declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} + interface ProcessEnv extends StringifyValues> {} } // Begin runtime types diff --git a/worker/wrangler.jsonc b/worker/wrangler.jsonc index 9f8f309..b41f37d 100644 --- a/worker/wrangler.jsonc +++ b/worker/wrangler.jsonc @@ -19,8 +19,8 @@ "GITHUB_ALLOWED_REPOSITORY_IDS": "1312512520,1312519623,1312811498,1312961609,1312942188,1313911960,1313917945,1314116350,1314093835,1313927900,1314239450,1314421283,1313936481", }, "triggers": { - // Minute Identity maintenance; six-hour GitHub release reconciliation. - "crons": ["* * * * *", "0 */6 * * *"], + // Minute mail delivery; one cleanup lane per nonzero minute; six-hour releases. + "crons": ["* * * * *", "1-59 * * * *", "0 */6 * * *"], }, "d1_databases": [ {