unaiverse.networking.session.sess_msg¶
The Session between two nodes uses short messages of its own: the handshake (HELLO, PROFILE_OFFER and the others), the keep-alive (PING and PONG), the reconnection (RESUME) and the goodbye (GOAWAY). This module defines them as plain Python values together with the codec that turns them into bytes and back. It sits at the bottom of the session layer and imports nothing from it. The Session builds and reads SessMsg objects without ever encoding them. Only the transport (P2P.send_session and P2P.get_messages) calls to_bytes and from_bytes.
The module holds five groups of objects.
- The four protocol identifiers on which the Session messages travel and the set that groups them.
- The three capability bits that each side announces in its
HELLOorHELLO_ACK. - The reason codes that a refusal or a goodbye carries, their names and
reason_name. - The message class
SessMsgand the wrapperSessionInboundthat pairs an inbound message with its sender. - The values that the decision hook of a responder receives and returns:
VerifiedTokenClaims,ProfileDecisionResultandWorldGrantSpec.
A developer meets the last group when writing a decision policy for node.set_decision_policy(...) and meets the reason codes in the logs and in the reasons of the Session events (see Networking). Everything else is used by the session layer and the transport only.
Wire format¶
Every Session message is one frame on a one-shot stream of its protocol. The first byte of the frame is a kind tag that names the message. The rest is the payload in one of two encodings.
- The handshake messages and the goodbye (tags
0x01to0x0A) use the binary message format of the SDK. Its generated classes are imported only insideto_bytesandfrom_bytes. Importing this module therefore loads nothing heavy and works in the browser runtime. - The liveness and control messages added later (tags
0x0Bto0x10) use a small JSON object in UTF-8 with everybytesfield written as a hexadecimal string.
Because the tag names the message, the receiver does not need to infer the message from the direction or the fields. The native networking library never parses these bytes and only carries them.
>>> m = SessMsg(SessMsg.KIND_PING, {"session_id": bytes.fromhex("9f2c6a0b4d1e7f3a8c5b2e6d0a4f1c7e"),
... "nonce": bytes.fromhex("0011223344556677")})
>>> m.to_bytes()
b'\x0b{"session_id": "9f2c6a0b4d1e7f3a8c5b2e6d0a4f1c7e", "nonce": "0011223344556677"}'
>>> SessMsg.from_bytes(m.to_bytes()).fields
{'session_id': b'\x9f,j\x0bM\x1e\x7f:\x8c[.m\nO\x1c~', 'nonce': b'\x00\x11"3DUfw'}
Protocols¶
"/unaiverse/session/hello/1.0.0". The protocol of HELLO and HELLO_ACK. A manager also answers a simultaneous open on it with a HELLO_ACK that carries SIMULTANEOUS_OPEN_LOSS.
SESSION_PROFILE_PROTOCOL
module-attribute
¶
"/unaiverse/session/profile/1.0.0". The protocol of PROFILE_OFFER and PROFILE_DECISION.
"/unaiverse/session/world/1.0.0". The protocol of WORLD_GRANT. A world node sends the grant on it right after its decision. The decision and the grant travel on different protocols with no ordering guarantee and the joiner may therefore receive the grant first.
SESSION_CONTROL_PROTOCOL
module-attribute
¶
"/unaiverse/session/control/1.0.0". The protocol of everything that follows the handshake (GOAWAY, GOAWAY_ACK, PING, PONG, RESUME, RESUME_ACK, TOKEN_UPDATE and STOP_SENDING).
SESSION_PROTOCOL_IDS
module-attribute
¶
SESSION_PROTOCOL_IDS = frozenset({SESSION_HELLO_PROTOCOL, SESSION_PROFILE_PROTOCOL, SESSION_WORLD_PROTOCOL, SESSION_CONTROL_PROTOCOL})
The frozenset of the four protocols above. P2P.get_messages uses it to split the inbound frames into Session messages and chat messages. SessionManager.deliver drops a message whose protocol is not in it.
Capability bits¶
Each side writes an int that combines these bits into the capabilities field of its HELLO or HELLO_ACK. They describe what the transport of that side can do and not what the code knows. The browser transport runs the same Session code and announces 0. A peer that sends 0 (any node older than the bits) gets the old behavior: messages of up to 50 MB in one frame, files inside the message and no stop. The node passes the bits of the peer to its transport when the Session reaches ESTABLISHED or RESUMED (see Large messages and files).
1 (bit 0). The side accepts chat messages larger than one chunk (5 MB) as a sequence of chunk frames on the same stream. One such message can reach 1 GB.
2 (bit 1). The side accepts file messages. The sender of a file message streams its files from disk in chunks next to the message. A node announces it only when its transport can stream files and Custom.ACCEPT_FILES is true.
4 (bit 2). The side stops sending a large message when its receiver asks with STOP_SENDING. A receiver sends STOP_SENDING only to a peer with this bit.
Inbound messages¶
SessionInbound
module-attribute
¶
A namedtuple with three fields: peer_id (the sender as the transport verified it), protocol_id (one of SESSION_PROTOCOL_IDS) and sess_msg (the decoded SessMsg). The payload of a Session message carries neither the sender nor the protocol and the manager needs both to route it. P2P.get_messages builds one per inbound Session frame. NodeConn.pump_sessions hands each one to SessionManager.deliver of its network.
SessionInbound(peer_id="12D3KooW...", protocol_id="/unaiverse/session/control/1.0.0",
sess_msg=SessMsg(kind="pong", fields={"session_id": b"...", "nonce": b"...", "ok": True}))
Reason codes¶
A reason code is an int that tells why a handshake was refused or why a Session ended. It travels in the reason_code field of HELLO_ACK, PROFILE_DECISION and RESUME_ACK and in the reason field of GOAWAY. The Sessions put its name into the reasons of their events (profile_rejected:NOT_IN_ALLOW_LIST, remote_goaway:WORLD_DISENGAGEMENT and so on). The values match the enumeration of the binary message format. The current SDK never sends some of the codes of the format and the text of each such code says so.
0. No error. A positive HELLO_ACK, PROFILE_DECISION or RESUME_ACK carries it.
1. The HELLO offered no protocol version that the responder speaks (the only version is "1.0"). The responder answers with it in HELLO_ACK and fails its Session.
2. Reserved for a responder that has no room for the peer. No code of the current SDK sends it.
3. The peer did not prove who it is. A responder sends it in PROFILE_DECISION when the signature sig_a or the token of the offer does not verify. The decision hook of a world node also returns it when the token of a joiner attests no world peer id or no world address.
4. The node id of the peer is not among the nodes that the owner of the responder allows. The decision hook of the node returns it.
5. The CV in the profile offered by the peer does not hash to the value that its token attests. The CV is therefore forged or stale. The decision hook of the node returns it.
6. A world found no role for the joiner. The decision hook of a world node returns it when World.assign_role returns None.
7. Reserved for a world that admits nobody at the moment. No code of the current SDK sends it.
8. The hosted agent or world refused the peer. The decision hook returns it for a profile that cannot be parsed. A world node also closes with it the world Session of a joiner whose role lacks the world bit or whose profile has no world address.
9. An ordinary goodbye and the default of Session.close, SessionManager.close_session and SessionManager.close_all. An agent also closes with it the Session of a peer it removes on purpose.
10. The node leaves a world or stops working with a peer of that world. NodeConn.remove_all_world_agents and the agent close the Sessions of the former companions with it. The companions then see CLOSED and do not try to reconnect.
11. The joiner closes with it the public Session that brought its grant once the world Session is established (NodeConn.complete_world_handoff). The node recognizes this name in the reason of CLOSED and does not purge the world.
12. Reserved for a world that takes a role back. No code of the current SDK sends it.
13. Reserved for a peer whose token the UNaIVERSE server revoked. No code of the current SDK sends it.
14. Reserved for a host that removes a peer. No code of the current SDK sends it.
15. Something failed on the side that sends it. A responder refuses with it an offer whose profile is not valid JSON or whose decision hook raised. An agent or a world closes with it the Session of a peer to which a send failed.
16. Reserved for a grant redeemed too late. No code of the current SDK sends it because a joiner checks the expiry itself and fails with world_grant_expired.
17. Two nodes dialed each other at the same time. The manager of the node with the smaller peer id keeps its initiator and sends this code in a HELLO_ACK to the other node. The initiator of the other node fails with this code if it is still waiting (see SessionManager).
18. The receiver holds no Session with that session_id (typically because it restarted). A RESUME_ACK with accepted=false carries it and the initiator then runs a new handshake or reports LOST.
19. The token of the peer expired more than 3600 s ago with no TOKEN_UPDATE in between. The Session sends GOAWAY with it from tick_keepalive.
20. Reserved for the perimeter of a world. No code of the current SDK sends it because the perimeter cuts a non-member without any goodbye.
REASON_NAME
module-attribute
¶
REASON_NAME: dict[int, str] = {OK: 'OK', VERSION_UNSUPPORTED: 'VERSION_UNSUPPORTED', OVERLOADED: 'OVERLOADED', NOT_AUTHORIZED: 'NOT_AUTHORIZED', NOT_IN_ALLOW_LIST: 'NOT_IN_ALLOW_LIST', CV_HASH_MISMATCH: 'CV_HASH_MISMATCH', ROLE_INCOMPATIBLE: 'ROLE_INCOMPATIBLE', WORLD_BUSY: 'WORLD_BUSY', HOSTED_REJECTED: 'HOSTED_REJECTED', GRACEFUL_SHUTDOWN: 'GRACEFUL_SHUTDOWN', WORLD_DISENGAGEMENT: 'WORLD_DISENGAGEMENT', WORLD_HANDOFF_COMPLETE: 'WORLD_HANDOFF_COMPLETE', ROLE_REVOKED: 'ROLE_REVOKED', TOKEN_REVOKED: 'TOKEN_REVOKED', KICKED_BY_HOST: 'KICKED_BY_HOST', LOCAL_ERROR: 'LOCAL_ERROR', GRANT_EXPIRED: 'GRANT_EXPIRED', SIMULTANEOUS_OPEN_LOSS: 'SIMULTANEOUS_OPEN_LOSS', SESSION_UNKNOWN: 'SESSION_UNKNOWN', TOKEN_EXPIRED: 'TOKEN_EXPIRED', PERIMETER_CUT: 'PERIMETER_CUT'}
The dict[int, str] that maps every reason code above to its name ({0: "OK", 1: "VERSION_UNSUPPORTED", ...}).
reason_name
¶
Source code in unaiverse/networking/session/sess_msg.py
Returns the name of a reason code as REASON_NAME gives it. The argument goes through int() first and an unknown code returns its decimal string (reason_name(99) == "99"). It never raises for an int. The Session and the manager call it to build the reasons of their events and their logs.
The message¶
A Session message holds a kind and a dict of fields whose names follow the definition of the binary message format. bytes fields stay bytes and integers stay int. The class is a dataclass without validation and a missing field stays absent until the message is encoded. The Session builds messages with the kind constants below and reads their fields with get or msg["name"].
from unaiverse.networking.session import SessMsg
msg = SessMsg(SessMsg.KIND_GOAWAY, {"reason": 9, "drain_window_ms": 0, "session_id": sid})
msg.get("reason") # 9
msg.get("missing", "n/a") # "n/a"
msg["session_id"] # the bytes of sid
The table lists every kind with its tag, its protocol and its fields in the order in which the codec writes them. The Session never writes the fields marked unused.
| Constant | kind |
Tag | Protocol | Fields |
|---|---|---|---|---|
KIND_HELLO_REQ |
"hello_request" |
0x01 |
hello | session_id (16 bytes), nonce_a (32 bytes), protocol_versions (list of str), capabilities (int), client_id (str) |
KIND_HELLO_RESP |
"hello_response" |
0x02 |
hello | chosen_version (str), capabilities, nonce_b (32 bytes), sig_b (bytes), reason_code (int) |
KIND_PROFILE_OFFER |
"profile_offer" |
0x03 |
profile | profile (JSON bytes), sig_a (bytes), session_id, token (str) |
KIND_PROFILE_DECISION |
"profile_decision" |
0x04 |
profile | accepted (bool), profile_b (JSON bytes), reason_code, hint_addrs (list, unused), retry_after_ms (unused), session_id, token |
KIND_WORLD_GRANT |
"world_grant" |
0x05 |
world | grant_id (32 bytes), expiry_unix_ms (int), world_profile (bytes), role (int), code_bundle (bytes), initial_stats (bytes), rendezvous_tag (int) |
KIND_WORLD_GRANT_ACK |
"world_grant_ack" |
0x06 |
world | received (bool). It is never sent and stays decodable for old joiners. |
KIND_GOAWAY |
"goaway" |
0x09 |
control | reason (int), drain_window_ms (always 0), session_id |
KIND_GOAWAY_ACK |
"goaway_ack" |
0x0A |
control | received (bool) |
KIND_PING |
"ping" |
0x0B |
control | session_id, nonce (8 bytes) |
KIND_PONG |
"pong" |
0x0C |
control | session_id, nonce, ok (bool) |
KIND_RESUME |
"resume" |
0x0D |
control | session_id, nonce (8 bytes) |
KIND_RESUME_ACK |
"resume_ack" |
0x0E |
control | session_id, nonce, accepted (bool), reason_code (int) |
KIND_TOKEN_UPDATE |
"token_update" |
0x0F |
control | session_id, token (str) |
KIND_STOP_SENDING |
"stop_sending" |
0x10 |
control | session_id, seq (int) |
The kind of the message as one of the KIND_* strings.
The fields of the message as a dict keyed by field name. It is empty by default.
"hello_request". The HELLO that an initiator sends first. It opens the Session with its session_id and the nonce that the responder signs.
"hello_response". The HELLO_ACK of the responder with its signature over nonce_a || session_id. A refusal carries a non-zero reason_code and empty fields.
"profile_offer". The profile and the token of the initiator with its signature over nonce_b || session_id.
KIND_PROFILE_DECISION
class-attribute
instance-attribute
¶
"profile_decision". The answer of the responder. An acceptance carries its profile and its token. A refusal carries only accepted=False, the reason code and the session_id.
"world_grant". The admission that a world node grants to a joiner. It is not signed and the joiner trusts it because both tokens of the public Session were verified.
"world_grant_ack". An acknowledgement of the grant that the current SDK never sends.
"goaway". The goodbye with its reason code. The session_id lets the receiver ignore a goodbye meant for an older Session.
"goaway_ack". The acknowledgement of a GOAWAY. It has no session_id and the receiver matches it by its sender.
"ping". The keep-alive of an established Session and the probe of a reconnecting responder.
"pong". The answer to a PING with the same nonce. ok is true only when the receiver holds that Session in a usable state.
"resume". The request of a reconnecting initiator to continue the Session with the same session_id.
"resume_ack". The answer to a RESUME with the same nonce. A refusal carries SESSION_UNKNOWN.
"token_update". The refreshed node token of the sender.
"stop_sending". The request of a receiver to stop the large message whose sequence number in the send queue of the peer is seq.
get
¶
Source code in unaiverse/networking/session/sess_msg.py
Returns the field key or default (None unless given) when the message lacks it. It never raises. The Session reads every field through it.
to_bytes
¶
Source code in unaiverse/networking/session/sess_msg.py
Encodes the message as the kind tag followed by the payload and returns the bytes. A JSON kind writes every field that is present and not None with bytes turned into hexadecimal. Any other kind fills the generated class of the binary message format with the fields that are present and not None. An unknown kind raises ValueError and a field of the wrong type raises the error of the binary format. P2P.send_session calls it right before writing the frame and returns False when it raises.
from_bytes
classmethod
¶
from_bytes(payload: bytes, protocol_id: str | None = None) -> SessMsg
Source code in unaiverse/networking/session/sess_msg.py
Decodes the bytes of one frame into a new SessMsg. protocol_id is used only in the error message. A JSON kind restores the bytes fields from hexadecimal and fills missing fields with defaults: b"" for bytes, False for ok and accepted, "" for token and 0 for the rest. A kind of the binary format gets every field of its kind with the defaults of that format and its list fields as list. An empty payload or an unknown tag raises ValueError and malformed content raises the error of the decoder. P2P.get_messages calls it for every inbound Session frame and drops a frame that fails to decode.
Decision values¶
VerifiedTokenClaims
dataclass
¶
VerifiedTokenClaims(node_id: str, cv_hash: str, p2p_peers: tuple = (), exp: int = 0, code_hash: str | None = None)
The claims of a node token that the UNaIVERSE server signed and the responder verified against the peer id of the transport. A frozen dataclass. The Session builds it after the verification and passes it to the decision hook. The hook trusts these claims more than the profile offered by the peer. The hook receives None instead when no token verifier is configured.
| Field | Type | Default | Meaning |
|---|---|---|---|
node_id |
str |
required | The node id of the peer. The allow list of the owner is checked against it. |
cv_hash |
str |
required | The hash of the CV of the peer. The CV in the offered profile must hash to it. |
p2p_peers |
tuple |
() |
The peer ids of the node on the public and the world network. A world node uses them to admit the world peer id of a joiner. |
exp |
int |
0 |
The expiry of the token in Unix seconds. |
code_hash |
str \| None |
None |
The hash of the stored code of a world, present only in the token of a world node. The joiner checks the code bundle of its grant against it. |
The node id attested by the token.
The hash of the CV attested by the token.
The public and world peer ids attested by the token.
The expiry of the token in Unix seconds.
The hash of the code of a world or None.
ProfileDecisionResult
dataclass
¶
ProfileDecisionResult(accepted: bool, reason_code: int = OK, world_grant: WorldGrantSpec | None = None)
What a decision hook returns for one offer. With accepted=False the responder sends a negative PROFILE_DECISION with reason_code and fails its Session. With accepted=True and no world_grant the responder accepts and enters ESTABLISHED. With accepted=True and a world_grant the responder is a world node on the public network that sends a grant and waits for the handoff.
| Field | Type | Default | Meaning |
|---|---|---|---|
accepted |
bool |
required | Whether the offer is accepted. |
reason_code |
int |
OK |
The reason of a refusal. An acceptance ignores it. |
world_grant |
WorldGrantSpec \| None |
None |
The grant to send. Only a world node on its public network returns one. |
from unaiverse.networking.session import ProfileDecisionResult
from unaiverse.networking.session.sess_msg import NOT_IN_ALLOW_LIST
async def only_known(peer_id, node_id, profile, p2p_name, claims):
if claims is None or claims.node_id not in {"node-lab-arm-01", "node-lab-cam-02"}:
return ProfileDecisionResult(accepted=False, reason_code=NOT_IN_ALLOW_LIST)
return ProfileDecisionResult(accepted=True)
True to accept the offer.
The reason code sent with a refusal.
The specification of the grant or None.
WorldGrantSpec
dataclass
¶
WorldGrantSpec(role: int, world_profile_bytes: bytes, rendezvous_tag: int, code_bundle: bytes = b'', initial_stats: bytes = b'', grant_ttl_ms: int = 30000)
The grant that a world node puts in the ProfileDecisionResult for a joiner on its public network. The Session turns it into a WORLD_GRANT and adds a random 32-byte grant_id and the expiry. The fields of type bytes are already serialized and the joiner decodes them.
| Field | Type | Default | Meaning |
|---|---|---|---|
role |
int |
required | The role bits assigned to the joiner. |
world_profile_bytes |
bytes |
required | The profile of the world serialized for the joiner. It travels as world_profile. |
rendezvous_tag |
int |
required | The tag of the roster of the world at the time of the grant. The joiner holds its dials toward the other members until a newer roster lists it. |
code_bundle |
bytes |
b"" |
The code of the role, its behavior and the code of the statistics packed as one blob. |
initial_stats |
bytes |
b"" |
The initial statistics of the world. |
grant_ttl_ms |
int |
30000 |
The validity of the grant in milliseconds from the time it is sent. |
The role bits of the joiner.
The serialized profile of the world.
The roster tag at the time of the grant.
The packed code of the role.
The serialized initial statistics.
The validity of the grant in milliseconds.