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
42 changes: 42 additions & 0 deletions worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions worker/src/github-release-webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
61 changes: 58 additions & 3 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -45,6 +50,24 @@ export default {
request.method === 'GET' &&
(path === '/' || path === '/health' || path === '/api/health')
) {
let releaseDetail: Awaited<ReturnType<typeof loadReleaseHealthDetail>> = {
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,
Expand All @@ -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,
}),
],
});
Expand Down Expand Up @@ -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 {
Expand Down
40 changes: 40 additions & 0 deletions worker/src/release-health.ts
Original file line number Diff line number Diff line change
@@ -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<ReleaseHealthDetail> {
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),
};
}
54 changes: 54 additions & 0 deletions worker/src/release-ops-state.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading