Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ bothan-coinmarketcap = { path = "bothan-coinmarketcap", version = "0.0.1" }
bothan-htx = { path = "bothan-htx", version = "0.0.1" }
bothan-kraken = { path = "bothan-kraken", version = "0.0.1" }
bothan-okx = { path = "bothan-okx", version = "0.0.1" }
bothan-band = { path = "bothan-band", version = "0.0.1" }

anyhow = "1.0.86"
async-trait = "0.1.77"
Expand Down
2 changes: 1 addition & 1 deletion bothan-api/server-cli/src/commands/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ fn export_key(config: &AppConfig) -> anyhow::Result<()> {
read(&config.monitoring.path).with_context(|| "Failed to read monitoring key file")?;
let pk = String::from_utf8(pkb).with_context(|| "Failed to parse monitoring key file")?;
println!("Private Key");
println!("{}", pk);
println!("{pk}");
Ok(())
}

Expand Down
6 changes: 3 additions & 3 deletions bothan-api/server-cli/src/commands/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl RequestCli {
let client = match GrpcClient::connect(&uri).await {
Ok(client) => client,
Err(e) => {
eprintln!("Failed to connect to server: {:#?}", e);
eprintln!("Failed to connect to server: {e:#?}");
std::process::exit(1);
}
};
Expand All @@ -71,7 +71,7 @@ impl RequestCli {
.get_info()
.await
.with_context(|| "Failed to get info")?;
println!("{:#?}", info);
println!("{info:#?}");
}
RequestSubCommand::UpdateRegistry { ipfs_hash, version } => {
client
Expand All @@ -98,7 +98,7 @@ impl RequestCli {
.get_prices(&ids)
.await
.with_context(|| "Failed to get prices")?;
println!("{:#?}", prices);
println!("{prices:#?}");
}
}
Ok(())
Expand Down
2 changes: 2 additions & 0 deletions bothan-api/server-cli/src/commands/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,8 @@ async fn init_crypto_opts(
add_worker_opts(&mut worker_opts, &source.htx).await?;
add_worker_opts(&mut worker_opts, &source.kraken).await?;
add_worker_opts(&mut worker_opts, &source.okx).await?;
add_worker_opts(&mut worker_opts, &source.band1).await?;
add_worker_opts(&mut worker_opts, &source.band2).await?;

Ok(worker_opts)
}
Expand Down
2 changes: 1 addition & 1 deletion bothan-api/server-cli/src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl<T> Exitable<T> for anyhow::Result<T> {
match self {
Ok(t) => t,
Err(e) => {
eprintln!("{:?}", e);
eprintln!("{e:?}");
std::process::exit(code);
}
}
Expand Down
2 changes: 1 addition & 1 deletion bothan-api/server-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ async fn main() {
let cli = match Cli::try_parse() {
Ok(cli) => cli,
Err(e) => {
eprintln!("{}", e);
eprintln!("{e}");
std::process::exit(1);
}
};
Expand Down
1 change: 1 addition & 0 deletions bothan-api/server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ bothan-coinmarketcap = { workspace = true }
bothan-htx = { workspace = true }
bothan-kraken = { workspace = true }
bothan-okx = { workspace = true }
bothan-band = { workspace = true }

async-trait = { workspace = true }
chrono = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion bothan-api/server/src/config/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ impl Display for LogLevel {
LogLevel::Warn => "warn".to_string(),
LogLevel::Error => "error".to_string(),
};
write!(f, "{}", str)
write!(f, "{str}")
}
}

Expand Down
6 changes: 6 additions & 0 deletions bothan-api/server/src/config/manager/crypto_info/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ pub struct CryptoSourceConfigs {
pub kraken: Option<bothan_kraken::WorkerOpts>,
/// OKX worker options.
pub okx: Option<bothan_okx::WorkerOpts>,
/// Band1 worker options.
pub band1: Option<bothan_band::WorkerOpts>,
/// Band2 worker options.
pub band2: Option<bothan_band::WorkerOpts>,
}

impl CryptoSourceConfigs {
Expand All @@ -47,6 +51,8 @@ impl CryptoSourceConfigs {
htx: Some(bothan_htx::WorkerOpts::default()),
kraken: Some(bothan_kraken::WorkerOpts::default()),
okx: Some(bothan_okx::WorkerOpts::default()),
band1: Some(bothan_band::WorkerOpts::default()),
band2: Some(bothan_band::WorkerOpts::default()),
}
}
}
31 changes: 31 additions & 0 deletions bothan-band/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
[package]
name = "bothan-band"
version = "0.0.1"
description = "Rust client for the Band source with Bothan integration"
edition.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
bothan-lib = { workspace = true }

async-trait = { workspace = true }
chrono = { workspace = true }
humantime-serde = { workspace = true }
itertools = { workspace = true }
reqwest = { workspace = true }
rust_decimal = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
tokio-util = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }

[dev-dependencies]
mockito = { workspace = true }


[package.metadata.cargo-machete]
ignored = ["humantime-serde"]
26 changes: 26 additions & 0 deletions bothan-band/src/api.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! Band REST API client implementation.
//!
//! This module provides types and utilities for interacting with the Band REST API,
//! including configuration, request execution, error handling, and response deserialization.
//!
//! The module provides:
//!
//! - [`builder`] — A builder pattern for creating [`RestApi`] clients with optional parameters like base URL and API key.
//! - [`rest`] — Core API client implementation, including HTTP request logic and integration with Bothan's `AssetInfoProvider` trait.
//! - [`types`] — Data types that represent Band REST API responses such as [`Price`](types::Price)
//! - [`error`] — Custom error types used during API client configuration and request processing.
//!
//! # Integration with Workers
//!
//! This module is intended to be used by worker implementations (such as [`Worker`](`crate::worker::Worker`))
//! that periodically query Band for asset data. The [`RestApi`] implements the
//! [`AssetInfoProvider`](bothan_lib::worker::rest::AssetInfoProvider) trait, which allows
//! Band responses to be translated into Bothan-compatible asset updates.

pub use builder::RestApiBuilder;
pub use rest::RestApi;

pub mod builder;
pub mod error;
pub mod rest;
pub mod types;
100 changes: 100 additions & 0 deletions bothan-band/src/api/builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//! Builder for configuring and constructing `BandAPI`.
//!
//! This module provides a builder for constructing [`RestApi`] clients used
//! to interact with the Band REST API. The builder supports optional configuration
//! of base URL.
//!
//! The module provides:
//!
//! - The [`RestApiBuilder`] for REST API building
//! - Supports setting the API base URL
//! - Automatically uses the default Band URL when parameters are omitted during the [`build`](`RestApiBuilder::build`) call

use reqwest::ClientBuilder;
use reqwest::header::HeaderMap;
use url::Url;

use crate::api::RestApi;
use crate::api::error::BuildError;
use crate::api::types::DEFAULT_URL;

/// Builder for creating instances of [`RestApi`].
///
/// The `RestApiBuilder` provides a builder pattern for setting up a [`RestApi`] instance
/// by allowing users to specify optional configuration parameters such as the base URL.
///
/// # Example
/// ```
/// use bothan_band::api::RestApiBuilder;
///
/// #[tokio::main]
/// async fn main() {
/// let api = RestApiBuilder::default()
/// .with_url("https://bandsource-url.com")
/// .build()
/// .unwrap();
/// }
/// ```
pub struct RestApiBuilder {
/// Base URL of the Band REST API.
url: String,
}

impl RestApiBuilder {
/// Creates a new `RestApiBuilder` with the specified configuration.
///
/// This method allows manual initialization of the builder using
/// a required URL string.
///
/// # Examples
///
/// ```
/// use bothan_band::api::RestApiBuilder;
///
/// let builder = RestApiBuilder::new(
/// "https://bandsource-url.com",
/// );
/// ```
pub fn new<T>(url: T) -> Self
where
T: Into<String>,
{
RestApiBuilder { url: url.into() }
}

/// Sets the URL for the Band API.
/// The default URL is `DEFAULT_URL`.
pub fn with_url(mut self, url: &str) -> Self {
self.url = url.into();
self
}

/// Builds the [`RestApi`] instance.
///
/// This method consumes the builder and attempts to create a fully configured client.
///
/// # Errors
///
/// Returns a [`BuildError`] if:
/// - The URL is invalid
/// - The HTTP client fails to build
pub fn build(self) -> Result<RestApi, BuildError> {
let headers = HeaderMap::new();

let parsed_url = Url::parse(&self.url)?;

let client = ClientBuilder::new().default_headers(headers).build()?;

Ok(RestApi::new(parsed_url, client))
}
}

impl Default for RestApiBuilder {
/// Creates a new `BandRestAPIBuilder` with the
/// default URL.
fn default() -> Self {
RestApiBuilder {
url: DEFAULT_URL.into(),
}
}
}
65 changes: 65 additions & 0 deletions bothan-band/src/api/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
//! Error types for Band REST API client operations.
//!
//! This module provides custom error types used throughout the Band REST API integration,
//! particularly for REST API client configuration and concurrent background data fetching.

use thiserror::Error;

/// Errors from initializing the Band REST API builder.
///
/// These errors can occur during the initialization and configuration of the HTTP client
/// or while constructing request parameters.
#[derive(Debug, Error)]
pub enum BuildError {
/// Indicates the provided URL was invalid.
#[error("invalid url")]
InvalidURL(#[from] url::ParseError),

/// Indicates an HTTP header value was invalid or contained prohibited characters.
#[error("invalid header value")]
InvalidHeaderValue(#[from] reqwest::header::InvalidHeaderValue),

/// Represents general failures during HTTP client construction (e.g., TLS configuration issues).
#[error("reqwest error: {0}")]
FailedToBuild(#[from] reqwest::Error),
}

/// General errors from Band API operations.
///
/// These errors typically occur during API calls, response parsing, or data validation.
#[derive(Debug, Error)]
pub enum Error {
/// Indicates the requested limit is too high (must be <= 5000).
#[error("limit must be lower or equal to 5000")]
LimitTooHigh,

/// Indicates an HTTP request failure due to network issues or HTTP errors.
#[error("failed request: {0}")]
FailedRequest(#[from] reqwest::Error),
}

/// Errors from fetching and handling data from the Band REST API.
///
/// These errors typically occur during API calls, response parsing, or data validation.
#[derive(Debug, Error)]
pub enum ProviderError {
/// Indicates that an ID in the request is not a valid integer.
#[error("ids contains non integer value")]
InvalidId,

/// Indicates HTTP request failure due to network issues or HTTP errors.
#[error("failed to fetch tickers: {0}")]
RequestError(#[from] reqwest::Error),

/// Indicates a failure to parse the API response.
#[error("parse error: {0}")]
ParseError(#[from] ParseError),
}

/// Errors that can occur while parsing Band API responses.
#[derive(Debug, Error)]
pub enum ParseError {
/// Indicates that the price value is not a valid number (NaN).
#[error("price is NaN")]
InvalidPrice,
}
Loading