# `stream` — Stanza stream

The stanza stream is the layer of abstraction above the XML stream. It deals with sending and receiving stream-level elements, mainly stanzas. It also handles stream liveness and stream management.

It provides ways to track stanzas on their way to the remote, as far as that is possible.

## General information

### Timeouts / Stream Aliveness checks

The `StanzaStream` relies on the `XMLStream` dead time aliveness monitoring (see also `deadtime_soft_limit`) to detect a broken stream.

The limits can be configured with the two attributes `soft_timeout` and `round_trip_time`. When `soft_timeout` elapses after the last bit of data received from the server, the `StanzaStream` issues a ping. The server then has one `round_trip_time` worth of time to answer. If this does not happen, the `XMLStream` will be terminated by the aliveness monitor and normal handling of a broken connection takes over.

### Stanza Filters

Stanza filters allow to hook into the stanza sending/reception pipeline after/before the application sees the stanza.

#### Inbound stanza filters

Inbound stanza filters allow to hook into the stanza processing by replacing, modifying or otherwise processing stanza contents before the usual handlers for that stanza are invoked. With inbound stanza filters, there are no restrictions as to what processing may take place on a stanza, as no one but the stream may have references to its contents.

Warning

Raising an exception from within a stanza filter kills the stream.

Note that if a filter function drops an incoming stanza (by returning `None`), it must ensure that the client still behaves RFC compliant. The inbound stanza filters are found here:

- `service_inbound_message_filter`

- `service_inbound_presence_filter`

- `app_inbound_message_filter`

- `app_inbound_presence_filter`

#### Outbound stanza filters

Outbound stanza filters work similar to inbound stanza filters, but due to their location in the processing chain and possible interactions with senders of stanzas, there are some things to consider:

- Per convention, a outbound stanza filter must not modify any child elements which are already present in the stanza when it receives the stanza.

  It may however add new child elements or remove existing child elements, as well as copying and then modifying existing child elements.

- If the stanza filter replaces the stanza, it is responsible for making sure that the new stanza has appropriate `from_`, `to` and `id` values. There are no checks to enforce this, because error handling at this point is peculiar. The stanzas will be sent as-is.

- Similar to inbound filters, it is the responsibility of the filters that if stanzas are dropped, the client still behaves RFC-compliant.

Now that you have been warned, here are the attributes for accessing the outbound filter chains. These otherwise work exactly like their inbound counterparts, but service filters run after application filters on outbound processing.

- `service_outbound_message_filter`

- `service_outbound_presence_filter`

- `app_outbound_message_filter`

- `app_outbound_presence_filter`

#### When to use stanza filters?

In general, applications will rarely need them. However, services may make profitable use of them, and it is a convenient way for them to inspect or modify incoming or outgoing stanzas before any normally registered handler processes them.

In general, whenever you do something which supplements the use of the stanza with respect to the RFC but does not fulfill the original intent of the stanza, it is advisable to use a filter instead of a callback on the actual stanza.

Vice versa, if you were to develop a service which manages presence subscriptions, it would be more correct to use `register_presence_callback()`; this prevents other services which try to do the same from conflicting with you. You would then provide callbacks to the application to let it learn about presence subscriptions.

## Stanza Stream class

This section features the complete documentation of the (rather important and complex) `StanzaStream`. Some more general information has been moved to the previous section (General information) to make it easier to read and find.

class aioxmpp.stream.StanzaStream(local_jid=None, *, loop=None, base_logger=<Logger aioxmpp (WARNING)>)

  A stanza stream. This is the next layer of abstraction above the XMPP XML stream, which mostly deals with stanzas (but also with certain other stream-level elements, such as XEP-0198 Stream Management Request/Acks).

  It is independent from a specific `XMLStream` instance. A `StanzaStream` can be started with one XML stream, stopped later and then resumed with another XML stream. The user of the `StanzaStream` has to make sure that the XML streams are compatible, identity-wise (use the same JID).

  local_jid may be the bare sender JID associated with the stanza stream. This is required for compatibility with ejabberd. If it is omitted, communication with ejabberd instances may not work.

  loop may be used to explicitly specify the `asyncio.BaseEventLoop` to use, otherwise the current event loop is used.

  base_logger can be used to explicitly specify a `logging.Logger` instance to fork off the logger from. The `StanzaStream` will use a child logger of base_logger called `StanzaStream`.

  Changed in version 0.4: The local_jid argument was added.

  Changed in version 0.10: Ping handling was reworked.

  Starting/Stopping the stream:

  start(xmlstream)

    Start or resume the stanza stream on the given `aioxmpp.protocol.XMLStream` xmlstream.

    This starts the main broker task, registers stanza classes at the xmlstream .

  stop()

    Send a signal to the main broker task to terminate. You have to check `running` and possibly wait for it to become `False` — the task takes at least one loop through the event loop to terminate.

    It is guaranteed that the task will not attempt to send stanzas over the existing xmlstream after a call to `stop()` has been made.

    It is legal to call `stop()` even if the task is already stopped. It is a no-op in that case.

  async wait_stop()

    Stop the stream and wait for it to stop.

    See `stop()` for the general stopping conditions. You can assume that `stop()` is the first thing this coroutine calls.

  async close()

    Close the stream and the underlying XML stream (if any is connected).

    This is essentially a way of saying “I do not want to use this stream anymore” (until the next call to `start()`). If the stream is currently running, the XML stream is closed gracefully (potentially sending an SM ack), the worker is stopped and any Stream Management state is cleaned up.

    If an error occurs while the stream stops, the error is ignored.

    After the call to `close()` has started, `on_failure()` will not be emitted, even if the XML stream fails before closure has completed.

    After a call to `close()`, the stream is stopped, all SM state is discarded and calls to `enqueue_stanza()` raise a `DestructionRequested` `"close() called"`. Such a `StanzaStream` can be re-started by calling `start()`.

    Changed in version 0.8: Before 0.8, an error during a call to `close()` would stop the stream from closing completely, and the exception was re-raised. If SM was enabled, the state would have been kept, allowing for resumption and ensuring that stanzas still enqueued or unacknowledged would get a chance to be sent.

    If you want to have guarantees that all stanzas sent up to a certain point are sent, you should be using `send_and_wait_for_sent()` with stream management.

  running

    `True` if the broker task is currently running, and `False` otherwise.

  flush_incoming()

    Flush all incoming queues to the respective processing methods. The handlers are called as usual, thus it may require at least one iteration through the asyncio event loop before effects can be seen.

    The incoming queues are empty after a call to this method.

    It is legal (but pretty useless) to call this method while the stream is `running`.

  Timeout configuration (see Timeouts / Stream Aliveness checks):

  round_trip_time

    The maximum expected round-trip time as `datetime.timedelta`.

    This is used to configure the maximum time between asking the server to send something and receiving something from the server in stream aliveness checks.

    This does not affect IQ requests or other stanzas.

    If set to `None`, no application-level timeouts are used at all. This is not recommended since TCP timeouts are generally not sufficient for interactive applications.

  soft_timeout

    Soft timeout after which the server will be asked to send something if nothing has been received.

    If set to `None`, no application-level timeouts are used at all. This is not recommended since TCP timeouts are generally not sufficient for interactive applications.

  Sending stanzas:

  Deprecated since version 0.10: Sending stanzas directly on the stream is deprecated. The methods have been moved to the client:

  `aioxmpp.Client.send`(stanza, *[, timeout, cb]) | Send a stanza.
  `aioxmpp.Client.enqueue`(stanza, **kwargs) | Put a stanza in the internal transmission queue and return a token to track it.

  async send(stanza, timeout=None, *, cb=None)

    Deprecated alias of `aioxmpp.Client.send()`.

    This is only available on streams owned by a `aioxmpp.Client`.

    Deprecated since version 0.10.

  enqueue(stanza, **kwargs)

    Deprecated alias of `aioxmpp.Client.enqueue()`.

    This is only available on streams owned by a `aioxmpp.Client`.

    Deprecated since version 0.10.

  enqueue_stanza()

    Alias of `enqueue()`.

    Deprecated since version 0.8: This alias is deprecated and will be removed in 1.0.

  async send_and_wait_for_sent(stanza)

    Send the given stanza over the given `StanzaStream` stream.

    Deprecated since version 0.8: This method will be removed in 1.0. Use `send()` instead.

  async send_iq_and_wait_for_reply(iq, *, timeout=None)

    Send an IQ stanza iq and wait for the response. If timeout is not `None`, it must be the time in seconds for which to wait for a response.

    If the response is a `"result"` IQ, the value of the `payload` attribute is returned. Otherwise, the exception generated from the `error` attribute is raised.

    See also

    `register_iq_response_future()` and `send_and_wait_for_sent()` for other cases raising exceptions.

    Deprecated since version 0.8: This method will be removed in 1.0. Use `send()` instead.

    Changed in version 0.8: On a timeout, `TimeoutError` is now raised instead of `asyncio.TimeoutError`.

  Receiving stanzas:

  register_iq_request_handler(type_, payload_cls, cb, *, with_send_reply=False)

    Register a coroutine function or a function returning an awaitable to run when an IQ request is received.

    Parameters:

      - type (`IQType`) – IQ type to react to (must be a request type).

      - payload_cls (`XMLStreamClass`) – Payload class to react to (subclass of `XSO`)

      - cb – Function or coroutine function to invoke

      - with_send_reply (`bool`) – Whether to pass a function to send a reply to cb as second argument.

    Raises:

      - ValueError – if there is already a coroutine registered for this target

      - ValueError – if type_ is not a request IQ type

      - ValueError – if type_ is not a valid `IQType` (and cannot be cast to a `IQType`)

    The callback cb will be called whenever an IQ stanza with the given type_ and payload being an instance of the payload_cls is received.

    The callback must either be a coroutine function or otherwise return an awaitable. The awaitable must evaluate to a valid value for the `IQ.payload` attribute. That value will be set as the payload attribute value of an IQ response (with type `RESULT`) which is generated and sent by the stream.

    If the awaitable or the function raises an exception, it will be converted to a `Error` object. That error object is then used as payload for an IQ response (with type `ERROR`) which is generated and sent by the stream.

    If the exception is a subclass of `aioxmpp.errors.XMPPError`, it is converted to an `Error` instance directly. Otherwise, it is wrapped in a `aioxmpp.XMPPCancelError` with `undefined-condition`.

    For this to work, payload_cls must be registered using `as_payload_class()`. Otherwise, the payload will not be recognised by the stream parser and the IQ is automatically responded to with a `feature-not-implemented` error.

    Warning

    When using a coroutine function for cb, there is no guarantee that concurrent IQ handlers and other coroutines will execute in any defined order. This implies that the strong ordering guarantees normally provided by XMPP XML Streams are lost when using coroutine functions for cb. For this reason, the use of non-coroutine functions is allowed.

    Note

    Using a non-coroutine function for cb will generally lead to less readable code. For the sake of readability, it is recommended to prefer coroutine functions when strong ordering guarantees are not needed.

    New in version 0.11: When the argument with_send_reply is true cb will be called with two arguments: the IQ stanza to handle and a unary function send_reply(result=None) that sends a response to the IQ request and prevents that an automatic response is sent. If result is an instance of `XMPPError` an error result is generated.

    This is useful when the handler function needs to execute actions which happen after the IQ result has been sent, for example, sending other stanzas.

    Changed in version 0.10: Accepts an awaitable as last argument in addition to coroutine functions.

    Renamed from `register_iq_request_coro()`.

    New in version 0.6: If the stream is `stop()`-ped (only if SM is not enabled) or `close()`ed, running IQ response coroutines are `asyncio.Task.cancel()`-led.

    To protect against that, fork from your coroutine using `asyncio.ensure_future()`.

    Changed in version 0.7: The type_ argument is now supposed to be a `IQType` member.

    Deprecated since version 0.7: Passing a `str` as type_ argument is deprecated and will raise a `TypeError` as of the 1.0 release. See the Changelog for Version 0.7 for further details on how to upgrade your code efficiently.

  unregister_iq_request_handler(type_, payload_cls)

    Unregister a coroutine previously registered with `register_iq_request_handler()`.

    Parameters:

      - type (`IQType`) – IQ type to react to (must be a request type).

      - payload_cls (`XMLStreamClass`) – Payload class to react to (subclass of `XSO`)

    Raises:

      - KeyError – if no coroutine has been registered for the given `(type_, payload_cls)` pair

      - ValueError – if type_ is not a valid `IQType` (and cannot be cast to a `IQType`)

    The match is solely made using the type_ and payload_cls arguments, which have the same meaning as in `register_iq_request_coro()`.

    Changed in version 0.10: Renamed from `unregister_iq_request_coro()`.

    Changed in version 0.7: The type_ argument is now supposed to be a `IQType` member.

    Deprecated since version 0.7: Passing a `str` as type_ argument is deprecated and will raise a `TypeError` as of the 1.0 release. See the Changelog for Version 0.7 for further details on how to upgrade your code efficiently.

  register_message_callback(type_, from_, cb)

    Register a callback to be called when a message is received.

    Parameters:

      - type (`MessageType` or `None`) – Message type to listen for, or `None` for a wildcard match.

      - from (`JID` or `None`) – Sender JID to listen for, or `None` for a wildcard match.

      - cb – Callback function to call

    Raises:

      - ValueError – if another function is already registered for the same `(type_, from_)` pair.

      - ValueError – if type_ is not a valid `MessageType` (and cannot be cast to a `MessageType`)

    cb will be called whenever a message stanza matching the type_ and from_ is received, according to the wildcarding rules below. More specific callbacks win over less specific callbacks, and the match on the from_ address takes precedence over the match on the type_.

    See `SimpleStanzaDispatcher.register_callback()` for the exact wildcarding rules.

    Changed in version 0.7: The type_ argument is now supposed to be a `MessageType` member.

    Deprecated since version 0.7: Passing a `str` as type_ argument is deprecated and will raise a `TypeError` as of the 1.0 release. See the Changelog for Version 0.7 for further details on how to upgrade your code efficiently.

    Deprecated since version 0.9: This method has been deprecated in favour of and is now implemented in terms of the `aioxmpp.dispatcher.SimpleMessageDispatcher` service.

    It is equivalent to call `register_callback()`, except that the latter is not deprecated.

  unregister_message_callback(type_, from_)

    Unregister a callback previously registered with `register_message_callback()`.

    Parameters:

      - type (`MessageType` or `None`) – Message type to listen for.

      - from (`JID` or `None`) – Sender JID to listen for.

    Raises:

      - KeyError – if no function is currently registered for the given `(type_, from_)` pair.

      - ValueError – if type_ is not a valid `MessageType` (and cannot be cast to a `MessageType`)

    The match is made on the exact pair; it is not possible to unregister arbitrary listeners by passing `None` to both arguments (i.e. the wildcarding only applies for receiving stanzas, not for unregistering callbacks; unregistering the super-wildcard with both arguments set to `None` is of course possible).

    Changed in version 0.7: The type_ argument is now supposed to be a `MessageType` member.

    Deprecated since version 0.7: Passing a `str` as type_ argument is deprecated and will raise a `TypeError` as of the 1.0 release. See the Changelog for Version 0.7 for further details on how to upgrade your code efficiently.

    Deprecated since version 0.9: This method has been deprecated in favour of and is now implemented in terms of the `aioxmpp.dispatcher.SimpleMessageDispatcher` service.

    It is equivalent to call `unregister_callback()`, except that the latter is not deprecated.

  register_presence_callback(type_, from_, cb)

    Register a callback to be called when a presence stanza is received.

    Parameters:

      - type (`PresenceType`) – Presence type to listen for.

      - from (`JID` or `None`.) – Sender JID to listen for, or `None` for a wildcard match.

      - cb – Callback function

    Raises:

      - ValueError – if another listener with the same `(type_, from_)` pair is already registered

      - ValueError – if type_ is not a valid `PresenceType` (and cannot be cast to a `PresenceType`)

    cb will be called whenever a presence stanza matching the type_ is received from the specified sender. from_ may be `None` to indicate a wildcard. Like with `register_message_callback()`, more specific callbacks win over less specific callbacks. The fallback order is identical, except that the `type_=None` entries described there do not apply for presence stanzas and are thus omitted.

    See `SimpleStanzaDispatcher.register_callback()` for the exact wildcarding rules.

    Changed in version 0.7: The type_ argument is now supposed to be a `PresenceType` member.

    Deprecated since version 0.7: Passing a `str` as type_ argument is deprecated and will raise a `TypeError` as of the 1.0 release. See the Changelog for Version 0.7 for further details on how to upgrade your code efficiently.

    Deprecated since version 0.9: This method has been deprecated. It is recommended to use `aioxmpp.PresenceClient` instead.

  unregister_presence_callback(type_, from_)

    Unregister a callback previously registered with `register_presence_callback()`.

    Parameters:

      - type (`PresenceType`) – Presence type to listen for.

      - from (`JID` or `None`.) – Sender JID to listen for, or `None` for a wildcard match.

    Raises:

      - KeyError – if no callback is currently registered for the given `(type_, from_)` pair

      - ValueError – if type_ is not a valid `PresenceType` (and cannot be cast to a `PresenceType`)

    The match is made on the exact pair; it is not possible to unregister arbitrary listeners by passing `None` to the from_ arguments (i.e. the wildcarding only applies for receiving stanzas, not for unregistering callbacks; unregistering a wildcard match with from_ set to `None` is of course possible).

    Changed in version 0.7: The type_ argument is now supposed to be a `PresenceType` member.

    Deprecated since version 0.7: Passing a `str` as type_ argument is deprecated and will raise a `TypeError` as of the 1.0 release. See the Changelog for Version 0.7 for further details on how to upgrade your code efficiently.

    Deprecated since version 0.9: This method has been deprecated. It is recommended to use `aioxmpp.PresenceClient` instead.

  Rarely used registries / deprecated aliases:

  register_iq_request_coro(type_, payload_cls, coro)

    Alias of `register_iq_request_handler()`.

    Deprecated since version 0.10: This alias will be removed in version 1.0.

  unregister_iq_request_coro(type_, payload_cls)
  register_iq_response_future(from_, id_, fut)

    Register a future fut for an IQ stanza with type `result` or `error` from the `JID` from_ with the id id_.

    If the type of the IQ stanza is `result`, the stanza is set as result to the future. If the type of the IQ stanza is `error`, the stanzas error field is converted to an exception and set as the exception of the future.

    The future might also receive different exceptions:

    - `errors.ErroneousStanza`, if the response stanza received could not be parsed.

      Note that this exception is not emitted if the `from` address of the stanza is unset, because the code cannot determine whether a sender deliberately used an erroneous address to make parsing fail or no sender address was used. In the former case, an attacker could use that to inject a stanza which would be taken as a stanza from the peer server. Thus, the future will never be fulfilled in these cases.

      Also note that this exception does not derive from `errors.XMPPError`, as it cannot provide the same attributes. Instead, it derives from `errors.StanzaError`, from which `errors.XMPPError` also derives; to catch all possible stanza errors, catching `errors.StanzaError` is sufficient and future-proof.

    - `ConnectionError` if the stream is `stop()`-ped (only if SM is not enabled) or `close()`-ed.

    - Any `Exception` which may be raised from `send_xso()`, which are generally also `ConnectionError` or at least `OSError` subclasses.

  register_iq_response_callback(from_, id_, cb)

    Register a callback function cb to be called when a IQ stanza with type `result` or `error` is received from the `JID` from_ with the id id_.

    The callback is called at most once.

    Note

    In contrast to `register_iq_response_future()`, errors which occur on a level below XMPP stanzas cannot be caught using a callback.

    If you need notification about other errors and still want to use callbacks, use of a future with `asyncio.Future.add_done_callback()` is recommended.

  unregister_iq_response(from_, id_)

    Unregister a registered callback or future for the IQ response identified by from_ and id_. See `register_iq_response_future()` or `register_iq_response_callback()` for details on the arguments meanings and how to register futures and callbacks respectively.

    Note

    Futures will automatically be unregistered when they are cancelled.

  Inbound Stanza Filters (see Stanza Filters):

  app_inbound_presence_filter

    This is a `AppFilter` based filter chain on inbound presence stanzas. It can be used to attach application-specific filters.

  service_inbound_presence_filter

    This is another filter chain for inbound presence stanzas. It runs before the `app_inbound_presence_filter` chain and all functions registered there must have `service.Service` classes as order value (see `Filter.register()`).

    This filter chain is intended to be used by library services, such as a XEP-0115 implementation which may start a XEP-0030 lookup at the target entity to resolve the capability hash or prime the XEP-0030 cache with the service information obtained by interpreting the XEP-0115 hash value.

  app_inbound_message_filter

    This is a `AppFilter` based filter chain on inbound message stanzas. It can be used to attach application-specific filters.

  service_inbound_message_filter

    This is the analogon of `service_inbound_presence_filter` for `app_inbound_message_filter`.

  Outbound Stanza Filters (see Stanza Filters):

  app_outbound_presence_filter

    This is a `AppFilter` based filter chain on outbound presence stanzas. It can be used to attach application-specific filters.

    Before using this attribute, make sure that you have read the notes above.

  service_outbound_presence_filter

    This is the analogon of `service_inbound_presence_filter`, but for outbound presence. It runs after the `app_outbound_presence_filter()`.

    Before using this attribute, make sure that you have read the notes above.

  app_outbound_message_filter

    This is a `AppFilter` based filter chain on inbound message stanzas. It can be used to attach application-specific filters.

    Before using this attribute, make sure that you have read the notes above.

  service_outbound_messages_filter

    This is the analogon of `service_outbound_presence_filter`, but for outbound messages.

    Before using this attribute, make sure that you have read the notes above.

  Using stream management:

  async start_sm(request_resumption=True, resumption_timeout=None)

    Start stream management (version 3).

    Parameters:

      - request_resumption (`bool`) – Request that the stream shall be resumable.

      - resumption_timeout (`int`) – Maximum time in seconds for a stream to be resumable.

    Raises:

      aioxmpp.errors.StreamNegotiationFailure – if the server rejects the attempt to enable stream management.

    This method attempts to starts stream management on the stream.

    resumption_timeout is the `max` attribute on `nonza.SMEnabled`; it can be used to set a maximum time for which the server shall consider the stream to still be alive after the underlying transport (TCP) has failed. The server may impose its own maximum or ignore the request, so there are no guarantees that the session will stay alive for at most or at least resumption_timeout seconds. Passing a resumption_timeout of 0 is equivalent to passing false to request_resumption and takes precedence over request_resumption.

    Note

    In addition to server implementation details, it is very well possible that the server does not even detect that the underlying transport has failed for quite some time for various reasons (including high TCP timeouts).

    If the server rejects the attempt to enable stream management, a `errors.StreamNegotiationFailure` is raised. The stream is still running in that case.

    Warning

    This method cannot and does not check whether the server advertised support for stream management. Attempting to negotiate stream management without server support might lead to termination of the stream.

    If an XML stream error occurs during the negotiation, the result depends on a few factors. In any case, the stream is not running afterwards. If the `nonza.SMEnabled` response was not received before the XML stream died, SM is also disabled and the exception which caused the stream to die is re-raised (this is due to the implementation of `send_and_wait_for()`). If the `nonza.SMEnabled` response was received and annonuced support for resumption, SM is enabled. Otherwise, it is disabled. No exception is raised if `nonza.SMEnabled` was received, as this method has no way to determine that the stream failed.

    If negotiation succeeds, this coroutine initializes a new stream management session. The stream management state attributes become available and `sm_enabled` becomes `True`.

  async resume_sm(xmlstream)

    Resume an SM-enabled stream using the given xmlstream.

    If the server rejects the attempt to resume stream management, a `errors.StreamNegotiationFailure` is raised. The stream is then in stopped state and stream management has been stopped.

    Warning

    This method cannot and does not check whether the server advertised support for stream management. Attempting to negotiate stream management without server support might lead to termination of the stream.

    If the XML stream dies at any point during the negotiation, the SM state is left unchanged. If no response has been received yet, the exception which caused the stream to die is re-raised. The state of the stream depends on whether the main task already noticed the dead stream.

    If negotiation succeeds, this coroutine resumes the stream management session and initiates the retransmission of any unacked stanzas. The stream is then in running state.

    Changed in version 0.11: Support for using the counter value provided some servers on a failed resumption was added. Stanzas which are covered by the counter will be marked as `ACKED`; other stanzas will be marked as `DISCONNECTED`.

    This is in contrast to the behaviour when resumption fails without a counter given. In that case, stanzas which have not been acked are marked as `SENT_WITHOUT_SM`.

  stop_sm()

    Disable stream management on the stream.

    Attempting to call this method while the stream is running or without stream management enabled results in a `RuntimeError`.

    Any sent stanzas which have not been acked by the remote yet are put into `StanzaState.SENT_WITHOUT_SM` state.

  sm_enabled

    `True` if stream management is currently enabled on the stream, `False` otherwise.

  Stream management state inspection:

  sm_outbound_base

    The last value of the remote stanza counter.

    Note

    Accessing this attribute when `sm_enabled` is `False` raises `RuntimeError`.

  sm_inbound_ctr

    The current value of the inbound stanza counter.

    Note

    Accessing this attribute when `sm_enabled` is `False` raises `RuntimeError`.

  sm_unacked_list

    A copy of the list of stanza tokens which have not yet been acked by the remote party.

    Note

    Accessing this attribute when `sm_enabled` is `False` raises `RuntimeError`.

    Accessing this attribute is expensive, as the list is copied. In general, access to this attribute should not be necessary at all.

  sm_id

    The value of the `id` attribute of the `SMEnabled` response from the server.

    Note

    Accessing this attribute when `sm_enabled` is `False` raises `RuntimeError`.

  sm_max

    The value of the `max` attribute of the `SMEnabled` response from the server.

    Note

    Accessing this attribute when `sm_enabled` is `False` raises `RuntimeError`.

  sm_location

    The value of the `location` attribute of the `SMEnabled` response from the server.

    Note

    Accessing this attribute when `sm_enabled` is `False` raises `RuntimeError`.

  sm_resumable

    The value of the `resume` attribute of the `SMEnabled` response from the server.

    Note

    Accessing this attribute when `sm_enabled` is `False` raises `RuntimeError`.

  Miscellaneous:

  local_jid

    The local_jid argument to the constructor.

    Warning

    Changing this arbitrarily while the stream is running may have unintended side effects.

  Signals:

  signal on_failure(exc)

    Emits when the stream has failed, i.e. entered stopped state without request by the user.

    Parameters:

      exc (`Exception`) – The exception which caused the stream to fail.

    A failure occurs whenever the main task of the `StanzaStream` (the one started by `start()`) terminates with an exception.

    Examples are `ConnectionError` as raised upon a ping timeout and any exceptions which may be raised by the `aioxmpp.protocol.XMLStream.send_xso()` method.

    Before `on_failure()` is emitted, the `XMLStream` is `abort()`-ed if SM is enabled and `close()`-ed if SM is not enabled.

    Changed in version 0.6: The closing behaviour was added.

  signal on_stream_destroyed(reason)

    The stream has been stopped in a manner which means that all state must be discarded.

    Parameters:

      reason (`Exception`) – The exception which caused the stream to be destroyed.

    When this signal is emitted, others have or will most likely see unavailable presence from the XMPP resource associated with the stream, and stanzas sent in the mean time are not guaranteed to be received.

    reason may be a `DestructionRequested` instance to indicate that the destruction was requested by the user, in some way.

    There is no guarantee (it is not even likely) that it is possible to send stanzas over the stream at the time this signal is emitted.

    Changed in version 0.8: The reason argument was added.

  signal on_stream_established()

    When a stream is newly established, this signal is fired. This happens whenever a non-SM stream is started and whenever a stream which previously had SM disabled is started with SM enabled.

  signal on_message_received(stanza)

    Emits when a `aioxmpp.Message` stanza has been received.

    Parameters:

      stanza (`aioxmpp.Message`) – The received stanza.

    See also

    `aioxmpp.dispatcher.SimpleMessageDispatcher`

      for a service which allows to register callbacks for messages based on the sender and type of the message.

    New in version 0.9.

  signal on_presence_received(stanza)

    Emits when a `aioxmpp.Presence` stanza has been received.

    Parameters:

      stanza (`aioxmpp.Presence`) – The received stanza.

    See also

    `aioxmpp.dispatcher.SimplePresenceDispatcher`

      for a service which allows to register callbacks for presences based on the sender and type of the message.

    New in version 0.9.

## Context managers

The following context managers can be used together with `StanzaStream` instances and the filters available on them.

aioxmpp.stream.iq_handler(stream, type_, payload_cls, coro, *, with_send_reply=False)

  Context manager to temporarily register a coroutine to handle IQ requests on a `StanzaStream`.

  Parameters:

    - stream (`StanzaStream`) – Stanza stream to register the coroutine at

    - type (`IQType`) – IQ type to react to (must be a request type).

    - payload_cls (`XMLStreamClass`) – Payload class to react to (subclass of `XSO`)

    - coro – Coroutine to register

    - with_send_reply (`bool`) – Whether to pass a function to send the reply early to cb.

  The coroutine is registered when the context is entered and unregistered when the context is exited. Running coroutines are not affected by exiting the context manager.

  New in version 0.11: The with_send_reply argument. See `aioxmpp.stream.StanzaStream.register_iq_request_handler()` for more detail.

  New in version 0.8.

aioxmpp.stream.message_handler(stream, type_, from_, cb)

  Context manager to temporarily register a callback to handle messages on a `StanzaStream`.

  Parameters:

    - stream (`StanzaStream`) – Stanza stream to register the coroutine at

    - type (`MessageType` or `None`) – Message type to listen for, or `None` for a wildcard match.

    - from (`JID` or `None`) – Sender JID to listen for, or `None` for a wildcard match.

    - cb – Callback to register

  The callback is registered when the context is entered and unregistered when the context is exited.

  New in version 0.8.

aioxmpp.stream.presence_handler(stream, type_, from_, cb)

  Context manager to temporarily register a callback to handle presence stanzas on a `StanzaStream`.

  Parameters:

    - stream (`StanzaStream`) – Stanza stream to register the coroutine at

    - type (`PresenceType`) – Presence type to listen for.

    - from (`JID` or `None`.) – Sender JID to listen for, or `None` for a wildcard match.

    - cb – Callback to register

  The callback is registered when the context is entered and unregistered when the context is exited.

  New in version 0.8.

aioxmpp.stream.stanza_filter(filter_, func, order=<object object>)

  This is a deprecated alias of `aioxmpp.callbacks.Filter.context_register()`.

  New in version 0.8.

  Deprecated since version 0.9.

## Low-level stanza tracking

The following classes are used to track stanzas in the XML stream to the server. This is independent of things like Message Delivery Receipts (for which services are provided at `aioxmpp.tracking`); it only provides tracking to the remote server and even that only if stream management is used. Otherwise, it only provides tracking in the `aioxmpp` internal queues.

class aioxmpp.stream.StanzaToken(stanza, *, on_state_change=None)

  A token to follow the processing of a stanza.

  on_state_change may be a function which will be called with the token and the new `StanzaState` whenever the state of the token changes.

  New in version 0.8: Stanza tokens are awaitable.

  await token
  yield from token

    Wait until the stanza is either sent or failed to sent.

    Warning

    This only works with Python 3.5 or newer.

    Raises ConnectionError:

      if the stanza enters `DISCONNECTED` state.

    Raises RuntimeError:

      if the stanza enters `ABORTED` or `DROPPED` state.

    Raises Exception:

      re-raised if the stanza token fails to serialise or another transient transport problem occurs.

    Return:

      `None`

    If a coroutine awaiting a token is cancelled, the token is aborted. Use `asyncio.shield()` to prevent this.

    Warning

    This is no guarantee that the recipient received the stanza. Without stream management, it can not even guaranteed that the server has seen the stanza.

    This is primarily useful as a synchronisation primitive between the sending of a stanza and another stream operation, such as closing the stream.

  Note

  Exceptions sent to the stanza token (when it enters `StanzaState.FAILED`) are only available by awaiting the token, not via the callback.

  state

    The current `StanzaState` of the token. Tokens are created with `StanzaState.ACTIVE`.

  abort()

    Abort the stanza. Attempting to call this when the stanza is in any non-`ACTIVE`, non-`ABORTED` state results in a `RuntimeError`.

    When a stanza is aborted, it will reside in the active queue of the stream, not will be sent and instead discarded silently.

class aioxmpp.stream.StanzaState(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

  The various states an outgoing stanza can have.

  ACTIVE

    The stanza has just been enqueued for sending and has not been taken care of by the StanzaStream yet.

  SENT

    The stanza has been sent over a stream with Stream Management enabled, but not acked by the remote yet.

  ACKED

    The stanza has been sent over a stream with Stream Management enabled and has been acked by the remote.

    This is a final state.

  SENT_WITHOUT_SM

    The stanza has been sent over a stream without Stream Management enabled or has been sent over a stream with Stream Management enabled, but for which resumption has failed before the stanza has been acked.

    This is a final state.

  ABORTED

    The stanza has been retracted before it left the active queue.

    This is a final state.

  DROPPED

    The stanza has been dropped by one of the filters configured in the `StanzaStream`.

    This is a final state.

  DISCONNECTED

    The stream has been stopped (without SM) or closed before the stanza was sent.

    This is a final state.

  FAILED

    It was attempted to send the stanza, but it failed to serialise to valid XML or another non-fatal transport error occurred.

    This is a final state.

    New in version 0.9.

## Filters

The service-level filters used by the `StanzaStream` use `Filter`. The application-level filters are using the following class:

class aioxmpp.stream.AppFilter

  A specialized `Filter` version. The only difference is in the handling of the order argument to `register()`:

  register(func, order=0)

    This method works exactly like `Filter.register()`, but order has a default value of `0`.

## Exceptions

class aioxmpp.stream.DestructionRequested

  Subclass of `ConnectionError` indicating that the destruction of the stream was requested by the user, directly or indirectly.