Skip to content

An open-source, faster Devin alternative

TypeScript

feat(webhooks): create idempotency via Idempotency-Key

Igor Zalutski65cb2663a20c
diff --git a/cloudflare-workers/api-edge/src/webhooks.ts b/cloudflare-workers/api-edge/src/webhooks.ts
index badbf38f..b16d3854 100644
--- a/cloudflare-workers/api-edge/src/webhooks.ts
+++ b/cloudflare-workers/api-edge/src/webhooks.ts
@@ -322,6 +322,18 @@ async function createWebhook(req: Request, env: WebhookEnv, sx: SvixClient, call
return json({ error: `unknown event type(s): ${badTypes.join(", ")}` }, 400);
}
+ // Idempotency: a retried create with the same Idempotency-Key returns the same
+ // destination (200) instead of a duplicate. Fast path — replay a prior claim.
+ const idemKey = req.headers.get("Idempotency-Key") ?? undefined;
+ if (idemKey) {
+ const prior = await env.OPENCOMPUTER_DB.prepare(
+ "SELECT destination_id 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);
+ }
+
const { wire, secret } = await createDestination(env, sx, caller.orgID, {
url: body.url,
eventTypes: body.eventTypes,
@@ -331,10 +343,59 @@ async function createWebhook(req: Request, env: WebhookEnv, sx: SvixClient, call
secret: body.secret,
enabled: body.enabled,
});
- // Secret is returned once on create (Svix-generated; always re-fetchable via Svix).
+
+ if (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",
+ )
+ .bind(caller.orgID, idemKey, wire.id, nowSec())
+ .run();
+ const winner = await env.OPENCOMPUTER_DB.prepare(
+ "SELECT destination_id FROM webhook_idempotency WHERE org_id = ?1 AND idempotency_key = ?2",
+ )
+ .bind(caller.orgID, idemKey)
+ .first<{ destination_id: string }>();
+ if (winner && winner.destination_id !== wire.id) {
+ // Lost a concurrent race — drop our just-created duplicate, return the winner.
+ await deleteDestinationById(env, sx, caller.orgID, wire.id as string);
+ return idempotentReplay(env, sx, caller, winner.destination_id);
+ }
+ }
+ // Secret is returned on create (Svix-generated unless supplied; re-fetchable via GET /:id/secret).
return json({ ...wire, secret }, 201);
}
+// 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> {
+ const row = await getDest(env, caller.orgID, destId);
+ if (!row) return json({ error: "webhook not found" }, 404); // tombstoned/cross-org — shouldn't happen
+ let secret: string | undefined;
+ try {
+ secret = await sx.getEndpointSecret(row.svix_app_id, row.svix_endpoint_id);
+ } catch {
+ /* best-effort: omit secret, it's re-fetchable via GET /:id/secret */
+ }
+ return json(secret ? { ...toWire(row), secret } : toWire(row), 200);
+}
+
+// deleteDestinationById removes the Svix endpoint + soft-deletes the row. Used to
+// clean up the loser of a concurrent idempotent-create race.
+async function deleteDestinationById(env: WebhookEnv, sx: SvixClient, orgID: string, id: string): Promise<void> {
+ const row = await getDest(env, orgID, id);
+ if (!row) return;
+ try {
+ await sx.deleteEndpoint(row.svix_app_id, row.svix_endpoint_id);
+ } catch {
+ /* best-effort */
+ }
+ await env.OPENCOMPUTER_DB.prepare("UPDATE webhook_destinations SET deleted_at = ?1 WHERE id = ?2")
+ .bind(nowSec(), id)
+ .run();
+ await refreshHasWebhooks(env, orgID);
+}
+
async function listWebhooks(env: WebhookEnv, caller: Caller): Promise<Response> {
const rows = await env.OPENCOMPUTER_DB.prepare(
"SELECT * FROM webhook_destinations WHERE org_id = ?1 AND deleted_at IS NULL ORDER BY created_at DESC",
diff --git a/cloudflare-workers/schema_phase8_webhooks.sql b/cloudflare-workers/schema_phase8_webhooks.sql
index 2e286339..eace7f64 100644
--- a/cloudflare-workers/schema_phase8_webhooks.sql
+++ b/cloudflare-workers/schema_phase8_webhooks.sql
@@ -27,3 +27,15 @@ CREATE INDEX IF NOT EXISTS webhook_dest_org_idx
ON webhook_destinations (org_id) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS webhook_dest_svix_ep_idx
ON webhook_destinations (svix_endpoint_id);
+
+-- Create idempotency: a (org, Idempotency-Key) → destination map so a retried
+-- POST /api/webhooks returns the SAME destination instead of a duplicate. The
+-- PK makes the claim atomic; a concurrent loser deletes its just-created dup and
+-- returns the winner's row (see api-edge createWebhook).
+CREATE TABLE IF NOT EXISTS webhook_idempotency (
+ org_id TEXT NOT NULL,
+ idempotency_key TEXT NOT NULL,
+ destination_id TEXT NOT NULL,
+ created_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.mdx
index 7175587d..1c050e6a 100644
--- a/docs/api-reference/webhooks/create.mdx
+++ b/docs/api-reference/webhooks/create.mdx
@@ -29,7 +29,11 @@ Register a webhook destination for sandbox lifecycle events. See [Webhooks](/san
Whether the destination is active. Default `true`. `false` pauses delivery.
</ParamField>
-Each call creates a **new** destination and returns **`201`** — there is no get-or-create and no `Idempotency-Key` support.
+<ParamField header="Idempotency-Key" type="string">
+ Optional. A retried create with the same key returns the **same** destination (`200`) instead of creating a duplicate.
+</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`**.
**Validation (all `400`):** `url` must be HTTPS; each `eventTypes` entry must be a known sandbox event type or a `prefix.*` wildcard.
diff --git a/sdks/typescript/src/webhooks.ts b/sdks/typescript/src/webhooks.ts
index 967b4473..994a59d0 100644
--- a/sdks/typescript/src/webhooks.ts
+++ b/sdks/typescript/src/webhooks.ts
@@ -104,6 +104,8 @@ export interface CreateWebhookParams {
/** Scope to one sandbox; omit for all of the org's sandboxes. */
sandboxId?: string;
enabled?: boolean;
+ /** Idempotency-Key: a retried create with the same key returns the same destination (200), never a duplicate. */
+ idempotencyKey?: string;
}
/** The create response — includes the signing `secret` (also re-fetchable later via {@link Webhooks.getSecret}). */
@@ -254,15 +256,17 @@ export class Webhooks {
}
/**
- * Register a destination (HTTP 201). Each call creates a new destination — there is no
- * get-or-create. The response includes the signing `secret` (also re-fetchable later via
- * {@link getSecret}). Unknown `eventTypes` are rejected with a 400.
+ * Register a destination (HTTP 201). Without an `idempotencyKey`, each call creates a new
+ * destination — there is no get-or-create. With one, a retried call returns the same destination
+ * (HTTP 200) instead of a duplicate. The response includes the signing `secret` (also re-fetchable
+ * later via {@link getSecret}). Unknown `eventTypes` are rejected with a 400.
*/
async create(params: CreateWebhookParams): Promise<CreateWebhookResult> {
+ const { idempotencyKey, ...body } = params;
const resp = await fetch(`${this.apiUrl}/webhooks`, {
method: "POST",
- headers: this.headers(),
- body: JSON.stringify(params),
+ headers: this.headers(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined),
+ body: JSON.stringify(body),
});
if (!resp.ok) return fail(resp, "create webhook");
return resp.json();