From 1d17e74bc1d2bf5339c0dabf2338600a2745ff92 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Thu, 19 Nov 2026 11:08:19 +0100 Subject: [PATCH 1/3] Discover realtime connection settings from the API client_id, ws_url and app_key are now optional for client.realtime(). Each is taken from the argument, then the environment variable, then GET /websocket, which the SDK calls once at connect time (never in the constructor) only when something is still missing. With all three set, no extra request is made. - add client.websocket_config() (sync and async) returning the new WebSocketConfig / WebSocketConnection models - use the returned channel and auth endpoint when discovery ran - reject unusable discovery responses with RealtimeError - drop the hard-coded production WebSocket URL and app key defaults - update README, API reference, .env.example and the realtime example Co-Authored-By: Claude Opus 5.5 --- .env.example | 7 +- README.md | 26 ++- docs/api-reference.md | 57 +++++- examples/realtime_status.py | 5 +- src/deapi_sdk/__init__.py | 44 +++- src/deapi_sdk/_constants.py | 2 + src/deapi_sdk/_realtime/_discovery.py | 43 ++++ src/deapi_sdk/_realtime/_engine.py | 17 +- src/deapi_sdk/_realtime/_protocol.py | 11 +- src/deapi_sdk/_realtime/_session.py | 90 ++++++-- src/deapi_sdk/types/__init__.py | 3 + src/deapi_sdk/types/websocket.py | 36 ++++ tests/fake_pusher.py | 4 + tests/test_realtime.py | 284 +++++++++++++++++++++++++- 14 files changed, 563 insertions(+), 66 deletions(-) create mode 100644 src/deapi_sdk/_realtime/_discovery.py create mode 100644 src/deapi_sdk/types/websocket.py diff --git a/.env.example b/.env.example index 4566305..41c9d30 100644 --- a/.env.example +++ b/.env.example @@ -14,8 +14,9 @@ DEAPI_API_KEY=sk-dp-- # DEAPI_FILL_MODEL_DEFAULTS=1 # Real-time status over WebSocket (pip install "deapi-sdk[ws] @ git+https://github.com/deapi-ai/deapi-python-sdk.git") +# All optional: anything unset is fetched from the API (GET /websocket) when the connection opens. # The "Client ID" shown in your dashboard; pass client_id= explicitly when serving many users # DEAPI_CLIENT_ID=your-client-id -# Only needed for non-production environments -# DEAPI_WS_URL=wss://soketi.deapi.ai -# DEAPI_WS_APP_KEY=depin-api-prod-key +# Overrides, e.g. for a local WebSocket server +# DEAPI_WS_URL=wss://ws.example.test +# DEAPI_WS_APP_KEY=your-app-key diff --git a/README.md b/README.md index f341317..b43b6c0 100644 --- a/README.md +++ b/README.md @@ -102,9 +102,9 @@ client = DeapiClient( | `base_url` | `DEAPI_BASE_URL` | `https://api.deapi.ai` | | `api_version` | `DEAPI_API_VERSION` | `v2` | | `fill_model_defaults` | `DEAPI_FILL_MODEL_DEFAULTS` (`0` disables) | on | -| `client_id` (`client.realtime()`) | `DEAPI_CLIENT_ID` | none | -| `ws_url` (`client.realtime()`) | `DEAPI_WS_URL` | `wss://soketi.deapi.ai` | -| `app_key` (`client.realtime()`) | `DEAPI_WS_APP_KEY` | public app key | +| `client_id` (`client.realtime()`) | `DEAPI_CLIENT_ID` | discovered from the API | +| `ws_url` (`client.realtime()`) | `DEAPI_WS_URL` | discovered from the API | +| `app_key` (`client.realtime()`) | `DEAPI_WS_APP_KEY` | discovered from the API | | `timeout` | — | `30.0` | | `max_retries` | — | `3` | | `max_retry_after` | — | `60.0` (cap on a 429 `Retry-After` sleep, in seconds) | @@ -386,7 +386,7 @@ Instead of polling, follow your jobs live over one WebSocket connection. Install from deapi_sdk import DeapiClient with DeapiClient(api_key="sk-dp--") as client: - with client.realtime(client_id="your-client-id") as rt: + with client.realtime() as rt: # no other settings needed: the SDK asks the API where to connect job = client.images.generate(prompt="a cat in space", model="Flux1schnell", width=1024, height=1024) result = rt.wait(job, on_progress=lambda e: print(e.status, e.progress)) # same JobResult as job.wait() @@ -400,16 +400,20 @@ Async works the same way: ```python async with AsyncDeapiClient() as client: - async with client.realtime(client_id="your-client-id") as rt: + async with client.realtime() as rt: job = await client.images.generate(prompt="a cat in space", model="Flux1schnell", width=1024, height=1024) result = await rt.wait(job, on_progress=callback) # plain function or async function async for event in rt.events(): ... ``` -- **`client_id`** is the "Client ID" shown in your deAPI dashboard. It falls back to `DEAPI_CLIENT_ID` - only when you do not pass it; an explicit argument always wins. Servers handling many users should - pass it explicitly per user. A `client_id` that does not belong to the API key raises `RealtimeError`. +- **All settings are optional.** `client_id`, `ws_url` and `app_key` are each taken from the argument, + else from `DEAPI_CLIENT_ID` / `DEAPI_WS_URL` / `DEAPI_WS_APP_KEY`, else from the account's + `GET /websocket` response (`client.websocket_config()`). The SDK calls that endpoint once, on + `connect()` / `with` (never in the constructor), and only when something is still missing; with all three + set there is no extra request. `rt.client_id` is `None` until then if you did not pass one. + `client_id` is the "Client ID" shown in your deAPI dashboard; servers handling many users should pass it + explicitly per user. A `client_id` that does not belong to the API key raises `RealtimeError`. - **`rt.wait(job_or_request_id)`** accepts a `Job` or a request id. WebSocket events drive progress and completion; on `done` the SDK fetches the final `JobResult` over HTTP (fresh signed `result_url`, all fields). @@ -423,9 +427,9 @@ async with AsyncDeapiClient() as client: reconnecting. `rt.connected` tells you whether the socket is up. - `JobStatusEvent` has `request_id`, `status` (`processing`, repeated while `progress` grows, then `done`), `progress` (0-100), `preview` (base64 data URI, image jobs) and `result_url` (only on `done`). -- `ws_url` / `app_key` (env `DEAPI_WS_URL` / `DEAPI_WS_APP_KEY`) are only needed for non-production - environments. Without the extra, connecting raises an `ImportError` telling you to install - `deapi-sdk[ws]`. +- Without the extra, connecting raises an `ImportError` telling you to install `deapi-sdk[ws]`. A failed + discovery call raises the usual API exception (for example `AuthenticationError`); an unusable response + raises `RealtimeError`. See [`examples/realtime_status.py`](examples/realtime_status.py). diff --git a/docs/api-reference.md b/docs/api-reference.md index ac5e659..34e3269 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -58,6 +58,7 @@ account and key-management endpoints. | Method | Returns | Description | |--------|---------|-------------| | `client.balance()` | `Balance` | Account balance (ADMIN key) | +| `client.websocket_config()` | `WebSocketConfig` | Realtime WebSocket parameters of the account (`GET /websocket`, any key) | | `client.close()` | `None` | Close the HTTP connection | **Resources:** `images`, `audio`, `video`, `transcription`, `embeddings`, `ocr`, `prompts`, `models`, @@ -569,17 +570,38 @@ Live job status over one WebSocket connection. Needs the optional extra: ```python rt = client.realtime( - client_id: str | int | None = None, # "Client ID" from the dashboard; falls back to DEAPI_CLIENT_ID + client_id: str | int | None = None, # "Client ID" from the dashboard; falls back to DEAPI_CLIENT_ID, then discovery *, - ws_url: str | None = None, # falls back to DEAPI_WS_URL (default "wss://soketi.deapi.ai") - app_key: str | None = None, # falls back to DEAPI_WS_APP_KEY (default: the public app key) + ws_url: str | None = None, # falls back to DEAPI_WS_URL, then discovery + app_key: str | None = None, # falls back to DEAPI_WS_APP_KEY, then discovery connect_timeout: float = 30.0, ) -> Realtime # AsyncDeapiClient: AsyncRealtime ``` -`client_id` is an opaque string. The environment variable is used only when the argument is not -passed; an explicit argument always wins. Servers handling many users should pass it per user. -`ws_url` and `app_key` are only needed for non-production environments. +Every parameter is optional. Per field the precedence is: explicit argument, then the environment +variable, then the value from `GET /websocket` (`client.websocket_config()`, below). +When `client_id`, `ws_url` and `app_key` are all set (arguments or environment), no extra request is +made. Otherwise the SDK fetches the parameters **once at connect time** (`connect()` / `with` / +`await connect()` / `async with`; constructors do no I/O), fills only the missing fields and keeps the +result for reconnects. When discovery ran, the returned `auth_endpoint` is used to authorize the channel. + +`client_id` is an opaque string; servers handling many users should pass it per user. Until connect, +`rt.client_id` is `None` if it was neither passed nor set in the environment. A failed discovery call +raises the normal API exception (for example `AuthenticationError`); a malformed response, an unsupported +`connection.protocol` or an unexpected `event` raises `RealtimeError`. + +### `client.websocket_config()` + +```python +cfg = client.websocket_config() # AsyncDeapiClient: await client.websocket_config() +cfg.client_id # UUID string of the account's channel owner +cfg.channel # "private-client." +cfg.event # "request.status.updated" +cfg.auth_endpoint # URL that authorizes the private channel +cfg.connection.url # "wss://host" (port only when non-default) +``` + +`GET /websocket` works with any API key and returns no secrets. See `WebSocketConfig` under Types. ### `Realtime` / `AsyncRealtime` @@ -647,6 +669,21 @@ class JobStatusEvent(BaseModel): # realtime status event class PriceResult(BaseModel): price: float class Balance(BaseModel): balance: float + +class WebSocketConnection(BaseModel): + protocol: str # "pusher" + key: str # public application key + host: str + port: int + tls: bool + url: str # property: "wss://host" / "ws://host[:port]" + +class WebSocketConfig(BaseModel): + client_id: str + channel: str # "private-client." + event: str # "request.status.updated" + auth_endpoint: str | None + connection: WebSocketConnection class ModelsResponse(BaseModel): data: list[ModelInfo]; links; meta # meta.current_page, last_page, per_page, total class EnhancePromptResult(BaseModel): prompt: str; negative_prompt: str | None ``` @@ -810,6 +847,8 @@ it with a TTL longer than `tolerance`) so a retried or replayed delivery is proc | `DEAPI_BASE_URL` | `https://api.deapi.ai` | API base URL | | `DEAPI_API_VERSION` | `v2` | API version (only `v2` is accepted) | | `DEAPI_FILL_MODEL_DEFAULTS` | on | `0` stops the SDK filling unset parameters from model-card defaults | -| `DEAPI_CLIENT_ID` | *(none)* | Client ID for `client.realtime()` when `client_id` is not passed | -| `DEAPI_WS_URL` | `wss://soketi.deapi.ai` | WebSocket URL (non-production environments only) | -| `DEAPI_WS_APP_KEY` | public app key | WebSocket app key (non-production environments only) | +| `DEAPI_CLIENT_ID` | *(discovered)* | Client ID for `client.realtime()` when `client_id` is not passed | +| `DEAPI_WS_URL` | *(discovered)* | WebSocket URL override for `client.realtime()` | +| `DEAPI_WS_APP_KEY` | *(discovered)* | WebSocket app key override for `client.realtime()` | + +Unset realtime values are fetched from `GET /websocket` at connect time. diff --git a/examples/realtime_status.py b/examples/realtime_status.py index 8826fe1..c4622c0 100644 --- a/examples/realtime_status.py +++ b/examples/realtime_status.py @@ -8,7 +8,8 @@ Usage: export DEAPI_API_KEY="sk-dp--" - export DEAPI_CLIENT_ID="your-client-id" # the "Client ID" shown in your deAPI dashboard + # Optional: the SDK fetches the connection settings (client id, WebSocket host, app key) from the API. + # export DEAPI_CLIENT_ID="your-client-id" # the "Client ID" shown in your deAPI dashboard python examples/realtime_status.py python examples/realtime_status.py --watch """ @@ -25,7 +26,7 @@ def print_progress(event: JobStatusEvent) -> None: def main() -> None: # Open the connection BEFORE submitting jobs so no event is missed. - # client_id falls back to DEAPI_CLIENT_ID. + # No settings needed: they are fetched from the API on connect (override via client_id= or DEAPI_CLIENT_ID). with DeapiClient() as client, client.realtime() as rt: if "--watch" in sys.argv: print("Watching job events (Ctrl+C to stop)...") diff --git a/src/deapi_sdk/__init__.py b/src/deapi_sdk/__init__.py index fd9c3bc..9e15ab6 100644 --- a/src/deapi_sdk/__init__.py +++ b/src/deapi_sdk/__init__.py @@ -31,6 +31,7 @@ ) from deapi_sdk._polling import AsyncJob, AsyncJobs, Job, Jobs from deapi_sdk._realtime import AsyncRealtime, Realtime +from deapi_sdk._realtime._discovery import parse_websocket_config from deapi_sdk._types import InferenceType, JobStatus from deapi_sdk._version import __version__ from deapi_sdk.transcript import ( @@ -50,6 +51,7 @@ PriceResult, ) from deapi_sdk.types.video import VideoDescription, VideoEvent, parse_video_description +from deapi_sdk.types.websocket import WebSocketConfig, WebSocketConnection from deapi_sdk.webhook import ( InvalidSignatureError, JobPrice, @@ -182,6 +184,16 @@ def balance(self) -> Balance: resp = self._http_client.get(url) return Balance.model_validate(resp.get("data", resp)) + def websocket_config(self) -> WebSocketConfig: + """Realtime WebSocket parameters of this account (``GET /websocket``). + + Contains the Client ID, channel, event name, authorization endpoint and the + connection details (host, port, TLS, public app key). No secrets. + :meth:`realtime` uses it automatically when parameters are not supplied. + """ + resp = self._http_client.get(self._http_client._resolve_endpoint("websocket")) + return parse_websocket_config(resp) + def realtime( self, client_id: str | int | None = None, @@ -192,10 +204,12 @@ def realtime( ) -> Realtime: """Real-time job status updates over WebSocket (needs ``pip install "deapi-sdk[ws]"``). - ``client_id`` is the Client ID shown in your deAPI dashboard; when omitted, - ``DEAPI_CLIENT_ID`` is used. Servers acting for many users should always - pass it explicitly. ``ws_url`` (``DEAPI_WS_URL``) and ``app_key`` - (``DEAPI_WS_APP_KEY``) default to the production server. + Every parameter is optional. Each one is taken from the argument, else from its + environment variable (``DEAPI_CLIENT_ID``, ``DEAPI_WS_URL``, ``DEAPI_WS_APP_KEY``), + else from ``GET /websocket``, which the SDK calls once at connect time when + something is still missing (see :meth:`websocket_config`). With all three + set, no extra request is made. ``client_id`` is the Client ID shown in your + deAPI dashboard; servers acting for many users should pass it explicitly. The connection opens on ``with`` / ``connect()``. It is closed together with this client. @@ -281,6 +295,16 @@ async def balance(self) -> Balance: resp = await self._http_client.get(url) return Balance.model_validate(resp.get("data", resp)) + async def websocket_config(self) -> WebSocketConfig: + """Realtime WebSocket parameters of this account (``GET /websocket``). + + Contains the Client ID, channel, event name, authorization endpoint and the + connection details (host, port, TLS, public app key). No secrets. + :meth:`realtime` uses it automatically when parameters are not supplied. + """ + resp = await self._http_client.get(self._http_client._resolve_endpoint("websocket")) + return parse_websocket_config(resp) + def realtime( self, client_id: str | int | None = None, @@ -291,10 +315,12 @@ def realtime( ) -> AsyncRealtime: """Real-time job status updates over WebSocket (needs ``pip install "deapi-sdk[ws]"``). - ``client_id`` is the Client ID shown in your deAPI dashboard; when omitted, - ``DEAPI_CLIENT_ID`` is used. Servers acting for many users should always - pass it explicitly. ``ws_url`` (``DEAPI_WS_URL``) and ``app_key`` - (``DEAPI_WS_APP_KEY``) default to the production server. + Every parameter is optional. Each one is taken from the argument, else from its + environment variable (``DEAPI_CLIENT_ID``, ``DEAPI_WS_URL``, ``DEAPI_WS_APP_KEY``), + else from ``GET /websocket``, which the SDK calls once at connect time when + something is still missing (see :meth:`websocket_config`). With all three + set, no extra request is made. ``client_id`` is the Client ID shown in your + deAPI dashboard; servers acting for many users should pass it explicitly. The connection opens on ``async with`` / ``await connect()``. It is closed together @@ -341,6 +367,8 @@ async def __aexit__(self, *args: Any) -> None: "ModelInfo", "ModelsResponse", "PriceResult", + "WebSocketConfig", + "WebSocketConnection", # Results "Transcript", "TranscriptSegment", diff --git a/src/deapi_sdk/_constants.py b/src/deapi_sdk/_constants.py index e3738bc..60a005f 100644 --- a/src/deapi_sdk/_constants.py +++ b/src/deapi_sdk/_constants.py @@ -56,4 +56,6 @@ # Catalogue and jobs "models": "models", "request_status": "jobs", + # Realtime WebSocket parameters of the calling key's account (any role) + "websocket": "websocket", } diff --git a/src/deapi_sdk/_realtime/_discovery.py b/src/deapi_sdk/_realtime/_discovery.py new file mode 100644 index 0000000..29f705b --- /dev/null +++ b/src/deapi_sdk/_realtime/_discovery.py @@ -0,0 +1,43 @@ +"""Parsing of ``GET /websocket`` (realtime connection parameters). Pure functions, no I/O.""" + +from __future__ import annotations + +from typing import Any +from urllib.parse import urlsplit + +from pydantic import ValidationError as PydanticValidationError + +from deapi_sdk._exceptions import RealtimeError +from deapi_sdk._realtime import _protocol as protocol +from deapi_sdk.types.websocket import WebSocketConfig + +_HINT = "set client_id, ws_url and app_key (or DEAPI_CLIENT_ID, DEAPI_WS_URL, DEAPI_WS_APP_KEY) to skip discovery" + + +def parse_websocket_config(resp: Any) -> WebSocketConfig: + """Validate a ``GET /websocket`` body; raise :class:`RealtimeError` when it is unusable.""" + data = resp.get("data", resp) if isinstance(resp, dict) else resp + try: + config = WebSocketConfig.model_validate(data) + except PydanticValidationError as exc: + fields = ", ".join(sorted({".".join(str(p) for p in e["loc"]) for e in exc.errors()})) + raise RealtimeError(f"Unexpected response from the WebSocket discovery endpoint (invalid: {fields}).") from exc + if config.connection.protocol != "pusher": + raise RealtimeError( + f"Unsupported WebSocket protocol {config.connection.protocol!r}; this SDK speaks 'pusher'. " + f"Upgrade the SDK or {_HINT}." + ) + if not (config.client_id.strip() and config.channel and config.connection.key and config.connection.host): + raise RealtimeError("The WebSocket discovery response is missing client_id, channel, key or host.") + if config.event != protocol.STATUS_EVENT: + raise RealtimeError( + f"The server announces status updates as event {config.event!r}, but this SDK handles " + f"{protocol.STATUS_EVENT!r}. Upgrade the SDK." + ) + if config.auth_endpoint is not None: + parts = urlsplit(config.auth_endpoint) + if parts.scheme not in ("http", "https") or not parts.netloc: + raise RealtimeError( + f"The WebSocket discovery response has an invalid auth_endpoint: {config.auth_endpoint!r}" + ) + return config diff --git a/src/deapi_sdk/_realtime/_engine.py b/src/deapi_sdk/_realtime/_engine.py index afa921b..a2154a7 100644 --- a/src/deapi_sdk/_realtime/_engine.py +++ b/src/deapi_sdk/_realtime/_engine.py @@ -91,8 +91,8 @@ class Engine: def __init__( self, *, - url: str, - channel: str, + url: str | None, + channel: str | None, authorize: Authorizer, user_agent: str, connect_timeout: float, @@ -100,8 +100,8 @@ def __init__( pong_timeout: float = 30.0, max_activity_timeout: float = 120.0, ) -> None: - self._url = url - self._channel = channel + self._url: str = url or "" + self._channel: str = channel or "" self._authorize = authorize self._user_agent = user_agent self._connect_timeout = connect_timeout @@ -161,6 +161,13 @@ def connected(self) -> bool: """True while the channel subscription is active.""" return self._connected + def configure(self, url: str, channel: str) -> None: + """Set the target when it was not known at construction (discovered at connect time).""" + if self._started: + raise RealtimeError("Cannot reconfigure a started realtime session.") + self._url = url + self._channel = channel + def require_started(self) -> None: """Raise unless :meth:`start` was called (a closed engine is fine: consumers get :class:`Closed`).""" if not self._started: @@ -178,6 +185,8 @@ async def start(self) -> None: if self._started: raise RealtimeError("This realtime session was already started; create a new one to reconnect.") require_websockets() + if not self._url or not self._channel: + raise RealtimeError("The realtime session has no WebSocket URL or channel configured.") self._started = True self._ready = asyncio.Event() self._task = asyncio.create_task(self._run(), name="deapi-realtime") diff --git a/src/deapi_sdk/_realtime/_protocol.py b/src/deapi_sdk/_realtime/_protocol.py index e1fbf6f..0685a9a 100644 --- a/src/deapi_sdk/_realtime/_protocol.py +++ b/src/deapi_sdk/_realtime/_protocol.py @@ -17,8 +17,6 @@ PROTOCOL_VERSION = 7 -DEFAULT_WS_URL = "wss://soketi.deapi.ai" -DEFAULT_APP_KEY = "depin-api-prod-key" BROADCASTING_AUTH_PATH = "/broadcasting/auth" STATUS_EVENT = "request.status.updated" @@ -50,11 +48,16 @@ class CloseAction(Enum): RECONNECT = "reconnect" # reconnect immediately -def build_url(ws_url: str, app_key: str, client_version: str) -> str: - """Build the connection URL: ``{ws_url}/app/{app_key}?protocol=7&client=...&version=...``.""" +def check_ws_url(ws_url: str) -> None: + """Raise ``ValueError`` unless ``ws_url`` is a ``ws://`` or ``wss://`` URL.""" parts = urlsplit(ws_url) if parts.scheme not in ("ws", "wss") or not parts.netloc: raise ValueError(f"ws_url must be a ws:// or wss:// URL, got {ws_url!r}") + + +def build_url(ws_url: str, app_key: str, client_version: str) -> str: + """Build the connection URL: ``{ws_url}/app/{app_key}?protocol=7&client=...&version=...``.""" + check_ws_url(ws_url) if not app_key: raise ValueError("app_key must not be empty") query = urlencode({"protocol": PROTOCOL_VERSION, "client": "deapi-python", "version": client_version}) diff --git a/src/deapi_sdk/_realtime/_session.py b/src/deapi_sdk/_realtime/_session.py index 72edcec..c4f2a76 100644 --- a/src/deapi_sdk/_realtime/_session.py +++ b/src/deapi_sdk/_realtime/_session.py @@ -16,10 +16,12 @@ from deapi_sdk._exceptions import RealtimeError from deapi_sdk._polling import AsyncJob, Job, _timeout_error from deapi_sdk._realtime import _protocol as protocol +from deapi_sdk._realtime._discovery import parse_websocket_config from deapi_sdk._realtime._engine import RECONNECTED, Closed, Engine, SinkItem from deapi_sdk._types import JobStatus from deapi_sdk._version import __version__ from deapi_sdk.types.common import JobResult, JobStatusEvent +from deapi_sdk.types.websocket import WebSocketConfig if TYPE_CHECKING: from types import TracebackType @@ -59,8 +61,16 @@ def _is_terminal(result: JobResult) -> bool: return result.status in _TERMINAL +def _env(name: str) -> str | None: + return os.environ.get(name, "").strip() or None + + class _Settings: - """Connection settings resolved from arguments, then environment, then public defaults.""" + """Connection settings: argument, then environment, then the account's ``GET /websocket`` response. + + Nothing here does I/O. When an argument/environment value is missing, :meth:`apply` + fills the gaps from the discovery response at connect time (once; the result is cached). + """ def __init__( self, @@ -71,24 +81,46 @@ def __init__( connect_timeout: float, ) -> None: config = http._config - resolved_id = str(client_id).strip() if client_id is not None else os.environ.get("DEAPI_CLIENT_ID", "").strip() - if not resolved_id: - raise ValueError( - "client_id is required: pass client_id= (the Client ID shown in your deAPI dashboard) " - "or set the DEAPI_CLIENT_ID environment variable." - ) if connect_timeout <= 0: raise ValueError("connect_timeout must be positive") - self.client_id = resolved_id - self.channel = protocol.channel_for(resolved_id) - self.url = protocol.build_url( - ws_url or os.environ.get("DEAPI_WS_URL") or protocol.DEFAULT_WS_URL, - app_key or os.environ.get("DEAPI_WS_APP_KEY") or protocol.DEFAULT_APP_KEY, - __version__, + self.client_id: str | None = (str(client_id).strip() if client_id is not None else None) or _env( + "DEAPI_CLIENT_ID" ) + self._ws_url = ws_url or _env("DEAPI_WS_URL") + self._app_key = app_key or _env("DEAPI_WS_APP_KEY") + if self._ws_url is not None: + protocol.check_ws_url(self._ws_url) + self.channel: str | None = None + self.url: str | None = None + self.discovered = False self.auth_url = f"{config.base_url.rstrip('/')}{protocol.BROADCASTING_AUTH_PATH}" + self.discovery_url: str = http._resolve_endpoint("websocket") self.user_agent = config._user_agent self.connect_timeout = connect_timeout + if self.client_id and self._ws_url and self._app_key: + self._finish(self.client_id, self._ws_url, self._app_key, protocol.channel_for(self.client_id)) + + @property + def ready(self) -> bool: + return self.url is not None + + def _finish(self, client_id: str, ws_url: str, app_key: str, channel: str) -> None: + self.client_id = client_id + self.channel = channel + self.url = protocol.build_url(ws_url, app_key, __version__) + + def apply(self, discovered: WebSocketConfig) -> None: + """Fill every missing field from the discovery response (explicit values keep precedence).""" + conn = discovered.connection + if self.client_id: + client_id, channel = self.client_id, protocol.channel_for(self.client_id) + else: + # The server's channel is authoritative for the account it announced. + client_id, channel = discovered.client_id.strip(), discovered.channel + self._finish(client_id, self._ws_url or conn.url, self._app_key or conn.key, channel) + if discovered.auth_endpoint: + self.auth_url = discovered.auth_endpoint + self.discovered = True def _auth_signature(resp: Any) -> str: @@ -146,16 +178,27 @@ def __init__( ) @property - def client_id(self) -> str: + def client_id(self) -> str | None: + """The Client ID, or ``None`` until :meth:`connect` when it was not passed or set in the environment.""" return self._settings.client_id + def _discovered(self, config: WebSocketConfig) -> None: + self._settings.apply(config) + self._engine.configure(self._settings.url or "", self._settings.channel or "") + @property def connected(self) -> bool: """True while the channel subscription is live (False while reconnecting or after close).""" return self._engine.connected async def connect(self) -> None: - """Open the connection and subscribe. Raises :class:`RealtimeError` if that fails.""" + """Open the connection and subscribe. Raises :class:`RealtimeError` if that fails. + + Connection parameters that were not supplied are fetched first from ``GET /websocket``. + """ + if not self._settings.ready: + resp = await self._http.get(self._settings.discovery_url) + self._discovered(parse_websocket_config(resp)) await self._engine.start() async def close(self) -> None: @@ -351,16 +394,29 @@ def __init__( self._lock = threading.Lock() @property - def client_id(self) -> str: + def client_id(self) -> str | None: + """The Client ID, or ``None`` until :meth:`connect` when it was not passed or set in the environment.""" return self._settings.client_id + def _discovered(self, config: WebSocketConfig) -> None: + self._settings.apply(config) + self._engine.configure(self._settings.url or "", self._settings.channel or "") + @property def connected(self) -> bool: """True while the channel subscription is live (False while reconnecting or after close).""" return self._engine.connected def connect(self) -> None: - """Open the connection and subscribe. Raises :class:`RealtimeError` if that fails.""" + """Open the connection and subscribe. Raises :class:`RealtimeError` if that fails. + + Connection parameters that were not supplied are fetched first from ``GET /websocket`` + (a blocking HTTP call in the calling thread). + """ + with self._lock: + started = self._thread is not None + if not started and not self._settings.ready: + self._discovered(parse_websocket_config(self._http.get(self._settings.discovery_url))) with self._lock: if self._thread is not None: raise RealtimeError("This realtime session was already started; create a new one to reconnect.") diff --git a/src/deapi_sdk/types/__init__.py b/src/deapi_sdk/types/__init__.py index 31fdebe..5c58cf9 100644 --- a/src/deapi_sdk/types/__init__.py +++ b/src/deapi_sdk/types/__init__.py @@ -28,6 +28,7 @@ VideoEvent, parse_video_description, ) +from deapi_sdk.types.websocket import WebSocketConfig, WebSocketConnection __all__ = [ "Account", @@ -61,5 +62,7 @@ "UsageReport", "VideoDescription", "VideoEvent", + "WebSocketConfig", + "WebSocketConnection", "parse_video_description", ] diff --git a/src/deapi_sdk/types/websocket.py b/src/deapi_sdk/types/websocket.py new file mode 100644 index 0000000..3757458 --- /dev/null +++ b/src/deapi_sdk/types/websocket.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +from pydantic import BaseModel + + +class WebSocketConnection(BaseModel): + """Where to open the realtime WebSocket (the ``connection`` block of ``GET /websocket``).""" + + protocol: str # "pusher" + key: str # public application key of the WebSocket server (not a secret) + host: str + port: int + tls: bool + + model_config = {"extra": "allow"} + + @property + def url(self) -> str: + """``wss://host`` / ``ws://host``; the port is included only when it is not the scheme default.""" + scheme = "wss" if self.tls else "ws" + default_port = 443 if self.tls else 80 + host = f"[{self.host}]" if ":" in self.host and not self.host.startswith("[") else self.host + suffix = "" if self.port == default_port else f":{self.port}" + return f"{scheme}://{host}{suffix}" + + +class WebSocketConfig(BaseModel): + """Realtime WebSocket parameters of the calling account (``GET /websocket``). No secrets.""" + + client_id: str + channel: str + event: str + auth_endpoint: str | None = None + connection: WebSocketConnection + + model_config = {"extra": "allow"} diff --git a/tests/fake_pusher.py b/tests/fake_pusher.py index 874bbe7..eb309b6 100644 --- a/tests/fake_pusher.py +++ b/tests/fake_pusher.py @@ -81,6 +81,10 @@ def __enter__(self) -> FakePusherServer: def __exit__(self, *exc: object) -> None: self.stop() + @property + def port(self) -> int: + return self._port + @property def url(self) -> str: return f"ws://127.0.0.1:{self._port}" diff --git a/tests/test_realtime.py b/tests/test_realtime.py index 2dd351c..a3b1c82 100644 --- a/tests/test_realtime.py +++ b/tests/test_realtime.py @@ -34,6 +34,10 @@ CLIENT_ID = "test-client-1" CHANNEL = f"private-client.{CLIENT_ID}" AUTH_URL = f"{TEST_BASE_URL}/broadcasting/auth" +WEBSOCKET_URL = f"{TEST_BASE_URL}/api/v2/websocket" +DISCOVERED_ID = "00000000-0000-4000-8000-000000000000" +DISCOVERED_CHANNEL = f"private-client.{DISCOVERED_ID}" +DISCOVERED_AUTH_URL = "https://api.example.test/broadcasting/auth" REST_URL = "https://rest.test/final.png" EVENT_URL = "https://event.test/stale.png" @@ -248,14 +252,15 @@ def test_env_client_id_used( assert rt.client_id == "from-env" assert server.subscriptions[0][0] == "private-client.from-env" - def test_missing_client_id(self, client: DeapiClient) -> None: - with pytest.raises(ValueError, match="DEAPI_CLIENT_ID"): - client.realtime() + def test_no_params_constructs_without_io(self, client: DeapiClient, api: respx.MockRouter) -> None: + rt = client.realtime() + assert rt.client_id is None + assert "client_id=None" in repr(rt) + assert not api.calls def test_blank_env_client_id_is_missing(self, client: DeapiClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("DEAPI_CLIENT_ID", " ") - with pytest.raises(ValueError, match="DEAPI_CLIENT_ID"): - client.realtime() + assert client.realtime().client_id is None def test_int_client_id( self, client: DeapiClient, server: FakePusherServer, auth: AuthEndpoint @@ -790,9 +795,8 @@ async def test_client_close_closes_sessions( await async_client.close() assert rt.connected is False - async def test_missing_client_id(self, async_client: AsyncDeapiClient) -> None: - with pytest.raises(ValueError, match="DEAPI_CLIENT_ID"): - async_client.realtime() + async def test_no_params_constructs_without_io(self, async_client: AsyncDeapiClient) -> None: + assert async_client.realtime().client_id is None async def test_env_client_id_and_int( self, @@ -1124,3 +1128,267 @@ async def test_events_after_close_end_immediately( await rt.connect() await rt.close() assert [e async for e in rt.events()] == [] + + +# =========================================================================== discovery + + +def websocket_body(server: FakePusherServer | None = None, **overrides: Any) -> dict[str, Any]: + connection: dict[str, Any] = { + "protocol": "pusher", + "key": APP_KEY, + "host": "ws.example.test", + "port": 443, + "tls": True, + } + if server is not None: + connection.update(host="127.0.0.1", port=server.port, tls=False) + data: dict[str, Any] = { + "client_id": DISCOVERED_ID, + "channel": DISCOVERED_CHANNEL, + "event": "request.status.updated", + "auth_endpoint": DISCOVERED_AUTH_URL, + "connection": connection, + } + data.update(overrides) + return {"data": data} + + +@pytest.fixture +def discovery(api: respx.MockRouter, server: FakePusherServer) -> respx.Route: + return api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(200, json=websocket_body(server))) + + +@pytest.fixture +def discovered_auth(api: respx.MockRouter) -> AuthEndpoint: + endpoint = AuthEndpoint() + api.post(DISCOVERED_AUTH_URL).mock(side_effect=endpoint) + return endpoint + + +class TestDiscoverySync: + def test_no_params_uses_discovery( + self, client: DeapiClient, server: FakePusherServer, discovery: respx.Route, discovered_auth: AuthEndpoint + ) -> None: + rt = client.realtime(connect_timeout=2) + assert rt.client_id is None + assert discovery.call_count == 0 + with rt: + assert rt.client_id == DISCOVERED_ID + assert discovery.call_count == 1 + assert discovery.calls[0].request.headers["authorization"] == f"Bearer {TEST_API_KEY}" + assert server.last_path == f"/app/{APP_KEY}" + assert server.subscriptions[0][0] == DISCOVERED_CHANNEL + assert discovered_auth.bodies[0]["channel_name"] == DISCOVERED_CHANNEL + + def test_all_params_skip_discovery( + self, client: DeapiClient, server: FakePusherServer, api: respx.MockRouter, auth: AuthEndpoint + ) -> None: + route = api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(500)) + with make_rt(client, server): + pass + assert route.call_count == 0 + + def test_env_params_skip_discovery( + self, + client: DeapiClient, + server: FakePusherServer, + api: respx.MockRouter, + auth: AuthEndpoint, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + route = api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(500)) + monkeypatch.setenv("DEAPI_CLIENT_ID", CLIENT_ID) + monkeypatch.setenv("DEAPI_WS_URL", server.url) + monkeypatch.setenv("DEAPI_WS_APP_KEY", APP_KEY) + with client.realtime(connect_timeout=2): + pass + assert route.call_count == 0 + + def test_partial_params_fill_only_missing( + self, client: DeapiClient, server: FakePusherServer, discovery: respx.Route, discovered_auth: AuthEndpoint + ) -> None: + # explicit client_id and app_key win; ws_url and auth_endpoint come from discovery + with client.realtime(client_id="mine", app_key=APP_KEY, connect_timeout=2) as rt: + assert rt.client_id == "mine" + assert discovery.call_count == 1 + assert server.subscriptions[0][0] == "private-client.mine" + assert discovered_auth.bodies[0]["channel_name"] == "private-client.mine" + + def test_explicit_ws_url_and_key_win_over_discovered( + self, client: DeapiClient, server: FakePusherServer, api: respx.MockRouter, discovered_auth: AuthEndpoint + ) -> None: + body = websocket_body(server) + body["data"]["connection"].update(host="unreachable.example.test", port=1, key="other-key") + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(200, json=body)) + with client.realtime(ws_url=server.url, app_key=APP_KEY, connect_timeout=2) as rt: + assert rt.client_id == DISCOVERED_ID + assert server.last_path == f"/app/{APP_KEY}" + + def test_reconnect_does_not_refetch( + self, client: DeapiClient, server: FakePusherServer, discovery: respx.Route, discovered_auth: AuthEndpoint + ) -> None: + with client.realtime(connect_timeout=2) as rt: + server.drop_all() + connected_again(server, rt) + assert discovery.call_count == 1 + + def test_missing_auth_endpoint_falls_back( + self, client: DeapiClient, server: FakePusherServer, api: respx.MockRouter, auth: AuthEndpoint + ) -> None: + body = websocket_body(server) + del body["data"]["auth_endpoint"] + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(200, json=body)) + with client.realtime(connect_timeout=2): + pass + assert auth.bodies[0]["channel_name"] == DISCOVERED_CHANNEL + + def test_http_error_propagates_and_retry_works( + self, client: DeapiClient, server: FakePusherServer, api: respx.MockRouter, discovered_auth: AuthEndpoint + ) -> None: + route = api.get(WEBSOCKET_URL).mock( + side_effect=[ + httpx.Response(401, json={"message": "Unauthenticated."}), + httpx.Response(200, json=websocket_body(server)), + ] + ) + rt = client.realtime(connect_timeout=2) + with pytest.raises(AuthenticationError): + rt.connect() + assert rt.connected is False + with rt: + assert rt.client_id == DISCOVERED_ID + assert route.call_count == 2 + + @pytest.mark.parametrize( + ("mutate", "match"), + [ + (lambda d: d.pop("client_id"), "client_id"), + (lambda d: d.pop("connection"), "connection"), + (lambda d: d["connection"].update(protocol="mqtt"), "protocol"), + (lambda d: d.update(event="something.else"), "event"), + (lambda d: d.update(auth_endpoint="ftp://x"), "auth_endpoint"), + (lambda d: d["connection"].update(host=""), "host"), + ], + ) + def test_malformed_response( + self, client: DeapiClient, api: respx.MockRouter, mutate: Callable[[dict[str, Any]], Any], match: str + ) -> None: + body = websocket_body() + mutate(body["data"]) + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(200, json=body)) + with pytest.raises(RealtimeError, match=match): + client.realtime(connect_timeout=2).connect() + + def test_non_object_response(self, client: DeapiClient, api: respx.MockRouter) -> None: + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(200, json=["nope"])) + with pytest.raises(RealtimeError): + client.realtime(connect_timeout=2).connect() + + def test_server_channel_used_when_client_id_discovered( + self, client: DeapiClient, server: FakePusherServer, api: respx.MockRouter, discovered_auth: AuthEndpoint + ) -> None: + body = websocket_body(server, channel="private-client.custom") + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(200, json=body)) + with client.realtime(connect_timeout=2): + pass + assert server.subscriptions[0][0] == "private-client.custom" + + +class TestDiscoveryAsync: + async def test_no_params_uses_discovery( + self, + async_client: AsyncDeapiClient, + server: FakePusherServer, + discovery: respx.Route, + discovered_auth: AuthEndpoint, + ) -> None: + rt = async_client.realtime(connect_timeout=2) + assert rt.client_id is None + assert discovery.call_count == 0 + async with rt: + assert rt.client_id == DISCOVERED_ID + assert discovery.call_count == 1 + assert server.subscriptions[0][0] == DISCOVERED_CHANNEL + assert discovered_auth.bodies[0]["channel_name"] == DISCOVERED_CHANNEL + + async def test_all_params_skip_discovery( + self, async_client: AsyncDeapiClient, server: FakePusherServer, api: respx.MockRouter, auth: AuthEndpoint + ) -> None: + route = api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(500)) + async with make_async_rt(async_client, server): + pass + assert route.call_count == 0 + + async def test_partial_params( + self, + async_client: AsyncDeapiClient, + server: FakePusherServer, + discovery: respx.Route, + discovered_auth: AuthEndpoint, + ) -> None: + async with async_client.realtime(client_id="mine", app_key=APP_KEY, connect_timeout=2) as rt: + assert rt.client_id == "mine" + assert discovery.call_count == 1 + assert server.subscriptions[0][0] == "private-client.mine" + + async def test_http_error_propagates(self, async_client: AsyncDeapiClient, api: respx.MockRouter) -> None: + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(401, json={"message": "Unauthenticated."})) + with pytest.raises(AuthenticationError): + await async_client.realtime(connect_timeout=2).connect() + + async def test_malformed_response(self, async_client: AsyncDeapiClient, api: respx.MockRouter) -> None: + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(200, json={"data": {"client_id": "x"}})) + with pytest.raises(RealtimeError, match="connection"): + await async_client.realtime(connect_timeout=2).connect() + + +class TestWebsocketConfigMethod: + def test_sync(self, client: DeapiClient, api: respx.MockRouter) -> None: + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(200, json=websocket_body())) + cfg = client.websocket_config() + assert cfg.client_id == DISCOVERED_ID + assert cfg.channel == DISCOVERED_CHANNEL + assert cfg.event == "request.status.updated" + assert cfg.auth_endpoint == DISCOVERED_AUTH_URL + assert cfg.connection.key == APP_KEY + assert cfg.connection.url == "wss://ws.example.test" + + async def test_async(self, async_client: AsyncDeapiClient, api: respx.MockRouter) -> None: + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(200, json=websocket_body())) + cfg = await async_client.websocket_config() + assert cfg.client_id == DISCOVERED_ID + + def test_malformed(self, client: DeapiClient, api: respx.MockRouter) -> None: + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(200, json={"data": {}})) + with pytest.raises(RealtimeError): + client.websocket_config() + + def test_http_error(self, client: DeapiClient, api: respx.MockRouter) -> None: + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(401, json={"message": "Unauthenticated."})) + with pytest.raises(AuthenticationError): + client.websocket_config() + + def test_exported(self) -> None: + import deapi_sdk + from deapi_sdk import types + + assert deapi_sdk.WebSocketConfig is types.WebSocketConfig + + +@pytest.mark.parametrize( + ("tls", "port", "expected"), + [ + (True, 443, "wss://h.example.test"), + (True, 6001, "wss://h.example.test:6001"), + (False, 80, "ws://h.example.test"), + (False, 6001, "ws://h.example.test:6001"), + (False, 443, "ws://h.example.test:443"), + (True, 80, "wss://h.example.test:80"), + ], +) +def test_connection_url_building(tls: bool, port: int, expected: str) -> None: + from deapi_sdk.types import WebSocketConnection + + conn = WebSocketConnection(protocol="pusher", key="k", host="h.example.test", port=port, tls=tls) + assert conn.url == expected From cfc111ddfa027c610877cce0a254d51cb4decce2 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Thu, 19 Nov 2026 11:13:16 +0100 Subject: [PATCH 2/3] Bump version to 0.6.0 and add a changelog Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 27 +++++++++++++++++++++++++++ README.md | 1 + pyproject.toml | 2 +- src/deapi_sdk/_version.py | 2 +- 4 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..8b96f0d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,27 @@ +# Changelog + +All notable changes to this project are documented in this file. +Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versions may contain breaking changes). + +## [0.6.0] - 2026-11-19 + +### Added + +- `client.websocket_config()` (sync and async) returns the account's realtime connection settings + (`GET /websocket`) as the new `WebSocketConfig` / `WebSocketConnection` models. Works with any API key. + +### Changed + +- `client.realtime()` no longer needs any settings. `client_id`, `ws_url` and `app_key` are each taken + from the argument, then `DEAPI_CLIENT_ID` / `DEAPI_WS_URL` / `DEAPI_WS_APP_KEY`, then `GET /websocket`. + The discovery call is made once at connect time and only when something is still missing; with all + three set, no extra request is made. +- Setting only `DEAPI_CLIENT_ID` now triggers one `GET /websocket` call at connect time instead of + falling back to built-in WebSocket defaults. The hard-coded WebSocket URL and app key were removed. +- `Realtime.client_id` / `AsyncRealtime.client_id` is now `str | None`: `None` until connect when it was + neither passed nor set in the environment. +- An unusable discovery response raises `RealtimeError`; HTTP errors from it raise the usual API exceptions. + +## Earlier releases + +See the [tags](https://github.com/deapi-ai/deapi-python-sdk/tags) for 0.5.2 and older. diff --git a/README.md b/README.md index b43b6c0..d3f4ea7 100644 --- a/README.md +++ b/README.md @@ -302,6 +302,7 @@ print(f"Cost: ${price.price}") ```python client.balance().balance # ADMIN key only +client.websocket_config() # realtime connection settings (any role) client.account.get() # balance, currency, auto top-up (ADMIN) client.account.usage(group_by="day") # from_=, to=; group_by day|hour|key|type|model diff --git a/pyproject.toml b/pyproject.toml index 59a09db..fdd1ba8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "deapi-sdk" -version = "0.5.2" +version = "0.6.0" description = "Official Python SDK for DeAPI — distributed AI inference platform" readme = "README.md" license = "MIT" diff --git a/src/deapi_sdk/_version.py b/src/deapi_sdk/_version.py index ac5b4f7..34157b2 100644 --- a/src/deapi_sdk/_version.py +++ b/src/deapi_sdk/_version.py @@ -1,3 +1,3 @@ from __future__ import annotations -__version__ = "0.5.2" +__version__ = "0.6.0" From 878f7e17b5414a1c1f07c79844afe3e6e03e4507 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Thu, 19 Nov 2026 11:20:04 +0100 Subject: [PATCH 3/3] Add realtime integration tests and a changelog link - integration tests for websocket_config() and for realtime sessions that discover their settings (sync, async, and a job followed over the WebSocket to completion) - Changelog URL in the project metadata Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 1 + tests/test_integration.py | 54 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index fdd1ba8..9d6af3e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,6 +47,7 @@ dev = [ Homepage = "https://deapi.ai" Documentation = "https://docs.deapi.ai/other/sdks-and-integrations" Repository = "https://github.com/deapi-ai/deapi-python-sdk" +Changelog = "https://github.com/deapi-ai/deapi-python-sdk/blob/main/CHANGELOG.md" [tool.hatch.build.targets.wheel] packages = ["src/deapi_sdk"] diff --git a/tests/test_integration.py b/tests/test_integration.py index ef98428..3b30ea7 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -270,3 +270,57 @@ async def test_async_generate_price(self, live_async_client: AsyncDeapiClient) - params.pop("prompt") price = await live_async_client.images.generate_price(prompt="test", **params) assert price.price > 0 + + +# --------------------------------------------------------------------------- +# Realtime (WebSocket) — settings discovered from GET /websocket +# --------------------------------------------------------------------------- + +_WS_ENV = ("DEAPI_CLIENT_ID", "DEAPI_WS_URL", "DEAPI_WS_APP_KEY") + + +class TestRealtimeIntegration: + @requires_api_key + def test_websocket_config(self, live_client: DeapiClient) -> None: + cfg = live_client.websocket_config() + assert cfg.client_id + assert cfg.channel == f"private-client.{cfg.client_id}" + assert cfg.event == "request.status.updated" + assert cfg.connection.protocol == "pusher" + assert cfg.connection.url.startswith(("ws://", "wss://")) + + @requires_api_key + def test_realtime_connects_with_discovered_settings( + self, live_client: DeapiClient, monkeypatch: pytest.MonkeyPatch + ) -> None: + for name in _WS_ENV: + monkeypatch.delenv(name, raising=False) + expected = live_client.websocket_config().client_id + with live_client.realtime() as rt: + assert rt.connected + assert rt.client_id == expected + + @requires_api_key + def test_realtime_wait(self, live_client: DeapiClient, monkeypatch: pytest.MonkeyPatch) -> None: + """Submit a job and follow it to completion over the WebSocket.""" + for name in _WS_ENV: + monkeypatch.delenv(name, raising=False) + model = _find_model(live_client, "txt2img") + assert model, "No txt2img model available" + with live_client.realtime() as rt: + job = live_client.images.generate(**_build_txt2img_params(model)) + events: list[Any] = [] + result = rt.wait(job, max_wait=180.0, on_progress=events.append) + assert result.status == JobStatus.DONE + assert result.result_url is not None + + @requires_api_key + async def test_async_realtime_connects_with_discovered_settings( + self, live_async_client: AsyncDeapiClient, monkeypatch: pytest.MonkeyPatch + ) -> None: + for name in _WS_ENV: + monkeypatch.delenv(name, raising=False) + expected = (await live_async_client.websocket_config()).client_id + async with live_async_client.realtime() as rt: + assert rt.connected + assert rt.client_id == expected