1use std::fmt;
2use std::sync::Arc;
3use std::time::Duration;
4
5use url::Url;
6
7use crate::Error;
8use crate::consistency::{ConsistencyTokenCell, ConsistencyTokenStore};
9use crate::credentials::{self, Credentials};
10
11pub const VERSION: &str = env!("CARGO_PKG_VERSION");
13
14const ENV_REGION: &str = "ORIGINCLOUD_REGION";
15const DEFAULT_MAX_ATTEMPTS: u32 = 5;
16const DEFAULT_OPERATION_WAIT: Duration = Duration::from_secs(60);
18
19#[derive(Clone)]
23pub struct Client {
24 pub(crate) inner: Arc<Inner>,
25}
26
27pub(crate) struct Inner {
28 pub(crate) http: reqwest::Client,
29 pub(crate) credentials: Arc<dyn Credentials>,
30 region: String,
31 endpoint: Option<Url>,
32 pub(crate) user_agent: String,
33 pub(crate) max_attempts: u32,
34 pub(crate) timeout: Option<Duration>,
36 pub(crate) operation_wait: Duration,
38 pub(crate) tokens: Arc<dyn ConsistencyTokenStore>,
39}
40
41impl Client {
42 #[cfg_attr(
44 not(target_arch = "wasm32"),
45 doc = "[`default_credentials`](crate::default_credentials) finds, and the"
46 )]
47 #[cfg_attr(
48 target_arch = "wasm32",
49 doc = "`default_credentials` finds natively (in a browser, none), and the"
50 )]
51 pub fn new() -> Result<Self, Error> {
53 Self::builder().build()
54 }
55
56 pub fn builder() -> ClientBuilder {
58 ClientBuilder::default()
59 }
60
61 pub fn service(&self, shortcode: &str, regional: bool) -> Service {
69 let base = match &self.inner.endpoint {
70 Some(endpoint) => Ok(endpoint.clone()),
71 None if !is_label(shortcode) => Err(format!(
72 "the service shortcode must be [a-z0-9-]+, got {shortcode:?}"
73 )),
74 None => {
75 let region = &self.inner.region;
76 let host = if regional && !region.is_empty() {
77 format!("{shortcode}.{region}.origincloudapis.eu")
78 } else {
79 format!("{shortcode}.origincloudapis.eu")
80 };
81 Url::parse(&format!("https://{host}"))
82 .map_err(|e| format!("the service host {host:?} isn't valid: {e}"))
83 }
84 };
85 Service {
86 client: self.clone(),
87 base,
88 shortcode: shortcode.to_owned(),
89 options: CallOptions::default(),
90 }
91 }
92
93 pub fn consistency_token(&self) -> String {
99 self.inner.tokens.get()
100 }
101
102 pub fn set_consistency_token(&self, token: impl Into<String>) {
112 self.inner.tokens.set(token.into());
113 }
114}
115
116impl fmt::Debug for Client {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.debug_struct("Client")
119 .field("credentials", &self.inner.credentials)
120 .field("region", &self.inner.region)
121 .field("endpoint", &self.inner.endpoint.as_ref().map(Url::as_str))
122 .field("max_attempts", &self.inner.max_attempts)
123 .finish_non_exhaustive()
124 }
125}
126
127#[derive(Default)]
129pub struct ClientBuilder {
130 credentials: Option<Arc<dyn Credentials>>,
131 region: Option<String>,
132 endpoint: Option<String>,
133 http: Option<reqwest::Client>,
134 user_agent: Option<String>,
135 max_attempts: Option<u32>,
136 timeout: Option<Duration>,
137 operation_wait: Option<Duration>,
138 tokens: Option<Arc<dyn ConsistencyTokenStore>>,
139 #[cfg(not(target_arch = "wasm32"))]
140 impersonate: Option<String>,
141}
142
143impl ClientBuilder {
144 pub fn credentials(mut self, credentials: impl Credentials + 'static) -> Self {
147 self.credentials = Some(Arc::new(credentials));
148 self
149 }
150
151 pub fn region(mut self, region: impl Into<String>) -> Self {
157 self.region = Some(region.into());
158 self
159 }
160
161 pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
165 self.endpoint = Some(endpoint.into());
166 self
167 }
168
169 pub fn http_client(mut self, http: reqwest::Client) -> Self {
172 self.http = Some(http);
173 self
174 }
175
176 pub fn user_agent(mut self, product: impl Into<String>) -> Self {
178 self.user_agent = Some(product.into());
179 self
180 }
181
182 pub fn max_attempts(mut self, attempts: u32) -> Self {
185 self.max_attempts = Some(attempts);
186 self
187 }
188
189 pub fn timeout(mut self, timeout: Duration) -> Self {
197 self.timeout = Some(timeout);
198 self
199 }
200
201 pub fn operation_wait(mut self, wait: Duration) -> Self {
209 self.operation_wait = Some(wait);
210 self
211 }
212
213 pub fn consistency_token_store(mut self, store: Arc<dyn ConsistencyTokenStore>) -> Self {
221 self.tokens = Some(store);
222 self
223 }
224
225 #[cfg(not(target_arch = "wasm32"))]
241 pub fn impersonate_service_account(mut self, service_account: impl Into<String>) -> Self {
242 self.impersonate = Some(service_account.into());
243 self
244 }
245
246 pub fn build(self) -> Result<Client, Error> {
249 self.build_with(&|name| std::env::var(name).ok())
250 }
251
252 pub(crate) fn build_with(self, env: &dyn Fn(&str) -> Option<String>) -> Result<Client, Error> {
254 if self.timeout == Some(Duration::ZERO) {
255 return Err(Error::Config(
256 "the timeout must be longer than zero".to_owned(),
257 ));
258 }
259 let max_attempts = self.max_attempts.unwrap_or(DEFAULT_MAX_ATTEMPTS);
260 if max_attempts < 1 {
261 return Err(Error::Config(format!(
262 "the most attempts must be at least 1, got {max_attempts}"
263 )));
264 }
265 let mut user_agent = format!("origincloud-sdk-rust/{VERSION}");
266 if let Some(product) = self.user_agent.filter(|p| !p.is_empty()) {
267 user_agent = format!("{product} {user_agent}");
268 }
269 let region = match self.region {
270 Some(region) => region,
271 None => env(ENV_REGION).unwrap_or_default(),
272 };
273 if !region.is_empty() && !is_label(®ion) {
274 return Err(Error::Config(format!(
275 "the region must be [a-z0-9-]+, such as eu-central1, got {region:?}"
276 )));
277 }
278 let endpoint = match self.endpoint {
279 Some(endpoint) => {
280 let parsed = Url::parse(endpoint.trim_end_matches('/'))
281 .ok()
282 .filter(|u| u.has_host() && !u.cannot_be_a_base());
283 Some(parsed.ok_or_else(|| {
284 Error::Config(format!(
285 "the endpoint must be an absolute URL, got {endpoint:?}"
286 ))
287 })?)
288 }
289 None => None,
290 };
291 let http = match self.http {
292 Some(http) => http,
293 None => reqwest::Client::builder()
294 .build()
295 .map_err(|e| Error::Config(format!("creating the HTTP client: {e}")))?,
296 };
297 let credentials = match self.credentials {
298 Some(credentials) => credentials,
299 None => credentials::from_environment(env)?,
300 };
301 #[cfg(not(target_arch = "wasm32"))]
302 let credentials = credentials::impersonating(credentials, self.impersonate, env)?;
303 Ok(Client {
304 inner: Arc::new(Inner {
305 http,
306 credentials,
307 region,
308 endpoint,
309 user_agent,
310 max_attempts,
311 timeout: self.timeout,
312 operation_wait: self.operation_wait.unwrap_or(DEFAULT_OPERATION_WAIT),
313 tokens: self
314 .tokens
315 .unwrap_or_else(|| Arc::new(ConsistencyTokenCell::new())),
316 }),
317 })
318 }
319}
320
321impl fmt::Debug for ClientBuilder {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 f.debug_struct("ClientBuilder")
324 .field("credentials", &self.credentials)
325 .field("region", &self.region)
326 .field("endpoint", &self.endpoint)
327 .field("max_attempts", &self.max_attempts)
328 .field("timeout", &self.timeout)
329 .field("operation_wait", &self.operation_wait)
330 .field("consistency_token_store", &self.tokens)
331 .finish_non_exhaustive()
332 }
333}
334
335fn is_label(s: &str) -> bool {
338 !s.is_empty()
339 && s.bytes()
340 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
341}
342
343#[derive(Clone, Debug)]
346pub struct Service {
347 pub(crate) client: Client,
348 pub(crate) base: Result<Url, String>,
350 pub(crate) shortcode: String,
353 pub(crate) options: CallOptions,
354}
355
356impl Service {
357 pub fn with_options(&self, options: CallOptions) -> Self {
361 Self {
362 options,
363 ..self.clone()
364 }
365 }
366
367 pub fn options(&self) -> &CallOptions {
369 &self.options
370 }
371
372 pub(crate) fn max_attempts(&self) -> u32 {
375 self.options
376 .max_attempts
377 .unwrap_or(self.client.inner.max_attempts)
378 }
379
380 pub fn client(&self) -> &Client {
382 &self.client
383 }
384
385 pub fn base_url(&self) -> Option<&Url> {
388 self.base.as_ref().ok()
389 }
390}
391
392#[derive(Clone, Debug, Default, PartialEq, Eq)]
403#[non_exhaustive]
404pub struct CallOptions {
405 max_attempts: Option<u32>,
406}
407
408impl CallOptions {
409 pub fn new() -> Self {
411 Self::default()
412 }
413
414 pub fn max_attempts(mut self, attempts: u32) -> Self {
421 self.max_attempts = Some(attempts.max(1));
422 self
423 }
424
425 pub fn attempts(&self) -> Option<u32> {
427 self.max_attempts
428 }
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434 use crate::AccessToken;
435
436 fn no_env(_: &str) -> Option<String> {
437 None
438 }
439
440 fn base(client: &Client, regional: bool) -> String {
441 client
442 .service("pvs", regional)
443 .base_url()
444 .unwrap()
445 .as_str()
446 .trim_end_matches('/')
447 .to_owned()
448 }
449
450 #[test]
451 fn endpoints() {
452 for (region, regional, want) in [
453 ("", true, "https://pvs.origincloudapis.eu"),
454 (
455 "eu-central1",
456 true,
457 "https://pvs.eu-central1.origincloudapis.eu",
458 ),
459 ("eu-central1", false, "https://pvs.origincloudapis.eu"),
460 ] {
461 let client = Client::builder()
462 .credentials(AccessToken::new("t"))
463 .region(region)
464 .build_with(&no_env)
465 .unwrap();
466 assert_eq!(
467 base(&client, regional),
468 want,
469 "region {region:?}, regional {regional}"
470 );
471 }
472
473 let env = |name: &str| (name == ENV_REGION).then(|| "eu-west1".to_owned());
474 let client = Client::builder()
475 .credentials(AccessToken::new("t"))
476 .build_with(&env)
477 .unwrap();
478 assert_eq!(
479 base(&client, true),
480 "https://pvs.eu-west1.origincloudapis.eu"
481 );
482 let client = Client::builder()
483 .credentials(AccessToken::new("t"))
484 .region("")
485 .build_with(&env)
486 .unwrap();
487 assert_eq!(
488 base(&client, true),
489 "https://pvs.origincloudapis.eu",
490 "an empty region overrides the environment"
491 );
492 }
493
494 #[test]
495 fn a_region_that_isnt_a_host_label_is_refused() {
496 for region in [
497 "eu/central1",
498 "x@evil.com/",
499 "eu central1",
500 "eu-central1:443",
501 "EU-CENTRAL1",
502 ] {
503 let built = Client::builder()
504 .credentials(AccessToken::new("t"))
505 .region(region)
506 .build_with(&no_env);
507 let Err(Error::Config(message)) = built else {
508 panic!("region {region:?}: {built:?}");
509 };
510 assert!(message.contains(&format!("{region:?}")), "{message}");
511
512 let env = |name: &str| (name == ENV_REGION).then(|| region.to_owned());
513 let built = Client::builder()
514 .credentials(AccessToken::new("t"))
515 .build_with(&env);
516 assert!(
517 matches!(built, Err(Error::Config(_))),
518 "ORIGINCLOUD_REGION={region:?}"
519 );
520 }
521 }
522
523 #[test]
524 fn a_shortcode_that_isnt_a_host_label_fails_its_calls_instead_of_panicking() {
525 let client = Client::builder()
526 .credentials(AccessToken::new("t"))
527 .build_with(&no_env)
528 .unwrap();
529 assert!(client.service("x@evil.com/", true).base_url().is_none());
530 assert!(client.service("pvs", true).base_url().is_some());
531 }
532
533 #[test]
534 fn invalid_options_are_refused() {
535 let built = Client::builder()
536 .credentials(AccessToken::new("t"))
537 .max_attempts(0)
538 .build_with(&no_env);
539 assert!(matches!(built, Err(Error::Config(_))));
540 for endpoint in [
541 "localhost",
542 "",
543 "http://",
544 "not a url",
545 "http://exa mple.com",
546 "mailto:x@y",
547 ] {
548 let built = Client::builder()
549 .credentials(AccessToken::new("t"))
550 .endpoint(endpoint)
551 .build_with(&no_env);
552 assert!(
553 matches!(built, Err(Error::Config(_))),
554 "endpoint {endpoint:?}"
555 );
556 }
557 }
558
559 #[test]
560 fn no_credentials_at_all() {
561 let env = |name: &str| match name {
562 "XDG_DATA_HOME" => Some("/nonexistent/origincloud-sdk-test".to_owned()),
563 "ORIGINCLOUD_METADATA_DISABLED" => Some("true".to_owned()),
564 _ => None,
565 };
566 assert!(matches!(
567 Client::builder().build_with(&env),
568 Err(Error::NoCredentials)
569 ));
570 }
571}