Skip to main content

rungbot_exec/
http.rs

1//! The one door every venue call goes through.
2//!
3//! [`Transport`] sends a request; [`Minreq`] is the real one and the only place in the
4//! crate that opens a connection. It refuses every call, signed or public, while
5//! `RUNGBOT_OFFLINE` is set, so a test or a dry run that forgets to fake its client
6//! fails loudly instead of trading. Tests swap in a scripted transport and a fixed
7//! [`Clock`], which is also how request signatures are pinned byte for byte.
8
9use std::rc::Rc;
10
11use crate::pyfmt;
12
13/// Seconds a venue call may take, for every venue.
14pub const TIMEOUT_S: u64 = 15;
15
16#[derive(Debug, Clone, PartialEq)]
17pub struct Request {
18    pub method: String,
19    pub url: String,
20    pub headers: Vec<(String, String)>,
21    pub body: Option<String>,
22    pub timeout_s: u64,
23}
24
25#[derive(Debug, Clone, PartialEq)]
26pub struct Response {
27    pub status: u16,
28    pub body: String,
29}
30
31#[derive(Debug, Clone, PartialEq)]
32pub enum SendError {
33    /// The offline switch refused the call before anything was sent.
34    Offline(String),
35    /// Nothing usable came back: DNS, TLS, timeout, reset.
36    Network(String),
37}
38
39pub trait Transport {
40    fn send(&self, req: &Request) -> Result<Response, SendError>;
41}
42
43/// Is the offline switch on? Any value but empty, `0`, `no` or `false` turns it on.
44pub fn offline() -> bool {
45    match std::env::var("RUNGBOT_OFFLINE") {
46        Ok(v) => !matches!(v.trim(), "" | "0" | "no" | "false"),
47        Err(_) => false,
48    }
49}
50
51/// The real transport.
52#[derive(Debug, Default, Clone, Copy)]
53pub struct Minreq;
54
55impl Transport for Minreq {
56    fn send(&self, req: &Request) -> Result<Response, SendError> {
57        if offline() {
58            return Err(SendError::Offline(format!(
59                "RUNGBOT_OFFLINE is set: refusing network call {} {}",
60                req.method, req.url
61            )));
62        }
63        let mut r = match req.method.as_str() {
64            "GET" => minreq::get(&req.url),
65            "POST" => minreq::post(&req.url),
66            "DELETE" => minreq::delete(&req.url),
67            "PUT" => minreq::put(&req.url),
68            m => return Err(SendError::Network(format!("unsupported method {m}"))),
69        }
70        .with_timeout(req.timeout_s);
71        for (k, v) in &req.headers {
72            r = r.with_header(k.as_str(), v.as_str());
73        }
74        if let Some(b) = &req.body {
75            r = r.with_body(b.as_str());
76        }
77        let resp = r.send().map_err(|e| SendError::Network(e.to_string()))?;
78        Ok(Response {
79            status: resp.status_code as u16,
80            body: String::from_utf8_lossy(resp.as_bytes()).into_owned(),
81        })
82    }
83}
84
85/// Wall-clock seconds, as a float. Injected so signatures and caches are testable.
86pub type Clock = Rc<dyn Fn() -> f64>;
87
88pub fn system_clock() -> Clock {
89    Rc::new(|| {
90        std::time::SystemTime::now()
91            .duration_since(std::time::UNIX_EPOCH)
92            .map(|d| d.as_secs_f64())
93            .unwrap_or(0.0)
94    })
95}
96
97/// A transport and a clock: what every client is built on.
98#[derive(Clone)]
99pub struct Http {
100    pub transport: Rc<dyn Transport>,
101    pub clock: Clock,
102}
103
104impl Default for Http {
105    fn default() -> Self {
106        Http {
107            transport: Rc::new(Minreq),
108            clock: system_clock(),
109        }
110    }
111}
112
113impl Http {
114    pub fn new(transport: Rc<dyn Transport>, clock: Clock) -> Http {
115        Http { transport, clock }
116    }
117
118    pub fn now(&self) -> f64 {
119        (self.clock)()
120    }
121}
122
123/// A failed venue call. The message is the text a caller stores in the journal and
124/// mails, `{METHOD} {path} -> {status} {body}` for a refused request.
125#[derive(Debug, Clone, PartialEq)]
126pub struct VenueError {
127    pub venue: &'static str,
128    /// The HTTP status, when one came back.
129    pub status: Option<u16>,
130    pub message: String,
131}
132
133impl VenueError {
134    pub fn new(venue: &'static str, status: Option<u16>, message: impl Into<String>) -> Self {
135        VenueError {
136            venue,
137            status,
138            message: message.into(),
139        }
140    }
141
142    /// Did the offline switch refuse it?
143    pub fn is_offline(&self) -> bool {
144        self.message.starts_with("RUNGBOT_OFFLINE is set")
145    }
146
147    /// Did the call fail on the way (a timeout, a refused or dropped connection) instead
148    /// of coming back refused? Nothing was answered, so a read may safely ask again.
149    pub fn is_network_failure(&self) -> bool {
150        self.status.is_none() && self.message.contains("<urlopen error ")
151    }
152
153    /// The venue refused the key from this address. On Gate a key without an IP
154    /// allowlist is disabled after 90 days, silently, and that is what this looks like.
155    pub fn is_ip_refusal(&self) -> bool {
156        let m = self.message.to_lowercase();
157        m.contains("ip_forbidden")
158            || m.contains("not in the ip whitelist")
159            || m.contains("ip not allowed")
160    }
161
162    /// A human hint for the failures that look like bugs and are not.
163    pub fn hint(&self) -> Option<&'static str> {
164        if self.is_ip_refusal() {
165            return Some(
166                "the venue refused this key from this IP. Either your address changed, or a \
167                 key without an IP allowlist passed its 90-day expiry. Both are fixed in the \
168                 venue's API management page, not here.",
169            );
170        }
171        if matches!(self.status, Some(401)) {
172            return Some(
173                "the venue rejected the credentials: wrong key, wrong secret, or a revoked key.",
174            );
175        }
176        None
177    }
178}
179
180impl core::fmt::Display for VenueError {
181    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
182        f.write_str(&self.message)
183    }
184}
185
186impl std::error::Error for VenueError {}
187
188/// What came back from one call, before a client decides whether it is a success.
189#[derive(Debug, Clone)]
190pub struct Reply {
191    /// `None` when nothing usable came back (network failure, or a success body that is
192    /// not JSON).
193    pub status: Option<u16>,
194    pub json: Option<serde_json::Value>,
195    /// The body text, or the failure text when `status` is `None`.
196    pub text: String,
197}
198
199impl Reply {
200    /// The body as `f"{body}"` prints it.
201    pub fn body_str(&self) -> String {
202        if self.status.is_none() || self.json.is_none() {
203            return self.text.clone();
204        }
205        pyfmt::body_str(&self.text)
206    }
207
208    /// The status as `f"{st}"` prints it.
209    pub fn status_str(&self) -> String {
210        self.status
211            .map(|s| s.to_string())
212            .unwrap_or_else(|| "None".into())
213    }
214
215    pub fn json_or_null(&self) -> serde_json::Value {
216        self.json.clone().unwrap_or(serde_json::Value::Null)
217    }
218}
219
220/// Send one request the way every public and HMAC-signed call does.
221///
222/// A 2xx body must be JSON; one that is not reads as no reply at all. An error status
223/// keeps its body, parsed when it is JSON. A network failure gives no status. Only the
224/// offline switch is an immediate error, because nothing was attempted.
225pub fn request(
226    http: &Http,
227    venue: &'static str,
228    method: &str,
229    url: &str,
230    headers: Vec<(String, String)>,
231    body: Option<String>,
232) -> Result<Reply, VenueError> {
233    let req = Request {
234        method: method.into(),
235        url: url.into(),
236        headers,
237        body,
238        timeout_s: TIMEOUT_S,
239    };
240    match http.transport.send(&req) {
241        Err(SendError::Offline(m)) => Err(VenueError::new(venue, None, m)),
242        // The wording journals have always stored for a network failure.
243        Err(SendError::Network(m)) => Ok(Reply {
244            status: None,
245            json: None,
246            text: format!("<urlopen error {m}>"),
247        }),
248        Ok(r) if (200..300).contains(&r.status) => match serde_json::from_str(&r.body) {
249            Ok(v) => Ok(Reply {
250                status: Some(r.status),
251                json: Some(v),
252                text: r.body,
253            }),
254            Err(e) => Ok(Reply {
255                status: None,
256                json: None,
257                text: e.to_string(),
258            }),
259        },
260        Ok(r) => Ok(Reply {
261            status: Some(r.status),
262            json: serde_json::from_str(&r.body).ok(),
263            text: r.body,
264        }),
265    }
266}
267
268/// Header value lookup, case-insensitive.
269pub fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
270    headers
271        .iter()
272        .find(|(k, _)| k.eq_ignore_ascii_case(name))
273        .map(|(_, v)| v.as_str())
274}
275
276pub(crate) fn hex(bytes: &[u8]) -> String {
277    bytes.iter().map(|b| format!("{b:02x}")).collect()
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    #[test]
285    fn the_real_transport_refuses_everything_offline() {
286        let _env = crate::testenv::EnvGuard::offline();
287        let e = Minreq
288            .send(&Request {
289                method: "POST".into(),
290                url: "https://example.invalid/order".into(),
291                headers: vec![],
292                body: Some("{}".into()),
293                timeout_s: 1,
294            })
295            .unwrap_err();
296        assert!(matches!(e, SendError::Offline(_)), "{e:?}");
297    }
298
299    #[test]
300    fn the_offline_switch_reads_like_a_flag() {
301        for (v, on) in [
302            ("1", true),
303            ("yes", true),
304            ("0", false),
305            ("false", false),
306            ("", false),
307        ] {
308            let _env = crate::testenv::EnvGuard::set(&[("RUNGBOT_OFFLINE", Some(v))]);
309            assert_eq!(offline(), on, "{v:?}");
310        }
311    }
312}