Improve Rust code clarity across the workspace

Document public APIs and non-obvious control flow so the protocol, simulator, and macro crates are easier to follow. Tighten a few helper paths and feature gates while preserving behavior and keeping the workspace warning-free.
This commit is contained in:
Michael Mikovsky
2026-04-25 11:11:19 -06:00
parent f49af7fa22
commit ba3f28a78c
26 changed files with 571 additions and 402 deletions
+4
View File
@@ -58,6 +58,8 @@ pub fn set_logger(logger: &'static dyn Logger) {
}
/// Returns the currently installed global logger.
///
/// Until [`set_logger`] runs, this returns the internal null sink.
#[must_use]
pub fn global_logger() -> &'static dyn Logger {
GLOBAL_LOGGER.get()
@@ -66,6 +68,8 @@ pub fn global_logger() -> &'static dyn Logger {
/// Sends a single record through the installed global logger.
///
/// Most code should prefer the exported logging macros.
/// This helper exists for integrations that already have a preformatted message
/// and explicit source context.
pub fn log(level: LogLevel, message: &str, file: Option<&'static str>, line: Option<u32>) {
global_logger().log(&Record::new(level, message, file, line));
}
+6
View File
@@ -25,6 +25,12 @@ impl CompatibilityLogger {
Self { min_level }
}
/// Returns the minimum severity that passes the filter.
#[must_use]
pub const fn min_level(&self) -> LogLevel {
self.min_level
}
/// Returns whether a record at `level` would be accepted.
///
/// # Examples
+17 -4
View File
@@ -51,30 +51,44 @@ pub struct ParsedFrame<'a> {
}
impl<'a> ParsedFrame<'a> {
/// Returns the deserialized packet header.
///
/// The header is owned by `ParsedFrame` because decoding must validate it
/// before any routing decision is made.
#[must_use]
pub fn header(&self) -> &PacketHeader {
&self.header
}
/// Returns the header packet type for quick dispatch.
#[must_use]
pub fn packet_type(&self) -> PacketType {
self.header.packet_type
}
/// Returns the raw archived payload section.
#[must_use]
pub fn payload_bytes(&self) -> &'a [u8] {
self.payload_bytes
}
/// Clones the decoded header out of the parsed frame.
#[must_use]
pub fn deserialize_header(&self) -> PacketHeader {
self.header.clone()
}
/// Deserializes the payload as a [`CallMessage`].
pub fn deserialize_call(&self) -> Result<CallMessage, FrameError> {
deserialize_archived_bytes::<ArchivedCallMessage, CallMessage>(self.payload_bytes)
}
/// Deserializes the payload as a [`DataMessage`].
pub fn deserialize_data(&self) -> Result<DataMessage, FrameError> {
deserialize_archived_bytes::<ArchivedDataMessage, DataMessage>(self.payload_bytes)
}
/// Deserializes the payload as a [`FaultMessage`].
pub fn deserialize_fault(&self) -> Result<FaultMessage, FrameError> {
deserialize_archived_bytes::<ArchivedFaultMessage, FaultMessage>(self.payload_bytes)
}
@@ -211,10 +225,9 @@ where
}
fn align_section(bytes: &[u8]) -> AlignedVec {
if bytes.as_ptr().align_offset(16) == 0 {
// Still need to return AlignedVec for the API, but maybe we can avoid
// some overhead. Actually, AlignedVec is just a wrapper around Vec.
}
// The framed wire format prefixes each archived section with a 4-byte length,
// so callers cannot rely on the borrowed slice meeting rkyv's alignment.
// Copying into `AlignedVec` keeps the alignment fix local and predictable.
let mut aligned = AlignedVec::with_capacity(bytes.len());
aligned.extend_from_slice(bytes);
aligned
+5
View File
@@ -22,6 +22,10 @@ pub use types::{
};
pub use validation::{ValidationError, validate_call, validate_header, validate_procedure_id};
/// Encodes a header and payload with the crate's default frame codec.
///
/// This is a convenience wrapper around [`RkyvCodec`] for callers that do not
/// need to choose a codec explicitly.
pub fn encode_packet<P>(header: &PacketHeader, payload: &P) -> Result<FrameBytes, FrameError>
where
P: for<'a> rkyv::Serialize<
@@ -35,6 +39,7 @@ where
codec::encode_packet(header, payload)
}
/// Decodes a framed packet with the crate's default frame codec.
pub fn decode_frame(bytes: &[u8]) -> Result<ParsedFrame<'_>, FrameError> {
codec::decode_frame(bytes)
}
+25
View File
@@ -25,14 +25,31 @@ impl<T> RouteResolution for T where T: RouteProvider + ?Sized {}
/// Hook storage contract for pending and active protocol flows.
pub trait HookStore {
/// Allocates a hook identifier scoped to `return_path`.
fn allocate_hook_id(&mut self, return_path: &[String]) -> u64;
/// Inserts a hook created by an incoming call before the peer is confirmed.
fn insert_pending(&mut self, pending: PendingHook) -> Result<(), HookConflict>;
/// Inserts an already-established hook flow.
fn insert_active(&mut self, active: ActiveHook) -> Result<(), HookConflict>;
/// Promotes a pending hook once the responding peer is known.
fn activate_pending(&mut self, key: &HookKey, peer_path: Vec<String>) -> Option<()>;
/// Removes a pending hook.
fn remove_pending(&mut self, key: &HookKey) -> Option<PendingHook>;
/// Removes an active hook.
fn remove_active(&mut self, key: &HookKey) -> Option<ActiveHook>;
/// Returns immutable access to a pending hook.
fn pending(&self, key: &HookKey) -> Option<&PendingHook>;
/// Returns immutable access to an active hook.
fn active(&self, key: &HookKey) -> Option<&ActiveHook>;
/// Returns mutable access to an active hook.
fn active_mut(&mut self, key: &HookKey) -> Option<&mut ActiveHook>;
}
@@ -76,9 +93,13 @@ impl HookStore for HookTable {
/// Leaf metadata contract used for protocol discovery payloads.
pub trait LeafMetadata {
/// Returns the leaf name exposed in routing and introspection.
fn leaf_name(&self) -> &str;
/// Returns the supported canonical procedure identifiers.
fn procedures(&self) -> &[String];
/// Builds the compact endpoint-wide discovery record for this leaf.
fn summary(&self) -> LeafIntrospectionSummary {
LeafIntrospectionSummary {
leaf_name: self.leaf_name().into(),
@@ -86,6 +107,7 @@ pub trait LeafMetadata {
}
}
/// Builds the full leaf-specific discovery payload.
fn introspection(&self) -> LeafIntrospection {
LeafIntrospection {
leaf_name: self.leaf_name().into(),
@@ -116,7 +138,10 @@ impl LeafMetadata for LeafNode {
/// Packet processor and local runtime contract for framed protocol traffic.
pub trait PacketProcessor {
/// Returns the endpoint path that owns this processor.
fn path(&self) -> &[String];
/// Receives one framed packet from the given ingress side.
fn receive(
&mut self,
ingress: &Ingress,
+2
View File
@@ -23,6 +23,7 @@ impl ProtocolEndpoint {
/// let endpoint = ProtocolEndpoint::new(Vec::new(), None, Vec::new(), Vec::new());
/// assert!(endpoint.path().is_empty());
/// ```
#[must_use]
pub fn new(
path: Vec<String>,
parent_path: Option<Vec<String>>,
@@ -54,6 +55,7 @@ impl ProtocolEndpoint {
}
/// Allocates a locally unique hook id.
#[must_use]
pub fn allocate_hook_id(&mut self) -> u64 {
self.hooks.allocate_hook_id(&self.path)
}
+23
View File
@@ -21,19 +21,24 @@ use super::super::{HookTable, RouteDecision};
/// Local connection state used for child route eligibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionState {
/// The child exists in the static topology but is not currently routable.
Unregistered,
/// The child may receive routed traffic.
Registered,
}
/// Child path plus current registration state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChildRoute {
/// Absolute child endpoint path.
pub path: Vec<String>,
/// Whether the child currently participates in routing.
pub state: ConnectionState,
}
impl ChildRoute {
/// Convenience constructor for the common registered-child case.
#[must_use]
pub fn registered(path: Vec<String>) -> Self {
Self {
path,
@@ -45,14 +50,18 @@ impl ChildRoute {
/// Test leaf behavior implemented by the endpoint runtime.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LeafBehavior {
/// Mirrors the incoming payload back over the declared response hook.
Echo,
}
/// Static leaf metadata used for procedure dispatch and introspection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LeafSpec {
/// Stable local leaf name.
pub name: String,
/// Procedures supported by the leaf.
pub procedures: Vec<String>,
/// Built-in behavior used by the lightweight test runtime.
pub behavior: LeafBehavior,
}
@@ -62,22 +71,28 @@ pub struct LeafSpec {
/// `PROTOCOL.md` routing and call sections.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ingress {
/// Received from the parent link.
Parent,
/// Received from the child at the given absolute path.
Child(Vec<String>),
/// Injected locally by code running on this endpoint.
Local,
}
/// Locally delivered protocol events.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LocalEvent {
/// A call reached this endpoint runtime.
Call {
header: PacketHeader,
message: CallMessage,
},
/// Hook data reached this endpoint runtime.
Data {
header: PacketHeader,
message: DataMessage,
},
/// A protocol fault reached this endpoint runtime.
Fault {
header: PacketHeader,
message: FaultMessage,
@@ -87,15 +102,20 @@ pub enum LocalEvent {
/// Result of processing one framed packet.
#[derive(Debug, Default)]
pub struct EndpointOutcome {
/// Forwarding actions to perform after local processing.
pub forwards: Vec<(RouteDecision, FrameBytes)>,
/// Events delivered to local runtime consumers.
pub events: Vec<LocalEvent>,
/// Whether the packet was intentionally dropped with no other side effects.
pub dropped: bool,
}
/// Errors returned while decoding or validating a packet.
#[derive(Debug)]
pub enum EndpointError {
/// The frame could not be decoded.
Frame(FrameError),
/// The decoded packet violated protocol invariants.
Validation(ValidationError),
}
@@ -124,7 +144,10 @@ impl From<ValidationError> for EndpointError {
/// Public packet-processing trait exposed by the tree runtime.
pub trait Endpoint {
/// Returns the absolute endpoint path.
fn path(&self) -> &[String];
/// Processes one incoming frame from the given ingress side.
fn receive(
&mut self,
ingress: &Ingress,
+3
View File
@@ -61,6 +61,9 @@ impl ProtocolEndpoint {
message: DataMessage,
) -> Result<EndpointOutcome, EndpointError> {
let hook_id = header.hook_id.expect("validated");
// The hook host can address its hook directly with `self.path + hook_id`.
// A non-host peer only knows the hook id it was given earlier, so it must
// recover the host-scoped key from active state using its validated path.
let key = self
.hooks
.active(&HookKey::new(self.path.clone(), hook_id))
+25 -4
View File
@@ -12,6 +12,8 @@ pub struct HookKey {
}
impl HookKey {
/// Creates a host-scoped key from the return path and hook identifier.
#[must_use]
pub fn new(return_path: Vec<String>, hook_id: u64) -> Self {
Self {
return_path,
@@ -64,12 +66,18 @@ impl Default for HookTable {
}
impl HookTable {
/// Allocates the next locally unique hook identifier.
///
/// Hook IDs are scoped by return path, so this counter only needs to be
/// unique within one endpoint runtime.
#[must_use]
pub fn allocate_hook_id(&mut self, _return_path: &[String]) -> u64 {
let id = self.next_id;
self.next_id = self.next_id.wrapping_add(1);
id
}
/// Inserts a pending hook created by an inbound call.
pub fn insert_pending(&mut self, pending: PendingHook) -> Result<(), HookConflict> {
let key = HookKey::new(pending.return_path.clone(), pending.hook_id);
if self.pending.contains_key(&key) || self.active.contains_key(&key) {
@@ -79,6 +87,7 @@ impl HookTable {
Ok(())
}
/// Inserts an already-active hook flow.
pub fn insert_active(&mut self, active: ActiveHook) -> Result<(), HookConflict> {
let key = HookKey::new(active.return_path.clone(), active.hook_id);
if self.pending.contains_key(&key) || self.active.contains_key(&key) {
@@ -88,6 +97,7 @@ impl HookTable {
Ok(())
}
/// Promotes a pending hook into the active table once its peer is known.
pub fn activate_pending(&mut self, key: &HookKey, peer_path: Vec<String>) -> Option<()> {
let pending = self.pending.remove(key)?;
self.active.insert(
@@ -104,22 +114,29 @@ impl HookTable {
Some(())
}
/// Removes a pending hook entry.
pub fn remove_pending(&mut self, key: &HookKey) -> Option<PendingHook> {
self.pending.remove(key)
}
/// Removes an active hook entry.
pub fn remove_active(&mut self, key: &HookKey) -> Option<ActiveHook> {
self.active.remove(key)
}
/// Returns a pending hook by its host-scoped key.
#[must_use]
pub fn pending(&self, key: &HookKey) -> Option<&PendingHook> {
self.pending.get(key)
}
/// Returns an active hook by its host-scoped key.
#[must_use]
pub fn active(&self, key: &HookKey) -> Option<&ActiveHook> {
self.active.get(key)
}
/// Returns mutable access to an active hook by its host-scoped key.
pub fn active_mut(&mut self, key: &HookKey) -> Option<&mut ActiveHook> {
self.active.get_mut(key)
}
@@ -130,23 +147,27 @@ impl HookTable {
/// cannot derive the full key from the packet header alone. The peer uses
/// its already-validated active state to recover the host-scoped key.
pub fn find_active_key_by_peer(&self, hook_id: u64, peer_path: &[String]) -> Option<HookKey> {
let mut matches = self
let mut matching_keys = self
.active
.iter()
.filter(|(_key, active)| active.hook_id == hook_id && active.peer_path == peer_path)
.map(|(key, _)| key.clone());
let first = matches.next()?;
if matches.next().is_some() {
let key = matching_keys.next()?;
if matching_keys.next().is_some() {
return None;
}
Some(first)
Some(key)
}
/// Returns the number of pending hooks.
#[must_use]
pub fn pending_len(&self) -> usize {
self.pending.len()
}
/// Returns the number of active hooks.
#[must_use]
pub fn active_len(&self) -> usize {
self.active.len()
}
+3
View File
@@ -32,6 +32,9 @@ impl fmt::Display for ValidationError {
impl core::error::Error for ValidationError {}
/// Validates packet header invariants from the protocol.
///
/// This checks only the header fields themselves. Payload-dependent rules belong
/// in helpers such as [`validate_call`].
pub fn validate_header(header: &PacketHeader) -> Result<(), ValidationError> {
match header.packet_type {
PacketType::Call => {