diff --git a/.github/workflows/native-sdks.yml b/.github/workflows/native-sdks.yml index 3c69c5d68..c59aec3e2 100644 --- a/.github/workflows/native-sdks.yml +++ b/.github/workflows/native-sdks.yml @@ -53,6 +53,11 @@ jobs: needs: matrix if: needs.matrix.outputs.enabled == 'true' runs-on: ubuntu-latest + env: + # Full Rust feature/package verification exceeds hosted disk with DWARF. + # Keep the same checks and debug assertions, without compiler debug data. + CARGO_PROFILE_DEV_DEBUG: "0" + CARGO_PROFILE_TEST_DEBUG: "0" strategy: fail-fast: false matrix: ${{ fromJSON(needs.matrix.outputs.matrix) }} diff --git a/contracts/README.md b/contracts/README.md index 410eed95c..98ca38c23 100644 --- a/contracts/README.md +++ b/contracts/README.md @@ -1,5 +1,25 @@ # Contract coverage +## Idempotency response replay + +`idempotency-replay.json` is produced by +`scripts/sync-idempotency-replay-contract.mjs` from committed generated API +documents. It records the exact backend source, both complete input hashes, +the idempotency error enums and 28 unchanged one-hour header parameters. +It also explicitly pins conversion deduplication: different details for an +existing `eventId` return `422 idempotency_conflict` in this source contract. +The older baseline remains unchanged, and the transport still maps a received +409 to `PolymorfaConflictError` and a received 422 to `PolymorfaValidationError`. +The global baseline snapshots remain unchanged. The error catalog recognizes +both the new replay-unavailable code and legacy completed responses. + +The supplement is source-only and has `published: false`. It does not establish +deployed access or a sensitive-content retention exception. Opaque message and +campaign responses are not retained by default. Missing replay data preserves +the execution fence; clients must reconcile an uncertain outcome before deciding +whether another write is safe. SDK package publication requires matching API +acceptance through the existing release process. + ## Campaign and custody additions `campaign-custody-20261014.json` pins thirty machine-accessible operations and diff --git a/contracts/doc-snippets.json b/contracts/doc-snippets.json index a54183b92..ca0184dc2 100644 --- a/contracts/doc-snippets.json +++ b/contracts/doc-snippets.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "sourceCommit": "a6324a31225fc73be8c49dba5985a65a22c9b06b", - "sourceFilesSha256": "d34c36ef4b76e780e8f556fec4fe602aa1ebc58906e72fdf59730c1a6b635939", + "sourceCommit": "b79ae6ad2cff690b8a0b68085f0bc9d5ba7561e7", + "sourceFilesSha256": "bda9f28da0dc7fc9910174543fe3a31b5da2cfa8baf9b9fb6155318385fb486a", "apiVersion": "2026-09-22", "apiSourceCommit": "171a9683ff45d11a4b5d3917dc428ad2722b0d99", "specs": { diff --git a/contracts/idempotency-replay.json b/contracts/idempotency-replay.json new file mode 100644 index 000000000..642de43b0 --- /dev/null +++ b/contracts/idempotency-replay.json @@ -0,0 +1,447 @@ +{ + "schemaVersion": 1, + "repository": "polymorfa/polymorfa", + "sourceCommit": "1001684aff8317a455f74e526009f37cd3d98f2b", + "sources": [ + { + "path": "apps/api/docs/openapi.json", + "sha256": "32d44bb25f21ef63b1552526cb73433495d2c691a11f8d1326b9b7a9ad0a650a", + "info": { + "title": "Polymorfa WhatsApp API", + "version": "1.0.0", + "description": "Public Polymorfa REST API for sessions, messaging, media, webhooks, campaigns, templates, client tokens, QuickLinks, and bridge routing.", + "contact": { + "name": "Polymorfa API", + "url": "https://docs.polymorfa.com" + } + } + }, + { + "path": "apps/api/docs/openapi.management.json", + "sha256": "ac3879ecb9da2c05bef3cd5605a2b143eb4ca6e7ce04feb3a0f30358a3f5fada", + "info": { + "title": "Polymorfa Console & Management API", + "version": "1.0.0", + "description": "Complete console/management surface. Resource-oriented REST: `{param}` path variables, single-word action sub-resources.\n\nNamespaces decide inclusion:\n- `/platform/…` — **public registry** (282 endpoints): each endpoint declares either a scoped `pmfa_` team key or a verified live dashboard JWT, or dashboard-only authorization when a specific user's authority is required. Only implemented handlers are published to customers and SDKs.\n- `/console/…` — **console-only** (128 endpoints): verified dashboard identity. EXCLUDED from the published spec; reason per endpoint.\n\nThe published customer spec = this document filtered to `x-audience: public` endpoints with an implemented runtime handler.\nMost transitional body/response schemas remain loose (`additionalProperties: true`); session-control operations use explicit strict schemas." + } + } + ], + "errorCodes": [ + "idempotency_conflict", + "idempotency_in_progress", + "idempotency_outcome_unknown", + "idempotency_replay_unavailable" + ], + "operations": [ + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/messages/send", + "method": "POST", + "operationId": "sendMessage", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/messages/react", + "method": "POST", + "operationId": "sendReaction", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/chats/{conversation}/messages/{messageId}", + "method": "PUT", + "operationId": "editMessage", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/chats/{conversation}/messages/{messageId}", + "method": "DELETE", + "operationId": "deleteMessage", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/official-groups", + "method": "POST", + "operationId": "createOfficialGroup", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/official-groups/{group}", + "method": "PATCH", + "operationId": "updateOfficialGroup", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/official-groups/{group}", + "method": "DELETE", + "operationId": "deleteOfficialGroup", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/official-groups/{group}/invite-link/reset", + "method": "POST", + "operationId": "resetOfficialGroupInviteLink", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/official-groups/{group}/participants/remove", + "method": "POST", + "operationId": "removeOfficialGroupParticipants", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/official-groups/{group}/join-requests/approve", + "method": "POST", + "operationId": "approveOfficialGroupJoinRequests", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/official-groups/{group}/join-requests/reject", + "method": "POST", + "operationId": "rejectOfficialGroupJoinRequests", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/official-groups/{group}/pins", + "method": "POST", + "operationId": "pinOfficialGroupMessage", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/channels/{id}/messages/{messageId}/reaction", + "method": "POST", + "operationId": "reactToChannelMessage", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/templates", + "method": "POST", + "operationId": "createTemplate", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/{session}/templates/{name}", + "method": "DELETE", + "operationId": "deleteTemplate", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/projects/{projectSlug}/campaigns", + "method": "POST", + "operationId": "createCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/projects/{projectSlug}/campaigns/{id}/launch", + "method": "POST", + "operationId": "launchCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/projects/{projectSlug}/campaigns/{id}/pause", + "method": "POST", + "operationId": "pauseCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/projects/{projectSlug}/campaigns/{id}/resume", + "method": "POST", + "operationId": "resumeCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/projects/{projectSlug}/campaigns/{id}/stop", + "method": "POST", + "operationId": "stopCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/projects/{projectSlug}/campaigns/{id}/test-send", + "method": "POST", + "operationId": "testSendCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.json", + "path": "/messaging/projects/{projectSlug}/campaigns/{id}/reschedule", + "method": "POST", + "operationId": "rescheduleCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.management.json", + "path": "/platform/campaigns/{campaignId}/launch", + "method": "POST", + "operationId": "launchPlatformCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Optional unique key, 1 to 255 bytes, that makes this request safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version` and request never runs it again while its receipt is retained. Keep the first response. Opaque campaign bodies are not retained by default; an available authorized exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After`; the request does not run again. Missing replay data never releases the execution fence.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.management.json", + "path": "/platform/campaigns/{campaignId}/pause", + "method": "POST", + "operationId": "pausePlatformCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Optional unique key, 1 to 255 bytes, that makes this request safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version` and request never runs it again while its receipt is retained. Keep the first response. Opaque campaign bodies are not retained by default; an available authorized exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After`; the request does not run again. Missing replay data never releases the execution fence.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.management.json", + "path": "/platform/campaigns/{campaignId}/resume", + "method": "POST", + "operationId": "resumePlatformCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Optional unique key, 1 to 255 bytes, that makes this request safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version` and request never runs it again while its receipt is retained. Keep the first response. Opaque campaign bodies are not retained by default; an available authorized exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After`; the request does not run again. Missing replay data never releases the execution fence.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.management.json", + "path": "/platform/campaigns/{campaignId}/stop", + "method": "POST", + "operationId": "stopPlatformCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Optional unique key, 1 to 255 bytes, that makes this request safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version` and request never runs it again while its receipt is retained. Keep the first response. Opaque campaign bodies are not retained by default; an available authorized exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After`; the request does not run again. Missing replay data never releases the execution fence.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.management.json", + "path": "/platform/campaigns/{campaignId}/reschedule", + "method": "POST", + "operationId": "reschedulePlatformCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Optional unique key, 1 to 255 bytes, that makes this request safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version` and request never runs it again while its receipt is retained. Keep the first response. Opaque campaign bodies are not retained by default; an available authorized exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After`; the request does not run again. Missing replay data never releases the execution fence.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + }, + { + "sourcePath": "apps/api/docs/openapi.management.json", + "path": "/platform/campaigns/{campaignId}/test-send", + "method": "POST", + "operationId": "testSendPlatformCampaign", + "idempotencyParameter": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Optional unique key, 1 to 255 bytes, that makes this request safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version` and request never runs it again while its receipt is retained. Keep the first response. Opaque campaign bodies are not retained by default; an available authorized exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After`; the request does not run again. Missing replay data never releases the execution fence.", + "schema": { "type": "string", "minLength": 1, "maxLength": 255 } + } + } + ], + "conversionDeduplication": { + "sourcePath": "apps/api/docs/openapi.management.json", + "path": "/platform/campaigns/{campaignId}/conversions", + "method": "POST", + "operationId": "recordCampaignConversion", + "description": "Beta: requires team enrollment in campaign conversion reporting. Records a conversion your system observed for one campaign recipient, such as a purchase or a sign-up. Name the recipient with `recipientId` from the campaign's recipient list; Polymorfa never matches a conversion to a recipient by phone number, reply or link. The conversion is attributed to the campaign when `occurredAt` is no earlier than the recipient's send time and no more than 7 days after it. Otherwise `attribution.outcome` is `outside_window`, or `not_sent` when the recipient was never sent. A recipient on the team's opt-out list is recorded as `opted_out` without the recipient link or the value. The decision is made once and never recalculated. `eventId` deduplicates per project: sending the same `eventId` with the same details returns the original conversion with `replayed: true`; different details answer `422 idempotency_conflict`. `value` is an integer amount in the currency's minor unit (for example cents) and an ISO 4217 code; amounts are never converted between currencies. Values are reported by you and are not verified payments. `occurredAt` cannot be in the future or more than 90 days ago. Conversions are deleted 400 days after they are recorded. Send `projectId` in the body when using a team API key.\n\nRequires `campaigns:manage`. Project tokens only access resources in their own project.", + "responses": { + "200": { + "description": "Success", + "headers": { + "X-Request-Id": { + "schema": { "type": "string" }, + "description": "Stable request correlation identifier." + }, + "X-Trace-Id": { + "schema": { "type": "string", "pattern": "^[0-9a-f]{32}$" }, + "description": "W3C trace ID of this request. Your `traceparent` trace ID when you sent a valid one." + }, + "Polymorfa-Version": { + "schema": { "type": "string" }, + "description": "API version applied to this response." + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": false, + "properties": { + "data": { "$ref": "#/components/schemas/CampaignConversion" } + }, + "required": ["data"] + } + } + } + }, + "400": { "$ref": "#/components/responses/BadRequest" }, + "401": { "$ref": "#/components/responses/Unauthorized" }, + "403": { "$ref": "#/components/responses/Forbidden" }, + "404": { "$ref": "#/components/responses/NotFound" }, + "409": { "$ref": "#/components/responses/Conflict" }, + "422": { "$ref": "#/components/responses/Unprocessable" } + } + }, + "extraction": "Idempotency error enums and unchanged one-hour header parameters from committed generated API documents; the baseline snapshots are unchanged", + "published": false +} diff --git a/packages/dotnet/src/Polymorfa.Sdk/ErrorCodes.cs b/packages/dotnet/src/Polymorfa.Sdk/ErrorCodes.cs index a9b6d5d8f..de2852535 100644 --- a/packages/dotnet/src/Polymorfa.Sdk/ErrorCodes.cs +++ b/packages/dotnet/src/Polymorfa.Sdk/ErrorCodes.cs @@ -6,7 +6,7 @@ public static class PolymorfaErrorCodes public static IReadOnlyList Known { get; } = Array.AsReadOnly(new[] { "invalid_parameter", "invalid_credential", "entitlement_required", "cloud_template_authority_restricted", "gate_limit_reached", "method_not_allowed", "permission_denied", "missing_scope", "resource_not_found", "hms_not_enabled", "media_fetch_failed", "resource_gone", "state_conflict", "rate_limit_exceeded", "internal_error", "operation_not_supported", "upstream_failure", "service_unavailable", "credential_verification_unavailable", "session_not_ready", "hybrid_routing_paused", "hybrid_automation_unavailable", "hybrid_transport_unavailable", "hybrid_target_reference_unavailable", "hybrid_choice_required", "hybrid_transition_ineligible", "send_outcome_unknown", "command_dispatch_failed", "result_unknown", "recipient_not_on_whatsapp", "conversation_window_closed", "template_not_approved", "media_too_large", "whatsapp_rate_limited", "new_chat_limit_reached", "whatsapp_account_restricted", "whatsapp_groups_ineligible", "whatsapp_group_creation_paused", "whatsapp_group_limit_reached", "whatsapp_group_full", "whatsapp_group_suspended", "whatsapp_group_has_no_participants", "order_status_transition_invalid", "order_cancellation_failed", "number_restricted", - "bansafe_suspended", "bansafe_org_suspended", "bansafe_cold_blocked", "bansafe_cold_held", "bansafe_throttled", "bansafe_daily_allowance_reached", "bansafe_accounting_unavailable", "bansafe_send_outcome_unknown", "campaign_throughput_capped", "addon_required", "campaigns_not_entitled", "idempotency_completed", "idempotency_conflict", "idempotency_in_progress", "idempotency_outcome_unknown", "feature_unavailable", "stream_connection_limit_reached", "stream_cursor_expired", "stream_cursor_invalid", "payg_required", "premium_required", + "bansafe_suspended", "bansafe_org_suspended", "bansafe_cold_blocked", "bansafe_cold_held", "bansafe_throttled", "bansafe_daily_allowance_reached", "bansafe_accounting_unavailable", "bansafe_send_outcome_unknown", "campaign_throughput_capped", "addon_required", "campaigns_not_entitled", "idempotency_completed", "idempotency_conflict", "idempotency_in_progress", "idempotency_outcome_unknown", "idempotency_replay_unavailable", "feature_unavailable", "stream_connection_limit_reached", "stream_cursor_expired", "stream_cursor_invalid", "payg_required", "premium_required", "call_claimed", "call_not_ringing", "call_permission_required", "calls_disabled", "call_recipient_opted_out", "call_destination_blocked", "call_permission_request_limited", "call_permission_granted", "call_opt_out_limit", "asset_not_ready", "connection_limit", "invalid_sip_trunk", "sip_trunk_in_use", "sip_trunk_limit", "sip_trunk_revision_conflict", "sip_unavailable", "provider_credential_invalid", "provider_unavailable", "voice_asset_in_use", "voice_asset_revision_conflict", "voice_not_enabled", "voice_unavailable", "unsupported_for_connection", "whatsapp_authorization_required","whatsapp_payment_method_required","whatsapp_number_not_registered","marketing_disabled_on_cloud_api","parent_bsuid_not_supported","hybrid_group_linked_devices_unavailable","catalog_cache_full","catalog_sync_cooldown", "campaign_approval_required", "campaign_approval_stale", "campaign_variables_missing", "zero_knowledge_session" }); public static bool IsKnown(string? code) => code is not null && Known.Contains(code, StringComparer.Ordinal); diff --git a/packages/dotnet/tests/Polymorfa.Sdk.Tests/Program.cs b/packages/dotnet/tests/Polymorfa.Sdk.Tests/Program.cs index ec2073478..2264e51be 100644 --- a/packages/dotnet/tests/Polymorfa.Sdk.Tests/Program.cs +++ b/packages/dotnet/tests/Polymorfa.Sdk.Tests/Program.cs @@ -142,6 +142,7 @@ Equal(valid, fixture.GetProperty("valid").GetBoolean(), id); Console.WriteLine($"PASS configuration {id}"); count++; } ResourceTests.True(PolymorfaErrorCodes.IsKnown("voice_unavailable")); + ResourceTests.True(PolymorfaErrorCodes.IsKnown("idempotency_replay_unavailable")); ResourceTests.True(!PolymorfaErrorCodes.IsKnown("future_error")); WebhookTests.Run(); await SystemTests.RunAsync(); diff --git a/packages/go/error_codes.go b/packages/go/error_codes.go index 966048354..055eaedd8 100644 --- a/packages/go/error_codes.go +++ b/packages/go/error_codes.go @@ -23,5 +23,5 @@ const ( var knownErrorCodes = [...]string{ ErrorCampaignApprovalRequired, ErrorCampaignApprovalStale, ErrorCampaignVariablesMissing, ErrorZeroKnowledgeSession, - "invalid_parameter", "invalid_credential", "entitlement_required", "cloud_template_authority_restricted", "gate_limit_reached", "method_not_allowed", "permission_denied", "missing_scope", "resource_not_found", "hms_not_enabled", "media_fetch_failed", "resource_gone", "state_conflict", "rate_limit_exceeded", "internal_error", "operation_not_supported", "upstream_failure", "service_unavailable", "credential_verification_unavailable", "session_not_ready", "hybrid_routing_paused", "hybrid_automation_unavailable", "hybrid_transport_unavailable", "hybrid_target_reference_unavailable", "hybrid_choice_required", "hybrid_transition_ineligible", "send_outcome_unknown", "command_dispatch_failed", "result_unknown", "recipient_not_on_whatsapp", "conversation_window_closed", "template_not_approved", "media_too_large", "whatsapp_rate_limited", "new_chat_limit_reached", "whatsapp_account_restricted", "whatsapp_groups_ineligible", "whatsapp_group_creation_paused", "whatsapp_group_limit_reached", "whatsapp_group_full", "whatsapp_group_suspended", "whatsapp_group_has_no_participants", "order_status_transition_invalid", "order_cancellation_failed", "number_restricted", "bansafe_suspended", "bansafe_org_suspended", "bansafe_cold_blocked", "bansafe_cold_held", "bansafe_throttled", "bansafe_daily_allowance_reached", "bansafe_accounting_unavailable", "bansafe_send_outcome_unknown", "campaign_throughput_capped", "addon_required", "campaigns_not_entitled", "idempotency_completed", "idempotency_conflict", "idempotency_in_progress", "idempotency_outcome_unknown", "feature_unavailable", "stream_connection_limit_reached", "stream_cursor_expired", "stream_cursor_invalid", "payg_required", "premium_required", "call_claimed", "call_not_ringing", "call_permission_required", "calls_disabled", "call_recipient_opted_out", "call_destination_blocked", "call_permission_request_limited", "call_permission_granted", "call_opt_out_limit", "asset_not_ready", "connection_limit", "invalid_sip_trunk", "sip_trunk_in_use", "sip_trunk_limit", "sip_trunk_revision_conflict", "sip_unavailable", "provider_credential_invalid", "provider_unavailable", "voice_asset_in_use", "voice_asset_revision_conflict", "voice_not_enabled", "voice_unavailable", "unsupported_for_connection", "whatsapp_authorization_required", "whatsapp_payment_method_required", "whatsapp_number_not_registered", "marketing_disabled_on_cloud_api", "parent_bsuid_not_supported", "hybrid_group_linked_devices_unavailable", "catalog_cache_full", "catalog_sync_cooldown", + "invalid_parameter", "invalid_credential", "entitlement_required", "cloud_template_authority_restricted", "gate_limit_reached", "method_not_allowed", "permission_denied", "missing_scope", "resource_not_found", "hms_not_enabled", "media_fetch_failed", "resource_gone", "state_conflict", "rate_limit_exceeded", "internal_error", "operation_not_supported", "upstream_failure", "service_unavailable", "credential_verification_unavailable", "session_not_ready", "hybrid_routing_paused", "hybrid_automation_unavailable", "hybrid_transport_unavailable", "hybrid_target_reference_unavailable", "hybrid_choice_required", "hybrid_transition_ineligible", "send_outcome_unknown", "command_dispatch_failed", "result_unknown", "recipient_not_on_whatsapp", "conversation_window_closed", "template_not_approved", "media_too_large", "whatsapp_rate_limited", "new_chat_limit_reached", "whatsapp_account_restricted", "whatsapp_groups_ineligible", "whatsapp_group_creation_paused", "whatsapp_group_limit_reached", "whatsapp_group_full", "whatsapp_group_suspended", "whatsapp_group_has_no_participants", "order_status_transition_invalid", "order_cancellation_failed", "number_restricted", "bansafe_suspended", "bansafe_org_suspended", "bansafe_cold_blocked", "bansafe_cold_held", "bansafe_throttled", "bansafe_daily_allowance_reached", "bansafe_accounting_unavailable", "bansafe_send_outcome_unknown", "campaign_throughput_capped", "addon_required", "campaigns_not_entitled", "idempotency_completed", "idempotency_conflict", "idempotency_in_progress", "idempotency_outcome_unknown", "idempotency_replay_unavailable", "feature_unavailable", "stream_connection_limit_reached", "stream_cursor_expired", "stream_cursor_invalid", "payg_required", "premium_required", "call_claimed", "call_not_ringing", "call_permission_required", "calls_disabled", "call_recipient_opted_out", "call_destination_blocked", "call_permission_request_limited", "call_permission_granted", "call_opt_out_limit", "asset_not_ready", "connection_limit", "invalid_sip_trunk", "sip_trunk_in_use", "sip_trunk_limit", "sip_trunk_revision_conflict", "sip_unavailable", "provider_credential_invalid", "provider_unavailable", "voice_asset_in_use", "voice_asset_revision_conflict", "voice_not_enabled", "voice_unavailable", "unsupported_for_connection", "whatsapp_authorization_required", "whatsapp_payment_method_required", "whatsapp_number_not_registered", "marketing_disabled_on_cloud_api", "parent_bsuid_not_supported", "hybrid_group_linked_devices_unavailable", "catalog_cache_full", "catalog_sync_cooldown", } diff --git a/packages/go/error_codes_test.go b/packages/go/error_codes_test.go index 0398bcb5b..f3594bc63 100644 --- a/packages/go/error_codes_test.go +++ b/packages/go/error_codes_test.go @@ -4,7 +4,7 @@ import "testing" func TestKnownErrorCatalog(t *testing.T) { codes := KnownErrorCodes() - if len(codes) != 101 || !IsKnownErrorCode("voice_unavailable") || IsKnownErrorCode("future_api_code") { + if len(codes) != 102 || !IsKnownErrorCode("idempotency_replay_unavailable") || !IsKnownErrorCode("voice_unavailable") || IsKnownErrorCode("future_api_code") { t.Fatal("catalog boundary") } for _, code := range []string{"catalog_cache_full", "catalog_sync_cooldown", "hybrid_group_linked_devices_unavailable", "marketing_disabled_on_cloud_api", "parent_bsuid_not_supported", "whatsapp_authorization_required", "whatsapp_number_not_registered", "whatsapp_payment_method_required"} { diff --git a/packages/go/media_upload.go b/packages/go/media_upload.go index 3443b7f4b..6fdbed692 100644 --- a/packages/go/media_upload.go +++ b/packages/go/media_upload.go @@ -196,6 +196,11 @@ func uploadStatus(status int) error { } return &directUploadFailure{status: status, retry: status == 401 || status == 408 || (status >= 500 && status != 507), final: &Error{Kind: ServerError, Status: status, Code: code, Message: "The WhatsApp media host rejected the upload."}} } + +// directPost submits encrypted bytes without following redirects or forwarding +// API credentials. Deadline and cancellation errors retain no signed-URL cause, +// including when cancellation closes the response body as an ordinary EOF. +// The caller owns retry decisions; this method performs one HTTP submission. func (r *WhatsAppMediaResource) directPost(ctx context.Context, target string, body io.Reader, length int64) ([]byte, error) { request, err := http.NewRequestWithContext(ctx, "POST", target, body) if err != nil { @@ -224,10 +229,12 @@ func (r *WhatsAppMediaResource) directPost(ctx context.Context, target string, b return nil, uploadStatus(response.StatusCode) } value, err := io.ReadAll(io.LimitReader(response.Body, 65537)) + // A body closed by cancellation can finish as EOF rather than a read error. + // Preserve the deadline/cancellation result before parsing an empty location. + if ctx.Err() != nil { + return nil, contextError(ctx, nil) + } if err != nil { - if ctx.Err() != nil { - return nil, contextError(ctx, nil) - } return nil, &directUploadFailure{retry: true, final: &Error{Kind: ConnectionError, Message: "The upload response could not be read."}} } if len(value) > 65536 || (len(value) > 0 && !json.Valid(value)) { diff --git a/packages/go/media_upload_test.go b/packages/go/media_upload_test.go index e5b58d926..bcdf4bec2 100644 --- a/packages/go/media_upload_test.go +++ b/packages/go/media_upload_test.go @@ -268,6 +268,54 @@ func TestNativeDocumentPartsAndChangedSourceNeverFinalize(t *testing.T) { }) } } + +type cancelledUploadEOF struct { + ctx context.Context + cancel context.CancelFunc +} + +func (body cancelledUploadEOF) Read([]byte) (int, error) { + if body.cancel != nil { + body.cancel() + } + <-body.ctx.Done() + return 0, io.EOF +} + +func TestNativeDirectBodyEOFStillPreservesCancellation(t *testing.T) { + for _, deadline := range []bool{false, true} { + t.Run(fmt.Sprintf("deadline=%t", deadline), func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + if deadline { + cancel() + ctx, cancel = context.WithTimeout(context.Background(), time.Millisecond) + } + defer cancel() + body := cancelledUploadEOF{ctx: ctx} + if !deadline { + body.cancel = cancel + } + config := orgConfig("https://api.example.invalid") + config.HTTPClient = &http.Client{Transport: mediaRoundTripper(func(req *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(body), Request: req}, nil + })} + sdk, err := NewMessagingClient(config) + if err != nil { + t.Fatal(err) + } + _, err = sdk.WhatsAppMedia().directPost(ctx, "https://cdn.whatsapp.net/mms/image/fixture?auth=synthetic_grant", strings.NewReader("encrypted fixture"), 17) + want := CancelledError + if deadline { + want = TimeoutError + } + var typed *Error + if !errors.As(err, &typed) || typed.Kind != want || typed.Cause != nil || strings.Contains(fmt.Sprintf("%#v", err), "synthetic_grant") { + t.Fatal("cancelled EOF lost its safe cancellation classification", err) + } + }) + } +} + func TestNativeDirectBodyDeadlineRedirectAndSourceCancellation(t *testing.T) { var grants, hops atomic.Int32 sdk := uploadFixture(t, func(w http.ResponseWriter, req *http.Request) { diff --git a/packages/php/src/ErrorCodes.php b/packages/php/src/ErrorCodes.php index 0a2a6c9b2..f069a7709 100644 --- a/packages/php/src/ErrorCodes.php +++ b/packages/php/src/ErrorCodes.php @@ -8,7 +8,7 @@ final class ErrorCodes { public const KNOWN = [ - 'invalid_parameter','invalid_credential','entitlement_required','cloud_template_authority_restricted','gate_limit_reached','method_not_allowed','permission_denied','missing_scope','resource_not_found','hms_not_enabled','media_fetch_failed','resource_gone','state_conflict','rate_limit_exceeded','internal_error','operation_not_supported','upstream_failure','service_unavailable','credential_verification_unavailable','session_not_ready','hybrid_routing_paused','hybrid_automation_unavailable','hybrid_transport_unavailable','hybrid_target_reference_unavailable','hybrid_choice_required','hybrid_transition_ineligible','send_outcome_unknown','command_dispatch_failed','result_unknown','recipient_not_on_whatsapp','conversation_window_closed','template_not_approved','media_too_large','whatsapp_rate_limited','new_chat_limit_reached','whatsapp_account_restricted','whatsapp_groups_ineligible','whatsapp_group_creation_paused','whatsapp_group_limit_reached','whatsapp_group_full','whatsapp_group_suspended','whatsapp_group_has_no_participants','order_status_transition_invalid','order_cancellation_failed','number_restricted','bansafe_suspended','bansafe_org_suspended','bansafe_cold_blocked','bansafe_cold_held','bansafe_throttled','bansafe_daily_allowance_reached','bansafe_accounting_unavailable','bansafe_send_outcome_unknown','campaign_throughput_capped','addon_required','campaigns_not_entitled','idempotency_completed','idempotency_conflict','idempotency_in_progress','idempotency_outcome_unknown','feature_unavailable','stream_connection_limit_reached','stream_cursor_expired','stream_cursor_invalid','payg_required','premium_required','call_claimed','call_not_ringing','call_permission_required','calls_disabled','call_recipient_opted_out','call_destination_blocked','call_permission_request_limited','call_permission_granted','call_opt_out_limit','asset_not_ready','connection_limit','invalid_sip_trunk','sip_trunk_in_use','sip_trunk_limit','sip_trunk_revision_conflict','sip_unavailable','provider_credential_invalid','provider_unavailable','voice_asset_in_use','voice_asset_revision_conflict','voice_not_enabled','voice_unavailable','unsupported_for_connection', 'whatsapp_authorization_required','whatsapp_payment_method_required','whatsapp_number_not_registered','marketing_disabled_on_cloud_api','parent_bsuid_not_supported','hybrid_group_linked_devices_unavailable','catalog_cache_full','catalog_sync_cooldown','campaign_approval_required','campaign_approval_stale','campaign_variables_missing','zero_knowledge_session', + 'invalid_parameter','invalid_credential','entitlement_required','cloud_template_authority_restricted','gate_limit_reached','method_not_allowed','permission_denied','missing_scope','resource_not_found','hms_not_enabled','media_fetch_failed','resource_gone','state_conflict','rate_limit_exceeded','internal_error','operation_not_supported','upstream_failure','service_unavailable','credential_verification_unavailable','session_not_ready','hybrid_routing_paused','hybrid_automation_unavailable','hybrid_transport_unavailable','hybrid_target_reference_unavailable','hybrid_choice_required','hybrid_transition_ineligible','send_outcome_unknown','command_dispatch_failed','result_unknown','recipient_not_on_whatsapp','conversation_window_closed','template_not_approved','media_too_large','whatsapp_rate_limited','new_chat_limit_reached','whatsapp_account_restricted','whatsapp_groups_ineligible','whatsapp_group_creation_paused','whatsapp_group_limit_reached','whatsapp_group_full','whatsapp_group_suspended','whatsapp_group_has_no_participants','order_status_transition_invalid','order_cancellation_failed','number_restricted','bansafe_suspended','bansafe_org_suspended','bansafe_cold_blocked','bansafe_cold_held','bansafe_throttled','bansafe_daily_allowance_reached','bansafe_accounting_unavailable','bansafe_send_outcome_unknown','campaign_throughput_capped','addon_required','campaigns_not_entitled','idempotency_completed','idempotency_conflict','idempotency_in_progress','idempotency_outcome_unknown','idempotency_replay_unavailable','feature_unavailable','stream_connection_limit_reached','stream_cursor_expired','stream_cursor_invalid','payg_required','premium_required','call_claimed','call_not_ringing','call_permission_required','calls_disabled','call_recipient_opted_out','call_destination_blocked','call_permission_request_limited','call_permission_granted','call_opt_out_limit','asset_not_ready','connection_limit','invalid_sip_trunk','sip_trunk_in_use','sip_trunk_limit','sip_trunk_revision_conflict','sip_unavailable','provider_credential_invalid','provider_unavailable','voice_asset_in_use','voice_asset_revision_conflict','voice_not_enabled','voice_unavailable','unsupported_for_connection', 'whatsapp_authorization_required','whatsapp_payment_method_required','whatsapp_number_not_registered','marketing_disabled_on_cloud_api','parent_bsuid_not_supported','hybrid_group_linked_devices_unavailable','catalog_cache_full','catalog_sync_cooldown','campaign_approval_required','campaign_approval_stale','campaign_variables_missing','zero_knowledge_session', ]; private function __construct() { diff --git a/packages/php/tests/webhook_models.php b/packages/php/tests/webhook_models.php index 203a445cb..132784c53 100644 --- a/packages/php/tests/webhook_models.php +++ b/packages/php/tests/webhook_models.php @@ -64,7 +64,7 @@ check(Polymorfa\Webhooks::verifyLocal($raw, $signature, $local, nowUnixSeconds:1000)->event === 'future.event', 'Local signature normalizes numeric timestamp and decodes byte key'); raises(fn () => Polymorfa\Webhooks::verifyLocal($raw, $signature, $local, nowUnixSeconds:1301), Polymorfa\WebhookSignatureException::class); raises(fn () => Polymorfa\Webhooks::verifyLocal($raw, strtoupper($signature), $local, nowUnixSeconds:1000), Polymorfa\WebhookSignatureException::class); -check(count(Polymorfa\ErrorCodes::KNOWN) === 101 && Polymorfa\ErrorCodes::isKnown('voice_unavailable') && !Polymorfa\ErrorCodes::isKnown('future_api_code'), 'Known API code catalog'); +check(count(Polymorfa\ErrorCodes::KNOWN) === 102 && Polymorfa\ErrorCodes::isKnown('idempotency_replay_unavailable') && Polymorfa\ErrorCodes::isKnown('voice_unavailable') && !Polymorfa\ErrorCodes::isKnown('future_api_code'), 'Known API code catalog'); check(Polymorfa\ErrorCodes::isKnown('catalog_cache_full'), 'Known Official API code: catalog_cache_full'); check(Polymorfa\ErrorCodes::isKnown('catalog_sync_cooldown'), 'Known Official API code: catalog_sync_cooldown'); check(Polymorfa\ErrorCodes::isKnown('hybrid_group_linked_devices_unavailable'), 'Known Official API code: hybrid_group_linked_devices_unavailable'); diff --git a/packages/python/src/polymorfa/error_codes.py b/packages/python/src/polymorfa/error_codes.py index 1dffb0f5c..b34cef5c5 100644 --- a/packages/python/src/polymorfa/error_codes.py +++ b/packages/python/src/polymorfa/error_codes.py @@ -46,6 +46,7 @@ "idempotency_conflict", "idempotency_in_progress", "idempotency_outcome_unknown", + "idempotency_replay_unavailable", "internal_error", "invalid_credential", "invalid_parameter", @@ -172,6 +173,7 @@ "idempotency_conflict", "idempotency_in_progress", "idempotency_outcome_unknown", + "idempotency_replay_unavailable", "feature_unavailable", "stream_connection_limit_reached", "stream_cursor_expired", diff --git a/packages/rust/src/errors.rs b/packages/rust/src/errors.rs index b92714279..e8d09bf42 100644 --- a/packages/rust/src/errors.rs +++ b/packages/rust/src/errors.rs @@ -190,6 +190,7 @@ pub const POLYMORFA_ERROR_CODES: &[&str] = &[ "idempotency_conflict", "idempotency_in_progress", "idempotency_outcome_unknown", + "idempotency_replay_unavailable", "feature_unavailable", "stream_connection_limit_reached", "stream_cursor_expired", diff --git a/packages/rust/tests/fixtures/known-error-codes.json b/packages/rust/tests/fixtures/known-error-codes.json index 3344d212b..a9e92fe1f 100644 --- a/packages/rust/tests/fixtures/known-error-codes.json +++ b/packages/rust/tests/fixtures/known-error-codes.json @@ -61,6 +61,7 @@ "idempotency_conflict", "idempotency_in_progress", "idempotency_outcome_unknown", + "idempotency_replay_unavailable", "feature_unavailable", "stream_connection_limit_reached", "stream_cursor_expired", diff --git a/packages/typescript/README.md b/packages/typescript/README.md index b73853eba..3181cf795 100644 --- a/packages/typescript/README.md +++ b/packages/typescript/README.md @@ -508,8 +508,9 @@ an optional language; the API defaults to `en_US`. Deleting a name deletes all its languages. Create, edit and delete make one attempt, even if an idempotency key or a retry override is supplied. Create and delete send your `idempotencyKey` to the API, so a manual retry with the same key -returns `PolymorfaConflictError` (`idempotency_completed`) instead of writing -again. Edit has no key; list or retrieve the template to reconcile an +does not submit the same write again while its receipt is retained. Keep the first +response; a retry may report that replay data is unavailable. Edit has no key; +list or retrieve the template to reconcile an uncertain result before submitting another write. ```ts @@ -1415,8 +1416,11 @@ These methods send an `Idempotency-Key` on every call: If you don't pass `idempotencyKey`, the SDK generates a random UUID for the call. Every automatic retry of that call reuses the key, so the API never runs the write twice. If the first attempt succeeded but its response was lost, -the retry fails with `PolymorfaConflictError` (`idempotency_completed`) instead -of sending the message again. Pass your own key, such as +the retained receipt prevents another execution within the endpoint\'s window. +Response replay depends on the API contract and available replay data. A retry +can report `503 idempotency_replay_unavailable` without executing the write again. +When the API returns a replayed response, it has +`metadata.headers["idempotent-replayed"] === "true"`. Pass your own key, such as an order event ID, to deduplicate across processes or restarts: ```ts @@ -1430,8 +1434,18 @@ await messaging.messages.send( ); ``` -The API keeps each key for 24 hours per credential. Reusing a key for a -different request fails with `PolymorfaConflictError` (`idempotency_conflict`). +Messaging writes and campaign lifecycle requests on both APIs use a one-hour +receipt window in the response-replay contract. Other Platform operations keep +their documented windows. Older pinned contracts can have different windows +and can return the legacy `idempotency_completed` error. Reusing a key for a different request fails with +`PolymorfaValidationError` (`422 idempotency_conflict`) in the response-replay +contract. A recorded error does not prove the write had no effect. Reconcile +message events, webhooks or the resource before deciding whether another write +is safe. Never change keys merely to bypass an uncertain result. Keep the first +response: opaque response bodies are not retained by default. Denied or missing +exact replay data returns `503 idempotency_replay_unavailable` with `Retry-After`. +The SDK's configured retry policy reuses the same key; waiting does not guarantee +that replay data becomes available. A retry that arrives while the first request is still running receives `idempotency_in_progress`, and the SDK retries it after `Retry-After`. When a response carries `Idempotent-Replayed: true`, the SDK treats it as final and @@ -2151,9 +2165,9 @@ and was cancelled immediately. Check for null before calling scheduled start can be stopped or rescheduled. Rescheduling after sending has started returns `409`. Launch, reschedule, pause, resume, and stop generate one idempotency key per call unless you -pass one. Automatic retries reuse that key; a completed replay returns the -API's `idempotency_completed` conflict, so inspect the campaign state after a -lost response. +pass one. Automatic retries reuse that key. Keep the original response and +inspect the campaign after a lost response; unavailable replay data does not +permit another execution with a fresh key. #### A/B tests (beta) @@ -2288,7 +2302,7 @@ on the team's opt-out list is recorded as `opted_out`, with no recipient link and no value. The decision is fixed when the conversion is recorded. `eventId` deduplicates per project: sending the same body again returns the original with `replayed: true`, so retries are safe. Changing any detail -answers `409 idempotency_conflict`. Amounts are integer minor units of an ISO +answers `422 idempotency_conflict`. Amounts are integer minor units of an ISO 4217 currency. The report sums them per currency, as decimal strings, and never converts between currencies. Values are as reported, not verified payments. @@ -2310,10 +2324,12 @@ members, and `Client.optOuts` reads and replaces team keyword settings. Platform `create` route has no replay contract, so the SDK sends it once and does not accept an idempotency key or retry setting. After a lost create response, inspect the campaign list before creating another draft. For launch -and reschedule, a supplied key is preserved across retries within the API's -24-hour replay window. If the outcome remains uncertain after that window, -reconcile campaign state before starting another request; see -[Idempotent sends](#idempotent-sends). +and reschedule, a supplied key is preserved across retries. The older pinned +Platform contract has a 24-hour replay window; the response-replay contract uses +the one-hour receipt window described in [Idempotent sends](#idempotent-sends). +Use the window of the API contract serving the request. If the outcome remains +uncertain, reconcile campaign state before starting another request. Retrying +after the receipt expires can run the operation again. `archive` returns a receipt for a completed, failed, or cancelled campaign; other states return `409`. A pending final event or active delivery run also returns `409`; retry after both finish. Platform `delete` accepts draft, diff --git a/packages/typescript/src/errors.ts b/packages/typescript/src/errors.ts index eacd7a191..ee49d4248 100644 --- a/packages/typescript/src/errors.ts +++ b/packages/typescript/src/errors.ts @@ -90,6 +90,7 @@ export const POLYMORFA_ERROR_CODES = [ "idempotency_conflict", "idempotency_in_progress", "idempotency_outcome_unknown", + "idempotency_replay_unavailable", "feature_unavailable", "whatsapp_authorization_required", "whatsapp_payment_method_required", diff --git a/packages/typescript/src/messaging/cloud-templates.ts b/packages/typescript/src/messaging/cloud-templates.ts index 8883276e3..112c62ea2 100644 --- a/packages/typescript/src/messaging/cloud-templates.ts +++ b/packages/typescript/src/messaging/cloud-templates.ts @@ -110,9 +110,9 @@ export class CloudTemplatesResource { /** * Sends one request; the SDK never retries this provider write. Pass - * `options.idempotencyKey` so a manual retry after an unknown outcome returns - * `409 idempotency_completed` instead of submitting again, and list templates - * before resubmitting. + * `options.idempotencyKey` so a manual retry uses the same execution fence. + * Keep the first response. If replay data is unavailable or the outcome is + * unknown, list templates before deciding whether another write is safe. */ create( session: string, diff --git a/packages/typescript/src/platform/campaigns.ts b/packages/typescript/src/platform/campaigns.ts index 671bf61a1..16980ade1 100644 --- a/packages/typescript/src/platform/campaigns.ts +++ b/packages/typescript/src/platform/campaigns.ts @@ -458,7 +458,8 @@ export class CampaignsResource { * recipient was sent; the decision is made once and never recalculated. * `eventId` deduplicates per project, so a retry with the same body returns * the original conversion with `replayed: true`, and a different body is - * refused with `409 idempotency_conflict`. Retries are therefore safe. + * refused with `422 idempotency_conflict` (`PolymorfaValidationError`). + * Retries are therefore safe. */ recordConversion( campaignId: string, diff --git a/packages/typescript/src/transport/idempotency.ts b/packages/typescript/src/transport/idempotency.ts index 760b786bf..77113f541 100644 --- a/packages/typescript/src/transport/idempotency.ts +++ b/packages/typescript/src/transport/idempotency.ts @@ -6,9 +6,9 @@ import { PolymorfaConfigurationError } from "../errors.js"; * * The explicit key option wins, then one case-insensitive header value. * Otherwise one random key is generated per call, - * so every automatic retry of that call reuses it. The endpoint determines the - * retry response: completed messaging writes return idempotency_completed - * without the original response body. + * so every automatic retry of that call reuses it. The API contract and + * available replay data determine the response. Keep the same key while + * reconciling an uncertain outcome; a new key may execute another write. */ export function withIdempotencyKey(options: RequestOptions): RequestOptions { let key = options.idempotencyKey; diff --git a/packages/typescript/test/error-body.test.ts b/packages/typescript/test/error-body.test.ts index 5fbe3caf8..123051f87 100644 --- a/packages/typescript/test/error-body.test.ts +++ b/packages/typescript/test/error-body.test.ts @@ -195,7 +195,33 @@ describe("error codes", () => { "utf8", ), ) as { errorCodes: string[] }; + const replay = JSON.parse( + await readFile( + new URL("../../../contracts/idempotency-replay.json", import.meta.url), + "utf8", + ), + ) as { + errorCodes: string[]; + sourceCommit: string; + published: boolean; + conversionDeduplication: { + operationId: string; + description: string; + responses: Record; + }; + }; + expect(replay.sourceCommit).toMatch(/^[0-9a-f]{40}$/); + expect(replay.published).toBe(false); + expect(replay.errorCodes).toContain("idempotency_replay_unavailable"); + expect(replay.conversionDeduplication.operationId).toBe( + "recordCampaignConversion", + ); + expect(replay.conversionDeduplication.description).toContain( + "422 idempotency_conflict", + ); + expect(replay.conversionDeduplication.responses["422"]).toBeDefined(); const published = new Set([ + ...replay.errorCodes, ...round2.errorCodes, ...messaging.components.schemas.PublicError!.properties.error.properties .code.enum, @@ -205,7 +231,7 @@ describe("error codes", () => { ]); // Older API deployments returned this code; keep recognizing it even // though the pinned API contract no longer advertises it. - const legacyCodes = ["premium_required"]; + const legacyCodes = ["premium_required", "idempotency_completed"]; // The baseline remains pinned; these additive1014 codes are also in the // independently pinned supplement and do not advance its release status. const additiveCodes = [ @@ -223,9 +249,10 @@ describe("error codes", () => { ); for (const code of additiveCodes) expect(supplement).toContain(`"${code}"`); expect([...POLYMORFA_ERROR_CODES].sort()).toEqual( - [...published, ...legacyCodes, ...additiveCodes].sort(), + [...new Set([...published, ...legacyCodes, ...additiveCodes])].sort(), ); expect(isKnownPolymorfaErrorCode("premium_required")).toBe(true); + expect(isKnownPolymorfaErrorCode("idempotency_completed")).toBe(true); }); it("accepts codes added by a newer API", () => { diff --git a/packages/typescript/test/transport.test.ts b/packages/typescript/test/transport.test.ts index 6b9685b94..5b2f9a818 100644 --- a/packages/typescript/test/transport.test.ts +++ b/packages/typescript/test/transport.test.ts @@ -43,6 +43,74 @@ function makeTransport( } describe("HttpTransport", () => { + it.each([undefined, "false", "true"])( + "exposes only the received replay marker %s in safe response metadata", + async (marker) => { + const fetch = vi.fn(async () => + Response.json( + { ok: true }, + { + headers: { + ...(marker === undefined + ? {} + : { "Idempotent-Replayed": marker }), + "set-cookie": "session=private", + "x-internal-debug": "private", + }, + }, + ), + ); + const response = await makeTransport("https://api.example.com", { + fetch, + }).request({ + method: "POST", + path: "/messaging/test", + idempotencyKey: "same-key", + }); + + expect(response.metadata.headers["idempotent-replayed"]).toBe(marker); + expect(response.metadata.headers).not.toHaveProperty("set-cookie"); + expect(response.metadata.headers).not.toHaveProperty("x-internal-debug"); + expect(Object.isFrozen(response.metadata.headers)).toBe(true); + expect(fetch).toHaveBeenCalledTimes(1); + }, + ); + + it("exposes a replayed server error without another attempt", async () => { + const fetch = vi.fn(async () => + Response.json( + { + error: { code: "service_unavailable", message: "Recorded failure." }, + }, + { + status: 503, + headers: { "Idempotent-Replayed": "true", "Retry-After": "1" }, + }, + ), + ); + const sleep = vi.fn(async () => undefined); + const error = await makeTransport("https://api.example.com", { + fetch, + sleep, + maxNetworkRetries: 2, + }) + .request({ + method: "POST", + path: "/messaging/test", + idempotencyKey: "same-key", + }) + .catch((caught) => caught); + + expect(error).toBeInstanceOf(PolymorfaServerError); + expect(error.metadata).toMatchObject({ + status: 503, + attempts: 1, + headers: { "idempotent-replayed": "true" }, + }); + expect(fetch).toHaveBeenCalledTimes(1); + expect(sleep).not.toHaveBeenCalled(); + }); + it("rejects cleartext credential transport outside loopback", () => { expect(() => makeTransport("http://api.example.com")).toThrow( PolymorfaConfigurationError, diff --git a/scripts/doc-snippets/recipes.mjs b/scripts/doc-snippets/recipes.mjs index ddc102dc9..3d397d029 100644 --- a/scripts/doc-snippets/recipes.mjs +++ b/scripts/doc-snippets/recipes.mjs @@ -1,7 +1,7 @@ // Requests come from the pinned OpenAPI and existing native wire fixtures. // Calls are handwritten in the language modules. Never derive arguments from // contracts/coverage.json's display-only method names. -export const sourceCommit = "a6324a31225fc73be8c49dba5985a65a22c9b06b"; +export const sourceCommit = "b79ae6ad2cff690b8a0b68085f0bc9d5ba7561e7"; export const apiVersion = "2026-09-22"; export const languages = [ "typescript", diff --git a/scripts/sync-idempotency-replay-contract.mjs b/scripts/sync-idempotency-replay-contract.mjs new file mode 100644 index 000000000..559b00654 --- /dev/null +++ b/scripts/sync-idempotency-replay-contract.mjs @@ -0,0 +1,104 @@ +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { writeFileSync } from "node:fs"; +import { format } from "prettier"; + +const [repository, revision] = process.argv.slice(2); +if (!repository || !/^[0-9a-f]{40}$/.test(revision ?? "")) { + throw new Error( + "Usage: sync-idempotency-replay-contract ", + ); +} +const actual = execFileSync( + "git", + ["-C", repository, "rev-parse", `${revision}^{commit}`], + { encoding: "utf8" }, +).trim(); +if (actual !== revision) + throw new Error("Source must be the exact recorded commit"); +const sources = []; +const errorCodes = new Set(); +const operations = []; +let conversionDeduplication; +for (const path of [ + "apps/api/docs/openapi.json", + "apps/api/docs/openapi.management.json", +]) { + const bytes = execFileSync( + "git", + ["-C", repository, "show", `${revision}:${path}`], + { maxBuffer: 32 * 1024 * 1024 }, + ); + const document = JSON.parse(bytes); + const schemas = document.components?.schemas ?? {}; + const codes = Object.values(schemas).flatMap( + (schema) => schema?.properties?.error?.properties?.code?.enum ?? [], + ); + for (const code of codes) + if (code.startsWith("idempotency_")) errorCodes.add(code); + sources.push({ + path, + sha256: createHash("sha256").update(bytes).digest("hex"), + info: document.info, + }); + for (const [route, item] of Object.entries(document.paths)) { + for (const [method, operation] of Object.entries(item)) { + if (!operation || typeof operation !== "object" || !operation.operationId) + continue; + if (operation.operationId === "recordCampaignConversion") { + if ( + !operation.responses?.["422"] || + !operation.description?.includes("422 idempotency_conflict") + ) { + throw new Error( + "Conversion deduplication is not documented as 422 in the pinned source", + ); + } + conversionDeduplication = { + sourcePath: path, + path: route, + method: method.toUpperCase(), + operationId: operation.operationId, + description: operation.description, + responses: operation.responses, + }; + } + const parameter = operation.parameters?.find( + (entry) => entry.name === "Idempotency-Key" && entry.in === "header", + ); + if (!parameter?.description?.includes("1 hour")) continue; + operations.push({ + sourcePath: path, + path: route, + method: method.toUpperCase(), + operationId: operation.operationId, + idempotencyParameter: parameter, + }); + } + } +} +if ( + !errorCodes.has("idempotency_replay_unavailable") || + operations.length === 0 || + !conversionDeduplication +) + throw new Error("Source does not contain the response-replay contract"); +const contract = { + schemaVersion: 1, + repository: "polymorfa/polymorfa", + sourceCommit: revision, + sources, + errorCodes: [...errorCodes].sort(), + operations, + conversionDeduplication, + extraction: + "Idempotency error enums and unchanged one-hour header parameters from committed generated API documents; the baseline snapshots are unchanged", + published: false, +}; +writeFileSync( + new URL("../contracts/idempotency-replay.json", import.meta.url), + await format(JSON.stringify(contract), { parser: "json" }), +); +console.log( + `Wrote the replay supplement from ${operations.length} source operations`, +);