Skip to main content

epochal_api/
client.rs

1use std::env;
2use std::fmt;
3use std::hash::{BuildHasher, RandomState};
4use std::time::Duration;
5
6use chrono::{DateTime, SecondsFormat, Utc};
7
8use reqwest::header::{CONTENT_TYPE, USER_AGENT};
9use reqwest::redirect::Policy;
10use reqwest::{Method, RequestBuilder, Response};
11use serde::Serialize;
12use serde::de::DeserializeOwned;
13
14use crate::error::{Error, failure, transport};
15
16const DEFAULT_BASE_URL: &str = "https://api.epochal.com";
17pub(crate) const API_KEY_ENV: &str = "EPOCHAL_API_KEY";
18const BASE_URL_ENV: &str = "EPOCHAL_BASE_URL";
19
20const AGENT: &str = concat!("epochal-api/", env!("CARGO_PKG_VERSION"));
21const API_KEY_HEADER: &str = "x-api-key";
22const ACCEPT_DATETIME: &str = "accept-datetime";
23const IDEMPOTENCY_KEY: &str = "idempotency-key";
24const JSON: &str = "application/json";
25
26/// The longest the API holds a call that waits, such as
27/// [`TimePortal::get_sandbox`](crate::time_portal::TimePortal::get_sandbox) with a `wait`.
28pub const MAX_WAIT: Duration = Duration::from_secs(55);
29
30/// The longest the API takes to answer any call: a file write's deadline, past [`MAX_WAIT`] plus
31/// the server's own slack on a wait.
32const LONGEST_ANSWER: Duration = Duration::from_secs(80);
33
34/// An Epochal API client, from [`Client::builder`]. Each API module is a handle from it, such as
35/// [`time_portal`](Self::time_portal). Cheap to clone; clones share one connection pool.
36#[derive(Clone)]
37pub struct Client {
38    http: reqwest::Client,
39    base_url: String,
40    api_key: String,
41}
42
43/// Configures a [`Client`]. Anything not set takes its default when [`build`](Self::build) runs.
44pub struct ClientBuilder {
45    api_key: Option<String>,
46    base_url: Option<String>,
47}
48
49impl ClientBuilder {
50    /// The API key. Defaults to `EPOCHAL_API_KEY`.
51    pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
52        self.api_key = Some(api_key.into());
53        self
54    }
55
56    /// Where requests go. Defaults to `EPOCHAL_BASE_URL`, then `https://api.epochal.com`.
57    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
58        self.base_url = Some(base_url.into());
59        self
60    }
61
62    /// The client, with defaults for anything not set.
63    pub fn build(self) -> Result<Client, Error> {
64        self.build_with(|name| env::var(name).ok())
65    }
66
67    fn build_with(self, var: impl Fn(&str) -> Option<String>) -> Result<Client, Error> {
68        let or_env =
69            |value: Option<String>, name| value.or_else(|| var(name)).filter(|v| !v.is_empty());
70        let api_key = or_env(self.api_key, API_KEY_ENV).ok_or(Error::MissingApiKey)?;
71        let base_url =
72            or_env(self.base_url, BASE_URL_ENV).unwrap_or_else(|| DEFAULT_BASE_URL.to_owned());
73        let http = reqwest::Client::builder()
74            .redirect(Policy::none())
75            .connect_timeout(Duration::from_secs(10))
76            .read_timeout(LONGEST_ANSWER + Duration::from_secs(5))
77            .build()
78            .map_err(transport)?;
79        Ok(Client {
80            http,
81            base_url: base_url.trim_end_matches('/').to_owned(),
82            api_key,
83        })
84    }
85}
86
87impl Client {
88    /// A builder for a client; `Client::builder().build()` takes every default. The client never
89    /// follows redirects, which would carry the key elsewhere, gives up connecting after 10 s, and
90    /// gives up on a response that sends nothing for 85 s, 5 s past the longest the API takes to
91    /// answer (a file write).
92    pub fn builder() -> ClientBuilder {
93        ClientBuilder {
94            api_key: None,
95            base_url: None,
96        }
97    }
98
99    /// A request to `path` on the API, carrying the key.
100    pub(crate) fn request(&self, method: Method, path: &str) -> RequestBuilder {
101        self.http
102            .request(method, format!("{}{path}", self.base_url))
103            .header(API_KEY_HEADER, &self.api_key)
104            .header(USER_AGENT, AGENT)
105    }
106
107    /// The response, whatever its status.
108    pub(crate) async fn send_any(&self, request: RequestBuilder) -> Result<Response, Error> {
109        request.send().await.map_err(transport)
110    }
111
112    /// The response if it succeeded, its [`Error::Api`] if not.
113    pub(crate) async fn send(&self, request: RequestBuilder) -> Result<Response, Error> {
114        let resp = self.send_any(request).await?;
115        if resp.status().is_success() {
116            return Ok(resp);
117        }
118        Err(failure(resp).await)
119    }
120
121    /// A successful response's body, decoded.
122    pub(crate) async fn json<T: DeserializeOwned>(
123        &self,
124        request: RequestBuilder,
125    ) -> Result<T, Error> {
126        let body = self.send(request).await?.bytes().await.map_err(transport)?;
127        Ok(serde_json::from_slice(&body)?)
128    }
129}
130
131/// An instant as the API reads one: RFC 3339 in whole seconds, UTC.
132pub(crate) fn instant(at: DateTime<Utc>) -> String {
133    at.to_rfc3339_opts(SecondsFormat::Secs, true)
134}
135
136/// Holds `request` to `as_of` through `Accept-Datetime`.
137pub(crate) fn with_as_of(request: RequestBuilder, as_of: DateTime<Utc>) -> RequestBuilder {
138    request.header(ACCEPT_DATETIME, instant(as_of))
139}
140
141/// Marks `request` with `key`, so a retry the API already applied is applied once.
142pub(crate) fn with_idempotency_key(request: RequestBuilder, key: &str) -> RequestBuilder {
143    request.header(IDEMPOTENCY_KEY, key)
144}
145
146/// A fresh random idempotency key, which says nothing about the time it was made. A call that
147/// sets none sends one of these; set your own to send the same one again on a retry.
148pub fn idempotency_key() -> String {
149    let random = || RandomState::new().hash_one(0u8);
150    format!("{:016x}{:016x}", random(), random())
151}
152
153/// `request` with `body` as JSON; a value the API can't take is the caller's error.
154pub(crate) fn with_json(
155    request: RequestBuilder,
156    body: &impl Serialize,
157) -> Result<RequestBuilder, Error> {
158    let body = serde_json::to_vec(body).map_err(|e| Error::InvalidArgument(e.to_string()))?;
159    Ok(request.header(CONTENT_TYPE, JSON).body(body))
160}
161
162impl fmt::Debug for Client {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        f.debug_struct("Client")
165            .field("base_url", &self.base_url)
166            .field("api_key", &"<redacted>")
167            .finish_non_exhaustive()
168    }
169}
170
171impl fmt::Debug for ClientBuilder {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        f.debug_struct("ClientBuilder")
174            .field("base_url", &self.base_url)
175            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
176            .finish_non_exhaustive()
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
185        move |name| {
186            vars.iter()
187                .find(|(k, _)| *k == name)
188                .map(|(_, v)| (*v).to_owned())
189        }
190    }
191
192    #[test]
193    fn debug_output_never_shows_the_key() {
194        let builder = Client::builder().with_api_key("sk-secret-123");
195        assert!(!format!("{builder:?}").contains("sk-secret-123"));
196        let shown = format!("{:?}", builder.build_with(env(&[])).unwrap());
197        assert!(!shown.contains("sk-secret-123"), "{shown}");
198        assert!(shown.contains("https://api.epochal.com"), "{shown}");
199    }
200
201    #[test]
202    fn a_key_is_required_from_the_builder_or_the_environment() {
203        let no_key = Client::builder().build_with(env(&[]));
204        assert!(matches!(no_key, Err(Error::MissingApiKey)));
205        let empty = Client::builder().build_with(env(&[(API_KEY_ENV, "")]));
206        assert!(matches!(empty, Err(Error::MissingApiKey)));
207        let from_env = Client::builder()
208            .build_with(env(&[(API_KEY_ENV, "k")]))
209            .unwrap();
210        assert_eq!(from_env.api_key, "k");
211    }
212
213    #[test]
214    fn defaults_come_from_the_environment_then_production() {
215        let c = Client::builder()
216            .build_with(env(&[(API_KEY_ENV, "k")]))
217            .unwrap();
218        assert_eq!(c.base_url, "https://api.epochal.com");
219        let vars = [(API_KEY_ENV, "k"), (BASE_URL_ENV, "http://localhost:8080/")];
220        let c = Client::builder().build_with(env(&vars)).unwrap();
221        assert_eq!(c.base_url, "http://localhost:8080");
222    }
223
224    #[test]
225    fn what_the_builder_sets_wins_over_the_environment() {
226        let vars = [
227            (API_KEY_ENV, "env-key"),
228            (BASE_URL_ENV, "http://env.example"),
229        ];
230        let c = Client::builder()
231            .with_api_key("set-key")
232            .with_base_url("http://set.example/")
233            .build_with(env(&vars))
234            .unwrap();
235        assert_eq!(
236            (c.api_key.as_str(), c.base_url.as_str()),
237            ("set-key", "http://set.example")
238        );
239    }
240}