sobry-api 0.1.0

Async Rust client for the Sobry.co electricity price API v2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Async client for the [Sobry API v2](https://api.sobry.co/v2/docs).
//!
//! A Sobry API key belongs to one contract, so no contract identifier is needed.
//!
//! ```no_run
//! use chrono::NaiveDate;
//! use sobry_api::{Client, DailyPricesRequest, Granularity, TaxMode};
//!
//! # async fn example() -> Result<(), sobry_api::Error> {
//! let client = Client::new(std::env::var("SOBRY_API_KEY").unwrap())?;
//! let request = DailyPricesRequest::new()
//!     .day(NaiveDate::from_ymd_opt(2026, 6, 12).unwrap())
//!     .granularity(Granularity::QuarterHour)
//!     .tax_mode(TaxMode::IncludingTax);
//! let prices = client.daily_prices(&request).await?;
//! println!("received {} price points", prices.len());
//! # Ok(())
//! # }
//! ```

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;

/// Default base URL for Sobry API v2.
pub const DEFAULT_BASE_URL: &str = "https://api.sobry.co/v2/";

/// An asynchronous Sobry API client.
#[derive(Clone)]
pub struct Client {
    http: reqwest::Client,
    endpoint_url: Url,
}

impl Client {
    /// Creates a client for a Sobry contract API key.
    pub fn new(api_key: impl AsRef<str>) -> Result<Self, Error> {
        ClientBuilder::new(api_key).build()
    }

    /// Starts configuring a client.
    pub fn builder(api_key: impl AsRef<str>) -> ClientBuilder {
        ClientBuilder::new(api_key)
    }

    /// Returns daily contract prices for the requested date range.
    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()
    }
}

/// Configuration for a [`Client`].
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),
        }
    }

    /// Overrides the API base URL, primarily for proxies and tests.
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = base_url.into();
        self
    }

    /// Sets the complete request timeout. The default is 30 seconds.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Builds the client.
    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 })
    }
}

/// Query options accepted by `GET /user/daily-prices`.
#[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 {
    /// Uses all API defaults: today, one day, 15-minute granularity, excluding tax.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the first delivery day. It defaults to today in France.
    pub fn day(mut self, day: NaiveDate) -> Self {
        self.day = Some(day);
        self
    }

    /// Includes this many days after the first day (`0..=10`).
    ///
    /// For example, `days(3)` returns four calendar days: J through J+3.
    pub fn days(mut self, days: u8) -> Self {
        self.days = Some(days);
        self
    }

    /// Sets the interval represented by each price point.
    pub fn granularity(mut self, granularity: Granularity) -> Self {
        self.granularity = Some(granularity);
        self
    }

    /// Selects whether `price` includes VAT.
    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(()),
        }
    }
}

/// Price-point granularity.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub enum Granularity {
    /// One point every 15 minutes (API default).
    #[serde(rename = "15m")]
    QuarterHour,
    /// One point per hour.
    #[serde(rename = "1h")]
    Hour,
}

/// Tax treatment of the all-inclusive `price` field.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub enum TaxMode {
    /// Price excluding VAT (`ht`, API default).
    #[serde(rename = "ht")]
    ExcludingTax,
    /// Price including VAT (`ttc`).
    #[serde(rename = "ttc")]
    IncludingTax,
}

/// One electricity-price time slot returned by Sobry.
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DailyPrice {
    /// Delivery date in the French timezone.
    pub date: NaiveDate,
    /// Start of the time slot in Europe/Paris.
    pub time: NaiveTime,
    /// All-inclusive contract price in EUR/kWh, using the requested tax mode.
    pub price: f64,
    /// Raw wholesale spot price in EUR/kWh, excluding tax.
    pub raw_price_amount: f64,
    /// Price category relative to the regulated tariff.
    pub color_label: ColorLabel,
    /// Hexadecimal display color corresponding to `color_label`.
    pub color: String,
    /// Whether this point is a forecast rather than published day-ahead data.
    pub estimated: bool,
}

/// Price category relative to the French regulated tariff (TRV).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ColorLabel {
    Green,
    Orange,
    Red,
    /// A category introduced by a future API version.
    #[serde(other)]
    Unknown,
}

/// Structured fields commonly returned by a failed API call.
///
/// Unknown fields are retained in [`Self::details`] for forward compatibility.
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
pub struct ApiError {
    /// Machine-readable API error code, when the response is JSON.
    #[serde(default, alias = "error")]
    pub code: Option<String>,
    /// Human-readable API error description, when supplied.
    #[serde(default)]
    pub message: Option<String>,
    /// Additional response fields, such as contract binding identifiers.
    #[serde(flatten)]
    pub details: serde_json::Map<String, Value>,
}

/// Errors produced by this crate.
#[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);
    }
}