Module autobahn.util

class autobahn.util.EqualityMixin[source]

Mixing to add equality comparison operators to a class.

Two objects are identical under this mixin, if and only if:

  1. both object have the same class

  2. all non-private object attributes are equal

class autobahn.util.IdGenerator[source]

ID generator for WAMP request IDs.

WAMP request IDs are sequential per WAMP session, starting at 1 and wrapping around at 2**53 (both value are inclusive [1, 2**53]).

The upper bound 2**53 is chosen since it is the maximum integer that can be represented as a IEEE double such that all smaller integers are representable as well.

Hence, IDs can be safely used with languages that use IEEE double as their main (or only) number type (JavaScript, Lua, etc).

See https://github.com/wamp-proto/wamp-proto/blob/master/spec/basic.md#ids

next()[source]

Returns next ID.

Returns

The next ID.

Return type

int

class autobahn.util.ObservableMixin[source]

Internal utility for enabling event-listeners on particular objects

fire(event, *args, **kwargs)[source]

Fire a particular event.

Parameters

event – the event to fire. All other args and kwargs are passed on to the handler(s) for the event.

Returns

a Deferred/Future gathering all async results from all handlers and/or parent handlers.

off(event=None, handler=None)[source]

Stop listening for a single event, or all events.

Parameters
  • event – if None, remove all listeners. Otherwise, remove listeners for the single named event.

  • handler – if None, remove all handlers for the named event; otherwise remove just the given handler.

on(event, handler)[source]

Add a handler for an event.

Parameters
  • event – the name of the event

  • handler – a callable thats invoked when .fire() is called for this events. Arguments will be whatever are given to .fire()

set_valid_events(valid_events=None)[source]
Parameters

valid_events – if non-None, .on() or .fire() with an event not listed in valid_events raises an exception.

class autobahn.util.Stopwatch(start=True)[source]

Stopwatch based on walltime.

This can be used to do code timing and uses the most precise walltime measurement available on the platform. This is a very light-weight object, so create/dispose is very cheap.

Parameters

start (bool) – If True, immediately start the stopwatch.

elapsed()[source]

Return total time elapsed in seconds during which the stopwatch was running.

Returns

The elapsed time in seconds.

Return type

float

pause()[source]

Pauses the stopwatch and returns total time elapsed in seconds during which the stopwatch was running.

Returns

The elapsed time in seconds.

Return type

float

resume()[source]

Resumes a paused stopwatch and returns total elapsed time in seconds during which the stopwatch was running.

Returns

The elapsed time in seconds.

Return type

float

stop()[source]

Stops the stopwatch and returns total time elapsed in seconds during which the stopwatch was (previously) running.

Returns

The elapsed time in seconds.

Return type

float

class autobahn.util.Tracker(tracker, tracked)[source]

A key-based statistics tracker.

absolute(key)[source]

Return the UTC wall-clock time at which a tracked event occurred.

Parameters

key (str) – The key

Returns

Timezone-naive datetime.

Return type

instance of datetime.datetime

diff(start_key, end_key, formatted=True)[source]

Get elapsed difference between two previously tracked keys.

Parameters
  • start_key (str) – First key for interval (older timestamp).

  • end_key (str) – Second key for interval (younger timestamp).

  • formatted (bool) – If True, format computed time period and return string.

Returns

Computed time period in seconds (or formatted string).

Return type

float or str

track(key)[source]

Track elapsed for key.

Parameters

key (str) – Key under which to track the timing.

autobahn.util.encode_truncate(text, limit, encoding='utf8', return_encoded=True)[source]

Given a string, return a truncated version of the string such that the UTF8 encoding of the string is smaller than the given limit.

This function correctly truncates even in the presence of Unicode code points that encode to multi-byte encodings which must not be truncated in the middle.

Parameters
  • text (str) – The (Unicode) string to truncate.

  • limit (int) – The number of bytes to limit the UTF8 encoding to.

  • encoding (str) – Truncate the string in this encoding (default is utf-8).

  • return_encoded (bool) – If True, return the string encoded into bytes according to the specified encoding, else return the string as a string.

Returns

The truncated string.

Return type

str or bytes

autobahn.util.generate_activation_code()[source]

Generate a one-time activation code or token of the form 'W97F-96MJ-YGJL'. The generated value is cryptographically strong and has (at least) 57 bits of entropy.

Returns

The generated activation code.

Return type

str

autobahn.util.generate_serial_number()[source]

Generate a globally unique serial / product code of the form 'YRAC-EL4X-FQQE-AW4T-WNUV-VN6T'. The generated value is cryptographically strong and has (at least) 114 bits of entropy.

Returns

The generated serial number / product code.

Return type

str

autobahn.util.generate_token(char_groups: int, chars_per_group: int, chars: Optional[str] = None, sep: Optional[str] = None, lower_case: Optional[bool] = False) str[source]

Generate cryptographically strong tokens, which are strings like M6X5-YO5W-T5IK. These can be used e.g. for used-only-once activation tokens or the like.

The returned token has an entropy of math.log(len(chars), 2.) * chars_per_group * char_groups bits.

With the default charset and 4 characters per group, generate_token() produces strings with the following entropy:

character groups

entropy (at least)

recommended use

2

38 bits

3

57 bits

one-time activation or pairing code

4

76 bits

secure user password

5

95 bits

6

114 bits

globally unique serial / product code

7

133 bits

Here are some examples:

  • token(3): 9QXT-UXJW-7R4H

  • token(4): LPNN-JMET-KWEP-YK45

  • token(6): NXW9-74LU-6NUH-VLPV-X6AG-QUE3

Parameters
  • char_groups – Number of character groups (or characters if chars_per_group == 1).

  • chars_per_group – Number of characters per character group (or 1 to return a token with no grouping).

  • chars – Characters to choose from. Default is 27 character subset of the ISO basic Latin alphabet (see: DEFAULT_TOKEN_CHARS).

  • sep – When separating groups in the token, the separater string.

  • lower_case – If True, generate token in lower-case.

Returns

The generated token.

autobahn.util.generate_user_password()[source]

Generate a secure, random user password of the form 'kgojzi61dn5dtb6d'. The generated value is cryptographically strong and has (at least) 76 bits of entropy.

Returns

The generated password.

Return type

str

autobahn.util.id()[source]

Generate a new random integer ID from range [0, 2**53].

The generated ID is based on a pseudo-random number generator (Mersenne Twister, which has a period of 2**19937-1). It is NOT cryptographically strong, and hence NOT suitable to generate e.g. secret keys or access tokens.

The upper bound 2**53 is chosen since it is the maximum integer that can be represented as a IEEE double such that all smaller integers are representable as well.

Hence, IDs can be safely used with languages that use IEEE double as their main (or only) number type (JavaScript, Lua, etc).

Returns

A random integer ID.

Return type

int

autobahn.util.machine_id() str[source]

For informational purposes, get a unique ID or serial for this machine (device).

Returns

Unique machine (device) ID (serial), e.g. 81655b901e334fc1ad59cbf2719806b7.

autobahn.util.newid(length=16)[source]

Generate a new random string ID.

The generated ID is uniformly distributed and cryptographically strong. It is hence usable for things like secret keys and access tokens.

Parameters

length (int) – The length (in chars) of the ID to generate.

Returns

A random string ID.

Return type

str

autobahn.util.parse_keyfile(key_path: str, private: bool = True) OrderedDict[source]

Internal helper. This parses a node.pub or node.priv file and returns a dict mapping tags -> values.

autobahn.util.public(obj)[source]

The public user API of Autobahn is marked using this decorator. Everything that is not decorated @public is library internal, can change at any time and should not be used in user program code.

autobahn.util.rid()[source]

Generate a new random integer ID from range [0, 2**53].

The generated ID is uniformly distributed over the whole range, doesn’t have a period (no pseudo-random generator is used) and cryptographically strong.

The upper bound 2**53 is chosen since it is the maximum integer that can be represented as a IEEE double such that all smaller integers are representable as well.

Hence, IDs can be safely used with languages that use IEEE double as their main (or only) number type (JavaScript, Lua, etc).

Returns

A random integer ID.

Return type

int

autobahn.util.rtime()[source]

Precise, fast wallclock time.

Returns

The current wallclock in seconds. Returned values are only guaranteed to be meaningful relative to each other.

Return type

float

autobahn.util.utcnow()[source]

Get current time in UTC as ISO 8601 string.

Returns

Current time as string in ISO 8601 format.

Return type

str

autobahn.util.utcstr(ts=None)[source]

Format UTC timestamp in ISO 8601 format.

Note: to parse an ISO 8601 formatted string, use the iso8601 module instead (e.g. iso8601.parse_date("2014-05-23T13:03:44.123Z")).

>>> txaio.time_ns()
1641121311914026419
>>> int(iso8601.parse_date(utcnow()).timestamp() * 1000000000.)
1641121313209000192
Parameters

ts (instance of datetime.datetime or None) – The timestamp to format.

Returns

Timestamp formatted in ISO 8601 format.

Return type

str

autobahn.util.write_keyfile(filepath, tags, msg)[source]

Internal helper, write the given tags to the given file-

autobahn.util.xor(d1: bytes, d2: bytes) bytes[source]

XOR two binary strings of arbitrary (equal) length.

Parameters
  • d1 – The first binary string.

  • d2 – The second binary string.

Returns

XOR of the binary strings (XOR(d1, d2))