# Transport adapters Every backend implements the same interface: synchronous clients subclass {class}`~contree_client.base.ContreeSyncClient`, asynchronous ones subclass {class}`~contree_client.base.ContreeAsyncClient`. An adapter provides only the transport primitives — `request`, `stream(spec, auto_decompress=True)`, `open` and `close` — the whole API surface lives in the base classes and is documented on the [generated API page](api.md). Synchronous adapters export `ContreeClient`, asynchronous ones export `ContreeAsyncClient`: | Backend | Extra | Import | |-------------|----------------------------|-----------------------------------------------------------------| | http.client | — (stdlib) | `from contree_client.http import ContreeClient` | | urllib3 | `contree-client[urllib3]` | `from contree_client.urllib3 import ContreeClient` | | requests | `contree-client[requests]` | `from contree_client.requests import ContreeClient` | | httpx | `contree-client[httpx]` | `from contree_client.httpx import ContreeClient` / `ContreeAsyncClient` | | aiohttp | `contree-client[aiohttp]` | `from contree_client.aiohttp import ContreeAsyncClient` | Thanks to the Liskov substitution principle any adapter of the matching flavour is interchangeable — annotate code against the base classes from {mod}`contree_client.types` and let the caller decide: ::::{tab-set} :::{tab-item} Sync :sync: sync ```python from contree_client.types import ContreeSyncClient def biggest_image(client: ContreeSyncClient) -> str: images = client.list_images(tagged=True).images return max(images, key=lambda image: image.created_at or "").uuid assert biggest_image(double) == IMAGE_UUID # any backend, the test double too ``` ::: :::{tab-item} Async :sync: async ```python from contree_client.types import ContreeAsyncClient async def biggest_image(client: ContreeAsyncClient) -> str: images = (await client.list_images(tagged=True)).images return max(images, key=lambda image: image.created_at or "").uuid assert await biggest_image(double) == IMAGE_UUID ``` ::: :::: ## Autodetect When any installed backend will do, let the package pick one — the first importable backend wins, ordered by ecosystem popularity (sync: requests → urllib3 → httpx → stdlib http.client; async: aiohttp → httpx). Popularity is judged by all-time PyPI download totals from [ClickPy](https://clickpy.clickhouse.com) (PyPI analytics powered by ClickHouse): requests ~34B, urllib3 ~39B (mostly transitive — it ships inside requests/botocore), aiohttp ~10B, httpx ~7.6B. The async variant raises an `ImportError` with an installation suggestion when neither aiohttp nor httpx is installed: ```python from contree_client.sync import ContreeClient from contree_client.asyncio import ContreeAsyncClient ``` ## Creating a client ::::{tab-set} :::{tab-item} Sync :sync: sync ```python from contree_client.requests import ContreeClient client = ContreeClient( "IAM_TOKEN", # Authorization: Bearer project="my-project-id", # Project header (IAM); omit for JWT # base_url defaults to the public endpoint from the spec; # override for self-hosted deployments: # base_url="https://contree.example.com", timeout=300.0, ) ``` ::: :::{tab-item} Async :sync: async ```python from contree_client.httpx import ContreeAsyncClient client = ContreeAsyncClient( "IAM_TOKEN", # Authorization: Bearer project="my-project-id", # Project header (IAM); omit for JWT # base_url defaults to the public endpoint from the spec; # override for self-hosted deployments: # base_url="https://contree.example.com", timeout=300.0, ) ``` ::: :::: All clients are context managers. Entering the context calls `open()` — asynchronous adapters use it to create loop-bound resources (the `aiohttp.ClientSession`) eagerly; `close()` releases the transport: ::::{tab-set} :::{tab-item} Sync :sync: sync ```python with ContreeClient("IAM_TOKEN", project="p") as client: print(client.whoami().permissions) ``` ::: :::{tab-item} Async :sync: async ```python async with ContreeAsyncClient("IAM_TOKEN", project="p") as client: print((await client.whoami()).permissions) ``` ::: :::: ### Reuse a saved profile With a Contree profile saved under `$CONTREE_HOME` (the configuration shared by all Contree tooling), every adapter can be built from the same profiles (`$CONTREE_HOME/auth.ini`): ::::{tab-set} :::{tab-item} Sync :sync: sync ```python client = ContreeClient.from_profile() # the active profile client = ContreeClient.from_profile("staging") # a specific one ``` ::: :::{tab-item} Async :sync: async ```python client = ContreeAsyncClient.from_profile() # the active profile client = ContreeAsyncClient.from_profile("staging") # a specific one ``` ::: :::: Resolution order: explicit argument → `CONTREE_PROFILE` environment variable → the active profile from the config file. Environments without config files (CI, containers) can describe a profile entirely through the standard Contree variables: {func}`contree_client.profiles.from_env` returns a {class}`~contree_client.profiles.Profile` built from `CONTREE_TOKEN` (or `NEBIUS_API_KEY`), `CONTREE_URL` and optionally `CONTREE_PROJECT` (or `NEBIUS_AI_PROJECT`) — or `None` when they are not set, so a caller can fall through to `from_profile()`. ## Bring your own transport instance Each adapter accepts a preconfigured transport object (proxies, TLS tweaks, connection pooling — anything the library supports): ```python from contree_client.urllib3 import ContreeClient as Urllib3Client from contree_client.requests import ContreeClient as RequestsClient from contree_client.httpx import ContreeAsyncClient as HttpxAsyncClient from contree_client.aiohttp import ContreeAsyncClient as AiohttpClient Urllib3Client("token", urllib3_pool_manager=urllib3.PoolManager(maxsize=50)) RequestsClient("token", requests_session=my_requests_session) HttpxAsyncClient("token", httpx_client=httpx.AsyncClient(http2=True)) AiohttpClient("token", aiohttp_session=my_aiohttp_session) ``` Adapter-specific constructor arguments always carry the adapter name as a prefix (`aiohttp_session`, `httpx_client`, ...) — everything unprefixed is part of the common interface and works identically on every backend. A transport you pass in is *not* closed by `client.close()` — the client only closes what it created itself. ## Custom TLS Every adapter takes an optional `ssl_context` — a standard `ssl.SSLContext` handed to the transport untouched (private CAs, client certificates, pinned ciphers): ```python import ssl context = ssl.create_default_context(cafile="internal-ca.pem") client = ContreeClient("token", ssl_context=context) ``` `ssl_context` cannot be combined with a bring-your-own transport instance: the transport you built owns its TLS configuration, so passing both raises `ValueError` instead of silently ignoring one. ## Connection reuse Every adapter keeps pooled keepalive connections for the lifetime of the client: urllib3 (`PoolManager`), requests (`Session`), httpx (`Client` / `AsyncClient`), aiohttp (`ClientSession`), and the stdlib `http.client` adapter runs its own small LIFO pool (the `http_max_connections` constructor kwarg, 25 by default) — buffered requests borrow a warm connection instead of paying a TLS handshake per call, concurrent callers borrow distinct connections (the cap bounds the total; extra callers wait instead of stampeding the server). Before handing a pooled connection out the pool verifies it is still alive (an idle socket must be silent - EOF or unsolicited bytes mean the server dropped it), so an expired keepalive is replaced by a fresh dial without ever sending into a dead socket; a connection that dies in the race window between the check and the send is still covered by one transparent re-send. Streams always own a dedicated connection until EOF. ## Compression The server compresses every response (including streams) with gzip. Adapters decode it transparently, incrementally for streams (`Z_SYNC_FLUSH`-friendly), and every adapter advertises `Accept-Encoding: gzip`; passing `auto_decompress=False` to `stream()` yields the body exactly as served. ## Retries Retries are opt-in. A `RetryPolicy` retries `APIConnectionError` and 410/425/429/5xx responses. It honors `Retry-After` when the server sends one and uses a backoff ladder (0.1 → 5 s) otherwise. The budget is finite by default (10 attempts); unbounded retries are an explicit `max_attempts=None`. Non-idempotent requests (POST — spawn, import, upload) are **never replayed** unless you opt into the double-execution risk with `retry_unsafe=True`: a lost response may mean the server already executed the call. File-like request bodies are rewound to their initial offset before each attempt (non-seekable bodies fail fast). Buffered-request timeouts follow the same retry policy. The configured `timeout` applies to each attempt, so the complete call can take longer. An explicit `wait_operation` or `follow_operation_events` timeout covers event connections, status probes, reconnect delays, and the final status fetch. Sync buffered reads can report expiry after the response completes. This timeout is an absolute deadline. The client checks it whenever iteration resumes, but it does not interrupt caller code between yielded events. A synchronous native read started before expiry can delay `TimeoutError` until it returns. Status probes use one transport attempt because the event follower controls reconnection. Low-level streaming requests use the shared exception hierarchy and are not retried by `call()`. `follow_operation_events` handles network interruptions and reconnects with `Last-Event-Id`; a transport timeout only ends the follower when its absolute deadline has elapsed. Unexpected errors, including malformed event data and corrupt compressed bodies, propagate without retry. After observing terminal status, the Python follower reads the retained log with `follow=False`, preserving the cursor, filters, and original deadline. Live and retained streams use the caller's overall timeout. Both `wait_operation` and `follow_operation_events` accept `idle_timeout`, a float in seconds with a 15.0 default. Any incoming SSE frame, including ping/keepalive comments, renews this inactivity limit. Set it to 0 to disable the limit. When it expires, the client closes the stream before checking status and reconnecting. It never extends the overall timeout. An interrupted read resumes from the last received event id. These drain attempts use the configured `RetryPolicy` statuses, delays, and `max_attempts`, or three attempts with the default delays when no policy is configured. A clean EOF completes a filtered or explicitly resumed log even without a `completion` event. An unfiltered log must include `completion`; otherwise the follower raises `APIConnectionError`. A permanent HTTP failure or exhausted drain budget raises `APIConnectionError` with the original failure as its cause, rather than silently returning partial events. `wait_operation` uses events for instances and polls image imports every 0.5 seconds when `follow_events=None` (the default). Set it to `True` or `False` to force events or polling. Both modes return failed and cancelled responses unchanged and share one deadline across requests, retries, and delays. ::::{tab-set} :::{tab-item} Sync :sync: sync ```python from contree_client import RetryPolicy client = ContreeClient( "IAM_TOKEN", retry=RetryPolicy(), # finite budget: 10 attempts # retry=RetryPolicy(max_attempts=None), # explicitly unbounded # retry=RetryPolicy(retry_unsafe=True), # replay POSTs too (risky) ) ``` ::: :::{tab-item} Async :sync: async ```python from contree_client import RetryPolicy client = ContreeAsyncClient( "IAM_TOKEN", retry=RetryPolicy(), # finite budget: 10 attempts # retry=RetryPolicy(max_attempts=None), # explicitly unbounded # retry=RetryPolicy(retry_unsafe=True), # replay POSTs too (risky) ) ``` ::: :::: ## Request errors All adapters use the shared [exception hierarchy](api.md#exception-hierarchy) for both buffered `request()` and streaming `stream()`. HTTP statuses of 400 or greater become the matching `APIStatusError`, including the response error body and `Retry-After` when available. Connection failures and interrupted bodies become `APIConnectionError`, with the backend exception as `__cause__`. Its `timed_out` flag identifies a transport timeout; it does not mean the operation deadline has elapsed. Streaming methods previously exposed native backend exceptions. Callers must now catch `APIConnectionError` or `APIStatusError` for transport failures. Unknown errors, malformed event data, and corrupt compressed bodies propagate unchanged in both request modes. Task cancellation also propagates unchanged. ## Adding an adapter Use one normalization boundary for `request()` and `stream()`. It must cover connection setup, body reads, and cleanup, including reads after yielded chunks. Convert only recognized network failures to `APIConnectionError` and preserve their cause and timeout flag. Use `error_for_response()` for HTTP errors. Keep parsing and programming errors visible. Retry decisions belong to the shared client code. Adapters must not inspect `RetryPolicy` to classify errors or infer deadline expiry from a transport timeout. Add request/stream contract tests for native connect/read/reset/ truncated/status failures. Verify cursor resume, deadlines, cancellation, and stream closure with the shared lifecycle tests. ## User-Agent Every request carries `contree-client/ / Python/ ` unless the caller supplies its own `User-Agent` header. The tokens come from the `UA_*` class attributes of the base client; adapters override `UA_TRANSPORT_LIBRARY` (e.g. `httpx/0.28.1`, `http.client` for the stdlib backend). An application announces itself with the `identity` constructor kwarg — its token leads and the library tokens stay intact: ::::{tab-set} :::{tab-item} Sync :sync: sync ```python client = ContreeClient("IAM_TOKEN", identity="my-app/1.2.3") # User-Agent: my-app/1.2.3 contree-client/0.1.0 httpx/0.28.1 Python/... assert client.user_agent().startswith("my-app/1.2.3 contree-client/") ``` ::: :::{tab-item} Async :sync: async ```python client = ContreeAsyncClient("IAM_TOKEN", identity="my-app/1.2.3") # User-Agent: my-app/1.2.3 contree-client/0.1.0 httpx/0.28.1 Python/... assert client.user_agent().startswith("my-app/1.2.3 contree-client/") ``` ::: :::: ## Logging The library logs under the `contree_client` logger with one child per adapter (`contree_client.requests`, `contree_client.aiohttp`, ...). The base logger level is explicitly set to `logging.ERROR`, so even an application configured with root `DEBUG` sees nothing from the client unless it opts in: ```python import logging from contree_client.types import set_log_level set_log_level(logging.DEBUG) ``` At `DEBUG` the client logs the raw exchange: - outgoing requests — method, URL, headers and body (`Authorization` and other sensitive headers are redacted; JSON bodies are logged with the values of secret-suffixed keys structurally redacted, truncated at 4 KiB; binary bodies become a `` marker); - buffered responses — status, headers and body, same formatting; - streaming responses — the status line and per-chunk sizes; - every received SSE event (`sse event: OperationEvent(...)`); - backend autodetection decisions. ## Reference ### contree_client.types ```{eval-rst} .. automodule:: contree_client.types ``` ### contree_client.sync ```{eval-rst} .. automodule:: contree_client.sync ``` ### contree_client.asyncio ```{eval-rst} .. automodule:: contree_client.asyncio ``` ### contree_client.http ```{eval-rst} .. automodule:: contree_client.http ``` ### contree_client.urllib3 ```{eval-rst} .. automodule:: contree_client.urllib3 ``` ### contree_client.requests ```{eval-rst} .. automodule:: contree_client.requests ``` ### contree_client.httpx ```{eval-rst} .. automodule:: contree_client.httpx ``` ### contree_client.aiohttp ```{eval-rst} .. automodule:: contree_client.aiohttp ``` ### contree_client.profiles ```{eval-rst} .. automodule:: contree_client.profiles ``` ### contree_client.runtime ```{eval-rst} .. automodule:: contree_client.runtime ```