network

Subpackage to connect to a Brayns service instance (backend).

An instance is a wrapper around a websocket connection and a JSON-RPC context.

It provides functionalities to send JSON-RPC requests and receive replies with a Brayns instance.

errors

exception ConnectionClosedError(reason: str)

Bases: WebSocketError

Raised when doing operation on a disconnected instance.

Happens after the connection to an instance.

reason: str
exception InvalidServerCertificateError(reason: str)

Bases: WebSocketError

Raised when the server certificate is rejected by the client.

SSL specific error happening during the connection to an instance.

reason: str
exception ProtocolError(reason: str)

Bases: WebSocketError

Raised when a websocket protocol error occurs.

Usually happens during the connection to an instance.

reason: str
exception ServiceUnavailableError(reason: str)

Bases: WebSocketError

Raised when braynsService instance is not available at given URI.

Occurs when the backend instance is not ready or started.

Can be used to try multiple connections to wait for an instance to be ready.

reason: str
exception WebSocketError(reason: str)

Bases: Error

Base class of all network exceptions.

Parameters:

reason (str) – Short description of what happened.

reason: str

connector

class Connector(uri: str, ssl_context: SslClientContext | None = None, logger: logging.Logger = <factory>, max_attempts: int | None = 1, attempt_period: float = 0.1)

Bases: object

Used to connect to a braynsService instance.

A connector must at least have the URI the braynsService instance was started with.

URI is always in format host:port, wss:// or ws:// will be added depending if an SSL context is provided (SSL is disabled if context is None).

SSL context can be provided for a secure connection. If the instance uses a certificate signed by a CA installed on the local machine, the default value of brayns.SslClientContext() can be used. Otherwise, the CA file or path must be provided in the SSL context constructor.

Binary messages received from the instance are not JSON-RPC requests but can be handled using an optional callback (see binary_handler).

If you don’t know when your instance of braynsService will be ready when you call connect(), you can set max_attempts to None to try to connect in loop until it works (or with a maximum count and a delay to have a timeout).

Parameters:
  • uri (str) – Instance URI with format ‘host:port’.

  • ssl_context (SslClientContext | None, optional) – SSL context if secure, defaults to None.

  • logger (logging.Logger, optional) – Instance logger, defaults to brayns.Logger().

  • max_attempts (int | None, optional) – Max connection attempts, defaults to 1.

  • attempt_period (float, optional) – Delay in seconds between attempts, defaults to 0.1.

attempt_period: float = 0.1
connect() Instance

Connect to instance and return it.

Try to connect max_attempts times waiting attempt_period between two attempts. If it fails, ServiceUnavailableError will be raised.

:raises WebSocketError :return: Connected braynsService instance. :rtype: Instance

logger: logging.Logger
max_attempts: int | None = 1
ssl_context: SslClientContext | None = None
uri: str

future

class Future(future: JsonRpcFuture, reply_handler: Callable[[JsonRpcReply], T])

Bases: Generic[T]

JSON-RPC future wrapper to include the reply processing.

Add a new method wait_for_result to retreive the result of the reply processing.

cancel() None
get_progress() JsonRpcProgress
has_progress() bool
is_ready() bool
poll(block: bool) None
wait_for_reply() JsonRpcReply
wait_for_result() T

instance

class Instance(*args, **kwargs)

Bases: Protocol

Object used to interact with a connected instance of the backend.

Contains the connection state with a backend instance and provide methods to interact with it.

An instance is a running process of braynsService executable that runs a websocket server and performs the rendering tasks.

The backend instance can be running on the local machine or a remote one.

Once finished using an instance, user must call disconnect() on it or use its context manager to do it automatically when it goes out of scope.

The recommended way of doing this is the context manager because it is safe regarding exceptions (ie with instance: …).

If a websocket communication error occurs, a WebSocketError is raised.

If a JSON-RPC error message is replied, a RequestError is raised.

For non-blocking requests, the future is iterable and yield RequestProgess objects. Call wait_for_result() to wait for the result.

cancel(id: int | str) None

Cancel request with given ID.

Send a cancellation request to the instance for a given task.

Parameters:

id (int | str) – JSON-RPC request ID.

Raises:

RequestError – Task is not running.

property connected: bool

Check if the instance is connected.

Returns:

Connection state.

Return type:

bool

disconnect() None

Disconnect instance (mandatory once done with it).

execute(method: str, params: Any | None = None, binary: bytes = b'') JsonRpcReply

Extended version of request to accept and return binary data.

Parameters:
  • method (str) – JSON-RPC method.

  • params (Any, optional) – JSON-RPC params, defaults to None

  • binary (bytes, optional) – Binary data to send with the request, defaults to b’’

Returns:

JSON-RPC result and binary data received with the reply.

Return type:

tuple[Any, bytes]

is_running(id: int | str) bool

Check if the request with the given ID is running.

Parameters:

id (int | str) – JSON-RPC request ID.

Returns:

Running state.

Return type:

bool

poll(block: bool) None

Check if messages are received from the instance.

When a message is received, it will update all existing futures.

The futures call this method in blocking mode when iterated.

Parameters:

block (bool) – Wait until a message is received if True.

request(method: str, params: Any | None = None) Any

Send a request to the instance and wait its result.

Generate automatically the JSON-RPC ID using integers.

Parameters:
  • method (str) – JSON-RPC method (entrypoint name).

  • params (Any, optional) – JSON-RPC params, defaults to None

Returns:

JSON-RPC result.

Return type:

Any

send(request: JsonRpcRequest) JsonRpcFuture

Send a request in a non blocking way.

This method is the most basic one, it doesn’t generate any ID and can be used asynchronously (doesn’t block until result is received).

Parameters:

request (JsonRpcRequest) – JSON-RPC request to send.

Returns:

Future object to monitor the request.

Return type:

RequestFuture

task(method: str, params: Any | None = None, binary: bytes = b'') JsonRpcFuture

Send a request to the instance in a non-blocking way.

Generate automatically the JSON-RPC ID using integers.

Use the future returned to wait for progresses or results.

Parameters:
  • method (str) – JSON-RPC method.

  • params (Any, optional) – JSON-RPC params, defaults to None

Returns:

Future object to monitor the request.

Return type:

RequestFuture

json_rpc_error

exception JsonRpcError(id: int | str | None, code: int, message: str, data: Any = None)

Bases: Exception

Error raised by an instance when a request fails.

Parameters:
  • id (int | str | None) – ID of the request sending the error. None for global errors with no requests attached (like invalid JSON).

  • code (int) – Error code.

  • message (str) – Error description.

  • data (Any, optional) – Optional additional error information, defaults to None.

code: int
data: Any = None
static general(message: str) JsonRpcError
id: int | str | None
message: str

json_rpc_future

class JsonRpcFuture(task: JsonRpcTask, cancel: Callable[[], None], poll: Callable[[bool], None])

Bases: object

Future used to monitor a running JSON-RPC request.

Can be iterated to yield JsonRpcProgress if the request send any.

Use wait_for_reply to wait and get the reply or raise the error.

Use poll to refresh the state of the request.

Use cancel to send a message to cancel the request.

Future ready and progress state can also be queried.

cancel() None
static from_reply(reply: JsonRpcReply) JsonRpcFuture
get_progress() JsonRpcProgress
has_progress() bool
is_ready() bool
poll(block: bool) None
wait_for_reply() JsonRpcReply

json_rpc_progress

class JsonRpcProgress(id: int | str, operation: str, amount: float)

Bases: object

Request progress info.

Parameters:
  • id (int | str) – Request ID.

  • operation (str) – Description of the current task.

  • amount (float) – Progress amount [0-1].

amount: float
id: int | str
operation: str

json_rpc_reply

class JsonRpcReply(id: int | str | None, result: Any = None, binary: bytes = b'')

Bases: object

Reply received from a request sent to a brayns instance.

Parameters:
  • id (int | str) – ID of the corresponding request.

  • result (Any, optional) – Reply result (usually objects), defaults to None.

  • binary (bytes, optional) – Reply binary data, defaults to empty bytes.

binary: bytes = b''
static for_notifications() JsonRpcReply
id: int | str | None
result: Any = None

json_rpc_request

class JsonRpcRequest(id: int | str | None, method: str, params: Any = None, binary: bytes = b'')

Bases: object

Request to send to a running instance of brayns service.

Parameters:
  • id (int | str | None) – Request ID to monitor the request. No replies will be received if set to None.

  • method (str) – JSON-RPC method.

  • params (Any, optional) – Request parameters (usually objects), defaults to None.

  • binary (bytes, optional) – Request binary data, defaults to empty bytes.

binary: bytes = b''
id: int | str | None
method: str
params: Any = None

logger

class Logger(level: int = 30)

Bases: Logger

Brayns default logger.

Log to stdout with simple formatting (name, level, message).

Can be used to change only the log level without creating a new logger.

Parameters:

level (int, optional) – Log level from logging module, defaults to WARN.

Initialize the logger with a name and an optional level.

web_socket_connector

class SslClientContext(cafile: 'str | None' = None, capath: 'str | None' = None, cadata: 'str | None' = None)

Bases: object

cadata: str | None = None
cafile: str | None = None
capath: str | None = None