lib.rs
Overview
This file serves as a core utility and configuration module within the system, providing essential data types, helper functions, and serialization/deserialization logic primarily related to network communication and message handling. It defines enums for message delivery phases and send modes, utility functions for parsing and serializing network socket addresses, and modules that organize different aspects of the system such as messaging, networking, metrics, and configuration.
The file also exposes and re-exports key components like direct_sender for use in other parts of the system. It is foundational for enabling reliable network communication and message exchange, supporting both broadcast and direct messaging modes.
Modules
channel: Manages communication channels.
cli: Command-line interface utilities.
config: System configuration.
direct_sender: Implements direct sending capabilities. This module is re-exported for external use.
message: Defines message formats and protocols.
metrics: Metrics collection and reporting.
network: Network-related utilities and abstractions.
pub_sub: Publish-subscribe pattern implementation.
resolver: Address and service resolution mechanisms.
tests: Contains unit tests for the module (enabled only in test builds).
transfer: Handles data or message transfer logic.
unix_signals: UNIX signal handling.
Constants
ACKI_NACKI_DIRECT_PROTOCOL, ACKI_NACKI_SUBSCRIPTION_FROM_NODE_PROTOCOL, ACKI_NACKI_SUBSCRIPTION_FROM_PROXY_PROTOCOL: Define protocol string constants used for different communication protocols.
DEFAULT_PUBLISHER_PORT: Default port number (8500) used when parsing publisher socket addresses.
Enums
DeliveryPhase
#[derive(Copy, Clone)]
pub enum DeliveryPhase {
OutgoingBuffer,
OutgoingTransfer,
IncomingTransfer,
IncomingBuffer,
}
Represents the phase of message delivery:
OutgoingBuffer: Message is buffered before sending.OutgoingTransfer: Message is in the process of being sent.IncomingTransfer: Message is being received.IncomingBuffer: Message is buffered after receiving.
Usage Example:
let phase = DeliveryPhase::OutgoingTransfer;
match phase {
DeliveryPhase::OutgoingBuffer => println!("Buffering outgoing message"),
DeliveryPhase::OutgoingTransfer => println!("Sending message"),
_ => {}
}
SendMode
pub enum SendMode {
Broadcast,
Direct,
}
Defines how messages are sent:
Broadcast: Message is sent to all subscribers.Direct: Message is sent directly to specific recipients.
Methods:
as_str(&self) -> &'static str: Returns string representation ("broadcast"or"direct").is_broadcast(&self) -> bool: Returnstrueif mode is broadcast, otherwisefalse.Implements
Displaytrait for formatting.
Usage Example:
let mode = SendMode::Broadcast;
println!("Send mode: {}", mode); // Output: "Send mode: broadcast"
Structs
PublisherConfig
#[derive(Clone, Debug)]
pub struct PublisherConfig {
pub addrs: Vec<SocketAddr>,
}
Configuration structure holding a list of publisher socket addresses.
addrs: Vector ofSocketAddrrepresenting publisher endpoints.
This struct can be used to configure network publishers and manage their addresses.
Functions
host_id_prefix
pub fn host_id_prefix(s: &str) -> &str
Extracts the first 6 characters from a string, intended to be used as a host ID prefix.
Parameters:
s: input string.
Returns:
Slice of the first 6 characters if possible; otherwise, returns the whole string.
Example:
let prefix = host_id_prefix("abcdef12345");
assert_eq!(prefix, "abcdef");
detailed
pub(crate) fn detailed(err: &impl Debug) -> String
Formats a debug error object into a single-line string by removing line breaks.
Parameters:
err: any type implementingDebug.
Returns:
A
Stringwith debug information without newline characters.
try_parse_socket_addr
pub fn try_parse_socket_addr(s: impl AsRef<str>, default_port: u16) -> anyhow::Result<SocketAddr>
Parses a string into a SocketAddr. If the string does not contain a port, appends the provided default_port.
Parameters:
s: string representation of an address (e.g.,"127.0.0.1:8080"or"127.0.0.1").default_port: port number to append if missing.
Returns:
Ok(SocketAddr)if parsing is successful.Errotherwise with context.
Example:
let addr = try_parse_socket_addr("127.0.0.1", 8500).unwrap();
assert_eq!(addr.port(), 8500);
parse_publisher_addr
pub fn parse_publisher_addr(s: impl AsRef<str>) -> anyhow::Result<SocketAddr>
Helper function that parses a string into a SocketAddr using the default publisher port (8500).
Parameters:
s: string address.
Returns:
Parsed
SocketAddror error.
deserialize_publisher_addr
pub fn deserialize_publisher_addr<'de, D>(deserializer: D) -> Result<SocketAddr, D::Error>
where
D: Deserializer<'de>,
Deserializes a string into a SocketAddr, using parse_publisher_addr. Used with Serde for config or message parsing.
deserialize_optional_publisher_addr
pub fn deserialize_optional_publisher_addr<'de, D>(deserializer: D) -> Result<Option<SocketAddr>, D::Error>
where
D: Deserializer<'de>,
Deserializes an optional string into an optional SocketAddr.
serialize_subscribe
pub fn serialize_subscribe<S>(value: &Vec<Vec<SocketAddr>>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
Serializes a nested list of socket addresses (publishers with their addresses) into a flat list for serialization.
deserialize_subscribe
pub fn deserialize_subscribe<'de, D>(deserializer: D) -> Result<Vec<Vec<SocketAddr>>, D::Error>
where
D: Deserializer<'de>,
Deserializes a flat list of socket address strings into a nested vector structure (publishers with their addresses), parsing each address.
deserialize_publisher_addrs
pub fn deserialize_publisher_addrs<'de, D>(deserializer: D) -> Result<Vec<SocketAddr>, D::Error>
where
D: Deserializer<'de>,
Deserializes a list of publisher address strings into a vector of SocketAddr.
extract_msg_type
pub fn extract_msg_type(s: impl AsRef<str>) -> String
Extracts the message type from a string representation of a message. It looks for a substring after "::" in the first token of the string.
Parameters:
s: string containing message type info.
Returns:
Extracted message type as
String, or empty string if none found.
Example:
let msg_type = extract_msg_type("MsgType::MyMessage (1, 22222)");
assert_eq!(msg_type, "MyMessage");
Testing
The file includes unit tests under the unit_tests module to validate:
try_parse_socket_addrcorrectness.extract_msg_typebehavior for valid and invalid input.
Implementation Details
Uses
anyhowcrate for error handling with context.Serialization and deserialization leverage the
serdecrate for structured data conversion.Network addresses are handled using Rust’s standard library
std::net::SocketAddrandToSocketAddrs.The
SendModeenum implements theDisplaytrait for easy textual representation.The function
host_id_prefixuses a safe split operation to extract the prefix.Flattening and nesting of socket addresses during (de)serialization allow flexible configuration structures.
Interactions with Other Parts of the Application
The modules declared here (
channel,cli,config,message,network, etc.) encapsulate different components of the system, facilitating modular design.The
direct_sendermodule is re-exported for use elsewhere, indicating this file acts as a façade or entry point.Serialization and deserialization functions are intended for use in configuration parsing or message processing workflows, enabling network communication setup.
The
SendModeandDeliveryPhaseenums are likely utilized by message routing and delivery components to control message flow.Socket address parsing ensures network endpoints are correctly interpreted and used by networking modules.
Mermaid Diagram: File Structure and Main Functions Flowchart
flowchart TD
A[lib.rs] --> B[channel]
A --> C[cli]
A --> D[config]
A --> E[direct_sender]
A --> F[message]
A --> G[metrics]
A --> H[network]
A --> I[pub_sub]
A --> J[resolver]
A --> K[tests]
A --> L[transfer]
A --> M[unix_signals]
A --> N[Enums]
N --> N1[DeliveryPhase]
N --> N2[SendMode]
A --> O[Functions]
O --> O1[host_id_prefix]
O --> O2[detailed]
O --> O3[try_parse_socket_addr]
O --> O4[parse_publisher_addr]
O --> O5[deserialize_publisher_addr]
O --> O6[deserialize_optional_publisher_addr]
O --> O7[serialize_subscribe]
O --> O8[deserialize_subscribe]
O --> O9[deserialize_publisher_addrs]
O --> O10[extract_msg_type]
A --> P[Structs]
P --> P1[PublisherConfig]
This diagram illustrates the hierarchical organization of the file, showing the primary modules, enums, functions, and structs contained within lib.rs.