Skip to main content

simpleplatform_sdk/
http.rs

1//! Calling a service outside the platform.
2//!
3//! One function does the work, and five name a method for you:
4//!
5//! ```
6//! # use simpleplatform_sdk::prelude::*;
7//! # use simpleplatform_sdk::testing;
8//! #[derive(Deserialize)]
9//! struct Rate {
10//!     usd: f64,
11//! }
12//!
13//! # let _session = testing::install(|_name, _params| {
14//! #     Ok(json!({ "body": { "usd": 1.09 }, "headers": {}, "ok": true, "status": 200 }))
15//! # });
16//! let rate: Rate = simple::http::get("https://api.example.com/rates/eur")?;
17//!
18//! assert_eq!(rate.usd, 1.09);
19//! # Ok::<(), Error>(())
20//! ```
21//!
22//! # The answer is the body
23//!
24//! A call answers with the response body, read into the type the call site asked
25//! for — the same bargain [`crate::graphql`] makes. A body the service sent as
26//! JSON is read as JSON; a body it sent as text is read as text, which is what an
27//! answer type of `String` receives; and a body with nothing in it reads as
28//! null, which is what `()` and `Option<_>` receive. The status decides whether
29//! there is an answer at all, and travels with the failure when there is not.
30//!
31//! # Three outcomes, told apart at the call site
32//!
33//! | what happened | variant | code |
34//! |---|---|---|
35//! | the request produced no answer | [`Error::Host`] | `ACTION_FAILED` |
36//! | the service answered outside 2xx | [`Error::Domain`] | `HTTP_STATUS_<status>` |
37//! | the answer did not fit the answer type | [`Error::Json`] | `HTTP_RESPONSE_UNREADABLE` |
38//!
39//! So a 404 and an unreachable host are two different things to an action, by
40//! the variant it matches on and by the code it reports, and the status a
41//! service refused on is carried in the code, the message and the details.
42//!
43//! # What a failed call says about repeating it
44//!
45//! A service that answers 4xx has refused the request, so the repair is the
46//! request. A service that answers 5xx, or that answers nothing at all, accepted
47//! the request and then failed — and what repeating it costs depends on the
48//! method, which is the same argument [`crate::graphql`] makes about a read and
49//! a write. A `GET` changes nothing and may simply be made again; a `PUT` or a
50//! `DELETE` may already have landed, and reaches the same state when it is sent
51//! twice; a `POST` or a `PATCH` may already have landed, and can apply twice.
52//! Each failure carries the sentence that fits it in its hint.
53//!
54//! # Why `get` takes a URL and nothing else
55//!
56//! Most calls carry no headers, so the five method functions take what that call
57//! needs and no more — a URL, and a body where the method has one. A call that
58//! does carry headers is a [`Request`], which is a plain struct with a
59//! [`Default`], so the fields it does not set are the ones it does not write:
60//!
61//! ```
62//! # use simpleplatform_sdk::prelude::*;
63//! # use simpleplatform_sdk::testing;
64//! use simpleplatform_sdk::http;
65//!
66//! # let _session = testing::install(|_name, _params| {
67//! #     Ok(json!({ "body": [], "headers": {}, "ok": true, "status": 200 }))
68//! # });
69//! let leads: Vec<Value> = http::fetch(http::Request {
70//!     url: "https://api.example.com/leads".to_string(),
71//!     headers: http::headers(&[("Authorization", "Bearer T")]),
72//!     ..http::Request::default()
73//! })?;
74//!
75//! assert!(leads.is_empty());
76//! # Ok::<(), Error>(())
77//! ```
78//!
79//! That is one shape rather than two: no empty map to build for the common call,
80//! no type parameter beyond the answer type, and no builder to learn — the struct
81//! literal already names every field it sets.
82//!
83//! # Two requests, two names, one file
84//!
85//! An action already has a `Request`: the one it was called with, which the
86//! prelude brings in. So an outbound request is written under the module it
87//! belongs to — `http::Request` — and both names stay available in the same
88//! file, each meaning one thing:
89//!
90//! ```
91//! # use simpleplatform_sdk::prelude::*;
92//! # use simpleplatform_sdk::testing;
93//! use simpleplatform_sdk::http;
94//!
95//! #[derive(Deserialize)]
96//! struct Input {
97//!     lead_id: String,
98//! }
99//!
100//! fn handler(request: Request<Input>) -> Result<Value, Error> {
101//!     http::fetch(http::Request {
102//!         url: format!("https://api.example.com/leads/{}", request.data.lead_id),
103//!         headers: http::headers(&[("Accept", "application/json")]),
104//!         ..http::Request::default()
105//!     })
106//! }
107//!
108//! # let _session = testing::install(|_name, _params| {
109//! #     Ok(json!({ "body": { "id": "L1" }, "headers": {}, "ok": true, "status": 200 }))
110//! # });
111//! let lead = handler(Request::new(Input { lead_id: "L1".to_string() }))?;
112//!
113//! assert_eq!(lead["id"], json!("L1"));
114//! # Ok::<(), Error>(())
115//! ```
116
117use std::collections::HashMap;
118use std::fmt;
119
120use serde::de::DeserializeOwned;
121use serde_json::{json, Map, Value};
122
123use crate::codes::Code;
124use crate::error::{Error, Fault};
125use crate::host;
126
127/// The host action that makes an outbound request.
128const HTTP_FETCH: &str = "action:http/fetch";
129
130/// The code an answer that could not be read is filed under.
131const UNREADABLE: &str = "HTTP_RESPONSE_UNREADABLE";
132
133/// How much of what a service said is quoted back in the failure message.
134const EXCERPT_CHARS: usize = 240;
135
136/// What marks a quotation that goes on past what is shown.
137const CUT_MARKER: &str = "...";
138
139/// The method a request is made with.
140///
141/// Each one says what it does to the resource it names, which is what decides
142/// whether a failed call may be made again.
143#[non_exhaustive]
144#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
145pub enum Method {
146    /// Read the resource. Changes nothing, so it may always be repeated.
147    #[default]
148    Get,
149    /// Submit to the resource. Sent twice, it can apply twice.
150    Post,
151    /// Replace the resource. Sent twice, it reaches the same state.
152    Put,
153    /// Change part of the resource. Sent twice, it can apply twice.
154    Patch,
155    /// Remove the resource. Sent twice, it reaches the same state.
156    Delete,
157}
158
159impl Method {
160    /// The method exactly as it travels on the wire.
161    pub fn as_str(&self) -> &str {
162        match self {
163            Method::Get => "GET",
164            Method::Post => "POST",
165            Method::Put => "PUT",
166            Method::Patch => "PATCH",
167            Method::Delete => "DELETE",
168        }
169    }
170}
171
172impl fmt::Display for Method {
173    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
174        formatter.write_str(self.as_str())
175    }
176}
177
178/// Whether a request made from the browser carries the page's credentials:
179/// its cookies and its HTTP authentication.
180///
181/// These are the three modes of the browser's own fetch, and the browser host
182/// hands the one a request names straight to it. A request that names none
183/// sends none, and the browser host then omits credentials. The server host
184/// makes its requests from no page, so it has no such credentials to send and
185/// ignores the mode.
186///
187/// ```
188/// # use simpleplatform_sdk::prelude::*;
189/// # use simpleplatform_sdk::testing;
190/// use simpleplatform_sdk::http::{self, Credentials};
191///
192/// # let session = testing::install(|_name, _params| {
193/// #     Ok(json!({ "body": { "user": "U1" }, "headers": {}, "ok": true, "status": 200 }))
194/// # });
195/// let signed_in: Value = http::fetch(http::Request {
196///     url: "https://api.example.com/session".to_string(),
197///     credentials: Some(Credentials::Include),
198///     ..http::Request::default()
199/// })?;
200///
201/// assert_eq!(signed_in["user"], json!("U1"));
202/// # assert_eq!(session.calls()[0].params["credentials"], json!("include"));
203/// # Ok::<(), Error>(())
204/// ```
205///
206/// A cross-origin request that includes them still needs the service to allow
207/// the page's origin and credentials through CORS.
208#[derive(Clone, Copy, Debug, PartialEq, Eq)]
209pub enum Credentials {
210    /// Send no cookies and no HTTP authentication.
211    Omit,
212    /// Send them only to the page's own origin.
213    SameOrigin,
214    /// Send them to any origin, a cross-origin one included.
215    Include,
216}
217
218impl Credentials {
219    /// The mode exactly as it travels on the wire.
220    pub fn as_str(&self) -> &str {
221        match self {
222            Credentials::Omit => "omit",
223            Credentials::SameOrigin => "same-origin",
224            Credentials::Include => "include",
225        }
226    }
227}
228
229/// One outbound request.
230///
231/// Every field has a default — `GET`, no headers, no body, no credentials
232/// mode — so a literal names the ones it sets and closes with
233/// `..Request::default()`.
234///
235/// ```
236/// # use simpleplatform_sdk::prelude::*;
237/// # use simpleplatform_sdk::testing;
238/// use simpleplatform_sdk::http::{self, Method};
239///
240/// #[derive(Deserialize)]
241/// struct Created {
242///     id: String,
243/// }
244///
245/// # let _session = testing::install(|_name, _params| {
246/// #     Ok(json!({ "body": { "id": "L1" }, "headers": {}, "ok": true, "status": 201 }))
247/// # });
248/// let created: Created = http::fetch(http::Request {
249///     url: "https://api.example.com/leads".to_string(),
250///     method: Method::Post,
251///     headers: http::headers(&[("Content-Type", "application/json")]),
252///     body: Some(json!({ "email": "lead@example.com" })),
253///     ..http::Request::default()
254/// })?;
255///
256/// assert_eq!(created.id, "L1");
257/// # Ok::<(), Error>(())
258/// ```
259#[derive(Clone, Default)]
260pub struct Request {
261    /// The address to call. Required, and trimmed before it is sent.
262    pub url: String,
263    /// What to do to the resource. `GET` unless something else is named.
264    pub method: Method,
265    /// The headers to send, as they are written.
266    pub headers: HashMap<String, String>,
267    /// The body to send.
268    ///
269    /// A [`Value::String`] is the body itself, so a form-encoded or already
270    /// rendered payload arrives byte for byte. Anything else is sent as its
271    /// JSON text.
272    pub body: Option<Value>,
273    /// Whether a request made from the browser carries the page's cookies and
274    /// HTTP authentication. `None` names no mode, and the browser host then
275    /// omits them. See [`Credentials`].
276    pub credentials: Option<Credentials>,
277}
278
279impl fmt::Debug for Request {
280    /// The call, and never what authorises it.
281    ///
282    /// A request carries credentials in two places an author does not think of as
283    /// secret-shaped: `Authorization` is an ordinary entry in `headers`, and a
284    /// token exchange puts a client secret in the body. Both would reach a log
285    /// line through an ordinary `{:?}`.
286    ///
287    /// So the header NAMES are rendered and their values are not, and the body is
288    /// rendered as its size. Nothing is hidden from the author -- both fields are
289    /// public and print in full when asked for directly -- and what changes is
290    /// only what an incidental `{:?}` of the whole request discloses.
291    ///
292    /// ```
293    /// use simpleplatform_sdk::http::{self, Method, Request};
294    ///
295    /// let request = Request {
296    ///     url: "https://api.example.com/leads".to_string(),
297    ///     method: Method::Get,
298    ///     headers: http::headers(&[("Authorization", "Bearer t-1234")]),
299    ///     ..Request::default()
300    /// };
301    ///
302    /// assert!(!format!("{request:?}").contains("t-1234"));
303    /// assert!(format!("{request:?}").contains("Authorization"));
304    /// ```
305    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
306        // Sorted, because a map's own order varies between runs and a diagnostic
307        // that reorders itself is one nobody can compare against yesterday's.
308        let mut names: Vec<&str> = self.headers.keys().map(String::as_str).collect();
309        names.sort_unstable();
310
311        formatter
312            .debug_struct("Request")
313            .field("url", &self.url)
314            .field("method", &self.method)
315            .field("headers", &names)
316            .field("body", &self.body.as_ref().map(Sized_))
317            .field("credentials", &self.credentials)
318            .finish()
319    }
320}
321
322/// Renders a body as how much of it there is, rather than what it says.
323struct Sized_<'a>(&'a Value);
324
325impl fmt::Debug for Sized_<'_> {
326    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
327        match self.0 {
328            Value::String(text) => write!(formatter, "<string, {} bytes>", text.len()),
329            other => write!(formatter, "<{} json bytes>", other.to_string().len()),
330        }
331    }
332}
333
334/// The headers for a request, from the pairs that make them up.
335///
336/// A header map is `HashMap<String, String>`, and this is the one line that
337/// builds one from string literals.
338///
339/// ```
340/// use simpleplatform_sdk::http;
341///
342/// let sending = http::headers(&[
343///     ("Authorization", "Bearer T"),
344///     ("Accept", "application/json"),
345/// ]);
346///
347/// assert_eq!(sending["Accept"], "application/json");
348/// ```
349pub fn headers(pairs: &[(&str, &str)]) -> HashMap<String, String> {
350    pairs
351        .iter()
352        .map(|(name, value)| ((*name).to_string(), (*value).to_string()))
353        .collect()
354}
355
356/// Make a request and answer with its body.
357///
358/// Refuses a request with no URL before anything is sent.
359///
360/// ```
361/// # use simpleplatform_sdk::prelude::*;
362/// # use simpleplatform_sdk::testing;
363/// use simpleplatform_sdk::http::{self, Method};
364///
365/// # let _session = testing::install(|_name, _params| {
366/// #     Ok(json!({ "body": "pong", "headers": {}, "ok": true, "status": 200 }))
367/// # });
368/// let answer: String = http::fetch(http::Request {
369///     url: "https://api.example.com/ping".to_string(),
370///     method: Method::Get,
371///     ..http::Request::default()
372/// })?;
373///
374/// assert_eq!(answer, "pong");
375/// # Ok::<(), Error>(())
376/// ```
377pub fn fetch<T: DeserializeOwned>(request: Request) -> Result<T, Error> {
378    let url = request.url.trim().to_string();
379
380    if url.is_empty() {
381        return Err(Error::invalid("A URL is required for an HTTP request.")
382            .hint("Set the request's url to the address to call."));
383    }
384
385    let method = request.method;
386    let request = Request { url, ..request };
387
388    let answer = host::transport()?
389        .call(HTTP_FETCH.to_string(), params(&request))
390        .map_err(|cause| {
391            cause.hint(format!(
392                "The request produced no answer. {}",
393                repeat_advice(method)
394            ))
395        })?;
396
397    let response = read(answer)?;
398
399    if !response.ok {
400        return Err(refused(method, &response));
401    }
402
403    decode(response.body)
404}
405
406/// Read a resource.
407///
408/// ```
409/// # use simpleplatform_sdk::prelude::*;
410/// # use simpleplatform_sdk::testing;
411/// # let _session = testing::install(|_name, _params| {
412/// #     Ok(json!({ "body": { "id": "L1" }, "headers": {}, "ok": true, "status": 200 }))
413/// # });
414/// let lead: Value = simple::http::get("https://api.example.com/leads/L1")?;
415///
416/// assert_eq!(lead["id"], json!("L1"));
417/// # Ok::<(), Error>(())
418/// ```
419pub fn get<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
420    fetch(request(url, Method::Get, None))
421}
422
423/// Submit to a resource.
424///
425/// ```
426/// # use simpleplatform_sdk::prelude::*;
427/// # use simpleplatform_sdk::testing;
428/// # let _session = testing::install(|_name, _params| {
429/// #     Ok(json!({ "body": { "id": "L2" }, "headers": {}, "ok": true, "status": 201 }))
430/// # });
431/// let created: Value = simple::http::post(
432///     "https://api.example.com/leads",
433///     json!({ "email": "lead@example.com" }),
434/// )?;
435///
436/// assert_eq!(created["id"], json!("L2"));
437/// # Ok::<(), Error>(())
438/// ```
439pub fn post<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
440    fetch(request(url, Method::Post, Some(body)))
441}
442
443/// Replace a resource.
444pub fn put<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
445    fetch(request(url, Method::Put, Some(body)))
446}
447
448/// Change part of a resource.
449pub fn patch<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
450    fetch(request(url, Method::Patch, Some(body)))
451}
452
453/// Remove a resource.
454///
455/// `delete` is a name Rust leaves free, so the method keeps the word it is
456/// called everywhere else — here, and in [`Method::Delete`].
457///
458/// A service that answers `204` sends no body, and no body reads as null, which
459/// is what an answer type of `()` receives:
460///
461/// ```
462/// # use simpleplatform_sdk::prelude::*;
463/// # use simpleplatform_sdk::testing;
464/// # let _session = testing::install(|_name, _params| {
465/// #     Ok(json!({ "body": "", "headers": {}, "ok": true, "status": 204 }))
466/// # });
467/// simple::http::delete::<()>("https://api.example.com/leads/L1")?;
468/// # Ok::<(), Error>(())
469/// ```
470pub fn delete<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
471    fetch(request(url, Method::Delete, None))
472}
473
474/// The request a method function makes: a URL, a method, and a body where the
475/// method carries one.
476fn request(url: &str, method: Method, body: Option<Value>) -> Request {
477    Request {
478        url: url.to_string(),
479        method,
480        headers: HashMap::new(),
481        body,
482        credentials: None,
483    }
484}
485
486/// The parameters as the host reads them.
487///
488/// A member is present when it has something to say: headers that are empty, a
489/// body that was never set and a credentials mode that was never named are left
490/// out rather than sent as nothing. So the host's own default is the one that
491/// applies to a request that names no mode.
492fn params(request: &Request) -> Value {
493    let mut params = Map::new();
494
495    params.insert("url".to_string(), json!(request.url));
496    params.insert("method".to_string(), json!(request.method.as_str()));
497
498    if !request.headers.is_empty() {
499        params.insert("headers".to_string(), json!(request.headers));
500    }
501
502    if let Some(body) = &request.body {
503        params.insert("body".to_string(), json!(wire_body(body)));
504    }
505
506    if let Some(credentials) = request.credentials {
507        params.insert("credentials".to_string(), json!(credentials.as_str()));
508    }
509
510    Value::Object(params)
511}
512
513/// The body as the wire carries it: one string.
514fn wire_body(body: &Value) -> String {
515    match body {
516        Value::String(text) => text.clone(),
517        other => other.to_string(),
518    }
519}
520
521/// What the service answered.
522struct Response {
523    /// The status it answered with.
524    status: u64,
525    /// Whether that status carries a result.
526    ok: bool,
527    /// The body it sent.
528    body: Value,
529}
530
531/// Read the answer once, so everything below works from the same three facts.
532fn read(answer: Value) -> Result<Response, Error> {
533    let status = answer
534        .get("status")
535        .and_then(Value::as_u64)
536        .ok_or_else(|| {
537            unreadable("The answer to the request carried no HTTP status.").hint(
538                "Treat the effect as unknown and establish the outcome by reading the \
539                 resource back.",
540            )
541        })?;
542
543    let ok = answer
544        .get("ok")
545        .and_then(Value::as_bool)
546        .unwrap_or(is_success(status));
547
548    let body = match answer {
549        Value::Object(mut members) => members.remove("body").unwrap_or(Value::Null),
550        _not_an_object => Value::Null,
551    };
552
553    Ok(Response { status, ok, body })
554}
555
556/// Whether a status carries a result.
557fn is_success(status: u64) -> bool {
558    (200..300).contains(&status)
559}
560
561/// Read the body into the type the call site asked for.
562fn decode<T: DeserializeOwned>(body: Value) -> Result<T, Error> {
563    serde_json::from_value(as_json(body)).map_err(|cause| {
564        unreadable(format!(
565            "The response body does not match the type this action asked for: {cause}"
566        ))
567        .hint(
568            "Ask for a type that matches what the service answers with, or take the body as a \
569             Value and read it from there.",
570        )
571    })
572}
573
574/// The body as a JSON value.
575///
576/// A body the service sent as JSON is already one. A body it sent as text is
577/// read as JSON when it is JSON, and stays text when it is not — which is what
578/// an answer type of `String` receives. A body with nothing in it is null.
579fn as_json(body: Value) -> Value {
580    match body {
581        Value::String(text) if text.trim().is_empty() => Value::Null,
582        Value::String(text) => match serde_json::from_str(&text) {
583            Ok(json) => json,
584            Err(_text_rather_than_json) => Value::String(text),
585        },
586        already_json => already_json,
587    }
588}
589
590/// The failure for a status that carries no result.
591fn refused(method: Method, response: &Response) -> Error {
592    let status = response.status;
593
594    Error::Domain(Fault::new(
595        Code::Custom(format!("HTTP_STATUS_{status}")),
596        format!("The service answered {status}.{}", excerpt(&response.body)),
597    ))
598    .details(json!({ "status": status }))
599    .hint(status_advice(method, status))
600}
601
602/// The failure for an answer that could not be read.
603fn unreadable(message: impl Into<String>) -> Error {
604    Error::Json(Fault::new(Code::Custom(UNREADABLE.to_string()), message))
605}
606
607/// What to do about a status that carries no result.
608fn status_advice(method: Method, status: u64) -> String {
609    match status {
610        400..=499 => "The service refused the request as written. Correct the address, the \
611                      headers or the body before sending it again."
612            .to_string(),
613        500..=599 => format!(
614            "The service failed after accepting the request. {}",
615            repeat_advice(method)
616        ),
617        _other => "The service answered without delivering a result. Establish what this \
618                   status means for this service before sending the request again."
619            .to_string(),
620    }
621}
622
623/// What repeating this method costs when a call has already been made and its
624/// effect is not established.
625fn repeat_advice(method: Method) -> &'static str {
626    match method {
627        Method::Get => {
628            "A GET changes nothing, so the same call may be made again once the cause is \
629             addressed."
630        }
631        Method::Put | Method::Delete => {
632            "Treat the effect as unknown: read the resource back to establish what happened. \
633             A PUT or a DELETE sent twice reaches the same state."
634        }
635        Method::Post | Method::Patch => {
636            "Treat the effect as unknown: read the resource back before sending it again, \
637             since a POST or a PATCH sent twice can apply twice."
638        }
639    }
640}
641
642/// What the service said, as the sentence a failure carries.
643///
644/// The failure message travels within a byte budget, so the status comes first
645/// and this is bounded to what fits beside it.
646fn excerpt(body: &Value) -> String {
647    match body {
648        Value::Null => String::new(),
649        Value::String(text) => said(text),
650        rendered => said(&rendered.to_string()),
651    }
652}
653
654/// The opening of a piece of text, quoted.
655fn said(text: &str) -> String {
656    let mut characters = text.trim().chars();
657    let shown: String = characters.by_ref().take(EXCERPT_CHARS).collect();
658
659    if shown.is_empty() {
660        return String::new();
661    }
662
663    let marker = if characters.next().is_some() {
664        CUT_MARKER
665    } else {
666        ""
667    };
668
669    format!(" It said: {shown}{marker}")
670}
671
672#[cfg(test)]
673mod tests {
674    use serde_json::json;
675
676    use super::*;
677    use crate::testing;
678
679    /// The answer a host gives for a call that reached the service.
680    fn answered(status: u64, body: Value) -> Value {
681        json!({
682            "body": body,
683            "headers": { "content-type": "application/json" },
684            "ok": is_success(status),
685            "status": status,
686        })
687    }
688
689    #[test]
690    fn a_read_asks_for_the_address_and_answers_with_the_body() {
691        let session = testing::install(move |name, params| {
692            assert_eq!(name, HTTP_FETCH);
693            assert_eq!(params["url"], json!("https://api.example.com/leads/L1"));
694            assert_eq!(params["method"], json!("GET"));
695            assert_eq!(params.get("headers"), None, "no headers were asked for");
696            assert_eq!(params.get("body"), None, "a GET carries no body");
697            assert_eq!(
698                params.get("credentials"),
699                None,
700                "no credentials mode was named"
701            );
702
703            Ok(answered(200, json!({ "id": "L1" })))
704        });
705
706        #[derive(Debug, serde::Deserialize)]
707        struct Lead {
708            id: String,
709        }
710
711        let lead: Lead = get("https://api.example.com/leads/L1").unwrap();
712
713        assert_eq!(lead.id, "L1");
714        assert_eq!(session.calls().len(), 1);
715    }
716
717    #[test]
718    fn headers_and_a_body_travel_with_the_request() {
719        let session = testing::install(|_name, params| {
720            assert_eq!(params["headers"]["Authorization"], json!("Bearer T"));
721            assert_eq!(params["body"], json!(r#"{"email":"lead@example.com"}"#));
722
723            Ok(answered(201, json!({ "id": "L2" })))
724        });
725
726        let created: Value = fetch(Request {
727            url: "https://api.example.com/leads".to_string(),
728            method: Method::Post,
729            headers: headers(&[("Authorization", "Bearer T")]),
730            body: Some(json!({ "email": "lead@example.com" })),
731            ..Request::default()
732        })
733        .unwrap();
734
735        assert_eq!(created, json!({ "id": "L2" }));
736        assert_eq!(session.calls().len(), 1);
737    }
738
739    // The wire carries one string, and a body that is already a string is the
740    // string it carries.
741    #[test]
742    fn a_body_that_is_text_is_sent_as_itself() {
743        let _session = testing::install(|_name, params| {
744            assert_eq!(params["body"], json!("grant_type=client_credentials"));
745
746            Ok(answered(200, json!(null)))
747        });
748
749        let _: Value = post(
750            "https://api.example.com/token",
751            json!("grant_type=client_credentials"),
752        )
753        .unwrap();
754    }
755
756    // The mode travels in the words the browser's own fetch takes.
757    #[test]
758    fn a_credentials_mode_travels_as_the_browser_names_it() {
759        let session = testing::install(|_name, _params| Ok(answered(200, json!(null))));
760
761        for credentials in [
762            Credentials::Omit,
763            Credentials::SameOrigin,
764            Credentials::Include,
765        ] {
766            let _: Value = fetch(Request {
767                url: "https://api.example.com/session".to_string(),
768                credentials: Some(credentials),
769                ..Request::default()
770            })
771            .unwrap();
772        }
773
774        let sent: Vec<Value> = session
775            .calls()
776            .iter()
777            .map(|call| call.params["credentials"].clone())
778            .collect();
779
780        assert_eq!(
781            sent,
782            vec![json!("omit"), json!("same-origin"), json!("include")]
783        );
784    }
785
786    #[test]
787    fn each_method_function_names_its_own_method() {
788        let session = testing::install(|_name, _params| Ok(answered(200, json!(null))));
789
790        let _: Value = get("https://api.example.com/a").unwrap();
791        let _: Value = post("https://api.example.com/a", json!({})).unwrap();
792        let _: Value = put("https://api.example.com/a", json!({})).unwrap();
793        let _: Value = patch("https://api.example.com/a", json!({})).unwrap();
794        let _: Value = delete("https://api.example.com/a").unwrap();
795
796        let sent: Vec<Value> = session
797            .calls()
798            .iter()
799            .map(|call| call.params["method"].clone())
800            .collect();
801
802        assert_eq!(
803            sent,
804            vec![
805                json!("GET"),
806                json!("POST"),
807                json!("PUT"),
808                json!("PATCH"),
809                json!("DELETE")
810            ]
811        );
812    }
813
814    #[test]
815    fn a_blank_url_is_refused_before_anything_is_sent() {
816        let session = testing::install(|_name, _params| Ok(answered(200, json!(null))));
817
818        let error = get::<Value>("   ").unwrap_err();
819
820        assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
821        assert!(session.calls().is_empty(), "nothing was sent");
822    }
823
824    #[test]
825    fn the_address_is_sent_trimmed() {
826        let _session = testing::install(|_name, params| {
827            assert_eq!(params["url"], json!("https://api.example.com/a"));
828
829            Ok(answered(200, json!(null)))
830        });
831
832        let _: Value = get("  https://api.example.com/a\n").unwrap();
833    }
834
835    // The three outcomes, told apart by the variant and by the code.
836    #[test]
837    fn a_status_outside_2xx_is_a_failure_carrying_that_status() {
838        let _session = testing::install(|_name, _params| {
839            Ok(answered(404, json!({ "detail": "no such lead" })))
840        });
841
842        let error = get::<Value>("https://api.example.com/leads/L9").unwrap_err();
843
844        assert!(matches!(error, Error::Domain(_)));
845        assert_eq!(error.code().as_str(), "HTTP_STATUS_404");
846        assert_eq!(error.fault().details(), &json!({ "status": 404 }));
847        assert!(error.message().contains("404"));
848        assert!(error.message().contains("no such lead"));
849    }
850
851    #[test]
852    fn a_request_that_produced_no_answer_is_a_different_failure() {
853        let _session = testing::install(|_name, _params| {
854            Err(Error::failed("HTTP request failed: connection refused"))
855        });
856
857        let error = get::<Value>("https://api.example.com/leads").unwrap_err();
858
859        assert!(matches!(error, Error::Host(_)));
860        assert_eq!(error.code().as_str(), "ACTION_FAILED");
861        assert!(error.message().contains("connection refused"));
862    }
863
864    #[test]
865    fn a_body_that_does_not_fit_the_answer_type_says_so() {
866        let _session = testing::install(|_name, _params| Ok(answered(200, json!({ "id": 7 }))));
867
868        #[derive(Debug, serde::Deserialize)]
869        struct Lead {
870            #[allow(dead_code)]
871            id: String,
872        }
873
874        let error = get::<Lead>("https://api.example.com/leads/L1").unwrap_err();
875
876        assert!(matches!(error, Error::Json(_)));
877        assert_eq!(error.code().as_str(), UNREADABLE);
878    }
879
880    #[test]
881    fn an_answer_with_no_status_is_read_as_unreadable() {
882        let _session = testing::install(|_name, _params| Ok(json!({ "body": { "id": "L1" } })));
883
884        let error = get::<Value>("https://api.example.com/leads/L1").unwrap_err();
885
886        assert_eq!(error.code().as_str(), UNREADABLE);
887        assert!(error.message().contains("status"));
888    }
889
890    #[test]
891    fn a_text_body_reads_into_a_string() {
892        let _session = testing::install(|_name, _params| Ok(answered(200, json!("pong"))));
893
894        let answer: String = get("https://api.example.com/ping").unwrap();
895
896        assert_eq!(answer, "pong");
897    }
898
899    #[test]
900    fn a_body_sent_as_json_text_reads_as_json() {
901        let _session =
902            testing::install(|_name, _params| Ok(answered(200, json!(r#"{"id":"L1"}"#))));
903
904        let lead: Value = get("https://api.example.com/leads/L1").unwrap();
905
906        assert_eq!(lead, json!({ "id": "L1" }));
907    }
908
909    #[test]
910    fn a_body_with_nothing_in_it_reads_as_null() {
911        let _session = testing::install(|_name, _params| Ok(answered(204, json!(""))));
912
913        let answer: Value = delete("https://api.example.com/leads/L1").unwrap();
914
915        assert_eq!(answer, json!(null));
916
917        delete::<()>("https://api.example.com/leads/L1").expect("no body is an answer of its own");
918    }
919
920    #[test]
921    fn an_answer_with_no_body_member_reads_as_null() {
922        let _session = testing::install(|_name, _params| Ok(json!({ "ok": true, "status": 200 })));
923
924        let answer: Option<String> = get("https://api.example.com/a").unwrap();
925
926        assert_eq!(answer, None);
927    }
928
929    // The status is what says whether there is an answer, so it stands on its
930    // own when the host states only that.
931    #[test]
932    fn the_status_alone_decides_a_success() {
933        let _session =
934            testing::install(|_name, _params| Ok(json!({ "body": "made", "status": 201 })));
935
936        let answer: String = post("https://api.example.com/leads", json!({})).unwrap();
937
938        assert_eq!(answer, "made");
939    }
940
941    #[test]
942    fn the_status_alone_decides_a_refusal() {
943        let _session =
944            testing::install(|_name, _params| Ok(json!({ "body": "gone", "status": 410 })));
945
946        let error = get::<Value>("https://api.example.com/leads/L1").unwrap_err();
947
948        assert_eq!(error.code().as_str(), "HTTP_STATUS_410");
949    }
950
951    // A service that refuses a request has not acted on it; a service that
952    // fails after accepting one may have.
953    #[test]
954    fn a_refusal_and_a_failure_advise_differently() {
955        let _session = testing::install(|_name, _params| Ok(answered(422, json!("bad email"))));
956
957        let refusal = post::<Value>("https://api.example.com/leads", json!({})).unwrap_err();
958
959        assert!(refusal.fault().hint().contains("refused the request"));
960
961        let _session = testing::install(|_name, _params| Ok(answered(500, json!("boom"))));
962
963        let failure = post::<Value>("https://api.example.com/leads", json!({})).unwrap_err();
964
965        assert!(failure.fault().hint().contains("can apply twice"));
966    }
967
968    #[test]
969    fn what_a_failed_call_advises_follows_the_method() {
970        assert!(repeat_advice(Method::Get).contains("changes nothing"));
971        assert!(repeat_advice(Method::Put).contains("same state"));
972        assert!(repeat_advice(Method::Delete).contains("same state"));
973        assert!(repeat_advice(Method::Post).contains("apply twice"));
974        assert!(repeat_advice(Method::Patch).contains("apply twice"));
975    }
976
977    #[test]
978    fn a_call_that_never_answered_advises_by_its_method() {
979        let _session = testing::install(|_name, _params| Err(Error::failed("timed out")));
980
981        let read = get::<Value>("https://api.example.com/a").unwrap_err();
982        let write = post::<Value>("https://api.example.com/a", json!({})).unwrap_err();
983
984        assert!(read.fault().hint().contains("changes nothing"));
985        assert!(write.fault().hint().contains("Treat the effect as unknown"));
986    }
987
988    #[test]
989    fn a_long_answer_is_quoted_up_to_what_fits() {
990        let _session = testing::install(|_name, _params| Ok(answered(500, json!("x".repeat(900)))));
991
992        let error = get::<Value>("https://api.example.com/a").unwrap_err();
993
994        assert!(error.message().ends_with(CUT_MARKER));
995        assert!(error.message().len() < 400);
996    }
997
998    #[test]
999    fn a_status_with_nothing_beside_it_is_still_a_sentence() {
1000        let _session = testing::install(|_name, _params| Ok(answered(503, json!(null))));
1001
1002        let error = get::<Value>("https://api.example.com/a").unwrap_err();
1003
1004        assert_eq!(error.message(), "The service answered 503.");
1005    }
1006
1007    #[test]
1008    fn every_method_travels_under_the_name_the_wire_uses() {
1009        assert_eq!(Method::default(), Method::Get);
1010        assert_eq!(Method::Get.to_string(), "GET");
1011        assert_eq!(Method::Post.as_str(), "POST");
1012        assert_eq!(Method::Put.as_str(), "PUT");
1013        assert_eq!(Method::Patch.as_str(), "PATCH");
1014        assert_eq!(Method::Delete.as_str(), "DELETE");
1015    }
1016
1017    #[test]
1018    fn the_headers_a_call_names_are_the_headers_it_sends() {
1019        let built = headers(&[("Accept", "application/json"), ("X-Trace", "T1")]);
1020
1021        assert_eq!(built["Accept"], "application/json");
1022        assert_eq!(built["X-Trace"], "T1");
1023        assert_eq!(built.len(), 2);
1024        assert!(headers(&[]).is_empty());
1025    }
1026
1027    // Every code this module reports is one the wire carries as written.
1028    #[test]
1029    fn the_codes_this_module_reports_travel_as_written() {
1030        assert_eq!(
1031            Code::Custom("HTTP_STATUS_404".to_string()).wire(),
1032            "HTTP_STATUS_404"
1033        );
1034        assert_eq!(Code::Custom(UNREADABLE.to_string()).wire(), UNREADABLE);
1035    }
1036}