Classes And Functions

Reference information for the significant classes, methods and functions in the library, appears here.

Listening And Connecting

ansar.connect.transporting.connect()

Initiates a network connection to the specified IP address and port number.

Parameters
  • self (Point) – async entity

  • requested_ipp (HostPort) – host and port to connect to

  • session (CreateFrame) – object to create on successful connection

  • encrypted (bool) – is the server encrypting

  • self_checking (bool) – enable periodic enquiry/ack to verify transport

  • api_client (str) – leading part of the outgoing request URI

  • ansar_server (bool) – is the remote server ansar-enabled

ansar.connect.transporting.listen()

Establishes a network presence at the specified IP address and port number.

Parameters
  • self (Point) – async entity

  • requested_ipp (HostPort) – host and port to listen at

  • session (CreateFrame) – object to create on successful connection

  • encrypted (bool) – is the client encrypting

  • api_server (list of classes) – declared list of expected messages (i.e. request URIs)

  • default_to_request (bool) – convert unknown request names into HttpRequests

  • ansar_client (bool) – is the remote client ansar-enabled

class ansar.connect.socketry.HostPort(host=None, port=None)

Combination of an IP address or name, and a port number.

Parameters
  • host (str) – IP address or name

  • port (int) – network port

class ansar.connect.socketry.SocketProxy(s, channel, transport, self_checking=False)

Local representation of an object at remote end of a network connection.

Parameters
  • s (socket descriptor) – associated network connection

  • channel (internal) – async socket loop

  • transport (internal) – associated buffering

class ansar.connect.socketry.Connected

Session notification, transport to server established.

Parameters
  • requested_ipp (HostPort) – IP and port to connect to

  • connected_ipp (HostPort) – local IP and port

  • remote_address (async address) – address of SocketProxy

  • opened_at (datetime) – moment of connection

class ansar.connect.socketry.Accepted

Session notification, transport to client established.

Parameters
  • requested_ipp (HostPort) – IP and port listening at

  • accepted_ipp (HostPort) – local IP and port

  • remote_address (async address) – address of SocketProxy

  • opened_at (datetime) – moment of acceptance

class ansar.connect.socketry.Abandoned

Session notification, remote termination of the messaging transport.

Parameters
  • opened_ipp (HostPort) – local IP address and port number

  • opened_at (datetime) – moment of termination

class ansar.connect.socketry.Closed

Session notification, local termination of the messaging transport.

Parameters
  • value (any) – completion value for the session

  • reason (str) – short description

  • opened_ipp (HostPort) – local IP address and port number

  • opened_at (datetime) – moment of termination

class ansar.connect.socketry.CreateFrame

Capture values needed for async object creation.

Parameters
  • object_type (function or Point-based class) – type to be created

  • args (tuple) – positional parameters

  • kw (dict) – named parameters

Publish And Subscribe

ansar.connect.directory.publish()

Establishes a pub-sub service presence under the specified name.

Parameters
  • self (Point) – async entity

  • requested_name (str) – name this object will be known by

  • create_session (CreateFrame) – object to create on successful connection

  • requested_scope (enumeration) – highest level at which to expose name

ansar.connect.directory.subscribe()

Establishes a pub-sub client search for the specified name.

Parameters
  • self (Point) – async entity

  • requested_search (str) – name to search for (regular expression)

  • create_session (CreateFrame) – object to create on successful connection

  • requested_scope (enumeration) – highest level at which to search for name

class ansar.connect.directory_if.Available

Session notification, transport to server established.

Parameters
  • matched_search (str) – name the client was looking for (regular expression)

  • matched_name (str) – name the server is known by

  • matched_scope (enumeration) – level at which match was made

  • opened_at (datetime) – start of messaging

  • route_key (str) – unique id for this session

  • agent_address (async address) – internal pub-sub controller

class ansar.connect.directory_if.Delivered

Session notification, transport to client established.

Parameters
  • matched_search (str) – name the client was looking for (regular expression)

  • matched_name (str) – name the server is known by

  • matched_scope (enumeration) – level at which match was made

  • opened_at (datetime) – start of messaging

  • route_key (str) – unique id for this session

  • agent_address (async address) – internal pub-sub controller

class ansar.connect.directory_if.Dropped

Session notification, shutdown of transport by remote end.

Parameters
  • matched_search (str) – name the client was looking for (regular expression)

  • matched_name (str) – name the server is known by

  • matched_scope (enumeration) – level at which match was made

  • route_key (str) – unique id for this session

  • reason (str) – why the session could not proceed

class ansar.connect.directory_if.Cleared

Session notification, shutdown of transport by local end.

Parameters
  • matched_search (str) – name the client was looking for (regular expression)

  • matched_name (str) – name the server is known by

  • matched_scope (enumeration) – level at which match was made

  • route_key (str) – unique id for this session

  • reason (str) – why the session could not proceed

  • value (any) – result of session

Application Startup

ansar.create.object.create_object(object_type, *fixed_value, factory_settings=None, factory_input=None, input_type=None, factory_variables=None, upgrade=None, parameter_passing=<function object_passing>, parameter_table=None, start_vector=<function object_vector>, logs=<function log_to_nowhere>, properties=<class 'ansar.create.home.RoleProperties'>, **key_value)

Creates an async process shim around a “main” async object. Returns nothing.

Parameters
  • object_type (a function or a Point-based class) – the type of an async object to be instantiated

  • factory_settings (instance of a registered class) – persistent values

  • factory_input (instance of a registered class) – per-invocation values

  • factory_variables (instance of a registered class) – host environment values

  • upgrade (function) – function that accepts old versions of settings/input and produces the current version

  • parameter_passing (a function) – method for parsing sys.argv[]

  • parameter_table (dict) – table of sub-commands and their associated functions

  • logs (function or class with __call__ method) – a callable object expecting to receive log objects

Return type

None

ansar.connect.node.create_node(object_type, *fixed_value, factory_settings=None, factory_input=None, factory_variables=None, parameter_passing=<function node_passing>, parameter_table=None, upgrade=None, logs=<function log_to_nowhere>, scope=1, **key_value)

Creates an async pub-sub process shim around a “main” async object. Returns nothing.

Parameters
  • object_type (a function or a Point-based class) – the type of an async object to be instantiated

  • fixed_value (tuple) – position args to forward to the object

  • factory_settings (instance of a registered class) – persistent values

  • factory_input (instance of a registered class) – per-invocation values

  • factory_variables (instance of a registered class) – host environment values

  • parameter_passing (a function) – method for parsing sys.argv[]

  • parameter_table (dict) – table of sub-commands and their associated functions

  • upgrade (function) – function that accepts old versions of settings/input and produces the current version

  • logs (function or class with __call__ method) – a callable object expecting to receive log objects

  • scope (enumeration) – level of the internal directory object

  • key_value (dict) – named args to forward to the object

Return type

None

Connection Groups With Retry

class ansar.connect.grouping.GroupTable(**member_frame)

Table of objects that create runtime objects, e.g. manage multiple connections.

Parameters

member_frame (dict) – list of named CreateFrames

class ansar.connect.grouping.GroupUpdate(key=None, address=None)

A group notification, an address was acquired or lost.

Parameters
  • key (str) – name of the address

  • address (ansar address) – new address or None

GroupTable.update(message)

Process a GroupUpdate message from the AddressGroup object.

Parameters

message (GroupUpdate) – acquire a new address or lose an existing address

Return type

None

class ansar.connect.grouping.AddressGroup(table, session=None, resident_code=False, get_ready=None, until_stopped=False)

Manage a collection of objects that are acquiring addresses, e.g. network connections.

Parameters
  • table (dict) – table of named CreateFrames

  • session (CreateFrame) – object to be created at ready state, or None

  • resident_code (bool) – facilitate a series of sessions

  • get_ready (float) – time limit on achieving the ready state, or None

  • until_stopped (bool) – override the completion value with the session completion

class ansar.connect.networking.ConnectToAddress(ipp, keep_connected=True, session=None, group_address=None, encrypted=False, api_client=None, ansar_server=False)

Maintain a connection to an IP address and port, perform retries.

Parameters
  • ipp (HostPort) – IP address and port to connect to

  • keep_connected (bool) – restart retry sequence after successful connect

  • session (CreateFrame) – object to be created on connection, or None

  • group_address (async address) – where to forward session messages, or None

class ansar.connect.networking.ListenAtAddress(ipp, session=None, group_address=None, encrypted=False, api_server=None, ansar_client=False)

Maintain a network presence at an IP address and port.

Parameters
  • ipp (HostPort) – IP address and port to listen at

  • session (CreateFrame) – object to be created on accept, or None

  • group_address (async address) – where to forward session messages, or None

class ansar.connect.networking.SubscribeToListing(listing, scope=5, keep_connected=True, session=None, group_address=None)

Maintain a connection to a published name.

Parameters
  • listing (str) – the name of interest (not a regular expression)

  • scope (enumeration) – highest level to look for a match

  • keep_connected (bool) – allow for multiple sessions

  • session (CreateFrame) – object to be created on connection, or None

  • group_address (async address) – where to forward session messages, or None

class ansar.connect.networking.PublishAListing(listing, scope=5, session=None, group_address=None)

Maintain a network presence at a name.

Parameters
  • listing (str) – the name this object will be known by

  • session (CreateFrame) – object to be created on delivery, or None

  • group_address (async address) – where to forward session messages, or None

class ansar.connect.networking.SubscribeToSearch(search, scope=5, session=None, group_address=None)

Maintain connections with multiple published names.

Parameters
  • listing (str) – the names to search for (regular expression)

  • scope (enumeration) – highest level to look for a match

  • session (CreateFrame) – object to be created on connection, or None

  • group_address (async address) – where to forward session messages, or None

class ansar.connect.networking_if.UseAddress(address=None)

Utility message. Pass an address to the receiver.

Parameters

address (tuple) – the address to pass

HTTP Integration

class ansar.connect.http.HttpRequest(method=None, request_uri=None, http=None, header=None, body=None)

The message generated by an HTTP client and received by an HTTP server.

Parameters
  • method (str) – one of GET, POST, PUT, …

  • request_uri (str) – the path section of a URI

  • http (str) – version of HTTP

  • header (dict) – name-value pairs

  • body (bytearray) – payload, value

class ansar.connect.http.HttpResponse(http=None, status_code=200, reason_phrase=None, header=None, body=None, plain_text=None, application_json=None)

The message generated by an HTTP server and received by an HTTP client.

Parameters
  • http (str) – version of HTTP

  • status_code (int) – 100, 200, 300, …

  • reason_phrase (str) – short description

  • header (dict) – name-value pairs

  • body (bytearray) – payload, value

Ansar Create

Documentation appearing here belongs to the ansar-create library. Some material is duplicated here for convenient browsing.

For convenience, the bind() function is maintained as a pointer-to-a-function. It will be assigned to one of the two following functions, depending on which ansar library is imported.

ansar.encode.message.bind_message(message, object_schema=None, version_history=None, message_trail=True, execution_trace=True, copy_before_sending=True, not_portable=False)

Set the type information and runtime controls for the given message type.

Parameters
  • message (class) – a message class.

  • object_schema (a map of <name,portable declaration> pairs.) – application-supplied type information.

  • message_trail (bool) – log every time this message is sent.

  • version_history (a list of version changes.) – a version table.

  • execution_trace (bool) – log every time this message is received.

  • copy_before_sending (bool) – make a copy of the message before each send.

  • not_portable (bool) – prevent serialization/transfer, e.g. of a file handle.

Returns

nothing.

Values assigned in this function affect the behaviour for all instances of the given type.

ansar.create.binding.bind_any(object_type, *args, **kw_args)

Forwards all arguments on to a custom bind function according to the type of the first argument.

Refer to ansar.encode for registration of messages;

Parameters
  • object_type (message class, function or Point-based class) – type of async entity

  • args (positional argument tuple) – arguments passed to the object instance

  • kw_args (named arguments dict) – named arguments passed to the object instance

ansar.create.point.bind_point(point, thread=None, lifecycle=True, message_trail=True, execution_trace=True, user_logs=1)

Set the runtime flags for the given async object type.

Parameters
  • point (class) – a class derived from Point.

  • lifecycle (bool) – log all create() and complete() events

  • message_trail (bool) – log all send() events

  • execution_trace (bool) – log all receive events

  • user_logs (enumeration) – the logging level for this object type

ansar.create.point.bind_function(routine, lifecycle=True, message_trail=True, execution_trace=True, user_logs=1)

Set the runtime flags for the given async function.

Parameters
  • routine (function) – an async function.

  • lifecycle (bool) – log all create() and complete() events

  • message_trail (bool) – log all send() events

  • execution_trace (bool) – log all receive events

  • user_logs (enumeration) – the logging level for this object type

class ansar.create.lifecycle.Completed

Last message sent, from child to creator.

Parameters

value (any) – return value for an async object

class ansar.create.lifecycle.Aborted
class ansar.create.lifecycle.Ack

Report in the positive.

class ansar.create.lifecycle.Stop

Initiate teardown in the receiving object.

class ansar.create.lifecycle.Enquiry

Prompt an action from receiver.

class ansar.create.point.Point

The essential async object.

Methods of this class are the user entry-point for SDL primitives such as send() and start(). There are also methods associated with logging and child object management.

Point.create(object_type, *args, object_ending=<function completed_object>, **kw)

Create a child instance of object_type. Return the address of the new object.

Parameters
  • object_type (function or Point-based class) – async type to instantiate

  • args (positional arguments tuple) – arguments passed to the new object

  • kw (name arguments dict) – arguments passed to the new object

Return type

an ansar address or the actual object (e.g. Channel)

Point.send(m, to)

Transfer a message to an address.

Message delivery is not guaranteed and non-delivery is not notified. There are multiple reasons delivery can fail, e.g. the destination address no longer exists. Unless the reason is a fault within the sending machinery, failure to deliver is not considered an error. Refer to application logs for details on why a particular message failed to reach its intended destination.

A copy of the message is taken for every actual transfer, i.e. by default remote objects always receive a copy of the message originally presented to send(). Obviously this is behaviour motivated by the multi-threaded runtime context but where it is deemed unnecessary, copying can be disabled on a per-message-type basis. bind_any() for more details.

Parameters
  • m (instance of a registered message) – the message to be sent

  • to (ansar address) – the intended receiver of the message

Point.reply(m)

Send a response to the sender of the current message.

This is a shorthand for self.send(m, self.return_address). Reduces keystrokes and risk of typos.

Parameters

m (instance of a registered message) – the message to be sent

Point.forward(m, to, return_address)

Send a message to an address, as if it came from a 3rd party.

Send a message but override the return address with the address of another arbitrary object. To the receiver the message appears to have come from the arbitrary object.

Useful when building relationships between objects. This allows objects to “drop out” of 3-way conversations, leaving simpler and faster 2-way conversations behind.

Parameters
  • m (instance of a registered message) – the message to send

  • to (ansar address) – the intended receiver of the message

  • return_address (ansar address) – the other object

Point.start(timer, seconds, repeating=False)

Start the specified timer for this object.

An instance of the timer class will be sent to this address after the given number of seconds. Any registered message can be used as a timer. Ansar provides the standard timers T1, T2, T3, and T4 for convenience and to reduce duplication.

Timers are private to each async object and there is no limit to the number of pending timers an object may have. Starting a timer with the same class is not an error, the timeout for that timer is reset to the new number of seconds. It is also not an error to terminate an object with outstanding timers - they fall on the floor.

It is difficult to make guarantees about the order that messages will arrive at an object. In the case of timers, its possible to receive the timeout after the sending of a cancellation. Async objects are best written to cope with every possible receive ordering.

Parameters
  • timer (a registered class) – the type of the object that will be sent back on timeout

  • seconds (float) – time span before expiry

Point.cancel(timer)

Abort the specified timer for this object.

Discard the pending timer. It is not an error to find that there is no such pending timer. The timeout can still be received after a cancellation.

Parameters

timer (a registered class) – the pending timer

Point.complete(value=None)

Cause an immediate termination. The method never returns.

Parameters

value (any) – value to be returned to parent.

class ansar.create.point.Threaded

Base class for async machines that require dedicated threads.

Parameters
  • blocking (bool) – block on queue full

  • maximum_size (int) – number of pending messages

class ansar.create.point.T1

Predeclared timer class.

A class suitable for passing to Point.start(). The library provides the T1, T2, T3 and T4 timer classes for general use.

Buffering.select(*matching, saving=None, seconds=0)

Expect one of the listed messages, with optional saving and timeout.

Parameters
  • matching (the positional arguments tuple) – message types to be accepted

  • saving (tuple) – message types to be deferred

  • seconds (float) – waiting period

Return type

message object

class ansar.create.machine.Stateless

Base for simple machines that maintain no formal state.

Messages are received by an assigned thread and dispatched to handlers according to the type of the received message.

class ansar.create.machine.StateMachine(initial)

Base for machines that maintain a formal state.

Messages are received by an assigned thread and dispatched to handlers according to the current state and the type of the received message.

Parameters

initial (class) – Start state for all instances of derived class

ansar.create.machine.bind_stateless(machine, dispatch, *args, **kw_args)

Sets the runtime environment for the given stateless machine. Returns nothing.

This function (optionally) auto-constructs the message dispatch table and also saves control values.

The dispatch is a simple list of the expected messages:

dispatch = (Start, Job, Stop)

Using this list and a naming convention the bind function searches the application for the matching functions and installs them in the appropriate dispatch entry. The naming convention is;

<machine name>_<expected message>

The control values are the same as for Points (see bind_point()). This function actually calls the bind_point function to ensure consistent initialization.

Parameters
  • machine (a class) – class derived from machine.Stateless

  • dispatch (a tuple) – the list of expected messages

  • args (a tuple) – the positional arguments to be forwarded

  • kw_args (a dict) – the named arguments to be forwarded

ansar.create.machine.bind_statemachine(machine, dispatch, *args, **kw_args)

Sets the runtime environment for the given FSM. Returns nothing.

This function (optionally) auto-constructs the message dispatch table and also saves control values.

The dispatch is a description of states, expected messages and messages that deserve saving:

dispatch = {
        STATE_1: (Start, ()),
        STATE_2: ((Job, Pause, UnPause, Stop), (Check,)),
        STATE_3: ((Stop, ()),
}

Consider STATE_2; The machine will accept 4 messages and will save an additional message, Check.

Using this list and a naming convention the bind function searches the application for the matching functions and installs them in the appropriate dispatch entry. The naming convention is;

<machine name>_<state>_<expected message>

The control values available are the same as for Points (see bind_point()). This function actually calls the bind_point function to ensure consistent initialization.

Parameters
  • machine (a class) – class derived from machine.StateMachine

  • dispatch (a dict of tuples) – specification of a FSM

  • args (a tuple) – the positional arguments to be forwarded

  • kw_args (a dict) – the named arguments to be forwarded