Skip to main content

openadr/
client.rs

1//! HTTP clients for the two roles.
2//!
3//! The role is a type parameter, so the compiler enforces what the specification's scopes describe:
4//! [`Client<BusinessLogic>`] can create events, [`Client<VirtualEndNode>`] cannot, and asking for
5//! the wrong one is a compile error rather than a `403` in production.
6//!
7//! Guide, including a VEN polling loop: <https://hupe1980.github.io/openadr/docs/client/>.
8//!
9//! ```no_run
10//! use openadr::client::{Client, BusinessLogic, Credentials};
11//! # async fn run() -> Result<(), openadr::client::ClientError> {
12//! let client = Client::<BusinessLogic>::builder("https://vtn.example.com/openadr3/3.1.0")?
13//!     .credentials(Credentials::new("client-id", "client-secret"))
14//!     .build()?;
15//!
16//! let programs = client.programs().list().await?;
17//! # Ok(())
18//! # }
19//! ```
20
21use std::{
22    marker::PhantomData,
23    sync::{Arc, Mutex},
24    time::{Duration as StdDuration, Instant},
25};
26
27use reqwest::{Method, StatusCode, header};
28use serde::{Serialize, de::DeserializeOwned};
29use url::Url;
30
31use crate::model::{
32    AuthServerInfo, ClientCredentialResponse, Event, EventRequest, NotifiersResponse, ObjectId,
33    Problem, Program, ProgramRequest, Report, ReportRequest, Resource, ResourceRequest,
34    Subscription, SubscriptionRequest, Target, TopicsResponse, Ven, VenRequest,
35    adapt::{AdapterChain, WireAdapter},
36};
37
38/// Why a request failed.
39#[derive(Debug, thiserror::Error)]
40pub enum ClientError {
41    /// The base URL could not be parsed or joined.
42    #[error("invalid URL: {0}")]
43    Url(#[from] url::ParseError),
44    /// The transport failed.
45    #[error("transport error: {0}")]
46    Transport(#[from] reqwest::Error),
47    /// The VTN returned a problem.
48    #[error("{} {}: {}", status, problem.title.as_deref().unwrap_or("error"),
49            problem.detail.as_deref().unwrap_or("no detail"))]
50    Api {
51        /// The HTTP status.
52        status: StatusCode,
53        /// The problem body.
54        problem: Box<Problem>,
55    },
56    /// The VTN returned something unparseable.
57    #[error("could not decode the response: {0}")]
58    Decode(String),
59    /// Obtaining an access token failed.
60    #[error("authentication failed: {0}")]
61    Auth(String),
62}
63
64impl ClientError {
65    /// The HTTP status, when the VTN answered at all.
66    ///
67    /// `None` for a transport failure, which is the distinction that matters: a `404` is the VTN
68    /// saying "not here", and a refused connection is the VTN saying nothing.
69    pub fn status(&self) -> Option<u16> {
70        match self {
71            ClientError::Api { status, .. } => Some(status.as_u16()),
72            _ => None,
73        }
74    }
75}
76
77/// OAuth2 client-credentials, plus where to redeem them.
78#[derive(Clone)]
79pub struct Credentials {
80    client_id: String,
81    client_secret: String,
82    token_url: Option<Url>,
83    scopes: Option<String>,
84}
85
86impl std::fmt::Debug for Credentials {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        // Never print the secret, not even in a panic message.
89        f.debug_struct("Credentials")
90            .field("client_id", &self.client_id)
91            .field("client_secret", &"<redacted>")
92            .field("token_url", &self.token_url)
93            .finish()
94    }
95}
96
97impl Credentials {
98    /// The `clientID` half, which is not a secret.
99    pub fn client_id(&self) -> &str {
100        &self.client_id
101    }
102
103    /// Credentials whose token endpoint will be discovered from `GET /auth/server`.
104    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
105        Self {
106            client_id: client_id.into(),
107            client_secret: client_secret.into(),
108            token_url: None,
109            scopes: None,
110        }
111    }
112
113    /// Pin the token endpoint instead of discovering it.
114    pub fn with_token_url(mut self, url: Url) -> Self {
115        self.token_url = Some(url);
116        self
117    }
118
119    /// Request specific scopes.
120    pub fn with_scopes(mut self, scopes: impl Into<String>) -> Self {
121        self.scopes = Some(scopes.into());
122        self
123    }
124}
125
126/// A cached access token.
127#[derive(Debug)]
128struct CachedToken {
129    value: String,
130    /// When to stop using it. Refreshed early so a request never races the expiry.
131    refresh_at: Instant,
132}
133
134/// Marks a client that acts as business logic.
135#[derive(Debug, Clone, Copy)]
136pub struct BusinessLogic;
137
138/// Marks a client that acts as a virtual end node.
139#[derive(Debug, Clone, Copy)]
140pub struct VirtualEndNode;
141
142/// Sealed marker for the two roles.
143pub trait Role: Send + Sync + 'static {}
144impl Role for BusinessLogic {}
145impl Role for VirtualEndNode {}
146
147/// Builds a [`Client`].
148#[derive(Debug)]
149pub struct ClientBuilder<R> {
150    base: Url,
151    credentials: Option<Credentials>,
152    bearer_token: Option<String>,
153    timeout: StdDuration,
154    user_agent: String,
155    adapters: AdapterChain,
156    role: PhantomData<R>,
157}
158
159impl<R: Role> ClientBuilder<R> {
160    /// Provide credentials. Without them the client sends unauthenticated requests, which is what a
161    /// public tariff server expects.
162    pub fn credentials(mut self, credentials: Credentials) -> Self {
163        self.credentials = Some(credentials);
164        self
165    }
166
167    /// Present a fixed bearer token instead of minting one.
168    ///
169    /// For deployments where the credential does not come from an OAuth2 exchange: a pre-shared
170    /// token, or a gateway that has already authenticated the caller — Fluvius' NetFlex profile, for
171    /// instance, authenticates with mutual TLS and does not use OAuth2 at all.
172    pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
173        self.bearer_token = Some(token.into());
174        self
175    }
176
177    /// Per-request timeout.
178    pub fn timeout(mut self, timeout: StdDuration) -> Self {
179        self.timeout = timeout;
180        self
181    }
182
183    /// Override the `User-Agent`.
184    pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
185        self.user_agent = ua.into();
186        self
187    }
188
189    /// Speak to a peer that bends the schema.
190    ///
191    /// Deployed profiles deviate — Fluvius' NetFlex sends `reportDescriptor.frequency` as an ISO
192    /// duration where the schema says integer. An [adapter](crate::model::adapt) rewrites the JSON
193    /// on the way out and back, so the deviation is a named, tested transformation at the edge
194    /// rather than a hole in [`ReportDescriptor`](crate::model::ReportDescriptor) that every other
195    /// deployment would also have to live with.
196    ///
197    /// A chain is a pipeline: adapters apply in the order they were added on the way **out**
198    /// (canonical → the peer's shape) and in reverse on the way **in**, so that the chain undoes
199    /// itself exactly.
200    pub fn adapter(mut self, adapter: impl WireAdapter + 'static) -> Self {
201        self.adapters = std::mem::take(&mut self.adapters).with(adapter);
202        self
203    }
204
205    /// Finish.
206    pub fn build(self) -> Result<Client<R>, ClientError> {
207        // `reqwest` is built without a crypto provider of its own, so the process default has to
208        // exist before a client does. See `crate::crypto`.
209        crate::crypto::install_crypto_provider();
210        let http = reqwest::Client::builder()
211            .timeout(self.timeout)
212            .user_agent(self.user_agent)
213            .build()?;
214        Ok(Client {
215            inner: Arc::new(Inner {
216                base: self.base,
217                http,
218                credentials: self.credentials,
219                bearer_token: self.bearer_token,
220                token: Mutex::new(None),
221                adapters: self.adapters,
222            }),
223            role: PhantomData,
224        })
225    }
226}
227
228#[derive(Debug)]
229struct Inner {
230    base: Url,
231    http: reqwest::Client,
232    credentials: Option<Credentials>,
233    bearer_token: Option<String>,
234    token: Mutex<Option<CachedToken>>,
235    adapters: AdapterChain,
236}
237
238/// A VTN client.
239#[derive(Debug)]
240pub struct Client<R> {
241    inner: Arc<Inner>,
242    role: PhantomData<R>,
243}
244
245impl<R> Clone for Client<R> {
246    fn clone(&self) -> Self {
247        Self {
248            inner: Arc::clone(&self.inner),
249            role: PhantomData,
250        }
251    }
252}
253
254impl<R: Role> Client<R> {
255    /// Start building a client against a VTN base URL.
256    ///
257    /// A trailing slash is added if missing: without one, joining a relative path would replace the
258    /// last segment rather than extend it, which silently drops `/openadr3/3.1.0` from the URL.
259    pub fn builder(base_url: &str) -> Result<ClientBuilder<R>, ClientError> {
260        let mut base = base_url.to_string();
261        if !base.ends_with('/') {
262            base.push('/');
263        }
264        Ok(ClientBuilder {
265            base: Url::parse(&base)?,
266            credentials: None,
267            bearer_token: None,
268            timeout: StdDuration::from_secs(30),
269            user_agent: concat!("openadr-rs/", env!("CARGO_PKG_VERSION")).to_string(),
270            adapters: AdapterChain::new(),
271            role: PhantomData,
272        })
273    }
274
275    /// The base URL.
276    pub fn base_url(&self) -> &Url {
277        &self.inner.base
278    }
279
280    /// The `clientID` these credentials authenticate as, if the client has any.
281    ///
282    /// `None` for a pre-shared bearer token: the identity is inside the token and this client never
283    /// looks. Anything that has to *name* the identity out of band — the MQTT username, which the
284    /// VTN's broker callback derives authorization from `[Notifiers §12.2]` — needs it configured
285    /// explicitly rather than guessed.
286    pub fn client_id(&self) -> Option<&str> {
287        self.inner.credentials.as_ref().map(Credentials::client_id)
288    }
289
290    /// Where this VTN says tokens come from.
291    ///
292    /// Sent without a token: the specification marks this endpoint unauthenticated, and it has to
293    /// be — it is how a client discovers where to get a token in the first place.
294    pub async fn auth_server(&self) -> Result<AuthServerInfo, ClientError> {
295        self.send(Method::GET, "auth/server", None::<&()>, &[], None)
296            .await
297    }
298
299    /// The VTN's own clock, from the `Date` header of an unauthenticated request.
300    ///
301    /// `None` when the VTN — or a proxy in front of it — sends no `Date`, which is legal and which
302    /// a caller must treat as "unknown" rather than as agreement.
303    ///
304    /// Exists because every interval in OpenADR is an absolute instant, so a client whose clock is
305    /// wrong acts at the wrong time and reports compliance it did not achieve. `Date` is the only
306    /// reference the protocol offers, and second precision is enough for the question being asked.
307    pub async fn server_time(&self) -> Result<Option<crate::model::Timestamp>, ClientError> {
308        let (_, headers, _) = self
309            .send_raw(Method::GET, "auth/server", None::<&()>, &[], None, None)
310            .await?;
311        let Some(date) = headers.get(header::DATE).and_then(|v| v.to_str().ok()) else {
312            return Ok(None);
313        };
314        Ok(parse_http_date(date))
315    }
316
317    /// What push transports this VTN offers.
318    pub async fn notifiers(&self) -> Result<NotifiersResponse, ClientError> {
319        self.request(Method::GET, "notifiers", None::<&()>, &[])
320            .await
321    }
322
323    /// MQTT topic names for a collection or a scoped path, e.g. `vens/ven-1/events`.
324    pub async fn mqtt_topics(&self, path: &str) -> Result<TopicsResponse, ClientError> {
325        self.request(
326            Method::GET,
327            &format!("notifiers/mqtt/topics/{path}"),
328            None::<&()>,
329            &[],
330        )
331        .await
332    }
333
334    /// A `GET` against an arbitrary path under the base URL, decoded as JSON.
335    ///
336    /// The escape hatch under the typed collections. It exists for the two things a typed API
337    /// cannot serve: a VTN extension this crate does not model, and a tool that wants the VTN's
338    /// bytes rather than this crate's reading of them — which is what makes `openadr get` usable
339    /// for comparing two implementations.
340    pub async fn get_json<T: DeserializeOwned>(
341        &self,
342        path: &str,
343        query: &Query,
344    ) -> Result<T, ClientError> {
345        self.request(Method::GET, path, None::<&()>, &query.pairs)
346            .await
347    }
348
349    /// A `POST`, `PUT` or `DELETE` against an arbitrary path, with an optional JSON body.
350    pub async fn send_json<T: DeserializeOwned>(
351        &self,
352        method: &str,
353        path: &str,
354        body: Option<&serde_json::Value>,
355    ) -> Result<T, ClientError> {
356        let method = Method::from_bytes(method.as_bytes())
357            .map_err(|e| ClientError::Decode(format!("invalid HTTP method: {e}")))?;
358        self.request(method, path, body, &[]).await
359    }
360
361    /// One HTTP exchange, with nothing interpreted.
362    ///
363    /// Status, headers and bytes exactly as they arrived — a non-2xx is a *response*, not an error.
364    /// Every other method on this client turns a `4xx` into [`ClientError::Api`], which is right for
365    /// a program acting on the result and wrong for one *checking* it: a conformance run asserts on
366    /// the status, the `problem` body and the headers, and a helpful error type has already thrown
367    /// two of the three away.
368    ///
369    /// Carries the client's token, if it has one. Extra headers are appended verbatim.
370    pub async fn exchange(
371        &self,
372        method: &str,
373        path: &str,
374        query: &Query,
375        body: Option<&serde_json::Value>,
376        headers: &[(String, String)],
377    ) -> Result<RawResponse, ClientError> {
378        let method = Method::from_bytes(method.as_bytes())
379            .map_err(|e| ClientError::Decode(format!("invalid HTTP method: {e}")))?;
380        let token = self.access_token().await?;
381
382        let mut url = self.inner.base.join(path)?;
383        if !query.pairs.is_empty() {
384            let mut pairs = url.query_pairs_mut();
385            for (k, v) in &query.pairs {
386                pairs.append_pair(k, v);
387            }
388        }
389
390        let mut request = self.inner.http.request(method, url);
391        if let Some(token) = token {
392            request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
393        }
394        for (name, value) in headers {
395            request = request.header(name.as_str(), value.as_str());
396        }
397        if let Some(body) = body {
398            request = request.json(body);
399        }
400
401        let response = request.send().await?;
402        let status = response.status();
403        let headers = response.headers().clone();
404        let body = response.bytes().await?.to_vec();
405        Ok(RawResponse {
406            status,
407            headers,
408            body,
409        })
410    }
411
412    /// A conditional `GET` against an arbitrary path, as JSON.
413    ///
414    /// `None` when the VTN answers `304`, exactly as [`Collection::list_if_changed`].
415    pub async fn list_json_if_changed<T: DeserializeOwned>(
416        &self,
417        path: &str,
418        query: &Query,
419        etag: Option<&str>,
420    ) -> Result<Option<Tagged<T>>, ClientError> {
421        self.request_if_changed(path, &query.pairs, etag).await
422    }
423
424    /// Programmes.
425    pub fn programs(&self) -> Collection<'_, R, Program, ProgramRequest> {
426        Collection::new(self, "programs")
427    }
428
429    /// Events.
430    pub fn events(&self) -> Collection<'_, R, Event, EventRequest> {
431        Collection::new(self, "events")
432    }
433
434    /// Reports.
435    pub fn reports(&self) -> Collection<'_, R, Report, ReportRequest> {
436        Collection::new(self, "reports")
437    }
438
439    /// Subscriptions.
440    pub fn subscriptions(&self) -> Collection<'_, R, Subscription, SubscriptionRequest> {
441        Collection::new(self, "subscriptions")
442    }
443
444    /// VENs.
445    pub fn vens(&self) -> Collection<'_, R, Ven, VenRequest> {
446        Collection::new(self, "vens")
447    }
448
449    /// Resources.
450    pub fn resources(&self) -> Collection<'_, R, Resource, ResourceRequest> {
451        Collection::new(self, "resources")
452    }
453
454    /// A bearer token, minted or reused.
455    ///
456    /// Public because OpenADR itself sends this credential somewhere other than an HTTP header: the
457    /// MQTT binding presents the access token as the broker password `[Notifiers §12.2]`. A caller
458    /// doing that gets token caching and renewal for free instead of running a second OAuth2 client
459    /// beside this one — and, more to the point, gets the *same* token, so revoking the credential
460    /// closes both surfaces at once.
461    ///
462    /// `None` when the client has neither a pre-shared token nor credentials, which is the
463    /// anonymous reader of a public tariff server.
464    pub async fn access_token(&self) -> Result<Option<String>, ClientError> {
465        // A fixed token wins: it is what the operator explicitly configured.
466        if let Some(token) = &self.inner.bearer_token {
467            return Ok(Some(token.clone()));
468        }
469        let Some(credentials) = self.inner.credentials.as_ref() else {
470            return Ok(None);
471        };
472
473        if let Some(cached) = self
474            .inner
475            .token
476            .lock()
477            .unwrap_or_else(|e| e.into_inner())
478            .as_ref()
479            && Instant::now() < cached.refresh_at
480        {
481            return Ok(Some(cached.value.clone()));
482        }
483
484        // Discover the token endpoint if it was not pinned.
485        let token_url = match &credentials.token_url {
486            Some(u) => u.clone(),
487            None => {
488                let info = self.auth_server().await?;
489                Url::parse(&info.token_url)?
490            }
491        };
492
493        let mut form = vec![
494            ("grant_type", "client_credentials"),
495            ("client_id", credentials.client_id.as_str()),
496            ("client_secret", credentials.client_secret.as_str()),
497        ];
498        if let Some(scopes) = &credentials.scopes {
499            form.push(("scope", scopes.as_str()));
500        }
501
502        let response = self.inner.http.post(token_url).form(&form).send().await?;
503
504        if !response.status().is_success() {
505            let status = response.status();
506            let body = response.text().await.unwrap_or_default();
507            return Err(ClientError::Auth(format!("{status}: {body}")));
508        }
509
510        let token: ClientCredentialResponse = response
511            .json()
512            .await
513            .map_err(|e| ClientError::Auth(e.to_string()))?;
514
515        // Refresh at 90% of the lifetime, and never trust a lifetime of zero.
516        let lifetime = token.expires_in.unwrap_or(3600).max(1);
517        let refresh_in = StdDuration::from_secs(lifetime * 9 / 10).max(StdDuration::from_secs(1));
518
519        *self.inner.token.lock().unwrap_or_else(|e| e.into_inner()) = Some(CachedToken {
520            value: token.access_token.clone(),
521            refresh_at: Instant::now() + refresh_in,
522        });
523        Ok(Some(token.access_token))
524    }
525
526    /// Issue an authenticated request and decode the response.
527    async fn request<B: Serialize, T: DeserializeOwned>(
528        &self,
529        method: Method,
530        path: &str,
531        body: Option<&B>,
532        query: &[(String, String)],
533    ) -> Result<T, ClientError> {
534        let token = self.access_token().await?;
535        self.send(method, path, body, query, token).await
536    }
537
538    /// Decode a response body, running the inbound adapter chain first.
539    ///
540    /// Every path that turns bytes into a typed value goes through here, including the conditional
541    /// reads, which decode bytes of their own. Adapting in only one of them would give a client
542    /// speaking to a peer that bends the schema the adapters on `list()` and not on
543    /// `list_if_changed()`.
544    fn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> Result<T, ClientError> {
545        if self.inner.adapters.is_empty() {
546            return serde_json::from_slice(bytes).map_err(|e| ClientError::Decode(e.to_string()));
547        }
548        let mut json: serde_json::Value =
549            serde_json::from_slice(bytes).map_err(|e| ClientError::Decode(e.to_string()))?;
550        self.inner.adapters.inbound(&mut json);
551        serde_json::from_value(json).map_err(|e| ClientError::Decode(e.to_string()))
552    }
553
554    /// Issue a conditional request, returning `None` when the VTN answers `304`.
555    async fn request_if_changed<T: DeserializeOwned>(
556        &self,
557        path: &str,
558        query: &[(String, String)],
559        since: Option<&str>,
560    ) -> Result<Option<Tagged<T>>, ClientError> {
561        let token = self.access_token().await?;
562        let (status, headers, bytes) = self
563            .send_raw(Method::GET, path, None::<&()>, query, token, since)
564            .await?;
565        if status == StatusCode::NOT_MODIFIED {
566            return Ok(None);
567        }
568        let etag = headers
569            .get(header::ETAG)
570            .and_then(|v| v.to_str().ok())
571            .map(str::to_string);
572        let value = self.decode(&bytes)?;
573        Ok(Some(Tagged { value, etag }))
574    }
575
576    /// Issue a request with an explicit (possibly absent) token.
577    ///
578    /// Kept separate from [`Client::request`] so that token discovery cannot recurse into itself.
579    async fn send<B: Serialize, T: DeserializeOwned>(
580        &self,
581        method: Method,
582        path: &str,
583        body: Option<&B>,
584        query: &[(String, String)],
585        token: Option<String>,
586    ) -> Result<T, ClientError> {
587        let (_, _, bytes) = self
588            .send_raw(method, path, body, query, token, None)
589            .await?;
590        self.decode(&bytes)
591    }
592
593    /// The transport itself: everything above decodes what this returns.
594    async fn send_raw<B: Serialize>(
595        &self,
596        method: Method,
597        path: &str,
598        body: Option<&B>,
599        query: &[(String, String)],
600        token: Option<String>,
601        if_none_match: Option<&str>,
602    ) -> Result<(StatusCode, header::HeaderMap, Vec<u8>), ClientError> {
603        let mut url = self.inner.base.join(path)?;
604        if !query.is_empty() {
605            let mut pairs = url.query_pairs_mut();
606            for (k, v) in query {
607                pairs.append_pair(k, v);
608            }
609        }
610
611        let mut request = self.inner.http.request(method, url);
612        if let Some(token) = token {
613            request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
614        }
615        if let Some(tag) = if_none_match {
616            request = request.header(header::IF_NONE_MATCH, tag);
617        }
618        if let Some(body) = body {
619            if self.inner.adapters.is_empty() {
620                request = request.json(body);
621            } else {
622                // Serialise, let the adapters rewrite, then send. Going through `serde_json::Value`
623                // costs one extra pass and is only paid by a client that asked for an adapter.
624                let mut json =
625                    serde_json::to_value(body).map_err(|e| ClientError::Decode(e.to_string()))?;
626                self.inner.adapters.outbound(&mut json);
627                request = request.json(&json);
628            }
629        }
630
631        let response = request.send().await?;
632        let status = response.status();
633        let headers = response.headers().clone();
634        let bytes = response.bytes().await?.to_vec();
635
636        if status == StatusCode::NOT_MODIFIED {
637            return Ok((status, headers, bytes));
638        }
639        if !status.is_success() {
640            // Every error carries a problem body; fall back to a synthetic one if this peer does not.
641            let problem = serde_json::from_slice::<Problem>(&bytes).unwrap_or_else(|_| {
642                Problem::new(
643                    status.as_u16(),
644                    "unexpected",
645                    status.canonical_reason().unwrap_or("Error"),
646                )
647                .with_detail(String::from_utf8_lossy(&bytes).to_string())
648            });
649            return Err(ClientError::Api {
650                status,
651                problem: Box::new(problem),
652            });
653        }
654        Ok((status, headers, bytes))
655    }
656}
657
658/// Parse an RFC 9110 `Date` header — `Sun, 06 Nov 1994 08:49:37 GMT`.
659///
660/// Hand-written because `jiff` parses RFC 2822 and RFC 3339 and this is neither: it is IMF-fixdate,
661/// which is RFC 2822 with a fixed field order and `GMT` where an offset belongs. Swapping `GMT`
662/// for `+0000` makes it the former, which is one substitution against a dependency.
663fn parse_http_date(value: &str) -> Option<crate::model::Timestamp> {
664    let trimmed = value.trim();
665    let rfc2822 = trimmed
666        .strip_suffix("GMT")
667        .map(|head| format!("{head}+0000"));
668    let candidate = rfc2822.as_deref().unwrap_or(trimmed);
669    jiff::fmt::rfc2822::parse(candidate)
670        .ok()
671        .map(|zoned| zoned.timestamp())
672}
673
674/// One HTTP response, uninterpreted. See [`Client::exchange`].
675#[derive(Debug, Clone)]
676pub struct RawResponse {
677    /// The status, whatever it was.
678    pub status: StatusCode,
679    /// Every response header.
680    pub headers: header::HeaderMap,
681    /// The body bytes, possibly empty.
682    pub body: Vec<u8>,
683}
684
685impl RawResponse {
686    /// The body as JSON, or `None` if it is empty or not JSON.
687    pub fn json(&self) -> Option<serde_json::Value> {
688        serde_json::from_slice(&self.body).ok()
689    }
690
691    /// The body as a `problem`, or `None` if it is not one.
692    pub fn problem(&self) -> Option<Problem> {
693        serde_json::from_slice(&self.body).ok()
694    }
695
696    /// One header, as a string.
697    pub fn header(&self, name: &str) -> Option<&str> {
698        self.headers.get(name).and_then(|v| v.to_str().ok())
699    }
700
701    /// Whether the response carries a `problem+json` content type.
702    pub fn is_problem_json(&self) -> bool {
703        self.header("content-type")
704            .is_some_and(|v| v.starts_with("application/problem+json"))
705    }
706}
707
708/// A representation and the tag that identifies it.
709///
710/// OpenADR has no delta sync: a client that wants to know whether anything changed re-reads the
711/// collection, and every deployment does exactly that on a timer. Keeping the tag turns the next
712/// poll into a `304` with no body — see [`Collection::list_if_changed`].
713#[derive(Debug, Clone, PartialEq, Eq)]
714pub struct Tagged<T> {
715    /// The decoded body.
716    pub value: T,
717    /// The `ETag` the VTN returned. Hand it back on the next read.
718    ///
719    /// `None` from a VTN that does not implement caching, in which case every read returns a body.
720    pub etag: Option<String>,
721}
722
723/// Filters shared by every list endpoint.
724#[derive(Debug, Clone, Default)]
725pub struct Query {
726    pairs: Vec<(String, String)>,
727}
728
729impl Query {
730    /// An empty query.
731    pub fn new() -> Self {
732        Self::default()
733    }
734
735    /// Add a target. Repeat for several.
736    pub fn target(mut self, target: &Target) -> Self {
737        self.pairs.push(("targets".into(), target.to_string()));
738        self
739    }
740
741    /// Add several targets.
742    pub fn targets(mut self, targets: &[Target]) -> Self {
743        for t in targets {
744            self.pairs.push(("targets".into(), t.to_string()));
745        }
746        self
747    }
748
749    /// Restrict to one programme.
750    pub fn program(mut self, id: &ObjectId) -> Self {
751        self.pairs.push(("programID".into(), id.to_string()));
752        self
753    }
754
755    /// Restrict to one event, for `GET /reports`.
756    pub fn event(mut self, id: &ObjectId) -> Self {
757        self.pairs.push(("eventID".into(), id.to_string()));
758        self
759    }
760
761    /// Restrict to one VEN, for `GET /resources`.
762    pub fn ven(mut self, id: &ObjectId) -> Self {
763        self.pairs.push(("venID".into(), id.to_string()));
764        self
765    }
766
767    /// Look a programme up by name.
768    ///
769    /// Not in the specification — proposed as oadr3-org/specification#418 and already served by
770    /// public price servers, where finding one tariff among hundreds otherwise means paging the
771    /// whole collection.
772    pub fn program_name(mut self, name: &crate::model::ProgramName) -> Self {
773        self.pairs.push(("programName".into(), name.to_string()));
774        self
775    }
776
777    /// Look a VEN up by name.
778    pub fn ven_name(mut self, name: &crate::model::VenName) -> Self {
779        self.pairs.push(("venName".into(), name.to_string()));
780        self
781    }
782
783    /// Look a resource up by name, within its VEN.
784    pub fn resource_name(mut self, name: &crate::model::ResourceName) -> Self {
785        self.pairs.push(("resourceName".into(), name.to_string()));
786        self
787    }
788
789    /// Restrict to one reporting or subscribing client.
790    pub fn client_name(mut self, name: &crate::model::ClientName) -> Self {
791        self.pairs.push(("clientName".into(), name.to_string()));
792        self
793    }
794
795    /// Restrict subscriptions to those watching an object type.
796    pub fn watching(mut self, object: crate::model::ObjectType) -> Self {
797        self.pairs
798            .push(("objects".into(), object.as_str().to_string()));
799        self
800    }
801
802    /// Drop events whose intervals have elapsed.
803    pub fn active(mut self, active: bool) -> Self {
804        self.pairs.push(("active".into(), active.to_string()));
805        self
806    }
807
808    /// Skip records, for pagination.
809    pub fn skip(mut self, skip: usize) -> Self {
810        self.pairs.push(("skip".into(), skip.to_string()));
811        self
812    }
813
814    /// Limit the page size. The specification caps this at 50.
815    pub fn limit(mut self, limit: usize) -> Self {
816        self.pairs.push(("limit".into(), limit.to_string()));
817        self
818    }
819
820    /// An arbitrary parameter, for VTN extensions such as `programName`.
821    pub fn param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
822        self.pairs.push((key.into(), value.into()));
823        self
824    }
825
826    /// The parameters as they will be sent.
827    pub fn pairs(&self) -> &[(String, String)] {
828        &self.pairs
829    }
830
831    /// The first value for a key.
832    pub fn value(&self, key: &str) -> Option<String> {
833        self.pairs
834            .iter()
835            .find(|(k, _)| k == key)
836            .map(|(_, v)| v.clone())
837    }
838
839    /// Drop every occurrence of a key.
840    pub fn without(mut self, key: &str) -> Self {
841        self.pairs.retain(|(k, _)| k != key);
842        self
843    }
844
845    fn with_page(&self, skip: usize, limit: usize) -> Vec<(String, String)> {
846        let mut pairs: Vec<(String, String)> = self
847            .pairs
848            .iter()
849            .filter(|(k, _)| k != "skip" && k != "limit")
850            .cloned()
851            .collect();
852        pairs.push(("skip".into(), skip.to_string()));
853        pairs.push(("limit".into(), limit.to_string()));
854        pairs
855    }
856}
857
858/// Typed access to one collection.
859#[derive(Debug)]
860pub struct Collection<'c, R, T, Q> {
861    client: &'c Client<R>,
862    path: &'static str,
863    _types: PhantomData<(T, Q)>,
864}
865
866impl<'c, R: Role, T: DeserializeOwned, Q: Serialize> Collection<'c, R, T, Q> {
867    fn new(client: &'c Client<R>, path: &'static str) -> Self {
868        Self {
869            client,
870            path,
871            _types: PhantomData,
872        }
873    }
874
875    /// One page of objects.
876    pub async fn list(&self) -> Result<Vec<T>, ClientError> {
877        self.list_with(&Query::new()).await
878    }
879
880    /// One page, filtered.
881    pub async fn list_with(&self, query: &Query) -> Result<Vec<T>, ClientError> {
882        self.client
883            .request(Method::GET, self.path, None::<&()>, &query.pairs)
884            .await
885    }
886
887    /// Every matching object, following pagination to the end.
888    ///
889    /// The specification caps a page at 50, so a collection of any size needs this. Pages are
890    /// fetched sequentially because `skip`/`limit` has no cursor: a parallel fetch could miss or
891    /// duplicate a record if the collection changes underneath it.
892    pub async fn list_all(&self, query: &Query) -> Result<Vec<T>, ClientError> {
893        const PAGE: usize = 50;
894        let mut out = Vec::new();
895        let mut skip = 0usize;
896        loop {
897            let page: Vec<T> = self
898                .client
899                .request(
900                    Method::GET,
901                    self.path,
902                    None::<&()>,
903                    &query.with_page(skip, PAGE),
904                )
905                .await?;
906            let received = page.len();
907            out.extend(page);
908            if received < PAGE {
909                return Ok(out);
910            }
911            skip += PAGE;
912        }
913    }
914
915    /// One page, or `None` if nothing has changed since `etag`.
916    ///
917    /// The counterpart of the VTN's `ETag`: pass the tag from the previous read and a poll that
918    /// finds nothing new costs a `304` with no body rather than the whole collection again. OpenADR
919    /// has no delta sync, so for a client that polls this is the difference between a kilobyte and
920    /// a megabyte per cycle.
921    ///
922    /// A VTN with caching switched off never answers `304`, so this simply always returns the page.
923    pub async fn list_if_changed(
924        &self,
925        query: &Query,
926        etag: Option<&str>,
927    ) -> Result<Option<Tagged<Vec<T>>>, ClientError> {
928        self.client
929            .request_if_changed(self.path, &query.pairs, etag)
930            .await
931    }
932
933    /// One object, or `None` if it has not changed since `etag`.
934    pub async fn get_if_changed(
935        &self,
936        id: &ObjectId,
937        etag: Option<&str>,
938    ) -> Result<Option<Tagged<T>>, ClientError> {
939        self.client
940            .request_if_changed(&format!("{}/{id}", self.path), &[], etag)
941            .await
942    }
943
944    /// Fetch one object.
945    pub async fn get(&self, id: &ObjectId) -> Result<T, ClientError> {
946        self.client
947            .request(
948                Method::GET,
949                &format!("{}/{id}", self.path),
950                None::<&()>,
951                &[],
952            )
953            .await
954    }
955
956    /// Fetch one object, or `None` if the VTN says it does not exist.
957    ///
958    /// A targeted object the caller may not see also reads as absent, which is deliberate.
959    pub async fn try_get(&self, id: &ObjectId) -> Result<Option<T>, ClientError> {
960        match self.get(id).await {
961            Ok(v) => Ok(Some(v)),
962            Err(ClientError::Api { status, .. }) if status == StatusCode::NOT_FOUND => Ok(None),
963            Err(e) => Err(e),
964        }
965    }
966}
967
968/// Writes that both roles may perform.
969impl<R: Role, T: DeserializeOwned, Q: Serialize> Collection<'_, R, T, Q> {
970    async fn create_inner(&self, request: &Q) -> Result<T, ClientError> {
971        self.client
972            .request(Method::POST, self.path, Some(request), &[])
973            .await
974    }
975
976    async fn update_inner(&self, id: &ObjectId, request: &Q) -> Result<T, ClientError> {
977        self.client
978            .request(
979                Method::PUT,
980                &format!("{}/{id}", self.path),
981                Some(request),
982                &[],
983            )
984            .await
985    }
986
987    async fn delete_inner(&self, id: &ObjectId) -> Result<T, ClientError> {
988        self.client
989            .request(
990                Method::DELETE,
991                &format!("{}/{id}", self.path),
992                None::<&()>,
993                &[],
994            )
995            .await
996    }
997}
998
999/// Programmes and events are business logic's to write.
1000macro_rules! bl_writes {
1001    ($t:ty, $q:ty) => {
1002        impl Collection<'_, BusinessLogic, $t, $q> {
1003            /// Create.
1004            pub async fn create(&self, request: &$q) -> Result<$t, ClientError> {
1005                self.create_inner(request).await
1006            }
1007            /// Replace.
1008            pub async fn update(&self, id: &ObjectId, request: &$q) -> Result<$t, ClientError> {
1009                self.update_inner(id, request).await
1010            }
1011            /// Delete.
1012            pub async fn delete(&self, id: &ObjectId) -> Result<$t, ClientError> {
1013                self.delete_inner(id).await
1014            }
1015        }
1016    };
1017}
1018
1019bl_writes!(Program, ProgramRequest);
1020bl_writes!(Event, EventRequest);
1021
1022/// Reports and subscriptions are the VEN's to write.
1023macro_rules! ven_writes {
1024    ($t:ty, $q:ty) => {
1025        impl Collection<'_, VirtualEndNode, $t, $q> {
1026            /// Create.
1027            pub async fn create(&self, request: &$q) -> Result<$t, ClientError> {
1028                self.create_inner(request).await
1029            }
1030            /// Replace.
1031            pub async fn update(&self, id: &ObjectId, request: &$q) -> Result<$t, ClientError> {
1032                self.update_inner(id, request).await
1033            }
1034            /// Delete.
1035            pub async fn delete(&self, id: &ObjectId) -> Result<$t, ClientError> {
1036                self.delete_inner(id).await
1037            }
1038        }
1039    };
1040}
1041
1042ven_writes!(Report, ReportRequest);
1043ven_writes!(Subscription, SubscriptionRequest);
1044
1045/// VENs and resources are writable by both roles, with different request bodies.
1046macro_rules! both_writes {
1047    ($t:ty, $q:ty) => {
1048        impl<R: Role> Collection<'_, R, $t, $q> {
1049            /// Create.
1050            pub async fn create(&self, request: &$q) -> Result<$t, ClientError> {
1051                self.create_inner(request).await
1052            }
1053            /// Replace.
1054            pub async fn update(&self, id: &ObjectId, request: &$q) -> Result<$t, ClientError> {
1055                self.update_inner(id, request).await
1056            }
1057            /// Delete.
1058            pub async fn delete(&self, id: &ObjectId) -> Result<$t, ClientError> {
1059                self.delete_inner(id).await
1060            }
1061        }
1062    };
1063}
1064
1065both_writes!(Ven, VenRequest);
1066both_writes!(Resource, ResourceRequest);
1067
1068/// Business logic may also delete reports, which is how orphaned data is cleaned up.
1069impl Collection<'_, BusinessLogic, Report, ReportRequest> {
1070    /// Delete a report.
1071    pub async fn delete(&self, id: &ObjectId) -> Result<Report, ClientError> {
1072        self.delete_inner(id).await
1073    }
1074}
1075
1076#[cfg(test)]
1077mod tests {
1078    use super::*;
1079
1080    #[test]
1081    fn a_missing_trailing_slash_does_not_eat_the_base_path() {
1082        // `Url::join` replaces the last segment when the base has no trailing slash, which silently
1083        // turns `/openadr3/3.1.0` into nothing. This is a real and easily-missed footgun.
1084        let client = Client::<BusinessLogic>::builder("https://vtn.example.com/openadr3/3.1.0")
1085            .unwrap()
1086            .build()
1087            .unwrap();
1088        assert_eq!(
1089            client.base_url().join("programs").unwrap().as_str(),
1090            "https://vtn.example.com/openadr3/3.1.0/programs"
1091        );
1092    }
1093
1094    #[test]
1095    fn a_trailing_slash_is_left_alone() {
1096        let client = Client::<BusinessLogic>::builder("https://vtn.example.com/openadr3/3.1.0/")
1097            .unwrap()
1098            .build()
1099            .unwrap();
1100        assert_eq!(
1101            client.base_url().join("events").unwrap().as_str(),
1102            "https://vtn.example.com/openadr3/3.1.0/events"
1103        );
1104    }
1105
1106    #[test]
1107    fn queries_accumulate_repeated_targets() {
1108        let q = Query::new()
1109            .target(&Target::new("group1").unwrap())
1110            .target(&Target::new("group2").unwrap())
1111            .active(true);
1112        assert_eq!(q.pairs.len(), 3);
1113        assert_eq!(q.pairs.iter().filter(|(k, _)| k == "targets").count(), 2);
1114    }
1115
1116    #[test]
1117    fn paging_replaces_rather_than_appends_bounds() {
1118        let q = Query::new().limit(10).skip(0);
1119        let paged = q.with_page(50, 50);
1120        assert_eq!(paged.iter().filter(|(k, _)| k == "limit").count(), 1);
1121        assert_eq!(paged.iter().find(|(k, _)| k == "skip").unwrap().1, "50");
1122    }
1123
1124    #[test]
1125    fn credentials_never_print_their_secret() {
1126        let c = Credentials::new("id", "hunter2");
1127        let rendered = format!("{c:?}");
1128        assert!(!rendered.contains("hunter2"), "{rendered}");
1129        assert!(rendered.contains("id"));
1130    }
1131}