energy-api 0.5.0

Rust client and server implementation for German energy market API-Webdienste (MaKo)
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! HTTP client for the Control Measures API v1 (`controlMeasuresV1.yaml`).
//!
//! Covers all eight endpoints across the four workflow roles:
//!
//! | Role  | Direction | Endpoints |
//! |-------|-----------|-----------|
//! | NB/LF | → MSB | `konfiguration`, `initialZustand` |
//! | MSB   | → NB/LF | `vorlaeufigePositiveAntwort`, `vorlaeufigeNegativeAntwort`, `positiveAntwort`, `negativeAntwort`, `informationAnweisung` |
//! | NB/LF/MSB/ÜNB | → MSB | `information` |
//!
//! ## Content-layer security (TR-03116-3)
//!
//! Enable automatic `DIGEST` + `SIGNATURE` signing via [`ControlMeasuresClient::with_signing`]
//! (requires feature `crypto`).

use reqwest::{Client, StatusCode};
use url::Url;
use uuid::Uuid;

use crate::error::Error;
use crate::models::electricity::{
    CommandControl, CommandRegular, LocationId, PreliminaryStatePositive, ReasonNegative,
    ReferenceId, StateNegative, StatePositive, StateUnknown,
};

#[cfg(feature = "crypto")]
use p256::ecdsa::SigningKey;

/// HTTP client for the [EDI-Energy Control Measures API v1][spec].
///
/// Build the underlying [`reqwest::Client`] via [`crate::transport::http::build_client`]
/// with the appropriate mTLS configuration, then pass it to [`Self::new`].
///
/// All requests are answered synchronously with HTTP 202 Accepted; the
/// business-logic response arrives via a separate asynchronous callback.
///
/// [spec]: https://github.com/EDI-Energy/api-electricity/blob/main/api/controlMeasures/controlMeasuresV1.yaml
#[derive(Clone, Debug)]
pub struct ControlMeasuresClient {
    inner: Client,
    base_url: Url,
    #[cfg(feature = "crypto")]
    signing_key: Option<SigningKey>,
}

impl ControlMeasuresClient {
    /// Create a client with the provided `reqwest::Client`.
    pub fn new(base_url: Url, client: Client) -> Self {
        Self {
            inner: client,
            base_url,
            #[cfg(feature = "crypto")]
            signing_key: None,
        }
    }

    /// Enable TR-03116-3 content-layer signing on every outgoing request.
    ///
    /// The `key` must belong to an EMT.API certificate from the BSI SM-PKI.
    /// Every request will carry `DIGEST` and `SIGNATURE` HTTP headers.
    #[cfg(feature = "crypto")]
    pub fn with_signing(mut self, key: SigningKey) -> Self {
        self.signing_key = Some(key);
        self
    }

    // ── Anweisung Steuerbefehl (NB/LF → MSB) ─────────────────────────────────

    /// `POST /[Post]/steuerbefehl/konfiguration/`
    ///
    /// Instruct the MSB to regulate a location to a specific maximum power
    /// value starting at `command.execution_time_from`.
    pub async fn send_konfiguration(
        &self,
        transaction_id: Uuid,
        creation_date_time: &str,
        location_id: &LocationId,
        command: &CommandControl,
        initial_transaction_id: Option<Uuid>,
    ) -> Result<(), Error> {
        let command_json = serde_json::to_string(command)?;
        let mut url = self.url("[Post]/steuerbefehl/konfiguration/")?;
        {
            let mut qp = url.query_pairs_mut();
            qp.append_pair("locationId", &location_id.to_string());
            qp.append_pair("commandControl", &command_json);
        }
        let mut req = self
            .inner
            .post(url.clone())
            .header("transactionId", transaction_id.to_string())
            .header("creationDateTime", creation_date_time);
        req = self.sign_if_enabled(
            req,
            url.as_str(),
            &[],
            creation_date_time,
            &transaction_id.to_string(),
        )?;
        if let Some(id) = initial_transaction_id {
            req = req.header("initialTransactionId", id.to_string());
        }
        check_accepted(req.send().await?).await
    }

    /// `POST /[Post]/steuerbefehl/initialZustand/`
    ///
    /// Instruct the MSB to reset a location to its initial / uncontrolled
    /// state starting at `command.execution_time_from`.
    pub async fn send_initial_zustand(
        &self,
        transaction_id: Uuid,
        creation_date_time: &str,
        location_id: &LocationId,
        command: &CommandRegular,
        initial_transaction_id: Option<Uuid>,
    ) -> Result<(), Error> {
        let command_json = serde_json::to_string(command)?;
        let mut url = self.url("[Post]/steuerbefehl/initialZustand/")?;
        {
            let mut qp = url.query_pairs_mut();
            qp.append_pair("locationId", &location_id.to_string());
            qp.append_pair("commandRegular", &command_json);
        }
        let mut req = self
            .inner
            .post(url.clone())
            .header("transactionId", transaction_id.to_string())
            .header("creationDateTime", creation_date_time);
        req = self.sign_if_enabled(
            req,
            url.as_str(),
            &[],
            creation_date_time,
            &transaction_id.to_string(),
        )?;
        if let Some(id) = initial_transaction_id {
            req = req.header("initialTransactionId", id.to_string());
        }
        check_accepted(req.send().await?).await
    }

    // ── Mitteilung zum weiteren Vorgehen (MSB → NB/LF) ───────────────────────

    /// `POST /[Post]/steuerbefehl/vorlaeufigePositiveAntwort/`
    ///
    /// Preliminary positive response: the command can in principle be executed.
    pub async fn send_vorlaeufigepositiveantwort(
        &self,
        transaction_id: Uuid,
        creation_date_time: &str,
        reference_id: ReferenceId,
        location_id: &LocationId,
        state: PreliminaryStatePositive,
        initial_transaction_id: Option<Uuid>,
    ) -> Result<(), Error> {
        let payload = serde_json::json!({ "preliminaryStatePositive": state });
        let mut url = self.url("[Post]/steuerbefehl/vorlaeufigePositiveAntwort/")?;
        {
            let mut qp = url.query_pairs_mut();
            qp.append_pair("referenceId", &reference_id.to_string());
            qp.append_pair("locationId", &location_id.to_string());
            qp.append_pair("preliminaryResultPositive", &payload.to_string());
        }
        let mut req = self
            .inner
            .post(url.clone())
            .header("transactionId", transaction_id.to_string())
            .header("creationDateTime", creation_date_time);
        req = self.sign_if_enabled(
            req,
            url.as_str(),
            &[],
            creation_date_time,
            &transaction_id.to_string(),
        )?;
        if let Some(id) = initial_transaction_id {
            req = req.header("initialTransactionId", id.to_string());
        }
        check_accepted(req.send().await?).await
    }

    /// `POST /[Post]/steuerbefehl/vorlaeufigeNegativeAntwort/`
    ///
    /// Preliminary negative response: the command cannot be executed.
    pub async fn send_vorlaeufige_negative_antwort(
        &self,
        transaction_id: Uuid,
        creation_date_time: &str,
        reference_id: ReferenceId,
        location_id: &LocationId,
        state: StateNegative,
        reason: ReasonNegative,
        initial_transaction_id: Option<Uuid>,
    ) -> Result<(), Error> {
        let payload = serde_json::json!({ "stateNegative": state, "reasonNegative": reason });
        let mut url = self.url("[Post]/steuerbefehl/vorlaeufigeNegativeAntwort/")?;
        {
            let mut qp = url.query_pairs_mut();
            qp.append_pair("referenceId", &reference_id.to_string());
            qp.append_pair("locationId", &location_id.to_string());
            qp.append_pair("resultNegative", &payload.to_string());
        }
        let mut req = self
            .inner
            .post(url.clone())
            .header("transactionId", transaction_id.to_string())
            .header("creationDateTime", creation_date_time);
        req = self.sign_if_enabled(
            req,
            url.as_str(),
            &[],
            creation_date_time,
            &transaction_id.to_string(),
        )?;
        if let Some(id) = initial_transaction_id {
            req = req.header("initialTransactionId", id.to_string());
        }
        check_accepted(req.send().await?).await
    }

    // ── Antwort Steuerbefehl (MSB → NB/LF) ───────────────────────────────────

    /// `POST /[Post]/steuerbefehl/positiveAntwort/`
    ///
    /// Final positive response: the command was successfully executed.
    pub async fn send_positive_antwort(
        &self,
        transaction_id: Uuid,
        creation_date_time: &str,
        reference_id: ReferenceId,
        location_id: &LocationId,
        state: StatePositive,
        initial_transaction_id: Option<Uuid>,
    ) -> Result<(), Error> {
        let payload = serde_json::json!({ "statePositive": state });
        let mut url = self.url("[Post]/steuerbefehl/positiveAntwort/")?;
        {
            let mut qp = url.query_pairs_mut();
            qp.append_pair("referenceId", &reference_id.to_string());
            qp.append_pair("locationId", &location_id.to_string());
            qp.append_pair("resultPositive", &payload.to_string());
        }
        let mut req = self
            .inner
            .post(url.clone())
            .header("transactionId", transaction_id.to_string())
            .header("creationDateTime", creation_date_time);
        req = self.sign_if_enabled(
            req,
            url.as_str(),
            &[],
            creation_date_time,
            &transaction_id.to_string(),
        )?;
        if let Some(id) = initial_transaction_id {
            req = req.header("initialTransactionId", id.to_string());
        }
        check_accepted(req.send().await?).await
    }

    /// `POST /[Post]/steuerbefehl/negativeAntwort/`
    ///
    /// Final negative response: the command could not be executed.
    pub async fn send_negative_antwort(
        &self,
        transaction_id: Uuid,
        creation_date_time: &str,
        reference_id: ReferenceId,
        location_id: &LocationId,
        state: StateNegative,
        reason: ReasonNegative,
        initial_transaction_id: Option<Uuid>,
    ) -> Result<(), Error> {
        let payload = serde_json::json!({ "stateNegative": state, "reasonNegative": reason });
        let mut url = self.url("[Post]/steuerbefehl/negativeAntwort/")?;
        {
            let mut qp = url.query_pairs_mut();
            qp.append_pair("referenceId", &reference_id.to_string());
            qp.append_pair("locationId", &location_id.to_string());
            qp.append_pair("resultNegative", &payload.to_string());
        }
        let mut req = self
            .inner
            .post(url.clone())
            .header("transactionId", transaction_id.to_string())
            .header("creationDateTime", creation_date_time);
        req = self.sign_if_enabled(
            req,
            url.as_str(),
            &[],
            creation_date_time,
            &transaction_id.to_string(),
        )?;
        if let Some(id) = initial_transaction_id {
            req = req.header("initialTransactionId", id.to_string());
        }
        check_accepted(req.send().await?).await
    }

    // ── Information Steuerbefehl Anweisender (MSB → NB/LF) ──────────────────

    /// `POST /[Post]/steuerbefehl/informationAnweisung/`
    ///
    /// Inform the commanding party that the final status is not yet known.
    pub async fn send_information_anweisung(
        &self,
        transaction_id: Uuid,
        creation_date_time: &str,
        reference_id: ReferenceId,
        location_id: &LocationId,
        state: StateUnknown,
        initial_transaction_id: Option<Uuid>,
    ) -> Result<(), Error> {
        let payload = serde_json::json!({ "stateUnknown": state });
        let mut url = self.url("[Post]/steuerbefehl/informationAnweisung/")?;
        {
            let mut qp = url.query_pairs_mut();
            qp.append_pair("referenceId", &reference_id.to_string());
            qp.append_pair("locationId", &location_id.to_string());
            qp.append_pair("stateUnknown", &payload.to_string());
        }
        let mut req = self
            .inner
            .post(url.clone())
            .header("transactionId", transaction_id.to_string())
            .header("creationDateTime", creation_date_time);
        req = self.sign_if_enabled(
            req,
            url.as_str(),
            &[],
            creation_date_time,
            &transaction_id.to_string(),
        )?;
        if let Some(id) = initial_transaction_id {
            req = req.header("initialTransactionId", id.to_string());
        }
        check_accepted(req.send().await?).await
    }

    // ── Information Steuerbefehl Berechtigte (NB/LF/MSB/ÜNB → MSB) ─────────

    /// `POST /[Post]/steuerbefehl/information/`
    ///
    /// Broadcast the confirmed control command to all authorized parties.
    pub async fn send_information(
        &self,
        transaction_id: Uuid,
        creation_date_time: &str,
        location_id: &LocationId,
        partner_id: i64,
        command_control: Option<&CommandControl>,
        command_regular: Option<&CommandRegular>,
        initial_transaction_id: Option<Uuid>,
    ) -> Result<(), Error> {
        let mut url = self.url("[Post]/steuerbefehl/information/")?;
        {
            let mut qp = url.query_pairs_mut();
            qp.append_pair("locationId", &location_id.to_string());
            qp.append_pair("partnerId", &partner_id.to_string());
            if let Some(cc) = command_control {
                qp.append_pair("commandControl", &serde_json::to_string(cc)?);
            }
            if let Some(cr) = command_regular {
                qp.append_pair("commandRegular", &serde_json::to_string(cr)?);
            }
        }
        let mut req = self
            .inner
            .post(url.clone())
            .header("transactionId", transaction_id.to_string())
            .header("creationDateTime", creation_date_time);
        req = self.sign_if_enabled(
            req,
            url.as_str(),
            &[],
            creation_date_time,
            &transaction_id.to_string(),
        )?;
        if let Some(id) = initial_transaction_id {
            req = req.header("initialTransactionId", id.to_string());
        }
        check_accepted(req.send().await?).await
    }

    // ── Helpers ───────────────────────────────────────────────────────────────

    fn url(&self, path: &str) -> Result<Url, Error> {
        self.base_url.join(path).map_err(Error::Url)
    }

    /// Attach `DIGEST` and `SIGNATURE` headers when a signing key is configured.
    #[inline]
    fn sign_if_enabled(
        &self,
        req: reqwest::RequestBuilder,
        _uri: &str,
        _canonical_payload: &[u8],
        _creation_dt: &str,
        _tx_id: &str,
    ) -> Result<reqwest::RequestBuilder, Error> {
        #[cfg(feature = "crypto")]
        if let Some(key) = &self.signing_key {
            use crate::transport::content_security::{self, HEADER_DIGEST, HEADER_SIGNATURE};
            let (digest, sig) = content_security::sign_request(
                _uri,
                _canonical_payload,
                _creation_dt,
                _tx_id,
                key,
            )?;
            return Ok(req
                .header(HEADER_DIGEST, digest)
                .header(HEADER_SIGNATURE, sig));
        }
        Ok(req)
    }
}

async fn check_accepted(resp: reqwest::Response) -> Result<(), Error> {
    match resp.status() {
        StatusCode::ACCEPTED => Ok(()),
        s => Err(Error::Http {
            status: s.as_u16(),
            body: resp.text().await.unwrap_or_default(),
        }),
    }
}