hotshot_query_service/
lib.rs

1// Copyright (c) 2022 Espresso Systems (espressosys.com)
2// This file is part of the HotShot Query Service library.
3//
4// This program is free software: you can redistribute it and/or modify it under the terms of the GNU
5// General Public License as published by the Free Software Foundation, either version 3 of the
6// License, or (at your option) any later version.
7// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
8// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9// General Public License for more details.
10// You should have received a copy of the GNU General Public License along with this program. If not,
11// see <https://www.gnu.org/licenses/>.
12
13//! The HotShot Query Service is a minimal, generic query service that can be integrated into any
14//! decentralized application running on the [hotshot] consensus layer. It provides all the features
15//! that HotShot itself expects of a query service (such as providing consensus-related data for
16//! catchup and synchronization) as well as some application-level features that deal only with
17//! consensus-related or application-agnostic data. In addition, the query service is provided as an
18//! extensible library, which makes it easy to add additional, application-specific features.
19//!
20//! # Basic usage
21//!
22//! ```
23//! # use hotshot::types::SystemContextHandle;
24//! # use hotshot_query_service::testing::mocks::{
25//! #   MockNodeImpl as AppNodeImpl, MockTypes as AppTypes, MockVersions as AppVersions,
26//! # };
27//! # use hotshot_example_types::node_types::TestVersions;
28//! # use hotshot_types::consensus::ConsensusMetricsValue;
29//! # use std::path::Path;
30//! # async fn doc(storage_path: &std::path::Path) -> anyhow::Result<()> {
31//! use hotshot_query_service::{
32//!     availability,
33//!     data_source::{FileSystemDataSource, Transaction, UpdateDataSource, VersionedDataSource},
34//!     fetching::provider::NoFetching,
35//!     node,
36//!     status::UpdateStatusData,
37//!     status,
38//!     testing::mocks::MockBase,
39//!     ApiState, Error,
40//! };
41//!
42//! use futures::StreamExt;
43//! use vbs::version::StaticVersionType;
44//! use hotshot::SystemContext;
45//! use std::sync::Arc;
46//! use tide_disco::App;
47//! use tokio::spawn;
48//!
49//! // Create or open a data source.
50//! let data_source = FileSystemDataSource::<AppTypes, NoFetching>::create(storage_path, NoFetching)
51//!     .await?;
52//!
53//! // Create hotshot, giving it a handle to the status metrics.
54//! let hotshot = SystemContext::<AppTypes, AppNodeImpl, AppVersions>::init(
55//! #   panic!(), panic!(), panic!(), panic!(), panic!(), panic!(), panic!(),
56//!     ConsensusMetricsValue::new(&*data_source.populate_metrics()), panic!(),
57//!     panic!()
58//!     // Other fields omitted
59//! ).await?.0;
60//!
61//! // Create API modules.
62//! let availability_api = availability::define_api(&Default::default(),  MockBase::instance())?;
63//! let node_api = node::define_api(&Default::default(),  MockBase::instance())?;
64//! let status_api = status::define_api(&Default::default(),  MockBase::instance())?;
65//!
66//! // Create app.
67//! let data_source = ApiState::from(data_source);
68//! let mut app = App::<_, Error>::with_state(data_source.clone());
69//! app
70//!     .register_module("availability", availability_api)?
71//!     .register_module("node", node_api)?
72//!     .register_module("status", status_api)?;
73//!
74//! // Serve app.
75//! spawn(app.serve("0.0.0.0:8080", MockBase::instance()));
76//!
77//! // Update query data using HotShot events.
78//! let mut events = hotshot.event_stream();
79//! while let Some(event) = events.next().await {
80//!     // Update the query data based on this event.
81//!     data_source.update(&event).await.ok();
82//! }
83//! # Ok(())
84//! # }
85//! ```
86//!
87//! Shortcut for starting an out-of-the-box service with no extensions (does exactly the above and
88//! nothing more):
89//!
90//! ```
91//! # use hotshot::types::SystemContextHandle;
92//! # use vbs::version::StaticVersionType;
93//! # use hotshot_query_service::{data_source::FileSystemDataSource, Error, Options};
94//! # use hotshot_query_service::fetching::provider::NoFetching;
95//! # use hotshot_query_service::testing::mocks::{MockBase, MockNodeImpl, MockTypes, MockVersions};
96//! # use std::path::Path;
97//! # use tokio::spawn;
98//! # async fn doc(storage_path: &Path, options: Options, hotshot: SystemContextHandle<MockTypes, MockNodeImpl, MockVersions>) -> Result<(), Error> {
99//! use hotshot_query_service::run_standalone_service;
100//!
101//! let data_source = FileSystemDataSource::create(storage_path, NoFetching).await.map_err(Error::internal)?;
102//! spawn(run_standalone_service(options, data_source, hotshot,  MockBase::instance()));
103//! # Ok(())
104//! # }
105//! ```
106//!
107//! # Persistence
108//!
109//! Naturally, an archival query service such as this is heavily dependent on a persistent storage
110//! implementation. The APIs provided by this query service are generic over the specific type of
111//! the persistence layer, which we call a _data source_. This crate provides several data source
112//! implementations in the [`data_source`] module.
113//!
114//! # Interaction with other components
115//!
116//! While the HotShot Query Service [can be used as a standalone service](run_standalone_service),
117//! it is designed to be used as a single component of a larger service consisting of several other
118//! interacting components. This interaction has two dimensions:
119//! * _extension_, adding new functionality to the API modules provided by this crate
120//! * _composition_, combining the API modules from this crate with other, application-specific API
121//!   modules to create a single [tide_disco] API
122//!
123//! ## Extension
124//!
125//! It is possible to add new functionality directly to the modules provided by this create. This
126//! allows you to keep semantically related functionality grouped together in a single API module,
127//! for interface purposes, even while some of the functionality of that module is provided by this
128//! crate and some of it is an application-specific extension.
129//!
130//! For example, consider an application which is a UTXO-based blockchain. Each transaction consists
131//! of a handful of new _output records_, and you want your query service to provide an API for
132//! looking up a specific output by its index. Semantically, this functionality belongs in the
133//! _data availability_ API, however it is application-specific -- HotShot itself makes no
134//! assumptions and provides no guarantees about the internal structure of a transaction. In order
135//! to expose this UTXO-specific functionality as well as the generic data availability
136//! functionality provided by this crate as part of the same public API, you can extend the
137//! [availability] module of this crate with additional data structures and endpoints that know
138//! about the internal structure of your transactions.
139//!
140//! There are two parts to adding additional functionality to a module in this crate: adding the
141//! required additional data structures to the data source, and creating a new API endpoint to
142//! expose the functionality. The mechanism for the former will depend on the specific data source
143//! you are using. Check the documentation for your data source implementation to see how it can be
144//! extended.
145//!
146//! For the latter, you can modify the default availability API with the addition of a new endpoint
147//! that accesses the custom state you have added to the data source. It is good practice to define
148//! a trait for accessing this custom state, so that if you want to switch data sources in the
149//! future, you can easily extend the new data source, implement the trait, and then transparently
150//! replace the data source that you use to set up your API. In the case of
151//! adding a UTXO index, this trait might look like this:
152//!
153//! ```
154//! # use hotshot_query_service::{
155//! #   availability::{AvailabilityDataSource, TransactionIndex},
156//! #   testing::mocks::MockTypes as AppTypes,
157//! # };
158//! use async_trait::async_trait;
159//!
160//! #[async_trait]
161//! trait UtxoDataSource: AvailabilityDataSource<AppTypes> {
162//!     // Index mapping UTXO index to (block index, transaction index, output index)
163//!     async fn find_utxo(&self, utxo: u64) -> Option<(usize, TransactionIndex<AppTypes>, usize)>;
164//! }
165//! ```
166//!
167//! Implement this trait for the extended data source you're using, and then add a new endpoint to
168//! the availability API like so:
169//!
170//! ```
171//! # use async_trait::async_trait;
172//! # use futures::FutureExt;
173//! # use hotshot_query_service::availability::{
174//! #   self, AvailabilityDataSource, FetchBlockSnafu, TransactionIndex,
175//! # };
176//! # use hotshot_query_service::testing::mocks::MockTypes as AppTypes;
177//! # use hotshot_query_service::testing::mocks::MockBase;
178//! # use hotshot_query_service::{ApiState, Error};
179//! # use snafu::ResultExt;
180//! # use tide_disco::{api::ApiError, method::ReadState, Api, App, StatusCode};
181//! # use vbs::version::StaticVersionType;
182//! # #[async_trait]
183//! # trait UtxoDataSource: AvailabilityDataSource<AppTypes> {
184//! #   async fn find_utxo(&self, utxo: u64) -> Option<(usize, TransactionIndex<AppTypes>, usize)>;
185//! # }
186//!
187//! fn define_app_specific_availability_api<State, Ver: StaticVersionType + 'static>(
188//!     options: &availability::Options,
189//!     bind_version: Ver,
190//! ) -> Result<Api<State, availability::Error, Ver>, ApiError>
191//! where
192//!     State: 'static + Send + Sync + ReadState,
193//!     <State as ReadState>::State: UtxoDataSource + Send + Sync,
194//! {
195//!     let mut api = availability::define_api(options, bind_version)?;
196//!     api.get("get_utxo", |req, state: &<State as ReadState>::State| async move {
197//!         let utxo_index = req.integer_param("index")?;
198//!         let (block_index, txn_index, output_index) = state
199//!             .find_utxo(utxo_index)
200//!             .await
201//!             .ok_or_else(|| availability::Error::Custom {
202//!                 message: format!("no such UTXO {}", utxo_index),
203//!                 status: StatusCode::NOT_FOUND,
204//!             })?;
205//!         let block = state
206//!             .get_block(block_index)
207//!             .await
208//!             .context(FetchBlockSnafu { resource: block_index.to_string() })?;
209//!         let txn = block.transaction(&txn_index).unwrap();
210//!         let utxo = // Application-specific logic to extract a UTXO from a transaction.
211//! #           todo!();
212//!         Ok(utxo)
213//!     }.boxed())?;
214//!     Ok(api)
215//! }
216//!
217//! fn init_server<D: UtxoDataSource + Send + Sync + 'static, Ver: StaticVersionType + 'static>(
218//!     options: &availability::Options,
219//!     data_source: D,
220//!     bind_version: Ver,
221//! ) -> Result<App<ApiState<D>, Error>, availability::Error> {
222//!     let api = define_app_specific_availability_api(options, bind_version)
223//!         .map_err(availability::Error::internal)?;
224//!     let mut app = App::<_, _>::with_state(ApiState::from(data_source));
225//!     app.register_module("availability", api).map_err(availability::Error::internal)?;
226//!     Ok(app)
227//! }
228//! ```
229//!
230//! Now you need to define the new route, `get_utxo`, in your API specification. Create a file
231//! `app_specific_availability.toml`:
232//!
233//! ```toml
234//! [route.get_utxo]
235//! PATH = ["utxo/:index"]
236//! ":index" = "Integer"
237//! DOC = "Get a UTXO by its index"
238//! ```
239//!
240//! and make sure `options.extensions` includes `"app_specific_availability.toml"`.
241//!
242//! ## Composition
243//!
244//! Composing the modules provided by this crate with other, unrelated modules to create a unified
245//! service is fairly simple, as most of the complexity is handled by [tide_disco], which already
246//! provides a mechanism for composing several modules into a single application. In principle, all
247//! you need to do is register the [availability], [node], and [status] APIs provided by this crate
248//! with a [tide_disco::App], and then register your own API modules with the same app.
249//!
250//! The one wrinkle is that all modules within a [tide_disco] app must share the same state type. It
251//! is for this reason that the modules provided by this crate are generic on the state type --
252//! [availability::define_api], [node::define_api], and [status::define_api] can all work with any
253//! state type, provided that type implements the corresponding data source traits. The data sources
254//! provided by this crate implement these traits, but if you want to use a custom state type that
255//! includes state for other modules, you will need to implement these traits for your custom type.
256//! The basic pattern looks like this:
257//!
258//! ```
259//! # use async_trait::async_trait;
260//! # use hotshot_query_service::{Header, QueryResult, VidShare};
261//! # use hotshot_query_service::availability::{
262//! #   AvailabilityDataSource, BlockId, BlockQueryData, Fetch, FetchStream, LeafId, LeafQueryData,
263//! #   PayloadMetadata, PayloadQueryData, TransactionFromBlock, TransactionHash,
264//! #   VidCommonMetadata, VidCommonQueryData,
265//! # };
266//! # use hotshot_query_service::metrics::PrometheusMetrics;
267//! # use hotshot_query_service::node::{
268//! #   NodeDataSource, SyncStatus, TimeWindowQueryData, WindowStart,
269//! # };
270//! # use hotshot_query_service::status::{HasMetrics, StatusDataSource};
271//! # use hotshot_query_service::testing::mocks::MockTypes as AppTypes;
272//! # use std::ops::{Bound, RangeBounds};
273//! # type AppQueryData = ();
274//! // Our AppState takes an underlying data source `D` which already implements the relevant
275//! // traits, and adds some state for use with other modules.
276//! struct AppState<D> {
277//!     hotshot_qs: D,
278//!     // additional state for other modules
279//! }
280//!
281//! // Implement data source trait for availability API by delegating to the underlying data source.
282//! #[async_trait]
283//! impl<D: AvailabilityDataSource<AppTypes> + Send + Sync>
284//!     AvailabilityDataSource<AppTypes> for AppState<D>
285//! {
286//!     async fn get_leaf<ID>(&self, id: ID) -> Fetch<LeafQueryData<AppTypes>>
287//!     where
288//!         ID: Into<LeafId<AppTypes>> + Send + Sync,
289//!     {
290//!         self.hotshot_qs.get_leaf(id).await
291//!     }
292//!
293//!     // etc
294//! #   async fn get_block<ID>(&self, id: ID) -> Fetch<BlockQueryData<AppTypes>>
295//! #   where
296//! #       ID: Into<BlockId<AppTypes>> + Send + Sync { todo!() }
297//! #   async fn get_payload<ID>(&self, id: ID) -> Fetch<PayloadQueryData<AppTypes>>
298//! #   where
299//! #       ID: Into<BlockId<AppTypes>> + Send + Sync { todo!() }
300//! #   async fn get_payload_metadata<ID>(&self, id: ID) -> Fetch<PayloadMetadata<AppTypes>>
301//! #   where
302//! #       ID: Into<BlockId<AppTypes>> + Send + Sync { todo!() }
303//! #   async fn get_vid_common<ID>(&self, id: ID) -> Fetch<VidCommonQueryData<AppTypes>>
304//! #   where
305//! #       ID: Into<BlockId<AppTypes>> + Send + Sync { todo!() }
306//! #   async fn get_vid_common_metadata<ID>(&self, id: ID) -> Fetch<VidCommonMetadata<AppTypes>>
307//! #   where
308//! #       ID: Into<BlockId<AppTypes>> + Send + Sync { todo!() }
309//! #   async fn get_transaction<T: TransactionFromBlock<AppTypes>>(&self, hash: TransactionHash<AppTypes>) -> Fetch<T> { todo!() }
310//! #   async fn get_leaf_range<R>(&self, range: R) -> FetchStream<LeafQueryData<AppTypes>>
311//! #   where
312//! #       R: RangeBounds<usize> + Send { todo!() }
313//! #   async fn get_block_range<R>(&self, range: R) -> FetchStream<BlockQueryData<AppTypes>>
314//! #   where
315//! #       R: RangeBounds<usize> + Send { todo!() }
316//! #   async fn get_payload_range<R>(&self, range: R) -> FetchStream<PayloadQueryData<AppTypes>>
317//! #   where
318//! #       R: RangeBounds<usize> + Send { todo!() }
319//! #   async fn get_payload_metadata_range<R>(&self, range: R) -> FetchStream<PayloadMetadata<AppTypes>>
320//! #   where
321//! #       R: RangeBounds<usize> + Send { todo!() }
322//! #   async fn get_vid_common_range<R>(&self, range: R) -> FetchStream<VidCommonQueryData<AppTypes>>
323//! #   where
324//! #       R: RangeBounds<usize> + Send { todo!() }
325//! #   async fn get_vid_common_metadata_range<R>(&self, range: R) -> FetchStream<VidCommonMetadata<AppTypes>>
326//! #   where
327//! #       R: RangeBounds<usize> + Send { todo!() }
328//! #   async fn get_leaf_range_rev(&self, start: Bound<usize>, end: usize) -> FetchStream<LeafQueryData<AppTypes>> { todo!() }
329//! #   async fn get_block_range_rev(&self, start: Bound<usize>, end: usize) -> FetchStream<BlockQueryData<AppTypes>> { todo!() }
330//! #   async fn get_payload_range_rev(&self, start: Bound<usize>, end: usize) -> FetchStream<PayloadQueryData<AppTypes>> { todo!() }
331//! #   async fn get_payload_metadata_range_rev(&self, start: Bound<usize>, end: usize) -> FetchStream<PayloadMetadata<AppTypes>> { todo!() }
332//! #   async fn get_vid_common_range_rev(&self, start: Bound<usize>, end: usize) -> FetchStream<VidCommonQueryData<AppTypes>> { todo!() }
333//! #   async fn get_vid_common_metadata_range_rev(&self, start: Bound<usize>, end: usize) -> FetchStream<VidCommonMetadata<AppTypes>> { todo!() }
334//! }
335//!
336//! // Implement data source trait for node API by delegating to the underlying data source.
337//! #[async_trait]
338//! impl<D: NodeDataSource<AppTypes> + Send + Sync> NodeDataSource<AppTypes> for AppState<D> {
339//!     async fn block_height(&self) -> QueryResult<usize> {
340//!         self.hotshot_qs.block_height().await
341//!     }
342//!
343//!     async fn count_transactions_in_range(
344//!         &self,
345//!         range: impl RangeBounds<usize> + Send,
346//!     ) -> QueryResult<usize> {
347//!         self.hotshot_qs.count_transactions_in_range(range).await
348//!     }
349//!
350//!     async fn payload_size_in_range(
351//!         &self,
352//!         range: impl RangeBounds<usize> + Send,
353//!     ) -> QueryResult<usize> {
354//!         self.hotshot_qs.payload_size_in_range(range).await
355//!     }
356//!
357//!     async fn vid_share<ID>(&self, id: ID) -> QueryResult<VidShare>
358//!     where
359//!         ID: Into<BlockId<AppTypes>> + Send + Sync,
360//!     {
361//!         self.hotshot_qs.vid_share(id).await
362//!     }
363//!
364//!     async fn sync_status(&self) -> QueryResult<SyncStatus> {
365//!         self.hotshot_qs.sync_status().await
366//!     }
367//!
368//!     async fn get_header_window(
369//!         &self,
370//!         start: impl Into<WindowStart<AppTypes>> + Send + Sync,
371//!         end: u64,
372//!         limit: usize,
373//!     ) -> QueryResult<TimeWindowQueryData<Header<AppTypes>>> {
374//!         self.hotshot_qs.get_header_window(start, end, limit).await
375//!     }
376//! }
377//!
378//! // Implement data source trait for status API by delegating to the underlying data source.
379//! impl<D: HasMetrics> HasMetrics for AppState<D> {
380//!     fn metrics(&self) -> &PrometheusMetrics {
381//!         self.hotshot_qs.metrics()
382//!     }
383//! }
384//! #[async_trait]
385//! impl<D: StatusDataSource + Send + Sync> StatusDataSource for AppState<D> {
386//!     async fn block_height(&self) -> QueryResult<usize> {
387//!         self.hotshot_qs.block_height().await
388//!     }
389//! }
390//!
391//! // Implement data source traits for other modules, using additional state from AppState.
392//! ```
393//!
394//! In the future, we may provide derive macros for
395//! [AvailabilityDataSource](availability::AvailabilityDataSource),
396//! [NodeDataSource](node::NodeDataSource), and [StatusDataSource](status::StatusDataSource) to
397//! eliminate the boilerplate of implementing them for a custom type that has an existing
398//! implementation as one of its fields.
399//!
400//! Once you have created your `AppState` type aggregating the state for each API module, you can
401//! initialize the state as normal, instantiating `D` with a concrete implementation of a data
402//! source and initializing `hotshot_qs` as you normally would that data source.
403//!
404//! _However_, this only works if you want the persistent storage for the availability and node
405//! modules (managed by `hotshot_qs`) to be independent of the persistent storage for other modules.
406//! You may well want to synchronize the storage for all modules together, so that updates to the
407//! entire application state can be done atomically. This is particularly relevant if one of your
408//! application-specific modules updates its storage based on a stream of HotShot leaves. Since the
409//! availability and node modules also update with each new leaf, you probably want all of these
410//! modules to stay in sync. The data source implementations provided by this crate provide means by
411//! which you can add additional data to the same persistent store and synchronize the entire store
412//! together. Refer to the documentation for you specific data source for information on how to
413//! achieve this.
414//!
415
416mod api;
417pub mod availability;
418pub mod data_source;
419mod error;
420pub mod explorer;
421pub mod fetching;
422pub mod merklized_state;
423pub mod metrics;
424pub mod node;
425mod resolvable;
426pub mod status;
427pub mod task;
428pub mod testing;
429pub mod types;
430
431use std::sync::Arc;
432
433use async_trait::async_trait;
434use derive_more::{Deref, From, Into};
435pub use error::Error;
436use futures::{future::BoxFuture, stream::StreamExt};
437use hotshot::types::SystemContextHandle;
438use hotshot_types::traits::{
439    BlockPayload,
440    node_implementation::{NodeImplementation, NodeType},
441};
442pub use hotshot_types::{data::Leaf2, simple_certificate::QuorumCertificate};
443pub use resolvable::Resolvable;
444use serde::{Deserialize, Serialize};
445use snafu::Snafu;
446use task::BackgroundTask;
447use tide_disco::{App, StatusCode, method::ReadState};
448use vbs::version::StaticVersionType;
449
450pub type Payload<Types> = <Types as NodeType>::BlockPayload;
451pub type Header<Types> = <Types as NodeType>::BlockHeader;
452pub type Metadata<Types> = <Payload<Types> as BlockPayload<Types>>::Metadata;
453/// Item within a [`Payload`].
454pub type Transaction<Types> = <Payload<Types> as BlockPayload<Types>>::Transaction;
455pub type SignatureKey<Types> = <Types as NodeType>::SignatureKey;
456
457#[derive(Clone, Debug, Snafu, Deserialize, Serialize)]
458#[snafu(visibility(pub))]
459pub enum QueryError {
460    /// The requested resource does not exist or is not known to this query service.
461    NotFound,
462    /// The requested resource exists but is not currently available.
463    ///
464    /// In most cases a missing resource can be recovered from DA.
465    Missing,
466    /// There was an error while trying to fetch the requested resource.
467    #[snafu(display("Failed to fetch requested resource: {message}"))]
468    #[snafu(context(suffix(ErrorSnafu)))]
469    Error { message: String },
470}
471
472impl QueryError {
473    pub fn status(&self) -> StatusCode {
474        match self {
475            Self::NotFound | Self::Missing => StatusCode::NOT_FOUND,
476            Self::Error { .. } => StatusCode::INTERNAL_SERVER_ERROR,
477        }
478    }
479}
480
481pub type QueryResult<T> = Result<T, QueryError>;
482
483#[derive(Default)]
484pub struct Options {
485    pub availability: availability::Options,
486    pub node: node::Options,
487    pub status: status::Options,
488    pub port: u16,
489}
490
491/// Read-only wrapper for API state which does not require locking.
492#[derive(Clone, Debug, Deref, From, Into)]
493pub struct ApiState<D>(Arc<D>);
494
495#[async_trait]
496impl<D: 'static + Send + Sync> ReadState for ApiState<D> {
497    type State = D;
498    async fn read<T>(
499        &self,
500        op: impl Send + for<'a> FnOnce(&'a Self::State) -> BoxFuture<'a, T> + 'async_trait,
501    ) -> T {
502        op(&self.0).await
503    }
504}
505
506impl<D> From<D> for ApiState<D> {
507    fn from(d: D) -> Self {
508        Self::from(Arc::new(d))
509    }
510}
511
512/// Run an instance of the HotShot Query service with no customization.
513pub async fn run_standalone_service<Types: NodeType, I: NodeImplementation<Types>, D, ApiVer>(
514    options: Options,
515    data_source: D,
516    hotshot: SystemContextHandle<Types, I>,
517    bind_version: ApiVer,
518) -> Result<(), Error>
519where
520    Payload<Types>: availability::QueryablePayload<Types>,
521    Header<Types>: availability::QueryableHeader<Types>,
522    D: availability::AvailabilityDataSource<Types>
523        + data_source::UpdateDataSource<Types>
524        + node::NodeDataSource<Types>
525        + status::StatusDataSource
526        + data_source::VersionedDataSource
527        + Send
528        + Sync
529        + 'static,
530    ApiVer: StaticVersionType + 'static,
531{
532    // Create API modules.
533    let availability_api_v0 = availability::define_api(
534        &options.availability,
535        bind_version,
536        "0.0.1".parse().unwrap(),
537    )
538    .map_err(Error::internal)?;
539
540    let availability_api_v1 = availability::define_api(
541        &options.availability,
542        bind_version,
543        "1.0.0".parse().unwrap(),
544    )
545    .map_err(Error::internal)?;
546    let node_api = node::define_api(&options.node, bind_version, "0.0.1".parse().unwrap())
547        .map_err(Error::internal)?;
548    let status_api = status::define_api(&options.status, bind_version, "0.0.1".parse().unwrap())
549        .map_err(Error::internal)?;
550
551    // Create app.
552    let data_source = Arc::new(data_source);
553    let mut app = App::<_, Error>::with_state(ApiState(data_source.clone()));
554    app.register_module("availability", availability_api_v0)
555        .map_err(Error::internal)?
556        .register_module("availability", availability_api_v1)
557        .map_err(Error::internal)?
558        .register_module("node", node_api)
559        .map_err(Error::internal)?
560        .register_module("status", status_api)
561        .map_err(Error::internal)?;
562
563    // Serve app.
564    let url = format!("0.0.0.0:{}", options.port);
565    let _server =
566        BackgroundTask::spawn("server", async move { app.serve(&url, bind_version).await });
567
568    // Subscribe to events before starting consensus, so we don't miss any events.
569    let mut events = hotshot.event_stream();
570    hotshot.hotshot.start_consensus().await;
571
572    // Update query data using HotShot events.
573    while let Some(event) = events.next().await {
574        // Update the query data based on this event. It is safe to ignore errors here; the error
575        // just returns the failed block height for use in garbage collection, but this simple
576        // implementation isn't doing any kind of garbage collection.
577        data_source.update(&event).await.ok();
578    }
579
580    Ok(())
581}
582
583#[cfg(test)]
584mod test {
585    use std::{
586        ops::{Bound, RangeBounds},
587        time::Duration,
588    };
589
590    use async_lock::RwLock;
591    use async_trait::async_trait;
592    use atomic_store::{AtomicStore, AtomicStoreLoader, RollingLog, load_store::BincodeLoadStore};
593    use futures::future::FutureExt;
594    use hotshot_example_types::node_types::TEST_VERSIONS;
595    use hotshot_types::{data::VidShare, simple_certificate::QuorumCertificate2};
596    use surf_disco::Client;
597    use tempfile::TempDir;
598    use test_utils::reserve_tcp_port;
599    use testing::mocks::MockBase;
600    use tide_disco::App;
601    use toml::toml;
602
603    use super::*;
604    use crate::{
605        availability::{
606            AvailabilityDataSource, BlockId, BlockInfo, BlockQueryData, BlockWithTransaction,
607            Fetch, FetchStream, LeafId, LeafQueryData, NamespaceId, PayloadMetadata,
608            PayloadQueryData, TransactionHash, UpdateAvailabilityData, VidCommonMetadata,
609            VidCommonQueryData,
610        },
611        metrics::PrometheusMetrics,
612        node::{NodeDataSource, SyncStatusQueryData, TimeWindowQueryData, WindowStart},
613        status::{HasMetrics, StatusDataSource},
614        testing::{
615            consensus::MockDataSource,
616            mocks::{MockHeader, MockPayload, MockTypes},
617        },
618    };
619
620    struct CompositeState {
621        store: AtomicStore,
622        hotshot_qs: MockDataSource,
623        module_state: RollingLog<BincodeLoadStore<u64>>,
624    }
625
626    #[async_trait]
627    impl AvailabilityDataSource<MockTypes> for CompositeState {
628        async fn get_leaf<ID>(&self, id: ID) -> Fetch<LeafQueryData<MockTypes>>
629        where
630            ID: Into<LeafId<MockTypes>> + Send + Sync,
631        {
632            self.hotshot_qs.get_leaf(id).await
633        }
634        async fn get_block<ID>(&self, id: ID) -> Fetch<BlockQueryData<MockTypes>>
635        where
636            ID: Into<BlockId<MockTypes>> + Send + Sync,
637        {
638            self.hotshot_qs.get_block(id).await
639        }
640
641        async fn get_header<ID>(&self, id: ID) -> Fetch<Header<MockTypes>>
642        where
643            ID: Into<BlockId<MockTypes>> + Send + Sync,
644        {
645            self.hotshot_qs.get_header(id).await
646        }
647        async fn get_payload<ID>(&self, id: ID) -> Fetch<PayloadQueryData<MockTypes>>
648        where
649            ID: Into<BlockId<MockTypes>> + Send + Sync,
650        {
651            self.hotshot_qs.get_payload(id).await
652        }
653        async fn get_payload_metadata<ID>(&self, id: ID) -> Fetch<PayloadMetadata<MockTypes>>
654        where
655            ID: Into<BlockId<MockTypes>> + Send + Sync,
656        {
657            self.hotshot_qs.get_payload_metadata(id).await
658        }
659        async fn get_vid_common<ID>(&self, id: ID) -> Fetch<VidCommonQueryData<MockTypes>>
660        where
661            ID: Into<BlockId<MockTypes>> + Send + Sync,
662        {
663            self.hotshot_qs.get_vid_common(id).await
664        }
665        async fn get_vid_common_metadata<ID>(&self, id: ID) -> Fetch<VidCommonMetadata<MockTypes>>
666        where
667            ID: Into<BlockId<MockTypes>> + Send + Sync,
668        {
669            self.hotshot_qs.get_vid_common_metadata(id).await
670        }
671        async fn get_leaf_range<R>(&self, range: R) -> FetchStream<LeafQueryData<MockTypes>>
672        where
673            R: RangeBounds<usize> + Send + 'static,
674        {
675            self.hotshot_qs.get_leaf_range(range).await
676        }
677        async fn get_block_range<R>(&self, range: R) -> FetchStream<BlockQueryData<MockTypes>>
678        where
679            R: RangeBounds<usize> + Send + 'static,
680        {
681            self.hotshot_qs.get_block_range(range).await
682        }
683
684        async fn get_header_range<R>(&self, range: R) -> FetchStream<Header<MockTypes>>
685        where
686            R: RangeBounds<usize> + Send + 'static,
687        {
688            self.hotshot_qs.get_header_range(range).await
689        }
690        async fn get_payload_range<R>(&self, range: R) -> FetchStream<PayloadQueryData<MockTypes>>
691        where
692            R: RangeBounds<usize> + Send + 'static,
693        {
694            self.hotshot_qs.get_payload_range(range).await
695        }
696        async fn get_payload_metadata_range<R>(
697            &self,
698            range: R,
699        ) -> FetchStream<PayloadMetadata<MockTypes>>
700        where
701            R: RangeBounds<usize> + Send + 'static,
702        {
703            self.hotshot_qs.get_payload_metadata_range(range).await
704        }
705        async fn get_vid_common_range<R>(
706            &self,
707            range: R,
708        ) -> FetchStream<VidCommonQueryData<MockTypes>>
709        where
710            R: RangeBounds<usize> + Send + 'static,
711        {
712            self.hotshot_qs.get_vid_common_range(range).await
713        }
714        async fn get_vid_common_metadata_range<R>(
715            &self,
716            range: R,
717        ) -> FetchStream<VidCommonMetadata<MockTypes>>
718        where
719            R: RangeBounds<usize> + Send + 'static,
720        {
721            self.hotshot_qs.get_vid_common_metadata_range(range).await
722        }
723        async fn get_leaf_range_rev(
724            &self,
725            start: Bound<usize>,
726            end: usize,
727        ) -> FetchStream<LeafQueryData<MockTypes>> {
728            self.hotshot_qs.get_leaf_range_rev(start, end).await
729        }
730        async fn get_block_range_rev(
731            &self,
732            start: Bound<usize>,
733            end: usize,
734        ) -> FetchStream<BlockQueryData<MockTypes>> {
735            self.hotshot_qs.get_block_range_rev(start, end).await
736        }
737        async fn get_payload_range_rev(
738            &self,
739            start: Bound<usize>,
740            end: usize,
741        ) -> FetchStream<PayloadQueryData<MockTypes>> {
742            self.hotshot_qs.get_payload_range_rev(start, end).await
743        }
744        async fn get_payload_metadata_range_rev(
745            &self,
746            start: Bound<usize>,
747            end: usize,
748        ) -> FetchStream<PayloadMetadata<MockTypes>> {
749            self.hotshot_qs
750                .get_payload_metadata_range_rev(start, end)
751                .await
752        }
753        async fn get_vid_common_range_rev(
754            &self,
755            start: Bound<usize>,
756            end: usize,
757        ) -> FetchStream<VidCommonQueryData<MockTypes>> {
758            self.hotshot_qs.get_vid_common_range_rev(start, end).await
759        }
760        async fn get_vid_common_metadata_range_rev(
761            &self,
762            start: Bound<usize>,
763            end: usize,
764        ) -> FetchStream<VidCommonMetadata<MockTypes>> {
765            self.hotshot_qs
766                .get_vid_common_metadata_range_rev(start, end)
767                .await
768        }
769        async fn get_block_containing_transaction(
770            &self,
771            hash: TransactionHash<MockTypes>,
772        ) -> Fetch<BlockWithTransaction<MockTypes>> {
773            self.hotshot_qs.get_block_containing_transaction(hash).await
774        }
775    }
776
777    // Imiplement data source trait for node API.
778    #[async_trait]
779    impl NodeDataSource<MockTypes> for CompositeState {
780        async fn block_height(&self) -> QueryResult<usize> {
781            StatusDataSource::block_height(self).await
782        }
783        async fn count_transactions_in_range(
784            &self,
785            range: impl RangeBounds<usize> + Send,
786            namespace: Option<NamespaceId<MockTypes>>,
787        ) -> QueryResult<usize> {
788            self.hotshot_qs
789                .count_transactions_in_range(range, namespace)
790                .await
791        }
792        async fn payload_size_in_range(
793            &self,
794            range: impl RangeBounds<usize> + Send,
795            namespace: Option<NamespaceId<MockTypes>>,
796        ) -> QueryResult<usize> {
797            self.hotshot_qs
798                .payload_size_in_range(range, namespace)
799                .await
800        }
801        async fn vid_share<ID>(&self, id: ID) -> QueryResult<VidShare>
802        where
803            ID: Into<BlockId<MockTypes>> + Send + Sync,
804        {
805            self.hotshot_qs.vid_share(id).await
806        }
807        async fn sync_status(&self) -> QueryResult<SyncStatusQueryData> {
808            self.hotshot_qs.sync_status().await
809        }
810        async fn get_header_window(
811            &self,
812            start: impl Into<WindowStart<MockTypes>> + Send + Sync,
813            end: u64,
814            limit: usize,
815        ) -> QueryResult<TimeWindowQueryData<Header<MockTypes>>> {
816            self.hotshot_qs.get_header_window(start, end, limit).await
817        }
818    }
819
820    // Implement data source trait for status API.
821    impl HasMetrics for CompositeState {
822        fn metrics(&self) -> &PrometheusMetrics {
823            self.hotshot_qs.metrics()
824        }
825    }
826    #[async_trait]
827    impl StatusDataSource for CompositeState {
828        async fn block_height(&self) -> QueryResult<usize> {
829            StatusDataSource::block_height(&self.hotshot_qs).await
830        }
831    }
832
833    #[tokio::test(flavor = "multi_thread")]
834    async fn test_composition() {
835        let dir = TempDir::with_prefix("test_composition").unwrap();
836        let mut loader = AtomicStoreLoader::create(dir.path(), "test_composition").unwrap();
837        let hotshot_qs = MockDataSource::create_with_store(&mut loader, Default::default())
838            .await
839            .unwrap();
840
841        // Mock up some data and add a block to the store.
842        let leaf = Leaf2::<MockTypes>::genesis(
843            &Default::default(),
844            &Default::default(),
845            TEST_VERSIONS.test.base,
846        )
847        .await;
848        let qc = QuorumCertificate2::genesis(
849            &Default::default(),
850            &Default::default(),
851            TEST_VERSIONS.test,
852        )
853        .await;
854        let leaf = LeafQueryData::new(leaf, qc).unwrap();
855        let block = BlockQueryData::new(leaf.header().clone(), MockPayload::genesis());
856        hotshot_qs
857            .append(BlockInfo::new(leaf, Some(block), None, None))
858            .await
859            .unwrap();
860
861        let module_state =
862            RollingLog::create(&mut loader, Default::default(), "module_state", 1024).unwrap();
863        let state = CompositeState {
864            hotshot_qs,
865            module_state,
866            store: AtomicStore::open(loader).unwrap(),
867        };
868
869        let module_spec = toml! {
870            [route.post_ext]
871            PATH = ["/ext/:val"]
872            METHOD = "POST"
873            ":val" = "Integer"
874
875            [route.get_ext]
876            PATH = ["/ext"]
877            METHOD = "GET"
878        };
879
880        let mut app = App::<_, Error>::with_state(RwLock::new(state));
881        app.register_module(
882            "availability",
883            availability::define_api(
884                &Default::default(),
885                MockBase::instance(),
886                "0.0.1".parse().unwrap(),
887            )
888            .unwrap(),
889        )
890        .unwrap()
891        .register_module(
892            "node",
893            node::define_api(
894                &Default::default(),
895                MockBase::instance(),
896                "0.0.1".parse().unwrap(),
897            )
898            .unwrap(),
899        )
900        .unwrap()
901        .register_module(
902            "status",
903            status::define_api(
904                &Default::default(),
905                MockBase::instance(),
906                "0.0.1".parse().unwrap(),
907            )
908            .unwrap(),
909        )
910        .unwrap()
911        .module::<Error, MockBase>("mod", module_spec)
912        .unwrap()
913        .get("get_ext", |_, state| {
914            async move { state.module_state.load_latest().map_err(Error::internal) }.boxed()
915        })
916        .unwrap()
917        .post("post_ext", |req, state| {
918            async move {
919                state
920                    .module_state
921                    .store_resource(&req.integer_param("val").map_err(Error::internal)?)
922                    .map_err(Error::internal)?;
923                state
924                    .module_state
925                    .commit_version()
926                    .map_err(Error::internal)?;
927                state
928                    .hotshot_qs
929                    .skip_version()
930                    .await
931                    .map_err(Error::internal)?;
932                state.store.commit_version().map_err(Error::internal)
933            }
934            .boxed()
935        })
936        .unwrap();
937
938        let port = reserve_tcp_port().unwrap();
939        let _server = BackgroundTask::spawn(
940            "server",
941            app.serve(format!("0.0.0.0:{port}"), MockBase::instance()),
942        );
943
944        let client =
945            Client::<Error, MockBase>::new(format!("http://localhost:{port}").parse().unwrap());
946        assert!(client.connect(Some(Duration::from_secs(60))).await);
947
948        client.post::<()>("mod/ext/42").send().await.unwrap();
949        assert_eq!(client.get::<u64>("mod/ext").send().await.unwrap(), 42);
950
951        // Check that we can still access the built-in modules.
952        assert_eq!(
953            client
954                .get::<u64>("status/block-height")
955                .send()
956                .await
957                .unwrap(),
958            1
959        );
960        let sync_status: SyncStatusQueryData = client.get("node/sync-status").send().await.unwrap();
961        assert_eq!(sync_status.blocks.missing, 0);
962        assert_eq!(sync_status.leaves.missing, 0);
963        assert_eq!(sync_status.vid_common.missing, 1);
964        assert_eq!(sync_status.vid_shares.missing, 1);
965
966        assert_eq!(
967            client
968                .get::<MockHeader>("availability/header/0")
969                .send()
970                .await
971                .unwrap()
972                .block_number,
973            0
974        );
975    }
976}