# `utils` — Internal utils

Miscellaneous utilities used throughout the aioxmpp codebase.

aioxmpp.utils.namespaces

  Collects all the namespaces from the various standards. Each namespace is given a shortname and its value is the namespace string.

  Note

  This is intended to be promoted to the public API in a future release. Third-party users should not assign short-names for their own namespaces here, but instead use a separate instance of `Namespaces`.

class aioxmpp.utils.Namespaces

  Manage short-hands for XML namespaces.

  Instances of this class may be used to assign mnemonic short-hands to XML namespaces, for example:

      namespaces = Namespaces()
      namespaces.foo = "urn:example:foo"
      namespaces.bar = "urn:example:bar"

  The class ensures that

  1. only one short-hand is bound to each namespace, so continuing the example, the following raises `ValueError`:

         namespace.example_foo = "urn:example:foo"

  2. no short-hand is redefined to point to a different namespace, continuing the example, the following raises `ValueError`:

         namespaces.foo = "urn:example:foo:2"

  3. deleting a short-hand is prohibited, the following raises `AttributeError`:

         del namespaces.foo

  The defined short-hands MUST NOT start with an underscore.

  Note

  This is intended to be promoted to the public API in a future release.

async aioxmpp.utils.gather_reraise_multi(*fut_or_coros, message='gather_reraise_multi')

  Wrap all the arguments fut_or_coros in futures with `asyncio.ensure_future()` and wait until all of them are finish or fail.

  Parameters

    - fut_or_coros (future or coroutine) – the futures or coroutines to wait for

    - message (`str`) – the message included with the raised `aioxmpp.errors.GatherError` in the case of failure.

  Returns

    the list of the results of the arguments.

  Raises

    aioxmpp.errors.GatherError – if any of the futures or coroutines fail.

  If an exception was raised, reraise all exceptions wrapped in a `aioxmpp.errors.GatherError` with the message set to message.

  Note

  This is similar to the standard function `asyncio.gather()`, but avoids the in-band signalling of raised exceptions as return values, by raising exceptions bundled as a `aioxmpp.errors.GatherError`.

  Note

  Use this function only if you are either

  1. not interested in the return values, or

  2. only interested in the return values if all futures are successful.

aioxmpp.utils.mkdir_exist_ok(path)

  Create a directory (including parents) if it does not exist yet.

  Parameters

    path (`pathlib.Path`) – Path to the directory to create.

  Uses `pathlib.Path.mkdir()`; if the call fails with `FileNotFoundError` and path refers to a directory, it is treated as success.

aioxmpp.utils.to_nmtoken(rand_token)

  Convert a (random) token given as raw `bytes` or `int` to a valid NMTOKEN <https://www.w3.org/TR/xml/#NT-Nmtoken>.

  The encoding as a valid nmtoken is injective, ensuring that two different inputs cannot yield the same token. Nevertheless, it is recommended to only use one kind of inputs (integers or bytes of a consistent length) in one context.

class aioxmpp.utils.LazyTask(coroutine_function, *args)

  `asyncio.Future` subclass which spawns a coroutine when it is first awaited.

  Parameters

    - coroutine_function – The coroutine function to invoke.

    - args – Arguments to pass to coroutine_function.

  `LazyTask` objects are awaitable. When the first attempt to await them is made, the coroutine_function is started with the given args and the result is awaited. Any further awaits on the `LazyTask` will await the same coroutine.

class aioxmpp.utils.AlivenessMonitor(loop)

  Monitors aliveness of a data stream.

  New in version 0.10.

  Parameters

    loop (`asyncio.BaseEventLoop`) – The event loop to operate the checks in.

  This class is a utility class to implement a traffic-efficient timeout mechanism.

  This class can be used to monitor a stream if it is possible to ask the remote party send some data (classic ping mechanism). It works particularly well if the remote party will send data even without being specifically asked for it (saves traffic).

  It is notabily not a mean to enforce a maximum acceptable round-trip time. Quite on the contrary, this class was designed specifically to provide a reliable experience even without an upper bound on the round-trip time.

  To use this class, the using code has to configure the `deadtime_soft_limit`, `deadtime_hard_limit`, subscribe to the signals below and call `notify_received()` whenever any data is received from the peer.

  There exist two timers, the soft limit timer and the hard limit timer (configured by the respective limit attributes). When the class is instantiated, the timers are reset to zero (but they start running immediately!).

  When a timer exceeds its respective limit, its corresponding signal is emitted. The signal is not re-emitted until the next call of `notfiy_received()`.

  When `notify_received()` is called, the timers are reset to zero.

  This allows for the following features:

  - Keep a stream alive on a high-latency link as long as data is pouring in.

    This is very useful on saturated (mobile) links. Imagine firing a MAM query and a bunch of avatar requests after connecting. With naive ping logic, this would easily cause the stream to be considered dead because the round-trip time is extremely high.

    However, with this logic, as long as data is pouring in, the stream is considered alive.

  - When using the soft limit to trigger a ping and a reasonable difference between the soft and the hard limit timeout, this logic gracefully reverts to classic pinging when no traffic is seen on the stream.

  - If the peer is pinging us in an interval which works for us (i.e. is less than the soft limit), we don’t need to ping the peer; no extra logic required.

  This mechanism is used by `aioxmpp.protocol.XMLStream`.

  signal on_deadtime_soft_limit_tripped()

    Emits when the `deadtime_soft_limit` expires.

  signal on_deadtime_hard_limit_tripped()

    Emits when the `deadtime_hard_limit` expires.

  notify_received()

    Inform the aliveness check that something was received.

    Resets the internal soft/hard limit timers.

  deadtime_soft_limit = None

    Soft limit for the timespan in which no data is received in the stream.

    When the last data reception was longer than this limit ago, `on_deadtime_soft_limit_tripped()` emits once.

    Changing this makes the monitor re-check its limits immediately. Setting this to `None` disables the soft limit check.

    Note that setting this to a value greater than `deadtime_hard_limit` means that the hard limit will fire first.

  deadtime_hard_limit = None

    Hard limit for the timespan in which no data is received in the stream.

    When the last data reception was longer than this limit ago, `on_deadtime_hard_limit_tripped()` emits once.

    Changing this makes the monitor re-check its limits immediately. Setting this to `None` disables the hard limit check.

    Note that setting this to a value less than `deadtime_soft_limit` means that the hard limit will fire first.

@aioxmpp.utils.magicmethod

  Decorator for methods that makes them work as instance and class method. The first argument will be the class if called on the class and the instance when called on the instance.

aioxmpp.utils.proxy_property(owner_attr, member_attr, *, readonly=False, allow_delete=False)

  Proxy a property of a member.

  Parameters

    - owner_attr (`str`) – The name of the attribute at which the member can be found.

    - member_attr (`str`) – The name of the member property to proxy.

    - readonly (`bool`) – If true, the proxied property will not be writable, even if the original property is writable.

    - allow_delete (`bool`) – If true, the `del` operator is allowed on the proxy property and will be forwarded to the target property.

  New in version 0.11.0.

  This can be useful when combining classes via composition instead of inheritance.

  It is not necessary to set readonly to true if the target property is already readonly.