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
@@ -85,6 +85,7 @@ fn infer_safety_class(operation: &RuntimeOperation) -> OperationSafetyClass {
|
||||
match &operation.target {
|
||||
Target::Rest(target) => match target.method {
|
||||
HttpMethod::Get => OperationSafetyClass::Read,
|
||||
HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
|
||||
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
||||
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
||||
},
|
||||
|
||||
@@ -185,6 +185,7 @@ mod tests {
|
||||
fn operation() -> RuntimeOperation {
|
||||
let schema = Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: None,
|
||||
description: None,
|
||||
required: true,
|
||||
nullable: false,
|
||||
@@ -204,6 +205,9 @@ mod tests {
|
||||
method: HttpMethod::Post,
|
||||
path_template: "/".to_owned(),
|
||||
static_headers: BTreeMap::new(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: BTreeMap::new(),
|
||||
}),
|
||||
input_schema: schema.clone(),
|
||||
output_schema: schema,
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use crank_core::{
|
||||
AdapterRegistry, CoordinationStateStore, ExecutionMode, InvocationSource, InvocationStatus,
|
||||
MeteringEvent, ResponseCacheStore, SharedMeteringSink, SharedProtocolAdapter,
|
||||
MeteringEvent, ResponseCacheStore, SharedMeteringSink, SharedProtocolAdapter, Target,
|
||||
};
|
||||
use crank_metrics::{
|
||||
CacheOutcome, ConfirmationOutcome, IdempotencyOutcome, InFlightGuard,
|
||||
@@ -24,7 +24,7 @@ use crate::{
|
||||
AdapterResponse, ExecutionAuthorization, PreparedRequest, RuntimeError,
|
||||
RuntimeExecutionRequest, RuntimeLimits, RuntimeOperation, RuntimeRequestContext,
|
||||
auth::apply_resolved_auth,
|
||||
request_preparation::adapter_prepared_request,
|
||||
request_preparation::{adapter_prepared_request, validate_selected_body_variant},
|
||||
response_cache::{
|
||||
adapter_response_from_cached, cached_response_from_adapter, response_cache_key,
|
||||
response_cache_ttl,
|
||||
@@ -284,6 +284,7 @@ impl RuntimeExecutor {
|
||||
.input_schema
|
||||
.validate_shape(input)
|
||||
.map_err(RuntimeError::InputSchema)?;
|
||||
validate_selected_body_variant(operation, input)?;
|
||||
|
||||
if operation.input_mapping.is_empty() {
|
||||
return Ok(PreparedRequest::default());
|
||||
@@ -293,7 +294,16 @@ impl RuntimeExecutor {
|
||||
.input_mapping
|
||||
.apply(&json!({ "mcp": input }))
|
||||
.map_err(RuntimeError::InputMapping)?;
|
||||
PreparedRequest::from_mapping_output(&mapped_input)
|
||||
let mut prepared = PreparedRequest::from_mapping_output(&mapped_input, &operation.target)?;
|
||||
let Target::Rest(target) = &operation.target;
|
||||
if let Some(contract) = &target.request_contract
|
||||
&& input.get(&contract.body_field).is_none()
|
||||
{
|
||||
// Mapping initializes an empty body object for legacy field mappings.
|
||||
// A typed optional body is absent unless its public argument was supplied.
|
||||
prepared.body = None;
|
||||
}
|
||||
Ok(prepared)
|
||||
}
|
||||
|
||||
async fn execute_prepared(
|
||||
@@ -838,8 +848,7 @@ fn transform_response(
|
||||
let span = Stage::RuntimeResponseTransform.span();
|
||||
let result = span.in_scope(|| {
|
||||
let finalized_output = finalize_output(operation, response)?;
|
||||
operation
|
||||
.output_schema
|
||||
output_schema_for_response(operation, response)?
|
||||
.validate_shape(&finalized_output)
|
||||
.map_err(RuntimeError::OutputSchema)?;
|
||||
Ok(finalized_output)
|
||||
@@ -854,6 +863,43 @@ fn transform_response(
|
||||
result
|
||||
}
|
||||
|
||||
fn output_schema_for_response<'a>(
|
||||
operation: &'a RuntimeOperation,
|
||||
response: &AdapterResponse,
|
||||
) -> Result<&'a crank_schema::Schema, RuntimeError> {
|
||||
let Target::Rest(target) = &operation.target;
|
||||
if target.response_contract.is_empty() {
|
||||
return Ok(&operation.output_schema);
|
||||
}
|
||||
let media_type = response
|
||||
.headers
|
||||
.get("content-type")
|
||||
.and_then(|value| value.split(';').next())
|
||||
.map(str::trim);
|
||||
let descriptor = target
|
||||
.response_contract
|
||||
.iter()
|
||||
.filter(|descriptor| descriptor.status_code == response.status_code)
|
||||
.find(|descriptor| match (&descriptor.media_type, media_type) {
|
||||
(Some(expected), Some(actual)) => expected.eq_ignore_ascii_case(actual),
|
||||
(None, _) => response.body.is_null(),
|
||||
_ => false,
|
||||
})
|
||||
.ok_or(RuntimeError::InvalidExecutionRequest)?;
|
||||
if target.response_contract.len() > 1
|
||||
&& operation.output_schema.kind == crank_schema::SchemaKind::Oneof
|
||||
{
|
||||
return operation
|
||||
.output_schema
|
||||
.variants
|
||||
.get(descriptor.schema_variant)
|
||||
.ok_or(RuntimeError::InvalidExecutionRequest);
|
||||
}
|
||||
(descriptor.schema_variant == 0)
|
||||
.then_some(&operation.output_schema)
|
||||
.ok_or(RuntimeError::InvalidExecutionRequest)
|
||||
}
|
||||
|
||||
fn record_runtime_result<T>(span: &Span, result: &Result<T, RuntimeError>) {
|
||||
match result {
|
||||
Ok(_) => StageOutcome::Success.record(span),
|
||||
|
||||
@@ -262,8 +262,14 @@ async fn resolve_existing(
|
||||
}
|
||||
|
||||
pub fn policy(operation: &RuntimeOperation) -> Option<&IdempotencyPolicy> {
|
||||
let is_mutating_rest =
|
||||
matches!(&operation.target, Target::Rest(target) if target.method != HttpMethod::Get);
|
||||
let is_mutating_rest = matches!(
|
||||
&operation.target,
|
||||
Target::Rest(target)
|
||||
if matches!(
|
||||
target.method,
|
||||
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch | HttpMethod::Delete
|
||||
)
|
||||
);
|
||||
if !is_mutating_rest {
|
||||
return None;
|
||||
}
|
||||
@@ -398,9 +404,13 @@ mod tests {
|
||||
method: HttpMethod::Post,
|
||||
path_template: "/orders".to_owned(),
|
||||
static_headers: BTreeMap::new(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: BTreeMap::new(),
|
||||
}),
|
||||
input_schema: Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: None,
|
||||
description: None,
|
||||
required: true,
|
||||
nullable: false,
|
||||
@@ -412,6 +422,7 @@ mod tests {
|
||||
},
|
||||
output_schema: Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: None,
|
||||
description: None,
|
||||
required: true,
|
||||
nullable: false,
|
||||
|
||||
@@ -51,6 +51,8 @@ pub struct PreparedRequest {
|
||||
pub trusted_header_names: BTreeSet<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub body: Option<serde_json::Value>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub body_content_type: Option<String>,
|
||||
#[serde(default)]
|
||||
pub timeout_ms: u64,
|
||||
}
|
||||
@@ -72,6 +74,7 @@ impl From<PreparedRequest> for crank_core::PreparedRequest {
|
||||
headers: value.headers,
|
||||
trusted_header_names: value.trusted_header_names,
|
||||
body: value.body,
|
||||
body_content_type: value.body_content_type,
|
||||
timeout_ms: value.timeout_ms,
|
||||
}
|
||||
}
|
||||
@@ -85,6 +88,7 @@ impl From<crank_core::PreparedRequest> for PreparedRequest {
|
||||
headers: value.headers,
|
||||
trusted_header_names: value.trusted_header_names,
|
||||
body: value.body,
|
||||
body_content_type: value.body_content_type,
|
||||
timeout_ms: value.timeout_ms,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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