helpers.rs
Overview
The helpers.rs file provides utility functions for handling and processing TON Virtual Machine (TVM) messages within an HTTP server context. Its primary responsibilities include decoding and parsing base64-encoded TVM messages into structured Message objects and extracting specific timestamp metadata from HTTP headers. This file relies on types and functions from the tvm_block and tvm_types crates to deserialize and interpret the binary message data.
Functions
parse_message
pub fn parse_message(id: &str, message_b64: &str) -> Result<Message, String>
Purpose:
Decodes a base64-encoded string representing a TVM message, deserializes it into a TVMMessageobject, and handles any errors encountered during this process.Parameters:
id: &str
An identifier for the message, used primarily for logging/tracing purposes.message_b64: &str
The base64-encoded string containing the serialized TVM message.
Returns:
Ok(Message)upon successful decoding and deserialization.Err(String)containing a descriptive error message if decoding or deserialization fails.
Implementation Details:
The function first logs a trace event with the message
idto the target"http_server".It decodes the base64-encoded message string into raw bytes using
base64_decode.It reads the bytes as a single root Bag of Cells (BOC) structure using
tvm_types::boc::read_single_root_boc.Constructs a
Messageobject from the deserialized cell usingMessage::construct_from_cell.Each step is wrapped with error handling that maps errors into human-readable strings and logs deserialization errors.
Usage Example:
let msg_id = "msg123";
let encoded_msg = "te6ccgEBAQEA..."; // base64 string
match parse_message(msg_id, encoded_msg) {
Ok(message) => println!("Parsed message: {:?}", message),
Err(e) => eprintln!("Failed to parse message: {}", e),
}
extract_ext_msg_sent_time
pub fn extract_ext_msg_sent_time(headers: &salvo::http::HeaderMap) -> Option<u64>
Purpose:
Extracts the message sent timestamp from HTTP headers, specifically from the"X-EXT-MSG-SENT"header.Parameters:
headers: &salvo::http::HeaderMap
A reference to the HTTP headers map, typically from an incoming HTTP request.
Returns:
Some(u64)containing the parsed timestamp (in UNIX epoch seconds) if the header exists and is correctly formatted.Noneif the header is absent, cannot be converted to a string, or fails to parse as au64.
Implementation Details:
Attempts to retrieve the
"X-EXT-MSG-SENT"header value.Converts the header value to a UTF-8 string.
Parses the string into a 64-bit unsigned integer representing the timestamp.
Returns
Noneif any step fails.
Usage Example:
use salvo::http::HeaderMap;
let mut headers = HeaderMap::new();
headers.insert("X-EXT-MSG-SENT", "1680000000".parse().unwrap());
if let Some(sent_time) = extract_ext_msg_sent_time(&headers) {
println!("Message sent time: {}", sent_time);
} else {
println!("No sent time header found or invalid format");
}
Implementation Details and Algorithms
The
parse_messagefunction leverages TVM-specific deserialization mechanics:Uses
base64_decodeto convert the encoded string to raw binary.Reads a single root BOC, a data structure used in TON to represent serialized cells.
Uses
Message::construct_from_cellto transform the BOC cell into a high-levelMessageobject.
Error handling is comprehensive, converting errors from decoding and deserialization steps into descriptive strings and logging relevant error information to the
"http_server"tracing target.The
extract_ext_msg_sent_timefunction provides a streamlined way to safely extract and parse an HTTP header field, returning an optional timestamp value without panicking or crashing on malformed input.
Interactions with Other Parts of the System
Dependencies:
tvm_block::Messageandtvm_block::Deserializable: Core abstractions for TVM message deserialization.tvm_types::base64_decode: Utility for decoding base64 strings.tvm_types::boc::read_single_root_boc: Reads serialized cell data structures.salvo::http::HeaderMap: HTTP header representation from the web framework, used for extracting metadata.
This file is designed to be used in HTTP request handling contexts where incoming requests contain base64-encoded TVM messages and associated metadata in headers. It aids in converting raw HTTP payloads into strongly-typed message objects for further processing.
Logging and error reporting via the
tracingcrate target"http_server"integrate with the server's monitoring infrastructure.
Diagram: Function Workflow in helpers.rs
flowchart TD
A["parse_message(id, message_b64)"]
A --> B[Decode base64 string]
B --> C[Read single root BOC]
C --> D[Construct Message from cell]
D -->|Success| E[Return Message]
B -->|Failure| F[Return decode error]
C -->|Failure| G[Return deserialization error]
D -->|Failure| H[Return parsing error]
I["extract_ext_msg_sent_time(headers)"]
I --> J[Get "X-EXT-MSG-SENT" header]
J --> K[Convert header to string]
K --> L[Parse string to u64]
L -->|Success| M["Return Some(timestamp)"]
J -->|Missing| N[Return None]
K -->|Error| N
L -->|Error| N
This flowchart illustrates the stepwise processing and error handling paths of the two main functions in this file.