Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 40 additions & 16 deletions worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,16 +157,21 @@ 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 runs Mail send and reconciliation only. A separate
`1-59 * * * *` trigger runs one cleanup lane per invocation: challenge cleanup,
Separate Cron triggers run Mail send every minute and reconciliation every
minute except minute zero (at most a two-minute reconciliation gap). Each
invocation processes at most one operation, retaining its own scan cursor.
Idle runs do not import an unused HMAC key; secret validation remains eager. A separate
`0-58 * * * *` 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.
repairs stored data. Paged Identity and Support cleanup also consumes at most
one record per invocation. Support cleanup composes only storage, its clock,
and limiters; it does not build Identity, roles, or HTTP handlers.

Each run reads its cursor record once, merges successful lane results into a
single conditional update, and skips unchanged cursors (including empty
Expand Down Expand Up @@ -260,19 +265,38 @@ 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 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.
**Schedules:** `* * * * *` runs Identity Mail send.
`1-59 * * * *` independently runs Mail reconciliation, skipping minute zero.
`0-58 * * * *` runs one rotating Identity or Support cleanup lane.
`0-59 */6 * * *` reconciles one GitHub repository per invocation, using the
scheduled UTC minute as the slot in the allowlisted catalog. The current
13-repository catalog completes in minutes 0-12 of each six-hour window;
remaining slots return without database or GitHub I/O. The 60-slot capacity is
checked in code. Fetches use stable numeric repository IDs, conditional ETags,
and bounded timeouts/bodies. Full-catalog backfill remains available explicitly.

Each successful scheduled shard records its scheduled timestamp durably in the
existing operations collection. Global reconciliation health advances only
when every currently allowlisted catalog repository has succeeded in that
six-hour cycle. Failed or missing shards keep the prior full-catalog success;
concurrent shards merge progress and preserve webhook ETag invalidation.
Existing records decode missing per-repository progress as empty. No D1 schema
migration is required, and reconciliation never fabricates webhook receipts.

After deploying maintenance changes, check CPU distributions and resource-limit
outcomes for all four triggers, including populated mail pages and release
200/304 responses. Local D1 tests prove bounded page progress and delivery
idempotency, not Cloudflare's production CPU accounting. These changes target
the Workers Free 10 ms allowance; they cannot guarantee an absolute CPU ceiling.

One-record pages trade throughput for headroom: mail scans at most 60 send and 59 reconciliation operation
records per hour, including retained terminal records. A full scan
must remain comfortably shorter than the email-code lifetime; inspect scan
backlogs as usage grows. Cleanup pages advance once per lane every 14-15
minutes. The published Sessions and rate-limit packages still expose
whole-partition sweeps, so their work grows with partition size. Sustained
backlogs need indexed discovery and paginated component APIs, or a larger CPU
allowance. Reducing frequency alone does not raise the per-invocation limit.

**Organization webhook (Phase E):** create one org webhook subscribed only to
`release` events, payload URL `https://pegma.dev/api/webhooks/github/releases`,
Expand Down
12 changes: 6 additions & 6 deletions worker/src/identity-maintenance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,12 +185,12 @@ describe('Identity maintenance', () => {
await runIdentityMaintenance(value.runtime, value.logger, {
tasks: ['mail_send'],
});
expect(value.sendPage).toHaveBeenNthCalledWith(2, { limit: 5 });
expect(value.sendPage).toHaveBeenNthCalledWith(2, { limit: 1 });
await runIdentityMaintenance(value.runtime, value.logger, {
tasks: ['mail_send'],
});
expect(value.sendPage).toHaveBeenNthCalledWith(3, {
limit: 5,
limit: 1,
cursor: 'send-next',
});
});
Expand Down Expand Up @@ -293,20 +293,20 @@ describe('Identity maintenance', () => {

expect(value.challengeSweep).toHaveBeenNthCalledWith(
2,
100,
1,
'challenge-next',
);
expect(value.operationSweep).toHaveBeenNthCalledWith(
2,
100,
1,
'operation-next',
);
expect(value.sendPage).toHaveBeenNthCalledWith(2, {
limit: 5,
limit: 1,
cursor: 'send-next',
});
expect(value.reconciliationPage).toHaveBeenNthCalledWith(2, {
limit: 5,
limit: 1,
});
expect(value.mailSweep).toHaveBeenCalledTimes(2);
expect(value.limiterSweep).toHaveBeenCalledTimes(2);
Expand Down
23 changes: 14 additions & 9 deletions worker/src/identity-maintenance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,9 @@ type CursorName =
| 'mailSweepCursor';

const KEY = { partition: 'identity', id: 'maintenance' } as const;
// Each provider call has a 10-second timeout and workers process a page
// sequentially. Five keeps a worst-case I/O lane inside the one-minute cadence
// and far below Cloudflare's scheduled-handler wall limit.
const MAIL_PROVIDER_PAGE_LIMIT = 5;
// A record can require several conditional writes and a provider call. Bound
// CPU work as well as I/O; durable cursors continue the scan on the next tick.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 One-record pages bound CPU but can starve mail and retention (risk)

With PAGE_LIMIT = 1 and separate 1-minute triggers, a burst of >60 sends or >59 reconciliations per hour plus retained terminal records keeps the scan cursor on terminal rows, extending time-to-drain beyond the email-code lifetime and turning a transient spike into expired codes and dead-letter growth.

worker/src/identity-maintenance.ts:59 and worker/src/support-maintenance.ts:23 cap every sweep and runSendPage/runReconciliationPage to 1. Mail still retains terminal records for operator inspection until sweepMail deletes after 7 days (worker/src/identity-maintenance.ts:232), and worker/README.md:294 itself notes scanning "at most 60 send and 59 reconciliation operation records per hour, including retained terminal records." Support queue repair has the same cap while repairQueueProjectionPage can touch multiple rows per ticket.

Checked worker/src/identity-maintenance.ts:187, worker/src/maintenance-cursors.d1.test.ts:122 (drains 3 jobs over 6 ticks), and worker/README.md:292. No adaptive back-pressure or batch acknowledgement exists.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a real, intentionally documented capacity tradeoff, rather than an unacknowledged throughput guarantee. The request is to reduce per-invocation work for this low-traffic Worker; the README explicitly states 60 send / 59 reconciliation scanned records per hour (including retained records), requires a full scan comfortably below the ten-minute code lifetime, and calls for indexed discovery / paginated component APIs or a larger CPU allowance as backlog grows. Raising the page size or processing several pages in one invocation would remove the CPU bound this change introduces. The cursors make bounded progress; retained rows increase scan latency rather than pinning a cursor permanently. I am leaving this unresolved for a maintainer's capacity/design decision. A larger-traffic queue-discovery redesign is outside this CPU-reduction patch.

const MAINTENANCE_PAGE_LIMIT = 1;
const maintenance = defineCollection<MaintenanceRecord>({
name: 'pegma-dev-maintenance',
key: (value) => ({
Expand Down Expand Up @@ -164,12 +163,18 @@ export async function runIdentityMaintenance(
const tasks: Record<IdentityMaintenanceTask, () => Promise<void>> = {
challenges: async () => {
const previous = cursor(prior?.challengeCursor ?? null);
const result = await runtime.identity.sweepChallenges(100, previous);
const result = await runtime.identity.sweepChallenges(
MAINTENANCE_PAGE_LIMIT,
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);
const result = await runtime.identity.sweepEmailOperations(
MAINTENANCE_PAGE_LIMIT,
previous,
);
saveCursor('emailOperationCursor', result.hasMore ? result.cursor : null);
},
rate_limits: async () => {
Expand All @@ -187,7 +192,7 @@ export async function runIdentityMaintenance(
if (mailWorker === null) return;
const previous = cursor(prior?.mailSendCursor ?? null);
const result = await mailWorker.runSendPage({
limit: MAIL_PROVIDER_PAGE_LIMIT,
limit: MAINTENANCE_PAGE_LIMIT,
...(previous === undefined ? {} : { cursor: previous }),
});
const terminal = result.results.filter(
Expand All @@ -206,7 +211,7 @@ export async function runIdentityMaintenance(
if (mailWorker === null) return;
const previous = cursor(prior?.mailReconcileCursor ?? null);
const result = await mailWorker.runReconciliationPage({
limit: MAIL_PROVIDER_PAGE_LIMIT,
limit: MAINTENANCE_PAGE_LIMIT,
...(previous === undefined ? {} : { cursor: previous }),
});
const terminal = result.results.filter(
Expand All @@ -225,7 +230,7 @@ export async function runIdentityMaintenance(
if (runtime.mailWorker === null) return;
const previous = cursor(prior?.mailSweepCursor ?? null);
const result = await runtime.identity.sweepMail({
limit: 100,
limit: MAINTENANCE_PAGE_LIMIT,
...(previous === undefined ? {} : { cursor: previous }),
terminalBefore: new Date(
Date.now() - 7 * 24 * 60 * 60_000,
Expand Down
24 changes: 24 additions & 0 deletions worker/src/identity-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,30 @@ function mutation(path: string, body: unknown): Request {
}

describe('published Identity composition', () => {
it('avoids importing an unused email HMAC key on idle maintenance', async () => {
const imported = vi.spyOn(crypto.subtle, 'importKey');
try {
const runtime = createIdentityRuntime(
options({ emailEnabled: true, resendApiKey: 're_test_secret' }),
logger,
);
await runtime.identity.sweepChallenges(1);
await runtime.identity.sweepEmailOperations(1);
await runtime.mailWorker!.runSendPage({ limit: 1 });
await runtime.mailWorker!.runReconciliationPage({ limit: 1 });
expect(imported).not.toHaveBeenCalled();
const response = await runtime.api(
mutation('/api/identity/email-code/account/options', {
email: 'lazy@example.test',
}),
);
expect(response.status).toBe(200);
expect(imported).toHaveBeenCalledTimes(1);
} finally {
imported.mockRestore();
}
});

it('composes Identity, the claims adapter, Sessions, and the account API', async () => {
const runtime = createIdentityRuntime(options(), logger);
const user = await runtime.identity.provisionVerifiedUser({
Expand Down
53 changes: 31 additions & 22 deletions worker/src/identity-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
createHmacEmailCodeProtector,
createIdentity,
type Identity,
type EmailCodeProtector,
type MailProvider,
type MailReconciliationPort,
type MailWorker,
Expand Down Expand Up @@ -91,6 +92,18 @@ function durableLimiter(
);
}

/** Keep key validation eager, but import HMAC only when code work needs it. */
function deferredEmailCodeProtector(secret: Uint8Array): EmailCodeProtector {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Deferred EmailCodeProtector proxies only three methods (bug)

A request that exercises an EmailCodeProtector method not proxied by the deferred wrapper throws TypeError: get(...).<method> is not a function and fails closed for email-code verification or code generation.

worker/src/identity-runtime.ts:96 builds deferredEmailCodeProtector that only forwards deriveCode, verifier, and matches. If @​pegma/identity's EmailCodeProtector exposes additional members (e.g., hash, create, verify, or future rotation helpers), createIdentity will receive an incomplete implementation. The current test identity-runtime.test.ts:42 only exercises deriveCode via account/options, so a missing method is not caught.

Checked worker/src/identity-runtime.ts, recipes/cf-passkey-accounts/composition.ts:83 (type is ReturnType<typeof createHmacEmailCodeProtector> with no inline shape), and grep for EmailCodeProtector — the exact interface is in the external @​pegma/identity package and could not be read from this checkout. Proof gap: could not list the canonical method names, so kept as bug/risk rather than nit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not applicable to the pinned dependency. The installed @pegma/identity@0.1.2 canonical dist/crypto.d.ts declares exactly deriveCode(handleHash), verifier(handleHash, code), and matches(expectedVerifier, handleHash, candidateCode) on EmailCodeProtector; all three are forwarded here. The helper explicitly returns that imported interface, so adding a required member in a future dependency update fails tsc rather than silently deploying an incomplete wrapper. The suggested hash/create/verify methods do not exist on this interface. No code change needed.

let protector: EmailCodeProtector | undefined;
const get = () => (protector ??= createHmacEmailCodeProtector(secret));
return {
deriveCode: (handleHash) => get().deriveCode(handleHash),
verifier: (handleHash, code) => get().verifier(handleHash, code),
matches: (expected, handleHash, code) =>
get().matches(expected, handleHash, code),
};
}

/**
* Production composition for pegma.dev's first-party Identity provider.
*
Expand Down Expand Up @@ -159,37 +172,33 @@ export function createIdentityRuntime(
origins: ['https://pegma.dev'],
registrationLimiter,
authenticationLimiter,
emailCodeProtector: createHmacEmailCodeProtector(
emailCodeProtector: deferredEmailCodeProtector(
emailCodeSecret(options.emailCodeSecretBase64),
),
emailCodeRequestLimiter,
emailCodeVerificationLimiter,
});

const resendKey =
typeof options.resendApiKey === 'string' &&
options.resendApiKey.length > 0
typeof options.resendApiKey === 'string' && options.resendApiKey.length > 0
? options.resendApiKey
: null;
const delivery =
!options.emailEnabled
? null
: options.mailDelivery ??
(resendKey === null
? null
: (() => {
const ports = createResendMailPorts({
apiKey: resendKey,
from: options.emailFrom,
...(options.fetch === undefined
? {}
: { fetch: options.fetch }),
});
return {
...ports,
classifyFailure: classifyResendFailure,
};
})());
const delivery = !options.emailEnabled
? null
: (options.mailDelivery ??
(resendKey === null
? null
: (() => {
const ports = createResendMailPorts({
apiKey: resendKey,
from: options.emailFrom,
...(options.fetch === undefined ? {} : { fetch: options.fetch }),
});
return {
...ports,
classifyFailure: classifyResendFailure,
};
})()));
const mailWorker =
delivery === null
? null
Expand Down
54 changes: 21 additions & 33 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,18 @@ import {
createAdminLookupLimiter,
createAdminMutationLimiter,
createProductionSupportRuntime,
createProductionSupportMaintenanceRuntime,
probeSupportStore,
supportHealthProbeEnabled,
type SupportRuntimeEnv,
} from './support-desk';
import { runSupportMaintenance } from './support-maintenance';
import { MAIL_CRON, CLEANUP_CRON, cleanupLaneAt } from './maintenance-schedule';
import {
MAIL_CRON,
MAIL_RECONCILE_CRON,
CLEANUP_CRON,
cleanupLaneAt,
} from './maintenance-schedule';
import { createPegmaMcpHandler } from './mcp-server';
import type { CatalogFetchEnv } from './mcp-catalog-fetch';

Expand Down Expand Up @@ -387,6 +393,7 @@ export default {
store: createProductionStore(env),
logger,
config: releasesConfig,
scheduledTime: controller.scheduledTime,
});
} catch (error) {
logger.log('error', 'release_reconciliation.unavailable', {
Expand All @@ -402,7 +409,11 @@ export default {
controller.cron === CLEANUP_CRON
? cleanupLaneAt(controller.scheduledTime)
: null;
if (controller.cron !== MAIL_CRON && cleanup === null) {
if (
controller.cron !== MAIL_CRON &&
controller.cron !== MAIL_RECONCILE_CRON &&
cleanup === null
) {
logger.log('warn', 'maintenance.unknown_cron', { cron: controller.cron });
return;
}
Expand All @@ -415,7 +426,13 @@ export default {
createProductionIdentityRuntime(env, logger),
logger,
cleanup === null
? { tasks: ['mail_send', 'mail_reconcile'] }
? {
tasks: [
controller.cron === MAIL_CRON
? 'mail_send'
: 'mail_reconcile',
],
}
: {
tasks: [cleanup.task],
...(cleanup.limiterIndex === undefined
Expand All @@ -435,37 +452,8 @@ export default {
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,
},
createProductionSupportMaintenanceRuntime(env),
logger,
{
tasks: [cleanup.task],
Expand Down
Loading
Loading