class Channel(ChannelBase): (source)
Known subclasses: nebius.sdk.SDK
Constructor: Channel(resolver, substitutions, user_agent_prefix, domain, ...)
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_tokenandget_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
LoopErroris 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 | |
| resolver | Optional 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. |
| substitutions | Optional 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 | Optional 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)". |
| domain | Optional 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. |
| options | Global channel options passed to gRPC when creating address channels. This should follow the ChannelArgumentType shape (sequence of key/value tuples). |
| interceptors | Global 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 | Optional 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 | Optional 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:
Unsupported types raise |
| service | Service 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 | Public 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 | Path 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 | Path 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 | Optional 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 | Optional 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 | Optional 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 | Number 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 | Optional 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 | Optional file-like writer passed to the config reader to display the URL for federation authentication during interactive credential acquisition. |
| federation | When 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 |
Run a coroutine in the background and log uncaught exceptions. |
| Async Method | channel |
Channel is always ready, nothing to do here. |
| Async Method | close |
Gracefully close the channel and all associated background work. |
| Method | create |
Create a new underlying gRPC channel for the given address. |
| Method | discard |
Dispose of an AddressChannel by scheduling its close. |
| Method | get |
Return the cached address for a fully-qualified RPC method name. |
| Method | get |
Resolve a logical service name into a transport address. |
| Method | get |
Resolve the concrete address for a generated service stub class. |
| Method | get |
Return the ordered list of interceptors to apply to a channel. |
| Method | get |
Compute effective gRPC channel options for a specific address. |
| Method | get |
Return the configured AuthorizationProvider. |
| Method | get |
Request an AddressChannel for the given resolved address. |
| Method | get |
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 |
Return an operations service stub for the same address as a generated service stub. |
| Method | get |
Compatibility helper returning the alpha-version operations service stub for the same address as a generated service stub. |
| Method | get |
Nebius Python SDK channels are always ready unless closed. |
| Async Method | get |
Asynchronously fetch an authorization Token. |
| Method | get |
Synchronously fetch an authorization Token. |
| Method | parent |
Return the channel-wide default parent ID used for certain requests. |
| Method | return |
Return an AddressChannel to the internal pool. |
| Method | run |
Run an awaitable to completion on the channel's event loop. |
| Method | stream |
Nebius Python SDK does not support streaming RPCs. |
| Method | stream |
Nebius Python SDK does not support streaming RPCs. |
| Method | sync |
Synchronously close the channel and wait for graceful shutdown. |
| Method | unary |
Nebius Python SDK does not support streaming RPCs. |
| Method | unary |
A method to support using SDK channel as gRPC Channel. |
| Async Method | wait |
Nebius Python SDK channels are always ready unless closed. This method is provided to satisfy the gRPC Channel interface. |
| Instance Variable | user |
The user-agent string used by channels created by this Channel instance. |
| Instance Variable | _address |
Undocumented |
| Instance Variable | _address |
Undocumented |
| Instance Variable | _authorization |
Undocumented |
| Instance Variable | _closed |
Undocumented |
| Instance Variable | _event |
Undocumented |
| Instance Variable | _free |
Undocumented |
| Instance Variable | _global |
Undocumented |
| Instance Variable | _global |
Undocumented |
| Instance Variable | _global |
Undocumented |
| Instance Variable | _gracefuls |
Undocumented |
| Instance Variable | _max |
Undocumented |
| Instance Variable | _methods |
Undocumented |
| Instance Variable | _parent |
Undocumented |
| Instance Variable | _resolver |
Undocumented |
| Instance Variable | _tasks |
Undocumented |
| Instance Variable | _tls |
Undocumented |
| Instance Variable | _token |
Undocumented |
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.
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 | |
SDKError | Raised for unsupported credential types or if parent_id is an explicitly empty string. |
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[ | An awaitable object to run in the background. |
| Returns | |
Task[ | The created asyncio.Task. |
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 float | Optional per-transport grace period passed to underlying channel close methods. |
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:str | Resolved address string. |
| Returns | |
AddressChannel | An AddressChannel containing the created channel. |
Dispose of an AddressChannel by scheduling its close.
The close is performed asynchronously via bg_task to avoid
blocking the caller.
| Parameters | |
chan:AddressChannel | None | The AddressChannel to discard, or None. |
| Raises | |
ChannelClosedError | If the SDK channel has been closed. |
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 | |
methodstr | Full RPC method string ('/package.service/Method'). |
| Returns | |
| str | Resolved address string. |
Resolve the concrete address for a generated service stub class.
| Parameters | |
servicetype[ | The generated gRPC stub class for a service. |
| Returns | |
| str | The resolved address string used by the SDK to reach that service (for example 'host:port' or a resolver template expanded value). |
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:str | Resolved address string. |
| Returns | |
A sequence of ClientInterceptor | Combined global and per-address interceptors. |
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:str | Resolved address string. |
| Returns | |
| list of tuple[str, Any] | A sequence of channel option tuples ready to be passed to gRPC when creating a channel. |
Return the configured AuthorizationProvider.
| Returns | |
AuthorizationProvider or None | The authorization provider instance if any authorization mechanism was configured; otherwise None. |
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:str | Resolved address string. |
| Returns | |
AddressChannel | An AddressChannel wrapper for a gRPC channel. |
| Raises | |
ChannelClosedError | If the SDK channel has already been closed. |
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 | |
methodstr | Full RPC method string. |
| Returns | |
AddressChannel | An AddressChannel bound to the resolved address. |
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 | |
servicetype[ | Generated gRPC service stub class (the SDK service descriptor type). |
| Returns | |
OperationServiceStub | An operations service stub bound to the same backend used by the provided service. |
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.
Nebius Python SDK channels are always ready unless closed.
| Parameters | |
| try | Ignored parameter to satisfy the gRPC Channel interface. |
| Returns | |
grpc.ChannelConnectivity | grpc.ChannelConnectivity.READY if the channel is open,
grpc.ChannelConnectivity.SHUTDOWN if closed. |
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 float | Maximum 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 | |
Token | A Token instance containing the access token. |
| Raises | |
SDKError | If no token bearer was configured on the channel. |
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 float | Maximum 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 | |
Token | A Token instance. |
| Raises | |
TimeoutError | If the token could not be obtained within the supplied timeout. |
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 | None | The configured parent ID or None. |
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 | None | The AddressChannel to return, or None. |
| Raises | |
ChannelClosedError | If the SDK channel has been closed. |
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[ | The awaitable to run to completion. |
| timeout:optional float | Optional wall-clock timeout in seconds. If provided
and the awaitable does not complete within the timeout a
TimeoutError is raised. |
| Returns | |
T | The awaitable's result. |
| Raises | |
LoopError | When called synchronously inside a running loop and no separate event loop was provided at construction. |
str, request_serializer: SerializingFunction | None = None, response_deserializer: DeserializingFunction | None = None) -> StreamStreamMultiCallable:
(source)
¶
Nebius Python SDK does not support streaming RPCs.
| Raises | |
NotImplementedError | |
str, request_serializer: SerializingFunction | None = None, response_deserializer: DeserializingFunction | None = None) -> StreamUnaryMultiCallable:
(source)
¶
Nebius Python SDK does not support streaming RPCs.
| Raises | |
NotImplementedError | |
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 float | Optional timeout in seconds for the shutdown. |
| Raises | |
TimeoutError | If the shutdown did not complete within the supplied timeout. |
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 | |
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 | Full RPC method string, i.e., '/package.service/method'. |
| request | A function that serializes a request message to bytes. |
| response | A function that deserializes a response message from bytes. |
| Returns | |
NebiusUnaryUnaryMultiCallable wrapper. | A UnaryUnaryMultiCallable object that can be used to make
the call. |
Nebius Python SDK channels are always ready unless closed. This method is provided to satisfy the gRPC Channel interface.
| Raises | |
NotImplementedError | |