unaiverse.networking.p2p.messages¶
Two kinds of traffic travel between nodes. The Session messages (handshake, keep-alive, reconnection, close) are SessMsg objects on their own protocols. Everything else (profiles, stream samples, interactions, behaviors, statistics) is a chat message. This module defines the class Msg that represents it.
A Msg is a plain value object. Its fields are Python values (strings and a content that is a dict, a list or a dict of samples) and the class owns its wire codec in to_bytes and from_bytes. The codec writes the binary message format of the SDK. The codec imports its dependencies (the generated message classes, torch, PIL, gzip) only inside those two methods. Importing this module therefore loads nothing beyond the standard library. The same module also works in the browser runtime because there the codec runs on the JavaScript side.
The path of a chat message through the node is the following.
- The sender builds a
MsginNodeConnwith its own peer ID assender, a channel and its token inpiggyback. P2P.sendorP2P.broadcastencodes it withto_bytesin a worker thread and hands the bytes to the native networking library.- On the receiver,
P2P.get_messagesdecodes it withfrom_bytesand drops it whensenderdiffers from the peer ID that the transport verified. NodeConn.get_messageschecks the token inpiggybackand replaces it with the node ID of the sender. The node then dispatches the message on itscontent_type.
The developer meets Msg objects when reading the internals of the node or when writing tests. To talk to another agent, an agent calls the methods of Agent and the SDK builds the messages. It never builds a Msg itself.
Msg
¶
Msg(sender: str | None = None, content: Any = None, timestamp_net: str | None = None, channel: str | None = None, content_type: str = MISC, piggyback: str | None = None)
Source code in unaiverse/networking/p2p/messages.py
A message of the chat path with its own codec.
| Argument | Type | Default | Meaning |
|---|---|---|---|
sender |
str |
None |
The peer ID of the sender on the network the message travels on. It is required and None fails an assert. |
content |
Any |
None |
The content as a Python value (see the table of content types). None means no content. |
timestamp_net |
str \| None |
None |
The time of creation. None takes the current UTC time in the format "%Y-%m-%d %H:%M:%S.%f". |
channel |
str \| None |
None |
The channel of the message. None becomes "<unknown>". |
content_type |
str |
Msg.MISC |
One of the content types of the class. Any other value fails an assert. |
piggyback |
str \| None |
None |
The string carried next to the content. None becomes "". |
The checks are assert statements. Python run with -O skips them and a wrong value then travels to the codec.
The channel names the conversation. A direct message uses <sender peer ID>::dm:<receiver peer ID>-<content type> with an optional ~<trail> and a broadcast uses <owner peer ID>::ps:<topic>. The native networking library routes on this string. P2P.send_message_to_peer rejects a direct channel without ::dm: and P2P.broadcast_message rejects a broadcast channel without ::ps:.
The piggyback string is the node token of the sender followed by one character ("0" or "1") that tells whether the sender is an inspector. Once the receiver has checked the token, the string holds the node ID of the sender followed by the same character.
P2P.get_messages also gives every received message an attribute wire_size that holds the length of its encoded bytes. The node uses it to bound the memory of the messages that wait for the end of a tick.
from unaiverse.networking.p2p.messages import Msg
msg = Msg(sender="12D3KooWSender",
content={"addresses": ["/ip4/203.0.113.7/tcp/4001/p2p/12D3KooWSender"]},
channel="12D3KooWSender::dm:12D3KooWWorld-address_update",
content_type=Msg.ADDRESS_UPDATE,
piggyback="<token>0")
wire = msg.to_bytes()
same = Msg.from_bytes(wire)
assert same.content == msg.content
"profile". The message that carried the profile of a node in the old handshake. The Session handshake now carries profiles and the node ignores a received PROFILE with a log line.
"address_update". The new addresses of an agent, sent to its world node as {"addresses": [...]}. The world node stores them for the roster it publishes.
"stream_sample". Samples of one or more data streams. The content is a dict stream name -> {"data": ..., "data_tag": int, "data_uuid": str | None} and data is a torch.Tensor, a PIL.Image.Image, a str or a FileContainer. This is the only content type with a dedicated encoding (see to_bytes) and the only one that can travel as a file message.
"role_suggestion". A new role that the world node gives to an agent. The agent accepts it only from its world node and only when the content names its own world peer ID.
"interaction". An interaction request from one agent to another (see Interactions).
"interaction_status". The status of an interaction (accepted, rejected, completed and the others) sent back to the agent that asked for it.
"hsm". A request to change the behavior (the hybrid state machine) of an agent. An agent accepts it only from a world master of its world.
"misc". A message with no predefined meaning and the default content type of the constructor. The node logs it and takes no action.
"get_cv_from_root". A notice that the CV of the receiver changed on the UNaIVERSE server. The receiver downloads its CV again and then a new token that carries the new CV hash.
"badge_suggestions". A list of badges that an agent suggests for other agents and sends to the world node. Only a world node acts on it.
"inspect_on". Turns on the inspector mode of a node. The node accepts it only from the inspector node it expects.
"inspect_cmd". A command of the inspector in the form {"cmd": ..., "arg": ...}. The node runs it only after an INSPECT_ON of the same inspector.
"world_agents_list". The roster that a world node broadcasts on its rendezvous channel <world peer ID>::ps:rv. The content is {"peers": [...], "update_count": int} and each peer is a dict with id, addrs and misc (the role bits).
CONSOLE_AND_BEHAV_STATUS
class-attribute
instance-attribute
¶
"console_and_behav_status". The report that a node sends to its inspector. It holds the console of the node, its behavior and the state of that behavior, the profiles of the agents it knows and the properties of the streams it knows.
"stats_update". A batch of statistics that an agent sends to its world. The content is a list of dicts with group_key, stat_name, timestamp (an int) and value (any JSON value). The batch has its own encoding. A send of this type does not count as communication for NodeConn.passed_time_since_last_communication.
"stats_request". A request of an agent for the statistics of its world. As with the other two statistics types, sending it does not count as communication.
"stats_response". The answer of a world to a STATS_REQUEST.
CONTENT_TYPES
class-attribute
instance-attribute
¶
CONTENT_TYPES = {PROFILE, ADDRESS_UPDATE, STREAM_SAMPLE, ROLE_SUGGESTION, HSM, MISC, GET_CV_FROM_ROOT, BADGE_SUGGESTIONS, INSPECT_ON, INSPECT_CMD, WORLD_AGENTS_LIST, CONSOLE_AND_BEHAV_STATUS, STATS_UPDATE, STATS_REQUEST, STATS_RESPONSE, INTERACTION, INTERACTION_STATUS}
The set of the 17 content types above. The constructor accepts a content_type only when it belongs to this set. from_bytes does not check it.
The peer ID of the sender (str). The setter turns None into "". P2P.get_messages compares this value with the peer ID that the transport verified and drops the message when the two differ.
The content type (str). The setter turns None into Msg.MISC and does not check that the value belongs to CONTENT_TYPES.
The channel (str). The setter turns None into "<unknown>".
The piggyback string (str). NodeConn.get_messages writes it on the receiver to replace the token with the node ID of the sender. The setter turns None into "".
The time of creation as a str in the format "%Y-%m-%d %H:%M:%S.%f" (UTC). The setter turns None into "".
The content as a Python value. A message without content holds the sentinel string "<empty>". This property has no setter.
to_bytes
¶
Source code in unaiverse/networking/p2p/messages.py
Encodes the message in the binary message format and returns the bytes. P2P.send and P2P.broadcast call it in a worker thread because the encoding of tensors and images takes time.
| Argument | Type | Default | Meaning |
|---|---|---|---|
streamed_keys |
set[str] \| None |
None |
The names of the FILE samples whose file travels next to the message (a file message). For them the method writes the file name and the MIME type without the content. |
The content goes to one of three encodings.
STREAM_SAMPLE: every sample with a non-Nonedatabecomes an entry with itsdata_tag(default -1) and itsdata_uuidwhen it is notNone. A sample whosedataisNoneis left out. Atorch.Tensoris moved to the CPU and made contiguous. Its raw bytes are compressed with gzip at level 1 and travel with its dtype name and its shape. APIL.Image.Imagebecomes a PNG at compression level 9. Astris sent as text. AFileContaineris sent with its file name, its MIME type and its content (astrcontent is encoded to UTF-8) unless its name is instreamed_keys. Adataof any other type is left empty.STATS_UPDATE: every dict of the list becomes one entry and itsvaluekeeps its JSON type (null, bool, number, string, list or object). A value of another type is sent as itsstr.- Every other type: the content is serialized with
json.dumps. A content that JSON cannot represent raisesTypeError.
A message without content encodes no content field. The method does not check the size of the result. The native networking library refuses a message above the limits of the peer (see Networking).
from_bytes
classmethod
¶
from_bytes(msg_bytes: bytes) -> Msg
Source code in unaiverse/networking/p2p/messages.py
Decodes bytes of the binary message format into a new Msg and returns it. This classmethod is called by P2P.get_messages for every chat frame it pops.
| Argument | Type | Meaning |
|---|---|---|
msg_bytes |
bytes-like |
The encoded message. A memoryview is accepted. |
The object is built without calling the constructor and therefore skips its checks. A frame from the network is accepted as it is. The content is rebuilt as follows.
- A stream sample gives the dict of samples. A tensor is decompressed straight into the buffer of a new tensor of the encoded dtype and shape. An image gives a
PIL.Image.Imageopened lazily on the PNG bytes. A text gives astrand a file gives aFileContainerwith its content, file name and MIME type. - A statistics batch gives the list of dicts with
group_key,stat_name,timestampandvalue. A number comes back as afloatbecause the format stores every number as a double. - A JSON content gives the result of
json.loads. - No content gives the sentinel
"<empty>".
It raises the parse error of the binary message format for malformed bytes, json.JSONDecodeError for a malformed JSON content and ValueError when the decompressed tensor data do not match the size of its shape and dtype. An unknown dtype name raises AttributeError. P2P.get_messages catches all of them and drops the frame.
attach_received_files
¶
Source code in unaiverse/networking/p2p/messages.py
Attaches to the FILE samples of a received file message the files that arrived with it. P2P.get_messages calls it after place_received_file has moved each file to the downloads folder.
| Argument | Type | Meaning |
|---|---|---|
files |
dict[str, str] |
Sample name mapped to the final path of its file. |
Each named sample whose data is a FileContainer gets a new FileContainer with the same file name and MIME type and with path pointing to the file. The content stays on disk and is not loaded. Names without a matching FILE sample are ignored. The method changes nothing on a message that is not a stream sample and returns None.