1use 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
127const HTTP_FETCH: &str = "action:http/fetch";
129
130const UNREADABLE: &str = "HTTP_RESPONSE_UNREADABLE";
132
133const EXCERPT_CHARS: usize = 240;
135
136const CUT_MARKER: &str = "...";
138
139#[non_exhaustive]
144#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
145pub enum Method {
146 #[default]
148 Get,
149 Post,
151 Put,
153 Patch,
155 Delete,
157}
158
159impl Method {
160 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
209pub enum Credentials {
210 Omit,
212 SameOrigin,
214 Include,
216}
217
218impl Credentials {
219 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#[derive(Clone, Default)]
260pub struct Request {
261 pub url: String,
263 pub method: Method,
265 pub headers: HashMap<String, String>,
267 pub body: Option<Value>,
273 pub credentials: Option<Credentials>,
277}
278
279impl fmt::Debug for Request {
280 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
306 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
322struct 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
334pub 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
356pub 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
406pub fn get<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
420 fetch(request(url, Method::Get, None))
421}
422
423pub fn post<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
440 fetch(request(url, Method::Post, Some(body)))
441}
442
443pub fn put<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
445 fetch(request(url, Method::Put, Some(body)))
446}
447
448pub fn patch<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
450 fetch(request(url, Method::Patch, Some(body)))
451}
452
453pub fn delete<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
471 fetch(request(url, Method::Delete, None))
472}
473
474fn 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
486fn 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
513fn wire_body(body: &Value) -> String {
515 match body {
516 Value::String(text) => text.clone(),
517 other => other.to_string(),
518 }
519}
520
521struct Response {
523 status: u64,
525 ok: bool,
527 body: Value,
529}
530
531fn 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
556fn is_success(status: u64) -> bool {
558 (200..300).contains(&status)
559}
560
561fn 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
574fn 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
590fn 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
602fn unreadable(message: impl Into<String>) -> Error {
604 Error::Json(Fault::new(Code::Custom(UNREADABLE.to_string()), message))
605}
606
607fn 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
623fn 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
642fn 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
654fn 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 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 #[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 #[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 #[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 #[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 #[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 #[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}