наблюдаемость: ввести безопасный контракт метрик
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:
bsodfather committed 2026-07-31 05:04:08 +03:00
1 parent ec2453c00f
commit 9b1a739e39
50 files changed
+3066 -433

No files matched your search

+70 -56
View File
@@ -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(),
})
}
}