use std::{future::Future, num::NonZeroUsize, time::Duration};
use reqwest::Url;
use crate::{
book::{BookFeedConfig, BookSnapshot, ReceivedAt},
pamm::protocols::metric::{
client::{MetricClient, DEFAULT_BID_ASK_CONCURRENCY},
source::MetricBookSource,
FALLBACK_PROTOCOL_SYSTEM, PROTOCOL_SYSTEM,
},
snapshot_feed::{
errors::FeedError,
http::{default_http_feed_config, run_http_poll_feed, HttpFeedConfig},
Publisher, SnapshotFeed,
},
};
#[derive(Debug, Clone)]
pub struct MetricFeed {
feed_config: HttpFeedConfig,
source: MetricBookSource,
}
pub struct MetricFeedBuilder {
protocol_system: &'static str,
book_config: BookFeedConfig,
base_url: Option<String>,
api_key: String,
bid_ask_concurrency: NonZeroUsize,
feed_config: HttpFeedConfig,
}
impl MetricFeedBuilder {
pub fn new(book_config: BookFeedConfig, api_key: String) -> Self {
Self {
book_config,
base_url: None,
api_key,
bid_ask_concurrency: DEFAULT_BID_ASK_CONCURRENCY,
feed_config: Self::default_feed_config(),
protocol_system: PROTOCOL_SYSTEM,
}
}
pub fn base_url(mut self, base_url: String) -> Self {
self.base_url = Some(base_url);
self
}
pub fn bid_ask_concurrency(mut self, requests_in_flight: NonZeroUsize) -> Self {
self.bid_ask_concurrency = requests_in_flight;
self
}
pub fn default_feed_config() -> HttpFeedConfig {
HttpFeedConfig {
poll_interval: Duration::from_secs(2),
request_timeout: Duration::from_secs(5),
max_snapshot_age: Some(Duration::from_secs(15)),
..default_http_feed_config()
}
}
pub fn with_fallback_router(mut self) -> Self {
self.protocol_system = FALLBACK_PROTOCOL_SYSTEM;
self
}
pub fn feed_config(mut self, feed_config: HttpFeedConfig) -> Self {
self.feed_config = feed_config;
self
}
pub fn build(self) -> Result<MetricFeed, FeedError> {
if self.api_key.is_empty() {
return Err(FeedError::InvalidInput("Metric trading key is empty".to_string()));
}
let chain_id = self.book_config.chain_id()?;
if let Some(base_url) = &self.base_url {
Url::parse(base_url).map_err(|error| {
FeedError::InvalidInput(format!("Metric base URL {base_url}: {error}"))
})?;
}
Ok(MetricFeed {
feed_config: self.feed_config,
source: MetricBookSource {
protocol_system: self.protocol_system,
book_config: self.book_config,
client: MetricClient::new(
self.base_url.as_deref(),
chain_id,
self.api_key,
self.bid_ask_concurrency,
),
},
})
}
}
impl SnapshotFeed for MetricFeed {
type Snapshot = BookSnapshot<ReceivedAt>;
type Error = FeedError;
fn run(
self,
publisher: Publisher<Self::Snapshot>,
) -> impl Future<Output = Result<(), FeedError>> + Send + 'static {
run_http_poll_feed(self.feed_config, publisher, self.source)
}
}
#[cfg(test)]
mod tests {
use std::{collections::HashMap, sync::Arc};
use tycho_common::models::Chain;
use super::*;
fn builder(chain: Chain) -> MetricFeedBuilder {
MetricFeedBuilder::new(
BookFeedConfig { chain, tokens: Arc::new(HashMap::new()), min_tvl_usd: 0.0 },
"secret_key".to_string(),
)
}
#[test]
fn debug_output_omits_the_api_key() {
let feed = builder(Chain::Ethereum)
.base_url("https://metric.example".to_string())
.build()
.unwrap();
let rendered = format!("{feed:?}");
assert!(!rendered.contains("secret_key"));
assert!(rendered.contains("metric.example"));
}
#[test]
fn a_base_url_that_is_not_one_is_rejected() {
let error = builder(Chain::Ethereum)
.base_url("api.metric.xyz".to_string())
.build()
.unwrap_err();
assert!(matches!(error, FeedError::InvalidInput(_)), "{error}");
}
#[test]
fn an_empty_trading_key_is_rejected() {
let config = BookFeedConfig {
chain: Chain::Ethereum,
tokens: Arc::new(HashMap::new()),
min_tvl_usd: 0.0,
};
let error = MetricFeedBuilder::new(config, String::new())
.build()
.unwrap_err();
assert!(matches!(error, FeedError::InvalidInput(_)), "{error}");
}
}