v2.rs
Overview
This file defines a generic handler struct ExtMessagesHandler designed to process external messages received via an HTTP interface. It implements the Handler trait for asynchronous request handling using the Salvo web framework. The handler is responsible for:
Authorizing incoming requests based on bearer tokens.
Resolving the appropriate block producer (BP) for the message thread.
Converting low-level TVM messages into higher-level domain message types.
Sending the processed messages for further asynchronous processing.
Returning appropriate JSON responses with success or detailed error information.
Reporting telemetry metrics related to message processing and delivery times.
The structure and behavior of this handler are highly parameterized by types representing messages, message converters, BP resolvers, and other utilities, making it adaptable for various message processing logic.
Structs and Implementations
ExtMessagesHandler<TMessage, TMsgConverter, TBPResolver, TBocByAddrGetter, TSeqnoGetter>
A generic struct representing the external messages handler.
Type parameters:
TMessage: The domain-specific message type after conversion.TMsgConverter: A function or closure type that converts a low-level TVM message and thread ID into aTMessage.TBPResolver: A function or closure type that resolves block producers given a thread ID.TBocByAddrGetter: A function or closure type that retrieves BOC data by address (not directly used in the shown code).TSeqnoGetter: A function or closure type that retrieves sequence numbers (not directly used in the shown code).
Fields:
Uses
PhantomDatafor each generic type to mark usage without storing actual values.
Methods:
new() -> Self
Constructs a new instance ofExtMessagesHandlerwith all phantom data fields initialized.
Usage example:
let handler = ExtMessagesHandler::<MyMessageType, MyMsgConverter, MyBPResolver, MyBocGetter, MySeqnoGetter>::new();
Trait Implementations
Handler Trait Implementation for ExtMessagesHandler
Implements the Handler trait asynchronously to process HTTP requests.
Constraints on type parameters:
TMessage: Must implementClone,Send,Sync,Debug, and'static.TMsgConverter: Must be aFn(tvm_block::Message, [u8; 34]) -> anyhow::Result<TMessage>+Clone,Send,Sync,'static.TBPResolver: Must be a mutableFnMut([u8; 34]) -> ResolvingResult+Clone,Send,Sync,'static.TBocByAddrGetter: Must be aFn(String) -> anyhow::Result<(String, Option<String>)>+Clone,Send,Sync,'static.TSeqnoGetter: Must be aFn() -> anyhow::Result<u32>+Clone,Send,Sync,'static.
handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, _ctrl: &mut FlowCtrl)
Asynchronously handles a single HTTP request representing an external message.
Parameters:
req: Mutable reference to the incoming HTTP request.depot: Mutable reference to theDepotused for dependency injection and request-scoped state.res: Mutable reference to the HTTP response to be sent back._ctrl: Mutable reference to flow control (unused here).
Workflow:
Acquire
WebServerinstance fromdepot:
If theWebServerstate is missing, immediately respond with an internal server error.Retrieve
ExternalMessage:
Extracts the external message payload from the depot.Authorization check:
Determines if authorization is required using
is_auth_required().Checks if authorized by bearer token (
AUTHORIZED_BY_BK_KEY).If authorization is required and not authorized, validates the token from the message asynchronously.
Responds with detailed error responses on token verification failures (
BAD_TOKEN,INVALID_SIGNATURE,TOKEN_EXPIRED).
Block Producer resolution:
Resolves the active block producer(s) for the message's thread ID using the
bp_resolver.If the current node is not the active BP, responds with an error advising to resend the message to the active BP.
Message conversion:
Converts the low-level TVM message into the domain message type
TMessageusing theinto_external_messagecallback.On failure, responds with an internal server error indicating message rejection.
Telemetry metrics reporting:
Extracts the message sent time from headers.
Reports delivery duration to metrics if available.
Message queueing:
Sends the converted message via the
incoming_message_senderchannel for asynchronous processing.Awaits feedback about the processing outcome.
Response generation:
On successful feedback, constructs an
ExtMsgResponsewith the message result and active producers, responds with HTTP 200 OK.On error or unknown status, responds with internal server error.
Telemetry reporting:
Reports message processing duration and status code to metrics.
Return:
Does not return a value; directly writes to the
Responseobject.
Error Handling:
Returns structured JSON errors via
render_error_responseorrender_erroron various failure modes, including authorization, message conversion, and queuing errors.
Important Implementation Details
Message Authorization:
Uses external crateext_messages_authto validate tokens asynchronously. Authorization is conditional based on a global requirement flag.Block Producer Resolution:
Uses a closure (bp_resolver) to determine if the current node is the active block producer for the message's thread ID. This prevents processing messages not intended for this node.Message Conversion:
Converts raw TVM messages into strongly typed domain messages using a user-provided converter (into_external_message), allowing flexible message formats.Feedback Handling:
Uses Tokio's oneshot channel to receive asynchronous feedback about message processing, enabling request-response communication despite asynchronous processing.Metrics Collection:
Reports delivery duration and processing times via an optional telemetry metrics interface, supporting system monitoring.Error Responses:
Uses helper functions to render structured JSON error responses with codes and optional detailed data.
Interactions with Other Components
WebServer:
The handler obtains aWebServerinstance from the request-scoped depot. TheWebServerprovides:The
bp_resolverclosure.The
incoming_message_senderchannel for message queuing.Token issuing capabilities.
Metrics reporting.
ExternalMessage:
Represents the input message payload extracted from the request depot.Authorization Utilities (
ext_messages_auth):
Provides token verification utilities and authorization requirement flags.Telemetry Utilities (
telemetry_utils):
Used to compute elapsed time for message delivery metrics.Error Rendering Utilities (
render_error,render_error_response):
Provides JSON error response formatting.
Visual Diagram
classDiagram
class ExtMessagesHandler {
+new()
+handle()
}
class WebServer {
+bp_resolver: FnMut
+incoming_message_sender: Sender
+issue_token()
+metrics
+into_external_message: Fn
}
class ExternalMessage {
}
ExtMessagesHandler --> WebServer : obtains from depot
ExtMessagesHandler --> ExternalMessage : reads from depot
ExtMessagesHandler --> "Authorization Module" : validates tokens
ExtMessagesHandler --> "Telemetry Utilities" : reports metrics
ExtMessagesHandler --> "Error Rendering" : renders error responses
This class diagram illustrates the primary relationships where ExtMessagesHandler interacts with the WebServer and related modules to process and respond to external messages.