transfer.rs
Overview
The transfer.rs file provides core functionality for serializing and sending network messages over a connection, as well as handling and representing errors that may arise during the transport process. It defines a custom error enumeration TransportError encapsulating various transport-related failures, and it exposes an asynchronous function transfer that transmits serialized messages over a network connection while optionally reporting transmission metrics.
Entities and Functions
TransportError Enum
TransportError is an error type representing various failure modes that can occur during network transport operations. It leverages the thiserror::Error derive macro to provide human-readable error messages and integrates with underlying errors from the wtransport crate.
Variants
Connection(ConnectionError): Wraps errors related to the network connection.StreamOpening(StreamOpeningError): Represents errors occurring when opening a stream.StreamWrite(StreamWriteError): Covers errors from writing to a stream.Send(String): General send errors represented as strings.BincodeSerialization(String): Serialization errors encoded as strings, typically frombincode.
Methods
kind_str(&self) -> &'static strReturns a static string slice describing the kind of error. This can be used for error categorization or logging. The method matches on the variant and, where applicable, on the inner error type to provide a concise kind identifier.
Usage Example:
match error.kind_str() { "connection_closed" => { /* handle closed connection */ } "bincode" => { /* handle serialization error */ } _ => { /* other cases */ } }
transfer Function
pub async fn transfer(
connection: &impl NetConnection,
net_message: &NetMessage,
metrics: &Option<NetMetrics>,
) -> Result<usize, TransportError>
Purpose
Serializes a given network message and asynchronously sends it over the provided network connection. It optionally records metrics about the serialization and sending process.
Parameters
connection: &impl NetConnection
A reference to an object implementing theNetConnectiontrait. This connection is used to send the serialized data.net_message: &NetMessage
The message to serialize and send.NetMessageis a domain-specific message type representing data to be transmitted.metrics: &Option<NetMetrics>
An optional reference to aNetMetricsinstance. If present, metrics related to serialization time are recorded after the message is serialized and sent.
Return Value
Returns a Result<usize, TransportError>:
Ok(usize): The number of bytes successfully sent.Err(TransportError): An error occurred during serialization or sending.
Implementation Details
Serialization: Uses
bincode::serializeto convert thenet_messageinto a byte vector. Serialization errors are wrapped inTransportError::BincodeSerialization.Timing: Captures the current time immediately before sending to measure the duration of the serialization process for metrics.
Sending: Sends serialized data asynchronously via the
sendmethod of theNetConnection. Errors during sending are logged with a detailed error message and converted into theTransportError::Sendvariant.Metrics Reporting: If a metrics collector is provided, it reports the elapsed time since serialization started.
Usage Example
let bytes_sent = transfer(&connection, &message, &Some(metrics)).await?;
println!("Sent {} bytes", bytes_sent);
Implementation and Algorithm Details
Error Handling: The file centrally manages error conversions between different lower-level error types (
ConnectionError,StreamOpeningError,StreamWriteError) and a unifiedTransportErrorenum. This enables consistent error handling and simplification of upstream error processing.Serialization with
bincode: Efficient binary serialization is used to encode messages before transmission. Errors from this process are explicitly handled and converted.Asynchronous Sending: The
transferfunction is async and returns aFuture. It uses.awaitto asynchronously send data over the network connection, allowing non-blocking IO.Instrumentation: The function records serialization and sending latency via a
NetMetricsinstance, if available, enabling performance monitoring.Error Logging: When sending fails, the error is logged with detailed context using the
tracingcrate, facilitating debugging.
Interactions with Other Components
NetConnectionTrait: Thetransferfunction requires an implementation of theNetConnectiontrait from thetransport_layercrate, which abstracts network connection functionality.NetMessage: The message type being sent, defined elsewhere in the project, represents the data payload.NetMetrics: Optional metrics collector used for performance tracking, defined in themetricsmodule.wtransportcrate: Provides foundational types for errors related to connection and stream management (ConnectionError,StreamOpeningError,StreamWriteError).bincodecrate: Used for message serialization.tracingcrate: Used for error logging and diagnostics.
Mermaid Class Diagram
classDiagram
class TransportError {
<<enum>>
+Connection(ConnectionError)
+StreamOpening(StreamOpeningError)
+StreamWrite(StreamWriteError)
+Send(String)
+BincodeSerialization(String)
+kind_str() string
}
class transfer {
<<async fn>>
+transfer(connection: NetConnection, net_message: NetMessage, metrics: Option<NetMetrics>) Result<usize, TransportError>
}
TransportError <|-- ConnectionError
TransportError <|-- StreamOpeningError
TransportError <|-- StreamWriteError
transfer ..> TransportError : returns
transfer ..> NetConnection : uses
transfer ..> NetMessage : uses
transfer ..> NetMetrics : optionally uses
This diagram shows the TransportError enum with its variants and method, the transfer asynchronous function, and their relationships with other types used in this file.