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    node_implementation::{NodeImplementation, NodeType, Versions},
440    BlockPayload,
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::{method::ReadState, App, StatusCode};
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<
514    Types: NodeType,
515    I: NodeImplementation<Types>,
516    D,
517    ApiVer,
518    HsVer: Versions,
519>(
520    options: Options,
521    data_source: D,
522    hotshot: SystemContextHandle<Types, I, HsVer>,
523    bind_version: ApiVer,
524) -> Result<(), Error>
525where
526    Payload<Types>: availability::QueryablePayload<Types>,
527    Header<Types>: availability::QueryableHeader<Types>,
528    D: availability::AvailabilityDataSource<Types>
529        + data_source::UpdateDataSource<Types>
530        + node::NodeDataSource<Types>
531        + status::StatusDataSource
532        + data_source::VersionedDataSource
533        + Send
534        + Sync
535        + 'static,
536    ApiVer: StaticVersionType + 'static,
537{
538    // Create API modules.
539    let availability_api_v0 = availability::define_api(
540        &options.availability,
541        bind_version,
542        "0.0.1".parse().unwrap(),
543    )
544    .map_err(Error::internal)?;
545
546    let availability_api_v1 = availability::define_api(
547        &options.availability,
548        bind_version,
549        "1.0.0".parse().unwrap(),
550    )
551    .map_err(Error::internal)?;
552    let node_api = node::define_api(&options.node, bind_version, "0.0.1".parse().unwrap())
553        .map_err(Error::internal)?;
554    let status_api = status::define_api(&options.status, bind_version, "0.0.1".parse().unwrap())
555        .map_err(Error::internal)?;
556
557    // Create app.
558    let data_source = Arc::new(data_source);
559    let mut app = App::<_, Error>::with_state(ApiState(data_source.clone()));
560    app.register_module("availability", availability_api_v0)
561        .map_err(Error::internal)?
562        .register_module("availability", availability_api_v1)
563        .map_err(Error::internal)?
564        .register_module("node", node_api)
565        .map_err(Error::internal)?
566        .register_module("status", status_api)
567        .map_err(Error::internal)?;
568
569    // Serve app.
570    let url = format!("0.0.0.0:{}", options.port);
571    let _server =
572        BackgroundTask::spawn("server", async move { app.serve(&url, bind_version).await });
573
574    // Subscribe to events before starting consensus, so we don't miss any events.
575    let mut events = hotshot.event_stream();
576    hotshot.hotshot.start_consensus().await;
577
578    // Update query data using HotShot events.
579    while let Some(event) = events.next().await {
580        // Update the query data based on this event. It is safe to ignore errors here; the error
581        // just returns the failed block height for use in garbage collection, but this simple
582        // implementation isn't doing any kind of garbage collection.
583        data_source.update(&event).await.ok();
584    }
585
586    Ok(())
587}
588
589#[cfg(test)]
590mod test {
591    use std::{
592        ops::{Bound, RangeBounds},
593        time::Duration,
594    };
595
596    use async_lock::RwLock;
597    use async_trait::async_trait;
598    use atomic_store::{load_store::BincodeLoadStore, AtomicStore, AtomicStoreLoader, RollingLog};
599    use futures::future::FutureExt;
600    use hotshot_types::{data::VidShare, simple_certificate::QuorumCertificate2};
601    use portpicker::pick_unused_port;
602    use surf_disco::Client;
603    use tempfile::TempDir;
604    use testing::mocks::MockBase;
605    use tide_disco::App;
606    use toml::toml;
607
608    use super::*;
609    use crate::{
610        availability::{
611            AvailabilityDataSource, BlockId, BlockInfo, BlockQueryData, BlockWithTransaction,
612            Fetch, FetchStream, LeafId, LeafQueryData, NamespaceId, PayloadMetadata,
613            PayloadQueryData, TransactionHash, UpdateAvailabilityData, VidCommonMetadata,
614            VidCommonQueryData,
615        },
616        metrics::PrometheusMetrics,
617        node::{NodeDataSource, SyncStatus, TimeWindowQueryData, WindowStart},
618        status::{HasMetrics, StatusDataSource},
619        testing::{
620            consensus::MockDataSource,
621            mocks::{MockHeader, MockPayload, MockTypes},
622        },
623    };
624
625    struct CompositeState {
626        store: AtomicStore,
627        hotshot_qs: MockDataSource,
628        module_state: RollingLog<BincodeLoadStore<u64>>,
629    }
630
631    #[async_trait]
632    impl AvailabilityDataSource<MockTypes> for CompositeState {
633        async fn get_leaf<ID>(&self, id: ID) -> Fetch<LeafQueryData<MockTypes>>
634        where
635            ID: Into<LeafId<MockTypes>> + Send + Sync,
636        {
637            self.hotshot_qs.get_leaf(id).await
638        }
639        async fn get_block<ID>(&self, id: ID) -> Fetch<BlockQueryData<MockTypes>>
640        where
641            ID: Into<BlockId<MockTypes>> + Send + Sync,
642        {
643            self.hotshot_qs.get_block(id).await
644        }
645
646        async fn get_header<ID>(&self, id: ID) -> Fetch<Header<MockTypes>>
647        where
648            ID: Into<BlockId<MockTypes>> + Send + Sync,
649        {
650            self.hotshot_qs.get_header(id).await
651        }
652        async fn get_payload<ID>(&self, id: ID) -> Fetch<PayloadQueryData<MockTypes>>
653        where
654            ID: Into<BlockId<MockTypes>> + Send + Sync,
655        {
656            self.hotshot_qs.get_payload(id).await
657        }
658        async fn get_payload_metadata<ID>(&self, id: ID) -> Fetch<PayloadMetadata<MockTypes>>
659        where
660            ID: Into<BlockId<MockTypes>> + Send + Sync,
661        {
662            self.hotshot_qs.get_payload_metadata(id).await
663        }
664        async fn get_vid_common<ID>(&self, id: ID) -> Fetch<VidCommonQueryData<MockTypes>>
665        where
666            ID: Into<BlockId<MockTypes>> + Send + Sync,
667        {
668            self.hotshot_qs.get_vid_common(id).await
669        }
670        async fn get_vid_common_metadata<ID>(&self, id: ID) -> Fetch<VidCommonMetadata<MockTypes>>
671        where
672            ID: Into<BlockId<MockTypes>> + Send + Sync,
673        {
674            self.hotshot_qs.get_vid_common_metadata(id).await
675        }
676        async fn get_leaf_range<R>(&self, range: R) -> FetchStream<LeafQueryData<MockTypes>>
677        where
678            R: RangeBounds<usize> + Send + 'static,
679        {
680            self.hotshot_qs.get_leaf_range(range).await
681        }
682        async fn get_block_range<R>(&self, range: R) -> FetchStream<BlockQueryData<MockTypes>>
683        where
684            R: RangeBounds<usize> + Send + 'static,
685        {
686            self.hotshot_qs.get_block_range(range).await
687        }
688
689        async fn get_header_range<R>(&self, range: R) -> FetchStream<Header<MockTypes>>
690        where
691            R: RangeBounds<usize> + Send + 'static,
692        {
693            self.hotshot_qs.get_header_range(range).await
694        }
695        async fn get_payload_range<R>(&self, range: R) -> FetchStream<PayloadQueryData<MockTypes>>
696        where
697            R: RangeBounds<usize> + Send + 'static,
698        {
699            self.hotshot_qs.get_payload_range(range).await
700        }
701        async fn get_payload_metadata_range<R>(
702            &self,
703            range: R,
704        ) -> FetchStream<PayloadMetadata<MockTypes>>
705        where
706            R: RangeBounds<usize> + Send + 'static,
707        {
708            self.hotshot_qs.get_payload_metadata_range(range).await
709        }
710        async fn get_vid_common_range<R>(
711            &self,
712            range: R,
713        ) -> FetchStream<VidCommonQueryData<MockTypes>>
714        where
715            R: RangeBounds<usize> + Send + 'static,
716        {
717            self.hotshot_qs.get_vid_common_range(range).await
718        }
719        async fn get_vid_common_metadata_range<R>(
720            &self,
721            range: R,
722        ) -> FetchStream<VidCommonMetadata<MockTypes>>
723        where
724            R: RangeBounds<usize> + Send + 'static,
725        {
726            self.hotshot_qs.get_vid_common_metadata_range(range).await
727        }
728        async fn get_leaf_range_rev(
729            &self,
730            start: Bound<usize>,
731            end: usize,
732        ) -> FetchStream<LeafQueryData<MockTypes>> {
733            self.hotshot_qs.get_leaf_range_rev(start, end).await
734        }
735        async fn get_block_range_rev(
736            &self,
737            start: Bound<usize>,
738            end: usize,
739        ) -> FetchStream<BlockQueryData<MockTypes>> {
740            self.hotshot_qs.get_block_range_rev(start, end).await
741        }
742        async fn get_payload_range_rev(
743            &self,
744            start: Bound<usize>,
745            end: usize,
746        ) -> FetchStream<PayloadQueryData<MockTypes>> {
747            self.hotshot_qs.get_payload_range_rev(start, end).await
748        }
749        async fn get_payload_metadata_range_rev(
750            &self,
751            start: Bound<usize>,
752            end: usize,
753        ) -> FetchStream<PayloadMetadata<MockTypes>> {
754            self.hotshot_qs
755                .get_payload_metadata_range_rev(start, end)
756                .await
757        }
758        async fn get_vid_common_range_rev(
759            &self,
760            start: Bound<usize>,
761            end: usize,
762        ) -> FetchStream<VidCommonQueryData<MockTypes>> {
763            self.hotshot_qs.get_vid_common_range_rev(start, end).await
764        }
765        async fn get_vid_common_metadata_range_rev(
766            &self,
767            start: Bound<usize>,
768            end: usize,
769        ) -> FetchStream<VidCommonMetadata<MockTypes>> {
770            self.hotshot_qs
771                .get_vid_common_metadata_range_rev(start, end)
772                .await
773        }
774        async fn get_block_containing_transaction(
775            &self,
776            hash: TransactionHash<MockTypes>,
777        ) -> Fetch<BlockWithTransaction<MockTypes>> {
778            self.hotshot_qs.get_block_containing_transaction(hash).await
779        }
780    }
781
782    // Imiplement data source trait for node API.
783    #[async_trait]
784    impl NodeDataSource<MockTypes> for CompositeState {
785        async fn block_height(&self) -> QueryResult<usize> {
786            StatusDataSource::block_height(self).await
787        }
788        async fn count_transactions_in_range(
789            &self,
790            range: impl RangeBounds<usize> + Send,
791            namespace: Option<NamespaceId<MockTypes>>,
792        ) -> QueryResult<usize> {
793            self.hotshot_qs
794                .count_transactions_in_range(range, namespace)
795                .await
796        }
797        async fn payload_size_in_range(
798            &self,
799            range: impl RangeBounds<usize> + Send,
800            namespace: Option<NamespaceId<MockTypes>>,
801        ) -> QueryResult<usize> {
802            self.hotshot_qs
803                .payload_size_in_range(range, namespace)
804                .await
805        }
806        async fn vid_share<ID>(&self, id: ID) -> QueryResult<VidShare>
807        where
808            ID: Into<BlockId<MockTypes>> + Send + Sync,
809        {
810            self.hotshot_qs.vid_share(id).await
811        }
812        async fn sync_status(&self) -> QueryResult<SyncStatus> {
813            self.hotshot_qs.sync_status().await
814        }
815        async fn get_header_window(
816            &self,
817            start: impl Into<WindowStart<MockTypes>> + Send + Sync,
818            end: u64,
819            limit: usize,
820        ) -> QueryResult<TimeWindowQueryData<Header<MockTypes>>> {
821            self.hotshot_qs.get_header_window(start, end, limit).await
822        }
823    }
824
825    // Implement data source trait for status API.
826    impl HasMetrics for CompositeState {
827        fn metrics(&self) -> &PrometheusMetrics {
828            self.hotshot_qs.metrics()
829        }
830    }
831    #[async_trait]
832    impl StatusDataSource for CompositeState {
833        async fn block_height(&self) -> QueryResult<usize> {
834            StatusDataSource::block_height(&self.hotshot_qs).await
835        }
836    }
837
838    #[tokio::test(flavor = "multi_thread")]
839    async fn test_composition() {
840        use hotshot_example_types::node_types::TestVersions;
841
842        let dir = TempDir::with_prefix("test_composition").unwrap();
843        let mut loader = AtomicStoreLoader::create(dir.path(), "test_composition").unwrap();
844        let hotshot_qs = MockDataSource::create_with_store(&mut loader, Default::default())
845            .await
846            .unwrap();
847
848        // Mock up some data and add a block to the store.
849        let leaf =
850            Leaf2::<MockTypes>::genesis::<TestVersions>(&Default::default(), &Default::default())
851                .await;
852        let qc =
853            QuorumCertificate2::genesis::<TestVersions>(&Default::default(), &Default::default())
854                .await;
855        let leaf = LeafQueryData::new(leaf, qc).unwrap();
856        let block = BlockQueryData::new(leaf.header().clone(), MockPayload::genesis());
857        hotshot_qs
858            .append(BlockInfo::new(leaf, Some(block), None, None))
859            .await
860            .unwrap();
861
862        let module_state =
863            RollingLog::create(&mut loader, Default::default(), "module_state", 1024).unwrap();
864        let state = CompositeState {
865            hotshot_qs,
866            module_state,
867            store: AtomicStore::open(loader).unwrap(),
868        };
869
870        let module_spec = toml! {
871            [route.post_ext]
872            PATH = ["/ext/:val"]
873            METHOD = "POST"
874            ":val" = "Integer"
875
876            [route.get_ext]
877            PATH = ["/ext"]
878            METHOD = "GET"
879        };
880
881        let mut app = App::<_, Error>::with_state(RwLock::new(state));
882        app.register_module(
883            "availability",
884            availability::define_api(
885                &Default::default(),
886                MockBase::instance(),
887                "0.0.1".parse().unwrap(),
888            )
889            .unwrap(),
890        )
891        .unwrap()
892        .register_module(
893            "node",
894            node::define_api(
895                &Default::default(),
896                MockBase::instance(),
897                "0.0.1".parse().unwrap(),
898            )
899            .unwrap(),
900        )
901        .unwrap()
902        .register_module(
903            "status",
904            status::define_api(
905                &Default::default(),
906                MockBase::instance(),
907                "0.0.1".parse().unwrap(),
908            )
909            .unwrap(),
910        )
911        .unwrap()
912        .module::<Error, MockBase>("mod", module_spec)
913        .unwrap()
914        .get("get_ext", |_, state| {
915            async move { state.module_state.load_latest().map_err(Error::internal) }.boxed()
916        })
917        .unwrap()
918        .post("post_ext", |req, state| {
919            async move {
920                state
921                    .module_state
922                    .store_resource(&req.integer_param("val").map_err(Error::internal)?)
923                    .map_err(Error::internal)?;
924                state
925                    .module_state
926                    .commit_version()
927                    .map_err(Error::internal)?;
928                state
929                    .hotshot_qs
930                    .skip_version()
931                    .await
932                    .map_err(Error::internal)?;
933                state.store.commit_version().map_err(Error::internal)
934            }
935            .boxed()
936        })
937        .unwrap();
938
939        let port = pick_unused_port().unwrap();
940        let _server = BackgroundTask::spawn(
941            "server",
942            app.serve(format!("0.0.0.0:{port}"), MockBase::instance()),
943        );
944
945        let client =
946            Client::<Error, MockBase>::new(format!("http://localhost:{port}").parse().unwrap());
947        assert!(client.connect(Some(Duration::from_secs(60))).await);
948
949        client.post::<()>("mod/ext/42").send().await.unwrap();
950        assert_eq!(client.get::<u64>("mod/ext").send().await.unwrap(), 42);
951
952        // Check that we can still access the built-in modules.
953        assert_eq!(
954            client
955                .get::<u64>("status/block-height")
956                .send()
957                .await
958                .unwrap(),
959            1
960        );
961        let sync_status: SyncStatus = client.get("node/sync-status").send().await.unwrap();
962        assert_eq!(
963            sync_status,
964            SyncStatus {
965                missing_blocks: 0,
966                missing_leaves: 0,
967                missing_vid_common: 1,
968                missing_vid_shares: 1,
969                pruned_height: None
970            }
971        );
972        assert_eq!(
973            client
974                .get::<MockHeader>("availability/header/0")
975                .send()
976                .await
977                .unwrap()
978                .block_number,
979            0
980        );
981    }
982}