Transport adapters¶
Every backend implements the same interface: synchronous clients
subclass ContreeSyncClient, asynchronous
ones subclass 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.
Synchronous adapters export ContreeClient, asynchronous ones export
ContreeAsyncClient:
Backend |
Extra |
Import |
|---|---|---|
http.client |
— (stdlib) |
|
urllib3 |
|
|
requests |
|
|
httpx |
|
|
aiohttp |
|
|
Thanks to the Liskov substitution principle any adapter of the
matching flavour is interchangeable — annotate code against the base
classes from contree_client.types and let the caller decide:
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
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 (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:
from contree_client.sync import ContreeClient
from contree_client.asyncio import ContreeAsyncClient
Creating a client¶
from contree_client.requests import ContreeClient
client = ContreeClient(
"IAM_TOKEN", # Authorization: Bearer <token>
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,
)
from contree_client.httpx import ContreeAsyncClient
client = ContreeAsyncClient(
"IAM_TOKEN", # Authorization: Bearer <token>
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:
with ContreeClient("IAM_TOKEN", project="p") as client:
print(client.whoami().permissions)
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):
client = ContreeClient.from_profile() # the active profile
client = ContreeClient.from_profile("staging") # a specific one
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:
contree_client.profiles.from_env() returns a
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):
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):
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.
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)
)
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
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/<version> <transport>/<version> Python/<version> <platform> 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:
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/")
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:
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 (
Authorizationand 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<binary NB>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¶
Typing-oriented re-exports of the client base classes and the package logging subsystem.
Annotate code against these interfaces instead of a concrete backend, so any transport can be substituted:
from contree_client.types import ContreeSyncClient
def biggest_image(client: ContreeSyncClient) -> str:
...
Every implementation logs into a child of logger. The base
logger level is explicitly set to logging.ERROR, so the library
stays silent unless the user opts in:
from contree_client.types import set_log_level
set_log_level(logging.DEBUG)
contree_client.sync¶
Autodetected synchronous client.
Tries the installed backends in priority order and exposes the first
importable one as ContreeClient:
from contree_client.sync import ContreeClient
The stdlib http.client backend needs no third-party packages, so
detection always succeeds; install contree-client[requests],
[urllib3] or [httpx] to get a higher-priority backend.
contree_client.asyncio¶
Autodetected asynchronous client.
Tries the installed backends in priority order and exposes the first
importable one as ContreeAsyncClient:
from contree_client.asyncio import ContreeAsyncClient
Raises an ImportError with an installation suggestion when neither aiohttp nor httpx is available.
contree_client.http¶
Contree API client backed by the standard library http.client.
No third-party dependencies. The server compresses every response (including SSE streams) and http.client neither advertises nor decodes gzip, so both are handled here: buffered bodies are inflated in one go, streams are inflated incrementally (Z_SYNC_FLUSH-friendly), and reading uses read1() - a plain read(n) would block until n bytes arrive and stall SSE frames.
Buffered requests borrow keepalive connections from a small pool (saving a TLS handshake per call); each stream owns a dedicated connection until EOF.
- contree_client.http.read_response(response)[source]¶
Read the whole body, inflating gzip when the server used it.
Content-Encoding/Content-Length are dropped after inflation so nobody downstream attempts a second decode against a stale length.
- Parameters:
response (HTTPResponse)
- Return type:
- contree_client.http.connection_alive(connection)[source]¶
True when an idle keepalive connection is still usable.
An idle HTTP connection must be silent: a readable socket while no request is in flight means the server closed it (EOF/close_notify) or broke the protocol - either way it must not be handed out. The zero-timeout select works for TLS sockets too, where a MSG_PEEK recv would not.
- Parameters:
connection (HTTPConnection)
- Return type:
- contree_client.http.normalize_errors()[source]¶
Normalize transport failures for buffered and streaming requests.
- Return type:
Iterator[None]
- class contree_client.http.ConnectionPool(factory, maxsize=5)[source]¶
Bases:
objectA bounded LIFO pool of keepalive http.client connections.
maxsize caps the TOTAL number of live connections, not just the idle ones: borrowing takes the most recently used idle connection (the warmest, least likely to have been closed by the server), dials a new one while under the cap, and otherwise blocks until a concurrent caller returns or discards one - concurrency cannot stampede the server with extra dials. A Condition rather than a Queue: discarding a broken connection frees a slot and must wake a blocked borrower, which a plain Queue.get() cannot express.
- Parameters:
factory (Callable[[], http.client.HTTPConnection])
maxsize (int)
- acquire(deadline=None)[source]¶
Borrow a connection before deadline.
True means the returned connection was reused and can be stale.
- Parameters:
deadline (float | None)
- Return type:
- release(connection)[source]¶
Return a healthy connection for reuse.
- Parameters:
connection (HTTPConnection)
- Return type:
None
- discard(connection)[source]¶
Close a broken connection and free its slot.
- Parameters:
connection (HTTPConnection)
- Return type:
None
- class contree_client.http.ContreeClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, http_max_connections=25)[source]¶
Bases:
ContreeSyncClientSynchronous Contree API client on top of http.client.
Buffered requests share a keepalive
ConnectionPool(default 25 connections) - a request re-sent once on a fresh connection when the borrowed one went stale server-side. Streams hold their socket until fully consumed, so each stream gets a dedicated connection closed at its end.- Parameters:
token (str)
base_url (str)
project (str | None)
timeout (float | None)
retry (RetryPolicy | None)
identity (str | None)
ssl_context (ssl.SSLContext | None)
http_max_connections (int)
- UA_TRANSPORT_LIBRARY = 'http.client'¶
- request(spec)[source]¶
Execute the request and return the buffered response.
- Parameters:
spec (RequestSpec)
- Return type:
- stream(spec, auto_decompress=True)[source]¶
Execute the request and yield response body chunks.
With
auto_decompress=Falsethe body is yielded exactly as served (e.g. the gzip the server always applies is kept).- Parameters:
spec (RequestSpec)
auto_decompress (bool)
- Return type:
contree_client.urllib3¶
Contree API client backed by urllib3.
- contree_client.urllib3.normalize_errors()[source]¶
Normalize transport failures for buffered and streaming requests.
- Return type:
Iterator[None]
- class contree_client.urllib3.ContreeClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, urllib3_pool_manager=None)[source]¶
Bases:
ContreeSyncClientSynchronous Contree API client on top of urllib3.PoolManager.
The server compresses every response (including streams); unlike requests/httpx/aiohttp, urllib3 does not advertise gzip support on its own, so the Accept-Encoding header is set explicitly and the responses are transparently decoded (decode_content=True).
- Parameters:
token (str)
base_url (str)
project (str | None)
timeout (float | None)
retry (RetryPolicy | None)
identity (str | None)
ssl_context (ssl.SSLContext | None)
urllib3_pool_manager (urllib3.PoolManager | None)
- UA_TRANSPORT_LIBRARY = 'urllib3/2.7.0'¶
- request(spec)[source]¶
Execute the request and return the buffered response.
- Parameters:
spec (RequestSpec)
- Return type:
- stream(spec, auto_decompress=True)[source]¶
Execute the request and yield response body chunks.
With
auto_decompress=Falsethe body is yielded exactly as served (e.g. the gzip the server always applies is kept).- Parameters:
spec (RequestSpec)
auto_decompress (bool)
- Return type:
contree_client.requests¶
Contree API client backed by requests.
- contree_client.requests.normalize_errors()[source]¶
Normalize transport failures for buffered and streaming requests.
- Return type:
Iterator[None]
- class contree_client.requests.SSLContextAdapter(ssl_context, **kwargs)[source]¶
Bases:
HTTPAdapterAn HTTPAdapter that hands a caller-supplied SSLContext down to the underlying urllib3 pool - requests has no direct kwarg for it.
- Parameters:
ssl_context (ssl.SSLContext)
kwargs (Any)
- class contree_client.requests.ContreeClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, requests_session=None)[source]¶
Bases:
ContreeSyncClientSynchronous Contree API client on top of requests.Session.
- Parameters:
token (str)
base_url (str)
project (str | None)
timeout (float | None)
retry (RetryPolicy | None)
identity (str | None)
ssl_context (ssl.SSLContext | None)
requests_session (requests.Session | None)
- UA_TRANSPORT_LIBRARY = 'requests/2.34.2'¶
- request(spec)[source]¶
Execute the request and return the buffered response.
- Parameters:
spec (RequestSpec)
- Return type:
- stream(spec, auto_decompress=True)[source]¶
Execute the request and yield response body chunks.
With
auto_decompress=Falsethe body is yielded exactly as served (e.g. the gzip the server always applies is kept).- Parameters:
spec (RequestSpec)
auto_decompress (bool)
- Return type:
contree_client.httpx¶
Contree API clients backed by httpx (sync and async).
- contree_client.httpx.normalize_errors()[source]¶
Normalize transport failures for sync/async requests and streams.
- Return type:
Iterator[None]
- class contree_client.httpx.ContreeClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, httpx_client=None)[source]¶
Bases:
ContreeSyncClientSynchronous Contree API client on top of httpx.Client.
- Parameters:
token (str)
base_url (str)
project (str | None)
timeout (float | None)
retry (RetryPolicy | None)
identity (str | None)
ssl_context (ssl.SSLContext | None)
httpx_client (httpx.Client | None)
- UA_TRANSPORT_LIBRARY = 'httpx/0.28.1'¶
- request(spec)[source]¶
Execute the request and return the buffered response.
- Parameters:
spec (RequestSpec)
- Return type:
- stream(spec, auto_decompress=True)[source]¶
Execute the request and yield response body chunks.
With
auto_decompress=Falsethe body is yielded exactly as served (e.g. the gzip the server always applies is kept).- Parameters:
spec (RequestSpec)
auto_decompress (bool)
- Return type:
- class contree_client.httpx.ContreeAsyncClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, httpx_client=None)[source]¶
Bases:
ContreeAsyncClientAsynchronous Contree API client on top of httpx.AsyncClient.
- Parameters:
token (str)
base_url (str)
project (str | None)
timeout (float | None)
retry (RetryPolicy | None)
identity (str | None)
ssl_context (ssl.SSLContext | None)
httpx_client (httpx.AsyncClient | None)
- UA_TRANSPORT_LIBRARY = 'httpx/0.28.1'¶
- async request(spec)[source]¶
Execute the request and return the buffered response.
- Parameters:
spec (RequestSpec)
- Return type:
- async stream(spec, auto_decompress=True)[source]¶
Execute the request and yield response body chunks.
With
auto_decompress=Falsethe body is yielded exactly as served (e.g. the gzip the server always applies is kept).- Parameters:
spec (RequestSpec)
auto_decompress (bool)
- Return type:
AsyncGenerator[bytes, None]
contree_client.aiohttp¶
Contree API client backed by aiohttp.
- contree_client.aiohttp.normalize_errors()[source]¶
Normalize transport failures for buffered and streaming requests.
- Return type:
Iterator[None]
- class contree_client.aiohttp.ContreeAsyncClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, aiohttp_session=None)[source]¶
Bases:
ContreeAsyncClientAsynchronous Contree API client on top of aiohttp.ClientSession.
The owned session is created lazily inside a running event loop.
- Parameters:
token (str)
base_url (str)
project (str | None)
timeout (float | None)
retry (RetryPolicy | None)
identity (str | None)
ssl_context (ssl.SSLContext | None)
aiohttp_session (aiohttp.ClientSession | None)
- UA_TRANSPORT_LIBRARY = 'aiohttp/3.14.1'¶
- async request(spec)[source]¶
Execute the request and return the buffered response.
- Parameters:
spec (RequestSpec)
- Return type:
- async stream(spec, auto_decompress=True)[source]¶
Execute the request and yield response body chunks.
With
auto_decompress=Falsethe body is yielded exactly as served (e.g. the gzip the server always applies is kept).- Parameters:
spec (RequestSpec)
auto_decompress (bool)
- Return type:
AsyncGenerator[bytes, None]
contree_client.profiles¶
Contree configuration profiles.
The INI files under $CONTREE_HOME: auth.ini (secrets) merged over $CONTREE_HOME/cli.ini (non-secret defaults), where CONTREE_HOME defaults to $XDG_CONFIG_HOME/contree and finally ~/.config/contree.
- exception contree_client.profiles.ProfileError[source]¶
Bases:
ValueErrorThe requested profile is missing or incomplete.
- class contree_client.profiles.Profile(name, url, token, auth_type='jwt', project=None)[source]¶
Bases:
objectOne Contree authentication profile.
Frozen and comparable; the token never shows up in repr().
- save(config)[source]¶
- Parameters:
config (ConfigParser)
- Return type:
None
- contree_client.profiles.load_profiles(path=None)[source]¶
Read all profiles; return (profiles, active_profile_name).
cli.ini is read first, then auth.ini - values from auth.ini win on conflicts.
- contree_client.profiles.from_env()[source]¶
Build a profile from the environment, bypassing config files.
Reads the standard Contree variables:
CONTREE_TOKEN(orNEBIUS_API_KEY),CONTREE_URLand optionallyCONTREE_PROJECT(orNEBIUS_AI_PROJECT). Reports None unless both a token and a URL are present, so callers can fall through toresolve_profile().- Return type:
Profile | None
contree_client.runtime¶
Transport-agnostic request/response plumbing and SSE parsing.
- contree_client.runtime.closing_iterator(source)[source]¶
Release a closable iterator before the caller starts another request.
- contree_client.runtime.remaining_timeout(deadline, maximum)[source]¶
Return the smaller of the remaining deadline and maximum.
Raise
TimeoutErrorwhen the absolute monotonic deadline has elapsed. This check cannot interrupt work already in progress.
- contree_client.runtime.redact_json(value)[source]¶
Recursively replace values of secret-suffixed keys.
- class contree_client.runtime.HeaderFormatter(headers)[source]¶
Bases:
objectLazy %s argument for logging HTTP headers, redacts secrets.
- class contree_client.runtime.BodyFormatter(body, content_type='', max_size=4096)[source]¶
Bases:
objectLazy %s argument for logging HTTP bodies.
JSON payloads are parsed and re-rendered with the values of secret-suffixed keys structurally redacted; other textual payloads are rendered as-is. Everything is truncated at max_size, binary payloads become a size marker and file-like bodies are never consumed.
- class contree_client.runtime.RequestSpec(method, path, query=<factory>, headers=<factory>, body=None, content_type=None, accept=None, idempotent=False, deadline=None, read_timeout=None)[source]¶
Bases:
objectA backend-agnostic description of a single API request.
- Parameters:
- class contree_client.runtime.ResponseData(status, headers, body)[source]¶
Bases:
objectA fully buffered response; header names are lower-cased.
- contree_client.runtime.distribution_version(name)[source]¶
The installed distribution version via package metadata.
Editable installs report
"editable"(their recorded version is whatever was current at install time, i.e. a lie); missing metadata reports None.
- contree_client.runtime.library_version(module)[source]¶
A
name/versionUser-Agent token for a transport module.Version resolution: package metadata (
editablefor editable installs), then the module’s__version__, thenunknown- building the token must never fail the import.
- contree_client.runtime.file_sha256(content)[source]¶
The sha256 hexdigest of an upload payload.
File-like payloads are hashed from their current position - the exact bytes a subsequent send would transmit - and the position is restored afterwards. A non-seekable stream cannot be re-read, so it reports None (the caller skips deduplication).
- contree_client.runtime.retry_generator(delays=(0.1, 0.2, 0.5, 1.0, 2.0, 5.0))[source]¶
An endless ladder of backoff delays.
Every
next()returns a valid sleep time: the ladder is walked once and then the tail delay repeats forever, so callers never guard againstStopIterationand never do index arithmetic. A finite retry budget is bounded externally (an attempt counter).
- class contree_client.runtime.RetryPolicy(statuses=(410, 425, 429), server_errors=True, delays=(0.1, 0.2, 0.5, 1.0, 2.0, 5.0), max_attempts=10, retry_unsafe=False)[source]¶
Bases:
objectOpt-in retries for buffered request failures.
Retries
APIConnectionErrorand the configured HTTP statuses.server_errorsextends this to every 5xx status. SSE consumers handle stream reconnection separately.- Parameters:
- contree_client.runtime.body_start(spec)[source]¶
The position a file-like body starts sending from.
Captured before the first attempt so a retry replays exactly the same bytes; None for absent/bytes/non-seekable bodies.
- Parameters:
spec (RequestSpec)
- Return type:
int | None
- contree_client.runtime.rewind_body(spec, start)[source]¶
Rewind a file-like request body to start before a retry.
- Parameters:
spec (RequestSpec)
start (int | None)
- Return type:
None
- contree_client.runtime.parse_retry_after(value)[source]¶
Parse a Retry-After header: delta-seconds or an HTTP-date.
Negative values clamp to 0.0; anything unparsable reports None.
- contree_client.runtime.retry_after_delay(response)[source]¶
The Retry-After header as seconds, when present and valid.
- Parameters:
response (ResponseData)
- Return type:
float | None
- contree_client.runtime.json_body(response)[source]¶
- Parameters:
response (ResponseData)
- Return type:
- contree_client.runtime.json_object(response)[source]¶
- Parameters:
response (ResponseData)
- Return type:
- contree_client.runtime.json_array(response)[source]¶
- Parameters:
response (ResponseData)
- Return type:
- contree_client.runtime.error_for_response(status_code, headers, body)[source]¶
Build the exception matching an error response.
- contree_client.runtime.preserve_response_status(status, headers)[source]¶
Keep a known HTTP failure when its error body is interrupted.
- class contree_client.runtime.GzipStreamDecoder[source]¶
Bases:
objectIncremental gzip decoder for streamed response bodies.
Used by transports without built-in decompression (http.client); handles Z_SYNC_FLUSH-style streams, so decoded data comes out as soon as the server flushes it.
- class contree_client.runtime.IdentityStreamDecoder[source]¶
Bases:
objectNo-op decoder for uncompressed response bodies.
- contree_client.runtime.stream_decoder(content_encoding)[source]¶
- Parameters:
content_encoding (str | None)
- Return type:
- contree_client.runtime.request_content(body)[source]¶
Normalize a request body to something httpx accepts as content.
- contree_client.runtime.async_request_content(body)[source]¶
Normalize a request body for an asynchronous transport.
A file-like body becomes an async iterator whose reads run in a worker thread, so blocking file I/O never stalls the event loop (and an async client never receives a sync iterator).
- class contree_client.runtime.SSEFrame(id=None, event=None, data='')[source]¶
Bases:
objectOne parsed Server-Sent Events frame.
- class contree_client.runtime.SSEParser[source]¶
Bases:
objectIncremental sans-io parser for text/event-stream bytes.
Feed raw chunks, get complete frames back. Comment lines (: keepalive) are discarded per the SSE specification.
- MAX_BUFFER = 4194304¶
- contree_client.runtime.decode_event_frame(frame, last_event_id=None)[source]¶
Decode an SSE frame into an OperationEvent.
Return None for frames that carry no event payload.
- Parameters:
- Return type:
OperationEvent | None