1use std::{fmt, time::Duration};
22
23use chrono::{NaiveDate, NaiveTime};
24use reqwest::{
25 StatusCode, Url,
26 header::{AUTHORIZATION, HeaderMap, HeaderValue},
27};
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30
31pub const DEFAULT_BASE_URL: &str = "https://api.sobry.co/v2/";
33
34#[derive(Clone)]
36pub struct Client {
37 http: reqwest::Client,
38 endpoint_url: Url,
39}
40
41impl Client {
42 pub fn new(api_key: impl AsRef<str>) -> Result<Self, Error> {
44 ClientBuilder::new(api_key).build()
45 }
46
47 pub fn builder(api_key: impl AsRef<str>) -> ClientBuilder {
49 ClientBuilder::new(api_key)
50 }
51
52 pub async fn daily_prices(
54 &self,
55 request: &DailyPricesRequest,
56 ) -> Result<Vec<DailyPrice>, Error> {
57 request.validate()?;
58
59 let response = self
60 .http
61 .get(self.endpoint_url.clone())
62 .query(request)
63 .send()
64 .await
65 .map_err(Error::Request)?;
66 let status = response.status();
67 let bytes = response.bytes().await.map_err(Error::Request)?;
68
69 if !status.is_success() {
70 let body = String::from_utf8_lossy(&bytes).into_owned();
71 let api_error = serde_json::from_slice(&bytes).unwrap_or_default();
72 return Err(Error::Api {
73 status,
74 error: api_error,
75 body,
76 });
77 }
78
79 serde_json::from_slice(&bytes).map_err(|source| Error::InvalidResponse {
80 source,
81 body: String::from_utf8_lossy(&bytes).into_owned(),
82 })
83 }
84}
85
86impl fmt::Debug for Client {
87 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88 formatter
89 .debug_struct("Client")
90 .field("endpoint_url", &self.endpoint_url)
91 .field("authorization", &"<redacted>")
92 .finish_non_exhaustive()
93 }
94}
95
96pub struct ClientBuilder {
98 api_key: String,
99 base_url: String,
100 timeout: Duration,
101}
102
103impl fmt::Debug for ClientBuilder {
104 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
105 formatter
106 .debug_struct("ClientBuilder")
107 .field("api_key", &"<redacted>")
108 .field("base_url", &self.base_url)
109 .field("timeout", &self.timeout)
110 .finish()
111 }
112}
113
114impl ClientBuilder {
115 fn new(api_key: impl AsRef<str>) -> Self {
116 Self {
117 api_key: api_key.as_ref().to_owned(),
118 base_url: DEFAULT_BASE_URL.to_owned(),
119 timeout: Duration::from_secs(30),
120 }
121 }
122
123 pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
125 self.base_url = base_url.into();
126 self
127 }
128
129 pub fn timeout(mut self, timeout: Duration) -> Self {
131 self.timeout = timeout;
132 self
133 }
134
135 pub fn build(self) -> Result<Client, Error> {
137 if self.api_key.trim().is_empty() {
138 return Err(Error::InvalidApiKey);
139 }
140
141 let mut authorization = HeaderValue::from_str(&format!("Bearer {}", self.api_key))
142 .map_err(|_| Error::InvalidApiKey)?;
143 authorization.set_sensitive(true);
144 let mut headers = HeaderMap::new();
145 headers.insert(AUTHORIZATION, authorization);
146
147 let normalized = format!("{}/", self.base_url.trim_end_matches('/'));
148 let base_url = Url::parse(&normalized).map_err(Error::InvalidBaseUrl)?;
149 let endpoint_url = base_url
150 .join("user/daily-prices")
151 .map_err(Error::InvalidBaseUrl)?;
152 let http = reqwest::Client::builder()
153 .default_headers(headers)
154 .timeout(self.timeout)
155 .user_agent(concat!("sobry-api/", env!("CARGO_PKG_VERSION")))
156 .build()
157 .map_err(Error::BuildClient)?;
158
159 Ok(Client { http, endpoint_url })
160 }
161}
162
163#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
165#[serde(rename_all = "camelCase")]
166pub struct DailyPricesRequest {
167 #[serde(skip_serializing_if = "Option::is_none")]
168 day: Option<NaiveDate>,
169 #[serde(skip_serializing_if = "Option::is_none")]
170 days: Option<u8>,
171 #[serde(skip_serializing_if = "Option::is_none")]
172 granularity: Option<Granularity>,
173 #[serde(skip_serializing_if = "Option::is_none")]
174 tax_mode: Option<TaxMode>,
175}
176
177impl DailyPricesRequest {
178 pub fn new() -> Self {
180 Self::default()
181 }
182
183 pub fn day(mut self, day: NaiveDate) -> Self {
185 self.day = Some(day);
186 self
187 }
188
189 pub fn days(mut self, days: u8) -> Self {
193 self.days = Some(days);
194 self
195 }
196
197 pub fn granularity(mut self, granularity: Granularity) -> Self {
199 self.granularity = Some(granularity);
200 self
201 }
202
203 pub fn tax_mode(mut self, tax_mode: TaxMode) -> Self {
205 self.tax_mode = Some(tax_mode);
206 self
207 }
208
209 fn validate(&self) -> Result<(), Error> {
210 match self.days {
211 Some(days) if days > 10 => Err(Error::InvalidDays(days)),
212 _ => Ok(()),
213 }
214 }
215}
216
217#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
219pub enum Granularity {
220 #[serde(rename = "15m")]
222 QuarterHour,
223 #[serde(rename = "1h")]
225 Hour,
226}
227
228#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
230pub enum TaxMode {
231 #[serde(rename = "ht")]
233 ExcludingTax,
234 #[serde(rename = "ttc")]
236 IncludingTax,
237}
238
239#[derive(Clone, Debug, PartialEq, Deserialize)]
241#[serde(rename_all = "camelCase")]
242pub struct DailyPrice {
243 pub date: NaiveDate,
245 pub time: NaiveTime,
247 pub price: f64,
249 pub raw_price_amount: f64,
251 pub color_label: ColorLabel,
253 pub color: String,
255 pub estimated: bool,
257}
258
259#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)]
261#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
262pub enum ColorLabel {
263 Green,
264 Orange,
265 Red,
266 #[serde(other)]
268 Unknown,
269}
270
271#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
275pub struct ApiError {
276 #[serde(default, alias = "error")]
278 pub code: Option<String>,
279 #[serde(default)]
281 pub message: Option<String>,
282 #[serde(flatten)]
284 pub details: serde_json::Map<String, Value>,
285}
286
287#[derive(Debug, thiserror::Error)]
289pub enum Error {
290 #[error("the Sobry API key is empty or is not a valid HTTP header value")]
291 InvalidApiKey,
292 #[error("days must be between 0 and 10, got {0}")]
293 InvalidDays(u8),
294 #[error("invalid Sobry base URL")]
295 InvalidBaseUrl(#[source] url::ParseError),
296 #[error("failed to build HTTP client")]
297 BuildClient(#[source] reqwest::Error),
298 #[error("Sobry request failed")]
299 Request(#[source] reqwest::Error),
300 #[error("Sobry API returned HTTP {status}: {body}")]
301 Api {
302 status: StatusCode,
303 error: ApiError,
304 body: String,
305 },
306 #[error("Sobry returned an invalid success response")]
307 InvalidResponse {
308 #[source]
309 source: serde_json::Error,
310 body: String,
311 },
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317 use tokio::io::{AsyncReadExt, AsyncWriteExt};
318
319 #[test]
320 fn serializes_documented_query_names_and_values() {
321 let request = DailyPricesRequest::new()
322 .day(NaiveDate::from_ymd_opt(2026, 6, 12).unwrap())
323 .days(3)
324 .granularity(Granularity::QuarterHour)
325 .tax_mode(TaxMode::IncludingTax);
326
327 let query = serde_urlencoded::to_string(request).unwrap();
328 assert_eq!(query, "day=2026-06-12&days=3&granularity=15m&taxMode=ttc");
329 }
330
331 #[test]
332 fn rejects_more_than_ten_additional_days() {
333 assert!(matches!(
334 DailyPricesRequest::new().days(11).validate(),
335 Err(Error::InvalidDays(11))
336 ));
337 }
338
339 #[test]
340 fn deserializes_documented_response() {
341 let json = r##"[{"date":"2026-06-12","time":"11:15","color":"#6CC264","colorLabel":"GREEN","price":0.07194,"rawPriceAmount":-0.00001,"estimated":false}]"##;
342 let prices: Vec<DailyPrice> = serde_json::from_str(json).unwrap();
343
344 assert_eq!(prices[0].date.to_string(), "2026-06-12");
345 assert_eq!(prices[0].time.to_string(), "11:15:00");
346 assert_eq!(prices[0].color_label, ColorLabel::Green);
347 assert_eq!(prices[0].raw_price_amount, -0.00001);
348 assert!(!prices[0].estimated);
349 }
350
351 #[test]
352 fn redacts_key_from_debug_output() {
353 let client = Client::new("sob_apikey_a-secret").unwrap();
354 let debug = format!("{client:?}");
355 assert!(!debug.contains("a-secret"));
356 assert!(debug.contains("<redacted>"));
357
358 let builder_debug = format!("{:?}", Client::builder("sob_apikey_a-secret"));
359 assert!(!builder_debug.contains("a-secret"));
360 assert!(builder_debug.contains("<redacted>"));
361 }
362
363 #[tokio::test]
364 async fn sends_authenticated_request_and_decodes_response() {
365 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
366 let address = listener.local_addr().unwrap();
367 let server = tokio::spawn(async move {
368 let (mut stream, _) = listener.accept().await.unwrap();
369 let mut buffer = vec![0; 4096];
370 let size = stream.read(&mut buffer).await.unwrap();
371 let request = String::from_utf8_lossy(&buffer[..size]);
372 assert!(request.starts_with(
373 "GET /v2/user/daily-prices?days=1&granularity=1h&taxMode=ttc HTTP/1.1"
374 ));
375 assert!(
376 request
377 .to_ascii_lowercase()
378 .contains("authorization: bearer sob_apikey_test")
379 );
380
381 let body = r##"[{"date":"2026-06-12","time":"00:00","price":0.18,"rawPriceAmount":0.11,"colorLabel":"RED","color":"#F03131","estimated":false}]"##;
382 let response = format!(
383 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
384 body.len()
385 );
386 stream.write_all(response.as_bytes()).await.unwrap();
387 });
388
389 let client = Client::builder("sob_apikey_test")
390 .base_url(format!("http://{address}/v2"))
391 .build()
392 .unwrap();
393 let prices = client
394 .daily_prices(
395 &DailyPricesRequest::new()
396 .days(1)
397 .granularity(Granularity::Hour)
398 .tax_mode(TaxMode::IncludingTax),
399 )
400 .await
401 .unwrap();
402
403 server.await.unwrap();
404 assert_eq!(prices.len(), 1);
405 assert_eq!(prices[0].color_label, ColorLabel::Red);
406 }
407}