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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use std::time;

use snafu::{ensure, ResultExt, Snafu};

use crate::client::ClientError;
use crate::{Client, Parameters};

#[derive(Debug, Snafu)]
pub enum BuildError {
    #[snafu(display("missing host"))]
    MissingHost,

    #[snafu(display("missing username"))]
    MissingUsername,

    #[snafu(display("missing password"))]
    MissingPassword,

    #[snafu(display("failed to build: {}", source))]
    Build { source: ClientError },
}

pub struct ClientBuilder {
    host: Option<String>,
    username: Option<String>,
    password: Option<String>,

    pool_idle_timeout: time::Duration,
    request_timeout: time::Duration,

    metadata_detection: bool,
}

impl ClientBuilder {
    pub fn with_host<S: Into<String>>(mut self, host: S) -> Self {
        self.host = Some(host.into());
        self
    }

    pub fn with_username<S: Into<String>>(mut self, username: S) -> Self {
        self.username = Some(username.into());
        self
    }

    pub fn with_password<S: Into<String>>(mut self, password: S) -> Self {
        self.password = Some(password.into());
        self
    }

    pub fn with_pool_idle_timeout<T: Into<time::Duration>>(mut self, timeout: T) -> Self {
        self.pool_idle_timeout = timeout.into();
        self
    }

    pub fn with_request_timeout<T: Into<time::Duration>>(mut self, timeout: T) -> Self {
        self.request_timeout = timeout.into();
        self
    }

    pub fn with_metadata_detection(mut self) -> Self {
        self.metadata_detection = true;
        self
    }

    pub async fn build(self) -> Result<Client, BuildError> {
        ensure!(self.host.is_some(), MissingHostSnafu);
        ensure!(self.password.is_some(), MissingPasswordSnafu);
        ensure!(self.username.is_some(), MissingUsernameSnafu);

        let params = Parameters {
            host: self.host.unwrap(),
            username: self.username.unwrap(),
            password: self.password.unwrap(),
            pool_idle_timeout: self.pool_idle_timeout,
            request_timeout: self.request_timeout,
        };

        Client::new_with_params(params).await.context(BuildSnafu)
    }
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self {
            host: None,
            username: None,
            password: None,
            pool_idle_timeout: time::Duration::from_secs(5),
            request_timeout: time::Duration::from_secs(60),
            metadata_detection: false,
        }
    }
}