use crate::constants::{BodyFormat, ErrorCode};
use crate::registry::{Registry, RegistryError};
use crate::structs::{RequestBody, ResponseBody};
use std::sync::Arc;
use std::time::Duration;
pub const MEDIA_JSON: &str = "application/json";
pub const MEDIA_BEVE: &str = "application/x-beve";
pub const MEDIA_PROBLEM: &str = "application/problem+json";
const ALLOW_CALL: &str = "GET, HEAD, PUT, POST, OPTIONS";
const ALLOW_READ_ONLY: &str = "GET, HEAD, OPTIONS";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Repr {
Json,
Beve,
}
impl Repr {
fn media_type(self) -> &'static str {
match self {
Repr::Json => MEDIA_JSON,
Repr::Beve => MEDIA_BEVE,
}
}
fn body_format(self) -> BodyFormat {
match self {
Repr::Json => BodyFormat::Json,
Repr::Beve => BodyFormat::Beve,
}
}
fn from_body_format(format: BodyFormat) -> Self {
match format {
BodyFormat::Beve => Repr::Beve,
_ => Repr::Json,
}
}
}
#[derive(Debug, Clone)]
pub struct RestConfig {
pub max_body_bytes: usize,
pub cache_control: Option<String>,
pub application_error_status: u16,
pub read_only: bool,
pub accept_beve_bodies: bool,
pub max_connections: usize,
pub request_timeout: Option<Duration>,
}
impl Default for RestConfig {
fn default() -> Self {
Self {
max_body_bytes: 1024 * 1024,
cache_control: Some("no-cache".to_string()),
application_error_status: 500,
read_only: false,
accept_beve_bodies: true,
max_connections: 1024,
request_timeout: Some(Duration::from_secs(30)),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct RestRequest<'a> {
pub method: &'a str,
pub target: &'a str,
pub content_type: Option<&'a str>,
pub accept: Option<&'a str>,
pub if_none_match: Option<&'a str>,
pub body: &'a [u8],
}
impl<'a> RestRequest<'a> {
pub fn new(method: &'a str, target: &'a str) -> Self {
Self {
method,
target,
content_type: None,
accept: None,
if_none_match: None,
body: &[],
}
}
pub fn with_body(mut self, content_type: &'a str, body: &'a [u8]) -> Self {
self.content_type = Some(content_type);
self.body = body;
self
}
pub fn with_accept(mut self, accept: &'a str) -> Self {
self.accept = Some(accept);
self
}
pub fn with_if_none_match(mut self, tag: &'a str) -> Self {
self.if_none_match = Some(tag);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestResponse {
pub status: u16,
pub content_type: Option<&'static str>,
pub etag: Option<String>,
pub cache_control: Option<String>,
pub vary: Option<&'static str>,
pub allow: Option<&'static str>,
pub repe_error_code: Option<u32>,
pub omit_body: bool,
pub body: Vec<u8>,
}
impl RestResponse {
fn empty(status: u16) -> Self {
Self {
status,
content_type: None,
etag: None,
cache_control: None,
vary: None,
allow: None,
repe_error_code: None,
omit_body: false,
body: Vec::new(),
}
}
fn problem(status: u16, detail: impl Into<String>, repe_code: Option<u32>) -> Self {
let problem = Problem {
kind: "about:blank",
title: reason_phrase(status),
status,
detail: detail.into(),
repe_code,
};
Self {
content_type: Some(MEDIA_PROBLEM),
cache_control: Some("no-store".to_string()),
repe_error_code: repe_code,
body: structio::json::to_vec_with::<structio::SkipNull, _>(&problem),
..Self::empty(status)
}
}
}
#[derive(Default)]
struct Problem<'a> {
kind: &'a str,
title: &'a str,
status: u16,
detail: String,
repe_code: Option<u32>,
}
structio::object!(['de] Problem<'de> {
"type" => kind,
title,
status,
detail,
repe_code,
});
#[derive(Clone)]
pub struct RestGateway {
registry: Arc<Registry>,
mount: String,
config: RestConfig,
}
impl std::fmt::Debug for RestGateway {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RestGateway")
.field("mount", &self.mount)
.field("config", &self.config)
.finish_non_exhaustive()
}
}
impl RestGateway {
pub fn new(mount: &str, registry: Arc<Registry>) -> Self {
Self::with_config(mount, registry, RestConfig::default())
}
pub fn with_config(mount: &str, registry: Arc<Registry>, config: RestConfig) -> Self {
Self {
registry,
mount: crate::registry::normalize_mount(mount),
config,
}
}
pub fn registry(&self) -> &Arc<Registry> {
&self.registry
}
pub fn respond(&self, request: RestRequest<'_>) -> RestResponse {
let path = request.target.split(['?', '#']).next().unwrap_or("");
if request.method == "OPTIONS" && path == "*" {
let allow = if self.config.read_only {
ALLOW_READ_ONLY
} else {
ALLOW_CALL
};
return RestResponse {
allow: Some(allow),
..RestResponse::empty(204)
};
}
let Some(remainder) = self.strip_mount(path) else {
return RestResponse::problem(
404,
format!("`{path}` is not under this gateway's mount"),
None,
);
};
let pointer = match path_to_pointer(remainder) {
Ok(pointer) => pointer,
Err(detail) => return RestResponse::problem(400, detail, None),
};
match request.method {
"GET" | "HEAD" => self.read(&pointer, request),
"PUT" | "POST" => self.call(&pointer, request),
"OPTIONS" => RestResponse {
allow: Some(self.allow()),
..RestResponse::empty(204)
},
_ => method_not_allowed(self.allow(), "unsupported method"),
}
}
fn allow(&self) -> &'static str {
if self.config.read_only {
ALLOW_READ_ONLY
} else {
ALLOW_CALL
}
}
fn read(&self, pointer: &str, request: RestRequest<'_>) -> RestResponse {
let (body, media) = match self.invoke(pointer, None, negotiate(request.accept)) {
Ok(encoded) => encoded,
Err(err) => return self.problem_for(err),
};
let etag = etag_for(&body);
let cache_control = self.config.cache_control.clone();
if let Some(header) = request.if_none_match
&& if_none_match_matches(header, &etag)
{
return RestResponse {
etag: Some(etag),
cache_control,
vary: Some("Accept"),
..RestResponse::empty(304)
};
}
RestResponse {
status: 200,
content_type: Some(media),
etag: Some(etag),
cache_control,
vary: Some("Accept"),
omit_body: request.method == "HEAD",
body,
..RestResponse::empty(200)
}
}
fn call(&self, pointer: &str, request: RestRequest<'_>) -> RestResponse {
if self.config.read_only {
return method_not_allowed(ALLOW_READ_ONLY, "this gateway is configured read-only");
}
if request.body.is_empty() {
return RestResponse::problem(
400,
"a body is required; send `null` for a call that takes no arguments",
Some(ErrorCode::InvalidBody as u32),
);
}
let format = match self.body_format(request.content_type) {
Ok(format) => format,
Err(detail) => {
return RestResponse::problem(415, detail, Some(ErrorCode::InvalidBody as u32));
}
};
let params = RequestBody::new(request.body, format);
let (body, media) = match self.invoke(pointer, Some(params), negotiate(request.accept)) {
Ok(encoded) => encoded,
Err(err) => return self.problem_for(err),
};
RestResponse {
content_type: Some(media),
vary: Some("Accept"),
body,
..RestResponse::empty(200)
}
}
fn invoke(
&self,
pointer: &str,
params: Option<RequestBody<'_>>,
repr: Repr,
) -> Result<(Vec<u8>, &'static str), RegistryError> {
let mut buf = Vec::new();
let mut out = ResponseBody::with_format(&mut buf, repr.body_format());
let ctx = crate::CallContext::detached(pointer);
self.registry.call(pointer, params, &ctx, &mut out)?;
let media = Repr::from_body_format(out.format()).media_type();
Ok((buf, media))
}
fn body_format(&self, content_type: Option<&str>) -> Result<BodyFormat, &'static str> {
let Some(content_type) = content_type else {
return Ok(BodyFormat::Json);
};
match bare_media(content_type, ';').as_str() {
"" | MEDIA_JSON | "text/json" => Ok(BodyFormat::Json),
"application/x-www-form-urlencoded" => Ok(BodyFormat::Json),
MEDIA_BEVE | "application/beve" if self.config.accept_beve_bodies => {
Ok(BodyFormat::Beve)
}
MEDIA_BEVE | "application/beve" => Err(
"BEVE request bodies are disabled; enable `RestConfig::accept_beve_bodies` \
or send application/json",
),
_ => Err("unsupported Content-Type; send application/json"),
}
}
fn strip_mount<'p>(&self, path: &'p str) -> Option<&'p str> {
if self.mount.is_empty() {
return Some(path);
}
let rest = path.strip_prefix(self.mount.as_str())?;
if rest.is_empty() || rest.starts_with('/') {
Some(rest)
} else {
None
}
}
fn problem_for(&self, err: RegistryError) -> RestResponse {
let code = err.code();
RestResponse::problem(self.status_for(code), err.to_string(), Some(code as u32))
}
fn status_for(&self, code: ErrorCode) -> u16 {
match code {
ErrorCode::Ok => 200,
ErrorCode::MethodNotFound => 404,
ErrorCode::Timeout => 504,
ErrorCode::ResourceExhausted => 503,
ErrorCode::InternalError => 500,
ErrorCode::ApplicationErrorBase => self.config.application_error_status,
_ => 400,
}
}
}
fn method_not_allowed(allow: &'static str, detail: &str) -> RestResponse {
RestResponse {
allow: Some(allow),
..RestResponse::problem(405, detail, None)
}
}
fn path_to_pointer(path: &str) -> Result<String, &'static str> {
if path.is_empty() || path == "/" {
return Ok(String::new());
}
let path = path.strip_suffix('/').unwrap_or(path);
if path.is_empty() {
return Ok(String::new());
}
if !path.starts_with('/') {
return Err("request path must be absolute");
}
let mut pointer = String::with_capacity(path.len());
for segment in path.split('/').skip(1) {
pointer.push('/');
pointer.push_str(&crate::json_pointer::escape_token(&percent_decode(
segment,
)?));
}
Ok(pointer)
}
fn percent_decode(segment: &str) -> Result<String, &'static str> {
if !segment.contains('%') {
return Ok(segment.to_string());
}
let bytes = segment.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
if i + 2 >= bytes.len() {
return Err("truncated percent-escape in request path");
}
let (hi, lo) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]));
let (Some(hi), Some(lo)) = (hi, lo) else {
return Err("invalid percent-escape in request path");
};
out.push((hi << 4) | lo);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).map_err(|_| "percent-escape decoded to invalid UTF-8")
}
fn hex_nibble(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn negotiate(accept: Option<&str>) -> Repr {
let Some(accept) = accept else {
return Repr::Json;
};
let mut best: Option<(u32, Repr)> = None;
for entry in accept.split(',') {
let media = bare_media(entry, ';');
let mut quality = 1000;
for param in entry.split(';').skip(1) {
let param = param.trim();
if let Some(value) = param
.strip_prefix("q=")
.or_else(|| param.strip_prefix("Q="))
{
quality = parse_quality(value);
}
}
let repr = match media.as_str() {
MEDIA_BEVE | "application/beve" => Repr::Beve,
MEDIA_JSON | "application/*" | "*/*" => Repr::Json,
_ => continue,
};
if quality == 0 {
continue;
}
if best.is_none_or(|(best_quality, _)| quality > best_quality) {
best = Some((quality, repr));
}
}
best.map_or(Repr::Json, |(_, repr)| repr)
}
fn parse_quality(value: &str) -> u32 {
value
.trim()
.parse::<f32>()
.map_or(1000, |q| (q.clamp(0.0, 1.0) * 1000.0).round() as u32)
}
fn bare_media(value: &str, delimiter: char) -> String {
value
.split(delimiter)
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase()
}
fn etag_for(body: &[u8]) -> String {
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
let mut hash = FNV_OFFSET_BASIS;
for byte in body {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(FNV_PRIME);
}
format!("\"{hash:016x}\"")
}
fn if_none_match_matches(header: &str, etag: &str) -> bool {
header.split(',').any(|candidate| {
let candidate = candidate.trim();
candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag
})
}
fn reason_phrase(status: u16) -> &'static str {
hyper::StatusCode::from_u16(status)
.ok()
.and_then(|status| status.canonical_reason())
.unwrap_or("Error")
}
use http_body_util::{BodyExt, Full, LengthLimitError, Limited};
use hyper::body::{Bytes, Incoming};
use hyper::{Request, Response};
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
use hyper_util::server::conn::auto;
use std::convert::Infallible;
impl RestGateway {
pub async fn serve(self, listener: tokio::net::TcpListener) -> std::io::Result<()> {
let gateway = Arc::new(self);
let permits = Arc::new(tokio::sync::Semaphore::new(gateway.config.max_connections));
let mut backoff = ACCEPT_BACKOFF;
loop {
let Ok(permit) = Arc::clone(&permits).acquire_owned().await else {
return Ok(());
};
let stream = match listener.accept().await {
Ok((stream, _peer)) => {
backoff = ACCEPT_BACKOFF;
stream
}
Err(err) if is_per_connection_accept_error(&err) => continue,
Err(_) => {
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(MAX_ACCEPT_BACKOFF);
continue;
}
};
let gateway = Arc::clone(&gateway);
tokio::spawn(async move {
let service = hyper::service::service_fn(move |request: Request<Incoming>| {
let gateway = Arc::clone(&gateway);
async move {
let response = match gateway.config.request_timeout {
Some(limit) => tokio::time::timeout(limit, gateway.handle(request))
.await
.unwrap_or_else(|_| request_timeout_response()),
None => gateway.handle(request).await,
};
Ok::<_, Infallible>(response)
}
});
let mut builder = auto::Builder::new(TokioExecutor::new());
builder
.http1()
.timer(TokioTimer::new())
.header_read_timeout(HEADER_READ_TIMEOUT);
let _ = builder
.serve_connection(TokioIo::new(stream), service)
.await;
drop(permit);
});
}
}
async fn handle(&self, request: Request<Incoming>) -> Response<Full<Bytes>> {
let (parts, body) = request.into_parts();
let method = parts.method.as_str().to_owned();
let target = parts
.uri
.path_and_query()
.map_or("/", |path_and_query| path_and_query.as_str())
.to_owned();
let header = |name: hyper::header::HeaderName| {
parts
.headers
.get(name)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
};
let content_type = header(hyper::header::CONTENT_TYPE);
let accept = header(hyper::header::ACCEPT);
let if_none_match = header(hyper::header::IF_NONE_MATCH);
let body = match Limited::new(body, self.config.max_body_bytes)
.collect()
.await
{
Ok(collected) => collected.to_bytes(),
Err(err) => {
let response = if err.downcast_ref::<LengthLimitError>().is_some() {
RestResponse::problem(
413,
format!(
"request body exceeds the {}-byte limit",
self.config.max_body_bytes
),
None,
)
} else {
RestResponse::problem(400, "request body could not be read", None)
};
return to_hyper(response);
}
};
to_hyper(self.respond(RestRequest {
method: &method,
target: &target,
content_type: content_type.as_deref(),
accept: accept.as_deref(),
if_none_match: if_none_match.as_deref(),
body: &body,
}))
}
}
const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30);
const ACCEPT_BACKOFF: Duration = Duration::from_millis(50);
const MAX_ACCEPT_BACKOFF: Duration = Duration::from_secs(1);
fn is_per_connection_accept_error(err: &std::io::Error) -> bool {
use std::io::ErrorKind;
matches!(
err.kind(),
ErrorKind::ConnectionAborted | ErrorKind::ConnectionReset | ErrorKind::Interrupted
)
}
fn request_timeout_response() -> Response<Full<Bytes>> {
let mut response = to_hyper(RestResponse::problem(
408,
"the request was not completed within the gateway's time limit",
None,
));
response.headers_mut().insert(
hyper::header::CONNECTION,
hyper::header::HeaderValue::from_static("close"),
);
response
}
fn to_hyper(response: RestResponse) -> Response<Full<Bytes>> {
let mut builder = Response::builder().status(response.status);
if let Some(content_type) = response.content_type {
builder = builder.header(hyper::header::CONTENT_TYPE, content_type);
}
if let Some(etag) = &response.etag {
builder = builder.header(hyper::header::ETAG, etag);
}
if let Some(cache_control) = &response.cache_control {
builder = builder.header(hyper::header::CACHE_CONTROL, cache_control);
}
if let Some(vary) = response.vary {
builder = builder.header(hyper::header::VARY, vary);
}
if let Some(allow) = response.allow {
builder = builder.header(hyper::header::ALLOW, allow);
}
if let Some(code) = response.repe_error_code {
builder = builder.header("x-repe-error-code", code);
}
let built = if response.omit_body {
builder
.header(hyper::header::CONTENT_LENGTH, response.body.len())
.body(Full::new(Bytes::new()))
} else {
builder.body(Full::new(Bytes::from(response.body)))
};
built.unwrap_or_else(|_| {
Response::builder()
.status(500)
.body(Full::new(Bytes::new()))
.expect("a status-only response is always buildable")
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicI64, Ordering};
#[derive(Default, Debug, PartialEq)]
struct Operands {
a: i64,
b: i64,
}
structio::object!(Operands { a, b });
#[derive(Default, Debug, PartialEq)]
struct Sum {
result: i64,
}
structio::object!(Sum { result });
#[derive(Default, Debug, PartialEq)]
struct Counter {
counter: i64,
}
structio::object!(Counter { counter });
#[derive(Default, Debug, PartialEq)]
struct Config {
verbose: bool,
}
structio::object!(Config { verbose });
#[derive(Default, Debug, PartialEq)]
struct Label {
label: String,
}
structio::object!(Label { label });
#[derive(Default, Debug, PartialEq)]
struct ProblemBody {
kind: String,
title: String,
status: u16,
detail: String,
repe_code: Option<u32>,
}
structio::object!(ProblemBody {
"type" => kind,
title,
status,
detail,
repe_code
});
fn gateway_with(config: RestConfig) -> RestGateway {
let registry = Arc::new(Registry::new());
let counter = Arc::new(AtomicI64::new(7));
let read_counter = Arc::clone(&counter);
registry
.register_function("/counter", move |params: Option<RequestBody<'_>>| {
if let Some(body) = params {
let next: i64 = body
.read("/counter")
.map_err(|err| (ErrorCode::InvalidBody, err.to_string()))?;
read_counter.store(next, Ordering::SeqCst);
}
Ok(read_counter.load(Ordering::SeqCst))
})
.unwrap();
registry
.register_function("/config", |_: Option<RequestBody<'_>>| {
Ok(Config { verbose: false })
})
.unwrap();
registry
.register_function("/items/a~1b", |_: Option<RequestBody<'_>>| {
Ok("slashed".to_string())
})
.unwrap();
registry
.register_function("/tilde/a~0b", |_: Option<RequestBody<'_>>| {
Ok("tilded".to_string())
})
.unwrap();
registry
.register_function("/add", |params: Option<RequestBody<'_>>| {
let Some(body) = params else {
return Err((ErrorCode::InvalidBody, "expected an object".into()));
};
let operands: Operands = body
.read("/add")
.map_err(|err| (ErrorCode::InvalidBody, err.to_string()))?;
Ok(Sum {
result: operands.a + operands.b,
})
})
.unwrap();
registry
.register_function("/boom", |_: Option<RequestBody<'_>>| {
Err::<(), _>((ErrorCode::ApplicationErrorBase, "handler said no".into()))
})
.unwrap();
RestGateway::with_config("/api/v1", registry, config)
}
fn gateway() -> RestGateway {
gateway_with(RestConfig::default())
}
fn body_as<T: crate::structs::ServableOwned>(response: &RestResponse) -> T {
structio::from_slice(&response.body).expect("response body is JSON")
}
fn counter_of(gateway: &RestGateway) -> i64 {
body_as(&gateway.respond(RestRequest::new("GET", "/api/v1/counter")))
}
#[test]
fn get_calls_a_function_with_no_arguments() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1/counter"));
assert_eq!(response.status, 200);
assert_eq!(response.content_type, Some(MEDIA_JSON));
assert_eq!(body_as::<i64>(&response), 7);
}
#[test]
fn post_calls_a_function_with_the_body_as_arguments() {
let response = gateway().respond(
RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_JSON, br#"{"a":2,"b":3}"#),
);
assert_eq!(response.status, 200);
assert_eq!(body_as::<Sum>(&response), Sum { result: 5 });
}
#[test]
fn put_and_post_are_the_same_call() {
let gateway = gateway();
let via_put = gateway.respond(
RestRequest::new("PUT", "/api/v1/add").with_body(MEDIA_JSON, br#"{"a":2,"b":3}"#),
);
let via_post = gateway.respond(
RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_JSON, br#"{"a":2,"b":3}"#),
);
assert_eq!(via_put.status, 200);
assert_eq!(via_post.status, 200);
assert_eq!(via_put.body, via_post.body);
assert_eq!(via_put.content_type, via_post.content_type);
}
#[test]
fn a_call_with_no_body_is_refused_rather_than_read() {
for method in ["PUT", "POST"] {
let response = gateway().respond(RestRequest::new(method, "/api/v1/add"));
assert_eq!(response.status, 400, "{method}");
assert_eq!(
response.repe_error_code,
Some(ErrorCode::InvalidBody as u32),
"{method}"
);
}
}
#[test]
fn a_no_argument_call_is_spelled_with_a_null_body() {
let registry = Arc::new(Registry::new());
registry
.register_function("/ping", |_: Option<RequestBody<'_>>| Ok("pong".to_string()))
.unwrap();
let gateway = RestGateway::new("/api/v1", registry);
let response = gateway
.respond(RestRequest::new("POST", "/api/v1/ping").with_body(MEDIA_JSON, b"null"));
assert_eq!(response.status, 200);
assert_eq!(body_as::<String>(&response), "pong");
}
#[test]
fn options_advertises_the_verbs_the_gateway_supports() {
let response = gateway().respond(RestRequest::new("OPTIONS", "/api/v1/counter"));
assert_eq!(response.status, 204);
assert_eq!(response.allow, Some(ALLOW_CALL));
}
#[test]
fn an_unsupported_method_is_405_with_allow() {
let response = gateway().respond(RestRequest::new("DELETE", "/api/v1/counter"));
assert_eq!(response.status, 405);
assert_eq!(response.allow, Some(ALLOW_CALL));
}
#[test]
fn head_reports_the_length_without_the_body() {
let gateway = gateway();
let get = gateway.respond(RestRequest::new("GET", "/api/v1/config"));
let head = gateway.respond(RestRequest::new("HEAD", "/api/v1/config"));
assert!(head.omit_body);
assert!(!get.omit_body);
assert_eq!(head.body, get.body, "HEAD carries what GET would have sent");
assert_eq!(head.etag, get.etag);
}
#[test]
fn a_read_carries_a_validator_and_a_freshness_directive() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1/counter"));
assert!(response.etag.is_some());
assert_eq!(response.cache_control.as_deref(), Some("no-cache"));
assert_eq!(response.vary, Some("Accept"));
}
#[test]
fn a_call_carries_neither() {
let response = gateway().respond(
RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_JSON, br#"{"a":1,"b":1}"#),
);
assert_eq!(response.etag, None);
assert_eq!(response.cache_control, None);
}
#[test]
fn a_matching_validator_answers_304_with_no_body() {
let gateway = gateway();
let first = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
let tag = first.etag.clone().unwrap();
let second =
gateway.respond(RestRequest::new("GET", "/api/v1/counter").with_if_none_match(&tag));
assert_eq!(second.status, 304);
assert!(second.body.is_empty());
assert_eq!(second.etag, first.etag, "304 still carries the validator");
}
#[test]
fn the_handler_runs_even_when_the_answer_is_304() {
let calls = Arc::new(AtomicI64::new(0));
let counted = Arc::clone(&calls);
let registry = Arc::new(Registry::new());
registry
.register_function("/probe", move |_: Option<RequestBody<'_>>| {
counted.fetch_add(1, Ordering::SeqCst);
Ok(1i64)
})
.unwrap();
let gateway = RestGateway::new("/api/v1", registry);
let first = gateway.respond(RestRequest::new("GET", "/api/v1/probe"));
assert_eq!(calls.load(Ordering::SeqCst), 1);
let tag = first.etag.unwrap();
let second =
gateway.respond(RestRequest::new("GET", "/api/v1/probe").with_if_none_match(&tag));
assert_eq!(second.status, 304);
assert_eq!(
calls.load(Ordering::SeqCst),
2,
"the 304 was decided from the handler's own output"
);
}
#[test]
fn a_stale_validator_answers_the_full_body() {
let gateway = gateway();
let response = gateway.respond(
RestRequest::new("GET", "/api/v1/counter").with_if_none_match("\"0000000000000000\""),
);
assert_eq!(response.status, 200);
assert_eq!(body_as::<i64>(&response), 7);
}
#[test]
fn the_validator_changes_when_the_answer_does() {
let gateway = gateway();
let before = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
gateway.respond(RestRequest::new("PUT", "/api/v1/counter").with_body(MEDIA_JSON, b"8"));
let after = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
assert_ne!(before.etag, after.etag);
let conditional = gateway.respond(
RestRequest::new("GET", "/api/v1/counter").with_if_none_match(&before.etag.unwrap()),
);
assert_eq!(conditional.status, 200);
}
#[test]
fn a_weak_validator_and_a_star_both_match() {
let gateway = gateway();
let tag = gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.etag
.unwrap();
for header in [format!("W/{tag}"), "*".to_string(), format!("\"x\", {tag}")] {
let response = gateway
.respond(RestRequest::new("GET", "/api/v1/counter").with_if_none_match(&header));
assert_eq!(response.status, 304, "{header}");
}
}
#[test]
fn the_two_representations_get_different_validators() {
let gateway = gateway();
let as_json = gateway.respond(RestRequest::new("GET", "/api/v1/config"));
let as_beve =
gateway.respond(RestRequest::new("GET", "/api/v1/config").with_accept(MEDIA_BEVE));
assert_ne!(as_json.etag, as_beve.etag);
assert_eq!(as_json.vary, Some("Accept"));
assert_eq!(as_beve.vary, Some("Accept"));
}
#[test]
fn beve_is_served_on_request_and_decodes_to_the_same_value() {
let response =
gateway().respond(RestRequest::new("GET", "/api/v1/config").with_accept(MEDIA_BEVE));
assert_eq!(response.content_type, Some(MEDIA_BEVE));
let decoded: Config = structio::from_beve(&response.body).unwrap();
assert_eq!(decoded, Config { verbose: false });
}
#[test]
fn a_beve_request_body_is_accepted_by_default() {
let body = structio::to_beve(&Operands { a: 20, b: 22 });
let response =
gateway().respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_BEVE, &body));
assert_eq!(response.status, 200);
assert_eq!(body_as::<Sum>(&response), Sum { result: 42 });
}
#[test]
fn the_request_and_response_formats_are_independent() {
let gateway = gateway();
let beve_in = structio::to_beve(&Operands { a: 1, b: 2 });
let json_out = gateway.respond(
RestRequest::new("POST", "/api/v1/add")
.with_body(MEDIA_BEVE, &beve_in)
.with_accept(MEDIA_JSON),
);
assert_eq!(json_out.content_type, Some(MEDIA_JSON));
assert_eq!(body_as::<Sum>(&json_out), Sum { result: 3 });
let beve_out = gateway.respond(
RestRequest::new("POST", "/api/v1/add")
.with_body(MEDIA_JSON, br#"{"a":1,"b":2}"#)
.with_accept(MEDIA_BEVE),
);
assert_eq!(beve_out.content_type, Some(MEDIA_BEVE));
assert_eq!(
structio::from_beve::<Sum>(&beve_out.body).unwrap(),
Sum { result: 3 }
);
}
#[test]
fn quality_values_are_honored() {
let gateway = gateway();
let cases = [
("application/json", MEDIA_JSON),
("application/x-beve", MEDIA_BEVE),
("*/*", MEDIA_JSON),
(
"application/json;q=0.1, application/x-beve;q=0.9",
MEDIA_BEVE,
),
(
"application/json;q=0.9, application/x-beve;q=0.1",
MEDIA_JSON,
),
("application/x-beve;q=0, application/json", MEDIA_JSON),
("application/x-beve, application/json", MEDIA_BEVE),
("text/plain", MEDIA_JSON),
];
for (accept, expected) in cases {
let response =
gateway.respond(RestRequest::new("GET", "/api/v1/counter").with_accept(accept));
assert_eq!(response.content_type, Some(expected), "Accept: {accept}");
}
}
#[test]
fn an_unsupported_content_type_is_415() {
let response = gateway().respond(
RestRequest::new("PUT", "/api/v1/counter").with_body("application/xml", b"<x/>"),
);
assert_eq!(response.status, 415);
}
#[test]
fn a_missing_content_type_is_treated_as_json() {
let mut request = RestRequest::new("PUT", "/api/v1/counter");
request.body = b"99";
let gateway = gateway();
assert_eq!(gateway.respond(request).status, 200);
assert_eq!(counter_of(&gateway), 99);
}
#[test]
fn a_malformed_body_is_400_not_500() {
let response = gateway()
.respond(RestRequest::new("PUT", "/api/v1/counter").with_body(MEDIA_JSON, b"{oops"));
assert_eq!(response.status, 400);
}
#[test]
fn a_path_outside_the_mount_is_404() {
for target in ["/counter", "/other/counter", "/"] {
assert_eq!(
gateway().respond(RestRequest::new("GET", target)).status,
404,
"{target}"
);
}
}
#[test]
fn the_mount_must_match_on_a_segment_boundary() {
assert_eq!(
gateway()
.respond(RestRequest::new("GET", "/api/v1x/counter"))
.status,
404
);
}
#[test]
fn a_percent_encoded_separator_stays_inside_one_segment() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1/items/a%2Fb"));
assert_eq!(response.status, 200);
assert_eq!(body_as::<String>(&response), "slashed");
}
#[test]
fn a_literal_tilde_in_a_segment_is_escaped_not_interpreted() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1/tilde/a~b"));
assert_eq!(response.status, 200);
assert_eq!(body_as::<String>(&response), "tilded");
}
#[test]
fn a_trailing_slash_is_the_same_resource() {
let gateway = gateway();
assert_eq!(
gateway
.respond(RestRequest::new("GET", "/api/v1/counter/"))
.body,
gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.body
);
}
#[test]
fn the_query_string_and_fragment_are_not_part_of_the_resource() {
let gateway = gateway();
let plain = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
for target in ["/api/v1/counter?pretty=1", "/api/v1/counter#x"] {
assert_eq!(
gateway.respond(RestRequest::new("GET", target)).body,
plain.body,
"{target}"
);
}
}
#[test]
fn a_malformed_percent_escape_is_400() {
for target in ["/api/v1/a%zz", "/api/v1/a%2"] {
assert_eq!(
gateway().respond(RestRequest::new("GET", target)).status,
400,
"{target}"
);
}
}
#[test]
fn a_root_mount_serves_every_path() {
let registry = Arc::new(Registry::new());
registry
.register_function("/counter", |_: Option<RequestBody<'_>>| Ok(1i64))
.unwrap();
for mount in ["", "/"] {
let gateway = RestGateway::new(mount, Arc::clone(®istry));
assert_eq!(
gateway.respond(RestRequest::new("GET", "/counter")).status,
200,
"mount {mount:?}"
);
}
}
#[test]
fn every_spelling_of_a_mount_names_the_same_mount() {
let registry = Arc::new(Registry::new());
registry
.register_function("/counter", |_: Option<RequestBody<'_>>| Ok(1i64))
.unwrap();
for mount in ["/api/v1", "/api/v1/", "api/v1"] {
let gateway = RestGateway::new(mount, Arc::clone(®istry));
assert_eq!(
gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.status,
200,
"mount {mount:?}"
);
}
}
#[test]
fn a_doubled_slash_does_not_reach_the_root() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1//"));
assert_eq!(response.status, 404);
}
#[test]
fn a_missing_path_is_404_as_problem_details_carrying_the_repe_code() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1/absent"));
assert_eq!(response.status, 404);
assert_eq!(response.content_type, Some(MEDIA_PROBLEM));
assert_eq!(
response.repe_error_code,
Some(ErrorCode::MethodNotFound as u32)
);
let problem: ProblemBody = body_as(&response);
assert_eq!(problem.status, 404);
assert_eq!(problem.title, "Not Found");
assert_eq!(problem.repe_code, Some(ErrorCode::MethodNotFound as u32));
}
#[test]
fn a_problem_with_no_repe_code_omits_the_member_rather_than_nulling_it() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1x/counter"));
assert_eq!(response.repe_error_code, None);
let text = std::str::from_utf8(&response.body).unwrap();
assert!(
!text.contains("repe_code"),
"an absent extension member must not appear at all: {text}"
);
}
#[test]
fn a_handler_error_defaults_to_500_and_is_configurable() {
let default = gateway()
.respond(RestRequest::new("POST", "/api/v1/boom").with_body(MEDIA_JSON, b"null"));
assert_eq!(default.status, 500);
assert_eq!(
default.repe_error_code,
Some(ErrorCode::ApplicationErrorBase as u32)
);
let problem: ProblemBody = body_as(&default);
assert!(problem.detail.contains("handler said no"));
let remapped = gateway_with(RestConfig {
application_error_status: 422,
..RestConfig::default()
})
.respond(RestRequest::new("POST", "/api/v1/boom").with_body(MEDIA_JSON, b"null"));
assert_eq!(remapped.status, 422);
}
#[test]
fn a_handler_rejecting_its_arguments_is_400() {
let response = gateway()
.respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_JSON, b"[1,2]"));
assert_eq!(response.status, 400);
}
#[test]
fn an_error_response_is_never_cacheable() {
let gateway = gateway();
let cases = [
gateway.respond(RestRequest::new("GET", "/api/v1/absent")),
gateway.respond(RestRequest::new("DELETE", "/api/v1/counter")),
];
for response in cases {
assert!(response.status >= 400);
assert_eq!(response.cache_control.as_deref(), Some("no-store"));
}
}
#[test]
fn beve_request_bodies_are_refused_when_the_knob_is_off() {
let gateway = gateway_with(RestConfig {
accept_beve_bodies: false,
..RestConfig::default()
});
let body = structio::to_beve(&Operands { a: 1, b: 2 });
let response =
gateway.respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_BEVE, &body));
assert_eq!(response.status, 415);
let read =
gateway.respond(RestRequest::new("GET", "/api/v1/config").with_accept(MEDIA_BEVE));
assert_eq!(read.status, 200);
assert_eq!(read.content_type, Some(MEDIA_BEVE));
}
#[test]
fn a_deeply_nested_beve_body_is_answered_rather_than_aborting() {
let mut body = Vec::new();
for _ in 0..20_000 {
body.extend_from_slice(&[0x05, 0x04]);
}
body.extend_from_slice(&[0x05, 0x00]);
let response =
gateway().respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_BEVE, &body));
assert_eq!(response.status, 400);
}
#[test]
fn read_only_refuses_every_mutation_and_says_so_in_allow() {
let gateway = gateway_with(RestConfig {
read_only: true,
..RestConfig::default()
});
for method in ["PUT", "POST"] {
let response = gateway
.respond(RestRequest::new(method, "/api/v1/counter").with_body(MEDIA_JSON, b"1"));
assert_eq!(response.status, 405, "{method}");
assert_eq!(response.allow, Some(ALLOW_READ_ONLY), "{method}");
}
assert_eq!(counter_of(&gateway), 7, "no refused call may have run");
}
#[test]
fn options_star_respects_read_only() {
let gateway = gateway_with(RestConfig {
read_only: true,
..RestConfig::default()
});
let response = gateway.respond(RestRequest::new("OPTIONS", "*"));
assert_eq!(response.status, 204);
assert_eq!(response.allow, Some(ALLOW_READ_ONLY));
}
#[test]
fn options_star_asks_about_the_server_not_a_resource() {
let response = gateway().respond(RestRequest::new("OPTIONS", "*"));
assert_eq!(response.status, 204);
assert_eq!(response.allow, Some(ALLOW_CALL));
}
#[test]
fn path_to_pointer_cases() {
let cases = [
("", ""),
("/", ""),
("/counter", "/counter"),
("/counter/", "/counter"),
("/a/b/c", "/a/b/c"),
("/a%2Fb", "/a~1b"),
("/a~b", "/a~0b"),
("/a%7Eb", "/a~0b"),
("/sp%20ace", "/sp ace"),
("/a//b", "/a//b"),
];
for (path, expected) in cases {
assert_eq!(path_to_pointer(path).unwrap(), expected, "{path}");
}
}
#[test]
fn etag_is_stable_and_content_addressed() {
assert_eq!(etag_for(b"abc"), etag_for(b"abc"));
assert_ne!(etag_for(b"abc"), etag_for(b"abd"));
assert_eq!(etag_for(b""), "\"cbf29ce484222325\"");
assert_eq!(etag_for(b"repe"), "\"4cac4e1fbfac553f\"");
}
}