1use 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#[derive(Debug, thiserror::Error)]
40pub enum ClientError {
41 #[error("invalid URL: {0}")]
43 Url(#[from] url::ParseError),
44 #[error("transport error: {0}")]
46 Transport(#[from] reqwest::Error),
47 #[error("{} {}: {}", status, problem.title.as_deref().unwrap_or("error"),
49 problem.detail.as_deref().unwrap_or("no detail"))]
50 Api {
51 status: StatusCode,
53 problem: Box<Problem>,
55 },
56 #[error("could not decode the response: {0}")]
58 Decode(String),
59 #[error("authentication failed: {0}")]
61 Auth(String),
62}
63
64impl ClientError {
65 pub fn status(&self) -> Option<u16> {
70 match self {
71 ClientError::Api { status, .. } => Some(status.as_u16()),
72 _ => None,
73 }
74 }
75}
76
77#[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 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 pub fn client_id(&self) -> &str {
100 &self.client_id
101 }
102
103 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 pub fn with_token_url(mut self, url: Url) -> Self {
115 self.token_url = Some(url);
116 self
117 }
118
119 pub fn with_scopes(mut self, scopes: impl Into<String>) -> Self {
121 self.scopes = Some(scopes.into());
122 self
123 }
124}
125
126#[derive(Debug)]
128struct CachedToken {
129 value: String,
130 refresh_at: Instant,
132}
133
134#[derive(Debug, Clone, Copy)]
136pub struct BusinessLogic;
137
138#[derive(Debug, Clone, Copy)]
140pub struct VirtualEndNode;
141
142pub trait Role: Send + Sync + 'static {}
144impl Role for BusinessLogic {}
145impl Role for VirtualEndNode {}
146
147#[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 pub fn credentials(mut self, credentials: Credentials) -> Self {
163 self.credentials = Some(credentials);
164 self
165 }
166
167 pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
173 self.bearer_token = Some(token.into());
174 self
175 }
176
177 pub fn timeout(mut self, timeout: StdDuration) -> Self {
179 self.timeout = timeout;
180 self
181 }
182
183 pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
185 self.user_agent = ua.into();
186 self
187 }
188
189 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 pub fn build(self) -> Result<Client<R>, ClientError> {
207 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#[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 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 pub fn base_url(&self) -> &Url {
277 &self.inner.base
278 }
279
280 pub fn client_id(&self) -> Option<&str> {
287 self.inner.credentials.as_ref().map(Credentials::client_id)
288 }
289
290 pub async fn auth_server(&self) -> Result<AuthServerInfo, ClientError> {
295 self.send(Method::GET, "auth/server", None::<&()>, &[], None)
296 .await
297 }
298
299 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 pub async fn notifiers(&self) -> Result<NotifiersResponse, ClientError> {
319 self.request(Method::GET, "notifiers", None::<&()>, &[])
320 .await
321 }
322
323 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 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 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 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 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 pub fn programs(&self) -> Collection<'_, R, Program, ProgramRequest> {
426 Collection::new(self, "programs")
427 }
428
429 pub fn events(&self) -> Collection<'_, R, Event, EventRequest> {
431 Collection::new(self, "events")
432 }
433
434 pub fn reports(&self) -> Collection<'_, R, Report, ReportRequest> {
436 Collection::new(self, "reports")
437 }
438
439 pub fn subscriptions(&self) -> Collection<'_, R, Subscription, SubscriptionRequest> {
441 Collection::new(self, "subscriptions")
442 }
443
444 pub fn vens(&self) -> Collection<'_, R, Ven, VenRequest> {
446 Collection::new(self, "vens")
447 }
448
449 pub fn resources(&self) -> Collection<'_, R, Resource, ResourceRequest> {
451 Collection::new(self, "resources")
452 }
453
454 pub async fn access_token(&self) -> Result<Option<String>, ClientError> {
465 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 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 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 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 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 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 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 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 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 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
658fn 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#[derive(Debug, Clone)]
676pub struct RawResponse {
677 pub status: StatusCode,
679 pub headers: header::HeaderMap,
681 pub body: Vec<u8>,
683}
684
685impl RawResponse {
686 pub fn json(&self) -> Option<serde_json::Value> {
688 serde_json::from_slice(&self.body).ok()
689 }
690
691 pub fn problem(&self) -> Option<Problem> {
693 serde_json::from_slice(&self.body).ok()
694 }
695
696 pub fn header(&self, name: &str) -> Option<&str> {
698 self.headers.get(name).and_then(|v| v.to_str().ok())
699 }
700
701 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#[derive(Debug, Clone, PartialEq, Eq)]
714pub struct Tagged<T> {
715 pub value: T,
717 pub etag: Option<String>,
721}
722
723#[derive(Debug, Clone, Default)]
725pub struct Query {
726 pairs: Vec<(String, String)>,
727}
728
729impl Query {
730 pub fn new() -> Self {
732 Self::default()
733 }
734
735 pub fn target(mut self, target: &Target) -> Self {
737 self.pairs.push(("targets".into(), target.to_string()));
738 self
739 }
740
741 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 pub fn program(mut self, id: &ObjectId) -> Self {
751 self.pairs.push(("programID".into(), id.to_string()));
752 self
753 }
754
755 pub fn event(mut self, id: &ObjectId) -> Self {
757 self.pairs.push(("eventID".into(), id.to_string()));
758 self
759 }
760
761 pub fn ven(mut self, id: &ObjectId) -> Self {
763 self.pairs.push(("venID".into(), id.to_string()));
764 self
765 }
766
767 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 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 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 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 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 pub fn active(mut self, active: bool) -> Self {
804 self.pairs.push(("active".into(), active.to_string()));
805 self
806 }
807
808 pub fn skip(mut self, skip: usize) -> Self {
810 self.pairs.push(("skip".into(), skip.to_string()));
811 self
812 }
813
814 pub fn limit(mut self, limit: usize) -> Self {
816 self.pairs.push(("limit".into(), limit.to_string()));
817 self
818 }
819
820 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 pub fn pairs(&self) -> &[(String, String)] {
828 &self.pairs
829 }
830
831 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 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#[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 pub async fn list(&self) -> Result<Vec<T>, ClientError> {
877 self.list_with(&Query::new()).await
878 }
879
880 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 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 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 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 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 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
968impl<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
999macro_rules! bl_writes {
1001 ($t:ty, $q:ty) => {
1002 impl Collection<'_, BusinessLogic, $t, $q> {
1003 pub async fn create(&self, request: &$q) -> Result<$t, ClientError> {
1005 self.create_inner(request).await
1006 }
1007 pub async fn update(&self, id: &ObjectId, request: &$q) -> Result<$t, ClientError> {
1009 self.update_inner(id, request).await
1010 }
1011 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
1022macro_rules! ven_writes {
1024 ($t:ty, $q:ty) => {
1025 impl Collection<'_, VirtualEndNode, $t, $q> {
1026 pub async fn create(&self, request: &$q) -> Result<$t, ClientError> {
1028 self.create_inner(request).await
1029 }
1030 pub async fn update(&self, id: &ObjectId, request: &$q) -> Result<$t, ClientError> {
1032 self.update_inner(id, request).await
1033 }
1034 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
1045macro_rules! both_writes {
1047 ($t:ty, $q:ty) => {
1048 impl<R: Role> Collection<'_, R, $t, $q> {
1049 pub async fn create(&self, request: &$q) -> Result<$t, ClientError> {
1051 self.create_inner(request).await
1052 }
1053 pub async fn update(&self, id: &ObjectId, request: &$q) -> Result<$t, ClientError> {
1055 self.update_inner(id, request).await
1056 }
1057 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
1068impl Collection<'_, BusinessLogic, Report, ReportRequest> {
1070 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 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}