Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: correct the defects a pre-release review found in this cycle's work

Yudhi Armyndharisf4c4db3ca70d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 581ab945e..490c5f830 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **The Go and Java SDKs can now send the explicit `null` the session-config route needs** — that route takes three states per field (an absent key leaves the value unchanged, `null` clears it to the default, a value sets it), and neither SDK could emit the middle one: Go's `omitempty` omits a nil pointer and Gson drops nulls by default, so restoring `maxReconnectAttempts` to unlimited — the one thing no in-range number can express — was unreachable. Both now carry explicit `clear*` flags.
+- **Three SDK response types dropped fields the API sends** — the per-participant group result omitted `message`, the product-send response omitted `timestamp`, and Python's new 503 error class was not exported from the package root, so the documented import failed for exactly the class that was added.
+- **A running gateway now serves the same schema-valid OpenAPI document as the committed snapshot** — the validity pass was added to the export script only, so `/api/docs` kept serving a document that fails validation while `openapi.json` was clean; a test now holds both producers to the same passes in the same order.
+
### Added
- **The SDKs can now read and change a running session's config, and read the webhook diagnostics** — `GET`/`PATCH /sessions/{id}/config` (0.14.5's headline feature), the cross-session `GET /webhooks`, and `GET /webhooks/delivery-failures` were absent from all five SDKs while `sdk/README.md` claimed every user-facing resource was exposed; that claim is now scoped to the exclusion list the SDK design doc actually states.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index b7e83d124..bd43e5a8f 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -4053,14 +4053,14 @@ Create a webhook for the session.
**Request body** — `CreateWebhookDto`
-| Field | Type | Required | Constraints | Description |
-| ---------- | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| url | string | yes | `@IsUrl({ require_tld: false })` (allows hostnames without a dot, e.g. `http://localhost:3000`); also run through the SSRF guard, which can reject with `400`. Entity column max 2048 chars. | Webhook URL to receive events. |
-| events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. |
-| secret | string | no | `@IsString`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned. Used for `X-OpenWA-Signature`. Defaults to `null`. |
-| headers | Record<string,string> | no | `@IsHeaderMap()` — flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard). | Custom headers added to deliveries. **Write-only** — never returned. At delivery, `content-type` and `x-openwa-*` names are stripped. Defaults to `{}`. |
-| filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()` — `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `body`, `type`, `isGroup`, `fromMe`, `hasMedia`, `mentions`. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. ⚠️ A condition whose field is absent from an event's payload cannot match, so it suppresses that event entirely — `message.ack`/`message.failed` carry `{ id, messageId, status, ack }` and `message.reaction` carries `{ messageId, chatId, reaction, senderId }`, none of which has a sender or body, so a `sender` filter silently drops all three. Scope the subscription with `events[]` rather than relying on a filter to be inert. Set `LOG_LEVEL=debug` to see each suppression and the payload fields that were available. |
-| retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Delivery retry attempts on failure. Defaults to `3`. |
+| Field | Type | Required | Constraints | Description |
+| ---------- | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| url | string | yes | `@IsUrl({ require_tld: false })` (allows hostnames without a dot, e.g. `http://localhost:3000`); also run through the SSRF guard, which can reject with `400`. Entity column max 2048 chars. | Webhook URL to receive events. |
+| events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. |
+| secret | string | no | `@IsString`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned. Used for `X-OpenWA-Signature`. Defaults to `null`. |
+| headers | Record<string,string> | no | `@IsHeaderMap()` — flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard). | Custom headers added to deliveries. **Write-only** — never returned. At delivery, `content-type` and `x-openwa-*` names are stripped. Defaults to `{}`. |
+| filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()` — `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `body`, `type`, `isGroup`, `fromMe`, `hasMedia`, `mentions`. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. ⚠️ A condition whose field is DEFINED for the event family but absent from that event's payload cannot match, so it suppresses the event entirely (a field with no definition for the family is skipped instead, and does not suppress) — `message.ack`/`message.failed` carry `{ id, messageId, status, ack }` and `message.reaction` carries `{ messageId, chatId, reaction, senderId }`, none of which has a sender or body, so a `sender` filter silently drops all three. Scope the subscription with `events[]` rather than relying on a filter to be inert. Set `LOG_LEVEL=debug` to see each suppression and the payload fields that were available. |
+| retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Delivery retry attempts on failure. Defaults to `3`. |
```json
{
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index 85ee0c0a9..e2f3a78d7 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -44,7 +44,7 @@ All five SDKs expose the same fluent surface:
| `calls` | rejectCall |
| `health` | check, live, ready |
-> The SDKs cover the user-facing resources above and stop there. The administrative and operational surfaces are deliberately left out — `auth/api-keys`, `audit`, `settings`, `stats`, `infra`, `plugins` and the `integration` management routes are predominantly `ADMIN`-gated; `metrics` is a `@Public()` Prometheus scrape gated by `METRICS_TOKEN` rather than by role; `mcp` is a Streamable-HTTP transport mounted straight onto the Express adapter; and `ingress` is the `@Public()` receiver that integration providers post into. `docker` has no HTTP surface at all — it is an internal service module. Methods that require an `OPERATOR`-level key are annotated **OPERATOR** in the per-language tables below.
+> The SDKs cover the user-facing resources above and stop there. The administrative and operational surfaces are deliberately left out — `auth/api-keys`, `audit`, `settings`, `stats`, `automation`, `infra`, `plugins` and the `integration` management routes are predominantly `ADMIN`-gated; `metrics` is a `@Public()` Prometheus scrape gated by `METRICS_TOKEN` rather than by role; `mcp` is a Streamable-HTTP transport mounted straight onto the Express adapter; and `ingress` is the `@Public()` receiver that integration providers post into. `docker` has no HTTP surface at all — it is an internal service module. Methods that require an `OPERATOR`-level key are annotated **OPERATOR** in the per-language tables below.
## 18.2 TypeScript / JavaScript SDK
@@ -305,16 +305,17 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime
On a non-2xx response the SDK throws a typed `OpenWAApiError` subclass carrying `.status` (HTTP status), `.body` (parsed JSON error envelope, or raw text), and `.errorKind` (the NestJS `error` field). All error classes extend `OpenWAError` and are exported, so they are `instanceof`-checkable. A timeout throws `OpenWATimeoutError`, which extends `OpenWAError` directly (not `OpenWAApiError`).
-| Error class | HTTP status | Meaning |
-| --------------------------- | ----------- | --------------------------------------------------------------------------------------------- |
-| `OpenWAAuthError` | 401 | Missing or invalid API key. |
-| `OpenWAForbiddenError` | 403 | The key's role is insufficient (e.g. an OPERATOR-only route). |
-| `OpenWANotFoundError` | 404 | Resource not found. |
-| `OpenWAConflictError` | 409 | Conflict — typically the engine is not ready. |
-| `OpenWARateLimitError` | 429 | Rate limited. |
-| `OpenWANotImplementedError` | 501 | The active engine does not support this operation. |
-| `OpenWAApiError` | any other | Generic non-2xx (the base API error, e.g. `400`; also surfaced for unfollowed 3xx redirects). |
-| `OpenWATimeoutError` | — | The request exceeded the configured timeout. |
+| Error class | HTTP status | Meaning |
+| ------------------------------- | ----------- | --------------------------------------------------------------------------------------------- |
+| `OpenWAAuthError` | 401 | Missing or invalid API key. |
+| `OpenWAForbiddenError` | 403 | The key's role is insufficient (e.g. an OPERATOR-only route). |
+| `OpenWANotFoundError` | 404 | Resource not found. |
+| `OpenWAConflictError` | 409 | Conflict — typically the engine is not ready. |
+| `OpenWARateLimitError` | 429 | Rate limited. |
+| `OpenWANotImplementedError` | 501 | The active engine does not support this operation. |
+| `OpenWAServiceUnavailableError` | 503 | The engine did not confirm in time. The only retryable error here — 501 is permanent. |
+| `OpenWAApiError` | any other | Generic non-2xx (the base API error, e.g. `400`; also surfaced for unfollowed 3xx redirects). |
+| `OpenWATimeoutError` | — | The request exceeded the configured timeout. |
```typescript
import {
@@ -627,16 +628,17 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
Every error inherits from `OpenWAError`. A non-2xx response raises an `OpenWAApiError` (or a more specific subclass picked by status); a timeout raises `OpenWATimeoutError`. The API-error classes carry `.status` (HTTP code), `.body` (parsed JSON or raw text), and `.error_kind` (the NestJS `error` field).
-| Exception | Trigger |
-| --------------------------- | -------------------------------------------------------- |
-| `OpenWAAuthError` | HTTP `401` — missing or invalid API key |
-| `OpenWAForbiddenError` | HTTP `403` — insufficient role |
-| `OpenWANotFoundError` | HTTP `404` — resource not found |
-| `OpenWAConflictError` | HTTP `409` — typically engine-not-ready |
-| `OpenWARateLimitError` | HTTP `429` — too many requests |
-| `OpenWANotImplementedError` | HTTP `501` — active engine doesn't support the operation |
-| `OpenWAApiError` | any other non-2xx status (incl. unfollowed `3xx`) |
-| `OpenWATimeoutError` | request exceeded `timeout` (has a `.timeout` attribute) |
+| Exception | Trigger |
+| ------------------------------- | -------------------------------------------------------- |
+| `OpenWAAuthError` | HTTP `401` — missing or invalid API key |
+| `OpenWAForbiddenError` | HTTP `403` — insufficient role |
+| `OpenWANotFoundError` | HTTP `404` — resource not found |
+| `OpenWAConflictError` | HTTP `409` — typically engine-not-ready |
+| `OpenWARateLimitError` | HTTP `429` — too many requests |
+| `OpenWANotImplementedError` | HTTP `501` — active engine doesn't support the operation |
+| `OpenWAServiceUnavailableError` | HTTP `503` — engine did not confirm in time; retryable |
+| `OpenWAApiError` | any other non-2xx status (incl. unfollowed `3xx`) |
+| `OpenWATimeoutError` | request exceeded `timeout` (has a `.timeout` attribute) |
```python
from openwa import (
@@ -924,17 +926,18 @@ All payloads are associative arrays; all listed methods are synchronous and retu
All exceptions live in `OpenWA\Exceptions` and descend from `OpenWAException` (which extends PHP's `\Exception`). Any non-2xx response is raised as an `OpenWAApiException`; the static `classify()` factory picks the most specific subclass by status code. An `OpenWAApiException` carries the HTTP status (`getStatus(): int`), the parsed error body (`getBody(): mixed`), and the NestJS `error` kind when present (`getErrorKind(): ?string`).
-| Exception | Extends | Trigger |
-| ------------------------------- | -------------------- | -------------------------------------------------------------------------------------------- |
-| `OpenWAException` | `\Exception` | Base for all SDK errors (also thrown for missing `baseUrl`/`apiKey`). |
-| `OpenWAApiException` | `OpenWAException` | Any non-2xx (including unfollowed 3xx and other 4xx/5xx). |
-| `OpenWAAuthException` | `OpenWAApiException` | `401` — missing/invalid API key. |
-| `OpenWAForbiddenException` | `OpenWAApiException` | `403` — insufficient role (e.g. operator-only endpoint). |
-| `OpenWANotFoundException` | `OpenWAApiException` | `404` — resource not found. |
-| `OpenWAConflictException` | `OpenWAApiException` | `409` — conflict (e.g. engine not ready). |
-| `OpenWARateLimitException` | `OpenWAApiException` | `429` — rate limited. |
-| `OpenWANotImplementedException` | `OpenWAApiException` | `501` — active engine does not support the operation. |
-| `OpenWATimeoutException` | `OpenWAException` | Request exceeded the timeout (`getTimeout(): float`). Not an API error — has no status/body. |
+| Exception | Extends | Trigger |
+| ----------------------------------- | -------------------- | -------------------------------------------------------------------------------------------- |
+| `OpenWAException` | `\Exception` | Base for all SDK errors (also thrown for missing `baseUrl`/`apiKey`). |
+| `OpenWAApiException` | `OpenWAException` | Any non-2xx (including unfollowed 3xx and other 4xx/5xx). |
+| `OpenWAAuthException` | `OpenWAApiException` | `401` — missing/invalid API key. |
+| `OpenWAForbiddenException` | `OpenWAApiException` | `403` — insufficient role (e.g. operator-only endpoint). |
+| `OpenWANotFoundException` | `OpenWAApiException` | `404` — resource not found. |
+| `OpenWAConflictException` | `OpenWAApiException` | `409` — conflict (e.g. engine not ready). |
+| `OpenWARateLimitException` | `OpenWAApiException` | `429` — rate limited. |
+| `OpenWANotImplementedException` | `OpenWAApiException` | `501` — active engine does not support the operation. |
+| `OpenWAServiceUnavailableException` | `OpenWAApiException` | `503` — engine did not confirm in time; the only retryable one. |
+| `OpenWATimeoutException` | `OpenWAException` | Request exceeded the timeout (`getTimeout(): float`). Not an API error — has no status/body. |
```php
<?php
diff --git a/openapi.json b/openapi.json
index 6372e80c0..21f752eea 100644
--- a/openapi.json
+++ b/openapi.json
@@ -6595,7 +6595,9 @@
"required": true,
"in": "path",
"description": "Session ID the API key must be authorized for",
- "schema": {}
+ "schema": {
+ "type": "string"
+ }
}
],
"responses": {
@@ -6625,7 +6627,9 @@
"required": true,
"in": "path",
"description": "Session ID the API key must be authorized for",
- "schema": {}
+ "schema": {
+ "type": "string"
+ }
}
],
"requestBody": {
@@ -6674,7 +6678,9 @@
"required": true,
"in": "path",
"description": "Session ID the API key must be authorized for",
- "schema": {}
+ "schema": {
+ "type": "string"
+ }
}
],
"requestBody": {
@@ -7444,7 +7450,8 @@
"in": "path",
"description": "Provider-defined trailing path the plugin claims (may contain slashes).",
"schema": {
- "example": "events/message"
+ "example": "events/message",
+ "type": "string"
}
}
],
@@ -7501,7 +7508,8 @@
"in": "path",
"description": "Provider-defined trailing path the plugin claims (may contain slashes).",
"schema": {
- "example": "events/message"
+ "example": "events/message",
+ "type": "string"
}
}
],
@@ -7558,7 +7566,8 @@
"in": "path",
"description": "Provider-defined trailing path the plugin claims (may contain slashes).",
"schema": {
- "example": "events/message"
+ "example": "events/message",
+ "type": "string"
}
}
],
@@ -7615,7 +7624,8 @@
"in": "path",
"description": "Provider-defined trailing path the plugin claims (may contain slashes).",
"schema": {
- "example": "events/message"
+ "example": "events/message",
+ "type": "string"
}
}
],
@@ -7672,7 +7682,8 @@
"in": "path",
"description": "Provider-defined trailing path the plugin claims (may contain slashes).",
"schema": {
- "example": "events/message"
+ "example": "events/message",
+ "type": "string"
}
}
],
@@ -7729,7 +7740,8 @@
"in": "path",
"description": "Provider-defined trailing path the plugin claims (may contain slashes).",
"schema": {
- "example": "events/message"
+ "example": "events/message",
+ "type": "string"
}
}
],
@@ -7786,7 +7798,8 @@
"in": "path",
"description": "Provider-defined trailing path the plugin claims (may contain slashes).",
"schema": {
- "example": "events/message"
+ "example": "events/message",
+ "type": "string"
}
}
],
diff --git a/sdk/README.md b/sdk/README.md
index dd829ad6b..be0e999b6 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -42,11 +42,12 @@ All five SDKs expose the same fluent resource surface:
| `health` | check, live, ready |
> ⚠️ Endpoints requiring an `OPERATOR`-level API key are noted in the inline
-> docs. Deliberately **not** exposed: the operator-only modules (`docker`,
-> `metrics`, `infra`, `plugins`, `mcp`, `automation`, `integration`) and the
-> admin surfaces `docs/18-sdk-design.md` excludes (`auth`/api-keys, `audit`,
-> `settings`, `statistics`). Those two lists have to agree — this one was
-> shorter than the design doc's, and the gap read as an accidental omission.
+> docs. Deliberately **not** exposed, matching `docs/18-sdk-design.md` exactly:
+> `auth`/api-keys, `audit`, `settings`, `stats`, `automation`, `infra`,
+> `plugins`, the `integration` management routes, `metrics`, `mcp`, `ingress`
+> and `docker`. These two lists have to agree — they did not, in both
+> directions, and a list that disagrees with its own design doc reads as an
+> accidental omission rather than a decision.
>
> Everything else the gateway publishes is exposed. That sentence used to be an
> unqualified "all user-facing resources are", which was false for the session
diff --git a/sdk/go/README.md b/sdk/go/README.md
index 5a9e27b84..aa1f41cf1 100644
--- a/sdk/go/README.md
+++ b/sdk/go/README.md
@@ -94,7 +94,8 @@ case err != nil:
```
Sentinels: `ErrUnauthorized` (401), `ErrForbidden` (403), `ErrNotFound` (404),
-`ErrConflict` (409), `ErrRateLimited` (429), `ErrNotImplemented` (501). A timeout
+`ErrConflict` (409), `ErrRateLimited` (429), `ErrNotImplemented` (501),
+`ErrServiceUnavailable` (503 — the only retryable one). A timeout
surfaces as `*openwa.TimeoutError`.
## Retries
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 96a92858d..ebce73571 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -1353,3 +1353,28 @@ func TestConvertVideo(t *testing.T) {
t.Fatalf("body = %s, want the url only", got)
}
}
+
+// The config route needs three states per field: absent leaves it unchanged, explicit null clears it
+// to the default, a value sets it. A *int with omitempty could only ever express two — a nil pointer
+// was OMITTED, so restoring unlimited reconnect attempts was unreachable through this SDK.
+func TestUpdateSessionConfigEmitsThreeStates(t *testing.T) {
+ cases := []struct {
+ name string
+ req UpdateSessionConfigRequest
+ want string
+ }{
+ {"absent leaves everything unchanged", UpdateSessionConfigRequest{}, `{}`},
+ {"a value sets it", UpdateSessionConfigRequest{MaxReconnectAttempts: Ptr(5)}, `{"maxReconnectAttempts":5}`},
+ {"clear sends explicit null", UpdateSessionConfigRequest{ClearMaxReconnectAttempts: true}, `{"maxReconnectAttempts":null}`},
+ {"clear wins over a value", UpdateSessionConfigRequest{MaxReconnectAttempts: Ptr(5), ClearMaxReconnectAttempts: true}, `{"maxReconnectAttempts":null}`},
+ }
+ for _, c := range cases {
+ b, err := json.Marshal(c.req)
+ if err != nil {
+ t.Fatalf("%s: %v", c.name, err)
+ }
+ if string(b) != c.want {
+ t.Fatalf("%s: got %s, want %s", c.name, b, c.want)
+ }
+ }
+}
diff --git a/sdk/go/sessions.go b/sdk/go/sessions.go
index 744db0c15..17bdde4c3 100644
--- a/sdk/go/sessions.go
+++ b/sdk/go/sessions.go
@@ -13,7 +13,6 @@ func (s *SessionsService) List(ctx context.Context, query *ListSessionsQuery) ([
return out, err
}
-// Get returns a single session.
// GetConfig reads a session's effective configuration.
func (s *SessionsService) GetConfig(ctx context.Context, sessionID string) (*SessionConfig, error) {
var out SessionConfig
@@ -35,6 +34,7 @@ func (s *SessionsService) UpdateConfig(ctx context.Context, sessionID string, bo
return &out, nil
}
+// Get returns a single session.
func (s *SessionsService) Get(ctx context.Context, sessionID string) (*SessionResponse, error) {
var out SessionResponse
err := s.client.do(ctx, "GET", "/api/sessions/"+pathEscape(sessionID), nil, nil, &out)
diff --git a/sdk/go/types.go b/sdk/go/types.go
index 52fd1dba1..f63bae6bd 100644
--- a/sdk/go/types.go
+++ b/sdk/go/types.go
@@ -30,6 +30,8 @@ type ParticipantResult struct {
ID string `json:"id"`
Success bool `json:"success"`
Status int `json:"status,omitempty"`
+ // Message is the engine-reported reason, when it gave one.
+ Message string `json:"message,omitempty"`
}
// ParticipantsResult is the response of the group membership writes.
@@ -48,4 +50,6 @@ type ParticipantsResult struct {
// routes use.
type ProductMessageResponse struct {
ID string `json:"id"`
+ // Timestamp is unix SECONDS the engine stamped on the outgoing message.
+ Timestamp int64 `json:"timestamp"`
}
diff --git a/sdk/go/types_session.go b/sdk/go/types_session.go
index 295f1c642..793f1f38f 100644
--- a/sdk/go/types_session.go
+++ b/sdk/go/types_session.go
@@ -1,6 +1,9 @@
package openwa
-import "net/url"
+import (
+ "encoding/json"
+ "net/url"
+)
// ListSessionsQuery paginates GET /sessions. Both fields optional.
type ListSessionsQuery struct {
@@ -169,12 +172,49 @@ type SessionConfig struct {
}
// UpdateSessionConfigRequest is a partial update of a RUNNING session's config — no re-link, no QR
-// scan. Send a nil MaxReconnectAttempts through Ptr to restore unlimited retries, which no in-range
-// number can express.
+// scan.
+//
+// The route needs THREE states per field, not two: a key that is absent leaves the value unchanged, a
+// key sent as explicit null clears it back to the default, and a value sets it. A `*int` with
+// `omitempty` can only express the first and the third — a nil pointer is OMITTED, never emitted as
+// null — so the one operation this route exists for, restoring `maxReconnectAttempts` to unlimited
+// (which no in-range number can express), was unreachable. The Clear* flags carry the null case, and
+// MarshalJSON below is what actually emits it.
type UpdateSessionConfigRequest struct {
- AutoRejectCalls *bool `json:"autoRejectCalls,omitempty"`
- MaxReconnectAttempts *int `json:"maxReconnectAttempts,omitempty"`
- ReconnectBaseDelay *int `json:"reconnectBaseDelay,omitempty"`
+ AutoRejectCalls *bool `json:"-"`
+ MaxReconnectAttempts *int `json:"-"`
+ ReconnectBaseDelay *int `json:"-"`
+
+ // ClearMaxReconnectAttempts sends an explicit null, restoring unlimited reconnect attempts. It
+ // wins over MaxReconnectAttempts if both are set.
+ ClearMaxReconnectAttempts bool `json:"-"`
+ // ClearAutoRejectCalls sends an explicit null, restoring the server default.
+ ClearAutoRejectCalls bool `json:"-"`
+ // ClearReconnectBaseDelay sends an explicit null, restoring the server default.
+ ClearReconnectBaseDelay bool `json:"-"`
+}
+
+// MarshalJSON emits only the fields the caller actually addressed: a Clear* flag becomes an explicit
+// null, a non-nil pointer becomes its value, and a field that is neither is left out entirely so the
+// server leaves it unchanged.
+func (r UpdateSessionConfigRequest) MarshalJSON() ([]byte, error) {
+ out := map[string]any{}
+ if r.ClearAutoRejectCalls {
+ out["autoRejectCalls"] = nil
+ } else if r.AutoRejectCalls != nil {
+ out["autoRejectCalls"] = *r.AutoRejectCalls
+ }
+ if r.ClearMaxReconnectAttempts {
+ out["maxReconnectAttempts"] = nil
+ } else if r.MaxReconnectAttempts != nil {
+ out["maxReconnectAttempts"] = *r.MaxReconnectAttempts
+ }
+ if r.ClearReconnectBaseDelay {
+ out["reconnectBaseDelay"] = nil
+ } else if r.ReconnectBaseDelay != nil {
+ out["reconnectBaseDelay"] = *r.ReconnectBaseDelay
+ }
+ return json.Marshal(out)
}
// DeliveryFailureQuery filters the cross-session webhook list and the delivery-failure log. Nil
diff --git a/sdk/go/webhooks.go b/sdk/go/webhooks.go
index 11e7bce7a..ded51674e 100644
--- a/sdk/go/webhooks.go
+++ b/sdk/go/webhooks.go
@@ -10,7 +10,6 @@ func (s *WebhooksService) base(sessionID string) string {
return "/api/sessions/" + pathEscape(sessionID) + "/webhooks"
}
-// List returns webhooks for a session.
// ListAll returns webhooks across EVERY session the key can see, not one session's. Requires an
// OPERATOR-level key.
func (s *WebhooksService) ListAll(ctx context.Context, query *DeliveryFailureQuery) ([]WebhookResponse, error) {
@@ -30,6 +29,7 @@ func (s *WebhooksService) DeliveryFailures(ctx context.Context, query *DeliveryF
return out, err
}
+// List returns webhooks for a session.
func (s *WebhooksService) List(ctx context.Context, sessionID string) ([]WebhookResponse, error) {
var out []WebhookResponse
err := s.client.do(ctx, "GET", s.base(sessionID), nil, nil, &out)
diff --git a/sdk/java/README.md b/sdk/java/README.md
index 179fbcc33..b59cac45f 100644
--- a/sdk/java/README.md
+++ b/sdk/java/README.md
@@ -91,16 +91,17 @@ try {
}
```
-| Class | HTTP | Meaning |
-| --------------------------- | ---- | --------------------------------------- |
-| `OpenWAAuthError` | 401 | Missing or invalid API key |
-| `OpenWAForbiddenError` | 403 | API key role insufficient |
-| `OpenWANotFoundError` | 404 | Resource not found |
-| `OpenWAConflictError` | 409 | Engine not ready |
-| `OpenWARateLimitError` | 429 | Rate limited |
-| `OpenWANotImplementedError` | 501 | Active engine does not support the call |
-| `OpenWAApiError` | — | Any other non-2xx (carries `.status()`) |
-| `OpenWATimeoutError` | — | Request exceeded the configured timeout |
+| Class | HTTP | Meaning |
+| ------------------------------- | ---- | ------------------------------------------------------- |
+| `OpenWAAuthError` | 401 | Missing or invalid API key |
+| `OpenWAForbiddenError` | 403 | API key role insufficient |
+| `OpenWANotFoundError` | 404 | Resource not found |
+| `OpenWAConflictError` | 409 | Engine not ready |
+| `OpenWARateLimitError` | 429 | Rate limited |
+| `OpenWANotImplementedError` | 501 | Active engine does not support the call |
+| `OpenWAServiceUnavailableError` | 503 | Engine did not confirm in time — the only retryable one |
+| `OpenWAApiError` | — | Any other non-2xx (carries `.status()`) |
+| `OpenWATimeoutError` | — | Request exceeded the configured timeout |
All extend `OpenWAError` (a `RuntimeException`).
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
index 1cc3ac9b8..21f42a55c 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
@@ -1,6 +1,7 @@
package com.rmyndharis.openwa;
import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.rmyndharis.openwa.errors.OpenWAApiError;
import com.rmyndharis.openwa.errors.OpenWAError;
@@ -8,6 +9,8 @@ import com.rmyndharis.openwa.http.BinaryResponse;
import com.rmyndharis.openwa.http.DefaultHttpTransport;
import com.rmyndharis.openwa.http.Http;
import com.rmyndharis.openwa.http.HttpMethod;
+import com.rmyndharis.openwa.model.UpdateSessionConfigRequest;
+import com.rmyndharis.openwa.model.UpdateSessionConfigRequestSerializer;
import com.rmyndharis.openwa.http.HttpRequestData;
import com.rmyndharis.openwa.http.HttpResponseData;
import com.rmyndharis.openwa.http.HttpTransport;
@@ -47,6 +50,17 @@ import java.util.Map;
*/
public final class OpenWAClient {
private final Gson gson = new Gson();
+
+ // Used for ONE body type. Emitting an explicit null needs two things that pull in opposite
+ // directions: a serializer that decides WHICH keys appear, and serializeNulls() so the ones it
+ // chose survive the writer — Gson drops JsonNull members otherwise, even from a JsonObject the
+ // serializer already built. Applying serializeNulls() to the shared instance instead would turn
+ // every unset field of every other body into an explicit null, which this very route reads as
+ // "reset to default": a far worse bug than the one it fixes.
+ private final Gson nullEmittingGson = new GsonBuilder()
+ .serializeNulls()
+ .registerTypeAdapter(UpdateSessionConfigRequest.class, new UpdateSessionConfigRequestSerializer())
+ .create();
private final ClientConfig config;
private final HttpTransport transport;
@@ -166,10 +180,15 @@ public final class OpenWAClient {
return body == null ? "" : new String(body, StandardCharsets.UTF_8);
}
+ /** The session-config body is the only one that must be able to emit an explicit null. */
+ private Gson bodySerializer(Object body) {
+ return body instanceof UpdateSessionConfigRequest ? nullEmittingGson : gson;
+ }
+
private HttpResponseData execute(HttpMethod method, String path, Object query, Object body) {
String url = Http.buildUrl(config.baseUrl, path, query, gson);
Map<String, String> headers = Http.mergeHeaders(config.defaultHeaders, null, config.apiKey);
- String bodyJson = body != null ? gson.toJson(body) : null;
+ String bodyJson = body != null ? bodySerializer(body).toJson(body) : null;
HttpRequestData reqData = new HttpRequestData(method, url, headers, bodyJson, config.timeout);
HttpResponseData res;
try {
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantResult.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantResult.java
index a08d15b4b..39a248d81 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantResult.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantResult.java
@@ -11,4 +11,4 @@ package com.rmyndharis.openwa.model;
* @param success whether the engine confirmed the change for this participant
* @param status the engine's own status code, when it gave one
*/
-public record ParticipantResult(String id, boolean success, Integer status) {}
+public record ParticipantResult(String id, boolean success, Integer status, String message) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ProductMessageResponse.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ProductMessageResponse.java
index 2d9dcd6d1..7ca59ddc1 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ProductMessageResponse.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ProductMessageResponse.java
@@ -8,4 +8,4 @@ package com.rmyndharis.openwa.model;
*
* @param id id of the sent product message
*/
-public record ProductMessageResponse(String id) {}
+public record ProductMessageResponse(String id, long timestamp) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionConfigRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionConfigRequest.java
index a54da8bcb..4e56f2f31 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionConfigRequest.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionConfigRequest.java
@@ -1,15 +1,81 @@
package com.rmyndharis.openwa.model;
/**
- * Partial update of a RUNNING session's configuration — no re-link and no QR scan. All three fields
- * were fixed at creation before this route existed.
+ * Partial update of a RUNNING session's configuration — no re-link and no QR scan.
*
- * <p>Send a null {@code maxReconnectAttempts} to restore unlimited retries, which no in-range number
- * can express.
+ * <p>The route needs THREE states per field, not two: an absent key leaves the value unchanged, a key
+ * sent as explicit null clears it back to the default, and a value sets it. A record of nullable
+ * boxes can only express two, because Gson omits nulls by default — so the one operation this route
+ * exists for, restoring {@code maxReconnectAttempts} to unlimited (which no in-range number can
+ * express), was unreachable. The {@code clear*} flags carry the null case and
+ * {@code UpdateSessionConfigRequestSerializer} is what emits it.
*
- * @param autoRejectCalls auto-reject incoming calls
- * @param maxReconnectAttempts cap on consecutive reconnect attempts; null restores unlimited
- * @param reconnectBaseDelay base delay of the reconnect backoff, in milliseconds
+ * <p>Build one with {@link #builder()}; a {@code clear} wins over a value for the same field.
*/
public record UpdateSessionConfigRequest(
- Boolean autoRejectCalls, Integer maxReconnectAttempts, Integer reconnectBaseDelay) {}
+ Boolean autoRejectCalls,
+ Integer maxReconnectAttempts,
+ Integer reconnectBaseDelay,
+ boolean clearAutoRejectCalls,
+ boolean clearMaxReconnectAttempts,
+ boolean clearReconnectBaseDelay) {
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder {
+ private Boolean autoRejectCalls;
+ private Integer maxReconnectAttempts;
+ private Integer reconnectBaseDelay;
+ private boolean clearAutoRejectCalls;
+ private boolean clearMaxReconnectAttempts;
+ private boolean clearReconnectBaseDelay;
+
+ /** Auto-reject incoming calls. */
+ public Builder autoRejectCalls(Boolean v) {
+ this.autoRejectCalls = v;
+ return this;
+ }
+
+ /** Cap consecutive reconnect attempts (0 disables reconnect entirely). */
+ public Builder maxReconnectAttempts(Integer v) {
+ this.maxReconnectAttempts = v;
+ return this;
+ }
+
+ /** Base delay of the reconnect backoff, in milliseconds. */
+ public Builder reconnectBaseDelay(Integer v) {
+ this.reconnectBaseDelay = v;
+ return this;
+ }
+
+ /** Send an explicit null for autoRejectCalls, restoring the server default. */
+ public Builder clearAutoRejectCalls() {
+ this.clearAutoRejectCalls = true;
+ return this;
+ }
+
+ /** Send an explicit null, restoring UNLIMITED reconnect attempts. */
+ public Builder clearMaxReconnectAttempts() {
+ this.clearMaxReconnectAttempts = true;
+ return this;
+ }
+
+ /** Send an explicit null for reconnectBaseDelay, restoring the server default. */
+ public Builder clearReconnectBaseDelay() {
+ this.clearReconnectBaseDelay = true;
+ return this;
+ }
+
+ public UpdateSessionConfigRequest build() {
+ return new UpdateSessionConfigRequest(
+ autoRejectCalls,
+ maxReconnectAttempts,
+ reconnectBaseDelay,
+ clearAutoRejectCalls,
+ clearMaxReconnectAttempts,
+ clearReconnectBaseDelay);
+ }
+ }
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionConfigRequestSerializer.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionConfigRequestSerializer.java
new file mode 100644
index 000000000..e8d160928
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionConfigRequestSerializer.java
@@ -0,0 +1,39 @@
+package com.rmyndharis.openwa.model;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import java.lang.reflect.Type;
+
+/**
+ * Emits only the fields the caller actually addressed: a {@code clear*} flag becomes an explicit
+ * null, a non-null box becomes its value, and a field that is neither is left out so the server
+ * leaves it unchanged.
+ *
+ * <p>Registered on the client's single Gson for this type only — a global {@code serializeNulls()}
+ * would turn every unset field of every other request body into an explicit null, which for this
+ * route means "reset to default" and would be far worse than the gap it fixes.
+ */
+public final class UpdateSessionConfigRequestSerializer implements JsonSerializer<UpdateSessionConfigRequest> {
+ @Override
+ public JsonElement serialize(UpdateSessionConfigRequest src, Type type, JsonSerializationContext ctx) {
+ JsonObject out = new JsonObject();
+ if (src.clearAutoRejectCalls()) {
+ out.add("autoRejectCalls", null);
+ } else if (src.autoRejectCalls() != null) {
+ out.addProperty("autoRejectCalls", src.autoRejectCalls());
+ }
+ if (src.clearMaxReconnectAttempts()) {
+ out.add("maxReconnectAttempts", null);
+ } else if (src.maxReconnectAttempts() != null) {
+ out.addProperty("maxReconnectAttempts", src.maxReconnectAttempts());
+ }
+ if (src.clearReconnectBaseDelay()) {
+ out.add("reconnectBaseDelay", null);
+ } else if (src.reconnectBaseDelay() != null) {
+ out.addProperty("reconnectBaseDelay", src.reconnectBaseDelay());
+ }
+ return out;
+ }
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java
index aeb5c9feb..f0500eb70 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java
@@ -51,7 +51,6 @@ public final class GroupsResource {
GroupInfo.class);
}
- /** Create a new group. */
/**
* Create a group. Answers the group SUMMARY, not the detail shape {@code get} returns — there is
* no participant list, description, owner or creation time on a create response.
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/model/UpdateSessionConfigRequestTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/model/UpdateSessionConfigRequestTest.java
new file mode 100644
index 000000000..5d9723329
--- /dev/null
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/model/UpdateSessionConfigRequestTest.java
@@ -0,0 +1,65 @@
+package com.rmyndharis.openwa.model;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.junit.jupiter.api.Test;
+
+/**
+ * The config route needs three states per field: an absent key leaves the value unchanged, an
+ * explicit null clears it to the default, a value sets it. Gson omits nulls by default, so a record
+ * of nullable boxes could only ever express two — and restoring unlimited reconnect attempts, the
+ * one thing this route exists for, was unreachable.
+ */
+class UpdateSessionConfigRequestTest {
+ // Mirrors the client's nullEmittingGson exactly: without serializeNulls the writer drops the
+ // very null the serializer was written to emit.
+ private final Gson gson = new GsonBuilder()
+ .serializeNulls()
+ .registerTypeAdapter(UpdateSessionConfigRequest.class, new UpdateSessionConfigRequestSerializer())
+ .create();
+
+ @Test
+ void absentFieldsAreOmitted() {
+ assertEquals("{}", gson.toJson(UpdateSessionConfigRequest.builder().build()));
+ }
+
+ @Test
+ void aValueIsSent() {
+ assertEquals(
+ "{\"maxReconnectAttempts\":5}",
+ gson.toJson(UpdateSessionConfigRequest.builder()
+ .maxReconnectAttempts(5)
+ .build()));
+ }
+
+ @Test
+ void clearSendsAnExplicitNull() {
+ assertEquals(
+ "{\"maxReconnectAttempts\":null}",
+ gson.toJson(UpdateSessionConfigRequest.builder()
+ .clearMaxReconnectAttempts()
+ .build()));
+ }
+
+ @Test
+ void clearWinsOverAValueForTheSameField() {
+ assertEquals(
+ "{\"maxReconnectAttempts\":null}",
+ gson.toJson(UpdateSessionConfigRequest.builder()
+ .maxReconnectAttempts(5)
+ .clearMaxReconnectAttempts()
+ .build()));
+ }
+
+ @Test
+ void oneClearedFieldDoesNotDragTheOthersIn() {
+ assertEquals(
+ "{\"autoRejectCalls\":true,\"maxReconnectAttempts\":null}",
+ gson.toJson(UpdateSessionConfigRequest.builder()
+ .autoRejectCalls(true)
+ .clearMaxReconnectAttempts()
+ .build()));
+ }
+}
diff --git a/sdk/javascript/README.md b/sdk/javascript/README.md
index 1e3cd5698..c09fcd2a0 100644
--- a/sdk/javascript/README.md
+++ b/sdk/javascript/README.md
@@ -41,7 +41,8 @@ CommonJS consumers use `require('@rmyndharis/openwa')` identically.
Non-2xx responses throw a typed `OpenWAApiError` subclass
(`OpenWAAuthError`, `OpenWAForbiddenError`, `OpenWANotFoundError`,
-`OpenWAConflictError`, `OpenWARateLimitError`, `OpenWANotImplementedError`),
+`OpenWAConflictError`, `OpenWARateLimitError`, `OpenWANotImplementedError`,
+`OpenWAServiceUnavailableError` — 503, the only retryable one),
each carrying `.status` and the parsed `.body`. Timeouts throw
`OpenWATimeoutError`. The SDK does **not** retry — wrap calls with your own
backoff if needed.
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index d4d27e65d..dca4bde0a 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -21,14 +21,7 @@ export type ChatKind = 'individual' | 'group' | 'channel' | 'status' | 'broadcas
/** Session lifecycle status. */
export type SessionStatus =
- | 'created'
- | 'initializing'
- | 'qr_ready'
- | 'authenticating'
- | 'ready'
- | 'disconnected'
- | 'action_required'
- | 'failed';
+ 'created' | 'initializing' | 'qr_ready' | 'authenticating' | 'ready' | 'disconnected' | 'action_required' | 'failed';
/** Minimal success envelope returned by some state-changing endpoints. */
export interface SuccessResult {
@@ -48,6 +41,8 @@ export interface ParticipantResult {
success: boolean;
/** The engine's own status code, when it gave one. */
status?: number;
+ /** Engine-reported reason, when it gave one. */
+ message?: string;
}
/**
@@ -162,8 +157,10 @@ export interface GroupJoinInfo {
}
/**
- * A session's effective runtime configuration. `null` on the two reconnect fields means "unlimited" /
- * "engine default" respectively — not "unset".
+ * A session's effective runtime configuration.
+ *
+ * Only `maxReconnectAttempts` is nullable, and `null` there means UNLIMITED — not "unset". The
+ * server always reports a concrete `reconnectBaseDelay` and `autoRejectCalls`.
*/
export interface SessionConfig {
autoRejectCalls: boolean;
@@ -1046,6 +1043,8 @@ export interface PaginatedProducts {
*/
export interface ProductMessageResponse {
id: string;
+ /** Unix SECONDS the engine stamped on the outgoing message. */
+ timestamp: number;
}
export interface SendProductRequest {
diff --git a/sdk/php/README.md b/sdk/php/README.md
index 5fefc4636..9d9b2632b 100644
--- a/sdk/php/README.md
+++ b/sdk/php/README.md
@@ -53,7 +53,8 @@ $client = new Client([
A non-2xx response throws a typed `OpenWA\Exceptions\OpenWAApiException` subclass —
`OpenWAAuthException` (401), `OpenWAForbiddenException` (403), `OpenWANotFoundException` (404),
`OpenWAConflictException` (409), `OpenWARateLimitException` (429),
-`OpenWANotImplementedException` (501) — each exposing `getStatus()` and the parsed `getBody()`.
+`OpenWANotImplementedException` (501), `OpenWAServiceUnavailableException` (503 — the only
+retryable one) — each exposing `getStatus()` and the parsed `getBody()`.
A timeout throws `OpenWATimeoutException`.
```php
diff --git a/sdk/python/README.md b/sdk/python/README.md
index c3d32c29d..f4c8ab383 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -67,7 +67,8 @@ for hit in res["hits"]:
A non-2xx response raises a typed `OpenWAApiError` subclass — `OpenWAAuthError` (401),
`OpenWAForbiddenError` (403), `OpenWANotFoundError` (404), `OpenWAConflictError` (409),
-`OpenWARateLimitError` (429), `OpenWANotImplementedError` (501) — each carrying `.status`
+`OpenWARateLimitError` (429), `OpenWANotImplementedError` (501),
+`OpenWAServiceUnavailableError` (503 — the only retryable one) — each carrying `.status`
and the parsed `.body`. A timeout raises `OpenWATimeoutError`.
```python
diff --git a/sdk/python/openwa/__init__.py b/sdk/python/openwa/__init__.py
index 511c60afa..90141dd7a 100644
--- a/sdk/python/openwa/__init__.py
+++ b/sdk/python/openwa/__init__.py
@@ -31,6 +31,7 @@ from .errors import (
OpenWAForbiddenError,
OpenWANotFoundError,
OpenWANotImplementedError,
+ OpenWAServiceUnavailableError,
OpenWARateLimitError,
OpenWATimeoutError,
)
@@ -45,5 +46,6 @@ __all__ = [
"OpenWAConflictError",
"OpenWARateLimitError",
"OpenWANotImplementedError",
+ "OpenWAServiceUnavailableError",
"OpenWATimeoutError",
]
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index ac72551c9..5d3b4ed52 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -53,6 +53,7 @@ class ParticipantResult(TypedDict, total=False):
id: str
success: bool
status: int
+ message: str
class ParticipantsResult(SuccessResult):
@@ -1040,8 +1041,6 @@ class PaginatedProducts(TypedDict):
pagination: ProductPagination
-# chatId + productId required; body optional. Modeled total=False for 3.9 compat
-# (callers pass plain dicts); the backend validates the required fields.
class ProductMessageResponse(TypedDict):
"""Response of ``send-product``.
@@ -1050,8 +1049,11 @@ class ProductMessageResponse(TypedDict):
"""
id: str
+ timestamp: int
+# chatId + productId required; body optional. Modeled total=False for 3.9 compat
+# (callers pass plain dicts); the backend validates the required fields.
class SendProductRequest(TypedDict, total=False):
chatId: Jid
productId: str
diff --git a/src/config/openapi-contract.spec.ts b/src/config/openapi-contract.spec.ts
index 19a1db487..c98cc5db7 100644
--- a/src/config/openapi-contract.spec.ts
+++ b/src/config/openapi-contract.spec.ts
@@ -49,6 +49,30 @@ describe('openapi.json structural invariants', () => {
expect(undeclared).toEqual([]);
});
+ // OpenAPI 3.0 requires a parameter to carry a schema; without one a generator has no type for the
+ // argument. Every path parameter in the document had one except the four added alongside this spec,
+ // which is exactly the blind spot a structural check exists to close.
+ it('every path parameter declares a schema type', () => {
+ const doc = snapshot();
+ const untyped: string[] = [];
+
+ for (const [route, item] of Object.entries(doc.paths)) {
+ const declared = [...((item.parameters ?? []) as { in?: string; name?: string; schema?: { type?: string } }[])];
+ for (const [method, operation] of Object.entries(item)) {
+ if (!OPERATION_KEYS.has(method)) continue;
+ declared.push(
+ ...((operation as { parameters?: { in?: string; name?: string; schema?: { type?: string } }[] }).parameters ??
+ []),
+ );
+ }
+ for (const p of declared) {
+ if (p.in === 'path' && !p.schema?.type) untyped.push(`${route} -> ${p.name}`);
+ }
+ }
+
+ expect(untyped).toEqual([]);
+ });
+
it('every operation declares at least one response', () => {
const doc = snapshot();
const silent = Object.entries(doc.paths).flatMap(([route, item]) =>
@@ -61,3 +85,32 @@ describe('openapi.json structural invariants', () => {
expect(silent).toEqual([]);
});
});
+
+// The document is produced in TWO places: scripts/export-openapi.ts for the committed snapshot, and
+// src/main.ts for the live /api/docs. The schema-validity pass was added to the export only, so a
+// running gateway kept serving a document that fails validation while the artifact was clean. A
+// structural check, because neither producer is reachable from a unit test.
+describe('both OpenAPI producers apply the same passes', () => {
+ const PASSES = ['dropUnexpressibleOperations', 'exemptPublicOperations'];
+ const producers = ['src/main.ts', 'scripts/export-openapi.ts'];
+
+ it.each(PASSES)('%s runs in every producer', pass => {
+ const missing = producers.filter(
+ file => !fs.readFileSync(path.join(__dirname, '..', '..', file), 'utf8').includes(`${pass}(`),
+ );
+ expect(missing).toEqual([]);
+ });
+
+ it('applies them in the same order in both', () => {
+ for (const file of producers) {
+ const text = fs.readFileSync(path.join(__dirname, '..', '..', file), 'utf8');
+ const order = PASSES.map(p =>
+ text.indexOf(`${p}(document`) >= 0 ? text.indexOf(`${p}(document`) : text.indexOf(`${p}(doc`),
+ );
+ // drop must precede exempt: exempting an operation about to be deleted is wasted work, and the
+ // reverse order would leave a security exemption attached to nothing.
+ expect(order[0]).toBeGreaterThan(-1);
+ expect(order[1]).toBeGreaterThan(order[0]);
+ }
+ });
+});
diff --git a/src/main.ts b/src/main.ts
index 17ab29a78..f858af09c 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -10,7 +10,7 @@ import helmet from 'helmet';
import { AppModule, DASHBOARD_DIST, dashboardServingEnabled, dashboardBuildPresent } from './app.module';
import { ShutdownService } from './common/services/shutdown.service';
import { LoggerService, LogLevel, createLogger } from './common/services/logger.service';
-import { createSwaggerConfig, exemptPublicOperations } from './config/swagger.config';
+import { createSwaggerConfig, dropUnexpressibleOperations, exemptPublicOperations } from './config/swagger.config';
import { registerUncaughtExceptionMonitor, registerUnhandledRejectionHandler } from './config/process-error-monitor';
import { runBootstrapOrExit } from './config/bootstrap-fatal';
import { resolveStorageRoot } from './config/storage-root';
@@ -323,6 +323,10 @@ async function bootstrap() {
if (swaggerEnabled) {
const config = createSwaggerConfig();
const document = SwaggerModule.createDocument(app, config);
+ // Same two passes, in the same order, as scripts/export-openapi.ts. The document is produced in
+ // TWO places — here for the live /api/docs and there for the committed snapshot — and fixing only
+ // the snapshot leaves a running gateway serving a document that fails schema validation.
+ dropUnexpressibleOperations(document);
exemptPublicOperations(document);
SwaggerModule.setup('api/docs', app, document);
}
diff --git a/src/modules/integration/ingress.controller.ts b/src/modules/integration/ingress.controller.ts
index 2612a088e..331aeed70 100644
--- a/src/modules/integration/ingress.controller.ts
+++ b/src/modules/integration/ingress.controller.ts
@@ -33,6 +33,7 @@ export class IngressController {
// `{path}` placeholder nothing declares. Awkward to express, not impossible.
@ApiParam({
name: 'path',
+ type: String,
description: 'Provider-defined trailing path the plugin claims (may contain slashes).',
example: 'events/message',
})
diff --git a/src/modules/media/media.controller.ts b/src/modules/media/media.controller.ts
index d525ce4df..78797df82 100644
--- a/src/modules/media/media.controller.ts
+++ b/src/modules/media/media.controller.ts
@@ -18,7 +18,7 @@ import { ApiKeyRole } from '../auth/entities/api-key.entity';
// Declared on the class because no handler binds the parameter — conversion needs no session id, only
// the guard does (see above). Without this the published paths carry a `{sessionId}` template with no
// parameter to fill it, which OpenAPI 3.0 does not allow and a generated client cannot satisfy.
-@ApiParam({ name: 'sessionId', description: 'Session ID the API key must be authorized for' })
+@ApiParam({ name: 'sessionId', type: String, description: 'Session ID the API key must be authorized for' })
@Controller('sessions/:sessionId/media')
export class MediaController {
constructor(private readonly mediaConversion: MediaConversionService) {}