Entities#

Messages#

class MessageContract#

Bases: ABC

Contract class for messages

A message is just a container of information identified by a type. To validate messages, override before_dispatch(), or on_message() to check them on delivery.

abstract property type: str#

Message type

abstract property payload: dict | list | str | int | float | None#

Message payload

property id: str | None#

Optional message identifier, e.g. the “id” field of an SSE event. None if the message has none.

class M#

Type of messages handled by generic queues and listeners.

alias of TypeVar(‘M’, bound=MessageContract)

class MIn#

Type of messages pushed to a queue, or dispatched to a channel.

alias of TypeVar(‘MIn’, bound=MessageContract)

class MOut#

Type of messages popped from a queue, or delivered by a channel.

alias of TypeVar(‘MOut’, bound=MessageContract)

class Message#

Bases: MessageContract

Models a simple message

Parameters:
  • msg_type (str) – Message type.

  • msg_payload – Message payload.

  • msg_id (str | None) – Optional message identifier, see id.

__init__(msg_type, msg_payload=None, msg_id=None)#
Parameters:
Return type:

None

property type: str#

Message type

property payload: dict | list | str | int | float | None#

Message payload

property id: str | None#

Optional message identifier, e.g. the “id” field of an SSE event. None if the message has none.

class SignedMessage#

Bases: Message

Message plus sender id

__init__(sender_id, msg_type, msg_payload=None, msg_id=None)#
Parameters:
property sender_id: str#

Returns the id of the listener that sent the message

Channels and connections#

class AbstractChannel#

Bases: ABC, Generic[MIn, MOut]

Base class for channels.

Provides functionalities for connections and message delivery management. A connection pairs a listener with its queue, and its id is the address messages are dispatched to, see Connection.

Generic on the type of messages it dispatches (MIn) and delivers (MOut), e.g. SSEChannel[SignedMessage, SignedMessage], as its queues are Queue[MIn, MOut] and its listeners MessageQueueListener[MOut]. They differ when queues transform messages, e.g. SSEChannel[MessageContract, ReliableMessage] with ReliableQueue queues. Plain channels handle any message.

InMemoryConnectionsFactory is the default implementation used for connections_factory parameter.

see SSEChannel

Hooks: subclasses can override on_connection_added(), on_connection_removed(), on_stream_start(), on_stream_end(), on_wait_timeout(), before_dispatch() and on_error(). They do nothing by default.

Error handlers: errors raised by queues and listeners are passed to the handlers registered with add_queuing_error_handler() and add_listener_error_handler(). Then they are either re-raised or, when the channel swallows them, logged. Control flow exceptions, like NoMessagesException, are neither logged nor handled.

Parameters:
  • stream_delay_seconds (int) – Pause in seconds after each message delivered by message_stream(). Can be used to limit its rate.

  • channel_id (str) – Optionally sets the channel id.

  • connections_factory (ConnectionsFactory) – Factory to be used for creating connections instances on channel subscriptions.

wait_timeout_seconds: float = 1.0#

How long message_stream() waits for a message before checking again whether its listener is running.

__init__(stream_delay_seconds=0, channel_id=None, connections_factory=None)#
Parameters:
add_queuing_error_handler(handler)#

Registers a handler for errors raised by queues. Handlers are called in registration order, and are not persisted.

Parameters:

handler (QueuingErrorHandler)

Return type:

None

add_listener_error_handler(handler)#

Registers a handler for errors raised by listeners. Handlers are called in registration order, and are not persisted.

Parameters:

handler (ListenerErrorHandler)

Return type:

None

_pop_next(connection_id)#

Pops the next message of given connection, without notifying its listener: the first half of deliver_next(), for subclasses that notify listeners their own way, e.g. in an executor. Then they must pass listener errors to _on_listener_error().

Raises as deliver_next() does. Queue errors are re-raised after error handlers.

Parameters:

connection_id (str)

Return type:

MOut

_on_listener_error(connection_id, msg, exception)#

Logs an error raised by a listener’s on_message, and passes it to error handlers.

Parameters:
Return type:

None

property id: str#

Unique identifier for this channel, it can be set by channel_id constructor parameter

to_dict()#

Channel configuration to be persisted. Keys must be constructor parameters, see from_dict().

Subclasses with additional configuration should extend it:

def to_dict(self) -> dict:
    return {**super().to_dict(), 'my_param': self.my_param}
Return type:

dict

classmethod from_dict(data, connections_factory=None)#

Builds a channel from a to_dict() representation. Override it if constructor parameters don’t match data keys.

Parameters:
  • data (dict) – Constructor parameters, except connections_factory.

  • connections_factory (ConnectionsFactory)

Return type:

_Channel

abstract adapt(msg)#

Models output of channel streams

Parameters:

msg (MOut)

Return type:

Any

abstract adapt_error(exception)#

Models errors in channel streams, see message_stream().

exception is safe to expose to clients: unexpected errors are replaced by an InternalStreamError, that hides their details.

Parameters:

exception (Exception)

Return type:

Any

on_connection_added(connection)#

Hook called by add_connection() and register_listener().

Not called when connections are registered with register_connection(), e.g. when a channel is loaded from persistence, because that’s not a new subscription.

Parameters:

connection (Connection)

Return type:

None

on_connection_removed(connection)#

Hook called by remove_connection(), after the connection has been removed.

Parameters:

connection (Connection)

Return type:

None

on_stream_start(connection)#

Hook called when message_stream() starts, after the listener has been started.

Parameters:

connection (Connection)

Return type:

None

on_stream_end(connection)#

Hook called when message_stream() ends, for any reason: listener stopped, error, or client disconnection.

Parameters:

connection (Connection)

Return type:

None

before_dispatch(connection_id, msg)#

Hook called by dispatch(), and so by broadcast() for each connection, before enqueuing msg.

Returns:

The message to enqueue, possibly a different one, or None to drop it.

Parameters:
  • connection_id (str)

  • msg (MIn)

Return type:

MIn | None

on_wait_timeout(connection)#

Hook called when message_stream() waited wait_timeout_seconds for a message and none arrived.

It is not an error: an idle stream times out periodically, to check whether its listener is still running. Can be used, for example, to collect metrics or to end idle streams by stopping their listener.

Parameters:

connection (Connection)

Return type:

None

on_error(connection, exception)#

Hook called when message_stream() catches an unexpected exception, before yielding an error.

By default, it goes on. The exception has already been logged, and, if raised by a queue, passed to error handlers. The stream waits wait_timeout_seconds before trying again, so a failing backend doesn’t make it spin.

Returns:

False to end the stream after the error.

Parameters:
Return type:

bool

async message_stream(connection_id)#

Entry point for message streaming. Starts the connection’s listener, and ends when it is stopped.

Waits for messages through wait_next(), so an idle stream doesn’t consume CPU. A stopped listener is noticed at the latest after wait_timeout_seconds.

Errors are yielded through adapt_error(). After an InvalidConnectionException, an InvalidChannelException or a StoppedListenerException, the stream ends. Unexpected errors are logged and yielded as an InternalStreamError, hiding their details, and on_error() decides whether the stream goes on.

Calls on_stream_start(), on_wait_timeout() and on_stream_end() hooks.

Parameters:

connection_id (str)

Return type:

AsyncIterable[Any]

add_connection()#

Creates a connection through the connections factory, and registers it.

Return type:

Connection

register_listener(listener)#

Creates a connection for an existing listener, and registers it.

Parameters:

listener (MessageQueueListener[MOut])

Return type:

Connection

register_connection(connection)#

Register and existing connection. add_connection() and register_listener() call it too, so subclasses can override it to set up every new connection.

Calls on_registered() on the connection’s listener.

Warning: Listener and queue should belong to the same classes created by the connections factory (the connections repository, for channels built by a channel repository) to avoid compatibility issues with persistence layer

Parameters:

connection (Connection)

deliver_next(connection_id)#

Returns next message of given connection.

Raises a StoppedListenerException if the listener is not running, even if its queue is empty, and a NoMessagesException if the queue is empty. Queue errors are re-raised after error handlers; listener errors are not, and the message is returned anyway.

Parameters:

connection_id (str)

Return type:

MOut

async wait_next(connection_id, timeout)#

Waits up to timeout seconds for the next message of given connection, without blocking the event loop.

Raises a StoppedListenerException if the listener is not running, as waiting for messages that it won’t receive is not allowed, and a NoMessagesException if no message arrives in time. Queue errors are re-raised after error handlers; listener errors are not, and the message is returned anyway.

Parameters:
Return type:

MOut

dispatch(connection_id, msg)#

Adds a message to the connection’s queue, unless before_dispatch() drops it.

Queue errors are re-raised after error handlers.

Parameters:
  • connection_id (str)

  • msg (MIn)

broadcast(msg)#

Enqueue a message to the connections registered when it starts. A queue error is logged, and doesn’t stop delivery to the other ones. Hooks and error handlers can remove connections meanwhile.

Parameters:

msg (MIn)

get_connection(connection_id)#

Raises an InvalidConnectionException if the channel has no such connection.

Parameters:

connection_id (str)

Return type:

Connection

async watch()#

Streams channel messages through a new connection, removed when the stream ends:

async for message in channel.watch():
    ...
Return type:

AsyncIterable[Any]

class Connection#

Bases: Generic[L, Q]

A connection is a listener and its related message queue.

It’s what channels and repositories identify: messages are dispatched to a connection id, and listeners and queues have no identity of their own.

Parameters:
__init__(listener, queue, connection_id=None)#
Parameters:
  • listener (L)

  • queue (Q)

  • connection_id (str | None)

class ConnectionsFactory#

Bases: ABC, Generic[L, Q]

abstract create(listener=None)#

Creates a connection

Parameters:

listener (MessageQueueListener) – If provided, assigns a concrete listener

Return type:

Connection[L, Q]

class InMemoryConnectionsFactory#

Bases: ConnectionsFactory[MessageQueueListener, InMemoryQueue]

Creates Connections with In memory queues (no persistence support)

create(listener=None)#

Creates a connection

Parameters:

listener (MessageQueueListener) – If provided, assigns a concrete listener

Return type:

Connection[MessageQueueListener, InMemoryQueue]

Queues#

class Queue#

Bases: ABC, Generic[MIn, MOut]

Abstract base class for queues (FIFO).

Generic on the type of messages pushed (MIn) and popped (MOut), e.g. Queue[SignedMessage, SignedMessage]. They differ when a queue transforms messages, as ReliableQueue does. Plain Queue holds any message.

Implementations must provide pop() and push(). Override wait_pop() too if the backend can wait for messages without blocking a thread, as InMemoryQueue does.

abstract pop(timeout=0)#

Next message from the queue.

Parameters:

timeout (float) – Seconds to wait for a message. With 0 it returns immediately.

Return type:

MOut

Raises a NoMessagesException if no message is available, after waiting timeout seconds.

abstract push(message)#
Parameters:

message (MIn)

Return type:

None

async wait_pop(timeout)#

Waits for the next message without blocking the event loop.

The default implementation runs pop() with timeout in a worker thread, so it takes one thread per waiting call. Override it with a native async wait when possible.

Parameters:

timeout (float) – Seconds to wait for a message.

Return type:

MOut

Raises a NoMessagesException if no message arrives within timeout.

class InMemoryQueue#

Bases: Queue[M, M]

In memory implementation. Not durable: its messages live in the current process only.

It has a single consumer, as a queue belongs to one listener: concurrent wait_pop() calls on the same queue are not supported. wait_pop() waits natively, without threads or polling. push() can be called from any thread.

It can’t be serialised (e.g. pickled), so it can only be persisted with storages that keep objects in process, such as InMemoryStorage.

__init__()#
pop(timeout=0)#

Next message from the queue.

Parameters:

timeout (float) – Seconds to wait for a message. With 0 it returns immediately.

Return type:

M

Raises a NoMessagesException if no message is available, after waiting timeout seconds.

push(message)#
Parameters:

message (M)

Return type:

None

async wait_pop(timeout)#

Waits for the next message without blocking the event loop.

The default implementation runs pop() with timeout in a worker thread, so it takes one thread per waiting call. Override it with a native async wait when possible.

Parameters:

timeout (float) – Seconds to wait for a message.

Return type:

M

Raises a NoMessagesException if no message arrives within timeout.

Listeners#

class MessageQueueListener#

Bases: Generic[M]

Base class for listeners.

Generic on the type of messages it handles, e.g. MessageQueueListener[SignedMessage]. Plain MessageQueueListener handles any message.

Optionally you can override on_message method if you need to inject code at message delivery time.

__init__()#
on_registered(channel, connection_id)#

Hook called when the listener is registered to channel, through connection connection_id, see register_connection(). Also called when a channel is loaded from persistence. Does nothing by default: override it if the listener needs its channel or its address, e.g. to dispatch messages.

Parameters:
Return type:

None

on_message(msg)#

Event handler. It executes when a message is delivered to client

Parameters:

msg (M)

Return type:

None

start()#
Return type:

None

stop()#
Return type:

None

is_running()#
Return type:

bool