Entities#
Messages#
- class MessageContract#
Bases:
ABCContract class for messages
A message is just a container of information identified by a type. To validate messages, override
before_dispatch(), oron_message()to check them on delivery.
- 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:
MessageContractModels a simple message
- Parameters:
- __init__(msg_type, msg_payload=None, msg_id=None)#
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 areQueue[MIn, MOut]and its listenersMessageQueueListener[MOut]. They differ when queues transform messages, e.g.SSEChannel[MessageContract, ReliableMessage]withReliableQueuequeues. Plain channels handle any message.InMemoryConnectionsFactoryis the default implementation used for connections_factory parameter.see
SSEChannelHooks: subclasses can override
on_connection_added(),on_connection_removed(),on_stream_start(),on_stream_end(),on_wait_timeout(),before_dispatch()andon_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()andadd_listener_error_handler(). Then they are either re-raised or, when the channel swallows them, logged. Control flow exceptions, likeNoMessagesException, 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:
stream_delay_seconds (int)
channel_id (str | None)
connections_factory (ConnectionsFactory | None)
- 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.
- _on_listener_error(connection_id, msg, exception)#
Logs an error raised by a listener’s
on_message, and passes it to error handlers.
- 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:
- 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_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.
- on_connection_added(connection)#
Hook called by
add_connection()andregister_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 bybroadcast()for each connection, before enqueuing msg.
- on_wait_timeout(connection)#
Hook called when
message_stream()waitedwait_timeout_secondsfor 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_secondsbefore trying again, so a failing backend doesn’t make it spin.- Returns:
False to end the stream after the error.
- Parameters:
connection (Connection)
exception (Exception)
- Return type:
- 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 afterwait_timeout_seconds.Errors are yielded through
adapt_error(). After anInvalidConnectionException, anInvalidChannelExceptionor aStoppedListenerException, the stream ends. Unexpected errors are logged and yielded as anInternalStreamError, hiding their details, andon_error()decides whether the stream goes on.Calls
on_stream_start(),on_wait_timeout()andon_stream_end()hooks.- Parameters:
connection_id (str)
- Return type:
- add_connection()#
Creates a connection through the connections factory, and registers it.
- Return type:
- register_listener(listener)#
Creates a connection for an existing listener, and registers it.
- Parameters:
listener (MessageQueueListener[MOut])
- Return type:
- register_connection(connection)#
Register and existing connection.
add_connection()andregister_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
StoppedListenerExceptionif 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.
- 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
StoppedListenerExceptionif 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.
- 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.
- 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
InvalidConnectionExceptionif the channel has no such connection.- Parameters:
connection_id (str)
- Return type:
- async watch()#
Streams channel messages through a new connection, removed when the stream ends:
async for message in channel.watch(): ...
- Return type:
- 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:
listener (MessageQueueListener)
queue (Queue)
- class ConnectionsFactory#
-
- 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:
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, asReliableQueuedoes. PlainQueueholds any message.Implementations must provide
pop()andpush(). Overridewait_pop()too if the backend can wait for messages without blocking a thread, asInMemoryQueuedoes.- 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:
Raises a
NoMessagesExceptionif no message is available, after waiting timeout seconds.
- 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.Raises a
NoMessagesExceptionif no message arrives within timeout.
- class InMemoryQueue#
-
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:
Raises a
NoMessagesExceptionif no message is available, after waiting timeout seconds.
- 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.Raises a
NoMessagesExceptionif no message arrives within timeout.
Listeners#
- class MessageQueueListener#
-
Base class for listeners.
Generic on the type of messages it handles, e.g.
MessageQueueListener[SignedMessage]. PlainMessageQueueListenerhandles 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:
channel (AbstractChannel[Any, M])
connection_id (str)
- 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