diff --git a/worker/src/github-release-webhook.ts b/worker/src/github-release-webhook.ts index 09630e7..4d929d8 100644 --- a/worker/src/github-release-webhook.ts +++ b/worker/src/github-release-webhook.ts @@ -8,7 +8,10 @@ import { decideReleaseProjection, type ReleaseEventFacts, } from './release-projection'; -import { markReleaseWebhookSuccess } from './release-ops-state'; +import { + invalidateReleaseRepositoryEtag, + markReleaseWebhookSuccess, +} from './release-ops-state'; export const GITHUB_RELEASE_EVENT_TYPE = 'github.release.published'; export const MAX_GITHUB_WEBHOOK_BODY_BYTES = 1024 * 1024; @@ -340,12 +343,17 @@ export async function handleGitHubReleaseWebhook( const observedAt = options.now ?? new Date().toISOString(); const decision = decideReleaseProjection(facts, observedAt); await applyReleaseProjection(store, decision); + // ETag invalidation is correctness-critical (not best-effort): a later + // 304 must not mask a missed delete after this projection change. + if (decision.kind === 'upsert' || decision.kind === 'delete') { + await invalidateReleaseRepositoryEtag(store, facts.repositoryId); + } 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. + // Projection, ETag invalidation, and ledger are already final; health + // marker failure must not re-enter markFailed or flip the delivery. logger.log('error', 'github_release_webhook.ops_marker_failed', { deliveryId, error: diff --git a/worker/src/release-ops-state.test.ts b/worker/src/release-ops-state.test.ts index 6a35672..244c25d 100644 --- a/worker/src/release-ops-state.test.ts +++ b/worker/src/release-ops-state.test.ts @@ -1,22 +1,28 @@ import { createMemoryStore } from '@pegma/storage-core'; import { describe, expect, it } from 'vitest'; import { + invalidateReleaseRepositoryEtag, isReconciliationStale, - markReleaseReconciliationSuccess, markReleaseWebhookSuccess, + mergeReleaseRepositoryEtagUpdates, 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( + await mergeReleaseRepositoryEtagUpdates( store, + [ + { + repositoryId: '1313911960', + etag: '"etag"', + expectedEpoch: 0, + }, + ], '2026-07-28T12:00:00.000Z', - { '1313911960': '"etag"' }, ); const ops = await readReleaseOpsState(store); @@ -27,12 +33,50 @@ describe('release ops state', () => { expect(ops.repositoryEtags).toEqual({ '1313911960': '"etag"' }); }); - it('saves etags without claiming reconciliation success', async () => { + it('invalidates a repository ETag and bumps its epoch', async () => { const store = createMemoryStore(); - await saveReleaseRepositoryEtags(store, { a: '1' }); + await mergeReleaseRepositoryEtagUpdates( + store, + [ + { + repositoryId: '1313911960', + etag: '"etag-a"', + expectedEpoch: 0, + }, + { + repositoryId: '1312512520', + etag: '"keep"', + expectedEpoch: 0, + }, + ], + '2026-07-28T12:00:00.000Z', + ); + await invalidateReleaseRepositoryEtag(store, '1313911960'); + const ops = await readReleaseOpsState(store); + expect(ops.repositoryEtags).toEqual({ '1312512520': '"keep"' }); + expect(ops.repositoryEtagEpochs['1313911960']).toBe(1); + expect(ops.lastSuccessfulReconciliationAt).toBe( + '2026-07-28T12:00:00.000Z', + ); + }); + + it('does not restore ETags after concurrent invalidation', async () => { + const store = createMemoryStore(); + await mergeReleaseRepositoryEtagUpdates( + store, + [{ repositoryId: 'a', etag: '1', expectedEpoch: 0 }], + null, + ); + // Recon observed epoch 0 for a, then webhook invalidates. + await invalidateReleaseRepositoryEtag(store, 'a'); + await mergeReleaseRepositoryEtagUpdates( + store, + [{ repositoryId: 'a', etag: 'stale', expectedEpoch: 0 }], + null, + ); const ops = await readReleaseOpsState(store); - expect(ops.lastSuccessfulReconciliationAt).toBeNull(); - expect(ops.repositoryEtags).toEqual({ a: '1' }); + expect(ops.repositoryEtags).toEqual({}); + expect(ops.repositoryEtagEpochs['a']).toBe(1); }); it('classifies reconciliation staleness', () => { diff --git a/worker/src/release-ops-state.ts b/worker/src/release-ops-state.ts index e887977..a93f5ff 100644 --- a/worker/src/release-ops-state.ts +++ b/worker/src/release-ops-state.ts @@ -15,23 +15,29 @@ export interface ReleaseOpsState { readonly lastSuccessfulReconciliationAt: string | null; /** Per-repository ETag for GitHub conditional requests (repoId → etag). */ readonly repositoryEtags: Readonly>; + /** + * Per-repository generation bumped on every ETag invalidation so recon + * cannot restore a stale ETag after a concurrent webhook projection. + */ + readonly repositoryEtagEpochs: Readonly>; } type EncodedReleaseOpsState = { readonly lastSuccessfulWebhookAt: StoredValue; readonly lastSuccessfulReconciliationAt: StoredValue; readonly repositoryEtagsJson: StoredValue; + readonly repositoryEtagEpochsJson: StoredValue; }; function opsKey(): EntityKey { return { partition: OPS_PARTITION, id: OPS_ID }; } -function encodeEtags(etags: Readonly>): string { - return JSON.stringify(etags); +function encodeStringMap(map: Readonly>): string { + return JSON.stringify(map); } -function decodeEtags(value: StoredValue): Record { +function decodeStringMap(value: StoredValue): Record { if (typeof value !== 'string' || value.length === 0 || value.length > 32_768) { return {}; } @@ -52,11 +58,37 @@ function decodeEtags(value: StoredValue): Record { } } +function encodeEpochMap(map: Readonly>): string { + return JSON.stringify(map); +} + +function decodeEpochMap(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 === 'number' && Number.isSafeInteger(entry) && entry >= 0) { + result[key] = entry; + } + } + return result; + } catch { + return {}; + } +} + function encode(value: ReleaseOpsState): EncodedReleaseOpsState { return { lastSuccessfulWebhookAt: value.lastSuccessfulWebhookAt, lastSuccessfulReconciliationAt: value.lastSuccessfulReconciliationAt, - repositoryEtagsJson: encodeEtags(value.repositoryEtags), + repositoryEtagsJson: encodeStringMap(value.repositoryEtags), + repositoryEtagEpochsJson: encodeEpochMap(value.repositoryEtagEpochs), }; } @@ -70,7 +102,10 @@ function decode(record: StoredRecord): ReleaseOpsState { typeof record['lastSuccessfulReconciliationAt'] === 'string' ? record['lastSuccessfulReconciliationAt'] : null, - repositoryEtags: decodeEtags(record['repositoryEtagsJson'] ?? null), + repositoryEtags: decodeStringMap(record['repositoryEtagsJson'] ?? null), + repositoryEtagEpochs: decodeEpochMap( + record['repositoryEtagEpochsJson'] ?? null, + ), }; } @@ -86,6 +121,7 @@ const EMPTY: ReleaseOpsState = { lastSuccessfulWebhookAt: null, lastSuccessfulReconciliationAt: null, repositoryEtags: {}, + repositoryEtagEpochs: {}, }; export async function readReleaseOpsState(store: Store): Promise { @@ -93,49 +129,89 @@ export async function readReleaseOpsState(store: Store): Promise { - await store.collection(releaseOpsCollection()).update(opsKey(), (current) => ({ - action: 'write', - value: { - ...(current ?? EMPTY), - lastSuccessfulWebhookAt: at, - }, - })); + await store.collection(releaseOpsCollection()).update(opsKey(), (current) => { + const base = current ?? EMPTY; + const etags = { ...base.repositoryEtags }; + const epochs = { ...base.repositoryEtagEpochs }; + delete etags[repositoryId]; + epochs[repositoryId] = (epochs[repositoryId] ?? 0) + 1; + return { + action: 'write', + value: { + ...base, + repositoryEtags: etags, + repositoryEtagEpochs: epochs, + }, + }; + }); } -export async function markReleaseReconciliationSuccess( +/** Record last successful webhook time only (health detail). */ +export async function markReleaseWebhookSuccess( store: Store, at: string, - repositoryEtags: Readonly>, ): Promise { await store.collection(releaseOpsCollection()).update(opsKey(), (current) => ({ action: 'write', value: { ...(current ?? EMPTY), - lastSuccessfulReconciliationAt: at, - repositoryEtags: { ...repositoryEtags }, + lastSuccessfulWebhookAt: at, }, })); } +/** One repository ETag update conditioned on the epoch observed at fetch time. */ +export interface ConditionalEtagUpdate { + readonly repositoryId: string; + /** ETag to store, or null to clear. */ + readonly etag: string | null; + /** Epoch value read when reconciliation began this repository. */ + readonly expectedEpoch: number; +} + /** - * Persist advanced per-repo ETags after a partial run without claiming a - * successful reconciliation completion. + * Merge conditional ETag updates. An update applies only when the live epoch + * still matches `expectedEpoch`, so a concurrent invalidation wins. */ -export async function saveReleaseRepositoryEtags( +export async function mergeReleaseRepositoryEtagUpdates( store: Store, - repositoryEtags: Readonly>, + updates: readonly ConditionalEtagUpdate[], + markSuccessAt: string | null, ): Promise { - await store.collection(releaseOpsCollection()).update(opsKey(), (current) => ({ - action: 'write', - value: { - ...(current ?? EMPTY), - repositoryEtags: { ...repositoryEtags }, - }, - })); + await store.collection(releaseOpsCollection()).update(opsKey(), (current) => { + const base = current ?? EMPTY; + const etags = { ...base.repositoryEtags }; + const epochs = { ...base.repositoryEtagEpochs }; + for (const update of updates) { + const liveEpoch = epochs[update.repositoryId] ?? 0; + if (liveEpoch !== update.expectedEpoch) { + continue; + } + if (update.etag === null) { + delete etags[update.repositoryId]; + } else { + etags[update.repositoryId] = update.etag; + } + } + return { + action: 'write', + value: { + ...base, + repositoryEtags: etags, + repositoryEtagEpochs: epochs, + lastSuccessfulReconciliationAt: + markSuccessAt ?? base.lastSuccessfulReconciliationAt, + }, + }; + }); } /** Reconciliation is stale when last success is older than this. */ diff --git a/worker/src/release-reconciliation.test.ts b/worker/src/release-reconciliation.test.ts index cbbdd49..65b153c 100644 --- a/worker/src/release-reconciliation.test.ts +++ b/worker/src/release-reconciliation.test.ts @@ -251,6 +251,80 @@ describe('runReleaseReconciliation', () => { expect(await releases.get(componentReleaseKey(WEBHOOKS_ID))).not.toBeNull(); }); + it('does not 304-mask a missed delete after a later webhook projection', async () => { + const store = createMemoryStore(); + // Recon caches etag for A. + await runReleaseReconciliation({ + store, + logger, + config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, + now: '2026-07-28T10:00:00.000Z', + fetchImpl: (async () => + new Response( + JSON.stringify({ + id: 100, + tag_name: 'v0.1.0', + published_at: '2026-06-01T00:00:00.000Z', + draft: false, + prerelease: false, + }), + { status: 200, headers: { ETag: '"etag-a"' } }, + )) as unknown as typeof fetch, + }); + + // Webhook later projects B and must drop etag-a. + const releases = store.collection(componentReleaseCollection()); + await releases.update(componentReleaseKey(WEBHOOKS_ID), () => ({ + action: 'write', + value: { + repositoryId: WEBHOOKS_ID, + repositoryName: 'webhooks', + releaseId: '200', + tagName: 'v0.2.0', + publishedAt: '2026-07-20T00:00:00.000Z', + releaseUrl: 'https://github.com/pegma-dev/webhooks/releases/tag/v0.2.0', + observedAt: '2026-07-28T11:00:00.000Z', + }, + })); + const { invalidateReleaseRepositoryEtag } = await import( + './release-ops-state' + ); + await invalidateReleaseRepositoryEtag(store, WEBHOOKS_ID); + + // Missed delete of B: GitHub is A again. Without ETag invalidation this + // would 304 and leave B; with invalidation we re-fetch A. + let sawIfNoneMatch = false; + const summary = await runReleaseReconciliation({ + store, + logger, + config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, + now: NOW, + fetchImpl: (async (_input: RequestInfo | URL, init?: RequestInit) => { + const headers = new Headers(init?.headers); + if (headers.get('If-None-Match')) { + sawIfNoneMatch = true; + } + return new Response( + JSON.stringify({ + id: 100, + tag_name: 'v0.1.0', + published_at: '2026-06-01T00:00:00.000Z', + draft: false, + prerelease: false, + }), + { status: 200, headers: { ETag: '"etag-a"' } }, + ); + }) as unknown as typeof fetch, + }); + + expect(sawIfNoneMatch).toBe(false); + expect(summary.upserted).toBe(1); + expect(await releases.get(componentReleaseKey(WEBHOOKS_ID))).toMatchObject({ + releaseId: '100', + tagName: 'v0.1.0', + }); + }); + it('replaces a local newer release with GitHub preceding stable after delete', async () => { const store = createMemoryStore(); const releases = store.collection(componentReleaseCollection()); diff --git a/worker/src/release-reconciliation.ts b/worker/src/release-reconciliation.ts index 635fb76..f22d034 100644 --- a/worker/src/release-reconciliation.ts +++ b/worker/src/release-reconciliation.ts @@ -9,9 +9,9 @@ import { type ReleaseCatalogEntry, } from './release-catalog'; import { - markReleaseReconciliationSuccess, + mergeReleaseRepositoryEtagUpdates, readReleaseOpsState, - saveReleaseRepositoryEtags, + type ConditionalEtagUpdate, } from './release-ops-state'; import { applyAuthoritativeCurrentRelease, @@ -284,8 +284,8 @@ export async function runReleaseReconciliation( 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 }; + // Epoch-conditioned ETag updates so a concurrent webhook invalidation wins. + const etagUpdates: ConditionalEtagUpdate[] = []; let examined = 0; let upserted = 0; @@ -295,6 +295,9 @@ export async function runReleaseReconciliation( for (const entry of catalog) { examined += 1; + // Re-read live ETags/epochs each repo so mid-run invalidations apply. + const live = await readReleaseOpsState(store); + const expectedEpoch = live.repositoryEtagEpochs[entry.repositoryId] ?? 0; let result: { readonly outcome: | 'upserted' @@ -308,37 +311,36 @@ export async function runReleaseReconciliation( result = await reconcileOneRepository({ store, entry, - etag: nextEtags[entry.repositoryId], + etag: live.repositoryEtags[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] }; + result = { outcome: 'failed', etag: undefined }; } - if (result.etag === undefined) { - delete nextEtags[entry.repositoryId]; + if (result.outcome === 'failed') { + failed += 1; + } else if (result.outcome === 'cleared') { + cleared += 1; + etagUpdates.push({ + repositoryId: entry.repositoryId, + etag: null, + expectedEpoch, + }); + } else if (result.outcome === 'not_modified') { + notModified += 1; } else { - nextEtags[entry.repositoryId] = result.etag; - } - - switch (result.outcome) { - case 'upserted': + if (result.outcome === 'upserted') { upserted += 1; - break; - case 'cleared': - cleared += 1; - break; - case 'not_modified': - notModified += 1; - break; - case 'failed': - failed += 1; - break; - default: - break; + } + etagUpdates.push({ + repositoryId: entry.repositoryId, + etag: result.etag ?? null, + expectedEpoch, + }); } } @@ -351,9 +353,9 @@ export async function runReleaseReconciliation( }; // Persist success only when every repository completed without failure so - // health "stale" stays honest. Always advance etags for successful repos. + // health "stale" stays honest. Merge ETag updates for successful repos. if (summary.failed === 0) { - await markReleaseReconciliationSuccess(store, observedAt, nextEtags); + await mergeReleaseRepositoryEtagUpdates(store, etagUpdates, observedAt); logger.log('info', 'release_reconciliation.completed', { examined: summary.examined, upserted: summary.upserted, @@ -361,7 +363,7 @@ export async function runReleaseReconciliation( notModified: summary.notModified, }); } else { - await saveReleaseRepositoryEtags(store, nextEtags); + await mergeReleaseRepositoryEtagUpdates(store, etagUpdates, null); logger.log('error', 'release_reconciliation.partial_failure', { examined: summary.examined, upserted: summary.upserted,