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, Default)]
207pub struct Request {
208 pub url: String,
210 pub method: Method,
212 pub headers: HashMap<String, String>,
214 pub body: Option<Value>,
220}
221
222impl fmt::Debug for Request {
223 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
249 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
264struct 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
276pub 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
298pub 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
348pub fn get<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
362 fetch(request(url, Method::Get, None))
363}
364
365pub fn post<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
382 fetch(request(url, Method::Post, Some(body)))
383}
384
385pub fn put<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
387 fetch(request(url, Method::Put, Some(body)))
388}
389
390pub fn patch<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
392 fetch(request(url, Method::Patch, Some(body)))
393}
394
395pub fn delete<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
413 fetch(request(url, Method::Delete, None))
414}
415
416fn 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
427fn 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
448fn wire_body(body: &Value) -> String {
450 match body {
451 Value::String(text) => text.clone(),
452 other => other.to_string(),
453 }
454}
455
456struct Response {
458 status: u64,
460 ok: bool,
462 body: Value,
464}
465
466fn 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
491fn is_success(status: u64) -> bool {
493 (200..300).contains(&status)
494}
495
496fn 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
509fn 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
525fn 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
537fn unreadable(message: impl Into<String>) -> Error {
539 Error::Json(Fault::new(Code::Custom(UNREADABLE.to_string()), message))
540}
541
542fn 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
558fn 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
577fn 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
589fn 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 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 #[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 #[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 #[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 #[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 #[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}