Files
crank/crates/crank-adapter-rest/src/response.rs
T

128 lines
3.7 KiB
Rust

use std::collections::BTreeMap;
use crank_core::RestTarget;
use futures_util::StreamExt;
use reqwest::header::HeaderMap;
use serde_json::Value;
use crate::RestAdapterError;
pub(crate) async fn decode_body(
response: reqwest::Response,
max_response_bytes: usize,
) -> Result<(Value, bool, bool), RestAdapterError> {
if response
.content_length()
.is_some_and(|length| length > max_response_bytes as u64)
{
return Err(RestAdapterError::ResponseTooLarge {
limit_bytes: max_response_bytes,
});
}
let mut stream = response.bytes_stream();
let mut bytes = Vec::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
if bytes.len().saturating_add(chunk.len()) > max_response_bytes {
return Err(RestAdapterError::ResponseTooLarge {
limit_bytes: max_response_bytes,
});
}
bytes.extend_from_slice(&chunk);
}
if bytes.is_empty() {
return Ok((Value::Null, false, false));
}
match serde_json::from_slice::<Value>(&bytes) {
Ok(value) => Ok((value, true, true)),
Err(_) => Ok((
Value::String(String::from_utf8_lossy(&bytes).trim().to_owned()),
true,
false,
)),
}
}
pub(crate) fn validate_response_contract(
target: &RestTarget,
status_code: u16,
headers: &BTreeMap<String, String>,
has_body: bool,
valid_json: bool,
) -> Result<(), RestAdapterError> {
if target.response_contract.is_empty() {
return Ok(());
}
let matching_status = target
.response_contract
.iter()
.filter(|descriptor| descriptor.status_code == status_code)
.collect::<Vec<_>>();
if matching_status.is_empty() {
return Err(RestAdapterError::UnexpectedStatus {
status: status_code,
body: Value::Null,
});
}
if !has_body {
return matching_status
.iter()
.any(|descriptor| descriptor.media_type.is_none())
.then_some(())
.ok_or_else(|| RestAdapterError::InvalidResponseContract {
reason: format!("status {status_code} requires a response body"),
});
}
let content_type = headers
.get("content-type")
.map(|value| normalized_media_type(value));
let Some(content_type) = content_type else {
return Err(RestAdapterError::InvalidResponseContract {
reason: format!("status {status_code} has a body without a content-type"),
});
};
if matching_status.iter().any(|descriptor| {
descriptor
.media_type
.as_deref()
.is_some_and(|expected| normalized_media_type(expected) == content_type)
}) {
if (content_type == "application/json" || content_type.ends_with("+json")) && !valid_json {
return Err(RestAdapterError::InvalidResponseContract {
reason: format!("status {status_code} has invalid JSON response body"),
});
}
return Ok(());
}
Err(RestAdapterError::InvalidResponseContract {
reason: format!("status {status_code} with content-type {content_type} is not declared"),
})
}
fn normalized_media_type(value: &str) -> String {
value
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
}
pub(crate) fn normalize_headers(headers: &HeaderMap) -> BTreeMap<String, String> {
headers
.iter()
.filter_map(|(name, value)| {
value
.to_str()
.ok()
.map(|value| (name.as_str().to_owned(), value.to_owned()))
})
.collect()
}