Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(webhook): add in webhook namespace support (#5400)
Will Hutchinson08717084d3a5
diff --git a/.sqlx/query-199c0cb77a4f34154fc85bb27392e1a89b9cc268f3a5b239bd628efba4e667a0.json b/.sqlx/query-199c0cb77a4f34154fc85bb27392e1a89b9cc268f3a5b239bd628efba4e667a0.jsondeleted file mode 100644index 9dbc4f27be..0000000000--- a/.sqlx/query-199c0cb77a4f34154fc85bb27392e1a89b9cc268f3a5b239bd628efba4e667a0.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO webhook (\n id, workspace_id, name, endpoint_url, signing_secret, headers,\n filters, status, is_valid, created_by_user_id\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, false, $9)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Text",- "Text",- "Text",- "Text",- "Jsonb",- "Jsonb",- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "199c0cb77a4f34154fc85bb27392e1a89b9cc268f3a5b239bd628efba4e667a0"-}diff --git a/.sqlx/query-cc37bd1f7c61dc4f15e72880577d363ca24b1abe3c8cd286735a26db5bc856d5.json b/.sqlx/query-55f6bf64d79cd6e8164676f45ef5880a0011b48c83c7d0d469b66a93ce80d75f.jsonsimilarity index 73%rename from .sqlx/query-cc37bd1f7c61dc4f15e72880577d363ca24b1abe3c8cd286735a26db5bc856d5.jsonrename to .sqlx/query-55f6bf64d79cd6e8164676f45ef5880a0011b48c83c7d0d469b66a93ce80d75f.jsonindex 28943e067d..c9257f392d 100644--- a/.sqlx/query-cc37bd1f7c61dc4f15e72880577d363ca24b1abe3c8cd286735a26db5bc856d5.json+++ b/.sqlx/query-55f6bf64d79cd6e8164676f45ef5880a0011b48c83c7d0d469b66a93ce80d75f.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n w.id,\n w.workspace_id,\n w.name,\n w.endpoint_url,\n w.signing_secret,\n w.headers,\n w.status,\n w.is_valid,\n w.created_by_user_id,\n w.created_at,\n w.updated_at,\n w.deleted_at,\n w.filters\n FROM webhook w\n WHERE w.id = $1\n AND w.deleted_at IS NULL\n ",+ "query": "\n SELECT\n w.id,\n w.workspace_id,\n w.namespace,\n w.name,\n w.endpoint_url,\n w.signing_secret,\n w.headers,\n w.status,\n w.is_valid,\n w.created_by_user_id,\n w.created_at,\n w.updated_at,\n w.deleted_at,\n w.filters\n FROM webhook w\n WHERE w.id = $1\n AND w.deleted_at IS NULL\n ","describe": {"columns": [{@@ -15,56 +15,61 @@},{"ordinal": 2,- "name": "name",+ "name": "namespace","type_info": "Text"},{"ordinal": 3,- "name": "endpoint_url",+ "name": "name","type_info": "Text"},{"ordinal": 4,- "name": "signing_secret",+ "name": "endpoint_url","type_info": "Text"},{"ordinal": 5,+ "name": "signing_secret",+ "type_info": "Text"+ },+ {+ "ordinal": 6,"name": "headers","type_info": "Jsonb"},{- "ordinal": 6,+ "ordinal": 7,"name": "status","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "is_valid","type_info": "Bool"},{- "ordinal": 8,+ "ordinal": 9,"name": "created_by_user_id","type_info": "Text"},{- "ordinal": 9,+ "ordinal": 10,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 10,+ "ordinal": 11,"name": "updated_at","type_info": "Timestamptz"},{- "ordinal": 11,+ "ordinal": 12,"name": "deleted_at","type_info": "Timestamptz"},{- "ordinal": 12,+ "ordinal": 13,"name": "filters","type_info": "Jsonb"}@@ -86,9 +91,10 @@false,false,false,+ false,true,false]},- "hash": "cc37bd1f7c61dc4f15e72880577d363ca24b1abe3c8cd286735a26db5bc856d5"+ "hash": "55f6bf64d79cd6e8164676f45ef5880a0011b48c83c7d0d469b66a93ce80d75f"}diff --git a/.sqlx/query-35cbfa36e3f14269f1bb5e18ab3a1d67a27f633f50736f8e92c59344b209b801.json b/.sqlx/query-7020a05c36af72e70266be78038707b0f1470066ddd9a93bbde438babb1c5fee.jsonsimilarity index 75%rename from .sqlx/query-35cbfa36e3f14269f1bb5e18ab3a1d67a27f633f50736f8e92c59344b209b801.jsonrename to .sqlx/query-7020a05c36af72e70266be78038707b0f1470066ddd9a93bbde438babb1c5fee.jsonindex 77f31f2e3f..a0affffd21 100644--- a/.sqlx/query-35cbfa36e3f14269f1bb5e18ab3a1d67a27f633f50736f8e92c59344b209b801.json+++ b/.sqlx/query-7020a05c36af72e70266be78038707b0f1470066ddd9a93bbde438babb1c5fee.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n d.id AS delivery_id,\n d.status AS delivery_status,\n d.attempt_count,\n d.next_attempt_at,\n w.id AS webhook_id,\n w.workspace_id,\n w.name,\n w.endpoint_url,\n w.signing_secret,\n w.headers,\n w.status AS webhook_status,\n w.is_valid,\n w.created_by_user_id,\n w.created_at,\n w.updated_at,\n w.deleted_at,\n w.filters\n FROM webhook_delivery d\n JOIN webhook w ON w.id = d.webhook_id\n WHERE d.webhook_id = $1\n AND d.event_id = $2\n ",+ "query": "\n SELECT\n d.id AS delivery_id,\n d.status AS delivery_status,\n d.attempt_count,\n d.next_attempt_at,\n w.id AS webhook_id,\n w.workspace_id,\n w.namespace,\n w.name,\n w.endpoint_url,\n w.signing_secret,\n w.headers,\n w.status AS webhook_status,\n w.is_valid,\n w.created_by_user_id,\n w.created_at,\n w.updated_at,\n w.deleted_at,\n w.filters\n FROM webhook_delivery d\n JOIN webhook w ON w.id = d.webhook_id\n WHERE d.webhook_id = $1\n AND d.event_id = $2\n ","describe": {"columns": [{@@ -35,56 +35,61 @@},{"ordinal": 6,- "name": "name",+ "name": "namespace","type_info": "Text"},{"ordinal": 7,- "name": "endpoint_url",+ "name": "name","type_info": "Text"},{"ordinal": 8,- "name": "signing_secret",+ "name": "endpoint_url","type_info": "Text"},{"ordinal": 9,+ "name": "signing_secret",+ "type_info": "Text"+ },+ {+ "ordinal": 10,"name": "headers","type_info": "Jsonb"},{- "ordinal": 10,+ "ordinal": 11,"name": "webhook_status","type_info": "Text"},{- "ordinal": 11,+ "ordinal": 12,"name": "is_valid","type_info": "Bool"},{- "ordinal": 12,+ "ordinal": 13,"name": "created_by_user_id","type_info": "Text"},{- "ordinal": 13,+ "ordinal": 14,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 14,+ "ordinal": 15,"name": "updated_at","type_info": "Timestamptz"},{- "ordinal": 15,+ "ordinal": 16,"name": "deleted_at","type_info": "Timestamptz"},{- "ordinal": 16,+ "ordinal": 17,"name": "filters","type_info": "Jsonb"}@@ -111,9 +116,10 @@false,false,false,+ false,true,false]},- "hash": "35cbfa36e3f14269f1bb5e18ab3a1d67a27f633f50736f8e92c59344b209b801"+ "hash": "7020a05c36af72e70266be78038707b0f1470066ddd9a93bbde438babb1c5fee"}diff --git a/.sqlx/query-789032d7c308dd2faedd24387f78362acb64f8f8b530c4bb54512c3aabce57c2.json b/.sqlx/query-789032d7c308dd2faedd24387f78362acb64f8f8b530c4bb54512c3aabce57c2.jsonnew file mode 100644index 0000000000..4718e57588--- /dev/null+++ b/.sqlx/query-789032d7c308dd2faedd24387f78362acb64f8f8b530c4bb54512c3aabce57c2.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO webhook (\n id, workspace_id, namespace, name, endpoint_url, signing_secret, headers,\n filters, status, is_valid, created_by_user_id\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, false, $10)\n ON CONFLICT (workspace_id, namespace) WHERE deleted_at IS NULL DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Jsonb",+ "Jsonb",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "789032d7c308dd2faedd24387f78362acb64f8f8b530c4bb54512c3aabce57c2"+}diff --git a/.sqlx/query-f151dbffae8ee031399d76f39e78b3e008eb2a93a170a4c6764e988502738570.json b/.sqlx/query-8d07edbac300d8210fde997e9872e8963f71911ff794a8f0e0c8b65cfe799855.jsonsimilarity index 59%rename from .sqlx/query-f151dbffae8ee031399d76f39e78b3e008eb2a93a170a4c6764e988502738570.jsonrename to .sqlx/query-8d07edbac300d8210fde997e9872e8963f71911ff794a8f0e0c8b65cfe799855.jsonindex 6756af2ac7..155b0dc000 100644--- a/.sqlx/query-f151dbffae8ee031399d76f39e78b3e008eb2a93a170a4c6764e988502738570.json+++ b/.sqlx/query-8d07edbac300d8210fde997e9872e8963f71911ff794a8f0e0c8b65cfe799855.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n w.id,\n w.workspace_id,\n w.name,\n w.endpoint_url,\n w.signing_secret,\n w.headers,\n w.status,\n w.is_valid,\n w.created_by_user_id,\n w.created_at,\n w.updated_at,\n w.deleted_at,\n w.filters\n FROM webhook w\n WHERE w.workspace_id = ANY($1)\n AND w.deleted_at IS NULL\n AND w.status = 'active'\n AND w.is_valid\n AND w.filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($2::text)))\n AND jsonb_path_exists(\n w.filters,\n '$[*] ? (@.events[*] == $event && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',\n jsonb_build_object('event', $2::text, 'id', $3::text)\n )\n ORDER BY w.id\n ",+ "query": "\n SELECT\n w.id,\n w.workspace_id,\n w.namespace,\n w.name,\n w.endpoint_url,\n w.signing_secret,\n w.headers,\n w.status,\n w.is_valid,\n w.created_by_user_id,\n w.created_at,\n w.updated_at,\n w.deleted_at,\n w.filters\n FROM webhook w\n WHERE w.workspace_id = ANY($1)\n AND w.deleted_at IS NULL\n AND w.status = 'active'\n AND w.is_valid\n AND w.filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($2::text)))\n AND jsonb_path_exists(\n w.filters,\n '$[*] ? (@.events[*] == $event && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',\n jsonb_build_object('event', $2::text, 'id', $3::text)\n )\n ORDER BY w.id\n ","describe": {"columns": [{@@ -15,56 +15,61 @@},{"ordinal": 2,- "name": "name",+ "name": "namespace","type_info": "Text"},{"ordinal": 3,- "name": "endpoint_url",+ "name": "name","type_info": "Text"},{"ordinal": 4,- "name": "signing_secret",+ "name": "endpoint_url","type_info": "Text"},{"ordinal": 5,+ "name": "signing_secret",+ "type_info": "Text"+ },+ {+ "ordinal": 6,"name": "headers","type_info": "Jsonb"},{- "ordinal": 6,+ "ordinal": 7,"name": "status","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "is_valid","type_info": "Bool"},{- "ordinal": 8,+ "ordinal": 9,"name": "created_by_user_id","type_info": "Text"},{- "ordinal": 9,+ "ordinal": 10,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 10,+ "ordinal": 11,"name": "updated_at","type_info": "Timestamptz"},{- "ordinal": 11,+ "ordinal": 12,"name": "deleted_at","type_info": "Timestamptz"},{- "ordinal": 12,+ "ordinal": 13,"name": "filters","type_info": "Jsonb"}@@ -88,9 +93,10 @@false,false,false,+ false,true,false]},- "hash": "f151dbffae8ee031399d76f39e78b3e008eb2a93a170a4c6764e988502738570"+ "hash": "8d07edbac300d8210fde997e9872e8963f71911ff794a8f0e0c8b65cfe799855"}diff --git a/.sqlx/query-c4eb16cfa4a17d4f2112e65cb449b726fdda45337b2b8a29990e160f97141693.json b/.sqlx/query-a3bd2e47243ebe0905fcc2e9bc4d30d89a3043995ed5e4289613ca9cfc56517b.jsonsimilarity index 68%rename from .sqlx/query-c4eb16cfa4a17d4f2112e65cb449b726fdda45337b2b8a29990e160f97141693.jsonrename to .sqlx/query-a3bd2e47243ebe0905fcc2e9bc4d30d89a3043995ed5e4289613ca9cfc56517b.jsonindex e78639ac0a..6a779c4f2c 100644--- a/.sqlx/query-c4eb16cfa4a17d4f2112e65cb449b726fdda45337b2b8a29990e160f97141693.json+++ b/.sqlx/query-a3bd2e47243ebe0905fcc2e9bc4d30d89a3043995ed5e4289613ca9cfc56517b.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n w.id,\n w.workspace_id,\n w.name,\n w.endpoint_url,\n w.signing_secret,\n w.headers,\n w.status,\n w.is_valid,\n w.created_by_user_id,\n w.created_at,\n w.updated_at,\n w.deleted_at,\n w.filters\n FROM webhook w\n WHERE w.workspace_id = ANY($1)\n AND w.deleted_at IS NULL\n ORDER BY w.created_at DESC, w.id DESC\n ",+ "query": "\n SELECT\n w.id,\n w.workspace_id,\n w.namespace,\n w.name,\n w.endpoint_url,\n w.signing_secret,\n w.headers,\n w.status,\n w.is_valid,\n w.created_by_user_id,\n w.created_at,\n w.updated_at,\n w.deleted_at,\n w.filters\n FROM webhook w\n WHERE w.workspace_id = ANY($1)\n AND w.deleted_at IS NULL\n ORDER BY w.created_at DESC, w.id DESC\n ","describe": {"columns": [{@@ -15,56 +15,61 @@},{"ordinal": 2,- "name": "name",+ "name": "namespace","type_info": "Text"},{"ordinal": 3,- "name": "endpoint_url",+ "name": "name","type_info": "Text"},{"ordinal": 4,- "name": "signing_secret",+ "name": "endpoint_url","type_info": "Text"},{"ordinal": 5,+ "name": "signing_secret",+ "type_info": "Text"+ },+ {+ "ordinal": 6,"name": "headers","type_info": "Jsonb"},{- "ordinal": 6,+ "ordinal": 7,"name": "status","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "is_valid","type_info": "Bool"},{- "ordinal": 8,+ "ordinal": 9,"name": "created_by_user_id","type_info": "Text"},{- "ordinal": 9,+ "ordinal": 10,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 10,+ "ordinal": 11,"name": "updated_at","type_info": "Timestamptz"},{- "ordinal": 11,+ "ordinal": 12,"name": "deleted_at","type_info": "Timestamptz"},{- "ordinal": 12,+ "ordinal": 13,"name": "filters","type_info": "Jsonb"}@@ -86,9 +91,10 @@false,false,false,+ false,true,false]},- "hash": "c4eb16cfa4a17d4f2112e65cb449b726fdda45337b2b8a29990e160f97141693"+ "hash": "a3bd2e47243ebe0905fcc2e9bc4d30d89a3043995ed5e4289613ca9cfc56517b"}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookRequest.tsindex 6070a15a3e..bbddaec471 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookRequest.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookRequest.ts@@ -20,6 +20,9 @@ export interface CreateWebhookRequest {headers?: CreateWebhookRequestHeaders;/** Display name. */name: string;+ /** Caller-chosen namespace, unique among the owning workspace's webhooks.+Set at creation time only; it cannot be changed afterwards. */+ namespace: string;/** Scope that owns the webhook. */scope: WebhookScope;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookResponse.tsindex 1ecc54b6a3..2e3441ca30 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookResponse.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookResponse.ts@@ -33,6 +33,9 @@ export interface CreateWebhookResponse {is_valid: boolean;/** Display name. */name: string;+ /** Caller-chosen namespace, unique among the owning workspace's webhooks.+Set at creation time only; it cannot be changed afterwards. */+ namespace: string;/** Signing secret used to verify webhook delivery signatures. */signing_secret: string;/** Webhook lifecycle status. */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchWebhookRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchWebhookRequest.tsindex 61f1555f2e..ca086074ad 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchWebhookRequest.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchWebhookRequest.ts@@ -11,7 +11,8 @@ import type { PatchWebhookRequestName } from './patchWebhookRequestName';import type { PatchWebhookRequestStatus } from './patchWebhookRequestStatus';/**- * Request to patch a webhook.+ * Request to patch a webhook. The webhook's namespace is fixed at creation+time and is deliberately not patchable.*/export interface PatchWebhookRequest {/** Endpoint URL. HTTPS is required outside local environments. */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhook.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhook.tsindex 7b1f50072e..6e041cf479 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhook.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhook.ts@@ -33,6 +33,9 @@ export interface Webhook {is_valid: boolean;/** Display name. */name: string;+ /** Caller-chosen namespace, unique among the owning workspace's webhooks.+Set at creation time only; it cannot be changed afterwards. */+ namespace: string;/** Webhook lifecycle status. */status: WebhookStatus;/** Update timestamp. */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex b027205f91..baa3b2e19f 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -24315,6 +24315,11 @@ export const listWebhooksResponse = zod'Whether the current endpoint configuration has passed validation.'),name: zod.string().describe('Display name.'),+ namespace: zod+ .string()+ .describe(+ "Caller-chosen namespace, unique among the owning workspace's webhooks.\nSet at creation time only; it cannot be changed afterwards."+ ),status: zod.enum(['active', 'paused', 'disabled']).describe('Webhook lifecycle status.'),@@ -24360,6 +24365,11 @@ export const createWebhookBody = zod.union([zod.null(), zod.record(zod.string(), zod.string())]).optional(),name: zod.string().describe('Display name.'),+ namespace: zod+ .string()+ .describe(+ "Caller-chosen namespace, unique among the owning workspace's webhooks.\nSet at creation time only; it cannot be changed afterwards."+ ),scope: zod.enum(['user', 'team']).describe('Scope that owns a newly-created webhook.'),@@ -24409,6 +24419,11 @@ export const getWebhookResponse = zod'Whether the current endpoint configuration has passed validation.'),name: zod.string().describe('Display name.'),+ namespace: zod+ .string()+ .describe(+ "Caller-chosen namespace, unique among the owning workspace's webhooks.\nSet at creation time only; it cannot be changed afterwards."+ ),status: zod.enum(['active', 'paused', 'disabled']).describe('Webhook lifecycle status.'),@@ -24472,7 +24487,9 @@ export const patchWebhookBody = zod]).optional(),})- .describe('Request to patch a webhook.');+ .describe(+ "Request to patch a webhook. The webhook's namespace is fixed at creation\ntime and is deliberately not patchable."+ );export const patchWebhookResponse = zod.object({@@ -24510,6 +24527,11 @@ export const patchWebhookResponse = zod'Whether the current endpoint configuration has passed validation.'),name: zod.string().describe('Display name.'),+ namespace: zod+ .string()+ .describe(+ "Caller-chosen namespace, unique among the owning workspace's webhooks.\nSet at creation time only; it cannot be changed afterwards."+ ),status: zod.enum(['active', 'paused', 'disabled']).describe('Webhook lifecycle status.'),diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 492709d071..f8db98f506 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -10268,6 +10268,16 @@}}},+ "409": {+ "description": "Namespace already used in the workspace",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "Internal server error","content": {@@ -14804,7 +14814,7 @@"CreateWebhookRequest": {"type": "object","description": "Request to create a webhook.",- "required": ["scope", "name", "endpoint_url", "filters"],+ "required": ["scope", "namespace", "name", "endpoint_url", "filters"],"properties": {"endpoint_url": {"type": "string",@@ -14829,6 +14839,10 @@"type": "string","description": "Display name."},+ "namespace": {+ "type": "string",+ "description": "Caller-chosen namespace, unique among the owning workspace's webhooks.\nSet at creation time only; it cannot be changed afterwards."+ },"scope": {"$ref": "#/components/schemas/WebhookScope","description": "Scope that owns the webhook."@@ -14841,6 +14855,7 @@"required": ["id","workspace_id",+ "namespace","name","endpoint_url","signing_secret",@@ -14891,6 +14906,10 @@"type": "string","description": "Display name."},+ "namespace": {+ "type": "string",+ "description": "Caller-chosen namespace, unique among the owning workspace's webhooks.\nSet at creation time only; it cannot be changed afterwards."+ },"signing_secret": {"type": "string","description": "Signing secret used to verify webhook delivery signatures."@@ -19130,7 +19149,7 @@},"PatchWebhookRequest": {"type": "object",- "description": "Request to patch a webhook.",+ "description": "Request to patch a webhook. The webhook's namespace is fixed at creation\ntime and is deliberately not patchable.","properties": {"endpoint_url": {"type": ["string", "null"],@@ -22964,6 +22983,7 @@"required": ["id","workspace_id",+ "namespace","name","endpoint_url","headers",@@ -23013,6 +23033,10 @@"type": "string","description": "Display name."},+ "namespace": {+ "type": "string",+ "description": "Caller-chosen namespace, unique among the owning workspace's webhooks.\nSet at creation time only; it cannot be changed afterwards."+ },"status": {"$ref": "#/components/schemas/WebhookStatus","description": "Webhook lifecycle status."diff --git a/crates/macro_db_client/migrations/20260804160907_webhook_namespace.down.sql b/crates/macro_db_client/migrations/20260804160907_webhook_namespace.down.sqlnew file mode 100644index 0000000000..584278d6cf--- /dev/null+++ b/crates/macro_db_client/migrations/20260804160907_webhook_namespace.down.sql@@ -0,0 +1,3 @@+DROP INDEX webhook_workspace_namespace_uq;++ALTER TABLE webhook DROP COLUMN namespace;diff --git a/crates/macro_db_client/migrations/20260804160907_webhook_namespace.up.sql b/crates/macro_db_client/migrations/20260804160907_webhook_namespace.up.sqlnew file mode 100644index 0000000000..03aa8b4615--- /dev/null+++ b/crates/macro_db_client/migrations/20260804160907_webhook_namespace.up.sql@@ -0,0 +1,12 @@+-- Add a caller-chosen namespace to webhooks, unique per owning workspace.+-- Existing rows receive a random UUID so the column can be NOT NULL.+ALTER TABLE webhook ADD COLUMN namespace TEXT;++UPDATE webhook SET namespace = gen_random_uuid()::text;++ALTER TABLE webhook ALTER COLUMN namespace SET NOT NULL;++-- Partial unique index: soft-deleted webhooks release their namespace for reuse.+CREATE UNIQUE INDEX webhook_workspace_namespace_uq+ ON webhook (workspace_id, namespace)+ WHERE deleted_at IS NULL;diff --git a/crates/webhook/src/domain/delivery/test.rs b/crates/webhook/src/domain/delivery/test.rsindex da3149b60f..5f9e055846 100644--- a/crates/webhook/src/domain/delivery/test.rs+++ b/crates/webhook/src/domain/delivery/test.rs@@ -49,6 +49,7 @@ fn webhook(endpoint_url: &str) -> Webhook {Webhook {id: WEBHOOK_ID.to_string(),workspace_id: "macro|[email protected]".to_string(),+ namespace: "delivery-test".to_string(),name: "Delivery test".to_string(),endpoint_url: endpoint_url.to_string(),signing_secret: "whsec_current".to_string(),diff --git a/crates/webhook/src/domain/events.rs b/crates/webhook/src/domain/events.rsindex b14ca89be6..58f726c7ea 100644--- a/crates/webhook/src/domain/events.rs+++ b/crates/webhook/src/domain/events.rs@@ -22,6 +22,13 @@ pub struct WebhookCreatedMetadata {pub webhook_id: String,/// Identifier of the workspace that owns the webhook.pub workspace_id: String,+ /// Caller-chosen namespace, unique among the workspace's webhooks.+ ///+ /// Defaults to an empty string when decoding schema-version-1 payloads+ /// persisted before namespaces existed; serialized payloads always+ /// include it.+ #[serde(default)]+ pub namespace: String,/// Authenticated user who created the webhook.pub created_by_user_id: MacroUserIdStr<'static>,/// Display name of the webhook.diff --git a/crates/webhook/src/domain/events/test.rs b/crates/webhook/src/domain/events/test.rsindex 09fc241d56..65db07b419 100644--- a/crates/webhook/src/domain/events/test.rs+++ b/crates/webhook/src/domain/events/test.rs@@ -40,6 +40,7 @@ fn created_event_has_exact_sanitized_wire_shape() {WebhookTopicEvent::Created(WebhookCreatedMetadata {webhook_id: WEBHOOK_ID.to_string(),workspace_id: WORKSPACE_ID.to_string(),+ namespace: "document-updates".to_string(),created_by_user_id: user_id("macro|[email protected]"),name: "Document updates".to_string(),endpoint_url: "https://example.com/hooks/macro".to_string(),@@ -60,6 +61,7 @@ fn created_event_has_exact_sanitized_wire_shape() {"metadata": {"webhook_id": WEBHOOK_ID,"workspace_id": WORKSPACE_ID,+ "namespace": "document-updates","created_by_user_id": "macro|[email protected]","name": "Document updates","endpoint_url": "https://example.com/hooks/macro",@@ -189,6 +191,35 @@ fn validated_event_has_exact_sanitized_wire_shape() {);}+#[test]+fn decodes_v1_created_payload_persisted_before_namespaces_existed() {+ let payload = serde_json::to_vec(&json!({+ "event_id": "01998a30-1a2b-7c3d-9e4f-5a6b7c8d9e0f",+ "schema_version": 1,+ "event_type": "webhook.created",+ "metadata": {+ "webhook_id": WEBHOOK_ID,+ "workspace_id": WORKSPACE_ID,+ "created_by_user_id": "macro|[email protected]",+ "name": "Document updates",+ "endpoint_url": "https://example.com/hooks/macro",+ "status": "active",+ "is_valid": false,+ "filters": [],+ "header_names": [],+ "created_at": "2026-07-20T17:01:02Z",+ },+ }))+ .expect("serializable payload");++ let decoded = WebhookMacroEvent::decode(WEBHOOK_ID, &payload).expect("decodable v1 event");+ let WebhookTopicEvent::Created(metadata) = &decoded.event().event else {+ panic!("expected a created event");+ };+ assert_eq!(metadata.namespace, "");+ assert_eq!(metadata.webhook_id, WEBHOOK_ID);+}+#[test]fn constructors_key_events_by_subject_webhook_id() {let cases = [@@ -197,6 +228,7 @@ fn constructors_key_events_by_subject_webhook_id() {WebhookCreatedMetadata {webhook_id: WEBHOOK_ID.to_string(),workspace_id: WORKSPACE_ID.to_string(),+ namespace: "lifecycle-events".to_string(),created_by_user_id: user_id("macro|[email protected]"),name: "Lifecycle events".to_string(),endpoint_url: "https://example.com/hooks/macro".to_string(),@@ -269,6 +301,7 @@ fn macro_event_round_trips_without_exposing_secrets_or_header_values() {WebhookCreatedMetadata {webhook_id: WEBHOOK_ID.to_string(),workspace_id: WORKSPACE_ID.to_string(),+ namespace: "lifecycle-events".to_string(),created_by_user_id: user_id("macro|[email protected]"),name: "Lifecycle events".to_string(),endpoint_url: "https://example.com/hooks/macro".to_string(),diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex e81889d744..8452946fcc 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -5,7 +5,8 @@ use crate::domain::{WebhookValidatedMetadata,},models::{- CreateWebhookRequest, PatchWebhookRequest, Webhook, WebhookEventQueueMessage, WebhookStatus,+ CreateWebhookOutcome, CreateWebhookRequest, PatchWebhookRequest, Webhook,+ WebhookEventQueueMessage, WebhookStatus,},ports::{WebhookEventEnqueuer, WebhookRepo, WebhookWorkspaceResolver},};@@ -247,7 +248,7 @@ impl WebhookRepo for MockRepository {_request: CreateWebhookRequest,_signing_secret: String,_headers: Value,- ) -> Result<Webhook, Self::Err> {+ ) -> Result<CreateWebhookOutcome, Self::Err> {unimplemented!("not used by webhook event ingestion")}@@ -362,6 +363,7 @@ fn webhook(id: &str, workspace_id: &str) -> Webhook {Webhook {id: id.to_string(),workspace_id: workspace_id.to_string(),+ namespace: id.to_string(),name: id.to_string(),endpoint_url: "https://example.com/webhook".to_string(),signing_secret: "not-queued".to_string(),@@ -758,6 +760,7 @@ fn webhook_event_cases() -> Vec<WebhookEventCase> {WebhookTopicEvent::Created(WebhookCreatedMetadata {webhook_id: "wh_created".to_string(),workspace_id: PERSONAL_WORKSPACE_ID.to_string(),+ namespace: "created-webhook".to_string(),created_by_user_id: user_id("macro|[email protected]"),name: "Created webhook".to_string(),endpoint_url: "https://example.com/created".to_string(),diff --git a/crates/webhook/src/domain/mod.rs b/crates/webhook/src/domain/mod.rsindex 191487e371..9fe3b95b26 100644--- a/crates/webhook/src/domain/mod.rs+++ b/crates/webhook/src/domain/mod.rs@@ -18,5 +18,3 @@ pub mod ports;#[cfg(feature = "ports")]/// Webhook service implementation.pub mod service;-#[cfg(test)]-mod service_test;diff --git a/crates/webhook/src/domain/models.rs b/crates/webhook/src/domain/models.rsindex d92aee6c14..46c1031026 100644--- a/crates/webhook/src/domain/models.rs+++ b/crates/webhook/src/domain/models.rs@@ -356,6 +356,9 @@ impl WebhookEndpointSchemePolicy {pub struct CreateWebhookRequest {/// Scope that owns the webhook.pub scope: WebhookScope,+ /// Caller-chosen namespace, unique among the owning workspace's webhooks.+ /// Set at creation time only; it cannot be changed afterwards.+ pub namespace: String,/// Display name.pub name: String,/// Endpoint URL. HTTPS is required outside local environments.@@ -366,7 +369,8 @@ pub struct CreateWebhookRequest {pub filters: WebhookFilters,}-/// Request to patch a webhook.+/// Request to patch a webhook. The webhook's namespace is fixed at creation+/// time and is deliberately not patchable.#[derive(Debug, Clone, Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]pub struct PatchWebhookRequest {@@ -382,6 +386,16 @@ pub struct PatchWebhookRequest {pub status: Option<WebhookStatus>,}+/// Outcome of persisting a new webhook.+#[cfg(feature = "ports")]+#[derive(Debug, Clone)]+pub enum CreateWebhookOutcome {+ /// The webhook was created.+ Created(Box<Webhook>),+ /// A live webhook in the workspace already uses the requested namespace.+ NamespaceConflict,+}+/// Webhook row returned by application APIs.#[derive(Debug, Clone, Serialize, Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]@@ -390,6 +404,9 @@ pub struct Webhook {pub id: WebhookId,/// Owning workspace id.pub workspace_id: String,+ /// Caller-chosen namespace, unique among the owning workspace's webhooks.+ /// Set at creation time only; it cannot be changed afterwards.+ pub namespace: String,/// Display name.pub name: String,/// Endpoint URL. HTTPS is required outside local environments.@@ -424,6 +441,9 @@ pub struct CreateWebhookResponse {pub id: WebhookId,/// Owning workspace id.pub workspace_id: String,+ /// Caller-chosen namespace, unique among the owning workspace's webhooks.+ /// Set at creation time only; it cannot be changed afterwards.+ pub namespace: String,/// Display name.pub name: String,/// Endpoint URL. HTTPS is required outside local environments.@@ -453,6 +473,7 @@ impl From<Webhook> for CreateWebhookResponse {Self {id: webhook.id,workspace_id: webhook.workspace_id,+ namespace: webhook.namespace,name: webhook.name,endpoint_url: webhook.endpoint_url,signing_secret: webhook.signing_secret,diff --git a/crates/webhook/src/domain/ports.rs b/crates/webhook/src/domain/ports.rsindex ae05206f9c..4d2440b597 100644--- a/crates/webhook/src/domain/ports.rs+++ b/crates/webhook/src/domain/ports.rs@@ -1,10 +1,11 @@//! Webhook domain ports.use super::models::{- CreateWebhookRequest, ListWebhooksResponse, NormalizedWebhookEvent, PatchWebhookRequest,- PreparedWebhookDelivery, RawWebhookEventQueueMessage, ValidateWebhookResponse, Webhook,- WebhookDeliveryAttempt, WebhookEventQueueMessage, WebhookHttpOutcome,- WebhookHttpOutcomeDetails, WebhookId, WebhookValidationResult, WebhookWorkerDisposition,+ CreateWebhookOutcome, CreateWebhookRequest, ListWebhooksResponse, NormalizedWebhookEvent,+ PatchWebhookRequest, PreparedWebhookDelivery, RawWebhookEventQueueMessage,+ ValidateWebhookResponse, Webhook, WebhookDeliveryAttempt, WebhookEventQueueMessage,+ WebhookHttpOutcome, WebhookHttpOutcomeDetails, WebhookId, WebhookValidationResult,+ WebhookWorkerDisposition,};use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;@@ -16,6 +17,10 @@ pub trait WebhookRepo: Clone + Send + Sync + 'static {type Err: Into<anyhow::Error> + Send;/// Create a webhook and its initial rule.+ ///+ /// Namespaces are unique among a workspace's live webhooks; implementations+ /// must report a clash as [`CreateWebhookOutcome::NamespaceConflict`]+ /// rather than an error.fn create_webhook(&self,created_by_user_id: MacroUserIdStr<'static>,@@ -23,7 +28,7 @@ pub trait WebhookRepo: Clone + Send + Sync + 'static {request: CreateWebhookRequest,signing_secret: String,headers: serde_json::Value,- ) -> impl Future<Output = Result<Webhook, Self::Err>> + Send;+ ) -> impl Future<Output = Result<CreateWebhookOutcome, Self::Err>> + Send;/// Get an active webhook by id.fn get_webhook(@@ -273,6 +278,9 @@ pub enum WebhookError {/// Bad request.#[error("{0}")]BadRequest(String),+ /// Conflict with existing state.+ #[error("{0}")]+ Conflict(String),/// Unauthorized.#[error("unauthorized")]Unauthorized,diff --git a/crates/webhook/src/domain/service.rs b/crates/webhook/src/domain/service.rsindex 4afbe4f002..dc25617ad4 100644--- a/crates/webhook/src/domain/service.rs+++ b/crates/webhook/src/domain/service.rs@@ -1,14 +1,17 @@//! Webhook service implementation.+#[cfg(test)]+mod test;+use super::{events::{WebhookCreatedMetadata, WebhookDeletedMetadata, WebhookMacroEvent, WebhookUpdatedMetadata,WebhookValidatedMetadata,},models::{- CreateWebhookRequest, ListWebhooksResponse, PatchWebhookRequest, ValidateWebhookResponse,- Webhook, WebhookEndpointSchemePolicy, WebhookFilters, WebhookId, WebhookScope,- WebhookValidationResult,+ CreateWebhookOutcome, CreateWebhookRequest, ListWebhooksResponse, PatchWebhookRequest,+ ValidateWebhookResponse, Webhook, WebhookEndpointSchemePolicy, WebhookFilters, WebhookId,+ WebhookScope, WebhookValidationResult,},ports::{WebhookError, WebhookRepo, WebhookService, WebhookValidationClient},};@@ -19,6 +22,7 @@ use std::net::IpAddr;use url::Url;const MAX_NAME_LEN: usize = 128;+const MAX_NAMESPACE_LEN: usize = 128;const MAX_FILTERS: usize = 50;const MAX_FILTER_EVENTS: usize = 100;const MAX_FILTER_IDS: usize = 100;@@ -71,6 +75,16 @@ fn validate_name(name: &str) -> Result<(), WebhookError> {Ok(())}+fn validate_namespace(namespace: &str) -> Result<(), WebhookError> {+ let namespace = namespace.trim();+ if namespace.is_empty() || namespace.len() > MAX_NAMESPACE_LEN {+ return Err(WebhookError::BadRequest(format!(+ "namespace must be non-empty and at most {MAX_NAMESPACE_LEN} characters"+ )));+ }+ Ok(())+}+fn validate_endpoint_url(endpoint_url: &str,endpoint_scheme_policy: WebhookEndpointSchemePolicy,@@ -204,6 +218,7 @@ fn validate_create_request(endpoint_scheme_policy: WebhookEndpointSchemePolicy,) -> Result<(), WebhookError> {validate_name(&request.name)?;+ validate_namespace(&request.namespace)?;validate_endpoint_url(&request.endpoint_url, endpoint_scheme_policy)?;validate_filters(&request.filters)}@@ -364,11 +379,19 @@ wherelet signing_secret = generate_signing_secret(&caller);let headers = serde_json::to_value(request.headers.clone().unwrap_or_default()).map_err(|err| WebhookError::Repo(err.into()))?;- let mut webhook = self+ let mut webhook = match self.repo.create_webhook(caller, workspace_id, request, signing_secret, headers).await- .map_err(|err| WebhookError::Repo(err.into()))?;+ .map_err(|err| WebhookError::Repo(err.into()))?+ {+ CreateWebhookOutcome::Created(webhook) => *webhook,+ CreateWebhookOutcome::NamespaceConflict => {+ return Err(WebhookError::Conflict(+ "namespace is already used by another webhook in this workspace".to_string(),+ ));+ }+ };webhook.is_valid = false;self.publish_webhook_event(&WebhookMacroEvent::created(@@ -376,6 +399,7 @@ whereWebhookCreatedMetadata {webhook_id: webhook.id.clone(),workspace_id: webhook.workspace_id.clone(),+ namespace: webhook.namespace.clone(),created_by_user_id,name: webhook.name.clone(),endpoint_url: webhook.endpoint_url.clone(),diff --git a/crates/webhook/src/domain/service_test.rs b/crates/webhook/src/domain/service/test.rssimilarity index 93%rename from crates/webhook/src/domain/service_test.rsrename to crates/webhook/src/domain/service/test.rsindex 1537251d78..25c9a73f9c 100644--- a/crates/webhook/src/domain/service_test.rs+++ b/crates/webhook/src/domain/service/test.rs@@ -1,11 +1,11 @@-use super::{+use super::WebhookServiceImpl;+use crate::domain::{models::{- CreateWebhookRequest, ListWebhooksResponse, PatchWebhookRequest, ValidateWebhookResponse,- Webhook, WebhookEndpointSchemePolicy, WebhookFilter, WebhookFilters, WebhookScope,- WebhookStatus, WebhookValidationResult,+ CreateWebhookOutcome, CreateWebhookRequest, ListWebhooksResponse, PatchWebhookRequest,+ ValidateWebhookResponse, Webhook, WebhookEndpointSchemePolicy, WebhookFilter,+ WebhookFilters, WebhookScope, WebhookStatus, WebhookValidationResult,},ports::{WebhookError, WebhookRepo, WebhookService, WebhookValidationClient},- service::WebhookServiceImpl,};use chrono::Utc;use macro_event_broker::{EventBrokerError, MacroEvent, MacroEventBroker, NoopMacroEventBroker};@@ -23,6 +23,7 @@ struct RepoState {webhook: Option<Webhook>,validation_updates: Vec<bool>,create_fails: bool,+ create_namespace_conflict: bool,patch_fails: bool,patch_returns_missing: bool,delete_fails: bool,@@ -53,6 +54,12 @@ impl FakeRepo {repo}+ async fn conflicting_namespace() -> Self {+ let repo = Self::default();+ repo.state.lock().await.create_namespace_conflict = true;+ repo+ }+async fn failing_team_lookup() -> Self {let repo = Self::default();repo.state.lock().await.team_lookup_fails = true;@@ -81,14 +88,19 @@ impl WebhookRepo for FakeRepo {request: CreateWebhookRequest,_signing_secret: String,_headers: serde_json::Value,- ) -> Result<Webhook, Self::Err> {- if self.state.lock().await.create_fails {+ ) -> Result<CreateWebhookOutcome, Self::Err> {+ let state = self.state.lock().await;+ if state.create_fails {anyhow::bail!("create failed");}+ if state.create_namespace_conflict {+ return Ok(CreateWebhookOutcome::NamespaceConflict);+ }+ drop(state);let webhook = webhook_from_create(created_by_user_id, workspace_id, request);self.state.lock().await.webhook = Some(webhook.clone());- Ok(webhook)+ Ok(CreateWebhookOutcome::Created(Box::new(webhook)))}async fn get_webhook(&self, webhook_id: String) -> Result<Option<Webhook>, Self::Err> {@@ -367,6 +379,7 @@ fn valid_filters() -> WebhookFilters {fn create_request() -> CreateWebhookRequest {CreateWebhookRequest {scope: WebhookScope::User,+ namespace: "files-hook".to_string(),name: "Files".to_string(),endpoint_url: "https://example.com/webhook".to_string(),headers: Some(BTreeMap::from([(@@ -396,6 +409,7 @@ fn webhook_from_create(Webhook {id: "wh_test".to_string(),workspace_id,+ namespace: request.namespace,name: request.name,endpoint_url: request.endpoint_url,signing_secret: "secret".to_string(),@@ -462,6 +476,7 @@ async fn create_publishes_full_sanitized_snapshot() {json!({"webhook_id": webhook.id,"workspace_id": webhook.workspace_id,+ "namespace": webhook.namespace,"created_by_user_id": caller().as_ref(),"name": webhook.name,"endpoint_url": webhook.endpoint_url,@@ -495,6 +510,68 @@ async fn create_request_validation_failure_publishes_nothing() {assert!(published.lock().unwrap().is_empty());}+#[tokio::test]+async fn create_with_taken_namespace_fails_conflict_and_publishes_nothing() {+ let event_broker = TestEventBroker::default();+ let published = event_broker.published();+ let service = WebhookServiceImpl::new(+ FakeRepo::conflicting_namespace().await,+ FakeValidationClient::default(),+ event_broker,+ );++ let result = service.create_webhook(caller(), create_request()).await;++ assert!(matches!(+ result,+ Err(WebhookError::Conflict(message))+ if message == "namespace is already used by another webhook in this workspace"+ ));+ assert!(published.lock().unwrap().is_empty());+}++#[tokio::test]+async fn create_with_blank_namespace_is_rejected() {+ let service = WebhookServiceImpl::new(+ FakeRepo::default(),+ FakeValidationClient::default(),+ NoopMacroEventBroker,+ );+ let mut request = create_request();+ request.namespace = " ".to_string();++ assert_bad_request(service.create_webhook(caller(), request).await);+}++#[tokio::test]+async fn create_with_oversized_namespace_is_rejected() {+ let service = WebhookServiceImpl::new(+ FakeRepo::default(),+ FakeValidationClient::default(),+ NoopMacroEventBroker,+ );+ let mut request = create_request();+ request.namespace = "n".repeat(129);++ assert_bad_request(service.create_webhook(caller(), request).await);+}++#[tokio::test]+async fn patch_leaves_namespace_unchanged() {+ let webhook = existing_webhook();+ let original_namespace = webhook.namespace.clone();+ let repo = FakeRepo::with_webhook(webhook, None).await;+ let service =+ WebhookServiceImpl::new(repo, FakeValidationClient::default(), NoopMacroEventBroker);++ let patched = service+ .patch_webhook(caller(), "wh_test".to_string(), patch_request())+ .await+ .expect("webhook should be patched");++ assert_eq!(patched.namespace, original_namespace);+}+#[tokio::test]async fn create_fails_bad_request_when_team_scope_user_has_no_team() {let event_broker = TestEventBroker::default();diff --git a/crates/webhook/src/inbound/axum_router.rs b/crates/webhook/src/inbound/axum_router.rsindex bb8df69242..63f0c82bb9 100644--- a/crates/webhook/src/inbound/axum_router.rs+++ b/crates/webhook/src/inbound/axum_router.rs@@ -1,5 +1,8 @@//! Axum router for webhook APIs.+#[cfg(test)]+mod test;+use crate::domain::{models::{CreateWebhookRequest, CreateWebhookResponse, ListWebhooksResponse, PatchWebhookRequest,@@ -220,6 +223,7 @@ where(status = 201, description = "Webhook created", body = CreateWebhookResponse),(status = 400, description = "Bad request", body = ErrorResponse),(status = 403, description = "Forbidden", body = ErrorResponse),+ (status = 409, description = "Namespace already used in the workspace", body = ErrorResponse),(status = 500, description = "Internal server error", body = ErrorResponse),),tag = "webhook"@@ -386,6 +390,7 @@ impl IntoResponse for WebhookHandlerError {fn into_response(self) -> Response {let status = match self.0 {WebhookError::BadRequest(_) => StatusCode::BAD_REQUEST,+ WebhookError::Conflict(_) => StatusCode::CONFLICT,WebhookError::Unauthorized => StatusCode::FORBIDDEN,WebhookError::NotFound(_) => StatusCode::NOT_FOUND,WebhookError::Repo(_) => StatusCode::INTERNAL_SERVER_ERROR,diff --git a/crates/webhook/src/inbound/axum_router_test.rs b/crates/webhook/src/inbound/axum_router/test.rssimilarity index 95%rename from crates/webhook/src/inbound/axum_router_test.rsrename to crates/webhook/src/inbound/axum_router/test.rsindex 9dc0000e8c..d884b7e0ad 100644--- a/crates/webhook/src/inbound/axum_router_test.rs+++ b/crates/webhook/src/inbound/axum_router/test.rs@@ -1,4 +1,4 @@-use super::axum_router::{WebhookRouterState, webhook_router};+use super::{WebhookRouterState, webhook_router};use crate::domain::{models::{CreateWebhookRequest, ListWebhooksResponse, PatchWebhookRequest, ValidateWebhookResponse,@@ -298,15 +298,43 @@ async fn create_passes_authenticated_user_and_body_to_service() {assert_eq!(status, StatusCode::CREATED);assert_eq!(body["signing_secret"], "whsec_test");+ assert_eq!(body["namespace"], "events-hook");match &service.calls()[0] {ServiceCall::Create(user, request) => {assert_eq!(user.as_ref(), user_id());assert_eq!(request.name, "Events");+ assert_eq!(request.namespace, "events-hook");}other => panic!("unexpected call: {other:?}"),}}+#[tokio::test]+async fn namespace_conflict_maps_to_409() {+ let service = FakeService::default();+ service.set_response(Err(WebhookError::Conflict(+ "namespace is already used by another webhook in this workspace".to_string(),+ )));++ let response = send(+ service,+ FakeRateLimiter::default(),+ "POST",+ "/webhooks",+ create_body(),+ )+ .await;++ let status = response.status();+ let body = response_json(response).await;++ assert_eq!(status, StatusCode::CONFLICT);+ assert_eq!(+ body["message"],+ "namespace is already used by another webhook in this workspace"+ );+}+#[tokio::test]async fn patch_passes_authenticated_user_path_and_body_to_service() {let service = FakeService::default();@@ -607,6 +635,7 @@ async fn response_json(response: axum::response::Response) -> serde_json::Valuefn create_body() -> serde_json::Value {json!({"scope": "user",+ "namespace": "events-hook","name": "Events","endpoint_url": "https://example.com/webhook","headers": {"x-custom": "value"},@@ -627,6 +656,7 @@ fn webhook() -> Webhook {serde_json::from_value(json!({"id": "wh_123","workspace_id": "workspace_1",+ "namespace": "events-hook","name": "Events","endpoint_url": "https://example.com/webhook","signing_secret": "whsec_test",diff --git a/crates/webhook/src/inbound/mod.rs b/crates/webhook/src/inbound/mod.rsindex 6efff1c630..0fd89fda58 100644--- a/crates/webhook/src/inbound/mod.rs+++ b/crates/webhook/src/inbound/mod.rs@@ -3,9 +3,6 @@#[cfg(feature = "inbound")]pub mod axum_router;-#[cfg(all(test, feature = "inbound"))]-mod axum_router_test;-#[cfg(feature = "consumer")]pub mod kafka_consumer;diff --git a/crates/webhook/src/outbound/http_delivery_test.rs b/crates/webhook/src/outbound/http_delivery_test.rsindex 9752e497a4..f606e69d7d 100644--- a/crates/webhook/src/outbound/http_delivery_test.rs+++ b/crates/webhook/src/outbound/http_delivery_test.rs@@ -11,6 +11,7 @@ fn webhook(endpoint_url: &str, headers: WebhookHeaders) -> Webhook {Webhook {id: "wh_test".to_string(),workspace_id: "workspace_test".to_string(),+ namespace: "test-webhook".to_string(),name: "Test webhook".to_string(),endpoint_url: endpoint_url.to_string(),signing_secret: "signing-secret".to_string(),diff --git a/crates/webhook/src/outbound/pg_delivery_repository.rs b/crates/webhook/src/outbound/pg_delivery_repository.rsindex 9c20be26b6..03d5adad3b 100644--- a/crates/webhook/src/outbound/pg_delivery_repository.rs+++ b/crates/webhook/src/outbound/pg_delivery_repository.rs@@ -40,6 +40,7 @@ struct PreparedDeliveryRow {next_attempt_at: Option<DateTime<Utc>>,webhook_id: String,workspace_id: String,+ namespace: String,name: String,endpoint_url: String,signing_secret: String,@@ -98,6 +99,7 @@ fn row_to_prepared_delivery(webhook: Webhook {id: row.webhook_id,workspace_id: row.workspace_id,+ namespace: row.namespace,name: row.name,endpoint_url: row.endpoint_url,signing_secret: row.signing_secret,@@ -396,6 +398,7 @@ impl WebhookDeliveryRepository for PgWebhookDeliveryRepository {d.next_attempt_at,w.id AS webhook_id,w.workspace_id,+ w.namespace,w.name,w.endpoint_url,w.signing_secret,diff --git a/crates/webhook/src/outbound/pg_delivery_repository_test.rs b/crates/webhook/src/outbound/pg_delivery_repository_test.rsindex f929b62add..04a173e481 100644--- a/crates/webhook/src/outbound/pg_delivery_repository_test.rs+++ b/crates/webhook/src/outbound/pg_delivery_repository_test.rs@@ -23,6 +23,7 @@ async fn insert_webhook(pool: &PgPool, deleted: bool) -> anyhow::Result<()> {INSERT INTO webhook (id,workspace_id,+ namespace,name,endpoint_url,signing_secret,@@ -33,10 +34,11 @@ async fn insert_webhook(pool: &PgPool, deleted: bool) -> anyhow::Result<()> {created_by_user_id,deleted_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, true, $9, $10)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, true, $10, $11)"#,WEBHOOK_ID,USER_ID,+ "delivery-test","Delivery test",ENDPOINT_URL,SIGNING_SECRET,diff --git a/crates/webhook/src/outbound/pg_repository.rs b/crates/webhook/src/outbound/pg_repository.rsindex 47219a01f0..d3aaa4e68a 100644--- a/crates/webhook/src/outbound/pg_repository.rs+++ b/crates/webhook/src/outbound/pg_repository.rs@@ -5,8 +5,8 @@ mod pg_repository_test;use crate::domain::{models::{- CreateWebhookRequest, PatchWebhookRequest, Webhook, WebhookFilters, WebhookHeaders,- WebhookId, WebhookStatus,+ CreateWebhookOutcome, CreateWebhookRequest, PatchWebhookRequest, Webhook, WebhookFilters,+ WebhookHeaders, WebhookId, WebhookStatus,},ports::{WebhookRepo, WebhookWorkspaceResolver},};@@ -32,6 +32,7 @@ impl PgRepository {struct WebhookRow {id: String,workspace_id: String,+ namespace: String,name: String,endpoint_url: String,signing_secret: String,@@ -71,6 +72,7 @@ fn row_to_webhook(row: WebhookRow) -> Result<Webhook, sqlx::Error> {Ok(Webhook {id: row.id,workspace_id: row.workspace_id,+ namespace: row.namespace,name: row.name,endpoint_url: row.endpoint_url,signing_secret: row.signing_secret,@@ -92,6 +94,7 @@ async fn fetch_webhook(pool: &PgPool, webhook_id: &str) -> Result<Option<WebhookSELECTw.id,w.workspace_id,+ w.namespace,w.name,w.endpoint_url,w.signing_secret,@@ -164,22 +167,24 @@ impl WebhookRepo for PgRepository {request: CreateWebhookRequest,signing_secret: String,headers: Value,- ) -> Result<Webhook, Self::Err> {+ ) -> Result<CreateWebhookOutcome, Self::Err> {let webhook_id = new_webhook_id();let status = WebhookStatus::Active.as_str();let created_by_user_id = created_by_user_id.as_ref();let filters = serde_json::to_value(&request.filters).map_err(|err| sqlx::Error::Encode(err.into()))?;- sqlx::query!(+ let inserted = sqlx::query!(r#"INSERT INTO webhook (- id, workspace_id, name, endpoint_url, signing_secret, headers,+ id, workspace_id, namespace, name, endpoint_url, signing_secret, headers,filters, status, is_valid, created_by_user_id)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, false, $9)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, false, $10)+ ON CONFLICT (workspace_id, namespace) WHERE deleted_at IS NULL DO NOTHING"#,webhook_id,workspace_id,+ request.namespace,request.name,request.endpoint_url,signing_secret,@@ -190,8 +195,14 @@ impl WebhookRepo for PgRepository {).execute(&self.pool).await?;++ if inserted.rows_affected() == 0 {+ return Ok(CreateWebhookOutcome::NamespaceConflict);+ }+fetch_webhook(&self.pool, &webhook_id).await?+ .map(|webhook| CreateWebhookOutcome::Created(Box::new(webhook))).ok_or(sqlx::Error::RowNotFound)}@@ -211,6 +222,7 @@ impl WebhookRepo for PgRepository {SELECTw.id,w.workspace_id,+ w.namespace,w.name,w.endpoint_url,w.signing_secret,@@ -248,6 +260,7 @@ impl WebhookRepo for PgRepository {SELECTw.id,w.workspace_id,+ w.namespace,w.name,w.endpoint_url,w.signing_secret,diff --git a/crates/webhook/src/outbound/pg_repository_test.rs b/crates/webhook/src/outbound/pg_repository_test.rsindex a5206a3ef2..f6b0c02ce1 100644--- a/crates/webhook/src/outbound/pg_repository_test.rs+++ b/crates/webhook/src/outbound/pg_repository_test.rs@@ -1,6 +1,6 @@use super::*;use crate::domain::{- models::{WebhookFilter, WebhookStatus},+ models::{WebhookFilter, WebhookScope, WebhookStatus},ports::{WebhookRepo, WebhookWorkspaceResolver},};use macro_db_migrator::MACRO_DB_MIGRATIONS;@@ -27,8 +27,13 @@ fn second_user_id() -> MacroUserIdStr<'static> {}fn create_request() -> CreateWebhookRequest {+ create_request_with_namespace("build-events")+}++fn create_request_with_namespace(namespace: &str) -> CreateWebhookRequest {CreateWebhookRequest {- scope: crate::domain::models::WebhookScope::User,+ scope: WebhookScope::User,+ namespace: namespace.to_string(),name: "Build events".to_string(),endpoint_url: "https://example.com/webhook".to_string(),headers: None,@@ -100,10 +105,29 @@ async fn insert_team_member(pool: &PgPool, user_id: &str, team_id: Uuid) -> anyh}async fn create_webhook(repo: &PgRepository) -> Webhook {+ create_webhook_in_workspace(repo, USER_ID, create_request()).await+}++async fn create_webhook_in_workspace(+ repo: &PgRepository,+ workspace_id: &str,+ request: CreateWebhookRequest,+) -> Webhook {+ match try_create_webhook(repo, workspace_id, request).await {+ CreateWebhookOutcome::Created(webhook) => *webhook,+ CreateWebhookOutcome::NamespaceConflict => panic!("unexpected namespace conflict"),+ }+}++async fn try_create_webhook(+ repo: &PgRepository,+ workspace_id: &str,+ request: CreateWebhookRequest,+) -> CreateWebhookOutcome {repo.create_webhook(user_id(),- USER_ID.to_string(),- create_request(),+ workspace_id.to_string(),+ request,"signing-secret".to_string(),json!({ "X-Test": "true" }),)@@ -140,13 +164,14 @@ async fn insert_webhook_for_matching(sqlx::query!(r#"INSERT INTO webhook (- id, workspace_id, name, endpoint_url, signing_secret,+ id, workspace_id, namespace, name, endpoint_url, signing_secret,filters, status, is_valid, created_by_user_id, deleted_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)"#,id,workspace_id,+ id,name,endpoint_url,"signing-secret",@@ -170,6 +195,7 @@ async fn create_inserts_webhook_with_filters(pool: PgPool) -> anyhow::Result<()>let webhook = create_webhook(&repo).await;assert!(webhook.id.starts_with("wh_"));+ assert_eq!(webhook.namespace, "build-events");assert_eq!(webhook.filters,vec![WebhookFilter {@@ -181,6 +207,51 @@ async fn create_inserts_webhook_with_filters(pool: PgPool) -> anyhow::Result<()>Ok(())}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_with_taken_namespace_returns_conflict(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool).await?;+ let repo = PgRepository::new(pool.clone());+ let first = create_webhook(&repo).await;++ let outcome = try_create_webhook(&repo, USER_ID, create_request()).await;++ assert!(matches!(outcome, CreateWebhookOutcome::NamespaceConflict));+ let webhooks = repo+ .list_webhooks_for_workspaces(vec![USER_ID.to_string()])+ .await?;+ assert_eq!(webhook_ids(&webhooks), vec![first.id.as_str()]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_with_same_namespace_in_another_workspace_succeeds(+ pool: PgPool,+) -> anyhow::Result<()> {+ insert_user(&pool).await?;+ let repo = PgRepository::new(pool.clone());+ create_webhook(&repo).await;++ let webhook = create_webhook_in_workspace(&repo, OTHER_WORKSPACE_ID, create_request()).await;++ assert_eq!(webhook.workspace_id, OTHER_WORKSPACE_ID);+ assert_eq!(webhook.namespace, "build-events");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn namespace_is_reusable_after_soft_delete(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool).await?;+ let repo = PgRepository::new(pool.clone());+ let deleted = create_webhook(&repo).await;+ repo.delete_webhook(deleted.id.clone()).await?;++ let webhook = create_webhook(&repo).await;++ assert_ne!(webhook.id, deleted.id);+ assert_eq!(webhook.namespace, "build-events");+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn object_shaped_filters_are_rejected_by_check_constraint(pool: PgPool,@@ -188,13 +259,14 @@ async fn object_shaped_filters_are_rejected_by_check_constraint(let result = sqlx::query!(r#"INSERT INTO webhook (- id, workspace_id, name, endpoint_url, signing_secret,+ id, workspace_id, namespace, name, endpoint_url, signing_secret,filters, created_by_user_id)- VALUES ($1, $2, $3, $4, $5, $6, $7)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"#,"wh_object_filters",USER_ID,+ "object-filters","Object filters","https://example.com/webhook","signing-secret",diff --git a/packages/sdk/examples/webhook-events.ts b/packages/sdk/examples/webhook-events.tsindex e781d983e3..4635e5c77a 100644--- a/packages/sdk/examples/webhook-events.ts+++ b/packages/sdk/examples/webhook-events.ts@@ -60,6 +60,7 @@ console.log(`listening on :${port} — expose it with: ngrok http ${port}`);const webhook = await macro.webhooks.create({url,+ namespace: `sdk-webhook-demo-${crypto.randomUUID()}`,name: 'sdk webhook demo',filters: [{ events: [...ALL_EVENTS] }],});diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex b5a9a2d06b..47aef0d2f6 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -2945,6 +2945,11 @@ export type CreateWebhookRequest = {* Display name.*/name: string;+ /**+ * Caller-chosen namespace, unique among the owning workspace's webhooks.+ * Set at creation time only; it cannot be changed afterwards.+ */+ namespace: string;/*** Scope that owns the webhook.*/@@ -2991,6 +2996,11 @@ export type CreateWebhookResponse = {* Display name.*/name: string;+ /**+ * Caller-chosen namespace, unique among the owning workspace's webhooks.+ * Set at creation time only; it cannot be changed afterwards.+ */+ namespace: string;/*** Signing secret used to verify webhook delivery signatures.*/@@ -5443,7 +5453,8 @@ export type PatchThreadRequestV2 = {};/**- * Request to patch a webhook.+ * Request to patch a webhook. The webhook's namespace is fixed at creation+ * time and is deliberately not patchable.*/export type PatchWebhookRequest = {/**@@ -7707,6 +7718,11 @@ export type Webhook = {* Display name.*/name: string;+ /**+ * Caller-chosen namespace, unique among the owning workspace's webhooks.+ * Set at creation time only; it cannot be changed afterwards.+ */+ namespace: string;/*** Webhook lifecycle status.*/@@ -12038,6 +12054,10 @@ export type CreateWebhookErrors = {* Forbidden*/403: ErrorResponse;+ /**+ * Namespace already used in the workspace+ */+ 409: ErrorResponse;/*** Internal server error*/diff --git a/packages/sdk/scripts/webhook.ts b/packages/sdk/scripts/webhook.tsindex 0a4c73a322..b026a4a8b4 100644--- a/packages/sdk/scripts/webhook.ts+++ b/packages/sdk/scripts/webhook.ts@@ -14,6 +14,7 @@ const { positionals, values } = parseArgs({events: { type: 'string' },help: { type: 'boolean', short: 'h' },name: { type: 'string' },+ namespace: { type: 'string' },port: { type: 'string' },scope: { type: 'string' },'user-id': { type: 'string' },@@ -52,9 +53,12 @@ async function register(): Promise<void> {? required(values['user-id'], '--user-id'): values['user-id'];+ const namespace = values.namespace ?? crypto.randomUUID();+const macro = new Macro({ env, requestedAs: userId });const webhook = await macro.webhooks.create({url: endpointUrl,+ namespace,name,filters: [{ events }],scope,@@ -123,6 +127,7 @@ Register a webhook or receive and print its events.webhook register --env <dev|prod|local> --url <endpoint URL>--name <webhook name> --events <event,event>--scope <user|team> [--user-id <macro-user-id>]+ [--namespace <workspace-unique namespace, random by default>]webhook receive <webhook-id> --env <dev|prod|local>[--port <port>] [--user-id <macro-user-id>]diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 492709d071..f8db98f506 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -10268,6 +10268,16 @@}}},+ "409": {+ "description": "Namespace already used in the workspace",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "Internal server error","content": {@@ -14804,7 +14814,7 @@"CreateWebhookRequest": {"type": "object","description": "Request to create a webhook.",- "required": ["scope", "name", "endpoint_url", "filters"],+ "required": ["scope", "namespace", "name", "endpoint_url", "filters"],"properties": {"endpoint_url": {"type": "string",@@ -14829,6 +14839,10 @@"type": "string","description": "Display name."},+ "namespace": {+ "type": "string",+ "description": "Caller-chosen namespace, unique among the owning workspace's webhooks.\nSet at creation time only; it cannot be changed afterwards."+ },"scope": {"$ref": "#/components/schemas/WebhookScope","description": "Scope that owns the webhook."@@ -14841,6 +14855,7 @@"required": ["id","workspace_id",+ "namespace","name","endpoint_url","signing_secret",@@ -14891,6 +14906,10 @@"type": "string","description": "Display name."},+ "namespace": {+ "type": "string",+ "description": "Caller-chosen namespace, unique among the owning workspace's webhooks.\nSet at creation time only; it cannot be changed afterwards."+ },"signing_secret": {"type": "string","description": "Signing secret used to verify webhook delivery signatures."@@ -19130,7 +19149,7 @@},"PatchWebhookRequest": {"type": "object",- "description": "Request to patch a webhook.",+ "description": "Request to patch a webhook. The webhook's namespace is fixed at creation\ntime and is deliberately not patchable.","properties": {"endpoint_url": {"type": ["string", "null"],@@ -22964,6 +22983,7 @@"required": ["id","workspace_id",+ "namespace","name","endpoint_url","headers",@@ -23013,6 +23033,10 @@"type": "string","description": "Display name."},+ "namespace": {+ "type": "string",+ "description": "Caller-chosen namespace, unique among the owning workspace's webhooks.\nSet at creation time only; it cannot be changed afterwards."+ },"status": {"$ref": "#/components/schemas/WebhookStatus","description": "Webhook lifecycle status."diff --git a/packages/sdk/src/entities/webhooks/namespace.ts b/packages/sdk/src/entities/webhooks/namespace.tsindex 9f38500546..b12edb7a54 100644--- a/packages/sdk/src/entities/webhooks/namespace.ts+++ b/packages/sdk/src/entities/webhooks/namespace.ts@@ -13,11 +13,14 @@ export class WebhooksNamespace {constructor(private readonly client: MacroClient) {}/**- * Register a webhook. `filters` must be non-empty (each entry matches event+ * Register a webhook. `namespace` must be unique among the owning+ * workspace's webhooks (the endpoint returns 409 on a clash) and cannot be+ * changed later. `filters` must be non-empty (each entry matches event* names, optionally narrowed to entity ids); `scope` defaults to `'user'`.*/create(opts: {url: string;+ namespace: string;name: string;filters: WebhookFilter[];scope?: WebhookScope;diff --git a/packages/sdk/src/entities/webhooks/webhook.ts b/packages/sdk/src/entities/webhooks/webhook.tsindex 50a357cf35..315d30eec2 100644--- a/packages/sdk/src/entities/webhooks/webhook.ts+++ b/packages/sdk/src/entities/webhooks/webhook.ts@@ -54,6 +54,7 @@ export class Webhook extends MacroEntity<WebhookRecord> {client: MacroClient,opts: {url: string;+ namespace: string;name: string;filters: WebhookFilter[];scope?: WebhookScope;@@ -64,6 +65,7 @@ export class Webhook extends MacroEntity<WebhookRecord> {await client.storage.createWebhook({body: {endpoint_url: opts.url,+ namespace: opts.namespace,name: opts.name,filters: opts.filters,scope: opts.scope ?? 'user',@@ -87,6 +89,12 @@ export class Webhook extends MacroEntity<WebhookRecord> {/** The webhook's display name. */readonly name = this.field('name');+ /**+ * The caller-chosen namespace, unique among the owning workspace's webhooks.+ * Fixed at creation time; it cannot be patched.+ */+ readonly namespace = this.field('namespace');+/** The HTTPS endpoint URL deliveries are sent to. */readonly endpointUrl = this.field('endpoint_url');