miden_node_store/server/
mod.rs

1use std::{net::ToSocketAddrs, sync::Arc};
2
3use miden_node_proto::generated::store::api_server;
4use miden_node_utils::errors::ApiError;
5use tokio::net::TcpListener;
6use tokio_stream::wrappers::TcpListenerStream;
7use tracing::info;
8
9use crate::{blocks::BlockStore, config::StoreConfig, db::Db, state::State, COMPONENT};
10
11mod api;
12
13/// Represents an initialized store component where the RPC connection is open, but not yet actively
14/// responding to requests.
15///
16/// Separating the connection binding from the server spawning allows the caller to connect other
17/// components to the store without resorting to sleeps or other mechanisms to spawn dependent
18/// components.
19pub struct Store {
20    api_service: api_server::ApiServer<api::StoreApi>,
21    listener: TcpListener,
22}
23
24impl Store {
25    /// Loads the required database data and initializes the TCP listener without
26    /// serving the API yet. Incoming requests will be queued until [`serve`](Self::serve) is
27    /// called.
28    pub async fn init(config: StoreConfig) -> Result<Self, ApiError> {
29        info!(target: COMPONENT, %config, "Loading database");
30
31        let block_store = Arc::new(BlockStore::new(config.blockstore_dir.clone()).await?);
32
33        let db = Db::setup(config.clone(), Arc::clone(&block_store))
34            .await
35            .map_err(|err| ApiError::ApiInitialisationFailed(err.to_string()))?;
36
37        let state = Arc::new(
38            State::load(db, block_store)
39                .await
40                .map_err(|err| ApiError::DatabaseConnectionFailed(err.to_string()))?,
41        );
42
43        let api_service = api_server::ApiServer::new(api::StoreApi { state });
44
45        let addr = config
46            .endpoint
47            .to_socket_addrs()
48            .map_err(ApiError::EndpointToSocketFailed)?
49            .next()
50            .ok_or_else(|| ApiError::AddressResolutionFailed(config.endpoint.to_string()))?;
51
52        let listener = TcpListener::bind(addr).await?;
53
54        info!(target: COMPONENT, "Database loaded");
55
56        Ok(Self { api_service, listener })
57    }
58
59    /// Serves the store's RPC API.
60    ///
61    /// Note: this blocks until the server dies.
62    pub async fn serve(self) -> Result<(), ApiError> {
63        tonic::transport::Server::builder()
64            .add_service(self.api_service)
65            .serve_with_incoming(TcpListenerStream::new(self.listener))
66            .await
67            .map_err(ApiError::ApiServeFailed)
68    }
69}