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/// One outbound request.
179///
180/// Every field has a default — `GET`, no headers, no body — so a literal names
181/// the ones it sets and closes with `..Request::default()`.
182///
183/// ```
184/// # use simpleplatform_sdk::prelude::*;
185/// # use simpleplatform_sdk::testing;
186/// use simpleplatform_sdk::http::{self, Method};
187///
188/// #[derive(Deserialize)]
189/// struct Created {
190///     id: String,
191/// }
192///
193/// # let _session = testing::install(|_name, _params| {
194/// #     Ok(json!({ "body": { "id": "L1" }, "headers": {}, "ok": true, "status": 201 }))
195/// # });
196/// let created: Created = http::fetch(http::Request {
197///     url: "https://api.example.com/leads".to_string(),
198///     method: Method::Post,
199///     headers: http::headers(&[("Content-Type", "application/json")]),
200///     body: Some(json!({ "email": "lead@example.com" })),
201/// })?;
202///
203/// assert_eq!(created.id, "L1");
204/// # Ok::<(), Error>(())
205/// ```
206#[derive(Clone, Default)]
207pub struct Request {
208    /// The address to call. Required, and trimmed before it is sent.
209    pub url: String,
210    /// What to do to the resource. `GET` unless something else is named.
211    pub method: Method,
212    /// The headers to send, as they are written.
213    pub headers: HashMap<String, String>,
214    /// The body to send.
215    ///
216    /// A [`Value::String`] is the body itself, so a form-encoded or already
217    /// rendered payload arrives byte for byte. Anything else is sent as its
218    /// JSON text.
219    pub body: Option<Value>,
220}
221
222impl fmt::Debug for Request {
223    /// The call, and never what authorises it.
224    ///
225    /// A request carries credentials in two places an author does not think of as
226    /// secret-shaped: `Authorization` is an ordinary entry in `headers`, and a
227    /// token exchange puts a client secret in the body. Both would reach a log
228    /// line through an ordinary `{:?}`.
229    ///
230    /// So the header NAMES are rendered and their values are not, and the body is
231    /// rendered as its size. Nothing is hidden from the author -- both fields are
232    /// public and print in full when asked for directly -- and what changes is
233    /// only what an incidental `{:?}` of the whole request discloses.
234    ///
235    /// ```
236    /// use simpleplatform_sdk::http::{self, Method, Request};
237    ///
238    /// let request = Request {
239    ///     url: "https://api.example.com/leads".to_string(),
240    ///     method: Method::Get,
241    ///     headers: http::headers(&[("Authorization", "Bearer t-1234")]),
242    ///     body: None,
243    /// };
244    ///
245    /// assert!(!format!("{request:?}").contains("t-1234"));
246    /// assert!(format!("{request:?}").contains("Authorization"));
247    /// ```
248    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
249        // Sorted, because a map's own order varies between runs and a diagnostic
250        // that reorders itself is one nobody can compare against yesterday's.
251        let mut names: Vec<&str> = self.headers.keys().map(String::as_str).collect();
252        names.sort_unstable();
253
254        formatter
255            .debug_struct("Request")
256            .field("url", &self.url)
257            .field("method", &self.method)
258            .field("headers", &names)
259            .field("body", &self.body.as_ref().map(Sized_))
260            .finish()
261    }
262}
263
264/// Renders a body as how much of it there is, rather than what it says.
265struct Sized_<'a>(&'a Value);
266
267impl fmt::Debug for Sized_<'_> {
268    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
269        match self.0 {
270            Value::String(text) => write!(formatter, "<string, {} bytes>", text.len()),
271            other => write!(formatter, "<{} json bytes>", other.to_string().len()),
272        }
273    }
274}
275
276/// The headers for a request, from the pairs that make them up.
277///
278/// A header map is `HashMap<String, String>`, and this is the one line that
279/// builds one from string literals.
280///
281/// ```
282/// use simpleplatform_sdk::http;
283///
284/// let sending = http::headers(&[
285///     ("Authorization", "Bearer T"),
286///     ("Accept", "application/json"),
287/// ]);
288///
289/// assert_eq!(sending["Accept"], "application/json");
290/// ```
291pub fn headers(pairs: &[(&str, &str)]) -> HashMap<String, String> {
292    pairs
293        .iter()
294        .map(|(name, value)| ((*name).to_string(), (*value).to_string()))
295        .collect()
296}
297
298/// Make a request and answer with its body.
299///
300/// Refuses a request with no URL before anything is sent.
301///
302/// ```
303/// # use simpleplatform_sdk::prelude::*;
304/// # use simpleplatform_sdk::testing;
305/// use simpleplatform_sdk::http::{self, Method};
306///
307/// # let _session = testing::install(|_name, _params| {
308/// #     Ok(json!({ "body": "pong", "headers": {}, "ok": true, "status": 200 }))
309/// # });
310/// let answer: String = http::fetch(http::Request {
311///     url: "https://api.example.com/ping".to_string(),
312///     method: Method::Get,
313///     ..http::Request::default()
314/// })?;
315///
316/// assert_eq!(answer, "pong");
317/// # Ok::<(), Error>(())
318/// ```
319pub fn fetch<T: DeserializeOwned>(request: Request) -> Result<T, Error> {
320    let url = request.url.trim().to_string();
321
322    if url.is_empty() {
323        return Err(Error::invalid("A URL is required for an HTTP request.")
324            .hint("Set the request's url to the address to call."));
325    }
326
327    let method = request.method;
328    let request = Request { url, ..request };
329
330    let answer = host::transport()?
331        .call(HTTP_FETCH.to_string(), params(&request))
332        .map_err(|cause| {
333            cause.hint(format!(
334                "The request produced no answer. {}",
335                repeat_advice(method)
336            ))
337        })?;
338
339    let response = read(answer)?;
340
341    if !response.ok {
342        return Err(refused(method, &response));
343    }
344
345    decode(response.body)
346}
347
348/// Read a resource.
349///
350/// ```
351/// # use simpleplatform_sdk::prelude::*;
352/// # use simpleplatform_sdk::testing;
353/// # let _session = testing::install(|_name, _params| {
354/// #     Ok(json!({ "body": { "id": "L1" }, "headers": {}, "ok": true, "status": 200 }))
355/// # });
356/// let lead: Value = simple::http::get("https://api.example.com/leads/L1")?;
357///
358/// assert_eq!(lead["id"], json!("L1"));
359/// # Ok::<(), Error>(())
360/// ```
361pub fn get<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
362    fetch(request(url, Method::Get, None))
363}
364
365/// Submit to a resource.
366///
367/// ```
368/// # use simpleplatform_sdk::prelude::*;
369/// # use simpleplatform_sdk::testing;
370/// # let _session = testing::install(|_name, _params| {
371/// #     Ok(json!({ "body": { "id": "L2" }, "headers": {}, "ok": true, "status": 201 }))
372/// # });
373/// let created: Value = simple::http::post(
374///     "https://api.example.com/leads",
375///     json!({ "email": "lead@example.com" }),
376/// )?;
377///
378/// assert_eq!(created["id"], json!("L2"));
379/// # Ok::<(), Error>(())
380/// ```
381pub fn post<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
382    fetch(request(url, Method::Post, Some(body)))
383}
384
385/// Replace a resource.
386pub fn put<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
387    fetch(request(url, Method::Put, Some(body)))
388}
389
390/// Change part of a resource.
391pub fn patch<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
392    fetch(request(url, Method::Patch, Some(body)))
393}
394
395/// Remove a resource.
396///
397/// `delete` is a name Rust leaves free, so the method keeps the word it is
398/// called everywhere else — here, and in [`Method::Delete`].
399///
400/// A service that answers `204` sends no body, and no body reads as null, which
401/// is what an answer type of `()` receives:
402///
403/// ```
404/// # use simpleplatform_sdk::prelude::*;
405/// # use simpleplatform_sdk::testing;
406/// # let _session = testing::install(|_name, _params| {
407/// #     Ok(json!({ "body": "", "headers": {}, "ok": true, "status": 204 }))
408/// # });
409/// simple::http::delete::<()>("https://api.example.com/leads/L1")?;
410/// # Ok::<(), Error>(())
411/// ```
412pub fn delete<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
413    fetch(request(url, Method::Delete, None))
414}
415
416/// The request a method function makes: a URL, a method, and a body where the
417/// method carries one.
418fn request(url: &str, method: Method, body: Option<Value>) -> Request {
419    Request {
420        url: url.to_string(),
421        method,
422        headers: HashMap::new(),
423        body,
424    }
425}
426
427/// The parameters as the host reads them.
428///
429/// A member is present when it has something to say: headers that are empty and
430/// a body that was never set are left out rather than sent as nothing.
431fn params(request: &Request) -> Value {
432    let mut params = Map::new();
433
434    params.insert("url".to_string(), json!(request.url));
435    params.insert("method".to_string(), json!(request.method.as_str()));
436
437    if !request.headers.is_empty() {
438        params.insert("headers".to_string(), json!(request.headers));
439    }
440
441    if let Some(body) = &request.body {
442        params.insert("body".to_string(), json!(wire_body(body)));
443    }
444
445    Value::Object(params)
446}
447
448/// The body as the wire carries it: one string.
449fn wire_body(body: &Value) -> String {
450    match body {
451        Value::String(text) => text.clone(),
452        other => other.to_string(),
453    }
454}
455
456/// What the service answered.
457struct Response {
458    /// The status it answered with.
459    status: u64,
460    /// Whether that status carries a result.
461    ok: bool,
462    /// The body it sent.
463    body: Value,
464}
465
466/// Read the answer once, so everything below works from the same three facts.
467fn read(answer: Value) -> Result<Response, Error> {
468    let status = answer
469        .get("status")
470        .and_then(Value::as_u64)
471        .ok_or_else(|| {
472            unreadable("The answer to the request carried no HTTP status.").hint(
473                "Treat the effect as unknown and establish the outcome by reading the \
474                 resource back.",
475            )
476        })?;
477
478    let ok = answer
479        .get("ok")
480        .and_then(Value::as_bool)
481        .unwrap_or(is_success(status));
482
483    let body = match answer {
484        Value::Object(mut members) => members.remove("body").unwrap_or(Value::Null),
485        _not_an_object => Value::Null,
486    };
487
488    Ok(Response { status, ok, body })
489}
490
491/// Whether a status carries a result.
492fn is_success(status: u64) -> bool {
493    (200..300).contains(&status)
494}
495
496/// Read the body into the type the call site asked for.
497fn decode<T: DeserializeOwned>(body: Value) -> Result<T, Error> {
498    serde_json::from_value(as_json(body)).map_err(|cause| {
499        unreadable(format!(
500            "The response body does not match the type this action asked for: {cause}"
501        ))
502        .hint(
503            "Ask for a type that matches what the service answers with, or take the body as a \
504             Value and read it from there.",
505        )
506    })
507}
508
509/// The body as a JSON value.
510///
511/// A body the service sent as JSON is already one. A body it sent as text is
512/// read as JSON when it is JSON, and stays text when it is not — which is what
513/// an answer type of `String` receives. A body with nothing in it is null.
514fn as_json(body: Value) -> Value {
515    match body {
516        Value::String(text) if text.trim().is_empty() => Value::Null,
517        Value::String(text) => match serde_json::from_str(&text) {
518            Ok(json) => json,
519            Err(_text_rather_than_json) => Value::String(text),
520        },
521        already_json => already_json,
522    }
523}
524
525/// The failure for a status that carries no result.
526fn refused(method: Method, response: &Response) -> Error {
527    let status = response.status;
528
529    Error::Domain(Fault::new(
530        Code::Custom(format!("HTTP_STATUS_{status}")),
531        format!("The service answered {status}.{}", excerpt(&response.body)),
532    ))
533    .details(json!({ "status": status }))
534    .hint(status_advice(method, status))
535}
536
537/// The failure for an answer that could not be read.
538fn unreadable(message: impl Into<String>) -> Error {
539    Error::Json(Fault::new(Code::Custom(UNREADABLE.to_string()), message))
540}
541
542/// What to do about a status that carries no result.
543fn status_advice(method: Method, status: u64) -> String {
544    match status {
545        400..=499 => "The service refused the request as written. Correct the address, the \
546                      headers or the body before sending it again."
547            .to_string(),
548        500..=599 => format!(
549            "The service failed after accepting the request. {}",
550            repeat_advice(method)
551        ),
552        _other => "The service answered without delivering a result. Establish what this \
553                   status means for this service before sending the request again."
554            .to_string(),
555    }
556}
557
558/// What repeating this method costs when a call has already been made and its
559/// effect is not established.
560fn repeat_advice(method: Method) -> &'static str {
561    match method {
562        Method::Get => {
563            "A GET changes nothing, so the same call may be made again once the cause is \
564             addressed."
565        }
566        Method::Put | Method::Delete => {
567            "Treat the effect as unknown: read the resource back to establish what happened. \
568             A PUT or a DELETE sent twice reaches the same state."
569        }
570        Method::Post | Method::Patch => {
571            "Treat the effect as unknown: read the resource back before sending it again, \
572             since a POST or a PATCH sent twice can apply twice."
573        }
574    }
575}
576
577/// What the service said, as the sentence a failure carries.
578///
579/// The failure message travels within a byte budget, so the status comes first
580/// and this is bounded to what fits beside it.
581fn excerpt(body: &Value) -> String {
582    match body {
583        Value::Null => String::new(),
584        Value::String(text) => said(text),
585        rendered => said(&rendered.to_string()),
586    }
587}
588
589/// The opening of a piece of text, quoted.
590fn said(text: &str) -> String {
591    let mut characters = text.trim().chars();
592    let shown: String = characters.by_ref().take(EXCERPT_CHARS).collect();
593
594    if shown.is_empty() {
595        return String::new();
596    }
597
598    let marker = if characters.next().is_some() {
599        CUT_MARKER
600    } else {
601        ""
602    };
603
604    format!(" It said: {shown}{marker}")
605}
606
607#[cfg(test)]
608mod tests {
609    use serde_json::json;
610
611    use super::*;
612    use crate::testing;
613
614    /// The answer a host gives for a call that reached the service.
615    fn answered(status: u64, body: Value) -> Value {
616        json!({
617            "body": body,
618            "headers": { "content-type": "application/json" },
619            "ok": is_success(status),
620            "status": status,
621        })
622    }
623
624    #[test]
625    fn a_read_asks_for_the_address_and_answers_with_the_body() {
626        let session = testing::install(move |name, params| {
627            assert_eq!(name, HTTP_FETCH);
628            assert_eq!(params["url"], json!("https://api.example.com/leads/L1"));
629            assert_eq!(params["method"], json!("GET"));
630            assert_eq!(params.get("headers"), None, "no headers were asked for");
631            assert_eq!(params.get("body"), None, "a GET carries no body");
632
633            Ok(answered(200, json!({ "id": "L1" })))
634        });
635
636        #[derive(Debug, serde::Deserialize)]
637        struct Lead {
638            id: String,
639        }
640
641        let lead: Lead = get("https://api.example.com/leads/L1").unwrap();
642
643        assert_eq!(lead.id, "L1");
644        assert_eq!(session.calls().len(), 1);
645    }
646
647    #[test]
648    fn headers_and_a_body_travel_with_the_request() {
649        let session = testing::install(|_name, params| {
650            assert_eq!(params["headers"]["Authorization"], json!("Bearer T"));
651            assert_eq!(params["body"], json!(r#"{"email":"lead@example.com"}"#));
652
653            Ok(answered(201, json!({ "id": "L2" })))
654        });
655
656        let created: Value = fetch(Request {
657            url: "https://api.example.com/leads".to_string(),
658            method: Method::Post,
659            headers: headers(&[("Authorization", "Bearer T")]),
660            body: Some(json!({ "email": "lead@example.com" })),
661        })
662        .unwrap();
663
664        assert_eq!(created, json!({ "id": "L2" }));
665        assert_eq!(session.calls().len(), 1);
666    }
667
668    // The wire carries one string, and a body that is already a string is the
669    // string it carries.
670    #[test]
671    fn a_body_that_is_text_is_sent_as_itself() {
672        let _session = testing::install(|_name, params| {
673            assert_eq!(params["body"], json!("grant_type=client_credentials"));
674
675            Ok(answered(200, json!(null)))
676        });
677
678        let _: Value = post(
679            "https://api.example.com/token",
680            json!("grant_type=client_credentials"),
681        )
682        .unwrap();
683    }
684
685    #[test]
686    fn each_method_function_names_its_own_method() {
687        let session = testing::install(|_name, _params| Ok(answered(200, json!(null))));
688
689        let _: Value = get("https://api.example.com/a").unwrap();
690        let _: Value = post("https://api.example.com/a", json!({})).unwrap();
691        let _: Value = put("https://api.example.com/a", json!({})).unwrap();
692        let _: Value = patch("https://api.example.com/a", json!({})).unwrap();
693        let _: Value = delete("https://api.example.com/a").unwrap();
694
695        let sent: Vec<Value> = session
696            .calls()
697            .iter()
698            .map(|call| call.params["method"].clone())
699            .collect();
700
701        assert_eq!(
702            sent,
703            vec![
704                json!("GET"),
705                json!("POST"),
706                json!("PUT"),
707                json!("PATCH"),
708                json!("DELETE")
709            ]
710        );
711    }
712
713    #[test]
714    fn a_blank_url_is_refused_before_anything_is_sent() {
715        let session = testing::install(|_name, _params| Ok(answered(200, json!(null))));
716
717        let error = get::<Value>("   ").unwrap_err();
718
719        assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
720        assert!(session.calls().is_empty(), "nothing was sent");
721    }
722
723    #[test]
724    fn the_address_is_sent_trimmed() {
725        let _session = testing::install(|_name, params| {
726            assert_eq!(params["url"], json!("https://api.example.com/a"));
727
728            Ok(answered(200, json!(null)))
729        });
730
731        let _: Value = get("  https://api.example.com/a\n").unwrap();
732    }
733
734    // The three outcomes, told apart by the variant and by the code.
735    #[test]
736    fn a_status_outside_2xx_is_a_failure_carrying_that_status() {
737        let _session = testing::install(|_name, _params| {
738            Ok(answered(404, json!({ "detail": "no such lead" })))
739        });
740
741        let error = get::<Value>("https://api.example.com/leads/L9").unwrap_err();
742
743        assert!(matches!(error, Error::Domain(_)));
744        assert_eq!(error.code().as_str(), "HTTP_STATUS_404");
745        assert_eq!(error.fault().details(), &json!({ "status": 404 }));
746        assert!(error.message().contains("404"));
747        assert!(error.message().contains("no such lead"));
748    }
749
750    #[test]
751    fn a_request_that_produced_no_answer_is_a_different_failure() {
752        let _session = testing::install(|_name, _params| {
753            Err(Error::failed("HTTP request failed: connection refused"))
754        });
755
756        let error = get::<Value>("https://api.example.com/leads").unwrap_err();
757
758        assert!(matches!(error, Error::Host(_)));
759        assert_eq!(error.code().as_str(), "ACTION_FAILED");
760        assert!(error.message().contains("connection refused"));
761    }
762
763    #[test]
764    fn a_body_that_does_not_fit_the_answer_type_says_so() {
765        let _session = testing::install(|_name, _params| Ok(answered(200, json!({ "id": 7 }))));
766
767        #[derive(Debug, serde::Deserialize)]
768        struct Lead {
769            #[allow(dead_code)]
770            id: String,
771        }
772
773        let error = get::<Lead>("https://api.example.com/leads/L1").unwrap_err();
774
775        assert!(matches!(error, Error::Json(_)));
776        assert_eq!(error.code().as_str(), UNREADABLE);
777    }
778
779    #[test]
780    fn an_answer_with_no_status_is_read_as_unreadable() {
781        let _session = testing::install(|_name, _params| Ok(json!({ "body": { "id": "L1" } })));
782
783        let error = get::<Value>("https://api.example.com/leads/L1").unwrap_err();
784
785        assert_eq!(error.code().as_str(), UNREADABLE);
786        assert!(error.message().contains("status"));
787    }
788
789    #[test]
790    fn a_text_body_reads_into_a_string() {
791        let _session = testing::install(|_name, _params| Ok(answered(200, json!("pong"))));
792
793        let answer: String = get("https://api.example.com/ping").unwrap();
794
795        assert_eq!(answer, "pong");
796    }
797
798    #[test]
799    fn a_body_sent_as_json_text_reads_as_json() {
800        let _session =
801            testing::install(|_name, _params| Ok(answered(200, json!(r#"{"id":"L1"}"#))));
802
803        let lead: Value = get("https://api.example.com/leads/L1").unwrap();
804
805        assert_eq!(lead, json!({ "id": "L1" }));
806    }
807
808    #[test]
809    fn a_body_with_nothing_in_it_reads_as_null() {
810        let _session = testing::install(|_name, _params| Ok(answered(204, json!(""))));
811
812        let answer: Value = delete("https://api.example.com/leads/L1").unwrap();
813
814        assert_eq!(answer, json!(null));
815
816        delete::<()>("https://api.example.com/leads/L1").expect("no body is an answer of its own");
817    }
818
819    #[test]
820    fn an_answer_with_no_body_member_reads_as_null() {
821        let _session = testing::install(|_name, _params| Ok(json!({ "ok": true, "status": 200 })));
822
823        let answer: Option<String> = get("https://api.example.com/a").unwrap();
824
825        assert_eq!(answer, None);
826    }
827
828    // The status is what says whether there is an answer, so it stands on its
829    // own when the host states only that.
830    #[test]
831    fn the_status_alone_decides_a_success() {
832        let _session =
833            testing::install(|_name, _params| Ok(json!({ "body": "made", "status": 201 })));
834
835        let answer: String = post("https://api.example.com/leads", json!({})).unwrap();
836
837        assert_eq!(answer, "made");
838    }
839
840    #[test]
841    fn the_status_alone_decides_a_refusal() {
842        let _session =
843            testing::install(|_name, _params| Ok(json!({ "body": "gone", "status": 410 })));
844
845        let error = get::<Value>("https://api.example.com/leads/L1").unwrap_err();
846
847        assert_eq!(error.code().as_str(), "HTTP_STATUS_410");
848    }
849
850    // A service that refuses a request has not acted on it; a service that
851    // fails after accepting one may have.
852    #[test]
853    fn a_refusal_and_a_failure_advise_differently() {
854        let _session = testing::install(|_name, _params| Ok(answered(422, json!("bad email"))));
855
856        let refusal = post::<Value>("https://api.example.com/leads", json!({})).unwrap_err();
857
858        assert!(refusal.fault().hint().contains("refused the request"));
859
860        let _session = testing::install(|_name, _params| Ok(answered(500, json!("boom"))));
861
862        let failure = post::<Value>("https://api.example.com/leads", json!({})).unwrap_err();
863
864        assert!(failure.fault().hint().contains("can apply twice"));
865    }
866
867    #[test]
868    fn what_a_failed_call_advises_follows_the_method() {
869        assert!(repeat_advice(Method::Get).contains("changes nothing"));
870        assert!(repeat_advice(Method::Put).contains("same state"));
871        assert!(repeat_advice(Method::Delete).contains("same state"));
872        assert!(repeat_advice(Method::Post).contains("apply twice"));
873        assert!(repeat_advice(Method::Patch).contains("apply twice"));
874    }
875
876    #[test]
877    fn a_call_that_never_answered_advises_by_its_method() {
878        let _session = testing::install(|_name, _params| Err(Error::failed("timed out")));
879
880        let read = get::<Value>("https://api.example.com/a").unwrap_err();
881        let write = post::<Value>("https://api.example.com/a", json!({})).unwrap_err();
882
883        assert!(read.fault().hint().contains("changes nothing"));
884        assert!(write.fault().hint().contains("Treat the effect as unknown"));
885    }
886
887    #[test]
888    fn a_long_answer_is_quoted_up_to_what_fits() {
889        let _session = testing::install(|_name, _params| Ok(answered(500, json!("x".repeat(900)))));
890
891        let error = get::<Value>("https://api.example.com/a").unwrap_err();
892
893        assert!(error.message().ends_with(CUT_MARKER));
894        assert!(error.message().len() < 400);
895    }
896
897    #[test]
898    fn a_status_with_nothing_beside_it_is_still_a_sentence() {
899        let _session = testing::install(|_name, _params| Ok(answered(503, json!(null))));
900
901        let error = get::<Value>("https://api.example.com/a").unwrap_err();
902
903        assert_eq!(error.message(), "The service answered 503.");
904    }
905
906    #[test]
907    fn every_method_travels_under_the_name_the_wire_uses() {
908        assert_eq!(Method::default(), Method::Get);
909        assert_eq!(Method::Get.to_string(), "GET");
910        assert_eq!(Method::Post.as_str(), "POST");
911        assert_eq!(Method::Put.as_str(), "PUT");
912        assert_eq!(Method::Patch.as_str(), "PATCH");
913        assert_eq!(Method::Delete.as_str(), "DELETE");
914    }
915
916    #[test]
917    fn the_headers_a_call_names_are_the_headers_it_sends() {
918        let built = headers(&[("Accept", "application/json"), ("X-Trace", "T1")]);
919
920        assert_eq!(built["Accept"], "application/json");
921        assert_eq!(built["X-Trace"], "T1");
922        assert_eq!(built.len(), 2);
923        assert!(headers(&[]).is_empty());
924    }
925
926    // Every code this module reports is one the wire carries as written.
927    #[test]
928    fn the_codes_this_module_reports_travel_as_written() {
929        assert_eq!(
930            Code::Custom("HTTP_STATUS_404".to_string()).wire(),
931            "HTTP_STATUS_404"
932        );
933        assert_eq!(Code::Custom(UNREADABLE.to_string()).wire(), UNREADABLE);
934    }
935}