unaiverse.networking.node.connpool¶
A node is present on two networks at once (see Networking). Any node can get in touch with it on the public network. Only the members of one world share the world network. This module holds the object that manages both networks on behalf of the node. NodeConn owns the two SessionManager objects of the node (one per network) and each manager owns its P2P transport. On top of them NodeConn keeps the pools of connected peers, the roles of the peers in the world, the membership of the world and the bookkeeping of a world join that spans both networks. The source and this page also call it the Coordinator.
Calls always go down one chain. The node calls NodeConn, NodeConn calls the manager of the right network and the manager calls its transport. NodeConn never touches a transport directly.
Node builds the object and hands it to the hosted agent or world as its node_conn attribute. The node calls almost every method. The code of Agent and World calls a few of them through self.node_conn (send, publish, subscribe, unsubscribe, get_role, find_addrs_by_role, is_connected, get_addrs, get_world_node_peer_id, get_last_token, sends_are_queued and get_world_connected_peers_info). A developer who writes an agent normally uses the higher-level methods of Agent and reads node_conn only to inspect the state of the connections.
Three helper objects complete the module. WorldMembership is a frozen snapshot of the members of the world for one cycle. HandoffCorrelation records which public Session yielded the grant that a world Session is redeeming. SendTicket reports the outcome of one direct message sent with NodeConn.send_tracked.
# Inside an action of an agent: send a message and wait until it has left on its stream
ticket = await self.node_conn.send_tracked(peer_id, None, Msg.MISC, {"text": "hello"})
if ticket is None:
print("the send queue of the peer is full")
elif await ticket.wait(timeout=5.0):
print("written")
else:
print(ticket.status, ticket.reason) # "queued" after a timeout, "dropped" with its reason
WorldMembership
module-attribute
¶
WorldMembership = namedtuple('WorldMembership', ['world_agents', 'world_masters', 'world_node_peer_id', 'inspector_peer_id'])
An immutable snapshot of the membership of the world that NodeConn.membership_snapshot builds once per update cycle. It is a namedtuple with four fields.
| Field | Type | Meaning |
|---|---|---|
world_agents |
frozenset[str] |
World peer ids of the agents admitted in the world. |
world_masters |
frozenset[str] |
World peer ids of the masters admitted in the world. |
world_node_peer_id |
str \| None |
World peer id of the world node that this agent joined (None outside a world and on the world node itself). |
inspector_peer_id |
str \| None |
Peer id of an inspector admitted to chat with the node (always None in the current version because nothing writes it). |
Two readers use the same snapshot within a cycle. The perimeter of the world network cuts every connected peer missing from it (see SessionManager.reconcile). The gate of NodeConn.get_messages accepts chat messages from listed peers not yet in a pool. Because both read the same frozen object, a member added in the middle of a cycle (a pre-admission at grant time) takes effect for both at the next update.
HandoffCorrelation
¶
HandoffCorrelation(is_world_established: Callable[[str], bool], abort_world: Callable, current_world: Callable[[], str | None], clear_world: Callable[[], None])
Source code in unaiverse/networking/node/connpool.py
A world join spans two Sessions on two networks (see Joining a world). The agent first gets a grant on its public Session with the world node. It then opens a Session on the world network to the world peer named in the grant and redeems the grant there. Until the world Session is established the public Session stays open as the carrier of the grant. HandoffCorrelation is the ledger of this pair. For each join in flight it maps the public peer id of the carrier to the world peer id of the redemption and back.
The class keeps only the two dictionaries. It acts on the rest of the node only through the callables that its constructor receives. NodeConn and the test suite can therefore share one implementation.
| Argument | Type | Meaning |
|---|---|---|
is_world_established |
Callable[[str], bool] |
Tells whether the world Session to a world peer id is ESTABLISHED. |
abort_world |
async Callable[[str], Awaitable] |
Aborts the world Session of a failed handoff. NodeConn passes a coroutine that calls drop on the world manager. |
current_world |
Callable[[], str \| None] |
Reads the world peer id that the pools route to (NodeConn.get_world_node_peer_id). |
clear_world |
Callable[[], None] |
Clears that pointer (NodeConn.set_world(None)). |
NodeConn builds one instance in its constructor and drives it through start_world_handoff, rollback_handoff, is_pending_handoff, handoff_carrier_of and complete_world_handoff.
The forward index as a dict[str, str] from the public peer id of a carrier to the world peer id of its redemption. It is empty when no join is in flight.
The reverse index as a dict[str, str] from the world peer id of a redemption to the public peer id of its carrier. It always holds the pairs of pending_world_handoff in the opposite direction.
start
¶
Source code in unaiverse/networking/node/connpool.py
Records a new join in flight in both indexes and returns None. public_peer_id is the world node on the public network and world_peer_id the world node on the world network. An earlier pair with the same keys is overwritten. NodeConn.start_world_handoff calls it.
is_pending
¶
Returns True when world_peer_id is the world side of a join in flight. The node calls it through NodeConn.is_pending_handoff to distinguish a world Session that redeems a grant from a plain Session between two members of the world.
carrier_of
¶
Source code in unaiverse/networking/node/connpool.py
Returns the public peer id of the carrier whose grant opened the join toward world_peer_id. It returns None when that peer is not the world side of a join in flight. The node compares the result with the join it started before it runs the body of the join.
rollback
async
¶
Source code in unaiverse/networking/node/connpool.py
Undoes the record of a join after one of its two Sessions reached a terminal state (async). peer_id may be either side.
- When
peer_idis a carrier whose world Session is already ESTABLISHED, nothing happens. The join is completing and its completion removes the entries. A rollback here would leave the agent in the world without a world node and the perimeter would then cut the world node itself. - When
peer_idis a carrier whose redemption is still in flight, both entries go away andabort_worldis awaited on the world peer id. A dial or a handshake left running would otherwise end in a join that nobody drives. - When
peer_idis the world side of a join, both entries go away. - When the rolled back world peer id is the one returned by
current_world(),clear_world()runs.
A peer_id missing from both indexes changes nothing. Through NodeConn.rollback_handoff the node calls it on the LOST, FAILED and CLOSED events of either Session.
complete
¶
Source code in unaiverse/networking/node/connpool.py
Removes the pair of a successful join and returns the public peer id of its carrier for the caller to retire. It returns None when world_peer_id was not part of a join. NodeConn.complete_world_handoff calls it.
SendTicket
¶
Source code in unaiverse/networking/node/connpool.py
The outcome of one direct message sent with NodeConn.send_tracked. A send only puts the message in the send queue of its peer (see The send queue) and the ticket follows the message until the queue reports its outcome.
| Argument | Type | Default | Meaning |
|---|---|---|---|
peer_id |
str |
The peer the message was sent to. | |
seq |
int \| None |
The sequence number of the message in the send queue of that peer. None when the transport has no queues (the browser transport) or when the send failed. | |
status |
str |
"queued" |
The initial status. Any value other than "queued" makes the ticket final at once. |
reason |
str \| None |
None |
Why the message was dropped when the ticket starts as "dropped". |
The status moves once from "queued" to one of two final values.
| Status | Meaning |
|---|---|
"queued" |
The message waits in the queue or is being written. |
"written" |
The whole message left on its stream. This does not prove that the peer processed it (the status of an interaction tells that). |
"dropped" |
The message will never be written. reason is "max_attempts", "max_age", "explicit" or "receiver_stopped" for a dropped queue and the text of the error for a failed send. |
NodeConn.pop_send_events resolves the tickets while the network task pops the events of the queues. An action that awaits wait() therefore wakes up only when the node runs its network task and its tick task. In a loop that drives the node with a cycle budget nothing pops the events during the wait and wait() can only time out. Never poll status in a loop without an await.
The peer the message was sent to (str).
The sequence number of the message in the queue of its peer (int). It is None for a ticket that was final at creation.
One of "queued", "written" and "dropped" as in the table above.
Why the message was dropped (str). Every other status leaves it None.
The progress of a message larger than one chunk as (bytes written, total bytes). The "progress" events of the queue update it. It stays None for a message sent in one frame.
wait
async
¶
Source code in unaiverse/networking/node/connpool.py
Waits until the ticket is final or until timeout seconds have passed (async). With timeout=None it waits Custom.SEND_TICKET_TIMEOUT seconds (10 by default). It returns True when the status is "written" and False when the message was dropped or the time ran out. A timeout leaves the ticket "queued". The message may still be written later and status will then show it.
resolve
¶
Source code in unaiverse/networking/node/connpool.py
Writes the final status ("written" or "dropped") with its reason and then wakes every wait(). Only the first call changes the ticket because a ticket that is no longer "queued" ignores later calls. NodeConn calls it and the developer never does.
NodeConn
¶
NodeConn(max_connections: int, is_world_node: bool, public_key: str, token: str, local_node_id: str = None)
Source code in unaiverse/networking/node/connpool.py
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | |
The networking Coordinator of a node. Node builds it as soon as it knows its profile and attaches the two transports later with attach_session_policy. Before that call the object has no transport and no manager and most of its methods fail because the manager is None.
| Argument | Type | Default | Meaning |
|---|---|---|---|
max_connections |
int |
Total number of peers the pools can hold. The node passes the max_connections of its profile. It must be at least 8 (one per pool). |
|
is_world_node |
bool |
True for the node of a world. It changes the capacity of each pool (see below). | |
public_key |
str |
Public key of the UNaIVERSE server that verifies the tokens of the peers (see tokens). With None no token is ever accepted. |
|
token |
str |
The token of this node that every chat message it sends carries. set_token replaces it after a refresh. |
|
local_node_id |
str |
None |
The node id of this node that the two managers receive. |
Pools¶
A pool is a set of peer ids connected to this node in one direction on one network and in one role. A connected peer is in at most one pool. There are eight pools. The name of each pool joins a direction prefix (in_ or out_), a group and a network suffix (_public or _private).
| Constant | Value | Network | Holds |
|---|---|---|---|
IN_PUBLIC |
"in_all_unaiverse_public" |
public | peers that dialed this node |
OUT_PUBLIC |
"out_all_unaiverse_public" |
public | peers this node dialed |
IN_WORLD_AGENTS |
"in_world_agents_private" |
world | agents of the world that dialed this node |
OUT_WORLD_AGENTS |
"out_world_agents_private" |
world | agents of the world this node dialed |
IN_WORLD_NODE |
"in_world_node_private" |
world | the world node when it dialed this agent |
OUT_WORLD_NODE |
"out_world_node_private" |
world | the world node when this agent dialed it |
IN_WORLD_MASTERS |
"in_world_masters_private" |
world | masters of the world that dialed this node |
OUT_WORLD_MASTERS |
"out_world_masters_private" |
world | masters of the world this node dialed |
Each pool has a fixed capacity that the constructor computes once from max_connections and a ratio per pool. The ratios differ for an agent and for a world node.
| Pool | Ratio for an agent | Ratio for a world node |
|---|---|---|
IN_PUBLIC, OUT_PUBLIC |
0.125 each | 0.125 each |
IN_WORLD_AGENTS, OUT_WORLD_AGENTS |
0.375 each | 0.25 each |
IN_WORLD_NODE, OUT_WORLD_NODE |
0 each | -1 each |
IN_WORLD_MASTERS, OUT_WORLD_MASTERS |
0 each | 0.125 each |
Let Z be the number of pools with ratio 0. A pool with a ratio of 0 or more gets max(floor(ratio * (max_connections - Z)), 1) places and a pool with a negative ratio gets none. The places left over by the rounding go to the last pool (OUT_WORLD_MASTERS). With max_connections=100 an agent gets 12 places in each public pool, 36 in each world agent pool and one in each of the four other pools. With the same value a world node gets 12 and 12 public places, 25 and 25 world agent places, no world node place and 12 and 14 master places. The constructor raises AssertionError when the positive ratios do not sum to 1.0 or when max_connections cannot give every pool its minimum.
The constructor creates the attributes below in the same step as the capacities. They have no entry of their own on this page.
| Attribute | Type | Meaning |
|---|---|---|
max_con |
int |
The max_connections given to the constructor. |
pool_count, pool_names, pool_ratios |
int, list[str], list[float] |
The number of pools with their names in the order above and their ratios. |
pool_name_to_pool_triple |
dict[str, list] |
For each pool the list [set of peer ids, capacity, SessionManager of its network]. The manager is None until set_session_managers runs. |
pool_name_to_peer_infos |
dict[str, dict[str, dict]] |
For each pool the peer info of each peer (id, addrs, direction, misc and what the transport reports). |
peer_id_to_pool_name |
dict[str, str] |
The pool of each connected peer. It is the index behind is_connected, get_pool_of and the chat gate. |
peer_id_to_misc |
dict[str, int] |
The role bits of each known peer (see get_role). They survive the removal of a peer from its pool. |
peer_id_to_token |
dict[str, str] |
The last valid token received from each peer in a pool. |
pool_name_to_added_in_last_update, pool_name_to_removed_in_last_update |
dict[str, set[str]] |
The pool changes of the last update for the pools that changed. |
The name of the public network ("p2p_public"). Every manager, transport, Session and Session event carries it as p2p_name.
The name of the world network ("p2p_world").
IN_PUBLIC
class-attribute
instance-attribute
¶
Name of the pool of the public peers that dialed this node (see the table of the pools).
OUT_PUBLIC
class-attribute
instance-attribute
¶
Name of the pool of the public peers that this node dialed.
IN_WORLD_AGENTS
class-attribute
instance-attribute
¶
Name of the pool of the world agents that dialed this node.
OUT_WORLD_AGENTS
class-attribute
instance-attribute
¶
Name of the pool of the world agents that this node dialed.
IN_WORLD_NODE
class-attribute
instance-attribute
¶
Name of the pool of the world node when it dialed this agent. Its capacity is 0 on a world node.
OUT_WORLD_NODE
class-attribute
instance-attribute
¶
Name of the pool of the world node when this agent dialed it. Its capacity is 0 on a world node.
IN_WORLD_MASTERS
class-attribute
instance-attribute
¶
Name of the pool of the world masters that dialed this node.
OUT_WORLD_MASTERS
class-attribute
instance-attribute
¶
Name of the pool of the world masters that this node dialed.
The set {IN_PUBLIC, OUT_PUBLIC}. Every method that takes pool_names accepts it as it accepts the other aggregates below.
The set {IN_WORLD_NODE, OUT_WORLD_NODE}.
WORLD_AGENTS
class-attribute
instance-attribute
¶
WORLD_AGENTS = {IN_WORLD_AGENTS, OUT_WORLD_AGENTS}
The set {IN_WORLD_AGENTS, OUT_WORLD_AGENTS}.
WORLD_MASTERS
class-attribute
instance-attribute
¶
WORLD_MASTERS = {IN_WORLD_MASTERS, OUT_WORLD_MASTERS}
The set {IN_WORLD_MASTERS, OUT_WORLD_MASTERS}.
The six pools of the world network (WORLD_NODE | WORLD_AGENTS | WORLD_MASTERS).
All eight pools (PUBLIC | WORLD).
OUTGOING
class-attribute
instance-attribute
¶
OUTGOING = {OUT_PUBLIC, OUT_WORLD_NODE, OUT_WORLD_AGENTS, OUT_WORLD_MASTERS}
The four out_ pools that hold the peers this node dialed.
INCOMING
class-attribute
instance-attribute
¶
INCOMING = {IN_PUBLIC, IN_WORLD_NODE, IN_WORLD_AGENTS, IN_WORLD_MASTERS}
The four in_ pools that hold the peers that dialed this node.
Peer id of an inspector that may chat with this node without being a world member. In the current version nothing writes it and it stays None. membership_snapshot copies it into every WorldMembership.
The inverse of peer_id_to_misc as a dict[int, set[str]] from a role value to the peer ids that hold it. set_role keeps the two in sync. find_addrs_by_role and count_by_role read it.
The addresses of the world peers as a dict[str, list[str]]. The methods that write the roster (set_world_agents_list, add_to_world_agents_list and their counterparts for the masters) fill it. get_addrs reads it and update passes it to the world manager as the list of known peers.
The update_count of the last roster that this node read from the rendezvous of the world (int, -1 before the first one). set_world_agents_and_world_masters_lists_from_rendezvous ignores every roster whose count is not larger. A world node also writes it directly when it publishes a roster.
On a world node it maps the world peer id of each joiner that received a grant and has not yet redeemed it to a deadline in time.monotonic() seconds. add_to_world_agents_list and add_to_world_masters_list with provisional_ttl_s write an entry. The same calls without that argument remove it and so does remove_from_world_lists. sweep_world_preadmissions drops the expired entries.
Identity of the node¶
The peer id of this node on the public network (str) as the public manager holds it. Before attach_session_policy it raises AttributeError.
The peer id of this node on the world network. It identifies this node and not the world node it joined (that one is get_world_node_peer_id()).
The addresses on which this node is reachable on the public network (list[str]). Each access reads them live from the transport and an empty list means that the transport could not answer.
The addresses of this node on the world network. Each access reads them live like public_addresses.
Whether the transport currently judges the world network of this node reachable from the internet (bool, None before a verdict). The node reads it together with world_relay_enabled to decide whether a world can offer its own relay (see Relays).
Whether the relay client is enabled on the world network (bool).
get_world_connected_peers_info
¶
Source code in unaiverse/networking/node/connpool.py
Returns the peer infos of every peer that the transport sees connected to the world network whether or not it is in a pool. A None return means that the transport could not answer. The caller must then skip its work and never read the None as "no peers". Agent.collect_and_store_own_stats reads it to compute the statistics of an agent.
Tokens¶
set_token
¶
Replaces the token of this node in every chat message sent from now on. The node calls it after each refresh of its token. The Sessions read the token through their own factory and push the new one to their peers on the next tick (see SessionManager.tick).
verify_token
async
¶
Source code in unaiverse/networking/node/connpool.py
Verifies the token of a peer with the public key given to the constructor (async). The token must carry the signature of the UNaIVERSE server, must not be expired and must list peer_id among its peer ids. On success it returns (node_id, cv_hash) from the token. On failure and when the constructor received no public key it returns (None, None). get_messages calls it on every chat message.
verify_token_claims
async
¶
Source code in unaiverse/networking/node/connpool.py
Verifies a token like verify_token and returns all of its claims as (node_id, cv_hash, p2p_peers, exp, code_hash) (async). A failure returns (None, None, (), 0, None). p2p_peers is the tuple of the peer ids of the node on both networks, exp the expiry in Unix seconds and code_hash the hash of the stored code of a world (None for an agent). attach_session_policy hands this method to both managers as their token verifier. Every Session calls it during its handshake and on each token update (see Session).
Pool bookkeeping¶
add
¶
Source code in unaiverse/networking/node/connpool.py
Puts a connected peer in a pool. peer_info must have an id key. It returns False when the pool is full or when the peer is already in another pool and True otherwise. On success it writes the role bits of the peer (0 when unknown) into peer_info["misc"] and stores the dictionary itself without copying it. Only update calls it.
drop_peer
async
¶
Source code in unaiverse/networking/node/connpool.py
Tears down the relation with one peer on the network of that peer and removes it from the pools (async). The node purges a peer only through this method.
| Argument | Type | Default | Meaning |
|---|---|---|---|
peer_id |
str |
The peer. | |
reason |
int \| None |
None |
A reason code of sess_msg. With a reason a live Session receives a GOAWAY and closes. Without one it is aborted at once. |
settled |
bool |
False |
True when the Session has already ended and its manager has already scheduled the cut of its connection. The method then leaves the Session untouched and only changes the pools. |
With settled=False it calls SessionManager.drop on the manager of the peer (see its table of cases). Then it empties the send queue of the peer unless a GOAWAY is still in flight. In that case the messages sent just before the purge can still go out on the live link. The settled purge that follows the CLOSED event drops what remains. The method finally removes the peer from its pool. For a peer unknown to every manager and every pool the call does nothing. The return value is always an empty list because the CLOSED event comes later. The flag settled prevents the teardown of an old Session from touching a new Session with the same peer created in the same pump.
get_pool_status
¶
Source code in unaiverse/networking/node/connpool.py
Returns a dict[str, set[str]] from each pool name to its set of peer ids. The sets are the live ones and not copies.
get_all_connected_peer_ids
¶
Source code in unaiverse/networking/node/connpool.py
Returns the list of the peer ids in every pool.
get_last_token
¶
Source code in unaiverse/networking/node/connpool.py
Returns the last valid token received from a peer in a pool and None when there is none. The world node reads it to check the identity behind a chat message.
get_pool_of
¶
Source code in unaiverse/networking/node/connpool.py
Returns the name of the pool of a peer. A peer in no pool gives None.
size
¶
Source code in unaiverse/networking/node/connpool.py
Returns the number of peers in the given pools. With pool_names=None it counts all pools. An unknown pool name raises KeyError.
is_connected
¶
Source code in unaiverse/networking/node/connpool.py
Returns True when the peer is in one of the given pools. With pool_names=None any pool counts.
in_connection_queues
¶
Source code in unaiverse/networking/node/connpool.py
Returns True when the peer is in any pool. It is equivalent to is_connected(peer_id).
is_public
¶
Source code in unaiverse/networking/node/connpool.py
Returns True when the pool of the peer is one of PUBLIC. This method concerns a remote peer and has nothing to do with the reachability of this node (world_is_public).
is_world_master
¶
Source code in unaiverse/networking/node/connpool.py
Returns True when the pool of the peer is one of WORLD_MASTERS.
is_world_node
¶
Source code in unaiverse/networking/node/connpool.py
Returns True when the pool of the peer is one of WORLD_NODE.
is_in_world
¶
Source code in unaiverse/networking/node/connpool.py
Returns True when the pool of the peer is one of WORLD.
get_all_connected_peer_infos
¶
Source code in unaiverse/networking/node/connpool.py
Returns the peer info dictionaries of every peer in the given pools (a list or set of pool names). The dictionaries are the stored ones and a change to them changes the pools.
get_added_after_updating
¶
Source code in unaiverse/networking/node/connpool.py
Returns the peers that the last update put in the pools. With pool_names=None it returns the whole mapping of the pools that changed. With a list of names it builds a new dictionary for those names and raises KeyError for any name unchanged in the last update. The node reads the return value of update instead.
get_removed_after_updating
¶
Source code in unaiverse/networking/node/connpool.py
Returns the peers that the last update found missing from the pools. It behaves like get_added_after_updating (KeyError included).
Roles and the world roster¶
The role of a peer is an int of bits called misc. The value 0 means a public peer. Bit 0 (value 1) marks a member of the world and bit 1 (value 2) a master. The bits from 2 upward encode the role name assigned by the world. An agent of the world therefore has misc & 3 == 1 and a master has misc & 3 == 3.
The members of the world live in the world manager (SessionManager.world_agents_set, world_masters_set and world_node_peer_id) next to the Sessions whose admission they control. Only the methods below change them and the node never writes these sets directly.
get_role
¶
Source code in unaiverse/networking/node/connpool.py
Returns the role bits of a peer and 0 for an unknown peer. A stored value that is negative or that has higher bits without bit 0 raises AssertionError.
set_role
¶
Source code in unaiverse/networking/node/connpool.py
Writes a new role for a peer into peer_id_to_misc, into the misc field of its peer info when the peer is in a pool and into role_to_peer_ids. In role_to_peer_ids it moves the peer from the set of the old role to the set of the new one and deletes an emptied old set. The node calls it when a world assigns or changes a role.
get_addrs
¶
Source code in unaiverse/networking/node/connpool.py
Returns the addresses of a world peer from peer_id_to_addrs. An unknown peer gives None.
set_addresses_in_peer_info
¶
Source code in unaiverse/networking/node/connpool.py
Replaces the addresses in the peer info of a peer in a pool with addresses. Other structures hold a reference to the list object and the method therefore empties and refills it in place. A peer in no pool is ignored. The node calls it when a peer announces new addresses.
find_addrs_by_role
¶
find_addrs_by_role(role: int, return_peer_ids_too: bool = False, discard_yourself: bool = False) -> list | tuple[list, list]
Source code in unaiverse/networking/node/connpool.py
Returns the address lists of the peers with exactly the role role whose addresses are known. With return_peer_ids_too=True it returns the tuple (addresses, peer_ids) in matching order. With discard_yourself=True it skips the two peer ids of this node. An unknown role gives empty lists.
count_by_role
¶
Source code in unaiverse/networking/node/connpool.py
Returns the number of peers with exactly the role role.
set_world
¶
Source code in unaiverse/networking/node/connpool.py
Writes the world peer id of the world node that this agent belongs to. The value None clears it. It also ends the wait for the roster and discards the dials held by that wait. The world routing reads this value to put the world node in its pool. The node calls it when it joins and leaves a world. start_world_handoff calls it at the start of a join.
get_world_node_peer_id
¶
Source code in unaiverse/networking/node/connpool.py
Returns the world peer id of the world node this agent joined. Outside a world and before attach_session_policy it returns None. It never returns the peer id of this node (that one is world_peer_id).
set_world_agents_list
¶
Source code in unaiverse/networking/node/connpool.py
Replaces the list of the world agents. It first deletes the role and the addresses of every peer whose role marks an agent. It then writes the new set of agents in the world manager and calls set_role for each entry of world_agents_list_peer_infos (dictionaries with id, addrs and misc) after storing its addresses. With None or an empty list the world has no agents afterwards. The rendezvous reader calls it on each new roster and the node calls it when it leaves a world.
set_world_masters_list
¶
Source code in unaiverse/networking/node/connpool.py
The counterpart of set_world_agents_list for the masters (misc & 3 == 3).
add_to_world_agents_list
¶
add_to_world_agents_list(peer_id: str, addrs: list[str], role: int = -1, provisional_ttl_s: float | None = None) -> None
Source code in unaiverse/networking/node/connpool.py
Adds one agent to the members of the world. A world node calls it twice for a joiner. The call at grant time passes provisional_ttl_s and makes a pre-admission that expires unless confirmed. The call on the world network without a TTL confirms it once the joiner redeems the grant. role must have bit 0 equal to 1 and bit 1 equal to 0 or AssertionError is raised. Its default of -1 never passes that check and the caller always passes a role.
add_to_world_masters_list
¶
add_to_world_masters_list(peer_id: str, addrs: list[str], role: int = -1, provisional_ttl_s: float | None = None) -> None
Source code in unaiverse/networking/node/connpool.py
The counterpart of add_to_world_agents_list for a master. role must have bits 0 and 1 both equal to 1.
remove_from_world_lists
¶
Source code in unaiverse/networking/node/connpool.py
Removes a peer from the agents and masters of the world, from the pre-admissions, from peer_id_to_addrs, from peer_id_to_misc and from role_to_peer_ids (an emptied role set is deleted). A world node calls it when the world Session of a member ends. The next roster then no longer lists that member.
sweep_world_preadmissions
¶
Source code in unaiverse/networking/node/connpool.py
On a world node it calls remove_from_world_lists on every pre-admitted joiner whose deadline passed and returns their peer ids. now is a time.monotonic() value and the method reads the clock itself when now is None. The failure of the public carrier cannot remove these entries because its event names the public peer id while the pre-admissions are keyed by the world peer id. The node calls it at every cycle before update.
get_world_roster_peer_infos
¶
Source code in unaiverse/networking/node/connpool.py
On a world node it returns the roster to publish as the tuple (agents, masters). Both items are lists of {"id", "addrs", "misc"} sorted by peer id. A confirmed member (no pending pre-admission) is listed when its transport is connected or its world Session is RECONNECTING. A pre-admitted joiner is left out. The other members would otherwise dial a peer that does not know them yet and the perimeter of that peer would cut them. A member in its reconnect window stays in to keep the other members from cutting their Sessions with it. The node publishes this roster on the rendezvous and in the profile of the world.
set_world_agents_and_world_masters_lists_from_rendezvous
async
¶
Source code in unaiverse/networking/node/connpool.py
On an agent it reads the latest roster of the rendezvous of the world from the world manager (async). A roster whose update_count is not larger than rendezvous_tag is ignored. A newer one updates the tag. Its peers are split into agents (misc & 3 == 1) and masters (misc & 3 == 3) and the entries with no addresses or an unexpected misc are skipped. The two list writers then receive the result. The wait for a roster that lists this agent (see start_world_handoff) ends when this roster is newer than the grant and lists the world peer id of this agent. The held dials then go out at the next pump. The node calls it at every cycle before update.
reset_rendezvous_tag
¶
Writes -1 into rendezvous_tag so that the next roster is accepted whatever its count. The node calls it when it enters or leaves a world.
remove_all_world_agents
async
¶
Source code in unaiverse/networking/node/connpool.py
Closes the relation with every peer in the WORLD pools (agents, masters and world node) through drop_peer(peer_id, WORLD_DISENGAGEMENT) (async). It also removes their addresses and takes them out of every role set with bit 0. Each peer receives a GOAWAY and observes CLOSED instead of a dropped link that it would try to recover. The node calls it when this agent leaves a world.
membership_snapshot
¶
membership_snapshot() -> WorldMembership
Source code in unaiverse/networking/node/connpool.py
Builds a WorldMembership from the current sets of the world manager and inspector_peer_id. The sets are copied into frozenset objects. Before attach_session_policy the snapshot is empty. update calls it once per cycle.
update
async
¶
Source code in unaiverse/networking/node/connpool.py
Runs the per-cycle update of the pools (async). It returns (added, removed) as two dict[str, set[str]] that hold only the pools that changed. The node calls it at every cycle.
- It hands the known world peers (
peer_id_to_addrswith their roles, minus this node) toSessionManager.sync_known_peersof the world manager. - It builds one
WorldMembershipand keeps it as the snapshot of the cycle forget_messages. - For each manager, public first, it reads the connected peers of the transport and asks
SessionManager.reconcileto classify them into pools. On the world network this also cuts every peer outside the membership. Each pool is then compared with the result. New peers enter throughadd. Gone peers appear inremovedand stay in their pool until the node removes them withon_peer_disconnected.
A manager whose transport cannot list its peers is skipped for that cycle. A transient failure therefore never empties the pools.
Messages¶
get_messages
async
¶
get_messages(p2p_name: str, allowed_not_connected_peers: set | None = None, kind: str = 'all') -> tuple[list[Msg], list[SessionInbound]]
Source code in unaiverse/networking/node/connpool.py
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 | |
Pops the inbound messages of one network and returns (chat_messages, session_messages) (async).
| Argument | Type | Default | Meaning |
|---|---|---|---|
p2p_name |
str |
P2P_PUBLIC or P2P_WORLD. |
|
allowed_not_connected_peers |
set \| None |
None |
Must be None (any other value raises AssertionError). The method fills it with the agents and masters of the snapshot of the cycle. |
kind |
str |
"all" |
"all", "network" (everything but the streams, for the network pass of the node) or "streams" (one message per stream channel, for the tick). |
The transport has already decoded every frame and checked that the sender written inside each chat message is the peer that sent it (see P2P.get_messages). A chat Msg is kept only when its sender is in a pool or in the membership snapshot and its piggyback holds a valid token followed by one inspector bit. The piggyback of a kept message becomes <node id of the sender><inspector bit>. For a sender in a pool the token is also stored for get_last_token. The other chat messages are logged and discarded. The Session messages (SessionInbound) come back as they arrived because the handshake itself proves the identity of the peer and no pool or token gates them. Any message received updates the time read by passed_time_since_last_communication. The node calls it twice per pass with one call per network.
send
async
¶
send(peer_id: str, channel_trail: str | None, content_type: str, content: bytes | dict | str | None = None) -> bool
Source code in unaiverse/networking/node/connpool.py
Sends a direct message to a peer (async). It returns True when the message was queued or written. It returns False in three cases: the send queue of the peer refused it, the send failed or no manager knows the peer.
| Argument | Type | Default | Meaning |
|---|---|---|---|
peer_id |
str |
The receiver. The message goes on the network that holds a Session with it (public first) and otherwise on the network of its pool. | |
channel_trail |
str \| None |
A suffix of the channel or None. | |
content_type |
str |
One of the content types of Msg. |
|
content |
bytes \| dict \| str \| None |
None |
The content. |
The channel of the message is <own peer id>::dm:<peer id>-<content_type> with ~<channel_trail> appended for a non-empty trail. The own peer id is the one of the network of the receiver. The piggyback of the message is the token of this node followed by the inspector bit "0". Every content type except the three statistics types updates the time read by passed_time_since_last_communication. With the send queues on, the refusals of a full queue are counted and logged as at most one warning per peer every Custom.SEND_REFUSED_LOG_EVERY seconds (5). A False after a refusal says nothing about whether the peer is alive (see sends_are_queued). The hosted agent and world call it through self.node_conn and so does the node.
send_tracked
async
¶
send_tracked(peer_id: str, channel_trail: str | None, content_type: str, content: bytes | dict | str | None = None) -> SendTicket | None
Source code in unaiverse/networking/node/connpool.py
Sends a direct message like send and returns a SendTicket that follows it (async). It returns None when the queue of the peer refused the message. Otherwise the ticket starts in one of three states.
"dropped"with the error as reason when the send failed."written"when the transport has no queues (the browser transport returns only once the message is written)."queued"with its sequence number in every other case.
pop_send_events resolves a queued ticket. The events of the queue may have been popped while the send was still returning its sequence number. The method therefore first checks the highest sequence number already written and the last eight dropped ranges of that peer and resolves the ticket at once when they cover it. Nothing in the SDK calls it. It serves code that must know when a message has left.
True when the transport of at least one network has its send queues on. A False from send is then the refusal of a full queue and does not mean that the peer is gone (the Session keep-alive tells whether a peer is alive). When it is False (a native networking library older than the queues or the browser transport) a False from send is a failed write. Agent and World read it to interpret a failed send.
pop_send_events
¶
Source code in unaiverse/networking/node/connpool.py
Pops the events of the send queues of both networks and returns them as a list of dictionaries with an added p2p_name key. The public events come first and each network gives its events oldest first. P2P.pop_send_events describes the fields of each event. Each event also resolves the tickets of send_tracked that it covers ("written" up to a sequence number and "queue_dropped" over a range) and updates their progress on a "progress" event. A transport without queues gives no event. The node calls it once per network pass and reacts to each event.
request_keepalive_probe
¶
Source code in unaiverse/networking/node/connpool.py
Asks the Session of a peer to send its next keep-alive PING at once instead of at the end of its period of 15 seconds. A dead peer is then confirmed within the 10 seconds of the PING timeout. The node calls it on a "write_failed" event of the send queue.
stop_sending
async
¶
Source code in unaiverse/networking/node/connpool.py
Asks the peer that is sending a large message to stop it because this node no longer wants it (async). seq is the sequence number of the message in the queue of the sender as its chunk frames carry it. The request goes as STOP_SENDING through the Session of the peer (see Session.send_stop_sending). It returns True when the request was sent. It returns False in four cases: the peer has no Session, the Session is not ESTABLISHED, seq is not positive or the peer did not announce that it understands STOP_SENDING. A peer of the last kind keeps sending. The Python SDK never calls this method. The stop control of the chat in the browser runtime uses it.
passed_time_since_last_communication
¶
Source code in unaiverse/networking/node/connpool.py
Returns the seconds since the last message sent (statistics excluded) or received on any network. The result is never negative. The node reads it to slow its clock down when it is idle.
subscribe
async
¶
Source code in unaiverse/networking/node/connpool.py
Subscribes this node to a broadcast channel (async). The chosen network is the one whose own peer id is peer_id (a channel of this node). Otherwise the method uses the network of the peer and falls back to default_p2p_name (the world network when None). It returns False when no network fits or the transport refused and True otherwise. The hosted entity calls it to follow the channels of a peer.
unsubscribe
async
¶
Source code in unaiverse/networking/node/connpool.py
The reverse of subscribe with the same choice of network and the same return value.
publish
async
¶
publish(peer_id: str, channel: str, content_type: str, content: bytes | dict | tuple | None = None) -> bool
Source code in unaiverse/networking/node/connpool.py
Broadcasts a message on a channel of this node (async). The network is chosen as in subscribe but without a default. The message carries the token and the inspector bit as in send. It returns True when the transport accepted the message and False otherwise. Broadcast messages travel in one frame of at most 50 MB (see Large messages and files). The hosted entity calls it for its broadcast streams and the world node calls it for the roster.
reserve
async
¶
Source code in unaiverse/networking/node/connpool.py
Reserves a relay slot on the relay peer_id of the network p2p_name (async). It returns the expiry of the reservation as an ISO 8601 string. An unknown network or a refusal of the relay gives None and the error is logged. The node calls it to stay reachable from behind a router (see Relays).
set_turn_credentials
¶
Source code in unaiverse/networking/node/connpool.py
Hands both networks new credentials of the servers that the browser transport uses to traverse routers. ice_turn_servers is a list of dictionaries with keys urls, username and credential. Connections already open keep their configuration. The node calls it when it receives fresh credentials from the UNaIVERSE server.
Sessions¶
attach_session_policy
¶
attach_session_policy(p2p_u: P2P, p2p_w: P2P, local_profile_factory: Callable[[], dict], decision_hook: Callable | None, token_factory: Callable[[], str] | None = None, address_lookup: Callable | None = None) -> None
Source code in unaiverse/networking/node/connpool.py
Makes the object operational. It receives the transports of the public network (p2p_u) and of the world network (p2p_w) and builds one SessionManager around each. Both managers receive four objects.
local_profile_factory, a callable that returns the current profile of the node as a JSON-serializable dictionary.decision_hook, the policy that accepts or refuses an offer (seeSession).token_factory, a callable that returns the current token of this node.verify_token_claimsas their token verifier.
The public manager also receives address_lookup, an async callable from a node id to its addresses on the UNaIVERSE server. The server holds only the public addresses and the rendezvous keeps the world addresses current. The public manager routes peers by direction only. The world manager also checks them against the membership. The node calls it once after it has created both transports.
set_session_managers
¶
set_session_managers(*session_managers: SessionManager) -> None
Source code in unaiverse/networking/node/connpool.py
Registers the managers and binds each pool to the manager of its network. It also fills the index that finds a manager by network name. attach_session_policy calls it and unit tests call it with stub managers. None entries are ignored.
pump_sessions
async
¶
Source code in unaiverse/networking/node/connpool.py
Runs one Session pump and returns the events in the order of their production (async). inbound_by_p2p_name maps P2P_PUBLIC and P2P_WORLD to the SessionInbound lists returned by get_messages. now is a time.monotonic() value.
- Every inbound message of the public network goes to
SessionManager.deliverbefore every one of the world network. SessionManager.tickruns on the public manager and then on the world manager.- The world dials held by the wait for the roster go out when that wait is over (see
start_world_handoff). - For every ESTABLISHED and RESUMED event the method tells the transport of its network what the peer can receive. It passes the capability bits of the HELLO of the peer and the
max_message_sizeandmax_file_sizeof the dynamic part of its profile.
A manager with no inbound message still ticks. The node calls it once per network pass and dispatches the events it returns.
on_peer_disconnected
async
¶
Source code in unaiverse/networking/node/connpool.py
Tells both managers that the transport lost a peer and returns their events with the public ones first (async). An ESTABLISHED Session moves to RECONNECTING. A Session in the middle of its handshake fails (see SessionManager.on_peer_disconnected). The peer then leaves its pool without a disconnect because the link is already gone. The node calls it for each peer that update reports as removed.
on_peer_reconnected
async
¶
Source code in unaiverse/networking/node/connpool.py
Tells both managers that the transport sees a peer again and returns their events (async). Only a RECONNECTING Session reacts. An initiator sends RESUME and a responder sends a probe. A call for a peer seen for the first time is harmless. The node calls it for each peer that update reports as added.
is_in_grace
¶
Source code in unaiverse/networking/node/connpool.py
Returns True when a Session of the peer is RECONNECTING on either network. The node then keeps the peer among its known agents across the drop of the link instead of purging it at once.
is_peer_session_pending
¶
Source code in unaiverse/networking/node/connpool.py
Returns True when the peer has a Session on either network whose first handshake is in flight. Such a Session has never reached ESTABLISHED and is neither KNOWN nor RECONNECTING nor terminal. Agent.agents_are_waiting uses it.
requires_fast_clock
¶
Source code in unaiverse/networking/node/connpool.py
Returns True when a Session on either network is in any state other than KNOWN, FAILED and CLOSED. The node then keeps its main loop at full speed because the timers of the handshake, of the keep-alive and of the closing assume a responsive loop.
initiate_session
async
¶
initiate_session(p2p_name: str, peer_id: str, addresses: list, is_world_join: bool = False, remote_node_id_hint: str | None = None, reject_relay: bool = False) -> list
Source code in unaiverse/networking/node/connpool.py
Opens an initiator Session to a peer on the network p2p_name and returns its first events (async). They may include a FAILED event for a quarantined peer. addresses are the addresses of the peer. is_world_join=True marks the public Session that asks a world for a grant. remote_node_id_hint is the node id expected at the peer. reject_relay=True fails a dial that only reaches the peer through a relay. Two checks come before the call to SessionManager.initiate.
- A world join toward a peer that holds an ESTABLISHED carrier with no join in flight replaces that carrier. Such a carrier is a leftover of a failed join and its reuse would keep the new join from starting.
- While this agent waits for a roster that lists it, a dial toward a member of the world other than the world node is registered and held in KNOWN.
pump_sessionsstarts it when the wait is over.
The node calls it whenever it gets in touch with a peer.
start_world_handoff
async
¶
start_world_handoff(public_peer_id: str, world_peer_id: str, world_addrs: list, grant_blob: dict, reject_relay: bool) -> list
Source code in unaiverse/networking/node/connpool.py
Starts the redemption of a grant on the world network and returns the events of the new world Session (async).
| Argument | Type | Meaning |
|---|---|---|
public_peer_id |
str |
The world node on the public network. Its Session carries the grant. |
world_peer_id |
str |
The world node on the world network as named in the grant. |
world_addrs |
list |
Its addresses. |
grant_blob |
dict |
The grant as delivered by the ESTABLISHED event of the carrier. Its keys include rendezvous_tag and expiry_unix_ms. |
reject_relay |
bool |
True to refuse a world node reached only through a relay. |
- It points the world routing to
world_peer_id(set_world). - It opens the wait for a roster that lists this agent and is newer than
grant_blob["rendezvous_tag"]. The wait lasts at most 30 seconds. During it the dials toward the other members are held because a member that has not read such a roster would cut this agent as an unknown peer. - It records the pair in the
HandoffCorrelation. - It lifts the quarantine of
world_peer_idon the world network only when the verified token of the carrier listsworld_peer_idamong the peer ids of the world node. The grant proves that the world is up and admits this agent. A world peer id missing from the token keeps its quarantine. - It opens the world Session carrying the grant with one dial attempt. The budget of the dial equals the time left before the grant expires and is clamped between 15 and 35 seconds.
The node calls it when the public carrier reaches ESTABLISHED with a grant.
rollback_handoff
async
¶
Source code in unaiverse/networking/node/connpool.py
Calls HandoffCorrelation.rollback (async). The node calls it on every terminal event of a Session that may be part of a join.
is_pending_handoff
¶
Source code in unaiverse/networking/node/connpool.py
Calls HandoffCorrelation.is_pending.
handoff_carrier_of
¶
Source code in unaiverse/networking/node/connpool.py
Calls HandoffCorrelation.carrier_of.
complete_world_handoff
async
¶
Source code in unaiverse/networking/node/connpool.py
Retires the carrier of a join whose world Session is established (async). It removes the pair from the ledger and cuts the remaining wait for the roster to at most 5 seconds. It then sends a GOAWAY with WORLD_HANDOFF_COMPLETE on the public Session of the carrier and removes the carrier from the pools. The connection of the carrier is cut once its CLOSED event arrives. For a world peer id that was not part of a join the call does nothing. The node calls it when the world Session reaches ESTABLISHED.
Shutdown¶
The node shuts its networking down in three steps: close_all_sessions, then drain_teardown, then close_transports.
close_all_sessions
async
¶
Source code in unaiverse/networking/node/connpool.py
Calls SessionManager.close_all on both managers (async). The live Sessions send a GOAWAY and the handshakes in flight are aborted. The events are discarded.
drain_teardown
async
¶
Source code in unaiverse/networking/node/connpool.py
Keeps pumping only the Session traffic until no Session is CLOSING and no connection cut is pending or until budget_s seconds (3.0 by default) have passed (async). The world network goes first in every pass and a pause of 50 ms separates two passes. The return of a send only means that the frame is queued locally. Closing the transports right after close_all_sessions would therefore destroy the GOAWAY frames. Only the GOAWAY_ACK of each peer proves that its GOAWAY arrived. The chat messages popped during the drain are discarded. An error in a pass is logged and the drain continues.
close_transports
¶
Source code in unaiverse/networking/node/connpool.py
Closes the transport of each network (world first) and frees its slot in the native networking library. Every remaining connection is cut abortively. An error is logged and the next transport is still closed.