Rename transport binding to WIP over HTTP
This commit is contained in:
@@ -0,0 +1,570 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use http::header::{ACCEPT, CONTENT_TYPE};
|
||||
use http::{Method, Request, Response, StatusCode};
|
||||
use serde_json::{Map, Value as Json};
|
||||
use wip_protocol::{
|
||||
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, ObserveRequest,
|
||||
ObserveResponse, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||
};
|
||||
|
||||
use crate::response::{self, DecodedResponse};
|
||||
use crate::{
|
||||
BodyKind, ClientResponseError, CodecError, EncodeHttpError, Endpoint, InvalidResponseKind,
|
||||
JSON_CONTENT_TYPE, Limits, ResourceLimitKind, Route, is_json_content_type, json,
|
||||
};
|
||||
|
||||
/// A retrieval method accepted by the standard v1 batch endpoint.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BatchMethod {
|
||||
/// Observe one object and its indexable descendants.
|
||||
Observe,
|
||||
/// Fetch one interface descriptor.
|
||||
FetchInterface,
|
||||
}
|
||||
|
||||
impl BatchMethod {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Observe => "observe",
|
||||
Self::FetchInterface => "fetch_interface",
|
||||
}
|
||||
}
|
||||
|
||||
fn interaction(self) -> ProtocolInteraction {
|
||||
match self {
|
||||
Self::Observe => ProtocolInteraction::Observe,
|
||||
Self::FetchInterface => ProtocolInteraction::FetchInterface,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One retrieval interaction accepted by the standard v1 batch endpoint.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum BatchRequestKind {
|
||||
/// Observe one object and its indexable descendants.
|
||||
Observe(ObserveRequest),
|
||||
/// Fetch one interface descriptor.
|
||||
FetchInterface(FetchInterfaceRequest),
|
||||
/// A known method whose `arguments` are not a valid logical request.
|
||||
Invalid {
|
||||
/// Method that was successfully identified from the item envelope.
|
||||
method: BatchMethod,
|
||||
/// Item-local `invalid_request` to return without rejecting other items.
|
||||
error: ProtocolError,
|
||||
},
|
||||
}
|
||||
|
||||
impl BatchRequestKind {
|
||||
fn interaction(&self) -> ProtocolInteraction {
|
||||
match self {
|
||||
Self::Observe(_) => ProtocolInteraction::Observe,
|
||||
Self::FetchInterface(_) => ProtocolInteraction::FetchInterface,
|
||||
Self::Invalid { method, .. } => method.interaction(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One uniquely identified batch subrequest.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BatchRequestItem {
|
||||
/// Identifier used only to correlate the corresponding subresponse.
|
||||
pub id: String,
|
||||
/// Retrieval interaction and arguments.
|
||||
pub request: BatchRequestKind,
|
||||
}
|
||||
|
||||
/// A standard v1 batch request.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BatchRequest {
|
||||
/// Independent subrequests. Identifiers must be unique.
|
||||
pub requests: Vec<BatchRequestItem>,
|
||||
}
|
||||
|
||||
/// Successful result of one batch item.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BatchSuccess {
|
||||
/// Successful `observe` result.
|
||||
Observe(ObserveResponse),
|
||||
/// Successful `fetch_interface` result.
|
||||
FetchInterface(FetchInterfaceResponse),
|
||||
}
|
||||
|
||||
/// One batch subresponse, correlated by `id` rather than array position.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct BatchResponseItem {
|
||||
/// Identifier copied from its subrequest.
|
||||
pub id: String,
|
||||
/// Direct interaction result or canonical item-local protocol failure.
|
||||
pub outcome: Result<BatchSuccess, ProtocolError>,
|
||||
}
|
||||
|
||||
/// A valid standard v1 batch response.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct BatchResponse {
|
||||
/// Exactly one response for each requested identifier, in any order.
|
||||
pub responses: Vec<BatchResponseItem>,
|
||||
}
|
||||
|
||||
fn validate_ids<'a>(ids: impl Iterator<Item = &'a str>, maximum: usize) -> Result<(), CodecError> {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut count = 0;
|
||||
for id in ids {
|
||||
count += 1;
|
||||
if !seen.insert(id) {
|
||||
return Err(CodecError::DuplicateBatchId { id: id.into() });
|
||||
}
|
||||
}
|
||||
if count > maximum {
|
||||
return Err(CodecError::TooManyBatchItems {
|
||||
actual: count,
|
||||
maximum,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn request_item_to_json(item: &BatchRequestItem) -> Result<Json, CodecError> {
|
||||
let (method, arguments) = match &item.request {
|
||||
BatchRequestKind::Observe(value) => ("observe", json::observe_request_to_json(value)),
|
||||
BatchRequestKind::FetchInterface(value) => (
|
||||
"fetch_interface",
|
||||
json::fetch_interface_request_to_json(value),
|
||||
),
|
||||
BatchRequestKind::Invalid { .. } => {
|
||||
return Err(CodecError::InvalidField {
|
||||
field: "requests".into(),
|
||||
reason: "item-local invalid requests cannot be encoded as client requests".into(),
|
||||
});
|
||||
}
|
||||
};
|
||||
Ok(serde_json::json!({"id": item.id, "method": method, "arguments": arguments}))
|
||||
}
|
||||
|
||||
fn request_to_json(request: &BatchRequest, limits: Limits) -> Result<Json, CodecError> {
|
||||
validate_ids(
|
||||
request.requests.iter().map(|item| item.id.as_str()),
|
||||
limits.max_batch_items,
|
||||
)?;
|
||||
for item in &request.requests {
|
||||
match &item.request {
|
||||
BatchRequestKind::Observe(value) => value.validate()?,
|
||||
BatchRequestKind::FetchInterface(_) | BatchRequestKind::Invalid { .. } => {}
|
||||
}
|
||||
}
|
||||
let requests = request
|
||||
.requests
|
||||
.iter()
|
||||
.map(request_item_to_json)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(serde_json::json!({"requests": requests}))
|
||||
}
|
||||
|
||||
fn request_from_json(value: &Json, limits: Limits) -> Result<BatchRequest, CodecError> {
|
||||
let fields = exact_object(value, "batch", &["requests"])?;
|
||||
let values = array(required(fields, "requests")?, "requests")?;
|
||||
if values.len() > limits.max_batch_items {
|
||||
return Err(CodecError::TooManyBatchItems {
|
||||
actual: values.len(),
|
||||
maximum: limits.max_batch_items,
|
||||
});
|
||||
}
|
||||
let mut requests = Vec::with_capacity(values.len());
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
let field = format!("requests[{index}]");
|
||||
let fields = exact_object(value, &field, &["id", "method", "arguments"])?;
|
||||
let id = string(required(fields, "id")?, &format!("{field}.id"))?;
|
||||
let method_name = string(required(fields, "method")?, &format!("{field}.method"))?;
|
||||
let arguments = required(fields, "arguments")?;
|
||||
let method = match method_name.as_str() {
|
||||
"observe" => BatchMethod::Observe,
|
||||
"fetch_interface" => BatchMethod::FetchInterface,
|
||||
_ => {
|
||||
return Err(CodecError::InvalidField {
|
||||
field: format!("{field}.method"),
|
||||
reason: "batch supports only observe and fetch_interface".into(),
|
||||
});
|
||||
}
|
||||
};
|
||||
let decoded = match method {
|
||||
BatchMethod::Observe => {
|
||||
json::observe_request_from_json(arguments).map(BatchRequestKind::Observe)
|
||||
}
|
||||
BatchMethod::FetchInterface => json::fetch_interface_request_from_json(arguments)
|
||||
.map(BatchRequestKind::FetchInterface),
|
||||
};
|
||||
let request = decoded.unwrap_or_else(|error| BatchRequestKind::Invalid {
|
||||
method,
|
||||
error: ProtocolError {
|
||||
code: ProtocolErrorCode::InvalidRequest,
|
||||
message: format!("invalid {} arguments: {error}", method.name()),
|
||||
},
|
||||
});
|
||||
requests.push(BatchRequestItem { id, request });
|
||||
}
|
||||
validate_ids(
|
||||
requests.iter().map(|item| item.id.as_str()),
|
||||
limits.max_batch_items,
|
||||
)?;
|
||||
Ok(BatchRequest { requests })
|
||||
}
|
||||
|
||||
/// Encodes a batch request using `POST v1/batch`.
|
||||
pub fn encode_batch_request(
|
||||
endpoint: &Endpoint,
|
||||
value: &BatchRequest,
|
||||
limits: Limits,
|
||||
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||
let body = json::serialize(&request_to_json(value, limits)?, BodyKind::Request, limits)?;
|
||||
Ok(Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri(endpoint.route(Route::Batch).as_str())
|
||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||
.header(ACCEPT, "application/json")
|
||||
.body(body)?)
|
||||
}
|
||||
|
||||
/// Decodes and validates a batch request body.
|
||||
pub fn decode_batch_request(body: &[u8], limits: Limits) -> Result<BatchRequest, CodecError> {
|
||||
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||
request_from_json(&value, limits)
|
||||
}
|
||||
|
||||
fn success_to_json(success: &BatchSuccess) -> Json {
|
||||
match success {
|
||||
BatchSuccess::Observe(value) => json::observe_response_to_json(value),
|
||||
BatchSuccess::FetchInterface(value) => json::fetch_interface_response_to_json(value),
|
||||
}
|
||||
}
|
||||
|
||||
fn response_to_json(
|
||||
request: &BatchRequest,
|
||||
response: &BatchResponse,
|
||||
limits: Limits,
|
||||
) -> Result<Json, CodecError> {
|
||||
correlate(request, response, limits)?;
|
||||
Ok(serde_json::json!({
|
||||
"responses": response.responses.iter().map(|item| {
|
||||
let mut fields = Map::new();
|
||||
fields.insert("id".into(), Json::String(item.id.clone()));
|
||||
match &item.outcome {
|
||||
Ok(success) => { fields.insert("result".into(), success_to_json(success)); }
|
||||
Err(error) => { fields.insert("error".into(), response::item_error_to_json(error)); }
|
||||
}
|
||||
Json::Object(fields)
|
||||
}).collect::<Vec<_>>()
|
||||
}))
|
||||
}
|
||||
|
||||
fn correlate(
|
||||
request: &BatchRequest,
|
||||
response: &BatchResponse,
|
||||
limits: Limits,
|
||||
) -> Result<(), CodecError> {
|
||||
validate_ids(
|
||||
request.requests.iter().map(|item| item.id.as_str()),
|
||||
limits.max_batch_items,
|
||||
)?;
|
||||
validate_ids(
|
||||
response.responses.iter().map(|item| item.id.as_str()),
|
||||
limits.max_batch_items,
|
||||
)?;
|
||||
let requested: BTreeMap<&str, &BatchRequestKind> = request
|
||||
.requests
|
||||
.iter()
|
||||
.map(|item| (item.id.as_str(), &item.request))
|
||||
.collect();
|
||||
for item in &response.responses {
|
||||
let Some(kind) = requested.get(item.id.as_str()) else {
|
||||
return Err(CodecError::UnexpectedBatchId {
|
||||
id: item.id.clone(),
|
||||
});
|
||||
};
|
||||
match (&item.outcome, *kind) {
|
||||
(Ok(BatchSuccess::Observe(value)), BatchRequestKind::Observe(request)) => {
|
||||
request.validate_response(value)?;
|
||||
}
|
||||
(
|
||||
Ok(BatchSuccess::FetchInterface(value)),
|
||||
BatchRequestKind::FetchInterface(request),
|
||||
) => {
|
||||
value.validate_for(request)?;
|
||||
}
|
||||
(
|
||||
Err(error),
|
||||
BatchRequestKind::Invalid {
|
||||
error: expected, ..
|
||||
},
|
||||
) if error == expected => {}
|
||||
(Err(error), kind)
|
||||
if !matches!(kind, BatchRequestKind::Invalid { .. })
|
||||
&& error.code.is_allowed_for(kind.interaction()) => {}
|
||||
_ => {
|
||||
return Err(CodecError::BatchInteractionMismatch {
|
||||
id: item.id.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for item in &request.requests {
|
||||
if !response.responses.iter().any(|other| other.id == item.id) {
|
||||
return Err(CodecError::MissingBatchId {
|
||||
id: item.id.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encodes a valid batch response. Item failures remain inside HTTP 200.
|
||||
pub fn encode_batch_response(
|
||||
request: &BatchRequest,
|
||||
value: &BatchResponse,
|
||||
limits: Limits,
|
||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||
let body = json::serialize(
|
||||
&response_to_json(request, value, limits)?,
|
||||
BodyKind::Response,
|
||||
limits,
|
||||
)?;
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||
.body(body)?)
|
||||
}
|
||||
|
||||
/// Encodes a top-level batch-envelope failure.
|
||||
///
|
||||
/// Item-local failures belong in [`BatchResponseItem`]. Only failures that can
|
||||
/// reject the batch envelope before item execution are accepted here. A
|
||||
/// resource-limit failure defaults to the logical-limit status; use
|
||||
/// [`encode_batch_resource_limit_error_response`] when the concrete class is
|
||||
/// known.
|
||||
pub fn encode_batch_error_response(
|
||||
error: &ProtocolError,
|
||||
limits: Limits,
|
||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||
if !matches!(
|
||||
error.code,
|
||||
ProtocolErrorCode::InvalidRequest
|
||||
| ProtocolErrorCode::ResourceLimitExceeded
|
||||
| ProtocolErrorCode::Internal
|
||||
) {
|
||||
return Err(CodecError::InvalidField {
|
||||
field: "error.code".into(),
|
||||
reason: "code is not valid for a top-level batch failure".into(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
||||
Ok(Response::builder()
|
||||
.status(response::status_for_error(error.code))
|
||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||
.body(body)?)
|
||||
}
|
||||
|
||||
/// Encodes a class-specific top-level batch `resource_limit_exceeded` failure.
|
||||
pub fn encode_batch_resource_limit_error_response(
|
||||
error: &ProtocolError,
|
||||
kind: ResourceLimitKind,
|
||||
limits: Limits,
|
||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||
if error.code != ProtocolErrorCode::ResourceLimitExceeded {
|
||||
return Err(CodecError::InvalidField {
|
||||
field: "error.code".into(),
|
||||
reason: "resource-limit encoder requires resource_limit_exceeded".into(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
||||
Ok(Response::builder()
|
||||
.status(response::status_for_resource_limit(kind))
|
||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||
.body(body)?)
|
||||
}
|
||||
|
||||
fn response_from_json(
|
||||
value: &Json,
|
||||
request: &BatchRequest,
|
||||
limits: Limits,
|
||||
) -> Result<BatchResponse, CodecError> {
|
||||
let fields = exact_object(value, "batch", &["responses"])?;
|
||||
let values = array(required(fields, "responses")?, "responses")?;
|
||||
if values.len() > limits.max_batch_items {
|
||||
return Err(CodecError::TooManyBatchItems {
|
||||
actual: values.len(),
|
||||
maximum: limits.max_batch_items,
|
||||
});
|
||||
}
|
||||
let requested: BTreeMap<&str, &BatchRequestKind> = request
|
||||
.requests
|
||||
.iter()
|
||||
.map(|item| (item.id.as_str(), &item.request))
|
||||
.collect();
|
||||
let mut responses = Vec::with_capacity(values.len());
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
let field = format!("responses[{index}]");
|
||||
let fields = object(value, &field)?;
|
||||
for name in fields.keys() {
|
||||
if !["id", "result", "error"].contains(&name.as_str()) {
|
||||
return Err(CodecError::UnknownField {
|
||||
field: format!("{field}.{name}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
let id = string(required(fields, "id")?, &format!("{field}.id"))?;
|
||||
let Some(kind) = requested.get(id.as_str()) else {
|
||||
return Err(CodecError::UnexpectedBatchId { id });
|
||||
};
|
||||
let outcome = match (fields.get("result"), fields.get("error")) {
|
||||
(Some(_), Some(_)) | (None, None) => {
|
||||
return Err(CodecError::InvalidField {
|
||||
field,
|
||||
reason: "batch item must contain exactly one of result or error".into(),
|
||||
});
|
||||
}
|
||||
(None, Some(error)) => {
|
||||
let error = response::item_error_from_json(error)?;
|
||||
match kind {
|
||||
BatchRequestKind::Invalid {
|
||||
error: expected, ..
|
||||
} if error == *expected => {}
|
||||
BatchRequestKind::Invalid { .. } => {
|
||||
return Err(CodecError::BatchInteractionMismatch { id });
|
||||
}
|
||||
kind if error.code.is_allowed_for(kind.interaction()) => {}
|
||||
_ => return Err(CodecError::BatchInteractionMismatch { id }),
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
(Some(result), None) => Ok(match kind {
|
||||
BatchRequestKind::Observe(request) => {
|
||||
let value = json::observe_response_from_json(result)?;
|
||||
request.validate_response(&value)?;
|
||||
BatchSuccess::Observe(value)
|
||||
}
|
||||
BatchRequestKind::FetchInterface(request) => {
|
||||
let value = json::fetch_interface_response_from_json(result)?;
|
||||
value.validate_for(request)?;
|
||||
BatchSuccess::FetchInterface(value)
|
||||
}
|
||||
BatchRequestKind::Invalid { .. } => {
|
||||
return Err(CodecError::BatchInteractionMismatch { id });
|
||||
}
|
||||
}),
|
||||
};
|
||||
responses.push(BatchResponseItem { id, outcome });
|
||||
}
|
||||
let response = BatchResponse { responses };
|
||||
correlate(request, &response, limits)?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Decodes a batch response, including item-local failures within HTTP 200.
|
||||
pub fn decode_batch_response<B: AsRef<[u8]>>(
|
||||
request: &BatchRequest,
|
||||
value: &Response<B>,
|
||||
limits: Limits,
|
||||
) -> Result<DecodedResponse<BatchResponse>, ClientResponseError> {
|
||||
let valid_content_type = value
|
||||
.headers()
|
||||
.get(CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(is_json_content_type);
|
||||
if !valid_content_type {
|
||||
if value.status().is_success() {
|
||||
return Err(ClientResponseError::invalid(
|
||||
InvalidResponseKind::InvalidBatch,
|
||||
"missing or non-UTF-8 application/json Content-Type",
|
||||
));
|
||||
}
|
||||
return Err(response::transport_failure(value.status()));
|
||||
}
|
||||
let decoded = response::decode(
|
||||
value.status(),
|
||||
value.body().as_ref(),
|
||||
ProtocolInteraction::Observe,
|
||||
limits,
|
||||
|json| response_from_json(json, request, limits),
|
||||
)
|
||||
.map_err(|error| match error {
|
||||
ClientResponseError::InvalidResponse { detail, .. } => {
|
||||
ClientResponseError::invalid(InvalidResponseKind::InvalidBatch, detail)
|
||||
}
|
||||
other => other,
|
||||
})?;
|
||||
if let DecodedResponse::ProtocolFailure { error, .. } = &decoded
|
||||
&& !matches!(
|
||||
error.code,
|
||||
ProtocolErrorCode::InvalidRequest
|
||||
| ProtocolErrorCode::ResourceLimitExceeded
|
||||
| ProtocolErrorCode::Internal
|
||||
)
|
||||
{
|
||||
return Err(ClientResponseError::invalid(
|
||||
InvalidResponseKind::InvalidBatch,
|
||||
"protocol code is not valid for a top-level batch failure",
|
||||
));
|
||||
}
|
||||
if let DecodedResponse::Success(success) = &decoded {
|
||||
for item in &success.responses {
|
||||
if let Ok(BatchSuccess::FetchInterface(interface)) = &item.outcome
|
||||
&& interface.descriptor.format != INTERFACE_FORMAT_V1
|
||||
{
|
||||
return Err(ClientResponseError::UnsupportedDescriptorFormat {
|
||||
format: interface.descriptor.format.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(decoded)
|
||||
}
|
||||
|
||||
fn object<'a>(value: &'a Json, field: &str) -> Result<&'a Map<String, Json>, CodecError> {
|
||||
value.as_object().ok_or_else(|| CodecError::InvalidField {
|
||||
field: field.into(),
|
||||
reason: "expected object".into(),
|
||||
})
|
||||
}
|
||||
|
||||
fn exact_object<'a>(
|
||||
value: &'a Json,
|
||||
field: &str,
|
||||
allowed: &[&str],
|
||||
) -> Result<&'a Map<String, Json>, CodecError> {
|
||||
let fields = object(value, field)?;
|
||||
for name in fields.keys() {
|
||||
if !allowed.contains(&name.as_str()) {
|
||||
return Err(CodecError::UnknownField {
|
||||
field: format!("{field}.{name}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(fields)
|
||||
}
|
||||
|
||||
fn required<'a>(fields: &'a Map<String, Json>, name: &str) -> Result<&'a Json, CodecError> {
|
||||
fields
|
||||
.get(name)
|
||||
.ok_or_else(|| CodecError::MissingField { field: name.into() })
|
||||
}
|
||||
|
||||
fn string(value: &Json, field: &str) -> Result<String, CodecError> {
|
||||
value
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| CodecError::InvalidField {
|
||||
field: field.into(),
|
||||
reason: "expected string".into(),
|
||||
})
|
||||
}
|
||||
|
||||
fn array<'a>(value: &'a Json, field: &str) -> Result<&'a [Json], CodecError> {
|
||||
value
|
||||
.as_array()
|
||||
.map(Vec::as_slice)
|
||||
.ok_or_else(|| CodecError::InvalidField {
|
||||
field: field.into(),
|
||||
reason: "expected array".into(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
use http::header::{ACCEPT, CONTENT_TYPE};
|
||||
use http::{HeaderMap, Method, Request, Response, StatusCode};
|
||||
use wip_protocol::{
|
||||
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, FetchInterfaceResponse,
|
||||
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceTarget, ObserveRequest, ObserveResponse,
|
||||
ProtocolError, ProtocolInteraction, Target,
|
||||
};
|
||||
|
||||
use crate::response::{self, DecodedResponse};
|
||||
use crate::{
|
||||
BodyKind, ClientResponseError, CodecError, Endpoint, InvalidResponseKind, JSON_CONTENT_TYPE,
|
||||
Limits, ResourceLimitKind, Route, json,
|
||||
};
|
||||
|
||||
fn request(
|
||||
endpoint: &Endpoint,
|
||||
route: Route,
|
||||
body: Vec<u8>,
|
||||
) -> Result<Request<Vec<u8>>, http::Error> {
|
||||
Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri(endpoint.route(route).as_str())
|
||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||
.header(ACCEPT, "application/json")
|
||||
.body(body)
|
||||
}
|
||||
|
||||
fn response(status: StatusCode, body: Vec<u8>) -> Result<Response<Vec<u8>>, http::Error> {
|
||||
Response::builder()
|
||||
.status(status)
|
||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||
.body(body)
|
||||
}
|
||||
|
||||
fn require_response_content_type<B>(response: &Response<B>) -> Result<(), ClientResponseError> {
|
||||
let valid = response
|
||||
.headers()
|
||||
.get(CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(is_json_content_type);
|
||||
if valid {
|
||||
Ok(())
|
||||
} else if response.status().is_success() {
|
||||
Err(ClientResponseError::invalid(
|
||||
InvalidResponseKind::InvalidSuccessBody,
|
||||
"missing or non-UTF-8 application/json Content-Type",
|
||||
))
|
||||
} else {
|
||||
Err(response::transport_failure(response.status()))
|
||||
}
|
||||
}
|
||||
|
||||
fn is_utf8_charset(value: &str) -> bool {
|
||||
let value = value.trim();
|
||||
value.eq_ignore_ascii_case("utf-8")
|
||||
|| value
|
||||
.strip_prefix('"')
|
||||
.and_then(|value| value.strip_suffix('"'))
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case("utf-8"))
|
||||
}
|
||||
|
||||
/// Returns whether a Content-Type value denotes UTF-8 `application/json`.
|
||||
///
|
||||
/// The charset parameter is optional because JSON exchanged by this binding is
|
||||
/// always UTF-8; when present, its value must be `utf-8`. Other parameters are
|
||||
/// rejected so intermediaries cannot silently select another representation.
|
||||
#[must_use]
|
||||
pub fn is_json_content_type(value: &str) -> bool {
|
||||
let mut parts = value.split(';');
|
||||
if !parts
|
||||
.next()
|
||||
.is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let mut saw_charset = false;
|
||||
for parameter in parts {
|
||||
let Some((name, value)) = parameter.trim().split_once('=') else {
|
||||
return false;
|
||||
};
|
||||
if !name.trim().eq_ignore_ascii_case("charset") || !is_utf8_charset(value) || saw_charset {
|
||||
return false;
|
||||
}
|
||||
saw_charset = true;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn accepts_json(headers: &HeaderMap) -> bool {
|
||||
let mut present = false;
|
||||
let mut best_match: Option<((u8, u8), f32)> = None;
|
||||
for value in headers.get_all(ACCEPT) {
|
||||
present = true;
|
||||
let Ok(value) = value.to_str() else {
|
||||
continue;
|
||||
};
|
||||
for range in value.split(',') {
|
||||
let mut parts = range.split(';');
|
||||
let media_range = parts.next().unwrap_or_default().trim();
|
||||
let mut quality = 1.0_f32;
|
||||
let mut saw_quality = false;
|
||||
let mut saw_charset = false;
|
||||
let mut media_parameter_count = 0;
|
||||
let mut valid = true;
|
||||
for parameter in parts {
|
||||
let parameter = parameter.trim();
|
||||
let (name, value) = parameter
|
||||
.split_once('=')
|
||||
.map_or((parameter, None), |(name, value)| {
|
||||
(name.trim(), Some(value))
|
||||
});
|
||||
if name.is_empty() {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
if saw_quality {
|
||||
// Parameters after q are Accept extensions and do not
|
||||
// constrain the selected representation.
|
||||
continue;
|
||||
}
|
||||
if name.eq_ignore_ascii_case("q") {
|
||||
let Some(value) = value else {
|
||||
valid = false;
|
||||
break;
|
||||
};
|
||||
saw_quality = true;
|
||||
match value.trim().parse::<f32>() {
|
||||
Ok(value) if (0.0..=1.0).contains(&value) => quality = value,
|
||||
_ => {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let Some(value) = value else {
|
||||
valid = false;
|
||||
break;
|
||||
};
|
||||
if !name.eq_ignore_ascii_case("charset")
|
||||
|| !is_utf8_charset(value)
|
||||
|| saw_charset
|
||||
{
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
saw_charset = true;
|
||||
media_parameter_count += 1;
|
||||
}
|
||||
}
|
||||
let media_specificity = if media_range.eq_ignore_ascii_case("application/json") {
|
||||
Some(2)
|
||||
} else if media_range.eq_ignore_ascii_case("application/*") {
|
||||
Some(1)
|
||||
} else if media_range == "*/*" {
|
||||
Some(0)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if valid && let Some(media_specificity) = media_specificity {
|
||||
let specificity = (media_specificity, media_parameter_count);
|
||||
match best_match {
|
||||
Some((best_specificity, _)) if best_specificity > specificity => {}
|
||||
Some((best_specificity, best_quality)) if best_specificity == specificity => {
|
||||
best_match = Some((specificity, best_quality.max(quality)));
|
||||
}
|
||||
_ => best_match = Some((specificity, quality)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if present {
|
||||
best_match.is_some_and(|(_, quality)| quality > 0.0)
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// A failure while validating inbound HTTP request metadata.
|
||||
#[derive(Debug)]
|
||||
pub enum RequestMetadataError {
|
||||
/// The method or route does not match the selected WIP interaction.
|
||||
InvalidRequest(CodecError),
|
||||
/// The request body does not use UTF-8 `application/json`.
|
||||
UnsupportedMediaType,
|
||||
/// The request's `Accept` metadata excludes `application/json`.
|
||||
NotAcceptable,
|
||||
}
|
||||
|
||||
impl RequestMetadataError {
|
||||
/// Returns the HTTP status for this metadata failure.
|
||||
#[must_use]
|
||||
pub const fn status(&self) -> StatusCode {
|
||||
match self {
|
||||
Self::InvalidRequest(_) => StatusCode::BAD_REQUEST,
|
||||
Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||
Self::NotAcceptable => StatusCode::NOT_ACCEPTABLE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for RequestMetadataError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidRequest(error) => error.fmt(formatter),
|
||||
Self::UnsupportedMediaType => {
|
||||
formatter.write_str("expected UTF-8 application/json Content-Type")
|
||||
}
|
||||
Self::NotAcceptable => formatter.write_str("request does not accept application/json"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RequestMetadataError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::InvalidRequest(error) => Some(error),
|
||||
Self::UnsupportedMediaType | Self::NotAcceptable => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates mandatory HTTP metadata for an inbound WIP request.
|
||||
///
|
||||
/// Both absolute-form and origin-form request URIs are accepted, but the path
|
||||
/// must exactly equal the selected endpoint route and a query is forbidden.
|
||||
/// Unsupported content negotiation is reported as a Transport Binding metadata
|
||||
/// failure rather than a Core `invalid_request`.
|
||||
pub fn validate_http_request<B>(
|
||||
endpoint: &Endpoint,
|
||||
route: Route,
|
||||
value: &Request<B>,
|
||||
) -> Result<(), RequestMetadataError> {
|
||||
if value.method() != Method::POST {
|
||||
return Err(RequestMetadataError::InvalidRequest(
|
||||
CodecError::InvalidField {
|
||||
field: "method".into(),
|
||||
reason: "standard WIP routes require POST".into(),
|
||||
},
|
||||
));
|
||||
}
|
||||
let expected = endpoint.route(route);
|
||||
if value.uri().path() != expected.path() || value.uri().query().is_some() {
|
||||
return Err(RequestMetadataError::InvalidRequest(
|
||||
CodecError::InvalidField {
|
||||
field: "route".into(),
|
||||
reason: "request URI does not match the selected standard route".into(),
|
||||
},
|
||||
));
|
||||
}
|
||||
let valid_content_type = value
|
||||
.headers()
|
||||
.get(CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(is_json_content_type);
|
||||
if !valid_content_type {
|
||||
return Err(RequestMetadataError::UnsupportedMediaType);
|
||||
}
|
||||
if !accepts_json(value.headers()) {
|
||||
return Err(RequestMetadataError::NotAcceptable);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encodes an `observe` HTTP request.
|
||||
pub fn encode_observe_request(
|
||||
endpoint: &Endpoint,
|
||||
value: &ObserveRequest,
|
||||
limits: Limits,
|
||||
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||
value.validate().map_err(CodecError::from)?;
|
||||
let body = json::serialize(
|
||||
&json::observe_request_to_json(value),
|
||||
BodyKind::Request,
|
||||
limits,
|
||||
)?;
|
||||
Ok(request(endpoint, Route::Observe, body)?)
|
||||
}
|
||||
|
||||
/// Decodes an `observe` request body.
|
||||
pub fn decode_observe_request(body: &[u8], limits: Limits) -> Result<ObserveRequest, CodecError> {
|
||||
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||
json::observe_request_from_json(&value)
|
||||
}
|
||||
|
||||
/// Encodes a `fetch_interface` HTTP request.
|
||||
pub fn encode_fetch_interface_request(
|
||||
endpoint: &Endpoint,
|
||||
value: &FetchInterfaceRequest,
|
||||
limits: Limits,
|
||||
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||
let body = json::serialize(
|
||||
&json::fetch_interface_request_to_json(value),
|
||||
BodyKind::Request,
|
||||
limits,
|
||||
)?;
|
||||
Ok(request(endpoint, Route::FetchInterface, body)?)
|
||||
}
|
||||
|
||||
/// Decodes a `fetch_interface` request body.
|
||||
pub fn decode_fetch_interface_request(
|
||||
body: &[u8],
|
||||
limits: Limits,
|
||||
) -> Result<FetchInterfaceRequest, CodecError> {
|
||||
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||
json::fetch_interface_request_from_json(&value)
|
||||
}
|
||||
|
||||
/// Descriptor-independent fields needed to resolve a `call_operation` request.
|
||||
///
|
||||
/// A Host decodes this metadata first, fixes the current interface descriptor,
|
||||
/// then passes the same body and descriptor to [`decode_call_operation_request`].
|
||||
/// This preserves canonical path/interface/operation lookup and error precedence
|
||||
/// without treating unvalidated argument JSON as a logical [`wip_protocol::Value`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CallOperationMetadata {
|
||||
/// Path and optional object-state precondition.
|
||||
pub target: Target,
|
||||
/// Interface reference and optional interface precondition.
|
||||
pub interface: InterfaceTarget,
|
||||
/// Operation name used to select a declaration.
|
||||
pub operation: String,
|
||||
}
|
||||
|
||||
impl CallOperationMetadata {
|
||||
/// Decodes the descriptor-bound request and verifies that routing metadata
|
||||
/// still matches the values used to resolve `descriptor`.
|
||||
pub fn decode_request(
|
||||
&self,
|
||||
body: &[u8],
|
||||
descriptor: &InterfaceDescriptor,
|
||||
limits: Limits,
|
||||
) -> Result<CallOperationRequest, CodecError> {
|
||||
let request = decode_call_operation_request(body, descriptor, limits)?;
|
||||
if request.target != self.target
|
||||
|| request.interface != self.interface
|
||||
|| request.operation != self.operation
|
||||
{
|
||||
return Err(CodecError::InvalidField {
|
||||
field: "request".into(),
|
||||
reason: "call metadata changed after descriptor resolution".into(),
|
||||
});
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes descriptor-independent `call_operation` routing metadata.
|
||||
pub fn decode_call_operation_metadata(
|
||||
body: &[u8],
|
||||
limits: Limits,
|
||||
) -> Result<CallOperationMetadata, CodecError> {
|
||||
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||
let (target, interface, operation) = json::call_request_metadata_from_json(&value)?;
|
||||
Ok(CallOperationMetadata {
|
||||
target,
|
||||
interface,
|
||||
operation,
|
||||
})
|
||||
}
|
||||
|
||||
/// Encodes a descriptor-bound `call_operation` HTTP request.
|
||||
pub fn encode_call_operation_request(
|
||||
endpoint: &Endpoint,
|
||||
value: &CallOperationRequest,
|
||||
descriptor: &InterfaceDescriptor,
|
||||
limits: Limits,
|
||||
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||
let value = json::call_request_to_json(value, descriptor)?;
|
||||
let body = json::serialize(&value, BodyKind::Request, limits)?;
|
||||
Ok(request(endpoint, Route::CallOperation, body)?)
|
||||
}
|
||||
|
||||
/// Decodes a descriptor-bound `call_operation` request body.
|
||||
pub fn decode_call_operation_request(
|
||||
body: &[u8],
|
||||
descriptor: &InterfaceDescriptor,
|
||||
limits: Limits,
|
||||
) -> Result<CallOperationRequest, CodecError> {
|
||||
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||
json::call_request_from_json(&value, descriptor)
|
||||
}
|
||||
|
||||
/// Encodes a successful `observe` response as a direct body with HTTP 200.
|
||||
pub fn encode_observe_response(
|
||||
request_value: &ObserveRequest,
|
||||
value: &ObserveResponse,
|
||||
limits: Limits,
|
||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||
request_value
|
||||
.validate_response(value)
|
||||
.map_err(CodecError::from)?;
|
||||
let body = json::serialize(
|
||||
&json::observe_response_to_json(value),
|
||||
BodyKind::Response,
|
||||
limits,
|
||||
)?;
|
||||
Ok(response(StatusCode::OK, body)?)
|
||||
}
|
||||
|
||||
/// Decodes and classifies an `observe` client response.
|
||||
pub fn decode_observe_response<B: AsRef<[u8]>>(
|
||||
request_value: &ObserveRequest,
|
||||
value: &Response<B>,
|
||||
limits: Limits,
|
||||
) -> Result<DecodedResponse<ObserveResponse>, ClientResponseError> {
|
||||
require_response_content_type(value)?;
|
||||
response::decode(
|
||||
value.status(),
|
||||
value.body().as_ref(),
|
||||
ProtocolInteraction::Observe,
|
||||
limits,
|
||||
|json| {
|
||||
let observation = json::observe_response_from_json(json)?;
|
||||
request_value.validate_response(&observation)?;
|
||||
Ok(observation)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Encodes a successful `fetch_interface` response as a direct body with HTTP 200.
|
||||
pub fn encode_fetch_interface_response(
|
||||
request_value: &FetchInterfaceRequest,
|
||||
value: &FetchInterfaceResponse,
|
||||
limits: Limits,
|
||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||
value
|
||||
.validate_for(request_value)
|
||||
.map_err(CodecError::from)?;
|
||||
let body = json::serialize(
|
||||
&json::fetch_interface_response_to_json(value),
|
||||
BodyKind::Response,
|
||||
limits,
|
||||
)?;
|
||||
Ok(response(StatusCode::OK, body)?)
|
||||
}
|
||||
|
||||
/// Decodes and classifies a `fetch_interface` client response.
|
||||
pub fn decode_fetch_interface_response<B: AsRef<[u8]>>(
|
||||
request_value: &FetchInterfaceRequest,
|
||||
value: &Response<B>,
|
||||
limits: Limits,
|
||||
) -> Result<DecodedResponse<FetchInterfaceResponse>, ClientResponseError> {
|
||||
require_response_content_type(value)?;
|
||||
let decoded = response::decode(
|
||||
value.status(),
|
||||
value.body().as_ref(),
|
||||
ProtocolInteraction::FetchInterface,
|
||||
limits,
|
||||
|json| {
|
||||
let interface = json::fetch_interface_response_from_json(json)?;
|
||||
interface.validate_for(request_value)?;
|
||||
Ok(interface)
|
||||
},
|
||||
)?;
|
||||
if let DecodedResponse::Success(success) = &decoded
|
||||
&& success.descriptor.format != INTERFACE_FORMAT_V1
|
||||
{
|
||||
return Err(ClientResponseError::UnsupportedDescriptorFormat {
|
||||
format: success.descriptor.format.clone(),
|
||||
});
|
||||
}
|
||||
Ok(decoded)
|
||||
}
|
||||
|
||||
/// Encodes a successful `call_operation` response as a direct body with HTTP 200.
|
||||
pub fn encode_call_operation_response(
|
||||
request_value: &CallOperationRequest,
|
||||
descriptor: &InterfaceDescriptor,
|
||||
value: &CallOperationResponse,
|
||||
limits: Limits,
|
||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||
let json = json::call_response_to_json(value, descriptor, &request_value.operation)?;
|
||||
let body = json::serialize(&json, BodyKind::Response, limits)?;
|
||||
Ok(response(StatusCode::OK, body)?)
|
||||
}
|
||||
|
||||
/// Decodes and classifies a descriptor-bound `call_operation` client response.
|
||||
pub fn decode_call_operation_response<B: AsRef<[u8]>>(
|
||||
request_value: &CallOperationRequest,
|
||||
descriptor: &InterfaceDescriptor,
|
||||
value: &Response<B>,
|
||||
limits: Limits,
|
||||
) -> Result<DecodedResponse<CallOperationResponse>, ClientResponseError> {
|
||||
require_response_content_type(value)?;
|
||||
response::decode(
|
||||
value.status(),
|
||||
value.body().as_ref(),
|
||||
ProtocolInteraction::CallOperation,
|
||||
limits,
|
||||
|json| json::call_response_from_json(json, descriptor, &request_value.operation),
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_protocol_error(
|
||||
interaction: ProtocolInteraction,
|
||||
error: &ProtocolError,
|
||||
) -> Result<(), CodecError> {
|
||||
if !error.code.is_allowed_for(interaction) {
|
||||
return Err(CodecError::InvalidField {
|
||||
field: "error.code".into(),
|
||||
reason: format!(
|
||||
"code `{}` is not allowed for {interaction:?}",
|
||||
response::error_code_name(error.code)
|
||||
),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn encode_protocol_error_with_status(
|
||||
interaction: ProtocolInteraction,
|
||||
error: &ProtocolError,
|
||||
status: StatusCode,
|
||||
limits: Limits,
|
||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||
validate_protocol_error(interaction, error)?;
|
||||
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
||||
Ok(response(status, body)?)
|
||||
}
|
||||
|
||||
/// Encodes a canonical Host error envelope using its standard HTTP status.
|
||||
///
|
||||
/// The code must be allowed for `interaction`. This API accepts only
|
||||
/// [`ProtocolError`], so client-local `InvalidResponse` and
|
||||
/// `UnsupportedDescriptorFormat` classifications cannot be emitted as Host
|
||||
/// error envelopes. Resource-limit errors use the logical-limit status; callers
|
||||
/// that know the concrete limit class should use
|
||||
/// [`encode_resource_limit_error_response`].
|
||||
pub fn encode_protocol_error_response(
|
||||
interaction: ProtocolInteraction,
|
||||
error: &ProtocolError,
|
||||
limits: Limits,
|
||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||
encode_protocol_error_with_status(
|
||||
interaction,
|
||||
error,
|
||||
response::status_for_error(error.code),
|
||||
limits,
|
||||
)
|
||||
}
|
||||
|
||||
/// Encodes a `resource_limit_exceeded` envelope with its class-specific status.
|
||||
pub fn encode_resource_limit_error_response(
|
||||
interaction: ProtocolInteraction,
|
||||
error: &ProtocolError,
|
||||
kind: ResourceLimitKind,
|
||||
limits: Limits,
|
||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||
if error.code != wip_protocol::ProtocolErrorCode::ResourceLimitExceeded {
|
||||
return Err(CodecError::InvalidField {
|
||||
field: "error.code".into(),
|
||||
reason: "resource-limit encoder requires resource_limit_exceeded".into(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
encode_protocol_error_with_status(
|
||||
interaction,
|
||||
error,
|
||||
response::status_for_resource_limit(kind),
|
||||
limits,
|
||||
)
|
||||
}
|
||||
|
||||
/// Failure while building an outbound framework-neutral HTTP message.
|
||||
#[derive(Debug)]
|
||||
pub enum EncodeHttpError {
|
||||
/// JSON or protocol encoding failed.
|
||||
Codec(CodecError),
|
||||
/// The framework-neutral HTTP message builder rejected the URI or headers.
|
||||
Http(http::Error),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EncodeHttpError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Codec(error) => error.fmt(formatter),
|
||||
Self::Http(error) => error.fmt(formatter),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for EncodeHttpError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::Codec(error) => Some(error),
|
||||
Self::Http(error) => Some(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CodecError> for EncodeHttpError {
|
||||
fn from(value: CodecError) -> Self {
|
||||
Self::Codec(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<http::Error> for EncodeHttpError {
|
||||
fn from(value: http::Error) -> Self {
|
||||
Self::Http(value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
use url::Url;
|
||||
|
||||
/// The media type emitted for every WIP request and every response with a body.
|
||||
pub const JSON_CONTENT_TYPE: &str = "application/json; charset=utf-8";
|
||||
|
||||
/// A fixed standard WIP over HTTP v1 route.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Route {
|
||||
/// Observe one object and its indexable descendants.
|
||||
Observe,
|
||||
/// Fetch an interface descriptor.
|
||||
FetchInterface,
|
||||
/// Call one operation.
|
||||
CallOperation,
|
||||
/// Package independent retrieval interactions.
|
||||
Batch,
|
||||
}
|
||||
|
||||
impl Route {
|
||||
/// Returns the RFC 3986 relative reference used below an endpoint prefix.
|
||||
#[must_use]
|
||||
pub const fn relative_reference(self) -> &'static str {
|
||||
match self {
|
||||
Self::Observe => "v1/observe",
|
||||
Self::FetchInterface => "v1/fetch_interface",
|
||||
Self::CallOperation => "v1/call_operation",
|
||||
Self::Batch => "v1/batch",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A canonical absolute hierarchical base URL whose path always ends in `/`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Endpoint(Url);
|
||||
|
||||
impl Endpoint {
|
||||
/// Parses and canonicalizes an endpoint.
|
||||
///
|
||||
/// The input must be an absolute hierarchical URL with a host and without a
|
||||
/// query or fragment. Its path is an endpoint prefix, not a Worldspace path.
|
||||
/// A trailing slash is appended when absent so RFC 3986 relative-reference
|
||||
/// resolution preserves the final prefix segment. The supplied scheme is
|
||||
/// preserved; scheme and transport security are deployment concerns.
|
||||
pub fn parse(input: &str) -> Result<Self, EndpointError> {
|
||||
let mut url = Url::parse(input).map_err(EndpointError::InvalidUrl)?;
|
||||
if url.cannot_be_a_base() || url.host_str().is_none() {
|
||||
return Err(EndpointError::NotAbsoluteBase);
|
||||
}
|
||||
if url.query().is_some() {
|
||||
return Err(EndpointError::HasQuery);
|
||||
}
|
||||
if url.fragment().is_some() {
|
||||
return Err(EndpointError::HasFragment);
|
||||
}
|
||||
if !url.path().ends_with('/') {
|
||||
let path = format!("{}/", url.path());
|
||||
url.set_path(&path);
|
||||
}
|
||||
Ok(Self(url))
|
||||
}
|
||||
|
||||
/// Returns the canonical base URL.
|
||||
#[must_use]
|
||||
pub fn as_url(&self) -> &Url {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Resolves one fixed v1 route below this endpoint prefix.
|
||||
#[must_use]
|
||||
pub fn route(&self, route: Route) -> Url {
|
||||
self.0
|
||||
.join(route.relative_reference())
|
||||
.expect("fixed relative WIP routes are valid URL references")
|
||||
}
|
||||
|
||||
/// Recognizes an exact standard route below this endpoint.
|
||||
///
|
||||
/// Query strings, fragments, additional path segments, and Worldspace paths
|
||||
/// are not route components and therefore never match.
|
||||
#[must_use]
|
||||
pub fn recognize(&self, candidate: &Url) -> Option<Route> {
|
||||
const ROUTES: [Route; 4] = [
|
||||
Route::Observe,
|
||||
Route::FetchInterface,
|
||||
Route::CallOperation,
|
||||
Route::Batch,
|
||||
];
|
||||
if candidate.query().is_some() || candidate.fragment().is_some() {
|
||||
return None;
|
||||
}
|
||||
ROUTES
|
||||
.into_iter()
|
||||
.find(|route| self.route(*route) == *candidate)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Endpoint {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
self.0.fmt(formatter)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for Endpoint {
|
||||
type Error = EndpointError;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
Self::parse(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an endpoint is not a valid standard WIP over HTTP base.
|
||||
#[derive(Debug)]
|
||||
pub enum EndpointError {
|
||||
/// URL parsing failed.
|
||||
InvalidUrl(url::ParseError),
|
||||
/// The URL is not a hierarchical absolute URL with an authority.
|
||||
NotAbsoluteBase,
|
||||
/// A query component was supplied.
|
||||
HasQuery,
|
||||
/// A fragment component was supplied.
|
||||
HasFragment,
|
||||
}
|
||||
|
||||
impl Display for EndpointError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidUrl(error) => write!(formatter, "invalid endpoint URL: {error}"),
|
||||
Self::NotAbsoluteBase => {
|
||||
formatter.write_str("WIP endpoint must be an absolute base URL")
|
||||
}
|
||||
Self::HasQuery => formatter.write_str("WIP endpoint must not contain a query"),
|
||||
Self::HasFragment => formatter.write_str("WIP endpoint must not contain a fragment"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for EndpointError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::InvalidUrl(error) => Some(error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
/// Caller-selected hard limits applied before or while decoding JSON.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
/// Largest accepted request body in bytes.
|
||||
pub(crate) max_request_bytes: usize,
|
||||
/// Largest accepted response body in bytes.
|
||||
pub(crate) max_response_bytes: usize,
|
||||
/// Largest accepted JSON container nesting depth.
|
||||
pub(crate) max_nesting: usize,
|
||||
/// Largest accepted number of batch items.
|
||||
pub(crate) max_batch_items: usize,
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
/// Creates a nonzero limit set.
|
||||
pub fn new(
|
||||
max_request_bytes: usize,
|
||||
max_response_bytes: usize,
|
||||
max_nesting: usize,
|
||||
max_batch_items: usize,
|
||||
) -> Result<Self, LimitConfigurationError> {
|
||||
if max_request_bytes == 0 {
|
||||
return Err(LimitConfigurationError::ZeroRequestBytes);
|
||||
}
|
||||
if max_response_bytes == 0 {
|
||||
return Err(LimitConfigurationError::ZeroResponseBytes);
|
||||
}
|
||||
if max_nesting == 0 {
|
||||
return Err(LimitConfigurationError::ZeroNesting);
|
||||
}
|
||||
if max_batch_items == 0 {
|
||||
return Err(LimitConfigurationError::ZeroBatchItems);
|
||||
}
|
||||
Ok(Self {
|
||||
max_request_bytes,
|
||||
max_response_bytes,
|
||||
max_nesting,
|
||||
max_batch_items,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the request body byte limit.
|
||||
#[must_use]
|
||||
pub const fn max_request_bytes(self) -> usize {
|
||||
self.max_request_bytes
|
||||
}
|
||||
|
||||
/// Returns the response body byte limit.
|
||||
#[must_use]
|
||||
pub const fn max_response_bytes(self) -> usize {
|
||||
self.max_response_bytes
|
||||
}
|
||||
|
||||
/// Returns the JSON container nesting limit.
|
||||
#[must_use]
|
||||
pub const fn max_nesting(self) -> usize {
|
||||
self.max_nesting
|
||||
}
|
||||
|
||||
/// Returns the batch item count limit.
|
||||
#[must_use]
|
||||
pub const fn max_batch_items(self) -> usize {
|
||||
self.max_batch_items
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a [`Limits`] configuration is not bounded.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LimitConfigurationError {
|
||||
/// Request-byte limit was zero.
|
||||
ZeroRequestBytes,
|
||||
/// Response-byte limit was zero.
|
||||
ZeroResponseBytes,
|
||||
/// Nesting limit was zero.
|
||||
ZeroNesting,
|
||||
/// Batch-item limit was zero.
|
||||
ZeroBatchItems,
|
||||
}
|
||||
|
||||
impl Display for LimitConfigurationError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(match self {
|
||||
Self::ZeroRequestBytes => "request byte limit must be nonzero",
|
||||
Self::ZeroResponseBytes => "response byte limit must be nonzero",
|
||||
Self::ZeroNesting => "nesting limit must be nonzero",
|
||||
Self::ZeroBatchItems => "batch item limit must be nonzero",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for LimitConfigurationError {}
|
||||
|
||||
/// Whether a body is being decoded as a request or response.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BodyKind {
|
||||
/// An inbound server request.
|
||||
Request,
|
||||
/// An inbound client response.
|
||||
Response,
|
||||
}
|
||||
|
||||
/// The class of a resource limit exceeded by a wire representation.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ResourceLimitKind {
|
||||
/// A request or response representation exceeded its byte-size limit.
|
||||
RepresentationBytes,
|
||||
/// A logical limit such as nesting depth, batch count, or collection size was exceeded.
|
||||
Logical,
|
||||
}
|
||||
|
||||
/// A malformed or locally disallowed wire representation.
|
||||
#[derive(Debug)]
|
||||
pub enum CodecError {
|
||||
/// The body exceeds its configured byte limit.
|
||||
BodyTooLarge {
|
||||
/// Actual body size.
|
||||
actual: usize,
|
||||
/// Configured maximum.
|
||||
maximum: usize,
|
||||
},
|
||||
/// JSON syntax is invalid.
|
||||
InvalidJson(serde_json::Error),
|
||||
/// A JSON container exceeds the configured nesting depth.
|
||||
NestingTooDeep {
|
||||
/// Configured maximum.
|
||||
maximum: usize,
|
||||
},
|
||||
/// A required field is absent.
|
||||
MissingField {
|
||||
/// Field name.
|
||||
field: String,
|
||||
},
|
||||
/// An undeclared field is present.
|
||||
UnknownField {
|
||||
/// Field name.
|
||||
field: String,
|
||||
},
|
||||
/// A field has an invalid JSON type or semantic representation.
|
||||
InvalidField {
|
||||
/// Field name or value location.
|
||||
field: String,
|
||||
/// Stable human-readable reason.
|
||||
reason: String,
|
||||
},
|
||||
/// An optional field was represented by JSON null rather than omission.
|
||||
NullOptionalField {
|
||||
/// Field name.
|
||||
field: String,
|
||||
},
|
||||
/// Base64 is not canonical RFC 4648 Section 4 encoding.
|
||||
InvalidBase64 {
|
||||
/// Field name or value location.
|
||||
field: String,
|
||||
},
|
||||
/// Logical protocol validation rejected the decoded representation.
|
||||
ProtocolValidation(wip_protocol::ValidationError),
|
||||
/// The batch exceeds its configured item count.
|
||||
TooManyBatchItems {
|
||||
/// Actual item count.
|
||||
actual: usize,
|
||||
/// Configured maximum.
|
||||
maximum: usize,
|
||||
},
|
||||
/// Batch item identifiers are not unique.
|
||||
DuplicateBatchId {
|
||||
/// Repeated identifier.
|
||||
id: String,
|
||||
},
|
||||
/// A response contains a batch identifier that was not requested.
|
||||
UnexpectedBatchId {
|
||||
/// Unexpected identifier.
|
||||
id: String,
|
||||
},
|
||||
/// A response omitted a requested batch identifier.
|
||||
MissingBatchId {
|
||||
/// Missing identifier.
|
||||
id: String,
|
||||
},
|
||||
/// A batch item result does not match its requested interaction.
|
||||
BatchInteractionMismatch {
|
||||
/// Item identifier.
|
||||
id: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl CodecError {
|
||||
/// Classifies this failure when it represents a canonical resource limit.
|
||||
#[must_use]
|
||||
pub const fn resource_limit_kind(&self) -> Option<ResourceLimitKind> {
|
||||
match self {
|
||||
Self::BodyTooLarge { .. } => Some(ResourceLimitKind::RepresentationBytes),
|
||||
Self::NestingTooDeep { .. } | Self::TooManyBatchItems { .. } => {
|
||||
Some(ResourceLimitKind::Logical)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for CodecError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::BodyTooLarge { actual, maximum } => {
|
||||
write!(formatter, "body has {actual} bytes; maximum is {maximum}")
|
||||
}
|
||||
Self::InvalidJson(error) => write!(formatter, "invalid JSON: {error}"),
|
||||
Self::NestingTooDeep { maximum } => {
|
||||
write!(formatter, "JSON nesting exceeds maximum {maximum}")
|
||||
}
|
||||
Self::MissingField { field } => write!(formatter, "missing field `{field}`"),
|
||||
Self::UnknownField { field } => write!(formatter, "unknown field `{field}`"),
|
||||
Self::InvalidField { field, reason } => {
|
||||
write!(formatter, "invalid field `{field}`: {reason}")
|
||||
}
|
||||
Self::NullOptionalField { field } => {
|
||||
write!(
|
||||
formatter,
|
||||
"optional field `{field}` must be omitted instead of null"
|
||||
)
|
||||
}
|
||||
Self::InvalidBase64 { field } => {
|
||||
write!(formatter, "field `{field}` is not canonical base64")
|
||||
}
|
||||
Self::ProtocolValidation(error) => error.fmt(formatter),
|
||||
Self::TooManyBatchItems { actual, maximum } => {
|
||||
write!(formatter, "batch has {actual} items; maximum is {maximum}")
|
||||
}
|
||||
Self::DuplicateBatchId { id } => write!(formatter, "duplicate batch id `{id}`"),
|
||||
Self::UnexpectedBatchId { id } => write!(formatter, "unexpected batch id `{id}`"),
|
||||
Self::MissingBatchId { id } => write!(formatter, "missing batch id `{id}`"),
|
||||
Self::BatchInteractionMismatch { id } => {
|
||||
write!(formatter, "batch result does not match request `{id}`")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CodecError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::InvalidJson(error) => Some(error),
|
||||
Self::ProtocolValidation(error) => Some(error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<wip_protocol::ValidationError> for CodecError {
|
||||
fn from(value: wip_protocol::ValidationError) -> Self {
|
||||
Self::ProtocolValidation(value)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,68 @@
|
||||
//! Framework-independent standard WIP over HTTP v1 binding.
|
||||
//!
|
||||
//! This crate owns endpoint and route derivation, UTF-8 JSON encoding, canonical
|
||||
//! success and error response handling, HTTP status mapping, descriptor-guided
|
||||
//! operation-value conversion, and retrieval batching. It deliberately performs
|
||||
//! no I/O and depends on no server framework, TLS implementation, filesystem
|
||||
//! projection, client cache, or presentation layer. URL schemes, TLS,
|
||||
//! certificates, authentication mechanisms, proxies, and caches are selected by
|
||||
//! the HTTP implementation and deployment rather than by WIP conformance.
|
||||
//!
|
||||
//! Logical values remain owned by [`wip_protocol`]. Validators and `Bytes` are
|
||||
//! encoded in JSON bodies using canonical RFC 4648 Section 4 base64; this crate
|
||||
//! does not infer WIP validator semantics from `ETag` or `If-Match`.
|
||||
//!
|
||||
//! ```
|
||||
//! use wip_http::{Endpoint, Limits, encode_observe_request};
|
||||
//! use wip_protocol::ObserveRequest;
|
||||
//!
|
||||
//! let endpoint = Endpoint::parse("http://example.test/api/wip")?;
|
||||
//! let limits = Limits::new(64 * 1024, 1024 * 1024, 64, 100)?;
|
||||
//! let request = encode_observe_request(
|
||||
//! &endpoint,
|
||||
//! &ObserveRequest { path: "/items/123".into(), depth: 0 },
|
||||
//! limits,
|
||||
//! )?;
|
||||
//! assert_eq!(request.uri(), "http://example.test/api/wip/v1/observe");
|
||||
//! assert_eq!(request.method(), http::Method::POST);
|
||||
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
//! ```
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
mod batch;
|
||||
mod codec;
|
||||
mod endpoint;
|
||||
mod error;
|
||||
mod json;
|
||||
mod response;
|
||||
|
||||
pub use batch::{
|
||||
BatchMethod, BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse,
|
||||
BatchResponseItem, BatchSuccess, decode_batch_request, decode_batch_response,
|
||||
encode_batch_error_response, encode_batch_request, encode_batch_resource_limit_error_response,
|
||||
encode_batch_response,
|
||||
};
|
||||
pub use codec::{
|
||||
CallOperationMetadata, EncodeHttpError, RequestMetadataError, decode_call_operation_metadata,
|
||||
decode_call_operation_request, decode_call_operation_response, decode_fetch_interface_request,
|
||||
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
|
||||
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
|
||||
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
|
||||
encode_protocol_error_response, encode_resource_limit_error_response, is_json_content_type,
|
||||
validate_http_request,
|
||||
};
|
||||
pub use endpoint::{Endpoint, EndpointError, JSON_CONTENT_TYPE, Route};
|
||||
pub use error::{BodyKind, CodecError, LimitConfigurationError, Limits, ResourceLimitKind};
|
||||
pub use response::{
|
||||
ClientResponseError, DecodedResponse, InvalidResponseKind, StatusMismatch,
|
||||
TransportBindingFailure, TransportFailureKind, error_code_name, status_for_error,
|
||||
status_for_resource_limit,
|
||||
};
|
||||
|
||||
/// Framework-neutral HTTP types used by this binding's public API.
|
||||
pub use http;
|
||||
/// URL type used by [`Endpoint`].
|
||||
pub use url;
|
||||
/// Transport-independent logical protocol model used by this binding.
|
||||
pub use wip_protocol;
|
||||
@@ -0,0 +1,365 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
use http::StatusCode;
|
||||
use serde_json::{Map, Value as Json};
|
||||
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||
|
||||
use crate::{BodyKind, CodecError, Limits, ResourceLimitKind, json};
|
||||
|
||||
/// A successfully classified client response.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum DecodedResponse<T> {
|
||||
/// A successful direct response body.
|
||||
Success(T),
|
||||
/// A canonical Host protocol failure.
|
||||
ProtocolFailure {
|
||||
/// The authoritative protocol error decoded from the envelope.
|
||||
error: ProtocolError,
|
||||
/// A diagnostic when the HTTP status differs from the canonical mapping.
|
||||
status_mismatch: Option<StatusMismatch>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Diagnostic evidence that HTTP metadata disagrees with a valid error envelope.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StatusMismatch {
|
||||
/// Status received from the peer.
|
||||
pub actual: StatusCode,
|
||||
/// Canonical status for the envelope's protocol code.
|
||||
pub expected: StatusCode,
|
||||
}
|
||||
|
||||
/// Class of non-protocol HTTP failure returned without a valid WIP envelope.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TransportFailureKind {
|
||||
/// HTTP 401, commonly emitted by authentication infrastructure.
|
||||
AuthenticationRequired,
|
||||
/// HTTP 403, commonly emitted by endpoint policy or infrastructure.
|
||||
EndpointForbidden,
|
||||
/// Another non-success HTTP response without a WIP error envelope.
|
||||
HttpStatus,
|
||||
}
|
||||
|
||||
/// A non-success HTTP response that is not a valid WIP protocol failure.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TransportBindingFailure {
|
||||
/// HTTP status returned by the peer or intermediary.
|
||||
pub status: StatusCode,
|
||||
/// Coarse classification which does not invent a protocol error code.
|
||||
pub kind: TransportFailureKind,
|
||||
}
|
||||
|
||||
/// Why a response violates the WIP v1 response contract.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum InvalidResponseKind {
|
||||
/// A 2xx response contained an error envelope.
|
||||
ErrorEnvelopeOnSuccessStatus,
|
||||
/// A non-2xx response contained a valid success body.
|
||||
SuccessBodyOnErrorStatus,
|
||||
/// A valid error envelope used a code forbidden for the interaction.
|
||||
DisallowedProtocolCode,
|
||||
/// A valid success body used a 2xx status other than canonical HTTP 200.
|
||||
NonCanonicalSuccessStatus,
|
||||
/// A 2xx body was malformed or semantically invalid.
|
||||
InvalidSuccessBody,
|
||||
/// A batch response did not correlate exactly with its request.
|
||||
InvalidBatch,
|
||||
}
|
||||
|
||||
/// A local failure while classifying or validating a peer response.
|
||||
#[derive(Debug)]
|
||||
pub enum ClientResponseError {
|
||||
/// The HTTP exchange failed outside the protocol envelope.
|
||||
TransportBinding(TransportBindingFailure),
|
||||
/// The peer supplied a contradictory or invalid WIP response.
|
||||
InvalidResponse {
|
||||
/// Stable response-failure category.
|
||||
kind: InvalidResponseKind,
|
||||
/// Bounded diagnostic from local decoding.
|
||||
detail: String,
|
||||
},
|
||||
/// The descriptor is structurally valid but uses an unsupported format.
|
||||
UnsupportedDescriptorFormat {
|
||||
/// Format identifier received from the Host.
|
||||
format: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl ClientResponseError {
|
||||
pub(crate) fn invalid(kind: InvalidResponseKind, detail: impl Into<String>) -> Self {
|
||||
Self::InvalidResponse {
|
||||
kind,
|
||||
detail: detail.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for ClientResponseError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::TransportBinding(failure) => write!(
|
||||
formatter,
|
||||
"transport binding failure ({:?}, HTTP {})",
|
||||
failure.kind, failure.status
|
||||
),
|
||||
Self::InvalidResponse { kind, detail } => {
|
||||
write!(formatter, "invalid WIP response ({kind:?}): {detail}")
|
||||
}
|
||||
Self::UnsupportedDescriptorFormat { format } => {
|
||||
write!(
|
||||
formatter,
|
||||
"unsupported interface descriptor format `{format}`"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ClientResponseError {}
|
||||
|
||||
/// Returns the canonical HTTP status for a wire-level protocol error.
|
||||
///
|
||||
/// [`ProtocolErrorCode::ResourceLimitExceeded`] defaults to the logical-limit
|
||||
/// status. Use [`status_for_resource_limit`] when the concrete limit class is
|
||||
/// known.
|
||||
#[must_use]
|
||||
pub const fn status_for_error(code: ProtocolErrorCode) -> StatusCode {
|
||||
match code {
|
||||
ProtocolErrorCode::InvalidRequest => StatusCode::BAD_REQUEST,
|
||||
ProtocolErrorCode::NotFound | ProtocolErrorCode::InterfaceNotFound => StatusCode::NOT_FOUND,
|
||||
ProtocolErrorCode::InterfaceMismatch => StatusCode::CONFLICT,
|
||||
ProtocolErrorCode::OperationNotFound => StatusCode::NOT_FOUND,
|
||||
ProtocolErrorCode::InvalidArguments => StatusCode::UNPROCESSABLE_ENTITY,
|
||||
ProtocolErrorCode::ValidatorRequired | ProtocolErrorCode::InterfaceValidatorRequired => {
|
||||
StatusCode::PRECONDITION_REQUIRED
|
||||
}
|
||||
ProtocolErrorCode::ValidatorMismatch | ProtocolErrorCode::InterfaceValidatorMismatch => {
|
||||
StatusCode::PRECONDITION_FAILED
|
||||
}
|
||||
ProtocolErrorCode::PermissionDenied => StatusCode::FORBIDDEN,
|
||||
ProtocolErrorCode::ResourceLimitExceeded => StatusCode::UNPROCESSABLE_ENTITY,
|
||||
ProtocolErrorCode::Internal | ProtocolErrorCode::OperationOutcomeUnknown => {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the canonical HTTP status for a concrete resource-limit class.
|
||||
#[must_use]
|
||||
pub const fn status_for_resource_limit(kind: ResourceLimitKind) -> StatusCode {
|
||||
match kind {
|
||||
ResourceLimitKind::RepresentationBytes => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
ResourceLimitKind::Logical => StatusCode::UNPROCESSABLE_ENTITY,
|
||||
}
|
||||
}
|
||||
|
||||
fn status_matches_error(status: StatusCode, code: ProtocolErrorCode) -> bool {
|
||||
match code {
|
||||
ProtocolErrorCode::ResourceLimitExceeded => {
|
||||
status == StatusCode::PAYLOAD_TOO_LARGE || status == StatusCode::UNPROCESSABLE_ENTITY
|
||||
}
|
||||
_ => status == status_for_error(code),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the stable snake-case wire spelling of a protocol code.
|
||||
#[must_use]
|
||||
pub const fn error_code_name(code: ProtocolErrorCode) -> &'static str {
|
||||
match code {
|
||||
ProtocolErrorCode::InvalidRequest => "invalid_request",
|
||||
ProtocolErrorCode::NotFound => "not_found",
|
||||
ProtocolErrorCode::InterfaceNotFound => "interface_not_found",
|
||||
ProtocolErrorCode::InterfaceMismatch => "interface_mismatch",
|
||||
ProtocolErrorCode::OperationNotFound => "operation_not_found",
|
||||
ProtocolErrorCode::InvalidArguments => "invalid_arguments",
|
||||
ProtocolErrorCode::ValidatorRequired => "validator_required",
|
||||
ProtocolErrorCode::ValidatorMismatch => "validator_mismatch",
|
||||
ProtocolErrorCode::InterfaceValidatorRequired => "interface_validator_required",
|
||||
ProtocolErrorCode::InterfaceValidatorMismatch => "interface_validator_mismatch",
|
||||
ProtocolErrorCode::PermissionDenied => "permission_denied",
|
||||
ProtocolErrorCode::ResourceLimitExceeded => "resource_limit_exceeded",
|
||||
ProtocolErrorCode::Internal => "internal",
|
||||
ProtocolErrorCode::OperationOutcomeUnknown => "operation_outcome_unknown",
|
||||
}
|
||||
}
|
||||
|
||||
fn error_code_from_name(name: &str) -> Option<ProtocolErrorCode> {
|
||||
Some(match name {
|
||||
"invalid_request" => ProtocolErrorCode::InvalidRequest,
|
||||
"not_found" => ProtocolErrorCode::NotFound,
|
||||
"interface_not_found" => ProtocolErrorCode::InterfaceNotFound,
|
||||
"interface_mismatch" => ProtocolErrorCode::InterfaceMismatch,
|
||||
"operation_not_found" => ProtocolErrorCode::OperationNotFound,
|
||||
"invalid_arguments" => ProtocolErrorCode::InvalidArguments,
|
||||
"validator_required" => ProtocolErrorCode::ValidatorRequired,
|
||||
"validator_mismatch" => ProtocolErrorCode::ValidatorMismatch,
|
||||
"interface_validator_required" => ProtocolErrorCode::InterfaceValidatorRequired,
|
||||
"interface_validator_mismatch" => ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||
"permission_denied" => ProtocolErrorCode::PermissionDenied,
|
||||
"resource_limit_exceeded" => ProtocolErrorCode::ResourceLimitExceeded,
|
||||
"internal" => ProtocolErrorCode::Internal,
|
||||
"operation_outcome_unknown" => ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn error_to_json(error: &ProtocolError) -> Json {
|
||||
serde_json::json!({
|
||||
"error": {
|
||||
"code": error_code_name(error.code),
|
||||
"message": error.message,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn item_error_to_json(error: &ProtocolError) -> Json {
|
||||
serde_json::json!({
|
||||
"code": error_code_name(error.code),
|
||||
"message": error.message,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn item_error_from_json(value: &Json) -> Result<ProtocolError, CodecError> {
|
||||
let fields = value
|
||||
.as_object()
|
||||
.ok_or_else(|| invalid_field("error", "expected object"))?;
|
||||
exact(fields, &["code", "message"], "error")?;
|
||||
let code_name = required_string(fields, "code")?;
|
||||
let code = error_code_from_name(code_name)
|
||||
.ok_or_else(|| invalid_field("error.code", "unknown protocol error code"))?;
|
||||
let message = required_string(fields, "message")?.to_owned();
|
||||
Ok(ProtocolError { code, message })
|
||||
}
|
||||
|
||||
fn envelope_error_from_json(value: &Json) -> Result<Option<ProtocolError>, CodecError> {
|
||||
let Some(fields) = value.as_object() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if fields.len() != 1 || !fields.contains_key("error") {
|
||||
return Ok(None);
|
||||
}
|
||||
item_error_from_json(&fields["error"]).map(Some)
|
||||
}
|
||||
|
||||
fn exact(fields: &Map<String, Json>, allowed: &[&str], parent: &str) -> Result<(), CodecError> {
|
||||
for name in fields.keys() {
|
||||
if !allowed.contains(&name.as_str()) {
|
||||
return Err(CodecError::UnknownField {
|
||||
field: format!("{parent}.{name}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
for name in allowed {
|
||||
if !fields.contains_key(*name) {
|
||||
return Err(CodecError::MissingField {
|
||||
field: format!("{parent}.{name}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn required_string<'a>(fields: &'a Map<String, Json>, name: &str) -> Result<&'a str, CodecError> {
|
||||
fields
|
||||
.get(name)
|
||||
.and_then(Json::as_str)
|
||||
.ok_or_else(|| invalid_field(&format!("error.{name}"), "expected string"))
|
||||
}
|
||||
|
||||
fn invalid_field(field: &str, reason: &str) -> CodecError {
|
||||
CodecError::InvalidField {
|
||||
field: field.into(),
|
||||
reason: reason.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode<T>(
|
||||
status: StatusCode,
|
||||
body: &[u8],
|
||||
interaction: ProtocolInteraction,
|
||||
limits: Limits,
|
||||
success: impl FnOnce(&Json) -> Result<T, CodecError>,
|
||||
) -> Result<DecodedResponse<T>, ClientResponseError> {
|
||||
let value = match json::parse(body, BodyKind::Response, limits) {
|
||||
Ok(value) => value,
|
||||
Err(_) if !status.is_success() => {
|
||||
return Err(transport_failure(status));
|
||||
}
|
||||
Err(error) => {
|
||||
return Err(ClientResponseError::invalid(
|
||||
InvalidResponseKind::InvalidSuccessBody,
|
||||
error.to_string(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
match envelope_error_from_json(&value) {
|
||||
Ok(Some(error)) => {
|
||||
if status.is_success() {
|
||||
return Err(ClientResponseError::invalid(
|
||||
InvalidResponseKind::ErrorEnvelopeOnSuccessStatus,
|
||||
"protocol error envelope carried by a success status",
|
||||
));
|
||||
}
|
||||
if !error.code.is_allowed_for(interaction) {
|
||||
return Err(ClientResponseError::invalid(
|
||||
InvalidResponseKind::DisallowedProtocolCode,
|
||||
format!(
|
||||
"code `{}` is not allowed for {interaction:?}",
|
||||
error_code_name(error.code)
|
||||
),
|
||||
));
|
||||
}
|
||||
let expected = status_for_error(error.code);
|
||||
let status_mismatch =
|
||||
(!status_matches_error(status, error.code)).then_some(StatusMismatch {
|
||||
actual: status,
|
||||
expected,
|
||||
});
|
||||
Ok(DecodedResponse::ProtocolFailure {
|
||||
error,
|
||||
status_mismatch,
|
||||
})
|
||||
}
|
||||
Err(_) if !status.is_success() => Err(transport_failure(status)),
|
||||
Err(error) => Err(ClientResponseError::invalid(
|
||||
InvalidResponseKind::InvalidSuccessBody,
|
||||
error.to_string(),
|
||||
)),
|
||||
Ok(None) if status == StatusCode::OK => success(&value)
|
||||
.map(DecodedResponse::Success)
|
||||
.map_err(|error| {
|
||||
ClientResponseError::invalid(
|
||||
InvalidResponseKind::InvalidSuccessBody,
|
||||
error.to_string(),
|
||||
)
|
||||
}),
|
||||
Ok(None) if status.is_success() => match success(&value) {
|
||||
Ok(_) => Err(ClientResponseError::invalid(
|
||||
InvalidResponseKind::NonCanonicalSuccessStatus,
|
||||
format!("success body carried by non-canonical HTTP {status}"),
|
||||
)),
|
||||
Err(error) => Err(ClientResponseError::invalid(
|
||||
InvalidResponseKind::InvalidSuccessBody,
|
||||
error.to_string(),
|
||||
)),
|
||||
},
|
||||
Ok(None) => match success(&value) {
|
||||
Ok(_) => Err(ClientResponseError::invalid(
|
||||
InvalidResponseKind::SuccessBodyOnErrorStatus,
|
||||
"valid success body carried by a non-success status",
|
||||
)),
|
||||
Err(_) => Err(transport_failure(status)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn transport_failure(status: StatusCode) -> ClientResponseError {
|
||||
let kind = match status {
|
||||
StatusCode::UNAUTHORIZED => TransportFailureKind::AuthenticationRequired,
|
||||
StatusCode::FORBIDDEN => TransportFailureKind::EndpointForbidden,
|
||||
_ => TransportFailureKind::HttpStatus,
|
||||
};
|
||||
ClientResponseError::TransportBinding(TransportBindingFailure { status, kind })
|
||||
}
|
||||
Reference in New Issue
Block a user