Skip to main content

sobry_api/
lib.rs

1//! Async client for the [Sobry API v2](https://api.sobry.co/v2/docs).
2//!
3//! A Sobry API key belongs to one contract, so no contract identifier is needed.
4//!
5//! ```no_run
6//! use chrono::NaiveDate;
7//! use sobry_api::{Client, DailyPricesRequest, Granularity, TaxMode};
8//!
9//! # async fn example() -> Result<(), sobry_api::Error> {
10//! let client = Client::new(std::env::var("SOBRY_API_KEY").unwrap())?;
11//! let request = DailyPricesRequest::new()
12//!     .day(NaiveDate::from_ymd_opt(2026, 6, 12).unwrap())
13//!     .granularity(Granularity::QuarterHour)
14//!     .tax_mode(TaxMode::IncludingTax);
15//! let prices = client.daily_prices(&request).await?;
16//! println!("received {} price points", prices.len());
17//! # Ok(())
18//! # }
19//! ```
20
21use 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
31/// Default base URL for Sobry API v2.
32pub const DEFAULT_BASE_URL: &str = "https://api.sobry.co/v2/";
33
34/// An asynchronous Sobry API client.
35#[derive(Clone)]
36pub struct Client {
37    http: reqwest::Client,
38    endpoint_url: Url,
39}
40
41impl Client {
42    /// Creates a client for a Sobry contract API key.
43    pub fn new(api_key: impl AsRef<str>) -> Result<Self, Error> {
44        ClientBuilder::new(api_key).build()
45    }
46
47    /// Starts configuring a client.
48    pub fn builder(api_key: impl AsRef<str>) -> ClientBuilder {
49        ClientBuilder::new(api_key)
50    }
51
52    /// Returns daily contract prices for the requested date range.
53    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
96/// Configuration for a [`Client`].
97pub 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    /// Overrides the API base URL, primarily for proxies and tests.
124    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
125        self.base_url = base_url.into();
126        self
127    }
128
129    /// Sets the complete request timeout. The default is 30 seconds.
130    pub fn timeout(mut self, timeout: Duration) -> Self {
131        self.timeout = timeout;
132        self
133    }
134
135    /// Builds the client.
136    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/// Query options accepted by `GET /user/daily-prices`.
164#[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    /// Uses all API defaults: today, one day, 15-minute granularity, excluding tax.
179    pub fn new() -> Self {
180        Self::default()
181    }
182
183    /// Sets the first delivery day. It defaults to today in France.
184    pub fn day(mut self, day: NaiveDate) -> Self {
185        self.day = Some(day);
186        self
187    }
188
189    /// Includes this many days after the first day (`0..=10`).
190    ///
191    /// For example, `days(3)` returns four calendar days: J through J+3.
192    pub fn days(mut self, days: u8) -> Self {
193        self.days = Some(days);
194        self
195    }
196
197    /// Sets the interval represented by each price point.
198    pub fn granularity(mut self, granularity: Granularity) -> Self {
199        self.granularity = Some(granularity);
200        self
201    }
202
203    /// Selects whether `price` includes VAT.
204    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/// Price-point granularity.
218#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
219pub enum Granularity {
220    /// One point every 15 minutes (API default).
221    #[serde(rename = "15m")]
222    QuarterHour,
223    /// One point per hour.
224    #[serde(rename = "1h")]
225    Hour,
226}
227
228/// Tax treatment of the all-inclusive `price` field.
229#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
230pub enum TaxMode {
231    /// Price excluding VAT (`ht`, API default).
232    #[serde(rename = "ht")]
233    ExcludingTax,
234    /// Price including VAT (`ttc`).
235    #[serde(rename = "ttc")]
236    IncludingTax,
237}
238
239/// One electricity-price time slot returned by Sobry.
240#[derive(Clone, Debug, PartialEq, Deserialize)]
241#[serde(rename_all = "camelCase")]
242pub struct DailyPrice {
243    /// Delivery date in the French timezone.
244    pub date: NaiveDate,
245    /// Start of the time slot in Europe/Paris.
246    pub time: NaiveTime,
247    /// All-inclusive contract price in EUR/kWh, using the requested tax mode.
248    pub price: f64,
249    /// Raw wholesale spot price in EUR/kWh, excluding tax.
250    pub raw_price_amount: f64,
251    /// Price category relative to the regulated tariff.
252    pub color_label: ColorLabel,
253    /// Hexadecimal display color corresponding to `color_label`.
254    pub color: String,
255    /// Whether this point is a forecast rather than published day-ahead data.
256    pub estimated: bool,
257}
258
259/// Price category relative to the French regulated tariff (TRV).
260#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)]
261#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
262pub enum ColorLabel {
263    Green,
264    Orange,
265    Red,
266    /// A category introduced by a future API version.
267    #[serde(other)]
268    Unknown,
269}
270
271/// Structured fields commonly returned by a failed API call.
272///
273/// Unknown fields are retained in [`Self::details`] for forward compatibility.
274#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
275pub struct ApiError {
276    /// Machine-readable API error code, when the response is JSON.
277    #[serde(default, alias = "error")]
278    pub code: Option<String>,
279    /// Human-readable API error description, when supplied.
280    #[serde(default)]
281    pub message: Option<String>,
282    /// Additional response fields, such as contract binding identifiers.
283    #[serde(flatten)]
284    pub details: serde_json::Map<String, Value>,
285}
286
287/// Errors produced by this crate.
288#[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}