node — XMPP network nodes (clients, mostly)

This module contains functions to connect to an XMPP server, as well as maintaining the stream. In addition, a client class which completely manages a stream based on a presence setting is provided.

Using XMPP

class aioxmpp.Client(local_jid, security_layer, *, negotiation_timeout=datetime.timedelta(seconds=60), max_initial_attempts=4, override_peer=[], loop=None, logger=None)[source]

Base class to implement an XMPP client.

Parameters
  • local_jid (JID) – Jabber ID to connect as.

  • security_layer (SecurityLayer) – Configuration for authentication and TLS.

  • negotiation_timeout (datetime.timedelta) – Timeout for the individual stream negotiation steps (bounds initial connect time)

  • override_peer – Connection options which take precedence over the standardised connection options

  • max_inital_attempts (int) – Maximum number of initial connection attempts before giving up.

  • loop (asyncio.BaseEventLoop or None) – Override the asyncio event loop to use.

  • logger (logging.Logger or None) – Override the logger to use.

These classes deal with managing the StanzaStream and the underlying XMLStream instances. The abstract client provides functionality for connecting the xmlstream as well as signals which indicate changes in the stream state.

The security_layer is best created using the aioxmpp.security_layer.make() function and must provide authentication for the given local_jid.

If loop is given, it must be a asyncio.BaseEventLoop instance. If it is not given, the current event loop is used.

As a glue between the stanza stream and the XML stream, it also knows about stream management and performs stream management negotiation. It is specialized on client operations, which implies that it will try to keep the stream alive as long as wished by the client.

The client will attempt to connect to the server(s) associated with the local_jid, using the prioritised override_peer setting or the standardised options for connecting (see discover_connectors()). The initial connection attempt must succeed within max_initial_attempts.

If the connection breaks after the first connection attempt, the client will try to resume the connection transparently. If the server supports stream management (XEP-0198) with resumption, this is entirely transparent to all operations over the stream. If the stream is not resumable or the resumption fails and allow_implicit_reconnect is true, the application and services using the stream are notified about that. If, in that situation, allow_implicit_reconnect is false instead, the client stops with an error.

The number of reconnection attempts is generally unbounded. The application is notified that the stream got interrupted with the on_stream_suspended() is emitted. After reconnection, on_stream_established() is emitted (possibly preceded by a on_stream_destroyed() emission if the stream failed to resume). If the application wishes to bound the time the stream tries to transparently reconnect, it should connect to the on_stream_suspended() signal and stop the stream as needed.

The reconnection attempts are throttled using expenential backoff controlled by the backoff_start, backoff_factor and backoff_cap attributes.

Note

If max_initial_attempts is None, the stream will try indefinitely to connect to the server even if the connection has never succeeded yet. This is may mask problems with the configuration of the client itself, because the client cannot successfully distinguish permanent problems arising from the configuration (of the client or the server) from problems arising from transient problems such as network failures.

This may severely degrade usabilty, because the client is then stuck in a connect loop without any usable feedback. Setting a bound for the initial connection attempt is usually better, for interactive applications an upper bound of 1 might make most sense (possibly the interactive application may retry on its own if the user did not indicate that they wish to do so after a timeout). We’ll leave the UX considerations up to you.

Changed in version 0.4: Since 0.4, support for legacy XMPP sessions has been implemented. Mainly for compatibility with ejabberd.

Changed in version 0.8: The amount of initial connection attempts is now bounded by max_initial_attempts. The on_stream_suspended() signal and the associated logic has been introduced.

Controlling the client:

connected(*, presence=<PresenceState>, **kwargs)[source]

Return a node.UseConnected context manager which does not modify the presence settings.

The keyword arguments are passed to the node.UseConnected context manager constructor.

New in version 0.8.

start()[source]

Start the client. If it is already running, RuntimeError is raised.

While the client is running, it will try to keep an XMPP connection open to the server associated with local_jid.

stop()[source]

Stop the client. This sends a signal to the clients main task which makes it terminate.

It may take some cycles through the event loop to stop the client task. To check whether the task has actually stopped, query running.

running

true if the client is currently running, false otherwise.

negotiation_timeout = timedelta(seconds=60)

The timeout applied to the connection process and the individual steps of negotiating the stream. See the negotiation_timeout argument to connect_xmlstream().

override_peer

A sequence of triples (host, port, connector), where host must be a host name or IP as string, port must be a port number and connector must be a aioxmpp.connector.BaseConnctor instance.

These connection options are passed to connect_xmlstream() and thus take precedence over the options discovered using discover_connectors().

Note

If Stream Management is used and the peer server provided a location to connect to on resumption, that location is preferred even over the options set here.

New in version 0.6.

resumption_timeout = None

The maximum time as integer in seconds for which the server shall hold on to the session if the underlying transport breaks.

This is only relevant if the server supports Stream Management and the server may ignore the request for a maximum timeout and/or impose its own maximum. After the stream has been negotiated, StanzaStream.sm_max holds the actual timeout announced by the server (may be None if the server did not specify a timeout).

The default value of None does not request any specific timeout from the server and leaves it up to the server to decide.

Setting a resumption_timeout of zero (0) disables resumption.

New in version 0.9.

Connection information:

established

true if the stream is currently established (as defined in on_stream_established) and false otherwise.

established_event

An asyncio.Event which indicates that the stream is established. A stream is valid after resource binding and before it has been destroyed.

While this event is cleared, enqueue() fails with ConnectionError and send() blocks.

suspended

true if the stream is currently suspended (see on_stream_suspended())

New in version 0.11.

local_jid

The JID the client currently has. While the client is disconnected, which parts of the local_jid can be relied upon depends on the authentication mechanism used. For example, using anonymous authentication, the server dictates even the local part of the JID and it will change after a reconnect. For more common authentication schemes (such as normal password-based authentication), the localpart is usually chosen by the client.

For interoperability with different authentication schemes, code must invalidate all copies of this attribute when a on_stream_established() or on_stream_destroyed() event is emitted.

Writing this attribute is not allowed, as changing the JID introduces a lot of issues with respect to reusability of the stream. Instantiate a new Client if you need to change the bare part of the JID.

Note

Changing the resource between reconnects may be allowed later.

stream

The StanzaStream instance used by the node.

stream_features

An instance of StreamFeatures. This is the most-recently received stream features information (the one received right before resource binding).

While no stream has been established yet, this is None. During transparent re-negotiation, that information may be obsolete. However, when before_stream_established fires, the information is up-to-date.

Sending stanzas:

async send(stanza, *, timeout=None, cb=None)[source]

Send a stanza.

Parameters
  • stanza (IQ, Presence or Message) – Stanza to send

  • timeout (Real or None) – Maximum time in seconds to wait for an IQ response, or None to disable the timeout.

  • cb – Optional callback which is called synchronously when the reply is received (IQ requests only!)

Raises
Returns

IQ response payload or None

Send the stanza and wait for it to be sent. If the stanza is an IQ request, the response is awaited and the payload of the response is returned.

If the stream is currently not ready, this method blocks until the stream is ready to send payload stanzas. Note that this may be before initial presence has been sent. To synchronise with that type of events, use the appropriate signals.

The timeout as well as any of the exception cases referring to a “response” do not apply for IQ response stanzas, message stanzas or presence stanzas sent with this method, as this method only waits for a reply if an IQ request stanza is being sent.

If stanza is an IQ request and the response is not received within timeout seconds, TimeoutError (not asyncio.TimeoutError!) is raised.

If cb is given, stanza must be an IQ request (otherwise, ValueError is raised before the stanza is sent). It must be a callable returning an awaitable. It receives the response stanza as first and only argument. The returned awaitable is awaited by send() and the result is returned instead of the original payload. cb is called synchronously from the stream handling loop when the response is received, so it can benefit from the strong ordering guarantees given by XMPP XML Streams.

The cb may also return None, in which case send() will simply return the IQ payload as if cb was not given. Since the return value of coroutine functions is awaitable, it is valid and supported to pass a coroutine function as cb.

Warning

Remember that it is an implementation detail of the event loop when a coroutine is scheduled after it awaited an awaitable; this implies that if the caller of send() is merely awaiting the send() coroutine, the strong ordering guarantees of XMPP XML Streams are lost.

To regain those, use the cb argument.

Note

For the sake of readability, unless you really need the strong ordering guarantees, avoid the use of the cb argument. Avoid using a coroutine function unless you really need to.

Changed in version 0.9: The cb argument was added.

New in version 0.8.

enqueue(stanza, **kwargs)[source]

Put a stanza in the internal transmission queue and return a token to track it.

Parameters
Raises

ConnectionError – if the stream is not established yet.

Returns

token which tracks the stanza

Return type

StanzaToken

The stanza is enqueued in the active queue for transmission and will be sent on the next opportunity. The relative ordering of stanzas enqueued is always preserved.

Return a fresh StanzaToken instance which traks the progress of the transmission of the stanza. The kwargs are forwarded to the StanzaToken constructor.

This method calls autoset_id() on the stanza automatically.

See also

send()

for a more high-level way to send stanzas.

Changed in version 0.10: This method has been moved from aioxmpp.stream.StanzaStream.enqueue().

Configuration of exponential backoff for reconnects:

backoff_start = timedelta(1)

When an underlying XML stream fails due to connectivity issues (generic OSError raised), exponential backoff takes place before attempting to reconnect.

The initial time to wait before reconnecting is described by backoff_start.

backoff_factor = 1.2

Each subsequent time a connection fails, the previous backoff time is multiplied with backoff_factor.

backoff_cap = timedelta(60)

The backoff time is capped to backoff_cap, to avoid having unrealistically high values.

Signals:

signal on_failure(err)

This signal is fired when the client fails and stops.

async signal before_stream_established()

This coroutine signal is executed right before on_stream_established() fires.

signal on_stopped()

Fires when the client stops gracefully. This is the counterpart to on_failure().

signal on_stream_established()

When the stream is established and resource binding took place, this event is fired. It means that the stream can now be used for XMPP interactions.

signal on_stream_suspended(reason)

The stream has been suspened due to a connection failure.

Parameters

reason (Exception) – The exception which terminated the stream.

This signal may be immediately followed by a on_stream_destroyed(), if the stream did not support stream resumption. Otherwise, a new connection is attempted transparently.

In general, this signal exists solely for informational purposes. It can be used to drive a user interface which indicates that messages may be delivered with delay, because the underlying network is transiently interrupted.

on_stream_suspended() is not emitted if the stream was stopped on user request.

After on_stream_suspended() is emitted, one of the two following signals is emitted:

  • on_stream_destroyed() indicates that state was actually lost and that others most likely see or saw an unavailable presence broadcast for the resource.

  • on_stream_resumed() indicates that no state was lost and the stream is fully usable again.

New in version 0.8.

signal on_stream_resumed()

The stream has been resumed after it has been suspended, without loss of data.

This is the counterpart to on_stream_suspended().

In general, this signal exists solely for informational purposes. It can be used to drive a user interface which indicates that messages may be delivered with delay, because the underlying network is transiently interrupted.

New in version 0.11.

signal on_stream_destroyed(reason=None)

This is called whenever a stream is destroyed. The conditions for this are the same as for aioxmpp.stream.StanzaStream.on_stream_destroyed.

Parameters

reason (Exception) – An optional exception which indicates the reason for the destruction of the stream.

This event can be used to know when to discard all state about the XMPP connection, such as roster information. Services implemented in aioxmpp generally subscribe to this signal to discard cached state.

reason is optional. It is given if there is has been a specific exception which describes the cause for the stream destruction, such as a ConnectionError.

Changed in version 0.8: The reason argument was added.

Services:

summon(class_)[source]

Summon a Service for the client.

If the class_ has already been summoned for the client, it’s instance is returned.

Otherwise, all requirements for the class are first summoned (if they are not there already). Afterwards, the class itself is summoned and the instance is returned.

Miscellaneous:

logger

The logging.Logger instance which is used by the Client. This is the logger passed to the constructor or a logger derived from the fully qualified name of the class.

New in version 0.6: The logger attribute was added.

class aioxmpp.PresenceManagedClient(jid, security_layer, **kwargs)[source]

Client whose connection is controlled by its configured presence.

See also

Client

for a description of the arguments.

The presence is set using presence or the PresenceServer service. If the set presence is an available presence, the client is started (if it is not already running). If the set presence is an unavailable presence, the unavailable presence is broadcast and the client is stopped.

While the start/stop interfaces of Client are still available, using them may interfere with the behaviour of the presence automagic.

The initial presence is set to unavailable, thus, the client will not connect immediately.

presence

Control or query the current presence state (see PresenceState) of the client. Note that when reading, the property only returns the “set” value, not the actual value known to the server (and others). This may differ if the connection is still being established.

See also

Setting the presence state using presence clears the status of the presence. To set the status and state at once, use set_presence().

Upon setting this attribute, the PresenceManagedClient will do whatever necessary to achieve the given presence. If the presence is an available presence, the client will attempt to connect to the server. If the presence is unavailable and the client is currently connected, it will disconnect.

Instead of setting the presence to unavailable, stop() can also be called. The presence attribute is not affected by calls to start() or stop().

set_presence(state, status)[source]

Set the presence state and status on the client. This has the same effects as writing state to presence, but the status of the presence is also set at the same time.

status must be either a string or something which can be passed to dict. If it is a string, the string is wrapped in a {None: status} dictionary. Otherwise, the dictionary is set as the status attribute of the presence stanza. It must map aioxmpp.structs.LanguageTag instances to strings.

The status is the text shown alongside the state (indicating availability such as away, do not disturb and free to chat).

connected(**kwargs)[source]

Return a node.UseConnected context manager which sets the presence to available.

The keyword arguments are passed to the node.UseConnected context manager constructor.

Note

In contrast to the same method on Client, this method implies setting an available presence.

New in version 0.6.

Signals:

on_presence_sent

The event is fired after Client.on_stream_established() and after the current presence has been sent to the server as initial presence.

Changed in version 0.8: Since 0.8, the PresenceManagedClient is implemented on top of PresenceServer. Changing the presence via the PresenceServer has the same effect as writing presence or calling set_presence().

class aioxmpp.node.AbstractClient

Alias of Client.

Deprecated since version 0.8: The alias will be removed in 1.0.

Connecting streams low-level

async aioxmpp.node.discover_connectors(domain: str, loop=None, logger=<Logger aioxmpp.node (WARNING)>)[source]

Discover all connection options for a domain, in descending order of preference.

This coroutine returns options discovered from SRV records, or if none are found, the generic option using the domain name and the default XMPP client port.

Each option is represented by a triple (host, port, connector). connector is a aioxmpp.connector.BaseConnector instance which is suitable to connect to the given host and port.

logger is the logger used by the function.

The following sources are supported:

  • RFC 6120 SRV records. One option is returned per SRV record.

    If one of the SRV records points to the root name (.), ValueError is raised (the domain specifically said that XMPP is not supported here).

  • XEP-0368 SRV records. One option is returned per SRV record.

  • RFC 6120 fallback process (only if no SRV records are found). One option is returned for the host name with the default XMPP client port.

The options discovered from SRV records are mixed together, ordered by priority and then within priorities are shuffled according to their weight. Thus, if there are multiple records of equal priority, the result of the function is not deterministic.

New in version 0.6.

async aioxmpp.node.connect_xmlstream(jid, metadata, negotiation_timeout=60.0, override_peer=[], loop=None, logger=<Logger aioxmpp.node (WARNING)>)[source]

Prepare and connect a aioxmpp.protocol.XMLStream to a server responsible for the given jid and authenticate against that server using the SASL mechanisms described in metadata.

Parameters
  • jid (aioxmpp.JID) – Address of the user for which the connection is made.

  • metadata (SecurityLayer) – Connection metadata for configuring the TLS usage.

  • negotiation_timeout (float in seconds) – Timeout for each individual negotiation step.

  • override_peer (sequence of (str, int, BaseConnector) triples) – Sequence of connection options which take precedence over normal discovery methods.

  • loop (asyncio.BaseEventLoop) – asyncio event loop to use (defaults to current)

  • logger (logging.Logger) – Logger to use (defaults to module-wide logger)

Raises
Returns

Transport, XML stream and the current stream features

Return type

tuple of (asyncio.BaseTransport, XMLStream, StreamFeatures)

The part of the metadata specifying the use of TLS is applied. If the security layer does not mandate TLS, the resulting XML stream may not be using TLS. TLS is used whenever possible.

The connection options in override_peer are tried before any standardised discovery of connection options is made. Only if all of them fail, automatic discovery of connection options is performed.

loop may be a asyncio.BaseEventLoop to use. Defaults to the current event loop.

If the domain from the jid announces that XMPP is not supported at all, ValueError is raised. If no options are returned from discover_connectors() and override_peer is empty, ValueError is raised, too.

If all connection attempts fail, aioxmpp.errors.MultiOSError is raised. The error contains one exception for each of the options discovered as well as the elements from override_peer in the order they were tried.

A TLS problem is treated like any other connection problem and the other connection options are considered. However, if all connection options fail and the set of encountered errors includes a TLS error, the TLS error is re-raised instead of raising a aioxmpp.errors.MultiOSError.

Return a triple (transport, xmlstream, features). transport the underlying asyncio.Transport which is used for the xmlstream XMLStream instance. features is the aioxmpp.nonza.StreamFeatures instance describing the features of the stream.

New in version 0.6.

Changed in version 0.8: The explicit raising of TLS errors has been introduced. Before, TLS errors were treated like any other connection error, possibly masking configuration problems.

Utilities

class aioxmpp.node.UseConnected(client, *, timeout=None, presence=<PresenceState available>)[source]

Asynchronous context manager which connects and disconnects a Client.

Parameters
  • client (Client) – The client to manage

  • timeout (datetime.timedelta or None) – Limit on the time it may take to start the client

  • presence (PresenceState) – Presence state to set on the client (deprecated)

When the asynchronous context is entered (see PEP 492), the client is connected. This blocks until the client has finished connecting and the stream is established. If the client takes longer than timeout to connect, TimeoutError is raised and the client is stopped. The context manager returns the stream of the client.

When the context is exited, the client is disconnected and the context manager waits for the client to cleanly shut down the stream.

If the client is already connected when the context is entered, the connection is re-used and not shut down when the context is entered, but leaving the context still disconnects the client.

If the presence refers to an available presence, the PresenceServer is summon()-ed on the client. The presence is set using set_presence() (clearing the status and resetting priority to 0) before the client is connected. If the client is already connected, the presence is set when the context is entered.

Deprecated since version 0.8: The use of the presence argument is deprecated. The deprecation will happen in two phases:

  1. Until (but not including the release of) 1.0, passing a presence state which refers to an available presence will emit DeprecationWarning. This includes the default of the argument, so unless an unavailable presence state is passed explicitly, all uses of UseConnected emit that warning.

  2. Starting with 1.0, passing an available presence will raise ValueError.

  3. Starting with a to-be-determined release after 1.0, passing the presence argument at all will raise TypeError.

Users which previously used the presence argument should use the PresenceServer service on the client and set the presence before using the context manager instead.

presence

See the description of the presence argument.

Deprecated since version 0.8: Using this attribute (for reading or writing) is deprecated and emits a deprecation warning.

timeout

See the description of the timeout argument.

Deprecated since version 0.8: Using this attribute (for reading or writing) is deprecated and emits a deprecation warning.