Broker connection¶
BrokerConnection is the client your
Django code uses to talk to the broker. It logs in with the API key and
secret from MOMOTOR_BROKER, keeps the session token in a
token store, and retries calls that fail with a
temporary connection error.
Create the connection inside async code, while an event loop is running. The first call opens the connection. Later calls reuse it.
Call a broker method¶
Use send_message() to
call a method on the broker’s
ClientStub and wait for the
response. Pass the method name and a protocol buffer request message:
response = await connection.send_message('jobStatus', request)
The protocol buffer messages and method names come from the
momotor-engine-proto package. If the broker rejects the stored token,
the connection deletes the token, logs in again, and sends the message
again.
Two related methods cover common cases:
server_info()returns the broker’s server information. The result is cached forMOMOTOR_BROKER.INFO_MAX_AGEseconds.fire_message()sends a message without waiting for the call to finish. Use it only when you do not need the response. A failed background send is logged and then discarded.
Follow job status¶
multi_job_status_stream()
is an async generator. It yields a status message each time a job changes
state on the broker:
async for status in connection.multi_job_status_stream():
print(status.jobId, status.status)
The generator ends when the stream closes, when a timeout expires, or when the connection is replaced. It does not reconnect by itself, so wrap it in your own loop if you need a permanent subscription.
Retries¶
Calls that fail with a temporary connection error are retried with growing
delays, up to a 10 second delay between attempts. The
retry_connection decorator implements
this. You can apply the same decorator to your own async functions that
call the broker through a stub from
get_stub().
Close the connection¶
Call disconnect() to
close the channel. Pass reset=True to also delete the stored token, for
example after the broker reports an authentication error. The next call
opens a new connection.
API reference¶
- class momotor.django.connection.BrokerConnection(*, executor=None, **token_pool_kwargs)¶
Connection class to Momotor broker.
Provides methods to connect to the Momotor broker and send and receive messages to and from the
ClientStubIs configured through the
MOMOTOR_BROKERsetting.Uses the running asyncio event loop. Create the connection inside async code, while an event loop is running.
Changed in version 6.0.0: The
loopargument and attribute were removed. The connection now always uses the running event loop.Produces log messages on the
momotor.djangologger.- Parameters:
executor (
Executor|None) – An executor to run I/O blocking tasks on. If None, uses the current loop’s default executor.token_pool_kwargs – Any additional keyword arguments are passed on to the token store
- async disconnect(reset=False)¶
Disconnect from the broker.
If reset is True, resets the authentication state by deleting the token.
- fire_message(method_name, request, *, private_channel=False, timeout=None)¶
Fire a message to the broker: send the message and don’t wait for the RPC completion
- get_stub(private_channel=False)¶
Context manager to get an authenticated
ClientStub- Parameters:
private_channel (
bool) – If True, creates a new single-use channel to the broker that will be closed when the context exits. If False, uses a shared channel.- Return type:
- async multi_job_status_stream(*, private_channel=False, connect_timeout=None, status_timeout=None)¶
Async generator that connects to the
multiJobStatusStream()client endpoint and yields theJobStatusStreamstatus messages- Parameters:
private_channel (
bool) – Keep False (the default). The stream only delivers messages on the shared channel. A private channel currently yields no status messages.connect_timeout (
float|None) – timeout (in seconds) to wait until connected. None for no timeoutstatus_timeout (
float|None) – timeout (in seconds) to wait for next status message. None for no timeout
- Return type:
- async send_message(method_name, request, *, private_channel=False, timeout=None)¶
Send a message to the broker’s
ClientStuband await the responseIf authentication fails, tries to send the message again after a delay.
- Parameters:
- Return type:
- Returns:
The response message
- async server_info()¶
Get the server info.
A cached version of the server info is returned if the server info was retrieved less than
MOMOTOR_BROKER.INFO_MAX_AGEseconds ago.- Return type:
- Returns:
The server info response
- momotor.django.connection.retry_connection = <function on_exception.<locals>.decorate>¶
A decorator to retry a function when a transient connection error occurs.
Catches the exception and retries the function several times whenever one of the following exceptions is raised:
Produces log messages on the
momotor.djangologger.
- momotor.django.connection.get_protocol_version()¶
Get the installed
momotor-engine-protoprotocol version.- Return type:
- Returns:
The protocol version of the installed package.
- async momotor.django.connection.version_check(server_info)¶
Warn when the broker uses a different protocol version than this client.
- Parameters:
server_info (
ServerInfoResponse) – The server info response received from the broker.- Return type:
- momotor.django.connection.consume_task_result(task)¶
Consume the result of a finished task and discard any exception it raised.
Used as the done callback for fire-and-forget messages sent with
BrokerConnection.fire_message(), so a failed background send does not leave an unretrieved exception on the task.