From 270a254b1bc89836980365b2d40d5118f555f91e Mon Sep 17 00:00:00 2001 From: Brendan Date: Thu, 17 Sep 2026 16:01:44 +0000 Subject: [PATCH] feat: add searchable webhook deliveries --- packages/app/src/flow-service.ts | 2 ++ packages/app/src/job-domain.ts | 13 ++++++++ packages/app/src/protected-api.ts | 5 +++ packages/app/src/tenant.ts | 53 +++++++++++++++++++++++++++++++ packages/docs/openapi.yaml | 2 ++ 5 files changed, 75 insertions(+) diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 132514ee..327310f4 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -53,6 +53,8 @@ export class ApiService { async listJobs() { return (await this.call("flows:read", "/v1/jobs") as any[]).map(value => this.publicJob(value)); } async getJob(jobId: string) { return this.publicJob(await this.call("flows:read", `/v1/jobs/${encodeURIComponent(jobId)}`)); } listJobEvents(jobId: string, limit = 50) { return this.call("runs:read", `/v1/jobs/${encodeURIComponent(jobId)}/events?limit=${limit}`); } + listWebhookDeliveries(query: URLSearchParams) { return this.call("runs:read", `/v1/webhooks/deliveries?${query}`); } + getWebhookDelivery(deliveryId: string) { return this.call("runs:read", `/v1/webhooks/deliveries/${encodeURIComponent(deliveryId)}`); } testJobHandler(input: { handlerCode: string; payload: Record }) { return this.call("flows:write", "/v1/job-handlers/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); } async createJob(input: JobInput) { return this.publicJob(await this.call("flows:write", "/v1/jobs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) })); } async updateJob(jobId: string, input: JobInput) { return this.publicJob(await this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) })); } diff --git a/packages/app/src/job-domain.ts b/packages/app/src/job-domain.ts index 96ea65b3..0fb93378 100644 --- a/packages/app/src/job-domain.ts +++ b/packages/app/src/job-domain.ts @@ -178,6 +178,19 @@ export const JOB_SCHEMA = ` detail TEXT NOT NULL, received_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS job_events_by_job ON job_events(job_id, received_at DESC); + CREATE TABLE IF NOT EXISTS webhook_deliveries ( + id TEXT PRIMARY KEY, provider TEXT NOT NULL, delivery_id TEXT NOT NULL, event_type TEXT NOT NULL DEFAULT 'unknown', + event_action TEXT NOT NULL DEFAULT 'unknown', outcome TEXT NOT NULL, detail TEXT NOT NULL, received_at TEXT NOT NULL, + UNIQUE(provider, delivery_id) + ); + CREATE TABLE IF NOT EXISTS webhook_delivery_events ( + id TEXT PRIMARY KEY, delivery_id TEXT NOT NULL REFERENCES webhook_deliveries(id) ON DELETE CASCADE, + job_id TEXT, outcome TEXT NOT NULL, detail TEXT NOT NULL, created_at TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS webhook_deliveries_order ON webhook_deliveries(received_at DESC, id DESC); + CREATE INDEX IF NOT EXISTS webhook_deliveries_provider ON webhook_deliveries(provider, received_at DESC, id DESC); + CREATE INDEX IF NOT EXISTS webhook_deliveries_outcome ON webhook_deliveries(outcome, received_at DESC, id DESC); + CREATE INDEX IF NOT EXISTS webhook_delivery_events_delivery ON webhook_delivery_events(delivery_id, created_at, id); CREATE TABLE IF NOT EXISTS schedule_state ( trigger_id TEXT PRIMARY KEY REFERENCES triggers(id) ON DELETE CASCADE, job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE, diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index e0e3c6f6..7bcff69d 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -58,6 +58,9 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP if (jobMatch && request.method === "PUT") return Response.json(await service.updateJob(decodeURIComponent(jobMatch[1]), jobInputSchema.parse(await request.json()))); if (jobMatch && request.method === "DELETE") return Response.json(await service.deleteJob(decodeURIComponent(jobMatch[1]))); if (request.method === "GET" && path === "/api/v1/runs") { const q = listRunsSchema.parse(queryInput(url)); return Response.json(await service.listRuns(queryOf(q))); } + if (request.method === "GET" && path === "/api/v1/webhooks/deliveries") return Response.json(await service.listWebhookDeliveries(url.searchParams)); + const webhookDeliveryMatch = path.match(/^\/api\/v1\/webhooks\/deliveries\/([^/]+)$/); + if (webhookDeliveryMatch && request.method === "GET") return Response.json(await service.getWebhookDelivery(decodeURIComponent(webhookDeliveryMatch[1]))); const runMatch = path.match(/^\/api\/v1\/runs\/([^/]+)$/); if (runMatch && request.method === "GET") return Response.json(await service.getRun(decodeURIComponent(runMatch[1]))); const stopMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/stop$/); @@ -88,6 +91,8 @@ function createMcpServer(service: ApiService): McpServer { tool("disable_job", "Disable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, false)); tool("invoke_job", "Invoke a job's manual trigger with a prompt exposed beneath that trigger's stable slug. Manual invocations are never coalesced. idempotencyKey is a client value and must not include the internal manual: claim-key prefix; reuse invocation.idempotency_key from get_run.", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input)); tool("list_job_webhook_activity", "List matching, rejected, duplicate, and accepted webhook activity for a job", z.object({ jobId: z.string().min(1), limit: z.number().int().min(1).max(100).default(50) }), ({ jobId, limit }: any) => service.listJobEvents(jobId, limit)); + tool("list_webhook_deliveries", "Search tenant-scoped webhook deliveries by provider, delivery ID, event, outcome, job, time range, or safe diagnostic text. Results are newest first and cursor paginated.", z.object({ provider: z.string().optional(), deliveryId: z.string().optional(), event: z.string().optional(), action: z.string().optional(), outcome: z.string().optional(), jobId: z.string().optional(), q: z.string().optional(), from: z.string().optional(), to: z.string().optional(), limit: z.number().int().min(1).max(100).default(50), cursor: z.string().optional() }), (input: any) => service.listWebhookDeliveries(queryOf(input))); + tool("get_webhook_delivery", "Get a webhook delivery and its safe processing timeline. Secrets and payloads are never returned.", z.object({ deliveryId: z.string().min(1) }), ({ deliveryId }: any) => service.getWebhookDelivery(deliveryId)); tool("test_job_webhook_handler", "Test an isolated synchronous Job webhook handler without creating a run. Returns the decision and never accepts credentials.", jobHandlerTestSchema, (input: any) => service.testJobHandler(input)); tool("list_execution_targets", "List non-secret execution target metadata and capabilities", z.object({}), () => service.listExecutionTargets()); tool("list_cloudflare_tail_integrations", "List installed Cloudflare Tail integrations and reference counts. Signing secrets are never returned.", z.object({}), () => service.listTailIntegrations()); diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index fa778f54..00fc2ffa 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -201,6 +201,9 @@ export class TenantV2 extends DurableObject { const url = new URL(request.url); try { if (request.method === "GET" && url.pathname === "/v1/runs") return this.listRuns(url); + if (request.method === "GET" && url.pathname === "/v1/webhooks/deliveries") return this.listWebhookDeliveries(url); + const webhookDeliveryMatch = url.pathname.match(/^\/v1\/webhooks\/deliveries\/([^/]+)$/); + if (request.method === "GET" && webhookDeliveryMatch) return this.getWebhookDelivery(decodeURIComponent(webhookDeliveryMatch[1])); if (request.method === "GET" && /^\/v1\/runs\/[^/]+$/.test(url.pathname)) return await this.getRun(decodeURIComponent(url.pathname.split("/")[3] ?? "")); if (request.method === "POST" && /^\/v1\/runs\/[^/]+\/stop$/.test(url.pathname)) return await this.stopRun(decodeURIComponent(url.pathname.split("/")[3] ?? "")); if (request.method === "GET" && url.pathname === "/v1/execution-targets") return await this.executionTargets(); @@ -1138,6 +1141,47 @@ export class TenantV2 extends DurableObject { private recordJobEvent(jobId: string, provider: string, deliveryId: string, outcome: string, detail: string): void { this.ctx.storage.sql.exec("INSERT INTO job_events VALUES (?,?,?,?,?,?)", id(), jobId, provider, deliveryId, outcome, detail, now()); + const receivedAt = now(), canonicalId = `${provider}:${deliveryId}`; + this.ctx.storage.sql.exec("INSERT OR IGNORE INTO webhook_deliveries (id,provider,delivery_id,event_type,event_action,outcome,detail,received_at) VALUES (?,?,?,?,?,?,?,?)", canonicalId, provider, deliveryId, "unknown", "unknown", outcome, detail, receivedAt); + this.ctx.storage.sql.exec("UPDATE webhook_deliveries SET outcome=?,detail=? WHERE id=?", outcome, detail, canonicalId); + this.ctx.storage.sql.exec("INSERT INTO webhook_delivery_events (id,delivery_id,job_id,outcome,detail,created_at) VALUES (?,?,?,?,?,?)", id(), canonicalId, jobId, outcome, detail, receivedAt); + } + + private setWebhookEvent(provider: string, deliveryId: string, eventType: unknown, eventAction: unknown): void { + this.ctx.storage.sql.exec("UPDATE webhook_deliveries SET event_type=?,event_action=? WHERE provider=? AND delivery_id=?", text(eventType) || "unknown", text(eventAction) || "unknown", provider, deliveryId); + } + + private ensureWebhookDelivery(provider: string, deliveryId: string, eventType?: unknown, eventAction?: unknown): void { + const timestamp = now(), canonicalId = `${provider}:${deliveryId}`; + this.ctx.storage.sql.exec("INSERT OR IGNORE INTO webhook_deliveries (id,provider,delivery_id,event_type,event_action,outcome,detail,received_at) VALUES (?,?,?,?,?,?,?,?)", canonicalId, provider, deliveryId, text(eventType) || "unknown", text(eventAction) || "unknown", "received", "Delivery received; processing is in progress.", timestamp); + } + + private finalizeWebhookDelivery(provider: string, deliveryId: string): void { + this.ctx.storage.sql.exec("UPDATE webhook_deliveries SET outcome='ignored',detail='Delivery was received but did not match an enabled trigger.' WHERE provider=? AND delivery_id=? AND outcome='received'", provider, deliveryId); + } + + private listWebhookDeliveries(url: URL): Response { + const limit = this.pageSize(url), cursor = this.cursor(url), clauses: string[] = [], args: unknown[] = []; + const filters: [string, string][] = [["provider", "provider"], ["deliveryId", "delivery_id"], ["event", "event_type"], ["action", "event_action"], ["outcome", "outcome"]]; + for (const [query, column] of filters) { const value = url.searchParams.get(query); if (value) { clauses.push(`${column} = ?`); args.push(value); } } + const jobId = url.searchParams.get("jobId"); + if (jobId) { clauses.push("EXISTS (SELECT 1 FROM webhook_delivery_events e WHERE e.delivery_id=webhook_deliveries.id AND e.job_id=?)"); args.push(jobId); } + const q = url.searchParams.get("q"); + if (q) { clauses.push("(delivery_id LIKE ? OR detail LIKE ?)"); args.push(`%${q}%`, `%${q}%`); } + const from = url.searchParams.get("from"), to = url.searchParams.get("to"); + if (from) { clauses.push("received_at >= ?"); args.push(from); } + if (to) { clauses.push("received_at <= ?"); args.push(to); } + if (cursor) { clauses.push("(received_at < ? OR (received_at = ? AND id < ?))"); args.push(cursor.at, cursor.at, cursor.id); } + const rows = this.rows(`SELECT id,provider,delivery_id AS deliveryId,event_type AS event,event_action AS action,outcome,detail,received_at AS receivedAt FROM webhook_deliveries ${clauses.length ? `WHERE ${clauses.join(" AND ")}` : ""} ORDER BY received_at DESC,id DESC LIMIT ?`, ...args, limit + 1); + const hasMore = rows.length > limit, items = rows.slice(0, limit); + return json({ items, nextCursor: hasMore ? this.nextCursor(items.at(-1), "receivedAt") : null }); + } + + private getWebhookDelivery(deliveryId: string): Response { + const row = this.one("SELECT id,provider,delivery_id AS deliveryId,event_type AS event,event_action AS action,outcome,detail,received_at AS receivedAt FROM webhook_deliveries WHERE id=? OR delivery_id=? ORDER BY received_at DESC LIMIT 1", deliveryId, deliveryId) as Row | undefined; + if (!row) return new Response("Not found", { status: 404 }); + const timeline = this.rows("SELECT job_id AS jobId,outcome,detail,created_at AS createdAt FROM webhook_delivery_events WHERE delivery_id=? ORDER BY created_at,id", row.id); + return json({ ...row, timeline }); } private async invokeWebhookJobs(provider: WebhookProvider, deliveryId: string, payload: Record, eventName?: string): Promise { @@ -1176,7 +1220,10 @@ export class TenantV2 extends DurableObject { private async acceptLinearWebhook(event: Record, deliveryId: string | null): Promise { if (!deliveryId) return new Response("Missing delivery ID", { status: 400 }); + this.ensureWebhookDelivery("linear", deliveryId, event.type, event.action); await this.invokeWebhookJobs("linear", deliveryId, event); + this.setWebhookEvent("linear", deliveryId, event.type, event.action); + this.finalizeWebhookDelivery("linear", deliveryId); await this.ctx.storage.setAlarm(Date.now()); return new Response(null, { status: 200 }); } @@ -1191,6 +1238,7 @@ export class TenantV2 extends DurableObject { if (!relevant) return new Response(null, { status: 202 }); const task = await clickUpJson(connection.accessToken, `/task/${encodeURIComponent(String(event.task_id))}`); const deliveryId = `clickup:${event.webhook_id}:${event.event}:${event.history_items?.[0]?.date ?? event.task_id}`; + this.ensureWebhookDelivery("clickup", deliveryId, event.event, event.action); for (const { job, triggerId, triggerSlug, config } of this.webhookJobs("clickup")) { const payload = { ...event, task, matches: matchingClickUpTask(task, String(config.listId), config.matchRules ?? []) }; const invocation = adaptWebhook(config, "clickup", deliveryId, payload, event.event); @@ -1198,13 +1246,18 @@ export class TenantV2 extends DurableObject { const result = await this.signalAutomaticJob(String(job.id), "webhook", triggerId, `webhook:${triggerId}:${invocation.claimKey}`, { [triggerSlug]: invocation.payload }, { ...invocation.occurrence, metadata: { ...invocation.occurrence.metadata, triggerId } }); this.recordJobEvent(String(job.id), "clickup", deliveryId, result?.duplicate ? "duplicate" : result ? "accepted" : "ignored", result ? "ClickUp task queued through canonical job invocation." : "Job was unavailable."); } + this.setWebhookEvent("clickup", deliveryId, event.event, event.action); + this.finalizeWebhookDelivery("clickup", deliveryId); await this.ctx.storage.setAlarm(Date.now()); return new Response(null, { status: 200 }); } private async acceptGitHubWebhook(event: Record, deliveryId: string | null, eventName: string | null): Promise { if (!deliveryId || !eventName) return new Response("Missing delivery metadata", { status: 400 }); + this.ensureWebhookDelivery("github", deliveryId, eventName, event.action); if (eventName !== "pull_request" || event.action !== "dequeued") await this.invokeWebhookJobs("github", deliveryId, event, eventName); + this.setWebhookEvent("github", deliveryId, eventName, event.action); + this.finalizeWebhookDelivery("github", deliveryId); if (eventName !== "pull_request" || event.action !== "dequeued") { await this.ctx.storage.setAlarm(Date.now()); return new Response(null, { status: 202 }); } const installationId = event.installation?.id, repositoryId = event.repository?.id, pull = event.pull_request; if (!Number.isSafeInteger(installationId) || !Number.isSafeInteger(repositoryId) || !Number.isSafeInteger(pull?.number)) return new Response(null, { status: 202 }); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 8db343b0..cfc0c0d5 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -44,6 +44,8 @@ paths: /api/v1/jobs/{jobId}/disable: { post: { summary: Disable job, responses: { '200': { description: Disabled } } } } /api/v1/jobs/{jobId}/invocations: { post: { summary: Invoke job, responses: { '202': { description: Accepted } } } } /api/v1/jobs/{jobId}/events: { get: { summary: List webhook activity, responses: { '200': { description: Activity } } } } + /api/v1/webhooks/deliveries: { get: { summary: Search webhook deliveries, responses: { '200': { description: Cursor-paginated safe delivery records } } } } + /api/v1/webhooks/deliveries/{deliveryId}: { get: { summary: Get webhook delivery detail and processing timeline, responses: { '200': { description: Safe delivery detail } } } } /api/v1/job-handlers/test: { post: { summary: Test webhook handler, responses: { '200': { description: Decision } } } } /api/v1/runs: get: { summary: List runs, parameters: [{ name: jobId, in: query, schema: { type: string } }, { name: state, in: query, schema: { type: string } }, { name: contextQuery, in: query, schema: { type: string } }, { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100 } }, { name: cursor, in: query, schema: { type: string } }], responses: { '200': { description: Paginated runs, content: { application/json: { schema: { $ref: '#/components/schemas/RunPage' } } } } } }