use std::collections::HashMap;
use std::fmt;
use serde::de::DeserializeOwned;
use serde_json::{json, Map, Value};
use crate::codes::Code;
use crate::error::{Error, Fault};
use crate::host;
const HTTP_FETCH: &str = "action:http/fetch";
const UNREADABLE: &str = "HTTP_RESPONSE_UNREADABLE";
const EXCERPT_CHARS: usize = 240;
const CUT_MARKER: &str = "...";
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Method {
#[default]
Get,
Post,
Put,
Patch,
Delete,
}
impl Method {
pub fn as_str(&self) -> &str {
match self {
Method::Get => "GET",
Method::Post => "POST",
Method::Put => "PUT",
Method::Patch => "PATCH",
Method::Delete => "DELETE",
}
}
}
impl fmt::Display for Method {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Credentials {
Omit,
SameOrigin,
Include,
}
impl Credentials {
pub fn as_str(&self) -> &str {
match self {
Credentials::Omit => "omit",
Credentials::SameOrigin => "same-origin",
Credentials::Include => "include",
}
}
}
#[derive(Clone, Default)]
pub struct Request {
pub url: String,
pub method: Method,
pub headers: HashMap<String, String>,
pub body: Option<Value>,
pub credentials: Option<Credentials>,
}
impl fmt::Debug for Request {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut names: Vec<&str> = self.headers.keys().map(String::as_str).collect();
names.sort_unstable();
formatter
.debug_struct("Request")
.field("url", &self.url)
.field("method", &self.method)
.field("headers", &names)
.field("body", &self.body.as_ref().map(Sized_))
.field("credentials", &self.credentials)
.finish()
}
}
struct Sized_<'a>(&'a Value);
impl fmt::Debug for Sized_<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Value::String(text) => write!(formatter, "<string, {} bytes>", text.len()),
other => write!(formatter, "<{} json bytes>", other.to_string().len()),
}
}
}
pub fn headers(pairs: &[(&str, &str)]) -> HashMap<String, String> {
pairs
.iter()
.map(|(name, value)| ((*name).to_string(), (*value).to_string()))
.collect()
}
pub fn fetch<T: DeserializeOwned>(request: Request) -> Result<T, Error> {
let url = request.url.trim().to_string();
if url.is_empty() {
return Err(Error::invalid("A URL is required for an HTTP request.")
.hint("Set the request's url to the address to call."));
}
let method = request.method;
let request = Request { url, ..request };
let answer = host::transport()?
.call(HTTP_FETCH.to_string(), params(&request))
.map_err(|cause| {
cause.hint(format!(
"The request produced no answer. {}",
repeat_advice(method)
))
})?;
let response = read(answer)?;
if !response.ok {
return Err(refused(method, &response));
}
decode(response.body)
}
pub fn get<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
fetch(request(url, Method::Get, None))
}
pub fn post<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
fetch(request(url, Method::Post, Some(body)))
}
pub fn put<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
fetch(request(url, Method::Put, Some(body)))
}
pub fn patch<T: DeserializeOwned>(url: &str, body: Value) -> Result<T, Error> {
fetch(request(url, Method::Patch, Some(body)))
}
pub fn delete<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
fetch(request(url, Method::Delete, None))
}
fn request(url: &str, method: Method, body: Option<Value>) -> Request {
Request {
url: url.to_string(),
method,
headers: HashMap::new(),
body,
credentials: None,
}
}
fn params(request: &Request) -> Value {
let mut params = Map::new();
params.insert("url".to_string(), json!(request.url));
params.insert("method".to_string(), json!(request.method.as_str()));
if !request.headers.is_empty() {
params.insert("headers".to_string(), json!(request.headers));
}
if let Some(body) = &request.body {
params.insert("body".to_string(), json!(wire_body(body)));
}
if let Some(credentials) = request.credentials {
params.insert("credentials".to_string(), json!(credentials.as_str()));
}
Value::Object(params)
}
fn wire_body(body: &Value) -> String {
match body {
Value::String(text) => text.clone(),
other => other.to_string(),
}
}
struct Response {
status: u64,
ok: bool,
body: Value,
}
fn read(answer: Value) -> Result<Response, Error> {
let status = answer
.get("status")
.and_then(Value::as_u64)
.ok_or_else(|| {
unreadable("The answer to the request carried no HTTP status.").hint(
"Treat the effect as unknown and establish the outcome by reading the \
resource back.",
)
})?;
let ok = answer
.get("ok")
.and_then(Value::as_bool)
.unwrap_or(is_success(status));
let body = match answer {
Value::Object(mut members) => members.remove("body").unwrap_or(Value::Null),
_not_an_object => Value::Null,
};
Ok(Response { status, ok, body })
}
fn is_success(status: u64) -> bool {
(200..300).contains(&status)
}
fn decode<T: DeserializeOwned>(body: Value) -> Result<T, Error> {
serde_json::from_value(as_json(body)).map_err(|cause| {
unreadable(format!(
"The response body does not match the type this action asked for: {cause}"
))
.hint(
"Ask for a type that matches what the service answers with, or take the body as a \
Value and read it from there.",
)
})
}
fn as_json(body: Value) -> Value {
match body {
Value::String(text) if text.trim().is_empty() => Value::Null,
Value::String(text) => match serde_json::from_str(&text) {
Ok(json) => json,
Err(_text_rather_than_json) => Value::String(text),
},
already_json => already_json,
}
}
fn refused(method: Method, response: &Response) -> Error {
let status = response.status;
Error::Domain(Fault::new(
Code::Custom(format!("HTTP_STATUS_{status}")),
format!("The service answered {status}.{}", excerpt(&response.body)),
))
.details(json!({ "status": status }))
.hint(status_advice(method, status))
}
fn unreadable(message: impl Into<String>) -> Error {
Error::Json(Fault::new(Code::Custom(UNREADABLE.to_string()), message))
}
fn status_advice(method: Method, status: u64) -> String {
match status {
400..=499 => "The service refused the request as written. Correct the address, the \
headers or the body before sending it again."
.to_string(),
500..=599 => format!(
"The service failed after accepting the request. {}",
repeat_advice(method)
),
_other => "The service answered without delivering a result. Establish what this \
status means for this service before sending the request again."
.to_string(),
}
}
fn repeat_advice(method: Method) -> &'static str {
match method {
Method::Get => {
"A GET changes nothing, so the same call may be made again once the cause is \
addressed."
}
Method::Put | Method::Delete => {
"Treat the effect as unknown: read the resource back to establish what happened. \
A PUT or a DELETE sent twice reaches the same state."
}
Method::Post | Method::Patch => {
"Treat the effect as unknown: read the resource back before sending it again, \
since a POST or a PATCH sent twice can apply twice."
}
}
}
fn excerpt(body: &Value) -> String {
match body {
Value::Null => String::new(),
Value::String(text) => said(text),
rendered => said(&rendered.to_string()),
}
}
fn said(text: &str) -> String {
let mut characters = text.trim().chars();
let shown: String = characters.by_ref().take(EXCERPT_CHARS).collect();
if shown.is_empty() {
return String::new();
}
let marker = if characters.next().is_some() {
CUT_MARKER
} else {
""
};
format!(" It said: {shown}{marker}")
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::testing;
fn answered(status: u64, body: Value) -> Value {
json!({
"body": body,
"headers": { "content-type": "application/json" },
"ok": is_success(status),
"status": status,
})
}
#[test]
fn a_read_asks_for_the_address_and_answers_with_the_body() {
let session = testing::install(move |name, params| {
assert_eq!(name, HTTP_FETCH);
assert_eq!(params["url"], json!("https://api.example.com/leads/L1"));
assert_eq!(params["method"], json!("GET"));
assert_eq!(params.get("headers"), None, "no headers were asked for");
assert_eq!(params.get("body"), None, "a GET carries no body");
assert_eq!(
params.get("credentials"),
None,
"no credentials mode was named"
);
Ok(answered(200, json!({ "id": "L1" })))
});
#[derive(Debug, serde::Deserialize)]
struct Lead {
id: String,
}
let lead: Lead = get("https://api.example.com/leads/L1").unwrap();
assert_eq!(lead.id, "L1");
assert_eq!(session.calls().len(), 1);
}
#[test]
fn headers_and_a_body_travel_with_the_request() {
let session = testing::install(|_name, params| {
assert_eq!(params["headers"]["Authorization"], json!("Bearer T"));
assert_eq!(params["body"], json!(r#"{"email":"lead@example.com"}"#));
Ok(answered(201, json!({ "id": "L2" })))
});
let created: Value = fetch(Request {
url: "https://api.example.com/leads".to_string(),
method: Method::Post,
headers: headers(&[("Authorization", "Bearer T")]),
body: Some(json!({ "email": "lead@example.com" })),
..Request::default()
})
.unwrap();
assert_eq!(created, json!({ "id": "L2" }));
assert_eq!(session.calls().len(), 1);
}
#[test]
fn a_body_that_is_text_is_sent_as_itself() {
let _session = testing::install(|_name, params| {
assert_eq!(params["body"], json!("grant_type=client_credentials"));
Ok(answered(200, json!(null)))
});
let _: Value = post(
"https://api.example.com/token",
json!("grant_type=client_credentials"),
)
.unwrap();
}
#[test]
fn a_credentials_mode_travels_as_the_browser_names_it() {
let session = testing::install(|_name, _params| Ok(answered(200, json!(null))));
for credentials in [
Credentials::Omit,
Credentials::SameOrigin,
Credentials::Include,
] {
let _: Value = fetch(Request {
url: "https://api.example.com/session".to_string(),
credentials: Some(credentials),
..Request::default()
})
.unwrap();
}
let sent: Vec<Value> = session
.calls()
.iter()
.map(|call| call.params["credentials"].clone())
.collect();
assert_eq!(
sent,
vec![json!("omit"), json!("same-origin"), json!("include")]
);
}
#[test]
fn each_method_function_names_its_own_method() {
let session = testing::install(|_name, _params| Ok(answered(200, json!(null))));
let _: Value = get("https://api.example.com/a").unwrap();
let _: Value = post("https://api.example.com/a", json!({})).unwrap();
let _: Value = put("https://api.example.com/a", json!({})).unwrap();
let _: Value = patch("https://api.example.com/a", json!({})).unwrap();
let _: Value = delete("https://api.example.com/a").unwrap();
let sent: Vec<Value> = session
.calls()
.iter()
.map(|call| call.params["method"].clone())
.collect();
assert_eq!(
sent,
vec![
json!("GET"),
json!("POST"),
json!("PUT"),
json!("PATCH"),
json!("DELETE")
]
);
}
#[test]
fn a_blank_url_is_refused_before_anything_is_sent() {
let session = testing::install(|_name, _params| Ok(answered(200, json!(null))));
let error = get::<Value>(" ").unwrap_err();
assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
assert!(session.calls().is_empty(), "nothing was sent");
}
#[test]
fn the_address_is_sent_trimmed() {
let _session = testing::install(|_name, params| {
assert_eq!(params["url"], json!("https://api.example.com/a"));
Ok(answered(200, json!(null)))
});
let _: Value = get(" https://api.example.com/a\n").unwrap();
}
#[test]
fn a_status_outside_2xx_is_a_failure_carrying_that_status() {
let _session = testing::install(|_name, _params| {
Ok(answered(404, json!({ "detail": "no such lead" })))
});
let error = get::<Value>("https://api.example.com/leads/L9").unwrap_err();
assert!(matches!(error, Error::Domain(_)));
assert_eq!(error.code().as_str(), "HTTP_STATUS_404");
assert_eq!(error.fault().details(), &json!({ "status": 404 }));
assert!(error.message().contains("404"));
assert!(error.message().contains("no such lead"));
}
#[test]
fn a_request_that_produced_no_answer_is_a_different_failure() {
let _session = testing::install(|_name, _params| {
Err(Error::failed("HTTP request failed: connection refused"))
});
let error = get::<Value>("https://api.example.com/leads").unwrap_err();
assert!(matches!(error, Error::Host(_)));
assert_eq!(error.code().as_str(), "ACTION_FAILED");
assert!(error.message().contains("connection refused"));
}
#[test]
fn a_body_that_does_not_fit_the_answer_type_says_so() {
let _session = testing::install(|_name, _params| Ok(answered(200, json!({ "id": 7 }))));
#[derive(Debug, serde::Deserialize)]
struct Lead {
#[allow(dead_code)]
id: String,
}
let error = get::<Lead>("https://api.example.com/leads/L1").unwrap_err();
assert!(matches!(error, Error::Json(_)));
assert_eq!(error.code().as_str(), UNREADABLE);
}
#[test]
fn an_answer_with_no_status_is_read_as_unreadable() {
let _session = testing::install(|_name, _params| Ok(json!({ "body": { "id": "L1" } })));
let error = get::<Value>("https://api.example.com/leads/L1").unwrap_err();
assert_eq!(error.code().as_str(), UNREADABLE);
assert!(error.message().contains("status"));
}
#[test]
fn a_text_body_reads_into_a_string() {
let _session = testing::install(|_name, _params| Ok(answered(200, json!("pong"))));
let answer: String = get("https://api.example.com/ping").unwrap();
assert_eq!(answer, "pong");
}
#[test]
fn a_body_sent_as_json_text_reads_as_json() {
let _session =
testing::install(|_name, _params| Ok(answered(200, json!(r#"{"id":"L1"}"#))));
let lead: Value = get("https://api.example.com/leads/L1").unwrap();
assert_eq!(lead, json!({ "id": "L1" }));
}
#[test]
fn a_body_with_nothing_in_it_reads_as_null() {
let _session = testing::install(|_name, _params| Ok(answered(204, json!(""))));
let answer: Value = delete("https://api.example.com/leads/L1").unwrap();
assert_eq!(answer, json!(null));
delete::<()>("https://api.example.com/leads/L1").expect("no body is an answer of its own");
}
#[test]
fn an_answer_with_no_body_member_reads_as_null() {
let _session = testing::install(|_name, _params| Ok(json!({ "ok": true, "status": 200 })));
let answer: Option<String> = get("https://api.example.com/a").unwrap();
assert_eq!(answer, None);
}
#[test]
fn the_status_alone_decides_a_success() {
let _session =
testing::install(|_name, _params| Ok(json!({ "body": "made", "status": 201 })));
let answer: String = post("https://api.example.com/leads", json!({})).unwrap();
assert_eq!(answer, "made");
}
#[test]
fn the_status_alone_decides_a_refusal() {
let _session =
testing::install(|_name, _params| Ok(json!({ "body": "gone", "status": 410 })));
let error = get::<Value>("https://api.example.com/leads/L1").unwrap_err();
assert_eq!(error.code().as_str(), "HTTP_STATUS_410");
}
#[test]
fn a_refusal_and_a_failure_advise_differently() {
let _session = testing::install(|_name, _params| Ok(answered(422, json!("bad email"))));
let refusal = post::<Value>("https://api.example.com/leads", json!({})).unwrap_err();
assert!(refusal.fault().hint().contains("refused the request"));
let _session = testing::install(|_name, _params| Ok(answered(500, json!("boom"))));
let failure = post::<Value>("https://api.example.com/leads", json!({})).unwrap_err();
assert!(failure.fault().hint().contains("can apply twice"));
}
#[test]
fn what_a_failed_call_advises_follows_the_method() {
assert!(repeat_advice(Method::Get).contains("changes nothing"));
assert!(repeat_advice(Method::Put).contains("same state"));
assert!(repeat_advice(Method::Delete).contains("same state"));
assert!(repeat_advice(Method::Post).contains("apply twice"));
assert!(repeat_advice(Method::Patch).contains("apply twice"));
}
#[test]
fn a_call_that_never_answered_advises_by_its_method() {
let _session = testing::install(|_name, _params| Err(Error::failed("timed out")));
let read = get::<Value>("https://api.example.com/a").unwrap_err();
let write = post::<Value>("https://api.example.com/a", json!({})).unwrap_err();
assert!(read.fault().hint().contains("changes nothing"));
assert!(write.fault().hint().contains("Treat the effect as unknown"));
}
#[test]
fn a_long_answer_is_quoted_up_to_what_fits() {
let _session = testing::install(|_name, _params| Ok(answered(500, json!("x".repeat(900)))));
let error = get::<Value>("https://api.example.com/a").unwrap_err();
assert!(error.message().ends_with(CUT_MARKER));
assert!(error.message().len() < 400);
}
#[test]
fn a_status_with_nothing_beside_it_is_still_a_sentence() {
let _session = testing::install(|_name, _params| Ok(answered(503, json!(null))));
let error = get::<Value>("https://api.example.com/a").unwrap_err();
assert_eq!(error.message(), "The service answered 503.");
}
#[test]
fn every_method_travels_under_the_name_the_wire_uses() {
assert_eq!(Method::default(), Method::Get);
assert_eq!(Method::Get.to_string(), "GET");
assert_eq!(Method::Post.as_str(), "POST");
assert_eq!(Method::Put.as_str(), "PUT");
assert_eq!(Method::Patch.as_str(), "PATCH");
assert_eq!(Method::Delete.as_str(), "DELETE");
}
#[test]
fn the_headers_a_call_names_are_the_headers_it_sends() {
let built = headers(&[("Accept", "application/json"), ("X-Trace", "T1")]);
assert_eq!(built["Accept"], "application/json");
assert_eq!(built["X-Trace"], "T1");
assert_eq!(built.len(), 2);
assert!(headers(&[]).is_empty());
}
#[test]
fn the_codes_this_module_reports_travel_as_written() {
assert_eq!(
Code::Custom("HTTP_STATUS_404".to_string()).wire(),
"HTTP_STATUS_404"
);
assert_eq!(Code::Custom(UNREADABLE.to_string()).wire(), UNREADABLE);
}
}