наблюдаемость: ввести безопасный контракт метрик
CI / Rust Checks (push) Successful in 6m9s
CI / UI Checks (push) Successful in 5s
CI / Community Image Smoke (push) Successful in 1m3s
CI / Frontend E2E (push) Successful in 3m47s
CI / Deploy (push) Failing after 3s
CI / Rust Checks (pull_request) Successful in 6m15s
CI / UI Checks (pull_request) Successful in 5s
CI / Frontend E2E (pull_request) Successful in 5m17s
CI / Community Image Smoke (pull_request) Successful in 4m25s
CI / Deploy (pull_request) Skipped
CI / Rust Checks (push) Successful in 6m9s
CI / UI Checks (push) Successful in 5s
CI / Community Image Smoke (push) Successful in 1m3s
CI / Frontend E2E (push) Successful in 3m47s
CI / Deploy (push) Failing after 3s
CI / Rust Checks (pull_request) Successful in 6m15s
CI / UI Checks (pull_request) Successful in 5s
CI / Frontend E2E (pull_request) Successful in 5m17s
CI / Community Image Smoke (pull_request) Successful in 4m25s
CI / Deploy (pull_request) Skipped
This commit is contained in:
1 parent
ec2453c00f
commit
9b1a739e39
50 files changed
+3066
-433
No files matched your search
@@ -1,93 +1,107 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use axum::{http::header::CONTENT_TYPE, response::Response};
|
||||
use crank_metrics::{
|
||||
InFlightGuard, LimitStage, McpMethod, McpOutcome, McpResponseMode, record_limit_rejection,
|
||||
record_mcp_request,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
|
||||
use crate::{
|
||||
jsonrpc::{is_notification, is_response, method_name},
|
||||
transport::ResponseMode,
|
||||
};
|
||||
use crate::jsonrpc::{is_notification, is_response, method_name};
|
||||
|
||||
pub(super) struct McpRequestMetrics {
|
||||
method: &'static str,
|
||||
response_mode: &'static str,
|
||||
outcome: &'static str,
|
||||
method: McpMethod,
|
||||
response_mode: McpResponseMode,
|
||||
outcome: McpOutcome,
|
||||
}
|
||||
|
||||
impl McpRequestMetrics {
|
||||
pub(super) fn new(message: &Value) -> Self {
|
||||
pub(super) const fn invalid() -> Self {
|
||||
Self {
|
||||
method: normalized_mcp_method(message),
|
||||
response_mode: "unknown",
|
||||
outcome: "rejected",
|
||||
method: McpMethod::Invalid,
|
||||
response_mode: McpResponseMode::Unknown,
|
||||
outcome: McpOutcome::Aborted,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_response_mode(&mut self, mode: ResponseMode) -> ResponseMode {
|
||||
self.response_mode = match mode {
|
||||
ResponseMode::Json => "json",
|
||||
ResponseMode::Sse => "sse",
|
||||
};
|
||||
mode
|
||||
pub(super) fn new(message: &Value) -> Self {
|
||||
Self {
|
||||
method: normalized_mcp_method(message),
|
||||
response_mode: McpResponseMode::Unknown,
|
||||
outcome: McpOutcome::Aborted,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn complete(&mut self, status: StatusCode) {
|
||||
self.outcome = match status.as_u16() {
|
||||
200..=299 => "success",
|
||||
400..=499 => "client_error",
|
||||
500..=599 => "server_error",
|
||||
_ => "other",
|
||||
pub(super) fn complete(&mut self, response: &Response) {
|
||||
self.response_mode = response
|
||||
.headers()
|
||||
.get(CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map_or(McpResponseMode::Unknown, |content_type| {
|
||||
if content_type.starts_with("application/json") {
|
||||
McpResponseMode::Json
|
||||
} else if content_type.starts_with("text/event-stream") {
|
||||
McpResponseMode::Sse
|
||||
} else {
|
||||
McpResponseMode::Unknown
|
||||
}
|
||||
});
|
||||
self.outcome = if response.status().is_success() {
|
||||
response
|
||||
.extensions()
|
||||
.get::<McpOutcome>()
|
||||
.copied()
|
||||
.unwrap_or_else(|| McpOutcome::from_http_status(response.status().as_u16()))
|
||||
} else {
|
||||
McpOutcome::from_http_status(response.status().as_u16())
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) const fn outcome(&self) -> McpOutcome {
|
||||
self.outcome
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) const fn response_mode(&self) -> McpResponseMode {
|
||||
self.response_mode
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for McpRequestMetrics {
|
||||
fn drop(&mut self) {
|
||||
::metrics::counter!(
|
||||
"crank_mcp_requests_total",
|
||||
"method" => self.method,
|
||||
"response_mode" => self.response_mode,
|
||||
"outcome" => self.outcome
|
||||
)
|
||||
.increment(1);
|
||||
record_mcp_request(self.method, self.response_mode, self.outcome);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn normalized_mcp_method(message: &Value) -> &'static str {
|
||||
pub(super) fn normalized_mcp_method(message: &Value) -> McpMethod {
|
||||
match method_name(message) {
|
||||
Some("initialize") => "initialize",
|
||||
Some("notifications/initialized") => "initialized",
|
||||
Some("ping") => "ping",
|
||||
Some("tools/list") => "tools_list",
|
||||
Some("tools/call") => "tools_call",
|
||||
Some(_) if is_notification(message) => "notification",
|
||||
Some(_) => "unsupported",
|
||||
None if is_response(message) => "response",
|
||||
None => "invalid",
|
||||
Some("initialize") => McpMethod::Initialize,
|
||||
Some("notifications/initialized") => McpMethod::Initialized,
|
||||
Some("ping") => McpMethod::Ping,
|
||||
Some("tools/list") => McpMethod::ToolsList,
|
||||
Some("tools/call") => McpMethod::ToolsCall,
|
||||
Some(_) if is_notification(message) => McpMethod::Notification,
|
||||
Some(_) => McpMethod::Unsupported,
|
||||
None if is_response(message) => McpMethod::Response,
|
||||
None => McpMethod::Invalid,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct ActiveSessionGuard {
|
||||
pub(super) struct ActiveStreamGuard {
|
||||
_permit: OwnedSemaphorePermit,
|
||||
_inflight: InFlightGuard,
|
||||
}
|
||||
|
||||
impl ActiveSessionGuard {
|
||||
impl ActiveStreamGuard {
|
||||
pub(super) fn try_acquire(slots: &Arc<Semaphore>) -> Result<Self, ()> {
|
||||
let permit = Arc::clone(slots).try_acquire_owned().map_err(|_| {
|
||||
::metrics::counter!(
|
||||
"crank_runtime_limit_rejections_total",
|
||||
"stage" => "mcp_session"
|
||||
)
|
||||
.increment(1);
|
||||
record_limit_rejection(LimitStage::McpStream);
|
||||
})?;
|
||||
::metrics::gauge!("crank_mcp_active_sessions").increment(1.0);
|
||||
Ok(Self { _permit: permit })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ActiveSessionGuard {
|
||||
fn drop(&mut self) {
|
||||
::metrics::gauge!("crank_mcp_active_sessions").decrement(1.0);
|
||||
Ok(Self {
|
||||
_permit: permit,
|
||||
_inflight: InFlightGuard::mcp_stream(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ use std::{
|
||||
|
||||
use axum::body::to_bytes;
|
||||
use crank_core::InvocationStatus;
|
||||
use crank_metrics::{McpMethod, McpOutcome, McpResponseMode};
|
||||
use crank_observability::{
|
||||
ObservabilityConfig, OperationalIncident, RedactionLimits, ServiceIdentity,
|
||||
operational_incident_total,
|
||||
@@ -16,16 +17,20 @@ use serde_json::{Value, json};
|
||||
use tracing_subscriber::fmt::MakeWriter;
|
||||
|
||||
use super::{
|
||||
ResponseMode, metrics::normalized_mcp_method, observe_invocation_history_outcome,
|
||||
tool_error_response,
|
||||
ResponseMode,
|
||||
metrics::{McpRequestMetrics, normalized_mcp_method},
|
||||
observe_invocation_history_outcome, tool_error_response,
|
||||
};
|
||||
use crate::jsonrpc::CURRENT_PROTOCOL_VERSION;
|
||||
use crate::jsonrpc::{CURRENT_PROTOCOL_VERSION, jsonrpc_error};
|
||||
use crate::tool_error::generic_tool_error_contract;
|
||||
use crate::transport::transport_response;
|
||||
|
||||
#[tokio::test]
|
||||
async fn tool_error_response_includes_structured_context() {
|
||||
let message = json!({"jsonrpc": "2.0", "id": "req-1", "method": "tools/call"});
|
||||
let mut request_metrics = McpRequestMetrics::new(&message);
|
||||
let response = tool_error_response(
|
||||
&json!({"jsonrpc": "2.0", "id": "req-1"}),
|
||||
&message,
|
||||
ResponseMode::Json,
|
||||
CURRENT_PROTOCOL_VERSION,
|
||||
generic_tool_error_contract(
|
||||
@@ -36,6 +41,12 @@ async fn tool_error_response_includes_structured_context() {
|
||||
Some("Проверьте параметры вызова инструмента."),
|
||||
),
|
||||
);
|
||||
assert_eq!(
|
||||
response.extensions().get::<McpOutcome>(),
|
||||
Some(&McpOutcome::ToolError)
|
||||
);
|
||||
request_metrics.complete(&response);
|
||||
assert_eq!(request_metrics.outcome(), McpOutcome::ToolError);
|
||||
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let payload: Value = serde_json::from_slice(&body).unwrap();
|
||||
@@ -53,6 +64,67 @@ async fn tool_error_response_includes_structured_context() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jsonrpc_error_over_http_200_is_not_counted_as_success() {
|
||||
let message = json!({"jsonrpc": "2.0", "id": 1, "method": "unsupported"});
|
||||
let mut request_metrics = McpRequestMetrics::new(&message);
|
||||
let response = transport_response(
|
||||
axum::http::StatusCode::OK,
|
||||
jsonrpc_error(json!(1), -32601, "unsupported"),
|
||||
ResponseMode::Json,
|
||||
None,
|
||||
Some(CURRENT_PROTOCOL_VERSION),
|
||||
);
|
||||
|
||||
request_metrics.complete(&response);
|
||||
|
||||
assert_eq!(request_metrics.outcome(), McpOutcome::JsonRpcError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metric_uses_actual_json_response_when_sse_request_falls_back() {
|
||||
let message = json!({"jsonrpc": "2.0", "id": 1, "method": "unsupported"});
|
||||
let mut request_metrics = McpRequestMetrics::new(&message);
|
||||
let response = transport_response(
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
jsonrpc_error(json!(1), -32603, "internal error"),
|
||||
ResponseMode::Json,
|
||||
None,
|
||||
Some(CURRENT_PROTOCOL_VERSION),
|
||||
);
|
||||
|
||||
request_metrics.complete(&response);
|
||||
|
||||
assert_eq!(request_metrics.response_mode(), McpResponseMode::Json);
|
||||
assert_eq!(request_metrics.outcome(), McpOutcome::ServerError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_failure_takes_priority_over_jsonrpc_payload() {
|
||||
let message = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call"});
|
||||
let mut request_metrics = McpRequestMetrics::new(&message);
|
||||
let response = transport_response(
|
||||
axum::http::StatusCode::TOO_MANY_REQUESTS,
|
||||
jsonrpc_error(json!(1), -32000, "rate limited"),
|
||||
ResponseMode::Json,
|
||||
None,
|
||||
Some(CURRENT_PROTOCOL_VERSION),
|
||||
);
|
||||
|
||||
request_metrics.complete(&response);
|
||||
|
||||
assert_eq!(request_metrics.outcome(), McpOutcome::ClientError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unfinished_request_is_classified_as_aborted() {
|
||||
let message = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call"});
|
||||
let request_metrics = McpRequestMetrics::new(&message);
|
||||
|
||||
assert_eq!(request_metrics.response_mode(), McpResponseMode::Unknown);
|
||||
assert_eq!(request_metrics.outcome(), McpOutcome::Aborted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emits_bounded_history_loss_incident() {
|
||||
let writer = SharedLogWriter::default();
|
||||
@@ -96,19 +168,19 @@ fn emits_bounded_history_loss_incident() {
|
||||
fn mcp_metric_method_is_always_from_a_closed_set() {
|
||||
assert_eq!(
|
||||
normalized_mcp_method(&json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call"})),
|
||||
"tools_call"
|
||||
McpMethod::ToolsCall
|
||||
);
|
||||
assert_eq!(
|
||||
normalized_mcp_method(
|
||||
&json!({"jsonrpc": "2.0", "id": 2, "method": "customer-controlled-method"})
|
||||
),
|
||||
"unsupported"
|
||||
McpMethod::Unsupported
|
||||
);
|
||||
assert_eq!(
|
||||
normalized_mcp_method(
|
||||
&json!({"jsonrpc": "2.0", "method": "customer-controlled-notification"})
|
||||
),
|
||||
"notification"
|
||||
McpMethod::Notification
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user