1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! This module defines the configuration and builder structs for the Materialize
//! cloud [`Client`].
//!
//! The main type exported from this module is the [`ClientBuilder`] struct,
//! which is used to configure and build instances of the [`Client`] struct. The
//! [`Client`] struct provides methods for interacting with various admin APIs,
//! such as creating and managing users, or listing passwords.
//!
use std::sync::Arc;
use std::sync::LazyLock;
use std::time::Duration;

use url::Url;

use crate::client::Client;

/// The default endpoint the client will use to issue the requests.
pub static DEFAULT_ENDPOINT: LazyLock<Url> =
    LazyLock::new(|| "https://api.cloud.materialize.com".parse().unwrap());

/// The header used by the Region API to specify which API version this client supports
pub static API_VERSION_HEADER: &str = "X-Materialize-Api-Version";

/// Configures the required parameters of a [`Client`].
pub struct ClientConfig {
    /// The authorization client to get the authorization token.
    pub auth_client: Arc<mz_frontegg_client::client::Client>,
}

/// A builder for a [`Client`].
pub struct ClientBuilder {
    /// Endpoint to issue the requests from the client.
    endpoint: Url,
}

impl Default for ClientBuilder {
    /// Returns a [`ClientBuilder`] using the default endpoint.
    fn default() -> ClientBuilder {
        ClientBuilder {
            endpoint: DEFAULT_ENDPOINT.clone(),
        }
    }
}

impl ClientBuilder {
    /// Overrides the default endpoint.
    pub fn endpoint(mut self, url: Url) -> ClientBuilder {
        self.endpoint = url;
        self
    }

    /// Creates a [`Client`] that incorporates the optional parameters
    /// configured on the builder and the specified required parameters.
    pub fn build(self, config: ClientConfig) -> Client {
        let inner = reqwest::ClientBuilder::new()
            .redirect(reqwest::redirect::Policy::none())
            .timeout(Duration::from_secs(60))
            .build()
            .unwrap();

        Client {
            auth_client: config.auth_client,
            endpoint: self.endpoint,
            inner,
        }
    }
}