Prefabs#

Prefab channels and listeners#

class SSEChannel#

Bases: AbstractChannel[MIn, MOut]

SSE streaming channel. See Mozilla docs

Messages are sent as SSE events, see adapt(), and stream errors as events of type error, see adapt_error().

__init__(stream_delay_seconds=0, retry_timeout_milliseconds=5, channel_id=None, connections_factory=None)#
Parameters:
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

adapt(msg)#

SSE adapter.

Returns:

{
    "event": "message type",
    "retry": "channel time out",
    "data": "original payload",
    "id": "message id"
}

“id” is optional, as in SSE specs: it’s there only if the message has an id.

Parameters:

msg (MOut)

Return type:

dict

adapt_error(exception)#

SSE adapter for stream errors.

Returns:

{
    "event": "error",
    "retry": "channel time out",
    "data": {"error": "exception class name", "message": "exception message"}
}
Parameters:

exception (Exception)

Return type:

dict

class DataProcessingChannel#

Bases: AbstractChannel[MIn, MOut]

Channel intended for concurrent processing of data.

Relies on concurrent.futures.Executor. Just override adapt method to control output returned to clients

__init__(max_workers, stream_delay_seconds=0, executor_class=<class 'concurrent.futures.thread.ThreadPoolExecutor'>, channel_id=None, connections_factory=None)#
Parameters:
  • max_workers (int) – Num of workers to use

  • stream_delay_seconds (int) – Can be used to limit response rate of streaming. Only applies to message_stream calls.

  • executor_class (type) – The constructor of some Executor class. Defaults to ThreadPoolExecutor.

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

  • connections_factory (ConnectionsFactory | None) – See AbstractChannel.

to_dict()#

executor_class is stored as a class object: the storage engine must be able to serialise it.

Return type:

dict

async process_queue(connection_id)#

Processes the messages in the queue of a given connection: runs its listener’s on_message concurrently in the executor, and yields each message, adapted, as soon as it’s processed. See adapt method.

Errors are handled as by deliver_next(), in the channel’s process: listener errors are logged and passed to error handlers, and the message is yielded anyway. Queue errors and a StoppedListenerException are re-raised after the messages already popped are yielded, so they are not lost.

Parameters:

connection_id (str)

Return type:

AsyncIterable[dict]

adapt(msg)#

Returns a dictionary in the following format:

{
    "event": message type
    "data": message payload
}
Parameters:

msg (MOut)

Return type:

dict

adapt_error(exception)#

Returns a dictionary in the following format:

{
    "event": "error",
    "data": {"error": "exception class name", "message": "exception message"}
}
Parameters:

exception (Exception)

Return type:

dict

class SimpleDistributedApplicationListener#

Bases: MessageQueueListener[SignedMessage]

Listener for distributed applications.

It dispatches through the channel it is registered to, see on_registered(): any channel, including when listeners are created or loaded from persistence.

__init__()#
on_registered(channel, connection_id)#

Keeps channel, to dispatch messages through it, and connection_id, to sign them.

Parameters:
Return type:

None

set_action(name, action)#

Hooks a callable to a string key.

Callables are selected when listener processes the message depending on its type.

They should return a list of MessageContract instances corresponding to response to action requested.

Reserved actions are ‘start’, ‘stop’. Receiving a message with one of these types will fire corresponding action.

Parameters:
dispatch_to(receiver_id, msg)#

Dispatches msg to connection receiver_id, signed with this listener’s connection id.

Parameters:
on_message(msg)#

Executes action corresponding to message’s type

Parameters:

msg (SignedMessage)

Return type:

None

class SimpleDistributedApplicationChannel#

Bases: SSEChannel[SignedMessage, SignedMessage]

Channel for SimpleDistributedApplicationListener instances.

Use a connections factory or repository that creates them, e.g. ChannelRepositoryBuilder(SimpleDistributedApplicationChannel).listeners(SimpleDistributedApplicationListener).

Prefab servers and clients#

class ChannelContainer#

Helper class for management of multiple channels cases of use.

__init__()#
register(channel)#
Parameters:

channel (AbstractChannel)

Return type:

None

register_iterable(channels)#
Parameters:

channels (Iterable[AbstractChannel])

Return type:

None

get(channel_id)#
Parameters:

channel_id (str)

Return type:

AbstractChannel

rm(channel_id)#
Parameters:

channel_id (str)

get_all_ids()#
Return type:

Iterable[str]

class SocketServer#

An implementation of a socket server that acts as a controller to interact with library

Accepted format: a plain JSON with the following keys:

{
    "c": "channel id"
    "v": "verb"
    "t": "message type"
    "p": "message payload"
    "r": "receiver (connection id when verb is 'rl')"
}

Possible values of verb identifies a supported action:

"d" dispatch
"b" broadcast
"c" create channel
"r" add connection
"l" listen (opens a stream)
"w" watch (opens a stream)
"rl" remove a connection
"rc" remove a channel

See examples

__init__(file_descriptor_path, channels=None, channel_factory=<class 'eric_sse.prefabs.SSEChannel'>)#
Parameters:
  • file_descriptor_path (str) – See start method

  • channels (ChannelContainer | None) – the channels the server works on. A new empty container by default.

  • channel_factory (Callable[[], AbstractChannel]) – creates the channels requested by the ‘c’ verb, e.g. lambda: repository.create({}) for channels built by a repository. Creates plain SSEChannel by default.

static start(file_descriptor_path)#

Shortcut to start a server given a file descriptor path

Parameters:

file_descriptor_path (str) – file descriptor path, all understood by Path is fine

async shutdown()#

Graceful Shutdown: stops accepting connections, ends open streams and removes the socket file. Returns when done, and so does main. Same as sending SIGINT or SIGTERM to the process.

async main()#

Starts the server. Returns after a shutdown.

class SocketClient#

A little facade to interact with SocketServer

__init__(file_descriptor_path)#
Parameters:

file_descriptor_path (str)

async send_payload(payload)#

Send an arbitrary payload to a socket

see SocketServer

Parameters:

payload (dict)

async create_channel()#
Return type:

str

async register(channel_id)#
Parameters:

channel_id (str)

async stream(channel_id, connection_id)#
Return type:

AsyncIterable[str]

async broadcast_message(channel_id, message_type, payload)#
Parameters:
async dispatch(channel_id, receiver_id, message_type, payload)#
Parameters:
async remove_connection(channel_id, connection_id)#
Parameters:
  • channel_id (str)

  • connection_id (str)

async remove_channel(channel_id)#
Parameters:

channel_id (str)