feat: complete Epic 1 production foundation
This commit is contained in:
1 parent
767428436d
commit
182bde8ac0
298 files changed
+35711
-5291
No files matched your search
@@ -1,5 +1,8 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crank_core::{
|
||||
AdapterRegistry, CoordinationStateStore, ExecutionMode, InvocationSource, InvocationStatus,
|
||||
@@ -11,18 +14,15 @@ use crank_metrics::{
|
||||
ToolOutcome, record_cache_outcome, record_confirmation_outcome, record_idempotency_outcome,
|
||||
record_limit_rejection,
|
||||
};
|
||||
use crank_trace::{
|
||||
ErrorCategory, Stage, StageOutcome, set_parent_from_trace_context, trace_context_for_span,
|
||||
};
|
||||
use crank_trace::{ErrorCategory, Stage, StageOutcome, set_parent_from_trace_context};
|
||||
use serde_json::{Map, Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
use tracing::{Instrument, Span, debug, warn};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
AdapterResponse, PreparedRequest, ResolvedAuth, RuntimeError, RuntimeLimits, RuntimeOperation,
|
||||
RuntimeRequestContext,
|
||||
AdapterResponse, ExecutionAuthorization, PreparedRequest, RuntimeError,
|
||||
RuntimeExecutionRequest, RuntimeLimits, RuntimeOperation, RuntimeRequestContext,
|
||||
auth::apply_resolved_auth,
|
||||
request_preparation::adapter_prepared_request,
|
||||
response_cache::{
|
||||
@@ -41,14 +41,6 @@ pub struct RuntimeExecutor {
|
||||
metering_sink: SharedMeteringSink,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RuntimeExecutionRequest<'a> {
|
||||
pub operation: &'a RuntimeOperation,
|
||||
pub input: &'a Value,
|
||||
pub resolved_auth: Option<&'a ResolvedAuth>,
|
||||
pub request_context: Option<&'a RuntimeRequestContext>,
|
||||
}
|
||||
|
||||
struct IdempotencyCancellationGuard {
|
||||
cleanup: Option<IdempotencyCancellationCleanup>,
|
||||
runtime: tokio::runtime::Handle,
|
||||
@@ -58,6 +50,7 @@ struct IdempotencyCancellationCleanup {
|
||||
store: Arc<dyn CoordinationStateStore>,
|
||||
operation: RuntimeOperation,
|
||||
reservation: crate::idempotency::IdempotencyReservation,
|
||||
dispatch_started: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl IdempotencyCancellationGuard {
|
||||
@@ -65,12 +58,14 @@ impl IdempotencyCancellationGuard {
|
||||
store: Arc<dyn CoordinationStateStore>,
|
||||
operation: RuntimeOperation,
|
||||
reservation: crate::idempotency::IdempotencyReservation,
|
||||
dispatch_started: Arc<AtomicBool>,
|
||||
) -> Self {
|
||||
Self {
|
||||
cleanup: Some(IdempotencyCancellationCleanup {
|
||||
store,
|
||||
operation,
|
||||
reservation,
|
||||
dispatch_started,
|
||||
}),
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
}
|
||||
@@ -87,14 +82,25 @@ impl Drop for IdempotencyCancellationGuard {
|
||||
return;
|
||||
};
|
||||
self.runtime.spawn(async move {
|
||||
let result = crate::idempotency::mark_outcome_unknown(
|
||||
cleanup.store.as_ref(),
|
||||
&cleanup.operation,
|
||||
&cleanup.reservation,
|
||||
)
|
||||
.await;
|
||||
let may_have_dispatched = cleanup.dispatch_started.load(Ordering::Acquire);
|
||||
let result = if may_have_dispatched {
|
||||
crate::idempotency::mark_outcome_unknown(
|
||||
cleanup.store.as_ref(),
|
||||
&cleanup.operation,
|
||||
&cleanup.reservation,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
crate::idempotency::release(
|
||||
cleanup.store.as_ref(),
|
||||
&cleanup.operation,
|
||||
&cleanup.reservation,
|
||||
)
|
||||
.await
|
||||
};
|
||||
record_idempotency_outcome(match &result {
|
||||
Ok(()) => IdempotencyOutcome::OutcomeUnknown,
|
||||
Ok(()) if may_have_dispatched => IdempotencyOutcome::OutcomeUnknown,
|
||||
Ok(()) => IdempotencyOutcome::Completed,
|
||||
Err(error) => idempotency_error_outcome(error),
|
||||
});
|
||||
if result.is_err() {
|
||||
@@ -108,40 +114,6 @@ impl Drop for IdempotencyCancellationGuard {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> RuntimeExecutionRequest<'a> {
|
||||
pub fn new(operation: &'a RuntimeOperation, input: &'a Value) -> Self {
|
||||
Self {
|
||||
operation,
|
||||
input,
|
||||
resolved_auth: None,
|
||||
request_context: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_auth(mut self, resolved_auth: &'a ResolvedAuth) -> Self {
|
||||
self.resolved_auth = Some(resolved_auth);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_optional_auth(mut self, resolved_auth: Option<&'a ResolvedAuth>) -> Self {
|
||||
self.resolved_auth = resolved_auth;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_context(mut self, request_context: &'a RuntimeRequestContext) -> Self {
|
||||
self.request_context = Some(request_context);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_optional_context(
|
||||
mut self,
|
||||
request_context: Option<&'a RuntimeRequestContext>,
|
||||
) -> Self {
|
||||
self.request_context = request_context;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RuntimeExecutor {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
@@ -192,106 +164,76 @@ impl RuntimeExecutor {
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn execute(
|
||||
&self,
|
||||
operation: &RuntimeOperation,
|
||||
input: &Value,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
self.execute_request(RuntimeExecutionRequest::new(operation, input))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn execute_with_auth(
|
||||
&self,
|
||||
operation: &RuntimeOperation,
|
||||
input: &Value,
|
||||
resolved_auth: Option<&ResolvedAuth>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
self.execute_request(
|
||||
RuntimeExecutionRequest::new(operation, input).with_optional_auth(resolved_auth),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn execute_with_context(
|
||||
&self,
|
||||
operation: &RuntimeOperation,
|
||||
input: &Value,
|
||||
request_context: Option<&RuntimeRequestContext>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
self.execute_request(
|
||||
RuntimeExecutionRequest::new(operation, input).with_optional_context(request_context),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn execute_with_auth_and_context(
|
||||
&self,
|
||||
operation: &RuntimeOperation,
|
||||
input: &Value,
|
||||
resolved_auth: Option<&ResolvedAuth>,
|
||||
request_context: Option<&RuntimeRequestContext>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
self.execute_request(
|
||||
RuntimeExecutionRequest::new(operation, input)
|
||||
.with_optional_auth(resolved_auth)
|
||||
.with_optional_context(request_context),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn execute_request(
|
||||
pub(crate) async fn execute_request(
|
||||
&self,
|
||||
request: RuntimeExecutionRequest<'_>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let runtime_span = Stage::RuntimeExecute.span();
|
||||
if let Some(context) = request.request_context {
|
||||
set_parent_from_trace_context(&runtime_span, &context.trace_context);
|
||||
}
|
||||
let generated_context = request.request_context.is_none().then(|| {
|
||||
RuntimeRequestContext::new(
|
||||
crank_core::RequestId::generate(),
|
||||
trace_context_for_span(&runtime_span)
|
||||
.unwrap_or_else(crank_core::TraceContext::generate),
|
||||
)
|
||||
});
|
||||
let request_context = request.request_context.or(generated_context.as_ref());
|
||||
log_runtime_event("unary.execute", request.operation, request_context);
|
||||
let started_at = Instant::now();
|
||||
let invocation_metrics = ToolInvocationMetrics::start_with_exemplar(
|
||||
metric_invocation_source(request_context),
|
||||
request_context.and_then(|context| {
|
||||
context
|
||||
.trace_context
|
||||
.is_sampled()
|
||||
.then(|| {
|
||||
crank_metrics::ExemplarTraceId::parse(
|
||||
&context.trace_context.trace_id().to_string(),
|
||||
)
|
||||
})
|
||||
.flatten()
|
||||
}),
|
||||
) -> Result<(Value, Value), RuntimeError> {
|
||||
let operation = request.operation();
|
||||
let input = request.input();
|
||||
let request_context = request.request_context();
|
||||
debug_assert_eq!(request.authorization(), ExecutionAuthorization::Authorized);
|
||||
debug_assert_eq!(
|
||||
request_context
|
||||
.metering_context()
|
||||
.map(|value| &value.workspace_id),
|
||||
Some(request.workspace_id())
|
||||
);
|
||||
let result = async {
|
||||
let _permit = self.acquire_unary_permit(request.operation)?;
|
||||
debug_assert_eq!(
|
||||
request_context
|
||||
.metering_context()
|
||||
.and_then(|value| value.agent_id.as_ref()),
|
||||
request.agent_id()
|
||||
);
|
||||
let operation_may_mutate = operation_may_mutate(operation);
|
||||
let runtime_span = Stage::RuntimeExecute.span();
|
||||
set_parent_from_trace_context(&runtime_span, &request_context.trace_context);
|
||||
log_runtime_event("unary.execute", operation, Some(request_context));
|
||||
let started_at = Instant::now();
|
||||
let dispatch_started = Arc::new(AtomicBool::new(false));
|
||||
let invocation_metrics = ToolInvocationMetrics::start_with_exemplar(
|
||||
metric_invocation_source(Some(request_context)),
|
||||
request_context
|
||||
.trace_context
|
||||
.is_sampled()
|
||||
.then(|| {
|
||||
crank_metrics::ExemplarTraceId::parse(
|
||||
&request_context.trace_context.trace_id().to_string(),
|
||||
)
|
||||
})
|
||||
.flatten(),
|
||||
);
|
||||
let execution = async {
|
||||
let _permit = self.acquire_unary_permit(operation)?;
|
||||
let _inflight = InFlightGuard::runtime();
|
||||
let mapping_span = Stage::RuntimeArgumentsMap.span();
|
||||
let prepared_request =
|
||||
mapping_span.in_scope(|| self.prepare_request(request.operation, request.input));
|
||||
let prepared_request = mapping_span.in_scope(|| self.prepare_request(operation, input));
|
||||
record_runtime_result(&mapping_span, &prepared_request);
|
||||
drop(mapping_span);
|
||||
let prepared_request = prepared_request?;
|
||||
let prepared_request = apply_resolved_auth(prepared_request, request.resolved_auth);
|
||||
self.execute_prepared(
|
||||
request.operation,
|
||||
request.input,
|
||||
prepared_request,
|
||||
request_context,
|
||||
)
|
||||
.await
|
||||
}
|
||||
.instrument(runtime_span.clone())
|
||||
.await;
|
||||
let request_preview = sanitized_request_preview(&prepared_request);
|
||||
let prepared_request = apply_resolved_auth(prepared_request, request.resolved_auth());
|
||||
let output = self
|
||||
.execute_prepared(
|
||||
operation,
|
||||
input,
|
||||
prepared_request,
|
||||
Some(request_context),
|
||||
Arc::clone(&dispatch_started),
|
||||
)
|
||||
.await?;
|
||||
Ok((output, request_preview))
|
||||
};
|
||||
let result = tokio::time::timeout_at(
|
||||
request.deadline().into(),
|
||||
execution.instrument(runtime_span.clone()),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|_| {
|
||||
Err(RuntimeError::ExecutionDeadlineElapsed {
|
||||
may_have_dispatched: operation_may_mutate
|
||||
&& dispatch_started.load(Ordering::Acquire),
|
||||
})
|
||||
});
|
||||
record_runtime_result(&runtime_span, &result);
|
||||
drop(runtime_span);
|
||||
let (outcome, error_kind) = match &result {
|
||||
@@ -299,23 +241,58 @@ impl RuntimeExecutor {
|
||||
Err(error) => (ToolOutcome::Error, runtime_error_kind(error)),
|
||||
};
|
||||
invocation_metrics.complete(outcome, error_kind);
|
||||
self.record_metering(request.operation, request_context, &result, started_at)
|
||||
self.record_metering(operation, Some(request_context), &result, started_at)
|
||||
.await;
|
||||
result
|
||||
}
|
||||
|
||||
pub fn prepare_request(
|
||||
pub async fn execute_outcome(
|
||||
&self,
|
||||
request: RuntimeExecutionRequest<'_>,
|
||||
) -> Result<crank_core::ExecutionSuccess, crank_core::ExecutionFailure> {
|
||||
let operation_id = request.operation().operation_id.clone();
|
||||
let operation_version = request.operation().operation_version;
|
||||
let operation = request.operation().clone();
|
||||
let origin = request.origin();
|
||||
let correlation = crank_core::CorrelationContext::new(
|
||||
request.request_context().request_id.clone(),
|
||||
request.request_context().trace_context.clone(),
|
||||
);
|
||||
match self.execute_request(request).await {
|
||||
Ok((output, request_preview)) => Ok(crank_core::ExecutionSuccess {
|
||||
operation_id,
|
||||
operation_version,
|
||||
origin,
|
||||
correlation,
|
||||
request_preview,
|
||||
output,
|
||||
}),
|
||||
Err(error) => Err(crate::normalize_runtime_error_for_operation(
|
||||
&error,
|
||||
&correlation,
|
||||
&operation,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_request(
|
||||
&self,
|
||||
operation: &RuntimeOperation,
|
||||
input: &Value,
|
||||
) -> Result<PreparedRequest, RuntimeError> {
|
||||
operation.input_schema.validate_shape(input)?;
|
||||
operation
|
||||
.input_schema
|
||||
.validate_shape(input)
|
||||
.map_err(RuntimeError::InputSchema)?;
|
||||
|
||||
if operation.input_mapping.is_empty() {
|
||||
return Ok(PreparedRequest::default());
|
||||
}
|
||||
|
||||
let mapped_input = operation.input_mapping.apply(&json!({ "mcp": input }))?;
|
||||
let mapped_input = operation
|
||||
.input_mapping
|
||||
.apply(&json!({ "mcp": input }))
|
||||
.map_err(RuntimeError::InputMapping)?;
|
||||
PreparedRequest::from_mapping_output(&mapped_input)
|
||||
}
|
||||
|
||||
@@ -325,6 +302,7 @@ impl RuntimeExecutor {
|
||||
input: &Value,
|
||||
prepared_request: PreparedRequest,
|
||||
request_context: Option<&RuntimeRequestContext>,
|
||||
dispatch_started: Arc<AtomicBool>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let mut prepared_request = prepared_request;
|
||||
let idempotency_applicable = crate::idempotency::policy(operation).is_some();
|
||||
@@ -418,6 +396,7 @@ impl RuntimeExecutor {
|
||||
Arc::clone(store),
|
||||
operation.clone(),
|
||||
reservation.clone(),
|
||||
Arc::clone(&dispatch_started),
|
||||
)
|
||||
})
|
||||
} else {
|
||||
@@ -431,7 +410,16 @@ impl RuntimeExecutor {
|
||||
Some(response) => Ok(response),
|
||||
None => {
|
||||
let adapter_response = self
|
||||
.execute_adapter(operation, prepared_request.clone(), request_context)
|
||||
.execute_adapter_with_retry(
|
||||
operation,
|
||||
&prepared_request,
|
||||
request_context,
|
||||
Arc::clone(&dispatch_started),
|
||||
crate::idempotency::verified_retry_key(
|
||||
operation,
|
||||
idempotency_key.as_deref(),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
if let Ok(response) = &adapter_response {
|
||||
self.store_cached_adapter_response(
|
||||
@@ -452,13 +440,20 @@ impl RuntimeExecutor {
|
||||
&& let Some(store) = self.coordination_store.as_deref()
|
||||
{
|
||||
let idempotency_span = Stage::RuntimeIdempotency.span();
|
||||
let cleanup_result =
|
||||
let may_have_dispatched = runtime_error_may_have_dispatched(&error);
|
||||
let cleanup_result = if may_have_dispatched {
|
||||
crate::idempotency::mark_outcome_unknown(store, operation, reservation)
|
||||
.instrument(idempotency_span.clone())
|
||||
.await;
|
||||
.await
|
||||
} else {
|
||||
crate::idempotency::release(store, operation, reservation)
|
||||
.instrument(idempotency_span.clone())
|
||||
.await
|
||||
};
|
||||
record_runtime_result(&idempotency_span, &cleanup_result);
|
||||
record_idempotency_outcome(match &cleanup_result {
|
||||
Ok(()) => IdempotencyOutcome::OutcomeUnknown,
|
||||
Ok(()) if may_have_dispatched => IdempotencyOutcome::OutcomeUnknown,
|
||||
Ok(()) => IdempotencyOutcome::Completed,
|
||||
Err(error) => idempotency_error_outcome(error),
|
||||
});
|
||||
if let Some(guard) = &mut cancellation_guard {
|
||||
@@ -485,7 +480,11 @@ impl RuntimeExecutor {
|
||||
guard.disarm();
|
||||
}
|
||||
drop(idempotency_span);
|
||||
completion_result?;
|
||||
if completion_result.is_err() {
|
||||
return Err(RuntimeError::IdempotencyCompletionUnknown {
|
||||
operation_id: operation.operation_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
transform_response(operation, &adapter_response)
|
||||
}
|
||||
@@ -524,6 +523,7 @@ impl RuntimeExecutor {
|
||||
operation: &RuntimeOperation,
|
||||
prepared_request: PreparedRequest,
|
||||
request_context: Option<&RuntimeRequestContext>,
|
||||
dispatch_started: Arc<AtomicBool>,
|
||||
) -> Result<AdapterResponse, RuntimeError> {
|
||||
log_runtime_event("adapter.dispatch", operation, request_context);
|
||||
let adapter = self.adapter_for(operation)?;
|
||||
@@ -539,8 +539,8 @@ impl RuntimeExecutor {
|
||||
&prepared_request,
|
||||
operation.execution_config.timeout_ms,
|
||||
);
|
||||
let adapter_context = adapter_request_context(request_context);
|
||||
|
||||
let adapter_context =
|
||||
adapter_request_context(request_context, Arc::clone(&dispatch_started))?;
|
||||
adapter
|
||||
.invoke_unary(
|
||||
&operation.target,
|
||||
@@ -552,6 +552,39 @@ impl RuntimeExecutor {
|
||||
.map_err(|error| map_protocol_adapter_error(operation, error))
|
||||
}
|
||||
|
||||
async fn execute_adapter_with_retry(
|
||||
&self,
|
||||
operation: &RuntimeOperation,
|
||||
prepared_request: &PreparedRequest,
|
||||
request_context: Option<&RuntimeRequestContext>,
|
||||
dispatch_started: Arc<AtomicBool>,
|
||||
verified_idempotency: bool,
|
||||
) -> Result<AdapterResponse, RuntimeError> {
|
||||
let max_attempts = retry_attempts(operation);
|
||||
let mut attempt = 1;
|
||||
loop {
|
||||
let result = self
|
||||
.execute_adapter(
|
||||
operation,
|
||||
prepared_request.clone(),
|
||||
request_context,
|
||||
Arc::clone(&dispatch_started),
|
||||
)
|
||||
.await;
|
||||
match result {
|
||||
Ok(response) => return Ok(response),
|
||||
Err(error)
|
||||
if attempt < max_attempts
|
||||
&& retry_is_allowed(operation, &error, verified_idempotency) =>
|
||||
{
|
||||
attempt += 1;
|
||||
tokio::time::sleep(retry_backoff(attempt)).await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn acquire_unary_permit(
|
||||
&self,
|
||||
_operation: &RuntimeOperation,
|
||||
@@ -654,12 +687,98 @@ impl RuntimeExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitized_request_preview(prepared: &PreparedRequest) -> Value {
|
||||
json!({
|
||||
"path_parameter_count": prepared.path_params.len(),
|
||||
"query_parameter_count": prepared.query_params.len(),
|
||||
"header_count": prepared.headers.len(),
|
||||
"body_configured": prepared.body.is_some(),
|
||||
})
|
||||
}
|
||||
|
||||
fn runtime_error_may_have_dispatched(error: &RuntimeError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
RuntimeError::ProtocolAdapter(
|
||||
crank_core::ProtocolAdapterError::Transport {
|
||||
dispatch: crank_core::DispatchEvidence::MayHaveDispatched,
|
||||
} | crank_core::ProtocolAdapterError::Timeout {
|
||||
dispatch: crank_core::DispatchEvidence::MayHaveDispatched,
|
||||
} | crank_core::ProtocolAdapterError::ResponseTooLarge {
|
||||
dispatch: crank_core::DispatchEvidence::MayHaveDispatched,
|
||||
} | crank_core::ProtocolAdapterError::UnexpectedStatus {
|
||||
dispatch: crank_core::DispatchEvidence::MayHaveDispatched,
|
||||
..
|
||||
} | crank_core::ProtocolAdapterError::InvalidResponse {
|
||||
dispatch: crank_core::DispatchEvidence::MayHaveDispatched,
|
||||
},
|
||||
) | RuntimeError::ExecutionDeadlineElapsed {
|
||||
may_have_dispatched: true,
|
||||
} | RuntimeError::IdempotencyCompletionUnknown { .. }
|
||||
)
|
||||
}
|
||||
|
||||
fn retry_attempts(operation: &RuntimeOperation) -> u32 {
|
||||
operation
|
||||
.execution_config
|
||||
.retry_policy
|
||||
.as_ref()
|
||||
.map_or(1, |policy| policy.max_attempts.clamp(1, 5))
|
||||
}
|
||||
|
||||
fn retry_backoff(attempt: u32) -> Duration {
|
||||
Duration::from_millis(u64::from(attempt.saturating_sub(1)).min(4))
|
||||
}
|
||||
|
||||
fn retry_is_allowed(
|
||||
operation: &RuntimeOperation,
|
||||
error: &RuntimeError,
|
||||
verified_idempotency: bool,
|
||||
) -> bool {
|
||||
let is_read = matches!(
|
||||
&operation.target,
|
||||
crank_core::Target::Rest(target) if target.method == crank_core::HttpMethod::Get
|
||||
);
|
||||
let safe_write = operation_may_mutate(operation) && verified_idempotency;
|
||||
if !(is_read || safe_write) {
|
||||
return false;
|
||||
}
|
||||
match error {
|
||||
RuntimeError::ProtocolAdapter(
|
||||
crank_core::ProtocolAdapterError::Transport { .. }
|
||||
| crank_core::ProtocolAdapterError::Timeout { .. },
|
||||
) => true,
|
||||
RuntimeError::ProtocolAdapter(crank_core::ProtocolAdapterError::UnexpectedStatus {
|
||||
status,
|
||||
..
|
||||
}) => matches!(status, 408 | 429 | 500..=599),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn operation_may_mutate(operation: &RuntimeOperation) -> bool {
|
||||
matches!(
|
||||
&operation.target,
|
||||
crank_core::Target::Rest(target)
|
||||
if matches!(
|
||||
target.method,
|
||||
crank_core::HttpMethod::Post
|
||||
| crank_core::HttpMethod::Put
|
||||
| crank_core::HttpMethod::Patch
|
||||
| crank_core::HttpMethod::Delete
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
fn adapter_request_context(
|
||||
request_context: Option<&RuntimeRequestContext>,
|
||||
) -> crank_core::RuntimeRequestContext {
|
||||
request_context.map(Into::into).unwrap_or_else(|| {
|
||||
crank_core::RuntimeRequestContext::from_request_id(Uuid::now_v7().to_string())
|
||||
})
|
||||
dispatch_started: Arc<AtomicBool>,
|
||||
) -> Result<crank_core::RuntimeRequestContext, RuntimeError> {
|
||||
request_context
|
||||
.map(|context| {
|
||||
crank_core::RuntimeRequestContext::from(context).with_dispatch_started(dispatch_started)
|
||||
})
|
||||
.ok_or(RuntimeError::InvalidExecutionRequest)
|
||||
}
|
||||
|
||||
fn map_protocol_adapter_error(
|
||||
@@ -673,9 +792,7 @@ fn map_protocol_adapter_error(
|
||||
mode,
|
||||
}
|
||||
}
|
||||
crank_core::ProtocolAdapterError::Message(message) => RuntimeError::ProtocolAdapter(
|
||||
format!("operation {}: {message}", operation.operation_id),
|
||||
),
|
||||
error => RuntimeError::ProtocolAdapter(error),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -696,14 +813,17 @@ fn finalize_output(
|
||||
operation: &RuntimeOperation,
|
||||
response: &AdapterResponse,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let mapped = operation.output_mapping.apply(&json!({
|
||||
"response": {
|
||||
"body": response.body,
|
||||
"data": response.data,
|
||||
"headers": response.headers,
|
||||
"status": response.status_code
|
||||
}
|
||||
}))?;
|
||||
let mapped = operation
|
||||
.output_mapping
|
||||
.apply(&json!({
|
||||
"response": {
|
||||
"body": response.body,
|
||||
"data": response.data,
|
||||
"headers": response.headers,
|
||||
"status": response.status_code
|
||||
}
|
||||
}))
|
||||
.map_err(RuntimeError::OutputMapping)?;
|
||||
|
||||
Ok(mapped
|
||||
.get("output")
|
||||
@@ -718,7 +838,10 @@ fn transform_response(
|
||||
let span = Stage::RuntimeResponseTransform.span();
|
||||
let result = span.in_scope(|| {
|
||||
let finalized_output = finalize_output(operation, response)?;
|
||||
operation.output_schema.validate_shape(&finalized_output)?;
|
||||
operation
|
||||
.output_schema
|
||||
.validate_shape(&finalized_output)
|
||||
.map_err(RuntimeError::OutputSchema)?;
|
||||
Ok(finalized_output)
|
||||
});
|
||||
match &result {
|
||||
@@ -743,12 +866,16 @@ fn record_runtime_result<T>(span: &Span, result: &Result<T, RuntimeError>) {
|
||||
|
||||
fn runtime_error_category(error: &RuntimeError) -> ErrorCategory {
|
||||
match error {
|
||||
RuntimeError::Schema(_) => ErrorCategory::Schema,
|
||||
RuntimeError::Mapping(_) | RuntimeError::InvalidPreparedRequest { .. } => {
|
||||
ErrorCategory::Mapping
|
||||
RuntimeError::InvalidExecutionRequest => ErrorCategory::Configuration,
|
||||
RuntimeError::ExecutionDeadlineElapsed { .. } => ErrorCategory::Upstream,
|
||||
RuntimeError::Schema(_) | RuntimeError::InputSchema(_) | RuntimeError::OutputSchema(_) => {
|
||||
ErrorCategory::Schema
|
||||
}
|
||||
RuntimeError::RestAdapter(_)
|
||||
| RuntimeError::ProtocolAdapter(_)
|
||||
RuntimeError::Mapping(_)
|
||||
| RuntimeError::InputMapping(_)
|
||||
| RuntimeError::OutputMapping(_)
|
||||
| RuntimeError::InvalidPreparedRequest { .. } => ErrorCategory::Mapping,
|
||||
RuntimeError::ProtocolAdapter(_)
|
||||
| RuntimeError::UnsupportedProtocol { .. }
|
||||
| RuntimeError::UnsupportedExecutionMode { .. } => ErrorCategory::Upstream,
|
||||
RuntimeError::ConcurrencyLimitExceeded { .. } => ErrorCategory::Concurrency,
|
||||
@@ -758,8 +885,11 @@ fn runtime_error_category(error: &RuntimeError) -> ErrorCategory {
|
||||
RuntimeError::IdempotencyStoreUnavailable { .. }
|
||||
| RuntimeError::IdempotencyInProgress { .. }
|
||||
| RuntimeError::IdempotencyConflict { .. }
|
||||
| RuntimeError::IdempotencyOutcomeUnknown { .. } => ErrorCategory::Idempotency,
|
||||
| RuntimeError::IdempotencyOutcomeUnknown { .. }
|
||||
| RuntimeError::IdempotencyCompletionUnknown { .. } => ErrorCategory::Idempotency,
|
||||
RuntimeError::MissingAuthProfile { .. }
|
||||
| RuntimeError::InvalidAuthProfileConfig { .. }
|
||||
| RuntimeError::AuthorizationStoreUnavailable
|
||||
| RuntimeError::MissingSecret { .. }
|
||||
| RuntimeError::MissingSecretVersion { .. }
|
||||
| RuntimeError::InvalidAuthSecretValue { .. }
|
||||
@@ -793,9 +923,14 @@ fn metric_invocation_source(
|
||||
|
||||
fn runtime_error_kind(error: &RuntimeError) -> ToolErrorKind {
|
||||
match error {
|
||||
RuntimeError::Schema(_) => ToolErrorKind::Schema,
|
||||
RuntimeError::Mapping(_) => ToolErrorKind::Mapping,
|
||||
RuntimeError::RestAdapter(_) => ToolErrorKind::RestAdapter,
|
||||
RuntimeError::InvalidExecutionRequest => ToolErrorKind::InvalidPreparedRequest,
|
||||
RuntimeError::ExecutionDeadlineElapsed { .. } => ToolErrorKind::RestAdapter,
|
||||
RuntimeError::Schema(_) | RuntimeError::InputSchema(_) | RuntimeError::OutputSchema(_) => {
|
||||
ToolErrorKind::Schema
|
||||
}
|
||||
RuntimeError::Mapping(_)
|
||||
| RuntimeError::InputMapping(_)
|
||||
| RuntimeError::OutputMapping(_) => ToolErrorKind::Mapping,
|
||||
RuntimeError::ProtocolAdapter(_) => ToolErrorKind::ProtocolAdapter,
|
||||
RuntimeError::UnsupportedProtocol { .. } => ToolErrorKind::UnsupportedProtocol,
|
||||
RuntimeError::UnsupportedExecutionMode { .. } => ToolErrorKind::UnsupportedExecutionMode,
|
||||
@@ -808,7 +943,12 @@ fn runtime_error_kind(error: &RuntimeError) -> ToolErrorKind {
|
||||
RuntimeError::IdempotencyInProgress { .. } => ToolErrorKind::IdempotencyInProgress,
|
||||
RuntimeError::IdempotencyConflict { .. } => ToolErrorKind::IdempotencyConflict,
|
||||
RuntimeError::IdempotencyOutcomeUnknown { .. } => ToolErrorKind::IdempotencyOutcomeUnknown,
|
||||
RuntimeError::IdempotencyCompletionUnknown { .. } => {
|
||||
ToolErrorKind::IdempotencyOutcomeUnknown
|
||||
}
|
||||
RuntimeError::MissingAuthProfile { .. } => ToolErrorKind::MissingAuthProfile,
|
||||
RuntimeError::InvalidAuthProfileConfig { .. } => ToolErrorKind::InvalidAuthSecret,
|
||||
RuntimeError::AuthorizationStoreUnavailable => ToolErrorKind::IdempotencyStore,
|
||||
RuntimeError::MissingSecret { .. } => ToolErrorKind::MissingSecret,
|
||||
RuntimeError::MissingSecretVersion { .. } => ToolErrorKind::MissingSecretVersion,
|
||||
RuntimeError::InvalidAuthSecretValue { .. } => ToolErrorKind::InvalidAuthSecret,
|
||||
@@ -820,7 +960,8 @@ fn idempotency_error_outcome(error: &RuntimeError) -> IdempotencyOutcome {
|
||||
match error {
|
||||
RuntimeError::IdempotencyConflict { .. } => IdempotencyOutcome::Conflict,
|
||||
RuntimeError::IdempotencyInProgress { .. } => IdempotencyOutcome::InProgress,
|
||||
RuntimeError::IdempotencyOutcomeUnknown { .. } => IdempotencyOutcome::OutcomeUnknown,
|
||||
RuntimeError::IdempotencyOutcomeUnknown { .. }
|
||||
| RuntimeError::IdempotencyCompletionUnknown { .. } => IdempotencyOutcome::OutcomeUnknown,
|
||||
RuntimeError::IdempotencyStoreUnavailable { .. } => IdempotencyOutcome::StoreUnavailable,
|
||||
_ => IdempotencyOutcome::Error,
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user