class documentation

A high-level gRPC channel manager used by the SDK.

Responsibilities and behavior

  • Resolve service names to addresses and create underlying gRPC channels for
    those addresses.
  • Maintain a small pool of free channels per address to reuse connections and
    reduce churn (see max_free_channels_per_address init param).
  • Provide helpers to attach authorization credentials and manage token
    providers, including synchronous and asynchronous token acquisition via get_token and get_token_sync.
  • Expose convenience wrappers for unary-unary RPCs that ensure the address
    channel is returned to the pool when the RPC completes (see NebiusUnaryUnaryMultiCallable).
  • Offer both async and sync usage models. Use the async context manager
    (async with Channel(...)) or call close()/sync_close() to gracefully shut down resources.

Important notes

  • The channel owns a configurable asyncio event loop (optionally provided at
    construction). When calling run_sync from within an already running loop, a LoopError is raised unless a separate loop was supplied at initialization.
  • The class cooperates with several SDK subsystems (token bearers,
    authorization providers, idempotency interceptor, and a resolver) and wires them together during initialization.
  • Public helper methods include: get_token/get_token_sync,
    run_sync, bg_task, get_channel_by_method, and create_address_channel.

Usage example

Async usage (recommended):

async with Channel(...) as channel:
    # use channel or pass it to generated service clients
    pass

Synchronous usage:

channel = Channel(...)
try:
    channel.run_sync(some_coroutine())
finally:
    channel.sync_close()
Parameters
resolverOptional custom Resolver used to resolve service names to concrete addresses. If omitted a Conventional resolver is used. If provided, it will be chained with the built-in resolver so both can be consulted.
substitutionsOptional mapping of template substitutions applied to resolved addresses. The construct inserts {"{domain}": domain} and then updates it with this mapping. Typical use is to override domain placeholders in generated service addresses.
user_agent_prefixOptional string prepended to the default SDK user-agent. The final user-agent string follows the pattern "<user_agent_prefix> nebius-python-sdk/<version> (python/X.Y.Z)". Recommended format: "my-app/1.0 (dependency-to-track/version; other-dependency)".
domainOptional domain to substitute into service addresses. When not provided the constructor will try to obtain it from the provided config_reader via config_reader.endpoint(), and fall back to the package-level DOMAIN constant if still unset.
optionsGlobal channel options passed to gRPC when creating address channels. This should follow the ChannelArgumentType shape (sequence of key/value tuples).
interceptorsGlobal list of gRPC ClientInterceptor instances that will be applied to all address channels. An idempotency-key interceptor is added by default; pass a list to extend or override additional behavior.
address_optionsOptional mapping from a resolved address to per-address channel options. Each value must follow the ChannelArgumentType shape (sequence of key/value tuples). If omitted an empty mapping is used.
address_interceptorsOptional mapping from a resolved address to a sequence of per-address interceptors. Per-address interceptors are invoked in addition to the global interceptors.
credentials

Credentials can be provided in several forms:

  • None (default): attempts to read credentials from
    credentials_file_name, then from provided service account fields, then from config_reader.get_credentials(...), and finally falls back to an environment-backed bearer (nebius.aio.token.static.EnvBearer).
  • str or Token: treated as a
    static token and wrapped with a static bearer.
  • TokenBearer to use an existing token bearer as-is.
  • TokenRequester to exchange tokens on demand.
  • AuthorizationProvider: an explicit authorization provider
    (used rarely by advanced users).
  • NoCredentials: disables authorization entirely.

Unsupported types raise SDKError.

service_account_idService account ID used when a private key file is supplied directly (alternate to using credentials_file_name). See the README for examples. If credentials is provided explicitly this parameter is ignored.
service_account_public_key_idPublic key ID corresponding to the private key file used for service-account authentication, as described in the README. If credentials is provided explicitly this parameter is ignored.
service_account_private_key_file_namePath to a PEM private key file. When provided with the key ID and service account ID fields above, the constructor wraps it in a service-account reader.
credentials_file_namePath to a credentials JSON file containing service-account information. If supplied this takes precedence over other implicit credential discovery (unless credentials is explicitly provided).
config_readerOptional nebius.aio.cli_config.Config instance used to populate defaults like domain, default parent ID, and to obtain credentials via the CLI-style configuration.
tls_credentialsOptional gRPC channel TLS credentials (ChannelCredentials). If omitted the constructor will load system root certificates via nebius.base.tls_certificates.get_system_certificates and create an SSL channel credentials object.
event_loopOptional asyncio event loop to be owned by this Channel. When a loop is provided, synchronous helpers such as run_sync may be called from other threads without raising LoopError. If not provided the Channel will lazily create its own loop when a synchronous call is made.
max_free_channels_per_addressNumber of free underlying gRPC channels to keep in the pool per resolved address. Defaults to 2. Lower values reduce resource usage but increase connection churn; larger values raise resource consumption.
parent_idOptional parent ID which will be automatically applied to many requests when left empty by the caller. If not provided and a config_reader is supplied the constructor will attempt to use config_reader.parent_id. An explicit empty string is treated as an error.
federation_invitation_writerOptional file-like writer passed to the config reader to display the URL for federation authentication during interactive credential acquisition.
federation_invitation_no_browser_openWhen using the config reader, set to True to avoid opening a web browser during interactive federation flows. Defaults to False.
Async Method __aenter__ Enter the async context manager. Returns self to allow usage like:
Async Method __aexit__ Exit the async context manager. Calls close() to gracefully shut down resources.
Method __init__ Construct a new Channel instance.
Method bg_task Run a coroutine in the background and log uncaught exceptions.
Async Method channel_ready Channel is always ready, nothing to do here.
Async Method close Gracefully close the channel and all associated background work.
Method create_address_channel Create a new underlying gRPC channel for the given address.
Method discard_channel Dispose of an AddressChannel by scheduling its close.
Method get_addr_by_method Return the cached address for a fully-qualified RPC method name.
Method get_addr_from_service_name Resolve a logical service name into a transport address.
Method get_addr_from_stub Resolve the concrete address for a generated service stub class.
Method get_address_interceptors Return the ordered list of interceptors to apply to a channel.
Method get_address_options Compute effective gRPC channel options for a specific address.
Method get_authorization_provider Return the configured AuthorizationProvider.
Method get_channel_by_addr Request an AddressChannel for the given resolved address.
Method get_channel_by_method Convenience to obtain an AddressChannel for an RPC method name. The method resolves the address via get_addr_by_method and then calls get_channel_by_addr to obtain the channel.
Method get_corresponding_operation_service Return an operations service stub for the same address as a generated service stub.
Method get_corresponding_operation_service_alpha Compatibility helper returning the alpha-version operations service stub for the same address as a generated service stub.
Method get_state Nebius Python SDK channels are always ready unless closed.
Async Method get_token Asynchronously fetch an authorization Token.
Method get_token_sync Synchronously fetch an authorization Token.
Method parent_id Return the channel-wide default parent ID used for certain requests.
Method return_channel Return an AddressChannel to the internal pool.
Method run_sync Run an awaitable to completion on the channel's event loop.
Method stream_stream Nebius Python SDK does not support streaming RPCs.
Method stream_unary Nebius Python SDK does not support streaming RPCs.
Method sync_close Synchronously close the channel and wait for graceful shutdown.
Method unary_stream Nebius Python SDK does not support streaming RPCs.
Method unary_unary A method to support using SDK channel as gRPC Channel.
Async Method wait_for_state_change Nebius Python SDK channels are always ready unless closed. This method is provided to satisfy the gRPC Channel interface.
Instance Variable user_agent The user-agent string used by channels created by this Channel instance.
Instance Variable _address_interceptors Undocumented
Instance Variable _address_options Undocumented
Instance Variable _authorization_provider Undocumented
Instance Variable _closed Undocumented
Instance Variable _event_loop Undocumented
Instance Variable _free_channels Undocumented
Instance Variable _global_interceptors Undocumented
Instance Variable _global_interceptors_inner Undocumented
Instance Variable _global_options Undocumented
Instance Variable _gracefuls Undocumented
Instance Variable _max_free_channels_per_address Undocumented
Instance Variable _methods Undocumented
Instance Variable _parent_id Undocumented
Instance Variable _resolver Undocumented
Instance Variable _tasks Undocumented
Instance Variable _tls_credentials Undocumented
Instance Variable _token_bearer Undocumented
async def __aenter__(self) -> Channel: (source)

Enter the async context manager. Returns self to allow usage like:

async with channel as chan:
    await chan.some_method()

Will close the channel on exit.

async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any): (source)

Exit the async context manager. Calls close() to gracefully shut down resources.

def __init__(self, *, resolver: Resolver | None = None, substitutions: dict[str, str] | None = None, user_agent_prefix: str | None = None, domain: str | None = None, options: ChannelArgumentType | None = None, interceptors: Sequence[ClientInterceptor] | None = None, address_options: dict[str, ChannelArgumentType] | None = None, address_interceptors: dict[str, Sequence[ClientInterceptor]] | None = None, credentials: Credentials = None, service_account_id: str | None = None, service_account_public_key_id: str | None = None, service_account_private_key_file_name: str | Path | None = None, credentials_file_name: str | Path | None = None, config_reader: ConfigReader | None = None, tls_credentials: ChannelCredentials | None = None, event_loop: AbstractEventLoop | None = None, max_free_channels_per_address: int = 2, parent_id: str | None = None, federation_invitation_writer: TextIO | None = None, federation_invitation_no_browser_open: bool = False): (source)

Construct a new Channel instance.

This constructor wires together the SDK's gRPC channel management, credential providers, resolvers, TLS configuration and interceptors.

The Channel is responsible for resolving logical service names to transport addresses, creating and pooling underlying gRPC channels, and exposing helpers for synchronous and asynchronous usage.

Notes

  • The constructor performs several discovery steps for credentials in the following precedence order when credentials is None: 1. credentials_file_name reader 2. service-account PEM reader (when id/key args are provided) 3. config_reader.get_credentials(...) 4. environment-backed bearer (EnvBearer)
  • Token readers are wrapped into exchangeable/renewable bearers so that token refresh happens transparently in the background and the Channel adds the bearer to its graceful shutdown set to ensure background tasks are cleaned up on close.

Examples

Typical, minimal construction that reads token from environment:

>>> channel = Channel()

Using explicit static token:

>>> channel = Channel(credentials="MY_TOKEN")

Creating channel from CLI config and a custom resolver:

>>> from nebius.aio.cli_config import Config
>>> channel = Channel(config_reader=Config(), resolver=my_resolver)
Raises
SDKErrorRaised for unsupported credential types or if parent_id is an explicitly empty string.
def bg_task(self, coro: Awaitable[T]) -> Task[None]: (source)

Run a coroutine in the background and log uncaught exceptions.

The returned task is automatically tracked by the channel and will be cancelled during close. Any non-cancellation exception is logged to the module logger.

Parameters
coro:Awaitable[T]An awaitable object to run in the background.
Returns
Task[None]The created asyncio.Task.
async def channel_ready(self): (source)

Channel is always ready, nothing to do here.

async def close(self, grace: float | None = None): (source)

Gracefully close the channel and all associated background work.

The channel will stop handing out address channels and will attempt to close any pooled gRPC channels and all registered GracefulInterface objects (for example token bearers). Background tasks started via bg_task are cancelled. Any exceptions raised during shutdown are logged.

Parameters
grace:optional floatOptional per-transport grace period passed to underlying channel close methods.
def create_address_channel(self, addr: str) -> AddressChannel: (source)

Create a new underlying gRPC channel for the given address.

The method composes options and interceptors, extracts known special options such as INSECURE and COMPRESSION, and then constructs either a secure or insecure gRPC channel wrapper. The returned object is an AddressChannel that pairs the gRPC channel with the resolved address string.

Parameters
addr:strResolved address string.
Returns
AddressChannelAn AddressChannel containing the created channel.
def discard_channel(self, chan: AddressChannel | None): (source)

Dispose of an AddressChannel by scheduling its close.

The close is performed asynchronously via bg_task to avoid blocking the caller.

Parameters
chan:AddressChannel | NoneThe AddressChannel to discard, or None.
Raises
ChannelClosedErrorIf the SDK channel has been closed.
def get_addr_by_method(self, method_name: str) -> str: (source)

Return the cached address for a fully-qualified RPC method name.

If the method-to-service mapping has not been seen before it is computed using service_from_method_name and resolved via get_addr_from_service_name. The result is cached to accelerate future lookups.

Parameters
method_name:strFull RPC method string ('/package.service/Method').
Returns
strResolved address string.
def get_addr_from_service_name(self, service_name: str) -> str: (source)

Resolve a logical service name into a transport address.

The method strips a leading dot (".") if present and delegates to the configured Resolver.

Parameters
service_name:strLogical service name as generated by stubs or conventions.
Returns
strResolved address string.
def get_addr_from_stub(self, service_stub_class: type[ServiceStub]) -> str: (source)

Resolve the concrete address for a generated service stub class.

Parameters
service_stub_class:type[ServiceStub]The generated gRPC stub class for a service.
Returns
strThe resolved address string used by the SDK to reach that service (for example 'host:port' or a resolver template expanded value).
def get_address_interceptors(self, addr: str) -> Sequence[ClientInterceptor]: (source)

Return the ordered list of interceptors to apply to a channel.

Global interceptors are applied first, then any per-address interceptors, and finally internal interceptors added by the channel implementation.

Parameters
addr:strResolved address string.
Returns
A sequence of ClientInterceptorCombined global and per-address interceptors.
def get_address_options(self, addr: str) -> ChannelArgumentType: (source)

Compute effective gRPC channel options for a specific address.

Global options are combined with per-address options and the SDK user-agent is appended via grpc.primary_user_agent.

Parameters
addr:strResolved address string.
Returns
list of tuple[str, Any]A sequence of channel option tuples ready to be passed to gRPC when creating a channel.
def get_authorization_provider(self) -> AuthorizationProvider | None: (source)

Return the configured AuthorizationProvider.

Returns
AuthorizationProvider or NoneThe authorization provider instance if any authorization mechanism was configured; otherwise None.
def get_channel_by_addr(self, addr: str) -> AddressChannel: (source)

Request an AddressChannel for the given resolved address.

The method returns a pooled channel if available; otherwise a new underlying gRPC channel is created. Pooled channels with state grpc.ChannelConnectivity.SHUTDOWN are closed asynchronously and skipped.

Parameters
addr:strResolved address string.
Returns
AddressChannelAn AddressChannel wrapper for a gRPC channel.
Raises
ChannelClosedErrorIf the SDK channel has already been closed.
def get_channel_by_method(self, method_name: str) -> AddressChannel: (source)

Convenience to obtain an AddressChannel for an RPC method name. The method resolves the address via get_addr_by_method and then calls get_channel_by_addr to obtain the channel.

Parameters
method_name:strFull RPC method string.
Returns
AddressChannelAn AddressChannel bound to the resolved address.
def get_corresponding_operation_service(self, service_stub_class: type[ServiceStub]) -> OperationServiceStub: (source)

Return an operations service stub for the same address as a generated service stub.

Many long-running operations are associated with the service that initiated them. This helper resolves the service address for the provided generated stub class and returns an instantiated OperationServiceStub bound to the transport channel for that address.

Parameters
service_stub_class:type[ServiceStub]Generated gRPC service stub class (the SDK service descriptor type).
Returns
OperationServiceStubAn operations service stub bound to the same backend used by the provided service.
def get_corresponding_operation_service_alpha(self, service_stub_class: type[ServiceStub]) -> OperationServiceStubDeprecated: (source)

Compatibility helper returning the alpha-version operations service stub for the same address as a generated service stub.

See get_corresponding_operation_service for details. This method returns the older alpha operations stub for callers that need to interoperate with legacy server implementations.

def get_state(self, try_to_connect: bool = False) -> ChannelConnectivity: (source)

Nebius Python SDK channels are always ready unless closed.

Parameters
try_to_connect:boolIgnored parameter to satisfy the gRPC Channel interface.
Returns
grpc.ChannelConnectivitygrpc.ChannelConnectivity.READY if the channel is open, grpc.ChannelConnectivity.SHUTDOWN if closed.
async def get_token(self, timeout: float | None, options: dict[str, str] | None = None) -> Token: (source)

Asynchronously fetch an authorization Token.

This helper delegates to the configured token bearer and performs any necessary refresh or exchange logic implemented by the bearer, if any was configured. If no bearer was configured, the method raises SDKError.

Parameters
timeout:optional floatMaximum time in seconds to wait for a token. If None the operation may block indefinitely according to the bearer semantics.
options:optional dict[str, str]Optional mapping of string options passed to the underlying token receiver.
Returns
TokenA Token instance containing the access token.
Raises
SDKErrorIf no token bearer was configured on the channel.
def get_token_sync(self, timeout: float | None, options: dict[str, str] | None = None) -> Token: (source)

Synchronously fetch an authorization Token.

This method is a convenience wrapper around get_token that runs the async fetch on the channel's owned event loop and blocks the calling thread until the token is available or the timeout expires.

A small grace period is added to the supplied timeout to allow the internal token bearer shutdown logic to complete during immediate handoff.

Parameters
timeout:optional floatMaximum time in seconds to wait for a token; may be None to wait indefinitely.
options:optional dict[str, str]Optional mapping of string options passed to the underlying token receiver.
Returns
TokenA Token instance.
Raises
TimeoutErrorIf the token could not be obtained within the supplied timeout.
def parent_id(self) -> str | None: (source)

Return the channel-wide default parent ID used for certain requests.

Some SDK methods automatically populate a parent_id field when missing using this channel-level default. The value may be None if not configured.

Returns
str | NoneThe configured parent ID or None.
def return_channel(self, chan: AddressChannel | None): (source)

Return an AddressChannel to the internal pool.

Channels returned to the pool will be reused by subsequent get_channel_by_addr calls up to the configured max_free_channels_per_address limit. Channels that are shut down or exceed the pool size are closed asynchronously.

Parameters
chan:AddressChannel | NoneThe AddressChannel to return, or None.
Raises
ChannelClosedErrorIf the SDK channel has been closed.
def run_sync(self, awaitable: Awaitable[T], timeout: float | None = None) -> T: (source)

Run an awaitable to completion on the channel's event loop.

This helper supports two usage patterns:

  • If the channel was initialized with an explicit event loop, the awaitable will be scheduled on that loop and this function may be safely called from another thread.
  • If the channel has no provided loop, an internal loop is created or reused and run_until_complete is used. Calling this from a running loop without providing a separate loop raises LoopError.
Parameters
awaitable:Awaitable[T]The awaitable to run to completion.
timeout:optional floatOptional wall-clock timeout in seconds. If provided and the awaitable does not complete within the timeout a TimeoutError is raised.
Returns
TThe awaitable's result.
Raises
LoopErrorWhen called synchronously inside a running loop and no separate event loop was provided at construction.
def stream_stream(self, method: str, request_serializer: SerializingFunction | None = None, response_deserializer: DeserializingFunction | None = None) -> StreamStreamMultiCallable: (source)

Nebius Python SDK does not support streaming RPCs.

Raises
NotImplementedError
def stream_unary(self, method: str, request_serializer: SerializingFunction | None = None, response_deserializer: DeserializingFunction | None = None) -> StreamUnaryMultiCallable: (source)

Nebius Python SDK does not support streaming RPCs.

Raises
NotImplementedError
def sync_close(self, timeout: float | None = None): (source)

Synchronously close the channel and wait for graceful shutdown.

This is a convenience wrapper around close that blocks until the shutdown completes or the optional timeout elapses.

Parameters
timeout:optional floatOptional timeout in seconds for the shutdown.
Raises
TimeoutErrorIf the shutdown did not complete within the supplied timeout.
def unary_stream(self, method: str, request_serializer: SerializingFunction | None = None, response_deserializer: DeserializingFunction | None = None) -> UnaryStreamMultiCallable[Req, Res]: (source)

Nebius Python SDK does not support streaming RPCs.

Raises
NotImplementedError
def unary_unary(self, method_name: str, request_serializer: SerializingFunction | None = None, response_deserializer: DeserializingFunction | None = None) -> UnaryUnaryMultiCallable[Req, Res]: (source)

A method to support using SDK channel as gRPC Channel.

Parameters
method_name:strFull RPC method string, i.e., '/package.service/method'.
request_serializer:SerializingFunction | NoneA function that serializes a request message to bytes.
response_deserializer:DeserializingFunction | NoneA function that deserializes a response message from bytes.
Returns
NebiusUnaryUnaryMultiCallable wrapper.A UnaryUnaryMultiCallable object that can be used to make the call.
async def wait_for_state_change(self, last_observed_state: ChannelConnectivity): (source)

Nebius Python SDK channels are always ready unless closed. This method is provided to satisfy the gRPC Channel interface.

Raises
NotImplementedError
user_agent = (source)

The user-agent string used by channels created by this Channel instance.

_address_interceptors = (source)

Undocumented

_address_options = (source)

Undocumented

_authorization_provider: AuthorizationProvider | None = (source)

Undocumented

Undocumented

_event_loop = (source)

Undocumented

_free_channels = (source)

Undocumented

_global_interceptors: list[ClientInterceptor] = (source)

Undocumented

_global_interceptors_inner: list[ClientInterceptor] = (source)

Undocumented

_global_options = (source)

Undocumented

_gracefuls = (source)

Undocumented

_max_free_channels_per_address = (source)

Undocumented

_methods = (source)

Undocumented

_parent_id = (source)

Undocumented

Undocumented

Undocumented

_tls_credentials = (source)

Undocumented

_token_bearer: TokenBearer | None = (source)

Undocumented