feat(import): preserve supported HTTP contracts
This commit is contained in:
1 parent
083974c27f
commit
f8ee7c9bfe
87 files changed
+7496
-534
No files matched your search
@@ -1,12 +1,85 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crank_core::Target;
|
||||
use crank_schema::{SchemaError, SchemaKind};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{PreparedRequest, RuntimeError, RuntimeOperation};
|
||||
|
||||
/// Validates the imported `content_type`/`body` pair before mapping. The
|
||||
/// public schema exposes the union of supported body shapes, while this check
|
||||
/// binds the selected media type to its corresponding branch.
|
||||
pub(crate) fn validate_selected_body_variant(
|
||||
operation: &RuntimeOperation,
|
||||
input: &Value,
|
||||
) -> Result<(), RuntimeError> {
|
||||
let Target::Rest(target) = &operation.target;
|
||||
let Some(contract) = &target.request_contract else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(input) = input.as_object() else {
|
||||
return Ok(());
|
||||
};
|
||||
let body_field = contract.body_field.as_str();
|
||||
let Some(selector_field) = contract.selector_field.as_deref() else {
|
||||
if contract.body_required && !input.contains_key(body_field) {
|
||||
return Err(RuntimeError::InputSchema(SchemaError::missing_field(
|
||||
format!("$.{body_field}"),
|
||||
)));
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
match (input.get(selector_field), input.get(body_field)) {
|
||||
(None, None) if !contract.body_required => Ok(()),
|
||||
(_, None) => Err(RuntimeError::InputSchema(SchemaError::missing_field(
|
||||
format!("$.{body_field}"),
|
||||
))),
|
||||
(None, Some(_)) => Err(RuntimeError::InputSchema(SchemaError::missing_field(
|
||||
format!("$.{selector_field}"),
|
||||
))),
|
||||
(Some(selector), Some(_)) => {
|
||||
let Some(selector) = selector.as_str() else {
|
||||
return Err(RuntimeError::InputSchema(SchemaError::invalid_type(
|
||||
format!("$.{selector_field}"),
|
||||
"enum",
|
||||
"non-string",
|
||||
)));
|
||||
};
|
||||
let Some(descriptor) = contract
|
||||
.variants
|
||||
.iter()
|
||||
.find(|variant| variant.media_type == selector)
|
||||
else {
|
||||
return Err(RuntimeError::InputSchema(SchemaError::invalid_enum_value(
|
||||
format!("$.{selector_field}"),
|
||||
contract
|
||||
.variants
|
||||
.iter()
|
||||
.map(|variant| variant.media_type.clone())
|
||||
.collect(),
|
||||
selector,
|
||||
)));
|
||||
};
|
||||
let selected_schema = if operation.input_schema.kind == SchemaKind::Oneof {
|
||||
operation
|
||||
.input_schema
|
||||
.variants
|
||||
.get(descriptor.schema_variant)
|
||||
.ok_or(RuntimeError::InvalidExecutionRequest)?
|
||||
} else if descriptor.schema_variant == 0 {
|
||||
&operation.input_schema
|
||||
} else {
|
||||
return Err(RuntimeError::InvalidExecutionRequest);
|
||||
};
|
||||
selected_schema
|
||||
.validate_shape(&Value::Object(input.clone()))
|
||||
.map_err(RuntimeError::InputSchema)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PreparedRequest {
|
||||
pub fn from_mapping_output(mapped: &Value) -> Result<Self, RuntimeError> {
|
||||
pub fn from_mapping_output(mapped: &Value, target: &Target) -> Result<Self, RuntimeError> {
|
||||
let request =
|
||||
mapped
|
||||
.get("request")
|
||||
@@ -15,12 +88,40 @@ impl PreparedRequest {
|
||||
reason: "mapped input must contain request root".to_owned(),
|
||||
})?;
|
||||
|
||||
let mut headers = read_string_map(request.get("headers"), "request.headers")?;
|
||||
for (index, (name, value)) in read_string_map(request.get("cookies"), "request.cookies")?
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
headers.insert(
|
||||
format!("x-crank-internal-cookie-{index}"),
|
||||
format!("{name}\t{value}"),
|
||||
);
|
||||
}
|
||||
let typed_body_contract =
|
||||
matches!(target, Target::Rest(target) if target.request_contract.is_some());
|
||||
let body = if typed_body_contract {
|
||||
request.get("body").cloned()
|
||||
} else {
|
||||
request.get("body").and_then(non_empty_legacy_body).cloned()
|
||||
};
|
||||
let body_content_type = match request.get("body_content_type") {
|
||||
Some(Value::String(value)) => Some(value.clone()),
|
||||
Some(_) => {
|
||||
return Err(RuntimeError::InvalidPreparedRequest {
|
||||
field: "request.body_content_type".to_owned(),
|
||||
reason: "must be a string".to_owned(),
|
||||
});
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
path_params: read_string_map(request.get("path"), "request.path")?,
|
||||
query_params: read_string_map(request.get("query"), "request.query")?,
|
||||
headers: read_string_map(request.get("headers"), "request.headers")?,
|
||||
headers,
|
||||
trusted_header_names: Default::default(),
|
||||
body: request.get("body").and_then(non_empty_body).cloned(),
|
||||
body,
|
||||
body_content_type,
|
||||
timeout_ms: 0,
|
||||
})
|
||||
}
|
||||
@@ -93,10 +194,74 @@ fn stringify_value(value: &Value) -> Result<String, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_body(value: &Value) -> Option<&Value> {
|
||||
fn non_empty_legacy_body(value: &Value) -> Option<&Value> {
|
||||
match value {
|
||||
Value::Null => None,
|
||||
Value::Object(object) if object.is_empty() => None,
|
||||
_ => Some(value),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crank_core::{
|
||||
HttpMethod, RestRequestContract, RestRequestContractVersion, RestRequestDescriptor,
|
||||
RestTarget, Target,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::PreparedRequest;
|
||||
|
||||
#[test]
|
||||
fn legacy_empty_and_null_bodies_remain_absent() {
|
||||
let target = legacy_target();
|
||||
for body in [json!(null), json!({})] {
|
||||
let mapped = json!({"request": {"body": body}});
|
||||
assert_eq!(
|
||||
PreparedRequest::from_mapping_output(&mapped, &target)
|
||||
.unwrap()
|
||||
.body,
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_contract_preserves_explicit_empty_and_null_bodies() {
|
||||
let mut target = legacy_target();
|
||||
let Target::Rest(rest) = &mut target;
|
||||
rest.request_contract = Some(RestRequestContract {
|
||||
version: RestRequestContractVersion::V1,
|
||||
body_field: "body".to_owned(),
|
||||
selector_field: None,
|
||||
body_required: true,
|
||||
variants: vec![RestRequestDescriptor {
|
||||
media_type: "application/json".to_owned(),
|
||||
schema_variant: 0,
|
||||
}],
|
||||
});
|
||||
for body in [json!(null), json!({})] {
|
||||
let mapped = json!({"request": {"body": body}});
|
||||
assert_eq!(
|
||||
PreparedRequest::from_mapping_output(&mapped, &target)
|
||||
.unwrap()
|
||||
.body,
|
||||
Some(body)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_target() -> Target {
|
||||
Target::Rest(RestTarget {
|
||||
base_url: "https://example.invalid".to_owned(),
|
||||
method: HttpMethod::Post,
|
||||
path_template: "/".to_owned(),
|
||||
static_headers: BTreeMap::new(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: BTreeMap::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user