An open-source, faster Devin alternative
TypeScript
chore(webhooks): review round 2 — contract accuracy + compress migrations
Igor Zalutski623376b97217
diff --git a/.agents/work/sandbox-webhooks-rearchitecture.md b/.agents/work/sandbox-webhooks-rearchitecture.mdindex 69870bd7..3055945b 100644--- a/.agents/work/sandbox-webhooks-rearchitecture.md+++ b/.agents/work/sandbox-webhooks-rearchitecture.md@@ -110,6 +110,14 @@ verify path exists here. The edge already has `org_id` on every event and an ide## 3. Target architecture+> **Note (post-implementation):** §3.1–§3.5 and §7 below predate the final+> *all-Svix-at-edge* decision — they still describe an edge `webhook_outbox`, a CP+> local index, and an older build order. The **authoritative** record is §0+> (Decisions locked) + §8 (dev env) + the as-built code. As built: the CP keeps+> only an in-tx outbox (`sandbox_lifecycle_events`) drained by the relay to the+> stream (no edge outbox; delivery handoff is events-ingest's sync Svix create);+> the destination index + `has_webhooks` live in **D1 at the edge**, not the CP.+```CP-origin transition (scaled/forked/preview/migrated/ready/cp-fallback stop)└─ write lifecycle_outbox row IN THE SAME DB TX as the state change [origin durability]diff --git a/docs/sandboxes/webhooks.mdx b/docs/sandboxes/webhooks.mdxindex f794284c..5639ea22 100644--- a/docs/sandboxes/webhooks.mdx+++ b/docs/sandboxes/webhooks.mdx@@ -45,7 +45,7 @@ Subscribe to all events, or filter with `eventTypes` (exact like `sandbox.stoppe## Destinations-A destination is **org-scoped** by default (all your sandboxes), or pinned to one sandbox with `sandboxId`. Set `enabled: false` to **pause** a destination — events that occur while paused are queued and delivered when you re-enable it, not dropped.+A destination is **org-scoped** by default (all your sandboxes), or pinned to one sandbox with `sandboxId`. Set `enabled: false` to **pause** a destination — it stops receiving deliveries until you re-enable it; events that occur while it's paused aren't backfilled.<CodeGroup>@@ -171,7 +171,7 @@ Redelivery re-sends the **same** message to the endpoint (same `svix-id`) — fo## Signing, retries, and dedupe-- **HTTPS only.** Private, loopback, link-local, and cloud-metadata addresses are refused (at registration and at send).+- **HTTPS only**, checked at registration. The delivery layer (Svix) additionally blocks private, loopback, link-local, and cloud-metadata addresses at send time.- **Always signed** with [Standard Webhooks](https://www.standardwebhooks.com) (delivery is by [Svix](https://www.svix.com)). Every request carries `svix-id`, `svix-timestamp`, and `svix-signature` = `v1,<base64(HMAC-SHA256(secret, "{svix-id}.{svix-timestamp}.{rawBody}"))>`. Verify against the **raw request body, before parsing it**; the timestamp guards replay. Any custom headers you attached as destination `metadata` ride along too. Your `secret` is write-only.- **At-least-once.** Once an event is handed off it's retried until it succeeds or the delivery layer gives up. A duplicate can still arrive, so **dedupe on `svix-id`** (= `deliveryId`).- **Not strictly ordered.** Events for one sandbox can arrive out of order (e.g. `sandbox.ready` before `sandbox.created`). Treat each event independently and key off `event.type`; don't assume an ordering.diff --git a/internal/db/migrations/049_sandbox_webhooks.down.sql b/internal/db/migrations/049_sandbox_webhooks.down.sqlindex 5b46451f..32d2e7d8 100644--- a/internal/db/migrations/049_sandbox_webhooks.down.sql+++ b/internal/db/migrations/049_sandbox_webhooks.down.sql@@ -1,4 +1 @@-DROP TABLE IF EXISTS webhook_idempotency_keys;-DROP TABLE IF EXISTS webhook_deliveries;DROP TABLE IF EXISTS sandbox_lifecycle_events;-DROP TABLE IF EXISTS webhook_destinations;diff --git a/internal/db/migrations/049_sandbox_webhooks.up.sql b/internal/db/migrations/049_sandbox_webhooks.up.sqlindex fc3574d2..72b67eb7 100644--- a/internal/db/migrations/049_sandbox_webhooks.up.sql+++ b/internal/db/migrations/049_sandbox_webhooks.up.sql@@ -1,99 +1,15 @@--- Sandbox lifecycle webhooks (.agents/work/sandbox-lifecycle-webhooks.md).--- Four additive tables; no outbox (the deliveries ledger is the work queue).--- The feature is dormant until a destination exists, so this migration is safe--- to apply ahead of the rest of the rollout.---- Subscriptions.-CREATE TABLE IF NOT EXISTS webhook_destinations (- id TEXT PRIMARY KEY, -- 'whk_' + random- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,- name TEXT, -- optional; get-or-create idempotency key- url TEXT NOT NULL, -- https only; SSRF-validated at write + send- event_types TEXT[] NOT NULL DEFAULT '{}', -- empty = all; exact ('sandbox.stopped') or prefix ('sandbox.*')- sandbox_id TEXT, -- optional: scope to one sandbox (NULL = all org sandboxes)- -- signing secret, ALWAYS present (auto-generated 'whsec_…' if not supplied), returned ONCE on- -- create/rotate then write-only. Encrypted via internal/crypto (nonce‖ciphertext bytea).- secret_enc BYTEA NOT NULL,- enabled BOOLEAN NOT NULL DEFAULT true, -- false = paused (pending rows not claimed)- created_after_event_seq BIGINT NOT NULL DEFAULT 0, -- watermark = sandbox_lifecycle_events.seq at- -- creation (skew-free); 0 = no floor- deleted_at TIMESTAMPTZ, -- soft-delete tombstone; history retained- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()-);-CREATE INDEX IF NOT EXISTS webhook_dest_org_idx- ON webhook_destinations (org_id) WHERE enabled AND deleted_at IS NULL;-CREATE UNIQUE INDEX IF NOT EXISTS webhook_dest_name_uq- ON webhook_destinations (org_id, name) WHERE name IS NOT NULL AND deleted_at IS NULL;--- The dormancy gate: "does this org have ANY live destination (enabled OR paused)--- that could receive this event?" — leading org_id, sandbox_id for the scope test.--- (webhook_dest_org_idx above is enabled-only, for the dispatcher's claim.)-CREATE INDEX IF NOT EXISTS webhook_dest_org_live_idx- ON webhook_destinations (org_id, sandbox_id) WHERE deleted_at IS NULL;---- Canonical lifecycle event store — the merge point for both origins. The single--- recordLifecycleEvent primitive inserts here (CP in-tx; worker via the stream--- ingress); the materializer reads it and creates delivery rows. `id` is the--- deterministic event id (dedupe in one place); `seq` is the monotonic watermark.+-- Sandbox lifecycle webhooks (all-Svix-at-edge). The CP's only webhook state is a+-- transient outbox: CP-origin transitions INSERT here in-tx; the relay publishes+-- each row to the cell stream (→ edge → Svix) and deletes it. Destination+-- management + delivery state live at the edge (Svix + the D1 index), not here.+-- See .agents/work/sandbox-webhooks-rearchitecture.md.CREATE TABLE IF NOT EXISTS sandbox_lifecycle_events (- id TEXT PRIMARY KEY, -- deterministic event id- seq BIGSERIAL NOT NULL, -- monotonic; the unified watermark- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,- sandbox_id TEXT NOT NULL,- type TEXT NOT NULL, -- public type, e.g. 'sandbox.stopped'- data JSONB NOT NULL DEFAULT '{}',- ts TIMESTAMPTZ NOT NULL DEFAULT now(),- materialized_at TIMESTAMPTZ -- NULL until the materializer has created deliveries-);-CREATE INDEX IF NOT EXISTS sandbox_lifecycle_events_unmat_idx- ON sandbox_lifecycle_events (seq) WHERE materialized_at IS NULL;---- Delivery ledger (also the work queue).-CREATE TABLE IF NOT EXISTS webhook_deliveries (- id TEXT PRIMARY KEY, -- 'whd_' + random- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,- destination_id TEXT NOT NULL REFERENCES webhook_destinations(id) ON DELETE CASCADE,- event_id TEXT NOT NULL, -- deterministic; dedup- event_type TEXT NOT NULL,- payload JSONB NOT NULL, -- the rendered envelope- -- pending: scheduled | delivering: claimed, in flight | delivered: 2xx (terminal)- -- failed: RETRYABLE, carries a future next_attempt_at | dead_letter: TERMINAL (permanent or exhausted)- -- canceled: TERMINAL (destination soft-deleted while non-terminal)- status TEXT NOT NULL DEFAULT 'pending',- attempts INT NOT NULL DEFAULT 0, -- lifetime total (audit; never reset)- retry_count INT NOT NULL DEFAULT 0, -- retry BUDGET vs MAX_ATTEMPTS; reset on manual redeliver- next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(), -- the timer (meaningful for pending|failed)- locked_by TEXT,- locked_until TIMESTAMPTZ,- response_code INT,- error TEXT,- last_attempt_at TIMESTAMPTZ,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),- delivered_at TIMESTAMPTZ,- UNIQUE (destination_id, event_id), -- idempotent projection- CHECK (status IN ('pending','delivering','delivered','failed','dead_letter','canceled'))-);--- The poll query's index: rows that are due.-CREATE INDEX IF NOT EXISTS webhook_deliveries_due_idx- ON webhook_deliveries (next_attempt_at) WHERE status IN ('pending','failed');-CREATE INDEX IF NOT EXISTS webhook_deliveries_dest_idx- ON webhook_deliveries (destination_id, created_at DESC);---- Idempotency-Key storage for POST /api/webhooks. Same (org,key) + same request--- → replay the stored ORIGINAL RESPONSE (incl. the one-time generated secret);--- same key + different request → 409. response_enc is the rendered create--- response, encrypted (it carries the plaintext secret). Prune past a ~24h TTL.--- Two-phase: a request first RESERVES (org_id,key,request_hash) atomically (so a--- concurrent same-key create can't double-create), then FINALIZES with the--- destination + encrypted response. destination_id/response_enc are therefore--- NULL between reserve and finalize (and a never-finalized claim is released).-CREATE TABLE IF NOT EXISTS webhook_idempotency_keys (- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,- key TEXT NOT NULL, -- caller's Idempotency-Key header- request_hash TEXT NOT NULL, -- fingerprint of the create body- destination_id TEXT REFERENCES webhook_destinations(id) ON DELETE CASCADE,- response_enc BYTEA, -- the original create response (incl. secret), encrypted; NULL until finalized- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- PRIMARY KEY (org_id, key)-);+ id TEXT PRIMARY KEY, -- stable/deterministic event id (dedupe key)+ seq BIGSERIAL NOT NULL, -- FIFO ordering for the relay drain+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+ sandbox_id TEXT NOT NULL,+ type TEXT NOT NULL, -- public type, e.g. 'sandbox.stopped'+ data JSONB NOT NULL DEFAULT '{}',+ ts TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS sandbox_lifecycle_events_seq_idx ON sandbox_lifecycle_events (seq);diff --git a/internal/db/migrations/050_webhooks_edge_cleanup.down.sql b/internal/db/migrations/050_webhooks_edge_cleanup.down.sqldeleted file mode 100644index 115e11b6..00000000--- a/internal/db/migrations/050_webhooks_edge_cleanup.down.sql+++ /dev/null@@ -1,4 +0,0 @@--- Irreversible cleanup: the dropped tables (webhook_destinations,--- webhook_deliveries, webhook_idempotency_keys) belonged to the retired CP-side--- webhook stack. Webhook management + delivery now live at the edge (Svix + D1),--- so there is nothing to restore here. To re-bootstrap, re-run migration 049.diff --git a/internal/db/migrations/050_webhooks_edge_cleanup.up.sql b/internal/db/migrations/050_webhooks_edge_cleanup.up.sqldeleted file mode 100644index 0b41db84..00000000--- a/internal/db/migrations/050_webhooks_edge_cleanup.up.sql+++ /dev/null@@ -1,7 +0,0 @@--- All-Svix-at-edge: webhook destination management + delivery state moved to the--- edge (api-edge → Svix, D1 index). The CP keeps only sandbox_lifecycle_events as--- the transient outbox (relay → cell stream → edge). Drop the now-unused CP tables--- created by migration 049. See .agents/work/sandbox-webhooks-rearchitecture.md.-DROP TABLE IF EXISTS webhook_deliveries CASCADE;-DROP TABLE IF EXISTS webhook_idempotency_keys CASCADE;-DROP TABLE IF EXISTS webhook_destinations CASCADE;diff --git a/internal/db/store.go b/internal/db/store.goindex 3075b78c..5f8a8fb6 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -197,7 +197,6 @@ func (s *Store) Migrate(ctx context.Context) error {{47, "migrations/047_orgs_billing_provider.up.sql"},{48, "migrations/048_orgs_usage_sync_watermark.up.sql"},{49, "migrations/049_sandbox_webhooks.up.sql"},- {50, "migrations/050_webhooks_edge_cleanup.up.sql"},}for _, m := range migrations {diff --git a/pkg/types/webhook.go b/pkg/types/webhook.goindex 1021d986..6887535f 100644--- a/pkg/types/webhook.go+++ b/pkg/types/webhook.go@@ -1,14 +1,11 @@package types-import (- "encoding/json"- "strings"- "time"-)+import "strings"-// Sandbox lifecycle webhook event types (the public taxonomy). Wire values are-// the camelCase/namespaced public names; internal worker strings ("created",-// "running", "migrated") are mapped to these at the ingress.+// Sandbox lifecycle webhook event types (the public taxonomy). The CP records+// these on the outbox; the edge delivers them via Svix. The delivery envelope ++// destination/delivery shapes live at the edge (TS) now, not here.+// See .agents/work/sandbox-webhooks-rearchitecture.md.const (WebhookEventCreated = "sandbox.created"WebhookEventReady = "sandbox.ready"@@ -23,9 +20,8 @@ const (WebhookEventTest = "sandbox.test")-// WebhookEventTypes is the full set of subscribable lifecycle types (excludes-// the synthetic sandbox.test, which is only sent by /test). Some are not emitted-// yet (P3) but are valid to subscribe to in advance.+// WebhookEventTypes is the full set of subscribable lifecycle types (excludes the+// synthetic sandbox.test, which is only sent by /test).var WebhookEventTypes = []string{WebhookEventCreated, WebhookEventReady, WebhookEventHibernated, WebhookEventResumed,WebhookEventStopped, WebhookEventMigrated, WebhookEventCheckpointCreated,@@ -34,7 +30,8 @@ var WebhookEventTypes = []string{// ValidWebhookEventFilter reports whether s is a valid eventTypes entry: an exact// known type, or a "prefix.*" wildcard that matches at least one known type-// (e.g. "sandbox.*", "sandbox.checkpoint.*").+// (e.g. "sandbox.*", "sandbox.checkpoint.*"). The edge expands wildcards to the+// concrete types before registering the Svix endpoint.func ValidWebhookEventFilter(s string) bool {if strings.HasSuffix(s, ".*") {prefix := strings.TrimSuffix(s, "*") // keep the trailing dot, e.g. "sandbox."@@ -53,109 +50,18 @@ func ValidWebhookEventFilter(s string) bool {return false}-// Delivery statuses. failed = retryable (future next_attempt_at); dead_letter &-// canceled are terminal.-const (- WebhookDeliveryPending = "pending"- WebhookDeliveryDelivering = "delivering"- WebhookDeliveryDelivered = "delivered"- WebhookDeliveryFailed = "failed"- WebhookDeliveryDeadLetter = "dead_letter"- WebhookDeliveryCanceled = "canceled"-)--// WebhookDestination is the public (camelCase) representation of a subscription.-// Name and SandboxID are pointers so an unset value serializes as JSON null-// (matching the documented contract). Secret is present ONLY on the create-// response or a generated rotation — never on reads.-type WebhookDestination struct {- ID string `json:"id"`- Name *string `json:"name"`- URL string `json:"url"`- EventTypes []string `json:"eventTypes"`- SandboxID *string `json:"sandboxId"`- Enabled bool `json:"enabled"`- HasSecret bool `json:"hasSecret"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`- Secret string `json:"secret,omitempty"`-}--// CreateWebhookRequest is the POST /api/webhooks body.-type CreateWebhookRequest struct {- URL string `json:"url"`- Name *string `json:"name,omitempty"`- Secret string `json:"secret,omitempty"`- EventTypes []string `json:"eventTypes,omitempty"`- SandboxID *string `json:"sandboxId,omitempty"`- Enabled *bool `json:"enabled,omitempty"`-}--// WebhookDelivery is the public (camelCase) delivery record. Nullable fields are-// pointers so they serialize as JSON null rather than being omitted.-type WebhookDelivery struct {- ID string `json:"id"`- Destination string `json:"destination"`- EventID string `json:"eventId"`- EventType string `json:"eventType"`- Status string `json:"status"`- Attempts int `json:"attempts"`- RetryCount int `json:"retryCount"`- LastAttemptAt *time.Time `json:"lastAttemptAt"`- ResponseCode *int `json:"responseCode"`- Error *string `json:"error"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`- DeliveredAt *time.Time `json:"deliveredAt"`-}--// WebhookDeliveryPage is a cursor-paginated list of deliveries.-type WebhookDeliveryPage struct {- Data []WebhookDelivery `json:"data"`- NextCursor *string `json:"nextCursor"`- HasMore bool `json:"hasMore"`-}--// WebhookTestResult is the synchronous POST /api/webhooks/:id/test response.-type WebhookTestResult struct {- Delivered bool `json:"delivered"`- ResponseCode *int `json:"responseCode"`- Error string `json:"error,omitempty"`-}--// SandboxLifecycleEvent is the lifecycle event nested under `event` in a-// delivery envelope.-type SandboxLifecycleEvent struct {- ID string `json:"id"`- Ts time.Time `json:"ts"`- OrgID string `json:"orgId"`- SandboxID string `json:"sandboxId"`- Type string `json:"type"`- Data json.RawMessage `json:"data"`-}--// SandboxWebhookEnvelope is the JSON body POSTed to a destination. webhook-id-// header == DeliveryID. Metadata is the sandbox's user-set metadata (verbatim,-// for routing without a second lookup); null if unset.-type SandboxWebhookEnvelope struct {- Type string `json:"type"`- SandboxID string `json:"sandboxId"`- EventID string `json:"eventId"`- DeliveryID string `json:"deliveryId"`- Metadata map[string]string `json:"metadata"`- Event SandboxLifecycleEvent `json:"event"`-}--// SandboxWebhookSpec is an inline webhook on POST /api/sandboxes — registered-// atomically with the sandbox and pinned to it, so it catches created/ready.+// SandboxWebhookSpec is an inline webhook on POST /api/sandboxes — pinned to the+// sandbox and registered (via the edge) before it emits `created`. Best-effort: a+// registration failure is logged and the sandbox still creates; check the create+// response's `webhooks` for what actually registered.type SandboxWebhookSpec struct {URL string `json:"url"`Secret string `json:"secret,omitempty"`EventTypes []string `json:"eventTypes,omitempty"`}-// SandboxWebhookResult echoes an inline-registered webhook on the create-// response. Secret is present once iff generated.+// SandboxWebhookResult echoes an inline-registered webhook on the create response.+// Secret is present once iff the edge generated it.type SandboxWebhookResult struct {ID string `json:"id"`URL string `json:"url"`diff --git a/sdks/typescript/src/webhooks.ts b/sdks/typescript/src/webhooks.tsindex 7fd53da5..29ccecf3 100644--- a/sdks/typescript/src/webhooks.ts+++ b/sdks/typescript/src/webhooks.ts@@ -129,30 +129,25 @@ export interface UpdateWebhookParams {// ---- deliveries (the control surface behind a deliveries dashboard) -----export type WebhookDeliveryStatus =- | "pending"- | "delivering"- | "delivered"- | "failed"- | "dead_letter"- | "canceled";+export type WebhookDeliveryStatus = "success" | "pending" | "failed";+/** One Svix delivery attempt to the endpoint (from `deliveries.list`). */export interface WebhookDeliveryRecord {+ /** The message id — the key for `get` / `redeliver`; equals the `svix-id` header. */id: string;- destination: string;- eventId: string;- eventType: string;status: WebhookDeliveryStatus;- /** Lifetime attempt count (audit). */- attempts: number;- /** Retry budget consumed since the last (re)enqueue; reset by a manual redeliver. */- retryCount: number;- lastAttemptAt: string | null;- responseCode: number | null;- error: string | null;- createdAt: string;- updatedAt: string;- deliveredAt: string | null;+ /** The consumer's HTTP response code, when the attempt reached it. */+ responseStatusCode?: number;+ timestamp?: string;+}++/** A delivered message (from `deliveries.get`). */+export interface WebhookMessage {+ id: string;+ eventType?: string;+ eventId?: string;+ payload?: unknown;+ timestamp?: string;}export interface WebhookTestResult {@@ -201,25 +196,18 @@ export class WebhookDeliveries {return h;}- /** List deliveries for a destination (cursor-paginated). */- async list(- destinationId: string,- params: { status?: WebhookDeliveryStatus; cursor?: string; limit?: number } = {},- ): Promise<ListPage<WebhookDeliveryRecord>> {- const q = new URLSearchParams();- if (params.status) q.set("status", params.status);- if (params.cursor) q.set("cursor", params.cursor);- if (params.limit != null) q.set("limit", String(params.limit));- const qs = q.toString();- const resp = await fetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries${qs ? `?${qs}` : ""}`, {+ /** List recent delivery attempts for a destination. */+ async list(destinationId: string): Promise<WebhookDeliveryRecord[]> {+ const resp = await fetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries`, {headers: this.headers,});if (!resp.ok) return fail(resp, "list deliveries");- return resp.json();+ const body = (await resp.json()) as { data?: WebhookDeliveryRecord[] };+ return body.data ?? [];}- /** Fetch one delivery in detail. */- async get(destinationId: string, deliveryId: string): Promise<WebhookDeliveryRecord> {+ /** Fetch one delivered message by id. */+ async get(destinationId: string, deliveryId: string): Promise<WebhookMessage> {const resp = await fetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries/${deliveryId}`, {headers: this.headers,});@@ -228,12 +216,10 @@ export class WebhookDeliveries {}/**- * Re-send any delivery (not only dead-lettered ones). Gives the delivery a fresh retry- * budget and returns the re-enqueued record; the redelivery carries the **same** `webhook-id`,- * so a receiver that dedupes will treat it as the same message — redelivery is for cases- * where the original never landed.+ * Re-send a message to the endpoint. The redelivery carries the **same** `svix-id`, so a+ * receiver that dedupes treats it as the same message — for when the original never landed.*/- async redeliver(destinationId: string, deliveryId: string): Promise<WebhookDeliveryRecord> {+ async redeliver(destinationId: string, deliveryId: string): Promise<{ ok: boolean }> {const resp = await fetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries/${deliveryId}/redeliver`, {method: "POST",headers: this.headers,