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
14 changes: 11 additions & 3 deletions worker/src/github-release-webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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:
Expand Down
60 changes: 52 additions & 8 deletions worker/src/release-ops-state.test.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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', () => {
Expand Down
134 changes: 105 additions & 29 deletions worker/src/release-ops-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,29 @@ export interface ReleaseOpsState {
readonly lastSuccessfulReconciliationAt: string | null;
/** Per-repository ETag for GitHub conditional requests (repoId → etag). */
readonly repositoryEtags: Readonly<Record<string, string>>;
/**
* Per-repository generation bumped on every ETag invalidation so recon
* cannot restore a stale ETag after a concurrent webhook projection.
*/
readonly repositoryEtagEpochs: Readonly<Record<string, number>>;
}

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<Record<string, string>>): string {
return JSON.stringify(etags);
function encodeStringMap(map: Readonly<Record<string, string>>): string {
return JSON.stringify(map);
}

function decodeEtags(value: StoredValue): Record<string, string> {
function decodeStringMap(value: StoredValue): Record<string, string> {
if (typeof value !== 'string' || value.length === 0 || value.length > 32_768) {
return {};
}
Expand All @@ -52,11 +58,37 @@ function decodeEtags(value: StoredValue): Record<string, string> {
}
}

function encodeEpochMap(map: Readonly<Record<string, number>>): string {
return JSON.stringify(map);
}

function decodeEpochMap(value: StoredValue): Record<string, number> {
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<string, number> = {};
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),
};
}

Expand All @@ -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,
),
};
}

Expand All @@ -86,56 +121,97 @@ const EMPTY: ReleaseOpsState = {
lastSuccessfulWebhookAt: null,
lastSuccessfulReconciliationAt: null,
repositoryEtags: {},
repositoryEtagEpochs: {},
};

export async function readReleaseOpsState(store: Store): Promise<ReleaseOpsState> {
const current = await store.collection(releaseOpsCollection()).get(opsKey());
return current ?? EMPTY;
}

export async function markReleaseWebhookSuccess(
/**
* Drop the recon ETag for one repository and bump its epoch. Critical for
* correctness after a webhook changes the local projection.
*/
export async function invalidateReleaseRepositoryEtag(
store: Store,
at: string,
repositoryId: string,
): Promise<void> {
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,
Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
repositoryEtagEpochs: epochs,
},
};
});
}

export async function markReleaseReconciliationSuccess(
/** Record last successful webhook time only (health detail). */
export async function markReleaseWebhookSuccess(
store: Store,
at: string,
repositoryEtags: Readonly<Record<string, string>>,
): Promise<void> {
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<Record<string, string>>,
updates: readonly ConditionalEtagUpdate[],
markSuccessAt: string | null,
): Promise<void> {
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. */
Expand Down
Loading