bk_set_summary.rs
Overview
This file implements data structures and an HTTP handler for managing and serving summaries of "Bk" sets, which appear to represent collections of nodes identified by an owner address, public key, and epoch sequence number. The primary functionality includes creating summaries of current and future Bk sets, serializing them for JSON responses, maintaining an up-to-date snapshot of the summary, and providing an HTTP endpoint handler that responds with the Bk set summary in JSON format, with support for conditional requests based on modification time.
Data Structures and Types
BkSetSummary
A serializable struct representing a snapshot of a Bk set summary at a specific sequence number.
Fields:
seq_no: u64— Sequence number representing the version or state of the Bk set.current: Vec<(String, [u8; 32], u64)>— List of current Bk nodes. Each tuple contains:String— Node identifier as a hex-encoded string of the owner's address bytes.[u8; 32]— Owner's public key bytes.u64— Epoch finish sequence number.
future: Vec<(String, [u8; 32], u64)>— List of future Bk nodes, with the same tuple structure ascurrent.
Methods:
new(bk_set: &ApiBkSet) -> Self
Constructs aBkSetSummaryfrom anApiBkSetby extracting the sequence number and transforming both current and future Bk lists into the required tuple format.
Usage Example:
let summary = BkSetSummary::new(&api_bk_set);Serialization Detail:
Uses a custom serializerbk_vec_serdeto convert the public key bytes to hex strings when serializing to JSON.
bk_vec_serde Module
Provides a custom serialization function for Vec<(String, [u8; 32], u64)> to ensure the public key bytes are hex-encoded strings in JSON output.
Function:
serialize<S>(vec: &Vec<(String, [u8; 32], u64)>, serializer: S) -> Result<S::Ok, S::Error>
Serializes each tuple by encoding the[u8; 32]public key as a hex string.
BkSetSummarySnapshot
A runtime snapshot holding the latest Bk set summary data and its update time.
Fields:
update_time: SystemTime— Timestamp of the last update.seq_no: u64— Sequence number of the snapshot.nodes: Vec<(String, [u8; 32], u64)>— Current Bk nodes.future_nodes: Vec<(String, [u8; 32], u64)>— Future Bk nodes.
Trait Implementations:
Default— Initializes with default values (epoch start time, zero sequence number, empty node lists).
Methods:
new() -> Self
Creates a new snapshot with default empty values.replace(&mut self, bk_update: BkSetSummary)
Replaces the current snapshot data with data from aBkSetSummaryand updates the timestamp to the current system time.
Usage Example:
let mut snapshot = BkSetSummarySnapshot::new(); snapshot.replace(new_summary);
BkSetSummaryResponse
A JSON-serializable response structure wrapping either a successful summary result or an error.
Fields:
result: Option<BkSetSummaryResult>— Contains the summary data if the request was successful.error: Option<BkSetSummaryError>— Contains error information if the request failed.
BkSummary
Represents a single node summary in the Bk set.
Fields:
node_id: String— Node identifier (owner address as hex string).node_owner_pk: String— Owner public key as a hex string.epoch_start_seq_no: u64— Epoch sequence number indicating when the node started.
Traits:
Serialize,Deserialize,Clone,Debug,Default— Supports JSON serialization and deserialization.
BkSetSummaryResult
Holds the full summary data for current and future Bk sets.
Fields:
bk_set: Vec<BkSummary>— Current Bk set nodes.future_bk_set: Vec<BkSummary>— Future Bk set nodes.seq_no: u64— Sequence number of the summary.
Trait Implementations:
From<&BkSetSummarySnapshot>— Converts from aBkSetSummarySnapshotby mapping its internal node tuples intoBkSummarystructs with hex-encoded public keys.
Usage Example:
let result: BkSetSummaryResult = (&snapshot).into();
BkSetSummaryError
Represents an error response for the Bk set summary endpoint.
Fields:
code: String— Error code identifier.message: String— Error message describing the problem.
HTTP Handler: BkSetSummaryHandler
A generic HTTP handler implemented with the salvo framework to serve Bk set summary data.
Generic Parameters:
TMessage— Message type representing TVM messages.TMsgConverter— Function type to convert raw messages toTMessage.TBPResolver— Function type to resolve blockchain parameters.TBocByAddrGetter— Function type to get BOC (bag of cells) data by address.TSeqnoGetter— Function type to get sequence numbers.
Struct Fields:
UsesPhantomDatafor all generic parameters—no runtime data is stored.Constructor:
new() -> Self
Creates a new instance withPhantomDataplaceholders.
Trait Implementation:
ImplementsHandlertrait fromsalvowith asynchandlemethod.handleMethod Behavior:Attempts to obtain a
WebServerinstance (which holds the sharedBkSetSummarySnapshot) from the request'sDepot.Parses the optional HTTP header
If-Modified-Sinceto support conditional GET requests.Reads the current
BkSetSummarySnapshotfrom the shared state.If the snapshot's
update_timeis not newer than theIf-Modified-Sinceheader, responds with304 Not Modified.Otherwise, converts the snapshot to a
BkSetSummaryResult.Sets HTTP status to
200 OK, addsLast-Modifiedheader with the snapshot's update time.Responds with the JSON representation of the summary result.
If errors occur at any stage (e.g., missing web server state), responds with appropriate error status and JSON error response.
Usage Example:
When registered as a route handler, it serves the current Bk set summary with HTTP semantics for caching.
Helper Function: render_error_response
Generates a JSON error response with an error code and optional message.
Parameters:
res: &mut Response— The HTTP response object to write to.code: &str— Error code string.message: Option<&str>— Optional error message; defaults to the error code ifNone.
Behavior:
RendersBkSetSummaryResponsewithresultasNoneanderrorfilled, serialized as JSON.
Interactions and Dependencies
Uses types and state from
crate::{ApiBk, ApiBkSet, ResolvingResult, WebServer}indicating integration with the WebServer's state management and API data abstractions.Depends on
salvocrate for HTTP server abstractions and request/response lifecycle (Handler,Request,Response,Depot,FlowCtrl).Uses
serdefor JSON serialization/deserialization with custom hex encoding logic for binary public key data.Uses
httpdatefor parsing and formatting HTTP date headers to support conditional requests.The handler relies on shared mutable state (
WebServer.bk_set_summary) protected by read-write locks (RwLock) to safely read the current Bk set summary snapshot.The Bk set summary data is constructed from domain-specific types
ApiBkSetandApiBk.
Implementation Details and Algorithms
Bk Set Summary Construction:
Uses iterator mapping to transform internal Bk sets (ApiBkSet) into tuples of(node_id, owner_pubkey, epoch_finish_seq_no). The node ID is hex-encoded from raw bytes, and the epoch finish sequence number falls back to zero if absent.Serialization:
Implements custom serialization viabk_vec_serdeto convert the public key bytes into hex strings for JSON output, ensuring readability and interoperability.Snapshot Management:
TheBkSetSummarySnapshotstruct maintains an in-memory state of the current and future Bk sets, with an associated update time to enable efficient HTTP caching.HTTP Conditional Responses:
The handler supports the HTTPIf-Modified-Sinceheader; if the data has not changed since the provided date, it returns304 Not Modifiedto save bandwidth.Error Handling:
Uses a dedicated error response structure and HTTP status codes (500 Internal Server Error,400 Bad Request) when the web server state is unavailable or client headers are malformed.
Visual Diagram: Structure of bk_set_summary.rs
classDiagram
class BkSetSummary {
+seq_no: u64
+current: Vec<(String, [u8;32], u64)>
+future: Vec<(String, [u8;32], u64)>
+new(bk_set: &ApiBkSet) BkSetSummary
}
class BkSetSummarySnapshot {
-update_time: SystemTime
-seq_no: u64
-nodes: Vec<(String, [u8;32], u64)>
-future_nodes: Vec<(String, [u8;32], u64)>
+new() BkSetSummarySnapshot
+replace(bk_update: BkSetSummary)
}
class BkSummary {
+node_id: String
+node_owner_pk: String
+epoch_start_seq_no: u64
}
class BkSetSummaryResult {
+bk_set: Vec<BkSummary>
+future_bk_set: Vec<BkSummary>
+seq_no: u64
+from(&BkSetSummarySnapshot) BkSetSummaryResult
}
class BkSetSummaryError {
+code: String
+message: String
}
class BkSetSummaryResponse {
+result: Option<BkSetSummaryResult>
+error: Option<BkSetSummaryError>
}
class BkSetSummaryHandler {
+new() BkSetSummaryHandler
+handle()
}
BkSetSummarySnapshot --> BkSetSummary : "updated from"
BkSetSummaryResult --> BkSetSummarySnapshot : "constructed from"
BkSetSummaryResponse --> BkSetSummaryResult : "contains"
BkSetSummaryResponse --> BkSetSummaryError : "contains"
BkSetSummaryHandler ..> BkSetSummaryResponse : "renders"
Notes on Usage within the System
The
BkSetSummaryHandleris intended to be registered as a route handler in the WebServer and serves JSON summaries of the current and future Bk sets.The shared
BkSetSummarySnapshotis typically managed and updated elsewhere in the system, likely in response to blockchain or network events.Consumers of this API can use the
Last-Modifiedheader andIf-Modified-Sincemechanism to optimize data refreshing.The module assumes a certain data model (
ApiBk,ApiBkSet) is maintained and synchronized by other parts of the system, which provide the authoritative Bk set data.Hex encoding of binary data ensures compatibility with JSON and standard web clients.
For deeper understanding of the WebServer state management and ApiBkSet structure, refer to WebServer and ApiBkSet topics.