Skip to main content

origincloud_core/
client.rs

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
11/// This SDK's version, sent in the `User-Agent` header.
12pub const VERSION: &str = env!("CARGO_PKG_VERSION");
13
14const ENV_REGION: &str = "ORIGINCLOUD_REGION";
15const DEFAULT_MAX_ATTEMPTS: u32 = 5;
16/// The longest the API waits for an operation in one call.
17const DEFAULT_OPERATION_WAIT: Duration = Duration::from_secs(60);
18
19/// What the clients of every service share: credentials, endpoints, an
20/// HTTP client and the consistency token's store. Cloning it is cheap, and
21/// the clones share all of it.
22#[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    /// The timeout of each attempt, when the builder set one.
35    pub(crate) timeout: Option<Duration>,
36    /// How long one call waiting on an operation asks the API to wait.
37    pub(crate) operation_wait: Duration,
38    pub(crate) tokens: Arc<dyn ConsistencyTokenStore>,
39}
40
41impl Client {
42    /// A client configured by the environment: the credentials
43    #[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    /// region `ORIGINCLOUD_REGION` names, if any.
52    pub fn new() -> Result<Self, Error> {
53        Self::builder().build()
54    }
55
56    /// A builder of a client configured otherwise.
57    pub fn builder() -> ClientBuilder {
58        ClientBuilder::default()
59    }
60
61    /// The endpoint of the service whose host starts with `shortcode`, such
62    /// as `pvs`. A regional service answers at its region's front door when
63    /// the client has a region; a global one always at its regionless host.
64    /// The generated clients call it.
65    ///
66    /// A shortcode that isn't a host label, `[a-z0-9-]+`, makes every call
67    /// of the service fail with [`Error::Config`].
68    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    /// The consistency token the client holds: the one the last answer
94    /// carrying one brought, or empty before any. Hand it to
95    /// [`Client::set_consistency_token`] of a client in another process for
96    /// its reads to show this client's writes. It is read from the client's
97    /// store ([`ClientBuilder::consistency_token_store`]).
98    pub fn consistency_token(&self) -> String {
99        self.inner.tokens.get()
100    }
101
102    /// Replaces the consistency token the client sends with its calls.
103    ///
104    /// The API merges a mutation's position into the token the mutation
105    /// presented, so writes made one after another each answer with a token
106    /// covering all of them. Writes made concurrently each present the same
107    /// earlier token, and the client keeps whichever token is answered last:
108    /// a read then sees that write, not necessarily the others, until it
109    /// presents a token covering them, such as one from waiting on their
110    /// operations.
111    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/// Configures a [`Client`].
128#[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    /// Sets the credentials, instead of taking them from the environment or
145    /// the CLI's session.
146    pub fn credentials(mut self, credentials: impl Credentials + 'static) -> Self {
147        self.credentials = Some(Arc::new(credentials));
148        self
149    }
150
151    /// Sends calls to a region's front door,
152    /// `{service}.{region}.origincloudapis.eu`, for the services that have
153    /// one. It overrides `ORIGINCLOUD_REGION`; an empty region uses the
154    /// regionless endpoint. A region, from either, is `[a-z0-9-]+`, such as
155    /// `eu-central1`: [`ClientBuilder::build`] refuses any other.
156    pub fn region(mut self, region: impl Into<String>) -> Self {
157        self.region = Some(region.into());
158        self
159    }
160
161    /// Sends the calls of every service to one base URL, such as a test
162    /// server's, instead of the service's own host. [`ClientBuilder::build`]
163    /// refuses one that isn't an absolute URL with a host.
164    pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
165        self.endpoint = Some(endpoint.into());
166        self
167    }
168
169    /// Sets the HTTP client calls are sent with. Its timeout, if any,
170    /// bounds each attempt.
171    pub fn http_client(mut self, http: reqwest::Client) -> Self {
172        self.http = Some(http);
173        self
174    }
175
176    /// Adds a product, such as `my-tool/1.2`, to the `User-Agent` header.
177    pub fn user_agent(mut self, product: impl Into<String>) -> Self {
178        self.user_agent = Some(product.into());
179        self
180    }
181
182    /// Sets how often a retryable call is sent at most, the first attempt
183    /// included; 1 turns retries off. The default is 5.
184    pub fn max_attempts(mut self, attempts: u32) -> Self {
185        self.max_attempts = Some(attempts);
186        self
187    }
188
189    /// Bounds each attempt of a call by `timeout`; an attempt that takes
190    /// longer fails as a transport error, which a safe call retries. By
191    /// default, only the HTTP client's own timeout, if any, bounds it.
192    ///
193    /// Waiting on an operation asks the API to wait less than this, so that
194    /// a wait call doesn't time out on the way; see
195    /// [`ClientBuilder::operation_wait`].
196    pub fn timeout(mut self, timeout: Duration) -> Self {
197        self.timeout = Some(timeout);
198        self
199    }
200
201    /// Sets how long one call of [`Operation::wait`](crate::Operation::wait)
202    /// asks the API to wait for the operation before answering with it as
203    /// it is, in whole seconds, at least one; the default, and the most the
204    /// API waits, is a minute. With a [`ClientBuilder::timeout`], a call
205    /// asks for a second less than it at most. A wait call that times out
206    /// all the same, such as under the HTTP client's own timeout, counts as
207    /// the operation not being done yet, and the next one is sent.
208    pub fn operation_wait(mut self, wait: Duration) -> Self {
209        self.operation_wait = Some(wait);
210        self
211    }
212
213    /// Keeps the consistency token in `store` instead of in a
214    /// [`ConsistencyTokenCell`] of the client's own. Clients given the same
215    /// store share one token: each presents the token the store holds, and
216    /// each answer carrying a token replaces it there, so a read through
217    /// any of them shows the writes made through all of them, as through
218    /// one client (see [`Client::set_consistency_token`] for concurrent
219    /// writes).
220    pub fn consistency_token_store(mut self, store: Arc<dyn ConsistencyTokenStore>) -> Self {
221        self.tokens = Some(store);
222        self
223    }
224
225    /// Acts as the service account `service_account`, by its full name
226    /// (`//iam.origincloudapis.eu/organizations/{organization}/serviceAccounts/{service_account}`):
227    /// the credentials' token is exchanged at the security token service
228    /// for the account's, which every call is sent with
229    /// ([`Impersonated`](crate::Impersonated)). The credentials must give a
230    /// person's token, such as the session of `origin id login`: the STS
231    /// refuses a service account's or a workload's. The caller needs
232    /// `roles/iam.service-account-token-creator` on the account; a refused
233    /// exchange fails the call, naming the account, and the caller's own
234    /// token is never sent instead. It overrides
235    /// `ORIGINCLOUD_IMPERSONATE_SERVICE_ACCOUNT`; an empty name
236    /// impersonates no one. `ORIGINCLOUD_STS_ENDPOINT` asks another STS
237    /// than [`STS_ENDPOINT`](crate::credentials::STS_ENDPOINT).
238    /// [`ClientBuilder::build`] refuses a name that isn't a service
239    /// account's.
240    #[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    /// The client. It fails when no credentials are found or an option is
247    /// invalid.
248    pub fn build(self) -> Result<Client, Error> {
249        self.build_with(&|name| std::env::var(name).ok())
250    }
251
252    /// [`ClientBuilder::build`] with the environment read through `env`.
253    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(&region) {
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
335/// Whether `s` can be one label of a host name, as a service shortcode or
336/// a region is: `[a-z0-9-]+`.
337fn 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/// The endpoint of one service, which its generated clients send calls to,
344/// and how they send them.
345#[derive(Clone, Debug)]
346pub struct Service {
347    pub(crate) client: Client,
348    /// The base URL, or why there is none.
349    pub(crate) base: Result<Url, String>,
350    /// The service's shortcode, such as `pvs`: its host's first label, and
351    /// the service a full resource name in a path field must name.
352    pub(crate) shortcode: String,
353    pub(crate) options: CallOptions,
354}
355
356impl Service {
357    /// The same endpoint, whose calls are sent as `options` says instead of
358    /// as the client's settings do. The generated clients'
359    /// `with_options` call it.
360    pub fn with_options(&self, options: CallOptions) -> Self {
361        Self {
362            options,
363            ..self.clone()
364        }
365    }
366
367    /// How the calls are sent where they differ from the client's settings.
368    pub fn options(&self) -> &CallOptions {
369        &self.options
370    }
371
372    /// The most attempts of a retryable call: the options', else the
373    /// client's.
374    pub(crate) fn max_attempts(&self) -> u32 {
375        self.options
376            .max_attempts
377            .unwrap_or(self.client.inner.max_attempts)
378    }
379
380    /// The client the service's calls go through.
381    pub fn client(&self) -> &Client {
382        &self.client
383    }
384
385    /// The base URL calls are sent to, such as `https://pvs.origincloudapis.eu`;
386    /// `None` when the service's shortcode can't name a host.
387    pub fn base_url(&self) -> Option<&Url> {
388        self.base.as_ref().ok()
389    }
390}
391
392/// How the calls of one service client are sent, where that differs from
393/// the [`Client`]'s settings: give it to a generated client's
394/// `with_options`, such as `ProjectClient::with_options`, for the calls
395/// made through the client it returns. Waiting on an operation such a call
396/// answers with follows the client's settings again.
397///
398/// ```
399/// let once = origincloud_core::CallOptions::new().max_attempts(1);
400/// assert_eq!(once.attempts(), Some(1));
401/// ```
402#[derive(Clone, Debug, Default, PartialEq, Eq)]
403#[non_exhaustive]
404pub struct CallOptions {
405    max_attempts: Option<u32>,
406}
407
408impl CallOptions {
409    /// The client's settings, unchanged.
410    pub fn new() -> Self {
411        Self::default()
412    }
413
414    /// Sends a retryable call `attempts` times at most, the first included,
415    /// instead of [`ClientBuilder::max_attempts`]; 1, or 0, turns retries
416    /// off, for a mutation that must not be sent twice even with its
417    /// request id. A call the API refused for its consistency token alone
418    /// is sent again all the same, as the API refused it before doing
419    /// anything.
420    pub fn max_attempts(mut self, attempts: u32) -> Self {
421        self.max_attempts = Some(attempts.max(1));
422        self
423    }
424
425    /// The most attempts set, if any.
426    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}