1use std::rc::Rc;
10
11use crate::pyfmt;
12
13pub 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 Offline(String),
35 Network(String),
37}
38
39pub trait Transport {
40 fn send(&self, req: &Request) -> Result<Response, SendError>;
41}
42
43pub 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#[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
85pub 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#[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#[derive(Debug, Clone, PartialEq)]
126pub struct VenueError {
127 pub venue: &'static str,
128 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 pub fn is_offline(&self) -> bool {
144 self.message.starts_with("RUNGBOT_OFFLINE is set")
145 }
146
147 pub fn is_network_failure(&self) -> bool {
150 self.status.is_none() && self.message.contains("<urlopen error ")
151 }
152
153 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 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#[derive(Debug, Clone)]
190pub struct Reply {
191 pub status: Option<u16>,
194 pub json: Option<serde_json::Value>,
195 pub text: String,
197}
198
199impl Reply {
200 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 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
220pub 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 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
268pub 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}