Skip to main content

ocre/
http.rs

1//! Outgoing HTTP requests: calling another service's API from a handler, a job or a scheduled task.
2//!
3//! A [`Request`] is built step by step (headers, a JSON or form body, a
4//! timeout) and [`Request::send`] returns a `Send` future, so axum handlers
5//! await it directly: no `worker::send::SendFuture` and no JavaScript types
6//! in the app. Every answer is a [`Response`], whatever its status; turn
7//! the non-2xx ones into errors with [`Response::error_for_status`].
8//!
9//! - Requests time out after [`DEFAULT_TIMEOUT`] (30 s) unless
10//!   [`timeout`](Request::timeout) says otherwise; the error then says so.
11//! - Redirects are followed unless [`follow_redirects(false)`](Request::follow_redirects),
12//!   for URLs a user typed (webhook endpoints), where a redirect could lead
13//!   to an address the app refused.
14//! - Errors are [`Error::Internal`] (500): the
15//!   message names the method, the URL without its query string (which may
16//!   hold credentials) and the cause.
17//!
18//! # Free plan
19//!
20//! Each `send` is one subrequest: 50 per invocation on the free plan (1,000
21//! on Workers Paid), counted with the D1, R2 and KV calls. Time spent
22//! waiting for the answer is not CPU time; parsing a JSON answer is (about
23//! 1 ms per 100 KB).
24//!
25//! # Tests
26//!
27//! `ocre test` runs the app in workerd, which can reach a server the test
28//! starts on `127.0.0.1` (`ocre::testing::FakeServer`, feature `testing`).
29//! Point the app at it with a test header read by [`test_override`]
30//! (debug builds only), so production code keeps the real URL.
31//!
32//! # Examples
33//!
34//! ```no_run
35//! use std::time::Duration;
36//!
37//! use axum::extract::State;
38//! use ocre::{Ctx, Result, http};
39//! use serde::Deserialize;
40//!
41//! #[derive(Deserialize)]
42//! struct Rates {
43//!     eur: f64,
44//! }
45//!
46//! async fn usd_to_eur(State(ctx): State<Ctx>) -> Result<String> {
47//!     let key = ctx.secret("RATES_API_KEY").await?;
48//!     let rates: Rates = http::Request::get("https://api.example.com/latest")
49//!         .query(&[("base", "usd")])
50//!         .bearer(&key)
51//!         .timeout(Duration::from_secs(5))
52//!         .send()
53//!         .await?
54//!         .error_for_status()?
55//!         .json()?;
56//!     Ok(rates.eur.to_string())
57//! }
58//! ```
59
60use std::time::Duration;
61
62use axum::http::{HeaderMap, Method};
63use serde::{Serialize, de::DeserializeOwned};
64
65use crate::{Error, Result, config::Environment};
66
67/// How long [`Request::send`] waits for an answer unless [`Request::timeout`] says otherwise: 30 seconds.
68///
69/// # Examples
70///
71/// ```
72/// assert_eq!(ocre::http::DEFAULT_TIMEOUT.as_secs(), 30);
73/// ```
74pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
75
76/// An outgoing HTTP request, built step by step and sent with [`send`](Request::send).
77///
78/// # Examples
79///
80/// ```
81/// use ocre::http::Request;
82/// use serde_json::json;
83///
84/// let request = Request::post("https://api.example.com/v1/jobs")
85///     .bearer("rk_123")
86///     .header("Idempotency-Key", "job-42")
87///     .json(&json!({"input": {"video": "a.mp4"}}));
88/// assert_eq!(request.method(), "POST");
89/// assert_eq!(request.headers(), [
90///     ("authorization".to_owned(), "Bearer rk_123".to_owned()),
91///     ("idempotency-key".to_owned(), "job-42".to_owned()),
92///     ("content-type".to_owned(), "application/json".to_owned()),
93/// ]);
94/// assert_eq!(request.body_bytes(), Some(br#"{"input":{"video":"a.mp4"}}"#.as_slice()));
95/// ```
96#[derive(Debug, Clone)]
97pub struct Request {
98    method: Method,
99    url: String,
100    headers: Vec<(String, String)>,
101    body: Option<Vec<u8>>,
102    timeout: Duration,
103    follow_redirects: bool,
104    /// A body that failed to serialize: `send` fails with it.
105    invalid: Option<String>,
106}
107
108impl Request {
109    /// A request of `method` to `url` (absolute, `https://` or `http://`).
110    ///
111    /// # Examples
112    ///
113    /// ```
114    /// use axum::http::Method;
115    ///
116    /// let request = ocre::http::Request::new(Method::OPTIONS, "https://example.com/");
117    /// assert_eq!((request.method(), request.url()), ("OPTIONS", "https://example.com/"));
118    /// ```
119    pub fn new(method: Method, url: impl Into<String>) -> Self {
120        Self {
121            method,
122            url: url.into(),
123            headers: Vec::new(),
124            body: None,
125            timeout: DEFAULT_TIMEOUT,
126            follow_redirects: true,
127            invalid: None,
128        }
129    }
130
131    /// A `GET` of `url`.
132    ///
133    /// # Examples
134    ///
135    /// ```
136    /// assert_eq!(ocre::http::Request::get("https://example.com").method(), "GET");
137    /// ```
138    pub fn get(url: impl Into<String>) -> Self {
139        Self::new(Method::GET, url)
140    }
141
142    /// A `POST` to `url`.
143    ///
144    /// # Examples
145    ///
146    /// ```
147    /// assert_eq!(ocre::http::Request::post("https://example.com").method(), "POST");
148    /// ```
149    pub fn post(url: impl Into<String>) -> Self {
150        Self::new(Method::POST, url)
151    }
152
153    /// A `PUT` to `url`.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// assert_eq!(ocre::http::Request::put("https://example.com").method(), "PUT");
159    /// ```
160    pub fn put(url: impl Into<String>) -> Self {
161        Self::new(Method::PUT, url)
162    }
163
164    /// A `PATCH` to `url`.
165    ///
166    /// # Examples
167    ///
168    /// ```
169    /// assert_eq!(ocre::http::Request::patch("https://example.com").method(), "PATCH");
170    /// ```
171    pub fn patch(url: impl Into<String>) -> Self {
172        Self::new(Method::PATCH, url)
173    }
174
175    /// A `DELETE` of `url`.
176    ///
177    /// # Examples
178    ///
179    /// ```
180    /// assert_eq!(ocre::http::Request::delete("https://example.com").method(), "DELETE");
181    /// ```
182    pub fn delete(url: impl Into<String>) -> Self {
183        Self::new(Method::DELETE, url)
184    }
185
186    /// A `HEAD` of `url`.
187    ///
188    /// # Examples
189    ///
190    /// ```
191    /// assert_eq!(ocre::http::Request::head("https://example.com").method(), "HEAD");
192    /// ```
193    pub fn head(url: impl Into<String>) -> Self {
194        Self::new(Method::HEAD, url)
195    }
196
197    /// Adds a header (the name is lowercased; a header set twice is sent twice).
198    ///
199    /// # Examples
200    ///
201    /// ```
202    /// let request = ocre::http::Request::get("https://example.com").header("Accept", "text/csv");
203    /// assert_eq!(request.headers(), [("accept".to_owned(), "text/csv".to_owned())]);
204    /// ```
205    pub fn header(mut self, name: &str, value: &str) -> Self {
206        self.headers.push((name.trim().to_ascii_lowercase(), value.trim().to_owned()));
207        self
208    }
209
210    /// Adds `Authorization: Bearer <token>`.
211    ///
212    /// # Examples
213    ///
214    /// ```
215    /// let request = ocre::http::Request::get("https://example.com").bearer("t0k");
216    /// assert_eq!(request.headers(), [("authorization".to_owned(), "Bearer t0k".to_owned())]);
217    /// ```
218    pub fn bearer(self, token: &str) -> Self {
219        let value = format!("Bearer {}", token.trim());
220        self.header("authorization", &value)
221    }
222
223    /// Appends query parameters to the URL, percent-encoded ([`percent_encode`](crate::percent_encode)).
224    ///
225    /// # Examples
226    ///
227    /// ```
228    /// let request = ocre::http::Request::get("https://example.com/search?page=2").query(&[("q", "a&b"), ("lang", "fr")]);
229    /// assert_eq!(request.url(), "https://example.com/search?page=2&q=a%26b&lang=fr");
230    /// ```
231    pub fn query(mut self, pairs: &[(&str, &str)]) -> Self {
232        for (name, value) in pairs {
233            let separator = if self.url.contains('?') { '&' } else { '?' };
234            self.url.push(separator);
235            self.url.push_str(&crate::percent_encode(name, false));
236            self.url.push('=');
237            self.url.push_str(&crate::percent_encode(value, false));
238        }
239        self
240    }
241
242    /// Sends `value` as JSON (`Content-Type: application/json`).
243    ///
244    /// A value that cannot be serialized (a map with non-string keys) makes
245    /// [`send`](Self::send) fail without sending anything.
246    ///
247    /// # Examples
248    ///
249    /// ```
250    /// let request = ocre::http::Request::post("https://example.com").json(&[1, 2]);
251    /// assert_eq!(request.body_bytes(), Some(b"[1,2]".as_slice()));
252    /// ```
253    pub fn json(self, value: &impl Serialize) -> Self {
254        match serde_json::to_vec(value) {
255            Ok(body) => self.body(body, "application/json"),
256            Err(err) => self.invalid(format!("the JSON body cannot be serialized: {err}")),
257        }
258    }
259
260    /// Sends `value` as a form (`Content-Type: application/x-www-form-urlencoded`).
261    ///
262    /// # Examples
263    ///
264    /// ```
265    /// let request = ocre::http::Request::post("https://example.com/token").form(&[("grant_type", "client_credentials")]);
266    /// assert_eq!(request.body_bytes(), Some(b"grant_type=client_credentials".as_slice()));
267    /// ```
268    pub fn form(self, value: &impl Serialize) -> Self {
269        match serde_urlencoded::to_string(value) {
270            Ok(body) => self.body(body.into_bytes(), "application/x-www-form-urlencoded"),
271            Err(err) => self.invalid(format!("the form body cannot be serialized: {err}")),
272        }
273    }
274
275    /// Sends `bytes` as the body, with `Content-Type: content_type`.
276    ///
277    /// # Examples
278    ///
279    /// ```
280    /// let request = ocre::http::Request::put("https://example.com/a.txt").body(b"hello".to_vec(), "text/plain");
281    /// assert_eq!(request.headers(), [("content-type".to_owned(), "text/plain".to_owned())]);
282    /// ```
283    pub fn body(mut self, bytes: impl Into<Vec<u8>>, content_type: &str) -> Self {
284        self.headers.retain(|(name, _)| name != "content-type");
285        self.body = Some(bytes.into());
286        self.header("content-type", content_type)
287    }
288
289    /// Gives up waiting for the answer after `timeout` (default [`DEFAULT_TIMEOUT`]).
290    ///
291    /// # Examples
292    ///
293    /// ```
294    /// use std::time::Duration;
295    ///
296    /// let request = ocre::http::Request::get("https://example.com").timeout(Duration::from_secs(5));
297    /// assert_eq!(request.timeout_duration(), Duration::from_secs(5));
298    /// ```
299    pub fn timeout(mut self, timeout: Duration) -> Self {
300        self.timeout = timeout;
301        self
302    }
303
304    /// Whether to follow redirects (default `true`); with `false`, a 3xx is the answer.
305    ///
306    /// # Examples
307    ///
308    /// ```
309    /// let request = ocre::http::Request::post("https://hooks.example.com").follow_redirects(false);
310    /// assert!(!request.follows_redirects());
311    /// ```
312    pub fn follow_redirects(mut self, follow: bool) -> Self {
313        self.follow_redirects = follow;
314        self
315    }
316
317    /// The method, uppercase.
318    pub fn method(&self) -> &str {
319        self.method.as_str()
320    }
321
322    /// The URL, query parameters included.
323    pub fn url(&self) -> &str {
324        &self.url
325    }
326
327    /// The headers, lowercase names, in the order they were added.
328    pub fn headers(&self) -> &[(String, String)] {
329        &self.headers
330    }
331
332    /// The body, if any.
333    pub fn body_bytes(&self) -> Option<&[u8]> {
334        self.body.as_deref()
335    }
336
337    /// The timeout.
338    pub fn timeout_duration(&self) -> Duration {
339        self.timeout
340    }
341
342    /// Whether redirects are followed.
343    pub fn follows_redirects(&self) -> bool {
344        self.follow_redirects
345    }
346
347    /// The URL without its query string or fragment, for error messages (a query may hold credentials).
348    pub(crate) fn display_url(&self) -> &str {
349        self.url.split(['?', '#']).next().unwrap_or_default()
350    }
351
352    /// Why the request cannot be sent, if it cannot.
353    pub(crate) fn invalid_reason(&self) -> Option<&str> {
354        self.invalid.as_deref()
355    }
356
357    fn invalid(mut self, reason: String) -> Self {
358        self.invalid = Some(reason);
359        self
360    }
361
362    /// An error about this request: `"POST https://api.example.com/v1/jobs failed: <cause>"`.
363    pub(crate) fn error(&self, cause: impl std::fmt::Display) -> Error {
364        Error::internal(format!("{} {} failed: {cause}", self.method, self.display_url()))
365    }
366}
367
368/// The answer to a [`Request`]: status, headers and the whole body.
369///
370/// # Examples
371///
372/// ```
373/// use ocre::http::Response;
374///
375/// let response = Response::new(200, Default::default(), br#"{"id": 7}"#.to_vec());
376/// assert!(response.is_success());
377/// let value: serde_json::Value = response.json().unwrap();
378/// assert_eq!(value["id"], 7);
379/// ```
380#[derive(Debug, Clone, PartialEq, Eq)]
381pub struct Response {
382    /// HTTP status (`200`, `404`...).
383    pub status: u16,
384    /// Response headers.
385    pub headers: HeaderMap,
386    /// The body, read whole.
387    pub body: Vec<u8>,
388    /// `METHOD url` of the request (no query string), for error messages.
389    request: String,
390}
391
392impl Response {
393    /// A response with this status, headers and body (for tests of code that reads responses).
394    ///
395    /// # Examples
396    ///
397    /// ```
398    /// let response = ocre::http::Response::new(404, Default::default(), Vec::new());
399    /// assert!(!response.is_success());
400    /// ```
401    pub fn new(status: u16, headers: HeaderMap, body: Vec<u8>) -> Self {
402        Self { status, headers, body, request: "the request".to_owned() }
403    }
404
405    /// The response to `request` (its method and URL name it in errors).
406    pub(crate) fn of(request: &Request, status: u16, headers: HeaderMap, body: Vec<u8>) -> Self {
407        Self { status, headers, body, request: format!("{} {}", request.method, request.display_url()) }
408    }
409
410    /// Whether the status is 2xx.
411    pub fn is_success(&self) -> bool {
412        (200..300).contains(&self.status)
413    }
414
415    /// The value of header `name` (case-insensitive), if present and text.
416    ///
417    /// # Examples
418    ///
419    /// ```
420    /// use axum::http::HeaderMap;
421    ///
422    /// let mut headers = HeaderMap::new();
423    /// headers.insert("ETag", "\"abc\"".parse().unwrap());
424    /// let response = ocre::http::Response::new(200, headers, Vec::new());
425    /// assert_eq!(response.header("etag"), Some("\"abc\""));
426    /// ```
427    pub fn header(&self, name: &str) -> Option<&str> {
428        self.headers.get(name)?.to_str().ok()
429    }
430
431    /// The body as text (invalid UTF-8 replaced).
432    ///
433    /// # Examples
434    ///
435    /// ```
436    /// assert_eq!(ocre::http::Response::new(200, Default::default(), b"ok".to_vec()).text(), "ok");
437    /// ```
438    pub fn text(&self) -> String {
439        String::from_utf8_lossy(&self.body).into_owned()
440    }
441
442    /// The body parsed as JSON.
443    ///
444    /// # Errors
445    ///
446    /// [`Error::Internal`] when the body is not
447    /// JSON of type `T`; the message quotes its first 200 characters.
448    ///
449    /// # Examples
450    ///
451    /// ```
452    /// let response = ocre::http::Response::new(200, Default::default(), b"<html>".to_vec());
453    /// assert!(response.json::<serde_json::Value>().unwrap_err().to_string().contains("<html>"));
454    /// ```
455    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
456        serde_json::from_slice(&self.body).map_err(|err| {
457            Error::internal(format!(
458                "{} answered a body that is not the JSON expected ({err}): {}",
459                self.request,
460                self.excerpt()
461            ))
462        })
463    }
464
465    /// `self` when the status is 2xx, else an error naming the request, the status and the start of the body.
466    ///
467    /// # Errors
468    ///
469    /// [`Error::Internal`] for a status outside 200-299.
470    ///
471    /// # Examples
472    ///
473    /// ```
474    /// let response = ocre::http::Response::new(503, Default::default(), b"busy".to_vec());
475    /// assert_eq!(response.error_for_status().unwrap_err().to_string(), "internal error: the request answered 503: busy");
476    /// ```
477    pub fn error_for_status(self) -> Result<Self> {
478        if self.is_success() {
479            return Ok(self);
480        }
481        Err(Error::internal(format!("{} answered {}: {}", self.request, self.status, self.excerpt())))
482    }
483
484    /// The first 200 characters of the body.
485    fn excerpt(&self) -> String {
486        self.text().chars().take(200).collect()
487    }
488}
489
490/// The value of the request header `x-ocre-test-<name>` in debug builds (`ocre dev`, `ocre test`); always `None` in release builds.
491///
492/// How request tests point the app at a fake service without a setting:
493/// the test sends `x-ocre-test-payments-api: http://127.0.0.1:41234` with its
494/// requests (`ocre::testing::Client::header`),
495/// and the code reads `http::test_override(&headers, "payments-api")
496/// .unwrap_or(API_URL)`. Release builds (`ocre deploy`) never read the
497/// header, so a visitor cannot redirect the app's calls.
498///
499/// # Examples
500///
501/// ```
502/// use axum::http::HeaderMap;
503///
504/// let mut headers = HeaderMap::new();
505/// headers.insert("x-ocre-test-payments-api", "http://127.0.0.1:41234".parse().unwrap());
506/// let base = ocre::http::test_override(&headers, "payments-api").unwrap_or("https://api.payments.example");
507/// assert_eq!(base, if cfg!(debug_assertions) { "http://127.0.0.1:41234" } else { "https://api.payments.example" });
508/// ```
509pub fn test_override<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
510    override_in(Environment::current(), headers, name)
511}
512
513/// [`test_override`] for an explicit environment.
514pub(crate) fn override_in<'a>(environment: Environment, headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
515    if !environment.is_development() {
516        return None;
517    }
518    headers.get(format!("x-ocre-test-{name}").as_str())?.to_str().ok().map(str::trim)
519}
520
521#[cfg(test)]
522#[path = "../tests/http.rs"]
523mod tests;