diff --git a/worker/README.md b/worker/README.md index 0928b92..6c25ab2 100644 --- a/worker/README.md +++ b/worker/README.md @@ -195,6 +195,48 @@ public acknowledgement endpoint. `componentReleases` collection through `@pegma/webhooks`. Do not configure the GitHub organization webhook until Phase E activation. +### GitHub release ingestion (operators) + +**Secret (never in git, Actions, Pages, health, or logs):** + +```sh +npx wrangler secret put GITHUB_WEBHOOK_SECRET -c worker/wrangler.jsonc +``` + +Use a high-entropy random value. GitHub organization webhooks expose one active +secret at a time — rotate by updating the Worker secret and the organization +webhook secret in the same maintenance window. + +**Vars (already in `wrangler.jsonc`):** `GITHUB_ORGANIZATION_ID` (numeric) and +`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 +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. + +**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 +authenticated `ping` (204) before relying on publish/redeliver. + +**Redelivery:** GitHub does not auto-retry failed deliveries. Use the GitHub +webhook delivery UI/API to redeliver; the ledger acknowledges duplicates +without re-applying a processed projection. Missed or deleted events converge +via six-hour reconciliation without operator D1 edits. + +**Rollback:** disable the organization webhook first. Keep `GET /api/releases` +serving last-known public records while investigating unless integrity is in +doubt — then disable release rendering (Stack still shows repository links). +Roll back the Worker version with the normal operator process; do not touch +Identity collections to remove this feature. + +**Health detail `githubReleases`:** `ingestionConfigured`, `readConfigured`, +`lastSuccessfulWebhookAt`, `lastSuccessfulReconciliationAt`, +`reconciliationStale` (true when last success is older than seven hours or +missing), and `currentReleaseCount`. No secrets, delivery IDs, or payloads. + Example body: ```json diff --git a/worker/src/github-release-webhook.ts b/worker/src/github-release-webhook.ts index f85e025..09630e7 100644 --- a/worker/src/github-release-webhook.ts +++ b/worker/src/github-release-webhook.ts @@ -8,6 +8,7 @@ import { decideReleaseProjection, type ReleaseEventFacts, } from './release-projection'; +import { markReleaseWebhookSuccess } from './release-ops-state'; export const GITHUB_RELEASE_EVENT_TYPE = 'github.release.published'; export const MAX_GITHUB_WEBHOOK_BODY_BYTES = 1024 * 1024; @@ -340,6 +341,17 @@ export async function handleGitHubReleaseWebhook( const decision = decideReleaseProjection(facts, observedAt); await applyReleaseProjection(store, decision); await ledger.markProcessed(deliveryId); + try { + await markReleaseWebhookSuccess(store, observedAt); + } catch (markerError) { + // Projection and ledger are already final; health-marker failure must + // not re-enter markFailed or flip the delivery outcome. + logger.log('error', 'github_release_webhook.ops_marker_failed', { + deliveryId, + error: + markerError instanceof Error ? markerError.name : 'unknown', + }); + } logger.log('info', 'github_release_webhook.processed', { deliveryId, action: facts.action, diff --git a/worker/src/index.ts b/worker/src/index.ts index 4b3e5cc..4f654a5 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -16,6 +16,11 @@ import { readGitHubReleaseWebhookConfig, type GitHubReleaseWebhookEnv, } from './github-release-webhook'; +import { loadReleaseHealthDetail } from './release-health'; +import { + RELEASE_RECONCILIATION_CRON, + runReleaseReconciliation, +} from './release-reconciliation'; import { handleGetReleases, readReleasesConfig } from './releases-api'; type AppEnv = Env & LoggerEnv & IdentityRuntimeEnv & GitHubReleaseWebhookEnv; @@ -45,6 +50,24 @@ export default { request.method === 'GET' && (path === '/' || path === '/health' || path === '/api/health') ) { + let releaseDetail: Awaited> = { + ingestionConfigured: Boolean(readGitHubReleaseWebhookConfig(env)), + readConfigured: Boolean(readReleasesConfig(env)), + lastSuccessfulWebhookAt: null, + lastSuccessfulReconciliationAt: null, + reconciliationStale: true, + currentReleaseCount: 0, + }; + try { + releaseDetail = await loadReleaseHealthDetail( + createProductionStore(env), + env, + ); + } catch (error) { + logger.log('error', 'releases_health.unavailable', { + error: error instanceof Error ? error.name : 'unknown', + }); + } const result = await runHealthChecks({ service: 'pegma-dev-api', logger, @@ -63,8 +86,14 @@ export default { String(env.IDENTITY_EMAIL_ENABLED) === 'true' && Boolean(env.RESEND_API_KEY), }), - createDetailCheck('githubReleaseWebhook', { - configured: Boolean(readGitHubReleaseWebhookConfig(env)), + createDetailCheck('githubReleases', { + ingestionConfigured: releaseDetail.ingestionConfigured, + readConfigured: releaseDetail.readConfigured, + lastSuccessfulWebhookAt: releaseDetail.lastSuccessfulWebhookAt, + lastSuccessfulReconciliationAt: + releaseDetail.lastSuccessfulReconciliationAt, + reconciliationStale: releaseDetail.reconciliationStale, + currentReleaseCount: releaseDetail.currentReleaseCount, }), ], }); @@ -179,11 +208,37 @@ export default { return new Response('Not Found', { status: 404 }); }, scheduled( - _controller: ScheduledController, + controller: ScheduledController, env: AppEnv, 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. + if (controller.cron === RELEASE_RECONCILIATION_CRON) { + ctx.waitUntil( + (async () => { + try { + const releasesConfig = readReleasesConfig(env); + if (releasesConfig === null) { + logger.log('error', 'release_reconciliation.not_configured', {}); + return; + } + await runReleaseReconciliation({ + store: createProductionStore(env), + logger, + config: releasesConfig, + }); + } catch (error) { + logger.log('error', 'release_reconciliation.unavailable', { + error: error instanceof Error ? error.name : 'unknown', + }); + } + })(), + ); + return; + } + ctx.waitUntil( (async () => { try { diff --git a/worker/src/release-health.ts b/worker/src/release-health.ts new file mode 100644 index 0000000..4b49d46 --- /dev/null +++ b/worker/src/release-health.ts @@ -0,0 +1,40 @@ +import type { Store } from '@pegma/storage-core'; +import { + isReconciliationStale, + readReleaseOpsState, +} from './release-ops-state'; +import { countCurrentReleases } from './release-reconciliation'; +import { + readGitHubReleaseWebhookConfig, + type GitHubReleaseWebhookEnv, +} from './github-release-webhook'; +import { readReleasesConfig } from './releases-api'; + +/** Public-safe health detail for the release ingestion surface. */ +export interface ReleaseHealthDetail { + readonly ingestionConfigured: boolean; + readonly readConfigured: boolean; + readonly lastSuccessfulWebhookAt: string | null; + readonly lastSuccessfulReconciliationAt: string | null; + readonly reconciliationStale: boolean; + readonly currentReleaseCount: number; +} + +export async function loadReleaseHealthDetail( + store: Store, + env: GitHubReleaseWebhookEnv, + nowMs: number = Date.now(), +): Promise { + const ops = await readReleaseOpsState(store); + return { + ingestionConfigured: Boolean(readGitHubReleaseWebhookConfig(env)), + readConfigured: Boolean(readReleasesConfig(env)), + lastSuccessfulWebhookAt: ops.lastSuccessfulWebhookAt, + lastSuccessfulReconciliationAt: ops.lastSuccessfulReconciliationAt, + reconciliationStale: isReconciliationStale( + ops.lastSuccessfulReconciliationAt, + nowMs, + ), + currentReleaseCount: await countCurrentReleases(store), + }; +} diff --git a/worker/src/release-ops-state.test.ts b/worker/src/release-ops-state.test.ts new file mode 100644 index 0000000..6a35672 --- /dev/null +++ b/worker/src/release-ops-state.test.ts @@ -0,0 +1,54 @@ +import { createMemoryStore } from '@pegma/storage-core'; +import { describe, expect, it } from 'vitest'; +import { + isReconciliationStale, + markReleaseReconciliationSuccess, + markReleaseWebhookSuccess, + readReleaseOpsState, + RECONCILIATION_STALE_AFTER_MS, + saveReleaseRepositoryEtags, +} from './release-ops-state'; + +describe('release ops state', () => { + it('records webhook and reconciliation markers independently', async () => { + const store = createMemoryStore(); + await markReleaseWebhookSuccess(store, '2026-07-28T10:00:00.000Z'); + await markReleaseReconciliationSuccess( + store, + '2026-07-28T12:00:00.000Z', + { '1313911960': '"etag"' }, + ); + + const ops = await readReleaseOpsState(store); + expect(ops.lastSuccessfulWebhookAt).toBe('2026-07-28T10:00:00.000Z'); + expect(ops.lastSuccessfulReconciliationAt).toBe( + '2026-07-28T12:00:00.000Z', + ); + expect(ops.repositoryEtags).toEqual({ '1313911960': '"etag"' }); + }); + + it('saves etags without claiming reconciliation success', async () => { + const store = createMemoryStore(); + await saveReleaseRepositoryEtags(store, { a: '1' }); + const ops = await readReleaseOpsState(store); + expect(ops.lastSuccessfulReconciliationAt).toBeNull(); + expect(ops.repositoryEtags).toEqual({ a: '1' }); + }); + + it('classifies reconciliation staleness', () => { + const now = Date.parse('2026-07-28T20:00:00.000Z'); + expect(isReconciliationStale(null, now)).toBe(true); + expect( + isReconciliationStale( + new Date(now - RECONCILIATION_STALE_AFTER_MS - 1).toISOString(), + now, + ), + ).toBe(true); + expect( + isReconciliationStale( + new Date(now - RECONCILIATION_STALE_AFTER_MS + 60_000).toISOString(), + now, + ), + ).toBe(false); + }); +}); diff --git a/worker/src/release-ops-state.ts b/worker/src/release-ops-state.ts new file mode 100644 index 0000000..e887977 --- /dev/null +++ b/worker/src/release-ops-state.ts @@ -0,0 +1,156 @@ +import { + defineCollection, + type EntityKey, + type Store, + type StoredRecord, + type StoredValue, +} from '@pegma/storage-core'; + +const OPS_PARTITION = 'ops'; +const OPS_ID = 'github-releases'; + +/** Durable operator markers for release webhook + reconciliation. */ +export interface ReleaseOpsState { + readonly lastSuccessfulWebhookAt: string | null; + readonly lastSuccessfulReconciliationAt: string | null; + /** Per-repository ETag for GitHub conditional requests (repoId → etag). */ + readonly repositoryEtags: Readonly>; +} + +type EncodedReleaseOpsState = { + readonly lastSuccessfulWebhookAt: StoredValue; + readonly lastSuccessfulReconciliationAt: StoredValue; + readonly repositoryEtagsJson: StoredValue; +}; + +function opsKey(): EntityKey { + return { partition: OPS_PARTITION, id: OPS_ID }; +} + +function encodeEtags(etags: Readonly>): string { + return JSON.stringify(etags); +} + +function decodeEtags(value: StoredValue): Record { + if (typeof value !== 'string' || value.length === 0 || value.length > 32_768) { + return {}; + } + try { + const parsed: unknown = JSON.parse(value); + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + return {}; + } + const result: Record = {}; + for (const [key, entry] of Object.entries(parsed)) { + if (typeof entry === 'string' && entry.length > 0 && entry.length <= 512) { + result[key] = entry; + } + } + return result; + } catch { + return {}; + } +} + +function encode(value: ReleaseOpsState): EncodedReleaseOpsState { + return { + lastSuccessfulWebhookAt: value.lastSuccessfulWebhookAt, + lastSuccessfulReconciliationAt: value.lastSuccessfulReconciliationAt, + repositoryEtagsJson: encodeEtags(value.repositoryEtags), + }; +} + +function decode(record: StoredRecord): ReleaseOpsState { + return { + lastSuccessfulWebhookAt: + typeof record['lastSuccessfulWebhookAt'] === 'string' + ? record['lastSuccessfulWebhookAt'] + : null, + lastSuccessfulReconciliationAt: + typeof record['lastSuccessfulReconciliationAt'] === 'string' + ? record['lastSuccessfulReconciliationAt'] + : null, + repositoryEtags: decodeEtags(record['repositoryEtagsJson'] ?? null), + }; +} + +export function releaseOpsCollection() { + return defineCollection({ + name: 'releaseOps', + key: () => opsKey(), + codec: { encode, decode }, + }); +} + +const EMPTY: ReleaseOpsState = { + lastSuccessfulWebhookAt: null, + lastSuccessfulReconciliationAt: null, + repositoryEtags: {}, +}; + +export async function readReleaseOpsState(store: Store): Promise { + const current = await store.collection(releaseOpsCollection()).get(opsKey()); + return current ?? EMPTY; +} + +export async function markReleaseWebhookSuccess( + store: Store, + at: string, +): Promise { + await store.collection(releaseOpsCollection()).update(opsKey(), (current) => ({ + action: 'write', + value: { + ...(current ?? EMPTY), + lastSuccessfulWebhookAt: at, + }, + })); +} + +export async function markReleaseReconciliationSuccess( + store: Store, + at: string, + repositoryEtags: Readonly>, +): Promise { + await store.collection(releaseOpsCollection()).update(opsKey(), (current) => ({ + action: 'write', + value: { + ...(current ?? EMPTY), + lastSuccessfulReconciliationAt: at, + repositoryEtags: { ...repositoryEtags }, + }, + })); +} + +/** + * Persist advanced per-repo ETags after a partial run without claiming a + * successful reconciliation completion. + */ +export async function saveReleaseRepositoryEtags( + store: Store, + repositoryEtags: Readonly>, +): Promise { + await store.collection(releaseOpsCollection()).update(opsKey(), (current) => ({ + action: 'write', + value: { + ...(current ?? EMPTY), + repositoryEtags: { ...repositoryEtags }, + }, + })); +} + +/** Reconciliation is stale when last success is older than this. */ +export const RECONCILIATION_STALE_AFTER_MS = 7 * 60 * 60 * 1000; + +export function isReconciliationStale( + lastSuccessfulReconciliationAt: string | null, + nowMs: number, +): boolean { + if (lastSuccessfulReconciliationAt === null) { + return true; + } + const at = Date.parse(lastSuccessfulReconciliationAt); + if (!Number.isFinite(at)) { + return true; + } + return nowMs - at > RECONCILIATION_STALE_AFTER_MS; +} diff --git a/worker/src/release-projection.ts b/worker/src/release-projection.ts index 43022be..60917d6 100644 --- a/worker/src/release-projection.ts +++ b/worker/src/release-projection.ts @@ -156,3 +156,61 @@ export async function applyReleaseProjection( return { action: 'keep' }; }); } + +/** + * Authoritative write of GitHub's current stable release (reconciliation / + * backfill). Unlike webhook projection, an older preceding stable release + * must displace a local current row after a missed delete/unpublish. + * + * Always writes (including a fresh `observedAt`) so UI staleness tracks + * successful recon. A rare concurrent webhook publish during the GitHub GET + * can lose a race; the webhook or the next recon restores truth within the + * six-hour cadence — delete convergence requires force-write here. + */ +export async function applyAuthoritativeCurrentRelease( + store: Store, + release: ComponentRelease, +): Promise<'written' | 'unchanged'> { + const releases = store.collection(componentReleaseCollection()); + let changed: 'written' | 'unchanged' = 'unchanged'; + await releases.update(componentReleaseKey(release.repositoryId), (current) => { + if ( + current !== null && + current.releaseId === release.releaseId && + current.tagName === release.tagName && + current.publishedAt === release.publishedAt && + current.releaseUrl === release.releaseUrl && + current.repositoryName === release.repositoryName && + current.observedAt === release.observedAt + ) { + return { action: 'keep' }; + } + changed = 'written'; + return { action: 'write', value: release }; + }); + return changed; +} + +/** Touch observedAt on an existing current row (successful 304 revalidation). */ +export async function touchCurrentReleaseObservedAt( + store: Store, + repositoryId: string, + observedAt: string, +): Promise { + const releases = store.collection(componentReleaseCollection()); + let touched = false; + await releases.update(componentReleaseKey(repositoryId), (current) => { + if (current === null) { + return { action: 'keep' }; + } + if (current.observedAt === observedAt) { + return { action: 'keep' }; + } + touched = true; + return { + action: 'write', + value: { ...current, observedAt }, + }; + }); + return touched; +} diff --git a/worker/src/release-reconciliation.test.ts b/worker/src/release-reconciliation.test.ts new file mode 100644 index 0000000..cbbdd49 --- /dev/null +++ b/worker/src/release-reconciliation.test.ts @@ -0,0 +1,302 @@ +import { createMemoryStore } from '@pegma/storage-core'; +import type { Logger } from '@pegma/spine'; +import { describe, expect, it, vi } from 'vitest'; +import { + componentReleaseCollection, + componentReleaseKey, +} from './component-release'; +import { readReleaseOpsState } from './release-ops-state'; +import { + backfillReleases, + githubLatestToFacts, + runReleaseReconciliation, +} from './release-reconciliation'; + +const logger: Logger = { log: vi.fn() }; +const NOW = '2026-07-28T21:00:00.000Z'; +const WEBHOOKS_ID = '1313911960'; +const SPINE_ID = '1312512520'; + +const config = { + allowedRepositoryIds: new Set([SPINE_ID, WEBHOOKS_ID]), +}; + +const webhooksLatest = { + id: 9001, + tag_name: 'v0.2.0', + published_at: '2026-07-27T10:00:00.000Z', + draft: false, + prerelease: false, + html_url: 'https://evil.example/ignore', +}; + +describe('githubLatestToFacts', () => { + it('maps a stable latest release and ignores payload URLs', () => { + const facts = githubLatestToFacts( + { repositoryId: WEBHOOKS_ID, repositoryName: 'webhooks' }, + webhooksLatest, + ); + expect(facts).toEqual({ + action: 'published', + repositoryId: WEBHOOKS_ID, + repositoryName: 'webhooks', + releaseId: '9001', + tagName: 'v0.2.0', + publishedAt: '2026-07-27T10:00:00.000Z', + draft: false, + prerelease: false, + }); + }); + + it('rejects drafts and prereleases', () => { + expect( + githubLatestToFacts( + { repositoryId: WEBHOOKS_ID, repositoryName: 'webhooks' }, + { ...webhooksLatest, prerelease: true }, + ), + ).toBeNull(); + }); +}); + +describe('runReleaseReconciliation', () => { + it('backfills stable releases and records success markers', async () => { + const store = createMemoryStore(); + const fetchImpl = vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.includes(`/repositories/${WEBHOOKS_ID}/releases/latest`)) { + return new Response(JSON.stringify(webhooksLatest), { + status: 200, + headers: { + ETag: '"webhooks-etag"', + 'Content-Type': 'application/json', + }, + }); + } + if (url.includes(`/repositories/${SPINE_ID}/releases/latest`)) { + return new Response('Not Found', { status: 404 }); + } + return new Response('unexpected', { status: 500 }); + }); + + const summary = await backfillReleases({ + store, + logger, + config, + now: NOW, + fetchImpl: fetchImpl as unknown as typeof fetch, + }); + + expect(summary).toEqual({ + examined: 2, + upserted: 1, + cleared: 0, + notModified: 0, + failed: 0, + }); + + const releases = store.collection(componentReleaseCollection()); + expect(await releases.get(componentReleaseKey(WEBHOOKS_ID))).toEqual({ + repositoryId: WEBHOOKS_ID, + repositoryName: 'webhooks', + releaseId: '9001', + tagName: 'v0.2.0', + publishedAt: '2026-07-27T10:00:00.000Z', + releaseUrl: 'https://github.com/pegma-dev/webhooks/releases/tag/v0.2.0', + observedAt: NOW, + }); + expect(await releases.get(componentReleaseKey(SPINE_ID))).toBeNull(); + + const ops = await readReleaseOpsState(store); + expect(ops.lastSuccessfulReconciliationAt).toBe(NOW); + expect(ops.repositoryEtags[WEBHOOKS_ID]).toBe('"webhooks-etag"'); + }); + + it('honors If-None-Match and clears when GitHub has no stable release', async () => { + const store = createMemoryStore(); + const releases = store.collection(componentReleaseCollection()); + await releases.update(componentReleaseKey(WEBHOOKS_ID), () => ({ + action: 'write', + value: { + repositoryId: WEBHOOKS_ID, + repositoryName: 'webhooks', + releaseId: '1', + tagName: 'v0.1.0', + publishedAt: '2026-07-01T00:00:00.000Z', + releaseUrl: 'https://github.com/pegma-dev/webhooks/releases/tag/v0.1.0', + observedAt: '2026-07-01T00:00:00.000Z', + }, + })); + + // Seed etag via a successful run first. + await runReleaseReconciliation({ + store, + logger, + config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, + now: '2026-07-28T12:00:00.000Z', + fetchImpl: (async () => + new Response(JSON.stringify(webhooksLatest), { + status: 200, + headers: { ETag: '"etag-1"' }, + })) as unknown as typeof fetch, + }); + + const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const headers = new Headers(init?.headers); + expect(headers.get('If-None-Match')).toBe('"etag-1"'); + // Simulate unpublish of the only stable release. + return new Response('Not Found', { status: 404 }); + }); + + const summary = await runReleaseReconciliation({ + store, + logger, + config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, + now: NOW, + fetchImpl: fetchImpl as unknown as typeof fetch, + }); + + expect(summary.cleared).toBe(1); + expect(await releases.get(componentReleaseKey(WEBHOOKS_ID))).toBeNull(); + }); + + it('does not mark global success when a repository fails', async () => { + const store = createMemoryStore(); + const fetchImpl = vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.includes(`/repositories/${WEBHOOKS_ID}/`)) { + return new Response(JSON.stringify(webhooksLatest), { + status: 200, + headers: { ETag: '"ok"' }, + }); + } + return new Response('rate limited', { status: 403 }); + }); + + const summary = await runReleaseReconciliation({ + store, + logger, + config, + now: NOW, + fetchImpl: fetchImpl as unknown as typeof fetch, + }); + + expect(summary.failed).toBe(1); + expect(summary.upserted).toBe(1); + const ops = await readReleaseOpsState(store); + expect(ops.lastSuccessfulReconciliationAt).toBeNull(); + expect(ops.repositoryEtags[WEBHOOKS_ID]).toBe('"ok"'); + }); + + it('returns not_modified without rewriting projection on 304', async () => { + const store = createMemoryStore(); + await runReleaseReconciliation({ + store, + logger, + config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, + now: '2026-07-28T12:00:00.000Z', + fetchImpl: (async () => + new Response(JSON.stringify(webhooksLatest), { + status: 200, + headers: { ETag: '"etag-1"' }, + })) as unknown as typeof fetch, + }); + + const summary = await runReleaseReconciliation({ + store, + logger, + config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, + now: NOW, + fetchImpl: (async () => + new Response(null, { status: 304, headers: { ETag: '"etag-1"' } })) as unknown as typeof fetch, + }); + + expect(summary.notModified).toBe(1); + const release = await store + .collection(componentReleaseCollection()) + .get(componentReleaseKey(WEBHOOKS_ID)); + // 304 still refreshes observedAt so UI staleness tracks successful recon. + expect(release?.observedAt).toBe(NOW); + expect(release?.tagName).toBe('v0.2.0'); + }); + + it('fails closed on 2xx bodies that are not a usable stable release', async () => { + const store = createMemoryStore(); + const releases = store.collection(componentReleaseCollection()); + await releases.update(componentReleaseKey(WEBHOOKS_ID), () => ({ + action: 'write', + value: { + repositoryId: WEBHOOKS_ID, + repositoryName: 'webhooks', + releaseId: '1', + tagName: 'v0.1.0', + publishedAt: '2026-07-01T00:00:00.000Z', + releaseUrl: 'https://github.com/pegma-dev/webhooks/releases/tag/v0.1.0', + observedAt: '2026-07-01T00:00:00.000Z', + }, + })); + + const summary = await runReleaseReconciliation({ + store, + logger, + config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, + now: NOW, + fetchImpl: (async () => + new Response(JSON.stringify({ id: 'not-a-number' }), { + status: 200, + headers: { ETag: '"bad"' }, + })) as unknown as typeof fetch, + }); + + expect(summary.failed).toBe(1); + expect(await releases.get(componentReleaseKey(WEBHOOKS_ID))).not.toBeNull(); + }); + + it('replaces a local newer release with GitHub preceding stable after delete', async () => { + const store = createMemoryStore(); + const releases = store.collection(componentReleaseCollection()); + // Local still shows a release that was deleted on GitHub (missed webhook). + await releases.update(componentReleaseKey(WEBHOOKS_ID), () => ({ + action: 'write', + value: { + repositoryId: WEBHOOKS_ID, + repositoryName: 'webhooks', + releaseId: '9999', + tagName: 'v9.9.9', + publishedAt: '2026-07-28T00:00:00.000Z', + releaseUrl: 'https://github.com/pegma-dev/webhooks/releases/tag/v9.9.9', + observedAt: '2026-07-28T00:00:00.000Z', + }, + })); + + const preceding = { + id: 100, + tag_name: 'v0.1.0', + published_at: '2026-06-01T00:00:00.000Z', + draft: false, + prerelease: false, + }; + + const summary = await runReleaseReconciliation({ + store, + logger, + config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, + now: NOW, + fetchImpl: (async () => + new Response(JSON.stringify(preceding), { + status: 200, + headers: { ETag: '"preceding"' }, + })) as unknown as typeof fetch, + }); + + expect(summary.upserted).toBe(1); + expect(await releases.get(componentReleaseKey(WEBHOOKS_ID))).toEqual({ + repositoryId: WEBHOOKS_ID, + repositoryName: 'webhooks', + releaseId: '100', + tagName: 'v0.1.0', + publishedAt: '2026-06-01T00:00:00.000Z', + releaseUrl: 'https://github.com/pegma-dev/webhooks/releases/tag/v0.1.0', + observedAt: NOW, + }); + }); +}); diff --git a/worker/src/release-reconciliation.ts b/worker/src/release-reconciliation.ts new file mode 100644 index 0000000..635fb76 --- /dev/null +++ b/worker/src/release-reconciliation.ts @@ -0,0 +1,389 @@ +import type { Store } from '@pegma/storage-core'; +import type { Logger } from '@pegma/spine'; +import { + componentReleaseCollection, + componentReleaseKey, +} from './component-release'; +import { + allowedReleaseCatalog, + type ReleaseCatalogEntry, +} from './release-catalog'; +import { + markReleaseReconciliationSuccess, + readReleaseOpsState, + saveReleaseRepositoryEtags, +} from './release-ops-state'; +import { + applyAuthoritativeCurrentRelease, + buildPegmaReleaseUrl, + touchCurrentReleaseObservedAt, + type ReleaseEventFacts, +} from './release-projection'; +import type { ComponentRelease } from './component-release'; + +/** Cron expression for six-hour release reconciliation (not identity). */ +export const RELEASE_RECONCILIATION_CRON = '0 */6 * * *'; + +const GITHUB_API = 'https://api.github.com'; +const REQUEST_TIMEOUT_MS = 10_000; +const MAX_RESPONSE_BYTES = 256 * 1024; +const USER_AGENT = 'pegma-dev-release-reconciliation'; + +export interface ReleaseReconciliationConfig { + readonly allowedRepositoryIds: ReadonlySet; +} + +export interface ReleaseReconciliationSummary { + readonly examined: number; + readonly upserted: number; + readonly cleared: number; + readonly notModified: number; + readonly failed: number; +} + +export interface RunReleaseReconciliationOptions { + readonly store: Store; + readonly logger: Logger; + readonly config: ReleaseReconciliationConfig; + readonly now?: string; + readonly fetchImpl?: typeof fetch; +} + +function asRecord(value: unknown): Record | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null; +} + +function asId(value: unknown): string | null { + if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) { + return String(value); + } + if (typeof value === 'string' && /^\d+$/.test(value) && value !== '0') { + return value; + } + return null; +} + +/** + * Map a GitHub /releases/latest JSON body into projection facts. + * Does not trust html_url from the payload. + */ +export function githubLatestToFacts( + entry: ReleaseCatalogEntry, + payload: unknown, +): ReleaseEventFacts | null { + const root = asRecord(payload); + if (root === null) { + return null; + } + const releaseId = asId(root['id']); + if ( + releaseId === null || + typeof root['tag_name'] !== 'string' || + typeof root['published_at'] !== 'string' || + typeof root['draft'] !== 'boolean' || + typeof root['prerelease'] !== 'boolean' + ) { + return null; + } + if (root['draft'] || root['prerelease']) { + return null; + } + // Prefer nested repository.id when GitHub includes it; otherwise trust the + // ID-addressed request URL and stamp the catalog id. + const nestedRepository = asRecord(root['repository']); + const nestedId = + nestedRepository === null ? null : asId(nestedRepository['id']); + if (nestedId !== null && nestedId !== entry.repositoryId) { + return null; + } + return { + action: 'published', + repositoryId: entry.repositoryId, + repositoryName: entry.repositoryName, + releaseId, + tagName: root['tag_name'], + publishedAt: root['published_at'], + draft: false, + prerelease: false, + }; +} + +async function readBoundedJson( + response: Response, +): Promise< + | { readonly ok: true; readonly value: unknown } + | { readonly ok: false; readonly reason: 'too_large' | 'invalid_json' } +> { + const declared = response.headers.get('content-length'); + if (declared !== null && /^\d+$/.test(declared)) { + if (Number(declared) > MAX_RESPONSE_BYTES) { + return { ok: false, reason: 'too_large' }; + } + } + const reader = response.body?.getReader(); + if (reader === undefined) { + return { ok: true, value: null }; + } + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) { + break; + } + if (value === undefined) { + continue; + } + total += value.byteLength; + if (total > MAX_RESPONSE_BYTES) { + try { + await reader.cancel(); + } catch { + // Size rejection is authoritative. + } + return { ok: false, reason: 'too_large' }; + } + chunks.push(value); + } + const body = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + body.set(chunk, offset); + offset += chunk.byteLength; + } + try { + return { ok: true, value: JSON.parse(new TextDecoder().decode(body)) }; + } catch { + return { ok: false, reason: 'invalid_json' }; + } +} + +async function clearCurrentRelease( + store: Store, + repositoryId: string, +): Promise { + const releases = store.collection(componentReleaseCollection()); + const key = componentReleaseKey(repositoryId); + for (let attempt = 0; attempt < 3; attempt += 1) { + const current = await releases.getVersioned(key); + if (current === null) { + return false; + } + if (await releases.deleteIfUnchanged(key, current.version)) { + return true; + } + } + throw new Error('Release clear conflicted repeatedly.'); +} + +async function reconcileOneRepository( + options: { + readonly store: Store; + readonly entry: ReleaseCatalogEntry; + readonly etag: string | undefined; + readonly observedAt: string; + readonly fetchImpl: typeof fetch; + }, +): Promise<{ + readonly outcome: 'upserted' | 'cleared' | 'not_modified' | 'unchanged' | 'failed'; + readonly etag: string | undefined; +}> { + const { store, entry, observedAt, fetchImpl } = options; + // Fetch by stable numeric repository ID so a rename/recreate cannot attach + // another repo's release under this catalog slot. + const url = `${GITHUB_API}/repositories/${entry.repositoryId}/releases/latest`; + const headers: Record = { + Accept: 'application/vnd.github+json', + 'User-Agent': USER_AGENT, + 'X-GitHub-Api-Version': '2022-11-28', + }; + if (options.etag !== undefined) { + headers['If-None-Match'] = options.etag; + } + + let response: Response; + try { + response = await fetchImpl(url, { + method: 'GET', + headers, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + } catch { + return { outcome: 'failed', etag: options.etag }; + } + + if (response.status === 304) { + await touchCurrentReleaseObservedAt(store, entry.repositoryId, observedAt); + return { outcome: 'not_modified', etag: options.etag }; + } + + const nextEtag = response.headers.get('etag') ?? undefined; + + if (response.status === 404) { + const cleared = await clearCurrentRelease(store, entry.repositoryId); + return { + outcome: cleared ? 'cleared' : 'unchanged', + etag: undefined, + }; + } + + if (response.status < 200 || response.status >= 300) { + return { outcome: 'failed', etag: options.etag }; + } + + const parsed = await readBoundedJson(response); + if (!parsed.ok) { + return { outcome: 'failed', etag: options.etag }; + } + + const facts = githubLatestToFacts(entry, parsed.value); + if (facts === null) { + // 2xx with an unusable body is not proof that no stable release exists + // (unlike 404). Fail closed so we do not clear good local state. + return { outcome: 'failed', etag: options.etag }; + } + // Catalog repositoryId is the authority; name is display-only. + if (facts.repositoryId !== entry.repositoryId) { + return { outcome: 'failed', etag: options.etag }; + } + + const releaseUrl = buildPegmaReleaseUrl(facts.repositoryName, facts.tagName); + if (releaseUrl === null) { + return { outcome: 'failed', etag: options.etag }; + } + + const release: ComponentRelease = { + repositoryId: facts.repositoryId, + repositoryName: facts.repositoryName, + releaseId: facts.releaseId, + tagName: facts.tagName, + publishedAt: facts.publishedAt, + releaseUrl, + observedAt, + }; + // Authoritative path: GitHub's current stable wins even when older than a + // local row left behind by a missed delete/unpublish webhook. + const wrote = await applyAuthoritativeCurrentRelease(store, release); + return { + outcome: wrote === 'written' ? 'upserted' : 'unchanged', + etag: nextEtag, + }; +} + +/** + * Authoritative sync of current stable releases from GitHub's public API. + * Also serves as initial backfill when the catalog is empty. + * Does not fabricate Webhooks receipt rows. + */ +export async function runReleaseReconciliation( + options: RunReleaseReconciliationOptions, +): Promise { + const { store, logger, config } = options; + const observedAt = options.now ?? new Date().toISOString(); + const fetchImpl = options.fetchImpl ?? fetch; + const catalog = allowedReleaseCatalog(config.allowedRepositoryIds); + const prior = await readReleaseOpsState(store); + const nextEtags: Record = { ...prior.repositoryEtags }; + + let examined = 0; + let upserted = 0; + let cleared = 0; + let notModified = 0; + let failed = 0; + + for (const entry of catalog) { + examined += 1; + let result: { + readonly outcome: + | 'upserted' + | 'cleared' + | 'not_modified' + | 'unchanged' + | 'failed'; + readonly etag: string | undefined; + }; + try { + result = await reconcileOneRepository({ + store, + entry, + etag: nextEtags[entry.repositoryId], + observedAt, + fetchImpl, + }); + } catch { + // Version conflicts and unexpected store errors stay per-repository so + // one hot key cannot abort the catalog pass or skip etag persistence. + result = { outcome: 'failed', etag: nextEtags[entry.repositoryId] }; + } + + if (result.etag === undefined) { + delete nextEtags[entry.repositoryId]; + } else { + nextEtags[entry.repositoryId] = result.etag; + } + + switch (result.outcome) { + case 'upserted': + upserted += 1; + break; + case 'cleared': + cleared += 1; + break; + case 'not_modified': + notModified += 1; + break; + case 'failed': + failed += 1; + break; + default: + break; + } + } + + const summary: ReleaseReconciliationSummary = { + examined, + upserted, + cleared, + notModified, + failed, + }; + + // Persist success only when every repository completed without failure so + // health "stale" stays honest. Always advance etags for successful repos. + if (summary.failed === 0) { + await markReleaseReconciliationSuccess(store, observedAt, nextEtags); + logger.log('info', 'release_reconciliation.completed', { + examined: summary.examined, + upserted: summary.upserted, + cleared: summary.cleared, + notModified: summary.notModified, + }); + } else { + await saveReleaseRepositoryEtags(store, nextEtags); + logger.log('error', 'release_reconciliation.partial_failure', { + examined: summary.examined, + upserted: summary.upserted, + cleared: summary.cleared, + notModified: summary.notModified, + failed: summary.failed, + }); + } + + return summary; +} + +/** Count current release summaries in D1 (for health detail). */ +export async function countCurrentReleases(store: Store): Promise { + const releases = store.collection(componentReleaseCollection()); + const rows = await releases.list('current'); + return rows.length; +} + +/** Backfill is the same path as reconciliation (no receipt rows). */ +export async function backfillReleases( + options: RunReleaseReconciliationOptions, +): Promise { + return runReleaseReconciliation(options); +} diff --git a/worker/wrangler.jsonc b/worker/wrangler.jsonc index 236f094..9f8f309 100644 --- a/worker/wrangler.jsonc +++ b/worker/wrangler.jsonc @@ -19,7 +19,8 @@ "GITHUB_ALLOWED_REPOSITORY_IDS": "1312512520,1312519623,1312811498,1312961609,1312942188,1313911960,1313917945,1314116350,1314093835,1313927900,1314239450,1314421283,1313936481", }, "triggers": { - "crons": ["* * * * *"], + // Minute Identity maintenance; six-hour GitHub release reconciliation. + "crons": ["* * * * *", "0 */6 * * *"], }, "d1_databases": [ {