use std::{fmt, time::Duration};
use chrono::{NaiveDate, NaiveTime};
use reqwest::{
StatusCode, Url,
header::{AUTHORIZATION, HeaderMap, HeaderValue},
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const DEFAULT_BASE_URL: &str = "https://api.sobry.co/v2/";
#[derive(Clone)]
pub struct Client {
http: reqwest::Client,
endpoint_url: Url,
}
impl Client {
pub fn new(api_key: impl AsRef<str>) -> Result<Self, Error> {
ClientBuilder::new(api_key).build()
}
pub fn builder(api_key: impl AsRef<str>) -> ClientBuilder {
ClientBuilder::new(api_key)
}
pub async fn daily_prices(
&self,
request: &DailyPricesRequest,
) -> Result<Vec<DailyPrice>, Error> {
request.validate()?;
let response = self
.http
.get(self.endpoint_url.clone())
.query(request)
.send()
.await
.map_err(Error::Request)?;
let status = response.status();
let bytes = response.bytes().await.map_err(Error::Request)?;
if !status.is_success() {
let body = String::from_utf8_lossy(&bytes).into_owned();
let api_error = serde_json::from_slice(&bytes).unwrap_or_default();
return Err(Error::Api {
status,
error: api_error,
body,
});
}
serde_json::from_slice(&bytes).map_err(|source| Error::InvalidResponse {
source,
body: String::from_utf8_lossy(&bytes).into_owned(),
})
}
}
impl fmt::Debug for Client {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Client")
.field("endpoint_url", &self.endpoint_url)
.field("authorization", &"<redacted>")
.finish_non_exhaustive()
}
}
pub struct ClientBuilder {
api_key: String,
base_url: String,
timeout: Duration,
}
impl fmt::Debug for ClientBuilder {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ClientBuilder")
.field("api_key", &"<redacted>")
.field("base_url", &self.base_url)
.field("timeout", &self.timeout)
.finish()
}
}
impl ClientBuilder {
fn new(api_key: impl AsRef<str>) -> Self {
Self {
api_key: api_key.as_ref().to_owned(),
base_url: DEFAULT_BASE_URL.to_owned(),
timeout: Duration::from_secs(30),
}
}
pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = base_url.into();
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn build(self) -> Result<Client, Error> {
if self.api_key.trim().is_empty() {
return Err(Error::InvalidApiKey);
}
let mut authorization = HeaderValue::from_str(&format!("Bearer {}", self.api_key))
.map_err(|_| Error::InvalidApiKey)?;
authorization.set_sensitive(true);
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, authorization);
let normalized = format!("{}/", self.base_url.trim_end_matches('/'));
let base_url = Url::parse(&normalized).map_err(Error::InvalidBaseUrl)?;
let endpoint_url = base_url
.join("user/daily-prices")
.map_err(Error::InvalidBaseUrl)?;
let http = reqwest::Client::builder()
.default_headers(headers)
.timeout(self.timeout)
.user_agent(concat!("sobry-api/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(Error::BuildClient)?;
Ok(Client { http, endpoint_url })
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DailyPricesRequest {
#[serde(skip_serializing_if = "Option::is_none")]
day: Option<NaiveDate>,
#[serde(skip_serializing_if = "Option::is_none")]
days: Option<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
granularity: Option<Granularity>,
#[serde(skip_serializing_if = "Option::is_none")]
tax_mode: Option<TaxMode>,
}
impl DailyPricesRequest {
pub fn new() -> Self {
Self::default()
}
pub fn day(mut self, day: NaiveDate) -> Self {
self.day = Some(day);
self
}
pub fn days(mut self, days: u8) -> Self {
self.days = Some(days);
self
}
pub fn granularity(mut self, granularity: Granularity) -> Self {
self.granularity = Some(granularity);
self
}
pub fn tax_mode(mut self, tax_mode: TaxMode) -> Self {
self.tax_mode = Some(tax_mode);
self
}
fn validate(&self) -> Result<(), Error> {
match self.days {
Some(days) if days > 10 => Err(Error::InvalidDays(days)),
_ => Ok(()),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub enum Granularity {
#[serde(rename = "15m")]
QuarterHour,
#[serde(rename = "1h")]
Hour,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub enum TaxMode {
#[serde(rename = "ht")]
ExcludingTax,
#[serde(rename = "ttc")]
IncludingTax,
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DailyPrice {
pub date: NaiveDate,
pub time: NaiveTime,
pub price: f64,
pub raw_price_amount: f64,
pub color_label: ColorLabel,
pub color: String,
pub estimated: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ColorLabel {
Green,
Orange,
Red,
#[serde(other)]
Unknown,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
pub struct ApiError {
#[serde(default, alias = "error")]
pub code: Option<String>,
#[serde(default)]
pub message: Option<String>,
#[serde(flatten)]
pub details: serde_json::Map<String, Value>,
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("the Sobry API key is empty or is not a valid HTTP header value")]
InvalidApiKey,
#[error("days must be between 0 and 10, got {0}")]
InvalidDays(u8),
#[error("invalid Sobry base URL")]
InvalidBaseUrl(#[source] url::ParseError),
#[error("failed to build HTTP client")]
BuildClient(#[source] reqwest::Error),
#[error("Sobry request failed")]
Request(#[source] reqwest::Error),
#[error("Sobry API returned HTTP {status}: {body}")]
Api {
status: StatusCode,
error: ApiError,
body: String,
},
#[error("Sobry returned an invalid success response")]
InvalidResponse {
#[source]
source: serde_json::Error,
body: String,
},
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[test]
fn serializes_documented_query_names_and_values() {
let request = DailyPricesRequest::new()
.day(NaiveDate::from_ymd_opt(2026, 6, 12).unwrap())
.days(3)
.granularity(Granularity::QuarterHour)
.tax_mode(TaxMode::IncludingTax);
let query = serde_urlencoded::to_string(request).unwrap();
assert_eq!(query, "day=2026-06-12&days=3&granularity=15m&taxMode=ttc");
}
#[test]
fn rejects_more_than_ten_additional_days() {
assert!(matches!(
DailyPricesRequest::new().days(11).validate(),
Err(Error::InvalidDays(11))
));
}
#[test]
fn deserializes_documented_response() {
let json = r##"[{"date":"2026-06-12","time":"11:15","color":"#6CC264","colorLabel":"GREEN","price":0.07194,"rawPriceAmount":-0.00001,"estimated":false}]"##;
let prices: Vec<DailyPrice> = serde_json::from_str(json).unwrap();
assert_eq!(prices[0].date.to_string(), "2026-06-12");
assert_eq!(prices[0].time.to_string(), "11:15:00");
assert_eq!(prices[0].color_label, ColorLabel::Green);
assert_eq!(prices[0].raw_price_amount, -0.00001);
assert!(!prices[0].estimated);
}
#[test]
fn redacts_key_from_debug_output() {
let client = Client::new("sob_apikey_a-secret").unwrap();
let debug = format!("{client:?}");
assert!(!debug.contains("a-secret"));
assert!(debug.contains("<redacted>"));
let builder_debug = format!("{:?}", Client::builder("sob_apikey_a-secret"));
assert!(!builder_debug.contains("a-secret"));
assert!(builder_debug.contains("<redacted>"));
}
#[tokio::test]
async fn sends_authenticated_request_and_decodes_response() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buffer = vec![0; 4096];
let size = stream.read(&mut buffer).await.unwrap();
let request = String::from_utf8_lossy(&buffer[..size]);
assert!(request.starts_with(
"GET /v2/user/daily-prices?days=1&granularity=1h&taxMode=ttc HTTP/1.1"
));
assert!(
request
.to_ascii_lowercase()
.contains("authorization: bearer sob_apikey_test")
);
let body = r##"[{"date":"2026-06-12","time":"00:00","price":0.18,"rawPriceAmount":0.11,"colorLabel":"RED","color":"#F03131","estimated":false}]"##;
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
stream.write_all(response.as_bytes()).await.unwrap();
});
let client = Client::builder("sob_apikey_test")
.base_url(format!("http://{address}/v2"))
.build()
.unwrap();
let prices = client
.daily_prices(
&DailyPricesRequest::new()
.days(1)
.granularity(Granularity::Hour)
.tax_mode(TaxMode::IncludingTax),
)
.await
.unwrap();
server.await.unwrap();
assert_eq!(prices.len(), 1);
assert_eq!(prices[0].color_label, ColorLabel::Red);
}
}