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
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use reqwest::header;
use std::{convert::TryFrom, sync::Arc, time::Duration};

pub mod batch;
pub mod billing;
mod util;

const DEFAULT_BATCH_URI: &str = "https://batch.hail.is";

#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
    #[error("{0}")]
    Header(#[from] header::InvalidHeaderValue),
    #[error("{0}")]
    Request(#[from] reqwest::Error),
    #[error("{0}")]
    InvalidUrl(#[from] url::ParseError),
    #[error("{0}")]
    Msg(std::borrow::Cow<'static, str>),
    #[error("{request_error} [{extra}]")]
    Service {
        extra: String,
        request_error: reqwest::Error,
    },
}

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Clone)]
pub struct Client {
    client: reqwest::Client,
    data: Arc<ClientData>,
}

#[derive(Debug, Clone)]
struct ClientData {
    base_url: reqwest::Url,
    billing_project: Option<String>,
}

pub struct ClientBuilder {
    billing_project: Option<String>,
    base_url: reqwest::Url,
    token: String,
    timeout: Duration,
    headers: header::HeaderMap,
}

impl Client {
    pub fn builder(token: impl Into<String>) -> ClientBuilder {
        ClientBuilder {
            token: token.into(),
            ..ClientBuilder::new()
        }
    }

    pub async fn list_billing_projects(&self) -> Result<Vec<billing::Project>> {
        self.get("/api/v1alpha/billing_projects").await
    }

    pub async fn get_billing_project<S: AsRef<str>>(&self, name: S) -> Result<billing::Project> {
        let path = format!("/api/v1alpha/billing_projects/{}", name.as_ref());
        self.get(&path).await
    }

    pub fn url(&self) -> &reqwest::Url {
        &self.data.base_url
    }

    fn join_url(&self, path: &str) -> reqwest::Url {
        let mut url = self.url().clone();
        url.set_path(path);
        url
    }

    async fn get<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T> {
        let url = self.join_url(path);
        let resp = self.client.get(url).send().await?;
        util::handle(resp)
            .await?
            .json()
            .await
            .map_err(Error::Request)
    }

    async fn patch(&self, path: &str) -> Result<reqwest::Response> {
        let url = self.join_url(path);
        util::handle(self.client.patch(url).send().await?).await
    }

    async fn post_json<T>(&self, path: &str, body: &T) -> Result<reqwest::Response>
    where
        T: serde::Serialize + ?Sized,
    {
        let url = self.join_url(path);
        let resp = self.client.post(url).json(body).send().await?;
        util::handle(resp).await
    }

    async fn post<T>(&self, path: &str, content_type: &str, body: T) -> Result<reqwest::Response>
    where
        T: Into<reqwest::Body>,
    {
        let url = self.join_url(path);
        let resp = self
            .client
            .post(url)
            .header(header::CONTENT_TYPE, content_type)
            .body(body)
            .send()
            .await?;
        util::handle(resp).await
    }
}

impl ClientBuilder {
    fn new() -> Self {
        Self {
            billing_project: None,
            base_url: reqwest::Url::parse(DEFAULT_BATCH_URI).unwrap(),
            timeout: Duration::from_secs(60),
            token: String::new(),
            headers: header::HeaderMap::new(),
        }
    }

    pub fn billing_project(mut self, project: impl Into<String>) -> Self {
        self.billing_project = Some(project.into());
        self
    }

    /// Sets the base url used for all api requests.
    ///
    /// # Default Value
    /// `https://batch.hail.is`
    ///
    /// # Notes
    /// The client will set the path when making requests, as such, any path component will be
    /// overridden. This must also be a valid http URI, like all URLs used with reqwest.
    pub fn service_url(mut self, url: impl AsRef<str>) -> Result<Self> {
        self.base_url = reqwest::Url::parse(url.as_ref())?;
        Ok(self)
    }

    /// Sets the request timeout for requests issued by the client
    ///
    /// # Default Value
    /// 60 Seconds
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Sets the Authorization header token
    pub fn token(mut self, token: impl Into<String>) -> Self {
        self.token = token.into();
        self
    }

    /// Sets an arbitrary header to be sent with all requests
    pub fn header<K>(mut self, name: K, value: header::HeaderValue) -> Self
    where
        K: header::IntoHeaderName,
    {
        self.headers.append(name, value);
        self
    }

    pub fn build(mut self) -> Result<Client> {
        let mut token = header::HeaderValue::try_from(format!("Bearer {}", self.token))?;
        token.set_sensitive(true);
        self.headers.insert(header::AUTHORIZATION, token);
        let client = reqwest::Client::builder()
            .timeout(self.timeout)
            .default_headers(self.headers)
            .build()?;
        Ok(Client {
            client,
            data: Arc::new(ClientData {
                base_url: self.base_url,
                billing_project: self.billing_project,
            }),
        })
    }
}