Python API reference#

pw_rpc2: Next gen, zero-copy async RPC with end-to-end backpressure

Generated API reference for the pw_rpc2 Python package (//pw_rpc2/py:pw_rpc2). For usage guides and examples, see Python client.

pw_rpc2#

Python client for pw_rpc2.

Client is a synchronous, thread-safe client; pw_rpc2.aio.Client is its asyncio counterpart.

Client and services#

class pw_rpc2.Client(
socket: ReliableSocket,
protos: Iterable[ModuleType | FileDescriptor | ServiceDescriptor] = (),
*,
default_timeout: float | None = None,
handshake_timeout: float = 5.0,
)#

A synchronous client for a pw_rpc2 server.

The client owns its ReliableSocket; closing the client closes the socket and ends any active calls with CLOSED. A background thread receives packets from the server.

__init__(
socket: ReliableSocket,
protos: Iterable[ModuleType | FileDescriptor | ServiceDescriptor] = (),
*,
default_timeout: float | None = None,
handshake_timeout: float = 5.0,
) → None#

Performs the server handshake over socket.

Parameters:
  • socket – A connected ReliableSocket, which the client takes ownership of.

  • protos – Generated protobuf modules or descriptors of the services to create service clients for.

  • default_timeout – The default for how long operations wait for a response from the server, in seconds; None waits forever.

  • handshake_timeout – How long to wait for the server to reply to the connection handshake, in seconds.

Raises:
  • HandshakeError – The server did not complete the handshake.

  • TypeError – Something in protos does not describe services.

  • ValueError – Services or methods with different names have the same ID, a service and a package share a name, or a timeout is negative.

add_services(
protos: Iterable[ModuleType | FileDescriptor | ServiceDescriptor],
) → None#

Creates service clients for more services.

A service with the same name as an existing service replaces it.

Raises:
  • TypeError – Something in protos does not describe services.

  • ValueError – Services or methods with different names have the same ID, or a service and a package share a name.

close() → None#

Closes the connection, ending all active calls with CLOSED.

property closed: bool#

True if the connection is closed, by either endpoint.

property default_timeout: float | None#

How long operations wait for a response by default, in seconds.

None waits forever.

methods() → Iterator[MethodClient]#

Yields every method client across all registered services.

property rpcs: Services[MethodClient]#

The service clients, e.g. client.rpcs.examples.Echo.

class pw_rpc2.Services(services: Iterable[ServiceClient[MethodClientT]] = ())#

RPC services, navigable by protobuf package.

Attribute access walks the package hierarchy (rpcs.examples.Echo). Services can also be looked up by their full name (rpcs['examples.Echo']), and iterating yields every service.

__init__(services: Iterable[ServiceClient[MethodClientT]] = ()) → None#
class pw_rpc2.Package(name: str)#

A protobuf package, whose services and subpackages are attributes.

__init__(name: str) → None#
class pw_rpc2.ServiceClient(
service: Service,
make_method: Callable[[Method], MethodClientT],
)#

The method clients of a service, accessible as attributes or by name.

__init__(
service: Service,
make_method: Callable[[Method], MethodClientT],
) → None#
property descriptor: ServiceDescriptor#

The protobuf ServiceDescriptor for this service.

property full_name: str#

The service’s fully qualified name, e.g. 'examples.Echo'.

property name: str#

The service’s unqualified protobuf name, e.g. 'Echo'.

property package: str#

The service’s protobuf package name, e.g. 'examples'.

class pw_rpc2.MethodClient(client: Client, method: Method)#

Invokes an RPC method.

For unary methods, calling the method client waits for and returns the response. For streaming methods, it starts the RPC and returns its call object.

Requests are given either as a message or as keyword arguments for the request’s fields:

echo.Echo(EchoMessage(msg='hello'))
echo.Echo(msg='hello')

The rpc2_timeout keyword argument sets the call’s timeout. It has a prefix so that it does not collide with a request field named timeout; a field named rpc2_timeout can only be set by passing a message.

__call__(
request: Message | None = None,
/,
*,
rpc2_timeout: float | None = None,
**fields: Any,
) → Any#

Calls the RPC: returns the response (unary) or call (streaming).

__init__(client: Client, method: Method) → None#
property descriptor: MethodDescriptor#

The protobuf MethodDescriptor for this method.

property full_name: str#

The method’s fully qualified name, e.g. 'examples.Echo.Echo'.

invoke(
request: Message | None = None,
/,
*,
rpc2_timeout: float | None = None,
**fields: Any,
) → Call#

Starts the RPC without waiting for a response.

Parameters:
  • request – The request message; streaming requests are instead sent with the call’s write() method.

  • rpc2_timeout – Default timeout for waiting on a response from the server, in seconds. None uses the client’s default.

  • **fields – Request fields, as an alternative to request.

Returns:

A call object whose type depends on the RPC type.

Raises:
  • TypeError – The request is invalid.

  • ValueError – A field name is not in the request type, the request is too large for the socket, or the timeout is negative.

  • DecodeError – A malformed packet closed the connection.

  • SocketClosed – The connection is closed.

property name: str#

The method’s unqualified protobuf name, e.g. 'Echo'.

property request: type[Message]#

The protobuf message class for this method’s requests.

property response: type[Message]#

The protobuf message class for this method’s responses.

property type: MethodType#

The method’s MethodType streaming mode.

class pw_rpc2.MethodType(*values)#

The streaming mode of an RPC method.

BIDIRECTIONAL_STREAMING = (True, True)#
CLIENT_STREAMING = (True, False)#
SERVER_STREAMING = (False, True)#
UNARY = (False, False)#
property client_streaming: bool#

True if the client sends a stream of requests.

property server_streaming: bool#

True if the server sends a stream of responses.

pw_rpc2.ProtoSource = module | google.protobuf.descriptor.FileDescriptor | google.protobuf.descriptor.ServiceDescriptor#

Represent a union type

E.g. for int | str

pw_rpc2.DEFAULT_HANDSHAKE_TIMEOUT = 5.0#

Convert a string or number to a floating-point number, if possible.

Calls#

class pw_rpc2.Call(state: CallState, timeout: float)#

Base class for handles to RPCs.

Using a call as a context manager cancels it on exit if it is still active, which ensures that the server does not keep working on a call that the client abandoned:

with service.StreamThings() as stream:
    for thing in stream:
        if is_what_i_wanted(thing):
            break  # The call is cancelled here.
__init__(state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

class pw_rpc2.Reader(state: CallState, timeout: float)#

A call that receives a stream of responses.

Both ServerStreamingCall and BidirectionalStreamingCall are readers, so functions that only consume responses can annotate their parameter as Reader.

__init__(state: CallState, timeout: float) → None#
__iter__() → Iterator[Any]#

Yields responses until the server finishes the stream.

Each response is subject to the call’s default timeout.

cancel() → bool#

Cancels the call, notifying the server.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

read(timeout: float | None = None) → Any | None#

Waits for the next response.

Returns:

The next response, or None if the server finished the stream.

Raises:
  • RpcError – The call failed with a protocol error.

  • RpcTimeout – No response arrived in time.

  • DecodeError – The response or an incoming packet was malformed.

  • SocketClosed – The connection was lost.

property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

class pw_rpc2.Writer(state: CallState, timeout: float)#

A call that sends a stream of requests.

Both ClientStreamingCall and BidirectionalStreamingCall are writers, so functions that only send requests can annotate their parameter as Writer.

__init__(state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

write(request: Message | None = None, /, **fields: Any) → None#

Sends a request, given as a message or as keyword arguments.

Raises:
  • StreamClosedError – The call is already complete or the request stream is already finished.

  • ValueError – The request is too large for the socket.

  • RpcError – The call ended with a protocol error.

  • SocketClosed – The connection is closed.

class pw_rpc2.UnaryCall(state: CallState, timeout: float)#

A unary RPC.

Calling a unary method client waits for its response. Use invoke() to obtain a UnaryCall instead, for example to issue several RPCs before waiting on any.

__init__(state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

response(timeout: float | None = None) → Any#

Waits for and returns the response.

Raises:
property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

class pw_rpc2.ServerStreamingCall(state: CallState, timeout: float)#

A server streaming RPC.

Iterate over the call, or call read(), to receive responses.

__init__(state: CallState, timeout: float) → None#
__iter__() → Iterator[Any]#

Yields responses until the server finishes the stream.

Each response is subject to the call’s default timeout.

cancel() → bool#

Cancels the call, notifying the server.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

read(timeout: float | None = None) → Any | None#

Waits for the next response.

Returns:

The next response, or None if the server finished the stream.

Raises:
  • RpcError – The call failed with a protocol error.

  • RpcTimeout – No response arrived in time.

  • DecodeError – The response or an incoming packet was malformed.

  • SocketClosed – The connection was lost.

property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

class pw_rpc2.ClientStreamingCall(state: CallState, timeout: float)#

A client streaming RPC.

Send requests with write(), then call finish() to end the request stream and receive the response.

__init__(state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

finish(timeout: float | None = None) → Any#

Ends the request stream and waits for the response.

The server may respond before the request stream ends, in which case this returns that response. timeout applies to waiting for the response after sending the stream end.

Raises:
property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

write(request: Message | None = None, /, **fields: Any) → None#

Sends a request, given as a message or as keyword arguments.

Raises:
  • StreamClosedError – The call is already complete or the request stream is already finished.

  • ValueError – The request is too large for the socket.

  • RpcError – The call ended with a protocol error.

  • SocketClosed – The connection is closed.

class pw_rpc2.BidirectionalStreamingCall(state: CallState, timeout: float)#

A bidirectional streaming RPC.

Send requests with write() and receive responses with read() or by iterating. Call finish() once all requests are sent; the server may keep responding until it finishes the call.

__init__(state: CallState, timeout: float) → None#
__iter__() → Iterator[Any]#

Yields responses until the server finishes the stream.

Each response is subject to the call’s default timeout.

cancel() → bool#

Cancels the call, notifying the server.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

finish() → None#

Ends the request stream.

Raises:

StreamClosedError – The call is already complete or the request stream is already finished.

read(timeout: float | None = None) → Any | None#

Waits for the next response.

Returns:

The next response, or None if the server finished the stream.

Raises:
  • RpcError – The call failed with a protocol error.

  • RpcTimeout – No response arrived in time.

  • DecodeError – The response or an incoming packet was malformed.

  • SocketClosed – The connection was lost.

property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

write(request: Message | None = None, /, **fields: Any) → None#

Sends a request, given as a message or as keyword arguments.

Raises:
  • StreamClosedError – The call is already complete or the request stream is already finished.

  • ValueError – The request is too large for the socket.

  • RpcError – The call ended with a protocol error.

  • SocketClosed – The connection is closed.

Errors and status codes#

class pw_rpc2.RpcStatus(*values)#

The outcome of a pw_rpc2 operation, expressed as what the caller should do next.

Each code maps to one distinct action, so the code alone is enough to decide how to respond. The precise cause of an error is not part of the status: pw_rpc2 logs it where it is detected.

These codes are never sent on the wire. Endpoints exchange more precise error codes, which the receiver converts to one of these. The numeric values may change.

ABORTED = 8#

The server started the call, then ended it for a reason outside the method’s control. The method may have partly run.

Action: Retry only if the method is idempotent; otherwise, report the failure.

CANCELLED = 2#

Application code on either side ended the call, explicitly (with Cancel()) or implicitly (for example, by dropping a call handle).

Action: Stop work on the call. Don’t retry automatically: application logic chose to end it.

CLOSED = 3#

You closed the Client or Server, or the object you used is empty.

Action: Up to you; you closed this call.

DATA_ERROR = 11#

A message could not be encoded or decoded.

Action: Don’t resend the same message unchanged; fix it or the schema mismatch. What remains of the call depends on where the error occurred:

  • Local write: nothing was sent, and the call is still open.

  • Local read: that one message is dropped. A stream stays open, and the next read may succeed.

  • The server could not decode the request: the call is over.

DISCONNECTED = 5#

The connection is gone or could not be made, for a reason that a new connection can fix. Whether the peer processed in-flight calls is unknown.

Action: Create a new Client, with backoff. Retry in-flight calls only if they are idempotent. On a server, stop work on the call.

END_OF_STREAM = 1#

The peer finished its stream and every message it sent has been read. Not a failure. For a client, the RPC finished successfully.

Action: Stop reading.

MESSAGE_TOO_LARGE = 10#

An outbound message is larger than the transport or reservation allows. Nothing was sent, and the call is still open.

Action: Send a smaller message (for example, split it), or raise the reservation or transport limit.

OK = 0#

The operation succeeded.

Action: Continue.

PROTOCOL_ERROR = 12#

An endpoint broke the protocol, the endpoints’ protocol versions are incompatible, or an RPC implementation has a bug. If the error closed the connection, later calls on the same Client also report PROTOCOL_ERROR.

Action: Nothing fixes this at runtime: reconnecting and retrying won’t help. Log or report it; it needs a code or deployment fix.

RESOURCE_EXHAUSTED = 6#

This endpoint could not allocate memory for the operation. The peer was not involved.

Action: Free local resources (finish or drop other calls, or run fewer at once), then retry. Backing off against the server won’t help.

UNAVAILABLE = 7#

The server could not take the call right now. The method never ran.

Action: Retry later with backoff. Retrying is safe even for methods that are not idempotent.

UNIMPLEMENTED = 9#

The server does not offer this method in the form the client expects.

Action: Don’t retry against this server. Fall back (for example, to an older API or a feature-detected path), or fix the deployment or schema mismatch.

WRITE_CLOSED = 4#

This call’s outbound direction is closed. The call itself may still be open.

Action: Stop writing. If a response or more messages are expected, keep reading.

classmethod is_valid(value: int) → bool#

Returns whether the integer is a value of this enum.

ok() → bool#

Returns whether this is OK.

exception pw_rpc2.RpcError(
method: Method,
status: RpcStatus,
detail: str = '',
*,
protocol_error: ProtocolError | UnknownProtocolError | None = None,
)#

An RPC failed with an error status.

method#

The RPC that failed.

status#

The RpcStatus that ended the call.

detail#

A description of the failure, which may be empty.

__init__(
method: Method,
status: RpcStatus,
detail: str = '',
*,
protocol_error: ProtocolError | UnknownProtocolError | None = None,
) → None#
exception pw_rpc2.RpcTimeout(method: Method, timeout: float)#

An RPC operation did not complete before its timeout expired.

Timing out does not end the call, except for unary RPCs invoked by calling the method client directly, whose call object is never exposed.

method#

The RPC that timed out.

timeout#

The timeout that expired, in seconds.

__init__(method: Method, timeout: float) → None#
exception pw_rpc2.HandshakeError(message: str, status: RpcStatus = RpcStatus.PROTOCOL_ERROR)#

The connection handshake with the server failed.

status#

The RpcStatus for the failure: RpcStatus.DISCONNECTED if the socket closed during the handshake, or RpcStatus.PROTOCOL_ERROR if the server sent an invalid reply or did not complete the handshake in time.

__init__(message: str, status: RpcStatus = RpcStatus.PROTOCOL_ERROR) → None#
exception pw_rpc2.StreamClosedError#

The client’s request stream is already closed.

Raised when calling write() or BidirectionalStreamingCall.finish() after the request stream has already been finished or the call has completed.

status#

Always RpcStatus.WRITE_CLOSED.

Type:

pw_rpc2.rpc_code.RpcStatus

exception pw_rpc2.DecodeError(message: str, status: RpcStatus = RpcStatus.PROTOCOL_ERROR)#

The bytes are not a valid pw_rpc2 packet or protobuf message.

status#

The RpcStatus for the failure: RpcStatus.PROTOCOL_ERROR for a malformed packet, or RpcStatus.DATA_ERROR for a payload that could not be decoded as a protobuf message.

__init__(message: str, status: RpcStatus = RpcStatus.PROTOCOL_ERROR) → None#

Transports#

pw_rpc2.SocketClosed is re-exported from pw_transport.SocketClosed. Socket interfaces and implementations (pw_transport.ReliableSocket, pw_transport.framed_tcp, and pw_transport.forwarding_socket) are documented in the pw_transport Python reference.

pw_rpc2.aio#

An asyncio pw_rpc2 client.

This mirrors pw_rpc2.Client, with coroutines in place of blocking operations:

from pw_rpc2 import aio
from pw_transport import framed_tcp
from echo_pb import echo_pb2

async with await aio.Client.connect(
    lambda: framed_tcp.connect('localhost', 8000), [echo_pb2]
) as client:
    echo = client.rpcs.examples.Echo

    # Awaiting a unary method returns its response.
    print((await echo.Echo(msg='hello')).msg)

    # Server streaming methods return a call to iterate over.
    async with echo.Repeat(msg='hi', count=3) as call:
        async for response in call:
            print(response.msg)

    # Client streaming calls are written to, then finished.
    async with echo.Collect() as call:
        await call.write(msg='one')
        await call.write(msg='two')
        print((await call.finish()).msg)

    # Bidirectional streaming calls are written to and read from.
    async with echo.EchoStream() as call:
        await call.write(msg='ping')
        print((await call.read()).msg)
        await call.finish()

Starting a streaming RPC does not block, so streaming method clients return their call directly.

Cancelling a task that is awaiting a unary RPC, as in await echo.Echo(msg='hello'), cancels the RPC.

Cancelling a task that is awaiting an operation on a call, such as read(), write(), finish(), or response(), only stops the wait; it does not cancel the RPC. To cancel the RPC, leave the call’s async with block or call cancel(). A cancelled write() or finish() may still be sent, because a packet that is already being sent cannot be recalled, so asyncio.CancelledError does not mean that the server did not receive the request.

Client and services#

class pw_rpc2.aio.Client#

An asyncio client for a pw_rpc2 server.

Create clients with connect(); there is no public constructor, since connecting requires awaiting the handshake. The client owns its ReliableSocket; closing the client closes the socket and ends any active calls with CLOSED.

Packets are received on a background thread and delivered to the event loop, and sent from a dedicated thread so that socket backpressure never blocks the event loop.

__init__() → None#
add_services(
protos: Iterable[ModuleType | FileDescriptor | ServiceDescriptor],
) → None#

Creates service clients for more services.

A service with the same name as an existing service replaces it.

Raises:
  • TypeError – Something in protos does not describe services.

  • ValueError – Services or methods with different names have the same ID, or a service and a package share a name.

async close() → None#

Closes the connection, ending all active calls with CLOSED.

property closed: bool#

True if the connection is closed, by either endpoint.

async classmethod connect(
target: ReliableSocket | Callable[[], ReliableSocket],
protos: Iterable[ModuleType | FileDescriptor | ServiceDescriptor] = (),
*,
default_timeout: float | None = None,
handshake_timeout: float = 5.0,
) → Client#

Connects (if given a callable) and performs the server handshake.

Parameters:
  • target – A connected ReliableSocket (which the client takes ownership of) or a zero-argument callable returning one, which is called on a worker thread.

  • protos – Generated protobuf modules or descriptors of the services to create service clients for.

  • default_timeout – The default for how long operations wait for a response from the server, in seconds; None waits forever.

  • handshake_timeout – How long to wait for the server to reply to the connection handshake, in seconds.

Raises:
  • HandshakeError – The server did not complete the handshake.

  • OSError – Opening a socket through target failed.

  • TypeError – Something in protos does not describe services.

  • ValueError – Services or methods with different names have the same ID, a service and a package share a name, or a timeout is negative.

property default_timeout: float | None#

How long operations wait for a response by default, in seconds.

None waits forever.

methods() → Iterator[MethodClient]#

Yields every method client across all registered services.

property rpcs: Services[MethodClient]#

The service clients, e.g. client.rpcs.examples.Echo.

class pw_rpc2.aio.MethodClient(client: Client, method: Method)#

Invokes an RPC method.

For unary methods, calling the method client returns a coroutine that starts the RPC and produces the response. For streaming methods, it starts the RPC and returns its call.

The rpc2_timeout keyword argument sets the call’s timeout. It has a prefix so that it does not collide with a request field named timeout; a field named rpc2_timeout can only be set by passing a message.

__call__(
request: Message | None = None,
/,
*,
rpc2_timeout: float | None = None,
**fields: Any,
) → Any#

Returns a response coroutine (unary) or call handle (streaming).

__init__(client: Client, method: Method) → None#
property descriptor: MethodDescriptor#

The protobuf MethodDescriptor for this method.

property full_name: str#

The method’s fully qualified name, e.g. 'examples.Echo.Echo'.

invoke(
request: Message | None = None,
/,
*,
rpc2_timeout: float | None = None,
**fields: Any,
) → Call#

Starts the RPC without waiting for a response.

This never blocks: the packet that starts the RPC is sent in the background. If sending it fails, the call ends with the error, which the call’s next operation (e.g. read(), write(), or response()) raises.

Parameters:
  • request – The request message; streaming requests are instead sent with the call’s write() method.

  • rpc2_timeout – Default timeout for waiting on a response from the server, in seconds. None uses the client’s default.

  • **fields – Request fields, as an alternative to request.

Returns:

A call object whose type depends on the RPC type.

Raises:
  • TypeError – The request is invalid.

  • ValueError – A field name is not in the request type, the request is too large for the socket, or the timeout is negative.

  • DecodeError – A malformed packet closed the connection.

  • SocketClosed – The connection was already closed.

property name: str#

The method’s unqualified protobuf name, e.g. 'Echo'.

property request: type[Message]#

The protobuf message class for this method’s requests.

property response: type[Message]#

The protobuf message class for this method’s responses.

property type: MethodType#

The method’s MethodType streaming mode.

Calls#

class pw_rpc2.aio.Call(client: Client, state: CallState, timeout: float)#

Base class for handles to RPCs.

Using a call as an async context manager cancels it on exit if it is still active.

__init__(client: Client, state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server in the background.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

class pw_rpc2.aio.Reader(client: Client, state: CallState, timeout: float)#

A call that receives a stream of responses.

Both ServerStreamingCall and BidirectionalStreamingCall are readers, so functions that only consume responses can annotate their parameter as Reader.

async __aiter__() → AsyncIterator[Any]#

Yields responses until the server finishes the stream.

Each response is subject to the call’s default timeout.

__init__(client: Client, state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server in the background.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

async read(timeout: float | None = None) → Any | None#

Waits for the next response.

Returns:

The next response, or None if the server finished the stream.

Raises:
  • RpcError – The call failed with a protocol error.

  • RpcTimeout – No response arrived in time.

  • DecodeError – The response or an incoming packet was malformed.

  • SocketClosed – The connection was lost.

property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

class pw_rpc2.aio.Writer(client: Client, state: CallState, timeout: float)#

A call that sends a stream of requests.

Both ClientStreamingCall and BidirectionalStreamingCall are writers, so functions that only send requests can annotate their parameter as Writer.

__init__(client: Client, state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server in the background.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

async write(request: Message | None = None, /, **fields: Any) → None#

Sends a request, given as a message or as keyword arguments.

If the awaiting task is cancelled, the request may still be sent.

Raises:
  • StreamClosedError – The call is already complete or the request stream is already finished.

  • ValueError – The request is too large for the socket.

  • RpcError – The call ended with a protocol error.

  • SocketClosed – The connection is closed.

class pw_rpc2.aio.UnaryCall(client: Client, state: CallState, timeout: float)#

A unary RPC, as returned by MethodClient.invoke().

__init__(client: Client, state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server in the background.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

async response(timeout: float | None = None) → Any#

Waits for and returns the response.

Raises:
property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

class pw_rpc2.aio.ServerStreamingCall(client: Client, state: CallState, timeout: float)#

A server streaming RPC; iterate over it to receive responses.

async __aiter__() → AsyncIterator[Any]#

Yields responses until the server finishes the stream.

Each response is subject to the call’s default timeout.

__init__(client: Client, state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server in the background.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

async read(timeout: float | None = None) → Any | None#

Waits for the next response.

Returns:

The next response, or None if the server finished the stream.

Raises:
  • RpcError – The call failed with a protocol error.

  • RpcTimeout – No response arrived in time.

  • DecodeError – The response or an incoming packet was malformed.

  • SocketClosed – The connection was lost.

property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

class pw_rpc2.aio.ClientStreamingCall(client: Client, state: CallState, timeout: float)#

A client streaming RPC.

Send requests with write(), then await finish() to end the request stream and receive the response.

__init__(client: Client, state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server in the background.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

async finish(timeout: float | None = None) → Any#

Ends the request stream and waits for the response.

The server may respond before the request stream ends, in which case this returns that response. timeout applies to waiting for the response after sending the stream end.

Raises:
property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

async write(request: Message | None = None, /, **fields: Any) → None#

Sends a request, given as a message or as keyword arguments.

If the awaiting task is cancelled, the request may still be sent.

Raises:
  • StreamClosedError – The call is already complete or the request stream is already finished.

  • ValueError – The request is too large for the socket.

  • RpcError – The call ended with a protocol error.

  • SocketClosed – The connection is closed.

class pw_rpc2.aio.BidirectionalStreamingCall(client: Client, state: CallState, timeout: float)#

A bidirectional streaming RPC.

Send requests with write() and receive responses with read() or by iterating. Await finish() once all requests are sent.

async __aiter__() → AsyncIterator[Any]#

Yields responses until the server finishes the stream.

Each response is subject to the call’s default timeout.

__init__(client: Client, state: CallState, timeout: float) → None#
cancel() → bool#

Cancels the call, notifying the server in the background.

Returns:

True if the call was cancelled; False if it had already completed.

property completed: bool#

True once the call has ended, successfully or not.

async finish() → None#

Ends the request stream.

Raises:

StreamClosedError – The call is already complete or the request stream is already finished.

async read(timeout: float | None = None) → Any | None#

Waits for the next response.

Returns:

The next response, or None if the server finished the stream.

Raises:
  • RpcError – The call failed with a protocol error.

  • RpcTimeout – No response arrived in time.

  • DecodeError – The response or an incoming packet was malformed.

  • SocketClosed – The connection was lost.

property status: RpcStatus | None#

The RpcStatus, or None while active.

A call that ended due to a local error, such as a lost connection, has no status.

async write(request: Message | None = None, /, **fields: Any) → None#

Sends a request, given as a message or as keyword arguments.

If the awaiting task is cancelled, the request may still be sent.

Raises:
  • StreamClosedError – The call is already complete or the request stream is already finished.

  • ValueError – The request is too large for the socket.

  • RpcError – The call ended with a protocol error.

  • SocketClosed – The connection is closed.