boc_by_address.rs
Overview
This file defines the BocByAddressHandler struct and its implementation as an HTTP request handler within an asynchronous web server framework. The handler processes incoming HTTP requests that query for a Bag of Cells (BOC) data structure associated with a specified blockchain address. It extracts the address parameter from the query string, invokes a backend resolver function to obtain the BOC and optional dapp identifier, and responds with a JSON payload or an error message. The handler also records metrics related to response time and HTTP status.
The file leverages generic type parameters to enable flexible integration with different message types, conversion functions, blockchain state resolvers, BOC retrieval functions, and sequence number getters. It is designed for use within the asynchronous web framework salvo and interacts closely with a shared WebServer state object.
Structs
BocByAddressHandler
pub struct BocByAddressHandler<
TMesssage,
TMsgConverter,
TBPResolver,
TBocByAddrGetter,
TSeqnoGetter,
>(PhantomData<TMesssage>, PhantomData<TMsgConverter>, PhantomData<TBPResolver>, PhantomData<TBocByAddrGetter>, PhantomData<TSeqnoGetter>);
Purpose:
Acts as a generic HTTP request handler that retrieves blockchain BOC data by address.Type Parameters:
TMessage: The type representing blockchain messages after conversion.TMsgConverter: A function type that converts raw blockchain messages intoTMessage.TBPResolver: A function type used for resolving blockchain proof or state from an address.TBocByAddrGetter: A function type that retrieves the BOC (and optionally a dapp ID) for a given address string.TSeqnoGetter: A function type to obtain the sequence number from the blockchain state.
Fields:
UsesPhantomDatafor each generic parameter to mark type usage without storing actual data.Constructor:
pub fn new() -> SelfCreates a new instance with all
PhantomDatamarkers initialized.
Trait Implementations
Handler trait for BocByAddressHandler
#[async_trait]
impl<TMessage, TMsgConverter, TBPResolver, TBocByAddrGetter, TSeqnoGetter> Handler
for BocByAddressHandler<TMessage, TMsgConverter, TBPResolver, TBocByAddrGetter, TSeqnoGetter>
where
TMessage: Clone + Send + Sync + 'static + std::fmt::Debug,
TMsgConverter: Clone + Send + Sync + 'static + Fn(tvm_block::Message, [u8; 34]) -> anyhow::Result<TMessage>,
TBPResolver: Clone + Send + Sync + 'static + FnMut([u8; 34]) -> ResolvingResult,
TBocByAddrGetter: Clone + Send + Sync + 'static + Fn(String) -> anyhow::Result<(String, Option<String>)>,
TSeqnoGetter: Clone + Send + Sync + 'static + Fn() -> anyhow::Result<u32>,
{
async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, _ctrl: &mut FlowCtrl);
}
Purpose:
Implements asynchronous HTTP request handling logic forBocByAddressHandler.Method:
handleParameters:
req: Mutable reference to the incoming HTTP request.depot: Mutable reference to the shared state container holding application-wide data.res: Mutable reference to the HTTP response builder._ctrl: Mutable reference to flow control (unused in this implementation).
Behavior:
Extracts the
"address"query parameter from the request URL.Strips the
"0:"prefix from the address if present.Responds with HTTP 400 if the address is missing or empty.
Obtains a shared
WebServerinstance from thedepot. Returns HTTP 500 if unavailable.Calls the
get_boc_by_addrfunction from theWebServerto retrieve the BOC and optional dapp ID associated with the address.Responds with HTTP 200 and a JSON object containing the BOC and optionally the dapp ID if retrieval succeeds.
Responds with HTTP 404 and an error message if the BOC is not found.
Records the duration of the request handling and HTTP status code with the metrics reporter associated with the
WebServer.
Return Value:
None (the response is written directly tores).Usage Example:
// Assuming appropriate type parameters and WebServer setup let handler = BocByAddressHandler::<MyMessage, MyMsgConverter, MyBPResolver, MyBocGetter, MySeqnoGetter>::new(); // Integrated with Salvo server routing router.get(handler);
Important Implementation Details
Generics and PhantomData:
The use ofPhantomDataindicates that the struct does not own any actual data but depends on type parameters for generic behavior. This design pattern ensures type safety and flexibility without runtime overhead.Address Normalization:
The handler removes the"0:"prefix from addresses, a common notation in blockchain address representation, to normalize the input before lookup.Error Handling:
The handler explicitly checks for missing parameters and backend state availability, returning appropriate HTTP status codes (400 Bad Request,500 Internal Server Error,404 Not Found).Metrics Reporting:
After processing, the handler reports the elapsed time and HTTP response code to a metrics subsystem, allowing for performance monitoring.Concurrency:
The handler usesasync_traitto support asynchronous execution consistent with the web server's non-blocking request handling.
Interactions with Other System Components
WebServer State:
The handler retrieves aWebServerinstance from the sharedDepot. TheWebServercontains:get_boc_by_addr: A function or closure responsible for fetching BOC data by address.metrics: An optional metrics collector for reporting request statistics.
ResolvingResult:
Used as a return type for the blockchain proof resolver function (TBPResolver), indicating that this file interacts with blockchain state resolution logic.HTTP Framework (
salvo):
Implements theHandlertrait from thesalvocrate, integrating within the HTTP request lifecycle.Serialization (
serde_json):
Produces JSON responses usingserde_json::json!macro for structured output.
Visual Diagram
classDiagram
class BocByAddressHandler {
+new()
+handle()
}
BocByAddressHandler ..> TMessage : generic
BocByAddressHandler ..> TMsgConverter : generic
BocByAddressHandler ..> TBPResolver : generic
BocByAddressHandler ..> TBocByAddrGetter : generic
BocByAddressHandler ..> TSeqnoGetter : generic
class WebServer {
+get_boc_by_addr()
+metrics
}
BocByAddressHandler --> WebServer : obtains from Depot
WebServer --> "1" TBocByAddrGetter : uses
WebServer --> "1" Metrics : reports to