An open-source, faster Devin alternative
TypeScript
fix(webhooks): prod E2E follow-ups (inline validation, idempotency 409, delivery-consistency docs)
Igor Zalutski9b3039edbe0a
diff --git a/cloudflare-workers/api-edge/src/webhooks.ts b/cloudflare-workers/api-edge/src/webhooks.tsindex b16d3854..e303ce48 100644--- a/cloudflare-workers/api-edge/src/webhooks.ts+++ b/cloudflare-workers/api-edge/src/webhooks.ts@@ -302,6 +302,8 @@ export async function handleWebhooksAPI(}async function createWebhook(req: Request, env: WebhookEnv, sx: SvixClient, caller: Caller): Promise<Response> {+ // Read the raw body once: needed both to parse and to fingerprint for idempotency.+ const rawBody = await req.text();let body: {url?: string;eventTypes?: string[];@@ -312,7 +314,7 @@ async function createWebhook(req: Request, env: WebhookEnv, sx: SvixClient, callenabled?: boolean;};try {- body = await req.json();+ body = rawBody ? JSON.parse(rawBody) : {};} catch {return json({ error: "invalid JSON body" }, 400);}@@ -323,15 +325,22 @@ async function createWebhook(req: Request, env: WebhookEnv, sx: SvixClient, call}// Idempotency: a retried create with the same Idempotency-Key returns the same- // destination (200) instead of a duplicate. Fast path — replay a prior claim.+ // destination (200) instead of a duplicate. Reusing a key with a DIFFERENT body+ // is a client error → 409 (we fingerprint the request body). Fast path first.const idemKey = req.headers.get("Idempotency-Key") ?? undefined;+ const reqHash = idemKey ? await sha256Hex(rawBody) : undefined;if (idemKey) {const prior = await env.OPENCOMPUTER_DB.prepare(- "SELECT destination_id FROM webhook_idempotency WHERE org_id = ?1 AND idempotency_key = ?2",+ "SELECT destination_id, request_hash FROM webhook_idempotency WHERE org_id = ?1 AND idempotency_key = ?2",).bind(caller.orgID, idemKey)- .first<{ destination_id: string }>();- if (prior) return idempotentReplay(env, sx, caller, prior.destination_id);+ .first<{ destination_id: string; request_hash: string | null }>();+ if (prior) {+ if (prior.request_hash && prior.request_hash !== reqHash) {+ return json({ error: "Idempotency-Key already used with a different request body" }, 409);+ }+ return idempotentReplay(env, sx, caller, prior.destination_id);+ }}const { wire, secret } = await createDestination(env, sx, caller.orgID, {@@ -347,18 +356,21 @@ async function createWebhook(req: Request, env: WebhookEnv, sx: SvixClient, callif (idemKey) {// Claim the key atomically (PK conflict = a concurrent create already won).await env.OPENCOMPUTER_DB.prepare(- "INSERT INTO webhook_idempotency (org_id, idempotency_key, destination_id, created_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT(org_id, idempotency_key) DO NOTHING",+ "INSERT INTO webhook_idempotency (org_id, idempotency_key, destination_id, request_hash, created_at) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(org_id, idempotency_key) DO NOTHING",)- .bind(caller.orgID, idemKey, wire.id, nowSec())+ .bind(caller.orgID, idemKey, wire.id, reqHash ?? null, nowSec()).run();const winner = await env.OPENCOMPUTER_DB.prepare(- "SELECT destination_id FROM webhook_idempotency WHERE org_id = ?1 AND idempotency_key = ?2",+ "SELECT destination_id, request_hash FROM webhook_idempotency WHERE org_id = ?1 AND idempotency_key = ?2",).bind(caller.orgID, idemKey)- .first<{ destination_id: string }>();+ .first<{ destination_id: string; request_hash: string | null }>();if (winner && winner.destination_id !== wire.id) {- // Lost a concurrent race — drop our just-created duplicate, return the winner.+ // Lost a concurrent race — drop our just-created duplicate.await deleteDestinationById(env, sx, caller.orgID, wire.id as string);+ if (winner.request_hash && winner.request_hash !== reqHash) {+ return json({ error: "Idempotency-Key already used with a different request body" }, 409);+ }return idempotentReplay(env, sx, caller, winner.destination_id);}}@@ -366,6 +378,12 @@ async function createWebhook(req: Request, env: WebhookEnv, sx: SvixClient, callreturn json({ ...wire, secret }, 201);}+// sha256Hex — request-body fingerprint for Idempotency-Key conflict detection.+async function sha256Hex(s: string): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s));+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");+}+// idempotentReplay returns an existing destination + its (re-fetched) signing// secret with 200 — the response to a retried idempotent create.async function idempotentReplay(env: WebhookEnv, sx: SvixClient, caller: Caller, destId: string): Promise<Response> {diff --git a/cloudflare-workers/schema_phase8_webhooks.sql b/cloudflare-workers/schema_phase8_webhooks.sqlindex eace7f64..73632fea 100644--- a/cloudflare-workers/schema_phase8_webhooks.sql+++ b/cloudflare-workers/schema_phase8_webhooks.sql@@ -36,6 +36,7 @@ CREATE TABLE IF NOT EXISTS webhook_idempotency (org_id TEXT NOT NULL,idempotency_key TEXT NOT NULL,destination_id TEXT NOT NULL,+ request_hash TEXT, -- sha256 of the create body; reuse with a different body → 409created_at INTEGER NOT NULL,PRIMARY KEY (org_id, idempotency_key));diff --git a/docs/api-reference/webhooks/create.mdx b/docs/api-reference/webhooks/create.mdxindex 1c050e6a..ddb98ce7 100644--- a/docs/api-reference/webhooks/create.mdx+++ b/docs/api-reference/webhooks/create.mdx@@ -30,7 +30,7 @@ Register a webhook destination for sandbox lifecycle events. See [Webhooks](/san</ParamField><ParamField header="Idempotency-Key" type="string">- Optional. A retried create with the same key returns the **same** destination (`200`) instead of creating a duplicate.+ Optional. A retried create with the same key **and same body** returns the **same** destination (`200`) instead of a duplicate. Reusing the key with a **different** body is a `409` conflict.</ParamField>Without an `Idempotency-Key`, each call creates a **new** destination and returns **`201`** — there is no get-or-create by `name`. With one, a retried call returns the same destination with **`200`**.diff --git a/docs/api-reference/webhooks/deliveries-list.mdx b/docs/api-reference/webhooks/deliveries-list.mdxindex e9089a22..70054c13 100644--- a/docs/api-reference/webhooks/deliveries-list.mdx+++ b/docs/api-reference/webhooks/deliveries-list.mdx@@ -4,7 +4,9 @@ api: 'GET /api/webhooks/{id}/deliveries'---List a destination's most recent delivery attempts (up to 50). Each entry is a delivery-provider-attempt record. The attempt index lags actual delivery by a few seconds. See [Webhooks](/sandboxes/webhooks#deliveries).+attempt record. The attempt index lags actual delivery by a few seconds, and resolving a single+message ([get](/api-reference/webhooks/delivery-get)) / [redeliver](/api-reference/webhooks/redeliver)+can lag longer (~30s+) — retry with backoff. See [Webhooks](/sandboxes/webhooks#deliveries).<ParamField path="id" type="string" required>Destination ID (`whk_…`).diff --git a/docs/api-reference/webhooks/delivery-get.mdx b/docs/api-reference/webhooks/delivery-get.mdxindex 9c800f44..d14e4f3b 100644--- a/docs/api-reference/webhooks/delivery-get.mdx+++ b/docs/api-reference/webhooks/delivery-get.mdx@@ -7,8 +7,10 @@ Fetch one delivered message by id. See [Webhooks](/sandboxes/webhooks#deliveries<Note>The delivery provider's attempt index and message store are eventually consistent: a message id can-appear in [list deliveries](/api-reference/webhooks/deliveries-list) a few seconds before this-endpoint can fetch it, so a `404` immediately after a delivery is transient — retry shortly.+appear in [list deliveries](/api-reference/webhooks/deliveries-list) **before** this endpoint (and+[redeliver](/api-reference/webhooks/redeliver)) can resolve it — observed up to ~30s+ after the+attempt. So a `404` shortly after a delivery is transient — **retry with backoff** rather than+treating it as final.</Note><ParamField path="id" type="string" required>diff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.goindex 0849883b..d72fbf8b 100644--- a/internal/api/internal_sandbox.go+++ b/internal/api/internal_sandbox.go@@ -114,6 +114,14 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {// so forks of that sandbox inherited a no-network config.cfg.EnsureNetworkEnabledDefault()+ // Validate inline webhook specs up-front, exactly as the public createSandbox+ // handler does at its entry. Without this the edge→CP create path skips+ // validation, so a bad url or unknown event type 201s (and spawns a sandbox)+ // instead of returning 400. (Prod E2E caught this.)+ if err := validateInlineWebhooks(c.Request().Context(), cfg.Webhooks); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }+// Same memory/cpu defaults the public POST /api/sandboxes applies.if cfg.MemoryMB == 0 {cfg.MemoryMB = 4096