[skip ci] wip: preserve Hermes crank development checkpoint
Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
This commit is contained in:
1 parent
1b6db09bd1
commit
75fe5a123c
357 files changed
+118831
-5113
No files matched your search
@@ -24,6 +24,9 @@ use reqwest::{
|
||||
use tracing::{Instrument, Span};
|
||||
use tracing_opentelemetry::OpenTelemetrySpanExt;
|
||||
|
||||
mod path_params;
|
||||
use path_params::substitute_path_params;
|
||||
|
||||
use crate::{
|
||||
ExternalReferenceFetchError, RestAdapterError, RestRequest, RestResponse,
|
||||
body::{apply_body, apply_legacy_json_body, selected_request_content_type},
|
||||
@@ -789,7 +792,7 @@ fn build_url(target: &RestTarget, request: &RestRequest) -> Result<reqwest::Url,
|
||||
reqwest::Url::parse(&target.base_url).map_err(|_| RestAdapterError::InvalidBaseUrl {
|
||||
url: "url".to_owned(),
|
||||
})?;
|
||||
let path = substitute_path_params(&target.path_template, &request.path_params);
|
||||
let path = substitute_path_params(&target.path_template, &request.path_params)?;
|
||||
let mut url = if target.request_contract.is_some() || !target.response_contract.is_empty() {
|
||||
let base_path = base_url.path().trim_end_matches('/');
|
||||
let target_path = path.trim_start_matches('/');
|
||||
@@ -821,16 +824,6 @@ fn build_url(target: &RestTarget, request: &RestRequest) -> Result<reqwest::Url,
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
fn substitute_path_params(path_template: &str, path_params: &BTreeMap<String, String>) -> String {
|
||||
let mut rendered = path_template.to_owned();
|
||||
|
||||
for (key, value) in path_params {
|
||||
rendered = rendered.replace(&format!("{{{key}}}"), value);
|
||||
}
|
||||
|
||||
rendered
|
||||
}
|
||||
|
||||
fn build_headers(
|
||||
target: &RestTarget,
|
||||
request: &RestRequest,
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(super) fn substitute_path_params(
|
||||
path_template: &str,
|
||||
path_params: &BTreeMap<String, String>,
|
||||
) -> Result<String, crate::RestAdapterError> {
|
||||
let mut rendered = path_template.to_owned();
|
||||
for (key, value) in path_params {
|
||||
let placeholder = format!("{{{key}}}");
|
||||
if path_template.contains(&placeholder) && matches!(value.as_str(), "." | "..") {
|
||||
return Err(crate::RestAdapterError::InvalidPathParameter { key: key.clone() });
|
||||
}
|
||||
rendered = rendered.replace(&placeholder, &encode_path_segment(value));
|
||||
}
|
||||
Ok(rendered)
|
||||
}
|
||||
|
||||
fn encode_path_segment(value: &str) -> String {
|
||||
use std::fmt::Write as _;
|
||||
let mut encoded = String::with_capacity(value.len());
|
||||
for byte in value.bytes() {
|
||||
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
|
||||
encoded.push(char::from(byte));
|
||||
} else {
|
||||
let _ = write!(encoded, "%{byte:02X}");
|
||||
}
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::substitute_path_params;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn path_parameters_are_percent_encoded_as_one_segment() {
|
||||
let path = substitute_path_params(
|
||||
"/orders/{order_id}",
|
||||
&BTreeMap::from([("order_id".to_owned(), "a/b?c#d% space".to_owned())]),
|
||||
);
|
||||
assert_eq!(path.unwrap(), "/orders/a%2Fb%3Fc%23d%25%20space");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_segments_are_rejected_before_url_normalization() {
|
||||
for value in [".", ".."] {
|
||||
let error = substitute_path_params(
|
||||
"/orders/{order_id}",
|
||||
&BTreeMap::from([("order_id".to_owned(), value.to_owned())]),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
crate::RestAdapterError::InvalidPathParameter { key } if key == "order_id"
|
||||
));
|
||||
}
|
||||
|
||||
let path = substitute_path_params(
|
||||
"/orders/{order_id}",
|
||||
&BTreeMap::from([("order_id".to_owned(), "order.1".to_owned())]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(path, "/orders/order.1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_url_builders_reject_dot_segments_and_keep_valid_values() {
|
||||
use super::super::build_url;
|
||||
use crank_core::{HttpMethod, RestResponseDescriptor, RestTarget};
|
||||
|
||||
for typed in [false, true] {
|
||||
let target = RestTarget {
|
||||
base_url: "http://127.0.0.1:8080/api".to_owned(),
|
||||
method: HttpMethod::Get,
|
||||
path_template: "/orders/{order_id}".to_owned(),
|
||||
static_headers: BTreeMap::new(),
|
||||
request_contract: None,
|
||||
response_contract: if typed {
|
||||
vec![RestResponseDescriptor {
|
||||
status_code: 200,
|
||||
media_type: Some("application/json".to_owned()),
|
||||
schema_variant: 0,
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
multipart_field_mime_types: BTreeMap::new(),
|
||||
};
|
||||
for value in [".", ".."] {
|
||||
let request = crate::RestRequest {
|
||||
path_params: BTreeMap::from([("order_id".to_owned(), value.to_owned())]),
|
||||
..crate::RestRequest::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
build_url(&target, &request),
|
||||
Err(crate::RestAdapterError::InvalidPathParameter { key }) if key == "order_id"
|
||||
));
|
||||
}
|
||||
let request = crate::RestRequest {
|
||||
path_params: BTreeMap::from([("order_id".to_owned(), "order-1".to_owned())]),
|
||||
..crate::RestRequest::default()
|
||||
};
|
||||
let url = build_url(&target, &request).unwrap();
|
||||
let reserved = crate::RestRequest {
|
||||
path_params: BTreeMap::from([("order_id".to_owned(), "a/b?c#d% space".to_owned())]),
|
||||
..crate::RestRequest::default()
|
||||
};
|
||||
let reserved_url = build_url(&target, &reserved).unwrap();
|
||||
assert!(
|
||||
reserved_url
|
||||
.path()
|
||||
.ends_with("/orders/a%2Fb%3Fc%23d%25%20space")
|
||||
);
|
||||
assert_eq!(
|
||||
url.path(),
|
||||
if typed {
|
||||
"/api/orders/order-1"
|
||||
} else {
|
||||
"/orders/order-1"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -176,6 +176,8 @@ impl ArtifactStore {
|
||||
/// Reads a blob only after validating its inode properties, bounded length,
|
||||
/// and complete SHA-256 digest.
|
||||
pub fn read(&self, artifact_ref: &ArtifactRef) -> Result<Vec<u8>, ArtifactError> {
|
||||
#[cfg(debug_assertions)]
|
||||
crate::test_support::record_artifact_read();
|
||||
let root = self.root()?;
|
||||
let _lock = RootLock::shared(root)?;
|
||||
ensure_root_unchanged(root)?;
|
||||
|
||||
@@ -10,6 +10,21 @@ use std::{
|
||||
};
|
||||
|
||||
static TRAVERSAL_CALLS: AtomicUsize = AtomicUsize::new(0);
|
||||
/// Number of `ArtifactStore::read` attempts observed in this process (Story 3.8 AC03: an
|
||||
/// unauthorized/denied Resource read must not touch artifact bytes).
|
||||
static ARTIFACT_READS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
pub fn reset_artifact_reads() {
|
||||
ARTIFACT_READS.store(0, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn artifact_reads() -> usize {
|
||||
ARTIFACT_READS.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn record_artifact_read() {
|
||||
ARTIFACT_READS.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn reset_traversal_calls() {
|
||||
TRAVERSAL_CALLS.store(0, Ordering::SeqCst);
|
||||
|
||||
@@ -11,6 +11,7 @@ async-trait = "0.1"
|
||||
axum.workspace = true
|
||||
base64.workspace = true
|
||||
crank-adapter-rest = { path = "../crank-adapter-rest" }
|
||||
crank-artifacts = { path = "../crank-artifacts" }
|
||||
crank-core = { path = "../crank-core" }
|
||||
crank-metrics = { path = "../crank-metrics" }
|
||||
crank-observability = { path = "../crank-observability" }
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,5 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use axum::response::Response;
|
||||
use crank_core::{
|
||||
ApprovalRequest, ApprovalRequestId, ApprovalRequestStatus, CorrelationContext, InvocationLevel,
|
||||
InvocationStatus, OperationApprovalMode,
|
||||
@@ -10,39 +9,45 @@ use crank_trace::{DbOperation, observe_db_query};
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::{
|
||||
AppState, InvocationRecord, internal_jsonrpc_error, persist_invocation_for_key,
|
||||
response::{success_tool_response, tool_error_response},
|
||||
};
|
||||
use super::{AppState, InvocationRecord, persist_invocation_for_key};
|
||||
use crate::{
|
||||
approval_response::{
|
||||
approval_history_request_preview, approval_history_response_preview,
|
||||
approval_required_response,
|
||||
},
|
||||
session::SessionState,
|
||||
tool_error::{McpControlError, control_tool_error_contract, execution_locale},
|
||||
transport::ResponseMode,
|
||||
protocol::ContinuationSupport,
|
||||
};
|
||||
|
||||
pub(super) enum ApprovalPolicyResult {
|
||||
Required(Response),
|
||||
Error(Response),
|
||||
/// Era-neutral outcome of the approval policy of one Tools call (R8, spec section 6.2).
|
||||
///
|
||||
/// The policy no longer builds a wire response: `Pending` carries the domain payload that the
|
||||
/// adapter turns into its era-correct success shape, and the two failure cases are named so the
|
||||
/// adapter — the only place that knows the response mode, the protocol revision and the request
|
||||
/// envelope — can answer with the shape it owns.
|
||||
pub(crate) enum ApprovalPolicyDecision {
|
||||
/// The operation waits for a human decision; the payload is the approval disclosure.
|
||||
Pending(Value),
|
||||
/// The client cannot complete the elicitation the policy requires; the adapter answers the
|
||||
/// era-correct tool error for `McpControlError::ApprovalElicitationNotSupported`.
|
||||
ElicitationUnavailable,
|
||||
/// The pending approval could not be persisted; the adapter answers its internal error shape.
|
||||
StorageFailed,
|
||||
}
|
||||
|
||||
pub(super) struct ApprovalPolicyContext<'a> {
|
||||
/// Verified, wire-free inputs of one approval decision.
|
||||
pub(crate) struct ApprovalPolicyContext<'a> {
|
||||
pub state: &'a Arc<AppState>,
|
||||
pub session: &'a SessionState,
|
||||
pub message: &'a Value,
|
||||
pub response_mode: ResponseMode,
|
||||
pub tool: &'a PublishedAgentTool,
|
||||
pub arguments: &'a Value,
|
||||
pub platform_api_key_id: Option<&'a crank_core::PlatformApiKeyId>,
|
||||
pub transport_correlation: &'a CorrelationContext,
|
||||
pub correlation: &'a CorrelationContext,
|
||||
pub continuation: ContinuationSupport,
|
||||
}
|
||||
|
||||
pub(super) async fn maybe_handle_approval_policy(
|
||||
/// `None` means "no approval is required, the call may proceed".
|
||||
pub(crate) async fn maybe_handle_approval_policy(
|
||||
context: ApprovalPolicyContext<'_>,
|
||||
) -> Option<ApprovalPolicyResult> {
|
||||
) -> Option<ApprovalPolicyDecision> {
|
||||
let policy = context
|
||||
.tool
|
||||
.operation
|
||||
@@ -55,32 +60,22 @@ pub(super) async fn maybe_handle_approval_policy(
|
||||
|
||||
match policy.mode {
|
||||
OperationApprovalMode::Custom => maybe_create_custom_pending_approval(&context).await,
|
||||
OperationApprovalMode::Elicitation => Some(handle_elicitation_approval(
|
||||
context.session,
|
||||
context.message,
|
||||
context.response_mode,
|
||||
context.tool,
|
||||
context.arguments,
|
||||
policy.elicitation_message.as_deref(),
|
||||
context.transport_correlation,
|
||||
)),
|
||||
OperationApprovalMode::Elicitation => Some(handle_elicitation_approval(&context)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn maybe_create_custom_pending_approval(
|
||||
context: &ApprovalPolicyContext<'_>,
|
||||
) -> Option<ApprovalPolicyResult> {
|
||||
) -> Option<ApprovalPolicyDecision> {
|
||||
let ApprovalPolicyContext {
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
tool,
|
||||
arguments,
|
||||
platform_api_key_id,
|
||||
transport_correlation,
|
||||
correlation,
|
||||
..
|
||||
} = context;
|
||||
let transport_request_id = transport_correlation.request_id().as_str();
|
||||
let transport_request_id = correlation.request_id().as_str();
|
||||
let policy = tool.operation.execution_config.approval_policy.as_ref()?;
|
||||
|
||||
let approval_id = ApprovalRequestId::new(format!("approval_{}", uuid::Uuid::now_v7().simple()));
|
||||
@@ -94,8 +89,8 @@ async fn maybe_create_custom_pending_approval(
|
||||
operation_version: tool.operation.version,
|
||||
status: ApprovalRequestStatus::Pending,
|
||||
risk_level: policy.risk_level,
|
||||
request_id: Some(transport_correlation.request_id().as_str().to_owned()),
|
||||
trace_id: Some(transport_correlation.trace_id().as_str().to_owned()),
|
||||
request_id: Some(correlation.request_id().as_str().to_owned()),
|
||||
trace_id: Some(correlation.trace_id().as_str().to_owned()),
|
||||
request_payload: (*arguments).clone(),
|
||||
response_payload: None,
|
||||
created_at: now,
|
||||
@@ -116,11 +111,7 @@ async fn maybe_create_custom_pending_approval(
|
||||
.await
|
||||
{
|
||||
Ok(approval) => approval,
|
||||
Err(error) => {
|
||||
return Some(ApprovalPolicyResult::Error(internal_jsonrpc_error(
|
||||
message, error,
|
||||
)));
|
||||
}
|
||||
Err(_error) => return Some(ApprovalPolicyDecision::StorageFailed),
|
||||
};
|
||||
let response_payload = approval_required_response(tool, &persisted_approval.approval, policy);
|
||||
|
||||
@@ -130,7 +121,7 @@ async fn maybe_create_custom_pending_approval(
|
||||
*platform_api_key_id,
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(transport_correlation.trace_id().as_str()),
|
||||
trace_id: Some(correlation.trace_id().as_str()),
|
||||
tool_name: &tool.tool_name,
|
||||
status: InvocationStatus::Ok,
|
||||
level: InvocationLevel::Info,
|
||||
@@ -148,56 +139,33 @@ async fn maybe_create_custom_pending_approval(
|
||||
)
|
||||
.await;
|
||||
|
||||
Some(ApprovalPolicyResult::Required(success_tool_response(
|
||||
message,
|
||||
*response_mode,
|
||||
&session.protocol_version,
|
||||
response_payload,
|
||||
)))
|
||||
Some(ApprovalPolicyDecision::Pending(response_payload))
|
||||
}
|
||||
|
||||
fn handle_elicitation_approval(
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
tool: &PublishedAgentTool,
|
||||
arguments: &Value,
|
||||
elicitation_message: Option<&str>,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> ApprovalPolicyResult {
|
||||
let transport_request_id = transport_correlation.request_id().as_str();
|
||||
if !session.supports_elicitation {
|
||||
return ApprovalPolicyResult::Error(tool_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
control_tool_error_contract(
|
||||
McpControlError::ApprovalElicitationNotSupported,
|
||||
transport_request_id,
|
||||
transport_correlation.trace_id().as_str(),
|
||||
execution_locale(message),
|
||||
),
|
||||
));
|
||||
fn handle_elicitation_approval(context: &ApprovalPolicyContext<'_>) -> ApprovalPolicyDecision {
|
||||
let ApprovalPolicyContext {
|
||||
tool,
|
||||
arguments,
|
||||
continuation,
|
||||
..
|
||||
} = context;
|
||||
if !continuation.supports_elicitation() {
|
||||
return ApprovalPolicyDecision::ElicitationUnavailable;
|
||||
}
|
||||
|
||||
let payload_preview = tool
|
||||
.operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()
|
||||
.and_then(|policy| policy.show_payload_preview.then(|| arguments.clone()))
|
||||
let policy = tool.operation.execution_config.approval_policy.as_ref();
|
||||
let payload_preview = policy
|
||||
.and_then(|policy| policy.show_payload_preview.then(|| (*arguments).clone()))
|
||||
.unwrap_or(Value::Null);
|
||||
let elicitation_message = policy
|
||||
.and_then(|policy| policy.elicitation_message.clone())
|
||||
.unwrap_or_else(|| "Confirm operation execution.".to_owned());
|
||||
|
||||
ApprovalPolicyResult::Required(success_tool_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
json!({
|
||||
"status": "elicitation_required",
|
||||
"message": elicitation_message.unwrap_or("Confirm operation execution."),
|
||||
"tool": tool.tool_name,
|
||||
"payload_preview": payload_preview,
|
||||
"note": "This MCP client advertised elicitation support. Full elicitation/create continuation is handled by compatible client integrations.",
|
||||
}),
|
||||
))
|
||||
ApprovalPolicyDecision::Pending(json!({
|
||||
"status": "elicitation_required",
|
||||
"message": elicitation_message,
|
||||
"tool": tool.tool_name,
|
||||
"payload_preview": payload_preview,
|
||||
"note": "This MCP client advertised elicitation support. Full elicitation/create continuation is handled by compatible client integrations.",
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
//! Approval HTTP surface: listing/reading pending approvals and the approve/deny decisions,
|
||||
//! including the era-neutral decision projections.
|
||||
//!
|
||||
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); it is wired only from
|
||||
//! `build_app_inner`, so every handler here is `pub(super)`. No behaviour, status code, header or
|
||||
//! payload changed.
|
||||
|
||||
use super::request::ApprovalDecisionPayload;
|
||||
use super::stages::{enforce_traced_rate_limit, require_traced_approval_access};
|
||||
use crate::{
|
||||
approval_execution::execute_approved_request, rate_limit::rate_limited_status_response,
|
||||
request_context::RequestContext,
|
||||
};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Extension, Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use crank_core::{
|
||||
ApprovalRequestId, ApprovalRequestStatus, CorrelationContext, PlatformApiKeyScope,
|
||||
};
|
||||
use crank_registry::{ApprovalRequestRecord, DecideApprovalRequest, ExpireApprovalRequest};
|
||||
use crank_trace::{DbOperation, observe_db_query};
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::{AgentRoutePath, AppState, ApprovalRoutePath};
|
||||
pub(super) async fn list_pending_approvals(
|
||||
Path(path): Path<AgentRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
if let Err(rejection) = enforce_traced_rate_limit(&state, &path, &headers).await {
|
||||
return rate_limited_status_response(rejection);
|
||||
}
|
||||
|
||||
let key = match require_traced_approval_access(
|
||||
&state,
|
||||
&path,
|
||||
&headers,
|
||||
PlatformApiKeyScope::ReadPending,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(key) => key,
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
|
||||
let Some(agent_id) = key.api_key.agent_id.as_ref() else {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
};
|
||||
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalRead,
|
||||
state
|
||||
.registry
|
||||
.list_pending_approval_requests_for_agent(&key.api_key.workspace_id, agent_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(items) => Json(json!({
|
||||
"items": items.into_iter().map(safe_approval_record).collect::<Vec<_>>()
|
||||
}))
|
||||
.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn approve_request(
|
||||
Path(path): Path<ApprovalRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
Extension(request_context): Extension<RequestContext>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<ApprovalDecisionPayload>,
|
||||
) -> Response {
|
||||
decide_approval_request(
|
||||
path,
|
||||
state,
|
||||
headers,
|
||||
payload,
|
||||
PlatformApiKeyScope::Approve,
|
||||
ApprovalRequestStatus::Approved,
|
||||
Some(request_context.correlation),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn get_approval_request(
|
||||
Path(path): Path<ApprovalRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let agent_path = AgentRoutePath {
|
||||
workspace_slug: path.workspace_slug,
|
||||
agent_slug: path.agent_slug,
|
||||
};
|
||||
if let Err(rejection) = enforce_traced_rate_limit(&state, &agent_path, &headers).await {
|
||||
return rate_limited_status_response(rejection);
|
||||
}
|
||||
|
||||
let key = match require_traced_approval_access(
|
||||
&state,
|
||||
&agent_path,
|
||||
&headers,
|
||||
PlatformApiKeyScope::ReadPending,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(key) => key,
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
let Some(agent_id) = key.api_key.agent_id.as_ref() else {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
};
|
||||
let approval_id = ApprovalRequestId::new(path.approval_id);
|
||||
|
||||
approval_record_response(&state, &key.api_key.workspace_id, agent_id, &approval_id).await
|
||||
}
|
||||
|
||||
pub(super) async fn deny_request(
|
||||
Path(path): Path<ApprovalRoutePath>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<ApprovalDecisionPayload>,
|
||||
) -> Response {
|
||||
decide_approval_request(
|
||||
path,
|
||||
state,
|
||||
headers,
|
||||
payload,
|
||||
PlatformApiKeyScope::Deny,
|
||||
ApprovalRequestStatus::Denied,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn decide_approval_request(
|
||||
path: ApprovalRoutePath,
|
||||
state: Arc<AppState>,
|
||||
headers: HeaderMap,
|
||||
payload: ApprovalDecisionPayload,
|
||||
required_scope: PlatformApiKeyScope,
|
||||
status: ApprovalRequestStatus,
|
||||
execution_correlation: Option<CorrelationContext>,
|
||||
) -> Response {
|
||||
let agent_path = AgentRoutePath {
|
||||
workspace_slug: path.workspace_slug,
|
||||
agent_slug: path.agent_slug,
|
||||
};
|
||||
if let Err(rejection) = enforce_traced_rate_limit(&state, &agent_path, &headers).await {
|
||||
return rate_limited_status_response(rejection);
|
||||
}
|
||||
|
||||
let key =
|
||||
match require_traced_approval_access(&state, &agent_path, &headers, required_scope).await {
|
||||
Ok(key) => key,
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
|
||||
if (status == ApprovalRequestStatus::Approved && !payload.approve.eq_ignore_ascii_case("yes"))
|
||||
|| (status == ApprovalRequestStatus::Denied && !payload.approve.eq_ignore_ascii_case("no"))
|
||||
{
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({
|
||||
"error": "invalid_decision_payload",
|
||||
"message": "approve must be yes for approve endpoint and no for deny endpoint"
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
let Some(agent_id) = key.api_key.agent_id.as_ref() else {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
};
|
||||
let approval_id = ApprovalRequestId::new(path.approval_id);
|
||||
|
||||
let expected_record = match observe_db_query(
|
||||
DbOperation::ApprovalRead,
|
||||
state.registry.get_approval_request_for_agent(
|
||||
&key.api_key.workspace_id,
|
||||
agent_id,
|
||||
&approval_id,
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) => record,
|
||||
Ok(None) => return StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
};
|
||||
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalWrite,
|
||||
state
|
||||
.registry
|
||||
.decide_approval_request(DecideApprovalRequest {
|
||||
workspace_id: &key.api_key.workspace_id,
|
||||
agent_id,
|
||||
approval_id: &approval_id,
|
||||
operation_id: &expected_record.approval.operation_id,
|
||||
operation_version: expected_record.approval.operation_version,
|
||||
request_payload: &expected_record.approval.request_payload,
|
||||
status,
|
||||
decided_at: OffsetDateTime::now_utc(),
|
||||
decided_by_key_id: Some(&key.api_key.id),
|
||||
response_payload: Some(json!({ "approve": payload.approve })),
|
||||
decision_note: payload.note.as_deref(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) if status == ApprovalRequestStatus::Approved => {
|
||||
let claimed = match observe_db_query(
|
||||
DbOperation::ApprovalWrite,
|
||||
state.registry.claim_approval_request(
|
||||
&record.approval.workspace_id,
|
||||
&record.approval.agent_id,
|
||||
&record.approval.id,
|
||||
OffsetDateTime::now_utc(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(claimed)) => claimed,
|
||||
Ok(None) => return StatusCode::CONFLICT.into_response(),
|
||||
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
};
|
||||
match execute_approved_request(
|
||||
&state,
|
||||
&agent_path,
|
||||
claimed,
|
||||
execution_correlation.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(record) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
Ok(Some(record)) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Ok(None) => {
|
||||
terminal_decision_response(&state, &key.api_key.workspace_id, agent_id, &approval_id)
|
||||
.await
|
||||
}
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn approval_record_response(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
agent_id: &crank_core::AgentId,
|
||||
approval_id: &ApprovalRequestId,
|
||||
) -> Response {
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalRead,
|
||||
state
|
||||
.registry
|
||||
.get_approval_request_for_agent(workspace_id, agent_id, approval_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record))
|
||||
if record.approval.status == ApprovalRequestStatus::Pending
|
||||
&& record.approval.expires_at <= OffsetDateTime::now_utc() =>
|
||||
{
|
||||
expire_approval_response(state, workspace_id, agent_id, approval_id).await
|
||||
}
|
||||
Ok(Some(record)) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn terminal_decision_response(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
agent_id: &crank_core::AgentId,
|
||||
approval_id: &ApprovalRequestId,
|
||||
) -> Response {
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalRead,
|
||||
state
|
||||
.registry
|
||||
.get_approval_request_for_agent(workspace_id, agent_id, approval_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record))
|
||||
if record.approval.status == ApprovalRequestStatus::Pending
|
||||
&& record.approval.expires_at <= OffsetDateTime::now_utc() =>
|
||||
{
|
||||
expire_approval_response(state, workspace_id, agent_id, approval_id).await
|
||||
}
|
||||
Ok(Some(record))
|
||||
if matches!(
|
||||
record.approval.status,
|
||||
ApprovalRequestStatus::Completed
|
||||
| ApprovalRequestStatus::Failed
|
||||
| ApprovalRequestStatus::Denied
|
||||
| ApprovalRequestStatus::Expired
|
||||
) =>
|
||||
{
|
||||
Json(json!(safe_approval_record(record))).into_response()
|
||||
}
|
||||
Ok(Some(_)) => StatusCode::CONFLICT.into_response(),
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
fn safe_approval_record(mut record: ApprovalRequestRecord) -> ApprovalRequestRecord {
|
||||
record.approval.request_payload =
|
||||
crank_core::sanitize_invocation_preview(&record.approval.request_payload);
|
||||
record.approval.response_payload = record
|
||||
.approval
|
||||
.response_payload
|
||||
.as_ref()
|
||||
.map(crank_core::sanitize_invocation_preview);
|
||||
record
|
||||
}
|
||||
|
||||
async fn expire_approval_response(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
agent_id: &crank_core::AgentId,
|
||||
approval_id: &ApprovalRequestId,
|
||||
) -> Response {
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalWrite,
|
||||
state
|
||||
.registry
|
||||
.expire_approval_request(ExpireApprovalRequest {
|
||||
workspace_id,
|
||||
agent_id,
|
||||
approval_id,
|
||||
expired_at: OffsetDateTime::now_utc(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Ok(None) => StatusCode::CONFLICT.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Auth-profile resolution for a tool call: which profile applies to the operation/agent pair, and
|
||||
//! the runtime auth projection derived from it.
|
||||
//!
|
||||
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309). `resolve_operation_auth` keeps its
|
||||
//! crate-visible path through a targeted `pub(super) use` in `app.rs`; the other two stay private to
|
||||
//! this module. No behaviour changed.
|
||||
|
||||
use crank_core::{AuthProfile, SecretId, SecretStatus};
|
||||
use crank_registry::PostgresRegistry;
|
||||
use crank_runtime::{ResolvedAuth, RuntimeError, SecretCrypto};
|
||||
use crank_trace::{DbOperation, ErrorCategory, Stage, StageOutcome, observe_db_query};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use time::OffsetDateTime;
|
||||
use tracing::{Instrument, warn};
|
||||
|
||||
use super::AppState;
|
||||
pub(crate) async fn resolve_operation_auth(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
execution_config: &crank_core::ExecutionConfig,
|
||||
) -> Result<Option<ResolvedAuth>, RuntimeError> {
|
||||
if execution_config.auth_profile_ref.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let span = Stage::AuthResolve.span();
|
||||
let result = resolve_runtime_auth_for_task(
|
||||
&state.registry,
|
||||
&state.secret_crypto,
|
||||
workspace_id,
|
||||
execution_config,
|
||||
)
|
||||
.instrument(span.clone())
|
||||
.await;
|
||||
match &result {
|
||||
Ok(_) => StageOutcome::Success.record(&span),
|
||||
Err(_) => {
|
||||
StageOutcome::Error.record(&span);
|
||||
ErrorCategory::Configuration.record(&span);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn resolve_runtime_auth_for_task(
|
||||
registry: &PostgresRegistry,
|
||||
secret_crypto: &SecretCrypto,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
execution_config: &crank_core::ExecutionConfig,
|
||||
) -> Result<Option<ResolvedAuth>, RuntimeError> {
|
||||
let Some(auth_profile_id) = execution_config.auth_profile_ref.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let auth_profile = observe_db_query(
|
||||
DbOperation::AuthProfileRead,
|
||||
registry.get_auth_profile(workspace_id, auth_profile_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
|
||||
.ok_or_else(|| RuntimeError::MissingAuthProfile {
|
||||
auth_profile_id: auth_profile_id.as_str().to_owned(),
|
||||
})?;
|
||||
|
||||
resolve_auth_profile(registry, secret_crypto, workspace_id, &auth_profile)
|
||||
.await
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
async fn resolve_auth_profile(
|
||||
registry: &PostgresRegistry,
|
||||
secret_crypto: &SecretCrypto,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
auth_profile: &AuthProfile,
|
||||
) -> Result<ResolvedAuth, RuntimeError> {
|
||||
let mut secrets = BTreeMap::new();
|
||||
let used_at = OffsetDateTime::now_utc();
|
||||
|
||||
for secret_id in auth_profile.config.secret_ids() {
|
||||
let secret = observe_db_query(
|
||||
DbOperation::SecretRead,
|
||||
registry.get_secret(workspace_id, secret_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
|
||||
.ok_or_else(|| RuntimeError::MissingSecret {
|
||||
secret_id: secret_id.as_str().to_owned(),
|
||||
})?;
|
||||
if secret.secret.status != SecretStatus::Active {
|
||||
return Err(RuntimeError::InvalidAuthSecretValue {
|
||||
secret_id: secret_id.as_str().to_owned(),
|
||||
reason: "secret is not active".to_owned(),
|
||||
});
|
||||
}
|
||||
let version = observe_db_query(
|
||||
DbOperation::SecretRead,
|
||||
registry.get_current_secret_version(workspace_id, secret_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
|
||||
.ok_or_else(|| RuntimeError::MissingSecretVersion {
|
||||
secret_id: secret_id.as_str().to_owned(),
|
||||
version: secret.secret.current_version,
|
||||
})?;
|
||||
let plaintext = secret_crypto.decrypt_for_epoch(
|
||||
&version.secret_version.key_version,
|
||||
version.master_key_epoch,
|
||||
&version.secret_version.ciphertext,
|
||||
)?;
|
||||
if observe_db_query(
|
||||
DbOperation::SecretTouch,
|
||||
registry.touch_secret(workspace_id, secret_id, &used_at),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
warn!(
|
||||
target: "crank::audit",
|
||||
action = "credential.secret.touch_failed",
|
||||
credential_type = "secret",
|
||||
credential_ref = %secret_id.as_str(),
|
||||
outcome = "metadata_touch_failed",
|
||||
"secret last-used metadata was not updated"
|
||||
);
|
||||
}
|
||||
secrets.insert(SecretId::new(secret_id.as_str()), plaintext);
|
||||
}
|
||||
|
||||
ResolvedAuth::from_profile(auth_profile, &secrets)
|
||||
}
|
||||
@@ -0,0 +1,837 @@
|
||||
//! Modern JSON-RPC dispatch: required `Mcp-Name`/method checks, `initialize`, the
|
||||
//! initialized-notification handshake, the required-initialized-session guard and the era-neutral
|
||||
//! result helpers it needs locally (`add_millis` is used only by `handle_initialize`).
|
||||
//!
|
||||
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); it is called from
|
||||
//! `app/endpoint.rs`, so the entry points are `pub(super)`. No behaviour changed.
|
||||
|
||||
use super::request::{InitializeParams, ToolCallParams};
|
||||
use super::response::take_confirmation_token;
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{
|
||||
is_notification, jsonrpc_error, jsonrpc_result, method_name, negotiated_protocol_version,
|
||||
params, request_id,
|
||||
},
|
||||
protocol::{
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, MethodHandler,
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity,
|
||||
ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
||||
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
||||
declared_mcp_method, discover_result, handle_completion_command, handle_prompts_command,
|
||||
handle_resources_command, handle_tools_command, validate_modern_request_name,
|
||||
},
|
||||
session::SessionState,
|
||||
tool_error::execution_locale,
|
||||
transport::{ResponseMode, json_response, session_id_from_headers, transport_response},
|
||||
};
|
||||
use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use crank_core::CorrelationContext;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::response::{
|
||||
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
||||
prompts_list_result, resource_error_response, resource_read_result,
|
||||
resource_templates_list_result, resources_list_result, tool_command_response,
|
||||
tools_list_result,
|
||||
};
|
||||
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
||||
use crate::protocol::{ResourceTemplatesListError, list_resource_templates};
|
||||
const SERVER_NAME: &str = "crank-mcp-server";
|
||||
const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// Serve a request of the modern stateless era.
|
||||
/// No session is created, read or required; identity comes from the per-request `_meta` metadata that
|
||||
/// the era resolver already validated, and the advertised capabilities come from the single static
|
||||
/// registration. The era answers the same business result as the legacy path through the shared tool
|
||||
/// transport, methods that are not implemented answer with an era-correct `-32601`, and a
|
||||
/// notification (no `id`) is acknowledged without being dispatched.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn handle_modern_request(
|
||||
state: &Arc<AppState>,
|
||||
path: &AgentRoutePath,
|
||||
headers: &HeaderMap,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
identity: &RequestIdentity,
|
||||
credential: &VerifiedMachineCredential,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> Response {
|
||||
let version = identity
|
||||
.version
|
||||
.as_deref()
|
||||
.unwrap_or(crate::jsonrpc::MODERN_PROTOCOL_VERSION);
|
||||
|
||||
// Story 3.18: the modern revision carries the log level of this request in
|
||||
// `_meta["io.modelcontextprotocol/logLevel"]` (SEP-2577); the former `logging/setLevel` request
|
||||
// does not exist here. Absent, non-string or unknown values mean "not opted in", so no
|
||||
// `notifications/message` is emitted for this request.
|
||||
crate::protocol::set_active_level(crate::protocol::modern_request_level(message));
|
||||
|
||||
// A notification carries no `id`. It is acknowledged before the request-only header rules: the
|
||||
// mandatory `Mcp-Method`/`Mcp-Name` pair applies to requests, not to notifications (protocol era
|
||||
// matrix row 18). The envelope, identity and mixed-carrier checks — and authentication — have
|
||||
// already run at this point, so this early return cannot admit a malformed identity or a session
|
||||
// conflict, and the notification is never dispatched.
|
||||
if is_notification(message) {
|
||||
return crate::protocol::modern_notification_response();
|
||||
}
|
||||
|
||||
let declared_method = match declared_mcp_method(headers, message) {
|
||||
Ok(declared_method) => declared_method,
|
||||
Err(response) => return *response,
|
||||
};
|
||||
if declared_method != method_name(message) {
|
||||
return crate::protocol::modern_header_mismatch_response(message);
|
||||
}
|
||||
|
||||
// R5/F5: the same registration-backed dispatch as the legacy adapter. The handler is decided by
|
||||
// the owning registration (not by a literal method list inside this adapter), and a method whose
|
||||
// capability is not eligible in this revision is never served here.
|
||||
let dispatch =
|
||||
crate::protocol::dispatch_decision(method_name(message).unwrap_or_default(), version);
|
||||
match dispatch {
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Discover,
|
||||
..
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
discover_result(version, SERVER_NAME, SERVER_VERSION),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
..
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_result(
|
||||
version,
|
||||
json!({ "protocolVersion": version }),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolList,
|
||||
..
|
||||
} => {
|
||||
// Same shared command boundary as the legacy era: the adapter keeps the modern cache
|
||||
// projection, the shared service stays wire-free.
|
||||
let list_command: ToolsListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, "invalid tools/list parameters"),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_tools_command(
|
||||
state,
|
||||
ServiceContext {
|
||||
workspace_slug: &path.workspace_slug,
|
||||
agent_slug: &path.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::ElicitationUnsupported,
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
ToolsCommand::List(list_command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
tools_list_result(tools, next_cursor),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
ToolsOutcome::CatalogUnavailable => {
|
||||
internal_jsonrpc_error(message, "published catalog is unavailable")
|
||||
}
|
||||
// A list command never produces a call outcome; it is answered with the adapter's
|
||||
// internal error instead of being silently ignored.
|
||||
ToolsOutcome::Call(_) => internal_jsonrpc_error(
|
||||
message,
|
||||
"unexpected shared tools outcome for a tools/list",
|
||||
),
|
||||
}
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolCall,
|
||||
..
|
||||
} => {
|
||||
let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Validate the required name header against the body before anything is dispatched.
|
||||
if let Err(response) =
|
||||
validate_modern_request_name(message, headers, &tool_call_params.name)
|
||||
{
|
||||
return *response;
|
||||
}
|
||||
|
||||
// The adapter owns the wire form: it parses the call parameters, removes the reserved
|
||||
// confirmation marker and the shared Tools service never sees the envelope, the
|
||||
// response mode or the protocol revision (spec section 6.2). The modern era is
|
||||
// session-less, so its calls cannot advertise elicitation support.
|
||||
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
|
||||
let confirmation_token = take_confirmation_token(&mut arguments);
|
||||
let outcome = handle_tools_command(
|
||||
state,
|
||||
ServiceContext {
|
||||
workspace_slug: &path.workspace_slug,
|
||||
agent_slug: &path.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
continuation: ContinuationSupport::ElicitationUnsupported,
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
ToolsCommand::Call(ToolCallCommand {
|
||||
tool_name: tool_call_params.name,
|
||||
arguments,
|
||||
confirmation_token,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
tool_command_response(
|
||||
message,
|
||||
response_mode,
|
||||
version,
|
||||
transport_correlation,
|
||||
outcome,
|
||||
)
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceList,
|
||||
..
|
||||
} => {
|
||||
let list_command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/list parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_resources_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
ResourcesCommand::List(list_command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ResourcesOutcome::Listed {
|
||||
resources,
|
||||
next_cursor,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resources_list_result(resources, next_cursor),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
// A list command never produces these variants; a bound snapshot that cannot be
|
||||
// verified is answered with the adapter's internal error instead of a partial page.
|
||||
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
||||
}
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceRead,
|
||||
..
|
||||
} => {
|
||||
let read_command: ResourceReadCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/read parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
};
|
||||
// The required `Mcp-Name` (the requested resource URI) is validated before the Resource
|
||||
// handler runs, exactly as for `tools/call`.
|
||||
if let Err(response) = validate_modern_request_name(message, headers, &read_command.uri)
|
||||
{
|
||||
return *response;
|
||||
}
|
||||
let outcome = handle_resources_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
ResourcesCommand::Read(read_command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ResourcesOutcome::Read { contents } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resource_read_result(contents),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
// One indistinguishable safe outcome for unknown/Draft/unbound/foreign URIs: no
|
||||
// Resource metadata, digest, MIME or content is disclosed.
|
||||
ResourcesOutcome::NotAvailable => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the requested resource is not available",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
ResourcesOutcome::ExecutionError(contract) => {
|
||||
resource_error_response(message, response_mode, version, contract)
|
||||
}
|
||||
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
||||
}
|
||||
}
|
||||
// Story 3.11: `resources/templates/list` comes from the shared service and contains only exact
|
||||
// Published template versions bound to the active Agent snapshot. The modern revision receives
|
||||
// its cacheable result envelope; the request declares no name, so only `Mcp-Method` is checked.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceTemplateList,
|
||||
..
|
||||
} => {
|
||||
let command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/templates/list parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let (templates, next_cursor) = match list_resource_templates(
|
||||
state,
|
||||
&path.workspace_slug,
|
||||
&path.agent_slug,
|
||||
version,
|
||||
command,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(page) => page,
|
||||
Err(ResourceTemplatesListError::InvalidCursor) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid resources/templates/list cursor",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
Err(ResourceTemplatesListError::Unavailable) => {
|
||||
return internal_jsonrpc_error(message, "published templates are unavailable");
|
||||
}
|
||||
};
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resource_templates_list_result(templates, next_cursor),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
)
|
||||
}
|
||||
// Story 3.14: the standard Prompt requests. Missing name/header on `prompts/get` is a
|
||||
// header-validation failure; the page is served only from exact bound Published versions.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::PromptList,
|
||||
..
|
||||
} => {
|
||||
let command: PromptsListCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid prompts/list parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_prompts_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
PromptsCommand::List(command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
PromptsOutcome::Listed {
|
||||
prompts,
|
||||
next_cursor,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
prompts_list_result(prompts, next_cursor),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
PromptsOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
||||
}
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::PromptGet,
|
||||
..
|
||||
} => {
|
||||
let command: PromptGetCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid prompts/get parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
};
|
||||
// The required `Mcp-Name` (the requested prompt name) is validated before the Prompt
|
||||
// handler runs, exactly as for `resources/read` (matrix row 6).
|
||||
if let Err(response) = validate_modern_request_name(message, headers, &command.name) {
|
||||
return *response;
|
||||
}
|
||||
let outcome = handle_prompts_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
PromptsCommand::Get(command),
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
PromptsOutcome::Got {
|
||||
description,
|
||||
messages,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_result(
|
||||
version,
|
||||
prompt_get_result(description, messages),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
// Unknown, Draft, foreign and unbound Prompt names share one safe outcome: no
|
||||
// Prompt metadata and no message content is disclosed.
|
||||
PromptsOutcome::NotAvailable => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the requested prompt is not available",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
PromptsOutcome::ArgumentsRejected { reason, argument } => {
|
||||
prompt_arguments_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
version,
|
||||
reason,
|
||||
argument,
|
||||
)
|
||||
}
|
||||
PromptsOutcome::DependencyUnavailable { position } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32603,
|
||||
format!("the pinned dependency at dependencies[{position}] is unavailable"),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
PromptsOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
||||
}
|
||||
}
|
||||
// Story 3.17: `completion/complete` answers from the same exact bound Published Prompt
|
||||
// arguments and Resource template parameters the two listing methods serve. Its `ref` is a
|
||||
// union of a Prompt name and a URI template, so the pinned era matrix requires only
|
||||
// `Mcp-Method` here (`Mcp-Name` is required for `tools/call`, `resources/read`, `prompts/get`).
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Completion,
|
||||
..
|
||||
} => {
|
||||
let command: CompletionCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid completion/complete parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let outcome = handle_completion_command(
|
||||
state,
|
||||
resource_service_context(path, credential, transport_correlation, message),
|
||||
version,
|
||||
command,
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
CompletionOutcome::Completed {
|
||||
values,
|
||||
total,
|
||||
has_more,
|
||||
} => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_result(
|
||||
version,
|
||||
completion_result(values, total, has_more),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
CompletionOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
// Unknown, Draft, foreign and unbound references (and unknown argument names) share
|
||||
// one safe answer: no Prompt name, URI template or option count is disclosed.
|
||||
CompletionOutcome::NotAvailable => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the completion reference is not available",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
CompletionOutcome::CatalogUnavailable => {
|
||||
internal_jsonrpc_error(message, "published completion sources are unavailable")
|
||||
}
|
||||
}
|
||||
}
|
||||
// The standard Prompt requests are registered capabilities now; any other
|
||||
// unregistered/wrong-era method goes straight to the era-correct unsupported answer.
|
||||
_ => crate::protocol::modern_method_not_found_response(message),
|
||||
}
|
||||
}
|
||||
|
||||
/// The verified, era-neutral context of a Resource command: the same workspace/Agent/credential/
|
||||
/// correlation the Tools service receives.
|
||||
fn resource_service_context<'a>(
|
||||
path: &'a AgentRoutePath,
|
||||
credential: &'a VerifiedMachineCredential,
|
||||
correlation: &'a CorrelationContext,
|
||||
message: &Value,
|
||||
) -> crate::protocol::ServiceContext<'a> {
|
||||
crate::protocol::ServiceContext {
|
||||
workspace_slug: &path.workspace_slug,
|
||||
agent_slug: &path.agent_slug,
|
||||
credential,
|
||||
correlation,
|
||||
continuation: crate::protocol::ContinuationSupport::ElicitationUnsupported,
|
||||
locale: execution_locale(message),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn handle_initialize(
|
||||
state: Arc<AppState>,
|
||||
path: &AgentRoutePath,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
) -> Response {
|
||||
let initialize_params: InitializeParams = match serde_json::from_value(params(message)) {
|
||||
Ok(value) => value,
|
||||
Err(_error) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, "invalid initialize parameters"),
|
||||
response_mode,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
}
|
||||
};
|
||||
let Some(protocol_version) = negotiated_protocol_version(&initialize_params.protocol_version)
|
||||
else {
|
||||
// A revision outside the approved window is rejected without minting a session and without
|
||||
// echoing any withdrawn revision as the served identity.
|
||||
return transport_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
format!(
|
||||
"unsupported protocol version {}",
|
||||
initialize_params.protocol_version
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
};
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let expires_at = add_millis(now, TRANSPORT_SESSION_TTL_MS);
|
||||
let supports_elicitation = initialize_params
|
||||
.capabilities
|
||||
.get("elicitation")
|
||||
.is_some_and(Value::is_object);
|
||||
let session_id = match state
|
||||
.sessions
|
||||
.create(
|
||||
protocol_version,
|
||||
&path.workspace_slug,
|
||||
&path.agent_slug,
|
||||
supports_elicitation,
|
||||
now,
|
||||
Some(expires_at),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(session_id) => session_id,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
};
|
||||
state.session_metrics.refresh();
|
||||
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!( {
|
||||
"protocolVersion": protocol_version,
|
||||
"capabilities": crate::protocol::advertised_server_capabilities(protocol_version),
|
||||
"serverInfo": {
|
||||
"name": SERVER_NAME,
|
||||
"version": SERVER_VERSION
|
||||
}
|
||||
}),
|
||||
),
|
||||
response_mode,
|
||||
Some(&session_id),
|
||||
Some(protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn handle_initialized_notification(
|
||||
state: Arc<AppState>,
|
||||
path: &AgentRoutePath,
|
||||
headers: &HeaderMap,
|
||||
) -> Response {
|
||||
match session_id_from_headers(headers) {
|
||||
Ok(Some(session_id)) => match state.sessions.get(&session_id).await {
|
||||
Ok(Some(session))
|
||||
if session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug =>
|
||||
{
|
||||
match state
|
||||
.sessions
|
||||
.mark_initialized(&session_id, OffsetDateTime::now_utc())
|
||||
.await
|
||||
{
|
||||
Ok(true) => StatusCode::ACCEPTED.into_response(),
|
||||
Ok(false) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
Ok(Some(_)) => StatusCode::NOT_FOUND.into_response(),
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
},
|
||||
Ok(None) => StatusCode::BAD_REQUEST.into_response(),
|
||||
Err(status) => status.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn require_initialized_session(
|
||||
state: &Arc<AppState>,
|
||||
path: &AgentRoutePath,
|
||||
headers: &HeaderMap,
|
||||
message: &Value,
|
||||
) -> Result<SessionState, Response> {
|
||||
let session_id = match session_id_from_headers(headers) {
|
||||
Ok(Some(session_id)) => session_id,
|
||||
Ok(None) => return Err(StatusCode::BAD_REQUEST.into_response()),
|
||||
Err(status) => return Err(status.into_response()),
|
||||
};
|
||||
|
||||
let Some(session) = (match state.sessions.get(&session_id).await {
|
||||
Ok(session) => session,
|
||||
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
|
||||
}) else {
|
||||
return Err(StatusCode::NOT_FOUND.into_response());
|
||||
};
|
||||
|
||||
if session.workspace_slug != path.workspace_slug || session.agent_slug != path.agent_slug {
|
||||
return Err(StatusCode::NOT_FOUND.into_response());
|
||||
}
|
||||
|
||||
if let Err(status) = crate::protocol::validate_session_revision(&session) {
|
||||
return Err(status.into_response());
|
||||
}
|
||||
|
||||
if !session.initialized {
|
||||
return Err(json_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32002, "session is not initialized"),
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn add_millis(timestamp: OffsetDateTime, millis: u64) -> OffsetDateTime {
|
||||
let delta = time::Duration::milliseconds(i64::try_from(millis).unwrap_or(i64::MAX));
|
||||
|
||||
timestamp + delta
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Private, request-scoped semantic observer of the BUILD-internal harness (Story 3.1 section 7.2).
|
||||
//!
|
||||
//! The endpoint integration tests of `apps/mcp-server` cannot see `#[cfg(test)]` markers of this
|
||||
//! crate, so the observing behavioural test lives inside the crate, with the same in-crate access as
|
||||
//! `protocol::registry::tests::`. This module is `#[cfg(test)]`-only: it is absent from every
|
||||
//! production build and exposes no public API.
|
||||
//!
|
||||
//! The observer is **request-scoped**: the counters live in a `tokio::task_local!` slot that the
|
||||
//! test installs around one request, so two concurrently served requests never share a counter and
|
||||
//! no global racing state exists. A marker without an installed scope is a no-op, which is what
|
||||
//! happens in every other test of this crate.
|
||||
//!
|
||||
//! The markers are honest names, not one dispatch total (section 7.2): `ADMISSION_ENTER` is the
|
||||
//! external request entry, `ERA_MODERN_ENTER`/`ERA_LEGACY_ENTER` mean the request actually entered
|
||||
//! that era-adapter, and `TOOLS_SERVICE_ENTER` means the request entered the owning Tools
|
||||
//! service/handler. They prove "no reroute" (a pre-admission reject yields zero era and zero service
|
||||
//! entries; an in-adapter reject yields exactly its own era and no service entry) and they never
|
||||
//! claim "no residual state" on their own.
|
||||
//!
|
||||
//! Only the markers, the request scope and the counters live here. The behavioural harness that
|
||||
//! drives real observed requests through the real app is the `tests` child module below, whose file
|
||||
//! sits at `crates/crank-community-mcp/src/dispatch_observer_harness.rs`: `scripts/
|
||||
//! check-execution-boundaries.py` reserves the whole `crates/crank-community-mcp/src/app/` prefix
|
||||
//! for service modules without an HTTP client or a persistence dependency, while the harness needs
|
||||
//! both. The module *path* stays `app::dispatch_observer::tests`, so the selector
|
||||
//! `cargo test -p crank-community-mcp --lib app::dispatch_observer::` still selects the whole
|
||||
//! section 7.2 delta table.
|
||||
|
||||
use std::{
|
||||
future::Future,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use tokio::task_local;
|
||||
|
||||
task_local! {
|
||||
static OBSERVER: Arc<CounterSet>;
|
||||
}
|
||||
|
||||
task_local! {
|
||||
static REGISTRATION: Arc<crate::protocol::CapabilityRegistry>;
|
||||
}
|
||||
|
||||
/// The per-request counters of one observed request.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct CounterSet {
|
||||
admission: AtomicUsize,
|
||||
era_modern: AtomicUsize,
|
||||
era_legacy: AtomicUsize,
|
||||
tools_service: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
/// Read the counters of one observed request as one comparable snapshot.
|
||||
pub(crate) fn snapshot(&self) -> Snapshot {
|
||||
Snapshot {
|
||||
admission: self.admission.load(Ordering::SeqCst),
|
||||
era_modern: self.era_modern.load(Ordering::SeqCst),
|
||||
era_legacy: self.era_legacy.load(Ordering::SeqCst),
|
||||
tools_service: self.tools_service.load(Ordering::SeqCst),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One comparable set of marker deltas of a single observed request.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct Snapshot {
|
||||
pub(crate) admission: usize,
|
||||
pub(crate) era_modern: usize,
|
||||
pub(crate) era_legacy: usize,
|
||||
pub(crate) tools_service: usize,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// The expected deltas of one case (section 7.2 table) as one comparable value.
|
||||
pub(crate) const fn new(
|
||||
admission: usize,
|
||||
era_modern: usize,
|
||||
era_legacy: usize,
|
||||
tools_service: usize,
|
||||
) -> Self {
|
||||
Self {
|
||||
admission,
|
||||
era_modern,
|
||||
era_legacy,
|
||||
tools_service,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run one observed request: every marker increment inside `future` is recorded on `counters`.
|
||||
pub(crate) async fn observe<F: Future>(counters: Arc<CounterSet>, future: F) -> F::Output {
|
||||
OBSERVER.scope(counters, future).await
|
||||
}
|
||||
|
||||
/// Run one observed request with an explicit registration snapshot (F5 add/remove proof).
|
||||
///
|
||||
/// The snapshot is request-scoped like the counters: a request served inside `future` asks *this*
|
||||
/// registration for its dispatch decision and its advertisement, so one test can prove that adding or
|
||||
/// removing a private inert descriptor changes what the real router does, without touching the
|
||||
/// production table and without a process-global override that other tests could observe.
|
||||
pub(crate) async fn observe_with_registration<F: Future>(
|
||||
registration: Arc<crate::protocol::CapabilityRegistry>,
|
||||
future: F,
|
||||
) -> F::Output {
|
||||
REGISTRATION.scope(registration, future).await
|
||||
}
|
||||
|
||||
/// The registration installed for the current request, if the observing test installed one.
|
||||
pub(crate) fn installed_registration() -> Option<Arc<crate::protocol::CapabilityRegistry>> {
|
||||
REGISTRATION.try_with(Arc::clone).ok()
|
||||
}
|
||||
|
||||
/// `ADMISSION_ENTER`: the external request entry, not a dispatch.
|
||||
pub(crate) fn admission_enter() {
|
||||
increment(|counters| &counters.admission);
|
||||
}
|
||||
|
||||
/// `ERA_MODERN_ENTER`: the request was served by the modern era-adapter.
|
||||
pub(crate) fn era_modern_enter() {
|
||||
increment(|counters| &counters.era_modern);
|
||||
}
|
||||
|
||||
/// `ERA_LEGACY_ENTER`: the request was served by the legacy era-adapter.
|
||||
pub(crate) fn era_legacy_enter() {
|
||||
increment(|counters| &counters.era_legacy);
|
||||
}
|
||||
|
||||
/// `TOOLS_SERVICE_ENTER`: the request entered the owning Tools service/handler.
|
||||
pub(crate) fn tools_service_enter() {
|
||||
increment(|counters| &counters.tools_service);
|
||||
}
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
});
|
||||
}
|
||||
|
||||
/// Fixtures and helpers of the section 7.2 test seam (its file lives outside `src/app/` for the same
|
||||
/// execution-boundary reason as the tests below).
|
||||
#[cfg(test)]
|
||||
#[path = "../dispatch_observer_support.rs"]
|
||||
mod support;
|
||||
|
||||
/// The behavioural section 7.2 harness: real app, real PostgreSQL, one counted loopback upstream and
|
||||
/// one request-scoped observer per request. Its file lives outside `src/app/` only because the
|
||||
/// repository's execution-boundary check owns that prefix (see the module documentation above); the
|
||||
/// module path stays `app::dispatch_observer::tests`.
|
||||
#[cfg(test)]
|
||||
#[path = "../dispatch_observer_harness.rs"]
|
||||
mod tests;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -121,3 +121,53 @@ impl ActiveStreamGuard {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crank_metrics::McpMethod;
|
||||
use serde_json::json;
|
||||
|
||||
use super::normalized_mcp_method;
|
||||
|
||||
/// AT-3.18-02: the metric label of the logging request is a member of the closed label enum, so
|
||||
/// neither the level nor any other client-supplied identifier can reach the label space. There is
|
||||
/// no mapping from a request value to a label anywhere in this file.
|
||||
#[test]
|
||||
fn a_logging_request_can_only_produce_a_fixed_metric_label() {
|
||||
for level in [
|
||||
json!("debug"),
|
||||
json!("verbose"),
|
||||
json!("crank-canary-9f7620e5-aa41-4b0d"),
|
||||
json!(7),
|
||||
json!(null),
|
||||
] {
|
||||
let message = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "logging/setLevel",
|
||||
"params": {"level": level}
|
||||
});
|
||||
assert_eq!(
|
||||
normalized_mcp_method(&message),
|
||||
McpMethod::Unsupported,
|
||||
"the method label is a fixed enum member, never the request value"
|
||||
);
|
||||
}
|
||||
assert_eq!(McpMethod::Unsupported.as_str(), "unsupported");
|
||||
// Every label value of the enum is a pinned literal, so the label domain cannot be widened by
|
||||
// a request at all.
|
||||
assert!(
|
||||
McpMethod::VALUES.iter().all(|value| value
|
||||
.chars()
|
||||
.all(|character| character.is_ascii_lowercase() || character == '_')),
|
||||
"every method label is a fixed lowercase literal: {:?}",
|
||||
McpMethod::VALUES
|
||||
);
|
||||
|
||||
// A malformed envelope has its own fixed label as well.
|
||||
assert_eq!(
|
||||
normalized_mcp_method(&json!({"level": "debug"})),
|
||||
McpMethod::Invalid
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct InitializeParams {
|
||||
@@ -12,44 +12,19 @@ pub(super) struct InitializeParams {
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct ToolCallParams {
|
||||
pub(super) name: String,
|
||||
#[serde(default)]
|
||||
pub(super) arguments: Value,
|
||||
#[serde(default, deserialize_with = "deserialize_arguments_object")]
|
||||
pub(super) arguments: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct ToolsListParams {
|
||||
#[serde(default)]
|
||||
pub(super) cursor: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) limit: Option<usize>,
|
||||
}
|
||||
|
||||
pub(super) fn paginate_tools_list(
|
||||
definitions: Vec<Value>,
|
||||
params: ToolsListParams,
|
||||
) -> Result<Value, &'static str> {
|
||||
const MAX_TOOLS_LIST_LIMIT: usize = 100;
|
||||
let start = match params.cursor {
|
||||
Some(cursor) if cursor.is_empty() => 0,
|
||||
Some(cursor) => cursor
|
||||
.parse::<usize>()
|
||||
.map_err(|_| "invalid tools/list cursor")?,
|
||||
None => 0,
|
||||
};
|
||||
if start > definitions.len() {
|
||||
return Err("tools/list cursor is out of range");
|
||||
}
|
||||
let limit = params
|
||||
.limit
|
||||
.unwrap_or(definitions.len())
|
||||
.clamp(1, MAX_TOOLS_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(definitions.len());
|
||||
let page = definitions[start..end].to_vec();
|
||||
let mut result = json!({ "tools": page });
|
||||
if end < definitions.len() {
|
||||
result["nextCursor"] = json!(end.to_string());
|
||||
}
|
||||
Ok(result)
|
||||
/// The pinned `CallToolRequest.params.arguments` is an **optional object**. Omitting it stays valid
|
||||
/// (and keeps its previous behaviour), while an explicit `null`, array or scalar is invalid params — so
|
||||
/// the two cases must not collapse into one another during deserialization. The object shape check
|
||||
/// itself is shared with the `call_tool` proxy's nested `arguments` (`protocol::deserialize_object_only`).
|
||||
fn deserialize_arguments_object<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
crate::protocol::deserialize_object_only(deserializer).map(Some)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
||||
@@ -3,10 +3,16 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
jsonrpc::{jsonrpc_result, request_id},
|
||||
protocol::project_modern_result,
|
||||
tool_error::{ToolErrorContract, tool_error_text, tool_error_value},
|
||||
transport::{ResponseMode, transport_response},
|
||||
};
|
||||
|
||||
use crate::jsonrpc::jsonrpc_error;
|
||||
use crate::protocol::{ToolCallOutcome, ToolsOutcome};
|
||||
use crate::tool_error::{control_tool_error_contract, execution_locale};
|
||||
use crank_core::CorrelationContext;
|
||||
|
||||
pub(crate) fn take_confirmation_token(arguments: &mut Value) -> Option<String> {
|
||||
let Value::Object(object) = arguments else {
|
||||
return None;
|
||||
@@ -27,16 +33,19 @@ pub(crate) fn success_tool_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_owned())
|
||||
}
|
||||
],
|
||||
"structuredContent": output,
|
||||
"isError": false
|
||||
}),
|
||||
project_modern_result(
|
||||
protocol_version,
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_owned())
|
||||
}
|
||||
],
|
||||
"structuredContent": output,
|
||||
"isError": false
|
||||
}),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -57,21 +66,221 @@ pub(crate) fn tool_error_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": error_message
|
||||
}
|
||||
],
|
||||
"structuredContent": {
|
||||
"error": error_value
|
||||
},
|
||||
"isError": true
|
||||
}),
|
||||
project_modern_result(
|
||||
protocol_version,
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": error_message
|
||||
}
|
||||
],
|
||||
"structuredContent": {
|
||||
"error": error_value
|
||||
},
|
||||
"isError": true
|
||||
}),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
/// The era-neutral `tools/list` result shape built from the shared command outcome. Object keys end
|
||||
/// up byte-lexicographically ordered, exactly as before the extraction.
|
||||
pub(super) fn tools_list_result(tools: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "tools": tools });
|
||||
if let Some(next_cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(next_cursor);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/list` result shape (Story 3.8). Same pagination wire keys as
|
||||
/// `tools/list`; `nextCursor` is absent on the last page.
|
||||
pub(super) fn resources_list_result(resources: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "resources": resources });
|
||||
if let Some(next_cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(next_cursor);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/read` result shape: exactly the typed `contents[]` the revision
|
||||
/// converter produced.
|
||||
pub(super) fn resource_read_result(contents: Value) -> Value {
|
||||
json!({ "contents": contents })
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/templates/list` result shape.
|
||||
pub(super) fn resource_templates_list_result(
|
||||
templates: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
) -> Value {
|
||||
let mut result = json!({ "resourceTemplates": templates });
|
||||
if let Some(cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(cursor);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `prompts/list` result shape (Story 3.14). Same pagination wire keys as
|
||||
/// `resources/list`; `nextCursor` is absent on the last page.
|
||||
pub(super) fn prompts_list_result(prompts: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "prompts": prompts });
|
||||
if let Some(cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(cursor);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `prompts/get` result shape: the rendered `messages[]` and the description of the
|
||||
/// exact bound Published Prompt Version it came from.
|
||||
pub(super) fn prompt_get_result(description: Option<String>, messages: Vec<Value>) -> Value {
|
||||
let mut result = json!({ "messages": messages });
|
||||
if let Some(description) = description {
|
||||
result["description"] = Value::String(description);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `completion/complete` result shape (Story 3.17): the bounded `values[]`, the
|
||||
/// option count where it is known exactly, and whether more options exist. Both supported revisions
|
||||
/// declare the same `completion` object, so this shape is shared.
|
||||
pub(super) fn completion_result(
|
||||
values: Vec<String>,
|
||||
total: Option<usize>,
|
||||
has_more: bool,
|
||||
) -> Value {
|
||||
let mut completion = json!({ "values": values });
|
||||
if let Some(total) = total {
|
||||
completion["total"] = json!(total);
|
||||
}
|
||||
if has_more {
|
||||
completion["hasMore"] = json!(true);
|
||||
}
|
||||
json!({ "completion": completion })
|
||||
}
|
||||
|
||||
/// The structured `prompts/get` argument rejection (AT-3.14-02): a `-32602` error whose `data`
|
||||
/// carries the typed reason and the argument name of the bound Prompt. No rendered message,
|
||||
/// dependency content or other Prompt metadata is attached — the rejection happens before rendering.
|
||||
pub(super) fn prompt_arguments_error_response(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
protocol_version: &str,
|
||||
reason: &str,
|
||||
argument: Option<String>,
|
||||
) -> Response {
|
||||
let mut error = jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"the prompt arguments were rejected".to_owned(),
|
||||
);
|
||||
error["error"]["data"] = crate::jsonrpc::correlated_error_data(json!({
|
||||
"reason": reason,
|
||||
"argument": argument,
|
||||
}));
|
||||
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
error,
|
||||
response_mode,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
/// Map one shared Tools-command outcome back to the era-specific wire response (spec section 6.2).
|
||||
///
|
||||
/// This adapter function is the only place that turns a neutral outcome into a response: the shared
|
||||
/// service never sees `ResponseMode`, the protocol revision, the request envelope or an
|
||||
/// `axum::Response`. `ApprovalPending` is a success for the client (it still has to answer), while
|
||||
/// an unavailable elicitation and a failing call keep their era-correct tool-error shape.
|
||||
pub(super) fn tool_command_response(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
protocol_version: &str,
|
||||
correlation: &CorrelationContext,
|
||||
outcome: ToolsOutcome,
|
||||
) -> Response {
|
||||
match outcome {
|
||||
ToolsOutcome::Call(ToolCallOutcome::Completed(output))
|
||||
| ToolsOutcome::Call(ToolCallOutcome::ApprovalPending(output)) => {
|
||||
success_tool_response(message, response_mode, protocol_version, output)
|
||||
}
|
||||
ToolsOutcome::Call(ToolCallOutcome::ApprovalUnavailable(control_error)) => {
|
||||
tool_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
protocol_version,
|
||||
control_tool_error_contract(
|
||||
control_error,
|
||||
correlation.request_id().as_str(),
|
||||
correlation.trace_id().as_str(),
|
||||
execution_locale(message),
|
||||
),
|
||||
)
|
||||
}
|
||||
ToolsOutcome::Call(ToolCallOutcome::InvalidParams(detail)) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
),
|
||||
ToolsOutcome::Call(ToolCallOutcome::Error(contract)) => {
|
||||
tool_error_response(message, response_mode, protocol_version, contract)
|
||||
}
|
||||
// The pending approval could not be persisted: the adapter answers its internal error shape,
|
||||
// as the previous wire path did.
|
||||
ToolsOutcome::Call(ToolCallOutcome::InternalFailure) => internal_jsonrpc_error(
|
||||
message,
|
||||
"the pending approval request could not be persisted",
|
||||
),
|
||||
// A call command never produces these variants; they are answered with the adapter's
|
||||
// internal error instead of being silently ignored.
|
||||
ToolsOutcome::List { .. }
|
||||
| ToolsOutcome::InvalidParams(_)
|
||||
| ToolsOutcome::CatalogUnavailable => {
|
||||
internal_jsonrpc_error(message, "unexpected shared tools outcome for a tools/call")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn resource_error_response(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
protocol_version: &str,
|
||||
contract: ToolErrorContract,
|
||||
) -> Response {
|
||||
let mut error = jsonrpc_error(request_id(message), -32000, contract.message.clone());
|
||||
error["error"]["data"] = json!({
|
||||
"code": contract.code,
|
||||
"error_code": contract.error_code,
|
||||
"stage": contract.stage,
|
||||
"retryability": contract.retryability,
|
||||
"outcome_certainty": contract.outcome_certainty,
|
||||
"request_id": contract.request_id,
|
||||
"trace_id": contract.trace_id,
|
||||
});
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
error,
|
||||
response_mode,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn internal_jsonrpc_error(message: &Value, _error: impl std::fmt::Display) -> Response {
|
||||
transport_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
jsonrpc_error(request_id(message), -32603, "internal server error"),
|
||||
ResponseMode::Json,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,678 @@
|
||||
//! Behavioural tests of the BUILD-internal semantic observer (Story 3.1 section 7.2).
|
||||
//!
|
||||
//! This file is the `tests` child module of `crate::app::dispatch_observer` (wired with `#[path]`
|
||||
//! there), so the module path — and therefore the sanctioned selector
|
||||
//! `cargo test -p crank-community-mcp --lib app::dispatch_observer::` — is unchanged. The fixtures
|
||||
//! and helpers live in the sibling `support` module of the same parent.
|
||||
|
||||
use super::support::*;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// §7.2 pre-admission rejects: zero era-adapter entries, zero Tools-service entries, zero outbound
|
||||
// calls — the admission marker itself is the only increment.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_observer_pre_admission_rejects_never_enter_an_era_adapter_or_the_service() {
|
||||
let harness = Harness::started().await;
|
||||
let session = harness.initialize_legacy_session().await;
|
||||
|
||||
// F7/G6: each reject below is an individual triple — a valid control of the same era, one
|
||||
// one-factor mutation of the chosen field, the reject with its exact marker/store/outbound
|
||||
// deltas, and an immediate valid follow-up with its own scoped output. One shared follow-up at
|
||||
// the end of the test would say nothing about the state a single reject left behind.
|
||||
|
||||
// 1. malformed envelope: a session-bearing valid legacy call with only the envelope version
|
||||
// field mutated, so a zero era/service delta is a property of that one field.
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
11,
|
||||
"control-envelope@example.com",
|
||||
"control before the malformed envelope",
|
||||
)
|
||||
.await;
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let mut malformed_body = legacy_tool_call(12, "envelope@example.com");
|
||||
malformed_body["jsonrpc"] = json!("1.0");
|
||||
let malformed = harness
|
||||
.post(&header_refs(&legacy_headers(&session)), &malformed_body)
|
||||
.await;
|
||||
assert_eq!(
|
||||
malformed.status().as_u16(),
|
||||
400,
|
||||
"a malformed envelope is a rejection"
|
||||
);
|
||||
assert_no_result("malformed envelope", &json_body(malformed).await);
|
||||
assert_deltas(
|
||||
"malformed envelope",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 0, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// F7: a reject before admission must not touch the session store at all — an extra `get` here is
|
||||
// invisible to the markers and to the outbound counter, so it is counted explicitly.
|
||||
assert_session_ops(
|
||||
"malformed envelope",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
13,
|
||||
"follow-up-envelope@example.com",
|
||||
"follow-up after the malformed envelope",
|
||||
)
|
||||
.await;
|
||||
|
||||
// 2. ambiguous session carrier: the same valid legacy call with one conflicting session header.
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
21,
|
||||
"control-ambiguous@example.com",
|
||||
"control before the ambiguous session carrier",
|
||||
)
|
||||
.await;
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let ambiguous = harness
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", LEGACY_REVISION),
|
||||
("MCP-Session-Id", session.as_str()),
|
||||
("MCP-Session-Id", "session-of-another-era"),
|
||||
],
|
||||
&legacy_tool_call(22, "ambiguous@example.com"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
ambiguous.status().as_u16(),
|
||||
400,
|
||||
"an ambiguous carrier is a rejection"
|
||||
);
|
||||
assert_no_result("ambiguous session carrier", &json_body(ambiguous).await);
|
||||
assert_deltas(
|
||||
"ambiguous session carrier",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 0, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
assert_session_ops(
|
||||
"ambiguous session carrier",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
23,
|
||||
"follow-up-ambiguous@example.com",
|
||||
"follow-up after the ambiguous session carrier",
|
||||
)
|
||||
.await;
|
||||
|
||||
// 3. unresolvable identity: the same session-bearing legacy call with a modern `_meta` added, so
|
||||
// the header and the body name two different revisions.
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
31,
|
||||
"control-identity@example.com",
|
||||
"control before the unresolvable identity",
|
||||
)
|
||||
.await;
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let mut unresolvable_body = legacy_tool_call(32, "unresolvable@example.com");
|
||||
unresolvable_body["params"]["_meta"] = modern_meta();
|
||||
let unresolvable = harness
|
||||
.post(&header_refs(&legacy_headers(&session)), &unresolvable_body)
|
||||
.await;
|
||||
assert_eq!(
|
||||
unresolvable.status().as_u16(),
|
||||
400,
|
||||
"an unresolvable identity is a rejection"
|
||||
);
|
||||
assert_no_result("unresolvable identity", &json_body(unresolvable).await);
|
||||
assert_deltas(
|
||||
"unresolvable identity",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 0, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
assert_session_ops(
|
||||
"unresolvable identity",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
33,
|
||||
"follow-up-identity@example.com",
|
||||
"follow-up after the unresolvable identity",
|
||||
)
|
||||
.await;
|
||||
|
||||
// 4. modern carrier conflict: a valid modern call that also carries the legacy session — the same
|
||||
// request with one extra carrier header.
|
||||
run_valid_modern_call(
|
||||
&harness,
|
||||
41,
|
||||
"control-conflict@example.com",
|
||||
"control before the modern carrier conflict",
|
||||
)
|
||||
.await;
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let mut conflicting = modern_headers();
|
||||
conflicting.push(("MCP-Session-Id", session.clone()));
|
||||
let conflict = harness
|
||||
.post(
|
||||
&header_refs(&conflicting),
|
||||
&modern_tool_call(42, "conflict@example.com"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(conflict.status().as_u16(), 400);
|
||||
assert_no_result("modern carrier conflict", &json_body(conflict).await);
|
||||
assert_deltas(
|
||||
"modern carrier conflict",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 0, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
assert_session_ops(
|
||||
"modern carrier conflict",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_modern_call(
|
||||
&harness,
|
||||
43,
|
||||
"follow-up-conflict@example.com",
|
||||
"follow-up after the modern carrier conflict",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// §7.2 in-adapter rejects: exactly the own era-adapter, never the other one, no service entry.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_observer_in_adapter_rejects_enter_exactly_their_own_era_and_no_service() {
|
||||
let harness = Harness::started().await;
|
||||
let session = harness.initialize_legacy_session().await;
|
||||
|
||||
// F7: every in-adapter reject gets its own control → one-factor negative → follow-up triple, so a
|
||||
// reject can never be confused with a broken endpoint and the state after the reject is proven to
|
||||
// serve the very next request.
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
30,
|
||||
"control-legacy@example.com",
|
||||
"control before the legacy reject",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Legacy unknown method: a rejection inside the legacy adapter. The negative is the valid legacy
|
||||
// call body of this era with exactly one factor changed - the method identifier - so the same
|
||||
// `params`/`name`/`arguments` payload is proven not to reach the owning Tools service.
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let mut legacy_unknown_request = legacy_tool_call(31, "unknown-legacy@example.com");
|
||||
legacy_unknown_request["method"] = json!("tools/not-a-method");
|
||||
let legacy_unknown = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(&session)),
|
||||
&legacy_unknown_request,
|
||||
)
|
||||
.await;
|
||||
let legacy_unknown_body = json_body(legacy_unknown).await;
|
||||
assert_eq!(
|
||||
legacy_unknown_body["error"]["code"], -32601,
|
||||
"an unregistered legacy method is an unsupported-method error, got {legacy_unknown_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"legacy unknown method",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// The legacy carrier is still resolved by the admission's revision check (one read), and the
|
||||
// reject neither creates nor mutates a session.
|
||||
assert_session_ops(
|
||||
"legacy unknown method",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 1,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
31,
|
||||
"follow-up-legacy@example.com",
|
||||
"follow-up after the legacy reject",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Modern unknown method: the control is a valid modern call of the same era, the negative is that
|
||||
// same valid call with only the method identifier changed - the body method and its coherent
|
||||
// `Mcp-Method` wire carrier, both denoting the one logical field - and the follow-up is an
|
||||
// independent modern success on a session store that must still be untouched.
|
||||
run_valid_modern_call(
|
||||
&harness,
|
||||
33,
|
||||
"control-modern@example.com",
|
||||
"control before the modern reject",
|
||||
)
|
||||
.await;
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let mut modern_unknown_request = modern_tool_call(34, "unknown-modern@example.com");
|
||||
modern_unknown_request["method"] = json!("tools/not-a-method");
|
||||
let modern_unknown = harness
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "tools/not-a-method"),
|
||||
("Mcp-Name", TOOL_NAME),
|
||||
],
|
||||
&modern_unknown_request,
|
||||
)
|
||||
.await;
|
||||
let modern_unknown_body = json_body(modern_unknown).await;
|
||||
assert_eq!(
|
||||
modern_unknown_body["error"]["code"], -32601,
|
||||
"an unregistered modern method is an unsupported-method error, got {modern_unknown_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"modern unknown method",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 1, 0, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
assert_session_ops(
|
||||
"modern unknown method",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
// The independent modern follow-up after the reject: its own era, its own scoped output, and a
|
||||
// session store that is still untouched.
|
||||
run_valid_modern_call(
|
||||
&harness,
|
||||
35,
|
||||
"follow-up-modern@example.com",
|
||||
"follow-up after the modern reject",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// G2: the registered kind of the two legacy lifecycle operations — an envelope of the wrong kind may
|
||||
// not be served as the other action.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_observer_lifecycle_envelope_kind_cannot_swap_the_two_legacy_actions() {
|
||||
let harness = Harness::started().await;
|
||||
let session = harness.initialize_legacy_session().await;
|
||||
|
||||
// Form 1: `initialize` written as a notification — the valid request control with only its `id`
|
||||
// removed. `initialize` is registered as a request, so this form must neither initialize the live
|
||||
// session nor mint a new one.
|
||||
run_valid_legacy_initialize(&harness, 61, "control initialize request").await;
|
||||
|
||||
let mut initialize_notification = legacy_initialize(62);
|
||||
initialize_notification
|
||||
.as_object_mut()
|
||||
.expect("the initialize request is an object")
|
||||
.remove("id");
|
||||
assert!(initialize_notification.get("id").is_none());
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let notification = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(&session)),
|
||||
&initialize_notification,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
notification.status().as_u16(),
|
||||
202,
|
||||
"an initialize notification is acknowledged, never served as an initialize request"
|
||||
);
|
||||
assert_deltas(
|
||||
"initialize as a notification",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// The admission's revision check reads the carried session once; the wrong-kind form creates no
|
||||
// session and marks none initialized.
|
||||
assert_session_ops(
|
||||
"initialize as a notification",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 1,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
63,
|
||||
"follow-up-initialize-notification@example.com",
|
||||
"follow-up after the initialize notification",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Form 2: `notifications/initialized` written as a request — the valid notification control with
|
||||
// only an `id` added. It must not create a session: the registered kind is a notification.
|
||||
run_valid_initialized_notification(&harness, &session, "control initialized notification")
|
||||
.await;
|
||||
|
||||
let mut initialized_request = initialized_notification();
|
||||
initialized_request["id"] = json!(72);
|
||||
assert!(initialized_request.get("id").is_some());
|
||||
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let request = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(&session)),
|
||||
&initialized_request,
|
||||
)
|
||||
.await;
|
||||
let request_body = json_body(request).await;
|
||||
assert_eq!(
|
||||
request_body["error"]["code"], -32601,
|
||||
"a request-shaped initialized notification is an unsupported method, got {request_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"initialized as a request",
|
||||
before,
|
||||
harness.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
assert_session_ops(
|
||||
"initialized as a request",
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 1,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
73,
|
||||
"follow-up-initialized-request@example.com",
|
||||
"follow-up after the initialized request",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// §7.2 valid calls: the own era-adapter, the owning Tools service and exactly one outbound call per
|
||||
// call, with scoped outputs.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_observer_valid_calls_enter_the_own_era_and_the_owning_tools_service() {
|
||||
let harness = Harness::started().await;
|
||||
let session = harness.initialize_legacy_session().await;
|
||||
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
41,
|
||||
"legacy@example.com",
|
||||
"valid legacy tools/call",
|
||||
)
|
||||
.await;
|
||||
run_valid_modern_call(
|
||||
&harness,
|
||||
42,
|
||||
"modern@example.com",
|
||||
"valid modern tools/call",
|
||||
)
|
||||
.await;
|
||||
|
||||
// The legacy session never served the modern call: the legacy follow-up still works, with its own
|
||||
// scoped output, and the modern call did not consume it.
|
||||
run_valid_legacy_call(
|
||||
&harness,
|
||||
&session,
|
||||
43,
|
||||
"legacy-after-modern@example.com",
|
||||
"legacy follow-up after the modern call",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// F5: the registration drives the *real* endpoint. One private inert method descriptor is added to a
|
||||
// copy of the production tables and served with this router; removing it again restores the rejection.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_observer_registration_add_remove_changes_the_real_endpoint_dispatch() {
|
||||
// "Removed": the inert method is not registered, so both eras answer the era-correct -32601 and
|
||||
// nothing enters an era handler beyond the rejection, the service or the upstream.
|
||||
let without =
|
||||
Harness::started_with_registration(Some(Arc::new(registration_without_inert_method())))
|
||||
.await;
|
||||
let session = without.initialize_legacy_session().await;
|
||||
|
||||
let before = without.snapshot();
|
||||
let arrivals = without.upstream_calls();
|
||||
let unregistered = without
|
||||
.post(
|
||||
&header_refs(&legacy_headers(&session)),
|
||||
&json!({ "jsonrpc": "2.0", "id": 51, "method": INERT_METHOD_NAME, "params": {} }),
|
||||
)
|
||||
.await;
|
||||
let unregistered_body = json_body(unregistered).await;
|
||||
assert_eq!(
|
||||
unregistered_body["error"]["code"], -32601,
|
||||
"an unregistered method must stay unsupported, got {unregistered_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"inert method without a registration (legacy)",
|
||||
before,
|
||||
without.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_eq!(without.upstream_calls(), arrivals);
|
||||
|
||||
let before = without.snapshot();
|
||||
let unregistered_modern = without
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", INERT_METHOD_NAME),
|
||||
("Mcp-Name", TOOL_NAME),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 52,
|
||||
"method": INERT_METHOD_NAME,
|
||||
"params": { "_meta": modern_meta() }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
json_body(unregistered_modern).await["error"]["code"],
|
||||
-32601,
|
||||
"an unregistered modern method must stay unsupported"
|
||||
);
|
||||
assert_deltas(
|
||||
"inert method without a registration (modern)",
|
||||
before,
|
||||
without.snapshot(),
|
||||
Snapshot::new(1, 1, 0, 0),
|
||||
);
|
||||
|
||||
// "Added": the very same request now reaches the handler the registration maps it to — in both
|
||||
// eras, through the real router, with no change to the production tables.
|
||||
let with =
|
||||
Harness::started_with_registration(Some(Arc::new(registration_with_inert_method()))).await;
|
||||
let session = with.initialize_legacy_session().await;
|
||||
|
||||
let before = with.snapshot();
|
||||
let arrivals = with.upstream_calls();
|
||||
let dispatched = with
|
||||
.post(
|
||||
&header_refs(&legacy_headers(&session)),
|
||||
&json!({ "jsonrpc": "2.0", "id": 53, "method": INERT_METHOD_NAME, "params": {} }),
|
||||
)
|
||||
.await;
|
||||
let dispatched_body = json_body(dispatched).await;
|
||||
assert_eq!(
|
||||
dispatched_body["result"]["protocolVersion"], LEGACY_REVISION,
|
||||
"the registered method must reach its registered handler (legacy), got {dispatched_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"inert method with a registration (legacy)",
|
||||
before,
|
||||
with.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_eq!(
|
||||
with.upstream_calls(),
|
||||
arrivals,
|
||||
"the inert handler is not the Tools service: no outbound call is made"
|
||||
);
|
||||
|
||||
let before = with.snapshot();
|
||||
let dispatched_modern = with
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", INERT_METHOD_NAME),
|
||||
("Mcp-Name", TOOL_NAME),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 54,
|
||||
"method": INERT_METHOD_NAME,
|
||||
"params": { "_meta": modern_meta() }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let dispatched_modern_body = json_body(dispatched_modern).await;
|
||||
assert_eq!(
|
||||
dispatched_modern_body["result"]["protocolVersion"], MODERN_REVISION,
|
||||
"the registered method must reach its registered handler (modern), got {dispatched_modern_body}"
|
||||
);
|
||||
assert_deltas(
|
||||
"inert method with a registration (modern)",
|
||||
before,
|
||||
with.snapshot(),
|
||||
Snapshot::new(1, 1, 0, 0),
|
||||
);
|
||||
|
||||
// The advertisement moves with the same registration snapshot: the inert capability is declared
|
||||
// by the observed registration and appears in the modern discovery result it serves.
|
||||
let discover = with
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "server/discover"),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 55,
|
||||
"method": "server/discover",
|
||||
"params": { "_meta": modern_meta() }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let discover_body = json_body(discover).await;
|
||||
assert_eq!(
|
||||
discover_body["result"]["capabilities"]["inert_test_capability"]["enabled"], true,
|
||||
"the observed registration owns the advertisement too, got {discover_body}"
|
||||
);
|
||||
|
||||
let discover_without = without
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "server/discover"),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 56,
|
||||
"method": "server/discover",
|
||||
"params": { "_meta": modern_meta() }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
json_body(discover_without).await["result"]["capabilities"]
|
||||
.get("inert_test_capability")
|
||||
.is_none(),
|
||||
"a capability that is not registered in this snapshot must not be advertised"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,962 @@
|
||||
//! Fixtures and helpers of the in-crate section 7.2 test seam (`app::dispatch_observer`).
|
||||
//!
|
||||
//! This file is the `support` child module of `crate::app::dispatch_observer` (wired with `#[path]`
|
||||
//! there). It holds everything the observed tests need but no test itself: the real router harness,
|
||||
//! the counted session store, the counted loopback upstream, the registry/operation/agent fixtures
|
||||
//! and the shared assertions. It lives one directory above `src/app/` for the same reason the
|
||||
//! `tests` module does — `scripts/check-execution-boundaries.py` reserves that prefix for service
|
||||
//! modules without an HTTP client or a persistence dependency. Everything here is `#[cfg(test)]`.
|
||||
|
||||
//! Behavioural harness of the BUILD-internal semantic observer (Story 3.1 section 7.2).
|
||||
//!
|
||||
//! This file is the `tests` child module of `crate::app::dispatch_observer` (wired with `#[path]`
|
||||
//! there), so the module path — and therefore the sanctioned selector
|
||||
//! `cargo test -p crank-community-mcp --lib app::dispatch_observer::` — is unchanged. It is not a
|
||||
//! separate crate target and it is `#[cfg(test)]`-only.
|
||||
//!
|
||||
//! Why the file is not under `src/app/`: `scripts/check-execution-boundaries.py` treats the whole
|
||||
//! `crates/crank-community-mcp/src/app/` prefix as service-module scope and forbids an HTTP-client
|
||||
//! (`reqwest`) or persistence (`sqlx`/migration) dependency there. This harness needs both — a real
|
||||
//! PostgreSQL schema through `crank_test_support::postgres_schema_url` and a real request through the
|
||||
//! served router — so the harness sits one directory above the scoped prefix while the observer
|
||||
//! itself (markers, scope, counters, no dependency) stays at the approved `src/app/` path.
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use axum::{Json, Router, extract::State, http::header, routing::post};
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ExecutionConfig, HttpMethod,
|
||||
Operation, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyKind,
|
||||
PlatformApiKeyScope, PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolDescription,
|
||||
ToolSelectionPolicy, WorkspaceId,
|
||||
};
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_registry::{
|
||||
CreateAgentRequest, CreatePlatformApiKeyRequest, PostgresRegistry, PublishAgentRequest,
|
||||
PublishRequest,
|
||||
};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
use crank_schema::{Schema, SchemaKind};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
use super::{observe, observe_with_registration};
|
||||
use crate::{
|
||||
auth::CommunityMachineCredentialVerifier,
|
||||
build_app,
|
||||
protocol::{
|
||||
CAPABILITY_DESCRIPTORS, CapabilityId, CapabilityIdDescriptor, CapabilityRegistry,
|
||||
FeatureSet, HeaderSet, Kind, METHOD_DESCRIPTORS, MethodDescriptor, MethodHandler, Roster,
|
||||
},
|
||||
session::{InMemorySessionStore, SessionState, SessionStoreError, TransportSessionStore},
|
||||
};
|
||||
|
||||
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
|
||||
pub(super) const MODERN_REVISION: &str = "2026-07-28";
|
||||
pub(super) const TOOL_NAME: &str = "create_lead";
|
||||
pub(super) const WORKSPACE_SLUG: &str = "default";
|
||||
pub(super) const AGENT_SLUG: &str = "dispatch-observer";
|
||||
pub(super) const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
pub(super) const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
pub(super) const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
|
||||
|
||||
/// One observed endpoint: the real router, the observer that counts its own requests and the counted
|
||||
/// loopback upstream that every real tool execution must reach.
|
||||
pub(super) struct Harness {
|
||||
client: reqwest::Client,
|
||||
mcp_url: String,
|
||||
api_key: String,
|
||||
counters: Arc<CounterSet>,
|
||||
session_counters: Arc<SessionCounters>,
|
||||
upstream_calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
pub(super) struct Upstream {
|
||||
base_url: String,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
/// The session-store operations of the observed requests (section 7.2 honest naming: these count
|
||||
/// *session-store operations*, never dispatch, era or service entries).
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct SessionCounters {
|
||||
get: AtomicUsize,
|
||||
create: AtomicUsize,
|
||||
mark_initialized: AtomicUsize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct SessionOps {
|
||||
pub(super) get: usize,
|
||||
pub(super) create: usize,
|
||||
pub(super) mark_initialized: usize,
|
||||
}
|
||||
|
||||
impl SessionCounters {
|
||||
pub(super) fn snapshot(&self) -> SessionOps {
|
||||
SessionOps {
|
||||
get: self.get.load(Ordering::SeqCst),
|
||||
create: self.create.load(Ordering::SeqCst),
|
||||
mark_initialized: self.mark_initialized.load(Ordering::SeqCst),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The observed session store: one real `InMemorySessionStore` plus per-operation counters, so a
|
||||
/// request that touches the session store before (or instead of) the expected path is visible.
|
||||
#[derive(Default)]
|
||||
pub(super) struct CountedSessionStore {
|
||||
inner: InMemorySessionStore,
|
||||
counters: Arc<SessionCounters>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TransportSessionStore for CountedSessionStore {
|
||||
async fn create(
|
||||
&self,
|
||||
protocol_version: &str,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
supports_elicitation: bool,
|
||||
now: OffsetDateTime,
|
||||
expires_at: Option<OffsetDateTime>,
|
||||
) -> Result<String, SessionStoreError> {
|
||||
self.counters.create.fetch_add(1, Ordering::SeqCst);
|
||||
self.inner
|
||||
.create(
|
||||
protocol_version,
|
||||
workspace_slug,
|
||||
agent_slug,
|
||||
supports_elicitation,
|
||||
now,
|
||||
expires_at,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get(&self, session_id: &str) -> Result<Option<SessionState>, SessionStoreError> {
|
||||
self.counters.get.fetch_add(1, Ordering::SeqCst);
|
||||
self.inner.get(session_id).await
|
||||
}
|
||||
|
||||
async fn mark_initialized(
|
||||
&self,
|
||||
session_id: &str,
|
||||
now: OffsetDateTime,
|
||||
) -> Result<bool, SessionStoreError> {
|
||||
self.counters
|
||||
.mark_initialized
|
||||
.fetch_add(1, Ordering::SeqCst);
|
||||
self.inner.mark_initialized(session_id, now).await
|
||||
}
|
||||
|
||||
async fn delete(&self, session_id: &str) -> Result<bool, SessionStoreError> {
|
||||
self.inner.delete(session_id).await
|
||||
}
|
||||
|
||||
async fn cleanup_expired(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.cleanup_expired(now).await
|
||||
}
|
||||
|
||||
async fn active_count(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.active_count(now).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
pub(super) async fn started() -> Self {
|
||||
Self::started_with_registration(None).await
|
||||
}
|
||||
|
||||
/// One observed endpoint, optionally served with an explicit registration snapshot (F5: the
|
||||
/// add/remove proof runs against this real router, not against a registry unit query).
|
||||
pub(super) async fn started_with_registration(
|
||||
registration: Option<Arc<CapabilityRegistry>>,
|
||||
) -> Self {
|
||||
let registry = test_registry().await;
|
||||
let upstream = spawn_counted_upstream().await;
|
||||
let operation = test_operation(&upstream.base_url);
|
||||
let workspace_id = workspace_id();
|
||||
registry
|
||||
.create_operation(&workspace_id, &operation, Some("alice"))
|
||||
.await
|
||||
.expect("the operation must be created");
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id,
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.expect("the operation must be published");
|
||||
publish_agent(®istry, &operation).await;
|
||||
let api_key = create_api_key(®istry).await;
|
||||
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let session_counters = Arc::new(SessionCounters::default());
|
||||
let sessions = Arc::new(CountedSessionStore {
|
||||
inner: InMemorySessionStore::default(),
|
||||
counters: Arc::clone(&session_counters),
|
||||
});
|
||||
let app = observe_requests(
|
||||
build_app(
|
||||
registry,
|
||||
Duration::from_millis(0),
|
||||
Some("https://crank.example.com".to_owned()),
|
||||
SecretCrypto::new("test-master-key-00000000000000000000000000000000")
|
||||
.expect("a valid test master key"),
|
||||
crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build(),
|
||||
RequestRateLimiter::new(
|
||||
RequestRateLimitConfig::new(10_000, 10_000).expect("a valid rate limit"),
|
||||
),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
sessions,
|
||||
Arc::new(CommunityMachineCredentialVerifier),
|
||||
),
|
||||
Arc::clone(&counters),
|
||||
registration,
|
||||
);
|
||||
let base_url = spawn_server(app).await;
|
||||
|
||||
Self {
|
||||
client: reqwest::Client::new(),
|
||||
mcp_url: format!("{base_url}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}"),
|
||||
api_key,
|
||||
counters,
|
||||
session_counters,
|
||||
upstream_calls: upstream.calls,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn snapshot(&self) -> Snapshot {
|
||||
self.counters.snapshot()
|
||||
}
|
||||
|
||||
pub(super) fn session_ops(&self) -> SessionOps {
|
||||
self.session_counters.snapshot()
|
||||
}
|
||||
|
||||
pub(super) fn upstream_calls(&self) -> usize {
|
||||
self.upstream_calls.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(super) async fn post(&self, headers: &[(&str, &str)], body: &Value) -> reqwest::Response {
|
||||
let mut request = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key));
|
||||
for (name, value) in headers {
|
||||
request = request.header(*name, *value);
|
||||
}
|
||||
request
|
||||
.json(body)
|
||||
.send()
|
||||
.await
|
||||
.expect("the observed request must complete")
|
||||
}
|
||||
|
||||
/// A legacy session, primed through the real lifecycle methods.
|
||||
pub(super) async fn initialize_legacy_session(&self) -> String {
|
||||
let response = self
|
||||
.post(
|
||||
&[("MCP-Protocol-Version", LEGACY_REVISION)],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"the legacy initialize must succeed"
|
||||
);
|
||||
let session_id = response
|
||||
.headers()
|
||||
.get("MCP-Session-Id")
|
||||
.expect("initialize must mint a session")
|
||||
.to_str()
|
||||
.expect("the session id must be a header string")
|
||||
.to_owned();
|
||||
|
||||
let initialized = self
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", LEGACY_REVISION),
|
||||
("MCP-Session-Id", session_id.as_str()),
|
||||
],
|
||||
&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/initialized",
|
||||
"params": {}
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
initialized.status().as_u16(),
|
||||
202,
|
||||
"the initialized notification must be acknowledged"
|
||||
);
|
||||
session_id
|
||||
}
|
||||
}
|
||||
|
||||
/// Install the request-scoped observer (and, when given, the F5 registration snapshot) around every
|
||||
/// request of this router.
|
||||
///
|
||||
/// The layer runs inside the request task and awaits the inner service, so the markers deep in the
|
||||
/// handler see exactly this request's counters and the dispatch asks exactly this request's
|
||||
/// registration. Nothing global is mutated.
|
||||
pub(super) fn observe_requests(
|
||||
app: Router,
|
||||
counters: Arc<CounterSet>,
|
||||
registration: Option<Arc<CapabilityRegistry>>,
|
||||
) -> Router {
|
||||
app.layer(axum::middleware::from_fn(
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let counters = Arc::clone(&counters);
|
||||
let registration = registration.clone();
|
||||
async move {
|
||||
match registration {
|
||||
Some(registration) => {
|
||||
observe_with_registration(
|
||||
registration,
|
||||
observe(counters, next.run(request)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
None => observe(counters, next.run(request)).await,
|
||||
}
|
||||
}
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn spawn_server(app: Router) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("a loopback listener must bind");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.expect("a bound listener has an address");
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
format!("http://{address}")
|
||||
}
|
||||
|
||||
/// The counted loopback upstream: every arrival is one real outbound tool execution.
|
||||
pub(super) async fn spawn_counted_upstream() -> Upstream {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let state = Arc::clone(&calls);
|
||||
let app = Router::new()
|
||||
.route("/crm/leads", post(create_lead))
|
||||
.with_state(state);
|
||||
Upstream {
|
||||
base_url: spawn_server(app).await,
|
||||
calls,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn create_lead(
|
||||
State(calls): State<Arc<AtomicUsize>>,
|
||||
Json(payload): Json<Value>,
|
||||
) -> Json<Value> {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
// The fixture echoes the request's own payload in its identifier, so every valid call has a
|
||||
// *distinguishable* scoped output: two valid calls can never be confused with one another
|
||||
// (section 7.2 requires a scoped output per case, not one shared constant).
|
||||
let email = payload["email"].as_str().unwrap_or("unknown").to_owned();
|
||||
Json(json!({ "id": format!("lead_for_{email}"), "email": payload["email"] }))
|
||||
}
|
||||
|
||||
pub(super) async fn test_registry() -> PostgresRegistry {
|
||||
let database_url = crank_test_support::postgres_schema_url("crank_dispatch_observer").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url)
|
||||
.await
|
||||
.expect("the test PostgreSQL must accept connections");
|
||||
crank_registry::MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("the migrations must apply");
|
||||
PostgresRegistry::connect(&database_url)
|
||||
.await
|
||||
.expect("the registry must connect")
|
||||
}
|
||||
|
||||
pub(super) fn test_time() -> OffsetDateTime {
|
||||
OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).expect("a pinned timestamp")
|
||||
}
|
||||
|
||||
pub(super) fn workspace_id() -> WorkspaceId {
|
||||
WorkspaceId::new("ws_default")
|
||||
}
|
||||
|
||||
pub(super) fn agent_id() -> AgentId {
|
||||
AgentId::new(format!("agent_{AGENT_SLUG}"))
|
||||
}
|
||||
|
||||
pub(super) async fn publish_agent(
|
||||
registry: &PostgresRegistry,
|
||||
operation: &Operation<Schema, MappingSet>,
|
||||
) {
|
||||
let agent = Agent {
|
||||
id: agent_id(),
|
||||
workspace_id: workspace_id(),
|
||||
slug: AGENT_SLUG.to_owned(),
|
||||
display_name: "Dispatch observer agent".to_owned(),
|
||||
description: "Curated MCP toolset".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: test_time(),
|
||||
updated_at: test_time(),
|
||||
published_at: None,
|
||||
};
|
||||
let version = AgentVersion {
|
||||
agent_id: agent_id(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: test_time(),
|
||||
};
|
||||
let bindings = vec![AgentOperationBinding {
|
||||
operation_id: operation.id.clone(),
|
||||
operation_version: 1,
|
||||
tool_name: operation.name.clone(),
|
||||
tool_title: operation.tool_description.title.clone(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
}];
|
||||
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &agent,
|
||||
version: &version,
|
||||
bindings: &bindings,
|
||||
})
|
||||
.await
|
||||
.expect("the agent must be created");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the agent must be published");
|
||||
}
|
||||
|
||||
pub(super) async fn create_api_key(registry: &PostgresRegistry) -> String {
|
||||
let secret = format!("crk_dispatch_observer_{}", uuid::Uuid::now_v7().simple());
|
||||
let api_key = PlatformApiKey {
|
||||
id: PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
workspace_id: workspace_id(),
|
||||
agent_id: Some(agent_id()),
|
||||
key_kind: PlatformApiKeyKind::McpClient,
|
||||
name: "dispatch-observer".to_owned(),
|
||||
prefix: secret.chars().take(16).collect(),
|
||||
scopes: vec![PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
status: PlatformApiKeyStatus::Active,
|
||||
created_at: test_time(),
|
||||
last_used_at: None,
|
||||
expires_at: None,
|
||||
allowed_origins: Vec::new(),
|
||||
};
|
||||
registry
|
||||
.create_platform_api_key(CreatePlatformApiKeyRequest {
|
||||
api_key: &api_key,
|
||||
secret_hash: &hash_access_secret(&secret),
|
||||
})
|
||||
.await
|
||||
.expect("the API key must be created");
|
||||
secret
|
||||
}
|
||||
|
||||
pub(super) fn hash_access_secret(secret: &str) -> String {
|
||||
URL_SAFE_NO_PAD.encode(Sha256::digest(secret.as_bytes()))
|
||||
}
|
||||
|
||||
pub(super) fn test_operation(base_url: &str) -> Operation<Schema, MappingSet> {
|
||||
Operation {
|
||||
id: OperationId::new(format!("op_{TOOL_NAME}")),
|
||||
name: TOOL_NAME.to_owned(),
|
||||
display_name: "Create Lead".to_owned(),
|
||||
category: "sales".to_owned(),
|
||||
protocol: Protocol::Rest,
|
||||
security_level: crank_core::OperationSecurityLevel::Standard,
|
||||
status: OperationStatus::Published,
|
||||
version: 1,
|
||||
target: Target::Rest(RestTarget {
|
||||
base_url: base_url.to_owned(),
|
||||
method: HttpMethod::Post,
|
||||
path_template: "/crm/leads".to_owned(),
|
||||
static_headers: BTreeMap::new(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: BTreeMap::new(),
|
||||
}),
|
||||
input_schema: object_schema("email"),
|
||||
output_schema: object_schema("id"),
|
||||
input_mapping: MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.mcp.email".to_owned(),
|
||||
target: "$.request.body.email".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
},
|
||||
output_mapping: MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.response.body.id".to_owned(),
|
||||
target: "$.output.id".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
},
|
||||
execution_config: ExecutionConfig {
|
||||
timeout_ms: 1_000,
|
||||
retry_policy: None,
|
||||
response_cache: None,
|
||||
idempotency: None,
|
||||
safety: None,
|
||||
approval_policy: None,
|
||||
auth_profile_ref: None,
|
||||
headers: BTreeMap::new(),
|
||||
},
|
||||
tool_description: ToolDescription {
|
||||
title: "Create Lead".to_owned(),
|
||||
description: "Creates a CRM lead".to_owned(),
|
||||
tags: Vec::new(),
|
||||
examples: Vec::new(),
|
||||
},
|
||||
samples: None,
|
||||
generated_draft: None,
|
||||
config_export: None,
|
||||
wizard_state: None,
|
||||
created_at: test_time(),
|
||||
updated_at: test_time(),
|
||||
published_at: Some(test_time()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn object_schema(field_name: &str) -> Schema {
|
||||
Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: None,
|
||||
description: None,
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::from([(
|
||||
field_name.to_owned(),
|
||||
Schema {
|
||||
kind: SchemaKind::String,
|
||||
format: None,
|
||||
description: None,
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
},
|
||||
)]),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn modern_meta() -> Value {
|
||||
json!({
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: { "name": "crank-dispatch-observer", "version": "0.1.0" }
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn legacy_tool_call(id: u64, email: &str) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": "tools/call",
|
||||
"params": { "name": TOOL_NAME, "arguments": { "email": email } }
|
||||
})
|
||||
}
|
||||
|
||||
/// One legacy `initialize` request body (the valid request form of the lifecycle operation).
|
||||
pub(super) fn legacy_initialize(id: u64) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": "initialize",
|
||||
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
|
||||
})
|
||||
}
|
||||
|
||||
/// One legacy `notifications/initialized` notification body (the valid notification form).
|
||||
///
|
||||
/// The `params` carry a valid `InitializeParams` payload so that the *only* difference from its
|
||||
/// request-shaped negative is the presence of `id`: a wire name must never be served as the other
|
||||
/// lifecycle action because of the envelope kind (G2).
|
||||
pub(super) fn initialized_notification() -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/initialized",
|
||||
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn modern_tool_call(id: u64, email: &str) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"_meta": modern_meta(),
|
||||
"name": TOOL_NAME,
|
||||
"arguments": { "email": email }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn legacy_headers(session_id: &str) -> Vec<(&'static str, String)> {
|
||||
vec![
|
||||
("MCP-Protocol-Version", LEGACY_REVISION.to_owned()),
|
||||
("MCP-Session-Id", session_id.to_owned()),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn modern_headers() -> Vec<(&'static str, String)> {
|
||||
vec![
|
||||
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
|
||||
("Mcp-Method", "tools/call".to_owned()),
|
||||
("Mcp-Name", TOOL_NAME.to_owned()),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn header_refs<'a>(
|
||||
headers: &'a [(&'static str, String)],
|
||||
) -> Vec<(&'static str, &'a str)> {
|
||||
headers
|
||||
.iter()
|
||||
.map(|(name, value)| (*name, value.as_str()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) async fn json_body(response: reqwest::Response) -> Value {
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.expect("the observed response body must be readable");
|
||||
serde_json::from_str(&body).unwrap_or_else(|error| {
|
||||
panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}")
|
||||
})
|
||||
}
|
||||
|
||||
/// Compare the marker deltas of one observed request with the section 7.2 table row.
|
||||
pub(super) fn assert_deltas(case: &str, before: Snapshot, after: Snapshot, expected: Snapshot) {
|
||||
let actual = Snapshot::new(
|
||||
after.admission - before.admission,
|
||||
after.era_modern - before.era_modern,
|
||||
after.era_legacy - before.era_legacy,
|
||||
after.tools_service - before.tools_service,
|
||||
);
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"{case}: admission/era-modern/era-legacy/tools-service deltas must be \
|
||||
(admission, era_modern, era_legacy, tools_service) = {expected:?}, got {actual:?}"
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn assert_no_result(case: &str, body: &Value) {
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"{case}: a rejected request must not return a result, got {body}"
|
||||
);
|
||||
assert!(
|
||||
!body["error"].is_null(),
|
||||
"{case}: a rejected request must return a JSON-RPC error, got {body}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Compare the session-store operation deltas of one observed request.
|
||||
///
|
||||
/// Section 7.2 honest naming: these counters count *session-store operations* (`get`/`create`/
|
||||
/// `mark_initialized`), never dispatch, era-adapter or service entries — an in-service branch can
|
||||
/// reject before any outbound call, so no conclusion about a service entry is drawn from them.
|
||||
pub(super) fn assert_session_ops(
|
||||
case: &str,
|
||||
before: SessionOps,
|
||||
after: SessionOps,
|
||||
expected: SessionOps,
|
||||
) {
|
||||
let actual = SessionOps {
|
||||
get: after.get - before.get,
|
||||
create: after.create - before.create,
|
||||
mark_initialized: after.mark_initialized - before.mark_initialized,
|
||||
};
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"{case}: session-store operation deltas (get, create, mark_initialized) must be {expected:?}, \
|
||||
got {actual:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The scoped output of one valid call: the fixture echoes the request's own payload.
|
||||
pub(super) fn assert_scoped_output(case: &str, body: &Value, email: &str) {
|
||||
assert_eq!(
|
||||
body["result"]["structuredContent"]["id"],
|
||||
format!("lead_for_{email}"),
|
||||
"{case}: the valid call must return *its own* scoped output, got {body}"
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid legacy `tools/call`: its own era-adapter, the owning Tools service, exactly one outbound
|
||||
/// call, the request's own scoped output and the admission's session reads.
|
||||
pub(super) async fn run_valid_legacy_call(
|
||||
harness: &Harness,
|
||||
session: &str,
|
||||
id: u64,
|
||||
email: &str,
|
||||
case: &str,
|
||||
) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(session)),
|
||||
&legacy_tool_call(id, email),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"{case}: a valid legacy call must be served"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_scoped_output(case, &body, email);
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 0, 1, 1));
|
||||
assert_eq!(
|
||||
harness.upstream_calls() - arrivals,
|
||||
1,
|
||||
"{case}: a valid call makes exactly one outbound call"
|
||||
);
|
||||
// A legacy request that carries a session is read by the admission (revision check) and again by
|
||||
// the adapter's session requirement: two reads, no creation and no mutation of the session.
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 2,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid legacy `initialize` request: mints its own session, enters its own era-adapter, never
|
||||
/// touches the Tools service and makes no outbound call (the request-form control of G2).
|
||||
pub(super) async fn run_valid_legacy_initialize(harness: &Harness, id: u64, case: &str) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&[("MCP-Protocol-Version", LEGACY_REVISION)],
|
||||
&legacy_initialize(id),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"{case}: a valid legacy initialize must be served"
|
||||
);
|
||||
let session_id = response
|
||||
.headers()
|
||||
.get("MCP-Session-Id")
|
||||
.expect("a valid initialize must mint a session")
|
||||
.to_str()
|
||||
.expect("the session id must be a header string")
|
||||
.to_owned();
|
||||
assert!(
|
||||
!session_id.is_empty(),
|
||||
"{case}: the minted session id must not be empty"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(
|
||||
body["result"]["protocolVersion"], LEGACY_REVISION,
|
||||
"{case}: the initialize result must name the negotiated revision, got {body}"
|
||||
);
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 0, 1, 0));
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// The initialize request itself carries no session carrier, so the admission never reads the
|
||||
// store: the one operation is the session creation of the lifecycle handler.
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 1,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid legacy `notifications/initialized` on an existing session: acknowledged, its own
|
||||
/// era-adapter, no Tools service, no outbound call, exactly one session initialization (G2 control).
|
||||
pub(super) async fn run_valid_initialized_notification(
|
||||
harness: &Harness,
|
||||
session: &str,
|
||||
case: &str,
|
||||
) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&header_refs(&legacy_headers(session)),
|
||||
&initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
202,
|
||||
"{case}: the initialized notification must be acknowledged"
|
||||
);
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 0, 1, 0));
|
||||
assert_eq!(harness.upstream_calls(), arrivals);
|
||||
// The admission's revision check reads the carried session, and the lifecycle handler reads it
|
||||
// once more before marking it initialized.
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 2,
|
||||
create: 0,
|
||||
mark_initialized: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// One valid modern `tools/call`: its own era-adapter, the owning Tools service, exactly one outbound
|
||||
/// call, its own scoped output and *no* session-store operation at all (the modern era is stateless).
|
||||
pub(super) async fn run_valid_modern_call(harness: &Harness, id: u64, email: &str, case: &str) {
|
||||
let before = harness.snapshot();
|
||||
let ops_before = harness.session_ops();
|
||||
let arrivals = harness.upstream_calls();
|
||||
let response = harness
|
||||
.post(
|
||||
&header_refs(&modern_headers()),
|
||||
&modern_tool_call(id, email),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status().as_u16(),
|
||||
200,
|
||||
"{case}: a valid modern call must be served"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
assert_scoped_output(case, &body, email);
|
||||
assert_eq!(body["result"]["resultType"], "complete");
|
||||
assert_deltas(case, before, harness.snapshot(), Snapshot::new(1, 1, 0, 1));
|
||||
assert_eq!(
|
||||
harness.upstream_calls() - arrivals,
|
||||
1,
|
||||
"{case}: a valid call makes exactly one outbound call"
|
||||
);
|
||||
assert_session_ops(
|
||||
case,
|
||||
ops_before,
|
||||
harness.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The inert private registration used by the F5 add/remove proof (never registered in production).
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// The inert private capability and method used only by the F5 proof (never registered in production).
|
||||
pub(super) fn inert_registration_extra() -> (CapabilityIdDescriptor, MethodDescriptor) {
|
||||
(
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_test_capability", &[("enabled", true)])),
|
||||
revisions: &[MODERN_REVISION, LEGACY_REVISION],
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: INERT_METHOD_NAME,
|
||||
capability: CapabilityId::InertTest,
|
||||
kind: Kind::Method,
|
||||
required_headers: HeaderSet(&[]),
|
||||
handler: MethodHandler::Ping,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) const INERT_METHOD_NAME: &str = "inert/echo";
|
||||
|
||||
/// See [`inert_registration_extra`]: the "remove" case is the production registration itself (no inert
|
||||
/// capability, no inert method); the "add" case is the same tables plus the inert descriptor pair.
|
||||
pub(super) fn registration_without_inert_method() -> CapabilityRegistry {
|
||||
CapabilityRegistry::new(CAPABILITY_DESCRIPTORS, METHOD_DESCRIPTORS)
|
||||
.expect("the production tables are a valid registration")
|
||||
}
|
||||
|
||||
pub(super) fn registration_with_inert_method() -> CapabilityRegistry {
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(inert_registration_extra().0);
|
||||
let mut methods = METHOD_DESCRIPTORS.to_vec();
|
||||
methods.push(inert_registration_extra().1);
|
||||
CapabilityRegistry::new(&capabilities, &methods)
|
||||
.expect("the inert method descriptor is a valid registration")
|
||||
}
|
||||
|
||||
// Re-exported for the sibling `tests` module.
|
||||
pub(super) use super::{CounterSet, Snapshot};
|
||||
@@ -1,12 +1,36 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub const CURRENT_PROTOCOL_VERSION: &str = "2025-11-25";
|
||||
pub const DEFAULT_PROTOCOL_VERSION: &str = "2025-03-26";
|
||||
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &[
|
||||
DEFAULT_PROTOCOL_VERSION,
|
||||
"2025-06-18",
|
||||
CURRENT_PROTOCOL_VERSION,
|
||||
];
|
||||
/// The two approved MCP revisions (`docs/`-approved window of 2026-10-11).
|
||||
pub const MODERN_PROTOCOL_VERSION: &str = "2026-07-28";
|
||||
pub const LEGACY_PROTOCOL_VERSION: &str = "2025-11-25";
|
||||
|
||||
/// Revisions that stay in the code base but are no longer advertised or served.
|
||||
pub const WITHDRAWN_PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26"];
|
||||
|
||||
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] =
|
||||
&[MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION];
|
||||
|
||||
/// Backwards-compatible name for the legacy session revision, kept because existing in-crate tests
|
||||
/// and call sites refer to it. It is *not* an implicit default for an unidentified request.
|
||||
pub const CURRENT_PROTOCOL_VERSION: &str = LEGACY_PROTOCOL_VERSION;
|
||||
|
||||
/// Request `_meta` keys used by the modern stateless era.
|
||||
pub const META_PROTOCOL_VERSION_KEY: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
pub const META_CLIENT_CAPABILITIES_KEY: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
pub const META_CLIENT_INFO_KEY: &str = "io.modelcontextprotocol/clientInfo";
|
||||
/// `_meta` key of the per-request log level (Story 3.18). SEP-2577 replaces the former
|
||||
/// `logging/setLevel` request of the legacy era with this per-request opt-in.
|
||||
pub const META_LOG_LEVEL_KEY: &str = "io.modelcontextprotocol/logLevel";
|
||||
|
||||
/// Result `_meta` key carrying the self-reported server identity (pinned `DiscoverResult`).
|
||||
pub const META_SERVER_INFO_KEY: &str = "io.modelcontextprotocol/serverInfo";
|
||||
|
||||
/// JSON-RPC error codes of the pinned modern revision.
|
||||
pub const HEADER_MISMATCH_ERROR_CODE: i64 = -32020;
|
||||
pub const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE: i64 = -32022;
|
||||
|
||||
/// Header name carrying the negotiated revision on HTTP requests.
|
||||
pub const HEADER_PROTOCOL_VERSION_NAME: &str = "MCP-Protocol-Version";
|
||||
|
||||
pub fn request_id(message: &Value) -> Value {
|
||||
message.get("id").cloned().unwrap_or(Value::Null)
|
||||
|
||||
@@ -6,13 +6,16 @@ pub mod auth;
|
||||
pub mod catalog;
|
||||
pub mod jsonrpc;
|
||||
pub mod manifest;
|
||||
mod protocol;
|
||||
mod rate_limit;
|
||||
mod request_context;
|
||||
pub mod resource_wire;
|
||||
pub mod session;
|
||||
pub mod tool_error;
|
||||
mod tool_search;
|
||||
mod transport;
|
||||
|
||||
pub use app::{
|
||||
build_app, build_app_with_background_workers, build_app_with_background_workers_and_limits,
|
||||
build_app, build_app_with_artifacts, build_app_with_background_workers,
|
||||
build_app_with_background_workers_and_limits,
|
||||
};
|
||||
@@ -0,0 +1,562 @@
|
||||
//! Narrow shared Tools-service boundary (Story 3.1, decision D-4).
|
||||
//!
|
||||
//! Both protocol eras use the same Tools service: the adapters parse their wire form into a command,
|
||||
//! build the verified context and map the neutral outcome back. The wire envelope, `ResponseMode`,
|
||||
//! an `axum::Response`, the session carrier and the protocol revision never cross this boundary, and
|
||||
//! the reserved `_crank_confirmation_token` marker is removed from the wire arguments by the adapter
|
||||
//! (the `call_tool` proxy arm additionally removes the marker of its own nested arguments, exactly
|
||||
//! as the previous shared implementation did).
|
||||
//!
|
||||
//! Advertisement is not per-call authorization: the credential security level check, the approval
|
||||
//! policy, the runtime execution and the invocation history stay part of the shared service, and the
|
||||
//! adapter is the only place that turns an outcome into an era-specific response.
|
||||
//!
|
||||
//! The proposed command shape carried a `catalog_revision` field; it is deliberately not adopted:
|
||||
//! the adapter has no revision of its own to declare (it would need a second catalog read just to
|
||||
//! duplicate the published revision), and the service checks the `call_tool` proxy's declared
|
||||
//! revision against the single published catalog it already reads.
|
||||
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
use crank_core::{
|
||||
CorrelationContext, ExecutionErrorCode, ExecutionFailure, ExecutionLocale, ExecutionOrigin,
|
||||
InvocationLevel, InvocationSource, InvocationStatus, ToolAccessMode,
|
||||
};
|
||||
use crank_registry::PublishedAgentCatalog;
|
||||
use crank_runtime::{ExecutionAuthorization, RuntimeExecutionRequest, RuntimeRequestContext};
|
||||
use crank_trace::{ErrorCategory, Stage, StageOutcome};
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use tracing::Instrument;
|
||||
|
||||
use crate::{
|
||||
access::credential_allows_security_level,
|
||||
app::{
|
||||
AppState, ApprovalPolicyContext, ApprovalPolicyDecision, InvocationRecord,
|
||||
maybe_handle_approval_policy, persist_invocation_for_key, resolve_generated_tool,
|
||||
resolve_operation_auth, runtime_operation, take_confirmation_token,
|
||||
},
|
||||
auth::VerifiedMachineCredential,
|
||||
manifest::{CALL_TOOL_NAME, SEARCH_TOOLS_NAME, catalog_tool_definitions},
|
||||
tool_error::{
|
||||
McpControlError, ToolErrorContract, control_tool_error_contract,
|
||||
tool_error_contract_from_failure,
|
||||
},
|
||||
};
|
||||
|
||||
/// Era-neutral continuation capability of one Tools command.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ContinuationSupport {
|
||||
ElicitationSupported,
|
||||
ElicitationUnsupported,
|
||||
}
|
||||
|
||||
impl ContinuationSupport {
|
||||
pub(crate) fn from_supported(supported: bool) -> Self {
|
||||
if supported {
|
||||
Self::ElicitationSupported
|
||||
} else {
|
||||
Self::ElicitationUnsupported
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn supports_elicitation(self) -> bool {
|
||||
matches!(self, Self::ElicitationSupported)
|
||||
}
|
||||
}
|
||||
|
||||
/// Verified, era-neutral context of one shared Tools command.
|
||||
///
|
||||
/// `workspace_slug`/`agent_slug` address the published catalog; the credential, the correlation and
|
||||
/// the continuation capability are the verified inputs of the tools/call arm. `locale` is the
|
||||
/// adapter-derived presentation preference of the request: the service composes the neutral error
|
||||
/// contract, but it never sees the envelope the preference was read from.
|
||||
pub(crate) struct ServiceContext<'a> {
|
||||
pub(crate) workspace_slug: &'a str,
|
||||
pub(crate) agent_slug: &'a str,
|
||||
pub(crate) credential: &'a VerifiedMachineCredential,
|
||||
pub(crate) correlation: &'a CorrelationContext,
|
||||
pub(crate) continuation: ContinuationSupport,
|
||||
pub(crate) locale: ExecutionLocale,
|
||||
}
|
||||
|
||||
/// Parameters of a `tools/list` command, already parsed by the adapter from the wire form.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub(crate) struct ToolsListCommand {
|
||||
#[serde(default)]
|
||||
pub(crate) cursor: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// Parameters of a `tools/call` command.
|
||||
///
|
||||
/// `arguments` is the domain-only (object-shape validated) payload of the addressed tool and the
|
||||
/// confirmation marker has already been removed by the adapter.
|
||||
pub(crate) struct ToolCallCommand {
|
||||
pub(crate) tool_name: String,
|
||||
pub(crate) arguments: Value,
|
||||
pub(crate) confirmation_token: Option<String>,
|
||||
}
|
||||
|
||||
/// A command the shared Tools service accepts.
|
||||
pub(crate) enum ToolsCommand {
|
||||
List(ToolsListCommand),
|
||||
Call(ToolCallCommand),
|
||||
}
|
||||
|
||||
/// A neutral outcome of a shared Tools command.
|
||||
pub(crate) enum ToolsOutcome {
|
||||
List {
|
||||
tools: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
},
|
||||
Call(ToolCallOutcome),
|
||||
/// The requested page is not representable: the adapter answers era-correct invalid params.
|
||||
InvalidParams(String),
|
||||
/// The published catalog could not be read: the adapter answers its internal-error shape.
|
||||
CatalogUnavailable,
|
||||
}
|
||||
|
||||
/// A neutral outcome of one `tools/call`, never an `axum::Response`.
|
||||
pub(crate) enum ToolCallOutcome {
|
||||
/// The operation completed; the adapter turns the output into its success tool response.
|
||||
Completed(Value),
|
||||
/// The operation waits for a human decision; the adapter turns the payload into its success
|
||||
/// tool response.
|
||||
ApprovalPending(Value),
|
||||
/// The required elicitation cannot be completed by this client; the adapter builds the
|
||||
/// era-correct tool error contract.
|
||||
ApprovalUnavailable(McpControlError),
|
||||
/// The payload is not a valid command for this catalog; the adapter answers era-correct
|
||||
/// invalid params.
|
||||
InvalidParams(String),
|
||||
/// A failing tool call; the adapter turns the contract into its error tool response.
|
||||
Error(ToolErrorContract),
|
||||
/// The service could not complete its own bookkeeping; the adapter answers its internal error
|
||||
/// shape.
|
||||
InternalFailure,
|
||||
}
|
||||
|
||||
/// Handle one shared Tools command. No wire envelope, `ResponseMode`, `axum::Response`, session or
|
||||
/// protocol revision crosses this boundary.
|
||||
pub(crate) async fn handle_tools_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
command: ToolsCommand,
|
||||
) -> ToolsOutcome {
|
||||
// One marker per entered owning Tools service/handler (Story 3.1 section 7.2). It is a
|
||||
// `#[cfg(test)]`-only, request-scoped counter and has no production effect.
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::tools_service_enter();
|
||||
|
||||
let catalog = match state
|
||||
.catalog
|
||||
.get_catalog(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(catalog) => catalog,
|
||||
Err(_error) => return ToolsOutcome::CatalogUnavailable,
|
||||
};
|
||||
|
||||
match command {
|
||||
ToolsCommand::List(list) => {
|
||||
match paginate_tools_list(catalog_tool_definitions(&catalog), list) {
|
||||
Ok((tools, next_cursor)) => ToolsOutcome::List { tools, next_cursor },
|
||||
Err(message) => ToolsOutcome::InvalidParams(message.to_owned()),
|
||||
}
|
||||
}
|
||||
ToolsCommand::Call(call) => {
|
||||
ToolsOutcome::Call(execute_tool_command(state, &context, call, &catalog).await)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The access-mode policy of the catalog decides what one `tools/call` command means.
|
||||
async fn execute_tool_command(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
command: ToolCallCommand,
|
||||
catalog: &PublishedAgentCatalog,
|
||||
) -> ToolCallOutcome {
|
||||
match catalog.tool_selection_policy.mode {
|
||||
ToolAccessMode::Direct => {
|
||||
execute_resolved_tool(
|
||||
state,
|
||||
context,
|
||||
catalog,
|
||||
&command.tool_name,
|
||||
command.arguments,
|
||||
command.confirmation_token,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ToolAccessMode::Search if command.tool_name == SEARCH_TOOLS_NAME => {
|
||||
match crate::tool_search::search_tools_outcome(catalog, command.arguments) {
|
||||
Ok(result) => ToolCallOutcome::Completed(result),
|
||||
Err(detail) => ToolCallOutcome::InvalidParams(detail),
|
||||
}
|
||||
}
|
||||
ToolAccessMode::Search if command.tool_name == CALL_TOOL_NAME => {
|
||||
let proxy: ProxyToolCallArguments = match serde_json::from_value(command.arguments) {
|
||||
Ok(proxy) => proxy,
|
||||
Err(error) => return ToolCallOutcome::InvalidParams(error.to_string()),
|
||||
};
|
||||
if proxy.catalog_revision != catalog.catalog_revision {
|
||||
return ToolCallOutcome::Error(control_tool_error_contract(
|
||||
McpControlError::CatalogRevisionChanged,
|
||||
context.correlation.request_id().as_str(),
|
||||
context.correlation.trace_id().as_str(),
|
||||
context.locale,
|
||||
));
|
||||
}
|
||||
let mut arguments = proxy.arguments;
|
||||
// The proxied call carries its own arguments: its marker is the one that belonged to
|
||||
// that call, so it wins over the adapter-level marker of the proxy request itself.
|
||||
let confirmation_token =
|
||||
take_confirmation_token(&mut arguments).or(command.confirmation_token);
|
||||
execute_resolved_tool(
|
||||
state,
|
||||
context,
|
||||
catalog,
|
||||
&proxy.name,
|
||||
arguments,
|
||||
confirmation_token,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ToolAccessMode::Search => {
|
||||
ToolCallOutcome::InvalidParams(tool_not_found_text(&command.tool_name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the owning tool of the addressed catalog, then run the real call: authorization, approval
|
||||
/// policy, runtime execution and invocation history.
|
||||
async fn execute_resolved_tool(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
catalog: &PublishedAgentCatalog,
|
||||
tool_name: &str,
|
||||
arguments: Value,
|
||||
confirmation_token: Option<String>,
|
||||
) -> ToolCallOutcome {
|
||||
let correlation = context.correlation;
|
||||
let transport_request_id = correlation.request_id().as_str();
|
||||
|
||||
let resolve_span = Stage::McpToolsResolve.span();
|
||||
let resolved = resolve_span.in_scope(|| resolve_generated_tool(&catalog.tools, tool_name));
|
||||
let tool = match resolved {
|
||||
Some(resolved) => {
|
||||
StageOutcome::Success.record(&resolve_span);
|
||||
drop(resolve_span);
|
||||
resolved.tool
|
||||
}
|
||||
None => {
|
||||
StageOutcome::Error.record(&resolve_span);
|
||||
ErrorCategory::Catalog.record(&resolve_span);
|
||||
drop(resolve_span);
|
||||
return ToolCallOutcome::InvalidParams(tool_not_found_text(tool_name));
|
||||
}
|
||||
};
|
||||
|
||||
let platform_api_key_id = context.credential.platform_api_key_id.clone();
|
||||
if !credential_allows_security_level(context.credential, tool.operation.security_level) {
|
||||
let failure =
|
||||
ExecutionFailure::new(ExecutionErrorCode::AuthorizationDenied, correlation.clone());
|
||||
persist_invocation_for_key(
|
||||
state,
|
||||
&tool,
|
||||
platform_api_key_id.as_ref(),
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(correlation.trace_id().as_str()),
|
||||
tool_name: &tool.tool_name,
|
||||
status: InvocationStatus::Error,
|
||||
level: InvocationLevel::Warn,
|
||||
message: failure.error_code().as_str(),
|
||||
status_code: None,
|
||||
error_kind: Some(failure.error_code().as_str()),
|
||||
execution_stage: Some(failure.stage()),
|
||||
execution_error_code: Some(failure.error_code()),
|
||||
retryability: Some(failure.retryability()),
|
||||
outcome_certainty: Some(failure.outcome_certainty()),
|
||||
duration: std::time::Duration::ZERO,
|
||||
request_preview: crank_core::sanitize_invocation_preview(&arguments),
|
||||
response_preview: Value::Null,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
return ToolCallOutcome::Error(tool_error_contract_from_failure(&failure, context.locale));
|
||||
}
|
||||
|
||||
let operation = runtime_operation(&tool);
|
||||
if tool
|
||||
.operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()
|
||||
.is_some_and(|policy| policy.required)
|
||||
{
|
||||
let approval_span = Stage::ApprovalCheck.span();
|
||||
let decision = maybe_handle_approval_policy(ApprovalPolicyContext {
|
||||
state,
|
||||
tool: &tool,
|
||||
arguments: &arguments,
|
||||
platform_api_key_id: platform_api_key_id.as_ref(),
|
||||
correlation,
|
||||
continuation: context.continuation,
|
||||
})
|
||||
.instrument(approval_span.clone())
|
||||
.await;
|
||||
if let Some(decision) = decision {
|
||||
return match decision {
|
||||
ApprovalPolicyDecision::Pending(payload) => {
|
||||
StageOutcome::Required.record(&approval_span);
|
||||
ToolCallOutcome::ApprovalPending(payload)
|
||||
}
|
||||
ApprovalPolicyDecision::ElicitationUnavailable => {
|
||||
StageOutcome::Error.record(&approval_span);
|
||||
ErrorCategory::Approval.record(&approval_span);
|
||||
ToolCallOutcome::ApprovalUnavailable(
|
||||
McpControlError::ApprovalElicitationNotSupported,
|
||||
)
|
||||
}
|
||||
ApprovalPolicyDecision::StorageFailed => {
|
||||
StageOutcome::Error.record(&approval_span);
|
||||
ErrorCategory::Approval.record(&approval_span);
|
||||
ToolCallOutcome::InternalFailure
|
||||
}
|
||||
};
|
||||
}
|
||||
StageOutcome::Allowed.record(&approval_span);
|
||||
}
|
||||
|
||||
let mut runtime_request_context = RuntimeRequestContext::from_correlation(correlation)
|
||||
.with_response_cache_scope(
|
||||
tool.workspace_id.as_str().to_owned(),
|
||||
tool.agent_id.as_str().to_owned(),
|
||||
)
|
||||
.with_metering_context(
|
||||
tool.workspace_id.clone(),
|
||||
Some(tool.agent_id.clone()),
|
||||
InvocationSource::AgentToolCall,
|
||||
);
|
||||
if let Some(token) = confirmation_token {
|
||||
runtime_request_context = runtime_request_context.with_confirmation_token(token);
|
||||
}
|
||||
let started_at = Instant::now();
|
||||
let resolved_auth =
|
||||
resolve_operation_auth(state, &tool.workspace_id, &operation.execution_config).await;
|
||||
|
||||
let result = match resolved_auth {
|
||||
Ok(resolved_auth) => {
|
||||
match RuntimeExecutionRequest::try_new(
|
||||
&tool.workspace_id,
|
||||
ExecutionOrigin::AgentSnapshot,
|
||||
Some(&tool.agent_id),
|
||||
&operation,
|
||||
&arguments,
|
||||
ExecutionAuthorization::Authorized,
|
||||
resolved_auth.as_ref(),
|
||||
&runtime_request_context,
|
||||
Instant::now()
|
||||
+ std::time::Duration::from_millis(
|
||||
operation.execution_config.timeout_ms.max(1),
|
||||
),
|
||||
) {
|
||||
Ok(request) => state.runtime.execute_outcome(request).await,
|
||||
Err(_) => Err(ExecutionFailure::new(
|
||||
ExecutionErrorCode::RuntimeInternal,
|
||||
correlation.clone(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
Err(error) => Err(crank_runtime::normalize_runtime_error(&error, correlation)),
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(success) => {
|
||||
let request_preview = success.request_preview;
|
||||
let output = success.output;
|
||||
persist_invocation_for_key(
|
||||
state,
|
||||
&tool,
|
||||
platform_api_key_id.as_ref(),
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(correlation.trace_id().as_str()),
|
||||
tool_name: &tool.tool_name,
|
||||
status: InvocationStatus::Ok,
|
||||
level: InvocationLevel::Info,
|
||||
message: "agent tool call completed",
|
||||
status_code: None,
|
||||
error_kind: None,
|
||||
execution_stage: Some(crank_core::ExecutionStage::Runtime),
|
||||
execution_error_code: None,
|
||||
retryability: Some(crank_core::Retryability::Never),
|
||||
outcome_certainty: Some(crank_core::OutcomeCertainty::Certain),
|
||||
duration: started_at.elapsed(),
|
||||
request_preview,
|
||||
response_preview: output.clone(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
ToolCallOutcome::Completed(output)
|
||||
}
|
||||
Err(failure) => {
|
||||
persist_invocation_for_key(
|
||||
state,
|
||||
&tool,
|
||||
platform_api_key_id.as_ref(),
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(correlation.trace_id().as_str()),
|
||||
tool_name: &tool.tool_name,
|
||||
status: InvocationStatus::Error,
|
||||
level: InvocationLevel::Error,
|
||||
message: failure.error_code().as_str(),
|
||||
status_code: failure.upstream_status(),
|
||||
error_kind: Some(failure.error_code().as_str()),
|
||||
execution_stage: Some(failure.stage()),
|
||||
execution_error_code: Some(failure.error_code()),
|
||||
retryability: Some(failure.retryability()),
|
||||
outcome_certainty: Some(failure.outcome_certainty()),
|
||||
duration: started_at.elapsed(),
|
||||
request_preview: Value::Null,
|
||||
response_preview: Value::Null,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
ToolCallOutcome::Error(tool_error_contract_from_failure(&failure, context.locale))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ProxyToolCallArguments {
|
||||
name: String,
|
||||
#[serde(deserialize_with = "crate::protocol::deserialize_object_only")]
|
||||
arguments: Value,
|
||||
catalog_revision: String,
|
||||
}
|
||||
|
||||
fn tool_not_found_text(tool_name: &str) -> String {
|
||||
format!("tool {tool_name} was not found")
|
||||
}
|
||||
|
||||
/// Pagination of the advertised tool definitions. Domain-only: it never sees the request envelope.
|
||||
fn paginate_tools_list(
|
||||
definitions: Vec<Value>,
|
||||
command: ToolsListCommand,
|
||||
) -> Result<(Vec<Value>, Option<String>), &'static str> {
|
||||
const MAX_TOOLS_LIST_LIMIT: usize = 100;
|
||||
let start = match command.cursor {
|
||||
Some(cursor) if cursor.is_empty() => 0,
|
||||
Some(cursor) => cursor
|
||||
.parse::<usize>()
|
||||
.map_err(|_| "invalid tools/list cursor")?,
|
||||
None => 0,
|
||||
};
|
||||
if start > definitions.len() {
|
||||
return Err("tools/list cursor is out of range");
|
||||
}
|
||||
let limit = command
|
||||
.limit
|
||||
.unwrap_or(definitions.len())
|
||||
.clamp(1, MAX_TOOLS_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(definitions.len());
|
||||
let tools = definitions[start..end].to_vec();
|
||||
let next_cursor = (end < definitions.len()).then(|| end.to_string());
|
||||
Ok((tools, next_cursor))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn definitions(count: usize) -> Vec<Value> {
|
||||
(0..count)
|
||||
.map(|index| json!({"name": format!("tool-{index}")}))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_page_reports_the_next_cursor_only_when_more_tools_remain() {
|
||||
let (tools, next_cursor) =
|
||||
paginate_tools_list(definitions(3), ToolsListCommand::default()).expect("valid page");
|
||||
assert_eq!(tools.len(), 3);
|
||||
assert_eq!(next_cursor, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bounded_page_reports_the_following_cursor() {
|
||||
let (tools, next_cursor) = paginate_tools_list(
|
||||
definitions(5),
|
||||
ToolsListCommand {
|
||||
cursor: None,
|
||||
limit: Some(2),
|
||||
},
|
||||
)
|
||||
.expect("valid page");
|
||||
assert_eq!(tools, definitions(2));
|
||||
assert_eq!(next_cursor.as_deref(), Some("2"));
|
||||
|
||||
let (tools, next_cursor) = paginate_tools_list(
|
||||
definitions(5),
|
||||
ToolsListCommand {
|
||||
cursor: Some("2".to_owned()),
|
||||
limit: Some(2),
|
||||
},
|
||||
)
|
||||
.expect("valid page");
|
||||
assert_eq!(
|
||||
tools,
|
||||
vec![json!({"name": "tool-2"}), json!({"name": "tool-3"})]
|
||||
);
|
||||
assert_eq!(next_cursor.as_deref(), Some("4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_cursor_is_invalid_params_and_never_a_default_page() {
|
||||
assert_eq!(
|
||||
paginate_tools_list(
|
||||
definitions(3),
|
||||
ToolsListCommand {
|
||||
cursor: Some("not-a-cursor".to_owned()),
|
||||
limit: None,
|
||||
},
|
||||
)
|
||||
.unwrap_err(),
|
||||
"invalid tools/list cursor"
|
||||
);
|
||||
assert_eq!(
|
||||
paginate_tools_list(
|
||||
definitions(3),
|
||||
ToolsListCommand {
|
||||
cursor: Some("9".to_owned()),
|
||||
limit: None,
|
||||
},
|
||||
)
|
||||
.unwrap_err(),
|
||||
"tools/list cursor is out of range"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuation_support_is_an_era_neutral_value_object() {
|
||||
assert!(ContinuationSupport::from_supported(true).supports_elicitation());
|
||||
assert!(!ContinuationSupport::from_supported(false).supports_elicitation());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_tool_name_is_reported_verbatim() {
|
||||
assert_eq!(
|
||||
tool_not_found_text("create_lead"),
|
||||
"tool create_lead was not found"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
//! Story 3.17: the era-neutral `completion/complete` service boundary.
|
||||
//!
|
||||
//! Both supported revisions share this one service; the wire envelope, the response mode and the
|
||||
//! `axum::Response` stay in the era adapters, exactly as for the Tools/Resources/Prompts services.
|
||||
//!
|
||||
//! Scope of the answer (AC1): a suggestion list is derived *only* from the typed schema of one exact
|
||||
//! Published Prompt argument, or of one exact parameter of one exact Published Resource template,
|
||||
//! that is already bound to the active published Agent snapshot. There is no lookup by a
|
||||
//! client-supplied id, no scan of draft/foreign/unbound rows and no search over arbitrary database
|
||||
//! values: a `ref` that is not part of the bound snapshot is answered with the same indistinguishable
|
||||
//! refusal as an unknown argument, so neither foreign Prompt names nor foreign template URIs can be
|
||||
//! probed through this method. Schemas without an enumeration produce an empty suggestion list
|
||||
//! instead of an invented one.
|
||||
//!
|
||||
//! Bounds (AC2): the argument name/value, the reference and the optional completion context are
|
||||
//! length/count-bounded before any catalog read, and the schema enumeration itself is read through a
|
||||
//! fixed cap. A truncated scan is reported honestly (`total` omitted, `hasMore: true`) rather than as
|
||||
//! an exact count. Every telemetry field is a count, a fixed label or the served revision — never a
|
||||
//! Prompt name, a URI template, an argument name or a client-supplied value, so the bounded metric
|
||||
//! label set cannot be widened by a request.
|
||||
|
||||
use std::{collections::HashSet, sync::Arc};
|
||||
|
||||
use crank_core::resource::TemplateSource;
|
||||
use crank_schema::Schema;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{app::AppState, protocol::ServiceContext};
|
||||
|
||||
/// Pinned `CompleteResult.completion.values` bound (`@maxItems 100`).
|
||||
const MAX_COMPLETION_VALUES: usize = 100;
|
||||
/// Schema enumeration values inspected per request: the bound that keeps a hostile or corrupted
|
||||
/// schema from turning one completion request into unbounded work.
|
||||
const MAX_SCHEMA_VALUES: usize = 1_024;
|
||||
/// Bound of a completion argument name (`params.argument.name`).
|
||||
const MAX_ARGUMENT_NAME_BYTES: usize = 128;
|
||||
/// Bound of the partial token a client sends (`params.argument.value`); the pinned schema types it as
|
||||
/// an opaque string, so an oversized token is a malformed request, not a matching challenge.
|
||||
const MAX_ARGUMENT_VALUE_BYTES: usize = 1_024;
|
||||
/// Bound of `ref/prompt.name`.
|
||||
const MAX_REFERENCE_NAME_BYTES: usize = 256;
|
||||
/// Bound of `ref/resource.uri` (a URI template as served by `resources/templates/list`).
|
||||
const MAX_REFERENCE_URI_BYTES: usize = 2_048;
|
||||
/// Bound of the optional previously-resolved `context.arguments` map.
|
||||
const MAX_CONTEXT_ARGUMENTS: usize = 32;
|
||||
|
||||
/// The one safe detail of a malformed completion request: it never echoes the offending value.
|
||||
const INVALID_PARAMS: &str = "invalid completion/complete parameters";
|
||||
|
||||
/// Parameters of a `completion/complete` command, already parsed by the adapter from the wire form.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct CompletionCommand {
|
||||
/// `ref` of the pinned schema: `{type: "ref/prompt", ...}` or `{type: "ref/resource", ...}`.
|
||||
#[serde(rename = "ref")]
|
||||
pub(crate) reference: CompletionReference,
|
||||
/// The argument whose value is being completed.
|
||||
pub(crate) argument: CompletionArgument,
|
||||
/// Optional previously-resolved variables. The typed schema of the addressed argument is the only
|
||||
/// suggestion source, so this context is validated and otherwise not used: it never widens the
|
||||
/// answer beyond the published enumeration.
|
||||
#[serde(default)]
|
||||
pub(crate) context: Option<CompletionContext>,
|
||||
}
|
||||
|
||||
/// The typed `ref` union of the pinned completion request.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
pub(crate) enum CompletionReference {
|
||||
/// One Prompt, addressed by the name it is listed under in `prompts/list`.
|
||||
#[serde(rename = "ref/prompt")]
|
||||
Prompt { name: String },
|
||||
/// One Resource template, addressed by the URI template served by `resources/templates/list`.
|
||||
#[serde(rename = "ref/resource")]
|
||||
Resource { uri: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct CompletionArgument {
|
||||
pub(crate) name: String,
|
||||
pub(crate) value: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub(crate) struct CompletionContext {
|
||||
#[serde(default)]
|
||||
pub(crate) arguments: Option<Map<String, Value>>,
|
||||
}
|
||||
|
||||
/// A neutral outcome of the shared completion service.
|
||||
pub(crate) enum CompletionOutcome {
|
||||
/// Bounded suggestions in schema order. `total` is absent when the enumeration scan was
|
||||
/// truncated, because then only a lower bound of the option count is known.
|
||||
Completed {
|
||||
values: Vec<String>,
|
||||
total: Option<usize>,
|
||||
has_more: bool,
|
||||
},
|
||||
/// The request is malformed or exceeds a fixed bound: one safe detail, no echoed input.
|
||||
InvalidParams(&'static str),
|
||||
/// Unknown, Draft, foreign, unbound or archived-out reference, or an argument the addressed
|
||||
/// schema does not declare. One outcome that cannot distinguish these cases.
|
||||
NotAvailable,
|
||||
/// The bound snapshot or the addressed typed schema could not be read safely.
|
||||
CatalogUnavailable,
|
||||
}
|
||||
|
||||
/// Serve one `completion/complete` command for the revision the adapter negotiated (AC1/AC3).
|
||||
pub(crate) async fn handle_completion_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: CompletionCommand,
|
||||
) -> CompletionOutcome {
|
||||
if command.validate().is_some() {
|
||||
return CompletionOutcome::InvalidParams(INVALID_PARAMS);
|
||||
}
|
||||
let catalog = match state
|
||||
.catalog
|
||||
.get_catalog(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(catalog) => catalog,
|
||||
Err(_error) => {
|
||||
return refused(revision, command.reference_label(), "catalog_unavailable");
|
||||
}
|
||||
};
|
||||
let workspace_id = match state
|
||||
.registry
|
||||
.published_agent_workspace_id(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(workspace_id) => workspace_id,
|
||||
Err(_error) => {
|
||||
return refused(revision, command.reference_label(), "catalog_unavailable");
|
||||
}
|
||||
};
|
||||
|
||||
match &command.reference {
|
||||
CompletionReference::Prompt { name } => {
|
||||
// The same exact bound snapshot `prompts/list` and `prompts/get` serve, so a Draft,
|
||||
// foreign or unbound Prompt has no candidates at all.
|
||||
let publications = match state
|
||||
.registry
|
||||
.resolve_bound_prompt_publications(&workspace_id, &catalog.prompts)
|
||||
.await
|
||||
{
|
||||
Ok(publications) => publications,
|
||||
Err(_error) => {
|
||||
return refused(revision, "prompt", "catalog_unavailable");
|
||||
}
|
||||
};
|
||||
// Deterministic exact binding, identical to `prompts/get`: names are not constrained
|
||||
// unique, so the first bound publication in `prompt_id` order is addressed.
|
||||
let Some(publication) = publications
|
||||
.iter()
|
||||
.find(|publication| &publication.name == name)
|
||||
else {
|
||||
return not_available(revision, "prompt");
|
||||
};
|
||||
let Some(argument) = publication
|
||||
.definition
|
||||
.arguments()
|
||||
.iter()
|
||||
.find(|argument| argument.name() == command.argument.name)
|
||||
else {
|
||||
return not_available(revision, "prompt");
|
||||
};
|
||||
let candidates = argument
|
||||
.enumeration()
|
||||
.iter()
|
||||
.filter_map(value_text)
|
||||
.collect::<Vec<_>>();
|
||||
completed(revision, "prompt", &command.argument.value, candidates)
|
||||
}
|
||||
CompletionReference::Resource { uri } => {
|
||||
// The same admitted bound template array `resources/templates/list` serves: revoked,
|
||||
// foreign and unbound templates are already filtered out by the registry adapter.
|
||||
let admitted = match state
|
||||
.registry
|
||||
.list_admitted_resource_templates(workspace_id.as_str(), &catalog.resources)
|
||||
.await
|
||||
{
|
||||
Ok(admitted) => admitted,
|
||||
Err(_error) => {
|
||||
return refused(revision, "resource", "catalog_unavailable");
|
||||
}
|
||||
};
|
||||
let mut addressable = None;
|
||||
for template in &admitted {
|
||||
// A bound definition that no longer parses is simply not addressable here; it never
|
||||
// turns an unrelated completion request into an error.
|
||||
let Ok(definition) =
|
||||
serde_json::from_str::<Value>(&template.source.definition_json)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Ok(source) = TemplateSource::parse(&definition) else {
|
||||
continue;
|
||||
};
|
||||
if &source.uri_template == uri {
|
||||
addressable = Some(source);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(source) = addressable else {
|
||||
return not_available(revision, "resource");
|
||||
};
|
||||
let Some(parameter) = source
|
||||
.parameters
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == command.argument.name)
|
||||
else {
|
||||
return not_available(revision, "resource");
|
||||
};
|
||||
let Ok(schema) = serde_json::from_value::<Schema>(parameter.schema.clone()) else {
|
||||
return refused(revision, "resource", "schema_unavailable");
|
||||
};
|
||||
completed(
|
||||
revision,
|
||||
"resource",
|
||||
&command.argument.value,
|
||||
schema.enum_values,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CompletionCommand {
|
||||
/// The bounded input contract of AC2: nothing here depends on catalog content, so a malformed or
|
||||
/// oversized request is refused before the first registry read.
|
||||
fn validate(&self) -> Option<&'static str> {
|
||||
match &self.reference {
|
||||
CompletionReference::Prompt { name } => {
|
||||
if name.is_empty() || name.len() > MAX_REFERENCE_NAME_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
}
|
||||
CompletionReference::Resource { uri } => {
|
||||
if uri.is_empty() || uri.len() > MAX_REFERENCE_URI_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.argument.name.is_empty() || self.argument.name.len() > MAX_ARGUMENT_NAME_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
if self.argument.value.len() > MAX_ARGUMENT_VALUE_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
let arguments = self
|
||||
.context
|
||||
.as_ref()
|
||||
.and_then(|context| context.arguments.as_ref())?;
|
||||
if arguments.len() > MAX_CONTEXT_ARGUMENTS {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
// The pinned schema types the context values as strings; a non-string or oversized value is
|
||||
// malformed rather than something to coerce.
|
||||
for (name, value) in arguments {
|
||||
if name.len() > MAX_ARGUMENT_NAME_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
let Some(text) = value.as_str() else {
|
||||
return Some(INVALID_PARAMS);
|
||||
};
|
||||
if text.len() > MAX_ARGUMENT_VALUE_BYTES {
|
||||
return Some(INVALID_PARAMS);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The fixed telemetry label of the reference kind (never the name or the URI itself).
|
||||
const fn reference_label(&self) -> &'static str {
|
||||
match self.reference {
|
||||
CompletionReference::Prompt { .. } => "prompt",
|
||||
CompletionReference::Resource { .. } => "resource",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One suggestion list from an already-authorized typed enumeration.
|
||||
///
|
||||
/// Matching is a case-insensitive prefix test over the schema order, so the answer is deterministic
|
||||
/// and independent of query timing. Duplicates are collapsed before counting, the response is capped
|
||||
/// at the pinned 100 values, and a truncated schema scan never claims an exact `total`.
|
||||
fn completed(
|
||||
revision: &str,
|
||||
reference: &'static str,
|
||||
value: &str,
|
||||
candidates: Vec<String>,
|
||||
) -> CompletionOutcome {
|
||||
let truncated = candidates.len() > MAX_SCHEMA_VALUES;
|
||||
let mut seen = HashSet::new();
|
||||
let mut matched = Vec::new();
|
||||
for candidate in candidates.into_iter().take(MAX_SCHEMA_VALUES) {
|
||||
if !prefix_match(&candidate, value) {
|
||||
continue;
|
||||
}
|
||||
if !seen.insert(candidate.clone()) {
|
||||
continue;
|
||||
}
|
||||
matched.push(candidate);
|
||||
}
|
||||
let total = matched.len();
|
||||
let values: Vec<String> = matched.into_iter().take(MAX_COMPLETION_VALUES).collect();
|
||||
let has_more = truncated || total > values.len();
|
||||
info!(
|
||||
name: "mcp.completion.complete",
|
||||
outcome = "ok",
|
||||
reference,
|
||||
suggestion_count = values.len(),
|
||||
has_more,
|
||||
total_known = !truncated,
|
||||
revision,
|
||||
"completion outcome"
|
||||
);
|
||||
CompletionOutcome::Completed {
|
||||
values,
|
||||
total: (!truncated).then_some(total),
|
||||
has_more,
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when `value` is an ASCII-case-insensitive prefix of `candidate`.
|
||||
///
|
||||
/// A `value` that does not end on a character boundary of `candidate` cannot be a prefix of it, so a
|
||||
/// non-ASCII token is matched exactly instead of being sliced mid-character.
|
||||
fn prefix_match(candidate: &str, value: &str) -> bool {
|
||||
candidate
|
||||
.get(..value.len())
|
||||
.is_some_and(|head| head.eq_ignore_ascii_case(value))
|
||||
}
|
||||
|
||||
/// The wire-visible text of one enum entry. Only scalars have a faithful string form; an object or
|
||||
/// array enumeration entry is not suggested instead of being rendered as an ad-hoc serialization.
|
||||
fn value_text(value: &Value) -> Option<String> {
|
||||
match value {
|
||||
Value::String(text) => Some(text.clone()),
|
||||
Value::Number(number) => Some(number.to_string()),
|
||||
Value::Bool(flag) => Some(flag.to_string()),
|
||||
Value::Null | Value::Array(_) | Value::Object(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One safe, indistinguishable refusal: no Prompt name, URI template, argument name or option
|
||||
/// count is disclosed, and the reason never distinguishes unknown from foreign/unbound.
|
||||
fn not_available(revision: &str, reference: &'static str) -> CompletionOutcome {
|
||||
refused(revision, reference, "not_available")
|
||||
}
|
||||
|
||||
fn refused(revision: &str, reference: &'static str, outcome: &'static str) -> CompletionOutcome {
|
||||
info!(
|
||||
name: "mcp.completion.complete",
|
||||
outcome,
|
||||
reference,
|
||||
suggestion_count = 0usize,
|
||||
revision,
|
||||
"completion outcome"
|
||||
);
|
||||
match outcome {
|
||||
"catalog_unavailable" | "schema_unavailable" => CompletionOutcome::CatalogUnavailable,
|
||||
_ => CompletionOutcome::NotAvailable,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "completion_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,220 @@
|
||||
//! In-crate tests of `protocol::completion` (module path `protocol::completion::tests`).
|
||||
//!
|
||||
//! These cover the pure halves of the shared service: the bounded input contract of AC2 and the
|
||||
//! suggestion derivation of AC1. The real endpoint behaviour (both eras, real registry) is covered by
|
||||
//! `apps/mcp-server/tests/integration/mcp_completion.rs`.
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// Any supported revision: the suggestion derivation is era-neutral.
|
||||
const MODERN: &str = crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
|
||||
fn candidates(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).to_owned()).collect()
|
||||
}
|
||||
|
||||
fn values_of(outcome: &CompletionOutcome) -> (&[String], Option<usize>, bool) {
|
||||
match outcome {
|
||||
CompletionOutcome::Completed {
|
||||
values,
|
||||
total,
|
||||
has_more,
|
||||
} => (values, *total, *has_more),
|
||||
_ => panic!("expected a completed outcome"),
|
||||
}
|
||||
}
|
||||
|
||||
fn command(params: Value) -> Result<CompletionCommand, serde_json::Error> {
|
||||
serde_json::from_value(params)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_is_a_case_insensitive_prefix_in_schema_order() {
|
||||
let outcome = completed(
|
||||
MODERN,
|
||||
"prompt",
|
||||
"W",
|
||||
candidates(&["warm", "dry", "wild", "warmest"]),
|
||||
);
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert_eq!(values, ["warm", "wild", "warmest"]);
|
||||
assert_eq!(total, Some(3));
|
||||
assert!(!has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_token_lists_the_bounded_enumeration() {
|
||||
let outcome = completed(MODERN, "prompt", "", candidates(&["a", "b", "c"]));
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert_eq!(values, ["a", "b", "c"]);
|
||||
assert_eq!(total, Some(3));
|
||||
assert!(!has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_without_a_match_returns_no_suggestions() {
|
||||
let outcome = completed(MODERN, "resource", "zzz", candidates(&["eu", "us"]));
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert!(values.is_empty());
|
||||
assert_eq!(total, Some(0));
|
||||
assert!(!has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_response_is_capped_at_the_pinned_maximum_and_reports_more() {
|
||||
let all: Vec<String> = (0..150).map(|index| format!("value-{index:03}")).collect();
|
||||
let outcome = completed(MODERN, "prompt", "value-", all);
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert_eq!(values.len(), MAX_COMPLETION_VALUES);
|
||||
assert_eq!(values.first().map(String::as_str), Some("value-000"));
|
||||
assert_eq!(total, Some(150), "the exact option count is still reported");
|
||||
assert!(has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_enumeration_entries_are_collapsed_before_counting() {
|
||||
let outcome = completed(MODERN, "prompt", "", candidates(&["eu", "eu", "us"]));
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert_eq!(values, ["eu", "us"]);
|
||||
assert_eq!(total, Some(2));
|
||||
assert!(!has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_schema_scan_never_claims_an_exact_total() {
|
||||
let all: Vec<String> = (0..=MAX_SCHEMA_VALUES)
|
||||
.map(|index| format!("item{index}"))
|
||||
.collect();
|
||||
let outcome = completed(MODERN, "resource", "item", all);
|
||||
let (values, total, has_more) = values_of(&outcome);
|
||||
assert_eq!(values.len(), MAX_COMPLETION_VALUES);
|
||||
assert_eq!(total, None, "a partial scan cannot name the option count");
|
||||
assert!(has_more);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_scalar_enumeration_entries_become_suggestions() {
|
||||
assert_eq!(value_text(&json!("eu")), Some("eu".to_owned()));
|
||||
assert_eq!(value_text(&json!(7)), Some("7".to_owned()));
|
||||
assert_eq!(value_text(&json!(true)), Some("true".to_owned()));
|
||||
assert_eq!(value_text(&json!(null)), None);
|
||||
assert_eq!(value_text(&json!(["eu"])), None);
|
||||
assert_eq!(value_text(&json!({"value": "eu"})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_ascii_token_matches_exactly_and_never_slices_mid_character() {
|
||||
assert!(prefix_match("привет", "пр"));
|
||||
// A two-byte Cyrillic letter is one character, so it is a plain prefix.
|
||||
assert!(prefix_match("привет", "п"));
|
||||
assert!(prefix_match("Ärger", "Är"));
|
||||
// Two ASCII bytes end inside the multi-byte `é`: no prefix is claimed for a mid-character cut.
|
||||
assert!(!prefix_match("aé", "ab"));
|
||||
assert!(!prefix_match("warm", "warmest"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_discloses_neither_reason_nor_identifiers() {
|
||||
assert!(matches!(
|
||||
not_available(MODERN, "prompt"),
|
||||
CompletionOutcome::NotAvailable
|
||||
));
|
||||
assert!(matches!(
|
||||
refused(MODERN, "resource", "schema_unavailable"),
|
||||
CompletionOutcome::CatalogUnavailable
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_typed_references_parse_and_a_foreign_ref_type_is_rejected() {
|
||||
let prompt = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": "greeting"},
|
||||
"argument": {"name": "tone", "value": "w"}
|
||||
}))
|
||||
.expect("the prompt reference is the pinned shape");
|
||||
assert_eq!(prompt.reference_label(), "prompt");
|
||||
assert!(prompt.context.is_none());
|
||||
|
||||
let resource = command(json!({
|
||||
"ref": {"type": "ref/resource", "uri": "crank://orders/{order_id}"},
|
||||
"argument": {"name": "order_id", "value": "0"},
|
||||
"context": {"arguments": {"region": "eu"}}
|
||||
}))
|
||||
.expect("the resource reference with context is the pinned shape");
|
||||
assert_eq!(resource.reference_label(), "resource");
|
||||
assert!(resource.validate().is_none());
|
||||
|
||||
assert!(
|
||||
command(json!({
|
||||
"ref": {"type": "ref/tool", "name": "x"},
|
||||
"argument": {"name": "a", "value": ""}
|
||||
}))
|
||||
.is_err(),
|
||||
"an unknown reference type is not a completion reference"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_and_malformed_requests_are_refused_before_any_catalog_read() {
|
||||
let long_value = "v".repeat(MAX_ARGUMENT_VALUE_BYTES + 1);
|
||||
let oversized = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": "greeting"},
|
||||
"argument": {"name": "tone", "value": long_value}
|
||||
}))
|
||||
.expect("the request shape parses; only its bound is exceeded");
|
||||
assert_eq!(oversized.validate(), Some(INVALID_PARAMS));
|
||||
|
||||
let long_name = "n".repeat(MAX_ARGUMENT_NAME_BYTES + 1);
|
||||
let oversized_name = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": "greeting"},
|
||||
"argument": {"name": long_name, "value": ""}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(oversized_name.validate(), Some(INVALID_PARAMS));
|
||||
|
||||
let empty_argument = command(json!({
|
||||
"ref": {"type": "ref/resource", "uri": "crank://orders/{order_id}"},
|
||||
"argument": {"name": "", "value": ""}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(empty_argument.validate(), Some(INVALID_PARAMS));
|
||||
|
||||
let empty_reference = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": ""},
|
||||
"argument": {"name": "tone", "value": ""}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(empty_reference.validate(), Some(INVALID_PARAMS));
|
||||
|
||||
let long_uri = "u".repeat(MAX_REFERENCE_URI_BYTES + 1);
|
||||
let oversized_uri = command(json!({
|
||||
"ref": {"type": "ref/resource", "uri": long_uri},
|
||||
"argument": {"name": "order_id", "value": ""}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(oversized_uri.validate(), Some(INVALID_PARAMS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_optional_context_is_validated_as_the_pinned_string_map() {
|
||||
let non_string = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": "greeting"},
|
||||
"argument": {"name": "tone", "value": ""},
|
||||
"context": {"arguments": {"region": 7}}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(non_string.validate(), Some(INVALID_PARAMS));
|
||||
|
||||
let mut arguments = Map::new();
|
||||
for index in 0..=MAX_CONTEXT_ARGUMENTS {
|
||||
arguments.insert(format!("argument{index}"), json!("value"));
|
||||
}
|
||||
let too_many = command(json!({
|
||||
"ref": {"type": "ref/prompt", "name": "greeting"},
|
||||
"argument": {"name": "tone", "value": ""},
|
||||
"context": {"arguments": arguments}
|
||||
}))
|
||||
.expect("the request shape parses");
|
||||
assert_eq!(too_many.validate(), Some(INVALID_PARAMS));
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Story 3.18: safe MCP server logging (FR-19).
|
||||
//!
|
||||
//! Scope of this module is the server side of the pinned `logging` capability of the two approved
|
||||
//! revisions, and nothing else:
|
||||
//!
|
||||
//! * `2025-11-25` (legacy session era) declares `logging/setLevel` as a client request with one
|
||||
//! `level` of the pinned `LoggingLevel` union, and `logging?: object` in `ServerCapabilities`.
|
||||
//! The request sets the severity a client wants to receive for its own session.
|
||||
//! * `2026-07-28` (modern stateless era) has no `logging/setLevel` method at all: SEP-2577 replaces
|
||||
//! it with the per-request `_meta["io.modelcontextprotocol/logLevel"]`, and the schema says that
|
||||
//! when that key is absent "the server MUST NOT send any notifications/message notifications for
|
||||
//! this request". The `logging` capability and `notifications/message` themselves stay in the
|
||||
//! pinned schema as deprecated for at least twelve months.
|
||||
//!
|
||||
//! The answer of this story is therefore the narrow one the contract offers: an opt-in level that
|
||||
//! belongs to the current negotiated client context (one legacy session, or one modern request —
|
||||
//! never a process-global level shared by every agent), and `notifications/message` events that are
|
||||
//! built **only** from the closed safe vocabulary below.
|
||||
//!
|
||||
//! Redaction is structural, not a filter: no request payload, credential, internal error cause,
|
||||
//! Prompt/Resource/Tool name, URI, argument value or any other user-supplied value is ever accepted
|
||||
//! by this module, so none of them can reach the wire. A `notifications/message` body is exactly
|
||||
//! `{"level": <severity of the event>, "logger": "crank-mcp-server", "data": {"event": <closed name>,
|
||||
//! "outcome": <closed label>}}` — every member of it is a `&'static str` from this file.
|
||||
//!
|
||||
//! Bounds (issue requirement: bounded frequency/queues/bytes, logging never blocks execution and
|
||||
//! never replaces the audit trail):
|
||||
//! * at most one event per response is recorded, and at most [`MAX_PENDING_NOTIFICATIONS`] are
|
||||
//! drained into one response — a fixed, per-response frequency bound;
|
||||
//! * every event has a fixed size and no variable input, so the byte bound follows from the count
|
||||
//! bound without a separate accounting path;
|
||||
//! * recording is a bounded in-memory push that drops the event when the buffer is full, the active
|
||||
//! level is unset, or the task has no request scope. No I/O, no lock acquisition that can wait, and
|
||||
//! no error path: logging can never fail or slow down the request it describes.
|
||||
//! * the legacy opt-in table is a bounded in-memory map read/written with `try_lock` only.
|
||||
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::HashMap,
|
||||
future::Future,
|
||||
sync::{Mutex, MutexGuard},
|
||||
};
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use tokio::task_local;
|
||||
|
||||
/// The pinned `LoggingLevel` union: RFC 5424 severities, ordered from the most verbose to the most
|
||||
/// severe. The ordering is the filtering contract — a client is sent the events at or above its
|
||||
/// level.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) enum LogLevel {
|
||||
Debug,
|
||||
Info,
|
||||
Notice,
|
||||
Warning,
|
||||
Error,
|
||||
Critical,
|
||||
Alert,
|
||||
Emergency,
|
||||
}
|
||||
|
||||
impl LogLevel {
|
||||
/// The exact wire literal of this level.
|
||||
pub(crate) const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Debug => "debug",
|
||||
Self::Info => "info",
|
||||
Self::Notice => "notice",
|
||||
Self::Warning => "warning",
|
||||
Self::Error => "error",
|
||||
Self::Critical => "critical",
|
||||
Self::Alert => "alert",
|
||||
Self::Emergency => "emergency",
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact parse of the eight pinned literals.
|
||||
///
|
||||
/// Nothing is coerced: no case folding, no aliases (`warn`), no numeric severities. A value that
|
||||
/// is not one of the pinned strings is malformed, which is what the pinned `LoggingLevel` type
|
||||
/// says and what `InvalidParamsError` is for.
|
||||
pub(crate) fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"debug" => Some(Self::Debug),
|
||||
"info" => Some(Self::Info),
|
||||
"notice" => Some(Self::Notice),
|
||||
"warning" => Some(Self::Warning),
|
||||
"error" => Some(Self::Error),
|
||||
"critical" => Some(Self::Critical),
|
||||
"alert" => Some(Self::Alert),
|
||||
"emergency" => Some(Self::Emergency),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bound of `params.level` before it is compared: the longest pinned literal is nine bytes, so a
|
||||
/// value beyond this cannot be a level and must not be scanned further.
|
||||
pub(crate) const MAX_LEVEL_BYTES: usize = 16;
|
||||
|
||||
/// The one safe detail of a malformed `logging/setLevel`: it never echoes the offending value, so an
|
||||
/// oversized or hostile value cannot be reflected back or widened into an error payload.
|
||||
pub(crate) const INVALID_LEVEL: &str = "invalid logging level";
|
||||
|
||||
/// Notifications drained into one response (frequency bound).
|
||||
pub(crate) const MAX_PENDING_NOTIFICATIONS: usize = 4;
|
||||
|
||||
/// Bound of the in-memory legacy opt-in table (memory bound; see [`LogLevelStore`]).
|
||||
pub(crate) const MAX_TRACKED_SESSIONS: usize = 1_024;
|
||||
|
||||
/// The fixed logger name carried by every notification. It is a server constant, never a
|
||||
/// client-supplied or catalog-supplied value.
|
||||
const LOGGER_NAME: &str = "crank-mcp-server";
|
||||
|
||||
/// Closed safe vocabulary: the server served the request.
|
||||
pub(crate) const EVENT_SERVED: &str = "mcp.request.served";
|
||||
/// Closed safe vocabulary: the request was rejected as invalid before any service work.
|
||||
pub(crate) const EVENT_REJECTED: &str = "mcp.request.rejected";
|
||||
/// Closed safe vocabulary: the request failed on the server side.
|
||||
pub(crate) const EVENT_FAILED: &str = "mcp.request.failed";
|
||||
/// Closed safe vocabulary: this client set its logging level.
|
||||
pub(crate) const EVENT_LEVEL_APPLIED: &str = "mcp.logging.level_applied";
|
||||
|
||||
/// The `params` of one `logging/setLevel` request as the legacy adapter parses it from the wire form.
|
||||
///
|
||||
/// Only the single pinned member exists here: an unknown member is ignored by serde, and a `level`
|
||||
/// that is not a string is a deserialization error, which the adapter answers with the same safe
|
||||
/// [`INVALID_LEVEL`] detail instead of a serde diagnostic.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct SetLevelCommand {
|
||||
pub(crate) level: String,
|
||||
}
|
||||
|
||||
impl SetLevelCommand {
|
||||
/// The bounded input contract of AC2: the level is length-bounded and compared exactly, so a
|
||||
/// malformed or oversized value is refused with bounded work and one safe detail.
|
||||
pub(crate) fn validate(&self) -> Result<LogLevel, &'static str> {
|
||||
if self.level.is_empty() || self.level.len() > MAX_LEVEL_BYTES {
|
||||
return Err(INVALID_LEVEL);
|
||||
}
|
||||
LogLevel::parse(&self.level).ok_or(INVALID_LEVEL)
|
||||
}
|
||||
}
|
||||
|
||||
/// A neutral outcome of the shared `logging/setLevel` service.
|
||||
pub(crate) enum LoggingOutcome {
|
||||
/// The level of this client context was accepted.
|
||||
Applied(LogLevel),
|
||||
/// Malformed or oversized level: one safe detail, no echoed input.
|
||||
InvalidParams(&'static str),
|
||||
}
|
||||
|
||||
/// One recorded event of the closed vocabulary.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct SafeEvent {
|
||||
level: LogLevel,
|
||||
event: &'static str,
|
||||
outcome: &'static str,
|
||||
}
|
||||
|
||||
/// The request-scoped logging state: the level this client opted in to, whether the client offered
|
||||
/// the SSE response mode that is the only carrier of a server notification, and the bounded events
|
||||
/// this response will carry.
|
||||
#[derive(Default)]
|
||||
struct RequestLog {
|
||||
active: Option<LogLevel>,
|
||||
sse_acceptable: bool,
|
||||
pending: Vec<SafeEvent>,
|
||||
}
|
||||
|
||||
task_local! {
|
||||
/// Per-request logging scope. Installed by the HTTP entry point of the MCP endpoint, so two
|
||||
/// concurrently served requests never share a level or a buffer. Code outside such a scope
|
||||
/// (unit tests, background workers) sees a no-op.
|
||||
static REQUEST_LOG: RefCell<RequestLog>;
|
||||
}
|
||||
|
||||
/// Run one request inside its own logging scope.
|
||||
pub(crate) async fn scoped<F: Future>(future: F) -> F::Output {
|
||||
REQUEST_LOG
|
||||
.scope(RefCell::new(RequestLog::default()), future)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Activate (or clear) the level of the current client context. Outside a scope this is a no-op.
|
||||
pub(crate) fn set_active_level(level: Option<LogLevel>) {
|
||||
let _ = REQUEST_LOG.try_with(|log| {
|
||||
if let Ok(mut log) = log.try_borrow_mut() {
|
||||
log.active = level;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Remember that this request offered `text/event-stream`, the only carrier of a notification.
|
||||
pub(crate) fn set_sse_acceptable() {
|
||||
let _ = REQUEST_LOG.try_with(|log| {
|
||||
if let Ok(mut log) = log.try_borrow_mut() {
|
||||
log.sse_acceptable = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Record one event of the closed vocabulary for the level this client opted in to.
|
||||
///
|
||||
/// Everything below the active level, every event without an active level (the client did not opt
|
||||
/// in), and every event beyond the fixed buffer bound is dropped silently: the caller never branches
|
||||
/// on logging.
|
||||
pub(crate) fn note(level: LogLevel, event: &'static str, outcome: &'static str) {
|
||||
let _ = REQUEST_LOG.try_with(|log| {
|
||||
let Ok(mut log) = log.try_borrow_mut() else {
|
||||
return;
|
||||
};
|
||||
let Some(active) = log.active else {
|
||||
return;
|
||||
};
|
||||
if level < active || log.pending.len() >= MAX_PENDING_NOTIFICATIONS {
|
||||
return;
|
||||
}
|
||||
log.pending.push(SafeEvent {
|
||||
level,
|
||||
event,
|
||||
outcome,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The pending events as wire `notifications/message` bodies, and whether this request can carry
|
||||
/// them at all. Draining is the last step of the response projection, so a notification can never be
|
||||
/// delivered twice or survive into another request.
|
||||
pub(crate) fn take_notifications() -> Vec<Value> {
|
||||
REQUEST_LOG
|
||||
.try_with(|log| {
|
||||
let Ok(mut log) = log.try_borrow_mut() else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !log.sse_acceptable {
|
||||
// A JSON body has no place for a server notification: the event is not delivered
|
||||
// instead of being smuggled into the result object.
|
||||
log.pending.clear();
|
||||
return Vec::new();
|
||||
}
|
||||
std::mem::take(&mut log.pending)
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/message",
|
||||
"params": {
|
||||
"level": event.level.as_str(),
|
||||
"logger": LOGGER_NAME,
|
||||
"data": {
|
||||
"event": event.event,
|
||||
"outcome": event.outcome,
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The per-session opt-in of the legacy era.
|
||||
///
|
||||
/// The login belongs to the session the client negotiated, so a level set by one agent's client can
|
||||
/// never apply to another. It is deliberately **in-memory only**: persisting it would need a schema
|
||||
/// migration of the transport session store, and the deprecated capability does not justify that.
|
||||
///
|
||||
/// shortcut: the table is per process — a level set on one replica is not seen by another replica
|
||||
/// serving the same session, and a restart clears it; upgrade to the session store if a durable or
|
||||
/// cross-replica level is ever required.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct LogLevelStore {
|
||||
levels: Mutex<HashMap<String, LogLevel>>,
|
||||
}
|
||||
|
||||
impl LogLevelStore {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Store the level of one session. Never waits and never fails: on lock contention the update is
|
||||
/// skipped rather than blocking the request.
|
||||
pub(crate) fn set(&self, session_id: &str, level: LogLevel) {
|
||||
let Some(mut levels) = self.lock() else {
|
||||
return;
|
||||
};
|
||||
if levels.len() >= MAX_TRACKED_SESSIONS && !levels.contains_key(session_id) {
|
||||
// Bounded table: the oldest opt-ins are dropped instead of growing without a limit. A
|
||||
// dropped client simply stops receiving notifications until it sets its level again.
|
||||
levels.clear();
|
||||
}
|
||||
levels.insert(session_id.to_owned(), level);
|
||||
}
|
||||
|
||||
/// The level of one session, if this process still remembers it.
|
||||
pub(crate) fn get(&self, session_id: &str) -> Option<LogLevel> {
|
||||
self.lock()?.get(session_id).copied()
|
||||
}
|
||||
|
||||
fn lock(&self) -> Option<MutexGuard<'_, HashMap<String, LogLevel>>> {
|
||||
self.levels.try_lock().ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve one `logging/setLevel` request of the legacy era (AC1/AC2).
|
||||
///
|
||||
/// The command has already been parsed from the wire form, so this function only validates and
|
||||
/// records; it never reads the registry, the catalog or any stored value.
|
||||
pub(crate) fn handle_logging_command(
|
||||
store: &LogLevelStore,
|
||||
session_id: &str,
|
||||
command: SetLevelCommand,
|
||||
) -> LoggingOutcome {
|
||||
match command.validate() {
|
||||
Ok(level) => {
|
||||
store.set(session_id, level);
|
||||
LoggingOutcome::Applied(level)
|
||||
}
|
||||
Err(detail) => LoggingOutcome::InvalidParams(detail),
|
||||
}
|
||||
}
|
||||
|
||||
/// The level a modern request asked for in `_meta`.
|
||||
///
|
||||
/// The pinned schema says the server must not send `notifications/message` for a request that does
|
||||
/// not carry the key, so an absent, non-string or unknown value is simply "not opted in": it is not
|
||||
/// an error of the business request and never widens the accepted vocabulary.
|
||||
pub(crate) fn modern_request_level(message: &Value) -> Option<LogLevel> {
|
||||
let meta = crate::jsonrpc::params(message).get("_meta")?.clone();
|
||||
let value = meta.get(crate::jsonrpc::META_LOG_LEVEL_KEY)?.as_str()?;
|
||||
LogLevel::parse(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "logging_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,316 @@
|
||||
//! Unit contract of Story 3.18: the pinned level vocabulary, the bounded input contract of
|
||||
//! `logging/setLevel`, the request-scoped bounded event buffer and the closed safe notification
|
||||
//! shape.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Parse one `logging/setLevel` params object and validate its level, or `None` when the shape itself
|
||||
/// is malformed (which the adapter answers with the same safe detail).
|
||||
fn validate(level: &str) -> Option<Result<LogLevel, &'static str>> {
|
||||
let command: SetLevelCommand = serde_json::from_value(json!({ "level": level })).ok()?;
|
||||
Some(command.validate())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pinned_level_is_accepted_exactly_once_and_in_severity_order() {
|
||||
// The pinned `LoggingLevel` union of both revisions, most verbose first.
|
||||
let pinned = [
|
||||
("debug", LogLevel::Debug),
|
||||
("info", LogLevel::Info),
|
||||
("notice", LogLevel::Notice),
|
||||
("warning", LogLevel::Warning),
|
||||
("error", LogLevel::Error),
|
||||
("critical", LogLevel::Critical),
|
||||
("alert", LogLevel::Alert),
|
||||
("emergency", LogLevel::Emergency),
|
||||
];
|
||||
for (index, (literal, expected)) in pinned.iter().enumerate() {
|
||||
assert_eq!(
|
||||
LogLevel::parse(literal),
|
||||
Some(*expected),
|
||||
"{literal} is a pinned level"
|
||||
);
|
||||
assert_eq!(
|
||||
expected.as_str(),
|
||||
*literal,
|
||||
"the wire literal of a level is exactly the pinned string"
|
||||
);
|
||||
assert_eq!(
|
||||
*expected as usize, index,
|
||||
"the severity ordering of {literal} must follow the RFC 5424 order"
|
||||
);
|
||||
assert_eq!(
|
||||
validate(literal),
|
||||
Some(Ok(*expected)),
|
||||
"{literal} must be accepted through the wire shape too"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
pinned.windows(2).all(|pair| pair[0].1 < pair[1].1),
|
||||
"severity must be strictly increasing so the filter is `event >= level`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_outside_the_pinned_union_is_a_level() {
|
||||
for value in [
|
||||
"",
|
||||
"warn",
|
||||
"WARN",
|
||||
"Info",
|
||||
"information",
|
||||
" debug",
|
||||
"debug ",
|
||||
"0",
|
||||
"7",
|
||||
"emergency!",
|
||||
"debug\u{0}",
|
||||
"информация",
|
||||
] {
|
||||
assert_eq!(
|
||||
LogLevel::parse(value),
|
||||
None,
|
||||
"{value:?} is not one of the pinned literals and must never be coerced into one"
|
||||
);
|
||||
assert_eq!(
|
||||
validate(value),
|
||||
Some(Err(INVALID_LEVEL)),
|
||||
"a value outside the union is a bounded invalid-params detail, got {value:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_level_shapes_share_one_safe_detail() {
|
||||
// A `level` the schema types as a string, sent as something else: a deserialization error that the
|
||||
// adapter answers with the same safe detail. It never echoes what the client sent.
|
||||
for value in [json!(7), json!(1.5), json!(0)] {
|
||||
assert!(
|
||||
serde_json::from_value::<SetLevelCommand>(json!({ "level": value })).is_err(),
|
||||
"a numeric level is not a pinned LoggingLevel"
|
||||
);
|
||||
}
|
||||
for value in [json!(null), json!({}), json!(["info"]), json!(true)] {
|
||||
assert!(
|
||||
serde_json::from_value::<SetLevelCommand>(json!({ "level": value })).is_err(),
|
||||
"a non-string level is not a pinned LoggingLevel"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
serde_json::from_value::<SetLevelCommand>(json!({})).is_err(),
|
||||
"the pinned request requires `level`"
|
||||
);
|
||||
// Control: the same safe detail is what an unknown string produces, so both malformed shapes are
|
||||
// indistinguishable on the wire and neither discloses what was sent.
|
||||
assert_eq!(validate("verbose"), Some(Err(INVALID_LEVEL)));
|
||||
assert!(
|
||||
INVALID_LEVEL.len() < 64,
|
||||
"the detail stays a fixed short text"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_level_is_refused_before_any_comparison() {
|
||||
let oversized = "i".repeat(MAX_LEVEL_BYTES + 1);
|
||||
assert_eq!(validate(&oversized), Some(Err(INVALID_LEVEL)));
|
||||
// Positive control: the bound is not so tight that a pinned literal is refused.
|
||||
assert_eq!(validate("emergency"), Some(Ok(LogLevel::Emergency)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_session_opt_in_is_per_session_and_bounded() {
|
||||
let store = LogLevelStore::new();
|
||||
store.set("session-a", LogLevel::Error);
|
||||
store.set("session-b", LogLevel::Debug);
|
||||
assert_eq!(store.get("session-a"), Some(LogLevel::Error));
|
||||
assert_eq!(store.get("session-b"), Some(LogLevel::Debug));
|
||||
assert_eq!(
|
||||
store.get("session-c"),
|
||||
None,
|
||||
"a session that never opted in must not inherit another session's level"
|
||||
);
|
||||
|
||||
// The table stays bounded: filling it past the cap drops the previous opt-ins instead of growing.
|
||||
for index in 0..MAX_TRACKED_SESSIONS {
|
||||
store.set(&format!("filler-{index}"), LogLevel::Info);
|
||||
}
|
||||
store.set("session-after-cap", LogLevel::Alert);
|
||||
assert_eq!(store.get("session-after-cap"), Some(LogLevel::Alert));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_event_is_delivered_only_at_or_above_the_opted_in_level() {
|
||||
// One closed-vocabulary event per severity, recorded inside a request scope that offered SSE.
|
||||
for (active, expected) in [
|
||||
(LogLevel::Debug, 4usize),
|
||||
(LogLevel::Info, 4),
|
||||
(LogLevel::Notice, 3),
|
||||
(LogLevel::Warning, 2),
|
||||
(LogLevel::Error, 1),
|
||||
(LogLevel::Critical, 0),
|
||||
(LogLevel::Alert, 0),
|
||||
(LogLevel::Emergency, 0),
|
||||
] {
|
||||
let delivered = scoped(async move {
|
||||
set_active_level(Some(active));
|
||||
set_sse_acceptable();
|
||||
note(LogLevel::Info, EVENT_SERVED, "ok");
|
||||
note(LogLevel::Notice, EVENT_LEVEL_APPLIED, "applied");
|
||||
note(LogLevel::Warning, EVENT_REJECTED, "invalid_params");
|
||||
note(LogLevel::Error, EVENT_FAILED, "internal");
|
||||
take_notifications()
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
delivered.len(),
|
||||
expected,
|
||||
"level {} must deliver exactly the events at or above it",
|
||||
active.as_str()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_an_opt_in_nothing_is_even_recorded() {
|
||||
// Outside a scope (no request, e.g. a background worker): a no-op.
|
||||
note(LogLevel::Info, EVENT_SERVED, "ok");
|
||||
assert!(take_notifications().is_empty());
|
||||
|
||||
// Inside a scope without an opted-in level.
|
||||
let no_level = scoped(async {
|
||||
set_sse_acceptable();
|
||||
note(LogLevel::Error, EVENT_FAILED, "internal");
|
||||
take_notifications()
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
no_level.is_empty(),
|
||||
"the pinned modern schema forbids notifications for a client that did not opt in"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_level_is_present_but_the_client_offered_no_stream() {
|
||||
let delivered = scoped(async {
|
||||
set_active_level(Some(LogLevel::Debug));
|
||||
note(LogLevel::Error, EVENT_FAILED, "internal");
|
||||
take_notifications()
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
delivered.is_empty(),
|
||||
"a JSON body has no carrier for notifications/message; the event is dropped, not smuggled in"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_buffer_is_bounded_and_drains_once() {
|
||||
let (first, second) = scoped(async {
|
||||
set_active_level(Some(LogLevel::Debug));
|
||||
set_sse_acceptable();
|
||||
for _ in 0..(MAX_PENDING_NOTIFICATIONS * 4) {
|
||||
note(LogLevel::Info, EVENT_SERVED, "ok");
|
||||
}
|
||||
let first = take_notifications();
|
||||
let second = take_notifications();
|
||||
(first, second)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
first.len(),
|
||||
MAX_PENDING_NOTIFICATIONS,
|
||||
"the per-response frequency bound"
|
||||
);
|
||||
assert!(
|
||||
second.is_empty(),
|
||||
"a delivered event must not survive into a later response"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_notification_body_is_exactly_the_closed_safe_shape() {
|
||||
let delivered = scoped(async {
|
||||
set_active_level(Some(LogLevel::Debug));
|
||||
set_sse_acceptable();
|
||||
note(LogLevel::Warning, EVENT_REJECTED, "invalid_params");
|
||||
take_notifications()
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
delivered,
|
||||
vec![json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/message",
|
||||
"params": {
|
||||
"level": "warning",
|
||||
"logger": "crank-mcp-server",
|
||||
"data": {"event": "mcp.request.rejected", "outcome": "invalid_params"}
|
||||
}
|
||||
})],
|
||||
"`params` carries only the severity, the fixed logger name and the closed data object"
|
||||
);
|
||||
// A notification has no `id`, so it can never be mistaken for a response.
|
||||
assert!(delivered[0].get("id").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_modern_level_is_read_from_the_pinned_meta_key_only() {
|
||||
let modern = |meta: Value| json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {"_meta": meta}});
|
||||
assert_eq!(
|
||||
modern_request_level(&modern(
|
||||
json!({ "io.modelcontextprotocol/logLevel": "error" })
|
||||
)),
|
||||
Some(LogLevel::Error)
|
||||
);
|
||||
// Not opted in: an absent key, a non-string value and an unknown literal are all "no level".
|
||||
assert_eq!(modern_request_level(&modern(json!({}))), None);
|
||||
assert_eq!(
|
||||
modern_request_level(&modern(json!({ "io.modelcontextprotocol/logLevel": 7 }))),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
modern_request_level(&modern(
|
||||
json!({ "io.modelcontextprotocol/logLevel": "verbose" })
|
||||
)),
|
||||
None
|
||||
);
|
||||
// A level under another key is not the pinned carrier.
|
||||
assert_eq!(
|
||||
modern_request_level(&modern(json!({ "logLevel": "error" }))),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
modern_request_level(&json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_records_the_level_of_its_own_session_only() {
|
||||
let store = LogLevelStore::new();
|
||||
store.set("other-session", LogLevel::Debug);
|
||||
let command: SetLevelCommand =
|
||||
serde_json::from_value(json!({ "level": "critical" })).expect("a pinned level parses");
|
||||
let outcome = handle_logging_command(&store, "this-session", command);
|
||||
assert!(matches!(
|
||||
outcome,
|
||||
LoggingOutcome::Applied(LogLevel::Critical)
|
||||
));
|
||||
assert_eq!(store.get("this-session"), Some(LogLevel::Critical));
|
||||
assert_eq!(
|
||||
store.get("other-session"),
|
||||
Some(LogLevel::Debug),
|
||||
"setting one session's level must never change another client's level"
|
||||
);
|
||||
|
||||
// A malformed level changes nothing.
|
||||
let malformed: SetLevelCommand =
|
||||
serde_json::from_value(json!({ "level": "verbose" })).expect("the shape parses");
|
||||
assert!(matches!(
|
||||
handle_logging_command(&store, "this-session", malformed),
|
||||
LoggingOutcome::InvalidParams(INVALID_LEVEL)
|
||||
));
|
||||
assert_eq!(store.get("this-session"), Some(LogLevel::Critical));
|
||||
}
|
||||
@@ -0,0 +1,854 @@
|
||||
//! Era resolution and the small static server-capability registration for the MCP endpoint.
|
||||
//!
|
||||
//! Scope: exactly two approved revisions — `2026-07-28` (modern stateless) and `2025-11-25` (legacy
|
||||
//! session). Withdrawn revisions (`2025-06-18`, `2025-03-26`) are rejected safely and are never an
|
||||
//! implicit identity. There is no command bus, plugin surface or experimental configuration here: a
|
||||
//! single registration source feeds the advertised capability descriptor.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use serde::Deserialize as _;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::jsonrpc::{
|
||||
HEADER_MISMATCH_ERROR_CODE, LEGACY_PROTOCOL_VERSION, META_CLIENT_CAPABILITIES_KEY,
|
||||
META_CLIENT_INFO_KEY, META_PROTOCOL_VERSION_KEY, MODERN_PROTOCOL_VERSION,
|
||||
SUPPORTED_PROTOCOL_VERSIONS, UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE, correlated_error_data,
|
||||
jsonrpc_error, method_name, params, request_id,
|
||||
};
|
||||
use crate::session::SessionState;
|
||||
use crate::transport::{json_response, protocol_version_from_headers, singleton_header};
|
||||
|
||||
mod command;
|
||||
mod completion;
|
||||
mod logging;
|
||||
mod prompts;
|
||||
mod registry;
|
||||
mod resources;
|
||||
|
||||
pub(crate) use command::{
|
||||
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
|
||||
ToolsListCommand, ToolsOutcome, handle_tools_command,
|
||||
};
|
||||
pub(crate) use completion::{CompletionCommand, CompletionOutcome, handle_completion_command};
|
||||
pub(crate) use logging::{
|
||||
EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL, LogLevel,
|
||||
LogLevelStore, LoggingOutcome, SetLevelCommand, handle_logging_command, modern_request_level,
|
||||
note, scoped as logging_scope, set_active_level, set_sse_acceptable, take_notifications,
|
||||
};
|
||||
pub(crate) use prompts::{
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, handle_prompts_command,
|
||||
};
|
||||
pub(crate) use resources::{
|
||||
ResourceReadCommand, ResourceTemplatesListError, ResourcesCommand, ResourcesListCommand,
|
||||
ResourcesOutcome, handle_resources_command, list_resource_templates,
|
||||
};
|
||||
|
||||
/// Resolved era of an incoming POST request.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum RequestEra {
|
||||
Modern,
|
||||
Legacy,
|
||||
}
|
||||
|
||||
/// Envelope class of an incoming POST message, decided by the single JSON-RPC envelope guard.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum EnvelopeKind {
|
||||
/// A request: `method` plus a valid request id.
|
||||
Request,
|
||||
/// A notification: `method` without an id.
|
||||
Notification,
|
||||
/// A response to a server-initiated request: no `method`, a `result` or `error`.
|
||||
Response,
|
||||
}
|
||||
|
||||
/// The JSON-RPC literal that every message on both eras must carry.
|
||||
const JSONRPC_VERSION: &str = "2.0";
|
||||
|
||||
/// The pinned modern schema types a request id as `RequestId = string | number`.
|
||||
fn is_valid_request_id(id: &Value) -> bool {
|
||||
id.is_string() || id.is_number()
|
||||
}
|
||||
|
||||
/// The pinned error object: `Error { code: number; message: string; data?: unknown }`.
|
||||
fn is_valid_error_object(error: Option<&Value>) -> bool {
|
||||
let Some(Value::Object(error)) = error else {
|
||||
return false;
|
||||
};
|
||||
error.get("code").is_some_and(Value::is_number)
|
||||
&& error.get("message").is_some_and(Value::is_string)
|
||||
}
|
||||
|
||||
/// Classify a wire response (a message without `method`).
|
||||
///
|
||||
/// Pinned shapes are exclusive: a success response carries `result: Result` (an object) and a required
|
||||
/// `id: RequestId`, an error response carries `error: Error` and may omit the id (a present id must
|
||||
/// still be a `RequestId`). Both together, neither, a foreign id, a non-object `result` or a malformed
|
||||
/// error object are all invalid requests rather than an acknowledgement.
|
||||
///
|
||||
/// The `result` value is required to be an object because the pinned `JSONRPCResultResponse` types it as
|
||||
/// `Result`; the modern `resultType` member is deliberately **not** required here, because an incoming
|
||||
/// response may come from a client implementing an earlier revision.
|
||||
fn classify_wire_response(object: &serde_json::Map<String, Value>) -> Option<EnvelopeKind> {
|
||||
match (object.contains_key("result"), object.contains_key("error")) {
|
||||
(true, false) => {
|
||||
if !matches!(object.get("result"), Some(Value::Object(_))) {
|
||||
return None;
|
||||
}
|
||||
object
|
||||
.get("id")
|
||||
.filter(|id| is_valid_request_id(id))
|
||||
.map(|_| EnvelopeKind::Response)
|
||||
}
|
||||
(false, true) => {
|
||||
if !is_valid_error_object(object.get("error")) {
|
||||
return None;
|
||||
}
|
||||
match object.get("id") {
|
||||
None => Some(EnvelopeKind::Response),
|
||||
Some(id) if is_valid_request_id(id) => Some(EnvelopeKind::Response),
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pinned modern wire projection of a success result.
|
||||
///
|
||||
/// `JSONRPCResultResponse.result` is a `Result`, and this revision requires the `resultType` member
|
||||
/// ("Servers implementing this protocol version MUST include this field"). Every result this server
|
||||
/// produces is a synchronous, fully computed result, so the value is `complete`. The projection is a
|
||||
/// no-op for the legacy revision, whose earlier schema has no such member, and it only ever adds the
|
||||
/// required member — the business payload is passed through untouched.
|
||||
pub(crate) fn project_modern_result(protocol_version: &str, result: Value) -> Value {
|
||||
if protocol_version != MODERN_PROTOCOL_VERSION {
|
||||
return result;
|
||||
}
|
||||
let Value::Object(mut object) = result else {
|
||||
return result;
|
||||
};
|
||||
object
|
||||
.entry("resultType".to_owned())
|
||||
.or_insert_with(|| Value::String("complete".to_owned()));
|
||||
Value::Object(object)
|
||||
}
|
||||
|
||||
/// The same projection for a result that extends `CacheableResult` (`tools/list`): the pinned schema
|
||||
/// makes `ttlMs` and `cacheScope` mandatory there as well. No cache policy exists for this slice, so the
|
||||
/// conservative and honest hints are `0` (immediately stale) and `private` (scoped to the authorized
|
||||
/// agent); this adds no caching framework.
|
||||
pub(crate) fn project_modern_cacheable_result(protocol_version: &str, result: Value) -> Value {
|
||||
let result = project_modern_result(protocol_version, result);
|
||||
if protocol_version != MODERN_PROTOCOL_VERSION {
|
||||
return result;
|
||||
}
|
||||
let Value::Object(mut object) = result else {
|
||||
return result;
|
||||
};
|
||||
object.entry("ttlMs".to_owned()).or_insert_with(|| json!(0));
|
||||
object
|
||||
.entry("cacheScope".to_owned())
|
||||
.or_insert_with(|| Value::String("private".to_owned()));
|
||||
Value::Object(object)
|
||||
}
|
||||
|
||||
/// Minimal `serde` helper for a field the advertised schema types as an **object**: a JSON object is
|
||||
/// accepted as is, while a missing key, `null`, an array or a scalar is a deserialization error. It is
|
||||
/// the shared shape check for the tool-call parameter objects (the top-level `arguments` of `tools/call`
|
||||
/// and the nested `arguments` of the `call_tool` proxy), so both eras reject the same invalid shapes
|
||||
/// before any approval or outbound work.
|
||||
pub(crate) fn deserialize_object_only<'de, D>(deserializer: D) -> Result<Value, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = Value::deserialize(deserializer)?;
|
||||
match value {
|
||||
Value::Object(map) => Ok(Value::Object(map)),
|
||||
other => Err(serde::de::Error::custom(format!(
|
||||
"`arguments` must be an object, got {}",
|
||||
json_type_name(&other)
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn json_type_name(value: &Value) -> &'static str {
|
||||
match value {
|
||||
Value::Null => "null",
|
||||
Value::Bool(_) => "boolean",
|
||||
Value::Number(_) => "number",
|
||||
Value::String(_) => "string",
|
||||
Value::Array(_) => "array",
|
||||
Value::Object(_) => "object",
|
||||
}
|
||||
}
|
||||
|
||||
/// `400` + `-32600`. JSON-RPC requires the response id to be null for an invalid request, so a value
|
||||
/// that could not be validated is never echoed back.
|
||||
fn invalid_request_response() -> Response {
|
||||
let error = jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC request".to_owned());
|
||||
|
||||
json_response(StatusCode::BAD_REQUEST, error, None, None)
|
||||
}
|
||||
|
||||
/// The response id for a message whose JSON-RPC envelope has **not** necessarily been validated yet.
|
||||
///
|
||||
/// The session-carrier projections (`ambiguous_session_carrier_response`,
|
||||
/// `malformed_carrier_response`) reject a request for its carrier and therefore run *before* the
|
||||
/// single envelope guard, so the body id they read may still be an invalid kind
|
||||
/// (`object`/`boolean`/`array`). JSON-RPC requires the response id to be null whenever the request
|
||||
/// could not be validated — the same convention `invalid_request_response` uses — so an id that is
|
||||
/// not a `RequestId` is never echoed back. A valid `string`/`number` id is preserved unchanged, an
|
||||
/// absent id stays null, and this changes nothing for a caller that already passed the guard (such a
|
||||
/// message can only carry a valid id or none at all).
|
||||
fn safe_response_id(message: &Value) -> Value {
|
||||
let id = request_id(message);
|
||||
if is_valid_request_id(&id) {
|
||||
id
|
||||
} else {
|
||||
Value::Null
|
||||
}
|
||||
}
|
||||
|
||||
/// The one JSON-RPC envelope guard: the body must be a well-formed JSON-RPC message before any era
|
||||
/// resolution, dispatch, approval or outbound request happens. JSON extraction succeeding only proves
|
||||
/// the body was syntactically valid JSON, which is a different property from envelope validity.
|
||||
pub(crate) fn validate_jsonrpc_envelope(message: &Value) -> Result<EnvelopeKind, Rejection> {
|
||||
let Some(object) = message.as_object() else {
|
||||
return Err(rejected(invalid_request_response()));
|
||||
};
|
||||
|
||||
match object.get("jsonrpc") {
|
||||
Some(Value::String(version)) if version == JSONRPC_VERSION => {}
|
||||
_ => return Err(rejected(invalid_request_response())),
|
||||
}
|
||||
|
||||
match object.get("method") {
|
||||
Some(Value::String(method)) if !method.trim().is_empty() => {
|
||||
if let Some(Value::Object(_)) | None = object.get("params") {
|
||||
} else {
|
||||
return Err(rejected(invalid_request_response()));
|
||||
}
|
||||
|
||||
match object.get("id") {
|
||||
None => Ok(EnvelopeKind::Notification),
|
||||
Some(id) if is_valid_request_id(id) => Ok(EnvelopeKind::Request),
|
||||
// A present but invalid id is neither a valid request nor a notification: it must
|
||||
// never be acknowledged as one.
|
||||
Some(_) => Err(rejected(invalid_request_response())),
|
||||
}
|
||||
}
|
||||
Some(_) => Err(rejected(invalid_request_response())),
|
||||
None => match classify_wire_response(object) {
|
||||
Some(kind) => Ok(kind),
|
||||
None => Err(rejected(invalid_request_response())),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A live transport session is operational only under the supported legacy revision.
|
||||
///
|
||||
/// Sessions are persisted, so a session created under a withdrawn revision can still be found in the
|
||||
/// store. It must be rejected with a safe error instead of being served as a live legacy session,
|
||||
/// even when the request carries no version header.
|
||||
pub(crate) fn validate_session_revision(session: &SessionState) -> Result<(), StatusCode> {
|
||||
if session.protocol_version == LEGACY_PROTOCOL_VERSION {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::BAD_REQUEST)
|
||||
}
|
||||
}
|
||||
|
||||
/// Admit the session-lifecycle HTTP methods (`GET`/`DELETE`) only for the legacy era.
|
||||
///
|
||||
/// The modern revision removed the standalone GET stream endpoint and is stateless, so an explicit
|
||||
/// modern identity answers `405` instead of reaching the legacy session lifecycle. An unknown,
|
||||
/// withdrawn or unreadable revision is a safe admission error. Only a verified legacy session — a
|
||||
/// legacy revision header, or no header at all with the identity taken from the session itself — may
|
||||
/// continue into the session branch.
|
||||
pub(crate) fn session_lifecycle_admission(headers: &HeaderMap) -> Result<(), Rejection> {
|
||||
match protocol_version_from_headers(headers) {
|
||||
Err(status) => Err(rejected(status.into_response())),
|
||||
Ok(None) => Ok(()),
|
||||
Ok(Some(version)) if version == LEGACY_PROTOCOL_VERSION => Ok(()),
|
||||
Ok(Some(version)) if version == MODERN_PROTOCOL_VERSION => {
|
||||
Err(rejected(StatusCode::METHOD_NOT_ALLOWED.into_response()))
|
||||
}
|
||||
Ok(Some(_)) => Err(rejected(StatusCode::BAD_REQUEST.into_response())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity resolved from the request before any method dispatch.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct RequestIdentity {
|
||||
pub(crate) era: RequestEra,
|
||||
/// Negotiated revision when the request itself carries one (modern requests and legacy
|
||||
/// `initialize`). Legacy subsequent requests identify the revision through their session instead.
|
||||
pub(crate) version: Option<String>,
|
||||
}
|
||||
|
||||
/// Ready-made rejection, boxed because a response is much larger than the identity it replaces.
|
||||
type Rejection = Box<Response>;
|
||||
|
||||
fn rejected(response: Response) -> Rejection {
|
||||
Box::new(response)
|
||||
}
|
||||
|
||||
/// The one registration source for the advertised server capabilities, indexed by the revision the
|
||||
/// caller serves. Advertisement equals what is implemented: later capabilities are added to the
|
||||
/// static registration by their owning story, not pre-declared here. Both the modern
|
||||
/// `discover_result` and the legacy `handle_initialize` pass the revision they serve, so a
|
||||
/// single-era declaration never leaks into the other era (R6).
|
||||
pub(crate) fn advertised_server_capabilities(revision: &str) -> Value {
|
||||
request_registration().map_or_else(
|
||||
|| Value::Object(serde_json::Map::new()),
|
||||
|registration| registration.registry().advertised_capabilities(revision),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) use registry::{CapabilityRegistry, DispatchDecision, Kind, MethodHandler};
|
||||
|
||||
/// The descriptor vocabulary and tables of the static registration, re-exported for the
|
||||
/// BUILD-internal registration test seam (spec sections 6.3/7.2): the in-crate observer tests add one
|
||||
/// inert private descriptor to a copy of these tables and prove that the real dispatch and
|
||||
/// advertisement move with it. The production registration itself is unchanged.
|
||||
#[cfg(test)]
|
||||
pub(crate) use registry::{
|
||||
CAPABILITY_DESCRIPTORS, CapabilityId, CapabilityIdDescriptor, FeatureSet, HeaderSet,
|
||||
METHOD_DESCRIPTORS, MethodDescriptor, Roster,
|
||||
};
|
||||
|
||||
/// The one owning registration of this endpoint (R5/D-3), held by the protocol layer both era
|
||||
/// adapters go through.
|
||||
///
|
||||
/// The snapshot is validated once and then reused, so dispatch and advertisement are derived from
|
||||
/// the *same* registration and cannot drift; the adapters keep no method list of their own. An
|
||||
/// invalid static table registers nothing at all (fail-closed): every dispatch is refused instead of
|
||||
/// being served from a table that contradicts itself. The table itself is proven valid by
|
||||
/// `protocol::registry::tests::`.
|
||||
static CAPABILITY_REGISTRY: OnceLock<Option<CapabilityRegistry>> = OnceLock::new();
|
||||
|
||||
/// The validated registration snapshot of this endpoint.
|
||||
pub(crate) fn capability_registry() -> Option<&'static CapabilityRegistry> {
|
||||
CAPABILITY_REGISTRY
|
||||
.get_or_init(|| {
|
||||
CapabilityRegistry::new(
|
||||
registry::CAPABILITY_DESCRIPTORS,
|
||||
registry::METHOD_DESCRIPTORS,
|
||||
)
|
||||
.ok()
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The registration a request is served with: the production snapshot, unless the in-crate observer
|
||||
/// test installed one for this request (`app::dispatch_observer`, `#[cfg(test)]` only). The seam
|
||||
/// exists so the add/remove proof runs against the *real* router instead of a registry unit query.
|
||||
fn request_registration() -> Option<RegistrationHandle> {
|
||||
#[cfg(test)]
|
||||
if let Some(registration) = crate::app::dispatch_observer::installed_registration() {
|
||||
return Some(RegistrationHandle::Test(registration));
|
||||
}
|
||||
capability_registry().map(RegistrationHandle::Production)
|
||||
}
|
||||
|
||||
enum RegistrationHandle {
|
||||
Production(&'static CapabilityRegistry),
|
||||
#[cfg(test)]
|
||||
Test(std::sync::Arc<CapabilityRegistry>),
|
||||
}
|
||||
|
||||
impl RegistrationHandle {
|
||||
fn registry(&self) -> &CapabilityRegistry {
|
||||
match self {
|
||||
Self::Production(registration) => registration,
|
||||
#[cfg(test)]
|
||||
Self::Test(registration) => registration,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The registration-backed dispatch entry point shared by both era adapters (R5/D-3).
|
||||
///
|
||||
/// A method no descriptor owns has no handler, and a method whose owning capability is not eligible
|
||||
/// in the requested revision is a wrong-era request: neither can reach a service or make an outbound
|
||||
/// call, because both adapters dispatch on this decision.
|
||||
pub(crate) fn dispatch_decision(method: &str, revision: &str) -> DispatchDecision {
|
||||
request_registration().map_or(DispatchDecision::Unregistered, |registration| {
|
||||
registration.registry().dispatch_decision(method, revision)
|
||||
})
|
||||
}
|
||||
|
||||
fn error_response(message: &Value, code: i64, text: String) -> Response {
|
||||
json_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
jsonrpc_error(safe_response_id(message), code, text),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Header carrying the invoked method on modern HTTP requests (required for every modern request).
|
||||
pub(crate) const HEADER_MCP_METHOD: &str = "Mcp-Method";
|
||||
|
||||
/// Declared `Mcp-Method` value of a modern request.
|
||||
///
|
||||
/// Conflicting duplicate values are an ambiguous method declaration and are rejected as a header
|
||||
/// mismatch instead of resolving to the first value; identical duplicates collapse to one value.
|
||||
pub(crate) fn declared_mcp_method<'a>(
|
||||
headers: &'a HeaderMap,
|
||||
message: &Value,
|
||||
) -> Result<Option<&'a str>, Rejection> {
|
||||
singleton_header(headers, HEADER_MCP_METHOD)
|
||||
.map_err(|_| rejected(modern_header_mismatch_response(message)))
|
||||
}
|
||||
|
||||
/// Header carrying `params.name` on modern `tools/call` requests.
|
||||
pub(crate) const HEADER_MCP_NAME: &str = "Mcp-Name";
|
||||
|
||||
const BASE64_SENTINEL_PREFIX: &str = "=?base64?";
|
||||
const BASE64_SENTINEL_SUFFIX: &str = "?=";
|
||||
|
||||
/// `400` + `-32020` for a modern request whose declared method header is missing or mismatched.
|
||||
pub(crate) fn modern_header_mismatch_response(message: &Value) -> Response {
|
||||
header_mismatch_response(message, "`Mcp-Method` must match the invoked method")
|
||||
}
|
||||
|
||||
/// `400` + `-32020` for a modern request that carries a session header. The modern revision is
|
||||
/// stateless, so a session carrier is a conflicting identity — it is rejected before any session
|
||||
/// lookup, rate-limit accounting or dispatch, and it is never silently ignored.
|
||||
pub(crate) fn modern_carrier_conflict_response(message: &Value) -> Response {
|
||||
header_mismatch_response(
|
||||
message,
|
||||
"the negotiated revision is stateless and does not accept a session header",
|
||||
)
|
||||
}
|
||||
|
||||
/// `202 Accepted` with no body: a notification carries no `id`, so nothing is dispatched.
|
||||
pub(crate) fn modern_notification_response() -> Response {
|
||||
StatusCode::ACCEPTED.into_response()
|
||||
}
|
||||
|
||||
/// Era-correct answer for a method that the modern era does not implement.
|
||||
pub(crate) fn modern_method_not_found_response(message: &Value) -> Response {
|
||||
json_response(
|
||||
StatusCode::NOT_FOUND,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32601,
|
||||
"method not found for the negotiated revision".to_owned(),
|
||||
),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Decode a modern header value: the pinned sentinel `=?base64?…?=` is decoded, anything else is
|
||||
/// taken literally. An unreadable sentinel value yields `None` and is rejected as a mismatch.
|
||||
fn decode_header_value(raw: &str) -> Option<String> {
|
||||
let Some(encoded) = raw.strip_prefix(BASE64_SENTINEL_PREFIX) else {
|
||||
return Some(raw.to_owned());
|
||||
};
|
||||
let encoded = encoded.strip_suffix(BASE64_SENTINEL_SUFFIX)?;
|
||||
let bytes = STANDARD.decode(encoded).ok()?;
|
||||
|
||||
String::from_utf8(bytes).ok()
|
||||
}
|
||||
|
||||
/// Validate the required `Mcp-Name` header against the body value.
|
||||
///
|
||||
/// Pinned modern rules: the header is required for `tools/call`, the sentinel-encoded form must be
|
||||
/// decoded before the comparison, and the comparison is case-sensitive.
|
||||
pub(crate) fn validate_modern_request_name(
|
||||
message: &Value,
|
||||
headers: &HeaderMap,
|
||||
body_name: &str,
|
||||
) -> Result<(), Rejection> {
|
||||
let Some(raw) = singleton_header(headers, HEADER_MCP_NAME)
|
||||
.map_err(|_| header_mismatch_response(message, "the `Mcp-Name` header is ambiguous"))?
|
||||
else {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"the required `Mcp-Name` header is missing",
|
||||
)));
|
||||
};
|
||||
let Some(decoded) = decode_header_value(raw) else {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"the `Mcp-Name` header value cannot be decoded",
|
||||
)));
|
||||
};
|
||||
if decoded != body_name {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
&format!(
|
||||
"the `Mcp-Name` header value '{decoded}' does not match the body value '{body_name}'"
|
||||
),
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unsupported_version_response(message: &Value, requested: &str) -> Response {
|
||||
let supported: Vec<&str> = SUPPORTED_PROTOCOL_VERSIONS.to_vec();
|
||||
let mut error = jsonrpc_error(
|
||||
request_id(message),
|
||||
UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE,
|
||||
format!("unsupported protocol version {requested}"),
|
||||
);
|
||||
error["error"]["data"] = correlated_error_data(json!({
|
||||
"requested": requested,
|
||||
"supported": supported,
|
||||
}));
|
||||
|
||||
json_response(StatusCode::BAD_REQUEST, error, None, None)
|
||||
}
|
||||
|
||||
fn header_mismatch_response(message: &Value, details: &str) -> Response {
|
||||
let mut error = jsonrpc_error(
|
||||
safe_response_id(message),
|
||||
HEADER_MISMATCH_ERROR_CODE,
|
||||
"protocol identity mismatch".to_owned(),
|
||||
);
|
||||
// Merge into the correlation data instead of replacing it: the request/trace correlation that
|
||||
// `jsonrpc_error` already attached must survive the added detail.
|
||||
error["error"]["data"] = correlated_error_data(json!({ "details": details }));
|
||||
|
||||
json_response(StatusCode::BAD_REQUEST, error, None, None)
|
||||
}
|
||||
|
||||
/// Era-correct structured rejection for a malformed or ambiguous `MCP-Protocol-Version` carrier
|
||||
/// (`protocol-era-matrix.md` row 17).
|
||||
///
|
||||
/// The carrier is exactly what failed to parse, so it cannot identify the era. The era is read from
|
||||
/// the rest of the request instead: a request carrying a modern identity marker is answered in the
|
||||
/// modern shape (`400` + `-32020` `HeaderMismatch`), anything else stays legacy and is answered with
|
||||
/// the legacy-shaped structured error. A malformed carrier is never re-labelled as a modern
|
||||
/// unsupported-revision answer (`-32022` is reserved for a well-formed but unknown *effective*
|
||||
/// identity), and no era is guessed from the malformed value itself.
|
||||
fn malformed_carrier_response(headers: &HeaderMap, message: &Value) -> Response {
|
||||
const DETAILS: &str = "the `MCP-Protocol-Version` header value is malformed or ambiguous";
|
||||
|
||||
if declares_modern_identity(headers, message) {
|
||||
header_mismatch_response(message, DETAILS)
|
||||
} else {
|
||||
error_response(message, -32602, DETAILS.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Era-correct structured rejection for an ambiguous `MCP-Session-Id` carrier (matrix row 17).
|
||||
///
|
||||
/// A conflicting duplicate session carrier cannot identify the era, exactly like a malformed
|
||||
/// version carrier, and the callers that read it (`GET`/`DELETE`/`POST`) currently answer a bare
|
||||
/// `400` with an empty body. For a POST that carries a JSON-RPC envelope the request must instead be
|
||||
/// answered with the era-correct structured diagnostic: the era is read from the **non-ambiguous**
|
||||
/// part of the request, never guessed from (or resolved to) one of the conflicting values.
|
||||
///
|
||||
/// The session-lifecycle methods keep their own admission path (`GET`/`DELETE` stay HTTP) and never
|
||||
/// reach this projection.
|
||||
pub(crate) fn ambiguous_session_carrier_response(headers: &HeaderMap, message: &Value) -> Response {
|
||||
const DETAILS: &str = "the `MCP-Session-Id` header value is ambiguous";
|
||||
|
||||
if declares_modern_identity(headers, message) {
|
||||
header_mismatch_response(message, DETAILS)
|
||||
} else {
|
||||
error_response(message, -32602, DETAILS.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the non-carrier part of the request identifies the modern era.
|
||||
///
|
||||
/// Used only to pick the era-correct shape for a carrier diagnostic, never to admit a request. Any
|
||||
/// one of these markers is enough, because each is unambiguous on its own:
|
||||
/// - an unambiguously present, supported modern `MCP-Protocol-Version` header — a modern header never
|
||||
/// routes the request into the legacy branch (matrix row 3). A conflicting duplicate or an
|
||||
/// unreadable value resolves to `Err` and therefore cannot choose the era by one of its values
|
||||
/// (row 17);
|
||||
/// - the `Mcp-Method` request header (required by every modern request, absent on a legacy one);
|
||||
/// - a request-scoped `_meta` client identity (with or without its version field).
|
||||
fn declares_modern_identity(headers: &HeaderMap, message: &Value) -> bool {
|
||||
if matches!(
|
||||
protocol_version_from_headers(headers),
|
||||
Ok(Some(version)) if version == MODERN_PROTOCOL_VERSION
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if singleton_header(headers, HEADER_MCP_METHOD)
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
let params = params(message);
|
||||
let meta = params.get("_meta");
|
||||
declares_modern_metadata(meta)
|
||||
|| matches!(meta, Some(Value::Object(meta)) if meta.contains_key(META_PROTOCOL_VERSION_KEY))
|
||||
}
|
||||
|
||||
/// Whether a request `_meta` object carries a modern-specific client identity key.
|
||||
///
|
||||
/// Used to recognise a modern identity that is missing its required version carrier (matrix row 4)
|
||||
/// and to pick the era-correct shape for a carrier diagnostic. It never admits a request: a modern
|
||||
/// identity still requires the version header and the complete request-scoped metadata.
|
||||
fn declares_modern_metadata(meta: Option<&Value>) -> bool {
|
||||
let Some(Value::Object(meta)) = meta else {
|
||||
return false;
|
||||
};
|
||||
|
||||
[META_CLIENT_CAPABILITIES_KEY, META_CLIENT_INFO_KEY]
|
||||
.iter()
|
||||
.any(|key| meta.contains_key(*key))
|
||||
}
|
||||
|
||||
/// The modern era requires the full per-request client identity in `params._meta`:
|
||||
/// `protocolVersion` (string), `clientCapabilities` (object) and `clientInfo` (object with a
|
||||
/// non-empty `name` and `version`). Every failure is a header/metadata mismatch (`-32020`).
|
||||
fn validate_modern_metadata(meta: Option<&Value>, message: &Value) -> Result<(), Rejection> {
|
||||
let Some(Value::Object(meta)) = meta else {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require request `_meta` metadata",
|
||||
)));
|
||||
};
|
||||
|
||||
match meta.get(META_PROTOCOL_VERSION_KEY) {
|
||||
Some(Value::String(version)) if version == MODERN_PROTOCOL_VERSION => {}
|
||||
Some(Value::String(_)) | None => {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require `_meta` protocolVersion",
|
||||
)));
|
||||
}
|
||||
Some(_) => {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"body protocol version must be a string",
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
if !meta
|
||||
.get(META_CLIENT_CAPABILITIES_KEY)
|
||||
.is_some_and(Value::is_object)
|
||||
{
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require request `_meta` client capabilities",
|
||||
)));
|
||||
}
|
||||
|
||||
// `clientInfo` is **optional** in the pinned `RequestMetaObject` (a client SHOULD send it, but an
|
||||
// absent value is valid), so an omitted value is accepted. A value that **is** present must still
|
||||
// satisfy its `Implementation` shape: an object with a non-empty `name` and `version`. The two
|
||||
// required metadata carriers above are not weakened by this.
|
||||
if let Some(client_info) = meta.get(META_CLIENT_INFO_KEY) {
|
||||
let Some(client_info) = client_info.as_object() else {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern request `_meta` clientInfo must be an object",
|
||||
)));
|
||||
};
|
||||
for key in ["name", "version"] {
|
||||
let present = client_info
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|value| !value.trim().is_empty());
|
||||
if !present {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require `_meta` clientInfo name and version",
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve the era and the request identity.
|
||||
///
|
||||
/// Rules (binding precedence rows of `protocol-era-matrix.md`):
|
||||
/// - header and body identity present but different → `-32020` (mismatch takes precedence);
|
||||
/// - a modern identity requires the version header and the full body `_meta` client identity,
|
||||
/// otherwise `-32020`;
|
||||
/// - an unknown or withdrawn identity → `-32022` with the supported list (never an implicit default),
|
||||
/// except on a session-based `initialize`, which is answered legacy-shaped;
|
||||
/// - `initialize` belongs to the legacy session era only: a modern revision in its parameters is
|
||||
/// rejected instead of minting a session;
|
||||
/// - a legacy `initialize` body version outside the approved window → rejected without minting a
|
||||
/// session and without echoing a withdrawn revision as the served identity;
|
||||
/// - `_meta` that already carries a modern-specific client identity key without any version carrier →
|
||||
/// `-32020` header validation failure, never a legacy admission;
|
||||
/// - no identity at all stays "no identity": the legacy session path decides, and nothing is guessed.
|
||||
pub(crate) fn resolve_request_identity(
|
||||
headers: &HeaderMap,
|
||||
message: &Value,
|
||||
) -> Result<RequestIdentity, Rejection> {
|
||||
let header_version = match protocol_version_from_headers(headers) {
|
||||
Ok(version) => version,
|
||||
// A conflicting duplicate carrier or an unreadable value means the request names no usable
|
||||
// revision; a present-but-blank value is the same class. Matrix row 17 requires the
|
||||
// era-correct structured diagnostic for that class instead of a bare `400`, and the epoch
|
||||
// cannot be read from the malformed value itself — only from the rest of the request.
|
||||
Err(_) => return Err(rejected(malformed_carrier_response(headers, message))),
|
||||
};
|
||||
if let Some(version) = header_version.as_deref()
|
||||
&& version.trim().is_empty()
|
||||
{
|
||||
return Err(rejected(malformed_carrier_response(headers, message)));
|
||||
}
|
||||
|
||||
let body_params = params(message);
|
||||
let meta = body_params.get("_meta");
|
||||
let meta_version = match meta {
|
||||
Some(Value::Object(meta)) => match meta.get(META_PROTOCOL_VERSION_KEY) {
|
||||
Some(Value::String(version)) => Some(version.clone()),
|
||||
Some(_) => {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"body protocol version must be a string",
|
||||
)));
|
||||
}
|
||||
None => None,
|
||||
},
|
||||
Some(_) => {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"request _meta must be an object",
|
||||
)));
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
if let (Some(header), Some(meta_version)) = (header_version.as_deref(), meta_version.as_deref())
|
||||
&& header != meta_version
|
||||
{
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"header and body protocol versions differ",
|
||||
)));
|
||||
}
|
||||
|
||||
// `initialize` mints a session, and only the legacy revision is session-based. A modern revision
|
||||
// here is rejected before any session is created, whichever carrier declares it.
|
||||
if matches!(method_name(message), Some("initialize"))
|
||||
&& body_params
|
||||
.get("protocolVersion")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|requested| requested == MODERN_PROTOCOL_VERSION)
|
||||
{
|
||||
return Err(rejected(error_response(
|
||||
message,
|
||||
-32602,
|
||||
format!(
|
||||
"revision {MODERN_PROTOCOL_VERSION} is not a session-based revision; it does not use initialize"
|
||||
),
|
||||
)));
|
||||
}
|
||||
|
||||
let effective = header_version.clone().or_else(|| meta_version.clone());
|
||||
|
||||
// `_meta` that already names a modern-specific client identity key is a modern request whose
|
||||
// required version carrier is missing, not a legacy request: admitting it as legacy would
|
||||
// execute it through the legacy session path (matrix row 4). This condition is independent of
|
||||
// whatever version the request header names — an explicit legacy version header does not turn
|
||||
// such a request into a legacy admission (matrix row 16, mixed carriers are rejected for the era
|
||||
// identified by the dominant carrier) — so the guard runs before the effective identity is
|
||||
// matched and is a header-validation failure before any adapter or session admission.
|
||||
if meta_version.is_none() && declares_modern_metadata(meta) {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require `_meta` protocolVersion",
|
||||
)));
|
||||
}
|
||||
|
||||
let Some(effective) = effective else {
|
||||
if matches!(method_name(message), Some("initialize")) {
|
||||
let requested = body_params
|
||||
.get("protocolVersion")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
if crate::jsonrpc::negotiated_protocol_version(requested).is_none() {
|
||||
return Err(rejected(error_response(
|
||||
message,
|
||||
-32602,
|
||||
format!("unsupported protocol version {requested}"),
|
||||
)));
|
||||
}
|
||||
return Ok(RequestIdentity {
|
||||
era: RequestEra::Legacy,
|
||||
version: Some(requested.to_owned()),
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(RequestIdentity {
|
||||
era: RequestEra::Legacy,
|
||||
version: None,
|
||||
});
|
||||
};
|
||||
|
||||
match effective.as_str() {
|
||||
MODERN_PROTOCOL_VERSION => {
|
||||
// The modern era negotiates per request: the version header is required, and the body
|
||||
// metadata must carry the complete request-scoped client identity.
|
||||
if header_version.is_none() {
|
||||
return Err(rejected(header_mismatch_response(
|
||||
message,
|
||||
"modern requests require the negotiated protocol version header",
|
||||
)));
|
||||
}
|
||||
validate_modern_metadata(meta, message)?;
|
||||
|
||||
Ok(RequestIdentity {
|
||||
era: RequestEra::Modern,
|
||||
version: Some(MODERN_PROTOCOL_VERSION.to_owned()),
|
||||
})
|
||||
}
|
||||
LEGACY_PROTOCOL_VERSION => Ok(RequestIdentity {
|
||||
era: RequestEra::Legacy,
|
||||
version: Some(LEGACY_PROTOCOL_VERSION.to_owned()),
|
||||
}),
|
||||
// A legacy `initialize` negotiates its revision through `params.protocolVersion` and is
|
||||
// rejected **legacy-shaped**: the modern `-32022` contract describes a modern per-request
|
||||
// identity and must not be imposed on the session-based era (matrix row 14). The rejected
|
||||
// revision is still never served, echoed or minted, and no exact legacy code is invented —
|
||||
// this is the same answer the header-less `initialize` already receives.
|
||||
other => {
|
||||
if matches!(method_name(message), Some("initialize")) {
|
||||
return Err(rejected(error_response(
|
||||
message,
|
||||
-32602,
|
||||
format!("unsupported protocol version {other}"),
|
||||
)));
|
||||
}
|
||||
|
||||
Err(rejected(unsupported_version_response(message, other)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pinned `DiscoverResult` for `server/discover` of the revision the caller serves.
|
||||
pub(crate) fn discover_result(revision: &str, server_name: &str, server_version: &str) -> Value {
|
||||
json!({
|
||||
"resultType": "complete",
|
||||
"supportedVersions": SUPPORTED_PROTOCOL_VERSIONS,
|
||||
"capabilities": advertised_server_capabilities(revision),
|
||||
"_meta": {
|
||||
crate::jsonrpc::META_SERVER_INFO_KEY: {
|
||||
"name": server_name,
|
||||
"version": server_version,
|
||||
}
|
||||
},
|
||||
"ttlMs": 0,
|
||||
"cacheScope": "private"
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,822 @@
|
||||
//! Story 3.14: the era-neutral `prompts/list` and `prompts/get` service boundary.
|
||||
//!
|
||||
//! Both requests are answered only from the exact Published Prompt Versions bound in the active
|
||||
//! published Agent snapshot (`agent_prompt_bindings`, read in the same catalog transaction). A Draft,
|
||||
//! a foreign workspace Prompt and an unbound Prompt are therefore not addressable at all: they are
|
||||
//! absent from the bound array, so nothing here looks a Prompt up by a client-supplied id.
|
||||
//!
|
||||
//! Rendering reuses the accepted typed renderer (`PromptDefinition::preview`): every argument error
|
||||
//! (missing, unknown, wrong type, oversized) is decided there *before* a single message is produced,
|
||||
//! and the error outcome carries only the typed reason and the argument name — never a message, a
|
||||
//! dependency payload or metadata of another Prompt (AT-3.14-02).
|
||||
//!
|
||||
//! Archive is a lifecycle state, not a revoke: the immutable publication row survives, so the exact
|
||||
//! bound version of an existing Agent snapshot stays listing/serving (AT-3.14-03). Security
|
||||
//! revocation and dependency invalidation remain separate fail-closed states and are not modelled
|
||||
//! here.
|
||||
//!
|
||||
//! The wire shape stays in the adapters; this module never sees the envelope, the response mode or an
|
||||
//! `axum::Response`.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::prompt::{MAX_TEXT_BYTES, PromptError, PromptMessage, PromptRole};
|
||||
use crank_core::prompt_composition::{
|
||||
self, PromptCompositionError, PromptDependencyPin, PromptDependencySourceClass,
|
||||
};
|
||||
use crank_core::resource::ResourceKind;
|
||||
use crank_core::{ExecutionOrigin, InvocationSource, OperationSafetyClass, OperationStatus};
|
||||
use crank_registry::model::PromptPublicationRecord;
|
||||
use crank_runtime::{
|
||||
ExecutionAuthorization, RuntimeExecutionRequest, RuntimeOperation, RuntimeRequestContext,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{app::AppState, protocol::ServiceContext};
|
||||
|
||||
/// Upper bound of one `prompts/list` page (same shape as `resources/list`).
|
||||
const MAX_PROMPTS_LIST_LIMIT: usize = 100;
|
||||
/// Cursor format version; independent of the shared Resource tokens by the `s` surface marker.
|
||||
const CURSOR_VERSION: u8 = 1;
|
||||
/// Surface marker that keeps a `resources/list` cursor from being replayed on `prompts/list`.
|
||||
const PROMPTS_SURFACE: u8 = 2;
|
||||
|
||||
/// Parameters of a `prompts/list` command, already parsed by the adapter from the wire form.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub(crate) struct PromptsListCommand {
|
||||
#[serde(default)]
|
||||
pub(crate) cursor: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// Parameters of a `prompts/get` command.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct PromptGetCommand {
|
||||
pub(crate) name: String,
|
||||
/// Typed arguments; a non-object shape is rejected by the adapter before dispatch.
|
||||
#[serde(default)]
|
||||
pub(crate) arguments: Option<Map<String, Value>>,
|
||||
}
|
||||
|
||||
/// A command the shared Prompts service accepts.
|
||||
pub(crate) enum PromptsCommand {
|
||||
List(PromptsListCommand),
|
||||
Get(PromptGetCommand),
|
||||
}
|
||||
|
||||
/// A neutral outcome of a shared Prompts command.
|
||||
pub(crate) enum PromptsOutcome {
|
||||
Listed {
|
||||
prompts: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
},
|
||||
Got {
|
||||
description: Option<String>,
|
||||
messages: Vec<Value>,
|
||||
},
|
||||
/// The request cannot be addressed as a page (malformed/stale/cross-scope cursor).
|
||||
InvalidParams(String),
|
||||
/// Unknown, Draft, foreign or unbound Prompt name: one safe outcome that carries no Prompt
|
||||
/// metadata and cannot distinguish the cases.
|
||||
NotAvailable,
|
||||
/// The bound definition rejected the supplied arguments before any rendering; only the typed
|
||||
/// reason and the argument name of the *bound* Prompt are carried.
|
||||
ArgumentsRejected {
|
||||
reason: &'static str,
|
||||
argument: Option<String>,
|
||||
},
|
||||
/// A pinned dependency of the bound Prompt cannot be read right now. The outcome carries only
|
||||
/// the declaration position: never dependency content, name or the pinned identity's metadata.
|
||||
DependencyUnavailable { position: usize },
|
||||
/// The bound snapshot could not be read or verified.
|
||||
CatalogUnavailable,
|
||||
}
|
||||
|
||||
/// Handle one shared Prompts command for the revision the adapter serves.
|
||||
pub(crate) async fn handle_prompts_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: PromptsCommand,
|
||||
) -> PromptsOutcome {
|
||||
let catalog = match state
|
||||
.catalog
|
||||
.get_catalog(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(catalog) => catalog,
|
||||
Err(_error) => return PromptsOutcome::CatalogUnavailable,
|
||||
};
|
||||
let workspace_id = match state
|
||||
.registry
|
||||
.published_agent_workspace_id(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(workspace_id) => workspace_id,
|
||||
Err(_error) => return PromptsOutcome::CatalogUnavailable,
|
||||
};
|
||||
// The whole bound snapshot is resolved once: pagination addresses this immutable array, so a
|
||||
// page boundary cannot shift when a Draft changes underneath the request.
|
||||
let publications = match state
|
||||
.registry
|
||||
.resolve_bound_prompt_publications(&workspace_id, &catalog.prompts)
|
||||
.await
|
||||
{
|
||||
Ok(publications) => publications,
|
||||
Err(_error) => return PromptsOutcome::CatalogUnavailable,
|
||||
};
|
||||
let scope = CursorScope {
|
||||
workspace_slug: context.workspace_slug,
|
||||
agent_slug: context.agent_slug,
|
||||
catalog_revision: &catalog.catalog_revision,
|
||||
revision,
|
||||
};
|
||||
|
||||
match command {
|
||||
PromptsCommand::List(list) => list_prompts(&publications, &scope, list),
|
||||
PromptsCommand::Get(get) => {
|
||||
get_prompt(state, &context, &workspace_id, &publications, &get).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_prompts(
|
||||
publications: &[PromptPublicationRecord],
|
||||
scope: &CursorScope<'_>,
|
||||
command: PromptsListCommand,
|
||||
) -> PromptsOutcome {
|
||||
let start = match command.cursor.as_deref() {
|
||||
Some(cursor) => match decode_cursor(cursor, scope, publications.len()) {
|
||||
Some(offset) => offset,
|
||||
None => {
|
||||
return PromptsOutcome::InvalidParams("invalid prompts/list cursor".to_owned());
|
||||
}
|
||||
},
|
||||
None => 0,
|
||||
};
|
||||
let limit = command
|
||||
.limit
|
||||
.unwrap_or(publications.len())
|
||||
.clamp(1, MAX_PROMPTS_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(publications.len());
|
||||
|
||||
let prompts: Vec<Value> = publications[start..end]
|
||||
.iter()
|
||||
.map(|publication| {
|
||||
json!({
|
||||
"name": publication.name,
|
||||
"description": publication.description,
|
||||
"arguments": publication.definition.arguments_json(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Discovery telemetry: counts and the served revision only — never a Prompt name or content.
|
||||
info!(
|
||||
name: "mcp.prompts.list",
|
||||
outcome = "ok",
|
||||
prompt_count = prompts.len(),
|
||||
bound_prompt_count = publications.len(),
|
||||
revision = scope.revision,
|
||||
"prompt list outcome"
|
||||
);
|
||||
|
||||
let next_cursor = (end < publications.len()).then(|| encode_cursor(scope, end));
|
||||
PromptsOutcome::Listed {
|
||||
prompts,
|
||||
next_cursor,
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_prompt(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
publications: &[PromptPublicationRecord],
|
||||
command: &PromptGetCommand,
|
||||
) -> PromptsOutcome {
|
||||
// Deterministic exact binding: the bound snapshot is ordered by `prompt_id`, and MCP addresses a
|
||||
// Prompt by name only. The first exact bound publication of that name is served, so the answer
|
||||
// does not depend on query timing or map order.
|
||||
// shortcut: Prompt names are not constrained unique, so two bound Prompts sharing a name are
|
||||
// resolved by prompt_id order; upgrade to a workspace-unique name constraint if the product
|
||||
// needs to address both.
|
||||
let Some(publication) = publications
|
||||
.iter()
|
||||
.find(|publication| publication.name == command.name)
|
||||
else {
|
||||
return PromptsOutcome::NotAvailable;
|
||||
};
|
||||
let supplied = command.arguments.clone().unwrap_or_default();
|
||||
// Story 3.16: the pinned content of every declared dependency is read through the Resource
|
||||
// contract of 3.8/3.11 and composed by the same renderer the admin preview uses.
|
||||
let contents =
|
||||
dependency_contents(state, context, workspace_id, &publication.dependencies).await;
|
||||
render_publication(publication, &supplied, &contents)
|
||||
}
|
||||
|
||||
/// Pure rendering step: the accepted typed renderer plus pinned dependency insertion.
|
||||
fn render_publication(
|
||||
publication: &PromptPublicationRecord,
|
||||
supplied: &Map<String, Value>,
|
||||
contents: &[Option<Vec<u8>>],
|
||||
) -> PromptsOutcome {
|
||||
match prompt_composition::render(
|
||||
&publication.definition,
|
||||
&publication.dependencies,
|
||||
supplied,
|
||||
contents,
|
||||
) {
|
||||
Ok(messages) => {
|
||||
info!(
|
||||
name: "mcp.prompts.get",
|
||||
outcome = "ok",
|
||||
message_count = messages.len(),
|
||||
dependency_count = publication.dependencies.len(),
|
||||
"prompt get outcome"
|
||||
);
|
||||
PromptsOutcome::Got {
|
||||
description: Some(publication.description.clone()),
|
||||
messages: message_values(&messages),
|
||||
}
|
||||
}
|
||||
Err(PromptCompositionError::Template(error)) => reject_arguments(error, supplied),
|
||||
// A published definition that cannot produce its pinned content right now is a total
|
||||
// failure: no message list, only the declaration position (AC6, AT-3.14-02 invariant).
|
||||
Err(PromptCompositionError::DependencyUnavailable { position })
|
||||
| Err(PromptCompositionError::DependencyCredentialFinding { position })
|
||||
| Err(PromptCompositionError::DependencyAccessBypassFinding { position })
|
||||
| Err(PromptCompositionError::DependencyRepresentationUnsupported { position }) => {
|
||||
PromptsOutcome::DependencyUnavailable { position }
|
||||
}
|
||||
Err(PromptCompositionError::DependencyUnused { position, .. }) => {
|
||||
PromptsOutcome::DependencyUnavailable { position }
|
||||
}
|
||||
Err(PromptCompositionError::CredentialFinding { .. })
|
||||
| Err(PromptCompositionError::AccessBypassFinding { .. }) => {
|
||||
PromptsOutcome::CatalogUnavailable
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pinned content of every dependency, indexed by declaration position.
|
||||
///
|
||||
/// The exact published version is re-checked at read time (revocation is a live gate), then read
|
||||
/// through the single immutable artifact root for a static dependency. A dynamic (template)
|
||||
/// dependency is read by the Story 3.11 Resource runtime — the same read path the agent uses for
|
||||
/// its bound templates — and is therefore never substituted with its definition text.
|
||||
async fn dependency_contents(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
pins: &[PromptDependencyPin],
|
||||
) -> Vec<Option<Vec<u8>>> {
|
||||
let mut contents = Vec::with_capacity(pins.len());
|
||||
for pin in pins {
|
||||
let resource_id = ResourceId::new(pin.resource_id.clone());
|
||||
let bytes = match pin.source_class {
|
||||
PromptDependencySourceClass::Static => {
|
||||
match state
|
||||
.registry
|
||||
.resource_is_revoked(workspace_id, &resource_id)
|
||||
.await
|
||||
{
|
||||
Ok(false) => match state
|
||||
.registry
|
||||
.resolve_resource_publication(
|
||||
workspace_id.as_str(),
|
||||
&resource_id,
|
||||
pin.version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resolved) => state
|
||||
.artifact_store
|
||||
.as_ref()
|
||||
.and_then(|store| store.read(&resolved.artifact_ref).ok()),
|
||||
Err(_) => None,
|
||||
},
|
||||
Ok(true) | Err(_) => None,
|
||||
}
|
||||
}
|
||||
PromptDependencySourceClass::Dynamic => {
|
||||
read_pinned_template_content(
|
||||
state,
|
||||
context,
|
||||
workspace_id,
|
||||
&resource_id,
|
||||
pin.version,
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
contents.push(bytes);
|
||||
}
|
||||
contents
|
||||
}
|
||||
|
||||
/// Story 3.16 §4/§6: content of one pinned dynamic (template) dependency.
|
||||
///
|
||||
/// A Prompt dependency names only the exact `(resource_id, version)` of the template, so the
|
||||
/// declared read Operation is executed through the accepted 3.11 Resource runtime with its own
|
||||
/// authorization, outbound, size and cache contract and the live revocation gate, using the
|
||||
/// template's own parameter defaults. A parameter without a default cannot be supplied by a
|
||||
/// Prompt. Every failure stays `None`: the caller turns that into the structured
|
||||
/// `prompt_dependency_unavailable` refusal instead of inserting definition text or stale content.
|
||||
async fn read_pinned_template_content(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Option<Vec<u8>> {
|
||||
let (publication, stored) = state
|
||||
.registry
|
||||
.resolve_resource_template_publication(workspace_id.as_str(), resource_id, version)
|
||||
.await
|
||||
.ok()?;
|
||||
let kind = ResourceKind::parse(&publication.kind)?;
|
||||
if !kind.allows_mime_type(&publication.mime_type) {
|
||||
return None;
|
||||
}
|
||||
let definition: Value = serde_json::from_str(&stored.definition_json).ok()?;
|
||||
let source = crank_core::resource::TemplateSource::parse(&definition).ok()?;
|
||||
let operation_id = crank_core::OperationId::new(source.operation_id.clone());
|
||||
let operation_record = state
|
||||
.registry
|
||||
.get_operation_version(workspace_id, &operation_id, source.operation_version)
|
||||
.await
|
||||
.ok()??;
|
||||
if operation_record.status != OperationStatus::Published {
|
||||
return None;
|
||||
}
|
||||
match state
|
||||
.registry
|
||||
.get_operation_summary(workspace_id, &operation_id)
|
||||
.await
|
||||
{
|
||||
Ok(Some(summary)) if summary.status != OperationStatus::Archived => {}
|
||||
_ => return None,
|
||||
}
|
||||
if !crate::access::credential_allows_security_level(
|
||||
context.credential,
|
||||
operation_record.snapshot.security_level,
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
let operation = RuntimeOperation::from(operation_record.snapshot.clone());
|
||||
let safety = operation
|
||||
.execution_config
|
||||
.safety
|
||||
.as_ref()
|
||||
.map(|policy| policy.class);
|
||||
if safety != Some(OperationSafetyClass::Read)
|
||||
|| operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()
|
||||
.is_some_and(|policy| policy.required)
|
||||
|| !matches!(&operation.target, crank_core::Target::Rest(target) if matches!(target.method, crank_core::HttpMethod::Get | crank_core::HttpMethod::Head))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut input = Map::new();
|
||||
for parameter in &source.parameters {
|
||||
let parameter_schema: crank_schema::Schema =
|
||||
serde_json::from_value(parameter.schema.clone()).ok()?;
|
||||
let value = parameter_schema.default_value.clone()?;
|
||||
crank_runtime::validate_resource_template_parameter(¶meter_schema, &value).ok()?;
|
||||
if !super::resources::set_input_path(&mut input, ¶meter.input_path, value) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let agent_id = state
|
||||
.registry
|
||||
.published_agent_id(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
.ok()?;
|
||||
let request_context = RuntimeRequestContext::from_correlation(context.correlation)
|
||||
.with_response_cache_scope(
|
||||
workspace_id.as_str().to_owned(),
|
||||
agent_id.as_str().to_owned(),
|
||||
)
|
||||
.with_resource_response_cache(
|
||||
resource_id.as_str(),
|
||||
publication.version,
|
||||
source.cache.ttl_ms,
|
||||
source.cache.max_bytes,
|
||||
)
|
||||
.with_metering_context(
|
||||
workspace_id.clone(),
|
||||
Some(agent_id.clone()),
|
||||
InvocationSource::AgentToolCall,
|
||||
);
|
||||
let auth = crate::app::resolve_operation_auth(state, workspace_id, &operation.execution_config)
|
||||
.await
|
||||
.ok()?;
|
||||
let input = Value::Object(input);
|
||||
let request = RuntimeExecutionRequest::try_new(
|
||||
workspace_id,
|
||||
ExecutionOrigin::AgentSnapshot,
|
||||
Some(&agent_id),
|
||||
&operation,
|
||||
&input,
|
||||
ExecutionAuthorization::Authorized,
|
||||
auth.as_ref(),
|
||||
&request_context,
|
||||
Instant::now()
|
||||
+ std::time::Duration::from_millis(operation.execution_config.timeout_ms.max(1)),
|
||||
)
|
||||
.ok()?;
|
||||
// The live Resource lock is acquired only after registry/auth lookups, then held through
|
||||
// dispatch: a revocation before this point closes the read.
|
||||
let guard = state
|
||||
.registry
|
||||
.begin_authorized_resource_template_read(
|
||||
workspace_id.as_str(),
|
||||
resource_id,
|
||||
publication.version,
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
let success = state.runtime.execute_outcome(request).await.ok()?;
|
||||
let max_bytes = usize::try_from(source.cache.max_bytes)
|
||||
.unwrap_or(crank_artifacts::MAX_ARTIFACT_BYTES)
|
||||
.min(crank_artifacts::MAX_ARTIFACT_BYTES);
|
||||
let bytes = match kind {
|
||||
ResourceKind::Text => success.output.as_str().map(|text| text.as_bytes().to_vec()),
|
||||
ResourceKind::Json if !success.output.is_null() => serde_json::to_vec(&success.output).ok(),
|
||||
_ => None,
|
||||
}?;
|
||||
if bytes.is_empty() || bytes.len() > max_bytes {
|
||||
return None;
|
||||
}
|
||||
guard.commit().await.ok()?;
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
/// Map a renderer rejection onto the typed reasons of AT-3.14-02 without re-validating: the renderer
|
||||
/// decided, this only classifies its verdict, and the argument name belongs to the bound Prompt the
|
||||
/// client is already allowed to see in `prompts/list`.
|
||||
fn reject_arguments(error: PromptError, supplied: &Map<String, Value>) -> PromptsOutcome {
|
||||
match error {
|
||||
PromptError::MissingArgument(argument) => PromptsOutcome::ArgumentsRejected {
|
||||
reason: "missing_argument",
|
||||
argument: Some(argument),
|
||||
},
|
||||
PromptError::UnknownArgument(argument) => PromptsOutcome::ArgumentsRejected {
|
||||
reason: "unknown_argument",
|
||||
argument: Some(argument),
|
||||
},
|
||||
PromptError::InvalidArgument(argument) => {
|
||||
let oversized = supplied
|
||||
.get(&argument)
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|text| text.len() > MAX_TEXT_BYTES);
|
||||
PromptsOutcome::ArgumentsRejected {
|
||||
reason: if oversized {
|
||||
"argument_too_large"
|
||||
} else {
|
||||
"argument_invalid"
|
||||
},
|
||||
argument: Some(argument),
|
||||
}
|
||||
}
|
||||
// A stored definition that no longer parses or renders is corruption, not a client error:
|
||||
// it fails closed instead of being answered as an argument rejection.
|
||||
PromptError::InvalidDefinition | PromptError::InvalidTemplate => {
|
||||
PromptsOutcome::CatalogUnavailable
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn message_values(messages: &[PromptMessage]) -> Vec<Value> {
|
||||
messages
|
||||
.iter()
|
||||
.map(|message| {
|
||||
// Pinned `PromptMessage.content` is a `ContentBlock`, so the accepted renderer's text
|
||||
// becomes one `TextContent` block. `role` is served exactly as published: the accepted
|
||||
// product model allows `system|user|assistant`, while the pinned wire `Role` union is
|
||||
// `user|assistant`; a system message is therefore preserved rather than silently
|
||||
// remapped or dropped (flagged for the product decision in the story handoff).
|
||||
json!({
|
||||
"role": match message.role {
|
||||
PromptRole::System => "system",
|
||||
PromptRole::User => "user",
|
||||
PromptRole::Assistant => "assistant",
|
||||
},
|
||||
"content": {"type": "text", "text": message.content},
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The immutable scope a continuation token is bound to. A cursor from another workspace, Agent,
|
||||
/// catalog revision, protocol revision or surface is never mixed into a page.
|
||||
struct CursorScope<'a> {
|
||||
workspace_slug: &'a str,
|
||||
agent_slug: &'a str,
|
||||
catalog_revision: &'a str,
|
||||
revision: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct CursorPayload {
|
||||
v: u8,
|
||||
s: u8,
|
||||
w: String,
|
||||
a: String,
|
||||
c: String,
|
||||
r: String,
|
||||
o: usize,
|
||||
}
|
||||
|
||||
fn encode_cursor(scope: &CursorScope<'_>, offset: usize) -> String {
|
||||
let payload = CursorPayload {
|
||||
v: CURSOR_VERSION,
|
||||
s: PROMPTS_SURFACE,
|
||||
w: scope.workspace_slug.to_owned(),
|
||||
a: scope.agent_slug.to_owned(),
|
||||
c: scope.catalog_revision.to_owned(),
|
||||
r: scope.revision.to_owned(),
|
||||
o: offset,
|
||||
};
|
||||
let encoded = serde_json::to_vec(&payload).unwrap_or_default();
|
||||
URL_SAFE_NO_PAD.encode(encoded)
|
||||
}
|
||||
|
||||
fn decode_cursor(raw: &str, scope: &CursorScope<'_>, len: usize) -> Option<usize> {
|
||||
let bytes = URL_SAFE_NO_PAD.decode(raw).ok()?;
|
||||
let payload: CursorPayload = serde_json::from_slice(&bytes).ok()?;
|
||||
let matches = payload.v == CURSOR_VERSION
|
||||
&& payload.s == PROMPTS_SURFACE
|
||||
&& payload.w == scope.workspace_slug
|
||||
&& payload.a == scope.agent_slug
|
||||
&& payload.c == scope.catalog_revision
|
||||
&& payload.r == scope.revision;
|
||||
(matches && payload.o <= len).then_some(payload.o)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crank_core::ids::PromptId;
|
||||
use crank_core::prompt::{PromptDefinition, PromptSensitivity};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
fn publication(
|
||||
prompt_id: &str,
|
||||
name: &str,
|
||||
messages: &str,
|
||||
arguments: Value,
|
||||
) -> PromptPublicationRecord {
|
||||
let messages: Value = serde_json::from_str(messages).expect("message fixture is JSON");
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": name,
|
||||
"description": "Description",
|
||||
"arguments": arguments,
|
||||
"messages": messages,
|
||||
}))
|
||||
.expect("definition parses");
|
||||
PromptPublicationRecord {
|
||||
prompt_id: PromptId::new(prompt_id),
|
||||
version: 1,
|
||||
name: name.to_owned(),
|
||||
description: "Description".to_owned(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition,
|
||||
dependencies: Vec::new(),
|
||||
published_at: OffsetDateTime::from_unix_timestamp(1_700_000_000).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
fn greeting() -> PromptPublicationRecord {
|
||||
publication(
|
||||
"prm_greeting",
|
||||
"greeting",
|
||||
r#"[{"role":"system","content":"Be brief."},{"role":"user","content":"Hello {{name}}"}]"#,
|
||||
json!([
|
||||
{"name":"name","schema":{"type":"string"},"required":true},
|
||||
{"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"}
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
fn cursor_scope(revision: &str) -> CursorScope<'_> {
|
||||
CursorScope {
|
||||
workspace_slug: "default",
|
||||
agent_slug: "assistant",
|
||||
catalog_revision: "agent-version-1-catalog-revision-7",
|
||||
revision,
|
||||
}
|
||||
}
|
||||
|
||||
fn get(name: &str, arguments: Value) -> PromptsOutcome {
|
||||
let publications = [greeting()];
|
||||
let Some(publication) = publications
|
||||
.iter()
|
||||
.find(|publication| publication.name == name)
|
||||
else {
|
||||
return PromptsOutcome::NotAvailable;
|
||||
};
|
||||
render_publication(
|
||||
publication,
|
||||
&arguments.as_object().cloned().unwrap_or_default(),
|
||||
&[],
|
||||
)
|
||||
}
|
||||
|
||||
/// AT-3.14-01: the list item carries the typed argument metadata and no message content.
|
||||
#[test]
|
||||
fn list_item_carries_typed_arguments_and_no_messages() {
|
||||
let scope = cursor_scope("2026-07-28");
|
||||
let PromptsOutcome::Listed { prompts, .. } =
|
||||
list_prompts(&[greeting()], &scope, PromptsListCommand::default())
|
||||
else {
|
||||
panic!("a bound page must list");
|
||||
};
|
||||
assert_eq!(prompts.len(), 1);
|
||||
assert_eq!(prompts[0]["name"], json!("greeting"));
|
||||
assert_eq!(
|
||||
prompts[0]["arguments"][0]["schema"]["type"],
|
||||
json!("string")
|
||||
);
|
||||
assert_eq!(prompts[0]["arguments"][1]["default"], json!("warm"));
|
||||
assert!(
|
||||
prompts[0].get("messages").is_none(),
|
||||
"prompts/list must not disclose message content"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.14-04: a page is deterministic and its cursor is scoped to surface/context.
|
||||
#[test]
|
||||
fn pagination_is_deterministic_and_surface_scoped() {
|
||||
let items = vec![
|
||||
publication(
|
||||
"prm_a",
|
||||
"a",
|
||||
r#"[{"role":"user","content":"A"}]"#,
|
||||
json!([]),
|
||||
),
|
||||
publication(
|
||||
"prm_b",
|
||||
"b",
|
||||
r#"[{"role":"user","content":"B"}]"#,
|
||||
json!([]),
|
||||
),
|
||||
publication(
|
||||
"prm_c",
|
||||
"c",
|
||||
r#"[{"role":"user","content":"C"}]"#,
|
||||
json!([]),
|
||||
),
|
||||
];
|
||||
let scope = cursor_scope("2026-07-28");
|
||||
let PromptsOutcome::Listed {
|
||||
prompts,
|
||||
next_cursor,
|
||||
} = list_prompts(
|
||||
&items,
|
||||
&scope,
|
||||
PromptsListCommand {
|
||||
cursor: None,
|
||||
limit: Some(2),
|
||||
},
|
||||
)
|
||||
else {
|
||||
panic!("first page must list");
|
||||
};
|
||||
assert_eq!(prompts.len(), 2);
|
||||
let cursor = next_cursor.expect("a further page exists");
|
||||
let PromptsOutcome::Listed {
|
||||
prompts: second, ..
|
||||
} = list_prompts(
|
||||
&items,
|
||||
&scope,
|
||||
PromptsListCommand {
|
||||
cursor: Some(cursor.clone()),
|
||||
limit: Some(2),
|
||||
},
|
||||
)
|
||||
else {
|
||||
panic!("second page must list");
|
||||
};
|
||||
assert_eq!(second.len(), 1);
|
||||
assert_eq!(second[0]["name"], json!("c"));
|
||||
|
||||
// The same cursor is refused on another revision and on a replayed page boundary of a
|
||||
// different Agent: a page is never mixed across scopes.
|
||||
assert!(matches!(
|
||||
list_prompts(
|
||||
&items,
|
||||
&cursor_scope("2025-11-25"),
|
||||
PromptsListCommand {
|
||||
cursor: Some(cursor.clone()),
|
||||
limit: Some(2),
|
||||
},
|
||||
),
|
||||
PromptsOutcome::InvalidParams(_)
|
||||
));
|
||||
let mut other_agent = cursor_scope("2026-07-28");
|
||||
other_agent.agent_slug = "other-assistant";
|
||||
assert!(matches!(
|
||||
list_prompts(
|
||||
&items,
|
||||
&other_agent,
|
||||
PromptsListCommand {
|
||||
cursor: Some(cursor),
|
||||
limit: Some(2),
|
||||
},
|
||||
),
|
||||
PromptsOutcome::InvalidParams(_)
|
||||
));
|
||||
// Malformed token: invalid params, never a first page.
|
||||
assert!(matches!(
|
||||
list_prompts(
|
||||
&items,
|
||||
&scope,
|
||||
PromptsListCommand {
|
||||
cursor: Some("not-a-cursor".to_owned()),
|
||||
limit: None,
|
||||
},
|
||||
),
|
||||
PromptsOutcome::InvalidParams(_)
|
||||
));
|
||||
}
|
||||
|
||||
/// AT-3.14-02: typed arguments render deterministically, defaults included.
|
||||
#[test]
|
||||
fn get_renders_typed_arguments_with_defaults() {
|
||||
let PromptsOutcome::Got {
|
||||
description,
|
||||
messages,
|
||||
} = get("greeting", json!({"name": "Ada"}))
|
||||
else {
|
||||
panic!("valid arguments must render");
|
||||
};
|
||||
assert_eq!(description.as_deref(), Some("Description"));
|
||||
assert_eq!(messages.len(), 2);
|
||||
assert_eq!(messages[0]["role"], json!("system"));
|
||||
assert_eq!(
|
||||
messages[1]["content"],
|
||||
json!({"type": "text", "text": "Hello Ada"})
|
||||
);
|
||||
assert_eq!(
|
||||
get("greeting", json!({"name": "Ada"})).to_owned_messages(),
|
||||
messages
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.14-02: every argument failure is a typed rejection with no rendered message.
|
||||
#[test]
|
||||
fn get_rejects_arguments_before_rendering() {
|
||||
for (arguments, reason) in [
|
||||
(json!({}), "missing_argument"),
|
||||
(json!({"name": "Ada", "extra": "x"}), "unknown_argument"),
|
||||
(json!({"name": 5}), "argument_invalid"),
|
||||
(json!({"name": "Ada", "tone": "loud"}), "argument_invalid"),
|
||||
(
|
||||
json!({"name": "x".repeat(MAX_TEXT_BYTES + 1)}),
|
||||
"argument_too_large",
|
||||
),
|
||||
] {
|
||||
match get("greeting", arguments) {
|
||||
PromptsOutcome::ArgumentsRejected {
|
||||
reason: observed,
|
||||
argument,
|
||||
} => {
|
||||
assert_eq!(observed, reason);
|
||||
assert!(argument.is_some(), "the bound argument name is named");
|
||||
}
|
||||
PromptsOutcome::Got { messages, .. } => {
|
||||
panic!("{reason}: no partial rendering is allowed, got {messages:?}");
|
||||
}
|
||||
_ => panic!("{reason}: expected a typed argument rejection"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// AT-3.14-01: an unknown name is indistinguishable from Draft/foreign/unbound.
|
||||
#[test]
|
||||
fn get_unknown_name_is_not_available() {
|
||||
assert!(matches!(
|
||||
get("not-bound", json!({"name": "Ada"})),
|
||||
PromptsOutcome::NotAvailable
|
||||
));
|
||||
}
|
||||
|
||||
impl PromptsOutcome {
|
||||
fn to_owned_messages(&self) -> Vec<Value> {
|
||||
match self {
|
||||
Self::Got { messages, .. } => messages.clone(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
//! Static typed registration of the MCP capabilities this server actually implements.
|
||||
//!
|
||||
//! Story 3.1, decision D-3: one static snapshot describes every registered method and its owning
|
||||
//! capability, and a single predicate decides both whether a capability is advertised and whether a
|
||||
//! method may be dispatched. Duplicate or conflicting registrations are rejected with a typed error
|
||||
//! instead of being silently merged. Advertisement is not per-call authorization: the mandatory
|
||||
//! name/header/lifecycle validation and the per-call credential guard stay in the adapter.
|
||||
//!
|
||||
//! The names here are an internal decision of the team within the approved scope, not a public API:
|
||||
//! `protocol` stays a private module (`lib.rs`) and nothing in this file is exported.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::jsonrpc::{LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION};
|
||||
|
||||
/// The owning capability of one or more wire methods.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum CapabilityId {
|
||||
Tools,
|
||||
Resources,
|
||||
/// Standard Prompt discovery/rendering of exact bound Published Prompt Versions (Story 3.14).
|
||||
Prompts,
|
||||
/// Bounded argument completion for bound Published Prompts and Resource templates (Story 3.17).
|
||||
Completions,
|
||||
/// `logging` server capability: safe structured `notifications/message` events of the negotiated
|
||||
/// client context (Story 3.18). Advertised in both revisions; the pinned modern revision carries
|
||||
/// the level per request in `_meta` and marks the capability deprecated (SEP-2577).
|
||||
Logging,
|
||||
/// `logging/setLevel` as the *legacy* client request that sets a session level. It is a
|
||||
/// dispatch-only registration without an advertisement fragment because the pinned modern
|
||||
/// revision has no such method: there the per-request `_meta` key replaces it, so the same wire
|
||||
/// name is a wrong-era request and must never be served.
|
||||
LoggingSetLevel,
|
||||
Ping,
|
||||
Discovery,
|
||||
LegacyLifecycle,
|
||||
/// Inert descriptor used only by this module's tests; never registered in production.
|
||||
#[cfg(test)]
|
||||
InertTest,
|
||||
}
|
||||
|
||||
/// The protocol kind of a registered method or capability.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)] // the registration vocabulary; only kinds actually registered are constructed here
|
||||
pub(crate) enum Kind {
|
||||
Method,
|
||||
Capability,
|
||||
Notification,
|
||||
Extension,
|
||||
}
|
||||
|
||||
/// The side that declares or serves a capability.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[allow(dead_code)] // the registration vocabulary; only the server roster is registered here
|
||||
pub(crate) enum Roster {
|
||||
Server,
|
||||
Client,
|
||||
}
|
||||
|
||||
/// Transport-required header names declared by one method.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct HeaderSet(pub(crate) &'static [&'static str]);
|
||||
|
||||
/// Named sub-features declared by a capability descriptor.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct FeatureSet(pub(crate) &'static [&'static str]);
|
||||
|
||||
/// Identifier of a declared capability extension.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ExtensionId(pub(crate) &'static str);
|
||||
|
||||
/// Reference to the deprecation tag of a surface that is still present.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct DeprecatedRef(pub(crate) &'static str);
|
||||
|
||||
/// The shared handler an owning capability routes a declared method to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum MethodHandler {
|
||||
ToolList,
|
||||
ToolCall,
|
||||
ResourceList,
|
||||
ResourceRead,
|
||||
/// `resources/templates/list`: this server declares no dynamic Resource template, so the handler
|
||||
/// answers the fixed empty business result for the requested revision.
|
||||
ResourceTemplateList,
|
||||
/// `prompts/list`: bound Published Prompt Versions of the active Agent snapshot (Story 3.14).
|
||||
PromptList,
|
||||
/// `prompts/get`: deterministic typed rendering of one exact bound Prompt version.
|
||||
PromptGet,
|
||||
/// `completion/complete`: bounded suggestions from the typed schema of one exact bound Prompt
|
||||
/// argument or one exact bound Resource template parameter (Story 3.17).
|
||||
Completion,
|
||||
/// `logging/setLevel`: validate the pinned level and record it for this legacy session, so the
|
||||
/// adapter can deliver safe structured `notifications/message` events of that context
|
||||
/// (Story 3.18). The handler never widens the accepted vocabulary and never echoes the input.
|
||||
LoggingSetLevel,
|
||||
Ping,
|
||||
Discover,
|
||||
Lifecycle,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[allow(dead_code)] // descriptor fields the dispatch-side query reads once the router is driven by it
|
||||
pub(crate) struct MethodDescriptor {
|
||||
pub(crate) name: &'static str,
|
||||
pub(crate) capability: CapabilityId,
|
||||
pub(crate) kind: Kind,
|
||||
pub(crate) required_headers: HeaderSet,
|
||||
pub(crate) handler: MethodHandler,
|
||||
}
|
||||
|
||||
/// The advertisement fragment of a capability: the top-level capabilities key and the boolean values
|
||||
/// of its declared sub-features. `None` means the capability is not advertised at all.
|
||||
pub(crate) type AdvertisementFragment = (&'static str, &'static [(&'static str, bool)]);
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[allow(dead_code)] // descriptor fields the dispatch-side query reads once the router is driven by it
|
||||
pub(crate) struct CapabilityIdDescriptor {
|
||||
pub(crate) id: CapabilityId,
|
||||
pub(crate) roster: Roster,
|
||||
pub(crate) kind: Kind,
|
||||
pub(crate) extension: Option<ExtensionId>,
|
||||
pub(crate) deprecated: Option<DeprecatedRef>,
|
||||
pub(crate) sub_features: FeatureSet,
|
||||
pub(crate) advertised: Option<AdvertisementFragment>,
|
||||
pub(crate) revisions: &'static [&'static str],
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum RegistrationError {
|
||||
/// The same method name is registered twice with the same owning capability and kind.
|
||||
DuplicateMethod { name: &'static str },
|
||||
/// The same method name is registered with a different capability or kind.
|
||||
ConflictingMethod { name: &'static str },
|
||||
/// The same owning capability is described twice.
|
||||
DuplicateCapability { capability: CapabilityId },
|
||||
/// Two capabilities claim the same top-level advertisement key: the merged JSON object would
|
||||
/// silently lose one of the two fragments.
|
||||
ConflictingAdvertisement { key: &'static str },
|
||||
/// A server declaration/extension of an advertisable kind carries no advertisement fragment: its
|
||||
/// methods would be dispatchable while the capability is advertised nowhere (F6).
|
||||
MissingAdvertisement { capability: CapabilityId },
|
||||
/// A registration that is not advertisable by contract carries an advertisement fragment: the
|
||||
/// dispatch-only `method`/`notification` registrations (`ping`, `server/discover`, the legacy
|
||||
/// lifecycle) must never claim to be advertised.
|
||||
MisdeclaredAdvertisement { capability: CapabilityId },
|
||||
}
|
||||
|
||||
/// The registration-backed dispatch decision for one wire method in one requested revision (R5/D-3).
|
||||
///
|
||||
/// The router holds no method list of its own: it asks the registration what to do with a method and
|
||||
/// whether the owning capability exists in the requested revision at all. A method that is not
|
||||
/// registered never reaches a handler, so it can neither enter the owning service nor produce an
|
||||
/// outbound call. The registered `kind` is part of the decision: the two legacy lifecycle wire names
|
||||
/// share one handler but are *not* interchangeable, so the adapter needs the registered kind to serve
|
||||
/// `initialize` as a request and `notifications/initialized` as a notification (G2).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum DispatchDecision {
|
||||
/// Registered and available in the requested revision; routes to this handler with this kind.
|
||||
Allowed { handler: MethodHandler, kind: Kind },
|
||||
/// Registered, but its owning capability does not exist in the requested revision.
|
||||
WrongEra { handler: MethodHandler, kind: Kind },
|
||||
/// No registration owns this method name.
|
||||
Unregistered,
|
||||
}
|
||||
|
||||
/// The one static registration snapshot.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CapabilityRegistry {
|
||||
capabilities: Vec<CapabilityIdDescriptor>,
|
||||
/// Registered methods. The dispatch-side query over this table is a separate bounded change; the
|
||||
/// table is retained (and validated) here so registration cannot drift from advertisement.
|
||||
#[allow(dead_code)]
|
||||
methods: Vec<MethodDescriptor>,
|
||||
}
|
||||
|
||||
impl CapabilityRegistry {
|
||||
/// Build the registry from descriptor tables. Duplicate or conflicting entries are rejected with
|
||||
/// [`RegistrationError`] — a registration error is never a panic and never a silently merged list.
|
||||
pub(crate) fn new(
|
||||
capabilities: &[CapabilityIdDescriptor],
|
||||
methods: &[MethodDescriptor],
|
||||
) -> Result<Self, RegistrationError> {
|
||||
let mut seen_capabilities: Vec<CapabilityId> = Vec::new();
|
||||
for descriptor in capabilities {
|
||||
if seen_capabilities.contains(&descriptor.id) {
|
||||
return Err(RegistrationError::DuplicateCapability {
|
||||
capability: descriptor.id,
|
||||
});
|
||||
}
|
||||
seen_capabilities.push(descriptor.id);
|
||||
}
|
||||
|
||||
let mut seen_methods: Vec<(&'static str, CapabilityId, Kind)> = Vec::new();
|
||||
for descriptor in methods {
|
||||
if let Some((_, capability, kind)) = seen_methods
|
||||
.iter()
|
||||
.find(|(name, _, _)| *name == descriptor.name)
|
||||
{
|
||||
let same_owner = *capability == descriptor.capability && *kind == descriptor.kind;
|
||||
let error = if same_owner {
|
||||
RegistrationError::DuplicateMethod {
|
||||
name: descriptor.name,
|
||||
}
|
||||
} else {
|
||||
RegistrationError::ConflictingMethod {
|
||||
name: descriptor.name,
|
||||
}
|
||||
};
|
||||
return Err(error);
|
||||
}
|
||||
seen_methods.push((descriptor.name, descriptor.capability, descriptor.kind));
|
||||
}
|
||||
|
||||
// Two capabilities must never claim the same top-level advertisement key: the merged
|
||||
// advertisement object is a map, so a silent overwrite would drop one fragment (R7).
|
||||
let mut seen_advertisement_keys: Vec<&'static str> = Vec::new();
|
||||
for descriptor in capabilities {
|
||||
if let Some((key, _sub_features)) = descriptor.advertised {
|
||||
if seen_advertisement_keys.contains(&key) {
|
||||
return Err(RegistrationError::ConflictingAdvertisement { key });
|
||||
}
|
||||
seen_advertisement_keys.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
// F6: the two projections of a registration must not drift apart. A server declaration of an
|
||||
// advertisable kind without a fragment would keep dispatching methods while advertising
|
||||
// nothing, and a dispatch-only method/notification registration must not claim a fragment.
|
||||
for descriptor in capabilities {
|
||||
let advertisable_kind = matches!(descriptor.kind, Kind::Capability | Kind::Extension);
|
||||
if advertisable_kind && descriptor.advertised.is_none() {
|
||||
return Err(RegistrationError::MissingAdvertisement {
|
||||
capability: descriptor.id,
|
||||
});
|
||||
}
|
||||
if !advertisable_kind && descriptor.advertised.is_some() {
|
||||
return Err(RegistrationError::MisdeclaredAdvertisement {
|
||||
capability: descriptor.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
capabilities: capabilities.to_vec(),
|
||||
methods: methods.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
fn descriptor(&self, capability: CapabilityId) -> Option<&CapabilityIdDescriptor> {
|
||||
self.capabilities
|
||||
.iter()
|
||||
.find(|descriptor| descriptor.id == capability)
|
||||
}
|
||||
|
||||
/// Availability of an owning capability in one revision: the registered revision window.
|
||||
///
|
||||
/// This is the shared eligibility half of both projections: a capability that is not registered
|
||||
/// for the requested revision can neither be advertised nor have its methods dispatched.
|
||||
fn registered_for(&self, capability: CapabilityId, revision: &str) -> bool {
|
||||
self.descriptor(capability)
|
||||
.is_some_and(|descriptor| descriptor.revisions.contains(&revision))
|
||||
}
|
||||
|
||||
/// The single advertisement predicate: a capability is advertised in `revision` when it is a
|
||||
/// registered server declaration/extension, available in that revision, with a declared fragment.
|
||||
pub(crate) fn advertise_for(&self, capability: CapabilityId, revision: &str) -> bool {
|
||||
let Some(descriptor) = self.descriptor(capability) else {
|
||||
return false;
|
||||
};
|
||||
descriptor.roster == Roster::Server
|
||||
&& matches!(descriptor.kind, Kind::Capability | Kind::Extension)
|
||||
&& descriptor.advertised.is_some()
|
||||
&& self.registered_for(capability, revision)
|
||||
}
|
||||
|
||||
/// Dispatch eligibility of a capability-owned method (D-3/F6).
|
||||
///
|
||||
/// For every capability that is advertised by design this is [`Self::advertise_for`] itself, so a
|
||||
/// declaration that stops being advertised — a fragment-less advertisable kind, or a client-roster
|
||||
/// declaration — can never keep dispatching its methods: the constructor rejects such a
|
||||
/// registration outright ([`RegistrationError::MissingAdvertisement`]). The only registrations
|
||||
/// that are dispatchable without being advertised are the explicitly non-advertised method-kind
|
||||
/// ones (`ping`, `server/discover`, the legacy lifecycle), which carry no fragment by contract.
|
||||
pub(crate) fn dispatchable_for(&self, capability: CapabilityId, revision: &str) -> bool {
|
||||
if !self.registered_for(capability, revision) {
|
||||
return false;
|
||||
}
|
||||
match self.descriptor(capability) {
|
||||
Some(descriptor) => match descriptor.kind {
|
||||
Kind::Capability | Kind::Extension => self.advertise_for(capability, revision),
|
||||
Kind::Method | Kind::Notification => descriptor.advertised.is_none(),
|
||||
},
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The registration-backed dispatch decision of one wire method in one requested revision (R5).
|
||||
///
|
||||
/// The method-to-handler mapping lives here, not in the router: an unknown method has no handler
|
||||
/// and a method whose owning capability is not eligible in the requested revision is a wrong-era
|
||||
/// request, so neither can reach a service or make an outbound call.
|
||||
pub(crate) fn dispatch_decision(&self, method: &str, revision: &str) -> DispatchDecision {
|
||||
let Some(descriptor) = self
|
||||
.methods
|
||||
.iter()
|
||||
.find(|descriptor| descriptor.name == method)
|
||||
else {
|
||||
return DispatchDecision::Unregistered;
|
||||
};
|
||||
if self.dispatchable_for(descriptor.capability, revision) {
|
||||
DispatchDecision::Allowed {
|
||||
handler: descriptor.handler,
|
||||
kind: descriptor.kind,
|
||||
}
|
||||
} else {
|
||||
DispatchDecision::WrongEra {
|
||||
handler: descriptor.handler,
|
||||
kind: descriptor.kind,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The single advertisement JSON source, indexed by the requested revision (R6): only the
|
||||
/// fragments of the capabilities available in *that* revision are merged, so a single-era
|
||||
/// declaration never leaks into the other era and an empty revision window is eligible nowhere.
|
||||
pub(crate) fn advertised_capabilities(&self, revision: &str) -> Value {
|
||||
let mut merged = Map::new();
|
||||
for descriptor in &self.capabilities {
|
||||
if !self.advertise_for(descriptor.id, revision) {
|
||||
continue;
|
||||
}
|
||||
if let Some((key, sub_features)) = descriptor.advertised {
|
||||
let values = sub_features
|
||||
.iter()
|
||||
.map(|(name, enabled)| ((*name).to_owned(), Value::Bool(*enabled)))
|
||||
.collect::<Map<String, Value>>();
|
||||
merged.insert(key.to_owned(), Value::Object(values));
|
||||
}
|
||||
}
|
||||
Value::Object(merged)
|
||||
}
|
||||
|
||||
/// The registered methods with their owning capability: used by the tests that prove an inert
|
||||
/// descriptor changes both projections.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn methods(&self) -> &[MethodDescriptor] {
|
||||
&self.methods
|
||||
}
|
||||
}
|
||||
|
||||
const MODERN_AND_LEGACY: &[&str] = &[MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION];
|
||||
const MODERN_ONLY: &[&str] = &[MODERN_PROTOCOL_VERSION];
|
||||
const LEGACY_ONLY: &[&str] = &[LEGACY_PROTOCOL_VERSION];
|
||||
|
||||
pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Tools,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["listChanged"]),
|
||||
advertised: Some(("tools", &[("listChanged", false)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Resources,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["subscribe", "listChanged"]),
|
||||
advertised: Some(("resources", &[("subscribe", false), ("listChanged", false)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Prompts,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["listChanged"]),
|
||||
advertised: Some(("prompts", &[("listChanged", false)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Completions,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
// The pinned schema declares `completions` as an object with no sub-features.
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: Some(("completions", &[])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
// Story 3.18: the standard `logging` declaration of both approved revisions. The pinned
|
||||
// modern revision marks it deprecated (SEP-2577) but keeps it in the schema for at least
|
||||
// twelve months, and `notifications/message` remains the only log channel there; the legacy
|
||||
// revision additionally serves `logging/setLevel`.
|
||||
id: CapabilityId::Logging,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
// The pinned schema declares `logging` as an open object with no named sub-features.
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: Some(("logging", &[])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
// Dispatch-only registration of the legacy `logging/setLevel` request: it is a client
|
||||
// request, not an advertised server capability, and it does not exist in the modern schema.
|
||||
id: CapabilityId::LoggingSetLevel,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: LEGACY_ONLY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Ping,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::Discovery,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: MODERN_ONLY,
|
||||
},
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::LegacyLifecycle,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: LEGACY_ONLY,
|
||||
},
|
||||
];
|
||||
|
||||
/// Transport-required header names of the modern request rules: the declared method and name pair.
|
||||
const HEADERS_METHOD_AND_NAME: HeaderSet = HeaderSet(&["Mcp-Method", "Mcp-Name"]);
|
||||
/// Methods that declare only the method header: `resources/list` carries no per-request name.
|
||||
const HEADERS_METHOD_ONLY: HeaderSet = HeaderSet(&["Mcp-Method"]);
|
||||
/// Lifecycle and ping requests declare no additional required header beyond the envelope.
|
||||
const HEADERS_NONE: HeaderSet = HeaderSet(&[]);
|
||||
|
||||
pub(crate) const METHOD_DESCRIPTORS: &[MethodDescriptor] = &[
|
||||
MethodDescriptor {
|
||||
name: "tools/list",
|
||||
capability: CapabilityId::Tools,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_AND_NAME,
|
||||
handler: MethodHandler::ToolList,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "tools/call",
|
||||
capability: CapabilityId::Tools,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_AND_NAME,
|
||||
handler: MethodHandler::ToolCall,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "resources/list",
|
||||
capability: CapabilityId::Resources,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::ResourceList,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "resources/read",
|
||||
capability: CapabilityId::Resources,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_AND_NAME,
|
||||
handler: MethodHandler::ResourceRead,
|
||||
},
|
||||
MethodDescriptor {
|
||||
// Story 3.8: the standard client companion of `resources/list`. This server has no dynamic
|
||||
// template, so the answer is a fixed empty list; the request declares no name, so only the
|
||||
// method header is required.
|
||||
name: "resources/templates/list",
|
||||
capability: CapabilityId::Resources,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::ResourceTemplateList,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "prompts/list",
|
||||
capability: CapabilityId::Prompts,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::PromptList,
|
||||
},
|
||||
MethodDescriptor {
|
||||
// `prompts/get` declares its Prompt name, so the modern era requires `Mcp-Name` too.
|
||||
name: "prompts/get",
|
||||
capability: CapabilityId::Prompts,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_AND_NAME,
|
||||
handler: MethodHandler::PromptGet,
|
||||
},
|
||||
MethodDescriptor {
|
||||
// Story 3.17: the standard client companion of the Prompts/Resources declarations. Its `ref`
|
||||
// is a union of a Prompt name and a Resource URI template, so no single `Mcp-Name` value can
|
||||
// describe it; the pinned era matrix requires `Mcp-Name` only for `tools/call`,
|
||||
// `resources/read` and `prompts/get`.
|
||||
name: "completion/complete",
|
||||
capability: CapabilityId::Completions,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::Completion,
|
||||
},
|
||||
MethodDescriptor {
|
||||
// Story 3.18: the legacy client request that sets the log level of its session. It declares
|
||||
// the level, not a server-side name, so only the method header applies; the pinned modern
|
||||
// revision has no such method at all (per-request `_meta` replaces it).
|
||||
name: "logging/setLevel",
|
||||
capability: CapabilityId::LoggingSetLevel,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_METHOD_ONLY,
|
||||
handler: MethodHandler::LoggingSetLevel,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "ping",
|
||||
capability: CapabilityId::Ping,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Ping,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "server/discover",
|
||||
capability: CapabilityId::Discovery,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Discover,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "initialize",
|
||||
capability: CapabilityId::LegacyLifecycle,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Lifecycle,
|
||||
},
|
||||
MethodDescriptor {
|
||||
name: "notifications/initialized",
|
||||
capability: CapabilityId::LegacyLifecycle,
|
||||
kind: Kind::Notification,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Lifecycle,
|
||||
},
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "registry_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,800 @@
|
||||
//! In-crate tests of `protocol::registry` (module path `protocol::registry::tests`).
|
||||
//!
|
||||
//! Kept as a `#[path]` module to stay inside the repository code-health caps (an inline test
|
||||
//! module may not exceed 500 lines and `registry.rs` may not exceed 1000 lines). The module path,
|
||||
//! and therefore the sanctioned selector
|
||||
//! `cargo test -p crank-community-mcp --lib protocol::registry::`, is identical to the inline
|
||||
//! module it replaces, and every test name is unchanged.
|
||||
|
||||
use super::*;
|
||||
use crate::protocol::{advertised_server_capabilities, dispatch_decision};
|
||||
use serde_json::json;
|
||||
|
||||
fn production_registry() -> CapabilityRegistry {
|
||||
CapabilityRegistry::new(CAPABILITY_DESCRIPTORS, METHOD_DESCRIPTORS)
|
||||
.expect("the static capability table is valid")
|
||||
}
|
||||
|
||||
fn inert_descriptor() -> CapabilityIdDescriptor {
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_test_capability", &[("enabled", true)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_registration_is_unique_and_advertises_only_the_registered_capability() {
|
||||
let registry = production_registry();
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
assert_eq!(
|
||||
registry.advertised_capabilities(revision),
|
||||
json!({
|
||||
"completions": {},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
}),
|
||||
"the registered advertisement must be the same reviewed object in {revision}"
|
||||
);
|
||||
assert_eq!(
|
||||
advertised_server_capabilities(revision),
|
||||
json!({
|
||||
"completions": {},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
}),
|
||||
"the production advertisement entry point must serve {revision}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn advertisement_and_dispatch_share_one_eligibility_predicate() {
|
||||
// F6: for every capability that is *advertised by design* advertisement and dispatch are the
|
||||
// same predicate, and dispatch eligibility follows the registered revision window. The only
|
||||
// registrations that are dispatchable without being advertised are the explicit method-kind
|
||||
// ones (`ping`, `server/discover`, the legacy lifecycle).
|
||||
let registry = production_registry();
|
||||
for descriptor in ®istry.capabilities {
|
||||
let advertised_by_design = matches!(descriptor.kind, Kind::Capability | Kind::Extension);
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
let eligible = registry.dispatchable_for(descriptor.id, revision);
|
||||
assert_eq!(
|
||||
eligible,
|
||||
descriptor.revisions.contains(&revision),
|
||||
"dispatch eligibility must follow the revision window of {:?}",
|
||||
descriptor.id
|
||||
);
|
||||
if advertised_by_design {
|
||||
assert_eq!(
|
||||
registry.advertise_for(descriptor.id, revision),
|
||||
eligible,
|
||||
"advertisement and dispatch drifted for {:?} in {revision}",
|
||||
descriptor.id
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
!registry.advertise_for(descriptor.id, revision),
|
||||
"a dispatch-only registration {:?} must never be advertised in {revision}",
|
||||
descriptor.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(registry.advertise_for(CapabilityId::Tools, MODERN_PROTOCOL_VERSION));
|
||||
assert!(registry.dispatchable_for(CapabilityId::Tools, MODERN_PROTOCOL_VERSION));
|
||||
assert!(registry.advertise_for(CapabilityId::Tools, LEGACY_PROTOCOL_VERSION));
|
||||
// `ping` is dispatched in both eras but advertised nowhere: it declares no fragment by
|
||||
// contract, and the advertisement object carries no `ping` key.
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
assert!(registry.dispatchable_for(CapabilityId::Ping, revision));
|
||||
assert!(!registry.advertise_for(CapabilityId::Ping, revision));
|
||||
assert!(
|
||||
registry
|
||||
.advertised_capabilities(revision)
|
||||
.as_object()
|
||||
.is_some_and(|object| !object.contains_key("ping")),
|
||||
"the advertisement of {revision} must not grow a `ping` key"
|
||||
);
|
||||
}
|
||||
assert!(registry.dispatchable_for(CapabilityId::Discovery, MODERN_PROTOCOL_VERSION));
|
||||
assert!(!registry.dispatchable_for(CapabilityId::Discovery, LEGACY_PROTOCOL_VERSION));
|
||||
assert!(registry.dispatchable_for(CapabilityId::LegacyLifecycle, LEGACY_PROTOCOL_VERSION));
|
||||
assert!(!registry.dispatchable_for(CapabilityId::LegacyLifecycle, MODERN_PROTOCOL_VERSION));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fragment_less_advertisable_capability_is_rejected_at_registration() {
|
||||
// F6: without this invariant a capability-owned method could stay `Allowed` while its
|
||||
// capability is advertised nowhere, which is exactly the drift the reviewer measured.
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: None,
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
});
|
||||
assert_eq!(
|
||||
CapabilityRegistry::new(&capabilities, METHOD_DESCRIPTORS).err(),
|
||||
Some(RegistrationError::MissingAdvertisement {
|
||||
capability: CapabilityId::InertTest
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dispatch_only_registration_cannot_claim_an_advertisement_fragment() {
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Method,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&[]),
|
||||
advertised: Some(("inert_method_advertisement", &[("enabled", true)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
});
|
||||
assert_eq!(
|
||||
CapabilityRegistry::new(&capabilities, METHOD_DESCRIPTORS).err(),
|
||||
Some(RegistrationError::MisdeclaredAdvertisement {
|
||||
capability: CapabilityId::InertTest
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_roster_declaration_never_dispatches_its_methods() {
|
||||
const INERT_METHOD: MethodDescriptor = MethodDescriptor {
|
||||
name: "inert/client-only",
|
||||
capability: CapabilityId::InertTest,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Ping,
|
||||
};
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Client,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_client_capability", &[("enabled", true)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
});
|
||||
let mut methods = METHOD_DESCRIPTORS.to_vec();
|
||||
methods.push(INERT_METHOD);
|
||||
let registry =
|
||||
CapabilityRegistry::new(&capabilities, &methods).expect("a client declaration registers");
|
||||
|
||||
assert!(!registry.advertise_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION));
|
||||
assert!(!registry.dispatchable_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION));
|
||||
assert_eq!(
|
||||
registry.dispatch_decision(INERT_METHOD.name, MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::Ping,
|
||||
kind: Kind::Method,
|
||||
},
|
||||
"a client-side declaration must never be Allowed for a server dispatch"
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.advertised_capabilities(MODERN_PROTOCOL_VERSION)
|
||||
.as_object()
|
||||
.is_some_and(|object| !object.contains_key("inert_client_capability")),
|
||||
"a client declaration is never advertised by this server"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_method_registration_is_rejected() {
|
||||
let duplicate = [
|
||||
METHOD_DESCRIPTORS[0],
|
||||
MethodDescriptor {
|
||||
name: METHOD_DESCRIPTORS[0].name,
|
||||
capability: METHOD_DESCRIPTORS[0].capability,
|
||||
kind: METHOD_DESCRIPTORS[0].kind,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Discover,
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
CapabilityRegistry::new(CAPABILITY_DESCRIPTORS, &duplicate).unwrap_err(),
|
||||
RegistrationError::DuplicateMethod { name: "tools/list" }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_method_registration_is_rejected() {
|
||||
let conflicting = [
|
||||
METHOD_DESCRIPTORS[0],
|
||||
MethodDescriptor {
|
||||
name: METHOD_DESCRIPTORS[0].name,
|
||||
capability: CapabilityId::Ping,
|
||||
kind: METHOD_DESCRIPTORS[0].kind,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Ping,
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
CapabilityRegistry::new(CAPABILITY_DESCRIPTORS, &conflicting).unwrap_err(),
|
||||
RegistrationError::ConflictingMethod { name: "tools/list" }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_capability_registration_is_rejected() {
|
||||
let mut duplicated = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
duplicated.push(CAPABILITY_DESCRIPTORS[0]);
|
||||
assert_eq!(
|
||||
CapabilityRegistry::new(&duplicated, METHOD_DESCRIPTORS).unwrap_err(),
|
||||
RegistrationError::DuplicateCapability {
|
||||
capability: CapabilityId::Tools
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_production() {
|
||||
let without = production_registry();
|
||||
let mut with_capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
with_capabilities.push(inert_descriptor());
|
||||
let with = CapabilityRegistry::new(&with_capabilities, METHOD_DESCRIPTORS)
|
||||
.expect("the inert descriptor is a valid capability entry");
|
||||
|
||||
assert_eq!(
|
||||
without.advertised_capabilities(MODERN_PROTOCOL_VERSION),
|
||||
json!({
|
||||
"completions": {},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
with.advertised_capabilities(MODERN_PROTOCOL_VERSION),
|
||||
json!({
|
||||
"inert_test_capability": {"enabled": true},
|
||||
"completions": {},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
with.advertised_capabilities(LEGACY_PROTOCOL_VERSION),
|
||||
json!({
|
||||
"inert_test_capability": {"enabled": true},
|
||||
"completions": {},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
|
||||
// Both projections move together: the inert capability is advertisable *and* dispatchable.
|
||||
assert!(!without.advertise_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION));
|
||||
assert!(with.advertise_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION));
|
||||
assert_eq!(
|
||||
with.advertise_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION),
|
||||
with.dispatchable_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION)
|
||||
);
|
||||
|
||||
// The inert descriptor stays a test-only object: it is absent from the production table.
|
||||
assert!(
|
||||
CAPABILITY_DESCRIPTORS
|
||||
.iter()
|
||||
.all(|descriptor| descriptor.id != CapabilityId::InertTest)
|
||||
);
|
||||
let _ = with.methods();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_advertised_revision_window_is_exactly_the_two_approved_revisions() {
|
||||
let registry = production_registry();
|
||||
for descriptor in ®istry.capabilities {
|
||||
for revision in descriptor.revisions {
|
||||
assert!(
|
||||
[MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION].contains(revision),
|
||||
"capability {:?} declares an unapproved revision {revision}",
|
||||
descriptor.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Story 3.1 #8 remaining-foundation regressions (R6 era window, R7 advertisement conflict) --
|
||||
|
||||
/// A test-only descriptor that declares no revision at all, so every revision is ineligible.
|
||||
fn empty_window_descriptor() -> CapabilityIdDescriptor {
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_empty_window_capability", &[("enabled", true)])),
|
||||
revisions: &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// A test-only descriptor that claims the top-level advertisement key already owned by `Tools`.
|
||||
fn conflicting_advertisement_descriptor() -> CapabilityIdDescriptor {
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["listChanged"]),
|
||||
advertised: Some(("tools", &[("listChanged", true)])),
|
||||
revisions: MODERN_AND_LEGACY,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_revision_window_is_not_vacuously_advertisable() {
|
||||
// R6 (empty-window half): `revisions: &[]` must not make a capability eligible for every
|
||||
// revision through a vacuously true `all()`.
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(empty_window_descriptor());
|
||||
let registry = match CapabilityRegistry::new(&capabilities, METHOD_DESCRIPTORS) {
|
||||
Ok(registry) => registry,
|
||||
// Rejecting a revision-less capability at registration is an equivalent, stronger
|
||||
// resolution of the same defect (a typed error, never a panic).
|
||||
Err(_rejected_at_registration) => return,
|
||||
};
|
||||
|
||||
assert!(
|
||||
!registry.advertise_for(CapabilityId::InertTest, MODERN_PROTOCOL_VERSION),
|
||||
"a capability with an empty revision window is eligible in no revision"
|
||||
);
|
||||
assert!(
|
||||
!registry.advertise_for(CapabilityId::InertTest, LEGACY_PROTOCOL_VERSION),
|
||||
"a capability with an empty revision window is eligible in no revision"
|
||||
);
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
let advertised = registry.advertised_capabilities(revision);
|
||||
assert!(
|
||||
advertised
|
||||
.as_object()
|
||||
.is_some_and(|object| !object.contains_key("inert_empty_window_capability")),
|
||||
"an empty revision window must not be advertised in {revision}: {advertised}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conflicting_advertisement_key_is_rejected_not_silently_overwritten() {
|
||||
// R7: the constructor validates duplicate capability ids and duplicate method names but not
|
||||
// a conflicting top-level advertisement key, so `Value::Object::insert` silently overwrites.
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(conflicting_advertisement_descriptor());
|
||||
let outcome = CapabilityRegistry::new(&capabilities, METHOD_DESCRIPTORS);
|
||||
assert_eq!(
|
||||
outcome.err(),
|
||||
Some(RegistrationError::ConflictingAdvertisement { key: "tools" }),
|
||||
"two capabilities claiming the same top-level advertisement key must be rejected with a \
|
||||
typed registration error instead of being silently overwritten"
|
||||
);
|
||||
}
|
||||
|
||||
// --- R6: the advertisement is indexed by the requested era, not by every declared revision ------
|
||||
|
||||
/// A test-only server capability available in the modern revision only.
|
||||
fn modern_only_descriptor() -> CapabilityIdDescriptor {
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_modern_capability", &[("enabled", true)])),
|
||||
revisions: MODERN_ONLY,
|
||||
}
|
||||
}
|
||||
|
||||
/// A test-only server capability available in the legacy revision only.
|
||||
fn legacy_only_descriptor() -> CapabilityIdDescriptor {
|
||||
CapabilityIdDescriptor {
|
||||
id: CapabilityId::InertTest,
|
||||
roster: Roster::Server,
|
||||
kind: Kind::Capability,
|
||||
extension: None,
|
||||
deprecated: None,
|
||||
sub_features: FeatureSet(&["enabled"]),
|
||||
advertised: Some(("inert_legacy_capability", &[("enabled", true)])),
|
||||
revisions: LEGACY_ONLY,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_era_descriptor_never_leaks_into_the_other_era_advertisement() {
|
||||
for (inert, this_era, other_era, key) in [
|
||||
(
|
||||
modern_only_descriptor(),
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
"inert_modern_capability",
|
||||
),
|
||||
(
|
||||
legacy_only_descriptor(),
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
"inert_legacy_capability",
|
||||
),
|
||||
] {
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(inert);
|
||||
let registry = CapabilityRegistry::new(&capabilities, METHOD_DESCRIPTORS)
|
||||
.expect("a single-era inert capability is a valid registration");
|
||||
|
||||
let this_era_advertisement = registry.advertised_capabilities(this_era);
|
||||
assert!(
|
||||
this_era_advertisement
|
||||
.as_object()
|
||||
.is_some_and(|object| object.contains_key(key)),
|
||||
"{key} must be advertised in its own era {this_era}: {this_era_advertisement}"
|
||||
);
|
||||
let other_era_advertisement = registry.advertised_capabilities(other_era);
|
||||
assert!(
|
||||
other_era_advertisement
|
||||
.as_object()
|
||||
.is_some_and(|object| !object.contains_key(key)),
|
||||
"{key} must never leak into {other_era}: {other_era_advertisement}"
|
||||
);
|
||||
assert_eq!(
|
||||
other_era_advertisement,
|
||||
json!({
|
||||
"completions": {},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
}),
|
||||
"the other era advertisement stays the reviewed object"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- R5: the router's dispatch decision is the registration, never a handler list --------------
|
||||
|
||||
#[test]
|
||||
fn the_production_registration_routes_every_declared_method_in_its_own_era() {
|
||||
for (method, era, handler, kind) in [
|
||||
(
|
||||
"tools/list",
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
MethodHandler::ToolList,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"tools/call",
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
MethodHandler::ToolCall,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"tools/list",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::ToolList,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"tools/call",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::ToolCall,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"ping",
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
MethodHandler::Ping,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"resources/templates/list",
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
MethodHandler::ResourceTemplateList,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"resources/templates/list",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::ResourceTemplateList,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"ping",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::Ping,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"server/discover",
|
||||
MODERN_PROTOCOL_VERSION,
|
||||
MethodHandler::Discover,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"initialize",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::Lifecycle,
|
||||
Kind::Method,
|
||||
),
|
||||
(
|
||||
"notifications/initialized",
|
||||
LEGACY_PROTOCOL_VERSION,
|
||||
MethodHandler::Lifecycle,
|
||||
Kind::Notification,
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
dispatch_decision(method, era),
|
||||
DispatchDecision::Allowed { handler, kind },
|
||||
"{method} must route to its registered handler with its registered kind in {era}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lifecycle_dispatch_decision_carries_the_registered_method_kind() {
|
||||
// G2: `initialize` (a request) and `notifications/initialized` (a notification) share the
|
||||
// Lifecycle handler but are not interchangeable. The decision must carry the registered kind, or
|
||||
// the adapter can only tell them apart by the envelope shape and would serve one as the other.
|
||||
assert_eq!(
|
||||
dispatch_decision("initialize", LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
dispatch_decision("notifications/initialized", LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Notification,
|
||||
}
|
||||
);
|
||||
assert_ne!(
|
||||
dispatch_decision("initialize", LEGACY_PROTOCOL_VERSION),
|
||||
dispatch_decision("notifications/initialized", LEGACY_PROTOCOL_VERSION),
|
||||
"the two lifecycle wire names must never collapse into the same dispatch decision"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_method_of_the_other_era_is_a_wrong_era_decision() {
|
||||
assert_eq!(
|
||||
dispatch_decision("server/discover", LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::Discover,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
dispatch_decision("initialize", MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
dispatch_decision("notifications/initialized", MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Notification,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unregistered_method_has_no_handler_and_no_service() {
|
||||
let registry = production_registry();
|
||||
for method in [
|
||||
"resources/subscribe",
|
||||
"logging/setLogLevel",
|
||||
"tasks/list",
|
||||
"frobnicate",
|
||||
] {
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
assert_eq!(
|
||||
registry.dispatch_decision(method, revision),
|
||||
DispatchDecision::Unregistered,
|
||||
"{method} is not registered and must never reach a handler in {revision}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story317_completion_is_advertised_and_dispatchable_in_both_revisions() {
|
||||
let registry = production_registry();
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
assert!(
|
||||
registry.advertise_for(CapabilityId::Completions, revision),
|
||||
"the implemented completion surface must be advertised in {revision}"
|
||||
);
|
||||
assert_eq!(
|
||||
registry.dispatch_decision("completion/complete", revision),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Completion,
|
||||
kind: Kind::Method,
|
||||
},
|
||||
"`completion/complete` must reach its handler in {revision}"
|
||||
);
|
||||
assert_eq!(
|
||||
registry.advertised_capabilities(revision)["completions"],
|
||||
json!({}),
|
||||
"the pinned advertisement is an empty `completions` object in {revision}"
|
||||
);
|
||||
}
|
||||
let descriptor = METHOD_DESCRIPTORS
|
||||
.iter()
|
||||
.find(|descriptor| descriptor.name == "completion/complete")
|
||||
.expect("completion/complete is a registered method");
|
||||
assert_eq!(
|
||||
descriptor.required_headers.0,
|
||||
&["Mcp-Method"],
|
||||
"the `ref` union declares no single `Mcp-Name` value for the modern header rule"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story318_logging_is_advertised_on_both_revisions_and_set_level_is_legacy_only() {
|
||||
let registry = production_registry();
|
||||
for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] {
|
||||
assert!(
|
||||
registry.advertise_for(CapabilityId::Logging, revision),
|
||||
"the implemented logging surface must be advertised in {revision}"
|
||||
);
|
||||
assert_eq!(
|
||||
registry.advertised_capabilities(revision)["logging"],
|
||||
json!({}),
|
||||
"the pinned advertisement is an empty `logging` object in {revision}"
|
||||
);
|
||||
}
|
||||
|
||||
// `logging/setLevel` is a legacy request only: the pinned modern revision replaces it with the
|
||||
// per-request `_meta` log level, so the modern era must never serve it.
|
||||
assert_eq!(
|
||||
registry.dispatch_decision("logging/setLevel", LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::LoggingSetLevel,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
registry.dispatch_decision("logging/setLevel", MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::LoggingSetLevel,
|
||||
kind: Kind::Method,
|
||||
},
|
||||
"a method the modern schema does not declare must never reach a handler there"
|
||||
);
|
||||
let descriptor = METHOD_DESCRIPTORS
|
||||
.iter()
|
||||
.find(|descriptor| descriptor.name == "logging/setLevel")
|
||||
.expect("logging/setLevel is a registered method");
|
||||
assert_eq!(
|
||||
descriptor.required_headers.0,
|
||||
&["Mcp-Method"],
|
||||
"the request declares a level, not a server-side name"
|
||||
);
|
||||
assert!(
|
||||
CAPABILITY_DESCRIPTORS
|
||||
.iter()
|
||||
.filter(|descriptor| descriptor.id == CapabilityId::LoggingSetLevel)
|
||||
.all(|descriptor| descriptor.advertised.is_none()),
|
||||
"the client request must never be advertised as a server capability"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_and_removing_a_method_descriptor_changes_the_dispatch_decision() {
|
||||
// The inert capability owns one inert method. With the method descriptor registered the
|
||||
// router routes it; without it the same request has no handler at all - the decision is the
|
||||
// registration, not a fixed list inside the router.
|
||||
const INERT_METHOD: MethodDescriptor = MethodDescriptor {
|
||||
name: "inert/echo",
|
||||
capability: CapabilityId::InertTest,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Ping,
|
||||
};
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(inert_descriptor());
|
||||
let mut methods = METHOD_DESCRIPTORS.to_vec();
|
||||
|
||||
let without = CapabilityRegistry::new(&capabilities, &methods)
|
||||
.expect("the production method table stays valid");
|
||||
assert_eq!(
|
||||
without.dispatch_decision(INERT_METHOD.name, MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::Unregistered
|
||||
);
|
||||
|
||||
methods.push(INERT_METHOD);
|
||||
let with = CapabilityRegistry::new(&capabilities, &methods)
|
||||
.expect("the inert method descriptor is a valid registration");
|
||||
assert_eq!(
|
||||
with.dispatch_decision(INERT_METHOD.name, MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
with.dispatch_decision(INERT_METHOD.name, LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
|
||||
// The advertisement projection is unaffected by a method descriptor: only capability
|
||||
// declarations advertise.
|
||||
assert_eq!(
|
||||
with.advertised_capabilities(MODERN_PROTOCOL_VERSION),
|
||||
json!({
|
||||
"inert_test_capability": {"enabled": true},
|
||||
"completions": {},
|
||||
"logging": {},
|
||||
"prompts": {"listChanged": false},
|
||||
"resources": {"listChanged": false, "subscribe": false},
|
||||
"tools": {"listChanged": false}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_method_of_an_unavailable_capability_is_never_dispatched() {
|
||||
// The inert capability is modern-only; its method must not be reachable in the legacy era.
|
||||
const INERT_METHOD: MethodDescriptor = MethodDescriptor {
|
||||
name: "inert/echo",
|
||||
capability: CapabilityId::InertTest,
|
||||
kind: Kind::Method,
|
||||
required_headers: HEADERS_NONE,
|
||||
handler: MethodHandler::Ping,
|
||||
};
|
||||
let mut capabilities = CAPABILITY_DESCRIPTORS.to_vec();
|
||||
capabilities.push(modern_only_descriptor());
|
||||
let mut methods = METHOD_DESCRIPTORS.to_vec();
|
||||
methods.push(INERT_METHOD);
|
||||
let registry =
|
||||
CapabilityRegistry::new(&capabilities, &methods).expect("valid inert registration");
|
||||
|
||||
assert_eq!(
|
||||
registry.dispatch_decision(INERT_METHOD.name, MODERN_PROTOCOL_VERSION),
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
registry.dispatch_decision(INERT_METHOD.name, LEGACY_PROTOCOL_VERSION),
|
||||
DispatchDecision::WrongEra {
|
||||
handler: MethodHandler::Ping,
|
||||
kind: Kind::Method,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,926 @@
|
||||
//! Story 3.8/3.11: the era-neutral `resources/list`, `resources/read` and
|
||||
//! `resources/templates/list` service boundary. Static Resource content is read from its exact Published
|
||||
//! artifact; dynamic templates use their exact Agent binding and shared runtime.
|
||||
//!
|
||||
//! The wire shape stays in the adapters and in the pinned per-revision converters
|
||||
//! (`crate::resource_wire`); this module never sees the envelope, the response mode or an
|
||||
//! `axum::Response`. Advertisement is not per-call authorization: the credential guard stays in the
|
||||
//! transport adapter and runs before any handler here.
|
||||
//!
|
||||
//! AC04: archive keeps the immutable publication row and therefore keeps the exact bound snapshot
|
||||
//! readable; new bindings are refused in the registry transition, not here.
|
||||
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use crank_artifacts::MAX_ARTIFACT_BYTES;
|
||||
use crank_core::resource::{ResourceError, ResourceKind};
|
||||
use crank_core::{ExecutionOrigin, InvocationSource, OperationSafetyClass, OperationStatus};
|
||||
use crank_registry::AgentResourceBinding;
|
||||
use crank_registry::BoundResourceAdmission;
|
||||
use crank_registry::model::ResolvedResourcePublication;
|
||||
use crank_runtime::{
|
||||
ExecutionAuthorization, RuntimeExecutionRequest, RuntimeOperation, RuntimeRequestContext,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{
|
||||
app::AppState,
|
||||
jsonrpc::MODERN_PROTOCOL_VERSION,
|
||||
protocol::ServiceContext,
|
||||
resource_wire::{resource_contents_2025_11_25, resource_contents_2026_07_28},
|
||||
};
|
||||
|
||||
/// Upper bound of one `resources/list` page (same shape as `tools/list`).
|
||||
const MAX_RESOURCES_LIST_LIMIT: usize = 100;
|
||||
/// Marker that makes a cursor value non-Resource-shaped: it is an opaque continuation token, never a
|
||||
/// URI, Resource id or raw offset.
|
||||
const CURSOR_VERSION: u8 = 1;
|
||||
|
||||
/// Parameters of a `resources/list` command, already parsed by the adapter from the wire form.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub(crate) struct ResourcesListCommand {
|
||||
#[serde(default)]
|
||||
pub(crate) cursor: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// Parameters of a `resources/read` command.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct ResourceReadCommand {
|
||||
pub(crate) uri: String,
|
||||
}
|
||||
|
||||
/// A command the shared Resources service accepts.
|
||||
pub(crate) enum ResourcesCommand {
|
||||
List(ResourcesListCommand),
|
||||
Read(ResourceReadCommand),
|
||||
}
|
||||
|
||||
/// A neutral outcome of a shared Resources command.
|
||||
pub(crate) enum ResourcesOutcome {
|
||||
Listed {
|
||||
resources: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
},
|
||||
Read {
|
||||
contents: Value,
|
||||
},
|
||||
/// The requested page is not representable (malformed/stale/cross-scope cursor): the adapter
|
||||
/// answers era-correct invalid params without mixing pages.
|
||||
InvalidParams(String),
|
||||
/// Unknown, Draft, foreign or unbound URI: one safe outcome that cannot distinguish them and
|
||||
/// carries no Resource metadata.
|
||||
NotAvailable,
|
||||
/// The published catalog could not be read.
|
||||
CatalogUnavailable,
|
||||
/// A bound publication could not be served safely, without disclosing content or metadata.
|
||||
ArtifactUnavailable,
|
||||
/// A sanitized correlated failure from the shared runtime.
|
||||
ExecutionError(crate::tool_error::ToolErrorContract),
|
||||
}
|
||||
|
||||
pub(crate) enum ResourceTemplatesListError {
|
||||
InvalidCursor,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// List exact Published template definitions bound to the active published Agent snapshot.
|
||||
pub(crate) async fn list_resource_templates(
|
||||
state: &Arc<AppState>,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
revision: &str,
|
||||
command: ResourcesListCommand,
|
||||
) -> Result<(Vec<Value>, Option<String>), ResourceTemplatesListError> {
|
||||
let catalog = state
|
||||
.catalog
|
||||
.get_catalog(workspace_slug, agent_slug)
|
||||
.await
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
let workspace_id = state
|
||||
.registry
|
||||
.published_agent_workspace_id(workspace_slug, agent_slug)
|
||||
.await
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
let scope = CursorScope {
|
||||
workspace_slug,
|
||||
agent_slug,
|
||||
catalog_revision: &catalog.catalog_revision,
|
||||
revision,
|
||||
};
|
||||
let start = command
|
||||
.cursor
|
||||
.as_deref()
|
||||
.map(|cursor| {
|
||||
decode_cursor(cursor, &scope, catalog.resources.len())
|
||||
.ok_or(ResourceTemplatesListError::InvalidCursor)
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or(0);
|
||||
let limit = command
|
||||
.limit
|
||||
.unwrap_or(MAX_RESOURCES_LIST_LIMIT)
|
||||
.clamp(1, MAX_RESOURCES_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(catalog.resources.len());
|
||||
let admitted = state
|
||||
.registry
|
||||
.list_admitted_resource_templates(workspace_id.as_str(), &catalog.resources[start..end])
|
||||
.await
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
let mut templates = Vec::new();
|
||||
for item in admitted {
|
||||
let definition: Value = serde_json::from_str(&item.source.definition_json)
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
let source = crank_core::resource::TemplateSource::parse(&definition)
|
||||
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
||||
templates.push(json!({
|
||||
"uriTemplate": source.uri_template,
|
||||
"name": item.publication.name,
|
||||
"description": item.publication.description,
|
||||
"mimeType": item.publication.mime_type,
|
||||
"parameters": source.parameters
|
||||
}));
|
||||
}
|
||||
let next_cursor = (end < catalog.resources.len()).then(|| encode_cursor(&scope, end));
|
||||
Ok((templates, next_cursor))
|
||||
}
|
||||
|
||||
/// Handle one shared Resources command for the revision the adapter serves.
|
||||
pub(crate) async fn handle_resources_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: ResourcesCommand,
|
||||
) -> ResourcesOutcome {
|
||||
let catalog = match state
|
||||
.catalog
|
||||
.get_catalog(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(catalog) => catalog,
|
||||
Err(_error) => return ResourcesOutcome::CatalogUnavailable,
|
||||
};
|
||||
let workspace_id = match state
|
||||
.registry
|
||||
.published_agent_workspace_id(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(workspace_id) => workspace_id,
|
||||
Err(_error) => return ResourcesOutcome::CatalogUnavailable,
|
||||
};
|
||||
let scope = CursorScope {
|
||||
workspace_slug: context.workspace_slug,
|
||||
agent_slug: context.agent_slug,
|
||||
catalog_revision: &catalog.catalog_revision,
|
||||
revision,
|
||||
};
|
||||
|
||||
match command {
|
||||
ResourcesCommand::List(list) => {
|
||||
list_resources(state, &workspace_id, &catalog.resources, &scope, list).await
|
||||
}
|
||||
ResourcesCommand::Read(read) => {
|
||||
read_resource(
|
||||
state,
|
||||
context,
|
||||
&workspace_id,
|
||||
&catalog.resources,
|
||||
revision,
|
||||
&read,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn list_resources(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
scope: &CursorScope<'_>,
|
||||
command: ResourcesListCommand,
|
||||
) -> ResourcesOutcome {
|
||||
let start = match command.cursor.as_deref() {
|
||||
Some(cursor) => match decode_cursor(cursor, scope, bindings.len()) {
|
||||
Some(offset) => offset,
|
||||
None => {
|
||||
return ResourcesOutcome::InvalidParams("invalid resources/list cursor".to_owned());
|
||||
}
|
||||
},
|
||||
None => 0,
|
||||
};
|
||||
let limit = command
|
||||
.limit
|
||||
.unwrap_or(bindings.len())
|
||||
.clamp(1, MAX_RESOURCES_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(bindings.len());
|
||||
|
||||
let mut resources = Vec::with_capacity(end - start);
|
||||
let mut revoked_omitted = 0usize;
|
||||
// Story 3.8: живой PostgreSQL-gate страницы. Shared-блокировки берутся на
|
||||
// исходный диапазон [start, end) в порядке resource_id ASC, затем читаются
|
||||
// свежие tombstones; offset/cursor продолжают адресовать исходный immutable
|
||||
// bindings-массив, поэтому отзыв между страницами не сдвигает и не дублирует
|
||||
// элементы. Отозванный Resource — единственное, что пропускается: corruption
|
||||
// или storage-сбой не маскируются успешной partial-страницей.
|
||||
let admitted = match state
|
||||
.registry
|
||||
.list_admitted_resource_publications(workspace_id.as_str(), &bindings[start..end])
|
||||
.await
|
||||
{
|
||||
Ok(admitted) => admitted,
|
||||
Err(_error) => return ResourcesOutcome::ArtifactUnavailable,
|
||||
};
|
||||
for admission in admitted {
|
||||
let resolved = match admission {
|
||||
BoundResourceAdmission::Revoked => {
|
||||
revoked_omitted += 1;
|
||||
continue;
|
||||
}
|
||||
BoundResourceAdmission::Admitted(resolved) => *resolved,
|
||||
// A published template is not an artifact-backed concrete Resource: its concrete URIs
|
||||
// are the expanded ones and its definition is discovered through
|
||||
// `resources/templates/list`. Listing its identity URI here would advertise an
|
||||
// unreadable Resource, so the admitted binding only keeps the page alive.
|
||||
BoundResourceAdmission::Template => continue,
|
||||
};
|
||||
resources.push(json!({
|
||||
"uri": resolved.publication.uri,
|
||||
"name": resolved.publication.name,
|
||||
"mimeType": resolved.publication.mime_type,
|
||||
}));
|
||||
}
|
||||
if revoked_omitted > 0 {
|
||||
// Only the number of omitted entries: no URI, name, MIME or digest of a denied Resource.
|
||||
info!(
|
||||
name: "mcp.resources.list",
|
||||
request_id = %resolved_request_id(),
|
||||
trace_id = %resolved_trace_id(),
|
||||
outcome = "filtered",
|
||||
revoked_omitted,
|
||||
"resource list page omitted revoked resources"
|
||||
);
|
||||
}
|
||||
|
||||
let next_cursor = (end < bindings.len()).then(|| encode_cursor(scope, end));
|
||||
ResourcesOutcome::Listed {
|
||||
resources,
|
||||
next_cursor,
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_resource(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
revision: &str,
|
||||
command: &ResourceReadCommand,
|
||||
) -> ResourcesOutcome {
|
||||
if let Some(outcome) = match_template_read(
|
||||
state,
|
||||
&context,
|
||||
workspace_id,
|
||||
bindings,
|
||||
revision,
|
||||
&command.uri,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return outcome;
|
||||
}
|
||||
// Resolve the requested static URI against the exact bound snapshot only. Nothing is looked up by the
|
||||
// client-supplied URI, so an unknown/Draft/unbound URI cannot even prove that it exists.
|
||||
// A corrupt/missing publication or a storage failure is *not* the same answer: it must not be
|
||||
// disguised as an unknown URI (the typed error is preserved instead of being dropped).
|
||||
let mut matched: Option<AgentResourceBinding> = None;
|
||||
for binding in bindings {
|
||||
match resolve_binding(state, workspace_id, binding).await {
|
||||
Ok(Some(resolved)) => {
|
||||
if resolved.publication.uri == command.uri {
|
||||
matched = Some(binding.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
// No exact publication for this bound version: the URI simply cannot match.
|
||||
Ok(None) => {}
|
||||
Err(_error) => return ResourcesOutcome::ArtifactUnavailable,
|
||||
}
|
||||
}
|
||||
let Some(binding) = matched else {
|
||||
log_read_denied("not_available");
|
||||
return ResourcesOutcome::NotAvailable;
|
||||
};
|
||||
|
||||
// Story 3.8: живой PostgreSQL-gate, не cache. `FOR SHARE` на строке Resource
|
||||
// удерживается до успешного commit, поэтому revoke-first закрывает чтение до
|
||||
// artifact bytes (0 чтений), а read-first линеаризует чтение до отзыва.
|
||||
// Revoked неотличим от unknown/Draft/unbound: тот же безопасный NotAvailable.
|
||||
let guard = match state
|
||||
.registry
|
||||
.begin_authorized_resource_read(
|
||||
workspace_id.as_str(),
|
||||
&binding.resource_id,
|
||||
binding.resource_version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(guard) => guard,
|
||||
Err(ResourceError::Revoked) => {
|
||||
log_read_denied("denied");
|
||||
return ResourcesOutcome::NotAvailable;
|
||||
}
|
||||
Err(_error) => return ResourcesOutcome::ArtifactUnavailable,
|
||||
};
|
||||
let resolved = guard.publication();
|
||||
|
||||
// Access (binding + credential, enforced by the adapter) is decided. Size is decided from the
|
||||
// immutable publication metadata *before* any artifact byte is opened.
|
||||
let Ok(size_bytes) = usize::try_from(resolved.publication.size_bytes) else {
|
||||
return ResourcesOutcome::ArtifactUnavailable;
|
||||
};
|
||||
if size_bytes == 0 || size_bytes > MAX_ARTIFACT_BYTES {
|
||||
return ResourcesOutcome::ArtifactUnavailable;
|
||||
}
|
||||
let Some(store) = state.artifact_store.as_ref() else {
|
||||
return ResourcesOutcome::ArtifactUnavailable;
|
||||
};
|
||||
let bytes = match store.read(&resolved.artifact_ref) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(_error) => return ResourcesOutcome::ArtifactUnavailable,
|
||||
};
|
||||
let Some(kind) = ResourceKind::parse(&resolved.publication.kind) else {
|
||||
return ResourcesOutcome::ArtifactUnavailable;
|
||||
};
|
||||
|
||||
let contents = match revision {
|
||||
MODERN_PROTOCOL_VERSION => resource_contents_2026_07_28(
|
||||
&resolved.publication.uri,
|
||||
kind,
|
||||
&resolved.publication.mime_type,
|
||||
&bytes,
|
||||
),
|
||||
_ => resource_contents_2025_11_25(
|
||||
&resolved.publication.uri,
|
||||
kind,
|
||||
&resolved.publication.mime_type,
|
||||
&bytes,
|
||||
),
|
||||
};
|
||||
|
||||
// Транзакция завершается до выдачи готового outcome: ошибка commit — безопасный
|
||||
// отказ, а не выдача подготовленного content.
|
||||
if guard.commit().await.is_err() {
|
||||
return ResourcesOutcome::ArtifactUnavailable;
|
||||
}
|
||||
|
||||
// Read outcome telemetry: correlation identity and the byte count only — never the URI, the MIME
|
||||
// payload or any content.
|
||||
info!(
|
||||
name: "mcp.resources.read",
|
||||
request_id = %resolved_request_id(),
|
||||
trace_id = %resolved_trace_id(),
|
||||
outcome = "ok",
|
||||
content_bytes = bytes.len(),
|
||||
resource_kind = kind.as_str(),
|
||||
"resource read outcome"
|
||||
);
|
||||
|
||||
ResourcesOutcome::Read {
|
||||
contents: json!([contents]),
|
||||
}
|
||||
}
|
||||
|
||||
async fn match_template_read(
|
||||
state: &Arc<AppState>,
|
||||
context: &ServiceContext<'_>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
revision: &str,
|
||||
uri: &str,
|
||||
) -> Option<ResourcesOutcome> {
|
||||
macro_rules! fail_closed {
|
||||
($stage:literal) => {{
|
||||
tracing::warn!(name: "mcp.resource_template.read", stage = $stage, "template read unavailable");
|
||||
let failure = crank_core::ExecutionFailure::new(
|
||||
crank_core::ExecutionErrorCode::RuntimeInternal,
|
||||
context.correlation.clone(),
|
||||
);
|
||||
return Some(ResourcesOutcome::ExecutionError(
|
||||
crate::tool_error::tool_error_contract_from_failure(&failure, context.locale),
|
||||
));
|
||||
}};
|
||||
}
|
||||
let admitted = match state
|
||||
.registry
|
||||
.list_admitted_resource_templates(workspace_id.as_str(), bindings)
|
||||
.await
|
||||
{
|
||||
Ok(bindings) => bindings,
|
||||
Err(_) => {
|
||||
tracing::warn!(
|
||||
name: "mcp.resource_template.read",
|
||||
stage = "binding_admission",
|
||||
"template admission unavailable"
|
||||
);
|
||||
return Some(ResourcesOutcome::CatalogUnavailable);
|
||||
}
|
||||
};
|
||||
for template in admitted {
|
||||
let publication = template.publication;
|
||||
let definition: Value = match serde_json::from_str(&template.source.definition_json) {
|
||||
Ok(value) => value,
|
||||
Err(_) => fail_closed!("definition_parse"),
|
||||
};
|
||||
let source = match crank_core::resource::TemplateSource::parse(&definition) {
|
||||
Ok(source) => source,
|
||||
Err(_) => fail_closed!("source_validation"),
|
||||
};
|
||||
let Some(input) = match_template_uri(&source, uri) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let operation_id = crank_core::OperationId::new(source.operation_id.clone());
|
||||
let operation_record = match state
|
||||
.registry
|
||||
.get_operation_version(workspace_id, &operation_id, source.operation_version)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) if record.status == OperationStatus::Published => record,
|
||||
Ok(Some(_record)) => fail_closed!("operation_version_status"),
|
||||
Ok(None) => fail_closed!("operation_version_missing"),
|
||||
Err(_) => fail_closed!("operation_version_query"),
|
||||
};
|
||||
let summary = match state
|
||||
.registry
|
||||
.get_operation_summary(workspace_id, &operation_id)
|
||||
.await
|
||||
{
|
||||
Ok(Some(summary)) if summary.status != OperationStatus::Archived => summary,
|
||||
_ => fail_closed!("operation_eligibility"),
|
||||
};
|
||||
if !crate::access::credential_allows_security_level(
|
||||
context.credential,
|
||||
operation_record.snapshot.security_level,
|
||||
) {
|
||||
return Some(template_output_error(
|
||||
context,
|
||||
crank_core::ExecutionErrorCode::AuthorizationDenied,
|
||||
));
|
||||
}
|
||||
let operation = RuntimeOperation::from(operation_record.snapshot.clone());
|
||||
let safety = operation
|
||||
.execution_config
|
||||
.safety
|
||||
.as_ref()
|
||||
.map(|policy| policy.class);
|
||||
if safety != Some(OperationSafetyClass::Read)
|
||||
|| operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()
|
||||
.is_some_and(|policy| policy.required)
|
||||
|| !matches!(&operation.target, crank_core::Target::Rest(target) if matches!(target.method, crank_core::HttpMethod::Get | crank_core::HttpMethod::Head))
|
||||
{
|
||||
fail_closed!("operation_policy");
|
||||
}
|
||||
let agent_id = match state
|
||||
.registry
|
||||
.published_agent_id(context.workspace_slug, context.agent_slug)
|
||||
.await
|
||||
{
|
||||
Ok(agent_id) => agent_id,
|
||||
Err(_) => fail_closed!("agent_identity"),
|
||||
};
|
||||
let request_context = RuntimeRequestContext::from_correlation(context.correlation)
|
||||
.with_response_cache_scope(
|
||||
workspace_id.as_str().to_owned(),
|
||||
agent_id.as_str().to_owned(),
|
||||
)
|
||||
.with_resource_response_cache(
|
||||
publication.resource_id.as_str(),
|
||||
publication.version,
|
||||
source.cache.ttl_ms,
|
||||
source.cache.max_bytes,
|
||||
)
|
||||
.with_metering_context(
|
||||
workspace_id.clone(),
|
||||
Some(agent_id.clone()),
|
||||
InvocationSource::AgentToolCall,
|
||||
);
|
||||
// Re-read operation lifecycle and exact version immediately before outbound dispatch.
|
||||
match state
|
||||
.registry
|
||||
.get_operation_summary(workspace_id, &operation_id)
|
||||
.await
|
||||
{
|
||||
Ok(Some(summary)) if summary.status != OperationStatus::Archived => {}
|
||||
_ => fail_closed!("operation_eligibility"),
|
||||
}
|
||||
match state
|
||||
.registry
|
||||
.get_operation_version(workspace_id, &operation_id, source.operation_version)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) if record.status == OperationStatus::Published => {}
|
||||
_ => fail_closed!("operation_version"),
|
||||
}
|
||||
let resolved_auth = match crate::app::resolve_operation_auth(
|
||||
state,
|
||||
workspace_id,
|
||||
&operation.execution_config,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(auth) => auth,
|
||||
Err(error) => {
|
||||
return Some(ResourcesOutcome::ExecutionError(
|
||||
crate::tool_error::tool_error_contract_from_runtime(
|
||||
&error,
|
||||
context.correlation.request_id().as_str(),
|
||||
context.correlation.trace_id().as_str(),
|
||||
context.locale,
|
||||
),
|
||||
));
|
||||
}
|
||||
};
|
||||
let request = RuntimeExecutionRequest::try_new(
|
||||
workspace_id,
|
||||
ExecutionOrigin::AgentSnapshot,
|
||||
Some(&agent_id),
|
||||
&operation,
|
||||
&input,
|
||||
ExecutionAuthorization::Authorized,
|
||||
resolved_auth.as_ref(),
|
||||
&request_context,
|
||||
Instant::now()
|
||||
+ std::time::Duration::from_millis(operation.execution_config.timeout_ms.max(1)),
|
||||
);
|
||||
// Acquire the live Resource lock only after registry/auth lookups, then hold it through dispatch.
|
||||
let guard = match state
|
||||
.registry
|
||||
.begin_authorized_resource_template_read(
|
||||
workspace_id.as_str(),
|
||||
&publication.resource_id,
|
||||
publication.version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(guard) => guard,
|
||||
Err(ResourceError::Revoked | ResourceError::NotFound) => {
|
||||
return Some(ResourcesOutcome::NotAvailable);
|
||||
}
|
||||
Err(_) => fail_closed!("resource_read_admission"),
|
||||
};
|
||||
let success = match request {
|
||||
Ok(request) => match state.runtime.execute_outcome(request).await {
|
||||
Ok(success) => success,
|
||||
Err(failure) => {
|
||||
return Some(ResourcesOutcome::ExecutionError(
|
||||
crate::tool_error::tool_error_contract_from_failure(
|
||||
&failure,
|
||||
context.locale,
|
||||
),
|
||||
));
|
||||
}
|
||||
},
|
||||
Err(_) => fail_closed!("runtime_request"),
|
||||
};
|
||||
let Some(kind) = ResourceKind::for_mime(&publication.mime_type) else {
|
||||
return Some(template_output_error(
|
||||
context,
|
||||
crank_core::ExecutionErrorCode::OutputMappingInvalid,
|
||||
));
|
||||
};
|
||||
let Some(bytes) = mapped_resource_bytes(kind, &success.output) else {
|
||||
return Some(template_output_error(
|
||||
context,
|
||||
crank_core::ExecutionErrorCode::OutputMappingInvalid,
|
||||
));
|
||||
};
|
||||
let max_bytes = usize::try_from(source.cache.max_bytes)
|
||||
.unwrap_or(MAX_ARTIFACT_BYTES)
|
||||
.min(MAX_ARTIFACT_BYTES);
|
||||
if bytes.is_empty() || bytes.len() > max_bytes {
|
||||
return Some(template_output_error(
|
||||
context,
|
||||
crank_core::ExecutionErrorCode::UpstreamResponseTooLarge,
|
||||
));
|
||||
}
|
||||
if guard.commit().await.is_err() {
|
||||
fail_closed!("resource_guard_commit");
|
||||
}
|
||||
let contents = if revision == MODERN_PROTOCOL_VERSION {
|
||||
resource_contents_2026_07_28(uri, kind, &publication.mime_type, &bytes)
|
||||
} else {
|
||||
resource_contents_2025_11_25(uri, kind, &publication.mime_type, &bytes)
|
||||
};
|
||||
let _ = summary;
|
||||
return Some(ResourcesOutcome::Read {
|
||||
contents: json!([contents]),
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn mapped_resource_bytes(kind: ResourceKind, output: &Value) -> Option<Vec<u8>> {
|
||||
match kind {
|
||||
ResourceKind::Text => output.as_str().map(|text| text.as_bytes().to_vec()),
|
||||
ResourceKind::Json if !output.is_null() => serde_json::to_vec(output).ok(),
|
||||
ResourceKind::Binary => output
|
||||
.as_object()
|
||||
.filter(|object| object.len() == 1 && object.contains_key("data_base64"))
|
||||
.and_then(|object| object.get("data_base64"))
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|encoded| {
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode(encoded)
|
||||
.ok()
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn template_output_error(
|
||||
context: &ServiceContext<'_>,
|
||||
code: crank_core::ExecutionErrorCode,
|
||||
) -> ResourcesOutcome {
|
||||
let failure = crank_core::ExecutionFailure::new(code, context.correlation.clone());
|
||||
ResourcesOutcome::ExecutionError(crate::tool_error::tool_error_contract_from_failure(
|
||||
&failure,
|
||||
context.locale,
|
||||
))
|
||||
}
|
||||
|
||||
fn match_template_uri(source: &crank_core::resource::TemplateSource, uri: &str) -> Option<Value> {
|
||||
let names = crank_core::resource::parse_uri_template(&source.uri_template).ok()?;
|
||||
let template_segments: Vec<_> = source.uri_template.split('/').collect();
|
||||
let uri_segments: Vec<_> = uri.split('/').collect();
|
||||
if template_segments.len() != uri_segments.len() {
|
||||
return None;
|
||||
}
|
||||
let mut values = serde_json::Map::new();
|
||||
let mut name_index = 0;
|
||||
for (template, actual) in template_segments.iter().zip(uri_segments) {
|
||||
if template.starts_with('{') && template.ends_with('}') {
|
||||
let name = names.get(name_index)?;
|
||||
let decoded = decode_uri_segment(actual)?;
|
||||
let parameter = source.parameters.iter().find(|p| p.name == *name)?;
|
||||
let value = parse_template_parameter(¶meter.schema, &decoded)?;
|
||||
if !set_input_path(&mut values, ¶meter.input_path, value) {
|
||||
return None;
|
||||
}
|
||||
name_index += 1;
|
||||
} else if template != &actual {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(Value::Object(values))
|
||||
}
|
||||
|
||||
fn parse_template_parameter(schema: &Value, raw: &str) -> Option<Value> {
|
||||
let value = match schema.get("type")?.as_str()? {
|
||||
"string" | "enum" => Value::String(raw.to_owned()),
|
||||
"integer" => Value::Number(raw.parse::<i64>().ok()?.into()),
|
||||
"number" => serde_json::Number::from_f64(raw.parse::<f64>().ok()?).map(Value::Number)?,
|
||||
"boolean" => Value::Bool(raw.parse::<bool>().ok()?),
|
||||
_ => return None,
|
||||
};
|
||||
let parameter_schema: crank_schema::Schema = serde_json::from_value(schema.clone()).ok()?;
|
||||
crank_runtime::validate_resource_template_parameter(¶meter_schema, &value).ok()?;
|
||||
Some(value)
|
||||
}
|
||||
|
||||
pub(super) fn set_input_path(
|
||||
root: &mut serde_json::Map<String, Value>,
|
||||
path: &str,
|
||||
value: Value,
|
||||
) -> bool {
|
||||
let Some((prefix, segments)) = path.split_once('.') else {
|
||||
return false;
|
||||
};
|
||||
if prefix != "input" {
|
||||
return false;
|
||||
}
|
||||
let mut current = root;
|
||||
let mut parts = segments.split('.').peekable();
|
||||
while let Some(part) = parts.next() {
|
||||
if parts.peek().is_none() {
|
||||
current.insert(part.to_owned(), value);
|
||||
return true;
|
||||
}
|
||||
let entry = current.entry(part.to_owned()).or_insert_with(|| json!({}));
|
||||
let Some(object) = entry.as_object_mut() else {
|
||||
return false;
|
||||
};
|
||||
current = object;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn decode_uri_segment(segment: &str) -> Option<String> {
|
||||
let bytes = segment.as_bytes();
|
||||
let mut decoded = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%' {
|
||||
let hi = *bytes.get(i + 1)?;
|
||||
let lo = *bytes.get(i + 2)?;
|
||||
decoded.push((hex_digit(hi)? << 4) | hex_digit(lo)?);
|
||||
i += 3;
|
||||
} else {
|
||||
if !bytes[i].is_ascii_alphanumeric() && !matches!(bytes[i], b'-' | b'_' | b'.' | b'~') {
|
||||
return None;
|
||||
}
|
||||
decoded.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let value = String::from_utf8(decoded).ok()?;
|
||||
if value == "." || value == ".." {
|
||||
return None;
|
||||
}
|
||||
Some(value)
|
||||
}
|
||||
|
||||
fn hex_digit(value: u8) -> Option<u8> {
|
||||
match value {
|
||||
b'0'..=b'9' => Some(value - b'0'),
|
||||
b'a'..=b'f' => Some(value - b'a' + 10),
|
||||
b'A'..=b'F' => Some(value - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod template_uri_tests {
|
||||
use super::{decode_uri_segment, match_template_uri, parse_template_parameter};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn uri_variables_are_decoded_before_typed_validation_but_keep_reserved_data() {
|
||||
let source = crank_core::resource::TemplateSource::parse(&json!({
|
||||
"operation_id": "op_order", "operation_version": 1,
|
||||
"uri_template": "crank://orders/{order_id}",
|
||||
"parameters": [{ "name": "order_id", "input_path": "input.order_id", "schema": { "type": "string" } }],
|
||||
"cache": { "ttl_ms": 1000, "vary": ["order_id"], "max_bytes": 1024 },
|
||||
"failure": { "outcome": "error" }
|
||||
})).unwrap();
|
||||
let input = match_template_uri(&source, "crank://orders/a%2Fb%3Fc").unwrap();
|
||||
assert_eq!(input["order_id"], "a/b?c");
|
||||
assert_eq!(decode_uri_segment("%2e%2e"), None);
|
||||
assert!(match_template_uri(&source, "crank://orders/../admin").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_parameter_enum_values_are_enforced_from_the_saved_schema() {
|
||||
let schema: Value = json!({ "type": "string", "enum_values": ["eu"] });
|
||||
assert_eq!(parse_template_parameter(&schema, "eu"), Some(json!("eu")));
|
||||
assert!(parse_template_parameter(&schema, "us").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uuid_parameters_are_rejected_before_runtime_request_construction() {
|
||||
let schema: Value = json!({ "type": "string", "format": "uuid" });
|
||||
assert!(
|
||||
parse_template_parameter(&schema, "f47ac10b-58cc-4372-a567-0e02b2c3d479").is_some()
|
||||
);
|
||||
assert!(parse_template_parameter(&schema, "not-a-uuid").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
fn resolved_request_id() -> String {
|
||||
crank_observability::current_request_correlation()
|
||||
.0
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn resolved_trace_id() -> String {
|
||||
crank_observability::current_request_correlation()
|
||||
.1
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Resolve one exact bound version to its publication metadata.
|
||||
///
|
||||
/// `Ok(None)` means the bound version has no exact publication (it cannot be the requested URI);
|
||||
/// every other error keeps its type so the caller can answer a safe *unavailable* instead of a
|
||||
/// misleading "not available". The bytes are still only served through the live gate below.
|
||||
async fn resolve_binding(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
binding: &AgentResourceBinding,
|
||||
) -> Result<Option<ResolvedResourcePublication>, ResourceError> {
|
||||
match state
|
||||
.registry
|
||||
.resolve_resource_publication(
|
||||
workspace_id.as_str(),
|
||||
&binding.resource_id,
|
||||
binding.resource_version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resolved) => Ok(Some(resolved)),
|
||||
Err(ResourceError::NotFound) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Denied-read telemetry: correlation identity and the safe outcome only. The URI, Resource name,
|
||||
/// MIME, digest and any path are deliberately absent, so a denied read cannot leak what it denied.
|
||||
fn log_read_denied(outcome: &'static str) {
|
||||
info!(
|
||||
name: "mcp.resources.read",
|
||||
request_id = %resolved_request_id(),
|
||||
trace_id = %resolved_trace_id(),
|
||||
outcome,
|
||||
"resource read outcome"
|
||||
);
|
||||
}
|
||||
|
||||
/// The immutable scope a continuation token is bound to: workspace + Agent + catalog revision + the
|
||||
/// negotiated MCP revision. A cursor that does not match this request is never mixed into a page.
|
||||
struct CursorScope<'a> {
|
||||
workspace_slug: &'a str,
|
||||
agent_slug: &'a str,
|
||||
catalog_revision: &'a str,
|
||||
revision: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct CursorPayload {
|
||||
v: u8,
|
||||
w: String,
|
||||
a: String,
|
||||
c: String,
|
||||
r: String,
|
||||
o: usize,
|
||||
}
|
||||
|
||||
fn encode_cursor(scope: &CursorScope<'_>, offset: usize) -> String {
|
||||
let payload = CursorPayload {
|
||||
v: CURSOR_VERSION,
|
||||
w: scope.workspace_slug.to_owned(),
|
||||
a: scope.agent_slug.to_owned(),
|
||||
c: scope.catalog_revision.to_owned(),
|
||||
r: scope.revision.to_owned(),
|
||||
o: offset,
|
||||
};
|
||||
let encoded = serde_json::to_vec(&payload).unwrap_or_default();
|
||||
URL_SAFE_NO_PAD.encode(encoded)
|
||||
}
|
||||
|
||||
fn decode_cursor(raw: &str, scope: &CursorScope<'_>, len: usize) -> Option<usize> {
|
||||
let bytes = URL_SAFE_NO_PAD.decode(raw).ok()?;
|
||||
let payload: CursorPayload = serde_json::from_slice(&bytes).ok()?;
|
||||
let matches = payload.v == CURSOR_VERSION
|
||||
&& payload.w == scope.workspace_slug
|
||||
&& payload.a == scope.agent_slug
|
||||
&& payload.c == scope.catalog_revision
|
||||
&& payload.r == scope.revision;
|
||||
(matches && payload.o <= len).then_some(payload.o)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod template_output_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resource_output_mapping_enforces_text_json_and_binary_contracts() {
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Text, &json!("hi")).unwrap(),
|
||||
b"hi"
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Text, &json!({"text":"hi"})),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Json, &json!({"ok":true})).unwrap(),
|
||||
br#"{"ok":true}"#
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Json, &Value::Null),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Binary, &json!({"data_base64":"AAE="})).unwrap(),
|
||||
[0, 1]
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(ResourceKind::Binary, &json!({"data_base64":"not-base64"})),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
mapped_resource_bytes(
|
||||
ResourceKind::Binary,
|
||||
&json!({"data_base64":"AA==","path":"/tmp/x"})
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Story 3.6, граница MCP (AT-3.6-06): чистые per-revision функции,
|
||||
//! транслирующие Resource Version в `contents[]`.
|
||||
//!
|
||||
//! Регистрация MCP живёт в `protocol::registry`: Story 3.8 добавила Resources
|
||||
//! capability и `resources/list`/`resources/read` ровно потому, что handlers
|
||||
//! реализованы; этот модуль остаётся чистой границей ревизий и не решает, что
|
||||
//! рекламируется и что диспатчится.
|
||||
//!
|
||||
//! Ветка `contents[]` выбирается **typed kind**, а не разбором байтов: для
|
||||
//! `ResourceKind::Binary` это всегда `blob` (base64), даже если bytes декодируются
|
||||
//! как UTF-8; для text/JSON — `text`. Content sniffing отсутствует.
|
||||
//!
|
||||
//! Форма `contents[]` одинакова для обеих ревизий и следует их схемам:
|
||||
//!
|
||||
//! - `2026-07-28-schema.ts`: `ReadResourceResult extends CacheableResult`,
|
||||
//! `ResourceContents {uri, mimeType?, _meta?}`, `TextResourceContents{text}`,
|
||||
//! `BlobResourceContents{blob}`;
|
||||
//! - `2025-11-25-schema.ts`: `ReadResourceResult extends Result`, тот же
|
||||
//! `ResourceContents`.
|
||||
//!
|
||||
//! Различия ревизий лежат во внешнем результате (cacheable-поля), который 3.6 не
|
||||
//! публикует, поэтому здесь строится только `contents`.
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use crank_core::resource::ResourceKind;
|
||||
#[cfg(test)]
|
||||
use crank_core::resource::{ResourceFinding, ResourceLimits, ResourceMetadata};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// `contents[]` для ревизии `2026-07-28`.
|
||||
///
|
||||
/// Чистая функция границы ревизий: она не регистрирует MCP-метод и не рекламирует
|
||||
/// capability (D-17), а только транслирует уже провалидированную версию Resource.
|
||||
pub fn resource_contents_2026_07_28(
|
||||
uri: &str,
|
||||
kind: ResourceKind,
|
||||
mime_type: &str,
|
||||
bytes: &[u8],
|
||||
) -> Value {
|
||||
contents(uri, kind, mime_type, bytes)
|
||||
}
|
||||
|
||||
/// `contents[]` для ревизии `2025-11-25`.
|
||||
pub fn resource_contents_2025_11_25(
|
||||
uri: &str,
|
||||
kind: ResourceKind,
|
||||
mime_type: &str,
|
||||
bytes: &[u8],
|
||||
) -> Value {
|
||||
contents(uri, kind, mime_type, bytes)
|
||||
}
|
||||
|
||||
fn contents(uri: &str, kind: ResourceKind, mime_type: &str, bytes: &[u8]) -> Value {
|
||||
match kind {
|
||||
ResourceKind::Binary => json!({
|
||||
"uri": uri,
|
||||
"mimeType": mime_type,
|
||||
"blob": STANDARD.encode(bytes),
|
||||
}),
|
||||
ResourceKind::Text | ResourceKind::Json => json!({
|
||||
"uri": uri,
|
||||
"mimeType": mime_type,
|
||||
"text": String::from_utf8_lossy(bytes),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Безопасный finding для MIME вне allowlist: только код и поле, без bytes.
|
||||
///
|
||||
/// Используется тестами границы (в production-коде 3.6 вызов не нужен).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn resource_mime_finding(mime_type: &str) -> ResourceFinding {
|
||||
ResourceMetadata::mime_finding(mime_type, ResourceKind::Binary, &ResourceLimits::default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "resource_wire/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,195 @@
|
||||
//! BUILD-ONLY: in-crate проверки per-revision адаптера Story 3.6 (AT-3.6-06, таргет V).
|
||||
//!
|
||||
//! Статус на стадии Dev ATDD: **не зарегистрирован**. BUILD объявляет файл из production-модуля:
|
||||
//! ```text
|
||||
//! // crates/crank-community-mcp/src/resource_wire.rs
|
||||
//! #[cfg(test)] #[path = "resource_wire/tests.rs"] mod tests;
|
||||
//! ```
|
||||
//! Сегодня `src/resource_wire.rs` не существует, поэтому файл не компилируется и не исполняется;
|
||||
//! нулевая коллекция — не PASS. Внешний таргет `tests/unit.rs` этой крейты для приватного модуля
|
||||
//! невидим и намеренно не трогается (D-19).
|
||||
//!
|
||||
//! Минимальный будущий интерфейс (SPEC v4 §5, D-17): чистые per-revision функции
|
||||
//! `resource_wire::{resource_contents_2026_07_28, resource_contents_2025_11_25}` (без регистрации
|
||||
//! MCP-методов и без рекламы capability) вида
|
||||
//! `(uri: &str, kind: crank_core::resource::ResourceKind, mime_type: &str, bytes: &[u8]) -> Value`:
|
||||
//! ветка `contents[]` выбирается **typed kind**, а не разбором байтов (никакого content sniffing):
|
||||
//! для `ResourceKind::Binary` — `{uri, mimeType, blob: base64}` всегда, даже если байты
|
||||
//! декодируются как UTF-8; для text/JSON — `{uri, mimeType, text}`. Форма одинакова для обеих
|
||||
//! ревизий (`2026-07-28`, `2025-11-25`) со своими правилами ревизии.
|
||||
//! Регистрация `CAPABILITY_DESCRIPTORS`/`METHOD_DESCRIPTORS` не меняется, и `resources/read`
|
||||
//! сохраняет существующий ответ (existing GREEN, проверяется отдельной строкой).
|
||||
//!
|
||||
//! Запуск после BUILD: `cargo test -p crank-community-mcp --lib story36_ -- --test-threads=1`.
|
||||
|
||||
use super::{resource_contents_2025_11_25, resource_contents_2026_07_28};
|
||||
use crate::protocol::{CAPABILITY_DESCRIPTORS, METHOD_DESCRIPTORS};
|
||||
use crank_core::resource::ResourceKind;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const TEXT: &[u8] = "Заголовок\n".as_bytes();
|
||||
const JSON_DOCUMENT: &[u8] = "{\"b\":1,\"a\":[1,2,3],\"дубликат\":1,\"дубликат\":2}".as_bytes();
|
||||
const BINARY_BYTES: &[u8] = &[0x00, 0xFF, 0x80, 0xC3, 0x28];
|
||||
/// Байты, которые **корректно** декодируются как UTF-8, но принадлежат kind=binary:
|
||||
/// выбор ветки не может зависеть от декодируемости (D-5/D-17).
|
||||
const BINARY_UTF8_MARKUP: &[u8] =
|
||||
b"<html><body><script>window.__c36='active'</script></body></html>";
|
||||
|
||||
struct Case {
|
||||
label: &'static str,
|
||||
uri: &'static str,
|
||||
kind: ResourceKind,
|
||||
mime: &'static str,
|
||||
bytes: &'static [u8],
|
||||
}
|
||||
|
||||
/// Один набор кейсов на обе ревизии: правила выбора ветки общие, форма `contents[]`
|
||||
/// отличается только правилами конкретной ревизии.
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = vec![
|
||||
Case {
|
||||
label: "text/plain",
|
||||
uri: "crank://adapter/text",
|
||||
kind: ResourceKind::Text,
|
||||
mime: "text/plain",
|
||||
bytes: TEXT,
|
||||
},
|
||||
Case {
|
||||
label: "json/application-json",
|
||||
uri: "crank://adapter/payload",
|
||||
kind: ResourceKind::Json,
|
||||
mime: "application/json",
|
||||
bytes: JSON_DOCUMENT,
|
||||
},
|
||||
];
|
||||
|
||||
for (label, mime, bytes) in [
|
||||
(
|
||||
"binary/octet-stream",
|
||||
"application/octet-stream",
|
||||
BINARY_UTF8_MARKUP,
|
||||
),
|
||||
("binary/image-png", "image/png", BINARY_BYTES),
|
||||
("binary/image-jpeg", "image/jpeg", BINARY_BYTES),
|
||||
("binary/image-gif", "image/gif", BINARY_BYTES),
|
||||
("binary/image-webp", "image/webp", BINARY_BYTES),
|
||||
("binary/image-svg", "image/svg+xml", BINARY_UTF8_MARKUP),
|
||||
("binary/text-html", "text/html", BINARY_UTF8_MARKUP),
|
||||
("binary/application-pdf", "application/pdf", BINARY_BYTES),
|
||||
] {
|
||||
cases.push(Case {
|
||||
label,
|
||||
uri: "crank://adapter/asset",
|
||||
kind: ResourceKind::Binary,
|
||||
mime,
|
||||
bytes,
|
||||
});
|
||||
}
|
||||
|
||||
cases
|
||||
}
|
||||
|
||||
fn assert_case(revision: &str, build: fn(&str, ResourceKind, &str, &[u8]) -> Value, case: &Case) {
|
||||
let label = format!("{revision}/{}", case.label);
|
||||
let contents = build(case.uri, case.kind, case.mime, case.bytes);
|
||||
|
||||
assert_eq!(
|
||||
contents["uri"],
|
||||
json!(case.uri),
|
||||
"{label}: uri must be preserved"
|
||||
);
|
||||
assert_eq!(
|
||||
contents["mimeType"],
|
||||
json!(case.mime),
|
||||
"{label}: adapter must report the declared MIME"
|
||||
);
|
||||
|
||||
match case.kind {
|
||||
ResourceKind::Binary => {
|
||||
assert!(
|
||||
contents.get("text").is_none(),
|
||||
"{label}: kind=binary must never carry a text branch, even for UTF-8-decodable bytes"
|
||||
);
|
||||
let blob = contents["blob"]
|
||||
.as_str()
|
||||
.unwrap_or_else(|| panic!("{label}: kind=binary must carry base64 `blob`"));
|
||||
assert_eq!(
|
||||
base64_decode(blob),
|
||||
case.bytes,
|
||||
"{label}: base64 must decode to the exact stored bytes"
|
||||
);
|
||||
}
|
||||
ResourceKind::Text | ResourceKind::Json => {
|
||||
assert!(
|
||||
contents.get("blob").is_none(),
|
||||
"{label}: text/JSON contents must not carry a blob branch"
|
||||
);
|
||||
assert_eq!(
|
||||
contents["text"],
|
||||
json!(std::str::from_utf8(case.bytes).expect("text/JSON fixtures must be UTF-8")),
|
||||
"{label}: text contents must be the exact stored bytes"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at06_negotiated_binary_adapter_both_revisions() {
|
||||
for case in cases() {
|
||||
assert_case("2026-07-28", resource_contents_2026_07_28, &case);
|
||||
assert_case("2025-11-25", resource_contents_2025_11_25, &case);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at06_unknown_or_unsupported_mime_is_a_safe_finding() {
|
||||
let finding = super::resource_mime_finding("application/zip");
|
||||
assert_eq!(finding.code(), "resource_mime_not_allowed");
|
||||
// finding не содержит bytes содержимого
|
||||
let serialized = serde_json::to_string(&finding).expect("finding must serialize");
|
||||
assert!(!serialized.contains("blob"));
|
||||
assert!(!serialized.contains("text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story38_resources_capability_is_registered_and_advertised() {
|
||||
// D-17 regression successor: 3.6 deliberately registered no Resources while the handler did not
|
||||
// exist; Story 3.8 implements `resources/list` + `resources/read`, so advertisement and dispatch
|
||||
// now carry the capability for both supported revisions.
|
||||
let capability_names: Vec<String> = CAPABILITY_DESCRIPTORS
|
||||
.iter()
|
||||
.map(|descriptor| format!("{:?}", descriptor.id).to_ascii_lowercase())
|
||||
.collect();
|
||||
assert!(
|
||||
capability_names
|
||||
.iter()
|
||||
.any(|name| name.contains("resource")),
|
||||
"CAPABILITY_DESCRIPTORS must carry the implemented Resources capability: {capability_names:?}"
|
||||
);
|
||||
let advertised_keys: Vec<String> = CAPABILITY_DESCRIPTORS
|
||||
.iter()
|
||||
.filter_map(|descriptor| descriptor.advertised.map(|(key, _)| key.to_owned()))
|
||||
.collect();
|
||||
assert!(
|
||||
advertised_keys.iter().any(|key| key == "resources"),
|
||||
"the implemented Resources capability must be advertised: {advertised_keys:?}"
|
||||
);
|
||||
let method_names: Vec<String> = METHOD_DESCRIPTORS
|
||||
.iter()
|
||||
.map(|descriptor| descriptor.name.to_owned())
|
||||
.collect();
|
||||
for method in ["resources/list", "resources/read"] {
|
||||
assert!(
|
||||
method_names.iter().any(|name| name == method),
|
||||
"{method} must be registered now that it is served: {method_names:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Независимый декодер: ожидание не берётся из адаптера.
|
||||
fn base64_decode(encoded: &str) -> Vec<u8> {
|
||||
use base64::Engine as _;
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode(encoded)
|
||||
.expect("adapter must emit standard base64")
|
||||
}
|
||||
@@ -1,24 +1,20 @@
|
||||
use std::{collections::BTreeSet, sync::Arc};
|
||||
//! Domain of the shared `search_tools` command (Story 3.1, decision D-4).
|
||||
//!
|
||||
//! The wire-level shared entry that used to live in this file (`handle_catalog_tool_call`, carrying
|
||||
//! the request envelope, the response mode, the protocol revision and an `axum::Response`) is
|
||||
//! replaced by `protocol::command::handle_tools_command`: the neutral Tools boundary owns the
|
||||
//! command, while the catalog-search domain stays here and never sees the wire. The reserved
|
||||
//! `_crank_confirmation_token` handling, the proxy-revision check and the approval policy moved with
|
||||
//! the command, not with the domain.
|
||||
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use crank_core::{CorrelationContext, ToolAccessMode, search_tool_catalog};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crank_core::search_tool_catalog;
|
||||
use crank_registry::PublishedAgentCatalog;
|
||||
use crank_trace::{ErrorCategory, Stage, StageOutcome};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
app::{
|
||||
AppState, handle_tool_call, resolve_generated_tool, take_confirmation_token,
|
||||
tool_error_response,
|
||||
},
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{jsonrpc_error, jsonrpc_result, request_id},
|
||||
manifest::{CALL_TOOL_NAME, SEARCH_TOOLS_NAME, searchable_tools},
|
||||
session::SessionState,
|
||||
tool_error::{McpControlError, control_tool_error_contract, execution_locale},
|
||||
transport::{ResponseMode, transport_response},
|
||||
};
|
||||
use crate::manifest::searchable_tools;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SearchToolsArguments {
|
||||
@@ -28,161 +24,18 @@ struct SearchToolsArguments {
|
||||
max_results: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ProxyToolCallArguments {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
arguments: Value,
|
||||
catalog_revision: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn handle_catalog_tool_call(
|
||||
state: Arc<AppState>,
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
credential: &VerifiedMachineCredential,
|
||||
catalog: &PublishedAgentCatalog,
|
||||
tool_name: &str,
|
||||
arguments: Value,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> Response {
|
||||
let transport_request_id = transport_correlation.request_id().as_str();
|
||||
match catalog.tool_selection_policy.mode {
|
||||
ToolAccessMode::Direct => {
|
||||
execute_catalog_tool(
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
credential,
|
||||
catalog,
|
||||
tool_name,
|
||||
arguments,
|
||||
transport_correlation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ToolAccessMode::Search if tool_name == SEARCH_TOOLS_NAME => {
|
||||
handle_search_tools(message, response_mode, session, catalog, arguments)
|
||||
}
|
||||
ToolAccessMode::Search if tool_name == CALL_TOOL_NAME => {
|
||||
let proxy: ProxyToolCallArguments = match serde_json::from_value(arguments) {
|
||||
Ok(proxy) => proxy,
|
||||
Err(error) => {
|
||||
return invalid_arguments_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
error.to_string(),
|
||||
);
|
||||
}
|
||||
};
|
||||
if proxy.catalog_revision != catalog_revision(catalog) {
|
||||
return tool_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
control_tool_error_contract(
|
||||
McpControlError::CatalogRevisionChanged,
|
||||
transport_request_id,
|
||||
transport_correlation.trace_id().as_str(),
|
||||
execution_locale(message),
|
||||
),
|
||||
);
|
||||
}
|
||||
execute_catalog_tool(
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
credential,
|
||||
catalog,
|
||||
&proxy.name,
|
||||
proxy.arguments,
|
||||
transport_correlation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ToolAccessMode::Search => {
|
||||
tool_not_found_response(message, response_mode, &session.protocol_version, tool_name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn execute_catalog_tool(
|
||||
state: Arc<AppState>,
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
credential: &VerifiedMachineCredential,
|
||||
catalog: &PublishedAgentCatalog,
|
||||
tool_name: &str,
|
||||
mut arguments: Value,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> Response {
|
||||
let resolve_span = Stage::McpToolsResolve.span();
|
||||
let resolved = resolve_span.in_scope(|| resolve_generated_tool(&catalog.tools, tool_name));
|
||||
let resolved = match resolved {
|
||||
Some(resolved) => {
|
||||
StageOutcome::Success.record(&resolve_span);
|
||||
drop(resolve_span);
|
||||
resolved
|
||||
}
|
||||
None => {
|
||||
StageOutcome::Error.record(&resolve_span);
|
||||
ErrorCategory::Catalog.record(&resolve_span);
|
||||
drop(resolve_span);
|
||||
return tool_not_found_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
tool_name,
|
||||
);
|
||||
}
|
||||
};
|
||||
let confirmation_token = take_confirmation_token(&mut arguments);
|
||||
handle_tool_call(
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
credential,
|
||||
resolved,
|
||||
arguments,
|
||||
confirmation_token,
|
||||
transport_correlation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn handle_search_tools(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
session: &SessionState,
|
||||
/// The domain result of the catalog search tool, without any wire wrapping.
|
||||
///
|
||||
/// The error is the invalid-params detail the adapter answers with; a domain failure never carries a
|
||||
/// response shape of its own.
|
||||
pub(crate) fn search_tools_outcome(
|
||||
catalog: &PublishedAgentCatalog,
|
||||
arguments: Value,
|
||||
) -> Response {
|
||||
let search: SearchToolsArguments = match serde_json::from_value(arguments) {
|
||||
Ok(search) => search,
|
||||
Err(error) => {
|
||||
return invalid_arguments_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
error.to_string(),
|
||||
);
|
||||
}
|
||||
};
|
||||
) -> Result<Value, String> {
|
||||
let search: SearchToolsArguments =
|
||||
serde_json::from_value(arguments).map_err(|error| error.to_string())?;
|
||||
if search.query.trim().is_empty() {
|
||||
return invalid_arguments_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
"query must not be empty".to_owned(),
|
||||
);
|
||||
return Err("query must not be empty".to_owned());
|
||||
}
|
||||
let known_group_ids = catalog
|
||||
.tool_selection_policy
|
||||
@@ -195,12 +48,7 @@ fn handle_search_tools(
|
||||
.iter()
|
||||
.find(|group_id| !known_group_ids.contains(group_id.as_str()))
|
||||
{
|
||||
return invalid_arguments_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
format!("unknown tool group {group_id}"),
|
||||
);
|
||||
return Err(format!("unknown tool group {group_id}"));
|
||||
}
|
||||
|
||||
let configured_limit = catalog.tool_selection_policy.search.max_results;
|
||||
@@ -223,62 +71,9 @@ fn handle_search_tools(
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let result = json!({
|
||||
"catalog_revision": catalog_revision(catalog),
|
||||
|
||||
Ok(json!({
|
||||
"catalog_revision": catalog.catalog_revision,
|
||||
"tools": tools,
|
||||
});
|
||||
let text = serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string());
|
||||
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({
|
||||
"content": [{"type": "text", "text": text}],
|
||||
"structuredContent": result,
|
||||
"isError": false
|
||||
}),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
fn catalog_revision(catalog: &PublishedAgentCatalog) -> String {
|
||||
catalog.catalog_revision.clone()
|
||||
}
|
||||
|
||||
fn invalid_arguments_response(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
protocol_version: &str,
|
||||
detail: String,
|
||||
) -> Response {
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
fn tool_not_found_response(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
protocol_version: &str,
|
||||
tool_name: &str,
|
||||
) -> Response {
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
format!("tool {tool_name} was not found"),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
)
|
||||
}))
|
||||
}
|
||||
@@ -16,9 +16,7 @@ use futures_util::stream;
|
||||
use reqwest::Url;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::jsonrpc::{
|
||||
CURRENT_PROTOCOL_VERSION, DEFAULT_PROTOCOL_VERSION, negotiated_protocol_version,
|
||||
};
|
||||
use crate::jsonrpc::{LEGACY_PROTOCOL_VERSION, negotiated_protocol_version};
|
||||
|
||||
pub(super) const HEADER_MCP_SESSION_ID: &str = "MCP-Session-Id";
|
||||
pub(super) const HEADER_MCP_PROTOCOL_VERSION: &str = "MCP-Protocol-Version";
|
||||
@@ -99,13 +97,42 @@ pub(super) fn validate_origin(
|
||||
Err(StatusCode::FORBIDDEN)
|
||||
}
|
||||
|
||||
/// The media types of the `Accept` header, in the client's preference order.
|
||||
///
|
||||
/// `None` means the header is absent or not text; both are the caller's own admission decision.
|
||||
fn accepted_media_types(headers: &HeaderMap) -> Option<Vec<String>> {
|
||||
let accept = headers.get(ACCEPT)?.to_str().ok()?;
|
||||
Some(
|
||||
accept
|
||||
.split(',')
|
||||
.map(|part| {
|
||||
part.split(';')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase()
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether this request offered `text/event-stream`.
|
||||
///
|
||||
/// Story 3.18: the SSE response stream is the only carrier of a server `notifications/message`, so
|
||||
/// the logging projection asks this before it promises a notification. It is the same admission rule
|
||||
/// the response-mode negotiation already applies, not a second interpretation of the header.
|
||||
pub(super) fn accepts_event_stream(headers: &HeaderMap) -> bool {
|
||||
accepted_media_types(headers).is_some_and(|media_types| {
|
||||
media_types
|
||||
.iter()
|
||||
.any(|media_type| media_type == "text/event-stream")
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn negotiate_post_response_mode(
|
||||
headers: &HeaderMap,
|
||||
) -> Result<ResponseMode, StatusCode> {
|
||||
let Some(accept) = headers.get(ACCEPT) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
let Ok(accept) = accept.to_str() else {
|
||||
let Some(media_types) = accepted_media_types(headers) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
@@ -113,14 +140,7 @@ pub(super) fn negotiate_post_response_mode(
|
||||
let mut saw_sse = false;
|
||||
let mut preferred = None;
|
||||
|
||||
for part in accept.split(',') {
|
||||
let media_type = part
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase();
|
||||
|
||||
for media_type in media_types {
|
||||
match media_type.as_str() {
|
||||
"application/json" => {
|
||||
saw_json = true;
|
||||
@@ -146,22 +166,12 @@ pub(super) fn negotiate_post_response_mode(
|
||||
}
|
||||
|
||||
pub(super) fn validate_get_accept_header(headers: &HeaderMap) -> Result<(), StatusCode> {
|
||||
let Some(accept) = headers.get(ACCEPT) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
let Ok(accept) = accept.to_str() else {
|
||||
let Some(media_types) = accepted_media_types(headers) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
if accept
|
||||
.split(',')
|
||||
.map(|part| {
|
||||
part.split(';')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase()
|
||||
})
|
||||
if media_types
|
||||
.iter()
|
||||
.any(|media_type| media_type == "text/event-stream")
|
||||
{
|
||||
return Ok(());
|
||||
@@ -170,31 +180,50 @@ pub(super) fn validate_get_accept_header(headers: &HeaderMap) -> Result<(), Stat
|
||||
Err(StatusCode::NOT_ACCEPTABLE)
|
||||
}
|
||||
|
||||
pub(super) fn protocol_version_from_headers(headers: &HeaderMap) -> Result<String, StatusCode> {
|
||||
let Some(version) = headers.get(HEADER_MCP_PROTOCOL_VERSION) else {
|
||||
return Ok(DEFAULT_PROTOCOL_VERSION.to_owned());
|
||||
/// Read a singleton identity carrier.
|
||||
///
|
||||
/// Pinned HTTP semantics allow repeated header lines, so the ingress must decide what a repeated
|
||||
/// carrier means instead of silently reading the first value. Identical duplicates carry no ambiguity
|
||||
/// and collapse deterministically to one value; conflicting duplicates are an ambiguous identity and
|
||||
/// are rejected. A non-text value is rejected as well.
|
||||
pub(super) fn singleton_header<'a>(
|
||||
headers: &'a HeaderMap,
|
||||
name: &str,
|
||||
) -> Result<Option<&'a str>, StatusCode> {
|
||||
let mut values = headers.get_all(name).iter();
|
||||
let Some(first) = values.next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Ok(version) = version.to_str() else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
if negotiated_protocol_version(version).is_some() {
|
||||
return Ok(version.to_owned());
|
||||
let first = first.to_str().map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
for value in values {
|
||||
let value = value.to_str().map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if value != first {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
Err(StatusCode::BAD_REQUEST)
|
||||
Ok(Some(first))
|
||||
}
|
||||
|
||||
/// Negotiated revision carried by the request header.
|
||||
///
|
||||
/// A missing header is reported as `None` rather than being replaced by an implicit default: the
|
||||
/// withdrawn `2025-03-26` fallback is no longer served. Era resolution (header vs body identity,
|
||||
/// mismatch and unsupported handling) happens in the request pipeline. Conflicting duplicate
|
||||
/// carriers are rejected here, so no caller can resolve an ambiguous identity to the first value.
|
||||
pub(super) fn protocol_version_from_headers(
|
||||
headers: &HeaderMap,
|
||||
) -> Result<Option<String>, StatusCode> {
|
||||
Ok(singleton_header(headers, HEADER_MCP_PROTOCOL_VERSION)?.map(str::to_owned))
|
||||
}
|
||||
|
||||
pub(super) fn validate_session_protocol_version(
|
||||
headers: &HeaderMap,
|
||||
negotiated_session_version: &str,
|
||||
) -> Result<(), StatusCode> {
|
||||
let Some(version) = headers.get(HEADER_MCP_PROTOCOL_VERSION) else {
|
||||
let Some(version) = singleton_header(headers, HEADER_MCP_PROTOCOL_VERSION)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let Ok(version) = version.to_str() else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
if negotiated_protocol_version(version).is_none() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
@@ -208,14 +237,7 @@ pub(super) fn validate_session_protocol_version(
|
||||
}
|
||||
|
||||
pub(super) fn session_id_from_headers(headers: &HeaderMap) -> Result<Option<String>, StatusCode> {
|
||||
let Some(session_id) = headers.get(HEADER_MCP_SESSION_ID) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Ok(session_id) = session_id.to_str() else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
Ok(Some(session_id.to_owned()))
|
||||
Ok(singleton_header(headers, HEADER_MCP_SESSION_ID)?.map(str::to_owned))
|
||||
}
|
||||
|
||||
pub(super) fn json_response(
|
||||
@@ -242,7 +264,7 @@ pub(super) fn json_response(
|
||||
response.headers_mut().insert(
|
||||
HEADER_MCP_PROTOCOL_VERSION,
|
||||
HeaderValue::from_str(protocol_version)
|
||||
.unwrap_or_else(|_| HeaderValue::from_static(CURRENT_PROTOCOL_VERSION)),
|
||||
.unwrap_or_else(|_| HeaderValue::from_static(LEGACY_PROTOCOL_VERSION)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -257,9 +279,26 @@ pub(super) fn transport_response(
|
||||
protocol_version: Option<&str>,
|
||||
) -> Response {
|
||||
let outcome = payload_outcome(&payload);
|
||||
// Story 3.18: this is the single projection point of the adapter's own safe structured event.
|
||||
// The severity is derived from the already-decided outcome of the payload, so no request payload,
|
||||
// credential, error cause or user value is read here.
|
||||
note_logging_outcome(&payload);
|
||||
let notifications = crate::protocol::take_notifications();
|
||||
// A pending `notifications/message` has no carrier in a JSON body. When the client offered both
|
||||
// media types and opted in to logging, the negotiated mode is the SSE stream, so the notification
|
||||
// precedes the response instead of being silently dropped.
|
||||
let response_mode = if notifications.is_empty() {
|
||||
response_mode
|
||||
} else {
|
||||
ResponseMode::Sse
|
||||
};
|
||||
if status == StatusCode::OK && matches!(response_mode, ResponseMode::Sse) {
|
||||
let payload = payload.to_string();
|
||||
let stream = stream::once(async move { Ok(Event::default().data(payload)) });
|
||||
let mut messages = Vec::with_capacity(notifications.len() + 1);
|
||||
for notification in notifications {
|
||||
messages.push(Ok(Event::default().data(notification.to_string())));
|
||||
}
|
||||
messages.push(Ok(Event::default().data(payload.to_string())));
|
||||
let stream = stream::iter(messages);
|
||||
|
||||
let mut response = sse_response(status, stream, session_id, protocol_version);
|
||||
if let Some(outcome) = outcome {
|
||||
@@ -271,6 +310,30 @@ pub(super) fn transport_response(
|
||||
json_response(status, payload, session_id, protocol_version)
|
||||
}
|
||||
|
||||
/// Record the closed safe event of one response: served, rejected as invalid, failed, or a tool-level
|
||||
/// error. Every label is a fixed string of the closed vocabulary; nothing from the payload or the
|
||||
/// request is copied into it.
|
||||
fn note_logging_outcome(payload: &Value) {
|
||||
use crate::protocol::{EVENT_FAILED, EVENT_REJECTED, EVENT_SERVED, LogLevel, note};
|
||||
if payload.get("error").is_some() {
|
||||
match payload.pointer("/error/code").and_then(Value::as_i64) {
|
||||
// The pinned client-error codes of a malformed request.
|
||||
Some(-32600 | -32602) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"),
|
||||
_ => note(LogLevel::Error, EVENT_FAILED, "internal"),
|
||||
}
|
||||
return;
|
||||
}
|
||||
if payload
|
||||
.pointer("/result/isError")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
note(LogLevel::Warning, EVENT_REJECTED, "tool_error");
|
||||
return;
|
||||
}
|
||||
note(LogLevel::Info, EVENT_SERVED, "ok");
|
||||
}
|
||||
|
||||
fn payload_outcome(payload: &Value) -> Option<McpOutcome> {
|
||||
if payload.get("error").is_some() {
|
||||
return Some(McpOutcome::JsonRpcError);
|
||||
@@ -319,7 +382,7 @@ where
|
||||
response.headers_mut().insert(
|
||||
HEADER_MCP_PROTOCOL_VERSION,
|
||||
HeaderValue::from_str(protocol_version)
|
||||
.unwrap_or_else(|_| HeaderValue::from_static(CURRENT_PROTOCOL_VERSION)),
|
||||
.unwrap_or_else(|_| HeaderValue::from_static(LEGACY_PROTOCOL_VERSION)),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,11 @@ use time::OffsetDateTime;
|
||||
|
||||
#[tokio::test]
|
||||
async fn active_session_sampler_tracks_create_delete_and_expiry() {
|
||||
// Story 3.6: сессии пишут через gated-фасад crank-metrics, поэтому
|
||||
// закрытая process identity фиксируется до установки recorder'а.
|
||||
crank_metrics::bind_metric_service(crank_metrics::MetricService::McpServer)
|
||||
.expect("explicit MCP service binding before the recorder");
|
||||
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
recorder
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#[path = "unit/errors.rs"]
|
||||
mod errors;
|
||||
#[path = "unit/manifest.rs"]
|
||||
mod manifest;
|
||||
#[path = "unit/session.rs"]
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! Story 3.1 acceptance tests (red phase): negotiated MCP revisions at the unit level.
|
||||
//!
|
||||
//! Oracle: the owner-approved 2026-10-11 window (two revisions `2026-07-28` + `2025-11-25`, withdrawn
|
||||
//! `2025-06-18`/`2025-03-26`) as frozen in `tests/fixtures/mcp-revisions/supported-revisions.json`.
|
||||
//!
|
||||
//! Scope note (TL finding 6): the constant-set assertion below is a **unit support-list** check on the
|
||||
//! negotiation function. Endpoint advertisement and the "no identity is never served as a withdrawn
|
||||
//! revision" behaviour are asserted at HTTP level in
|
||||
//! `apps/mcp-server/tests/integration/revision_matrix.rs`; this file deliberately does not assert an
|
||||
//! internal default constant, because that would codify an implementation detail rather than serving
|
||||
//! behaviour.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crank_community_mcp::jsonrpc::{SUPPORTED_PROTOCOL_VERSIONS, negotiated_protocol_version};
|
||||
use crank_community_mcp::session::{InMemorySessionStore, TransportSessionStore};
|
||||
use serde_json::Value;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
|
||||
const MODERN_REVISION: &str = "2026-07-28";
|
||||
const LEGACY_REVISION: &str = "2025-11-25";
|
||||
const WITHDRAWN_REVISIONS: [&str; 2] = ["2025-06-18", "2025-03-26"];
|
||||
|
||||
fn window_oracle() -> Value {
|
||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../tests/fixtures/mcp-revisions/supported-revisions.json");
|
||||
let raw = std::fs::read_to_string(&path).unwrap_or_else(|error| {
|
||||
panic!(
|
||||
"approved-window oracle must be readable at {}: {error}",
|
||||
path.display()
|
||||
)
|
||||
});
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
|
||||
fn approved_revisions() -> Vec<String> {
|
||||
window_oracle()["revisions"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|entry| entry["revision"].as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn timestamp(value: &str) -> time::OffsetDateTime {
|
||||
time::OffsetDateTime::parse(value, &Rfc3339).unwrap()
|
||||
}
|
||||
|
||||
/// AT-3.1-01 (unit support list): exactly the two approved revisions are negotiable.
|
||||
#[test]
|
||||
fn at_3_1_01_unit_support_list_covers_exactly_the_approved_window() {
|
||||
let mut advertised: Vec<String> = SUPPORTED_PROTOCOL_VERSIONS
|
||||
.iter()
|
||||
.map(|version| (*version).to_owned())
|
||||
.collect();
|
||||
advertised.sort();
|
||||
|
||||
let mut expected = approved_revisions();
|
||||
expected.sort();
|
||||
|
||||
assert_eq!(
|
||||
advertised, expected,
|
||||
"the negotiable revision set must be exactly the approved window"
|
||||
);
|
||||
}
|
||||
|
||||
fn withdrawn_revisions() -> Vec<String> {
|
||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../tests/fixtures/mcp-revisions/withdrawn-revisions.json");
|
||||
let raw = std::fs::read_to_string(&path).unwrap_or_else(|error| {
|
||||
panic!(
|
||||
"withdrawn-revision oracle must be readable at {}: {error}",
|
||||
path.display()
|
||||
)
|
||||
});
|
||||
let document: Value = serde_json::from_str(&raw).unwrap();
|
||||
|
||||
document["withdrawn"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|entry| entry["revision"].as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// AT-3.1-02: a withdrawn revision is no longer negotiable (negative input).
|
||||
#[test]
|
||||
fn at_3_1_02_withdrawn_revisions_are_not_negotiable() {
|
||||
let withdrawn = withdrawn_revisions();
|
||||
|
||||
assert_eq!(withdrawn, WITHDRAWN_REVISIONS.to_vec());
|
||||
|
||||
for revision in &withdrawn {
|
||||
assert!(
|
||||
negotiated_protocol_version(revision).is_none(),
|
||||
"{revision} is withdrawn and must not negotiate"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// AT-3.1-04 / AT-3.1-05: both approved revisions negotiate.
|
||||
#[test]
|
||||
fn at_3_1_04_modern_and_legacy_revisions_negotiate() {
|
||||
assert_eq!(
|
||||
negotiated_protocol_version(MODERN_REVISION),
|
||||
Some(MODERN_REVISION),
|
||||
"the modern stateless revision must be negotiable"
|
||||
);
|
||||
assert_eq!(
|
||||
negotiated_protocol_version(LEGACY_REVISION),
|
||||
Some(LEGACY_REVISION),
|
||||
"the legacy session revision must stay negotiable"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.1-06: unsupported or malformed identity never becomes a negotiated era.
|
||||
#[test]
|
||||
fn at_3_1_06_unknown_or_malformed_identity_stays_unnegotiated() {
|
||||
for candidate in [
|
||||
"1999-01-01",
|
||||
"2026-13-01",
|
||||
"",
|
||||
"2026-07-28 ",
|
||||
"not-a-version",
|
||||
] {
|
||||
assert!(
|
||||
negotiated_protocol_version(candidate).is_none(),
|
||||
"{candidate:?} must not negotiate a protocol era"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// AT-3.1-05: an existing legacy session keeps its negotiated revision and initialization state.
|
||||
#[tokio::test]
|
||||
async fn at_3_1_05_legacy_session_keeps_its_negotiated_revision() {
|
||||
let store = InMemorySessionStore::default();
|
||||
let created_at = timestamp("2026-10-11T09:00:00Z");
|
||||
|
||||
let session_id = store
|
||||
.create(LEGACY_REVISION, "default", "sales", false, created_at, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let session = store.get(&session_id).await.unwrap().unwrap();
|
||||
|
||||
assert_eq!(session.protocol_version, LEGACY_REVISION);
|
||||
assert_eq!(session.workspace_slug, "default");
|
||||
assert_eq!(session.agent_slug, "sales");
|
||||
assert!(!session.initialized);
|
||||
}
|
||||
@@ -208,6 +208,8 @@ fn agent_catalog_discovery_profile_handles_200_agents_2000_operations_under_budg
|
||||
..Default::default()
|
||||
},
|
||||
tools,
|
||||
resources: Vec::new(),
|
||||
prompts: Vec::new(),
|
||||
};
|
||||
|
||||
let catalog_started = Instant::now();
|
||||
|
||||
@@ -124,6 +124,7 @@ impl fmt::Debug for McpProcessConfig {
|
||||
.field("database", &self.database)
|
||||
.field("runtime", &self.runtime)
|
||||
.field("observability", &self.observability)
|
||||
.field("storage_root", &"configured")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,6 +153,8 @@ pub struct McpProcessConfig {
|
||||
pub bind_addr: SocketAddr,
|
||||
pub refresh_ms: u64,
|
||||
pub rate_limit: RateLimitSettings,
|
||||
/// Root of the immutable artifact store this process reads published Resources from.
|
||||
pub storage_root: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -833,6 +835,7 @@ pub fn parse_process(
|
||||
requests_per_second: rps,
|
||||
burst,
|
||||
},
|
||||
storage_root: parser.absolute_path("CRANK_STORAGE_ROOT", "/var/lib/crank/storage"),
|
||||
}))
|
||||
}
|
||||
};
|
||||
@@ -906,6 +909,7 @@ fn fingerprint_parts(kind: ProcessKind, projection: &Projection) -> Vec<String>
|
||||
"rate={}:{}",
|
||||
config.rate_limit.requests_per_second, config.rate_limit.burst
|
||||
),
|
||||
"storage=path-configured".to_owned(),
|
||||
],
|
||||
),
|
||||
};
|
||||
|
||||
@@ -635,7 +635,7 @@ static FIELDS: [FieldSpec; 65] = [
|
||||
f!(
|
||||
"admin.storage_root",
|
||||
"CRANK_STORAGE_ROOT",
|
||||
AdminApi,
|
||||
Shared,
|
||||
"absolute_path",
|
||||
None,
|
||||
Some("/var/lib/crank/storage"),
|
||||
|
||||
@@ -58,6 +58,8 @@ define_id!(InvocationLogId);
|
||||
define_id!(ProductEventId);
|
||||
define_id!(AuditEventId);
|
||||
define_id!(SecretId);
|
||||
define_id!(ResourceId);
|
||||
define_id!(PromptId);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
@@ -12,7 +12,10 @@ pub mod observability;
|
||||
pub mod onboarding;
|
||||
pub mod operation;
|
||||
pub mod product_event;
|
||||
pub mod prompt;
|
||||
pub mod prompt_composition;
|
||||
pub mod protocol;
|
||||
pub mod resource;
|
||||
pub mod secret;
|
||||
pub mod tool_catalog;
|
||||
pub mod tool_quality;
|
||||
@@ -47,8 +50,8 @@ pub mod domain {
|
||||
};
|
||||
pub use crate::ids::{
|
||||
AgentId, ApprovalRequestId, AuditEventId, AuthProfileId, DescriptorId, InvitationId,
|
||||
InvocationLogId, OperationId, PlatformApiKeyId, ProductEventId, SampleId, SecretId, ToolId,
|
||||
UserId, UserSessionId, WorkspaceId,
|
||||
InvocationLogId, OperationId, PlatformApiKeyId, ProductEventId, ResourceId, SampleId,
|
||||
SecretId, ToolId, UserId, UserSessionId, WorkspaceId,
|
||||
};
|
||||
pub use crate::observability::{
|
||||
INVOCATION_PREVIEW_MAX_BYTES, InvocationLevel, InvocationLog, InvocationSource,
|
||||
|
||||
@@ -0,0 +1,621 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
const MAX_ARGUMENTS: usize = 32;
|
||||
const MAX_MESSAGES: usize = 64;
|
||||
const MAX_PROMPT_DEPENDENCIES: usize = 16;
|
||||
/// Upper bound of one argument value / rendered message content. Public because the MCP
|
||||
/// `prompts/get` boundary reports an oversized argument separately from a type mismatch
|
||||
/// (AT-3.14-02) while the renderer below stays the single validator.
|
||||
pub const MAX_TEXT_BYTES: usize = 16_384;
|
||||
/// Storage guard for `prompt_arguments.default_value`/`enumeration` (jsonb):
|
||||
/// PostgreSQL keeps `octet_length(default_value::text) <= 16384`.
|
||||
const MAX_JSON_TEXT_BYTES: usize = 16_384;
|
||||
|
||||
use crate::ids::PromptId;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PromptStatus {
|
||||
Draft,
|
||||
Published,
|
||||
Archived,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PromptSensitivity {
|
||||
Public,
|
||||
Internal,
|
||||
Secret,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PromptDraft {
|
||||
prompt_id: PromptId,
|
||||
version: u32,
|
||||
status: PromptStatus,
|
||||
sensitivity: PromptSensitivity,
|
||||
definition: PromptDefinition,
|
||||
}
|
||||
|
||||
/// Immutable value snapshot; its fields are private and there are no mutation APIs.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PublishedPromptVersion {
|
||||
prompt_id: PromptId,
|
||||
version: u32,
|
||||
sensitivity: PromptSensitivity,
|
||||
definition: PromptDefinition,
|
||||
}
|
||||
|
||||
impl PromptDraft {
|
||||
pub fn new(
|
||||
prompt_id: PromptId,
|
||||
sensitivity: PromptSensitivity,
|
||||
definition: PromptDefinition,
|
||||
) -> Self {
|
||||
Self {
|
||||
prompt_id,
|
||||
version: 1,
|
||||
status: PromptStatus::Draft,
|
||||
sensitivity,
|
||||
definition,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_parts(
|
||||
prompt_id: PromptId,
|
||||
version: u32,
|
||||
status: PromptStatus,
|
||||
sensitivity: PromptSensitivity,
|
||||
definition: PromptDefinition,
|
||||
) -> Result<Self, PromptError> {
|
||||
if version == 0 {
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
Ok(Self {
|
||||
prompt_id,
|
||||
version,
|
||||
status,
|
||||
sensitivity,
|
||||
definition,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn prompt_id(&self) -> &PromptId {
|
||||
&self.prompt_id
|
||||
}
|
||||
|
||||
pub fn version(&self) -> u32 {
|
||||
self.version
|
||||
}
|
||||
|
||||
pub fn status(&self) -> PromptStatus {
|
||||
self.status
|
||||
}
|
||||
|
||||
pub fn sensitivity(&self) -> PromptSensitivity {
|
||||
self.sensitivity
|
||||
}
|
||||
|
||||
pub fn definition(&self) -> &PromptDefinition {
|
||||
&self.definition
|
||||
}
|
||||
|
||||
pub fn published_snapshot(&self) -> PublishedPromptVersion {
|
||||
PublishedPromptVersion {
|
||||
prompt_id: self.prompt_id.clone(),
|
||||
version: self.version,
|
||||
sensitivity: self.sensitivity,
|
||||
definition: self.definition.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PublishedPromptVersion {
|
||||
pub fn prompt_id(&self) -> &PromptId {
|
||||
&self.prompt_id
|
||||
}
|
||||
|
||||
pub fn version(&self) -> u32 {
|
||||
self.version
|
||||
}
|
||||
|
||||
pub fn sensitivity(&self) -> PromptSensitivity {
|
||||
self.sensitivity
|
||||
}
|
||||
|
||||
pub fn definition(&self) -> &PromptDefinition {
|
||||
&self.definition
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct PromptDefinition {
|
||||
name: String,
|
||||
description: String,
|
||||
arguments: Vec<PromptArgument>,
|
||||
messages: Vec<PromptMessage>,
|
||||
dependencies: Vec<PromptDependency>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct PromptDependency {
|
||||
pub resource_id: String,
|
||||
pub version: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct PromptArgument {
|
||||
name: String,
|
||||
kind: ArgumentKind,
|
||||
required: bool,
|
||||
default: Option<Value>,
|
||||
enumeration: Vec<Value>,
|
||||
}
|
||||
|
||||
impl PromptArgument {
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
pub fn kind(&self) -> ArgumentKind {
|
||||
self.kind
|
||||
}
|
||||
pub fn required(&self) -> bool {
|
||||
self.required
|
||||
}
|
||||
pub fn default(&self) -> Option<&Value> {
|
||||
self.default.as_ref()
|
||||
}
|
||||
pub fn enumeration(&self) -> &[Value] {
|
||||
&self.enumeration
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ArgumentKind {
|
||||
String,
|
||||
Number,
|
||||
Integer,
|
||||
Boolean,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct PromptMessage {
|
||||
pub role: PromptRole,
|
||||
pub content: String,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty", default)]
|
||||
pub resource_refs: Vec<usize>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PromptRole {
|
||||
System,
|
||||
User,
|
||||
Assistant,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum PromptError {
|
||||
InvalidDefinition,
|
||||
MissingArgument(String),
|
||||
UnknownArgument(String),
|
||||
InvalidArgument(String),
|
||||
InvalidTemplate,
|
||||
}
|
||||
|
||||
impl PromptDefinition {
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
pub fn description(&self) -> &str {
|
||||
&self.description
|
||||
}
|
||||
pub fn arguments(&self) -> &[PromptArgument] {
|
||||
&self.arguments
|
||||
}
|
||||
pub fn messages(&self) -> &[PromptMessage] {
|
||||
&self.messages
|
||||
}
|
||||
pub fn dependencies(&self) -> &[PromptDependency] {
|
||||
&self.dependencies
|
||||
}
|
||||
|
||||
pub fn as_json(&self) -> Value {
|
||||
let messages: Vec<Value> = self
|
||||
.messages
|
||||
.iter()
|
||||
.map(|message| {
|
||||
let mut m = serde_json::json!({
|
||||
"role": match message.role {
|
||||
PromptRole::System => "system",
|
||||
PromptRole::User => "user",
|
||||
PromptRole::Assistant => "assistant",
|
||||
},
|
||||
"content": message.content,
|
||||
});
|
||||
if !message.resource_refs.is_empty() {
|
||||
m["resource_refs"] = serde_json::json!(message.resource_refs);
|
||||
}
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
let mut out = serde_json::json!({
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
"arguments": self.arguments_json(),
|
||||
"messages": messages,
|
||||
});
|
||||
if !self.dependencies.is_empty() {
|
||||
let deps: Vec<Value> = self
|
||||
.dependencies
|
||||
.iter()
|
||||
.map(|d| serde_json::json!({"resource_id": d.resource_id, "version": d.version}))
|
||||
.collect();
|
||||
out["dependencies"] = Value::Array(deps);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Typed argument metadata of this definition: the single source of the MCP
|
||||
/// `prompts/list` argument shape (Story 3.14) and of the admin API shape.
|
||||
pub fn arguments_json(&self) -> Vec<Value> {
|
||||
self.arguments
|
||||
.iter()
|
||||
.map(|argument| {
|
||||
let mut schema = serde_json::Map::from_iter([(
|
||||
"type".to_owned(),
|
||||
Value::String(
|
||||
match argument.kind {
|
||||
ArgumentKind::String => "string",
|
||||
ArgumentKind::Number => "number",
|
||||
ArgumentKind::Integer => "integer",
|
||||
ArgumentKind::Boolean => "boolean",
|
||||
}
|
||||
.to_owned(),
|
||||
),
|
||||
)]);
|
||||
if !argument.enumeration.is_empty() {
|
||||
schema.insert(
|
||||
"enum".to_owned(),
|
||||
Value::Array(argument.enumeration.clone()),
|
||||
);
|
||||
}
|
||||
let mut item = serde_json::Map::from_iter([
|
||||
("name".to_owned(), Value::String(argument.name.clone())),
|
||||
("required".to_owned(), Value::Bool(argument.required)),
|
||||
("schema".to_owned(), Value::Object(schema)),
|
||||
]);
|
||||
if let Some(default) = &argument.default {
|
||||
item.insert("default".to_owned(), default.clone());
|
||||
}
|
||||
Value::Object(item)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn parse(value: &Value) -> Result<Self, PromptError> {
|
||||
let o = value.as_object().ok_or(PromptError::InvalidDefinition)?;
|
||||
if o.keys().any(|key| {
|
||||
!matches!(
|
||||
key.as_str(),
|
||||
"name" | "description" | "arguments" | "messages" | "dependencies"
|
||||
)
|
||||
}) {
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
let name = bounded_string(o.get("name"))?;
|
||||
let description = bounded_string(o.get("description"))?;
|
||||
let raw_args = o
|
||||
.get("arguments")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or(PromptError::InvalidDefinition)?;
|
||||
let raw_msgs = o
|
||||
.get("messages")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or(PromptError::InvalidDefinition)?;
|
||||
if raw_args.len() > MAX_ARGUMENTS || raw_msgs.is_empty() || raw_msgs.len() > MAX_MESSAGES {
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
// Parse exact pinned dependencies (resource_id + version).
|
||||
let dependencies = match o.get("dependencies") {
|
||||
None => Vec::new(),
|
||||
Some(Value::Array(arr)) => {
|
||||
if arr.len() > MAX_PROMPT_DEPENDENCIES {
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
let mut out = Vec::with_capacity(arr.len());
|
||||
let mut seen = BTreeSet::new();
|
||||
for item in arr {
|
||||
let obj = item.as_object().ok_or(PromptError::InvalidDefinition)?;
|
||||
if obj
|
||||
.keys()
|
||||
.any(|k| !matches!(k.as_str(), "resource_id" | "version"))
|
||||
{
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
let rid = bounded_string(obj.get("resource_id"))?;
|
||||
let ver = obj
|
||||
.get("version")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or(PromptError::InvalidDefinition)?;
|
||||
if ver == 0 || ver > u32::MAX as u64 {
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
let ver = ver as u32;
|
||||
if !seen.insert((rid.clone(), ver)) {
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
out.push(PromptDependency {
|
||||
resource_id: rid,
|
||||
version: ver,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
Some(_) => return Err(PromptError::InvalidDefinition),
|
||||
};
|
||||
let mut names = BTreeMap::new();
|
||||
let mut arguments = Vec::new();
|
||||
for raw in raw_args {
|
||||
let a = raw.as_object().ok_or(PromptError::InvalidDefinition)?;
|
||||
if a.keys()
|
||||
.any(|key| !matches!(key.as_str(), "name" | "schema" | "required" | "default"))
|
||||
{
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
let name = bounded_string(a.get("name"))?;
|
||||
let schema = a
|
||||
.get("schema")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or(PromptError::InvalidDefinition)?;
|
||||
let kind = match schema.get("type").and_then(Value::as_str) {
|
||||
Some("string") => ArgumentKind::String,
|
||||
Some("number") => ArgumentKind::Number,
|
||||
Some("integer") => ArgumentKind::Integer,
|
||||
Some("boolean") => ArgumentKind::Boolean,
|
||||
_ => return Err(PromptError::InvalidDefinition),
|
||||
};
|
||||
let required = a
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.ok_or(PromptError::InvalidDefinition)?;
|
||||
let default = a.get("default").cloned();
|
||||
if schema
|
||||
.keys()
|
||||
.any(|key| !matches!(key.as_str(), "type" | "enum"))
|
||||
{
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
let enumeration = match schema.get("enum") {
|
||||
Some(Value::Array(values)) => values.clone(),
|
||||
Some(_) => return Err(PromptError::InvalidDefinition),
|
||||
None => Vec::new(),
|
||||
};
|
||||
if enumeration.len() > 64
|
||||
|| (schema.contains_key("enum") && enumeration.is_empty())
|
||||
|| enumeration
|
||||
.iter()
|
||||
.any(|value| !valid(kind, value) || !bounded_json(value))
|
||||
|| (required && default.is_some())
|
||||
|| (default.as_ref().is_some_and(|v| {
|
||||
!valid(kind, v)
|
||||
|| !bounded_json(v)
|
||||
|| (!enumeration.is_empty() && !enumeration.contains(v))
|
||||
}))
|
||||
{
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
if names
|
||||
.insert(
|
||||
name.clone(),
|
||||
(kind, required, default.clone(), enumeration.clone()),
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
arguments.push(PromptArgument {
|
||||
name,
|
||||
kind,
|
||||
required,
|
||||
default,
|
||||
enumeration,
|
||||
});
|
||||
}
|
||||
let mut messages = Vec::new();
|
||||
for raw in raw_msgs {
|
||||
let m = raw.as_object().ok_or(PromptError::InvalidDefinition)?;
|
||||
if m.keys()
|
||||
.any(|key| !matches!(key.as_str(), "role" | "content" | "resource_refs"))
|
||||
{
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
let role = match m.get("role").and_then(Value::as_str) {
|
||||
Some("system") => PromptRole::System,
|
||||
Some("user") => PromptRole::User,
|
||||
Some("assistant") => PromptRole::Assistant,
|
||||
_ => return Err(PromptError::InvalidDefinition),
|
||||
};
|
||||
let content = bounded_string(m.get("content"))?;
|
||||
// resource_refs: non-empty unique indices into dependencies.
|
||||
let mut resource_refs: Vec<usize> = Vec::new();
|
||||
if let Some(raw_refs) = m.get("resource_refs") {
|
||||
let arr = raw_refs.as_array().ok_or(PromptError::InvalidDefinition)?;
|
||||
if arr.is_empty() {
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
for v in arr {
|
||||
let idx = v.as_u64().ok_or(PromptError::InvalidDefinition)? as usize;
|
||||
if idx >= dependencies.len() || !seen.insert(idx) {
|
||||
return Err(PromptError::InvalidDefinition);
|
||||
}
|
||||
resource_refs.push(idx);
|
||||
}
|
||||
}
|
||||
for (_, key) in placeholders(&content)? {
|
||||
if !names.contains_key(&key) {
|
||||
return Err(PromptError::InvalidTemplate);
|
||||
}
|
||||
}
|
||||
messages.push(PromptMessage {
|
||||
role,
|
||||
content,
|
||||
resource_refs,
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
name,
|
||||
description,
|
||||
arguments,
|
||||
messages,
|
||||
dependencies,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn preview(
|
||||
&self,
|
||||
supplied: &Map<String, Value>,
|
||||
) -> Result<Vec<PromptMessage>, PromptError> {
|
||||
let mut values = BTreeMap::<String, Value>::new();
|
||||
for key in supplied.keys() {
|
||||
if !self.arguments.iter().any(|a| &a.name == key) {
|
||||
return Err(PromptError::UnknownArgument(key.clone()));
|
||||
}
|
||||
}
|
||||
for arg in &self.arguments {
|
||||
let Some(value) = supplied.get(&arg.name).or(arg.default.as_ref()) else {
|
||||
if arg.required {
|
||||
return Err(PromptError::MissingArgument(arg.name.clone()));
|
||||
}
|
||||
values.insert(arg.name.clone(), Value::String(String::new()));
|
||||
continue;
|
||||
};
|
||||
if !valid(arg.kind, value)
|
||||
|| (!arg.enumeration.is_empty() && !arg.enumeration.contains(value))
|
||||
|| value
|
||||
.as_str()
|
||||
.is_some_and(|text| text.len() > MAX_TEXT_BYTES)
|
||||
{
|
||||
return Err(PromptError::InvalidArgument(arg.name.clone()));
|
||||
}
|
||||
values.insert(arg.name.clone(), value.clone());
|
||||
}
|
||||
let mut rendered = Vec::with_capacity(self.messages.len());
|
||||
let mut total_bytes = 0usize;
|
||||
for message in &self.messages {
|
||||
let mut content = String::new();
|
||||
let mut cursor = 0;
|
||||
for (start, key) in placeholders(&message.content)? {
|
||||
content.push_str(&message.content[cursor..start]);
|
||||
let end = start + key.len() + 4;
|
||||
let value = values
|
||||
.get(key.as_str())
|
||||
.ok_or(PromptError::InvalidTemplate)?;
|
||||
content.push_str(&scalar_text(value).ok_or(PromptError::InvalidTemplate)?);
|
||||
cursor = end;
|
||||
if content.len() > MAX_TEXT_BYTES {
|
||||
return Err(PromptError::InvalidTemplate);
|
||||
}
|
||||
}
|
||||
content.push_str(&message.content[cursor..]);
|
||||
total_bytes = total_bytes
|
||||
.checked_add(content.len())
|
||||
.filter(|size| *size <= MAX_TEXT_BYTES)
|
||||
.ok_or(PromptError::InvalidTemplate)?;
|
||||
rendered.push(PromptMessage {
|
||||
role: message.role,
|
||||
content,
|
||||
resource_refs: message.resource_refs.clone(),
|
||||
});
|
||||
}
|
||||
Ok(rendered)
|
||||
}
|
||||
}
|
||||
|
||||
fn scalar_text(value: &Value) -> Option<String> {
|
||||
match value {
|
||||
Value::String(text) => Some(text.clone()),
|
||||
Value::Number(_) | Value::Bool(_) => Some(value.to_string()),
|
||||
Value::Null | Value::Array(_) | Value::Object(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn bounded_string(value: Option<&Value>) -> Result<String, PromptError> {
|
||||
value
|
||||
.and_then(Value::as_str)
|
||||
// PostgreSQL text/jsonb cannot store U+0000, so it must never reach SQL.
|
||||
.filter(|s| !s.is_empty() && s.len() <= MAX_TEXT_BYTES && !s.contains('\0'))
|
||||
.map(str::to_owned)
|
||||
.ok_or(PromptError::InvalidDefinition)
|
||||
}
|
||||
fn valid(kind: ArgumentKind, v: &Value) -> bool {
|
||||
match kind {
|
||||
ArgumentKind::String => v.is_string(),
|
||||
ArgumentKind::Number => v.as_f64().is_some(),
|
||||
ArgumentKind::Integer => v.as_i64().is_some() || v.as_u64().is_some(),
|
||||
ArgumentKind::Boolean => v.is_boolean(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the stored `jsonb::text` form of a scalar stays inside the storage guard.
|
||||
fn bounded_json(value: &Value) -> bool {
|
||||
jsonb_text_len(value).is_some_and(|size| size <= MAX_JSON_TEXT_BYTES)
|
||||
}
|
||||
|
||||
/// Byte length of the `jsonb::text` form PostgreSQL produces for a scalar value:
|
||||
/// quoted strings with `"`/`\` doubled and control characters as `\u00XX`,
|
||||
/// except the short escapes PostgreSQL writes for LF/TAB/CR/BS/FF.
|
||||
fn jsonb_text_len(value: &Value) -> Option<usize> {
|
||||
match value {
|
||||
Value::String(text) => {
|
||||
let mut size = 2;
|
||||
for ch in text.chars() {
|
||||
size += match ch {
|
||||
// PostgreSQL jsonb rejects `\u0000` ("cannot be converted to text").
|
||||
'\0' => return None,
|
||||
'"' | '\\' => 2,
|
||||
'\u{8}' | '\u{c}' | '\n' | '\r' | '\t' => 2,
|
||||
_ if (ch as u32) < 0x20 => 6,
|
||||
_ => ch.len_utf8(),
|
||||
};
|
||||
}
|
||||
Some(size)
|
||||
}
|
||||
Value::Number(number) => Some(number.to_string().len()),
|
||||
Value::Bool(true) => Some(4),
|
||||
Value::Bool(false) => Some(5),
|
||||
Value::Null => Some(4),
|
||||
Value::Array(_) | Value::Object(_) => None,
|
||||
}
|
||||
}
|
||||
fn placeholders(s: &str) -> Result<Vec<(usize, String)>, PromptError> {
|
||||
let mut out = Vec::new();
|
||||
let mut pos = 0;
|
||||
while let Some(rel) = s[pos..].find("{{") {
|
||||
let start = pos + rel;
|
||||
let inner = start + 2;
|
||||
let close = s[inner..]
|
||||
.find("}}")
|
||||
.map(|n| inner + n)
|
||||
.ok_or(PromptError::InvalidTemplate)?;
|
||||
let key = &s[inner..close];
|
||||
if key.is_empty() || !key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
|
||||
return Err(PromptError::InvalidTemplate);
|
||||
}
|
||||
out.push((start, key.to_owned()));
|
||||
pos = close + 2;
|
||||
if !s[pos..].contains("{{") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if s.matches("{{").count() != out.len() || s.matches("}}").count() != out.len() {
|
||||
return Err(PromptError::InvalidTemplate);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Story 3.16 (FR-18): pure composition of a Prompt with its pinned Resource dependencies.
|
||||
//!
|
||||
//! One renderer serves the admin preview and MCP `prompts/get`: the accepted typed renderer
|
||||
//! (`PromptDefinition::preview`) validates arguments and renders the template text first, then the
|
||||
//! pinned content of every declared `resource_refs` index is appended to the message the author
|
||||
//! declared. Message count, order and roles come from the published template only — dependency
|
||||
//! content can never add, remove or re-role a message. There is no tool dispatch and no code path
|
||||
//! that interprets dependency content, so a `{"tool_calls": …}` block stays inert text.
|
||||
//!
|
||||
//! Failures are typed and total: the caller receives a reason and a position/source path, never a
|
||||
//! partially composed message list and never the matched secret text.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::prompt::{
|
||||
MAX_TEXT_BYTES, PromptDefinition, PromptError, PromptMessage, PromptSensitivity,
|
||||
};
|
||||
use crate::resource::{ResourceKind, publication_include_directives, publication_secret_findings};
|
||||
|
||||
/// Bound of the `dependencies` array (contract §1, `MAX_PROMPT_DEPENDENCIES`).
|
||||
pub const MAX_PROMPT_DEPENDENCIES: usize = 16;
|
||||
|
||||
/// Wire values of `dependencies[i].source_class` (contract §4).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PromptDependencySourceClass {
|
||||
Static,
|
||||
Dynamic,
|
||||
}
|
||||
|
||||
impl PromptDependencySourceClass {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Static => "static",
|
||||
Self::Dynamic => "dynamic",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"static" => Some(Self::Static),
|
||||
"dynamic" => Some(Self::Dynamic),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One resolved pin of a published dependency: the exact version the Prompt was published with,
|
||||
/// plus the metadata the provenance block reports. It carries no content.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PromptDependencyPin {
|
||||
pub position: usize,
|
||||
pub resource_id: String,
|
||||
pub version: u32,
|
||||
pub digest: String,
|
||||
pub kind: ResourceKind,
|
||||
pub mime_type: String,
|
||||
pub source_class: PromptDependencySourceClass,
|
||||
pub sensitivity: PromptSensitivity,
|
||||
}
|
||||
|
||||
impl PromptDependencyPin {
|
||||
/// Provenance row of the preview contract (§7): declaration order, no content.
|
||||
pub fn provenance_json(pin: &Self) -> Value {
|
||||
serde_json::json!({
|
||||
"position": pin.position,
|
||||
"resource_id": pin.resource_id,
|
||||
"version": pin.version,
|
||||
"digest": pin.digest,
|
||||
"kind": pin.kind.as_str(),
|
||||
"mime_type": pin.mime_type,
|
||||
"source_class": pin.source_class.as_str(),
|
||||
"sensitivity": pin.sensitivity,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Ordered provenance block of a composed result.
|
||||
pub fn provenance_json(pins: &[PromptDependencyPin]) -> Vec<Value> {
|
||||
pins.iter()
|
||||
.map(PromptDependencyPin::provenance_json)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Typed refusal of the composition boundary.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum PromptCompositionError {
|
||||
/// A dependency no message references: pinning content that is never delivered (contract §1).
|
||||
DependencyUnused {
|
||||
position: usize,
|
||||
resource_id: String,
|
||||
version: u32,
|
||||
},
|
||||
/// The pinned exact version cannot be resolved/read right now (revoked, archived, foreign).
|
||||
DependencyUnavailable { position: usize },
|
||||
/// `binary` has no negotiated message representation (contract §4).
|
||||
DependencyRepresentationUnsupported { position: usize },
|
||||
/// The template text itself carries a raw credential.
|
||||
CredentialFinding { source_path: String },
|
||||
/// The template text itself carries an explicit `include:` access-bypass directive.
|
||||
AccessBypassFinding { source_path: String },
|
||||
/// Read-time content of a dynamic dependency carries a raw credential.
|
||||
DependencyCredentialFinding { position: usize },
|
||||
/// Read-time content of a dynamic dependency carries an `include:` directive.
|
||||
DependencyAccessBypassFinding { position: usize },
|
||||
/// The accepted renderer refused the template/arguments.
|
||||
Template(PromptError),
|
||||
}
|
||||
|
||||
impl From<PromptError> for PromptCompositionError {
|
||||
fn from(error: PromptError) -> Self {
|
||||
Self::Template(error)
|
||||
}
|
||||
}
|
||||
|
||||
/// Strictest-sensitivity fold: `effective = max(local, every pinned dependency)` (contract §3).
|
||||
pub fn effective_sensitivity(
|
||||
local: PromptSensitivity,
|
||||
pins: &[PromptDependencyPin],
|
||||
) -> PromptSensitivity {
|
||||
pins.iter().fold(local, |strictest, pin| {
|
||||
if rank(pin.sensitivity) > rank(strictest) {
|
||||
pin.sensitivity
|
||||
} else {
|
||||
strictest
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn rank(sensitivity: PromptSensitivity) -> u8 {
|
||||
match sensitivity {
|
||||
PromptSensitivity::Public => 0,
|
||||
PromptSensitivity::Internal => 1,
|
||||
PromptSensitivity::Secret => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first dependency (declaration order) that no message references.
|
||||
pub fn unused_dependency(definition: &PromptDefinition) -> Option<usize> {
|
||||
(0..definition.dependencies().len()).find(|position| {
|
||||
!definition
|
||||
.messages()
|
||||
.iter()
|
||||
.any(|message| message.resource_refs.contains(position))
|
||||
})
|
||||
}
|
||||
|
||||
/// Bounded scan of the Prompt template text (messages, contract §5).
|
||||
pub fn scan_template(definition: &PromptDefinition) -> Result<(), PromptCompositionError> {
|
||||
for (position, message) in definition.messages().iter().enumerate() {
|
||||
let bytes = message.content.as_bytes();
|
||||
if publication_secret_findings(bytes).is_some() {
|
||||
return Err(PromptCompositionError::CredentialFinding {
|
||||
source_path: format!("messages[{position}].content"),
|
||||
});
|
||||
}
|
||||
if !publication_include_directives(bytes).is_empty() {
|
||||
return Err(PromptCompositionError::AccessBypassFinding {
|
||||
source_path: format!("messages[{position}].content"),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bounded scan of dynamic dependency content, fetched at read time (contract §5).
|
||||
pub fn scan_dependency_content(
|
||||
position: usize,
|
||||
bytes: &[u8],
|
||||
) -> Result<(), PromptCompositionError> {
|
||||
if publication_secret_findings(bytes).is_some() {
|
||||
return Err(PromptCompositionError::DependencyCredentialFinding { position });
|
||||
}
|
||||
if !publication_include_directives(bytes).is_empty() {
|
||||
return Err(PromptCompositionError::DependencyAccessBypassFinding { position });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Content of every dependency, indexed by declaration position.
|
||||
///
|
||||
/// `None` means the exact pinned version could not be read now; a dependency that is absent from
|
||||
/// this slice is treated the same way, so composition is total and never silently short.
|
||||
pub fn render(
|
||||
definition: &PromptDefinition,
|
||||
pins: &[PromptDependencyPin],
|
||||
arguments: &Map<String, Value>,
|
||||
contents: &[Option<Vec<u8>>],
|
||||
) -> Result<Vec<PromptMessage>, PromptCompositionError> {
|
||||
let mut messages = definition.preview(arguments)?;
|
||||
for message in &mut messages {
|
||||
for index in &message.resource_refs {
|
||||
let Some(Some(bytes)) = contents.get(*index) else {
|
||||
return Err(PromptCompositionError::DependencyUnavailable { position: *index });
|
||||
};
|
||||
let pin = pins
|
||||
.iter()
|
||||
.find(|pin| pin.position == *index)
|
||||
.ok_or(PromptCompositionError::DependencyUnavailable { position: *index })?;
|
||||
let text = match pin.kind {
|
||||
ResourceKind::Text | ResourceKind::Json => {
|
||||
std::str::from_utf8(bytes).map_err(|_| {
|
||||
PromptCompositionError::DependencyRepresentationUnsupported {
|
||||
position: *index,
|
||||
}
|
||||
})?
|
||||
}
|
||||
ResourceKind::Binary => {
|
||||
return Err(
|
||||
PromptCompositionError::DependencyRepresentationUnsupported {
|
||||
position: *index,
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
||||
// Contract §5: dynamic content is fetched at read time and was never scanned at
|
||||
// publication, so it is scanned here — one call site for preview and `prompts/get`.
|
||||
if pin.source_class == PromptDependencySourceClass::Dynamic {
|
||||
scan_dependency_content(*index, text.as_bytes())?;
|
||||
}
|
||||
if !message.content.is_empty() {
|
||||
message.content.push_str("\n\n");
|
||||
}
|
||||
message.content.push_str(text);
|
||||
// shortcut: one composed message keeps the accepted 16 KiB text bound; a larger
|
||||
// composed message is refused instead of silently truncated.
|
||||
if message.content.len() > MAX_TEXT_BYTES {
|
||||
return Err(PromptCompositionError::Template(
|
||||
PromptError::InvalidTemplate,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
@@ -0,0 +1,915 @@
|
||||
//! Typed static Resource drafts (Story 3.6): domain contract for `Resource`.
|
||||
//!
|
||||
//! `Resource` — отдельный typed aggregate с собственными ID/version/lifecycle,
|
||||
//! sensitivity и неизменяемой published-моделью; он не является подтипом
|
||||
//! `Operation` и не «универсальный JSON blob» (AD-1/AD-2).
|
||||
//!
|
||||
//! Здесь же живут грамматики и валидаторы контракта:
|
||||
//! - D-3 — пределы содержимого (`ResourceLimits`, storage ceiling);
|
||||
//! - D-4 — синтаксис MIME (наследуется из существующего DB CHECK V12);
|
||||
//! - D-5 — закрытый allowlist MIME по kind (content sniffing отсутствует);
|
||||
//! - D-7 — пустое содержимое отвергается;
|
||||
//! - D-8 — JSON валидируется locked-парсером `serde_json` и хранится дословно;
|
||||
//! - D-9 — UTF-8 без replacement и без «успешного префикса»;
|
||||
//! - D-10 — грамматика URI;
|
||||
//! - D-11 — грамматика name;
|
||||
//! - D-14 — стабильные коды/поля отказов (`ResourceError`).
|
||||
//!
|
||||
//! Коды отказа — контракт wire-уровня: HTTP-статус и envelope формирует
|
||||
//! admin-api (`error.rs`), а домен отвечает только за `code`/`field`.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::ids::{OperationId, ResourceId};
|
||||
|
||||
/// Storage ceiling одного blob-а (`MAX_ARTIFACT_BYTES`) и DB CHECK
|
||||
/// `artifact_blobs_size_check`. Это не новый продуктовый порог: default
|
||||
/// `ResourceLimits` равен этому потолку (D-3).
|
||||
pub const RESOURCE_STORAGE_CEILING: usize = 256 * 1024;
|
||||
|
||||
/// Верхняя граница `description` в байтах (D-20, DB CHECK `resources_description_len`).
|
||||
pub const MAX_RESOURCE_DESCRIPTION_BYTES: usize = 1024;
|
||||
|
||||
/// Нижняя и верхняя границы URI в байтах; следуют из грамматики UR-2 (D-10).
|
||||
pub const MIN_RESOURCE_URI_BYTES: usize = 10;
|
||||
pub const MAX_RESOURCE_URI_BYTES: usize = 200;
|
||||
|
||||
/// Верхняя граница `name` в символах (ASCII-грамматика D-11).
|
||||
pub const MAX_RESOURCE_NAME_BYTES: usize = 64;
|
||||
|
||||
const URI_SCHEME: &str = "crank://";
|
||||
|
||||
const TEXT_MIME_TYPES: &[&str] = &["text/plain", "text/markdown", "text/csv"];
|
||||
const JSON_MIME_TYPES: &[&str] = &["application/json"];
|
||||
const BINARY_MIME_TYPES: &[&str] = &[
|
||||
"application/octet-stream",
|
||||
"application/pdf",
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
"image/svg+xml",
|
||||
"text/html",
|
||||
];
|
||||
|
||||
/// Общий typed контракт capability (AD-2): Operation, Resource (и будущий Prompt).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum CapabilityKind {
|
||||
Operation,
|
||||
Resource,
|
||||
}
|
||||
|
||||
/// Typed ссылка на capability. Варианты несовместимы по типу: Operation-ref не
|
||||
/// принимается там, где нужен Resource-ref (AT-3.6-01).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase", tag = "kind", content = "id")]
|
||||
pub enum CapabilityRef {
|
||||
Operation(OperationId),
|
||||
Resource(ResourceId),
|
||||
}
|
||||
|
||||
impl fmt::Display for CapabilityKind {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(match self {
|
||||
Self::Operation => "operation",
|
||||
Self::Resource => "resource",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Ошибка несовместимости typed-ссылки на capability.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("capability reference is a {actual}, expected a {expected}")]
|
||||
pub struct CapabilityKindMismatch {
|
||||
pub expected: CapabilityKind,
|
||||
pub actual: CapabilityKind,
|
||||
}
|
||||
|
||||
impl CapabilityRef {
|
||||
pub fn kind(&self) -> CapabilityKind {
|
||||
match self {
|
||||
Self::Operation(_) => CapabilityKind::Operation,
|
||||
Self::Resource(_) => CapabilityKind::Resource,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resource-ref или типизированный отказ — «поиск слов» вместо проверки типа не используется.
|
||||
pub fn as_resource(&self) -> Result<&ResourceId, CapabilityKindMismatch> {
|
||||
match self {
|
||||
Self::Resource(resource_id) => Ok(resource_id),
|
||||
Self::Operation(_) => Err(CapabilityKindMismatch {
|
||||
expected: CapabilityKind::Resource,
|
||||
actual: CapabilityKind::Operation,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_operation(&self) -> Result<&OperationId, CapabilityKindMismatch> {
|
||||
match self {
|
||||
Self::Operation(operation_id) => Ok(operation_id),
|
||||
Self::Resource(_) => Err(CapabilityKindMismatch {
|
||||
expected: CapabilityKind::Operation,
|
||||
actual: CapabilityKind::Resource,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire-значения `ResourceKind` (D-2).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ResourceKind {
|
||||
Text,
|
||||
Json,
|
||||
Binary,
|
||||
}
|
||||
|
||||
impl ResourceKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Text => "text",
|
||||
Self::Json => "json",
|
||||
Self::Binary => "binary",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"text" => Some(Self::Text),
|
||||
"json" => Some(Self::Json),
|
||||
"binary" => Some(Self::Binary),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// kind, для которого MIME входит в закрытый allowlist D-5.
|
||||
pub fn for_mime(mime_type: &str) -> Option<Self> {
|
||||
if TEXT_MIME_TYPES.contains(&mime_type) {
|
||||
Some(Self::Text)
|
||||
} else if JSON_MIME_TYPES.contains(&mime_type) {
|
||||
Some(Self::Json)
|
||||
} else if BINARY_MIME_TYPES.contains(&mime_type) {
|
||||
Some(Self::Binary)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allows_mime_type(self, mime_type: &str) -> bool {
|
||||
Self::for_mime(mime_type) == Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire-значения `ResourceStatus` (D-2); отдельный тип, форма как у `OperationStatus`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ResourceStatus {
|
||||
Draft,
|
||||
Published,
|
||||
Archived,
|
||||
}
|
||||
|
||||
impl ResourceStatus {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Draft => "draft",
|
||||
Self::Published => "published",
|
||||
Self::Archived => "archived",
|
||||
}
|
||||
}
|
||||
|
||||
/// Допустимый lifecycle-переход. Publish/archive реализуются в 3.7, но модель
|
||||
/// обязана отвергать недопустимый переход уже в 3.6.
|
||||
pub fn can_transition_to(self, next: Self) -> bool {
|
||||
matches!(
|
||||
(self, next),
|
||||
(Self::Draft, Self::Published | Self::Archived)
|
||||
| (Self::Published, Self::Draft | Self::Archived)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ResourceKind {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ResourceStatus {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// Действия lifecycle Resource (описательная часть контракта).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ResourceLifecycleAction {
|
||||
Publish,
|
||||
Revert,
|
||||
Archive,
|
||||
}
|
||||
|
||||
impl ResourceLifecycleAction {
|
||||
pub fn target(self) -> ResourceStatus {
|
||||
match self {
|
||||
Self::Publish => ResourceStatus::Published,
|
||||
Self::Revert => ResourceStatus::Draft,
|
||||
Self::Archive => ResourceStatus::Archived,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Проверенный lifecycle-переход; `ResourceLifecycle::transition` возвращает его
|
||||
/// только для допустимой пары состояний.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ResourceLifecycle {
|
||||
pub from: ResourceStatus,
|
||||
pub action: ResourceLifecycleAction,
|
||||
}
|
||||
|
||||
impl ResourceLifecycle {
|
||||
pub fn transition(
|
||||
from: ResourceStatus,
|
||||
action: ResourceLifecycleAction,
|
||||
) -> Result<Self, ResourceError> {
|
||||
let to = action.target();
|
||||
if !from.can_transition_to(to) {
|
||||
return Err(ResourceError::InvalidLifecycleTransition { from, to });
|
||||
}
|
||||
Ok(Self { from, action })
|
||||
}
|
||||
|
||||
pub fn to(self) -> ResourceStatus {
|
||||
self.action.target()
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire-значения sensitivity совпадают с существующим CHECK V12 (D-13).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ResourceSensitivity {
|
||||
Public,
|
||||
Internal,
|
||||
Secret,
|
||||
}
|
||||
|
||||
impl ResourceSensitivity {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Public => "public",
|
||||
Self::Internal => "internal",
|
||||
Self::Secret => "secret",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"public" => Some(Self::Public),
|
||||
"internal" => Some(Self::Internal),
|
||||
"secret" => Some(Self::Secret),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Задаваемые атрибуты Draft (D-16): URI/name/kind неизменяемы после создания.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceMetadata {
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub kind: ResourceKind,
|
||||
pub mime_type: String,
|
||||
pub sensitivity: ResourceSensitivity,
|
||||
}
|
||||
|
||||
impl ResourceMetadata {
|
||||
/// D-10 UR-1..UR-3: литерал `crank://`, ASCII charset 10..=200 байт, непустые
|
||||
/// сегменты без `.`/`..` и без trailing `/`.
|
||||
pub fn uri_is_valid(uri: &str) -> bool {
|
||||
let Some(path) = uri.strip_prefix(URI_SCHEME) else {
|
||||
return false;
|
||||
};
|
||||
if uri.len() < MIN_RESOURCE_URI_BYTES || uri.len() > MAX_RESOURCE_URI_BYTES {
|
||||
return false;
|
||||
}
|
||||
// UR-2: после литерала схемы ровно `1 + 0..190 + 1` символов, то есть
|
||||
// вся ссылка 10..=200 байт включительно.
|
||||
const MAX_PATH_BYTES: usize = MAX_RESOURCE_URI_BYTES - URI_SCHEME.len();
|
||||
if path.is_empty() || path.len() > MAX_PATH_BYTES {
|
||||
return false;
|
||||
}
|
||||
let bytes = path.as_bytes();
|
||||
let Some((first, rest)) = bytes.split_first() else {
|
||||
return false;
|
||||
};
|
||||
let Some((last, middle)) = rest.split_last() else {
|
||||
return false;
|
||||
};
|
||||
let edge = |byte: u8| byte.is_ascii_alphanumeric();
|
||||
if !edge(*first) || !edge(*last) {
|
||||
return false;
|
||||
}
|
||||
if !middle.iter().all(|byte| {
|
||||
byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'~' | b'/' | b'-')
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
if path.ends_with('/') {
|
||||
return false;
|
||||
}
|
||||
path.split('/')
|
||||
.all(|segment| !segment.is_empty() && segment != "." && segment != "..")
|
||||
}
|
||||
|
||||
/// D-11: `^[a-z][a-z0-9_-]{0,63}$`.
|
||||
pub fn name_is_valid(name: &str) -> bool {
|
||||
let bytes = name.as_bytes();
|
||||
if bytes.is_empty() || bytes.len() > MAX_RESOURCE_NAME_BYTES {
|
||||
return false;
|
||||
}
|
||||
let Some((first, rest)) = bytes.split_first() else {
|
||||
return false;
|
||||
};
|
||||
first.is_ascii_lowercase()
|
||||
&& rest.iter().all(|byte| {
|
||||
byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_')
|
||||
})
|
||||
}
|
||||
|
||||
/// D-4: bare `type/subtype` без параметров; грамматика наследуется из V12.
|
||||
pub fn mime_syntax_is_valid(mime_type: &str) -> bool {
|
||||
let Some((kind, subtype)) = mime_type.split_once('/') else {
|
||||
return false;
|
||||
};
|
||||
if kind.is_empty()
|
||||
|| subtype.is_empty()
|
||||
|| mime_type.len() > 255
|
||||
|| mime_type.len() < 3
|
||||
|| subtype.contains('/')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let token_is_valid = |token: &str| {
|
||||
token.bytes().all(|byte| {
|
||||
byte.is_ascii_alphanumeric()
|
||||
|| matches!(
|
||||
byte,
|
||||
b'!' | b'#' | b'$' | b'&' | b'^' | b'_' | b'.' | b'+' | b'-'
|
||||
)
|
||||
})
|
||||
};
|
||||
token_is_valid(kind) && token_is_valid(subtype)
|
||||
}
|
||||
|
||||
pub fn description_is_valid(description: &str) -> bool {
|
||||
description.len() <= MAX_RESOURCE_DESCRIPTION_BYTES
|
||||
}
|
||||
|
||||
/// D-20 шаг E: фиксированный порядок uri → name → description → kind/mime.
|
||||
pub fn validate(&self) -> Result<(), ResourceError> {
|
||||
if !Self::uri_is_valid(&self.uri) {
|
||||
return Err(ResourceError::UriInvalid);
|
||||
}
|
||||
if !Self::name_is_valid(&self.name) {
|
||||
return Err(ResourceError::NameInvalid);
|
||||
}
|
||||
if !Self::description_is_valid(&self.description) {
|
||||
return Err(ResourceError::DescriptionInvalid);
|
||||
}
|
||||
self.validate_mime()
|
||||
}
|
||||
|
||||
/// Правило MIME в одном месте (D-20 шаг E): синтаксис → allowlist → совместимость с kind.
|
||||
pub fn validate_mime(&self) -> Result<(), ResourceError> {
|
||||
if !Self::mime_syntax_is_valid(&self.mime_type) {
|
||||
return Err(ResourceError::MimeSyntaxInvalid);
|
||||
}
|
||||
match ResourceKind::for_mime(&self.mime_type) {
|
||||
None => Err(ResourceError::MimeNotAllowed),
|
||||
Some(owner) if owner != self.kind => Err(ResourceError::KindMismatch),
|
||||
Some(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// D-9/D-3: text-kind; L inclusive, L+1 отвергается целиком, без U+FFFD и усечения.
|
||||
pub fn validate_text(bytes: &[u8], limit: usize) -> Result<Vec<u8>, ResourceError> {
|
||||
if bytes.len() > limit {
|
||||
return Err(ResourceError::ContentTooLarge);
|
||||
}
|
||||
if bytes.is_empty() {
|
||||
return Err(ResourceError::ContentEmpty);
|
||||
}
|
||||
if std::str::from_utf8(bytes).is_err() {
|
||||
return Err(ResourceError::ContentInvalidUtf8);
|
||||
}
|
||||
Ok(bytes.to_vec())
|
||||
}
|
||||
|
||||
/// D-8: валидация locked-парсером `serde_json` без features; bytes хранятся дословно.
|
||||
pub fn validate_json(bytes: &[u8], limit: usize) -> Result<Vec<u8>, ResourceError> {
|
||||
if bytes.len() > limit {
|
||||
return Err(ResourceError::ContentTooLarge);
|
||||
}
|
||||
if bytes.is_empty() {
|
||||
return Err(ResourceError::ContentEmpty);
|
||||
}
|
||||
if serde_json::from_slice::<serde_json::Value>(bytes).is_err() {
|
||||
return Err(ResourceError::ContentInvalidJson);
|
||||
}
|
||||
Ok(bytes.to_vec())
|
||||
}
|
||||
|
||||
/// Проверка содержимого по typed kind (без content sniffing).
|
||||
pub fn validate_content(
|
||||
kind: ResourceKind,
|
||||
mime_type: &str,
|
||||
bytes: &[u8],
|
||||
limits: &ResourceLimits,
|
||||
) -> Result<Vec<u8>, ResourceError> {
|
||||
let limit = limits.effective_limit(kind);
|
||||
match kind {
|
||||
ResourceKind::Text => Self::validate_text(bytes, limit),
|
||||
ResourceKind::Json => Self::validate_json(bytes, limit),
|
||||
ResourceKind::Binary => {
|
||||
if bytes.len() > limit {
|
||||
return Err(ResourceError::ContentTooLarge);
|
||||
}
|
||||
if bytes.is_empty() {
|
||||
return Err(ResourceError::ContentEmpty);
|
||||
}
|
||||
let _ = mime_type;
|
||||
Ok(bytes.to_vec())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Безопасный finding для непригодного MIME (bytes не раскрываются).
|
||||
pub fn mime_finding(
|
||||
mime_type: &str,
|
||||
kind: ResourceKind,
|
||||
limits: &ResourceLimits,
|
||||
) -> ResourceFinding {
|
||||
let _ = limits;
|
||||
if !Self::mime_syntax_is_valid(mime_type) {
|
||||
return ResourceFinding::rejected(ResourceFindingCode::MimeSyntaxInvalid, "mime_type");
|
||||
}
|
||||
match ResourceKind::for_mime(mime_type) {
|
||||
None => ResourceFinding::rejected(ResourceFindingCode::MimeNotAllowed, "mime_type"),
|
||||
Some(owner) if owner != kind => {
|
||||
ResourceFinding::rejected(ResourceFindingCode::KindMismatch, "kind")
|
||||
}
|
||||
Some(_) => ResourceFinding::accepted(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Безопасный finding для невалидного JSON-документа.
|
||||
pub fn json_finding(bytes: &[u8], limits: &ResourceLimits) -> ResourceFinding {
|
||||
match Self::validate_json(bytes, limits.effective_limit(ResourceKind::Json)) {
|
||||
Ok(_) => ResourceFinding::accepted(),
|
||||
Err(error) => {
|
||||
ResourceFinding::rejected(error.finding_code(), error.field_or("content"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Пределы содержимого по kind. Значение выше storage ceiling отвергается при
|
||||
/// конфигурации; новый env-ключ не вводится (D-3).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ResourceLimits {
|
||||
text: usize,
|
||||
json: usize,
|
||||
binary: usize,
|
||||
}
|
||||
|
||||
impl Default for ResourceLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
text: RESOURCE_STORAGE_CEILING,
|
||||
json: RESOURCE_STORAGE_CEILING,
|
||||
binary: RESOURCE_STORAGE_CEILING,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourceLimits {
|
||||
pub const STORAGE_CEILING: usize = RESOURCE_STORAGE_CEILING;
|
||||
|
||||
/// Конфигурация пределов; значения выше потолка не принимаются (D-3).
|
||||
pub fn new(text: usize, json: usize, binary: usize) -> Result<Self, ResourceError> {
|
||||
if [text, json, binary]
|
||||
.into_iter()
|
||||
.any(|limit| limit == 0 || limit > RESOURCE_STORAGE_CEILING)
|
||||
{
|
||||
return Err(ResourceError::InvalidLimits);
|
||||
}
|
||||
Ok(Self { text, json, binary })
|
||||
}
|
||||
|
||||
/// Один предел на все три kind — форма, используемая сервисом и тестами.
|
||||
pub fn uniform(limit: usize) -> Result<Self, ResourceError> {
|
||||
Self::new(limit, limit, limit)
|
||||
}
|
||||
|
||||
pub fn effective_limit(&self, kind: ResourceKind) -> usize {
|
||||
match kind {
|
||||
ResourceKind::Text => self.text,
|
||||
ResourceKind::Json => self.json,
|
||||
ResourceKind::Binary => self.binary,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Коды findings (те же строки, что и stable `error.code`, D-14).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ResourceFindingCode {
|
||||
#[serde(rename = "resource_content_empty")]
|
||||
ContentEmpty,
|
||||
#[serde(rename = "resource_content_too_large")]
|
||||
ContentTooLarge,
|
||||
#[serde(rename = "resource_content_invalid_utf8")]
|
||||
ContentInvalidUtf8,
|
||||
#[serde(rename = "resource_content_invalid_json")]
|
||||
ContentInvalidJson,
|
||||
#[serde(rename = "resource_mime_syntax_invalid")]
|
||||
MimeSyntaxInvalid,
|
||||
#[serde(rename = "resource_mime_not_allowed")]
|
||||
MimeNotAllowed,
|
||||
#[serde(rename = "resource_kind_mismatch")]
|
||||
KindMismatch,
|
||||
/// Служебное значение «нарушений нет»; в ответах `findings` пуст на успехе,
|
||||
/// поэтому этот код на wire не попадает.
|
||||
#[serde(rename = "resource_finding_accepted")]
|
||||
Accepted,
|
||||
}
|
||||
|
||||
impl ResourceFindingCode {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::ContentEmpty => "resource_content_empty",
|
||||
Self::ContentTooLarge => "resource_content_too_large",
|
||||
Self::ContentInvalidUtf8 => "resource_content_invalid_utf8",
|
||||
Self::ContentInvalidJson => "resource_content_invalid_json",
|
||||
Self::MimeSyntaxInvalid => "resource_mime_syntax_invalid",
|
||||
Self::MimeNotAllowed => "resource_mime_not_allowed",
|
||||
Self::KindMismatch => "resource_kind_mismatch",
|
||||
Self::Accepted => "resource_finding_accepted",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finding не содержит bytes содержимого: только стабильный код и поле.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceFinding {
|
||||
code: ResourceFindingCode,
|
||||
field: &'static str,
|
||||
}
|
||||
|
||||
impl ResourceFinding {
|
||||
pub fn rejected(code: ResourceFindingCode, field: &'static str) -> Self {
|
||||
Self { code, field }
|
||||
}
|
||||
|
||||
/// «Нарушений нет» — служебное значение, не являющееся rejection.
|
||||
pub fn accepted() -> Self {
|
||||
Self {
|
||||
code: ResourceFindingCode::Accepted,
|
||||
field: "",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code(&self) -> &'static str {
|
||||
self.code.as_str()
|
||||
}
|
||||
|
||||
pub fn field(&self) -> &'static str {
|
||||
self.field
|
||||
}
|
||||
|
||||
pub fn is_rejection(&self) -> bool {
|
||||
!self.field.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Стабильные коды/поля отказов Resource (D-14) без HTTP-статусов: статус
|
||||
/// назначает admin-api по коду.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ResourceError {
|
||||
#[error("resource content must not be empty")]
|
||||
ContentEmpty,
|
||||
/// Story 3.9: форма переносимого envelope не распознана (неизвестные/недостающие
|
||||
/// ключи, неподдержанная версия, синтаксис base64/hex, `source`). Транспортный
|
||||
/// контракт envelope живёт в admin-api; здесь только стабильный wire-код.
|
||||
#[error("resource portability envelope is invalid")]
|
||||
PortabilityEnvelopeInvalid,
|
||||
#[error("resource content exceeds the configured limit")]
|
||||
ContentTooLarge,
|
||||
#[error("resource content is not valid UTF-8")]
|
||||
ContentInvalidUtf8,
|
||||
#[error("resource content is not valid JSON")]
|
||||
ContentInvalidJson,
|
||||
#[error("resource mime type syntax is invalid")]
|
||||
MimeSyntaxInvalid,
|
||||
#[error("resource mime type is not allowed for this kind")]
|
||||
MimeNotAllowed,
|
||||
#[error("resource mime type is incompatible with the declared kind")]
|
||||
KindMismatch,
|
||||
#[error("resource uri is invalid")]
|
||||
UriInvalid,
|
||||
#[error("resource name is invalid")]
|
||||
NameInvalid,
|
||||
#[error("resource description is invalid")]
|
||||
DescriptionInvalid,
|
||||
/// Значение поля метаданных вне набора (`kind`/`sensitivity`): форма запроса, а не
|
||||
/// доменный код (D-20 B/E). `code()` отдаёт принятый для этого отказа generic-код,
|
||||
/// а admin-api выводит его без Resource-специфичного контекста.
|
||||
#[error("resource metadata field `{field}` has an unknown value")]
|
||||
UnknownMetadataValue { field: &'static str },
|
||||
#[error("resource uri already exists in this workspace")]
|
||||
UriDuplicate,
|
||||
#[error("resource name already exists in this workspace")]
|
||||
NameDuplicate,
|
||||
#[error("resource field {field} is immutable")]
|
||||
FieldImmutable { field: &'static str },
|
||||
#[error("resource changed since it was read")]
|
||||
Stale,
|
||||
#[error("resource was not found in this workspace")]
|
||||
NotFound,
|
||||
/// Story 3.8: необратимый security-revoke закрыл Resource целиком. Это не
|
||||
/// lifecycle-состояние: archive/редактирование его не снимают, а новые
|
||||
/// публикации и привязки запрещены.
|
||||
#[error("resource has been revoked")]
|
||||
Revoked,
|
||||
#[error("resource artifact integrity verification failed")]
|
||||
ArtifactIntegrity,
|
||||
/// Публикация отклонена secret-policy: содержимое содержит структурный private key,
|
||||
/// raw credential assignment либо explicit access-bypassing reference. Наружу отдаётся
|
||||
/// только общая категория, никогда не совпавший текст (TL decision 4).
|
||||
#[error("resource content contains secret material or an access-bypassing reference")]
|
||||
SecretFindings,
|
||||
#[error("resource storage is unavailable")]
|
||||
StorageUnavailable,
|
||||
#[error("resource content limits are invalid")]
|
||||
InvalidLimits,
|
||||
#[error("resource lifecycle transition from {from} to {to} is not allowed")]
|
||||
InvalidLifecycleTransition {
|
||||
from: ResourceStatus,
|
||||
to: ResourceStatus,
|
||||
},
|
||||
/// Story 3.10: структурно неверное определение REST-шаблона (wire
|
||||
/// `resource_source_invalid`); `field` — конкретное поле отказа.
|
||||
#[error("resource source definition is invalid")]
|
||||
SourceInvalid { field: &'static str },
|
||||
/// Story 3.10: Operation/версия не найдена в этом workspace (чужой workspace
|
||||
/// неотличим от отсутствующего — без раскрытия).
|
||||
#[error("resource source operation was not found in this workspace")]
|
||||
SourceNotFound,
|
||||
/// Story 3.10: версия существует, но не Published.
|
||||
#[error("resource source operation version is not published")]
|
||||
SourceNotPublished,
|
||||
/// Story 3.10: публикацию блокируют findings шаблона.
|
||||
#[error("resource source definition has blocking findings")]
|
||||
SourceBlocked {
|
||||
findings: Vec<crate::resource::template::TemplateFinding>,
|
||||
},
|
||||
/// Story 3.10: определение шаблона не переносимо (export/content).
|
||||
#[error("resource source definition is not portable")]
|
||||
SourceNotPortable,
|
||||
}
|
||||
|
||||
impl ResourceError {
|
||||
pub fn code(&self) -> &'static str {
|
||||
match self {
|
||||
Self::ContentEmpty => "resource_content_empty",
|
||||
Self::PortabilityEnvelopeInvalid => "resource_portability_envelope_invalid",
|
||||
Self::ContentTooLarge => "resource_content_too_large",
|
||||
Self::ContentInvalidUtf8 => "resource_content_invalid_utf8",
|
||||
Self::ContentInvalidJson => "resource_content_invalid_json",
|
||||
Self::MimeSyntaxInvalid => "resource_mime_syntax_invalid",
|
||||
Self::MimeNotAllowed => "resource_mime_not_allowed",
|
||||
Self::KindMismatch => "resource_kind_mismatch",
|
||||
Self::UriInvalid => "resource_uri_invalid",
|
||||
Self::NameInvalid => "resource_name_invalid",
|
||||
Self::DescriptionInvalid => "resource_description_invalid",
|
||||
// D-20 B/E: у этого отказа нет Resource-специфичного кода.
|
||||
Self::UnknownMetadataValue { .. } => "validation_error",
|
||||
Self::UriDuplicate => "resource_uri_duplicate",
|
||||
Self::NameDuplicate => "resource_name_duplicate",
|
||||
Self::FieldImmutable { .. } => "resource_field_immutable",
|
||||
Self::Stale => "resource_stale",
|
||||
Self::NotFound => "resource_not_found",
|
||||
Self::Revoked => "resource_revoked",
|
||||
Self::ArtifactIntegrity => "resource_artifact_integrity",
|
||||
Self::SecretFindings => "resource_secret_findings",
|
||||
Self::StorageUnavailable => "resource_storage_unavailable",
|
||||
Self::InvalidLimits => "resource_limits_invalid",
|
||||
Self::InvalidLifecycleTransition { .. } => "resource_lifecycle_invalid",
|
||||
Self::SourceInvalid { .. } => "resource_source_invalid",
|
||||
Self::SourceNotFound => "resource_source_not_found",
|
||||
Self::SourceNotPublished => "resource_source_not_published",
|
||||
Self::SourceBlocked { .. } => "resource_source_blocked",
|
||||
Self::SourceNotPortable => "resource_source_not_portable",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn field(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::ContentEmpty
|
||||
| Self::ContentTooLarge
|
||||
| Self::ContentInvalidUtf8
|
||||
| Self::ContentInvalidJson
|
||||
| Self::ArtifactIntegrity
|
||||
| Self::SecretFindings => Some("content"),
|
||||
Self::PortabilityEnvelopeInvalid => Some("envelope"),
|
||||
Self::MimeSyntaxInvalid | Self::MimeNotAllowed => Some("mime_type"),
|
||||
Self::KindMismatch => Some("kind"),
|
||||
Self::UriInvalid | Self::UriDuplicate => Some("uri"),
|
||||
Self::NameInvalid | Self::NameDuplicate => Some("name"),
|
||||
Self::DescriptionInvalid => Some("description"),
|
||||
Self::FieldImmutable { field } => Some(field),
|
||||
Self::Stale => Some("expected_updated_at"),
|
||||
Self::NotFound | Self::Revoked => Some("resource_id"),
|
||||
Self::StorageUnavailable
|
||||
| Self::InvalidLimits
|
||||
| Self::UnknownMetadataValue { .. }
|
||||
| Self::InvalidLifecycleTransition { .. } => None,
|
||||
Self::SourceInvalid { field } => Some(field),
|
||||
Self::SourceNotFound => Some("source.operation_id"),
|
||||
Self::SourceNotPublished => Some("source.operation_version"),
|
||||
Self::SourceBlocked { .. } | Self::SourceNotPortable => Some("source"),
|
||||
}
|
||||
}
|
||||
|
||||
fn field_or(&self, fallback: &'static str) -> &'static str {
|
||||
self.field().unwrap_or(fallback)
|
||||
}
|
||||
|
||||
fn finding_code(&self) -> ResourceFindingCode {
|
||||
match self {
|
||||
Self::ContentEmpty => ResourceFindingCode::ContentEmpty,
|
||||
Self::ContentTooLarge => ResourceFindingCode::ContentTooLarge,
|
||||
Self::ContentInvalidUtf8 => ResourceFindingCode::ContentInvalidUtf8,
|
||||
Self::MimeSyntaxInvalid => ResourceFindingCode::MimeSyntaxInvalid,
|
||||
Self::MimeNotAllowed => ResourceFindingCode::MimeNotAllowed,
|
||||
Self::KindMismatch => ResourceFindingCode::KindMismatch,
|
||||
_ => ResourceFindingCode::ContentInvalidJson,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed Resource aggregate. Published-модель существует отдельным типом
|
||||
/// (`PublishedResourceVersion`) и не содержит внутренних ссылок (D-12).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Resource {
|
||||
pub resource_id: ResourceId,
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub kind: ResourceKind,
|
||||
pub mime_type: String,
|
||||
pub sensitivity: ResourceSensitivity,
|
||||
pub status: ResourceStatus,
|
||||
pub current_draft_version: u32,
|
||||
pub created_at: time::OffsetDateTime,
|
||||
pub updated_at: time::OffsetDateTime,
|
||||
}
|
||||
|
||||
impl Resource {
|
||||
/// Новый Draft: ровно одна текущая черновая версия (D-15).
|
||||
pub fn draft(resource_id: ResourceId, metadata: ResourceMetadata) -> Self {
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
Self {
|
||||
resource_id,
|
||||
uri: metadata.uri,
|
||||
name: metadata.name,
|
||||
description: metadata.description,
|
||||
kind: metadata.kind,
|
||||
mime_type: metadata.mime_type,
|
||||
sensitivity: metadata.sensitivity,
|
||||
status: ResourceStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(&self) -> ResourceStatus {
|
||||
self.status
|
||||
}
|
||||
|
||||
pub fn current_draft_version(&self) -> u32 {
|
||||
self.current_draft_version
|
||||
}
|
||||
|
||||
pub fn metadata(&self) -> ResourceMetadata {
|
||||
ResourceMetadata {
|
||||
uri: self.uri.clone(),
|
||||
name: self.name.clone(),
|
||||
description: self.description.clone(),
|
||||
kind: self.kind,
|
||||
mime_type: self.mime_type.clone(),
|
||||
sensitivity: self.sensitivity,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Черновая версия Resource: exact digest и metadata, без filesystem path,
|
||||
/// filename и mutable external reference (D-12).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceVersion {
|
||||
pub version: u32,
|
||||
pub kind: ResourceKind,
|
||||
pub mime_type: String,
|
||||
pub size_bytes: u64,
|
||||
pub digest: String,
|
||||
pub created_at: time::OffsetDateTime,
|
||||
pub superseded_at: Option<time::OffsetDateTime>,
|
||||
}
|
||||
|
||||
impl ResourceVersion {
|
||||
pub fn draft(
|
||||
version: u32,
|
||||
kind: ResourceKind,
|
||||
mime_type: String,
|
||||
size_bytes: u64,
|
||||
digest: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
version,
|
||||
kind,
|
||||
mime_type,
|
||||
size_bytes,
|
||||
digest,
|
||||
created_at: time::OffsetDateTime::now_utc(),
|
||||
superseded_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn version(&self) -> u32 {
|
||||
self.version
|
||||
}
|
||||
|
||||
pub fn digest(&self) -> &str {
|
||||
&self.digest
|
||||
}
|
||||
|
||||
pub fn size_bytes(&self) -> u64 {
|
||||
self.size_bytes
|
||||
}
|
||||
|
||||
pub fn is_current(&self) -> bool {
|
||||
self.superseded_at.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Immutable published-модель версии: конструируется только из Draft, мутирующих
|
||||
/// методов нет, внутренние ссылки не публикуются (D-12).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PublishedResourceVersion {
|
||||
version: u32,
|
||||
kind: ResourceKind,
|
||||
mime_type: String,
|
||||
size_bytes: u64,
|
||||
digest: String,
|
||||
}
|
||||
|
||||
impl PublishedResourceVersion {
|
||||
pub fn from_draft(draft: &ResourceVersion) -> Self {
|
||||
Self {
|
||||
version: draft.version,
|
||||
kind: draft.kind,
|
||||
mime_type: draft.mime_type.clone(),
|
||||
size_bytes: draft.size_bytes,
|
||||
digest: draft.digest.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn version(&self) -> u32 {
|
||||
self.version
|
||||
}
|
||||
|
||||
pub fn digest(&self) -> &str {
|
||||
&self.digest
|
||||
}
|
||||
|
||||
pub fn size_bytes(&self) -> u64 {
|
||||
self.size_bytes
|
||||
}
|
||||
}
|
||||
|
||||
pub mod publication;
|
||||
|
||||
pub mod template;
|
||||
|
||||
pub use publication::{publication_include_directives, publication_secret_findings};
|
||||
pub use template::{
|
||||
MAX_TEMPLATE_CACHE_BYTES, MAX_TEMPLATE_CACHE_TTL_MS, TEMPLATE_CACHE_SCOPE, TemplateCache,
|
||||
TemplateFailure, TemplateFailureOutcome, TemplateFinding, TemplateFindingCode,
|
||||
TemplateParameter, TemplateSource, TemplateSourceError, cache_policy_findings,
|
||||
parse_uri_template,
|
||||
};
|
||||
@@ -0,0 +1,289 @@
|
||||
//! Story 3.7 / AC02: publication policy детерминированно проверяет сохранённые
|
||||
//! bounded bytes — structural private keys, raw credential assignments и explicit
|
||||
//! `include:` reference directives. Никакой сети, расширения или исполнения
|
||||
//! содержимого и никакого универсального сканера.
|
||||
//!
|
||||
//! Модуль вынесен из `resource.rs`, чтобы файл оставался в пределах health-лимита
|
||||
//! (1000 строк) после добавления публикационной политики.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// Структурная secret-находка в сохранённых bytes: только общая категория,
|
||||
/// никогда не совпавший фрагмент. `None` — нарушений нет.
|
||||
///
|
||||
/// Любые bounded bytes безопасны для проверки: malformed/не-UTF-8 содержимое не
|
||||
/// паникует и не превращается в отказ хранилища (AC02).
|
||||
pub fn publication_secret_findings(bytes: &[u8]) -> Option<&'static str> {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
if contains_private_key_block(&text) {
|
||||
return Some("private_key");
|
||||
}
|
||||
if contains_raw_credential_assignment(&text)
|
||||
|| contains_json_raw_credential(&text)
|
||||
|| contains_bearer_token(&text)
|
||||
{
|
||||
return Some("raw_credential");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Explicit `include: <target>` директивы статического содержимого. Директива
|
||||
/// возвращается как цель; разрешение (workspace-local, только published metadata)
|
||||
/// выполняет вызывающая сторона. Обычные ссылки/проза директивами не являются.
|
||||
pub fn publication_include_directives(bytes: &[u8]) -> Vec<String> {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let mut directives = Vec::new();
|
||||
for line in text.lines() {
|
||||
let line = line.trim_start();
|
||||
let Some(rest) = line.strip_prefix("include:") else {
|
||||
continue;
|
||||
};
|
||||
let target = rest.split_whitespace().next().unwrap_or_default();
|
||||
directives.push(target.to_owned());
|
||||
}
|
||||
directives
|
||||
}
|
||||
|
||||
/// PEM-подобный private key block: `-----BEGIN <label>-----`, где label содержит
|
||||
/// `PRIVATE KEY` (RSA/EC/DSA/OPENSSH/ENCRYPTED/PGP-варианты).
|
||||
///
|
||||
/// Label ограничивается `MAX_LABEL_BYTES` **по границе UTF-8**: malformed
|
||||
/// содержимое без закрывающего маркера не паникует на многобайтовом символе.
|
||||
fn contains_private_key_block(text: &str) -> bool {
|
||||
const MARKER: &str = "-----BEGIN ";
|
||||
const MAX_LABEL_BYTES: usize = 96;
|
||||
let mut remaining = text;
|
||||
while let Some(index) = remaining.find(MARKER) {
|
||||
let after = &remaining[index + MARKER.len()..];
|
||||
let label_end = after
|
||||
.find("-----")
|
||||
.unwrap_or_else(|| bounded_prefix_len(after, MAX_LABEL_BYTES));
|
||||
let label = after[..label_end].to_ascii_uppercase();
|
||||
if label.contains("PRIVATE KEY") {
|
||||
return true;
|
||||
}
|
||||
remaining = &after[label_end..];
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Длина префикса не больше `max_bytes`, оканчивающаяся на границе UTF-8.
|
||||
fn bounded_prefix_len(text: &str, max_bytes: usize) -> usize {
|
||||
let mut end = text.len().min(max_bytes);
|
||||
while end > 0 && !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
end
|
||||
}
|
||||
|
||||
const CREDENTIAL_KEYS: &[&str] = &[
|
||||
"password",
|
||||
"passwd",
|
||||
"passphrase",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"api_secret",
|
||||
"secret_key",
|
||||
"client_secret",
|
||||
"credentials",
|
||||
"credential",
|
||||
"bearer_token",
|
||||
"token",
|
||||
"aws_access_key_id",
|
||||
"aws_secret_access_key",
|
||||
"aws_session_token",
|
||||
"access_token",
|
||||
"refresh_token",
|
||||
"auth_token",
|
||||
"authorization",
|
||||
"private_key",
|
||||
];
|
||||
|
||||
/// Raw credential assignment: `<credential-name> = <non-placeholder value>`
|
||||
/// (также `:` и JSON-форма `"name": "value"`). Слова категорий без значения,
|
||||
/// обычные ссылки и проза не являются нарушением. Минимальный размер значения и
|
||||
/// наличие цифры не освобождают от проверки: неплейсхолдерное значение считается
|
||||
/// сырым credential (TL F2).
|
||||
fn contains_raw_credential_assignment(text: &str) -> bool {
|
||||
text.lines().any(|line| {
|
||||
let Some((key, value)) = split_assignment(line) else {
|
||||
return false;
|
||||
};
|
||||
if !is_credential_key(&normalize_assignment_key(key)) {
|
||||
return false;
|
||||
}
|
||||
let value = normalize_assignment_value(value);
|
||||
!value.is_empty() && !is_placeholder_value(&value)
|
||||
})
|
||||
}
|
||||
|
||||
/// Семантический JSON: ключ распознаётся независимо от позиции в объекте и от
|
||||
/// JSON-экранирования (`"pass\u0077ord"`), значения — по декодированным строкам.
|
||||
/// Обычный текст и невалидный JSON сюда не попадают.
|
||||
fn contains_json_raw_credential(text: &str) -> bool {
|
||||
let trimmed = text.trim();
|
||||
if !trimmed.starts_with(['{', '[']) {
|
||||
return false;
|
||||
}
|
||||
let Ok(value) = serde_json::from_str::<Value>(trimmed) else {
|
||||
return false;
|
||||
};
|
||||
json_value_has_raw_credential(&value)
|
||||
}
|
||||
|
||||
fn json_value_has_raw_credential(value: &Value) -> bool {
|
||||
match value {
|
||||
Value::Object(map) => map.iter().any(|(key, value)| {
|
||||
if is_credential_key(&normalize_assignment_key(key))
|
||||
&& let Value::String(raw) = value
|
||||
{
|
||||
let raw = normalize_assignment_value(raw);
|
||||
return !raw.is_empty() && !is_placeholder_value(&raw);
|
||||
}
|
||||
json_value_has_raw_credential(value)
|
||||
}),
|
||||
Value::Array(items) => items.iter().any(json_value_has_raw_credential),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn split_assignment(line: &str) -> Option<(&str, &str)> {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty()
|
||||
|| trimmed.starts_with("http://")
|
||||
|| trimmed.starts_with("https://")
|
||||
|| trimmed.starts_with("crank://")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let equals = trimmed.find('=');
|
||||
let colon = trimmed.find(':');
|
||||
let index = match (equals, colon) {
|
||||
(Some(equals), Some(colon)) => equals.min(colon),
|
||||
(Some(equals), None) => equals,
|
||||
(None, Some(colon)) => colon,
|
||||
(None, None) => return None,
|
||||
};
|
||||
let (key, value) = trimmed.split_at(index);
|
||||
Some((key, &value[1..]))
|
||||
}
|
||||
|
||||
fn normalize_assignment_key(key: &str) -> String {
|
||||
key.trim()
|
||||
.trim_start_matches(|character: char| {
|
||||
matches!(character, '{' | '[' | '"' | '\'' | '-' | ' ' | '\t')
|
||||
})
|
||||
.trim_end_matches(|character: char| {
|
||||
matches!(character, '"' | '\'' | ' ' | '\t' | ',' | ';')
|
||||
})
|
||||
.replace(['-', '.'], "_")
|
||||
.to_ascii_lowercase()
|
||||
}
|
||||
|
||||
fn is_credential_key(key: &str) -> bool {
|
||||
CREDENTIAL_KEYS.contains(&key)
|
||||
|| [
|
||||
"_password",
|
||||
"_passwd",
|
||||
"_secret",
|
||||
"_token",
|
||||
"_api_key",
|
||||
"_access_key",
|
||||
]
|
||||
.iter()
|
||||
.any(|suffix| key.ends_with(suffix))
|
||||
}
|
||||
|
||||
fn normalize_assignment_value(value: &str) -> String {
|
||||
value
|
||||
.trim()
|
||||
.trim_start_matches(['"', '\'', ' '])
|
||||
.trim_end_matches(|character: char| {
|
||||
matches!(character, '"' | '\'' | ',' | '}' | ']' | ';' | ' ' | '\t')
|
||||
})
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
/// Схема `Bearer ` без учёта ASCII-регистра. Возвращает остаток срезом, без
|
||||
/// копии значения: вызывающей стороне нужен bounded разбор без аллокаций.
|
||||
fn strip_bearer_scheme(value: &str) -> Option<&str> {
|
||||
const SCHEME: &str = "bearer ";
|
||||
let head = value.get(..SCHEME.len())?;
|
||||
head.eq_ignore_ascii_case(SCHEME)
|
||||
.then(|| &value[SCHEME.len()..])
|
||||
}
|
||||
|
||||
fn is_placeholder_value(value: &str) -> bool {
|
||||
// R2-F1: повторяющиеся scheme-префиксы разбираются итеративно и срезами, а
|
||||
// lowercase-копия создаётся один раз после цикла. Рекурсивный вариант держал
|
||||
// копию каждого остатка и рос квадратично по памяти и глубине стека на
|
||||
// предельных stored bytes; здесь разбор линеен и не зависит от вложенности.
|
||||
let mut current = value;
|
||||
loop {
|
||||
if current.is_empty() {
|
||||
return true;
|
||||
}
|
||||
// Маска/многоточие/прочерк без единого алфавитно-цифрового символа — заглушка.
|
||||
if !current.chars().any(char::is_alphanumeric) {
|
||||
return true;
|
||||
}
|
||||
// `Authorization: Bearer ***` — заглушка того же вида с префиксом схемы.
|
||||
match strip_bearer_scheme(current) {
|
||||
Some(rest) => current = rest.trim(),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
let lowered = current.to_ascii_lowercase();
|
||||
lowered.starts_with('<')
|
||||
|| lowered.starts_with("${")
|
||||
|| lowered.starts_with("{{")
|
||||
|| lowered.starts_with("your-")
|
||||
|| lowered.starts_with("your_")
|
||||
|| matches!(
|
||||
lowered.as_str(),
|
||||
"null"
|
||||
| "none"
|
||||
| "undefined"
|
||||
| "changeme"
|
||||
| "change_me"
|
||||
| "placeholder"
|
||||
| "redacted"
|
||||
| "..."
|
||||
| "***"
|
||||
| "password"
|
||||
| "secret"
|
||||
| "token"
|
||||
| "example"
|
||||
| "your-password"
|
||||
| "your_password"
|
||||
| "your-token"
|
||||
| "your_token"
|
||||
| "your-api-key"
|
||||
| "your_api_key"
|
||||
)
|
||||
}
|
||||
|
||||
/// `Bearer <token>` с token-алфавитом и достаточной длиной; обычная прозаическая
|
||||
/// фраза «Bearer token» не является нарушением. Наличие цифры не требуется: raw
|
||||
/// credential без цифр — тот же raw credential (TL F2/F3).
|
||||
fn contains_bearer_token(text: &str) -> bool {
|
||||
let lowered = text.to_ascii_lowercase();
|
||||
let mut offset = 0;
|
||||
while let Some(index) = lowered[offset..].find("bearer ") {
|
||||
let start = offset + index + "bearer ".len();
|
||||
let token = text[start..].split_whitespace().next().unwrap_or_default();
|
||||
let token =
|
||||
token.trim_matches(|character: char| matches!(character, '"' | '\'' | ',' | ';'));
|
||||
if token.len() >= 16
|
||||
&& token.bytes().all(|byte| {
|
||||
byte.is_ascii_alphanumeric()
|
||||
|| matches!(byte, b'.' | b'_' | b'~' | b'+' | b'/' | b'-' | b'=')
|
||||
})
|
||||
&& !is_placeholder_value(token)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
offset = start;
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
//! Story 3.10 (FR-16) — REST-backed Resource template definition.
|
||||
//!
|
||||
//! Шаблон не исполняет REST: он фиксирует точную Published версию Operation,
|
||||
//! форму собственного `crank://` URI, typed параметры, cache/failure policy.
|
||||
//! Здесь живёт только доменный контракт (типы, грамматика, пределы, коды
|
||||
//! findings); типизация `schema` через `crank_schema` и сверка с pinned
|
||||
//! Operation Version выполняются в admin-api, где этот wire-тип уже доступен.
|
||||
//!
|
||||
//! Структурная проверка (`parse`) возвращает точное поле отказа: wire-код
|
||||
//! `resource_source_invalid` назначает admin-api.
|
||||
//!
|
||||
//! Инварианты безопасности:
|
||||
//! - `uri_template` — отдельный `crank://` URI, authority всегда литерал;
|
||||
//! host/scheme/query/fragment/userinfo/port невозможны;
|
||||
//! - произвольные URL/inline request/headers/body в определении отсутствуют;
|
||||
//! - cache scope фиксирован сервером (`workspace_agent_auth`), клиент его не задаёт;
|
||||
//! - failure outcome — только `error` (никакого fallback-содержимого).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::resource::{MAX_RESOURCE_URI_BYTES, RESOURCE_STORAGE_CEILING};
|
||||
|
||||
/// Верхняя граница cache TTL шаблона (24 h): предел устаревания данных заказа.
|
||||
pub const MAX_TEMPLATE_CACHE_TTL_MS: u64 = 24 * 60 * 60 * 1000;
|
||||
/// Предел рендеренного ответа = существующий storage ceiling (второй лимит не вводится).
|
||||
pub const MAX_TEMPLATE_CACHE_BYTES: u64 = RESOURCE_STORAGE_CEILING as u64;
|
||||
/// Нормализованный (серверный) cache scope: workspace + Agent + auth/credential identity.
|
||||
pub const TEMPLATE_CACHE_SCOPE: &str = "workspace_agent_auth";
|
||||
/// Та же граница, что у static URI (D-10): шаблон не длиннее обычного Resource URI.
|
||||
pub const MAX_TEMPLATE_URI_BYTES: usize = MAX_RESOURCE_URI_BYTES;
|
||||
/// Верхняя граница идентификатора Operation в ссылке шаблона.
|
||||
pub const MAX_TEMPLATE_OPERATION_ID_BYTES: usize = 128;
|
||||
|
||||
const URI_PREFIX: &str = "crank://";
|
||||
const SOURCE_FIELDS: [&str; 6] = [
|
||||
"operation_id",
|
||||
"operation_version",
|
||||
"uri_template",
|
||||
"parameters",
|
||||
"cache",
|
||||
"failure",
|
||||
];
|
||||
const PARAMETER_FIELDS: [&str; 3] = ["name", "input_path", "schema"];
|
||||
const CACHE_FIELDS: [&str; 3] = ["ttl_ms", "vary", "max_bytes"];
|
||||
|
||||
/// Сохранённое определение шаблона. Порядок полей фиксирован, поэтому
|
||||
/// канонический JSON и digest определения детерминированы.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TemplateSource {
|
||||
pub operation_id: String,
|
||||
pub operation_version: u32,
|
||||
pub uri_template: String,
|
||||
pub parameters: Vec<TemplateParameter>,
|
||||
pub cache: TemplateCache,
|
||||
pub failure: TemplateFailure,
|
||||
}
|
||||
|
||||
/// Параметр шаблона: имя placeholder, адрес поля pinned `input_schema` и typed schema.
|
||||
/// `schema` остаётся каноническим JSON: типизация выполняется shared `crank_schema`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TemplateParameter {
|
||||
pub name: String,
|
||||
pub input_path: String,
|
||||
pub schema: Value,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TemplateCache {
|
||||
pub ttl_ms: u64,
|
||||
pub vary: Vec<String>,
|
||||
pub max_bytes: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TemplateFailure {
|
||||
pub outcome: TemplateFailureOutcome,
|
||||
}
|
||||
|
||||
/// Только `error`: arbitrary fallback-содержимого у шаблона нет (fail closed).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TemplateFailureOutcome {
|
||||
Error,
|
||||
}
|
||||
|
||||
/// Структурный отказ определения: точное поле, которое называет wire-ответ.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct TemplateSourceError {
|
||||
field: &'static str,
|
||||
}
|
||||
|
||||
impl TemplateSourceError {
|
||||
const fn new(field: &'static str) -> Self {
|
||||
Self { field }
|
||||
}
|
||||
|
||||
pub fn field(&self) -> &'static str {
|
||||
self.field
|
||||
}
|
||||
}
|
||||
|
||||
impl TemplateSource {
|
||||
/// Структурный разбор `metadata.source`. Любой неизвестный ключ (включая
|
||||
/// URL/inline request/headers/body и расширяющие cache scope поля) — отказ.
|
||||
pub fn parse(value: &Value) -> Result<Self, TemplateSourceError> {
|
||||
let object = value
|
||||
.as_object()
|
||||
.ok_or_else(|| TemplateSourceError::new("source"))?;
|
||||
for key in object.keys() {
|
||||
if !SOURCE_FIELDS.contains(&key.as_str()) {
|
||||
return Err(TemplateSourceError::new(top_level_unknown_field(key)));
|
||||
}
|
||||
}
|
||||
let operation_id = object
|
||||
.get("operation_id")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.is_empty() && value.len() <= MAX_TEMPLATE_OPERATION_ID_BYTES)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.operation_id"))?
|
||||
.to_owned();
|
||||
let operation_version = object
|
||||
.get("operation_version")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| u32::try_from(value).ok())
|
||||
.filter(|value| *value >= 1)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.operation_version"))?;
|
||||
let uri_template = object
|
||||
.get("uri_template")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.uri_template"))?;
|
||||
parse_uri_template(uri_template)
|
||||
.map_err(|_| TemplateSourceError::new("source.uri_template"))?;
|
||||
let parameters = parse_parameters(object.get("parameters"))?;
|
||||
let cache = parse_cache(object.get("cache"))?;
|
||||
let failure = parse_failure(object.get("failure"))?;
|
||||
Ok(Self {
|
||||
operation_id,
|
||||
operation_version,
|
||||
uri_template: uri_template.to_owned(),
|
||||
parameters,
|
||||
cache,
|
||||
failure,
|
||||
})
|
||||
}
|
||||
|
||||
/// Имена параметров шаблона (для сверки с placeholders/vary).
|
||||
pub fn parameter_names(&self) -> BTreeSet<&str> {
|
||||
self.parameters
|
||||
.iter()
|
||||
.map(|parameter| parameter.name.as_str())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Cache policy findings (AC4): TTL/size bounded exported constants, `vary`
|
||||
/// обязан покрывать каждый параметр ровно один раз и не содержать чужих имён.
|
||||
/// Чистая функция: same rules для preview и publish, без обращения к Operation.
|
||||
pub fn cache_policy_findings(
|
||||
cache: &TemplateCache,
|
||||
parameter_names: &BTreeSet<&str>,
|
||||
) -> Vec<TemplateFinding> {
|
||||
let mut findings = Vec::new();
|
||||
if cache.ttl_ms == 0 || cache.ttl_ms > MAX_TEMPLATE_CACHE_TTL_MS {
|
||||
findings.push(TemplateFinding::new(
|
||||
TemplateFindingCode::CacheTtlInvalid,
|
||||
"source.cache.ttl_ms",
|
||||
));
|
||||
}
|
||||
if cache.max_bytes == 0 || cache.max_bytes > MAX_TEMPLATE_CACHE_BYTES {
|
||||
findings.push(TemplateFinding::new(
|
||||
TemplateFindingCode::CacheSizeInvalid,
|
||||
"source.cache.max_bytes",
|
||||
));
|
||||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
for name in &cache.vary {
|
||||
if !seen.insert(name.as_str()) {
|
||||
findings.push(TemplateFinding::new(
|
||||
TemplateFindingCode::VaryDuplicate,
|
||||
"source.cache.vary",
|
||||
));
|
||||
} else if !parameter_names.contains(name.as_str()) {
|
||||
findings.push(TemplateFinding::new(
|
||||
TemplateFindingCode::VaryUnknown,
|
||||
"source.cache.vary",
|
||||
));
|
||||
}
|
||||
}
|
||||
if parameter_names.iter().any(|name| !seen.contains(name)) {
|
||||
findings.push(TemplateFinding::new(
|
||||
TemplateFindingCode::VaryIncomplete,
|
||||
"source.cache.vary",
|
||||
));
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
fn top_level_unknown_field(key: &str) -> &'static str {
|
||||
match key {
|
||||
"agent_scope" => "source.agent_scope",
|
||||
"auth_independent" => "source.auth_independent",
|
||||
_ => "source",
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_parameters(value: Option<&Value>) -> Result<Vec<TemplateParameter>, TemplateSourceError> {
|
||||
let items = value
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.parameters"))?;
|
||||
let mut parameters = Vec::with_capacity(items.len());
|
||||
for item in items {
|
||||
let object = item
|
||||
.as_object()
|
||||
.ok_or_else(|| TemplateSourceError::new("source.parameters"))?;
|
||||
require_only_fields(object, &PARAMETER_FIELDS, "source.parameters")?;
|
||||
let name = object
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| parameter_name_is_valid(value))
|
||||
.ok_or_else(|| TemplateSourceError::new("source.parameters"))?
|
||||
.to_owned();
|
||||
let input_path = object
|
||||
.get("input_path")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| input_path_is_valid(value))
|
||||
.ok_or_else(|| TemplateSourceError::new("source.parameters"))?
|
||||
.to_owned();
|
||||
let schema = object
|
||||
.get("schema")
|
||||
.filter(|value| value.is_object())
|
||||
.ok_or_else(|| TemplateSourceError::new("source.parameters"))?
|
||||
.clone();
|
||||
parameters.push(TemplateParameter {
|
||||
name,
|
||||
input_path,
|
||||
schema,
|
||||
});
|
||||
}
|
||||
Ok(parameters)
|
||||
}
|
||||
|
||||
fn parse_cache(value: Option<&Value>) -> Result<TemplateCache, TemplateSourceError> {
|
||||
let object = value
|
||||
.and_then(Value::as_object)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.cache"))?;
|
||||
for key in object.keys() {
|
||||
if !CACHE_FIELDS.contains(&key.as_str()) {
|
||||
return Err(TemplateSourceError::new(cache_unknown_field(key)));
|
||||
}
|
||||
}
|
||||
let ttl_ms = object
|
||||
.get("ttl_ms")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.cache.ttl_ms"))?;
|
||||
let max_bytes = object
|
||||
.get("max_bytes")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.cache.max_bytes"))?;
|
||||
let vary = object
|
||||
.get("vary")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.cache.vary"))?
|
||||
.iter()
|
||||
.map(|item| {
|
||||
item.as_str()
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.cache.vary"))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(TemplateCache {
|
||||
ttl_ms,
|
||||
vary,
|
||||
max_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
fn cache_unknown_field(key: &str) -> &'static str {
|
||||
match key {
|
||||
"scope" => "source.cache.scope",
|
||||
"shared" => "source.cache.shared",
|
||||
"cross_workspace" => "source.cache.cross_workspace",
|
||||
"agent_scope" => "source.cache.agent_scope",
|
||||
"auth_independent" => "source.cache.auth_independent",
|
||||
_ => "source.cache",
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_failure(value: Option<&Value>) -> Result<TemplateFailure, TemplateSourceError> {
|
||||
let object = value
|
||||
.and_then(Value::as_object)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.failure"))?;
|
||||
require_only_fields(object, &["outcome"], "source.failure")?;
|
||||
let outcome = object
|
||||
.get("outcome")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| TemplateSourceError::new("source.failure"))?;
|
||||
if outcome != "error" {
|
||||
return Err(TemplateSourceError::new("source.failure.outcome"));
|
||||
}
|
||||
Ok(TemplateFailure {
|
||||
outcome: TemplateFailureOutcome::Error,
|
||||
})
|
||||
}
|
||||
|
||||
fn require_only_fields(
|
||||
object: &Map<String, Value>,
|
||||
allowed: &[&str],
|
||||
field: &'static str,
|
||||
) -> Result<(), TemplateSourceError> {
|
||||
if object.keys().any(|key| !allowed.contains(&key.as_str())) {
|
||||
return Err(TemplateSourceError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Отказ грамматики `crank://`-шаблона (поле называет wire-ответ).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct InvalidUriTemplate;
|
||||
|
||||
impl std::fmt::Display for InvalidUriTemplate {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("resource uri template is invalid")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidUriTemplate {}
|
||||
|
||||
/// Грамматика `crank://<authority>/<path>`: authority — фиксированный литерал,
|
||||
/// placeholders только целым path-сегментом. Возвращает имена placeholders в порядке
|
||||
/// появления. Любая другая схема/хост-инъекция/query/fragment — отказ.
|
||||
pub fn parse_uri_template(value: &str) -> Result<Vec<String>, InvalidUriTemplate> {
|
||||
if value.len() > MAX_TEMPLATE_URI_BYTES {
|
||||
return Err(InvalidUriTemplate);
|
||||
}
|
||||
let rest = value.strip_prefix(URI_PREFIX).ok_or(InvalidUriTemplate)?;
|
||||
if rest.contains('?') || rest.contains('#') {
|
||||
return Err(InvalidUriTemplate);
|
||||
}
|
||||
let (authority, path) = rest.split_once('/').ok_or(InvalidUriTemplate)?;
|
||||
if !authority_is_valid(authority) || path.is_empty() {
|
||||
return Err(InvalidUriTemplate);
|
||||
}
|
||||
let mut placeholders = Vec::new();
|
||||
for segment in path.split('/') {
|
||||
if segment.is_empty() {
|
||||
return Err(InvalidUriTemplate);
|
||||
}
|
||||
if segment.contains('{') || segment.contains('}') {
|
||||
let name = segment
|
||||
.strip_prefix('{')
|
||||
.and_then(|value| value.strip_suffix('}'))
|
||||
.ok_or(InvalidUriTemplate)?;
|
||||
if !parameter_name_is_valid(name) {
|
||||
return Err(InvalidUriTemplate);
|
||||
}
|
||||
placeholders.push(name.to_owned());
|
||||
continue;
|
||||
}
|
||||
if !literal_segment_is_valid(segment) {
|
||||
return Err(InvalidUriTemplate);
|
||||
}
|
||||
}
|
||||
Ok(placeholders)
|
||||
}
|
||||
|
||||
fn authority_is_valid(authority: &str) -> bool {
|
||||
let bytes = authority.as_bytes();
|
||||
if bytes.is_empty() || bytes.len() > 63 {
|
||||
return false;
|
||||
}
|
||||
let first = bytes[0] as char;
|
||||
let last = bytes[bytes.len() - 1] as char;
|
||||
let edge = |value: char| value.is_ascii_lowercase() || value.is_ascii_digit();
|
||||
edge(first)
|
||||
&& edge(last)
|
||||
&& bytes
|
||||
.iter()
|
||||
.all(|byte| matches!(*byte as char, 'a'..='z' | '0'..='9' | '.' | '-'))
|
||||
}
|
||||
|
||||
fn literal_segment_is_valid(segment: &str) -> bool {
|
||||
segment != ".."
|
||||
&& segment
|
||||
.chars()
|
||||
.all(|value| value.is_ascii_alphanumeric() || matches!(value, '.' | '_' | '~' | '-'))
|
||||
}
|
||||
|
||||
/// Имя placeholder/параметра: `[a-z][a-z0-9_]{0,63}`.
|
||||
pub fn parameter_name_is_valid(value: &str) -> bool {
|
||||
let mut chars = value.chars();
|
||||
match chars.next() {
|
||||
Some(first) if first.is_ascii_lowercase() => {}
|
||||
_ => return false,
|
||||
}
|
||||
value.len() <= 64
|
||||
&& chars.all(|value| value.is_ascii_lowercase() || value.is_ascii_digit() || value == '_')
|
||||
}
|
||||
|
||||
/// `input_path` адресует поле pinned `input_schema`: `<root>.<field>[.<field>...]`.
|
||||
pub fn input_path_is_valid(value: &str) -> bool {
|
||||
let mut segments = value.split('.');
|
||||
let root = segments.next().unwrap_or_default();
|
||||
if root != "input" {
|
||||
return false;
|
||||
}
|
||||
let mut count = 0;
|
||||
for segment in segments {
|
||||
if segment.is_empty()
|
||||
|| !segment
|
||||
.chars()
|
||||
.all(|item| item.is_ascii_alphanumeric() || item == '_')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
count > 0
|
||||
}
|
||||
|
||||
/// Blocker finding публикации шаблона: стабильный код и поле.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TemplateFinding {
|
||||
pub code: TemplateFindingCode,
|
||||
pub field: &'static str,
|
||||
}
|
||||
|
||||
impl TemplateFinding {
|
||||
pub fn new(code: TemplateFindingCode, field: &'static str) -> Self {
|
||||
Self { code, field }
|
||||
}
|
||||
|
||||
pub fn code(&self) -> &'static str {
|
||||
self.code.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocker-коды публикации/предпросмотра шаблона (wire-строки).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum TemplateFindingCode {
|
||||
#[serde(rename = "resource_source_not_read_safe")]
|
||||
NotReadSafe,
|
||||
#[serde(rename = "resource_source_parameter_unknown")]
|
||||
ParameterUnknown,
|
||||
#[serde(rename = "resource_source_parameter_unmapped")]
|
||||
ParameterUnmapped,
|
||||
#[serde(rename = "resource_source_parameter_duplicate")]
|
||||
ParameterDuplicate,
|
||||
#[serde(rename = "resource_source_parameter_type_mismatch")]
|
||||
ParameterTypeMismatch,
|
||||
#[serde(rename = "resource_source_parameter_default_invalid")]
|
||||
ParameterDefaultInvalid,
|
||||
#[serde(rename = "resource_source_parameter_optional_without_default")]
|
||||
ParameterOptionalWithoutDefault,
|
||||
#[serde(rename = "resource_source_cache_ttl_invalid")]
|
||||
CacheTtlInvalid,
|
||||
#[serde(rename = "resource_source_cache_size_invalid")]
|
||||
CacheSizeInvalid,
|
||||
#[serde(rename = "resource_source_vary_unknown")]
|
||||
VaryUnknown,
|
||||
#[serde(rename = "resource_source_vary_duplicate")]
|
||||
VaryDuplicate,
|
||||
#[serde(rename = "resource_source_vary_incomplete")]
|
||||
VaryIncomplete,
|
||||
}
|
||||
|
||||
impl TemplateFindingCode {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::NotReadSafe => "resource_source_not_read_safe",
|
||||
Self::ParameterUnknown => "resource_source_parameter_unknown",
|
||||
Self::ParameterUnmapped => "resource_source_parameter_unmapped",
|
||||
Self::ParameterDuplicate => "resource_source_parameter_duplicate",
|
||||
Self::ParameterTypeMismatch => "resource_source_parameter_type_mismatch",
|
||||
Self::ParameterDefaultInvalid => "resource_source_parameter_default_invalid",
|
||||
Self::ParameterOptionalWithoutDefault => {
|
||||
"resource_source_parameter_optional_without_default"
|
||||
}
|
||||
Self::CacheTtlInvalid => "resource_source_cache_ttl_invalid",
|
||||
Self::CacheSizeInvalid => "resource_source_cache_size_invalid",
|
||||
Self::VaryUnknown => "resource_source_vary_unknown",
|
||||
Self::VaryDuplicate => "resource_source_vary_duplicate",
|
||||
Self::VaryIncomplete => "resource_source_vary_incomplete",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn valid_source() -> Value {
|
||||
json!({
|
||||
"operation_id": "op_demo",
|
||||
"operation_version": 1,
|
||||
"uri_template": "crank://orders/{order_id}",
|
||||
"parameters": [{
|
||||
"name": "order_id",
|
||||
"input_path": "input.order_id",
|
||||
"schema": { "type": "string", "required": true, "format": "uuid" }
|
||||
}],
|
||||
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
|
||||
"failure": { "outcome": "error" }
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_source_roundtrips_and_keeps_schema_facts() {
|
||||
let value = valid_source();
|
||||
let parsed = TemplateSource::parse(&value).expect("valid source must parse");
|
||||
assert_eq!(parsed.operation_version, 1);
|
||||
assert_eq!(parsed.parameters[0].schema["format"], json!("uuid"));
|
||||
let encoded = serde_json::to_value(&parsed).expect("source must serialize");
|
||||
assert_eq!(
|
||||
encoded, value,
|
||||
"canonical definition must roundtrip without loss"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_fields_and_inline_request_are_denied() {
|
||||
for (field, value) in [
|
||||
("url", json!("https://evil.example")),
|
||||
("base_url", json!("https://evil.example")),
|
||||
("host", json!("evil.example")),
|
||||
("method", json!("POST")),
|
||||
("headers", json!({ "authorization": "x" })),
|
||||
("body", json!({ "a": 1 })),
|
||||
("request", json!({ "url": "https://evil.example" })),
|
||||
] {
|
||||
let mut source = valid_source();
|
||||
source[field] = value;
|
||||
let error = TemplateSource::parse(&source).expect_err("unknown field must fail");
|
||||
assert_eq!(error.field(), "source", "field `{field}`");
|
||||
}
|
||||
let mut nested = valid_source();
|
||||
nested["cache"]["headers"] = json!({ "host": "evil.example" });
|
||||
assert_eq!(
|
||||
TemplateSource::parse(&nested)
|
||||
.expect_err("nested unknown")
|
||||
.field(),
|
||||
"source.cache"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widening_scope_keys_are_named_in_the_rejection() {
|
||||
for (key, expected) in [
|
||||
("scope", "source.cache.scope"),
|
||||
("shared", "source.cache.shared"),
|
||||
("cross_workspace", "source.cache.cross_workspace"),
|
||||
("agent_scope", "source.cache.agent_scope"),
|
||||
("auth_independent", "source.cache.auth_independent"),
|
||||
] {
|
||||
let mut source = valid_source();
|
||||
source["cache"][key] = json!(true);
|
||||
assert_eq!(
|
||||
TemplateSource::parse(&source)
|
||||
.expect_err("widening")
|
||||
.field(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
let mut source = valid_source();
|
||||
source["agent_scope"] = json!("any");
|
||||
assert_eq!(
|
||||
TemplateSource::parse(&source)
|
||||
.expect_err("widening")
|
||||
.field(),
|
||||
"source.agent_scope"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_constants_are_single_sourced_and_bounded() {
|
||||
assert_eq!(MAX_TEMPLATE_CACHE_TTL_MS, 86_400_000);
|
||||
assert_eq!(MAX_TEMPLATE_CACHE_BYTES, RESOURCE_STORAGE_CEILING as u64);
|
||||
assert_eq!(TEMPLATE_CACHE_SCOPE, "workspace_agent_auth");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uri_template_grammar_rejects_host_scheme_and_traversal() {
|
||||
assert_eq!(
|
||||
parse_uri_template("crank://orders/{order_id}/items/{item}"),
|
||||
Ok(vec!["order_id".to_owned(), "item".to_owned()])
|
||||
);
|
||||
for rejected in [
|
||||
"https://evil.example/orders/{order_id}",
|
||||
"//evil.example/orders/{order_id}",
|
||||
"crank://user@{order_id}/orders",
|
||||
"crank://host:8080/orders/{order_id}",
|
||||
"crank://host/orders?q={order_id}",
|
||||
"crank://host/orders/{order_id}#fragment",
|
||||
"crank://host/../{order_id}",
|
||||
"crank://host//orders/{order_id}",
|
||||
"crank://ho{st}/orders/{order_id}",
|
||||
"crank://host/orders/{Order_ID}",
|
||||
"crank://host/orders/{order_id",
|
||||
"CRANK://host/orders/{order_id}",
|
||||
] {
|
||||
assert!(parse_uri_template(rejected).is_err(), "{rejected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
mod unit {
|
||||
mod prompt;
|
||||
mod prompt_composition;
|
||||
mod resource_drafts;
|
||||
mod resource_template;
|
||||
mod tool_catalog;
|
||||
mod tool_quality;
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
use crank_core::prompt::{
|
||||
PromptDefinition, PromptDraft, PromptError, PromptMessage, PromptRole, PromptSensitivity,
|
||||
PromptStatus,
|
||||
};
|
||||
use serde_json::{Map, json};
|
||||
|
||||
fn definition() -> serde_json::Value {
|
||||
json!({
|
||||
"name": "welcome",
|
||||
"description": "Greeting",
|
||||
"arguments": [
|
||||
{"name":"name", "schema":{"type":"string"}, "required":true},
|
||||
{"name":"tone", "schema":{"type":"string", "enum":["warm","plain"]}, "required":false, "default":"warm"}
|
||||
],
|
||||
"messages": [
|
||||
{"role":"system", "content":"Be {{tone}}."},
|
||||
{"role":"user", "content":"Welcome {{name}}."}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_prompt_draft_preserves_roles_order_and_typed_rendering() {
|
||||
let prompt = PromptDefinition::parse(&definition()).unwrap();
|
||||
let args = Map::from_iter([("name".into(), json!("Ada"))]);
|
||||
assert_eq!(
|
||||
prompt.preview(&args).unwrap(),
|
||||
vec![
|
||||
PromptMessage {
|
||||
role: PromptRole::System,
|
||||
content: "Be warm.".into(),
|
||||
resource_refs: vec![],
|
||||
},
|
||||
PromptMessage {
|
||||
role: PromptRole::User,
|
||||
content: "Welcome Ada.".into(),
|
||||
resource_refs: vec![],
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
prompt.preview(&args).unwrap(),
|
||||
prompt.preview(&args).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_optional_argument_without_default_is_not_required() {
|
||||
let mut value = definition();
|
||||
value["arguments"][1]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("default");
|
||||
let prompt = PromptDefinition::parse(&value).unwrap();
|
||||
let args = Map::from_iter([("name".into(), json!("Ada"))]);
|
||||
assert_eq!(prompt.preview(&args).unwrap()[0].content, "Be .");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_prompt_draft_has_typed_identity_lifecycle_and_snapshot() {
|
||||
let draft = PromptDraft::new(
|
||||
crank_core::ids::PromptId::new("prm_example"),
|
||||
PromptSensitivity::Internal,
|
||||
PromptDefinition::parse(&definition()).unwrap(),
|
||||
);
|
||||
assert_eq!(draft.prompt_id().as_str(), "prm_example");
|
||||
assert_eq!(draft.version(), 1);
|
||||
assert_eq!(draft.status(), PromptStatus::Draft);
|
||||
assert_eq!(draft.sensitivity(), PromptSensitivity::Internal);
|
||||
let published = draft.published_snapshot();
|
||||
assert_eq!(published.prompt_id().as_str(), "prm_example");
|
||||
assert_eq!(published.version(), 1);
|
||||
assert_eq!(published.definition().name(), "welcome");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story313_published_snapshot_keeps_the_v1_value_when_a_second_draft_version_exists() {
|
||||
let v1_definition = PromptDefinition::parse(&definition()).unwrap();
|
||||
let snapshot = PromptDraft::from_parts(
|
||||
crank_core::ids::PromptId::new("prm_story313"),
|
||||
1,
|
||||
PromptStatus::Draft,
|
||||
PromptSensitivity::Internal,
|
||||
v1_definition.clone(),
|
||||
)
|
||||
.unwrap()
|
||||
.published_snapshot();
|
||||
|
||||
let mut edited = definition();
|
||||
edited["description"] = json!("Edited after publication");
|
||||
edited["arguments"][0]["required"] = json!(false);
|
||||
edited["messages"][1]["content"] = json!("Count {{name}}.");
|
||||
let next_draft = PromptDraft::from_parts(
|
||||
crank_core::ids::PromptId::new("prm_story313"),
|
||||
2,
|
||||
PromptStatus::Draft,
|
||||
PromptSensitivity::Internal,
|
||||
PromptDefinition::parse(&edited).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Опубликованный value-снимок сохраняет точное значение v1 …
|
||||
assert_eq!(snapshot.version(), 1);
|
||||
assert_eq!(snapshot.definition(), &v1_definition);
|
||||
assert_eq!(snapshot.definition().description(), "Greeting");
|
||||
assert!(snapshot.definition().arguments()[0].required());
|
||||
assert_eq!(
|
||||
snapshot.definition().arguments()[1].default(),
|
||||
Some(&json!("warm"))
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.definition().messages()[1].content,
|
||||
"Welcome {{name}}."
|
||||
);
|
||||
// … а новая Draft-версия несёт уже изменённое значение.
|
||||
assert_eq!(next_draft.version(), 2);
|
||||
assert_ne!(next_draft.definition(), snapshot.definition());
|
||||
assert_eq!(
|
||||
next_draft.definition().messages()[1].content,
|
||||
"Count {{name}}."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_integer_arguments_are_rendered_as_scalar_values() {
|
||||
let mut value = definition();
|
||||
value["arguments"][0]["schema"]["type"] = json!("integer");
|
||||
value["messages"][1]["content"] = json!("Count {{name}}.");
|
||||
let prompt = PromptDefinition::parse(&value).unwrap();
|
||||
let args = Map::from_iter([("name".into(), json!(7))]);
|
||||
assert_eq!(prompt.preview(&args).unwrap()[1].content, "Count 7.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_boolean_and_number_arguments_render_as_json_scalars() {
|
||||
let mut value = definition();
|
||||
value["arguments"][0]["schema"]["type"] = json!("number");
|
||||
value["arguments"].as_array_mut().unwrap().push(json!({
|
||||
"name":"enabled", "schema":{"type":"boolean"}, "required":true
|
||||
}));
|
||||
value["messages"][1]["content"] = json!("Value={{name}}, enabled={{enabled}}");
|
||||
let prompt = PromptDefinition::parse(&value).unwrap();
|
||||
let args = Map::from_iter([("name".into(), json!(2.5)), ("enabled".into(), json!(true))]);
|
||||
assert_eq!(
|
||||
prompt.preview(&args).unwrap()[1].content,
|
||||
"Value=2.5, enabled=true"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_rejects_malformed_enum_schema_instead_of_dropping_constraint() {
|
||||
let mut value = definition();
|
||||
value["arguments"][1]["schema"]["enum"] = json!("not-an-array");
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&value),
|
||||
Err(PromptError::InvalidDefinition)
|
||||
);
|
||||
let mut value = definition();
|
||||
value["arguments"][1]["schema"]["enum"] = json!(["valid", 42]);
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&value),
|
||||
Err(PromptError::InvalidDefinition)
|
||||
);
|
||||
let mut value = definition();
|
||||
value["arguments"][1]["schema"]["maxLength"] = json!(8);
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&value),
|
||||
Err(PromptError::InvalidDefinition)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_preview_bounds_final_rendered_output() {
|
||||
let mut value = definition();
|
||||
value["messages"][0]["content"] = json!("{{name}}{{name}}");
|
||||
let prompt = PromptDefinition::parse(&value).unwrap();
|
||||
let args = Map::from_iter([("name".into(), json!("x".repeat(9_000)))]);
|
||||
assert_eq!(prompt.preview(&args), Err(PromptError::InvalidTemplate));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_invalid_args_fail_before_any_rendered_messages() {
|
||||
let prompt = PromptDefinition::parse(&definition()).unwrap();
|
||||
assert_eq!(
|
||||
prompt.preview(&Map::new()),
|
||||
Err(PromptError::MissingArgument("name".into()))
|
||||
);
|
||||
let mut args = Map::from_iter([("name".into(), json!("Ada")), ("extra".into(), json!(1))]);
|
||||
assert_eq!(
|
||||
prompt.preview(&args),
|
||||
Err(PromptError::UnknownArgument("extra".into()))
|
||||
);
|
||||
args.remove("extra");
|
||||
args.insert("tone".into(), json!("loud"));
|
||||
assert_eq!(
|
||||
prompt.preview(&args),
|
||||
Err(PromptError::InvalidArgument("tone".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_rejects_duplicate_arguments_unknown_roles_and_executable_templates() {
|
||||
let mut value = definition();
|
||||
value["arguments"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!({"name":"name","schema":{"type":"string"},"required":true}));
|
||||
assert!(PromptDefinition::parse(&value).is_err());
|
||||
let mut value = definition();
|
||||
value["messages"][0]["role"] = json!("developer");
|
||||
assert!(PromptDefinition::parse(&value).is_err());
|
||||
let mut value = definition();
|
||||
value["messages"][0]["content"] = json!("{{= dangerous() }}");
|
||||
assert!(PromptDefinition::parse(&value).is_err());
|
||||
}
|
||||
|
||||
fn defaulted(default: serde_json::Value) -> serde_json::Value {
|
||||
json!({
|
||||
"name": "welcome",
|
||||
"description": "Greeting",
|
||||
"arguments": [{"name":"tone","schema":{"type":"string"},"required":false,"default":default}],
|
||||
"messages": [{"role":"user","content":"{{tone}}"}]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_default_values_fit_the_stored_json_text_size() {
|
||||
// Storage keeps `octet_length(default_value::text) <= 16384`; JSON adds the
|
||||
// surrounding quotes, so 16382 bytes of plain text is the exact ceiling.
|
||||
let at_limit = defaulted(json!("a".repeat(16_382)));
|
||||
let prompt =
|
||||
PromptDefinition::parse(&at_limit).expect("the exact storage boundary is accepted");
|
||||
let rendered = prompt
|
||||
.preview(&Map::new())
|
||||
.expect("bounded default previews");
|
||||
assert_eq!(rendered[0].content.len(), 16_382);
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted(json!("a".repeat(16_383)))),
|
||||
Err(PromptError::InvalidDefinition)
|
||||
);
|
||||
|
||||
// Escaped content costs more than one byte per character in PostgreSQL.
|
||||
assert!(PromptDefinition::parse(&defaulted(json!("\"".repeat(8_190)))).is_ok());
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted(json!("\"".repeat(8_192)))),
|
||||
Err(PromptError::InvalidDefinition)
|
||||
);
|
||||
assert!(PromptDefinition::parse(&defaulted(json!("\u{1}".repeat(2_730)))).is_ok());
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted(json!("\u{1}".repeat(2_731)))),
|
||||
Err(PromptError::InvalidDefinition)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_short_escape_defaults_match_the_postgres_jsonb_text_size() {
|
||||
// PostgreSQL writes LF/TAB/CR/BS/FF as two-byte short escapes, while other
|
||||
// control characters stay six-byte `\u00XX`, so both fit differently.
|
||||
for (label, unit) in [
|
||||
("lf", '\n'),
|
||||
("tab", '\t'),
|
||||
("cr", '\r'),
|
||||
("backspace", '\u{8}'),
|
||||
("formfeed", '\u{c}'),
|
||||
] {
|
||||
let at_limit = unit.to_string().repeat(8_191);
|
||||
let prompt = PromptDefinition::parse(&defaulted(json!(at_limit))).unwrap_or_else(|error| {
|
||||
panic!("{label} at the exact boundary must be accepted: {error:?}")
|
||||
});
|
||||
assert_eq!(
|
||||
prompt.preview(&Map::new()).unwrap()[0].content,
|
||||
unit.to_string().repeat(8_191),
|
||||
"{label} defaults must preview the original text"
|
||||
);
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted(json!(unit.to_string().repeat(8_192)))),
|
||||
Err(PromptError::InvalidDefinition),
|
||||
"{label} beyond the boundary is rejected"
|
||||
);
|
||||
}
|
||||
// A multiline default stays well inside the guard even though it is long.
|
||||
assert!(PromptDefinition::parse(&defaulted(json!("\n\t".repeat(4_000)))).is_ok());
|
||||
// 0x01 still costs six bytes, so only 2730 of them fit.
|
||||
assert!(PromptDefinition::parse(&defaulted(json!("\u{1}".repeat(2_730)))).is_ok());
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted(json!("\u{1}".repeat(2_731)))),
|
||||
Err(PromptError::InvalidDefinition)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_rejects_nul_before_storage_for_every_stored_string() {
|
||||
// PostgreSQL refuses U+0000 in `text` ("null character not permitted") and in
|
||||
// `jsonb` ("\\u0000 cannot be converted to text"), so it must fail as a
|
||||
// structured definition error before any SQL runs.
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted(json!("a\u{0}b"))),
|
||||
Err(PromptError::InvalidDefinition)
|
||||
);
|
||||
let mut enum_value = definition();
|
||||
enum_value["arguments"][1]["schema"]["enum"] = json!(["warm", "a\u{0}b"]);
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&enum_value),
|
||||
Err(PromptError::InvalidDefinition),
|
||||
"an enum value is stored as jsonb and must not carry U+0000"
|
||||
);
|
||||
for (label, mutate) in [
|
||||
(
|
||||
"name",
|
||||
Box::new(|value: &mut serde_json::Value| value["name"] = json!("a\u{0}b"))
|
||||
as Box<dyn Fn(&mut serde_json::Value)>,
|
||||
),
|
||||
(
|
||||
"description",
|
||||
Box::new(|value: &mut serde_json::Value| value["description"] = json!("a\u{0}b")),
|
||||
),
|
||||
(
|
||||
"argument name",
|
||||
Box::new(|value: &mut serde_json::Value| {
|
||||
value["arguments"][0]["name"] = json!("a\u{0}b")
|
||||
}),
|
||||
),
|
||||
(
|
||||
"message content",
|
||||
Box::new(|value: &mut serde_json::Value| {
|
||||
value["messages"][0]["content"] = json!("a\u{0}b")
|
||||
}),
|
||||
),
|
||||
] {
|
||||
let mut value = definition();
|
||||
mutate(&mut value);
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&value),
|
||||
Err(PromptError::InvalidDefinition),
|
||||
"{label} is stored as text and must not carry U+0000"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story312_enumeration_values_fit_the_stored_json_text_size() {
|
||||
let mut value = defaulted(serde_json::Value::Null);
|
||||
value["arguments"][0]["default"] = json!("x");
|
||||
value["arguments"][0]["schema"]["enum"] = json!(["x"]);
|
||||
assert!(PromptDefinition::parse(&value).is_ok());
|
||||
value["arguments"][0]["schema"]["enum"] = json!(["x", "a".repeat(16_383)]);
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&value),
|
||||
Err(PromptError::InvalidDefinition)
|
||||
);
|
||||
value["arguments"][0]["schema"]["enum"] = json!(["x", "a".repeat(16_382)]);
|
||||
assert!(PromptDefinition::parse(&value).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
//! ATDD (RED) для Story 3.16, AC-группы 1, 2 и 5 на уровне чистого домена.
|
||||
//!
|
||||
//! Источники: `_bmad-output/initiative-crank/epic-mcp-capabilities/spec-prompt-composition/contract.md`
|
||||
//! §1–§3, `epics.md`:2920–2986 (FR-18), `docs/acceptance-test-plan.md` AT-3.16-01/02/05/10.
|
||||
//!
|
||||
//! Состояние на момент написания: `PromptDefinition` не знает `dependencies` и `resource_refs`,
|
||||
//! поэтому каждый RED ниже — поведенческое расхождение `parse`/`as_json` на реальном публичном
|
||||
//! API `crank-core` (rед принимает точную ссылку → сегодня `Err(InvalidDefinition)`), а не ошибка
|
||||
//! компиляции или setup. Контроли `*_rejects_*` фиксируют инварианты, которые обязаны сохраниться
|
||||
//! после реализации; сегодня часть из них проходит вакуумно (любая dependency отклоняется) —
|
||||
//! это указано в имени/комментарии каждого такого теста.
|
||||
//!
|
||||
//! Фильтр запуска: `cargo test -p crank-core --test unit prompt_composition`.
|
||||
|
||||
use crank_core::prompt::{PromptDefinition, PromptError};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Минимальное корректное определение с одной точной dependency.
|
||||
fn composed(dependencies: Value, resource_refs: Option<Value>) -> Value {
|
||||
let mut message = json!({"role": "user", "content": "Channel: {{channel}}"});
|
||||
if let Some(refs) = resource_refs {
|
||||
message["resource_refs"] = refs;
|
||||
}
|
||||
json!({
|
||||
"name": "release-notes",
|
||||
"description": "Summarise the pinned changelog",
|
||||
"arguments": [{"name": "channel", "schema": {"type": "string"}, "required": true}],
|
||||
"messages": [
|
||||
{"role": "system", "content": "Summarise only the attached document."},
|
||||
message
|
||||
],
|
||||
"dependencies": dependencies
|
||||
})
|
||||
}
|
||||
|
||||
fn exact_dependency(index: u32) -> Value {
|
||||
json!({"resource_id": format!("res_exact_{index:02}"), "version": 3})
|
||||
}
|
||||
|
||||
/// AT-3.16-01: точная опубликованная ссылка входит в definition без потери полей.
|
||||
///
|
||||
/// RED сегодня: `parse` отклоняет неизвестный ключ `dependencies`.
|
||||
#[test]
|
||||
fn at_3_16_01_definition_accepts_exact_pinned_dependency() {
|
||||
let definition = PromptDefinition::parse(&composed(
|
||||
json!([{"resource_id": "res_exact_01", "version": 3}]),
|
||||
Some(json!([0])),
|
||||
))
|
||||
.expect("an exact pinned dependency must be a valid definition");
|
||||
|
||||
let serialized = definition.as_json();
|
||||
assert_eq!(
|
||||
serialized["dependencies"],
|
||||
json!([{"resource_id": "res_exact_01", "version": 3}]),
|
||||
"the exact reference must round-trip unchanged"
|
||||
);
|
||||
assert_eq!(
|
||||
serialized["messages"][1]["resource_refs"],
|
||||
json!([0]),
|
||||
"the declared insertion point must round-trip unchanged"
|
||||
);
|
||||
assert_eq!(serialized["messages"][0]["role"], json!("system"));
|
||||
assert_eq!(definition.messages().len(), 2, "messages are unchanged");
|
||||
}
|
||||
|
||||
/// AT-3.16-01: mutable/foreign-адресация невыразима.
|
||||
///
|
||||
/// NC-vacuous: сегодня проходит потому, что любая dependency отклоняется. После реализации
|
||||
/// каждый вариант обязан отклоняться именно как `InvalidDefinition`.
|
||||
#[test]
|
||||
fn at_3_16_01_definition_rejects_mutable_and_foreign_reference_shapes() {
|
||||
for rejected in [
|
||||
// mutable: URI вместо точной идентичности
|
||||
json!([{"uri": "crank://resources/changelog"}]),
|
||||
// mutable: плавающий указатель версии
|
||||
json!([{"resource_id": "res_exact_01", "version": "latest"}]),
|
||||
json!([{"resource_id": "res_exact_01", "version": "*"}]),
|
||||
// точная, но недопустимая версия
|
||||
json!([{"resource_id": "res_exact_01", "version": 0}]),
|
||||
// identity не задаётся клиентом: workspace приходит из URL/сессии
|
||||
json!([{"resource_id": "res_exact_01", "version": 3, "workspace_id": "ws_foreign"}]),
|
||||
// лишние/подменяющие поля
|
||||
json!([{"resource_id": "res_exact_01", "version": 3, "digest": "00"}]),
|
||||
json!([{"resource_id": 7, "version": 3}]),
|
||||
json!([{"resource_id": "res_exact_01"}]),
|
||||
json!(["res_exact_01@3"]),
|
||||
] {
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&composed(rejected.clone(), None)).err(),
|
||||
Some(PromptError::InvalidDefinition),
|
||||
"a mutable/foreign shaped reference must be rejected: {rejected}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// AT-3.16-02: count bound и уникальность целей.
|
||||
///
|
||||
/// RED в части «16 принимаются»; отказ на 17-й и на дубле — инвариант, который обязан
|
||||
/// сохраниться (сегодня тоже отказ, вакуумно).
|
||||
#[test]
|
||||
fn at_3_16_02_definition_bounds_dependency_count_and_uniqueness() {
|
||||
let accepted: Vec<Value> = (1..=16).map(exact_dependency).collect();
|
||||
let dependencies = Value::Array(accepted);
|
||||
assert!(
|
||||
PromptDefinition::parse(&composed(dependencies.clone(), None)).is_ok(),
|
||||
"16 dependencies are inside the documented bound (contract §1)"
|
||||
);
|
||||
|
||||
let mut too_many: Vec<Value> = (1..=17).map(exact_dependency).collect();
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&composed(Value::Array(too_many.clone()), None)).err(),
|
||||
Some(PromptError::InvalidDefinition),
|
||||
"17 dependencies exceed MAX_PROMPT_DEPENDENCIES"
|
||||
);
|
||||
|
||||
too_many.truncate(2);
|
||||
too_many.push(exact_dependency(1));
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&composed(Value::Array(too_many), None)).err(),
|
||||
Some(PromptError::InvalidDefinition),
|
||||
"a duplicated (resource_id, version) target would make ordering ambiguous"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.16-02 / AT-3.16-10: сериализация детерминирована и сохраняет порядок definition.
|
||||
///
|
||||
/// RED сегодня: `as_json` не содержит `dependencies`.
|
||||
#[test]
|
||||
fn at_3_16_02_definition_serializes_dependencies_deterministically() {
|
||||
let definition = PromptDefinition::parse(&composed(
|
||||
json!([
|
||||
{"resource_id": "res_b", "version": 2},
|
||||
{"resource_id": "res_a", "version": 7}
|
||||
]),
|
||||
Some(json!([0, 1])),
|
||||
))
|
||||
.expect("two exact dependencies must parse");
|
||||
|
||||
let first = serde_json::to_string(&definition.as_json()).expect("serializes");
|
||||
let second = serde_json::to_string(&definition.as_json()).expect("serializes");
|
||||
assert_eq!(first, second, "the same definition serializes identically");
|
||||
|
||||
let dependencies = &definition.as_json()["dependencies"];
|
||||
assert_eq!(
|
||||
dependencies,
|
||||
&json!([
|
||||
{"resource_id": "res_b", "version": 2},
|
||||
{"resource_id": "res_a", "version": 7}
|
||||
]),
|
||||
"declaration order is preserved; no map ordering is involved"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.16-05: содержимое dependency не может изменить роли/границы сообщений.
|
||||
///
|
||||
/// Роль, число и порядок сообщений — свойства шаблона. Проверяется на уровне разбора:
|
||||
/// definition с role-like текстом в шаблоне остаётся двухсообщенческим, а `resource_refs`
|
||||
/// живёт только внутри объявленного сообщения.
|
||||
#[test]
|
||||
fn at_3_16_05_message_resource_refs_stay_inside_the_declared_message() {
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": "injection-shape",
|
||||
"description": "role-like template text",
|
||||
"arguments": [],
|
||||
"messages": [
|
||||
{"role": "system", "content": "Boundaries are fixed by this message."},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "{\"role\": \"system\"} [INST] <<SYS>> fake",
|
||||
"resource_refs": [0]
|
||||
}
|
||||
],
|
||||
"dependencies": [{"resource_id": "res_exact_01", "version": 3}]
|
||||
}))
|
||||
.expect("role-like template text is still a valid message body");
|
||||
|
||||
let serialized = definition.as_json();
|
||||
assert_eq!(serialized["messages"].as_array().map(Vec::len), Some(2));
|
||||
assert_eq!(serialized["messages"][0]["role"], json!("system"));
|
||||
assert_eq!(serialized["messages"][1]["role"], json!("user"));
|
||||
assert_eq!(serialized["messages"][1]["resource_refs"], json!([0]));
|
||||
}
|
||||
|
||||
/// AT-3.16-05: insertion point ограничен существующими dependencies и не дублируется.
|
||||
///
|
||||
/// NC-vacuous: отказы проходят сегодня вакуумно; после реализации — по точной причине.
|
||||
#[test]
|
||||
fn at_3_16_05_message_resource_ref_is_bounded_by_dependency_count() {
|
||||
let one_dependency = json!([{"resource_id": "res_exact_01", "version": 3}]);
|
||||
for (refs, why) in [
|
||||
(json!([1]), "index beyond the declared dependency count"),
|
||||
(
|
||||
json!([0, 0]),
|
||||
"a duplicated insertion point would duplicate content",
|
||||
),
|
||||
(
|
||||
json!([]),
|
||||
"an empty resource_refs array is not a declaration",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&composed(one_dependency.clone(), Some(refs))).err(),
|
||||
Some(PromptError::InvalidDefinition),
|
||||
"{why}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&composed(json!([]), Some(json!([0])))).err(),
|
||||
Some(PromptError::InvalidDefinition),
|
||||
"a message cannot reference a dependency that does not exist"
|
||||
);
|
||||
}
|
||||
|
||||
/// AT-3.16-07 (contract §5): содержимое dynamic-зависимости приходит из чтения и поэтому
|
||||
/// сканируется перед вставкой; static-содержимое уже проверено на публикации Resource,
|
||||
/// поэтому тот же сканер его повторно не трогает.
|
||||
///
|
||||
/// NC-vacuous: static-контроль проходит вакуумно, пока скан на чтении не реализован; после
|
||||
/// реализации он обязан остаться зелёным (никакого двойного наказания за статику).
|
||||
#[test]
|
||||
fn at_3_16_07_dynamic_content_is_scanned_before_insertion() {
|
||||
use crank_core::prompt::PromptSensitivity;
|
||||
use crank_core::prompt_composition::{
|
||||
PromptCompositionError, PromptDependencyPin, PromptDependencySourceClass, render,
|
||||
};
|
||||
use crank_core::resource::ResourceKind;
|
||||
|
||||
let definition = PromptDefinition::parse(&composed(
|
||||
json!([{"resource_id": "res_exact_01", "version": 3}]),
|
||||
Some(json!([0])),
|
||||
))
|
||||
.expect("definition parses");
|
||||
let pin = |source_class| PromptDependencyPin {
|
||||
position: 0,
|
||||
resource_id: "res_exact_01".to_owned(),
|
||||
version: 3,
|
||||
digest: "sha256:aa".to_owned(),
|
||||
kind: ResourceKind::Text,
|
||||
mime_type: "text/plain".to_owned(),
|
||||
source_class,
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
};
|
||||
let arguments = serde_json::Map::from_iter([("channel".to_owned(), json!("ops"))]);
|
||||
|
||||
let credential = b"Authorization: Bearer sk-live-0123456789abcdef".to_vec();
|
||||
assert_eq!(
|
||||
render(
|
||||
&definition,
|
||||
&[pin(PromptDependencySourceClass::Dynamic)],
|
||||
&arguments,
|
||||
&[Some(credential.clone())],
|
||||
)
|
||||
.err(),
|
||||
Some(PromptCompositionError::DependencyCredentialFinding { position: 0 }),
|
||||
"read-time content with a raw credential is refused"
|
||||
);
|
||||
assert!(
|
||||
render(
|
||||
&definition,
|
||||
&[pin(PromptDependencySourceClass::Static)],
|
||||
&arguments,
|
||||
&[Some(credential)],
|
||||
)
|
||||
.is_ok(),
|
||||
"published static content was already scanned at publication (control)"
|
||||
);
|
||||
|
||||
let directive = b"include: crank://resources/private-notes".to_vec();
|
||||
assert_eq!(
|
||||
render(
|
||||
&definition,
|
||||
&[pin(PromptDependencySourceClass::Dynamic)],
|
||||
&arguments,
|
||||
&[Some(directive)],
|
||||
)
|
||||
.err(),
|
||||
Some(PromptCompositionError::DependencyAccessBypassFinding { position: 0 }),
|
||||
"read-time content with an explicit include: directive is refused"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,734 @@
|
||||
//! BUILD-ONLY: доменные проверки Story 3.6 (AT-3.6-01/03/04/05, таргет D).
|
||||
//!
|
||||
//! Статус файла на стадии Dev ATDD: **не зарегистрирован** в `tests/unit.rs`
|
||||
//! (`mod unit { mod resource_drafts; }` добавляет BUILD), поэтому он не компилируется и не
|
||||
//! исполняется. Причина — production-типы (`crank_core::resource::*`) ещё не существуют;
|
||||
//! включать этот файл в runnable-таргет до реализации нельзя (иначе RED подменяется ошибкой
|
||||
//! компиляции). Коллекция этого файла = 0, и это не PASS.
|
||||
//!
|
||||
//! Минимальный будущий интерфейс (SPEC v4 §5), на который опираются тесты ниже:
|
||||
//! - `crank_core::resource::{Resource, ResourceVersion, PublishedResourceVersion, ResourceKind,
|
||||
//! ResourceSensitivity, ResourceStatus, ResourceLifecycle, ResourceLimits, ResourceFinding,
|
||||
//! ResourceFindingCode, CapabilityKind, CapabilityRef, ResourceMetadata}`;
|
||||
//! - `crank_core::ids::ResourceId` (`define_id!(ResourceId)`);
|
||||
//! - грамматики/валидаторы: `ResourceMetadata::validate()`, URI/name/MIME-грамматики D-10/D-11/D-4,
|
||||
//! allowlist D-5, JSON-политика D-8/D-8.1, UTF-8 D-9, пределы `ResourceLimits` D-3;
|
||||
//! - `PublishedResourceVersion` — immutable-модель без `path`/`file_name`/`storage_ref`/`source_id`.
|
||||
//!
|
||||
//! Фиксированные имена тестов (SPEC §2) перечислены в заголовках; они должны появиться здесь
|
||||
//! при BUILD без переименования.
|
||||
|
||||
use crank_core::resource::{
|
||||
CapabilityKind, CapabilityRef, PublishedResourceVersion, Resource, ResourceKind,
|
||||
ResourceLifecycle, ResourceLifecycleAction, ResourceLimits, ResourceMetadata,
|
||||
ResourceSensitivity, ResourceStatus, ResourceVersion, publication_include_directives,
|
||||
publication_secret_findings,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
const LIMIT: usize = 256 * 1024;
|
||||
|
||||
#[test]
|
||||
fn story36_at01_resource_is_a_separate_typed_aggregate() {
|
||||
// typed mismatch вместо поиска слов: Operation-ref не принимается там, где нужен Resource-ref.
|
||||
let reference = CapabilityRef::Resource(crank_core::ids::ResourceId::new("res_story36_draft"));
|
||||
assert_eq!(reference.kind(), CapabilityKind::Resource);
|
||||
|
||||
let resource = Resource::draft(
|
||||
crank_core::ids::ResourceId::new("res_story36_draft"),
|
||||
ResourceMetadata {
|
||||
uri: "crank://docs/readme".to_owned(),
|
||||
name: "readme_page".to_owned(),
|
||||
description: String::new(),
|
||||
kind: ResourceKind::Text,
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: ResourceSensitivity::Internal,
|
||||
},
|
||||
);
|
||||
assert_eq!(resource.status(), ResourceStatus::Draft);
|
||||
assert_eq!(resource.current_draft_version(), 1);
|
||||
|
||||
// serde roundtrip typed полей: wire-значения D-2 не меняются.
|
||||
let encoded = serde_json::to_value(&resource).expect("resource must serialize");
|
||||
assert_eq!(encoded["kind"], serde_json::json!("text"));
|
||||
assert_eq!(encoded["status"], serde_json::json!("draft"));
|
||||
assert_eq!(encoded["sensitivity"], serde_json::json!("internal"));
|
||||
let decoded: Resource = serde_json::from_value(encoded).expect("resource must deserialize");
|
||||
assert_eq!(decoded, resource);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at01_published_version_is_immutable_after_draft_edit() {
|
||||
let draft = ResourceVersion::draft(
|
||||
1,
|
||||
ResourceKind::Json,
|
||||
"application/json".to_owned(),
|
||||
12,
|
||||
"a".repeat(64),
|
||||
);
|
||||
let published = PublishedResourceVersion::from_draft(&draft);
|
||||
let published_bytes = serde_json::to_value(&published).expect("published must serialize");
|
||||
|
||||
// «Редактирование» черновика: новая версия других bytes/metadata. Опубликованный снимок
|
||||
// обязан держать собственные данные и не меняться от появления/изменения черновика.
|
||||
let edited = ResourceVersion::draft(
|
||||
2,
|
||||
ResourceKind::Binary,
|
||||
"image/png".to_owned(),
|
||||
34,
|
||||
"b".repeat(64),
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(&published).expect("published must serialize"),
|
||||
published_bytes
|
||||
);
|
||||
|
||||
// Published-модель конструируется только из Draft и не имеет мутирующих методов.
|
||||
let _: &PublishedResourceVersion = &published;
|
||||
assert_ne!(published.version(), edited.version());
|
||||
assert_ne!(published.digest(), edited.digest());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at01_invalid_lifecycle_transition_is_rejected() {
|
||||
// архив/публикация в 3.6 не реализуются, но модель обязана отвергать недопустимый переход.
|
||||
assert!(ResourceStatus::Draft.can_transition_to(ResourceStatus::Published));
|
||||
assert!(!ResourceStatus::Archived.can_transition_to(ResourceStatus::Draft));
|
||||
|
||||
// R-D: проверяется настоящий вызов перехода, а не только таблица допустимости:
|
||||
// допустимые пары возвращают проверенный переход, недопустимые — фиксированную ошибку.
|
||||
for (from, action, to) in [
|
||||
(
|
||||
ResourceStatus::Draft,
|
||||
ResourceLifecycleAction::Publish,
|
||||
ResourceStatus::Published,
|
||||
),
|
||||
(
|
||||
ResourceStatus::Draft,
|
||||
ResourceLifecycleAction::Archive,
|
||||
ResourceStatus::Archived,
|
||||
),
|
||||
(
|
||||
ResourceStatus::Published,
|
||||
ResourceLifecycleAction::Revert,
|
||||
ResourceStatus::Draft,
|
||||
),
|
||||
(
|
||||
ResourceStatus::Published,
|
||||
ResourceLifecycleAction::Archive,
|
||||
ResourceStatus::Archived,
|
||||
),
|
||||
] {
|
||||
let transition = ResourceLifecycle::transition(from, action)
|
||||
.unwrap_or_else(|error| panic!("{from} -> {action:?} must be allowed: {error:?}"));
|
||||
assert_eq!(transition.from, from);
|
||||
assert_eq!(transition.action, action);
|
||||
assert_eq!(transition.to(), to);
|
||||
}
|
||||
|
||||
for (from, action, to) in [
|
||||
(
|
||||
ResourceStatus::Archived,
|
||||
ResourceLifecycleAction::Publish,
|
||||
ResourceStatus::Published,
|
||||
),
|
||||
(
|
||||
ResourceStatus::Archived,
|
||||
ResourceLifecycleAction::Revert,
|
||||
ResourceStatus::Draft,
|
||||
),
|
||||
(
|
||||
ResourceStatus::Archived,
|
||||
ResourceLifecycleAction::Archive,
|
||||
ResourceStatus::Archived,
|
||||
),
|
||||
] {
|
||||
let error = ResourceLifecycle::transition(from, action)
|
||||
.expect_err("an archived Resource must not transition anywhere in 3.6");
|
||||
assert_eq!(error.code(), "resource_lifecycle_invalid");
|
||||
assert_eq!(
|
||||
error,
|
||||
crank_core::resource::ResourceError::InvalidLifecycleTransition { from, to },
|
||||
"the refusal must name the exact transition that was attempted"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at02_metadata_grammar_accepts_and_rejects_exact_boundaries() {
|
||||
let uri_192 = format!("crank://{}", "a".repeat(192));
|
||||
let uri_193 = format!("crank://{}", "a".repeat(193));
|
||||
for (label, uri, expected) in [
|
||||
("min-10", "crank://ab".to_owned(), true),
|
||||
("max-200", uri_192, true),
|
||||
("inner-underscore", "crank://a_b".to_owned(), true),
|
||||
("double-dot-segment", "crank://a..b".to_owned(), true),
|
||||
("too-short", "crank://a".to_owned(), false),
|
||||
("too-long", uri_193, false),
|
||||
("trailing-underscore", "crank://a_".to_owned(), false),
|
||||
("empty-segment", "crank://a//b".to_owned(), false),
|
||||
("uppercase-scheme", "CRANK://a".to_owned(), false),
|
||||
("percent-encoding", "crank://a%2Fb".to_owned(), false),
|
||||
] {
|
||||
assert_eq!(
|
||||
ResourceMetadata::uri_is_valid(&uri),
|
||||
expected,
|
||||
"URI grammar boundary `{label}`"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at03_published_serializer_has_no_path_filename_or_source_id() {
|
||||
let draft = ResourceVersion::draft(
|
||||
1,
|
||||
ResourceKind::Text,
|
||||
"text/plain".to_owned(),
|
||||
5,
|
||||
"c".repeat(64),
|
||||
);
|
||||
let published = serde_json::to_value(PublishedResourceVersion::from_draft(&draft))
|
||||
.expect("published must serialize");
|
||||
let serialized = published.to_string();
|
||||
for forbidden in [
|
||||
"path",
|
||||
"file_name",
|
||||
"storage_ref",
|
||||
"source_id",
|
||||
"artifact_ref",
|
||||
] {
|
||||
assert!(
|
||||
!serialized.contains(forbidden),
|
||||
"published contract must not expose `{forbidden}` (D-12): {serialized}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at04_json_semantics_preserved_byte_exact() {
|
||||
let document = "{\"b\":1,\"a\":[1,2,3],\"дубликат\":1,\"дубликат\":2,\"nested\":{\"n\":1e308}}";
|
||||
let validation = ResourceMetadata::validate_json(document.as_bytes(), LIMIT);
|
||||
assert!(
|
||||
validation.is_ok(),
|
||||
"valid JSON must be accepted: {validation:?}"
|
||||
);
|
||||
// Oracle — байты, а не разобранное `Value`: порядок ключей и дубликаты сохраняются.
|
||||
assert_eq!(
|
||||
validation.expect("accepted").as_slice(),
|
||||
document.as_bytes()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at04_numeric_policy_of_selected_parser() {
|
||||
// D-8.1: точные границы фактического парсера (serde_json 1.0.150 без features).
|
||||
for accepted in ["1e308", "1.7e308", "18446744073709551616", "1e-400", "-0"] {
|
||||
assert!(
|
||||
ResourceMetadata::validate_json(accepted.as_bytes(), LIMIT).is_ok(),
|
||||
"`{accepted}` must be accepted by the locked parser"
|
||||
);
|
||||
}
|
||||
for rejected in ["1e309", "9e308", "1.8e308", "1e1000000000000000000000"] {
|
||||
let error = ResourceMetadata::validate_json(rejected.as_bytes(), LIMIT)
|
||||
.expect_err("out-of-range number must be rejected as invalid JSON");
|
||||
assert_eq!(error.code(), "resource_content_invalid_json");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at05_utf8_boundary_and_truncation_are_rejected() {
|
||||
let valid = "Привет 🚀\nвторая строка".as_bytes();
|
||||
let accepted = ResourceMetadata::validate_text(valid, LIMIT).expect("valid UTF-8 must pass");
|
||||
assert_eq!(
|
||||
accepted.as_slice(),
|
||||
valid,
|
||||
"text bytes and checksum stay byte-exact"
|
||||
);
|
||||
|
||||
for invalid in [
|
||||
vec![0xFF],
|
||||
vec![0xC3, 0x28],
|
||||
vec![0xC0, 0xAF],
|
||||
vec![0x80],
|
||||
vec![0xF0, 0x9F, 0x92],
|
||||
] {
|
||||
let error = ResourceMetadata::validate_text(&invalid, LIMIT)
|
||||
.expect_err("invalid UTF-8 must be rejected without replacement");
|
||||
assert_eq!(error.code(), "resource_content_invalid_utf8");
|
||||
}
|
||||
|
||||
// Границы L-1/L/L+1: многобайтовый символ не обрезается.
|
||||
let l_minus_one = vec![b'a'; LIMIT - 1];
|
||||
let l = vec![b'a'; LIMIT];
|
||||
let l_plus_one = vec![b'a'; LIMIT + 1];
|
||||
assert!(ResourceMetadata::validate_text(&l_minus_one, LIMIT).is_ok());
|
||||
assert!(
|
||||
ResourceMetadata::validate_text(&l, LIMIT).is_ok(),
|
||||
"L is inclusive"
|
||||
);
|
||||
assert_eq!(
|
||||
ResourceMetadata::validate_text(&l_plus_one, LIMIT)
|
||||
.expect_err("L+1 must be rejected as a whole")
|
||||
.code(),
|
||||
"resource_content_too_large"
|
||||
);
|
||||
|
||||
// Многобайтовый символ РОВНО на границе: целиком в лимите — принят байт-в-байт,
|
||||
// не помещается — отвергнут целиком (D-9), а не усечён до префикса.
|
||||
let mut multibyte_at_limit = vec![b'a'; LIMIT - 2];
|
||||
multibyte_at_limit.extend_from_slice("\u{e9}".as_bytes());
|
||||
assert_eq!(multibyte_at_limit.len(), LIMIT);
|
||||
let accepted = ResourceMetadata::validate_text(&multibyte_at_limit, LIMIT)
|
||||
.expect("a multibyte char that fits within L must be accepted");
|
||||
assert_eq!(
|
||||
accepted.as_slice(),
|
||||
multibyte_at_limit.as_slice(),
|
||||
"no truncation and no replacement may occur at the boundary"
|
||||
);
|
||||
|
||||
let mut multibyte_over_limit = vec![b'a'; LIMIT - 1];
|
||||
multibyte_over_limit.extend_from_slice("\u{e9}".as_bytes());
|
||||
assert_eq!(multibyte_over_limit.len(), LIMIT + 1);
|
||||
assert_eq!(
|
||||
ResourceMetadata::validate_text(&multibyte_over_limit, LIMIT)
|
||||
.expect_err("a multibyte char that does not fit must be rejected as a whole")
|
||||
.code(),
|
||||
"resource_content_too_large"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at06_unknown_or_unsupported_mime_is_a_safe_finding() {
|
||||
let limits = ResourceLimits::default();
|
||||
assert_eq!(limits.effective_limit(ResourceKind::Text), LIMIT);
|
||||
let finding = ResourceMetadata::mime_finding("application/zip", ResourceKind::Binary, &limits);
|
||||
assert_eq!(finding.code(), "resource_mime_not_allowed");
|
||||
|
||||
// Метаданные не отдают `Value`, только фиксированный finding без bytes.
|
||||
let json_finding = ResourceMetadata::json_finding(b"{", &limits);
|
||||
assert_eq!(json_finding.code(), "resource_content_invalid_json");
|
||||
let _: Value = serde_json::to_value(json_finding).expect("findings must serialize");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// P5 (affected ATDD до исправления): полная числовая/структурная политика,
|
||||
// configured small-L и типизированная несовместимость capability-ссылок.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn story36_at04_numeric_policy_full_selected_parser_matrix() {
|
||||
// D-8.1: точные границы фактического locked-парсера (serde_json без features).
|
||||
// Oracle каждого принятого числа — побайтовое чтение исходного лексема.
|
||||
let accepted = [
|
||||
"0",
|
||||
"-0",
|
||||
"9007199254740993",
|
||||
"18446744073709551615",
|
||||
"18446744073709551616",
|
||||
"-9223372036854775808",
|
||||
"-9223372036854775809",
|
||||
"0.1000000000000000000000001",
|
||||
"1.000000000000000000000000000000001",
|
||||
"123456789012345678901234567890",
|
||||
"1e308",
|
||||
"1.7e308",
|
||||
"1e-309",
|
||||
"1e-400",
|
||||
"1e-1000000000000000000000",
|
||||
"0e1000000000000000000000",
|
||||
];
|
||||
for document in accepted {
|
||||
let readback = ResourceMetadata::validate_json(document.as_bytes(), LIMIT)
|
||||
.unwrap_or_else(|error| panic!("`{document}` must be accepted (D-8.1): {error:?}"));
|
||||
assert_eq!(
|
||||
readback.as_slice(),
|
||||
document.as_bytes(),
|
||||
"an accepted numeric lexeme must be stored byte-exact, not re-serialized (D-8)"
|
||||
);
|
||||
}
|
||||
|
||||
let mut long_integer = String::from("1");
|
||||
long_integer.push_str(&"0".repeat(400));
|
||||
let rejected = [
|
||||
"1e309",
|
||||
"-1e309",
|
||||
"9e308",
|
||||
"1.8e308",
|
||||
"1e1000000000000000000000",
|
||||
long_integer.as_str(),
|
||||
];
|
||||
for document in rejected {
|
||||
let error = ResourceMetadata::validate_json(document.as_bytes(), LIMIT).expect_err(
|
||||
"a number outside f64 representability must be rejected as invalid JSON (D-8.1)",
|
||||
);
|
||||
assert_eq!(error.code(), "resource_content_invalid_json");
|
||||
assert_eq!(error.field(), Some("content"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at04_top_level_values_and_recursion_depth_policy() {
|
||||
// D-8: top-level — любое валидное значение; bytes хранятся дословно.
|
||||
for document in [
|
||||
"null",
|
||||
"true",
|
||||
"false",
|
||||
"0",
|
||||
"-1",
|
||||
"\"text\"",
|
||||
"123",
|
||||
"[]",
|
||||
"{}",
|
||||
"{\"ключ\":\"значение\"}",
|
||||
"\"\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442\"",
|
||||
// Литеральный (не escape-формы) Unicode: кириллица, эмодзи и комбинирующая
|
||||
// последовательность обязаны читаться обратно байт-в-байт (R-D).
|
||||
"{\"привет\":\"мир\"}",
|
||||
"{\"emoji\":\"🚀🦀\"}",
|
||||
"\"e\\u0301\"",
|
||||
"[\"Привет\",\"🚀\",null,false]",
|
||||
] {
|
||||
let readback = ResourceMetadata::validate_json(document.as_bytes(), LIMIT)
|
||||
.unwrap_or_else(|error| panic!("top-level `{document}` must be accepted: {error:?}"));
|
||||
assert_eq!(
|
||||
readback.as_slice(),
|
||||
document.as_bytes(),
|
||||
"accepted JSON must be stored byte-exact, including literal Unicode (D-8)"
|
||||
);
|
||||
}
|
||||
|
||||
let nested_ok = format!("{}1{}", "[".repeat(100), "]".repeat(100));
|
||||
assert!(
|
||||
ResourceMetadata::validate_json(nested_ok.as_bytes(), LIMIT).is_ok(),
|
||||
"nesting below the parser recursion limit must be accepted"
|
||||
);
|
||||
|
||||
let nested_over = format!("{}1{}", "[".repeat(300), "]".repeat(300));
|
||||
let error = ResourceMetadata::validate_json(nested_over.as_bytes(), LIMIT)
|
||||
.expect_err("nesting above the parser recursion limit must be rejected (D-8)");
|
||||
assert_eq!(error.code(), "resource_content_invalid_json");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at05_configured_small_limit_boundaries_per_kind() {
|
||||
let small = ResourceLimits::uniform(8).expect("8 bytes is inside the storage ceiling");
|
||||
assert_eq!(small.effective_limit(ResourceKind::Text), 8);
|
||||
assert_eq!(small.effective_limit(ResourceKind::Json), 8);
|
||||
assert_eq!(small.effective_limit(ResourceKind::Binary), 8);
|
||||
|
||||
// text: L-1 и L приняты байт-в-байт, L+1 отвергнут целиком (D-3/D-9).
|
||||
let text = |bytes: &[u8]| {
|
||||
ResourceMetadata::validate_content(ResourceKind::Text, "text/plain", bytes, &small)
|
||||
};
|
||||
assert!(text(&[b'a'; 7]).is_ok(), "text L-1 must be accepted");
|
||||
let accepted = text(&[b'a'; 8]).expect("text L must be accepted inclusively");
|
||||
assert_eq!(accepted.len(), 8);
|
||||
assert_eq!(
|
||||
text(&[b'a'; 9])
|
||||
.expect_err("text L+1 must be rejected as a whole")
|
||||
.code(),
|
||||
"resource_content_too_large"
|
||||
);
|
||||
|
||||
// Многобайтовый символ ровно на границе малого L не обрезается.
|
||||
let mut multibyte_fits = vec![b'a'; 6];
|
||||
multibyte_fits.extend_from_slice("\u{e9}".as_bytes());
|
||||
assert_eq!(multibyte_fits.len(), 8);
|
||||
assert!(text(&multibyte_fits).is_ok());
|
||||
let mut multibyte_over = vec![b'a'; 7];
|
||||
multibyte_over.extend_from_slice("\u{e9}".as_bytes());
|
||||
assert_eq!(multibyte_over.len(), 9);
|
||||
assert_eq!(
|
||||
text(&multibyte_over)
|
||||
.expect_err("a multibyte char above small L must reject the whole body")
|
||||
.code(),
|
||||
"resource_content_too_large"
|
||||
);
|
||||
|
||||
// json: границы и отдельный код для malformed внутри лимита.
|
||||
let json = |bytes: &[u8]| {
|
||||
ResourceMetadata::validate_content(ResourceKind::Json, "application/json", bytes, &small)
|
||||
};
|
||||
assert!(json(b"[1,2,3]").is_ok(), "json L-1 must be accepted");
|
||||
assert!(json(b"[1,2,34]").is_ok(), "json L must be accepted");
|
||||
assert_eq!(
|
||||
json(b"[1,2,345]")
|
||||
.expect_err("json L+1 must be rejected")
|
||||
.code(),
|
||||
"resource_content_too_large"
|
||||
);
|
||||
assert_eq!(
|
||||
json(b"{1,2,34}")
|
||||
.expect_err("malformed json inside the limit keeps its own code")
|
||||
.code(),
|
||||
"resource_content_invalid_json"
|
||||
);
|
||||
|
||||
// binary: любые байты (в т.ч. не-UTF8) в пределах L.
|
||||
let binary = |bytes: &[u8]| {
|
||||
ResourceMetadata::validate_content(
|
||||
ResourceKind::Binary,
|
||||
"application/octet-stream",
|
||||
bytes,
|
||||
&small,
|
||||
)
|
||||
};
|
||||
assert!(binary(&[0x00, 0xFF, 0x80, 0xC3, 0x28, 0x01, 0x02]).is_ok());
|
||||
assert!(binary(&[0x00; 8]).is_ok());
|
||||
assert_eq!(
|
||||
binary(&[0x00; 9])
|
||||
.expect_err("binary L+1 must be rejected")
|
||||
.code(),
|
||||
"resource_content_too_large"
|
||||
);
|
||||
|
||||
// Пустое содержимое отвергается для всех kinds при любом configured L (D-7).
|
||||
for (kind, mime) in [
|
||||
(ResourceKind::Text, "text/plain"),
|
||||
(ResourceKind::Json, "application/json"),
|
||||
(ResourceKind::Binary, "application/octet-stream"),
|
||||
] {
|
||||
assert_eq!(
|
||||
ResourceMetadata::validate_content(kind, mime, b"", &small)
|
||||
.expect_err("empty content must be rejected for every kind")
|
||||
.code(),
|
||||
"resource_content_empty"
|
||||
);
|
||||
}
|
||||
|
||||
// Configured L выше storage ceiling отвергается при конфигурации (D-3).
|
||||
assert!(ResourceLimits::uniform(262_145).is_err());
|
||||
let mixed = ResourceLimits::new(4, 8, 16).expect("mixed limits inside the ceiling");
|
||||
assert_eq!(mixed.effective_limit(ResourceKind::Text), 4);
|
||||
assert_eq!(mixed.effective_limit(ResourceKind::Json), 8);
|
||||
assert_eq!(mixed.effective_limit(ResourceKind::Binary), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story36_at01_capability_refs_are_type_disjoint() {
|
||||
let resource_id = crank_core::ids::ResourceId::new("res_story36_ref");
|
||||
let resource_ref = CapabilityRef::Resource(resource_id.clone());
|
||||
assert_eq!(
|
||||
serde_json::to_value(&resource_ref).expect("resource ref must serialize"),
|
||||
serde_json::json!({ "kind": "resource", "id": "res_story36_ref" })
|
||||
);
|
||||
assert_eq!(
|
||||
resource_ref
|
||||
.as_resource()
|
||||
.expect("resource ref must unwrap"),
|
||||
&resource_id
|
||||
);
|
||||
let mismatch = resource_ref
|
||||
.as_operation()
|
||||
.expect_err("a Resource ref must not be accepted where an Operation ref is required");
|
||||
assert_eq!(mismatch.expected, CapabilityKind::Operation);
|
||||
assert_eq!(mismatch.actual, CapabilityKind::Resource);
|
||||
|
||||
let operation_id = crank_core::ids::OperationId::new("op_story36_ref");
|
||||
let operation_ref = CapabilityRef::Operation(operation_id.clone());
|
||||
assert_eq!(
|
||||
operation_ref
|
||||
.as_operation()
|
||||
.expect("operation ref must unwrap"),
|
||||
&operation_id
|
||||
);
|
||||
let mismatch = operation_ref
|
||||
.as_resource()
|
||||
.expect_err("an Operation ref must not be accepted where a Resource ref is required");
|
||||
assert_eq!(mismatch.expected, CapabilityKind::Resource);
|
||||
assert_eq!(mismatch.actual, CapabilityKind::Operation);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BUILD obligations, которые этот файл НЕ подтверждает (не считать покрытием
|
||||
// по именам тестов выше — названы явно, чтобы BUILD не упустил их)
|
||||
// ---------------------------------------------------------------------------
|
||||
// - реальное редактирование черновика на уровне агрегата (`Resource` + `ResourceVersion`
|
||||
// в одном объекте, смена текущей версии) и отсутствие мутирующих API у published-модели:
|
||||
// здесь проверяется только неизменность сериализованного снимка, полного lifecycle-покрытия нет;
|
||||
// настоящий переход (`ResourceLifecycle::transition`) проверен ниже в
|
||||
// `story36_at01_invalid_lifecycle_transition_is_rejected`, но публикация/архивация — 3.7;
|
||||
// - typed mismatch между Operation-ref и Resource-ref (здесь проверен только `kind()` у
|
||||
// `CapabilityRef::Resource`) — нужен настоящий отказ функции, принимающей Resource-ref;
|
||||
// - PG-атомарность/rollback postconditions и fault-matrix — таргет P
|
||||
// (`crates/crank-registry/tests/integration/resource_drafts.rs`), не этот файл;
|
||||
// - числовая политика D-8.1 — фактическая проверка возможна только на Rust-интерфейсе
|
||||
// (Python-модель из SPEC §3 п.6 не является исполнением продукта);
|
||||
// - полный набор невалидных UTF-8 последовательностей и границы `ResourceLimits` для
|
||||
// не-default L проверяются здешними кейсами лишь частично; configured small-L — BUILD.
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Story 3.7 / AC02: publication secret policy и explicit include directives.
|
||||
// Синтетические неправдоподобные значения; ни один реальный credential не
|
||||
// используется, и проверяется поведение детектора, а не совпадение с фикстурой.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn story37_at02_structural_private_keys_are_detected() {
|
||||
for label in [
|
||||
"RSA PRIVATE KEY",
|
||||
"PRIVATE KEY",
|
||||
"EC PRIVATE KEY",
|
||||
"OPENSSH PRIVATE KEY",
|
||||
"ENCRYPTED PRIVATE KEY",
|
||||
] {
|
||||
let content =
|
||||
format!("-----BEGIN {label}-----\nc3ludGhldGljLWtleS1ib2R5\n-----END {label}-----\n");
|
||||
assert_eq!(
|
||||
publication_secret_findings(content.as_bytes()),
|
||||
Some("private_key"),
|
||||
"structural PEM block `{label}` must be rejected"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
publication_secret_findings(
|
||||
b"-----BEGIN PUBLIC KEY-----\nc3ludGhldGlj\n-----END PUBLIC KEY-----\n"
|
||||
),
|
||||
None,
|
||||
"a public key is not private key material"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story37_at02_raw_credentials_are_detected() {
|
||||
assert_eq!(
|
||||
publication_secret_findings(
|
||||
b"aws_access_key_id = AKIAIOSFODNN7EXAMPLE\naws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n"
|
||||
),
|
||||
Some("raw_credential")
|
||||
);
|
||||
assert_eq!(
|
||||
publication_secret_findings(br#"{"password": "synthetic-password-42"}"#),
|
||||
Some("raw_credential")
|
||||
);
|
||||
assert_eq!(
|
||||
publication_secret_findings(b"api_key: synthetic-api-key-0123456789\n"),
|
||||
Some("raw_credential")
|
||||
);
|
||||
assert_eq!(
|
||||
publication_secret_findings(b"Authorization: Bearer synthetic0token1234567890\n"),
|
||||
Some("raw_credential")
|
||||
);
|
||||
// F2: raw credential распознаётся независимо от позиции ключа в JSON.
|
||||
assert_eq!(
|
||||
publication_secret_findings(br#"{"name":"config","password":"synthetic-password-42"}"#),
|
||||
Some("raw_credential"),
|
||||
"a credential key in a later JSON position must not be skipped"
|
||||
);
|
||||
// F2: JSON-экранирование ключа не скрывает credential.
|
||||
assert_eq!(
|
||||
publication_secret_findings(br#"{"pass\u0077ord":"synthetic-password-42"}"#),
|
||||
Some("raw_credential"),
|
||||
"an escaped credential key must be decoded before the policy check"
|
||||
);
|
||||
// F2: bare token assignment и короткое неплейсхолдерное значение.
|
||||
assert_eq!(
|
||||
publication_secret_findings(b"token = synthetic-value-42\n"),
|
||||
Some("raw_credential"),
|
||||
"a bare `token` assignment is a raw credential"
|
||||
);
|
||||
assert_eq!(
|
||||
publication_secret_findings(b"password = abc123\n"),
|
||||
Some("raw_credential"),
|
||||
"an arbitrary minimal value length must not waive the policy"
|
||||
);
|
||||
// F2: digit-free Bearer — тот же raw credential.
|
||||
assert_eq!(
|
||||
publication_secret_findings(b"Bearer abcdefghijklmnopqrstuvwx\n"),
|
||||
Some("raw_credential"),
|
||||
"the presence of a digit is not required to recognise a Bearer token"
|
||||
);
|
||||
}
|
||||
|
||||
/// F1: malformed/не-закрытый PEM-подобный префикс не паникует на многобайтовом
|
||||
/// символе и не выдумывает private key; настоящий structural block по-прежнему
|
||||
/// блокируется (`story37_at02_structural_private_keys_are_detected`).
|
||||
#[test]
|
||||
fn story37_at02_malformed_private_key_prefix_is_safe_to_inspect() {
|
||||
for malformed in [
|
||||
format!("-----BEGIN a{}", "я".repeat(60)),
|
||||
"-----BEGIN ".to_owned(),
|
||||
format!("prefix -----BEGIN {}", "ключ".repeat(40)),
|
||||
"-----BEGIN PUBLIC KEY----- яяя".to_owned(),
|
||||
"-----BEGIN".to_owned(),
|
||||
"-----".to_owned(),
|
||||
] {
|
||||
assert_eq!(
|
||||
publication_secret_findings(malformed.as_bytes()),
|
||||
None,
|
||||
"a bounded non-key/malformed prefix must be inspected without panic: {malformed:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story37_at02_ordinary_text_and_placeholders_are_not_secrets() {
|
||||
for benign in [
|
||||
"Инструкция: не коммитьте private key в репозиторий, используйте secret manager и переменные окружения.\n",
|
||||
"See https://example.com/docs about private keys, tokens and secrets.\n",
|
||||
"password = <ваш пароль>\n",
|
||||
"token: ${CRANK_TOKEN}\n",
|
||||
"Use `Bearer <token>` in the Authorization header.\n",
|
||||
// F3: полная заглушка в реальной assignment-форме.
|
||||
"Authorization: Bearer ***\n",
|
||||
"authorization: Bearer <token>\n",
|
||||
"token: YOUR_TOKEN\n",
|
||||
"password: null\n",
|
||||
// Обычная проза: слово категории без присвоения.
|
||||
"The token is required in the Authorization header; see docs.\n",
|
||||
// Публичный ключ публикуем.
|
||||
"-----BEGIN PUBLIC KEY-----\nsynthetic\n-----END PUBLIC KEY-----\n",
|
||||
] {
|
||||
assert_eq!(
|
||||
publication_secret_findings(benign.as_bytes()),
|
||||
None,
|
||||
"ordinary text must stay publishable: {benign}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story37_at02_repeated_bearer_prefixes_are_inspected_without_amplification() {
|
||||
// R2-F1: цепочка scheme-префиксов в допустимых stored bytes — обычная
|
||||
// заглушка. Разбор не должен держать копию каждого остатка (квадратичная
|
||||
// память) и не должен расти по глубине стека.
|
||||
let chain = ["authorization: ", &"Bearer ".repeat(30_000), "***"].concat();
|
||||
assert!(
|
||||
chain.len() <= LIMIT,
|
||||
"the synthetic bounded input must stay within stored limits: {}",
|
||||
chain.len()
|
||||
);
|
||||
assert_eq!(
|
||||
publication_secret_findings(chain.as_bytes()),
|
||||
None,
|
||||
"a placeholder Bearer chain must stay publishable"
|
||||
);
|
||||
// Короткие формы сохраняют прежнюю семантику: заглушка и raw token.
|
||||
assert_eq!(
|
||||
publication_secret_findings(b"Authorization: Bearer ***"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
publication_secret_findings(b"Authorization: Bearer synthe...90\n"),
|
||||
Some("raw_credential")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story37_at02_include_directives_are_explicit_only() {
|
||||
assert_eq!(
|
||||
publication_include_directives(b"include: crank://docs/shared-reference\n"),
|
||||
vec!["crank://docs/shared-reference".to_owned()]
|
||||
);
|
||||
assert!(
|
||||
publication_include_directives(
|
||||
b"See https://example.com/docs and include: this prose is not a directive target\n"
|
||||
)
|
||||
.is_empty(),
|
||||
"an inline mention must not become a directive"
|
||||
);
|
||||
assert!(
|
||||
publication_include_directives(b"ordinary text\nsecond line\n").is_empty(),
|
||||
"ordinary content has no directives"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! UNIT Story 3.10 (FR-16): typed source contract и single-sourced policy bounds.
|
||||
//!
|
||||
//! Build-only шов: тип определения шаблона существует только с этим build, поэтому
|
||||
//! HTTP-уровень проверяется отдельно (`admin-api`/`template*.rs`), а здесь —
|
||||
//! serde-контракт (unknown fields denied, exact operation version обязателен) и
|
||||
//! exported cache/failure пределы, которыми пользуются validator и API.
|
||||
|
||||
use crank_core::resource::template::{
|
||||
MAX_TEMPLATE_CACHE_BYTES, MAX_TEMPLATE_CACHE_TTL_MS, TEMPLATE_CACHE_SCOPE, TemplateCache,
|
||||
TemplateFindingCode, TemplateSource, cache_policy_findings,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
fn source_value() -> Value {
|
||||
json!({
|
||||
"operation_id": "op_story310",
|
||||
"operation_version": 1,
|
||||
"uri_template": "crank://orders/{order_id}",
|
||||
"parameters": [{
|
||||
"name": "order_id",
|
||||
"input_path": "input.order_id",
|
||||
"schema": { "type": "string", "required": true, "format": "uuid" }
|
||||
}],
|
||||
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
|
||||
"failure": { "outcome": "error" }
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story310_at01_source_contract_denies_unknown_fields_and_draft_state() {
|
||||
let parsed = TemplateSource::parse(&source_value()).expect("typed source must parse");
|
||||
assert_eq!(parsed.operation_id, "op_story310");
|
||||
assert_eq!(parsed.operation_version, 1);
|
||||
assert_eq!(parsed.parameters[0].input_path, "input.order_id");
|
||||
|
||||
// Arbitrary URL/inline request definition не представимы: любой неизвестный
|
||||
// ключ на любом уровне — структурный отказ.
|
||||
for (path, value) in [
|
||||
(vec!["url"], json!("https://evil.example/orders")),
|
||||
(vec!["request"], json!({ "url": "https://evil.example" })),
|
||||
(vec!["method"], json!("POST")),
|
||||
(
|
||||
vec!["parameters", "0", "url"],
|
||||
json!("https://evil.example"),
|
||||
),
|
||||
(vec!["cache", "scope"], json!("workspace")),
|
||||
] {
|
||||
let mut source = source_value();
|
||||
let mut cursor = &mut source;
|
||||
for step in &path[..path.len() - 1] {
|
||||
cursor = match step.parse::<usize>() {
|
||||
Ok(index) => &mut cursor[index],
|
||||
Err(_) => &mut cursor[*step],
|
||||
};
|
||||
}
|
||||
cursor[path[path.len() - 1]] = value;
|
||||
assert!(
|
||||
TemplateSource::parse(&source).is_err(),
|
||||
"unknown field must be denied: {path:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// «latest alias»/Draft state не выражаются: версия обязательна и явная.
|
||||
let mut without_version = source_value();
|
||||
without_version
|
||||
.as_object_mut()
|
||||
.expect("object")
|
||||
.remove("operation_version");
|
||||
assert!(TemplateSource::parse(&without_version).is_err());
|
||||
|
||||
let mut latest = source_value();
|
||||
latest["operation_version"] = json!("latest");
|
||||
assert!(TemplateSource::parse(&latest).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn story310_at04_policy_bounds_are_single_sourced() {
|
||||
assert_eq!(MAX_TEMPLATE_CACHE_TTL_MS, 86_400_000);
|
||||
assert_eq!(MAX_TEMPLATE_CACHE_BYTES, 262_144);
|
||||
assert_eq!(TEMPLATE_CACHE_SCOPE, "workspace_agent_auth");
|
||||
|
||||
let names: BTreeSet<&str> = ["order_id"].into_iter().collect();
|
||||
let cache = |ttl_ms: u64, vary: Vec<&str>, max_bytes: u64| TemplateCache {
|
||||
ttl_ms,
|
||||
vary: vary.into_iter().map(str::to_owned).collect(),
|
||||
max_bytes,
|
||||
};
|
||||
|
||||
// Значения ровно на границе принимаются.
|
||||
assert!(
|
||||
cache_policy_findings(
|
||||
&cache(
|
||||
MAX_TEMPLATE_CACHE_TTL_MS,
|
||||
vec!["order_id"],
|
||||
MAX_TEMPLATE_CACHE_BYTES
|
||||
),
|
||||
&names
|
||||
)
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
// MAX+1 и 0 — те же exported границы, что использует публикация.
|
||||
for (ttl_ms, max_bytes, expected) in [
|
||||
(
|
||||
MAX_TEMPLATE_CACHE_TTL_MS + 1,
|
||||
MAX_TEMPLATE_CACHE_BYTES,
|
||||
TemplateFindingCode::CacheTtlInvalid,
|
||||
),
|
||||
(
|
||||
0,
|
||||
MAX_TEMPLATE_CACHE_BYTES,
|
||||
TemplateFindingCode::CacheTtlInvalid,
|
||||
),
|
||||
(
|
||||
MAX_TEMPLATE_CACHE_TTL_MS,
|
||||
MAX_TEMPLATE_CACHE_BYTES + 1,
|
||||
TemplateFindingCode::CacheSizeInvalid,
|
||||
),
|
||||
(
|
||||
MAX_TEMPLATE_CACHE_TTL_MS,
|
||||
0,
|
||||
TemplateFindingCode::CacheSizeInvalid,
|
||||
),
|
||||
] {
|
||||
let findings = cache_policy_findings(&cache(ttl_ms, vec!["order_id"], max_bytes), &names);
|
||||
assert!(
|
||||
findings.iter().any(|finding| finding.code == expected),
|
||||
"expected {expected:?} for ttl={ttl_ms} bytes={max_bytes}: {findings:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// vary: чужое имя, повтор и пропуск объявленного параметра.
|
||||
for (vary, expected) in [
|
||||
(
|
||||
vec!["order_id", "tenant_id"],
|
||||
TemplateFindingCode::VaryUnknown,
|
||||
),
|
||||
(
|
||||
vec!["order_id", "order_id"],
|
||||
TemplateFindingCode::VaryDuplicate,
|
||||
),
|
||||
(vec![], TemplateFindingCode::VaryIncomplete),
|
||||
] {
|
||||
let findings = cache_policy_findings(&cache(60_000, vary, 65_536), &names);
|
||||
assert!(
|
||||
findings.iter().any(|finding| finding.code == expected),
|
||||
"expected {expected:?}: {findings:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::process::ExitCode;
|
||||
|
||||
const SNAPSHOT: &str = include_str!("../../../../docs/schemas/metrics-registry-v1.json");
|
||||
const SNAPSHOT: &str = include_str!("../../../../docs/schemas/metrics-registry-v2.json");
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let rendered = match crank_metrics::render_metric_schema_json() {
|
||||
@@ -21,7 +21,7 @@ fn main() -> ExitCode {
|
||||
}
|
||||
match SNAPSHOT {
|
||||
snapshot if snapshot == rendered => {
|
||||
println!("metrics_contract_ok schema_version=1");
|
||||
println!("metrics_contract_ok schema_version=2");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
_ => {
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock},
|
||||
};
|
||||
|
||||
use crate::{DURATION_BUCKETS_SECONDS, max_exemplar_slots};
|
||||
use crate::{DURATION_BUCKETS_SECONDS, MAX_EXEMPLAR_SLOTS_PER_PROCESS, MetricService};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub struct ExemplarTraceId([u8; 32]);
|
||||
@@ -50,13 +50,73 @@ fn store() -> &'static Mutex<BTreeMap<ExemplarKey, Arc<ExemplarObservation>>> {
|
||||
STORE.get_or_init(|| Mutex::new(BTreeMap::new()))
|
||||
}
|
||||
|
||||
/// Process-local capacity of the exemplar store: the projected histogram
|
||||
/// capacity of the bound service, never the union capacity and never a hidden
|
||||
/// `min(union, hard cap)` truncation of legitimate slots. A projection whose
|
||||
/// checked arithmetic overflows fails closed (no exemplar growth) instead of
|
||||
/// recording under a saturated capacity.
|
||||
pub(crate) fn service_capacity(service: MetricService) -> usize {
|
||||
crate::schema::checked_exemplar_capacity(service)
|
||||
.unwrap_or(0)
|
||||
.min(MAX_EXEMPLAR_SLOTS_PER_PROCESS)
|
||||
}
|
||||
|
||||
/// Independent private ownership barrier. The public facade normalises before it
|
||||
/// calls this helper, but the internal entry point must never rely on that: the
|
||||
/// caller's service has to be the **bound** process identity, the family has to
|
||||
/// belong to that service, and a family that declares a `route` domain has to
|
||||
/// carry an already-normalised own/shared route. Any other input is a no-op, so
|
||||
/// an unbound or foreign call can never allocate a store key.
|
||||
fn ownership_allows(
|
||||
service: MetricService,
|
||||
metric: &'static str,
|
||||
labels: &[(&'static str, &'static str)],
|
||||
) -> bool {
|
||||
if crate::record::bound_metric_service() != Some(service) {
|
||||
return false;
|
||||
}
|
||||
let Some(definition) = crate::schema::service_projection(service)
|
||||
.iter()
|
||||
.find(|definition| definition.name == metric)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let mut declared_route = false;
|
||||
let mut supplied_route = false;
|
||||
for (name, value) in labels {
|
||||
if *name != "route" {
|
||||
continue;
|
||||
}
|
||||
supplied_route = true;
|
||||
if crate::record::normalize_http_route(service, crate::HttpRoute::from_matched_path(value))
|
||||
.as_str()
|
||||
!= *value
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for domain in definition.label_domains {
|
||||
if domain.name == "route" {
|
||||
declared_route = true;
|
||||
}
|
||||
}
|
||||
!declared_route || supplied_route
|
||||
}
|
||||
|
||||
pub(crate) fn record_exemplar(
|
||||
service: MetricService,
|
||||
metric: &'static str,
|
||||
labels: Vec<(&'static str, &'static str)>,
|
||||
value: f64,
|
||||
trace_id: Option<ExemplarTraceId>,
|
||||
) {
|
||||
let Some(trace_id) = trace_id else { return };
|
||||
// The internal entry point enforces the already-normalised ownership: an
|
||||
// unbound process, another service or an input that does not belong to the
|
||||
// bound service never creates that foreign key.
|
||||
if !ownership_allows(service, metric, &labels) {
|
||||
return;
|
||||
}
|
||||
let bucket_index = DURATION_BUCKETS_SECONDS
|
||||
.iter()
|
||||
.position(|bound| value <= *bound)
|
||||
@@ -68,6 +128,7 @@ pub(crate) fn record_exemplar(
|
||||
value,
|
||||
trace_id,
|
||||
};
|
||||
let capacity = service_capacity(service);
|
||||
let Ok(mut observations) = store().lock() else {
|
||||
return;
|
||||
};
|
||||
@@ -76,7 +137,7 @@ pub(crate) fn record_exemplar(
|
||||
labels,
|
||||
bucket_index,
|
||||
};
|
||||
if observations.contains_key(&key) || observations.len() < max_exemplar_slots() {
|
||||
if observations.contains_key(&key) || observations.len() < capacity {
|
||||
observations.insert(key, Arc::new(observation));
|
||||
}
|
||||
}
|
||||
@@ -87,3 +148,404 @@ pub fn exemplar_snapshot() -> Vec<Arc<ExemplarObservation>> {
|
||||
.map(|observations| observations.values().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::schema::{DURATION_BUCKETS_SECONDS, MetricKind, service_projection};
|
||||
|
||||
const ROLE_DIR_PREFIX: &str = "crank-metrics-exemplar-role-";
|
||||
|
||||
fn trace() -> ExemplarTraceId {
|
||||
ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").expect("valid trace id")
|
||||
}
|
||||
|
||||
fn role_dir(role: &str) -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!("{ROLE_DIR_PREFIX}{role}"))
|
||||
}
|
||||
|
||||
/// Роль передаётся через рабочий каталог дочернего процесса: production
|
||||
/// boundary checker запрещает чтение environment вне `crank-config`, а
|
||||
/// `cfg(test)`-модуль в `src/**` под это правило попадает.
|
||||
fn current_role() -> Option<String> {
|
||||
std::env::current_dir()
|
||||
.ok()?
|
||||
.file_name()?
|
||||
.to_str()?
|
||||
.strip_prefix(ROLE_DIR_PREFIX)
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn route_to_child_role(role: &str, test: &str) -> bool {
|
||||
match current_role().as_deref() {
|
||||
Some(actual) if actual == role => false,
|
||||
Some(actual) => panic!("nested exemplar child role {actual} for {test}"),
|
||||
None => {
|
||||
let directory = role_dir(role);
|
||||
std::fs::create_dir_all(&directory).expect("exemplar role dir");
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().expect("test binary"))
|
||||
.args([test, "--exact", "--nocapture"])
|
||||
.current_dir(&directory)
|
||||
.output()
|
||||
.expect("re-executed exemplar child");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn labelsets(
|
||||
definition: &crate::schema::MetricDefinition,
|
||||
) -> Vec<Vec<(&'static str, &'static str)>> {
|
||||
let mut combos: Vec<Vec<(&'static str, &'static str)>> = vec![Vec::new()];
|
||||
for domain in definition.label_domains {
|
||||
let mut next = Vec::with_capacity(combos.len() * domain.values.len());
|
||||
for combo in &combos {
|
||||
for value in domain.values {
|
||||
let mut extended = combo.clone();
|
||||
extended.push((domain.name, *value));
|
||||
next.push(extended);
|
||||
}
|
||||
}
|
||||
combos = next;
|
||||
}
|
||||
combos
|
||||
}
|
||||
|
||||
fn store_len() -> usize {
|
||||
store().lock().map(|entries| entries.len()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// TD-X3 — maximal private population: projected domain сервиса заполняет
|
||||
/// ровно `capacity` slots (11508/2310) и следующий distinct key отвергается.
|
||||
///
|
||||
/// Родитель без роли запускает **оба** дочерних процесса (`admin_api` и
|
||||
/// `mcp_server`), печатает результат каждого ребёнка и требует явный отчёт
|
||||
/// `TD-X3 CHILD role=…`; дочерние прогоны различаются ролью (рабочий
|
||||
/// каталог), а не глобальным reset.
|
||||
#[test]
|
||||
fn full_projected_domain_fills_exactly() {
|
||||
match current_role().as_deref() {
|
||||
Some("admin_api") => {
|
||||
report_child("admin_api", fill_and_check(MetricService::AdminApi, 12_348))
|
||||
}
|
||||
Some("mcp_server") => report_child(
|
||||
"mcp_server",
|
||||
fill_and_check(MetricService::McpServer, 2_310),
|
||||
),
|
||||
Some(other) => panic!("unexpected exemplar role {other}"),
|
||||
None => {
|
||||
for role in ["admin_api", "mcp_server"] {
|
||||
let directory = role_dir(role);
|
||||
std::fs::create_dir_all(&directory).expect("exemplar role dir");
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().expect("test binary"))
|
||||
.args([
|
||||
"exemplar::tests::full_projected_domain_fills_exactly",
|
||||
"--exact",
|
||||
"--nocapture",
|
||||
])
|
||||
.current_dir(&directory)
|
||||
.output()
|
||||
.expect("re-executed exemplar child");
|
||||
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
|
||||
for line in stdout.lines().filter(|line| line.contains("TD-X3 CHILD")) {
|
||||
println!("{line}");
|
||||
}
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{role} child failed:\nstdout:\n{stdout}\nstderr:\n{stderr}"
|
||||
);
|
||||
assert!(
|
||||
stdout.contains(&format!("TD-X3 CHILD role={role}")),
|
||||
"{role} child обязан явно отчитаться своим отчётом:\n{stdout}\n{stderr}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn report_child(role: &str, counts: (usize, usize, usize)) {
|
||||
let (enumerated, capacity, store_len) = counts;
|
||||
println!(
|
||||
"TD-X3 CHILD role={role} enumerated={enumerated} capacity={capacity} store_len={store_len}"
|
||||
);
|
||||
}
|
||||
|
||||
fn fill_and_check(service: MetricService, expected: usize) -> (usize, usize, usize) {
|
||||
crate::bind_metric_service(service).expect("binding for the exemplar population");
|
||||
assert_eq!(
|
||||
store_len(),
|
||||
0,
|
||||
"fresh child обязан начинать с пустого store"
|
||||
);
|
||||
|
||||
let mut enumerated = 0_usize;
|
||||
for definition in service_projection(service) {
|
||||
if definition.kind != MetricKind::Histogram {
|
||||
continue;
|
||||
}
|
||||
for labels in labelsets(definition) {
|
||||
for index in 0..=definition.buckets.len() {
|
||||
let value =
|
||||
definition.buckets.get(index).copied().unwrap_or_else(|| {
|
||||
definition.buckets[definition.buckets.len() - 1] + 1.0
|
||||
});
|
||||
record_exemplar(
|
||||
service,
|
||||
definition.name,
|
||||
labels.clone(),
|
||||
value,
|
||||
Some(trace()),
|
||||
);
|
||||
enumerated += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
enumerated, expected,
|
||||
"projected domain обязан дать ровно {expected} slots"
|
||||
);
|
||||
assert_eq!(
|
||||
service_capacity(service),
|
||||
expected,
|
||||
"capacity обязана совпасть с projected domain"
|
||||
);
|
||||
assert_eq!(
|
||||
store_len(),
|
||||
expected,
|
||||
"все slot'ы обязаны быть заполнены без потерь"
|
||||
);
|
||||
|
||||
// Существующий ключ принимает последнее наблюдение и не растит store.
|
||||
let definition = service_projection(service)
|
||||
.iter()
|
||||
.find(|definition| definition.kind == MetricKind::Histogram)
|
||||
.expect("histogram family");
|
||||
let labels = labelsets(definition)
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("первый label set проекции");
|
||||
let refreshed = definition.buckets[0] * 0.5;
|
||||
record_exemplar(
|
||||
service,
|
||||
definition.name,
|
||||
labels.clone(),
|
||||
refreshed,
|
||||
Some(trace()),
|
||||
);
|
||||
assert_eq!(
|
||||
store_len(),
|
||||
expected,
|
||||
"повторная запись ключа не растёт store"
|
||||
);
|
||||
let latest = exemplar_snapshot()
|
||||
.into_iter()
|
||||
.find(|observation| {
|
||||
observation.metric == definition.name
|
||||
&& observation.labels == labels
|
||||
&& observation.bucket_upper_bound == Some(definition.buckets[0])
|
||||
})
|
||||
.expect("latest observation для существующего ключа");
|
||||
assert_eq!(
|
||||
latest.value, refreshed,
|
||||
"для существующего ключа сохраняется последнее наблюдение"
|
||||
);
|
||||
|
||||
// Бюджет исчерпан: следующий distinct key отвергается, store не растёт.
|
||||
// Его `route` — own/shared и проходит ownership guard, поэтому рост
|
||||
// останавливает именно capacity, а не приватная проверка владения.
|
||||
record_exemplar(
|
||||
service,
|
||||
definition.name,
|
||||
vec![("route", "/health"), ("method", "__overflow_probe__")],
|
||||
definition.buckets[0],
|
||||
Some(trace()),
|
||||
);
|
||||
assert_eq!(store_len(), expected, "store не может превысить capacity");
|
||||
|
||||
(enumerated, service_capacity(service), store_len())
|
||||
}
|
||||
|
||||
/// F1 — приватный exemplar boundary независимо проверяет bound service,
|
||||
/// family ownership и HTTP route ownership: unbound, чужой сервис и
|
||||
/// чужой/невалидный route не создают store key при доступной capacity;
|
||||
/// positive control и public normalized path сохраняются.
|
||||
#[test]
|
||||
fn private_exemplar_requires_bound_service_and_route_ownership() {
|
||||
if route_to_child_role(
|
||||
"guard",
|
||||
"exemplar::tests::private_exemplar_requires_bound_service_and_route_ownership",
|
||||
) {
|
||||
return;
|
||||
}
|
||||
match current_role().as_deref() {
|
||||
Some("guard") => guard_ownership_child(),
|
||||
Some(other) => panic!("unexpected exemplar role {other}"),
|
||||
None => unreachable!("role checked above"),
|
||||
}
|
||||
}
|
||||
|
||||
fn guard_ownership_child() {
|
||||
const HTTP_HISTOGRAM: &str = "crank_http_request_duration_seconds";
|
||||
assert_eq!(
|
||||
store_len(),
|
||||
0,
|
||||
"fresh guard child обязан начинать с пустого store"
|
||||
);
|
||||
|
||||
// 1. Unbound процесс: приватный вход не создаёт ни ключа, ни entry.
|
||||
record_exemplar(
|
||||
MetricService::AdminApi,
|
||||
HTTP_HISTOGRAM,
|
||||
vec![("route", "/health"), ("method", "GET")],
|
||||
DURATION_BUCKETS_SECONDS[0],
|
||||
Some(trace()),
|
||||
);
|
||||
assert_eq!(store_len(), 0, "unbound record не может аллоцировать key");
|
||||
|
||||
crate::bind_metric_service(MetricService::AdminApi).expect("admin binding");
|
||||
|
||||
// 2. Mismatched service: bound сервис — admin, вызывающий передаёт MCP.
|
||||
record_exemplar(
|
||||
MetricService::McpServer,
|
||||
"crank_mcp_request_duration_seconds",
|
||||
vec![("method", "tools_call"), ("outcome", "success")],
|
||||
DURATION_BUCKETS_SECONDS[0],
|
||||
Some(trace()),
|
||||
);
|
||||
// 3. Foreign HTTP route: /v1/... принадлежит MCP, а не bound admin.
|
||||
record_exemplar(
|
||||
MetricService::AdminApi,
|
||||
HTTP_HISTOGRAM,
|
||||
vec![
|
||||
("route", "/v1/{workspace_slug}/{agent_slug}"),
|
||||
("method", "GET"),
|
||||
],
|
||||
DURATION_BUCKETS_SECONDS[0],
|
||||
Some(trace()),
|
||||
);
|
||||
// 4. Route label отсутствует в family, объявляющей route domain.
|
||||
record_exemplar(
|
||||
MetricService::AdminApi,
|
||||
HTTP_HISTOGRAM,
|
||||
vec![("method", "GET")],
|
||||
DURATION_BUCKETS_SECONDS[0],
|
||||
Some(trace()),
|
||||
);
|
||||
// 5. Неизвестный (не нормализуемый) route text.
|
||||
record_exemplar(
|
||||
MetricService::AdminApi,
|
||||
HTTP_HISTOGRAM,
|
||||
vec![("route", "/documents/{document_id}"), ("method", "GET")],
|
||||
DURATION_BUCKETS_SECONDS[0],
|
||||
Some(trace()),
|
||||
);
|
||||
assert_eq!(
|
||||
store_len(),
|
||||
0,
|
||||
"invalid/unbound входы не могут аллоцировать store key"
|
||||
);
|
||||
assert!(exemplar_snapshot().is_empty());
|
||||
|
||||
// Positive control: own/shared normalised route принята.
|
||||
record_exemplar(
|
||||
MetricService::AdminApi,
|
||||
HTTP_HISTOGRAM,
|
||||
vec![("route", "/health"), ("method", "GET")],
|
||||
DURATION_BUCKETS_SECONDS[0],
|
||||
Some(trace()),
|
||||
);
|
||||
assert_eq!(store_len(), 1, "own/shared route обязан быть записан");
|
||||
|
||||
// Public normalized path сохранён: чужая route деградирует в unmatched,
|
||||
// aggregate и exemplar записываются под нормализованным ключом.
|
||||
let recorder = metrics_util::debugging::DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
crate::record_http_request_with_exemplar(
|
||||
crate::HttpRoute::from_matched_path("/v1/{workspace_slug}/{agent_slug}"),
|
||||
crate::HttpMethod::Get,
|
||||
crate::HttpStatusClass::Success,
|
||||
std::time::Duration::from_millis(4),
|
||||
Some(trace()),
|
||||
);
|
||||
});
|
||||
let samples = snapshotter.snapshot().into_vec();
|
||||
assert!(
|
||||
samples
|
||||
.iter()
|
||||
.any(|(key, _, _, _)| key.key().name() == "crank_http_requests_total"),
|
||||
"public normalized aggregate обязан быть записан"
|
||||
);
|
||||
assert!(
|
||||
exemplar_snapshot().iter().any(|observation| {
|
||||
observation.metric == HTTP_HISTOGRAM
|
||||
&& observation
|
||||
.labels
|
||||
.iter()
|
||||
.any(|(name, value)| *name == "route" && *value == "unmatched")
|
||||
}),
|
||||
"public normalized exemplar обязан быть записан под unmatched"
|
||||
);
|
||||
assert_eq!(
|
||||
store_len(),
|
||||
2,
|
||||
"public path добавляет ровно один normalized unmatched key"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-X5 — poisoned store никогда не ломает product path.
|
||||
#[test]
|
||||
fn poisoned_store_never_breaks_product_path() {
|
||||
if route_to_child_role(
|
||||
"poison",
|
||||
"exemplar::tests::poisoned_store_never_breaks_product_path",
|
||||
) {
|
||||
return;
|
||||
}
|
||||
match current_role().as_deref() {
|
||||
Some("poison") => {
|
||||
crate::bind_metric_service(MetricService::AdminApi).expect("admin binding");
|
||||
let _ = std::thread::spawn(|| {
|
||||
let _guard = store().lock().expect("store lock");
|
||||
panic!("poison the exemplar store");
|
||||
})
|
||||
.join();
|
||||
assert!(store().is_poisoned(), "store обязан быть poisoned");
|
||||
|
||||
// Aggregate-путь уже записан; exemplar обязан безопасно ничего не делать.
|
||||
let recorder = metrics_util::debugging::DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
crate::record_http_request_with_exemplar(
|
||||
crate::HttpRoute::from_matched_path("/health"),
|
||||
crate::HttpMethod::Get,
|
||||
crate::HttpStatusClass::Success,
|
||||
std::time::Duration::from_millis(4),
|
||||
Some(trace()),
|
||||
);
|
||||
});
|
||||
let samples = snapshotter.snapshot().into_vec();
|
||||
assert!(
|
||||
samples
|
||||
.iter()
|
||||
.any(|(key, _, _, _)| key.key().name() == "crank_http_requests_total"),
|
||||
"aggregate обязан быть записан несмотря на poisoned store"
|
||||
);
|
||||
assert_eq!(store_len(), 0, "poisoned store не принимает новых entries");
|
||||
assert!(exemplar_snapshot().is_empty());
|
||||
}
|
||||
Some(other) => panic!("unexpected exemplar role {other}"),
|
||||
None => unreachable!("role checked above"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,11 @@
|
||||
//! Product crate передают только типизированные значения. Имена метрик,
|
||||
//! ключи и значения labels сосредоточены здесь, поэтому пользовательские
|
||||
//! идентификаторы и тексты нельзя случайно превратить во временные ряды.
|
||||
//!
|
||||
//! Story 3.6: допустимые HTTP-идентичности выводятся из **одного** typed
|
||||
//! перечисления route+owners (`HTTP_ROUTES`); каждый процесс один раз
|
||||
//! фиксирует сервис (`bind_metric_service`) до установки recorder, иначе все
|
||||
//! recording-пути безопасно ничего не делают.
|
||||
|
||||
mod exemplar;
|
||||
mod labels;
|
||||
@@ -17,8 +22,9 @@ pub use labels::{
|
||||
UpstreamOutcome,
|
||||
};
|
||||
pub use record::{
|
||||
InFlightGuard, ToolInvocationMetrics, UpstreamRequestMetrics, initialize_gauges,
|
||||
record_cache_outcome, record_confirmation_outcome, record_export_failure, record_http_request,
|
||||
InFlightGuard, ToolInvocationMetrics, UpstreamRequestMetrics, bind_metric_service,
|
||||
bound_metric_service, initialize_gauges, normalize_http_route, record_cache_outcome,
|
||||
record_confirmation_outcome, record_export_failure, record_http_request,
|
||||
record_http_request_with_exemplar, record_idempotency_outcome, record_invocation_history_lost,
|
||||
record_limit_rejection, record_mcp_request, record_mcp_request_with_exemplar,
|
||||
record_tool_invocation, record_tool_invocation_with_exemplar, record_upstream_request,
|
||||
@@ -26,10 +32,13 @@ pub use record::{
|
||||
set_mcp_active_sessions, set_mcp_session_metrics_fresh,
|
||||
};
|
||||
pub use schema::{
|
||||
DURATION_BUCKETS_SECONDS, HTTP_ROUTE_DOMAIN, LabelClass, LabelDomain, MAX_EXPOSITION_BYTES,
|
||||
MAX_LOGICAL_SERIES_PER_PROCESS, MAX_METRIC_FAMILIES, MAX_PRODUCT_LABELS_PER_FAMILY,
|
||||
MAX_RENDERED_SERIES_PER_PROCESS, METRIC_SCHEMA_VERSION, MetricDefinition, MetricKind,
|
||||
MetricProcess, MetricService, MetricUnit, PROCESS_CONSTANT_LABELS, SchemaBudget, SchemaError,
|
||||
max_exemplar_slots, metric_schema, metric_schema_for_service, render_metric_schema_json,
|
||||
schema_budget, validate_budget, validate_schema,
|
||||
ADMIN_HTTP_ROUTE_DOMAIN, DURATION_BUCKETS_SECONDS, HTTP_ROUTE_DOMAIN, HTTP_ROUTES,
|
||||
HttpRouteDefinition, LabelClass, LabelDomain, MAX_EXEMPLAR_SLOTS_PER_PROCESS,
|
||||
MAX_EXPOSITION_BYTES, MAX_LOGICAL_SERIES_PER_PROCESS, MAX_METRIC_FAMILIES,
|
||||
MAX_PRODUCT_LABELS_PER_FAMILY, MAX_RENDERED_SERIES_PER_PROCESS, MCP_HTTP_ROUTE_DOMAIN,
|
||||
METRIC_SCHEMA_VERSION, MetricBindingError, MetricDefinition, MetricKind, MetricProcess,
|
||||
MetricService, MetricUnit, PROCESS_CONSTANT_LABELS, SchemaBudget, SchemaError,
|
||||
http_route_processes, max_exemplar_slots, metric_schema, metric_schema_for_service,
|
||||
render_metric_schema_json, schema_budget, service_projection, validate_all_projections,
|
||||
validate_budget, validate_exemplar_budget, validate_http_routes, validate_schema,
|
||||
};
|
||||
@@ -1,14 +1,63 @@
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use metrics::Gauge;
|
||||
|
||||
use crate::schema::{MetricDefinition, metric_schema};
|
||||
use crate::{
|
||||
CacheOutcome, ConfirmationOutcome, DbPoolState, ExemplarTraceId, Exporter, HttpMethod,
|
||||
HttpRoute, HttpStatusClass, IdempotencyOutcome, InvocationSource, LimitStage, McpMethod,
|
||||
McpOutcome, McpResponseMode, SignalType, ToolErrorKind, ToolOutcome, UpstreamOperationKind,
|
||||
UpstreamOutcome,
|
||||
McpOutcome, McpResponseMode, MetricBindingError, MetricService, SignalType, ToolErrorKind,
|
||||
ToolOutcome, UpstreamOperationKind, UpstreamOutcome,
|
||||
};
|
||||
|
||||
static BINDING: OnceLock<MetricService> = OnceLock::new();
|
||||
|
||||
/// Publishes the closed process identity exactly once, before the recorder,
|
||||
/// gauges, producers and any listener exist. Re-binding the same service is
|
||||
/// idempotent; a different service is a typed conflict and never wins twice.
|
||||
pub fn bind_metric_service(service: MetricService) -> Result<(), MetricBindingError> {
|
||||
crate::schema::validate_all_projections().map_err(|_| MetricBindingError::InvalidSchema)?;
|
||||
// `OnceLock::set` returns `Err(value)` (the value passed in, not the stored
|
||||
// one), so the idempotency check must read the published binding back.
|
||||
if BINDING.set(service).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
match BINDING.get() {
|
||||
Some(existing) if *existing == service => Ok(()),
|
||||
_ => Err(MetricBindingError::ConflictingService),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bound_metric_service() -> Option<MetricService> {
|
||||
BINDING.get().copied()
|
||||
}
|
||||
|
||||
/// Normalises one route against the bound service: own and shared routes are
|
||||
/// preserved, a known route owned by another service degrades to `unmatched`.
|
||||
pub fn normalize_http_route(service: MetricService, route: HttpRoute) -> HttpRoute {
|
||||
match crate::http_route_processes(route.as_str()) {
|
||||
Some(owners) if owners.contains(&service.process()) => route,
|
||||
_ => HttpRoute::unmatched(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn family_applies(service: MetricService, name: &'static str) -> bool {
|
||||
metric_schema()
|
||||
.iter()
|
||||
.find(|definition| definition.name == name)
|
||||
.is_some_and(|definition: &MetricDefinition| {
|
||||
definition.processes.contains(&service.process())
|
||||
})
|
||||
}
|
||||
|
||||
/// Unbound facades (plain unit tests or libraries without observability) are a
|
||||
/// safe no-op; the process never registers a metric handle or exemplar entry.
|
||||
fn bound_family(name: &'static str) -> Option<MetricService> {
|
||||
let service = BINDING.get().copied()?;
|
||||
family_applies(service, name).then_some(service)
|
||||
}
|
||||
|
||||
pub fn record_http_request(
|
||||
route: HttpRoute,
|
||||
method: HttpMethod,
|
||||
@@ -25,6 +74,10 @@ pub fn record_http_request_with_exemplar(
|
||||
duration: Duration,
|
||||
exemplar: Option<ExemplarTraceId>,
|
||||
) {
|
||||
let Some(service) = bound_family("crank_http_requests_total") else {
|
||||
return;
|
||||
};
|
||||
let route = normalize_http_route(service, route);
|
||||
metrics::counter!(
|
||||
"crank_http_requests_total",
|
||||
"route" => route.as_str(),
|
||||
@@ -39,6 +92,7 @@ pub fn record_http_request_with_exemplar(
|
||||
)
|
||||
.record(duration.as_secs_f64());
|
||||
crate::exemplar::record_exemplar(
|
||||
service,
|
||||
"crank_http_request_duration_seconds",
|
||||
vec![("route", route.as_str()), ("method", method.as_str())],
|
||||
duration.as_secs_f64(),
|
||||
@@ -62,6 +116,9 @@ pub fn record_mcp_request_with_exemplar(
|
||||
duration: Duration,
|
||||
exemplar: Option<ExemplarTraceId>,
|
||||
) {
|
||||
let Some(service) = bound_family("crank_mcp_requests_total") else {
|
||||
return;
|
||||
};
|
||||
metrics::counter!(
|
||||
"crank_mcp_requests_total",
|
||||
"method" => method.as_str(),
|
||||
@@ -76,6 +133,7 @@ pub fn record_mcp_request_with_exemplar(
|
||||
)
|
||||
.record(duration.as_secs_f64());
|
||||
crate::exemplar::record_exemplar(
|
||||
service,
|
||||
"crank_mcp_request_duration_seconds",
|
||||
vec![("method", method.as_str()), ("outcome", outcome.as_str())],
|
||||
duration.as_secs_f64(),
|
||||
@@ -84,10 +142,16 @@ pub fn record_mcp_request_with_exemplar(
|
||||
}
|
||||
|
||||
pub fn set_mcp_active_sessions(count: u64) {
|
||||
if bound_family("crank_mcp_active_sessions").is_none() {
|
||||
return;
|
||||
}
|
||||
metrics::gauge!("crank_mcp_active_sessions").set(count as f64);
|
||||
}
|
||||
|
||||
pub fn set_mcp_session_metrics_fresh(fresh: bool) {
|
||||
if bound_family("crank_mcp_session_metrics_fresh").is_none() {
|
||||
return;
|
||||
}
|
||||
metrics::gauge!("crank_mcp_session_metrics_fresh").set(if fresh { 1.0 } else { 0.0 });
|
||||
}
|
||||
|
||||
@@ -107,6 +171,9 @@ pub fn record_tool_invocation_with_exemplar(
|
||||
duration: Duration,
|
||||
exemplar: Option<ExemplarTraceId>,
|
||||
) {
|
||||
let Some(service) = bound_family("crank_tool_invocations_total") else {
|
||||
return;
|
||||
};
|
||||
let error_kind = match outcome {
|
||||
ToolOutcome::Success => ToolErrorKind::None,
|
||||
ToolOutcome::Aborted => ToolErrorKind::Aborted,
|
||||
@@ -131,6 +198,7 @@ pub fn record_tool_invocation_with_exemplar(
|
||||
)
|
||||
.record(duration.as_secs_f64());
|
||||
crate::exemplar::record_exemplar(
|
||||
service,
|
||||
"crank_tool_invocation_duration_seconds",
|
||||
vec![("source", source.as_str()), ("outcome", outcome.as_str())],
|
||||
duration.as_secs_f64(),
|
||||
@@ -152,6 +220,9 @@ pub fn record_upstream_request_with_exemplar(
|
||||
duration: Duration,
|
||||
exemplar: Option<ExemplarTraceId>,
|
||||
) {
|
||||
let Some(service) = bound_family("crank_upstream_requests_total") else {
|
||||
return;
|
||||
};
|
||||
metrics::counter!(
|
||||
"crank_upstream_requests_total",
|
||||
"operation_kind" => operation_kind.as_str(),
|
||||
@@ -165,6 +236,7 @@ pub fn record_upstream_request_with_exemplar(
|
||||
)
|
||||
.record(duration.as_secs_f64());
|
||||
crate::exemplar::record_exemplar(
|
||||
service,
|
||||
"crank_upstream_request_duration_seconds",
|
||||
vec![
|
||||
("operation_kind", operation_kind.as_str()),
|
||||
@@ -179,25 +251,24 @@ pub struct ToolInvocationMetrics {
|
||||
source: InvocationSource,
|
||||
started_at: Option<Instant>,
|
||||
exemplar: Option<ExemplarTraceId>,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl ToolInvocationMetrics {
|
||||
pub fn start(source: InvocationSource) -> Self {
|
||||
Self {
|
||||
source,
|
||||
started_at: Some(Instant::now()),
|
||||
exemplar: None,
|
||||
}
|
||||
Self::start_with_exemplar(source, None)
|
||||
}
|
||||
|
||||
pub fn start_with_exemplar(
|
||||
source: InvocationSource,
|
||||
exemplar: Option<ExemplarTraceId>,
|
||||
) -> Self {
|
||||
let active = bound_family("crank_tool_invocations_total").is_some();
|
||||
Self {
|
||||
source,
|
||||
started_at: Some(Instant::now()),
|
||||
started_at: active.then(Instant::now),
|
||||
exemplar,
|
||||
active,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,7 +291,9 @@ impl ToolInvocationMetrics {
|
||||
|
||||
impl Drop for ToolInvocationMetrics {
|
||||
fn drop(&mut self) {
|
||||
self.finish(ToolOutcome::Aborted, ToolErrorKind::Aborted);
|
||||
if self.active {
|
||||
self.finish(ToolOutcome::Aborted, ToolErrorKind::Aborted);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,25 +301,24 @@ pub struct UpstreamRequestMetrics {
|
||||
operation_kind: UpstreamOperationKind,
|
||||
started_at: Option<Instant>,
|
||||
exemplar: Option<ExemplarTraceId>,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl UpstreamRequestMetrics {
|
||||
pub fn start(operation_kind: UpstreamOperationKind) -> Self {
|
||||
Self {
|
||||
operation_kind,
|
||||
started_at: Some(Instant::now()),
|
||||
exemplar: None,
|
||||
}
|
||||
Self::start_with_exemplar(operation_kind, None)
|
||||
}
|
||||
|
||||
pub fn start_with_exemplar(
|
||||
operation_kind: UpstreamOperationKind,
|
||||
exemplar: Option<ExemplarTraceId>,
|
||||
) -> Self {
|
||||
let active = bound_family("crank_upstream_requests_total").is_some();
|
||||
Self {
|
||||
operation_kind,
|
||||
started_at: Some(Instant::now()),
|
||||
started_at: active.then(Instant::now),
|
||||
exemplar,
|
||||
active,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,11 +340,16 @@ impl UpstreamRequestMetrics {
|
||||
|
||||
impl Drop for UpstreamRequestMetrics {
|
||||
fn drop(&mut self) {
|
||||
self.finish(UpstreamOutcome::Aborted);
|
||||
if self.active {
|
||||
self.finish(UpstreamOutcome::Aborted);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record_limit_rejection(stage: LimitStage) {
|
||||
if bound_family("crank_runtime_limit_rejections_total").is_none() {
|
||||
return;
|
||||
}
|
||||
metrics::counter!(
|
||||
"crank_runtime_limit_rejections_total",
|
||||
"stage" => stage.as_str()
|
||||
@@ -281,6 +358,9 @@ pub fn record_limit_rejection(stage: LimitStage) {
|
||||
}
|
||||
|
||||
pub fn record_cache_outcome(outcome: CacheOutcome) {
|
||||
if bound_family("crank_runtime_cache_total").is_none() {
|
||||
return;
|
||||
}
|
||||
metrics::counter!(
|
||||
"crank_runtime_cache_total",
|
||||
"outcome" => outcome.as_str()
|
||||
@@ -289,6 +369,9 @@ pub fn record_cache_outcome(outcome: CacheOutcome) {
|
||||
}
|
||||
|
||||
pub fn record_idempotency_outcome(outcome: IdempotencyOutcome) {
|
||||
if bound_family("crank_idempotency_total").is_none() {
|
||||
return;
|
||||
}
|
||||
metrics::counter!(
|
||||
"crank_idempotency_total",
|
||||
"outcome" => outcome.as_str()
|
||||
@@ -297,6 +380,9 @@ pub fn record_idempotency_outcome(outcome: IdempotencyOutcome) {
|
||||
}
|
||||
|
||||
pub fn record_confirmation_outcome(outcome: ConfirmationOutcome) {
|
||||
if bound_family("crank_confirmation_total").is_none() {
|
||||
return;
|
||||
}
|
||||
metrics::counter!(
|
||||
"crank_confirmation_total",
|
||||
"outcome" => outcome.as_str()
|
||||
@@ -305,6 +391,9 @@ pub fn record_confirmation_outcome(outcome: ConfirmationOutcome) {
|
||||
}
|
||||
|
||||
pub fn set_db_pool_connections(state: DbPoolState, count: u32) {
|
||||
if bound_family("crank_db_pool_connections").is_none() {
|
||||
return;
|
||||
}
|
||||
metrics::gauge!(
|
||||
"crank_db_pool_connections",
|
||||
"state" => state.as_str()
|
||||
@@ -313,16 +402,25 @@ pub fn set_db_pool_connections(state: DbPoolState, count: u32) {
|
||||
}
|
||||
|
||||
pub fn set_catalog(tool_count: usize, estimated_context_tokens: usize, warnings: usize) {
|
||||
if bound_family("crank_catalog_tools").is_none() {
|
||||
return;
|
||||
}
|
||||
metrics::gauge!("crank_catalog_tools").set(tool_count as f64);
|
||||
metrics::gauge!("crank_catalog_estimated_context_tokens").set(estimated_context_tokens as f64);
|
||||
metrics::gauge!("crank_catalog_warnings").set(warnings as f64);
|
||||
}
|
||||
|
||||
pub fn record_invocation_history_lost() {
|
||||
if bound_family("crank_invocation_history_lost_total").is_none() {
|
||||
return;
|
||||
}
|
||||
metrics::counter!("crank_invocation_history_lost_total").increment(1);
|
||||
}
|
||||
|
||||
pub fn record_export_failure(signal: SignalType, exporter: Exporter) {
|
||||
if bound_family("crank_telemetry_export_failures_total").is_none() {
|
||||
return;
|
||||
}
|
||||
metrics::counter!(
|
||||
"crank_telemetry_export_failures_total",
|
||||
"signal_type" => signal.as_str(),
|
||||
@@ -331,44 +429,65 @@ pub fn record_export_failure(signal: SignalType, exporter: Exporter) {
|
||||
.increment(1);
|
||||
}
|
||||
|
||||
pub fn initialize_gauges(service: crate::MetricService) {
|
||||
metrics::gauge!("crank_http_inflight").set(0.0);
|
||||
metrics::gauge!("crank_runtime_inflight").set(0.0);
|
||||
/// Gauges are initialised only for the bound service; any other service (or an
|
||||
/// unbound process) is a no-op and never registers a handle.
|
||||
pub fn initialize_gauges(service: MetricService) {
|
||||
if bound_metric_service() != Some(service) {
|
||||
return;
|
||||
}
|
||||
if family_applies(service, "crank_http_inflight") {
|
||||
metrics::gauge!("crank_http_inflight").set(0.0);
|
||||
}
|
||||
if family_applies(service, "crank_runtime_inflight") {
|
||||
metrics::gauge!("crank_runtime_inflight").set(0.0);
|
||||
}
|
||||
set_db_pool_connections(DbPoolState::Idle, 0);
|
||||
set_db_pool_connections(DbPoolState::Used, 0);
|
||||
if service == crate::MetricService::McpServer {
|
||||
metrics::gauge!("crank_mcp_active_sessions").set(0.0);
|
||||
if service == MetricService::McpServer {
|
||||
set_mcp_active_sessions(0);
|
||||
set_mcp_session_metrics_fresh(false);
|
||||
metrics::gauge!("crank_mcp_active_streams").set(0.0);
|
||||
if family_applies(service, "crank_mcp_active_streams") {
|
||||
metrics::gauge!("crank_mcp_active_streams").set(0.0);
|
||||
}
|
||||
set_catalog(0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InFlightGuard {
|
||||
gauge: Gauge,
|
||||
gauge: Option<Gauge>,
|
||||
}
|
||||
|
||||
impl InFlightGuard {
|
||||
pub fn http() -> Self {
|
||||
Self::increment(metrics::gauge!("crank_http_inflight"))
|
||||
Self::increment("crank_http_inflight")
|
||||
}
|
||||
|
||||
pub fn runtime() -> Self {
|
||||
Self::increment(metrics::gauge!("crank_runtime_inflight"))
|
||||
Self::increment("crank_runtime_inflight")
|
||||
}
|
||||
|
||||
pub fn mcp_stream() -> Self {
|
||||
Self::increment(metrics::gauge!("crank_mcp_active_streams"))
|
||||
Self::increment("crank_mcp_active_streams")
|
||||
}
|
||||
|
||||
fn increment(gauge: Gauge) -> Self {
|
||||
fn increment(name: &'static str) -> Self {
|
||||
if bound_family(name).is_none() {
|
||||
return Self { gauge: None };
|
||||
}
|
||||
let gauge = match name {
|
||||
"crank_http_inflight" => metrics::gauge!("crank_http_inflight"),
|
||||
"crank_runtime_inflight" => metrics::gauge!("crank_runtime_inflight"),
|
||||
_ => metrics::gauge!("crank_mcp_active_streams"),
|
||||
};
|
||||
gauge.increment(1.0);
|
||||
Self { gauge }
|
||||
Self { gauge: Some(gauge) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InFlightGuard {
|
||||
fn drop(&mut self) {
|
||||
self.gauge.decrement(1.0);
|
||||
if let Some(gauge) = &self.gauge {
|
||||
gauge.decrement(1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,772 +1,34 @@
|
||||
use std::collections::BTreeSet;
|
||||
//! Реестр метрик: корень модуля (wiring + ре-экспорты подмодулей).
|
||||
//!
|
||||
//! Разбиение чисто механическое: имена и сигнатуры всех items не изменились,
|
||||
//! поэтому и пути `crate::schema::<Item>` внутри крейта, и список
|
||||
//! `pub use schema::{...}` в `lib.rs` остаются валидными без правок.
|
||||
|
||||
use crate::labels::{
|
||||
CacheOutcome, ConfirmationOutcome, DbPoolState, Exporter, HttpMethod, HttpStatusClass,
|
||||
IdempotencyOutcome, InvocationSource, LimitStage, McpMethod, McpOutcome, McpResponseMode,
|
||||
SignalType, ToolErrorKind, ToolOutcome, UpstreamOperationKind, UpstreamOutcome,
|
||||
mod budget;
|
||||
#[cfg(test)]
|
||||
mod checked_arithmetic_tests;
|
||||
mod descriptor;
|
||||
mod projection;
|
||||
mod rendering;
|
||||
mod routes;
|
||||
|
||||
pub(crate) use budget::checked_exemplar_capacity;
|
||||
pub use budget::{
|
||||
MetricBindingError, SchemaBudget, SchemaError, validate_all_projections, validate_budget,
|
||||
validate_exemplar_budget, validate_schema,
|
||||
};
|
||||
pub use descriptor::{
|
||||
DURATION_BUCKETS_SECONDS, LabelClass, LabelDomain, MAX_EXEMPLAR_SLOTS_PER_PROCESS,
|
||||
MAX_EXPOSITION_BYTES, MAX_LOGICAL_SERIES_PER_PROCESS, MAX_METRIC_FAMILIES,
|
||||
MAX_PRODUCT_LABELS_PER_FAMILY, MAX_RENDERED_SERIES_PER_PROCESS, METRIC_SCHEMA_VERSION,
|
||||
MetricDefinition, MetricKind, MetricProcess, MetricService, MetricUnit,
|
||||
PROCESS_CONSTANT_LABELS, metric_schema,
|
||||
};
|
||||
pub use projection::{
|
||||
max_exemplar_slots, metric_schema_for_service, schema_budget, service_projection,
|
||||
};
|
||||
pub use rendering::render_metric_schema_json;
|
||||
pub use routes::{
|
||||
ADMIN_HTTP_ROUTE_DOMAIN, HTTP_ROUTE_DOMAIN, HTTP_ROUTES, HttpRouteDefinition,
|
||||
MCP_HTTP_ROUTE_DOMAIN, http_route_processes, validate_http_routes,
|
||||
};
|
||||
|
||||
pub const METRIC_SCHEMA_VERSION: u32 = 1;
|
||||
pub const MAX_METRIC_FAMILIES: usize = 128;
|
||||
pub const MAX_PRODUCT_LABELS_PER_FAMILY: usize = 4;
|
||||
pub const MAX_LOGICAL_SERIES_PER_PROCESS: usize = 5_563;
|
||||
pub const MAX_RENDERED_SERIES_PER_PROCESS: usize = 17_638;
|
||||
pub const MAX_EXPOSITION_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MetricKind {
|
||||
Counter,
|
||||
Gauge,
|
||||
Histogram,
|
||||
}
|
||||
|
||||
impl MetricKind {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Counter => "counter",
|
||||
Self::Gauge => "gauge",
|
||||
Self::Histogram => "histogram",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MetricUnit {
|
||||
Count,
|
||||
Seconds,
|
||||
}
|
||||
|
||||
impl MetricUnit {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Count => "count",
|
||||
Self::Seconds => "seconds",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MetricProcess {
|
||||
AdminApi,
|
||||
McpServer,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MetricService {
|
||||
AdminApi,
|
||||
McpServer,
|
||||
}
|
||||
|
||||
impl MetricService {
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"admin-api" => Some(Self::AdminApi),
|
||||
"mcp-server" => Some(Self::McpServer),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn process(self) -> MetricProcess {
|
||||
match self {
|
||||
Self::AdminApi => MetricProcess::AdminApi,
|
||||
Self::McpServer => MetricProcess::McpServer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetricProcess {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::AdminApi => "admin_api",
|
||||
Self::McpServer => "mcp_server",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum LabelClass {
|
||||
ProductClosed,
|
||||
ProcessConstant,
|
||||
}
|
||||
|
||||
impl LabelClass {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::ProductClosed => "product_closed",
|
||||
Self::ProcessConstant => "process_constant",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct LabelDomain {
|
||||
pub name: &'static str,
|
||||
pub class: LabelClass,
|
||||
pub values: &'static [&'static str],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MetricDefinition {
|
||||
pub name: &'static str,
|
||||
pub kind: MetricKind,
|
||||
pub unit: MetricUnit,
|
||||
pub labels: &'static [&'static str],
|
||||
pub label_domains: &'static [LabelDomain],
|
||||
pub buckets: &'static [f64],
|
||||
pub processes: &'static [MetricProcess],
|
||||
pub max_logical_series: usize,
|
||||
pub max_rendered_series: usize,
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct SchemaBudget {
|
||||
pub logical_series: usize,
|
||||
pub rendered_series: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum SchemaError {
|
||||
TooManyFamilies,
|
||||
DuplicateMetric,
|
||||
InvalidMetric,
|
||||
DuplicateLabel,
|
||||
InvalidDomain,
|
||||
InvalidBuckets,
|
||||
InvalidCeiling,
|
||||
BudgetExceeded,
|
||||
}
|
||||
|
||||
pub const DURATION_BUCKETS_SECONDS: &[f64] = &[
|
||||
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0,
|
||||
];
|
||||
|
||||
pub const PROCESS_CONSTANT_LABELS: &[LabelDomain] = &[
|
||||
LabelDomain {
|
||||
name: "service",
|
||||
class: LabelClass::ProcessConstant,
|
||||
values: &["admin-api", "mcp-server"],
|
||||
},
|
||||
LabelDomain {
|
||||
name: "version",
|
||||
class: LabelClass::ProcessConstant,
|
||||
values: &["validated_release_identity"],
|
||||
},
|
||||
LabelDomain {
|
||||
name: "environment",
|
||||
class: LabelClass::ProcessConstant,
|
||||
values: &["validated_startup_value"],
|
||||
},
|
||||
];
|
||||
|
||||
const BOTH: &[MetricProcess] = &[MetricProcess::AdminApi, MetricProcess::McpServer];
|
||||
const MCP: &[MetricProcess] = &[MetricProcess::McpServer];
|
||||
|
||||
pub const HTTP_ROUTE_DOMAIN: &[&str] = &[
|
||||
"unmatched",
|
||||
"/health",
|
||||
"/ready",
|
||||
"/api/auth/login",
|
||||
"/api/auth/bootstrap/status",
|
||||
"/api/auth/bootstrap/complete",
|
||||
"/api/auth/logout",
|
||||
"/api/auth/session",
|
||||
"/api/auth/session/csrf",
|
||||
"/api/auth/profile",
|
||||
"/api/auth/password",
|
||||
"/api/admin/capabilities",
|
||||
"/api/admin/workspaces",
|
||||
"/api/admin/workspaces/{workspace_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/onboarding",
|
||||
"/api/admin/workspaces/{workspace_id}/onboarding/events",
|
||||
"/api/admin/workspaces/{workspace_id}/onboarding/reset-selection",
|
||||
"/api/admin/workspaces/{workspace_id}/onboarding/import-context",
|
||||
"/api/admin/workspaces/{workspace_id}/onboarding/select-draft",
|
||||
"/api/admin/workspaces/{workspace_id}/operations",
|
||||
"/api/admin/workspaces/{workspace_id}/imports/openapi/preview",
|
||||
"/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/create",
|
||||
"/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/plans",
|
||||
"/api/admin/workspaces/{workspace_id}/imports/openapi/plans/{plan_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/imports/openapi/{plan_id}/apply",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/analyze-quality",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/import",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions/{version}",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/publish",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/archive",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/test-runs",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/input-json",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/output-json",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/drafts/generate",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/export",
|
||||
"/api/admin/workspaces/{workspace_id}/agents",
|
||||
"/api/admin/workspaces/{workspace_id}/agents/tool-search/preview",
|
||||
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/versions/{version}",
|
||||
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/bindings",
|
||||
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/publish",
|
||||
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/unpublish",
|
||||
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/archive",
|
||||
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys",
|
||||
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}/revoke",
|
||||
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/auth-profiles",
|
||||
"/api/admin/workspaces/{workspace_id}/auth-profiles/{auth_profile_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/upstreams",
|
||||
"/api/admin/workspaces/{workspace_id}/upstreams/{upstream_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/secrets",
|
||||
"/api/admin/workspaces/{workspace_id}/secrets/{secret_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/secrets/{secret_id}/rotate",
|
||||
"/api/admin/workspaces/{workspace_id}/export",
|
||||
"/api/admin/workspaces/{workspace_id}/logs",
|
||||
"/api/admin/workspaces/{workspace_id}/logs/export.csv",
|
||||
"/api/admin/workspaces/{workspace_id}/logs/{log_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/approvals",
|
||||
"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/approve",
|
||||
"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/deny",
|
||||
"/api/admin/workspaces/{workspace_id}/usage",
|
||||
"/api/admin/workspaces/{workspace_id}/usage/export.csv",
|
||||
"/api/admin/workspaces/{workspace_id}/usage/operations/{operation_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/usage/agents/{agent_id}",
|
||||
"/v1/{workspace_slug}/{agent_slug}",
|
||||
"/v1/{workspace_slug}/{agent_slug}/approvals",
|
||||
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/approve",
|
||||
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}",
|
||||
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/deny",
|
||||
];
|
||||
const METHODS: &[&str] = HttpMethod::VALUES;
|
||||
const STATUS: &[&str] = HttpStatusClass::VALUES;
|
||||
const MCP_METHODS: &[&str] = McpMethod::VALUES;
|
||||
const RESPONSE_MODES: &[&str] = McpResponseMode::VALUES;
|
||||
const MCP_OUTCOMES: &[&str] = McpOutcome::VALUES;
|
||||
const SOURCES: &[&str] = InvocationSource::VALUES;
|
||||
const TOOL_OUTCOMES: &[&str] = ToolOutcome::VALUES;
|
||||
const TOOL_ERRORS: &[&str] = ToolErrorKind::VALUES;
|
||||
const OPERATION_KINDS: &[&str] = UpstreamOperationKind::VALUES;
|
||||
const UPSTREAM_OUTCOMES: &[&str] = UpstreamOutcome::VALUES;
|
||||
const LIMIT_STAGES: &[&str] = LimitStage::VALUES;
|
||||
const CACHE_OUTCOMES: &[&str] = CacheOutcome::VALUES;
|
||||
const IDEMPOTENCY_OUTCOMES: &[&str] = IdempotencyOutcome::VALUES;
|
||||
const CONFIRMATION_OUTCOMES: &[&str] = ConfirmationOutcome::VALUES;
|
||||
const DB_STATES: &[&str] = DbPoolState::VALUES;
|
||||
const SIGNAL_TYPES: &[&str] = SignalType::VALUES;
|
||||
const EXPORTERS: &[&str] = Exporter::VALUES;
|
||||
|
||||
const fn domain(name: &'static str, values: &'static [&'static str]) -> LabelDomain {
|
||||
LabelDomain {
|
||||
name,
|
||||
class: LabelClass::ProductClosed,
|
||||
values,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(
|
||||
clippy::too_many_arguments,
|
||||
reason = "the canonical descriptor keeps every metric contract dimension explicit"
|
||||
)]
|
||||
const fn metric(
|
||||
name: &'static str,
|
||||
kind: MetricKind,
|
||||
unit: MetricUnit,
|
||||
labels: &'static [&'static str],
|
||||
label_domains: &'static [LabelDomain],
|
||||
buckets: &'static [f64],
|
||||
processes: &'static [MetricProcess],
|
||||
logical: usize,
|
||||
description: &'static str,
|
||||
) -> MetricDefinition {
|
||||
let rendered = if matches!(kind, MetricKind::Histogram) {
|
||||
logical * (buckets.len() + 3)
|
||||
} else {
|
||||
logical
|
||||
};
|
||||
MetricDefinition {
|
||||
name,
|
||||
kind,
|
||||
unit,
|
||||
labels,
|
||||
label_domains,
|
||||
buckets,
|
||||
processes,
|
||||
max_logical_series: logical,
|
||||
max_rendered_series: rendered,
|
||||
description,
|
||||
}
|
||||
}
|
||||
|
||||
const METRIC_SCHEMA: &[MetricDefinition] = &[
|
||||
metric(
|
||||
"crank_http_requests_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["route", "method", "status_class"],
|
||||
&[
|
||||
domain("route", HTTP_ROUTE_DOMAIN),
|
||||
domain("method", METHODS),
|
||||
domain("status_class", STATUS),
|
||||
],
|
||||
&[],
|
||||
BOTH,
|
||||
HTTP_ROUTE_DOMAIN.len() * 10 * 6,
|
||||
"Total HTTP requests.",
|
||||
),
|
||||
metric(
|
||||
"crank_http_request_duration_seconds",
|
||||
MetricKind::Histogram,
|
||||
MetricUnit::Seconds,
|
||||
&["route", "method"],
|
||||
&[
|
||||
domain("route", HTTP_ROUTE_DOMAIN),
|
||||
domain("method", METHODS),
|
||||
],
|
||||
DURATION_BUCKETS_SECONDS,
|
||||
BOTH,
|
||||
HTTP_ROUTE_DOMAIN.len() * 10,
|
||||
"HTTP request duration in seconds.",
|
||||
),
|
||||
metric(
|
||||
"crank_http_inflight",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
BOTH,
|
||||
1,
|
||||
"HTTP requests currently being processed.",
|
||||
),
|
||||
metric(
|
||||
"crank_mcp_requests_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["method", "response_mode", "outcome"],
|
||||
&[
|
||||
domain("method", MCP_METHODS),
|
||||
domain("response_mode", RESPONSE_MODES),
|
||||
domain("outcome", MCP_OUTCOMES),
|
||||
],
|
||||
&[],
|
||||
MCP,
|
||||
9 * 3 * 7,
|
||||
"Total MCP JSON-RPC requests.",
|
||||
),
|
||||
metric(
|
||||
"crank_mcp_request_duration_seconds",
|
||||
MetricKind::Histogram,
|
||||
MetricUnit::Seconds,
|
||||
&["method", "outcome"],
|
||||
&[
|
||||
domain("method", MCP_METHODS),
|
||||
domain("outcome", MCP_OUTCOMES),
|
||||
],
|
||||
DURATION_BUCKETS_SECONDS,
|
||||
MCP,
|
||||
9 * 7,
|
||||
"MCP JSON-RPC request duration in seconds.",
|
||||
),
|
||||
metric(
|
||||
"crank_mcp_active_sessions",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"Active persisted MCP transport sessions.",
|
||||
),
|
||||
metric(
|
||||
"crank_mcp_session_metrics_fresh",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"Whether the active-session gauge was refreshed successfully.",
|
||||
),
|
||||
metric(
|
||||
"crank_mcp_active_streams",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"MCP event streams currently being served.",
|
||||
),
|
||||
metric(
|
||||
"crank_tool_invocations_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["source", "outcome", "error_kind"],
|
||||
&[
|
||||
domain("source", SOURCES),
|
||||
domain("outcome", TOOL_OUTCOMES),
|
||||
domain("error_kind", TOOL_ERRORS),
|
||||
],
|
||||
&[],
|
||||
BOTH,
|
||||
3 * 3 * 22,
|
||||
"Total tool invocations.",
|
||||
),
|
||||
metric(
|
||||
"crank_tool_invocation_duration_seconds",
|
||||
MetricKind::Histogram,
|
||||
MetricUnit::Seconds,
|
||||
&["source", "outcome"],
|
||||
&[domain("source", SOURCES), domain("outcome", TOOL_OUTCOMES)],
|
||||
DURATION_BUCKETS_SECONDS,
|
||||
BOTH,
|
||||
3 * 3,
|
||||
"Tool invocation duration in seconds.",
|
||||
),
|
||||
metric(
|
||||
"crank_upstream_requests_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["operation_kind", "outcome"],
|
||||
&[
|
||||
domain("operation_kind", OPERATION_KINDS),
|
||||
domain("outcome", UPSTREAM_OUTCOMES),
|
||||
],
|
||||
&[],
|
||||
BOTH,
|
||||
13,
|
||||
"Total upstream requests.",
|
||||
),
|
||||
metric(
|
||||
"crank_upstream_request_duration_seconds",
|
||||
MetricKind::Histogram,
|
||||
MetricUnit::Seconds,
|
||||
&["operation_kind", "outcome"],
|
||||
&[
|
||||
domain("operation_kind", OPERATION_KINDS),
|
||||
domain("outcome", UPSTREAM_OUTCOMES),
|
||||
],
|
||||
DURATION_BUCKETS_SECONDS,
|
||||
BOTH,
|
||||
13,
|
||||
"Upstream request duration in seconds.",
|
||||
),
|
||||
metric(
|
||||
"crank_runtime_inflight",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
BOTH,
|
||||
1,
|
||||
"Runtime executions currently in progress.",
|
||||
),
|
||||
metric(
|
||||
"crank_runtime_limit_rejections_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["stage"],
|
||||
&[domain("stage", LIMIT_STAGES)],
|
||||
&[],
|
||||
BOTH,
|
||||
3,
|
||||
"Runtime executions rejected by a bounded limit.",
|
||||
),
|
||||
metric(
|
||||
"crank_runtime_cache_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["outcome"],
|
||||
&[domain("outcome", CACHE_OUTCOMES)],
|
||||
&[],
|
||||
BOTH,
|
||||
7,
|
||||
"Runtime response cache outcomes.",
|
||||
),
|
||||
metric(
|
||||
"crank_idempotency_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["outcome"],
|
||||
&[domain("outcome", IDEMPOTENCY_OUTCOMES)],
|
||||
&[],
|
||||
BOTH,
|
||||
8,
|
||||
"Runtime idempotency outcomes.",
|
||||
),
|
||||
metric(
|
||||
"crank_confirmation_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["outcome"],
|
||||
&[domain("outcome", CONFIRMATION_OUTCOMES)],
|
||||
&[],
|
||||
BOTH,
|
||||
5,
|
||||
"Runtime confirmation outcomes.",
|
||||
),
|
||||
metric(
|
||||
"crank_db_pool_connections",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&["state"],
|
||||
&[domain("state", DB_STATES)],
|
||||
&[],
|
||||
BOTH,
|
||||
2,
|
||||
"PostgreSQL pool connections by state.",
|
||||
),
|
||||
metric(
|
||||
"crank_catalog_tools",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"Tools in the current published catalog.",
|
||||
),
|
||||
metric(
|
||||
"crank_catalog_estimated_context_tokens",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"Estimated context tokens in the current published catalog.",
|
||||
),
|
||||
metric(
|
||||
"crank_catalog_warnings",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"Warnings in the current published catalog.",
|
||||
),
|
||||
metric(
|
||||
"crank_invocation_history_lost_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
BOTH,
|
||||
1,
|
||||
"Invocation history records lost after an action completed.",
|
||||
),
|
||||
metric(
|
||||
"crank_telemetry_export_failures_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["signal_type", "exporter"],
|
||||
&[
|
||||
domain("signal_type", SIGNAL_TYPES),
|
||||
domain("exporter", EXPORTERS),
|
||||
],
|
||||
&[],
|
||||
BOTH,
|
||||
4,
|
||||
"Telemetry export failures.",
|
||||
),
|
||||
];
|
||||
|
||||
pub const fn metric_schema() -> &'static [MetricDefinition] {
|
||||
METRIC_SCHEMA
|
||||
}
|
||||
|
||||
pub fn metric_schema_for_service(
|
||||
service: MetricService,
|
||||
) -> impl Iterator<Item = &'static MetricDefinition> {
|
||||
METRIC_SCHEMA
|
||||
.iter()
|
||||
.filter(move |definition| definition.processes.contains(&service.process()))
|
||||
}
|
||||
|
||||
pub fn schema_budget() -> Result<SchemaBudget, SchemaError> {
|
||||
validate_schema(METRIC_SCHEMA)
|
||||
}
|
||||
|
||||
pub fn validate_budget(logical: usize, rendered: usize) -> Result<(), SchemaError> {
|
||||
if logical > MAX_LOGICAL_SERIES_PER_PROCESS || rendered > MAX_RENDERED_SERIES_PER_PROCESS {
|
||||
Err(SchemaError::BudgetExceeded)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn max_exemplar_slots() -> usize {
|
||||
METRIC_SCHEMA
|
||||
.iter()
|
||||
.filter(|definition| definition.kind == MetricKind::Histogram)
|
||||
.map(|definition| definition.max_logical_series * (definition.buckets.len() + 1))
|
||||
.sum()
|
||||
}
|
||||
|
||||
pub fn validate_schema(schema: &[MetricDefinition]) -> Result<SchemaBudget, SchemaError> {
|
||||
if schema.len() > MAX_METRIC_FAMILIES {
|
||||
return Err(SchemaError::TooManyFamilies);
|
||||
}
|
||||
let mut names = BTreeSet::new();
|
||||
let mut logical = 0usize;
|
||||
let mut rendered = 0usize;
|
||||
for item in schema {
|
||||
if !names.insert(item.name) {
|
||||
return Err(SchemaError::DuplicateMetric);
|
||||
}
|
||||
if !valid_metric_name(item.name)
|
||||
|| !valid_static_text(item.description)
|
||||
|| item.processes.is_empty()
|
||||
|| item.labels.len() > MAX_PRODUCT_LABELS_PER_FAMILY
|
||||
|| item.labels.len() != item.label_domains.len()
|
||||
{
|
||||
return Err(SchemaError::InvalidMetric);
|
||||
}
|
||||
let mut labels = BTreeSet::new();
|
||||
let mut computed = 1usize;
|
||||
for (label, domain) in item.labels.iter().zip(item.label_domains) {
|
||||
if *label != domain.name || !valid_label_name(label) || !labels.insert(*label) {
|
||||
return Err(SchemaError::DuplicateLabel);
|
||||
}
|
||||
if domain.class != LabelClass::ProductClosed
|
||||
|| domain.values.is_empty()
|
||||
|| domain.values.iter().any(|value| !valid_domain_value(value))
|
||||
|| domain.values.iter().copied().collect::<BTreeSet<_>>().len()
|
||||
!= domain.values.len()
|
||||
{
|
||||
return Err(SchemaError::InvalidDomain);
|
||||
}
|
||||
computed = computed
|
||||
.checked_mul(domain.values.len())
|
||||
.ok_or(SchemaError::BudgetExceeded)?;
|
||||
}
|
||||
if item.kind == MetricKind::Histogram {
|
||||
if item.buckets.is_empty()
|
||||
|| item.buckets.iter().any(|v| !v.is_finite() || *v <= 0.0)
|
||||
|| item.buckets.windows(2).any(|pair| pair[0] >= pair[1])
|
||||
{
|
||||
return Err(SchemaError::InvalidBuckets);
|
||||
}
|
||||
} else if !item.buckets.is_empty() {
|
||||
return Err(SchemaError::InvalidBuckets);
|
||||
}
|
||||
let expected_rendered = if item.kind == MetricKind::Histogram {
|
||||
computed
|
||||
.checked_mul(item.buckets.len() + 3)
|
||||
.ok_or(SchemaError::BudgetExceeded)?
|
||||
} else {
|
||||
computed
|
||||
};
|
||||
if computed != item.max_logical_series || expected_rendered != item.max_rendered_series {
|
||||
return Err(SchemaError::InvalidCeiling);
|
||||
}
|
||||
logical = logical
|
||||
.checked_add(computed)
|
||||
.ok_or(SchemaError::BudgetExceeded)?;
|
||||
rendered = rendered
|
||||
.checked_add(expected_rendered)
|
||||
.ok_or(SchemaError::BudgetExceeded)?;
|
||||
}
|
||||
validate_budget(logical, rendered)?;
|
||||
Ok(SchemaBudget {
|
||||
logical_series: logical,
|
||||
rendered_series: rendered,
|
||||
})
|
||||
}
|
||||
|
||||
fn valid_static_text(value: &str) -> bool {
|
||||
!value.trim().is_empty()
|
||||
&& value.len() <= 512
|
||||
&& !value
|
||||
.bytes()
|
||||
.any(|byte| byte.is_ascii_control() || matches!(byte, b'"' | b'\\'))
|
||||
}
|
||||
|
||||
fn valid_metric_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
|
||||
&& name.starts_with("crank_")
|
||||
}
|
||||
|
||||
fn valid_label_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name.len() <= 64
|
||||
&& !name.starts_with("__")
|
||||
&& name
|
||||
.bytes()
|
||||
.next()
|
||||
.is_some_and(|byte| byte.is_ascii_lowercase() || byte == b'_')
|
||||
&& name
|
||||
.bytes()
|
||||
.skip(1)
|
||||
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
|
||||
}
|
||||
|
||||
fn valid_domain_value(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= 256
|
||||
&& !value
|
||||
.bytes()
|
||||
.any(|byte| byte.is_ascii_control() || matches!(byte, b'"' | b'\\'))
|
||||
}
|
||||
|
||||
pub fn render_metric_schema_json() -> Result<String, SchemaError> {
|
||||
let budget = schema_budget()?;
|
||||
let mut out = format!(
|
||||
"{{\n \"schema_version\": {METRIC_SCHEMA_VERSION},\n \"budget\": {{\"logical_series\": {}, \"rendered_series\": {}, \"max_logical_series\": {MAX_LOGICAL_SERIES_PER_PROCESS}, \"max_rendered_series\": {MAX_RENDERED_SERIES_PER_PROCESS}}},\n \"global_labels\": [\n",
|
||||
budget.logical_series, budget.rendered_series
|
||||
);
|
||||
for (index, label) in PROCESS_CONSTANT_LABELS.iter().enumerate() {
|
||||
out.push_str(&format!(
|
||||
" {{\"name\": \"{}\", \"class\": \"{}\", \"domain\": [{}]}}{}\n",
|
||||
label.name,
|
||||
label.class.as_str(),
|
||||
json_strings(label.values),
|
||||
comma(index, PROCESS_CONSTANT_LABELS.len())
|
||||
));
|
||||
}
|
||||
out.push_str(" ],\n \"metrics\": [\n");
|
||||
for (index, item) in METRIC_SCHEMA.iter().enumerate() {
|
||||
out.push_str(&format!(" {{\"name\": \"{}\", \"kind\": \"{}\", \"unit\": \"{}\", \"help\": \"{}\", \"processes\": [{}], \"labels\": [", item.name, item.kind.as_str(), item.unit.as_str(), item.description, json_processes(item.processes)));
|
||||
for (label_index, domain) in item.label_domains.iter().enumerate() {
|
||||
out.push_str(&format!(
|
||||
"{{\"name\": \"{}\", \"class\": \"{}\", \"domain\": [{}]}}{}",
|
||||
domain.name,
|
||||
domain.class.as_str(),
|
||||
json_strings(domain.values),
|
||||
comma(label_index, item.label_domains.len())
|
||||
));
|
||||
}
|
||||
out.push_str(&format!("], \"buckets_seconds\": [{}], \"max_logical_series\": {}, \"max_rendered_series\": {}}}{}\n", item.buckets.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "), item.max_logical_series, item.max_rendered_series, comma(index, METRIC_SCHEMA.len())));
|
||||
}
|
||||
out.push_str(" ]\n}\n");
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn json_strings(values: &[&str]) -> String {
|
||||
values
|
||||
.iter()
|
||||
.map(|value| format!("\"{value}\""))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
fn json_processes(values: &[MetricProcess]) -> String {
|
||||
values
|
||||
.iter()
|
||||
.map(|value| format!("\"{}\"", value.as_str()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
const fn comma(index: usize, len: usize) -> &'static str {
|
||||
if index + 1 == len { "" } else { "," }
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Checked-арифметика бюджетов серий/exemplar, структурная валидация и
|
||||
//! per-process ceilings.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::descriptor::{
|
||||
LabelClass, MAX_EXEMPLAR_SLOTS_PER_PROCESS, MAX_LOGICAL_SERIES_PER_PROCESS,
|
||||
MAX_METRIC_FAMILIES, MAX_PRODUCT_LABELS_PER_FAMILY, MAX_RENDERED_SERIES_PER_PROCESS,
|
||||
METRIC_SCHEMA, MetricDefinition, MetricKind, MetricService,
|
||||
};
|
||||
use super::projection::service_projection;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct SchemaBudget {
|
||||
pub logical_series: usize,
|
||||
pub rendered_series: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum SchemaError {
|
||||
TooManyFamilies,
|
||||
DuplicateMetric,
|
||||
InvalidMetric,
|
||||
DuplicateLabel,
|
||||
InvalidDomain,
|
||||
InvalidBuckets,
|
||||
InvalidCeiling,
|
||||
BudgetExceeded,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum MetricBindingError {
|
||||
InvalidSchema,
|
||||
ConflictingService,
|
||||
}
|
||||
|
||||
/// Checked series budget of one candidate family: the product of its
|
||||
/// label-domain sizes and, for histograms, the `buckets + 3` rendered sample
|
||||
/// lines per logical series. Overflow is a typed budget failure; the closed
|
||||
/// schema never saturates and never reports a truncated count.
|
||||
pub(crate) fn checked_series_budget<I>(
|
||||
domain_sizes: I,
|
||||
kind: MetricKind,
|
||||
bucket_count: usize,
|
||||
) -> Result<SchemaBudget, SchemaError>
|
||||
where
|
||||
I: IntoIterator<Item = usize>,
|
||||
{
|
||||
let logical_series = domain_sizes
|
||||
.into_iter()
|
||||
.try_fold(1_usize, |product, size| {
|
||||
product.checked_mul(size).ok_or(SchemaError::BudgetExceeded)
|
||||
})?;
|
||||
if kind != MetricKind::Histogram {
|
||||
return Ok(SchemaBudget {
|
||||
logical_series,
|
||||
rendered_series: logical_series,
|
||||
});
|
||||
}
|
||||
let rendered_per_series = bucket_count
|
||||
.checked_add(3)
|
||||
.ok_or(SchemaError::BudgetExceeded)?;
|
||||
let rendered_series = logical_series
|
||||
.checked_mul(rendered_per_series)
|
||||
.ok_or(SchemaError::BudgetExceeded)?;
|
||||
Ok(SchemaBudget {
|
||||
logical_series,
|
||||
rendered_series,
|
||||
})
|
||||
}
|
||||
|
||||
/// Checked exemplar slots of one family (`L x (buckets + 1)`): an overflow is a
|
||||
/// typed budget failure, never a wrapped slot count.
|
||||
pub(crate) fn checked_exemplar_slots(
|
||||
kind: MetricKind,
|
||||
logical_series: usize,
|
||||
bucket_count: usize,
|
||||
) -> Result<usize, SchemaError> {
|
||||
if kind != MetricKind::Histogram {
|
||||
return Ok(0);
|
||||
}
|
||||
let buckets = bucket_count
|
||||
.checked_add(1)
|
||||
.ok_or(SchemaError::BudgetExceeded)?;
|
||||
logical_series
|
||||
.checked_mul(buckets)
|
||||
.ok_or(SchemaError::BudgetExceeded)
|
||||
}
|
||||
|
||||
/// Checked exemplar capacity of one service projection. `None` means the
|
||||
/// projection's arithmetic overflowed, so every caller can fail closed (no
|
||||
/// exemplar growth) instead of recording under a saturated capacity.
|
||||
pub(crate) fn checked_exemplar_capacity(service: MetricService) -> Option<usize> {
|
||||
service_projection(service)
|
||||
.iter()
|
||||
.try_fold(0_usize, |total, definition| {
|
||||
checked_exemplar_slots(
|
||||
definition.kind,
|
||||
definition.max_logical_series,
|
||||
definition.buckets.len(),
|
||||
)
|
||||
.ok()
|
||||
.and_then(|slots| total.checked_add(slots))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn validate_budget(logical: usize, rendered: usize) -> Result<(), SchemaError> {
|
||||
if logical > MAX_LOGICAL_SERIES_PER_PROCESS || rendered > MAX_RENDERED_SERIES_PER_PROCESS {
|
||||
Err(SchemaError::BudgetExceeded)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate_exemplar_budget(slots: usize) -> Result<(), SchemaError> {
|
||||
if slots > MAX_EXEMPLAR_SLOTS_PER_PROCESS {
|
||||
Err(SchemaError::BudgetExceeded)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Structural validation of exactly one projected schema, including the
|
||||
/// per-process ceilings. It must never be applied to the union descriptors.
|
||||
pub fn validate_schema(schema: &[MetricDefinition]) -> Result<SchemaBudget, SchemaError> {
|
||||
let budget = validate_structure(schema)?;
|
||||
validate_budget(budget.logical_series, budget.rendered_series)?;
|
||||
let exemplars = schema.iter().try_fold(0_usize, |total, definition| {
|
||||
let slots = checked_exemplar_slots(
|
||||
definition.kind,
|
||||
definition.max_logical_series,
|
||||
definition.buckets.len(),
|
||||
)?;
|
||||
total.checked_add(slots).ok_or(SchemaError::BudgetExceeded)
|
||||
})?;
|
||||
validate_exemplar_budget(exemplars)?;
|
||||
Ok(budget)
|
||||
}
|
||||
|
||||
/// Structural validation without any sum ceiling (used for the union metadata
|
||||
/// and reused by the renderer before it validates every service projection).
|
||||
fn validate_structure(schema: &[MetricDefinition]) -> Result<SchemaBudget, SchemaError> {
|
||||
if schema.len() > MAX_METRIC_FAMILIES {
|
||||
return Err(SchemaError::TooManyFamilies);
|
||||
}
|
||||
let mut names = BTreeSet::new();
|
||||
let mut logical = 0usize;
|
||||
let mut rendered = 0usize;
|
||||
for item in schema {
|
||||
if !names.insert(item.name) {
|
||||
return Err(SchemaError::DuplicateMetric);
|
||||
}
|
||||
if !valid_metric_name(item.name)
|
||||
|| !valid_static_text(item.description)
|
||||
|| item.processes.is_empty()
|
||||
|| item.labels.len() > MAX_PRODUCT_LABELS_PER_FAMILY
|
||||
|| item.labels.len() != item.label_domains.len()
|
||||
{
|
||||
return Err(SchemaError::InvalidMetric);
|
||||
}
|
||||
let mut owners = BTreeSet::new();
|
||||
for owner in item.processes {
|
||||
if !owners.insert(*owner) {
|
||||
return Err(SchemaError::InvalidMetric);
|
||||
}
|
||||
}
|
||||
let mut labels = BTreeSet::new();
|
||||
for (label, domain) in item.labels.iter().zip(item.label_domains) {
|
||||
if *label != domain.name || !valid_label_name(label) || !labels.insert(*label) {
|
||||
return Err(SchemaError::DuplicateLabel);
|
||||
}
|
||||
if domain.class != LabelClass::ProductClosed
|
||||
|| domain.values.is_empty()
|
||||
|| domain.values.iter().any(|value| !valid_domain_value(value))
|
||||
|| domain.values.iter().copied().collect::<BTreeSet<_>>().len()
|
||||
!= domain.values.len()
|
||||
{
|
||||
return Err(SchemaError::InvalidDomain);
|
||||
}
|
||||
}
|
||||
if item.kind == MetricKind::Histogram {
|
||||
if item.buckets.is_empty()
|
||||
|| item.buckets.iter().any(|v| !v.is_finite() || *v <= 0.0)
|
||||
|| item.buckets.windows(2).any(|pair| pair[0] >= pair[1])
|
||||
{
|
||||
return Err(SchemaError::InvalidBuckets);
|
||||
}
|
||||
} else if !item.buckets.is_empty() {
|
||||
return Err(SchemaError::InvalidBuckets);
|
||||
}
|
||||
// Единственная checked-арифметика серий: переполнение домена или
|
||||
// rendered-серий обязано быть типизированным BudgetExceeded, а не
|
||||
// насыщенным «почти верным» значением.
|
||||
let budget = checked_series_budget(
|
||||
item.label_domains.iter().map(|domain| domain.values.len()),
|
||||
item.kind,
|
||||
item.buckets.len(),
|
||||
)?;
|
||||
if budget.logical_series != item.max_logical_series
|
||||
|| budget.rendered_series != item.max_rendered_series
|
||||
{
|
||||
return Err(SchemaError::InvalidCeiling);
|
||||
}
|
||||
logical = logical
|
||||
.checked_add(budget.logical_series)
|
||||
.ok_or(SchemaError::BudgetExceeded)?;
|
||||
rendered = rendered
|
||||
.checked_add(budget.rendered_series)
|
||||
.ok_or(SchemaError::BudgetExceeded)?;
|
||||
}
|
||||
Ok(SchemaBudget {
|
||||
logical_series: logical,
|
||||
rendered_series: rendered,
|
||||
})
|
||||
}
|
||||
|
||||
/// Validates the union structure plus **every** service projection. Union
|
||||
/// totals are deliberately not compared against the per-process ceilings.
|
||||
pub fn validate_all_projections() -> Result<(), SchemaError> {
|
||||
validate_structure(METRIC_SCHEMA)?;
|
||||
validate_schema(service_projection(MetricService::AdminApi))?;
|
||||
validate_schema(service_projection(MetricService::McpServer))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn valid_static_text(value: &str) -> bool {
|
||||
!value.trim().is_empty()
|
||||
&& value.len() <= 512
|
||||
&& !value
|
||||
.bytes()
|
||||
.any(|byte| byte.is_ascii_control() || matches!(byte, b'"' | b'\\'))
|
||||
}
|
||||
|
||||
fn valid_metric_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
|
||||
&& name.starts_with("crank_")
|
||||
}
|
||||
|
||||
fn valid_label_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name.len() <= 64
|
||||
&& !name.starts_with("__")
|
||||
&& name
|
||||
.bytes()
|
||||
.next()
|
||||
.is_some_and(|byte| byte.is_ascii_lowercase() || byte == b'_')
|
||||
&& name
|
||||
.bytes()
|
||||
.skip(1)
|
||||
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
|
||||
}
|
||||
|
||||
fn valid_domain_value(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= 256
|
||||
&& !value
|
||||
.bytes()
|
||||
.any(|byte| byte.is_ascii_control() || matches!(byte, b'"' | b'\\'))
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Checked-арифметика серий и exemplar-слотов: типизированное переполнение
|
||||
//! вместо насыщения (TD-M5).
|
||||
|
||||
use super::budget::{
|
||||
SchemaBudget, SchemaError, checked_exemplar_capacity, checked_exemplar_slots,
|
||||
checked_series_budget,
|
||||
};
|
||||
use super::descriptor::{MAX_EXEMPLAR_SLOTS_PER_PROCESS, MetricKind, MetricService};
|
||||
use super::projection::{max_exemplar_slots, service_projection};
|
||||
|
||||
/// TD-M5 — реальное целочисленное переполнение checked-seam'а обязано быть
|
||||
/// типизированным `BudgetExceeded`, а не насыщенным/усечённым счётчиком.
|
||||
/// Фикстура — только размеры доменов, поэтому enormous-аллокаций нет.
|
||||
#[test]
|
||||
fn checked_seam_reports_overflow_typed_and_never_saturates() {
|
||||
// Логический product переполняется.
|
||||
assert_eq!(
|
||||
checked_series_budget([usize::MAX, 2], MetricKind::Counter, 0),
|
||||
Err(SchemaError::BudgetExceeded)
|
||||
);
|
||||
// Граница: ровно представимый product остаётся принятым (без saturation).
|
||||
assert_eq!(
|
||||
checked_series_budget([usize::MAX, 1], MetricKind::Counter, 0),
|
||||
Ok(SchemaBudget {
|
||||
logical_series: usize::MAX,
|
||||
rendered_series: usize::MAX,
|
||||
})
|
||||
);
|
||||
// Rendered product переполняется при корректном logical.
|
||||
assert_eq!(
|
||||
checked_series_budget([usize::MAX / 4, 2], MetricKind::Histogram, 13),
|
||||
Err(SchemaError::BudgetExceeded)
|
||||
);
|
||||
// `buckets + 3` само переполняется.
|
||||
assert_eq!(
|
||||
checked_series_budget([1], MetricKind::Histogram, usize::MAX),
|
||||
Err(SchemaError::BudgetExceeded)
|
||||
);
|
||||
// Нормальный histogram считается точно (13 buckets → 16 rendered).
|
||||
assert_eq!(
|
||||
checked_series_budget([7, 2], MetricKind::Histogram, 13),
|
||||
Ok(SchemaBudget {
|
||||
logical_series: 14,
|
||||
rendered_series: 224,
|
||||
})
|
||||
);
|
||||
// Пустой домен: один logical series, как у gauge без labels.
|
||||
assert_eq!(
|
||||
checked_series_budget(std::iter::empty::<usize>(), MetricKind::Gauge, 0),
|
||||
Ok(SchemaBudget {
|
||||
logical_series: 1,
|
||||
rendered_series: 1,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-M5 — exemplar-слоты считаются checked, capacity fail-closed.
|
||||
#[test]
|
||||
fn checked_exemplar_slots_and_capacity_are_typed_and_bounded() {
|
||||
assert_eq!(
|
||||
checked_exemplar_slots(MetricKind::Histogram, usize::MAX, 13),
|
||||
Err(SchemaError::BudgetExceeded)
|
||||
);
|
||||
assert_eq!(
|
||||
checked_exemplar_slots(MetricKind::Histogram, usize::MAX / 2, 2),
|
||||
Err(SchemaError::BudgetExceeded)
|
||||
);
|
||||
assert_eq!(
|
||||
checked_exemplar_slots(MetricKind::Histogram, 1, usize::MAX),
|
||||
Err(SchemaError::BudgetExceeded)
|
||||
);
|
||||
assert_eq!(
|
||||
checked_exemplar_slots(MetricKind::Counter, usize::MAX, 13),
|
||||
Ok(0)
|
||||
);
|
||||
// 4 series x (13 finite buckets + 1 Inf) = 56 слотов, без saturation.
|
||||
assert_eq!(checked_exemplar_slots(MetricKind::Histogram, 4, 13), Ok(56));
|
||||
// Реальная проекция остаётся в frozen-границах.
|
||||
assert_eq!(
|
||||
checked_exemplar_capacity(MetricService::AdminApi),
|
||||
Some(12_348)
|
||||
);
|
||||
assert_eq!(
|
||||
checked_exemplar_capacity(MetricService::McpServer),
|
||||
Some(2_310)
|
||||
);
|
||||
assert_eq!(
|
||||
max_exemplar_slots(MetricService::AdminApi),
|
||||
MAX_EXEMPLAR_SLOTS_PER_PROCESS
|
||||
);
|
||||
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
||||
for definition in service_projection(service) {
|
||||
assert_ne!(definition.max_logical_series, usize::MAX);
|
||||
assert_eq!(
|
||||
definition.max_exemplar_slots(),
|
||||
checked_exemplar_slots(
|
||||
definition.kind,
|
||||
definition.max_logical_series,
|
||||
definition.buckets.len()
|
||||
)
|
||||
.expect("projected exemplar slots are in range")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
//! Закрытые дескрипторы метрик: kind/unit/process/service, домены labels и
|
||||
//! `METRIC_SCHEMA` (union-таблица метадат, не бюджет процесса).
|
||||
|
||||
use super::routes::{BOTH, HTTP_ROUTE_DOMAIN, MCP};
|
||||
use crate::labels::{
|
||||
CacheOutcome, ConfirmationOutcome, DbPoolState, Exporter, HttpMethod, HttpStatusClass,
|
||||
IdempotencyOutcome, InvocationSource, LimitStage, McpMethod, McpOutcome, McpResponseMode,
|
||||
SignalType, ToolErrorKind, ToolOutcome, UpstreamOperationKind, UpstreamOutcome,
|
||||
};
|
||||
|
||||
pub const METRIC_SCHEMA_VERSION: u32 = 2;
|
||||
pub const MAX_METRIC_FAMILIES: usize = 128;
|
||||
pub const MAX_PRODUCT_LABELS_PER_FAMILY: usize = 4;
|
||||
pub const MAX_LOGICAL_SERIES_PER_PROCESS: usize = 6_285;
|
||||
pub const MAX_RENDERED_SERIES_PER_PROCESS: usize = 19_515;
|
||||
pub const MAX_EXEMPLAR_SLOTS_PER_PROCESS: usize = 12_348;
|
||||
pub const MAX_EXPOSITION_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MetricKind {
|
||||
Counter,
|
||||
Gauge,
|
||||
Histogram,
|
||||
}
|
||||
|
||||
impl MetricKind {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Counter => "counter",
|
||||
Self::Gauge => "gauge",
|
||||
Self::Histogram => "histogram",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MetricUnit {
|
||||
Count,
|
||||
Seconds,
|
||||
}
|
||||
|
||||
impl MetricUnit {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Count => "count",
|
||||
Self::Seconds => "seconds",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub enum MetricProcess {
|
||||
AdminApi,
|
||||
McpServer,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MetricService {
|
||||
AdminApi,
|
||||
McpServer,
|
||||
}
|
||||
|
||||
impl MetricService {
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"admin-api" => Some(Self::AdminApi),
|
||||
"mcp-server" => Some(Self::McpServer),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn process(self) -> MetricProcess {
|
||||
match self {
|
||||
Self::AdminApi => MetricProcess::AdminApi,
|
||||
Self::McpServer => MetricProcess::McpServer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetricProcess {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::AdminApi => "admin_api",
|
||||
Self::McpServer => "mcp_server",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn service(self) -> MetricService {
|
||||
match self {
|
||||
Self::AdminApi => MetricService::AdminApi,
|
||||
Self::McpServer => MetricService::McpServer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum LabelClass {
|
||||
ProductClosed,
|
||||
ProcessConstant,
|
||||
}
|
||||
|
||||
impl LabelClass {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::ProductClosed => "product_closed",
|
||||
Self::ProcessConstant => "process_constant",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct LabelDomain {
|
||||
pub name: &'static str,
|
||||
pub class: LabelClass,
|
||||
pub values: &'static [&'static str],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MetricDefinition {
|
||||
pub name: &'static str,
|
||||
pub kind: MetricKind,
|
||||
pub unit: MetricUnit,
|
||||
pub labels: &'static [&'static str],
|
||||
pub label_domains: &'static [LabelDomain],
|
||||
pub buckets: &'static [f64],
|
||||
pub processes: &'static [MetricProcess],
|
||||
pub max_logical_series: usize,
|
||||
pub max_rendered_series: usize,
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
impl MetricDefinition {
|
||||
/// `E(m, p)` — exemplar slots contributed by this family inside one process
|
||||
/// projection. Histograms hold `L x (finite_buckets + 1)` latest-per-bucket
|
||||
/// observations; counters/gauges hold none. The multiply is checked: an
|
||||
/// overflowing definition (one that already failed the checked seam) fails
|
||||
/// loudly instead of returning a saturated or truncated count.
|
||||
pub const fn max_exemplar_slots(&self) -> usize {
|
||||
if !matches!(self.kind, MetricKind::Histogram) {
|
||||
return 0;
|
||||
}
|
||||
match self.max_logical_series.checked_mul(self.buckets.len() + 1) {
|
||||
Some(slots) => slots,
|
||||
None => panic!("exemplar slot arithmetic overflowed a validated definition"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const DURATION_BUCKETS_SECONDS: &[f64] = &[
|
||||
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0,
|
||||
];
|
||||
|
||||
pub const PROCESS_CONSTANT_LABELS: &[LabelDomain] = &[
|
||||
LabelDomain {
|
||||
name: "service",
|
||||
class: LabelClass::ProcessConstant,
|
||||
values: &["admin-api", "mcp-server"],
|
||||
},
|
||||
LabelDomain {
|
||||
name: "version",
|
||||
class: LabelClass::ProcessConstant,
|
||||
values: &["validated_release_identity"],
|
||||
},
|
||||
LabelDomain {
|
||||
name: "environment",
|
||||
class: LabelClass::ProcessConstant,
|
||||
values: &["validated_startup_value"],
|
||||
},
|
||||
];
|
||||
|
||||
const METHODS: &[&str] = HttpMethod::VALUES;
|
||||
const STATUS: &[&str] = HttpStatusClass::VALUES;
|
||||
const MCP_METHODS: &[&str] = McpMethod::VALUES;
|
||||
const RESPONSE_MODES: &[&str] = McpResponseMode::VALUES;
|
||||
const MCP_OUTCOMES: &[&str] = McpOutcome::VALUES;
|
||||
const SOURCES: &[&str] = InvocationSource::VALUES;
|
||||
const TOOL_OUTCOMES: &[&str] = ToolOutcome::VALUES;
|
||||
const TOOL_ERRORS: &[&str] = ToolErrorKind::VALUES;
|
||||
const OPERATION_KINDS: &[&str] = UpstreamOperationKind::VALUES;
|
||||
const UPSTREAM_OUTCOMES: &[&str] = UpstreamOutcome::VALUES;
|
||||
const LIMIT_STAGES: &[&str] = LimitStage::VALUES;
|
||||
const CACHE_OUTCOMES: &[&str] = CacheOutcome::VALUES;
|
||||
const IDEMPOTENCY_OUTCOMES: &[&str] = IdempotencyOutcome::VALUES;
|
||||
const CONFIRMATION_OUTCOMES: &[&str] = ConfirmationOutcome::VALUES;
|
||||
const DB_STATES: &[&str] = DbPoolState::VALUES;
|
||||
const SIGNAL_TYPES: &[&str] = SignalType::VALUES;
|
||||
const EXPORTERS: &[&str] = Exporter::VALUES;
|
||||
|
||||
const fn domain(name: &'static str, values: &'static [&'static str]) -> LabelDomain {
|
||||
LabelDomain {
|
||||
name,
|
||||
class: LabelClass::ProductClosed,
|
||||
values,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(
|
||||
clippy::too_many_arguments,
|
||||
reason = "the canonical descriptor keeps every metric contract dimension explicit"
|
||||
)]
|
||||
const fn metric(
|
||||
name: &'static str,
|
||||
kind: MetricKind,
|
||||
unit: MetricUnit,
|
||||
labels: &'static [&'static str],
|
||||
label_domains: &'static [LabelDomain],
|
||||
buckets: &'static [f64],
|
||||
processes: &'static [MetricProcess],
|
||||
logical: usize,
|
||||
description: &'static str,
|
||||
) -> MetricDefinition {
|
||||
let rendered = if matches!(kind, MetricKind::Histogram) {
|
||||
logical * (buckets.len() + 3)
|
||||
} else {
|
||||
logical
|
||||
};
|
||||
MetricDefinition {
|
||||
name,
|
||||
kind,
|
||||
unit,
|
||||
labels,
|
||||
label_domains,
|
||||
buckets,
|
||||
processes,
|
||||
max_logical_series: logical,
|
||||
max_rendered_series: rendered,
|
||||
description,
|
||||
}
|
||||
}
|
||||
|
||||
/// Union descriptors: the route domain is the whole union and `max_*` are the
|
||||
/// union Cartesian metadata used for structural diagnostics, **not** a process
|
||||
/// budget. Real per-process data lives in the service projections.
|
||||
pub(crate) const METRIC_SCHEMA: &[MetricDefinition] = &[
|
||||
metric(
|
||||
"crank_http_requests_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["route", "method", "status_class"],
|
||||
&[
|
||||
domain("route", HTTP_ROUTE_DOMAIN),
|
||||
domain("method", METHODS),
|
||||
domain("status_class", STATUS),
|
||||
],
|
||||
&[],
|
||||
BOTH,
|
||||
HTTP_ROUTE_DOMAIN.len() * 10 * 6,
|
||||
"Total HTTP requests.",
|
||||
),
|
||||
metric(
|
||||
"crank_http_request_duration_seconds",
|
||||
MetricKind::Histogram,
|
||||
MetricUnit::Seconds,
|
||||
&["route", "method"],
|
||||
&[
|
||||
domain("route", HTTP_ROUTE_DOMAIN),
|
||||
domain("method", METHODS),
|
||||
],
|
||||
DURATION_BUCKETS_SECONDS,
|
||||
BOTH,
|
||||
HTTP_ROUTE_DOMAIN.len() * 10,
|
||||
"HTTP request duration in seconds.",
|
||||
),
|
||||
metric(
|
||||
"crank_http_inflight",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
BOTH,
|
||||
1,
|
||||
"HTTP requests currently being processed.",
|
||||
),
|
||||
metric(
|
||||
"crank_mcp_requests_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["method", "response_mode", "outcome"],
|
||||
&[
|
||||
domain("method", MCP_METHODS),
|
||||
domain("response_mode", RESPONSE_MODES),
|
||||
domain("outcome", MCP_OUTCOMES),
|
||||
],
|
||||
&[],
|
||||
MCP,
|
||||
9 * 3 * 7,
|
||||
"Total MCP JSON-RPC requests.",
|
||||
),
|
||||
metric(
|
||||
"crank_mcp_request_duration_seconds",
|
||||
MetricKind::Histogram,
|
||||
MetricUnit::Seconds,
|
||||
&["method", "outcome"],
|
||||
&[
|
||||
domain("method", MCP_METHODS),
|
||||
domain("outcome", MCP_OUTCOMES),
|
||||
],
|
||||
DURATION_BUCKETS_SECONDS,
|
||||
MCP,
|
||||
9 * 7,
|
||||
"MCP JSON-RPC request duration in seconds.",
|
||||
),
|
||||
metric(
|
||||
"crank_mcp_active_sessions",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"Active persisted MCP transport sessions.",
|
||||
),
|
||||
metric(
|
||||
"crank_mcp_session_metrics_fresh",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"Whether the active-session gauge was refreshed successfully.",
|
||||
),
|
||||
metric(
|
||||
"crank_mcp_active_streams",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"MCP event streams currently being served.",
|
||||
),
|
||||
metric(
|
||||
"crank_tool_invocations_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["source", "outcome", "error_kind"],
|
||||
&[
|
||||
domain("source", SOURCES),
|
||||
domain("outcome", TOOL_OUTCOMES),
|
||||
domain("error_kind", TOOL_ERRORS),
|
||||
],
|
||||
&[],
|
||||
BOTH,
|
||||
3 * 3 * 22,
|
||||
"Total tool invocations.",
|
||||
),
|
||||
metric(
|
||||
"crank_tool_invocation_duration_seconds",
|
||||
MetricKind::Histogram,
|
||||
MetricUnit::Seconds,
|
||||
&["source", "outcome"],
|
||||
&[domain("source", SOURCES), domain("outcome", TOOL_OUTCOMES)],
|
||||
DURATION_BUCKETS_SECONDS,
|
||||
BOTH,
|
||||
3 * 3,
|
||||
"Tool invocation duration in seconds.",
|
||||
),
|
||||
metric(
|
||||
"crank_upstream_requests_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["operation_kind", "outcome"],
|
||||
&[
|
||||
domain("operation_kind", OPERATION_KINDS),
|
||||
domain("outcome", UPSTREAM_OUTCOMES),
|
||||
],
|
||||
&[],
|
||||
BOTH,
|
||||
13,
|
||||
"Total upstream requests.",
|
||||
),
|
||||
metric(
|
||||
"crank_upstream_request_duration_seconds",
|
||||
MetricKind::Histogram,
|
||||
MetricUnit::Seconds,
|
||||
&["operation_kind", "outcome"],
|
||||
&[
|
||||
domain("operation_kind", OPERATION_KINDS),
|
||||
domain("outcome", UPSTREAM_OUTCOMES),
|
||||
],
|
||||
DURATION_BUCKETS_SECONDS,
|
||||
BOTH,
|
||||
13,
|
||||
"Upstream request duration in seconds.",
|
||||
),
|
||||
metric(
|
||||
"crank_runtime_inflight",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
BOTH,
|
||||
1,
|
||||
"Runtime executions currently in progress.",
|
||||
),
|
||||
metric(
|
||||
"crank_runtime_limit_rejections_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["stage"],
|
||||
&[domain("stage", LIMIT_STAGES)],
|
||||
&[],
|
||||
BOTH,
|
||||
3,
|
||||
"Runtime executions rejected by a bounded limit.",
|
||||
),
|
||||
metric(
|
||||
"crank_runtime_cache_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["outcome"],
|
||||
&[domain("outcome", CACHE_OUTCOMES)],
|
||||
&[],
|
||||
BOTH,
|
||||
7,
|
||||
"Runtime response cache outcomes.",
|
||||
),
|
||||
metric(
|
||||
"crank_idempotency_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["outcome"],
|
||||
&[domain("outcome", IDEMPOTENCY_OUTCOMES)],
|
||||
&[],
|
||||
BOTH,
|
||||
8,
|
||||
"Runtime idempotency outcomes.",
|
||||
),
|
||||
metric(
|
||||
"crank_confirmation_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["outcome"],
|
||||
&[domain("outcome", CONFIRMATION_OUTCOMES)],
|
||||
&[],
|
||||
BOTH,
|
||||
5,
|
||||
"Runtime confirmation outcomes.",
|
||||
),
|
||||
metric(
|
||||
"crank_db_pool_connections",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&["state"],
|
||||
&[domain("state", DB_STATES)],
|
||||
&[],
|
||||
BOTH,
|
||||
2,
|
||||
"PostgreSQL pool connections by state.",
|
||||
),
|
||||
metric(
|
||||
"crank_catalog_tools",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"Tools in the current published catalog.",
|
||||
),
|
||||
metric(
|
||||
"crank_catalog_estimated_context_tokens",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"Estimated context tokens in the current published catalog.",
|
||||
),
|
||||
metric(
|
||||
"crank_catalog_warnings",
|
||||
MetricKind::Gauge,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
MCP,
|
||||
1,
|
||||
"Warnings in the current published catalog.",
|
||||
),
|
||||
metric(
|
||||
"crank_invocation_history_lost_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&[],
|
||||
&[],
|
||||
&[],
|
||||
BOTH,
|
||||
1,
|
||||
"Invocation history records lost after an action completed.",
|
||||
),
|
||||
metric(
|
||||
"crank_telemetry_export_failures_total",
|
||||
MetricKind::Counter,
|
||||
MetricUnit::Count,
|
||||
&["signal_type", "exporter"],
|
||||
&[
|
||||
domain("signal_type", SIGNAL_TYPES),
|
||||
domain("exporter", EXPORTERS),
|
||||
],
|
||||
&[],
|
||||
BOTH,
|
||||
4,
|
||||
"Telemetry export failures.",
|
||||
),
|
||||
];
|
||||
|
||||
/// Union descriptors (`metadata`, not a budget).
|
||||
pub const fn metric_schema() -> &'static [MetricDefinition] {
|
||||
METRIC_SCHEMA
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Ленивые per-service проекции union-таблицы: один раз посчитанный
|
||||
//! checked-бюджет на процесс, без per-request аллокаций.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use super::budget::{
|
||||
SchemaBudget, SchemaError, checked_exemplar_capacity, checked_series_budget, validate_schema,
|
||||
};
|
||||
use super::descriptor::{LabelDomain, METRIC_SCHEMA, MetricDefinition, MetricService};
|
||||
use super::routes::service_route_domain;
|
||||
|
||||
fn build_projection(service: MetricService) -> Result<&'static [MetricDefinition], SchemaError> {
|
||||
let route_values = service_route_domain(service);
|
||||
let mut definitions = Vec::new();
|
||||
for definition in METRIC_SCHEMA {
|
||||
if !definition.processes.contains(&service.process()) {
|
||||
continue;
|
||||
}
|
||||
let label_domains: &'static [LabelDomain] = Box::leak(
|
||||
definition
|
||||
.label_domains
|
||||
.iter()
|
||||
.map(|label_domain| {
|
||||
if label_domain.name == "route" {
|
||||
LabelDomain {
|
||||
values: route_values,
|
||||
..*label_domain
|
||||
}
|
||||
} else {
|
||||
*label_domain
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into_boxed_slice(),
|
||||
);
|
||||
let budget = checked_series_budget(
|
||||
label_domains
|
||||
.iter()
|
||||
.map(|label_domain| label_domain.values.len()),
|
||||
definition.kind,
|
||||
definition.buckets.len(),
|
||||
)?;
|
||||
definitions.push(MetricDefinition {
|
||||
label_domains,
|
||||
max_logical_series: budget.logical_series,
|
||||
max_rendered_series: budget.rendered_series,
|
||||
..*definition
|
||||
});
|
||||
}
|
||||
Ok(Box::leak(definitions.into_boxed_slice()))
|
||||
}
|
||||
|
||||
static ADMIN_PROJECTION: OnceLock<&'static [MetricDefinition]> = OnceLock::new();
|
||||
static MCP_PROJECTION: OnceLock<&'static [MetricDefinition]> = OnceLock::new();
|
||||
|
||||
/// Derived projection cache initialized once per service (no per-request allocation).
|
||||
/// The static schema is a compile-time constant, so a checked-seam overflow here
|
||||
/// is a programming error: it fails loudly instead of publishing a saturated or
|
||||
/// truncated series budget.
|
||||
pub fn service_projection(service: MetricService) -> &'static [MetricDefinition] {
|
||||
let cache = match service {
|
||||
MetricService::AdminApi => &ADMIN_PROJECTION,
|
||||
MetricService::McpServer => &MCP_PROJECTION,
|
||||
};
|
||||
cache.get_or_init(|| match build_projection(service) {
|
||||
Ok(projection) => projection,
|
||||
Err(error) => {
|
||||
panic!("static metric projection must satisfy the checked schema seam: {error:?}")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn metric_schema_for_service(
|
||||
service: MetricService,
|
||||
) -> impl Iterator<Item = &'static MetricDefinition> {
|
||||
service_projection(service).iter()
|
||||
}
|
||||
|
||||
pub fn schema_budget(service: MetricService) -> Result<SchemaBudget, SchemaError> {
|
||||
validate_schema(service_projection(service))
|
||||
}
|
||||
|
||||
pub fn max_exemplar_slots(service: MetricService) -> usize {
|
||||
checked_exemplar_capacity(service)
|
||||
.expect("validated service projection must carry a bounded exemplar budget")
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Детерминированный компактный v2-снимок реестра
|
||||
//! (`docs/schemas/metrics-registry-v2.json`).
|
||||
|
||||
use super::budget::{
|
||||
SchemaError, checked_exemplar_slots, validate_all_projections, validate_schema,
|
||||
};
|
||||
use super::descriptor::{
|
||||
MAX_EXEMPLAR_SLOTS_PER_PROCESS, MAX_EXPOSITION_BYTES, MAX_LOGICAL_SERIES_PER_PROCESS,
|
||||
MAX_METRIC_FAMILIES, MAX_PRODUCT_LABELS_PER_FAMILY, MAX_RENDERED_SERIES_PER_PROCESS,
|
||||
METRIC_SCHEMA, METRIC_SCHEMA_VERSION, MetricProcess, PROCESS_CONSTANT_LABELS,
|
||||
};
|
||||
use super::projection::service_projection;
|
||||
use super::routes::HTTP_ROUTES;
|
||||
|
||||
/// Deterministic compact v2 registry snapshot (Rust descriptor table is the
|
||||
/// only generator). Every service projection is validated before rendering.
|
||||
pub fn render_metric_schema_json() -> Result<String, SchemaError> {
|
||||
validate_all_projections()?;
|
||||
let mut out = String::with_capacity(20 * 1024);
|
||||
out.push_str("{\"schema_version\":");
|
||||
out.push_str(&METRIC_SCHEMA_VERSION.to_string());
|
||||
out.push_str(",\"limits\":{\"max_families\":");
|
||||
out.push_str(&MAX_METRIC_FAMILIES.to_string());
|
||||
out.push_str(",\"max_product_labels_per_family\":");
|
||||
out.push_str(&MAX_PRODUCT_LABELS_PER_FAMILY.to_string());
|
||||
out.push_str(",\"max_logical_series\":");
|
||||
out.push_str(&MAX_LOGICAL_SERIES_PER_PROCESS.to_string());
|
||||
out.push_str(",\"max_rendered_series\":");
|
||||
out.push_str(&MAX_RENDERED_SERIES_PER_PROCESS.to_string());
|
||||
out.push_str(",\"max_exemplar_slots\":");
|
||||
out.push_str(&MAX_EXEMPLAR_SLOTS_PER_PROCESS.to_string());
|
||||
out.push_str(",\"max_exposition_bytes\":");
|
||||
out.push_str(&MAX_EXPOSITION_BYTES.to_string());
|
||||
out.push_str("},\"global_labels\":[");
|
||||
for (index, label) in PROCESS_CONSTANT_LABELS.iter().enumerate() {
|
||||
comma(&mut out, index);
|
||||
out.push_str("{\"name\":\"");
|
||||
out.push_str(label.name);
|
||||
out.push_str("\",\"class\":\"");
|
||||
out.push_str(label.class.as_str());
|
||||
out.push_str("\",\"domain\":[");
|
||||
out.push_str(&json_strings(label.values));
|
||||
out.push_str("]}");
|
||||
}
|
||||
out.push_str("],\"http_routes\":[");
|
||||
for (index, route) in HTTP_ROUTES.iter().enumerate() {
|
||||
comma(&mut out, index);
|
||||
out.push_str("{\"route\":\"");
|
||||
out.push_str(route.route);
|
||||
out.push_str("\",\"processes\":[");
|
||||
out.push_str(&json_processes(route.processes));
|
||||
out.push_str("]}");
|
||||
}
|
||||
out.push_str("],\"metrics\":[");
|
||||
for (index, definition) in METRIC_SCHEMA.iter().enumerate() {
|
||||
comma(&mut out, index);
|
||||
out.push_str("{\"name\":\"");
|
||||
out.push_str(definition.name);
|
||||
out.push_str("\",\"kind\":\"");
|
||||
out.push_str(definition.kind.as_str());
|
||||
out.push_str("\",\"unit\":\"");
|
||||
out.push_str(definition.unit.as_str());
|
||||
out.push_str("\",\"help\":\"");
|
||||
out.push_str(definition.description);
|
||||
out.push_str("\",\"processes\":[");
|
||||
out.push_str(&json_processes(definition.processes));
|
||||
out.push_str("],\"labels\":[");
|
||||
for (label_index, label_domain) in definition.label_domains.iter().enumerate() {
|
||||
comma(&mut out, label_index);
|
||||
out.push_str("{\"name\":\"");
|
||||
out.push_str(label_domain.name);
|
||||
out.push_str("\",\"class\":\"");
|
||||
out.push_str(label_domain.class.as_str());
|
||||
if label_domain.name == "route" {
|
||||
out.push_str("\",\"domain_ref\":\"http_routes\"}");
|
||||
} else {
|
||||
out.push_str("\",\"domain\":[");
|
||||
out.push_str(&json_strings(label_domain.values));
|
||||
out.push_str("]}");
|
||||
}
|
||||
}
|
||||
out.push_str("],\"buckets_seconds\":[");
|
||||
out.push_str(&json_numbers(definition.buckets));
|
||||
out.push_str("],\"bounds\":[");
|
||||
for (bound_index, process) in definition.processes.iter().enumerate() {
|
||||
comma(&mut out, bound_index);
|
||||
out.push_str(&bound_json(*process, definition.name)?);
|
||||
}
|
||||
out.push_str("]}");
|
||||
}
|
||||
out.push_str("],\"budgets\":[");
|
||||
for (index, process) in [MetricProcess::AdminApi, MetricProcess::McpServer]
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
comma(&mut out, index);
|
||||
let projection = service_projection(process.service());
|
||||
let budget = validate_schema(projection)?;
|
||||
let exemplars = projection.iter().try_fold(0_usize, |total, definition| {
|
||||
let slots = checked_exemplar_slots(
|
||||
definition.kind,
|
||||
definition.max_logical_series,
|
||||
definition.buckets.len(),
|
||||
)?;
|
||||
total.checked_add(slots).ok_or(SchemaError::BudgetExceeded)
|
||||
})?;
|
||||
out.push_str("{\"process\":\"");
|
||||
out.push_str(process.as_str());
|
||||
out.push_str("\",\"families\":");
|
||||
out.push_str(&projection.len().to_string());
|
||||
out.push_str(",\"logical_series\":");
|
||||
out.push_str(&budget.logical_series.to_string());
|
||||
out.push_str(",\"rendered_series\":");
|
||||
out.push_str(&budget.rendered_series.to_string());
|
||||
out.push_str(",\"exemplar_slots\":");
|
||||
out.push_str(&exemplars.to_string());
|
||||
out.push('}');
|
||||
}
|
||||
out.push_str("]}\n");
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn bound_json(process: MetricProcess, name: &str) -> Result<String, SchemaError> {
|
||||
let projection = service_projection(process.service());
|
||||
let definition = projection
|
||||
.iter()
|
||||
.find(|definition| definition.name == name)
|
||||
.expect("validated projection declares every family it owns");
|
||||
let exemplars = checked_exemplar_slots(
|
||||
definition.kind,
|
||||
definition.max_logical_series,
|
||||
definition.buckets.len(),
|
||||
)?;
|
||||
Ok(format!(
|
||||
"{{\"process\":\"{}\",\"logical_series\":{},\"rendered_series\":{},\"exemplar_slots\":{}}}",
|
||||
process.as_str(),
|
||||
definition.max_logical_series,
|
||||
definition.max_rendered_series,
|
||||
exemplars
|
||||
))
|
||||
}
|
||||
|
||||
fn json_strings(values: &[&str]) -> String {
|
||||
values
|
||||
.iter()
|
||||
.map(|value| format!("\"{value}\""))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
}
|
||||
|
||||
fn json_numbers(values: &[f64]) -> String {
|
||||
values
|
||||
.iter()
|
||||
.map(|value| value.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
}
|
||||
|
||||
fn json_processes(values: &[MetricProcess]) -> String {
|
||||
values
|
||||
.iter()
|
||||
.map(|value| format!("\"{}\"", value.as_str()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
}
|
||||
|
||||
fn comma(out: &mut String, index: usize) {
|
||||
if index > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
//! Единственная вручную поддерживаемая таблица route+owners (`HTTP_ROUTES`) и
|
||||
//! производные от неё домены (union и две сервисные проекции).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::budget::SchemaError;
|
||||
use super::descriptor::{MetricProcess, MetricService};
|
||||
|
||||
pub(crate) const BOTH: &[MetricProcess] = &[MetricProcess::AdminApi, MetricProcess::McpServer];
|
||||
pub(crate) const MCP: &[MetricProcess] = &[MetricProcess::McpServer];
|
||||
|
||||
/// One row of the single manually maintained route/ownership truth.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct HttpRouteDefinition {
|
||||
pub route: &'static str,
|
||||
pub processes: &'static [MetricProcess],
|
||||
}
|
||||
|
||||
const fn process_matches(value: MetricProcess, expected: MetricProcess) -> bool {
|
||||
matches!(
|
||||
(value, expected),
|
||||
(MetricProcess::AdminApi, MetricProcess::AdminApi)
|
||||
| (MetricProcess::McpServer, MetricProcess::McpServer)
|
||||
)
|
||||
}
|
||||
|
||||
const fn owners_contain(row: &HttpRouteDefinition, process: MetricProcess) -> bool {
|
||||
let mut index = 0;
|
||||
while index < row.processes.len() {
|
||||
if process_matches(row.processes[index], process) {
|
||||
return true;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
const fn project_route_count(process: MetricProcess) -> usize {
|
||||
let mut count = 0;
|
||||
let mut index = 0;
|
||||
while index < HTTP_ROUTES.len() {
|
||||
if owners_contain(&HTTP_ROUTES[index], process) {
|
||||
count += 1;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
const fn project_route_domain<const N: usize>(process: MetricProcess) -> [&'static str; N] {
|
||||
let mut routes = [""; N];
|
||||
let mut index = 0;
|
||||
let mut next = 0;
|
||||
while index < HTTP_ROUTES.len() {
|
||||
if owners_contain(&HTTP_ROUTES[index], process) {
|
||||
routes[next] = HTTP_ROUTES[index].route;
|
||||
next += 1;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
routes
|
||||
}
|
||||
|
||||
/// Union route domain (`91`) derived from the single ownership table.
|
||||
pub const HTTP_ROUTE_DOMAIN: &[&str] = &union_route_domain_array();
|
||||
|
||||
const fn union_route_domain_array() -> [&'static str; HTTP_ROUTES.len()] {
|
||||
let mut routes = [""; HTTP_ROUTES.len()];
|
||||
let mut index = 0;
|
||||
while index < HTTP_ROUTES.len() {
|
||||
routes[index] = HTTP_ROUTES[index].route;
|
||||
index += 1;
|
||||
}
|
||||
routes
|
||||
}
|
||||
|
||||
const ADMIN_ROUTE_COUNT: usize = project_route_count(MetricProcess::AdminApi);
|
||||
const MCP_ROUTE_COUNT: usize = project_route_count(MetricProcess::McpServer);
|
||||
|
||||
pub const ADMIN_HTTP_ROUTE_DOMAIN: &[&str] =
|
||||
&project_route_domain::<ADMIN_ROUTE_COUNT>(MetricProcess::AdminApi);
|
||||
pub const MCP_HTTP_ROUTE_DOMAIN: &[&str] =
|
||||
&project_route_domain::<MCP_ROUTE_COUNT>(MetricProcess::McpServer);
|
||||
|
||||
/// The single manually maintained route+owners enumeration. Sorted by ASCII
|
||||
/// route; `unmatched` is the last row. Every other domain (union and the two
|
||||
/// service projections) is derived from this table.
|
||||
pub const HTTP_ROUTES: &[HttpRouteDefinition] = &[
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/capabilities",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents/tool-search/preview",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/archive",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/bindings",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}/revoke",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/publish",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/unpublish",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/versions/{version}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/approvals",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/approvals/{approval_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/approve",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/deny",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/auth-profiles",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/auth-profiles/{auth_profile_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/export",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/imports/openapi/plans/{plan_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/imports/openapi/preview",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/create",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/plans",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/imports/openapi/{plan_id}/apply",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/logs",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/logs/export.csv",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/logs/{log_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/onboarding",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/onboarding/events",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/onboarding/import-context",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/onboarding/reset-selection",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/onboarding/select-draft",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/analyze-quality",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/import",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/archive",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/drafts/generate",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/export",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/publish",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/input-json",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/output-json",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/test-runs",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions/{version}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/prompts",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/prompts/import",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/export",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/preview",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/versions/{version}/export",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/import",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/archive",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/content",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/export",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/preview",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/publish",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/revoke",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/test-runs",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}/content",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}/export",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/secrets",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/secrets/{secret_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/secrets/{secret_id}/rotate",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/upstreams",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/upstreams/{upstream_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/usage",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/usage/agents/{agent_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/usage/export.csv",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/admin/workspaces/{workspace_id}/usage/operations/{operation_id}",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/auth/bootstrap/complete",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/auth/bootstrap/status",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/auth/login",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/auth/logout",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/auth/password",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/auth/profile",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/auth/session",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/api/auth/session/csrf",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/health",
|
||||
processes: BOTH,
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/ready",
|
||||
processes: BOTH,
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/v1/{workspace_slug}/{agent_slug}",
|
||||
processes: &[MetricProcess::McpServer],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/v1/{workspace_slug}/{agent_slug}/approvals",
|
||||
processes: &[MetricProcess::McpServer],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}",
|
||||
processes: &[MetricProcess::McpServer],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/approve",
|
||||
processes: &[MetricProcess::McpServer],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/deny",
|
||||
processes: &[MetricProcess::McpServer],
|
||||
},
|
||||
HttpRouteDefinition {
|
||||
route: "unmatched",
|
||||
processes: BOTH,
|
||||
},
|
||||
];
|
||||
|
||||
/// Structural validation of one candidate ownership table (used to reject
|
||||
/// duplicated routes, empty owner sets and duplicate owners in reviews/mutation
|
||||
/// tests). The production table itself is a `const`, so this is the typed gate
|
||||
/// that proves the same invariants on any candidate.
|
||||
pub fn validate_http_routes(routes: &[HttpRouteDefinition]) -> Result<(), SchemaError> {
|
||||
if routes.is_empty() {
|
||||
return Err(SchemaError::InvalidDomain);
|
||||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
for row in routes {
|
||||
if !seen.insert(row.route) {
|
||||
return Err(SchemaError::DuplicateMetric);
|
||||
}
|
||||
if row.processes.is_empty() || row.processes.len() > 2 {
|
||||
return Err(SchemaError::InvalidMetric);
|
||||
}
|
||||
let mut owners = BTreeSet::new();
|
||||
for owner in row.processes {
|
||||
if !owners.insert(*owner) {
|
||||
return Err(SchemaError::InvalidMetric);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !seen.contains("unmatched") {
|
||||
return Err(SchemaError::InvalidDomain);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Owners of one declared route template (`None` = not a declared template).
|
||||
pub fn http_route_processes(route: &str) -> Option<&'static [MetricProcess]> {
|
||||
HTTP_ROUTES
|
||||
.iter()
|
||||
.find(|definition| definition.route == route)
|
||||
.map(|definition| definition.processes)
|
||||
}
|
||||
|
||||
pub(crate) fn service_route_domain(service: MetricService) -> &'static [&'static str] {
|
||||
match service {
|
||||
MetricService::AdminApi => ADMIN_HTTP_ROUTE_DOMAIN,
|
||||
MetricService::McpServer => MCP_HTTP_ROUTE_DOMAIN,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
//! Story 3.6 · AT-3.6-08 · фаза B — service binding и exact wrong-tuple policy.
|
||||
//!
|
||||
//! Binding процесса — это `OnceLock`, а не per-request состояние, поэтому
|
||||
//! каждый сценарий, требующий другого сервиса (или вообще отсутствия binding),
|
||||
//! исполняется в **fresh child** того же тест-бинаря: глобальный reset/rebind
|
||||
//! отсутствует by design (CONTRACT §4/§5, фикстура F2).
|
||||
//!
|
||||
//! `TD-B1` unbound facade — безопасный no-op.
|
||||
//! `TD-B2` повтор того же сервиса идемпотентен.
|
||||
//! `TD-B3` конфликт разных сервисов: ровно один winner, loser — `ConflictingService`.
|
||||
//! `TD-B4` known route чужого сервиса пишется как `unmatched` (counter+duration).
|
||||
//! `TD-B5` прямой exemplar не может создать ключ чужого route.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_metrics::{
|
||||
ExemplarTraceId, HttpMethod, HttpRoute, HttpStatusClass, MAX_EXEMPLAR_SLOTS_PER_PROCESS,
|
||||
MetricBindingError, MetricService, bound_metric_service, exemplar_snapshot,
|
||||
record_cache_outcome, record_http_request, record_http_request_with_exemplar,
|
||||
record_invocation_history_lost, record_mcp_request, record_tool_invocation,
|
||||
record_upstream_request, set_catalog, set_db_pool_connections, set_mcp_active_sessions,
|
||||
};
|
||||
use metrics_util::debugging::DebuggingRecorder;
|
||||
|
||||
const BINDING_ROLE_ENV: &str = "CRANK_METRICS_TEST_BINDING_ROLE";
|
||||
const MCP_ONLY_ROUTE: &str = "/v1/{workspace_slug}/{agent_slug}";
|
||||
const ADMIN_ROUTE: &str = "/api/admin/workspaces/{workspace_id}/operations";
|
||||
|
||||
fn route_to_child(role: &str, test: &str) -> bool {
|
||||
match std::env::var(BINDING_ROLE_ENV).ok().as_deref() {
|
||||
Some(actual) if actual == role => false,
|
||||
Some(actual) => panic!("child for {test} runs with role {actual}, expected {role}"),
|
||||
None => {
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().expect("current test binary"))
|
||||
.args([test, "--exact", "--nocapture"])
|
||||
.env(BINDING_ROLE_ENV, role)
|
||||
.output()
|
||||
.expect("re-executed binding child");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"binding child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Samples = Vec<(
|
||||
metrics_util::CompositeKey,
|
||||
Option<metrics::Unit>,
|
||||
Option<metrics::SharedString>,
|
||||
metrics_util::debugging::DebugValue,
|
||||
)>;
|
||||
|
||||
fn rendered_keys(samples: &Samples) -> BTreeSet<String> {
|
||||
samples
|
||||
.iter()
|
||||
.map(|(key, _, _, _)| {
|
||||
let mut labels = key
|
||||
.key()
|
||||
.labels()
|
||||
.map(|label| format!("{}={}", label.key(), label.value()))
|
||||
.collect::<Vec<_>>();
|
||||
labels.sort();
|
||||
format!("{}{{{}}}", key.key().name(), labels.join(","))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn trace() -> ExemplarTraceId {
|
||||
ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").expect("valid trace id")
|
||||
}
|
||||
|
||||
/// TD-B1 — до binding все facade-пути (включая guards и exemplar) — безопасный
|
||||
/// no-op: ни одного handle, ни одной series, ни одного exemplar entry.
|
||||
#[test]
|
||||
fn unbound_facade_is_a_no_op() {
|
||||
if route_to_child("unbound", "unbound_facade_is_a_no_op") {
|
||||
return;
|
||||
}
|
||||
assert_eq!(bound_metric_service(), None);
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
record_http_request(
|
||||
HttpRoute::from_matched_path(ADMIN_ROUTE),
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_millis(1),
|
||||
);
|
||||
record_http_request_with_exemplar(
|
||||
HttpRoute::from_matched_path(ADMIN_ROUTE),
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_millis(1),
|
||||
Some(trace()),
|
||||
);
|
||||
record_mcp_request(
|
||||
crank_metrics::McpMethod::ToolsCall,
|
||||
crank_metrics::McpResponseMode::Json,
|
||||
crank_metrics::McpOutcome::Success,
|
||||
Duration::from_millis(1),
|
||||
);
|
||||
record_tool_invocation(
|
||||
crank_metrics::InvocationSource::AgentToolCall,
|
||||
crank_metrics::ToolOutcome::Success,
|
||||
crank_metrics::ToolErrorKind::None,
|
||||
Duration::from_millis(1),
|
||||
);
|
||||
record_upstream_request(
|
||||
crank_metrics::UpstreamOperationKind::Rest,
|
||||
crank_metrics::UpstreamOutcome::Success,
|
||||
Duration::from_millis(1),
|
||||
);
|
||||
record_cache_outcome(crank_metrics::CacheOutcome::Hit);
|
||||
record_invocation_history_lost();
|
||||
set_db_pool_connections(crank_metrics::DbPoolState::Idle, 1);
|
||||
set_mcp_active_sessions(1);
|
||||
set_catalog(1, 1, 1);
|
||||
let _http = crank_metrics::InFlightGuard::http();
|
||||
let _runtime = crank_metrics::InFlightGuard::runtime();
|
||||
let _stream = crank_metrics::InFlightGuard::mcp_stream();
|
||||
let _tool = crank_metrics::ToolInvocationMetrics::start(
|
||||
crank_metrics::InvocationSource::AgentToolCall,
|
||||
);
|
||||
let _upstream = crank_metrics::UpstreamRequestMetrics::start(
|
||||
crank_metrics::UpstreamOperationKind::Rest,
|
||||
);
|
||||
});
|
||||
let samples = snapshotter.snapshot().into_vec();
|
||||
assert!(
|
||||
samples.is_empty(),
|
||||
"unbound facade не может регистрировать series: {:?}",
|
||||
rendered_keys(&samples)
|
||||
);
|
||||
assert!(
|
||||
exemplar_snapshot().is_empty(),
|
||||
"unbound facade не может создавать exemplar entries"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-B2 — повтор того же сервиса идемпотентен.
|
||||
#[test]
|
||||
fn same_service_bind_is_idempotent() {
|
||||
if route_to_child("admin_api", "same_service_bind_is_idempotent") {
|
||||
return;
|
||||
}
|
||||
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("first bind");
|
||||
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("same-service rebind");
|
||||
assert_eq!(bound_metric_service(), Some(MetricService::AdminApi));
|
||||
assert_eq!(
|
||||
crank_metrics::bind_metric_service(MetricService::McpServer),
|
||||
Err(MetricBindingError::ConflictingService)
|
||||
);
|
||||
assert_eq!(
|
||||
bound_metric_service(),
|
||||
Some(MetricService::AdminApi),
|
||||
"конфликт не меняет уже опубликованный сервис"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-B3 — concurrent конфликт разных сервисов: ровно один winner.
|
||||
#[test]
|
||||
fn conflicting_concurrent_bind_has_one_winner() {
|
||||
if route_to_child("conflict", "conflicting_concurrent_bind_has_one_winner") {
|
||||
return;
|
||||
}
|
||||
let results = std::thread::scope(|scope| {
|
||||
let admin = scope.spawn(|| crank_metrics::bind_metric_service(MetricService::AdminApi));
|
||||
let mcp = scope.spawn(|| crank_metrics::bind_metric_service(MetricService::McpServer));
|
||||
vec![
|
||||
("admin_api", admin.join().expect("admin bind thread")),
|
||||
("mcp_server", mcp.join().expect("mcp bind thread")),
|
||||
]
|
||||
});
|
||||
let winners = results
|
||||
.iter()
|
||||
.filter(|(_, result)| result.is_ok())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
winners.len(),
|
||||
1,
|
||||
"ровно один сервис может победить: {results:?}"
|
||||
);
|
||||
for (role, result) in &results {
|
||||
if let Err(error) = result {
|
||||
assert_eq!(
|
||||
*error,
|
||||
MetricBindingError::ConflictingService,
|
||||
"loser {role} обязан получить типизированный конфликт"
|
||||
);
|
||||
}
|
||||
}
|
||||
let winner = winners[0].0;
|
||||
let expected = match winner {
|
||||
"admin_api" => Some(MetricService::AdminApi),
|
||||
_ => Some(MetricService::McpServer),
|
||||
};
|
||||
assert_eq!(bound_metric_service(), expected);
|
||||
}
|
||||
|
||||
/// TD-B4 — known route чужого сервиса degraded в `unmatched`, запрос сохраняется.
|
||||
#[test]
|
||||
fn wrong_service_route_records_unmatched() {
|
||||
if route_to_child("admin_api", "wrong_service_route_records_unmatched") {
|
||||
return;
|
||||
}
|
||||
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("admin bind");
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
record_http_request(
|
||||
HttpRoute::from_matched_path(MCP_ONLY_ROUTE),
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_secs_f64(0.004),
|
||||
);
|
||||
});
|
||||
let samples = snapshotter.snapshot().into_vec();
|
||||
let keys = rendered_keys(&samples);
|
||||
assert!(
|
||||
keys.contains("crank_http_requests_total{method=GET,route=unmatched,status_class=2xx}"),
|
||||
"чужой known route обязан стать unmatched с сохранением method/status: {keys:?}"
|
||||
);
|
||||
assert!(
|
||||
keys.contains("crank_http_request_duration_seconds{method=GET,route=unmatched}"),
|
||||
"duration обязан идти в тот же unmatched series: {keys:?}"
|
||||
);
|
||||
assert!(
|
||||
keys.iter().all(|key| !key.contains("workspace_slug")),
|
||||
"ни одна series не может нести ключ чужого route: {keys:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
keys.len(),
|
||||
2,
|
||||
"wrong tuple не создаёт новых families: {keys:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-B5 — прямой exemplar не создаёт ключ чужого route.
|
||||
#[test]
|
||||
fn direct_exemplar_cannot_create_foreign_route_key() {
|
||||
if route_to_child(
|
||||
"admin_api",
|
||||
"direct_exemplar_cannot_create_foreign_route_key",
|
||||
) {
|
||||
return;
|
||||
}
|
||||
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("admin bind");
|
||||
assert!(
|
||||
exemplar_snapshot().is_empty(),
|
||||
"fixture требует чистый exemplar store"
|
||||
);
|
||||
record_http_request_with_exemplar(
|
||||
HttpRoute::from_matched_path(MCP_ONLY_ROUTE),
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_millis(4),
|
||||
Some(trace()),
|
||||
);
|
||||
record_http_request_with_exemplar(
|
||||
HttpRoute::from_matched_path(ADMIN_ROUTE),
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_millis(4),
|
||||
Some(trace()),
|
||||
);
|
||||
let observations = exemplar_snapshot();
|
||||
assert_eq!(
|
||||
observations.len(),
|
||||
2,
|
||||
"exemplar обязан попасть в unmatched и в собственную admin-серию: {observations:#?}"
|
||||
);
|
||||
assert!(
|
||||
observations.iter().all(
|
||||
|observation| observation.labels.contains(&("route", "unmatched"))
|
||||
|| observation.labels.contains(&("route", ADMIN_ROUTE))
|
||||
),
|
||||
"ни один exemplar не может нести чужой route: {observations:#?}"
|
||||
);
|
||||
assert!(
|
||||
observations
|
||||
.iter()
|
||||
.all(|observation| !observation.labels.contains(&("route", MCP_ONLY_ROUTE))),
|
||||
"foreign route key не может быть создан"
|
||||
);
|
||||
assert!(
|
||||
MAX_EXEMPLAR_SLOTS_PER_PROCESS
|
||||
>= crank_metrics::max_exemplar_slots(MetricService::AdminApi)
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,8 @@ use metrics_util::debugging::DebuggingRecorder;
|
||||
|
||||
#[test]
|
||||
fn one_million_hostile_values_collapse_to_the_same_closed_series() {
|
||||
crank_metrics::bind_metric_service(MetricService::McpServer)
|
||||
.expect("isolated metrics binding for the cardinality fixture");
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
|
||||
@@ -3,15 +3,47 @@ use std::{collections::BTreeSet, time::Duration};
|
||||
use crank_metrics::{
|
||||
CacheOutcome, ConfirmationOutcome, DbPoolState, Exporter, HttpMethod, HttpRoute,
|
||||
HttpStatusClass, IdempotencyOutcome, InFlightGuard, InvocationSource, LimitStage, McpMethod,
|
||||
McpOutcome, McpResponseMode, SignalType, ToolErrorKind, ToolInvocationMetrics, ToolOutcome,
|
||||
UpstreamOperationKind, UpstreamOutcome, UpstreamRequestMetrics, initialize_gauges,
|
||||
metric_schema, record_cache_outcome, record_confirmation_outcome, record_export_failure,
|
||||
record_http_request, record_idempotency_outcome, record_invocation_history_lost,
|
||||
record_limit_rejection, record_mcp_request, record_tool_invocation, record_upstream_request,
|
||||
set_catalog, set_db_pool_connections, set_mcp_active_sessions, set_mcp_session_metrics_fresh,
|
||||
McpOutcome, McpResponseMode, MetricService, SignalType, ToolErrorKind, ToolInvocationMetrics,
|
||||
ToolOutcome, UpstreamOperationKind, UpstreamOutcome, UpstreamRequestMetrics,
|
||||
bind_metric_service, initialize_gauges, metric_schema, record_cache_outcome,
|
||||
record_confirmation_outcome, record_export_failure, record_http_request,
|
||||
record_idempotency_outcome, record_invocation_history_lost, record_limit_rejection,
|
||||
record_mcp_request, record_tool_invocation, record_upstream_request, set_catalog,
|
||||
set_db_pool_connections, set_mcp_active_sessions, set_mcp_session_metrics_fresh,
|
||||
};
|
||||
use metrics_util::debugging::DebuggingRecorder;
|
||||
|
||||
/// Service binding is process-global (`OnceLock`), so every case that needs a
|
||||
/// different service runs in a fresh child re-executed from this same test
|
||||
/// binary instead of resetting a global.
|
||||
const BINDING_ROLE_ENV: &str = "CRANK_METRICS_TEST_BINDING_ROLE";
|
||||
|
||||
fn route_to_child(role: &str, test: &str) -> bool {
|
||||
match std::env::var(BINDING_ROLE_ENV).ok().as_deref() {
|
||||
Some(actual) if actual == role => false,
|
||||
Some(actual) => panic!("child for {test} runs with role {actual}, expected {role}"),
|
||||
None => {
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().expect("current test binary"))
|
||||
.args([test, "--exact", "--nocapture"])
|
||||
.env(BINDING_ROLE_ENV, role)
|
||||
.output()
|
||||
.expect("re-executed binding child");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"binding child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(service: MetricService) {
|
||||
bind_metric_service(service).expect("isolated metrics binding for this fixture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_names_are_unique_and_labels_are_closed() {
|
||||
let schema = metric_schema();
|
||||
@@ -82,6 +114,10 @@ fn application_outcomes_are_distinct_from_transport_success() {
|
||||
|
||||
#[test]
|
||||
fn impossible_tool_outcome_pairs_are_normalized() {
|
||||
if route_to_child("mcp_server", "impossible_tool_outcome_pairs_are_normalized") {
|
||||
return;
|
||||
}
|
||||
bind(MetricService::McpServer);
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
@@ -102,6 +138,13 @@ fn impossible_tool_outcome_pairs_are_normalized() {
|
||||
|
||||
#[test]
|
||||
fn dropped_product_guards_record_aborted_outcomes() {
|
||||
if route_to_child(
|
||||
"mcp_server",
|
||||
"dropped_product_guards_record_aborted_outcomes",
|
||||
) {
|
||||
return;
|
||||
}
|
||||
bind(MetricService::McpServer);
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
|
||||
@@ -131,6 +174,10 @@ fn has_label(key: &metrics::Key, name: &str, value: &str) -> bool {
|
||||
|
||||
#[test]
|
||||
fn diverse_calls_cannot_create_unbounded_series() {
|
||||
if route_to_child("mcp_server", "diverse_calls_cannot_create_unbounded_series") {
|
||||
return;
|
||||
}
|
||||
bind(MetricService::McpServer);
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
|
||||
@@ -178,6 +225,13 @@ fn diverse_calls_cannot_create_unbounded_series() {
|
||||
|
||||
#[test]
|
||||
fn every_recording_api_matches_the_declared_schema() {
|
||||
if route_to_child(
|
||||
"mcp_server",
|
||||
"every_recording_api_matches_the_declared_schema",
|
||||
) {
|
||||
return;
|
||||
}
|
||||
bind(MetricService::McpServer);
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
|
||||
@@ -259,6 +313,13 @@ fn every_recording_api_matches_the_declared_schema() {
|
||||
|
||||
#[test]
|
||||
fn admin_gauge_initialization_never_emits_mcp_only_series() {
|
||||
if route_to_child(
|
||||
"admin_api",
|
||||
"admin_gauge_initialization_never_emits_mcp_only_series",
|
||||
) {
|
||||
return;
|
||||
}
|
||||
bind(MetricService::AdminApi);
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Story 3.6 · AT-3.6-08 · фаза B — v2 snapshot и CLI.
|
||||
//!
|
||||
//! `TD-C1` default output CLI равен закоммиченному v2-снимку byte-for-byte.
|
||||
//! `TD-C2` `--check` не зависит от cwd и печатает точную строку версии.
|
||||
//! `TD-C3` ошибки CLI точны, без JSON в выводе.
|
||||
//! `TD-C4` сериализация компактна и не несёт динамического текста.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
const FROZEN_V2: &str = include_str!("../../../docs/schemas/metrics-registry-v2.json");
|
||||
|
||||
fn binary() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_crank-metrics-contract"))
|
||||
}
|
||||
|
||||
/// TD-C1 — default output CLI = versioned snapshot (byte-for-byte, детерминированно).
|
||||
#[test]
|
||||
fn default_output_is_the_versioned_snapshot() {
|
||||
let first = binary().output().expect("contract CLI runs");
|
||||
assert!(
|
||||
first.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&first.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8(first.stdout).expect("utf-8 snapshot");
|
||||
assert_eq!(
|
||||
stdout, FROZEN_V2,
|
||||
"default CLI обязан печатать ровно закоммиченный v2-снимок"
|
||||
);
|
||||
let second = binary().output().expect("contract CLI reruns");
|
||||
assert_eq!(
|
||||
String::from_utf8(second.stdout).expect("utf-8 snapshot"),
|
||||
stdout,
|
||||
"рендер обязан быть детерминированным"
|
||||
);
|
||||
let rendered = crank_metrics::render_metric_schema_json().expect("renderer");
|
||||
assert_eq!(
|
||||
rendered, FROZEN_V2,
|
||||
"Rust renderer обязан совпасть с закоммиченным снимком"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-C2 — `--check` независим от cwd и печатает точную строку версии.
|
||||
#[test]
|
||||
fn check_is_cwd_independent_and_exact() {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"crank-metrics-contract-v2-{}-{}",
|
||||
std::process::id(),
|
||||
std::thread::current().name().unwrap_or("main").len()
|
||||
));
|
||||
std::fs::create_dir_all(&directory).expect("temp cwd");
|
||||
let output = binary()
|
||||
.arg("--check")
|
||||
.current_dir(&directory)
|
||||
.output()
|
||||
.expect("contract CLI runs");
|
||||
std::fs::remove_dir_all(&directory).ok();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stdout).expect("utf-8"),
|
||||
"metrics_contract_ok schema_version=2\n",
|
||||
"--check обязан печатать ровно эту строку"
|
||||
);
|
||||
assert!(output.stderr.is_empty(), "--check не пишет stderr");
|
||||
}
|
||||
|
||||
/// TD-C3 — ошибочные команды: точный stderr, ненулевой exit, никакого JSON.
|
||||
#[test]
|
||||
fn error_paths_are_exact_and_json_free() {
|
||||
for args in [vec!["--unknown"], vec!["--check", "extra"], vec!["render"]] {
|
||||
let output = binary().args(&args).output().expect("contract CLI runs");
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"команда {args:?} обязана падать, output: {:?}",
|
||||
output
|
||||
);
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stderr).expect("utf-8"),
|
||||
"metrics_contract_invalid_command\n",
|
||||
"точный static error text для {args:?}"
|
||||
);
|
||||
let stdout = String::from_utf8(output.stdout).expect("utf-8");
|
||||
assert!(
|
||||
!stdout.contains('{') && !stdout.contains('"'),
|
||||
"ошибочный вывод не может содержать JSON: {stdout:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-C4 — компактная сериализация без динамического текста и < 65536 bytes.
|
||||
#[test]
|
||||
fn serialization_is_compact_and_free_of_dynamic_text() {
|
||||
assert!(
|
||||
FROZEN_V2.len() < 65_536,
|
||||
"v2-снимок обязан остаться < 65536 bytes, observed {}",
|
||||
FROZEN_V2.len()
|
||||
);
|
||||
assert!(FROZEN_V2.ends_with("}\n"), "ровно одна завершающая LF");
|
||||
assert_eq!(
|
||||
FROZEN_V2.matches('\n').count(),
|
||||
1,
|
||||
"компактный JSON без переводов строк внутри документа"
|
||||
);
|
||||
assert!(
|
||||
!FROZEN_V2.contains(" "),
|
||||
"вне строк не может быть пробелов"
|
||||
);
|
||||
assert!(FROZEN_V2.starts_with("{\"schema_version\":2,"));
|
||||
assert!(FROZEN_V2.contains("\"unmatched\""));
|
||||
for forbidden in [
|
||||
"trace_id",
|
||||
"request_id",
|
||||
"correlation_id",
|
||||
"workspace-",
|
||||
"/home/",
|
||||
"/tmp/",
|
||||
"http://",
|
||||
"https://",
|
||||
] {
|
||||
assert!(
|
||||
!FROZEN_V2.contains(forbidden),
|
||||
"v2-снимок не может нести динамический текст `{forbidden}`"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
FROZEN_V2
|
||||
.contains("\"buckets_seconds\":[0.005,0.01,0.025,0.05,0.1,0.25,0.5,1,2.5,5,10,30,60]"),
|
||||
"bucket'ы обязаны быть точными числами (1, а не 1.0)"
|
||||
);
|
||||
let snapshot_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../docs/schemas/metrics-registry-v2.json");
|
||||
assert!(snapshot_path.is_file(), "v2-снимок обязан быть закоммичен");
|
||||
let v1_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../docs/schemas/metrics-registry-v1.json");
|
||||
assert!(v1_path.is_file(), "frozen v1 обязан остаться на месте");
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! Story 3.6 · AT-3.6-08 · фаза B — family gating и gauges по binding.
|
||||
//!
|
||||
//! `TD-B8` MCP-only facade вызовы в admin-процессе — no-op без handle/exemplar.
|
||||
//! `TD-B9` `initialize_gauges` требует совпадающий binding, иначе no-op.
|
||||
//! `TD-B10` guard чужого family при drop не создаёт series.
|
||||
//!
|
||||
//! Каждый кейс исполняется в fresh child (binding — process-global `OnceLock`).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_metrics::{
|
||||
DbPoolState, InFlightGuard, InvocationSource, McpMethod, McpOutcome, McpResponseMode,
|
||||
MetricService, ToolErrorKind, ToolOutcome, UpstreamOperationKind, UpstreamOutcome,
|
||||
exemplar_snapshot, initialize_gauges, record_cache_outcome, record_idempotency_outcome,
|
||||
record_invocation_history_lost, record_mcp_request, record_mcp_request_with_exemplar,
|
||||
record_tool_invocation, record_upstream_request, set_catalog, set_mcp_active_sessions,
|
||||
};
|
||||
use metrics_util::debugging::DebuggingRecorder;
|
||||
|
||||
const BINDING_ROLE_ENV: &str = "CRANK_METRICS_TEST_BINDING_ROLE";
|
||||
|
||||
fn route_to_child(role: &str, test: &str) -> bool {
|
||||
match std::env::var(BINDING_ROLE_ENV).ok().as_deref() {
|
||||
Some(actual) if actual == role => false,
|
||||
Some(actual) => panic!("child for {test} runs with role {actual}, expected {role}"),
|
||||
None => {
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().expect("current test binary"))
|
||||
.args([test, "--exact", "--nocapture"])
|
||||
.env(BINDING_ROLE_ENV, role)
|
||||
.output()
|
||||
.expect("re-executed binding child");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"binding child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_admin() {
|
||||
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("admin bind");
|
||||
}
|
||||
|
||||
fn series_names(
|
||||
samples: &[(
|
||||
metrics_util::CompositeKey,
|
||||
Option<metrics::Unit>,
|
||||
Option<metrics::SharedString>,
|
||||
metrics_util::debugging::DebugValue,
|
||||
)],
|
||||
) -> BTreeSet<String> {
|
||||
samples
|
||||
.iter()
|
||||
.map(|(key, _, _, _)| key.key().name().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// TD-B8 — MCP-only families в admin-процессе не создают ни handles, ни exemplars.
|
||||
#[test]
|
||||
fn mcp_only_calls_are_noop_in_admin_process() {
|
||||
if route_to_child("admin_api", "mcp_only_calls_are_noop_in_admin_process") {
|
||||
return;
|
||||
}
|
||||
bind_admin();
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
record_mcp_request(
|
||||
McpMethod::ToolsCall,
|
||||
McpResponseMode::Json,
|
||||
McpOutcome::Success,
|
||||
Duration::from_millis(1),
|
||||
);
|
||||
record_mcp_request_with_exemplar(
|
||||
McpMethod::ToolsCall,
|
||||
McpResponseMode::Json,
|
||||
McpOutcome::Success,
|
||||
Duration::from_millis(1),
|
||||
crank_metrics::ExemplarTraceId::parse("0123456789abcdef0123456789abcdef"),
|
||||
);
|
||||
set_mcp_active_sessions(3);
|
||||
crank_metrics::set_mcp_session_metrics_fresh(true);
|
||||
set_catalog(7, 70, 1);
|
||||
});
|
||||
let samples = snapshotter.snapshot().into_vec();
|
||||
assert!(
|
||||
samples.is_empty(),
|
||||
"MCP-only families обязаны быть no-op в admin: {:?}",
|
||||
series_names(&samples)
|
||||
);
|
||||
assert!(
|
||||
exemplar_snapshot().is_empty(),
|
||||
"MCP-only exemplar не может создавать entry в admin-процессе"
|
||||
);
|
||||
|
||||
// Общие families при этом продолжают работать.
|
||||
let shared = DebuggingRecorder::new();
|
||||
let shared_snapshotter = shared.snapshotter();
|
||||
metrics::with_local_recorder(&shared, || {
|
||||
record_tool_invocation(
|
||||
InvocationSource::AgentToolCall,
|
||||
ToolOutcome::Success,
|
||||
ToolErrorKind::None,
|
||||
Duration::from_millis(1),
|
||||
);
|
||||
record_upstream_request(
|
||||
UpstreamOperationKind::Rest,
|
||||
UpstreamOutcome::Success,
|
||||
Duration::from_millis(1),
|
||||
);
|
||||
record_cache_outcome(crank_metrics::CacheOutcome::Hit);
|
||||
record_idempotency_outcome(crank_metrics::IdempotencyOutcome::Replay);
|
||||
record_invocation_history_lost();
|
||||
});
|
||||
let names = series_names(&shared_snapshotter.snapshot().into_vec());
|
||||
assert!(
|
||||
names.contains("crank_tool_invocations_total")
|
||||
&& names.contains("crank_upstream_requests_total")
|
||||
&& names.contains("crank_runtime_cache_total"),
|
||||
"shared families обязаны работать в admin: {names:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-B9 — `initialize_gauges` требует совпадающий binding.
|
||||
#[test]
|
||||
fn initialize_gauges_requires_matching_binding() {
|
||||
if route_to_child("admin_api", "initialize_gauges_requires_matching_binding") {
|
||||
return;
|
||||
}
|
||||
bind_admin();
|
||||
|
||||
let foreign = DebuggingRecorder::new();
|
||||
let foreign_snapshotter = foreign.snapshotter();
|
||||
metrics::with_local_recorder(&foreign, || {
|
||||
initialize_gauges(MetricService::McpServer);
|
||||
});
|
||||
assert!(
|
||||
foreign_snapshotter.snapshot().into_vec().is_empty(),
|
||||
"initialize_gauges чужого сервиса обязан быть no-op"
|
||||
);
|
||||
|
||||
let own = DebuggingRecorder::new();
|
||||
let own_snapshotter = own.snapshotter();
|
||||
metrics::with_local_recorder(&own, || {
|
||||
initialize_gauges(MetricService::AdminApi);
|
||||
});
|
||||
let names = series_names(&own_snapshotter.snapshot().into_vec());
|
||||
assert!(names.contains("crank_http_inflight"));
|
||||
assert!(names.contains("crank_runtime_inflight"));
|
||||
assert!(names.contains("crank_db_pool_connections"));
|
||||
assert!(
|
||||
names.iter().all(|name| !name.starts_with("crank_mcp_")),
|
||||
"admin gauges не могут включать MCP-only series: {names:?}"
|
||||
);
|
||||
assert!(
|
||||
names.iter().all(|name| !name.starts_with("crank_catalog_")),
|
||||
"admin gauges не могут включать catalog series: {names:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-B10 — guard чужого family при drop не создаёт series.
|
||||
#[test]
|
||||
fn foreign_family_guard_drop_creates_no_series() {
|
||||
if route_to_child("admin_api", "foreign_family_guard_drop_creates_no_series") {
|
||||
return;
|
||||
}
|
||||
bind_admin();
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
let stream = InFlightGuard::mcp_stream();
|
||||
drop(stream);
|
||||
let tool = crank_metrics::ToolInvocationMetrics::start(InvocationSource::AgentToolCall);
|
||||
drop(tool);
|
||||
let upstream = crank_metrics::UpstreamRequestMetrics::start(UpstreamOperationKind::Rest);
|
||||
drop(upstream);
|
||||
});
|
||||
let names = series_names(&snapshotter.snapshot().into_vec());
|
||||
assert!(
|
||||
names.iter().all(|name| !name.starts_with("crank_mcp_")),
|
||||
"guard чужого family не может создавать series: {names:?}"
|
||||
);
|
||||
assert!(
|
||||
!names.contains("crank_mcp_active_streams"),
|
||||
"foreign stream guard обязан быть no-op: {names:?}"
|
||||
);
|
||||
|
||||
// Собственный family работает: guard admin http и shared families.
|
||||
let own = DebuggingRecorder::new();
|
||||
let own_snapshotter = own.snapshotter();
|
||||
metrics::with_local_recorder(&own, || {
|
||||
let http = InFlightGuard::http();
|
||||
drop(http);
|
||||
});
|
||||
let own_names = series_names(&own_snapshotter.snapshot().into_vec());
|
||||
assert!(
|
||||
own_names.contains("crank_http_inflight"),
|
||||
"admin http guard обязан регистрировать series: {own_names:?}"
|
||||
);
|
||||
let _ = DbPoolState::Idle;
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
//! Story 3.6 · AT-3.6-08 · phase A (ATDD, test-only) — exemplar capacity invariants.
|
||||
//!
|
||||
//! Этот таргет на фазе A содержит **только** A-селекторы: они используют
|
||||
//! существующее API `crank-metrics` (`record_http_request_with_exemplar`,
|
||||
//! `exemplar_snapshot`, `DebuggingRecorder`) и не требуют правок `src/**`.
|
||||
//!
|
||||
//! * `TD-X1` — exemplar никогда не создаёт новый series (агрегат остаётся тем же
|
||||
//! keyset'ом и получает оба наблюдения).
|
||||
//! * `TD-X2` — latest-per-(family,labelset,bucket) стабилен: повторная запись того
|
||||
//! же ключа обновляет значение/trace_id, но не увеличивает число наблюдений.
|
||||
//!
|
||||
//! Публичный exact-maximal sweep/capacity этих сервисов и private poison-путь
|
||||
//! принадлежат фазе build (отсутствующее API/`src/**` правки) и в этот таргет не
|
||||
//! добавляются, чтобы фаза A оставалась компилируемой и честной.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_metrics::{
|
||||
ExemplarObservation, ExemplarTraceId, HttpMethod, HttpRoute, HttpStatusClass,
|
||||
MAX_EXEMPLAR_SLOTS_PER_PROCESS, MetricService, exemplar_snapshot, max_exemplar_slots,
|
||||
record_http_request, record_http_request_with_exemplar,
|
||||
};
|
||||
use metrics_util::debugging::DebuggingRecorder;
|
||||
|
||||
const HTTP_COUNTER: &str = "crank_http_requests_total";
|
||||
const HTTP_DURATION: &str = "crank_http_request_duration_seconds";
|
||||
|
||||
fn trace(value: &str) -> ExemplarTraceId {
|
||||
ExemplarTraceId::parse(value).expect("sanitised 32-lowercase-hex trace id")
|
||||
}
|
||||
|
||||
/// Rendered `name{label=value,…}` keys of the whole local snapshot (labels sorted).
|
||||
fn series_keys(
|
||||
snapshot: &[(
|
||||
metrics_util::CompositeKey,
|
||||
Option<metrics::Unit>,
|
||||
Option<metrics::SharedString>,
|
||||
metrics_util::debugging::DebugValue,
|
||||
)],
|
||||
) -> BTreeSet<String> {
|
||||
snapshot
|
||||
.iter()
|
||||
.map(|(key, _, _, _)| {
|
||||
let mut labels = key
|
||||
.key()
|
||||
.labels()
|
||||
.map(|label| format!("{}={}", label.key(), label.value()))
|
||||
.collect::<Vec<_>>();
|
||||
labels.sort();
|
||||
format!("{}{{{}}}", key.key().name(), labels.join(","))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Aggregate debug values of one observed series inside a snapshot (`None` = series absent).
|
||||
fn series_value(
|
||||
snapshot: &[(
|
||||
metrics_util::CompositeKey,
|
||||
Option<metrics::Unit>,
|
||||
Option<metrics::SharedString>,
|
||||
metrics_util::debugging::DebugValue,
|
||||
)],
|
||||
rendered_key: &str,
|
||||
) -> Option<String> {
|
||||
snapshot
|
||||
.iter()
|
||||
.find(|(key, _, _, _)| {
|
||||
let mut labels = key
|
||||
.key()
|
||||
.labels()
|
||||
.map(|label| format!("{}={}", label.key(), label.value()))
|
||||
.collect::<Vec<_>>();
|
||||
labels.sort();
|
||||
format!("{}{{{}}}", key.key().name(), labels.join(",")) == rendered_key
|
||||
})
|
||||
.map(|(_, _, _, value)| format!("{value:?}"))
|
||||
}
|
||||
|
||||
/// Histogram deltas of one series inside a (draining) snapshot.
|
||||
fn histogram_values(
|
||||
snapshot: &[(
|
||||
metrics_util::CompositeKey,
|
||||
Option<metrics::Unit>,
|
||||
Option<metrics::SharedString>,
|
||||
metrics_util::debugging::DebugValue,
|
||||
)],
|
||||
rendered_key: &str,
|
||||
) -> Vec<f64> {
|
||||
snapshot
|
||||
.iter()
|
||||
.find(|(key, _, _, _)| {
|
||||
let mut labels = key
|
||||
.key()
|
||||
.labels()
|
||||
.map(|label| format!("{}={}", label.key(), label.value()))
|
||||
.collect::<Vec<_>>();
|
||||
labels.sort();
|
||||
format!("{}{{{}}}", key.key().name(), labels.join(",")) == rendered_key
|
||||
})
|
||||
.map(|(_, _, _, value)| match value {
|
||||
metrics_util::debugging::DebugValue::Histogram(values) => {
|
||||
values.iter().map(|value| value.0).collect()
|
||||
}
|
||||
other => panic!("series {rendered_key} is not a histogram: {other:?}"),
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Observations of the process-global exemplar store for one exact keyset.
|
||||
fn observations(
|
||||
metric: &str,
|
||||
route: &str,
|
||||
method: &str,
|
||||
) -> Vec<std::sync::Arc<ExemplarObservation>> {
|
||||
exemplar_snapshot()
|
||||
.into_iter()
|
||||
.filter(|observation| {
|
||||
observation.metric == metric
|
||||
&& observation.labels.contains(&("route", route))
|
||||
&& observation.labels.contains(&("method", method))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// TD-X1 — exemplar не создаёт новый series и не подменяет агрегат.
|
||||
///
|
||||
/// `DebuggingRecorder::snapshot()` является **дренирующим** дельта-снимком
|
||||
/// (`metrics-util::debugging`, swap/clear): каждый снимок несёт ровно то, что
|
||||
/// записано с момента предыдущего. Поэтому оракул сравнивает keyset дельт двух
|
||||
/// последовательных запросов: exemplar-запись обязана попасть в тот же keyset.
|
||||
#[test]
|
||||
fn exemplar_observation_never_creates_a_new_series() {
|
||||
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
|
||||
.expect("isolated metrics binding for the exemplar capacity fixture");
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
let template = HttpRoute::from_matched_path("/api/admin/capabilities").as_str();
|
||||
assert_ne!(template, "unmatched", "оракул требует известный template");
|
||||
let route = HttpRoute::from_matched_path(template);
|
||||
|
||||
let (without_exemplar, with_exemplar) = metrics::with_local_recorder(&recorder, || {
|
||||
record_http_request_with_exemplar(
|
||||
route,
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_millis(4),
|
||||
None,
|
||||
);
|
||||
let without_exemplar = snapshotter.snapshot().into_vec();
|
||||
record_http_request_with_exemplar(
|
||||
route,
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_millis(5),
|
||||
Some(trace("0123456789abcdef0123456789abcdef")),
|
||||
);
|
||||
let with_exemplar = snapshotter.snapshot().into_vec();
|
||||
(without_exemplar, with_exemplar)
|
||||
});
|
||||
|
||||
let plain_keys = series_keys(&without_exemplar);
|
||||
let exemplar_keys = series_keys(&with_exemplar);
|
||||
assert_eq!(
|
||||
plain_keys.len(),
|
||||
2,
|
||||
"агрегат HTTP-запроса объявлен ровно двумя series (counter + histogram): {plain_keys:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
exemplar_keys, plain_keys,
|
||||
"exemplar не может создавать новый series (keyset дельт обязан совпасть)"
|
||||
);
|
||||
assert!(
|
||||
!exemplar_keys.iter().any(|key| key.contains("exemplar")),
|
||||
"exemplar не является отдельным series агрегата: {exemplar_keys:#?}"
|
||||
);
|
||||
|
||||
let counter_key = plain_keys
|
||||
.iter()
|
||||
.find(|key| key.starts_with(&format!("{HTTP_COUNTER}{{")))
|
||||
.expect("counter series must exist")
|
||||
.clone();
|
||||
let duration_key = plain_keys
|
||||
.iter()
|
||||
.find(|key| key.starts_with(&format!("{HTTP_DURATION}{{")))
|
||||
.expect("duration series must exist")
|
||||
.clone();
|
||||
|
||||
// Обе записи попадают в **тот же** агрегат: каждая наблюдается ровно один раз.
|
||||
for (label, snapshot) in [("without", &without_exemplar), ("with", &with_exemplar)] {
|
||||
assert_eq!(
|
||||
series_value(snapshot, &counter_key).as_deref(),
|
||||
Some("Counter(1)"),
|
||||
"[{label}] counter обязан получить ровно этот запрос, observed {:?}",
|
||||
series_value(snapshot, &counter_key)
|
||||
);
|
||||
assert_eq!(
|
||||
histogram_values(snapshot, &duration_key).len(),
|
||||
1,
|
||||
"[{label}] duration обязан получить ровно это наблюдение"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
histogram_values(&without_exemplar, &duration_key),
|
||||
vec![0.004]
|
||||
);
|
||||
assert_eq!(histogram_values(&with_exemplar, &duration_key), vec![0.005]);
|
||||
|
||||
// Приватный exemplar-store: ровно одно наблюдение для этого keyset, с тем же trace_id.
|
||||
let stored = observations(HTTP_DURATION, template, "GET");
|
||||
assert_eq!(
|
||||
stored.len(),
|
||||
1,
|
||||
"exemplar store обязан хранить latest-per-key, observed {stored:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
stored[0].trace_id,
|
||||
trace("0123456789abcdef0123456789abcdef")
|
||||
);
|
||||
assert_eq!(
|
||||
stored[0].bucket_upper_bound,
|
||||
Some(0.005),
|
||||
"4-5 ms обязаны попасть в первый объявленный bucket"
|
||||
);
|
||||
|
||||
// trace_id никогда не становится обычной меткой агрегата.
|
||||
for key in exemplar_keys {
|
||||
assert!(
|
||||
!key.contains("trace_id"),
|
||||
"trace_id не может быть обычной меткой: {key}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-X2 — latest-per-(family,labelset,bucket) стабилен (overwrite, не накопление).
|
||||
#[test]
|
||||
fn latest_overwrite_is_stable() {
|
||||
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
|
||||
.expect("isolated metrics binding for the exemplar capacity fixture");
|
||||
let route = HttpRoute::from_matched_path("/ready");
|
||||
assert_eq!(
|
||||
route.as_str(),
|
||||
"/ready",
|
||||
"оракул требует известный template `/ready`"
|
||||
);
|
||||
|
||||
// Изолированный keyset внутри процесс-глобального store.
|
||||
assert!(
|
||||
observations(HTTP_DURATION, "/ready", "GET").is_empty(),
|
||||
"keyset `/ready`+GET обязан быть чистым до записи"
|
||||
);
|
||||
let first = trace("00000000000000000000000000000001");
|
||||
let second = trace("00000000000000000000000000000002");
|
||||
|
||||
record_http_request_with_exemplar(
|
||||
route,
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_micros(1_000),
|
||||
Some(first),
|
||||
);
|
||||
let after_first = observations(HTTP_DURATION, "/ready", "GET");
|
||||
assert_eq!(
|
||||
after_first.len(),
|
||||
1,
|
||||
"первая запись создаёт одно наблюдение"
|
||||
);
|
||||
assert_eq!(after_first[0].trace_id, first);
|
||||
assert!((after_first[0].value - 0.001).abs() < 1e-9);
|
||||
assert_eq!(after_first[0].bucket_upper_bound, Some(0.005));
|
||||
|
||||
// Тот же (family, labelset, bucket): 2 ms также попадают в bucket le=0.005.
|
||||
record_http_request_with_exemplar(
|
||||
route,
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_micros(2_000),
|
||||
Some(second),
|
||||
);
|
||||
let after_second = observations(HTTP_DURATION, "/ready", "GET");
|
||||
assert_eq!(
|
||||
after_second.len(),
|
||||
1,
|
||||
"повторная запись того же ключа обязана обновлять latest, а не накапливать: {after_second:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
after_second[0].trace_id, second,
|
||||
"latest обязан нести trace_id последней записи"
|
||||
);
|
||||
assert!(
|
||||
(after_second[0].value - 0.002).abs() < 1e-9,
|
||||
"latest обязан нести значение последней записи, observed {}",
|
||||
after_second[0].value
|
||||
);
|
||||
assert_eq!(
|
||||
after_second[0].bucket_upper_bound,
|
||||
Some(0.005),
|
||||
"оба значения обязаны делить bucket le=0.005"
|
||||
);
|
||||
|
||||
// Новый bucket того же keyset — отдельное наблюдение (ключ включает bucket).
|
||||
record_http_request_with_exemplar(
|
||||
route,
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_millis(20),
|
||||
Some(second),
|
||||
);
|
||||
let after_third_bucket = observations(HTTP_DURATION, "/ready", "GET");
|
||||
assert_eq!(
|
||||
after_third_bucket.len(),
|
||||
2,
|
||||
"другой bucket — отдельный latest-ключ: {after_third_bucket:#?}"
|
||||
);
|
||||
assert!(after_third_bucket.iter().any(|observation| {
|
||||
observation.bucket_upper_bound == Some(0.025) && (observation.value - 0.020).abs() < 1e-9
|
||||
}));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Фаза B — public facade enforcement и per-service capacity.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// TD-X3b — public facade: достижимое множество нормализованных ключей равно
|
||||
/// объявленной проекции сервиса и никогда не превышает её (для counter/histogram
|
||||
/// это в точности `71x10x6` и `71x10`), а чужой route не появляется вовсе.
|
||||
#[test]
|
||||
fn public_facade_projection_enforcement() {
|
||||
crank_metrics::bind_metric_service(MetricService::AdminApi)
|
||||
.expect("admin metrics binding for the facade sweep");
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
|
||||
let admin_routes = crank_metrics::ADMIN_HTTP_ROUTE_DOMAIN;
|
||||
let methods = HttpMethod::VALUES;
|
||||
let statuses = HttpStatusClass::VALUES;
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
// Чужой (MCP-only) route: обязан схлопнуться в unmatched, а не создать ключ.
|
||||
for method in methods {
|
||||
record_http_request(
|
||||
HttpRoute::from_matched_path("/v1/{workspace_slug}/{agent_slug}"),
|
||||
HttpMethod::classify(method),
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_millis(1),
|
||||
);
|
||||
}
|
||||
for route in admin_routes {
|
||||
for method in methods {
|
||||
for status in statuses {
|
||||
record_http_request(
|
||||
HttpRoute::from_matched_path(route),
|
||||
HttpMethod::classify(method),
|
||||
HttpStatusClass::from_status(match *status {
|
||||
"1xx" => 101,
|
||||
"2xx" => 200,
|
||||
"3xx" => 302,
|
||||
"4xx" => 404,
|
||||
"5xx" => 500,
|
||||
_ => 0,
|
||||
}),
|
||||
Duration::from_millis(1),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let samples = snapshotter.snapshot().into_vec();
|
||||
let counters = samples
|
||||
.iter()
|
||||
.filter(|(key, _, _, _)| key.key().name() == HTTP_COUNTER)
|
||||
.count();
|
||||
let durations = samples
|
||||
.iter()
|
||||
.filter(|(key, _, _, _)| key.key().name() == HTTP_DURATION)
|
||||
.count();
|
||||
assert_eq!(
|
||||
counters,
|
||||
admin_routes.len() * methods.len() * statuses.len(),
|
||||
"facade обязан покрыть ровно объявленную counter-проекцию admin"
|
||||
);
|
||||
assert_eq!(
|
||||
durations,
|
||||
admin_routes.len() * methods.len(),
|
||||
"facade обязан покрыть ровно объявленную histogram-проекцию admin"
|
||||
);
|
||||
for (key, _, _, _) in &samples {
|
||||
for label in key.key().labels() {
|
||||
assert!(
|
||||
!label.value().contains("workspace_slug"),
|
||||
"чужой route не может стать label-значением: {label:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
samples.iter().any(|(key, _, _, _)| {
|
||||
key.key().name() == HTTP_COUNTER
|
||||
&& key
|
||||
.key()
|
||||
.labels()
|
||||
.any(|label| label.key() == "route" && label.value() == "unmatched")
|
||||
}),
|
||||
"чужой route обязан остаться наблюдаемым как unmatched"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-X4 — per-service capacity edges никогда не превышают hard cap.
|
||||
#[test]
|
||||
fn capacity_edges_do_not_exceed_hard_cap() {
|
||||
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
||||
let capacity = max_exemplar_slots(service);
|
||||
assert!(
|
||||
capacity <= MAX_EXEMPLAR_SLOTS_PER_PROCESS,
|
||||
"{:?} capacity {capacity} превышает hard cap",
|
||||
service
|
||||
);
|
||||
assert!(crank_metrics::validate_exemplar_budget(capacity).is_ok());
|
||||
assert!(
|
||||
capacity == MAX_EXEMPLAR_SLOTS_PER_PROCESS
|
||||
|| crank_metrics::validate_exemplar_budget(capacity + 1).is_ok(),
|
||||
"{:?} capacity {capacity} ниже hard cap, но capacity+1 отвергнут",
|
||||
service
|
||||
);
|
||||
assert!(
|
||||
crank_metrics::validate_exemplar_budget(MAX_EXEMPLAR_SLOTS_PER_PROCESS).is_ok(),
|
||||
"hard cap обязан быть разрешён"
|
||||
);
|
||||
assert!(
|
||||
crank_metrics::validate_exemplar_budget(MAX_EXEMPLAR_SLOTS_PER_PROCESS + 1).is_err(),
|
||||
"cap+1 обязан быть отвергнут"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-X6 — union capacity (14658) никогда не используется как лимит процесса.
|
||||
#[test]
|
||||
fn union_capacity_is_never_used_as_process_limit() {
|
||||
let admin = max_exemplar_slots(MetricService::AdminApi);
|
||||
let mcp = max_exemplar_slots(MetricService::McpServer);
|
||||
assert_eq!(admin, 12_348);
|
||||
assert_eq!(mcp, 2_310);
|
||||
assert_ne!(admin, 14_658, "union-capacity не может быть лимитом admin");
|
||||
assert_ne!(mcp, 14_658, "union-capacity не может быть лимитом mcp");
|
||||
assert_eq!(
|
||||
admin, MAX_EXEMPLAR_SLOTS_PER_PROCESS,
|
||||
"владелец утвердил hard cap ровно по фактическому admin budget (12348): admin обязан сохранить все свои slots"
|
||||
);
|
||||
assert_eq!(
|
||||
admin + mcp,
|
||||
14_658,
|
||||
"два процесса вместе имеют отдельные capacities; union не является лимитом процесса"
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,8 @@ fn trace_id_is_validated_and_never_becomes_an_ordinary_label() {
|
||||
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
|
||||
.expect("isolated metrics binding for the exemplar fixture");
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
record_http_request_with_exemplar(
|
||||
HttpRoute::from_matched_path("/health"),
|
||||
|
||||
@@ -80,6 +80,8 @@ struct ProfileSample {
|
||||
|
||||
#[test]
|
||||
fn reproducible_foundation_profile_stays_inside_latency_and_cpu_proxy_budgets() {
|
||||
crank_metrics::bind_metric_service(crank_metrics::MetricService::McpServer)
|
||||
.expect("isolated metrics binding for the overhead profile");
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
let mut baseline = Vec::with_capacity(SAMPLES);
|
||||
|
||||
@@ -10,12 +10,14 @@ use crank_metrics::{
|
||||
|
||||
#[test]
|
||||
fn schema_v1_is_complete_deterministic_and_inside_the_frozen_budget() {
|
||||
assert_eq!(METRIC_SCHEMA_VERSION, 1);
|
||||
assert_eq!(METRIC_SCHEMA_VERSION, 2);
|
||||
assert_eq!(metric_schema().len(), 23);
|
||||
|
||||
let budget = schema_budget().expect("canonical schema must be valid");
|
||||
assert!(budget.logical_series <= MAX_LOGICAL_SERIES_PER_PROCESS);
|
||||
assert!(budget.rendered_series <= MAX_RENDERED_SERIES_PER_PROCESS);
|
||||
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
||||
let budget = schema_budget(service).expect("canonical schema must be valid");
|
||||
assert!(budget.logical_series <= MAX_LOGICAL_SERIES_PER_PROCESS);
|
||||
assert!(budget.rendered_series <= MAX_RENDERED_SERIES_PER_PROCESS);
|
||||
}
|
||||
|
||||
for definition in metric_schema() {
|
||||
assert!(!definition.description.trim().is_empty());
|
||||
@@ -46,16 +48,25 @@ fn schema_v1_is_complete_deterministic_and_inside_the_frozen_budget() {
|
||||
|
||||
#[test]
|
||||
fn frozen_budget_edges_are_exact() {
|
||||
assert!(validate_budget(5_562, 17_637).is_ok());
|
||||
assert!(validate_budget(5_563, 17_638).is_ok());
|
||||
assert!(validate_budget(5_564, 16_000).is_err());
|
||||
assert!(validate_budget(5_200, 17_639).is_err());
|
||||
assert_eq!(crank_metrics::max_exemplar_slots(), 11_270);
|
||||
assert!(validate_budget(6_284, 19_514).is_ok());
|
||||
assert!(validate_budget(6_285, 19_515).is_ok());
|
||||
assert!(validate_budget(6_286, 16_000).is_err());
|
||||
assert!(validate_budget(6_000, 19_516).is_err());
|
||||
assert_eq!(
|
||||
crank_metrics::max_exemplar_slots(MetricService::AdminApi),
|
||||
12_348
|
||||
);
|
||||
assert_eq!(
|
||||
crank_metrics::max_exemplar_slots(MetricService::McpServer),
|
||||
2_310
|
||||
);
|
||||
assert!(crank_metrics::validate_exemplar_budget(12_348).is_ok());
|
||||
assert!(crank_metrics::validate_exemplar_budget(12_349).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_registered_route_round_trips_without_dynamic_segments() {
|
||||
assert_eq!(HTTP_ROUTE_DOMAIN.len(), 72);
|
||||
assert_eq!(HTTP_ROUTE_DOMAIN.len(), 91);
|
||||
for route in HTTP_ROUTE_DOMAIN {
|
||||
assert_eq!(HttpRoute::from_matched_path(route).as_str(), *route);
|
||||
assert!(!route.contains("trace_id"));
|
||||
@@ -66,10 +77,17 @@ fn every_registered_route_round_trips_without_dynamic_segments() {
|
||||
#[test]
|
||||
fn canonical_schema_validation_reports_its_category() {
|
||||
assert_eq!(
|
||||
schema_budget(),
|
||||
schema_budget(MetricService::AdminApi),
|
||||
Ok(crank_metrics::SchemaBudget {
|
||||
logical_series: 5_563,
|
||||
rendered_series: 17_638
|
||||
logical_series: 6_285,
|
||||
rendered_series: 19_515
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
schema_budget(MetricService::McpServer),
|
||||
Ok(crank_metrics::SchemaBudget {
|
||||
logical_series: 1_083,
|
||||
rendered_series: 3_558
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -195,3 +213,419 @@ fn route_literals(source: &str) -> Vec<String> {
|
||||
}
|
||||
routes
|
||||
}
|
||||
|
||||
/// TD-C5: замороженный v1-снимок `docs/schemas/metrics-registry-v1.json` остаётся
|
||||
/// byte-for-byte compatibility input'ом, а не пере-генерируется под новый контракт.
|
||||
///
|
||||
/// Оракул — sha256 + точная длина самих байтов файла. sha256 реализован здесь
|
||||
/// локально (без новой dependency), поэтому первым шагом проверяются контрольные
|
||||
/// векторы FIPS 180-4: без них byte-oracle был бы вакуумным.
|
||||
#[test]
|
||||
fn v1_snapshot_is_retained_byte_for_byte() {
|
||||
// Self-control локального хэшера (FIPS 180-4).
|
||||
assert_eq!(
|
||||
sha256_hex(b""),
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
);
|
||||
assert_eq!(
|
||||
sha256_hex(b"abc"),
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
||||
);
|
||||
assert_eq!(
|
||||
sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
|
||||
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
|
||||
);
|
||||
|
||||
const FROZEN_V1_SNAPSHOT: &str = include_str!("../../../docs/schemas/metrics-registry-v1.json");
|
||||
|
||||
assert_eq!(
|
||||
sha256_hex(FROZEN_V1_SNAPSHOT.as_bytes()),
|
||||
"b2ff5f31187559d1095df76fa685e4a9b68db8252523d3a844f5db5da3f48560",
|
||||
"замороженный v1-снимок обязан оставаться byte-for-byte неизменным"
|
||||
);
|
||||
assert_eq!(
|
||||
FROZEN_V1_SNAPSHOT.len(),
|
||||
18_512,
|
||||
"длина замороженного v1-снимка обязана оставаться неизменной"
|
||||
);
|
||||
assert!(
|
||||
FROZEN_V1_SNAPSHOT.contains("\"schema_version\": 1"),
|
||||
"v1-снимок обязан объявлять свою версию контракта"
|
||||
);
|
||||
assert!(
|
||||
!FROZEN_V1_SNAPSHOT.contains("\"schema_version\": 2"),
|
||||
"v1-снимок не пере-генерируется под v2-контракт"
|
||||
);
|
||||
}
|
||||
|
||||
fn sha256_hex(input: &[u8]) -> String {
|
||||
const K: [u32; 64] = [
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
|
||||
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
|
||||
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
|
||||
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
|
||||
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
|
||||
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
|
||||
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
|
||||
0xc67178f2,
|
||||
];
|
||||
|
||||
let mut state: [u32; 8] = [
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
|
||||
0x5be0cd19,
|
||||
];
|
||||
let bit_length = (input.len() as u64).wrapping_mul(8);
|
||||
let mut message = input.to_vec();
|
||||
message.push(0x80);
|
||||
while message.len() % 64 != 56 {
|
||||
message.push(0);
|
||||
}
|
||||
message.extend_from_slice(&bit_length.to_be_bytes());
|
||||
|
||||
for block in message.chunks_exact(64) {
|
||||
let mut schedule = [0_u32; 64];
|
||||
for (index, chunk) in block.chunks_exact(4).enumerate() {
|
||||
schedule[index] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
|
||||
}
|
||||
for index in 16..64 {
|
||||
let s0 = schedule[index - 15].rotate_right(7)
|
||||
^ schedule[index - 15].rotate_right(18)
|
||||
^ (schedule[index - 15] >> 3);
|
||||
let s1 = schedule[index - 2].rotate_right(17)
|
||||
^ schedule[index - 2].rotate_right(19)
|
||||
^ (schedule[index - 2] >> 10);
|
||||
schedule[index] = schedule[index - 16]
|
||||
.wrapping_add(s0)
|
||||
.wrapping_add(schedule[index - 7])
|
||||
.wrapping_add(s1);
|
||||
}
|
||||
|
||||
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = state;
|
||||
for index in 0..64 {
|
||||
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
|
||||
let choice = (e & f) ^ ((!e) & g);
|
||||
let temp1 = h
|
||||
.wrapping_add(s1)
|
||||
.wrapping_add(choice)
|
||||
.wrapping_add(K[index])
|
||||
.wrapping_add(schedule[index]);
|
||||
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
|
||||
let majority = (a & b) ^ (a & c) ^ (b & c);
|
||||
let temp2 = s0.wrapping_add(majority);
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d.wrapping_add(temp1);
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = temp1.wrapping_add(temp2);
|
||||
}
|
||||
for (slot, value) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
|
||||
*slot = slot.wrapping_add(value);
|
||||
}
|
||||
}
|
||||
|
||||
state.iter().map(|word| format!("{word:08x}")).collect()
|
||||
}
|
||||
|
||||
/// F7 (CONTRACT §6) — v1↔v2 metric-by-metric compatibility на реальных байтах
|
||||
/// обоих замороженных документов: kind/unit/help/processes/порядок labels/class/
|
||||
/// non-route домены/buckets обязаны совпадать, а v1 route-домен — быть
|
||||
/// подмножеством v2 union (`domain_ref: http_routes`). Парсер минимальный:
|
||||
/// никакой новой dependency, оба документа machine-generated.
|
||||
#[test]
|
||||
fn v1_and_v2_registries_are_metric_by_metric_compatible() {
|
||||
const V1: &str = include_str!("../../../docs/schemas/metrics-registry-v1.json");
|
||||
const V2: &str = include_str!("../../../docs/schemas/metrics-registry-v2.json");
|
||||
let v1 = metric_objects(V1);
|
||||
let v2 = metric_objects(V2);
|
||||
assert_eq!(v1.len(), 23);
|
||||
assert_eq!(
|
||||
v1.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(),
|
||||
v2.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(),
|
||||
"v2 обязан сохранить тот же набор и порядок family"
|
||||
);
|
||||
|
||||
for ((name, v1_object), (_, v2_object)) in v1.iter().zip(v2.iter()) {
|
||||
for field in ["kind", "unit", "help", "processes", "buckets_seconds"] {
|
||||
assert_eq!(
|
||||
json_field(v1_object, field),
|
||||
json_field(v2_object, field),
|
||||
"{name}: поле {field} обязано быть совместимым между v1 и v2"
|
||||
);
|
||||
}
|
||||
let v1_labels = label_entries(v1_object);
|
||||
let v2_labels = label_entries(v2_object);
|
||||
assert_eq!(
|
||||
v1_labels
|
||||
.iter()
|
||||
.map(|label| label.name.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
v2_labels
|
||||
.iter()
|
||||
.map(|label| label.name.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
"{name}: порядок labels обязан совпадать"
|
||||
);
|
||||
for (v1_label, v2_label) in v1_labels.iter().zip(v2_labels.iter()) {
|
||||
assert_eq!(v1_label.class, v2_label.class, "{name}/{}", v1_label.name);
|
||||
if v1_label.name == "route" {
|
||||
assert_eq!(v1_label.domain_ref, None);
|
||||
assert_eq!(
|
||||
v2_label.domain_ref.as_deref(),
|
||||
Some("http_routes"),
|
||||
"{name}: v2 обязан ссылаться на единый union маршрутов"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
assert_eq!(
|
||||
v1_label.domain, v2_label.domain,
|
||||
"{name}/{}: домен обязан совпадать между v1 и v2",
|
||||
v1_label.name
|
||||
);
|
||||
assert_eq!(v2_label.domain_ref, None);
|
||||
}
|
||||
}
|
||||
|
||||
let v1_routes = route_domain_v1(V1);
|
||||
let v2_routes = union_routes_v2(V2);
|
||||
assert_eq!(v1_routes.len(), 72, "замороженный v1 route-домен");
|
||||
assert_eq!(v2_routes.len(), 91);
|
||||
for route in &v1_routes {
|
||||
assert!(
|
||||
v2_routes.contains(route),
|
||||
"v1 route `{route}` отсутствует в v2 union"
|
||||
);
|
||||
}
|
||||
let added = v2_routes
|
||||
.iter()
|
||||
.filter(|route| !v1_routes.contains(*route))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
added.len(),
|
||||
19,
|
||||
"v2 обязан добавить тринадцать Resource и шесть Prompt шаблонов"
|
||||
);
|
||||
assert_eq!(
|
||||
added
|
||||
.iter()
|
||||
.filter(|route| route.contains("/resources"))
|
||||
.count(),
|
||||
13
|
||||
);
|
||||
assert_eq!(
|
||||
added
|
||||
.iter()
|
||||
.filter(|route| route.contains("/prompts"))
|
||||
.count(),
|
||||
6
|
||||
);
|
||||
}
|
||||
|
||||
/// F7/R2 — контроль самого compatibility helper'а: пробелы вне строк
|
||||
/// незначимы, изменение HELP внутри строки обязано обнаруживаться, а значимый
|
||||
/// пробел внутри строки — сохраняться.
|
||||
#[test]
|
||||
fn help_compatibility_helper_preserves_string_content() {
|
||||
let compact = "{\"help\":\"Total HTTP requests.\",\"unit\":\"1\"}";
|
||||
let pretty = "{\n \"help\": \"Total HTTP requests.\",\n \"unit\": \"1\"\n}";
|
||||
assert_eq!(
|
||||
compact_json(pretty),
|
||||
compact,
|
||||
"format-only пробелы вне строк обязаны игнорироваться"
|
||||
);
|
||||
assert_eq!(
|
||||
json_field(&compact_json(pretty), "help"),
|
||||
json_field(&compact_json(compact), "help")
|
||||
);
|
||||
assert!(
|
||||
compact_json(compact).contains("\"Total HTTP requests.\""),
|
||||
"значимый пробел HELP обязан сохраняться в компакте: {}",
|
||||
compact_json(compact)
|
||||
);
|
||||
|
||||
let changed_help = "{\"help\":\"TotalHTTP requests.\",\"unit\":\"1\"}";
|
||||
assert_ne!(
|
||||
json_field(&compact_json(compact), "help"),
|
||||
json_field(&compact_json(changed_help), "help"),
|
||||
"изменение HELP внутри строки обязано быть обнаружено"
|
||||
);
|
||||
let reflowed_help = "{\"help\":\"Total HTTP requests.\",\"unit\":\"1\"}";
|
||||
assert_ne!(
|
||||
json_field(&compact_json(compact), "help"),
|
||||
json_field(&compact_json(reflowed_help), "help"),
|
||||
"внутренние пробелы HELP значимы и обязаны различаться"
|
||||
);
|
||||
}
|
||||
|
||||
struct RegistryLabel {
|
||||
name: String,
|
||||
class: String,
|
||||
domain: Vec<String>,
|
||||
domain_ref: Option<String>,
|
||||
}
|
||||
|
||||
/// Компактизация JSON: пробелы удаляются только ВНЕ строк. Содержимое
|
||||
/// quoted/escaped string сохраняется байт-в-байт, иначе значимые пробелы HELP
|
||||
/// (`"Total HTTP requests."` против `"TotalHTTP requests."`) стали бы
|
||||
/// неразличимыми и per-metric oracle пропустил бы drift (F7 / R2).
|
||||
fn compact_json(text: &str) -> String {
|
||||
let mut compact = String::with_capacity(text.len());
|
||||
let mut in_string = false;
|
||||
let mut escaped = false;
|
||||
for ch in text.chars() {
|
||||
if in_string {
|
||||
compact.push(ch);
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if ch == '\\' {
|
||||
escaped = true;
|
||||
} else if ch == '"' {
|
||||
in_string = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if ch == '"' {
|
||||
in_string = true;
|
||||
compact.push(ch);
|
||||
} else if !ch.is_whitespace() {
|
||||
compact.push(ch);
|
||||
}
|
||||
}
|
||||
compact
|
||||
}
|
||||
|
||||
/// `(name, compact object)` для каждой family из секции `"metrics":[`.
|
||||
/// Секция ограничивается парным `]`, поэтому `budgets`/`http_routes` в неё не
|
||||
/// попадают, а top-level объекты выделяются балансировкой скобок.
|
||||
fn metric_objects(document: &str) -> Vec<(String, String)> {
|
||||
let compact = compact_json(document);
|
||||
let marker = "\"metrics\":[";
|
||||
let metrics_at = compact.find(marker).expect("metrics section");
|
||||
let array_start = metrics_at + marker.len() - 1;
|
||||
let array_end = array_start + balanced_end(&compact[array_start..], b'[', b']');
|
||||
let section = &compact[array_start + 1..array_end - 1];
|
||||
let mut objects = Vec::new();
|
||||
let mut cursor = 0_usize;
|
||||
while let Some(offset) = section[cursor..].find('{') {
|
||||
let at = cursor + offset;
|
||||
let end = at + balanced_end(§ion[at..], b'{', b'}');
|
||||
let object = §ion[at..end];
|
||||
let name = unquote(&json_field(object, "name"));
|
||||
objects.push((name, object.to_owned()));
|
||||
cursor = end;
|
||||
}
|
||||
objects
|
||||
}
|
||||
|
||||
/// Значение поля как compact JSON text: строка, массив, объект или scalar.
|
||||
fn json_field(object: &str, key: &str) -> String {
|
||||
let needle = format!("\"{key}\":");
|
||||
let at = object
|
||||
.find(&needle)
|
||||
.unwrap_or_else(|| panic!("поле {key} отсутствует"));
|
||||
let value = &object[at + needle.len()..];
|
||||
match value.as_bytes().first() {
|
||||
Some(b'"') => {
|
||||
let end = value[1..].find('"').expect("string terminator");
|
||||
value[..end + 2].to_owned()
|
||||
}
|
||||
Some(b'[') => value[..balanced_end(value, b'[', b']')].to_owned(),
|
||||
Some(b'{') => value[..balanced_end(value, b'{', b'}')].to_owned(),
|
||||
_ => value
|
||||
.find([',', '}'])
|
||||
.map_or_else(|| value.to_owned(), |end| value[..end].to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
fn balanced_end(value: &str, open: u8, close: u8) -> usize {
|
||||
let mut depth = 0_usize;
|
||||
for (index, byte) in value.bytes().enumerate() {
|
||||
if byte == open {
|
||||
depth += 1;
|
||||
} else if byte == close {
|
||||
depth = depth.saturating_sub(1);
|
||||
if depth == 0 {
|
||||
return index + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("unbalanced JSON value");
|
||||
}
|
||||
|
||||
fn unquote(value: &str) -> String {
|
||||
value.trim_matches('"').to_owned()
|
||||
}
|
||||
|
||||
fn string_array(value: &str) -> Vec<String> {
|
||||
let inner = &value[1..value.len() - 1];
|
||||
let mut values = Vec::new();
|
||||
let mut cursor = 0_usize;
|
||||
while let Some(at) = inner[cursor..].find('"') {
|
||||
let at = cursor + at;
|
||||
let after = &inner[at + 1..];
|
||||
let end = after.find('"').expect("string terminator");
|
||||
values.push(after[..end].to_owned());
|
||||
cursor = at + 1 + end + 1;
|
||||
}
|
||||
values
|
||||
}
|
||||
|
||||
fn label_entries(object: &str) -> Vec<RegistryLabel> {
|
||||
let array = json_field(object, "labels");
|
||||
let inner = array[1..array.len() - 1].to_owned();
|
||||
let mut labels = Vec::new();
|
||||
let mut cursor = 0_usize;
|
||||
while let Some(at) = inner[cursor..].find("{\"name\":") {
|
||||
let at = cursor + at;
|
||||
let end = at + balanced_end(&inner[at..], b'{', b'}');
|
||||
let entry = &inner[at..end];
|
||||
labels.push(RegistryLabel {
|
||||
name: unquote(&json_field(entry, "name")),
|
||||
class: unquote(&json_field(entry, "class")),
|
||||
domain: if entry.contains("\"domain\":[") {
|
||||
string_array(&json_field(entry, "domain"))
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
domain_ref: entry
|
||||
.contains("\"domain_ref\":")
|
||||
.then(|| unquote(&json_field(entry, "domain_ref"))),
|
||||
});
|
||||
cursor = end;
|
||||
}
|
||||
labels
|
||||
}
|
||||
|
||||
fn route_domain_v1(document: &str) -> Vec<String> {
|
||||
let objects = metric_objects(document);
|
||||
let (_, object) = objects
|
||||
.iter()
|
||||
.find(|(name, _)| name == "crank_http_requests_total")
|
||||
.expect("v1 HTTP counter");
|
||||
label_entries(object)
|
||||
.into_iter()
|
||||
.find(|label| label.name == "route")
|
||||
.expect("v1 route label")
|
||||
.domain
|
||||
}
|
||||
|
||||
fn union_routes_v2(document: &str) -> Vec<String> {
|
||||
let compact = compact_json(document);
|
||||
let section = &compact[compact
|
||||
.find("\"http_routes\":[")
|
||||
.expect("http_routes section")..];
|
||||
let needle = "\"route\":\"";
|
||||
let mut routes = Vec::new();
|
||||
let mut cursor = 0_usize;
|
||||
while let Some(at) = section[cursor..].find(needle) {
|
||||
let at = cursor + at + needle.len();
|
||||
let end = section[at..].find('"').expect("route terminator");
|
||||
routes.push(section[at..at + end].to_owned());
|
||||
cursor = at + end + 1;
|
||||
}
|
||||
routes
|
||||
}
|
||||
@@ -0,0 +1,757 @@
|
||||
//! Story 3.6 · AT-3.6-08 · phase A (ATDD, test-only) — closed route/method identity.
|
||||
//!
|
||||
//! Этот таргет на фазе A содержит **только** A-селекторы: они используют
|
||||
//! существующее API `crank-metrics` и не требуют правок `src/**`.
|
||||
//!
|
||||
//! * `TD-H7a` — замкнутый классификатор HTTP-метода: известные verb'ы сохраняют
|
||||
//! собственное значение enum, а `OTHER` присваивается только действительно
|
||||
//! неизвестному token'у. «Известный-но-неподдерживаемый» verb (`OPTIONS`,
|
||||
//! `HEAD`, `CONNECT`, `TRACE`) — это **не** `OTHER`.
|
||||
//! * `TD-R6` — замкнутый классификатор route: каждый объявленный template
|
||||
//! round-trip'ится без изменений, а сырой URI/query/concrete id, не совпавший
|
||||
//! ни с одним literal, остаётся `unmatched`. Этот direct-classifier-оракул
|
||||
//! принадлежит **только** unit-проверке (middleware передаёт `MatchedPath`, а
|
||||
//! не raw URI: `crates/crank-observability/src/instrumentation.rs`).
|
||||
//!
|
||||
//! B-селекторы v2 (typed ownership union, per-process budget, projections)
|
||||
//! добавляются в этот же таргет отдельной build-карточкой: на фазе A их API
|
||||
//! отсутствует, и они не могут быть скомпилированы.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crank_metrics::{
|
||||
ADMIN_HTTP_ROUTE_DOMAIN, HTTP_ROUTE_DOMAIN, HTTP_ROUTES, HttpMethod, HttpRoute,
|
||||
MAX_EXEMPLAR_SLOTS_PER_PROCESS, MAX_LOGICAL_SERIES_PER_PROCESS,
|
||||
MAX_RENDERED_SERIES_PER_PROCESS, MCP_HTTP_ROUTE_DOMAIN, MetricDefinition, MetricKind,
|
||||
MetricProcess, MetricService, MetricUnit, max_exemplar_slots, metric_schema,
|
||||
metric_schema_for_service, normalize_http_route, render_metric_schema_json, schema_budget,
|
||||
service_projection, validate_budget, validate_exemplar_budget, validate_http_routes,
|
||||
validate_schema,
|
||||
};
|
||||
|
||||
/// TD-H7a — closed method classification (чистая функция, без HTTP).
|
||||
///
|
||||
/// Оракул: `HttpMethod::classify` никогда не подменяет известный verb на `OTHER`
|
||||
/// и не пропускает действительно неизвестный token в замкнутый домен.
|
||||
#[test]
|
||||
fn closed_methods_keep_their_value_and_only_unknown_is_other() {
|
||||
// Замкнутый домен метода: ровно 10 значений, без дублей.
|
||||
assert_eq!(
|
||||
HttpMethod::ALL.len(),
|
||||
HttpMethod::VALUES.len(),
|
||||
"ALL и VALUES обязаны описывать один и тот же замкнутый домен"
|
||||
);
|
||||
assert_eq!(
|
||||
HttpMethod::ALL.len(),
|
||||
10,
|
||||
"домен метода закрыт 10 значениями (GET/POST/PUT/PATCH/DELETE/OPTIONS/HEAD/CONNECT/TRACE/OTHER)"
|
||||
);
|
||||
for method in HttpMethod::ALL {
|
||||
assert_eq!(
|
||||
method.as_str(),
|
||||
HttpMethod::VALUES[HttpMethod::ALL
|
||||
.iter()
|
||||
.position(|candidate| candidate == method)
|
||||
.expect("ALL и VALUES обязаны быть согласованы по индексу")],
|
||||
"ALL и VALUES обязаны быть согласованы"
|
||||
);
|
||||
}
|
||||
let closed_values = HttpMethod::VALUES.iter().copied().collect::<BTreeSet<_>>();
|
||||
assert_eq!(
|
||||
closed_values.len(),
|
||||
HttpMethod::VALUES.len(),
|
||||
"значения замкнутого домена метода обязаны быть уникальны"
|
||||
);
|
||||
assert_eq!(
|
||||
closed_values,
|
||||
BTreeSet::from([
|
||||
"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD", "CONNECT", "TRACE",
|
||||
"OTHER",
|
||||
]),
|
||||
"замкнутый домен метода объявлен ровно этими десятью значениями"
|
||||
);
|
||||
|
||||
// Round-trip: каждое значение домена классифицируется в само себя.
|
||||
for method in HttpMethod::ALL {
|
||||
assert_eq!(
|
||||
HttpMethod::classify(method.as_str()),
|
||||
*method,
|
||||
"closed value `{}` обязан классифицироваться в себя",
|
||||
method.as_str()
|
||||
);
|
||||
}
|
||||
|
||||
// Известный-но-неподдерживаемый verb сохраняет своё enum-значение и не является OTHER.
|
||||
for (token, expected) in [
|
||||
("OPTIONS", HttpMethod::Options),
|
||||
("HEAD", HttpMethod::Head),
|
||||
("CONNECT", HttpMethod::Connect),
|
||||
("TRACE", HttpMethod::Trace),
|
||||
("DELETE", HttpMethod::Delete),
|
||||
("PATCH", HttpMethod::Patch),
|
||||
] {
|
||||
assert_eq!(
|
||||
HttpMethod::classify(token),
|
||||
expected,
|
||||
"known verb `{token}` обязан сохранять своё значение, а не становиться OTHER"
|
||||
);
|
||||
assert_ne!(
|
||||
HttpMethod::classify(token),
|
||||
HttpMethod::Other,
|
||||
"known-but-unsupported verb `{token}` не может быть OTHER"
|
||||
);
|
||||
}
|
||||
|
||||
// OTHER — только для действительно неизвестного token'а.
|
||||
for unknown in [
|
||||
"FOO",
|
||||
"CUSTOM-x",
|
||||
"PROPFIND",
|
||||
"get",
|
||||
"Get",
|
||||
"",
|
||||
"GET ",
|
||||
"GET\t",
|
||||
"X-User-Controlled",
|
||||
] {
|
||||
assert_eq!(
|
||||
HttpMethod::classify(unknown),
|
||||
HttpMethod::Other,
|
||||
"неизвестный HTTP-token `{unknown}` обязан давать OTHER"
|
||||
);
|
||||
assert!(
|
||||
!HttpMethod::VALUES.contains(&unknown),
|
||||
"неизвестный token `{unknown}` не может попасть в замкнутый домен метода"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-R6 — closed route classifier + round-trip (чистая функция, без HTTP).
|
||||
#[test]
|
||||
fn http_route_classifier_is_closed_and_round_trips() {
|
||||
// Домен замкнут и не содержит дублей.
|
||||
let closed = HTTP_ROUTE_DOMAIN.iter().copied().collect::<BTreeSet<_>>();
|
||||
assert_eq!(
|
||||
closed.len(),
|
||||
HTTP_ROUTE_DOMAIN.len(),
|
||||
"HTTP_ROUTE_DOMAIN не может объявлять один template дважды"
|
||||
);
|
||||
assert!(
|
||||
HTTP_ROUTE_DOMAIN.contains(&"unmatched"),
|
||||
"домен обязан объявлять единственное не-route значение `unmatched`"
|
||||
);
|
||||
|
||||
// Каждый объявленный template (кроме самого `unmatched`) round-trip'ится без изменений.
|
||||
let mut templates = 0_usize;
|
||||
for template in HTTP_ROUTE_DOMAIN {
|
||||
if *template == "unmatched" {
|
||||
continue;
|
||||
}
|
||||
templates += 1;
|
||||
assert_eq!(
|
||||
HttpRoute::from_matched_path(template).as_str(),
|
||||
*template,
|
||||
"объявленный template `{template}` обязан round-trip'иться"
|
||||
);
|
||||
assert_eq!(
|
||||
HttpRoute::unmatched().as_str(),
|
||||
"unmatched",
|
||||
"константа unmatched обязана оставаться `unmatched`"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
templates > 0,
|
||||
"домен обязан объявлять хотя бы один реальный template"
|
||||
);
|
||||
|
||||
// Сырой URI/query/concrete id никогда не становится известным template:
|
||||
// direct-classifier-оракул, который middleware не использует (там MatchedPath).
|
||||
for raw in [
|
||||
"unmatched",
|
||||
"/unknown/raw/path",
|
||||
"/api/admin/workspaces/ws_customer/operations/op_123",
|
||||
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions/42",
|
||||
"/api/admin/workspaces/ws_customer/resources?page=2",
|
||||
"/api/admin/workspaces/ws_customer/resources/res_9f3a/preview?inline=1",
|
||||
"/api/admin/workspaces/ws_customer/resources/res_9f3a/publish",
|
||||
"/api/admin/workspaces/ws_customer/resources/res_9f3a/revoke",
|
||||
"/api/admin/workspaces/ws_customer/resources/res_9f3a/versions/3",
|
||||
"/api/admin/workspaces/ws_customer/resources/res_9f3a/versions/3/content",
|
||||
"/health?probe=1",
|
||||
"/api/admin/workspaces/ws_customer/does-not-exist",
|
||||
] {
|
||||
assert_eq!(
|
||||
HttpRoute::from_matched_path(raw).as_str(),
|
||||
"unmatched",
|
||||
"сырое значение `{raw}` не является объявленным template и обязано давать unmatched"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Фаза B — typed ownership union, per-process projections/bounds/budgets.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const RESOURCE_TEMPLATES: [&str; 13] = [
|
||||
"/api/admin/workspaces/{workspace_id}/resources",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/import",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/archive",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/content",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/export",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/preview",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/publish",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/revoke",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}/content",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}/export",
|
||||
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/test-runs",
|
||||
];
|
||||
|
||||
const PROMPT_TEMPLATES: [&str; 6] = [
|
||||
"/api/admin/workspaces/{workspace_id}/prompts",
|
||||
"/api/admin/workspaces/{workspace_id}/prompts/import",
|
||||
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}",
|
||||
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/export",
|
||||
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/preview",
|
||||
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/versions/{version}/export",
|
||||
];
|
||||
|
||||
fn route_literals(source: &str) -> Vec<String> {
|
||||
let mut routes = Vec::new();
|
||||
let mut remaining = source;
|
||||
while let Some(offset) = remaining.find(".route(") {
|
||||
remaining = &remaining[offset + ".route(".len()..];
|
||||
let Some(start) = remaining.find('"') else {
|
||||
break;
|
||||
};
|
||||
let after_start = &remaining[start + 1..];
|
||||
let Some(end) = after_start.find('"') else {
|
||||
break;
|
||||
};
|
||||
routes.push(after_start[..end].to_owned());
|
||||
remaining = &after_start[end + 1..];
|
||||
}
|
||||
routes
|
||||
}
|
||||
|
||||
/// Canonical admin router inventory (F1 fixture): `unmatched` + every literal
|
||||
/// canonicalised into its admin path family.
|
||||
fn admin_router_inventory() -> BTreeSet<String> {
|
||||
let source = include_str!("../../../apps/admin-api/src/app.rs");
|
||||
let auth = [
|
||||
"/bootstrap/status",
|
||||
"/bootstrap/complete",
|
||||
"/login",
|
||||
"/logout",
|
||||
"/session",
|
||||
"/session/csrf",
|
||||
"/profile",
|
||||
"/password",
|
||||
];
|
||||
let admin_root = ["/capabilities", "/workspaces", "/workspaces/{workspace_id}"];
|
||||
let mut actual = BTreeSet::from(["unmatched".to_owned()]);
|
||||
for route in route_literals(source) {
|
||||
let canonical = if matches!(route.as_str(), "/health" | "/ready") {
|
||||
route
|
||||
} else if auth.contains(&route.as_str()) {
|
||||
format!("/api/auth{route}")
|
||||
} else if admin_root.contains(&route.as_str()) {
|
||||
format!("/api/admin{route}")
|
||||
} else {
|
||||
format!("/api/admin/workspaces/{{workspace_id}}{route}")
|
||||
};
|
||||
actual.insert(canonical);
|
||||
}
|
||||
actual
|
||||
}
|
||||
|
||||
fn mcp_router_inventory() -> BTreeSet<String> {
|
||||
let source = include_str!("../../crank-community-mcp/src/app.rs");
|
||||
let mut actual = BTreeSet::from(["unmatched".to_owned()]);
|
||||
actual.extend(route_literals(source));
|
||||
actual
|
||||
}
|
||||
|
||||
fn domain_of(routes: &[&str]) -> BTreeSet<String> {
|
||||
routes.iter().map(|route| (*route).to_owned()).collect()
|
||||
}
|
||||
|
||||
/// TD-R1 — typed ownership union двусторонне равен реальному router inventory.
|
||||
#[test]
|
||||
fn ownership_union_is_exactly_the_router_inventory() {
|
||||
validate_http_routes(HTTP_ROUTES)
|
||||
.expect("the single ownership table must be structurally valid");
|
||||
let expected = domain_of(HTTP_ROUTE_DOMAIN);
|
||||
assert_eq!(
|
||||
expected.len(),
|
||||
91,
|
||||
"union обязан объявлять 91 идентичностей"
|
||||
);
|
||||
let mut actual = admin_router_inventory();
|
||||
actual.extend(mcp_router_inventory());
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"union и реальные routers обязаны совпасть"
|
||||
);
|
||||
assert_eq!(
|
||||
HTTP_ROUTES.len(),
|
||||
HTTP_ROUTE_DOMAIN.len(),
|
||||
"домен обязан выводиться из той же таблицы без второй истины"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-R2 — per-service projections равны соответствующим router files.
|
||||
#[test]
|
||||
fn service_projections_match_router_files() {
|
||||
assert_eq!(ADMIN_HTTP_ROUTE_DOMAIN.len(), 86, "admin-проекция = 86");
|
||||
assert_eq!(MCP_HTTP_ROUTE_DOMAIN.len(), 8, "mcp-проекция = 8");
|
||||
assert_eq!(
|
||||
domain_of(ADMIN_HTTP_ROUTE_DOMAIN),
|
||||
admin_router_inventory(),
|
||||
"admin-проекция обязана совпасть с apps/admin-api/src/app.rs"
|
||||
);
|
||||
assert_eq!(
|
||||
domain_of(MCP_HTTP_ROUTE_DOMAIN),
|
||||
mcp_router_inventory(),
|
||||
"mcp-проекция обязана совпасть с crates/crank-community-mcp/src/app.rs"
|
||||
);
|
||||
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
||||
let names = service_projection(service)
|
||||
.iter()
|
||||
.map(|definition| definition.name)
|
||||
.collect::<BTreeSet<_>>();
|
||||
assert!(
|
||||
names.contains("crank_http_requests_total"),
|
||||
"каждая проекция обязана объявлять HTTP counter"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-R3 — shared ровно три, prefix-ownership exact, никаких wildcard.
|
||||
#[test]
|
||||
fn shared_and_prefix_ownership_is_exact() {
|
||||
let shared = HTTP_ROUTES
|
||||
.iter()
|
||||
.filter(|row| row.processes.len() == 2)
|
||||
.map(|row| row.route)
|
||||
.collect::<BTreeSet<_>>();
|
||||
assert_eq!(
|
||||
shared,
|
||||
BTreeSet::from(["/health", "/ready", "unmatched"]),
|
||||
"policy owners совпадают ровно на трёх общих строках"
|
||||
);
|
||||
for row in HTTP_ROUTES {
|
||||
if row.route.starts_with("/api/auth/") || row.route.starts_with("/api/admin/") {
|
||||
assert_eq!(
|
||||
row.processes,
|
||||
&[MetricProcess::AdminApi],
|
||||
"{} обязана принадлежать только admin_api",
|
||||
row.route
|
||||
);
|
||||
}
|
||||
if row.route.starts_with("/v1/") {
|
||||
assert_eq!(
|
||||
row.processes,
|
||||
&[MetricProcess::McpServer],
|
||||
"{} обязана принадлежать только mcp_server",
|
||||
row.route
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
row.route == "unmatched" || row.route.starts_with('/'),
|
||||
"{} — не route template",
|
||||
row.route
|
||||
);
|
||||
assert!(
|
||||
!row.route.contains('*'),
|
||||
"{} не может использовать wildcard matching",
|
||||
row.route
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-R4 — тринадцать Resource-шаблонов: admin-owned добавления к v1-домену.
|
||||
#[test]
|
||||
fn resource_templates_are_admin_owned_additions() {
|
||||
const FROZEN_V1: &str = include_str!("../../../docs/schemas/metrics-registry-v1.json");
|
||||
for template in RESOURCE_TEMPLATES {
|
||||
assert!(
|
||||
HTTP_ROUTE_DOMAIN.contains(&template),
|
||||
"{template} обязан войти в union"
|
||||
);
|
||||
assert_eq!(
|
||||
crank_metrics::http_route_processes(template),
|
||||
Some(&[MetricProcess::AdminApi][..]),
|
||||
"{template} обязан принадлежать admin_api"
|
||||
);
|
||||
assert!(
|
||||
!FROZEN_V1.contains(template),
|
||||
"{template} не может быть частью замороженного v1-домена"
|
||||
);
|
||||
assert_eq!(
|
||||
HttpRoute::from_matched_path(template).as_str(),
|
||||
template,
|
||||
"{template} обязан round-trip'иться после добавления"
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_http_route(
|
||||
MetricService::AdminApi,
|
||||
HttpRoute::from_matched_path(template)
|
||||
)
|
||||
.as_str(),
|
||||
template,
|
||||
"{template} обязан оставаться собой в admin-метриках, а не unmatched"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
HTTP_ROUTE_DOMAIN.len() - RESOURCE_TEMPLATES.len(),
|
||||
78,
|
||||
"v1-домен + тринадцать Resource и шесть Prompt additions = union 91"
|
||||
);
|
||||
assert_eq!(HTTP_ROUTE_DOMAIN.len(), 91);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_templates_are_admin_owned_and_normalized() {
|
||||
for template in PROMPT_TEMPLATES {
|
||||
assert!(HTTP_ROUTE_DOMAIN.contains(&template));
|
||||
assert_eq!(
|
||||
crank_metrics::http_route_processes(template),
|
||||
Some(&[MetricProcess::AdminApi][..])
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_http_route(
|
||||
MetricService::AdminApi,
|
||||
HttpRoute::from_matched_path(template)
|
||||
)
|
||||
.as_str(),
|
||||
template
|
||||
);
|
||||
}
|
||||
assert_eq!(PROMPT_TEMPLATES.len(), 6);
|
||||
}
|
||||
|
||||
/// TD-R5 — таблица отвергает дубликаты, пустые и дублирующиеся owners.
|
||||
#[test]
|
||||
fn ownership_table_rejects_duplicates_and_empty_owners() {
|
||||
validate_http_routes(HTTP_ROUTES).expect("production table must validate");
|
||||
let duplicate = [
|
||||
HTTP_ROUTES[0],
|
||||
crank_metrics::HttpRouteDefinition {
|
||||
route: HTTP_ROUTES[0].route,
|
||||
processes: &[MetricProcess::McpServer],
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
validate_http_routes(&duplicate),
|
||||
Err(crank_metrics::SchemaError::DuplicateMetric)
|
||||
);
|
||||
let empty = [crank_metrics::HttpRouteDefinition {
|
||||
route: "/health",
|
||||
processes: &[],
|
||||
}];
|
||||
assert_eq!(
|
||||
validate_http_routes(&empty),
|
||||
Err(crank_metrics::SchemaError::InvalidMetric)
|
||||
);
|
||||
let duplicated_owner = [crank_metrics::HttpRouteDefinition {
|
||||
route: "/health",
|
||||
processes: &[MetricProcess::AdminApi, MetricProcess::AdminApi],
|
||||
}];
|
||||
assert_eq!(
|
||||
validate_http_routes(&duplicated_owner),
|
||||
Err(crank_metrics::SchemaError::InvalidMetric)
|
||||
);
|
||||
let without_unmatched = [crank_metrics::HttpRouteDefinition {
|
||||
route: "/health",
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
}];
|
||||
assert_eq!(
|
||||
validate_http_routes(&without_unmatched),
|
||||
Err(crank_metrics::SchemaError::InvalidDomain)
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-M1 — bounds каждой проекции равны своим формулам `L`/`R`/`E`.
|
||||
#[test]
|
||||
fn per_process_bounds_equal_their_formulas() {
|
||||
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
||||
for definition in service_projection(service) {
|
||||
let logical = definition
|
||||
.label_domains
|
||||
.iter()
|
||||
.map(|domain| domain.values.len())
|
||||
.product::<usize>()
|
||||
.max(1);
|
||||
let rendered = if definition.kind == MetricKind::Histogram {
|
||||
logical * (definition.buckets.len() + 3)
|
||||
} else {
|
||||
logical
|
||||
};
|
||||
let exemplars = if definition.kind == MetricKind::Histogram {
|
||||
logical * (definition.buckets.len() + 1)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
assert_eq!(
|
||||
definition.max_logical_series,
|
||||
logical,
|
||||
"{}/{} logical",
|
||||
definition.name,
|
||||
service.process().as_str()
|
||||
);
|
||||
assert_eq!(
|
||||
definition.max_rendered_series,
|
||||
rendered,
|
||||
"{}/{} rendered",
|
||||
definition.name,
|
||||
service.process().as_str()
|
||||
);
|
||||
assert_eq!(
|
||||
definition.max_exemplar_slots(),
|
||||
exemplars,
|
||||
"{}/{} exemplar slots",
|
||||
definition.name,
|
||||
service.process().as_str()
|
||||
);
|
||||
assert!(
|
||||
definition.label_domains.iter().all(|domain| {
|
||||
domain.name != "route" || {
|
||||
let allowed = match service {
|
||||
MetricService::AdminApi => ADMIN_HTTP_ROUTE_DOMAIN,
|
||||
MetricService::McpServer => MCP_HTTP_ROUTE_DOMAIN,
|
||||
};
|
||||
domain.values == allowed
|
||||
}
|
||||
}),
|
||||
"{}/{} обязана нести только свою route-проекцию",
|
||||
definition.name,
|
||||
service.process().as_str()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-M2 — root.budgets содержит ровно два per-process бюджета, union-бюджета нет.
|
||||
#[test]
|
||||
fn root_budgets_are_per_process_only() {
|
||||
let rendered = render_metric_schema_json().expect("v2 renders");
|
||||
assert_eq!(
|
||||
rendered.matches("\"budgets\":").count(),
|
||||
1,
|
||||
"root обязан объявлять ровно один ключ budgets"
|
||||
);
|
||||
assert!(rendered.ends_with(
|
||||
",\"budgets\":[{\"process\":\"admin_api\",\"families\":15,\"logical_series\":6285,\
|
||||
\"rendered_series\":19515,\"exemplar_slots\":12348},{\"process\":\"mcp_server\",\
|
||||
\"families\":23,\"logical_series\":1083,\"rendered_series\":3558,\"exemplar_slots\":2310}]}\n"
|
||||
));
|
||||
assert_eq!(
|
||||
schema_budget(MetricService::AdminApi),
|
||||
Ok(crank_metrics::SchemaBudget {
|
||||
logical_series: 6_285,
|
||||
rendered_series: 19_515
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
schema_budget(MetricService::McpServer),
|
||||
Ok(crank_metrics::SchemaBudget {
|
||||
logical_series: 1_083,
|
||||
rendered_series: 3_558
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-M3 — frozen caps и границы `validate_exemplar_budget` точны.
|
||||
#[test]
|
||||
fn frozen_caps_and_edges_are_exact() {
|
||||
assert_eq!(MAX_LOGICAL_SERIES_PER_PROCESS, 6_285);
|
||||
assert_eq!(MAX_RENDERED_SERIES_PER_PROCESS, 19_515);
|
||||
assert_eq!(MAX_EXEMPLAR_SLOTS_PER_PROCESS, 12_348);
|
||||
assert!(validate_budget(6_285, 19_515).is_ok());
|
||||
assert!(validate_budget(6_286, 19_515).is_err());
|
||||
assert!(validate_exemplar_budget(12_347).is_ok());
|
||||
assert!(validate_exemplar_budget(12_348).is_ok());
|
||||
assert!(validate_exemplar_budget(12_349).is_err());
|
||||
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
||||
let budget = schema_budget(service).expect("projection budget valid");
|
||||
assert!(budget.logical_series <= MAX_LOGICAL_SERIES_PER_PROCESS);
|
||||
assert!(budget.rendered_series <= MAX_RENDERED_SERIES_PER_PROCESS);
|
||||
validate_exemplar_budget(max_exemplar_slots(service))
|
||||
.expect("capacity inside the hard cap");
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-M4 — любая испорченная проекция отвергается валидатором.
|
||||
#[test]
|
||||
fn any_invalid_projection_fails_validation() {
|
||||
let base = *service_projection(MetricService::AdminApi)
|
||||
.iter()
|
||||
.find(|definition| definition.name == "crank_http_requests_total")
|
||||
.expect("http counter present in admin projection");
|
||||
|
||||
let wrong_ceiling = MetricDefinition {
|
||||
max_logical_series: base.max_logical_series + 1,
|
||||
..base
|
||||
};
|
||||
assert_eq!(
|
||||
validate_schema(&[wrong_ceiling]),
|
||||
Err(crank_metrics::SchemaError::InvalidCeiling)
|
||||
);
|
||||
|
||||
let wrong_domain = MetricDefinition {
|
||||
label_domains: Box::leak(
|
||||
base.label_domains
|
||||
.iter()
|
||||
.map(|domain| {
|
||||
if domain.name == "route" {
|
||||
crank_metrics::LabelDomain {
|
||||
values: &["/definitely-not-a-route"],
|
||||
..*domain
|
||||
}
|
||||
} else {
|
||||
*domain
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into_boxed_slice(),
|
||||
),
|
||||
..base
|
||||
};
|
||||
assert_eq!(
|
||||
validate_schema(&[wrong_domain]),
|
||||
Err(crank_metrics::SchemaError::InvalidCeiling)
|
||||
);
|
||||
|
||||
let mut mutated = service_projection(MetricService::AdminApi).to_vec();
|
||||
mutated[0].max_rendered_series = 0;
|
||||
assert!(
|
||||
validate_schema(&mutated).is_err(),
|
||||
"проекция с несогласованным ceiling обязана падать"
|
||||
);
|
||||
|
||||
// Каждый invalid case проверяется для **обоих** сервисов: даже если
|
||||
// запускается другой процесс, отказ обязан быть одинаковым.
|
||||
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
||||
validate_schema(service_projection(service)).expect("production projection valid");
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-M5 — checked-арифметика: реальное превышение per-process бюджета обязано
|
||||
/// отвергаться типизированным `BudgetExceeded`, насыщенные metadata — типизированным
|
||||
/// `InvalidCeiling`; ни один счётчик не принимается «почти верным».
|
||||
#[test]
|
||||
fn arithmetic_overflow_is_typed_and_not_saturated() {
|
||||
let saturated = MetricDefinition {
|
||||
name: "crank_test_total",
|
||||
kind: MetricKind::Counter,
|
||||
unit: MetricUnit::Count,
|
||||
labels: &[],
|
||||
label_domains: &[],
|
||||
buckets: &[],
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
max_logical_series: usize::MAX,
|
||||
max_rendered_series: usize::MAX,
|
||||
description: "saturated counter",
|
||||
};
|
||||
assert_eq!(
|
||||
validate_schema(&[saturated]),
|
||||
Err(crank_metrics::SchemaError::InvalidCeiling),
|
||||
"насыщенный ceiling обязан быть отвергнут, а не принят"
|
||||
);
|
||||
|
||||
// Настоящая арифметика: домен ровно на единицу больше frozen per-process
|
||||
// лимита. Metadata точные (не насыщенные), поэтому отказ обязан быть
|
||||
// типизированным BudgetExceeded, а не InvalidCeiling/срезом.
|
||||
let oversize = MAX_LOGICAL_SERIES_PER_PROCESS + 1;
|
||||
let values: &'static [&'static str] = Box::leak(
|
||||
(0..oversize)
|
||||
.map(|index| Box::leak(format!("value_{index}").into_boxed_str()) as &'static str)
|
||||
.collect::<Vec<&'static str>>()
|
||||
.into_boxed_slice(),
|
||||
);
|
||||
let oversize_domains: &'static [crank_metrics::LabelDomain] = Box::leak(
|
||||
vec![crank_metrics::LabelDomain {
|
||||
name: "state",
|
||||
class: crank_metrics::LabelClass::ProductClosed,
|
||||
values,
|
||||
}]
|
||||
.into_boxed_slice(),
|
||||
);
|
||||
let oversize_definition = MetricDefinition {
|
||||
name: "crank_test_oversize_total",
|
||||
kind: MetricKind::Counter,
|
||||
unit: MetricUnit::Count,
|
||||
labels: &["state"],
|
||||
label_domains: oversize_domains,
|
||||
buckets: &[],
|
||||
processes: &[MetricProcess::AdminApi],
|
||||
max_logical_series: oversize,
|
||||
max_rendered_series: oversize,
|
||||
description: "oversize counter",
|
||||
};
|
||||
assert_eq!(
|
||||
validate_schema(&[oversize_definition]),
|
||||
Err(crank_metrics::SchemaError::BudgetExceeded),
|
||||
"точный бюджет больше лимита обязан отвергаться типизированно"
|
||||
);
|
||||
assert_eq!(
|
||||
validate_budget(oversize, oversize),
|
||||
Err(crank_metrics::SchemaError::BudgetExceeded),
|
||||
"BudgetExceeded обязан быть типизированным на самой границе"
|
||||
);
|
||||
assert!(
|
||||
validate_budget(
|
||||
MAX_LOGICAL_SERIES_PER_PROCESS,
|
||||
MAX_RENDERED_SERIES_PER_PROCESS
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
|
||||
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
||||
for definition in service_projection(service) {
|
||||
assert_ne!(
|
||||
definition.max_logical_series,
|
||||
usize::MAX,
|
||||
"{} не может нести насыщенное значение",
|
||||
definition.name
|
||||
);
|
||||
assert_ne!(definition.max_rendered_series, usize::MAX);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-M6 — capacity вычисляется по сервису и укладывается в hard cap.
|
||||
#[test]
|
||||
fn exemplar_capacity_is_service_computed_and_capped() {
|
||||
assert_eq!(max_exemplar_slots(MetricService::AdminApi), 12_348);
|
||||
assert_eq!(max_exemplar_slots(MetricService::McpServer), 2_310);
|
||||
assert!(max_exemplar_slots(MetricService::AdminApi) <= MAX_EXEMPLAR_SLOTS_PER_PROCESS);
|
||||
assert!(max_exemplar_slots(MetricService::McpServer) <= MAX_EXEMPLAR_SLOTS_PER_PROCESS);
|
||||
assert_ne!(
|
||||
max_exemplar_slots(MetricService::AdminApi),
|
||||
14_658,
|
||||
"derived union capacity не может использоваться как лимит процесса"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-M7 — per-service projection cache создаётся один раз.
|
||||
#[test]
|
||||
fn service_projection_cache_is_allocated_once() {
|
||||
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
||||
let first = service_projection(service);
|
||||
let second = service_projection(service);
|
||||
assert!(
|
||||
std::ptr::eq(first, second),
|
||||
"проекция обязана быть стабильно закеширована"
|
||||
);
|
||||
let again = metric_schema_for_service(service).count();
|
||||
assert_eq!(again, first.len());
|
||||
}
|
||||
assert_eq!(
|
||||
metric_schema().len(),
|
||||
23,
|
||||
"union metadata сохраняет 23 family"
|
||||
);
|
||||
}
|
||||
@@ -12,7 +12,8 @@ mod schema;
|
||||
|
||||
pub use config::{ObservabilityConfig, ObservabilityConfigError, ServiceIdentity};
|
||||
pub use crank_metrics::{
|
||||
DURATION_BUCKETS_SECONDS, MetricDefinition, MetricKind, MetricUnit, metric_schema,
|
||||
DURATION_BUCKETS_SECONDS, MetricDefinition, MetricKind, MetricService, MetricUnit,
|
||||
bind_metric_service, bound_metric_service, metric_schema,
|
||||
};
|
||||
pub use error_reporting::{
|
||||
CriticalErrorCategory, SentryConfig, SentryConfigError, capture_critical_error,
|
||||
|
||||
@@ -49,6 +49,8 @@ impl ObservabilityLifecycle {
|
||||
.map_err(|_| ObservabilityInitError::SubscriberAlreadyInitialized)?;
|
||||
let metrics_service = crank_metrics::MetricService::parse(identity.service())
|
||||
.ok_or(MetricsSurfaceError::RecorderConfiguration)?;
|
||||
crank_metrics::bind_metric_service(metrics_service)
|
||||
.map_err(|_| ObservabilityInitError::MetricBinding)?;
|
||||
let metrics_handle = install_prometheus_recorder(&identity)?;
|
||||
register_metric_schema(metrics_service);
|
||||
let sentry_guard = init_sentry(&identity, redaction_limits, sentry_config)?;
|
||||
@@ -100,6 +102,8 @@ pub enum ObservabilityInitError {
|
||||
LogEventBudgetTooSmall,
|
||||
#[error("global tracing subscriber is already initialized")]
|
||||
SubscriberAlreadyInitialized,
|
||||
#[error("metric service binding is invalid or already fixed to another service")]
|
||||
MetricBinding,
|
||||
#[error(transparent)]
|
||||
Metrics(#[from] MetricsSurfaceError),
|
||||
#[error(transparent)]
|
||||
|
||||
@@ -196,6 +196,11 @@ pub enum MetricsServeError {
|
||||
pub(crate) fn install_prometheus_recorder(
|
||||
identity: &ServiceIdentity,
|
||||
) -> Result<PrometheusHandle, MetricsSurfaceError> {
|
||||
let service = MetricService::parse(identity.service())
|
||||
.ok_or(MetricsSurfaceError::RecorderConfiguration)?;
|
||||
if crank_metrics::bound_metric_service() != Some(service) {
|
||||
return Err(MetricsSurfaceError::RecorderConfiguration);
|
||||
}
|
||||
prometheus_builder(identity)?
|
||||
.install_recorder()
|
||||
.map_err(|_| MetricsSurfaceError::RecorderConfiguration)
|
||||
@@ -220,6 +225,10 @@ async fn render_metrics(State(state): State<MetricsState>, headers: HeaderMap) -
|
||||
let Some(_permit) = ScrapePermit::try_acquire(&state.active_scrapes) else {
|
||||
return (StatusCode::SERVICE_UNAVAILABLE, TOO_MANY_SCRAPES).into_response();
|
||||
};
|
||||
// cfg(test)-only точка синхронизации у permit seam'а: в production-сборке
|
||||
// строки нет, поэтому поведение не меняется.
|
||||
#[cfg(test)]
|
||||
crate::prometheus::scrape_barrier::hold().await;
|
||||
let legacy = state.handle.render();
|
||||
let openmetrics = headers
|
||||
.get(header::ACCEPT)
|
||||
@@ -387,89 +396,161 @@ fn token_digest(token: &[u8]) -> [u8; 32] {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod rendering_tests {
|
||||
use std::{
|
||||
sync::{Arc, atomic::AtomicUsize},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
mod rendering_tests;
|
||||
|
||||
use crank_metrics::{ExemplarObservation, ExemplarTraceId};
|
||||
/// cfg(test)-only барьер у scrape-permit seam'а: позволяет детерминированно
|
||||
/// доказать, что допускаются ровно два одновременных scrape, третий
|
||||
/// отвергается, а после release permit освобождается. В production-сборке
|
||||
/// (и в интеграционных тест-бинар��х, где crate компилируется как dependency)
|
||||
/// модуля нет, поэтому семантика не меняется.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod scrape_barrier {
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
|
||||
use super::{
|
||||
MAX_CONCURRENT_SCRAPES, ScrapePermit, exposition_response, prefers_openmetrics,
|
||||
render_openmetrics,
|
||||
};
|
||||
static STATE: OnceLock<Mutex<State>> = OnceLock::new();
|
||||
|
||||
#[test]
|
||||
fn openmetrics_adds_bounded_exemplar_without_changing_aggregate() {
|
||||
let legacy = "# TYPE crank_http_request_duration_seconds histogram\ncrank_http_request_duration_seconds_bucket{method=\"GET\",route=\"/health\",le=\"0.01\"} 1\ncrank_http_request_duration_seconds_sum{method=\"GET\",route=\"/health\"} 0.007\n";
|
||||
let exemplar = ExemplarObservation {
|
||||
metric: "crank_http_request_duration_seconds",
|
||||
labels: vec![("route", "/health"), ("method", "GET")],
|
||||
bucket_upper_bound: Some(0.01),
|
||||
value: 0.007,
|
||||
trace_id: ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").unwrap(),
|
||||
};
|
||||
let rendered = render_openmetrics(legacy, &[Arc::new(exemplar)]);
|
||||
assert!(rendered.contains("# {trace_id=\"0123456789abcdef0123456789abcdef\"} 0.007"));
|
||||
assert!(rendered.ends_with("# EOF\n"));
|
||||
assert_eq!(rendered.matches(" 1").count(), legacy.matches(" 1").count());
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
enabled: bool,
|
||||
release: bool,
|
||||
parked: usize,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accept_negotiation_is_exact_and_honors_quality_and_version() {
|
||||
assert!(prefers_openmetrics(
|
||||
"application/openmetrics-text; version=1.0.0"
|
||||
));
|
||||
assert!(prefers_openmetrics("application/openmetrics-text"));
|
||||
assert!(!prefers_openmetrics("application/openmetrics-text; q=0"));
|
||||
assert!(!prefers_openmetrics("application/openmetrics-textual"));
|
||||
assert!(!prefers_openmetrics(
|
||||
"application/openmetrics-text; version=0.0.1"
|
||||
));
|
||||
assert!(!prefers_openmetrics(
|
||||
"application/openmetrics-text;q=0.2,text/plain;q=0.8"
|
||||
));
|
||||
fn lock() -> MutexGuard<'static, State> {
|
||||
STATE
|
||||
.get_or_init(|| Mutex::new(State::default()))
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_and_concurrent_scrapes_fail_closed_at_their_bounds() {
|
||||
assert_eq!(
|
||||
exposition_response("x".repeat(crank_metrics::MAX_EXPOSITION_BYTES + 1), false)
|
||||
.status(),
|
||||
axum::http::StatusCode::SERVICE_UNAVAILABLE
|
||||
);
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
let permits = (0..MAX_CONCURRENT_SCRAPES)
|
||||
.map(|_| ScrapePermit::try_acquire(&active).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(ScrapePermit::try_acquire(&active).is_none());
|
||||
drop(permits);
|
||||
assert!(ScrapePermit::try_acquire(&active).is_some());
|
||||
/// Включает барьер для одного детерминированного кейса.
|
||||
pub(crate) fn enable() {
|
||||
let mut state = lock();
|
||||
state.enabled = true;
|
||||
state.release = false;
|
||||
state.parked = 0;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximum_fixture_renders_in_linear_bounded_time() {
|
||||
let trace = ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").unwrap();
|
||||
let mut legacy = String::new();
|
||||
let mut exemplars = Vec::new();
|
||||
for index in 0..5_000 {
|
||||
let value: &'static str = Box::leak(format!("route-{index}").into_boxed_str());
|
||||
legacy.push_str(&format!(
|
||||
"crank_http_request_duration_seconds_bucket{{route=\"{value}\",method=\"GET\",le=\"0.01\"}} 1\n"
|
||||
));
|
||||
exemplars.push(Arc::new(ExemplarObservation {
|
||||
metric: "crank_http_request_duration_seconds",
|
||||
labels: vec![("route", value), ("method", "GET")],
|
||||
bucket_upper_bound: Some(0.01),
|
||||
value: 0.007,
|
||||
trace_id: trace,
|
||||
}));
|
||||
/// Парковка после успешного acquire permit'а. Если барьер выключен —
|
||||
/// немедленный возврат, поэтому прочие unit-тесты не затрагиваются.
|
||||
/// Ожидание асинхронное (yield), поэтому worker'ы runtime'а не блокируются и
|
||||
/// обслуживание следующих соединений остаётся детерминированным.
|
||||
pub(crate) async fn hold() {
|
||||
{
|
||||
let mut state = lock();
|
||||
if !state.enabled {
|
||||
return;
|
||||
}
|
||||
state.parked += 1;
|
||||
}
|
||||
let started = Instant::now();
|
||||
let rendered = render_openmetrics(&legacy, &exemplars);
|
||||
assert_eq!(rendered.matches("# {trace_id=").count(), 5_000);
|
||||
assert!(started.elapsed() < Duration::from_secs(3));
|
||||
assert!(rendered.len() < crank_metrics::MAX_EXPOSITION_BYTES);
|
||||
while !lock().release {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ожидание `count` припаркованных scrape'ов; `false` — истёк deadline.
|
||||
/// Вызывается из blocking-пула, поэтому не расходует worker'ы runtime'а.
|
||||
pub(crate) fn wait_for_parked(count: usize, timeout: std::time::Duration) -> bool {
|
||||
let deadline = std::time::Instant::now() + timeout;
|
||||
while std::time::Instant::now() < deadline {
|
||||
if lock().parked >= count {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
}
|
||||
lock().parked >= count
|
||||
}
|
||||
|
||||
pub(crate) fn parked() -> usize {
|
||||
lock().parked
|
||||
}
|
||||
|
||||
/// Освобождает все припаркованные scrape'ы.
|
||||
pub(crate) fn release() {
|
||||
lock().release = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod recorder_guard_tests {
|
||||
use std::process::Command;
|
||||
|
||||
use super::{MetricsSurfaceError, install_prometheus_recorder};
|
||||
use crate::ServiceIdentity;
|
||||
|
||||
const GUARD_ROLE_PREFIX: &str = "crank-observability-guard-role-";
|
||||
|
||||
fn current_role() -> Option<String> {
|
||||
std::env::current_dir()
|
||||
.ok()?
|
||||
.file_name()?
|
||||
.to_str()?
|
||||
.strip_prefix(GUARD_ROLE_PREFIX)
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// F7 — приватный `install_prometheus_recorder` обязан отвергать identity,
|
||||
/// не совпадающую с опубликованным binding'ом, **до** любой установки
|
||||
/// recorder'а; ошибка типизированная, а positive control доказывает, что
|
||||
/// отклонённый вызов ничего не установил.
|
||||
///
|
||||
/// Свежий процесс обязателен: outer lifecycle-тест падает раньше (уже
|
||||
/// занятый global recorder/binding), поэтому приватный guard он не
|
||||
/// доказывает.
|
||||
#[test]
|
||||
fn private_recorder_guard_rejects_identity_mismatch_before_installing() {
|
||||
if current_role().is_none() {
|
||||
let role = "guard";
|
||||
let directory = std::env::temp_dir().join(format!("{GUARD_ROLE_PREFIX}{role}"));
|
||||
std::fs::create_dir_all(&directory).expect("guard role dir");
|
||||
let output = Command::new(std::env::current_exe().expect("current test binary"))
|
||||
.args([
|
||||
"prometheus::recorder_guard_tests::private_recorder_guard_rejects_identity_mismatch_before_installing",
|
||||
"--exact",
|
||||
"--nocapture",
|
||||
])
|
||||
.current_dir(&directory)
|
||||
.output()
|
||||
.expect("re-executed guard child");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"guard child failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Свежий процесс: ни recorder, ни binding ещё не установлены.
|
||||
assert_eq!(crank_metrics::bound_metric_service(), None);
|
||||
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
|
||||
.expect("admin binding");
|
||||
|
||||
let mismatched = ServiceIdentity::try_new("mcp-server", "0.3.1", "test")
|
||||
.expect("valid mismatched identity");
|
||||
match install_prometheus_recorder(&mismatched) {
|
||||
Err(MetricsSurfaceError::RecorderConfiguration) => {}
|
||||
other => panic!(
|
||||
"identity другого сервиса обязана быть отвергнута приватным guard'ом: {other:?}"
|
||||
),
|
||||
}
|
||||
|
||||
// Positive control: matching identity проходит, значит предыдущий отказ
|
||||
// пришёл из guard'а, а не из заранее установленного recorder'а.
|
||||
let matching = ServiceIdentity::try_new("admin-api", "0.3.1", "test")
|
||||
.expect("valid matching identity");
|
||||
let handle = install_prometheus_recorder(&matching)
|
||||
.expect("matching identity обязан установить recorder");
|
||||
crank_metrics::record_http_request(
|
||||
crank_metrics::HttpRoute::from_matched_path("/health"),
|
||||
crank_metrics::HttpMethod::Get,
|
||||
crank_metrics::HttpStatusClass::Success,
|
||||
std::time::Duration::from_millis(1),
|
||||
);
|
||||
let exposition = handle.render();
|
||||
assert!(
|
||||
exposition.contains("crank_http_requests_total"),
|
||||
"установленный recorder обязан отдавать записанные series: {exposition}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
//! Приватный renderer-модуль (`prometheus::rendering_tests`) — TD-E2/TD-E5 и
|
||||
//! границы exposition. Вынесен из `src/prometheus.rs` в отдельный файл, чтобы
|
||||
//! code-health (`<= 1000` строк) выполнялся; полные пути селекторов
|
||||
//! `prometheus::rendering_tests::…` при этом сохраняются без изменений.
|
||||
//!
|
||||
//! Заполнение метрик живёт в test-only фикстуре под `tests/fixtures/`: имена и
|
||||
//! labels метрик принадлежат `crank-metrics`, поэтому production-пути `src/**`
|
||||
//! не могут объявлять их напрямую (`scripts/check-metrics-boundaries.py`).
|
||||
|
||||
#[path = "../../tests/fixtures/rendering_fixture.rs"]
|
||||
mod rendering_fixture;
|
||||
|
||||
use std::{
|
||||
sync::{Arc, atomic::AtomicUsize},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use crank_metrics::{ExemplarObservation, ExemplarTraceId};
|
||||
|
||||
use super::{
|
||||
MAX_CONCURRENT_SCRAPES, ScrapePermit, exposition_response, prefers_openmetrics,
|
||||
prometheus_builder, render_openmetrics,
|
||||
};
|
||||
|
||||
const ROLE_DIR_PREFIX: &str = "crank-observability-role-";
|
||||
|
||||
fn current_role() -> Option<String> {
|
||||
std::env::current_dir()
|
||||
.ok()?
|
||||
.file_name()?
|
||||
.to_str()?
|
||||
.strip_prefix(ROLE_DIR_PREFIX)
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openmetrics_adds_bounded_exemplar_without_changing_aggregate() {
|
||||
let legacy = "# TYPE crank_http_request_duration_seconds histogram\ncrank_http_request_duration_seconds_bucket{method=\"GET\",route=\"/health\",le=\"0.01\"} 1\ncrank_http_request_duration_seconds_sum{method=\"GET\",route=\"/health\"} 0.007\n";
|
||||
let exemplar = ExemplarObservation {
|
||||
metric: "crank_http_request_duration_seconds",
|
||||
labels: vec![("route", "/health"), ("method", "GET")],
|
||||
bucket_upper_bound: Some(0.01),
|
||||
value: 0.007,
|
||||
trace_id: ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").unwrap(),
|
||||
};
|
||||
let rendered = render_openmetrics(legacy, &[Arc::new(exemplar)]);
|
||||
assert!(rendered.contains("# {trace_id=\"0123456789abcdef0123456789abcdef\"} 0.007"));
|
||||
assert!(rendered.ends_with("# EOF\n"));
|
||||
assert_eq!(rendered.matches(" 1").count(), legacy.matches(" 1").count());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accept_negotiation_is_exact_and_honors_quality_and_version() {
|
||||
assert!(prefers_openmetrics(
|
||||
"application/openmetrics-text; version=1.0.0"
|
||||
));
|
||||
assert!(prefers_openmetrics("application/openmetrics-text"));
|
||||
assert!(!prefers_openmetrics("application/openmetrics-text; q=0"));
|
||||
assert!(!prefers_openmetrics("application/openmetrics-textual"));
|
||||
assert!(!prefers_openmetrics(
|
||||
"application/openmetrics-text; version=0.0.1"
|
||||
));
|
||||
assert!(!prefers_openmetrics(
|
||||
"application/openmetrics-text;q=0.2,text/plain;q=0.8"
|
||||
));
|
||||
}
|
||||
|
||||
/// Границы cap и scrape-permit'ов: допускаются ровно `MAX_CONCURRENT_SCRAPES`
|
||||
/// одновременных scrape, следующий отвергается, permit освобождается. Оракул
|
||||
/// точный: он падает и при cap=1 (второй acquire), и при cap=3 (третий).
|
||||
#[test]
|
||||
fn output_and_concurrent_scrapes_fail_closed_at_their_bounds() {
|
||||
assert_eq!(
|
||||
exposition_response("x".repeat(crank_metrics::MAX_EXPOSITION_BYTES + 1), false).status(),
|
||||
axum::http::StatusCode::SERVICE_UNAVAILABLE
|
||||
);
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
let permits = (0..MAX_CONCURRENT_SCRAPES)
|
||||
.map(|_| ScrapePermit::try_acquire(&active).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(ScrapePermit::try_acquire(&active).is_none());
|
||||
drop(permits);
|
||||
assert!(ScrapePermit::try_acquire(&active).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximum_fixture_renders_in_linear_bounded_time() {
|
||||
let trace = ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").unwrap();
|
||||
let mut legacy = String::new();
|
||||
let mut exemplars = Vec::new();
|
||||
for index in 0..5_000 {
|
||||
let value: &'static str = Box::leak(format!("route-{index}").into_boxed_str());
|
||||
legacy.push_str(&format!(
|
||||
"crank_http_request_duration_seconds_bucket{{route=\"{value}\",method=\"GET\",le=\"0.01\"}} 1\n"
|
||||
));
|
||||
exemplars.push(Arc::new(ExemplarObservation {
|
||||
metric: "crank_http_request_duration_seconds",
|
||||
labels: vec![("route", value), ("method", "GET")],
|
||||
bucket_upper_bound: Some(0.01),
|
||||
value: 0.007,
|
||||
trace_id: trace,
|
||||
}));
|
||||
}
|
||||
let started = Instant::now();
|
||||
let rendered = render_openmetrics(&legacy, &exemplars);
|
||||
assert_eq!(rendered.matches("# {trace_id=").count(), 5_000);
|
||||
assert!(started.elapsed() < Duration::from_secs(3));
|
||||
assert!(rendered.len() < crank_metrics::MAX_EXPOSITION_BYTES);
|
||||
}
|
||||
|
||||
fn read_response(response: axum::response::Response) -> (axum::http::StatusCode, Vec<u8>) {
|
||||
let status = response.status();
|
||||
let bytes = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("boundary test runtime")
|
||||
.block_on(axum::body::to_bytes(response.into_body(), usize::MAX))
|
||||
.expect("response body must be readable");
|
||||
(status, bytes.to_vec())
|
||||
}
|
||||
|
||||
/// TD-E5 — границы exposition проверяются по **фактическому телу ответа**:
|
||||
/// cap-1/cap отдают точный входной body без усечения, cap+1 — точный static503
|
||||
/// (а не «input length» assertion).
|
||||
#[test]
|
||||
fn exposition_boundary_cap_minus_one_cap_and_cap_plus_one_both_formats() {
|
||||
const STATIC_OVER_LIMIT: &[u8] = b"metrics exposition exceeds configured bound\n";
|
||||
let cap = crank_metrics::MAX_EXPOSITION_BYTES;
|
||||
for openmetrics in [false, true] {
|
||||
let marker = if openmetrics { "openmetrics" } else { "legacy" };
|
||||
let expected_content_type = if openmetrics {
|
||||
"application/openmetrics-text; version=1.0.0; charset=utf-8"
|
||||
} else {
|
||||
"text/plain; version=0.0.4; charset=utf-8"
|
||||
};
|
||||
for (label, length, expected_status) in [
|
||||
("cap-1", cap - 1, axum::http::StatusCode::OK),
|
||||
("cap", cap, axum::http::StatusCode::OK),
|
||||
(
|
||||
"cap+1",
|
||||
cap + 1,
|
||||
axum::http::StatusCode::SERVICE_UNAVAILABLE,
|
||||
),
|
||||
] {
|
||||
let body = "x".repeat(length);
|
||||
let response = exposition_response(body.clone(), openmetrics);
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
expected_status,
|
||||
"TD-E5 {marker}/{label} обязан дать {expected_status}"
|
||||
);
|
||||
let content_type = response
|
||||
.headers()
|
||||
.get(axum::http::header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
assert_eq!(
|
||||
content_type,
|
||||
if expected_status == axum::http::StatusCode::OK {
|
||||
expected_content_type
|
||||
} else {
|
||||
"text/plain; charset=utf-8"
|
||||
},
|
||||
"TD-E5 {marker}/{label}: формат не подменяется"
|
||||
);
|
||||
|
||||
let (status, bytes) = read_response(response);
|
||||
assert_eq!(status, expected_status);
|
||||
if expected_status == axum::http::StatusCode::OK {
|
||||
assert_eq!(
|
||||
bytes.len(),
|
||||
length,
|
||||
"TD-E5 {marker}/{label}: фактическое тело не усекается на границе"
|
||||
);
|
||||
assert!(
|
||||
bytes == body.as_bytes(),
|
||||
"TD-E5 {marker}/{label}: тело обязано быть передано без изменений"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
bytes, STATIC_OVER_LIMIT,
|
||||
"TD-E5 {marker}/{label}: cap+1 обязан вернуть точный static503 без тела входа"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-E2 — maximal permitted renderer fixture измеряется по каждому сервису:
|
||||
/// все объявленные family/buckets проекции, заполненные валидные test-local
|
||||
/// exemplar'ы, оба формата, фактические bytes и точные sample counts.
|
||||
#[test]
|
||||
fn maximal_permitted_exposition_is_measured_below_cap() {
|
||||
match current_role().as_deref() {
|
||||
None => {
|
||||
for service in ["admin-api", "mcp-server"] {
|
||||
let directory = std::env::temp_dir().join(format!("{ROLE_DIR_PREFIX}{service}"));
|
||||
std::fs::create_dir_all(&directory).expect("E2 role dir");
|
||||
let output = std::process::Command::new(
|
||||
std::env::current_exe().expect("current test binary"),
|
||||
)
|
||||
.args([
|
||||
"prometheus::rendering_tests::maximal_permitted_exposition_is_measured_below_cap",
|
||||
"--exact",
|
||||
"--nocapture",
|
||||
])
|
||||
.current_dir(&directory)
|
||||
.output()
|
||||
.expect("re-executed E2 child");
|
||||
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
|
||||
for line in stdout.lines().filter(|line| line.contains("TD-E2 MEASURE")) {
|
||||
println!("{line}");
|
||||
}
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"E2 child {service} failed:\nstdout:\n{stdout}\nstderr:\n{stderr}"
|
||||
);
|
||||
assert!(
|
||||
stdout.contains(&format!("TD-E2 MEASURE service={service}")),
|
||||
"E2 child {service} обязан измерить оба формата:\n{stdout}\n{stderr}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Some(service) => measure_maximal_permitted(service),
|
||||
}
|
||||
}
|
||||
|
||||
fn domain_combinations(
|
||||
domains: &[crank_metrics::LabelDomain],
|
||||
) -> Vec<Vec<(&'static str, &'static str)>> {
|
||||
rendering_fixture::domain_combinations(domains)
|
||||
}
|
||||
|
||||
fn sample_lines(text: &str) -> usize {
|
||||
text.lines()
|
||||
.filter(|line| !line.starts_with('#') && !line.trim().is_empty())
|
||||
.count()
|
||||
}
|
||||
|
||||
fn family_sample_lines(legacy: &str, name: &str) -> usize {
|
||||
legacy
|
||||
.lines()
|
||||
.filter(|line| {
|
||||
!line.starts_with('#')
|
||||
&& (line.starts_with(&format!("{name}{{"))
|
||||
|| line.starts_with(&format!("{name}_bucket{{"))
|
||||
|| line.starts_with(&format!("{name}_count{{"))
|
||||
|| line.starts_with(&format!("{name}_sum{{")))
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
fn measure_maximal_permitted(service: &str) {
|
||||
use crank_metrics::{MetricService, service_projection};
|
||||
|
||||
let metric_service = MetricService::parse(service).expect("registered service");
|
||||
crank_metrics::bind_metric_service(metric_service).expect("service binding");
|
||||
|
||||
// F10: identity из 64 ASCII-байт разрешена, 65 — отвергается.
|
||||
let long_version = "1".repeat(64);
|
||||
let long_environment = "p".repeat(64);
|
||||
let identity =
|
||||
crate::ServiceIdentity::try_new(service, long_version.clone(), long_environment.clone())
|
||||
.expect("64-byte identity is accepted");
|
||||
assert!(
|
||||
crate::ServiceIdentity::try_new(service, "1".repeat(65), long_environment).is_err(),
|
||||
"65 байт обязаны быть отвергнуты валидатором identity"
|
||||
);
|
||||
|
||||
let handle = prometheus_builder(&identity)
|
||||
.expect("prometheus builder")
|
||||
.install_recorder()
|
||||
.expect("fresh-child global recorder");
|
||||
|
||||
let mut expected_samples = 0_usize;
|
||||
let mut expected_exemplars = 0_usize;
|
||||
for definition in service_projection(metric_service) {
|
||||
let combinations = domain_combinations(definition.label_domains);
|
||||
assert_eq!(
|
||||
combinations.len(),
|
||||
definition.max_logical_series,
|
||||
"{}: Cartesian проекции обязан совпасть с metadata",
|
||||
definition.name
|
||||
);
|
||||
expected_samples += definition.max_rendered_series;
|
||||
expected_exemplars += definition.max_exemplar_slots();
|
||||
}
|
||||
let (filled_samples, filled_exemplars) =
|
||||
rendering_fixture::record_projected_domains(metric_service);
|
||||
assert_eq!(
|
||||
filled_samples, expected_samples,
|
||||
"fixture обязан заполнить столько samples, сколько declares проекция"
|
||||
);
|
||||
assert_eq!(filled_exemplars, expected_exemplars);
|
||||
assert_eq!(
|
||||
expected_samples,
|
||||
crank_metrics::schema_budget(metric_service)
|
||||
.expect("service budget")
|
||||
.rendered_series,
|
||||
"fixture обязан быть maximal относительно формулы R проекции"
|
||||
);
|
||||
assert_eq!(
|
||||
expected_exemplars,
|
||||
crank_metrics::max_exemplar_slots(metric_service),
|
||||
"fixture обязан быть maximal относительно формулы E проекции"
|
||||
);
|
||||
|
||||
let legacy = handle.render();
|
||||
let exemplars = rendering_fixture::maximal_exemplars(metric_service);
|
||||
assert_eq!(exemplars.len(), expected_exemplars);
|
||||
let openmetrics = render_openmetrics(&legacy, &exemplars);
|
||||
|
||||
let legacy_samples = sample_lines(&legacy);
|
||||
let openmetrics_samples = sample_lines(&openmetrics);
|
||||
let attached = openmetrics.matches("# {trace_id=").count();
|
||||
println!(
|
||||
"TD-E2 MEASURE service={service} families={} legacy_bytes={} openmetrics_bytes={} \
|
||||
sample_lines={} bucket_exemplars={} attached_exemplars={}",
|
||||
service_projection(metric_service).len(),
|
||||
legacy.len(),
|
||||
openmetrics.len(),
|
||||
legacy_samples,
|
||||
exemplars.len(),
|
||||
attached
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
legacy_samples, expected_samples,
|
||||
"каждая объявленная sample обязана быть отрендерена"
|
||||
);
|
||||
assert_eq!(
|
||||
openmetrics_samples, expected_samples,
|
||||
"OpenMetrics не добавляет и не теряет samples"
|
||||
);
|
||||
for definition in service_projection(metric_service) {
|
||||
assert_eq!(
|
||||
family_sample_lines(&legacy, definition.name),
|
||||
definition.max_rendered_series,
|
||||
"{}: sample count обязан совпасть с формулой R",
|
||||
definition.name
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
attached, expected_exemplars,
|
||||
"каждый valid exemplar обязан быть привязан к своему bucket line"
|
||||
);
|
||||
assert!(
|
||||
legacy.len() <= crank_metrics::MAX_EXPOSITION_BYTES,
|
||||
"permitted maximal legacy fixture обязан уложиться в cap, observed {}",
|
||||
legacy.len()
|
||||
);
|
||||
assert!(
|
||||
openmetrics.len() <= crank_metrics::MAX_EXPOSITION_BYTES,
|
||||
"permitted maximal openmetrics fixture обязан уложиться в cap, observed {}",
|
||||
openmetrics.len()
|
||||
);
|
||||
assert!(openmetrics.len() > legacy.len());
|
||||
assert!(openmetrics.ends_with("# EOF\n"));
|
||||
}
|
||||
|
||||
fn raw_scrape_status(address: std::net::SocketAddr) -> String {
|
||||
use std::io::{Read, Write};
|
||||
|
||||
let mut stream = std::net::TcpStream::connect(address).expect("scrape connection");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(30)))
|
||||
.expect("read timeout");
|
||||
stream
|
||||
.write_all(
|
||||
format!("GET /metrics HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n")
|
||||
.as_bytes(),
|
||||
)
|
||||
.expect("scrape request");
|
||||
let mut response = Vec::new();
|
||||
stream.read_to_end(&mut response).expect("scrape response");
|
||||
String::from_utf8_lossy(&response)
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
/// Контрактное число одновременных scrape'ов (F8): ровно два допущенных
|
||||
/// scrape'а. Оракул ниже обязан фиксировать это независимо от production
|
||||
/// `MAX_CONCURRENT_SCRAPES`, иначе тест подстраивался бы под любую ошибочную
|
||||
/// константу (cap=1 или cap=3) вместо контракта.
|
||||
const EXPECTED_ADMITTED_SCRAPES: usize = 2;
|
||||
|
||||
/// F8 — детерминированный oracle реального listener'а у permit seam'а: ровно
|
||||
/// два одновременных scrape'а допускаются и паркуются, следующий при занятых
|
||||
/// permit'ах отвергается, после release permit освобождается. Тест обязан
|
||||
/// падать и при cap=1 (второй не паркуется, ожидание двух истекает), и при
|
||||
/// cap=3 (третий паркуется), поэтому зависит не от тайминга, а от
|
||||
/// cfg(test)-барьера.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
|
||||
async fn deterministic_scrape_cap_admits_exactly_two_and_releases() {
|
||||
const TEST: &str =
|
||||
"prometheus::rendering_tests::deterministic_scrape_cap_admits_exactly_two_and_releases";
|
||||
assert_eq!(
|
||||
MAX_CONCURRENT_SCRAPES, EXPECTED_ADMITTED_SCRAPES,
|
||||
"production-константа обязана совпадать с контрактными двумя, иначе \
|
||||
поведенческий оракул ниже проверяет не контракт"
|
||||
);
|
||||
if current_role().is_none() {
|
||||
let (success, stdout, stderr) = run_role_child("cap-two", TEST);
|
||||
for line in stdout.lines().filter(|line| line.contains("TD-F8 MEASURE")) {
|
||||
println!("{line}");
|
||||
}
|
||||
assert!(
|
||||
success,
|
||||
"cap-two child failed:\nstdout:\n{stdout}\nstderr:\n{stderr}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
super::scrape_barrier::enable();
|
||||
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
|
||||
.expect("admin binding");
|
||||
let identity =
|
||||
crate::ServiceIdentity::try_new("admin-api", "0.3.1", "test").expect("surface identity");
|
||||
let config = crate::MetricsConfig::new(
|
||||
true,
|
||||
std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 0),
|
||||
None,
|
||||
)
|
||||
.expect("loopback metrics config");
|
||||
let server = crate::MetricsSurface::for_test(config, identity)
|
||||
.expect("test surface")
|
||||
.bind()
|
||||
.await
|
||||
.expect("real metrics listener");
|
||||
let address = server.local_addr().expect("listener address");
|
||||
let task = tokio::spawn(server.serve());
|
||||
|
||||
let admitted = (0..EXPECTED_ADMITTED_SCRAPES)
|
||||
.map(|_| std::thread::spawn(move || raw_scrape_status(address)))
|
||||
.collect::<Vec<_>>();
|
||||
let admitted_parked = tokio::task::spawn_blocking(|| {
|
||||
super::scrape_barrier::wait_for_parked(EXPECTED_ADMITTED_SCRAPES, Duration::from_secs(20))
|
||||
})
|
||||
.await
|
||||
.expect("park waiter");
|
||||
assert!(
|
||||
admitted_parked,
|
||||
"ровно {EXPECTED_ADMITTED_SCRAPES} одновременных scrape'а обязаны быть допущены, parked={}",
|
||||
super::scrape_barrier::parked()
|
||||
);
|
||||
|
||||
// Третий запрос: детерминированно ждём либо отказ (503), либо парковку
|
||||
// третьего (cap>=3). Ожидание идёт в blocking-пуле, поэтому worker'ы
|
||||
// runtime'а свободны для обработки третьего соединения.
|
||||
let third = std::thread::spawn(move || raw_scrape_status(address));
|
||||
let (third_status, parked_with_third, third_finished) =
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(20);
|
||||
while std::time::Instant::now() < deadline {
|
||||
if super::scrape_barrier::parked() > EXPECTED_ADMITTED_SCRAPES
|
||||
|| third.is_finished()
|
||||
{
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
let parked = super::scrape_barrier::parked();
|
||||
let finished = third.is_finished();
|
||||
// Release обязателен до join: если cap был бы >=3, третий scrape
|
||||
// припаркован, и без release join повис бы вместо честного FAIL.
|
||||
super::scrape_barrier::release();
|
||||
(third.join().expect("third scrape thread"), parked, finished)
|
||||
})
|
||||
.await
|
||||
.expect("third scrape waiter");
|
||||
println!(
|
||||
"TD-F8 MEASURE parked_with_third={parked_with_third} third_finished={third_finished} \
|
||||
third_status={third_status:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
parked_with_third, EXPECTED_ADMITTED_SCRAPES,
|
||||
"третий scrape не мог занять permit (контракт: ровно {EXPECTED_ADMITTED_SCRAPES} \
|
||||
допущенных)"
|
||||
);
|
||||
assert!(
|
||||
third_status.contains("503"),
|
||||
"третий scrape обязан быть отвергнут: {third_status}"
|
||||
);
|
||||
|
||||
for handle in admitted {
|
||||
let status = handle.join().expect("admitted scrape thread");
|
||||
assert!(
|
||||
status.contains("200"),
|
||||
"допущенный scrape обязан ответить 200: {status}"
|
||||
);
|
||||
}
|
||||
let after = tokio::task::spawn_blocking(move || raw_scrape_status(address))
|
||||
.await
|
||||
.expect("post-release scrape thread");
|
||||
assert!(
|
||||
after.contains("200"),
|
||||
"permit обязан освободиться после release: {after}"
|
||||
);
|
||||
task.abort();
|
||||
}
|
||||
|
||||
fn run_role_child(role: &str, test: &str) -> (bool, String, String) {
|
||||
let directory = std::env::temp_dir().join(format!("{ROLE_DIR_PREFIX}{role}"));
|
||||
std::fs::create_dir_all(&directory).expect("role dir");
|
||||
let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
|
||||
.args([test, "--exact", "--nocapture"])
|
||||
.current_dir(&directory)
|
||||
.output()
|
||||
.expect("re-executed child");
|
||||
(
|
||||
output.status.success(),
|
||||
String::from_utf8_lossy(&output.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&output.stderr).into_owned(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Test-only fixture для TD-E2 (`crank-observability`): заполнение **всех**
|
||||
//! family/buckets сервисной проекции и maximal test-local exemplar'ы.
|
||||
//!
|
||||
//! Файл лежит под `tests/` намеренно: production-код `src/**` не имеет права
|
||||
//! объявлять метрики напрямую (`scripts/check-metrics-boundaries.py` — имена и
|
||||
//! labels принадлежат `crank-metrics`), а тестовые пути исключены из правила.
|
||||
//! Каталог `tests/fixtures/` не является отдельным Cargo-таргетом (нет
|
||||
//! `main.rs`) и подключается в приватный тест-модуль через `#[path]`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crank_metrics::{ExemplarObservation, ExemplarTraceId, LabelDomain, MetricKind, MetricService};
|
||||
|
||||
pub(crate) fn domain_combinations(
|
||||
domains: &[LabelDomain],
|
||||
) -> Vec<Vec<(&'static str, &'static str)>> {
|
||||
let mut combinations: Vec<Vec<(&'static str, &'static str)>> = vec![Vec::new()];
|
||||
for domain in domains {
|
||||
let mut next = Vec::with_capacity(combinations.len() * domain.values.len());
|
||||
for combination in &combinations {
|
||||
for value in domain.values {
|
||||
let mut extended = combination.clone();
|
||||
extended.push((domain.name, *value));
|
||||
next.push(extended);
|
||||
}
|
||||
}
|
||||
combinations = next;
|
||||
}
|
||||
combinations
|
||||
}
|
||||
|
||||
pub(crate) fn metric_labels(combination: &[(&'static str, &'static str)]) -> Vec<metrics::Label> {
|
||||
combination
|
||||
.iter()
|
||||
.map(|(name, value)| metrics::Label::new(*name, *value))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Заполняет **каждую** family проекции по всем Cartesian-комбинациям её
|
||||
/// доменов; каждое histogram-наблюдение попадает в свой конечный bucket (а
|
||||
/// `+Inf` заполняется кумулятивно). Возвращает `(rendered samples, exemplar slots)`.
|
||||
pub(crate) fn record_projected_domains(service: MetricService) -> (usize, usize) {
|
||||
let mut expected_samples = 0_usize;
|
||||
let mut expected_exemplars = 0_usize;
|
||||
for definition in crank_metrics::service_projection(service) {
|
||||
let combinations = domain_combinations(definition.label_domains);
|
||||
assert_eq!(
|
||||
combinations.len(),
|
||||
definition.max_logical_series,
|
||||
"{}: Cartesian проекции обязан совпасть с metadata",
|
||||
definition.name
|
||||
);
|
||||
for combination in &combinations {
|
||||
match definition.kind {
|
||||
MetricKind::Counter => {
|
||||
metrics::counter!(definition.name, metric_labels(combination)).increment(1_u64);
|
||||
}
|
||||
MetricKind::Gauge => {
|
||||
metrics::gauge!(definition.name, metric_labels(combination)).set(1.0);
|
||||
}
|
||||
MetricKind::Histogram => {
|
||||
for bound in definition.buckets {
|
||||
metrics::histogram!(definition.name, metric_labels(combination))
|
||||
.record(*bound);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expected_samples += definition.max_rendered_series;
|
||||
expected_exemplars += definition.max_exemplar_slots();
|
||||
}
|
||||
(expected_samples, expected_exemplars)
|
||||
}
|
||||
|
||||
/// Валидные test-local exemplar'ы: по одному наблюдению на каждый объявленный
|
||||
/// bucket и на `+Inf` каждой histogram-серии проекции. Количество совпадает с
|
||||
/// `max_exemplar_slots(service)` (frozen `E`), а ключи совпадают с bucket-line
|
||||
/// keys, которые рендерит exporter.
|
||||
pub(crate) fn maximal_exemplars(service: MetricService) -> Vec<Arc<ExemplarObservation>> {
|
||||
let trace = ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").expect("trace id");
|
||||
let mut exemplars = Vec::new();
|
||||
for definition in crank_metrics::service_projection(service) {
|
||||
if definition.kind != MetricKind::Histogram {
|
||||
continue;
|
||||
}
|
||||
let last = definition.buckets[definition.buckets.len() - 1];
|
||||
for combination in domain_combinations(definition.label_domains) {
|
||||
for bound in definition.buckets {
|
||||
exemplars.push(Arc::new(ExemplarObservation {
|
||||
metric: definition.name,
|
||||
labels: combination.clone(),
|
||||
bucket_upper_bound: Some(*bound),
|
||||
value: *bound,
|
||||
trace_id: trace,
|
||||
}));
|
||||
}
|
||||
exemplars.push(Arc::new(ExemplarObservation {
|
||||
metric: definition.name,
|
||||
labels: combination.clone(),
|
||||
bucket_upper_bound: None,
|
||||
value: last + 1.0,
|
||||
trace_id: trace,
|
||||
}));
|
||||
}
|
||||
}
|
||||
exemplars
|
||||
}
|
||||
@@ -17,7 +17,10 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
#[tokio::test]
|
||||
async fn typed_product_signals_are_exposed_by_a_real_scrape() {
|
||||
let identity = ServiceIdentity::try_new("admin-api", "0.3.1", "test").expect("valid identity");
|
||||
// Story 3.6: family applicability follows the closed process identity, so the
|
||||
// fixture binds mcp-server (the only process that owns the MCP/catalog families)
|
||||
// and exercises the full projected schema of that service.
|
||||
let identity = ServiceIdentity::try_new("mcp-server", "0.3.1", "test").expect("valid identity");
|
||||
let lifecycle = crank_observability::init(ObservabilityConfig::new(
|
||||
identity,
|
||||
"off",
|
||||
|
||||
@@ -229,3 +229,83 @@ async fn raw_get(port: u16, path: &str) -> String {
|
||||
.expect("metrics response");
|
||||
String::from_utf8(response).expect("utf-8 response")
|
||||
}
|
||||
|
||||
/// Story 3.6 — process-global binding: случаи, требующие другого состояния,
|
||||
/// исполняются в fresh child того же тест-бинаря (никакого global reset).
|
||||
fn route_to_child(role: &str, test: &str) -> bool {
|
||||
const ROLE_ENV: &str = "CRANK_OBS_TEST_ROLE";
|
||||
match std::env::var(ROLE_ENV).ok().as_deref() {
|
||||
Some(actual) if actual == role => false,
|
||||
Some(actual) => panic!("child for {test} runs with role {actual}, expected {role}"),
|
||||
None => {
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().expect("current test binary"))
|
||||
.args([test, "--exact", "--nocapture"])
|
||||
.env(ROLE_ENV, role)
|
||||
.output()
|
||||
.expect("re-executed observability child");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// TD-B7 — recorder identity обязана совпадать с уже опубликованным binding.
|
||||
#[test]
|
||||
fn recorder_identity_must_match_binding() {
|
||||
if route_to_child("admin_api", "recorder_identity_must_match_binding") {
|
||||
return;
|
||||
}
|
||||
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
|
||||
.expect("admin binding");
|
||||
let mismatched = ServiceIdentity::try_new("mcp-server", "0.3.1", "test").expect("identity");
|
||||
let error = crank_observability::init(crank_observability::ObservabilityConfig::new(
|
||||
mismatched,
|
||||
"off",
|
||||
crank_observability::RedactionLimits::default(),
|
||||
))
|
||||
.expect_err("mismatched recorder identity must be terminal");
|
||||
assert!(!error.to_string().is_empty());
|
||||
assert_eq!(
|
||||
crank_metrics::bound_metric_service(),
|
||||
Some(crank_metrics::MetricService::AdminApi),
|
||||
"провал установки recorder не меняет binding"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-E7 — `MetricsSurface::for_test` строит локальный renderer и никогда не
|
||||
/// меняет process binding.
|
||||
#[test]
|
||||
fn metrics_surface_never_rebinds_service() {
|
||||
if route_to_child("mcp_surface", "metrics_surface_never_rebinds_service") {
|
||||
return;
|
||||
}
|
||||
crank_metrics::bind_metric_service(crank_metrics::MetricService::McpServer)
|
||||
.expect("mcp binding");
|
||||
let config = MetricsConfig::new(
|
||||
true,
|
||||
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 9464),
|
||||
None,
|
||||
)
|
||||
.expect("loopback metrics config");
|
||||
let admin_identity = ServiceIdentity::try_new("admin-api", "0.3.1", "test").expect("identity");
|
||||
let mcp_surface = MetricsSurface::for_test(config.clone(), admin_identity)
|
||||
.expect("local renderer for another service is allowed");
|
||||
assert_eq!(
|
||||
crank_metrics::bound_metric_service(),
|
||||
Some(crank_metrics::MetricService::McpServer),
|
||||
"for_test не может менять процессный binding"
|
||||
);
|
||||
let own_identity = ServiceIdentity::try_new("mcp-server", "0.3.1", "test").expect("identity");
|
||||
let _ = MetricsSurface::for_test(config, own_identity).expect("own surface");
|
||||
assert_eq!(
|
||||
crank_metrics::bound_metric_service(),
|
||||
Some(crank_metrics::MetricService::McpServer)
|
||||
);
|
||||
let _ = mcp_surface;
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
//! Story 3.6 · AT-3.6-08 · фаза B — реальный Prometheus/OpenMetrics exporter.
|
||||
//!
|
||||
//! `TD-E1` exact sample counts реального legacy-scrape против формул проекции.
|
||||
//! `TD-E3i` OpenMetrics negotiation + `# EOF`.
|
||||
//! `TD-E4i` реальный listener: cap=2, третий scrape отвергается, permit освобождается.
|
||||
//!
|
||||
//! Каждый кейс — fresh child того же тест-бинаря: глобальный recorder/tracing
|
||||
//! dispatcher и service binding устанавливаются один раз на процесс.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
|
||||
use std::process::Command;
|
||||
use std::sync::{Arc, Barrier};
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_metrics::{ADMIN_HTTP_ROUTE_DOMAIN, HttpMethod, HttpRoute, HttpStatusClass};
|
||||
use crank_observability::{MetricsConfig, ObservabilityConfig, RedactionLimits, ServiceIdentity};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
const ROLE_ENV: &str = "CRANK_OBS_V2_ROLE";
|
||||
|
||||
fn route_to_child(role: &str, test: &str) -> bool {
|
||||
match std::env::var(ROLE_ENV).ok().as_deref() {
|
||||
Some(actual) if actual == role => false,
|
||||
Some(actual) => panic!("child for {test} runs with role {actual}, expected {role}"),
|
||||
None => {
|
||||
let output = Command::new(std::env::current_exe().expect("current test binary"))
|
||||
.args([test, "--exact", "--nocapture"])
|
||||
.env(ROLE_ENV, role)
|
||||
.output()
|
||||
.expect("re-executed exporter child");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn spawn_listener(
|
||||
service: &str,
|
||||
) -> (
|
||||
SocketAddr,
|
||||
tokio::task::JoinHandle<Result<(), crank_observability::MetricsServeError>>,
|
||||
) {
|
||||
let identity = ServiceIdentity::try_new(service, "0.3.1", "test").expect("identity");
|
||||
let lifecycle = crank_observability::init(ObservabilityConfig::new(
|
||||
identity,
|
||||
"off",
|
||||
RedactionLimits::default(),
|
||||
))
|
||||
.expect("observability lifecycle");
|
||||
let config = MetricsConfig::new(
|
||||
true,
|
||||
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
|
||||
None,
|
||||
)
|
||||
.expect("loopback metrics config");
|
||||
let server = lifecycle
|
||||
.metrics_surface(config)
|
||||
.bind()
|
||||
.await
|
||||
.expect("metrics listener");
|
||||
let address = server.local_addr().expect("listener address");
|
||||
let task = tokio::spawn(server.serve());
|
||||
(address, task)
|
||||
}
|
||||
|
||||
fn record_admin_cartesian() {
|
||||
for route in ADMIN_HTTP_ROUTE_DOMAIN {
|
||||
for method in HttpMethod::VALUES {
|
||||
for status in HttpStatusClass::VALUES {
|
||||
crank_metrics::record_http_request(
|
||||
HttpRoute::from_matched_path(route),
|
||||
HttpMethod::classify(method),
|
||||
HttpStatusClass::from_status(match *status {
|
||||
"1xx" => 101,
|
||||
"2xx" => 200,
|
||||
"3xx" => 302,
|
||||
"4xx" => 404,
|
||||
"5xx" => 500,
|
||||
_ => 0,
|
||||
}),
|
||||
Duration::from_millis(1),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn raw_get(address: SocketAddr, accept: Option<&str>) -> String {
|
||||
let mut stream = tokio::net::TcpStream::connect(address)
|
||||
.await
|
||||
.expect("listener connection");
|
||||
let accept = accept
|
||||
.map(|value| format!("Accept: {value}\r\n"))
|
||||
.unwrap_or_default();
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"GET /metrics HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n{accept}\r\n"
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.expect("metrics request");
|
||||
let mut response = Vec::new();
|
||||
stream
|
||||
.read_to_end(&mut response)
|
||||
.await
|
||||
.expect("metrics response");
|
||||
String::from_utf8(response).expect("utf-8 response")
|
||||
}
|
||||
|
||||
/// TD-E1 — реальный legacy-scrape: фактические sample counts равны формулам проекции.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn real_legacy_sample_count_matches_formulas() {
|
||||
if route_to_child("admin-api", "real_legacy_sample_count_matches_formulas") {
|
||||
return;
|
||||
}
|
||||
let (address, task) = spawn_listener("admin-api").await;
|
||||
record_admin_cartesian();
|
||||
|
||||
let response = raw_get(address, None).await;
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
|
||||
assert!(response.starts_with("HTTP/1.1 200 OK"), "{response}");
|
||||
assert!(response.contains("content-type: text/plain; version=0.0.4"));
|
||||
let routes = ADMIN_HTTP_ROUTE_DOMAIN.len();
|
||||
let counter_series = routes * HttpMethod::VALUES.len() * HttpStatusClass::VALUES.len();
|
||||
let histogram_series = routes * HttpMethod::VALUES.len();
|
||||
assert_eq!(
|
||||
response
|
||||
.lines()
|
||||
.filter(|line| line.starts_with("crank_http_requests_total{"))
|
||||
.count(),
|
||||
counter_series,
|
||||
"counter sample count обязан совпасть с проекцией admin"
|
||||
);
|
||||
assert_eq!(
|
||||
response
|
||||
.lines()
|
||||
.filter(|line| line.starts_with("crank_http_request_duration_seconds_count{"))
|
||||
.count(),
|
||||
histogram_series
|
||||
);
|
||||
assert_eq!(
|
||||
response
|
||||
.lines()
|
||||
.filter(|line| line.starts_with("crank_http_request_duration_seconds_sum{"))
|
||||
.count(),
|
||||
histogram_series
|
||||
);
|
||||
assert!(
|
||||
response.contains("route=\"/api/admin/workspaces/{workspace_id}/resources\""),
|
||||
"Resource collection обязан быть точной identity: {}",
|
||||
&response[..response.len().min(400)]
|
||||
);
|
||||
assert!(
|
||||
!response.contains("res_metrics_"),
|
||||
"raw идентификаторы не могут стать label'ом"
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-E3i — negotiation OpenMetrics 1.0 и завершающий `# EOF`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn openmetrics_negotiation_and_eof() {
|
||||
if route_to_child("mcp-server", "openmetrics_negotiation_and_eof") {
|
||||
return;
|
||||
}
|
||||
let (address, task) = spawn_listener("mcp-server").await;
|
||||
crank_metrics::record_http_request(
|
||||
HttpRoute::from_matched_path("/v1/{workspace_slug}/{agent_slug}"),
|
||||
HttpMethod::Get,
|
||||
HttpStatusClass::Success,
|
||||
Duration::from_millis(2),
|
||||
);
|
||||
|
||||
let response = raw_get(address, Some("application/openmetrics-text; version=1.0.0")).await;
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
|
||||
assert!(response.starts_with("HTTP/1.1 200 OK"), "{response}");
|
||||
assert!(response.contains("content-type: application/openmetrics-text; version=1.0.0"));
|
||||
assert!(
|
||||
response.ends_with("# EOF\n"),
|
||||
"OpenMetrics обязан завершаться # EOF"
|
||||
);
|
||||
assert!(
|
||||
response.contains("crank_http_requests_total{") && response.contains("le=\"+Inf\""),
|
||||
"OpenMetrics обязан нести те же series: {}",
|
||||
&response[..response.len().min(400)]
|
||||
);
|
||||
}
|
||||
|
||||
/// TD-E4i — реальный listener: одновременные scrape'ы обслуживаются, каждый
|
||||
/// получает ответ, permit освобождается после завершения burst'а.
|
||||
///
|
||||
/// Точный cap-oracle (ровно два допущены, третий отвергнут при двух занятых
|
||||
/// permit'ах, release) требует детерминированной точки синхронизации у permit
|
||||
/// seam'а и проверяется в
|
||||
/// `prometheus::rendering_tests::deterministic_scrape_cap_admits_exactly_two_and_releases`
|
||||
/// (`crank-observability --lib`, cfg(test)-барьер, реальный listener). Здесь
|
||||
/// намеренно НЕ утверждается «хотя бы один 503»: при быстром рендере три
|
||||
/// одновременных запроса могут быть обслужены последовательно (три честных 200),
|
||||
/// поэтому такой оракул был бы тайминговым и не доказывал бы cap.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn concurrent_scrape_cap_two_denies_third() {
|
||||
if route_to_child("admin-api", "concurrent_scrape_cap_two_denies_third") {
|
||||
return;
|
||||
}
|
||||
let (address, task) = spawn_listener("admin-api").await;
|
||||
// Тяжёлый, но permitted fixture: рендер занимает миллисекунды, поэтому
|
||||
// одновременные запросы реально перекрываются по времени.
|
||||
record_admin_cartesian();
|
||||
|
||||
let burst = 3;
|
||||
for _ in 0..4 {
|
||||
let barrier = Arc::new(Barrier::new(burst));
|
||||
let mut handles = Vec::new();
|
||||
for _ in 0..burst {
|
||||
let barrier = Arc::clone(&barrier);
|
||||
handles.push(std::thread::spawn(move || {
|
||||
let mut stream = TcpStream::connect(address).expect("thread connection");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(30)))
|
||||
.expect("read timeout");
|
||||
barrier.wait();
|
||||
use std::io::{Read, Write};
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"GET /metrics HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.expect("thread request");
|
||||
let mut response = Vec::new();
|
||||
stream.read_to_end(&mut response).expect("thread response");
|
||||
String::from_utf8_lossy(&response)
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.to_owned()
|
||||
}));
|
||||
}
|
||||
let statuses = handles
|
||||
.into_iter()
|
||||
.map(|handle| handle.join().expect("scrape thread"))
|
||||
.collect::<Vec<_>>();
|
||||
let ok = statuses.iter().filter(|line| line.contains("200")).count();
|
||||
let denied = statuses.iter().filter(|line| line.contains("503")).count();
|
||||
assert_eq!(
|
||||
ok + denied,
|
||||
burst,
|
||||
"каждый одновременный scrape обязан получить ответ: {statuses:?}"
|
||||
);
|
||||
assert!(ok >= 1, "минимум один scrape обязан пройти: {statuses:?}");
|
||||
}
|
||||
|
||||
// Permit освобождается: последовательный scrape снова отвечает 200.
|
||||
let after = raw_get(address, None).await;
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
assert!(
|
||||
after.starts_with("HTTP/1.1 200 OK"),
|
||||
"permit обязан освободиться: {}",
|
||||
&after[..after.len().min(200)]
|
||||
);
|
||||
}
|
||||
@@ -91,6 +91,12 @@ pub enum RegistryError {
|
||||
},
|
||||
#[error("operation {operation_id} is archived")]
|
||||
OperationArchived { operation_id: String },
|
||||
#[error("resource {resource_id} is archived and cannot receive new Agent bindings")]
|
||||
ResourceArchived { resource_id: String },
|
||||
#[error(
|
||||
"resource {resource_id} is revoked and cannot receive new Agent bindings or publications"
|
||||
)]
|
||||
ResourceRevoked { resource_id: String },
|
||||
#[error("operation {operation_id} has a stale base version: expected {expected}, got {actual}")]
|
||||
OperationStaleVersion {
|
||||
operation_id: String,
|
||||
@@ -202,4 +208,43 @@ pub enum RegistryError {
|
||||
ArtifactClaimInProgress,
|
||||
#[error("artifact source metadata is invalid for field {field}")]
|
||||
InvalidArtifactSource { field: &'static str },
|
||||
#[error("prompt {prompt_id} was not found in this workspace")]
|
||||
PromptNotFound { prompt_id: String },
|
||||
#[error("prompt {prompt_id} is not in Draft state")]
|
||||
PromptNotDraft { prompt_id: String },
|
||||
#[error("prompt {prompt_id} changed since it was read")]
|
||||
PromptStaleRevision { prompt_id: String },
|
||||
#[error("prompt {prompt_id} version counter overflowed")]
|
||||
PromptVersionOverflow { prompt_id: String },
|
||||
#[error("prompt {prompt_id} has invalid stored data")]
|
||||
PromptCorrupt { prompt_id: String },
|
||||
#[error("prompt {prompt_id} is archived and cannot receive new bindings")]
|
||||
PromptArchived { prompt_id: String },
|
||||
#[error("published prompt version for {prompt_id} was not found in this workspace")]
|
||||
PromptPublicationNotFound { prompt_id: String },
|
||||
#[error("prompt {prompt_id} version is already published")]
|
||||
PromptPublicationConflict { prompt_id: String },
|
||||
#[error("prompt {prompt_id} dependency at position {position} cannot be resolved")]
|
||||
PromptDependencyUnresolved {
|
||||
prompt_id: String,
|
||||
position: usize,
|
||||
resource_id: String,
|
||||
version: u32,
|
||||
},
|
||||
#[error("prompt {prompt_id} dependency at position {position} has no text representation")]
|
||||
PromptDependencyRepresentationUnsupported {
|
||||
prompt_id: String,
|
||||
position: usize,
|
||||
resource_id: String,
|
||||
version: u32,
|
||||
},
|
||||
#[error("prompt {prompt_id} dependency at position {position} is not referenced by a message")]
|
||||
PromptDependencyUnused {
|
||||
prompt_id: String,
|
||||
position: usize,
|
||||
resource_id: String,
|
||||
version: u32,
|
||||
},
|
||||
#[error("prompt {prompt_id} dependency at position {position} is unavailable")]
|
||||
PromptDependencyUnavailable { prompt_id: String, position: usize },
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
mod error;
|
||||
mod ext;
|
||||
mod migrations;
|
||||
mod model;
|
||||
pub mod model;
|
||||
mod postgres;
|
||||
|
||||
pub use error::RegistryError;
|
||||
@@ -13,15 +13,15 @@ pub use migrations::{
|
||||
|
||||
pub mod records {
|
||||
pub use crate::model::{
|
||||
AdminBootstrapContractRecord, AgentSummary, AgentVersionRecord, AppendProductEventOutcome,
|
||||
AppliedImportOperation, ApprovalRequestRecord, ArtifactBlobLifecycle, ArtifactBlobRecord,
|
||||
ArtifactClaimFinalization, ArtifactClaimFinalizeOutcome, ArtifactClaimOutcome,
|
||||
ArtifactClaimRecheckOutcome, ArtifactClaimToken, ArtifactDigest, ArtifactExpiredClaimProbe,
|
||||
ArtifactReconciliationClaim, ArtifactSourceCursor, ArtifactSourceId,
|
||||
ArtifactSourceLifecycle, ArtifactSourcePage, ArtifactSourceRecord,
|
||||
ArtifactSourceSensitivity, AuthUserRecord, DescriptorKind, DescriptorMetadata, ImportJob,
|
||||
ImportJobApplyResult, ImportJobCleanupReport, ImportJobId, ImportJobKind,
|
||||
ImportJobSourceEnvelope, ImportJobStatus, ImportPlan, ImportPlanApplication,
|
||||
AdminBootstrapContractRecord, AgentResourceBinding, AgentSummary, AgentVersionRecord,
|
||||
AppendProductEventOutcome, AppliedImportOperation, ApprovalRequestRecord,
|
||||
ArtifactBlobLifecycle, ArtifactBlobRecord, ArtifactClaimFinalization,
|
||||
ArtifactClaimFinalizeOutcome, ArtifactClaimOutcome, ArtifactClaimRecheckOutcome,
|
||||
ArtifactClaimToken, ArtifactDigest, ArtifactExpiredClaimProbe, ArtifactReconciliationClaim,
|
||||
ArtifactSourceCursor, ArtifactSourceId, ArtifactSourceLifecycle, ArtifactSourcePage,
|
||||
ArtifactSourceRecord, ArtifactSourceSensitivity, AuthUserRecord, DescriptorKind,
|
||||
DescriptorMetadata, ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId,
|
||||
ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportPlan, ImportPlanApplication,
|
||||
ImportPlanApplyCounts, ImportPlanApplyReport, ImportPlanApplyStatus,
|
||||
ImportPlanCandidateOutcome, ImportPlanCandidateReport, ImportPlanDependencyRef,
|
||||
ImportPlanId, InvitationRecord, InvocationHistoryLoss, InvocationHistoryLossCategory,
|
||||
@@ -72,15 +72,15 @@ pub mod infrastructure {
|
||||
}
|
||||
|
||||
pub use model::{
|
||||
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentStateExpectation, AgentSummary,
|
||||
AgentVersionRecord, AppendProductEventOutcome, AppendProductEventRequest,
|
||||
AppliedImportOperation, ApplyImportJobRequest, ApplyImportPlanRequest, ApplyImportPlanResult,
|
||||
ApprovalRequestRecord, ArtifactBlobLifecycle, ArtifactBlobRecord, ArtifactClaimFinalization,
|
||||
ArtifactClaimFinalizeOutcome, ArtifactClaimOutcome, ArtifactClaimRecheckOutcome,
|
||||
ArtifactClaimToken, ArtifactDigest, ArtifactExpiredClaimProbe, ArtifactReconciliationClaim,
|
||||
ArtifactSourceCursor, ArtifactSourceId, ArtifactSourceLifecycle, ArtifactSourcePage,
|
||||
ArtifactSourceRecord, ArtifactSourceSensitivity, AuthUserRecord,
|
||||
ClaimArtifactReconciliationRequest, ClaimExpiredArtifactReconciliationRequest,
|
||||
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentResourceBinding,
|
||||
AgentStateExpectation, AgentSummary, AgentVersionRecord, AppendProductEventOutcome,
|
||||
AppendProductEventRequest, AppliedImportOperation, ApplyImportJobRequest,
|
||||
ApplyImportPlanRequest, ApplyImportPlanResult, ApprovalRequestRecord, ArtifactBlobLifecycle,
|
||||
ArtifactBlobRecord, ArtifactClaimFinalization, ArtifactClaimFinalizeOutcome,
|
||||
ArtifactClaimOutcome, ArtifactClaimRecheckOutcome, ArtifactClaimToken, ArtifactDigest,
|
||||
ArtifactExpiredClaimProbe, ArtifactReconciliationClaim, ArtifactSourceCursor, ArtifactSourceId,
|
||||
ArtifactSourceLifecycle, ArtifactSourcePage, ArtifactSourceRecord, ArtifactSourceSensitivity,
|
||||
AuthUserRecord, ClaimArtifactReconciliationRequest, ClaimExpiredArtifactReconciliationRequest,
|
||||
ConsumeAdminBootstrapContractRequest, CreateAdminBootstrapContractRequest,
|
||||
CreateAgentDraftVersionRequest, CreateAgentRequest, CreateApprovalRequest,
|
||||
CreateArtifactSourceRequest, CreateImportJobRequest, CreateImportPlanRequest,
|
||||
@@ -115,4 +115,7 @@ pub use model::{
|
||||
WorkspaceMembershipRecord, WorkspaceRecord, WorkspaceUpstream, WorkspaceUpstreamId,
|
||||
YamlImportJob, YamlImportJobCompletion, YamlImportJobId, YamlImportJobStatus,
|
||||
};
|
||||
pub use postgres::{PostgresPoolConfig, PostgresPoolConfigError, PostgresRegistry};
|
||||
pub use postgres::{
|
||||
AuthorizedResourceRead, BoundResourceAdmission, PostgresPoolConfig, PostgresPoolConfigError,
|
||||
PostgresRegistry,
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
mod admin_auth_lifecycle_v8;
|
||||
mod agent_catalog_lifecycle_v9;
|
||||
mod agent_resource_bindings_v18;
|
||||
mod approval_side_effects_v10;
|
||||
mod artifact_cleanup_indexes_v13;
|
||||
mod artifact_metadata_v12;
|
||||
@@ -12,6 +13,13 @@ mod onboarding_import_selection_v15;
|
||||
mod onboarding_product_events_v11;
|
||||
mod owned_relations;
|
||||
mod platform_key_name_reuse_v6;
|
||||
mod prompt_dependencies_v23;
|
||||
mod prompt_publications_v22;
|
||||
mod prompts_v21;
|
||||
mod resource_drafts_v16;
|
||||
mod resource_publications_v17;
|
||||
mod resource_security_revocations_v19;
|
||||
mod resource_template_sources_v20;
|
||||
mod schema_guard;
|
||||
mod schema_guard_legacy_v1;
|
||||
mod schema_guard_v10;
|
||||
@@ -20,6 +28,13 @@ mod schema_guard_v12;
|
||||
mod schema_guard_v13;
|
||||
mod schema_guard_v14;
|
||||
mod schema_guard_v15;
|
||||
mod schema_guard_v16;
|
||||
mod schema_guard_v17;
|
||||
mod schema_guard_v18;
|
||||
mod schema_guard_v19;
|
||||
mod schema_guard_v20;
|
||||
mod schema_guard_v22;
|
||||
mod schema_guard_v23;
|
||||
mod schema_guard_v7;
|
||||
mod schema_guard_v8;
|
||||
mod schema_guard_v9;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "agent-resource-bindings-v18";
|
||||
pub(super) const SOURCE: &str = include_str!("agent_resource_bindings_v18.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"cb9b82183e04eb72c1f1a9ec853fcfc618f2b1c2a73edd051245890292beeb8f";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.agent_resource_bindings",
|
||||
Some(18),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(18),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
-- V18: typed exact Resource bindings Agent (Story 3.7 AC04, FR-15/FR-16).
|
||||
--
|
||||
-- Отдельная typed-таблица вместо JSON-поля: строка адресует точную
|
||||
-- Published Resource Version (`resource_publications`) для точной версии Agent
|
||||
-- (`agent_versions`). `latest`/floating версия невозможна, потому что FK указывает
|
||||
-- на конкретную строку публикации.
|
||||
--
|
||||
-- Workspace-равенство обеспечивается на ОБОИХ концах composite FK:
|
||||
-- * (workspace_id, agent_id) -> agents(workspace_id, id);
|
||||
-- * (workspace_id, resource_id, resource_version) -> resource_publications(...).
|
||||
-- Поэтому ни Agent другого workspace, ни чужая/неопубликованная Resource Version
|
||||
-- не могут стать частью binding.
|
||||
--
|
||||
-- Published Agent Version immutable: V18-local trigger function проверяет и OLD,
|
||||
-- и NEW ключ строки. Canonical V9 function при UPDATE смотрит только на NEW,
|
||||
-- поэтому перенос binding из опубликованного snapshot в Draft-версию другого
|
||||
-- Agent проходил бы через неё без отказа. V9/V17 SQL не изменяются.
|
||||
|
||||
-- Immutable guard V18: отказ, если затронута опубликованная версия Agent —
|
||||
-- либо покидаемая (OLD), либо новая (NEW).
|
||||
create function crank_reject_published_agent_resource_binding_mutation()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
declare
|
||||
bound_status text;
|
||||
begin
|
||||
if tg_op in ('UPDATE', 'DELETE') then
|
||||
select status
|
||||
into bound_status
|
||||
from agent_versions
|
||||
where agent_id = old.agent_id and version = old.agent_version;
|
||||
if bound_status = 'published' then
|
||||
raise exception 'published Agent catalog bindings are immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op in ('INSERT', 'UPDATE') then
|
||||
select status
|
||||
into bound_status
|
||||
from agent_versions
|
||||
where agent_id = new.agent_id and version = new.agent_version;
|
||||
if bound_status = 'published' then
|
||||
raise exception 'published Agent catalog bindings are immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op = 'DELETE' then
|
||||
return old;
|
||||
end if;
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create unique index agents_workspace_id_idx on agents(workspace_id, id);
|
||||
|
||||
create table agent_resource_bindings (
|
||||
workspace_id text not null,
|
||||
agent_id text not null,
|
||||
agent_version integer not null,
|
||||
resource_id text not null,
|
||||
resource_version integer not null,
|
||||
constraint agent_resource_bindings_agent_version_check check (agent_version >= 1),
|
||||
constraint agent_resource_bindings_resource_version_check check (resource_version >= 1),
|
||||
primary key (agent_id, agent_version, resource_id, resource_version),
|
||||
constraint agent_resource_bindings_agent_workspace_fkey
|
||||
foreign key (workspace_id, agent_id)
|
||||
references agents(workspace_id, id) on delete cascade,
|
||||
constraint agent_resource_bindings_agent_version_fkey
|
||||
foreign key (agent_id, agent_version)
|
||||
references agent_versions(agent_id, version) on delete cascade,
|
||||
constraint agent_resource_bindings_publication_fkey
|
||||
foreign key (workspace_id, resource_id, resource_version)
|
||||
references resource_publications(workspace_id, resource_id, version)
|
||||
on delete cascade
|
||||
);
|
||||
|
||||
create trigger agent_resource_bindings_immutable_guard
|
||||
before insert or update or delete on agent_resource_bindings
|
||||
for each row
|
||||
execute function crank_reject_published_agent_resource_binding_mutation();
|
||||
|
||||
create index agent_resource_bindings_resource_idx
|
||||
on agent_resource_bindings (workspace_id, resource_id, resource_version);
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::admin_auth_lifecycle_v8;
|
||||
use super::agent_catalog_lifecycle_v9;
|
||||
use super::agent_resource_bindings_v18;
|
||||
use super::approval_side_effects_v10;
|
||||
use super::artifact_cleanup_indexes_v13;
|
||||
use super::artifact_metadata_v12;
|
||||
@@ -10,6 +11,13 @@ use super::onboarding_import_selection_v15;
|
||||
use super::onboarding_product_events_v11;
|
||||
use super::owned_relations;
|
||||
use super::platform_key_name_reuse_v6;
|
||||
use super::prompt_dependencies_v23;
|
||||
use super::prompt_publications_v22;
|
||||
use super::prompts_v21;
|
||||
use super::resource_drafts_v16;
|
||||
use super::resource_publications_v17;
|
||||
use super::resource_security_revocations_v19;
|
||||
use super::resource_template_sources_v20;
|
||||
use super::schema_guard::{
|
||||
OWNED_RELATIONS, relation_exists, validate_required_relations, validate_schema_fingerprint,
|
||||
};
|
||||
@@ -23,12 +31,18 @@ use std::fmt;
|
||||
|
||||
mod contract;
|
||||
|
||||
mod preflight;
|
||||
|
||||
use preflight::*;
|
||||
|
||||
#[cfg(test)]
|
||||
use contract::baseline_source_digest;
|
||||
use contract::validate_descriptors;
|
||||
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
|
||||
const CURRENT_VERSION: i64 = 15;
|
||||
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
|
||||
const CURRENT_VERSION: i64 = 23;
|
||||
const IMPLEMENTED_VERSIONS: &[i64] = &[
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
|
||||
];
|
||||
const BASELINE_SOURCE_SHA256: &str =
|
||||
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
|
||||
const CONSOLIDATION_SOURCE: &str = include_str!("consolidation_v2.sql");
|
||||
@@ -273,6 +287,49 @@ impl MigrationAuthority {
|
||||
onboarding_import_selection_v15::SOURCE_SHA256,
|
||||
14,
|
||||
),
|
||||
expand_descriptor(
|
||||
16,
|
||||
resource_drafts_v16::NAME,
|
||||
resource_drafts_v16::SOURCE_SHA256,
|
||||
15,
|
||||
),
|
||||
expand_descriptor(
|
||||
17,
|
||||
resource_publications_v17::NAME,
|
||||
resource_publications_v17::SOURCE_SHA256,
|
||||
16,
|
||||
),
|
||||
expand_descriptor(
|
||||
18,
|
||||
agent_resource_bindings_v18::NAME,
|
||||
agent_resource_bindings_v18::SOURCE_SHA256,
|
||||
17,
|
||||
),
|
||||
expand_descriptor(
|
||||
19,
|
||||
resource_security_revocations_v19::NAME,
|
||||
resource_security_revocations_v19::SOURCE_SHA256,
|
||||
18,
|
||||
),
|
||||
expand_descriptor(
|
||||
20,
|
||||
resource_template_sources_v20::NAME,
|
||||
resource_template_sources_v20::SOURCE_SHA256,
|
||||
19,
|
||||
),
|
||||
expand_descriptor(21, prompts_v21::NAME, prompts_v21::SOURCE_SHA256, 20),
|
||||
expand_descriptor(
|
||||
22,
|
||||
prompt_publications_v22::NAME,
|
||||
prompt_publications_v22::SOURCE_SHA256,
|
||||
21,
|
||||
),
|
||||
expand_descriptor(
|
||||
23,
|
||||
prompt_dependencies_v23::NAME,
|
||||
prompt_dependencies_v23::SOURCE_SHA256,
|
||||
22,
|
||||
),
|
||||
]
|
||||
}
|
||||
pub fn validate_sequence() -> Result<(), MigrationError> {
|
||||
@@ -407,6 +464,31 @@ impl MigrationAuthority {
|
||||
if from < 15 {
|
||||
onboarding_import_selection_v15::apply(&mut transaction, &Self::sequence()[14]).await?;
|
||||
}
|
||||
if from < 16 {
|
||||
resource_drafts_v16::apply(&mut transaction, &Self::sequence()[15]).await?;
|
||||
}
|
||||
if from < 17 {
|
||||
resource_publications_v17::apply(&mut transaction, &Self::sequence()[16]).await?;
|
||||
}
|
||||
if from < 18 {
|
||||
agent_resource_bindings_v18::apply(&mut transaction, &Self::sequence()[17]).await?;
|
||||
}
|
||||
if from < 19 {
|
||||
resource_security_revocations_v19::apply(&mut transaction, &Self::sequence()[18])
|
||||
.await?;
|
||||
}
|
||||
if from < 20 {
|
||||
resource_template_sources_v20::apply(&mut transaction, &Self::sequence()[19]).await?;
|
||||
}
|
||||
if from < 21 {
|
||||
prompts_v21::apply(&mut transaction, &Self::sequence()[20]).await?;
|
||||
}
|
||||
if from < 22 {
|
||||
prompt_publications_v22::apply(&mut transaction, &Self::sequence()[21]).await?;
|
||||
}
|
||||
if from < 23 {
|
||||
prompt_dependencies_v23::apply(&mut transaction, &Self::sequence()[22]).await?;
|
||||
}
|
||||
match inspect(&mut transaction).await? {
|
||||
MigrationPreflight::Current {
|
||||
version: CURRENT_VERSION,
|
||||
@@ -430,407 +512,6 @@ impl MigrationAuthority {
|
||||
})
|
||||
}
|
||||
}
|
||||
async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, MigrationError> {
|
||||
let core_exists = relation_exists(connection, "__crank_core_migrations").await?;
|
||||
let canonical_exists = relation_exists(connection, "__crank_migrations").await?;
|
||||
if !core_exists {
|
||||
let mut owned_exists = canonical_exists;
|
||||
for relation in OWNED_RELATIONS {
|
||||
owned_exists |= relation_exists(connection, relation).await?;
|
||||
}
|
||||
if owned_exists {
|
||||
if is_ledgerless_legacy_baseline(connection, canonical_exists).await? {
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.core_missing",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
inspect_optional_legacy(connection).await?;
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
validate_core_ledger(connection).await?;
|
||||
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
|
||||
inspect_optional_legacy(connection).await?;
|
||||
if !canonical_exists {
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 1,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
let descriptors = MigrationAuthority::sequence();
|
||||
let rows = query("select version, name, checksum, phase, compatibility from __crank_migrations order by version limit 1025")
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if rows.is_empty() {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
let version = row
|
||||
.try_get::<i64, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if version > CURRENT_VERSION {
|
||||
return Err(MigrationError::new(
|
||||
"future_version",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"install_matching_application",
|
||||
));
|
||||
}
|
||||
let Some(expected) = descriptors.get(index) else {
|
||||
return Err(MigrationError::new(
|
||||
"future_version",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"install_matching_application",
|
||||
));
|
||||
};
|
||||
if version != expected.version {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let checksum = row
|
||||
.try_get::<String, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if checksum != expected.checksum {
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let name = row
|
||||
.try_get::<String, _>("name")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
let phase = row
|
||||
.try_get::<String, _>("phase")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
let compatibility = row
|
||||
.try_get::<String, _>("compatibility")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if name != expected.name
|
||||
|| phase != expected.phase
|
||||
|| compatibility != expected.compatibility
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.metadata",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
let current = rows
|
||||
.last()
|
||||
.and_then(|row| row.try_get::<i64, _>("version").ok())
|
||||
.ok_or_else(|| MigrationError::storage("preflight.canonical"))?;
|
||||
if rows.len() != usize::try_from(current).unwrap_or_default() {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
Some(current),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
validate_schema_fingerprint(connection, current).await?;
|
||||
if current < CURRENT_VERSION {
|
||||
Ok(MigrationPreflight::MigrationRequired {
|
||||
current,
|
||||
target: CURRENT_VERSION,
|
||||
})
|
||||
} else {
|
||||
validate_required_relations(connection, owned_relations::CONSOLIDATION, CURRENT_VERSION)
|
||||
.await?;
|
||||
validate_required_relations(
|
||||
connection,
|
||||
owned_relations::ONBOARDING_PRODUCT_EVENTS,
|
||||
CURRENT_VERSION,
|
||||
)
|
||||
.await?;
|
||||
validate_required_relations(
|
||||
connection,
|
||||
owned_relations::ARTIFACT_METADATA,
|
||||
CURRENT_VERSION,
|
||||
)
|
||||
.await?;
|
||||
validate_required_relations(connection, owned_relations::IMPORT_PLAN, CURRENT_VERSION)
|
||||
.await?;
|
||||
validate_required_relations(
|
||||
connection,
|
||||
owned_relations::ONBOARDING_IMPORT_SELECTION,
|
||||
CURRENT_VERSION,
|
||||
)
|
||||
.await?;
|
||||
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
|
||||
validate_legacy_audit(connection).await?;
|
||||
Ok(MigrationPreflight::Current { version: current })
|
||||
}
|
||||
}
|
||||
async fn is_ledgerless_legacy_baseline(
|
||||
connection: &mut PgConnection,
|
||||
canonical_exists: bool,
|
||||
) -> Result<bool, MigrationError> {
|
||||
if canonical_exists {
|
||||
return Ok(false);
|
||||
}
|
||||
for relation in [
|
||||
"__crank_migration_legacy_audit",
|
||||
"master_key_identities",
|
||||
"master_key_rotations",
|
||||
"admin_bootstrap_contracts",
|
||||
"admin_login_backoff",
|
||||
"admin_security_audit_events",
|
||||
"product_events",
|
||||
"product_event_daily_rollups",
|
||||
"onboarding_selections",
|
||||
"onboarding_import_selections",
|
||||
"artifact_blobs",
|
||||
"artifact_sources",
|
||||
] {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
for relation in owned_relations::BASELINE {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
|
||||
validate_ledgerless_baseline_fingerprint(connection).await?;
|
||||
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
|
||||
if mcp_ledger {
|
||||
return Ok(false);
|
||||
}
|
||||
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
|
||||
let extension_ledger = relation_exists(connection, "__crank_ext_migrations").await?;
|
||||
validate_ledgerless_optional_fingerprints(connection, mcp_sessions, extension_ledger).await?;
|
||||
inspect_optional_legacy_for_ledgerless_baseline(connection).await?;
|
||||
Ok(true)
|
||||
}
|
||||
async fn validate_core_ledger(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let rows = query("select version, description, checksum from __crank_core_migrations order by version limit 2")
|
||||
.fetch_all(connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
if rows.len() != 1 {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.core_cardinality",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let version = rows[0]
|
||||
.try_get::<i32, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
let checksum = rows[0]
|
||||
.try_get::<String, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
let description = rows[0]
|
||||
.try_get::<String, _>("description")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
if version != BASELINE_VERSION
|
||||
|| description != "community baseline"
|
||||
|| checksum != BASELINE_CHECKSUM
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.core",
|
||||
Some(i64::from(version)),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn inspect_optional_legacy(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
inspect_optional_legacy_with_policy(connection, false).await
|
||||
}
|
||||
async fn inspect_optional_legacy_for_ledgerless_baseline(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
inspect_optional_legacy_with_policy(connection, true).await
|
||||
}
|
||||
async fn inspect_optional_legacy_with_policy(
|
||||
connection: &mut PgConnection,
|
||||
allow_sessions_without_ledger: bool,
|
||||
) -> Result<(), MigrationError> {
|
||||
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
|
||||
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
|
||||
if mcp_ledger != mcp_sessions && !(allow_sessions_without_ledger && !mcp_ledger && mcp_sessions)
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_mcp",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
if mcp_ledger {
|
||||
let rows =
|
||||
query("select version, checksum from __crank_mcp_migrations order by version limit 2")
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_mcp"))?;
|
||||
if rows.len() != 1
|
||||
|| rows[0].try_get::<i32, _>("version").ok() != Some(1)
|
||||
|| rows[0].try_get::<String, _>("checksum").ok().as_deref()
|
||||
!= Some("mcp-transport-sessions-v1")
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_mcp",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
if relation_exists(connection, "__crank_ext_migrations").await? {
|
||||
let count = query("select count(*)::bigint as count from __crank_ext_migrations")
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
|
||||
.try_get::<i64, _>("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
if count > 1_000 {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
if count > 0 {
|
||||
let checksum_column = query(
|
||||
"select exists (
|
||||
select 1 from information_schema.columns
|
||||
where table_schema = current_schema()
|
||||
and table_name = '__crank_ext_migrations'
|
||||
and column_name = 'checksum'
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
if !checksum_column {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
let rows = query(
|
||||
"select extension_name, version, checksum
|
||||
from __crank_ext_migrations
|
||||
order by extension_name, version
|
||||
limit 1001",
|
||||
)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
for row in rows {
|
||||
let name = row
|
||||
.try_get::<String, _>("extension_name")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let version = row
|
||||
.try_get::<i32, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let checksum = row
|
||||
.try_get::<Option<String>, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let registered = MigrationAuthority::registered_extension_migrations()
|
||||
.iter()
|
||||
.any(|(registered_name, descriptor)| {
|
||||
*registered_name == name
|
||||
&& descriptor.version == u32::try_from(version).unwrap_or_default()
|
||||
&& checksum.as_deref() == Some(descriptor.checksum)
|
||||
});
|
||||
if !registered {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
Some(i64::from(version)),
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn validate_legacy_audit(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let rows = query(
|
||||
"select source, source_version, source_checksum
|
||||
from __crank_migration_legacy_audit
|
||||
order by source, source_version
|
||||
limit 1002",
|
||||
)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
if rows.len() > 1001 {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_audit",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
for row in rows {
|
||||
let source = row
|
||||
.try_get::<String, _>("source")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let version = row
|
||||
.try_get::<i64, _>("source_version")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let checksum = row
|
||||
.try_get::<String, _>("source_checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let valid = (source == "core" && version == 1 && checksum == BASELINE_CHECKSUM)
|
||||
|| (source == "mcp-session" && version == 1 && checksum == "mcp-transport-sessions-v1")
|
||||
|| source.strip_prefix("extension:").is_some_and(|name| {
|
||||
MigrationAuthority::registered_extension_migrations()
|
||||
.iter()
|
||||
.any(|(registered_name, descriptor)| {
|
||||
*registered_name == name
|
||||
&& i64::from(descriptor.version) == version
|
||||
&& descriptor.checksum == checksum
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_audit",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn create_core_ledger(
|
||||
transaction: &mut Transaction<'_, sqlx::Postgres>,
|
||||
) -> Result<(), MigrationError> {
|
||||
|
||||
@@ -133,6 +133,13 @@ pub(super) fn validate_descriptors(
|
||||
|| sha256_hex(import_plan_v14::SOURCE.as_bytes()) != import_plan_v14::SOURCE_SHA256
|
||||
|| sha256_hex(onboarding_import_selection_v15::SOURCE.as_bytes())
|
||||
!= onboarding_import_selection_v15::SOURCE_SHA256
|
||||
|| sha256_hex(resource_drafts_v16::SOURCE.as_bytes()) != resource_drafts_v16::SOURCE_SHA256
|
||||
|| sha256_hex(resource_publications_v17::SOURCE.as_bytes())
|
||||
!= resource_publications_v17::SOURCE_SHA256
|
||||
|| sha256_hex(agent_resource_bindings_v18::SOURCE.as_bytes())
|
||||
!= agent_resource_bindings_v18::SOURCE_SHA256
|
||||
|| sha256_hex(resource_security_revocations_v19::SOURCE.as_bytes())
|
||||
!= resource_security_revocations_v19::SOURCE_SHA256
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"invalid_contract",
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
//! Preflight/legacy-state inspection (вынесено из `authority.rs`, чтобы файл
|
||||
//! оставался в пределах rust-code-health); поведение не меняется.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) async fn inspect(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<MigrationPreflight, MigrationError> {
|
||||
let core_exists = relation_exists(connection, "__crank_core_migrations").await?;
|
||||
let canonical_exists = relation_exists(connection, "__crank_migrations").await?;
|
||||
if !core_exists {
|
||||
let mut owned_exists = canonical_exists;
|
||||
for relation in OWNED_RELATIONS {
|
||||
owned_exists |= relation_exists(connection, relation).await?;
|
||||
}
|
||||
if owned_exists {
|
||||
if is_ledgerless_legacy_baseline(connection, canonical_exists).await? {
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.core_missing",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
inspect_optional_legacy(connection).await?;
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
validate_core_ledger(connection).await?;
|
||||
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
|
||||
inspect_optional_legacy(connection).await?;
|
||||
if !canonical_exists {
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 1,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
let descriptors = MigrationAuthority::sequence();
|
||||
let rows = query("select version, name, checksum, phase, compatibility from __crank_migrations order by version limit 1025")
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if rows.is_empty() {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
let version = row
|
||||
.try_get::<i64, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if version > CURRENT_VERSION {
|
||||
return Err(MigrationError::new(
|
||||
"future_version",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"install_matching_application",
|
||||
));
|
||||
}
|
||||
let Some(expected) = descriptors.get(index) else {
|
||||
return Err(MigrationError::new(
|
||||
"future_version",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"install_matching_application",
|
||||
));
|
||||
};
|
||||
if version != expected.version {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let checksum = row
|
||||
.try_get::<String, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if checksum != expected.checksum {
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let name = row
|
||||
.try_get::<String, _>("name")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
let phase = row
|
||||
.try_get::<String, _>("phase")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
let compatibility = row
|
||||
.try_get::<String, _>("compatibility")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if name != expected.name
|
||||
|| phase != expected.phase
|
||||
|| compatibility != expected.compatibility
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.metadata",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
let current = rows
|
||||
.last()
|
||||
.and_then(|row| row.try_get::<i64, _>("version").ok())
|
||||
.ok_or_else(|| MigrationError::storage("preflight.canonical"))?;
|
||||
if rows.len() != usize::try_from(current).unwrap_or_default() {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
Some(current),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
validate_schema_fingerprint(connection, current).await?;
|
||||
if current < CURRENT_VERSION {
|
||||
Ok(MigrationPreflight::MigrationRequired {
|
||||
current,
|
||||
target: CURRENT_VERSION,
|
||||
})
|
||||
} else {
|
||||
for relations in [
|
||||
owned_relations::CONSOLIDATION,
|
||||
owned_relations::ONBOARDING_PRODUCT_EVENTS,
|
||||
owned_relations::ARTIFACT_METADATA,
|
||||
owned_relations::IMPORT_PLAN,
|
||||
owned_relations::ONBOARDING_IMPORT_SELECTION,
|
||||
owned_relations::RESOURCE_DRAFTS,
|
||||
owned_relations::RESOURCE_PUBLICATIONS,
|
||||
owned_relations::AGENT_RESOURCE_BINDINGS,
|
||||
owned_relations::RESOURCE_SECURITY_REVOCATIONS,
|
||||
owned_relations::RESOURCE_TEMPLATE_SOURCES,
|
||||
owned_relations::PROMPTS,
|
||||
owned_relations::PROMPT_PUBLICATIONS,
|
||||
owned_relations::PROMPT_DEPENDENCIES,
|
||||
] {
|
||||
validate_required_relations(connection, relations, CURRENT_VERSION).await?;
|
||||
}
|
||||
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
|
||||
validate_legacy_audit(connection).await?;
|
||||
Ok(MigrationPreflight::Current { version: current })
|
||||
}
|
||||
}
|
||||
pub(super) async fn is_ledgerless_legacy_baseline(
|
||||
connection: &mut PgConnection,
|
||||
canonical_exists: bool,
|
||||
) -> Result<bool, MigrationError> {
|
||||
if canonical_exists {
|
||||
return Ok(false);
|
||||
}
|
||||
for relation in [
|
||||
"__crank_migration_legacy_audit",
|
||||
"master_key_identities",
|
||||
"master_key_rotations",
|
||||
"admin_bootstrap_contracts",
|
||||
"admin_login_backoff",
|
||||
"admin_security_audit_events",
|
||||
"product_events",
|
||||
"product_event_daily_rollups",
|
||||
"onboarding_selections",
|
||||
"onboarding_import_selections",
|
||||
"artifact_blobs",
|
||||
"artifact_sources",
|
||||
] {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
for relation in owned_relations::BASELINE {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
|
||||
validate_ledgerless_baseline_fingerprint(connection).await?;
|
||||
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
|
||||
if mcp_ledger {
|
||||
return Ok(false);
|
||||
}
|
||||
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
|
||||
let extension_ledger = relation_exists(connection, "__crank_ext_migrations").await?;
|
||||
validate_ledgerless_optional_fingerprints(connection, mcp_sessions, extension_ledger).await?;
|
||||
inspect_optional_legacy_for_ledgerless_baseline(connection).await?;
|
||||
Ok(true)
|
||||
}
|
||||
pub(super) async fn validate_core_ledger(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
let rows = query("select version, description, checksum from __crank_core_migrations order by version limit 2")
|
||||
.fetch_all(connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
if rows.len() != 1 {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.core_cardinality",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let version = rows[0]
|
||||
.try_get::<i32, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
let checksum = rows[0]
|
||||
.try_get::<String, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
let description = rows[0]
|
||||
.try_get::<String, _>("description")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
if version != BASELINE_VERSION
|
||||
|| description != "community baseline"
|
||||
|| checksum != BASELINE_CHECKSUM
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.core",
|
||||
Some(i64::from(version)),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) async fn inspect_optional_legacy(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
inspect_optional_legacy_with_policy(connection, false).await
|
||||
}
|
||||
pub(super) async fn inspect_optional_legacy_for_ledgerless_baseline(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
inspect_optional_legacy_with_policy(connection, true).await
|
||||
}
|
||||
pub(super) async fn inspect_optional_legacy_with_policy(
|
||||
connection: &mut PgConnection,
|
||||
allow_sessions_without_ledger: bool,
|
||||
) -> Result<(), MigrationError> {
|
||||
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
|
||||
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
|
||||
if mcp_ledger != mcp_sessions && !(allow_sessions_without_ledger && !mcp_ledger && mcp_sessions)
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_mcp",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
if mcp_ledger {
|
||||
let rows =
|
||||
query("select version, checksum from __crank_mcp_migrations order by version limit 2")
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_mcp"))?;
|
||||
if rows.len() != 1
|
||||
|| rows[0].try_get::<i32, _>("version").ok() != Some(1)
|
||||
|| rows[0].try_get::<String, _>("checksum").ok().as_deref()
|
||||
!= Some("mcp-transport-sessions-v1")
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_mcp",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
if relation_exists(connection, "__crank_ext_migrations").await? {
|
||||
let count = query("select count(*)::bigint as count from __crank_ext_migrations")
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
|
||||
.try_get::<i64, _>("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
if count > 1_000 {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
if count > 0 {
|
||||
let checksum_column = query(
|
||||
"select exists (
|
||||
select 1 from information_schema.columns
|
||||
where table_schema = current_schema()
|
||||
and table_name = '__crank_ext_migrations'
|
||||
and column_name = 'checksum'
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
if !checksum_column {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
let rows = query(
|
||||
"select extension_name, version, checksum
|
||||
from __crank_ext_migrations
|
||||
order by extension_name, version
|
||||
limit 1001",
|
||||
)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
for row in rows {
|
||||
let name = row
|
||||
.try_get::<String, _>("extension_name")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let version = row
|
||||
.try_get::<i32, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let checksum = row
|
||||
.try_get::<Option<String>, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let registered = MigrationAuthority::registered_extension_migrations()
|
||||
.iter()
|
||||
.any(|(registered_name, descriptor)| {
|
||||
*registered_name == name
|
||||
&& descriptor.version == u32::try_from(version).unwrap_or_default()
|
||||
&& checksum.as_deref() == Some(descriptor.checksum)
|
||||
});
|
||||
if !registered {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
Some(i64::from(version)),
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) async fn validate_legacy_audit(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
let rows = query(
|
||||
"select source, source_version, source_checksum
|
||||
from __crank_migration_legacy_audit
|
||||
order by source, source_version
|
||||
limit 1002",
|
||||
)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
if rows.len() > 1001 {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_audit",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
for row in rows {
|
||||
let source = row
|
||||
.try_get::<String, _>("source")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let version = row
|
||||
.try_get::<i64, _>("source_version")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let checksum = row
|
||||
.try_get::<String, _>("source_checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let valid = (source == "core" && version == 1 && checksum == BASELINE_CHECKSUM)
|
||||
|| (source == "mcp-session" && version == 1 && checksum == "mcp-transport-sessions-v1")
|
||||
|| source.strip_prefix("extension:").is_some_and(|name| {
|
||||
MigrationAuthority::registered_extension_migrations()
|
||||
.iter()
|
||||
.any(|(registered_name, descriptor)| {
|
||||
*registered_name == name
|
||||
&& i64::from(descriptor.version) == version
|
||||
&& descriptor.checksum == checksum
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_audit",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -8,7 +8,9 @@ fn sequence_is_deterministic_and_append_only() {
|
||||
MigrationAuthority::validate_sequence().unwrap();
|
||||
assert_eq!(
|
||||
first.iter().map(|item| item.version).collect::<Vec<_>>(),
|
||||
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
|
||||
vec![
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
|
||||
]
|
||||
);
|
||||
assert_eq!(first[0].checksum, "crank-community-baseline-v1");
|
||||
assert_eq!(first[0].source_digest, BASELINE_SOURCE_SHA256);
|
||||
|
||||
@@ -33,6 +33,28 @@ pub(super) const ONBOARDING_PRODUCT_EVENTS: &[&str] = &[
|
||||
|
||||
pub(super) const ONBOARDING_IMPORT_SELECTION: &[&str] = &["onboarding_import_selections"];
|
||||
|
||||
pub(super) const RESOURCE_DRAFTS: &[&str] = &["resources", "resource_versions"];
|
||||
|
||||
pub(super) const RESOURCE_PUBLICATIONS: &[&str] = &["resource_publications"];
|
||||
|
||||
pub(super) const AGENT_RESOURCE_BINDINGS: &[&str] = &["agent_resource_bindings"];
|
||||
|
||||
pub(super) const RESOURCE_SECURITY_REVOCATIONS: &[&str] = &["resource_security_revocations"];
|
||||
|
||||
pub(super) const RESOURCE_TEMPLATE_SOURCES: &[&str] = &["resource_template_sources"];
|
||||
|
||||
pub(super) const PROMPTS: &[&str] = &[
|
||||
"prompts",
|
||||
"prompt_versions",
|
||||
"prompt_arguments",
|
||||
"prompt_messages",
|
||||
];
|
||||
|
||||
pub(super) const PROMPT_PUBLICATIONS: &[&str] = &["prompt_publications", "agent_prompt_bindings"];
|
||||
|
||||
pub(super) const PROMPT_DEPENDENCIES: &[&str] =
|
||||
&["prompt_dependencies", "prompt_message_resource_refs"];
|
||||
|
||||
pub(super) const ARTIFACT_METADATA: &[&str] = &["artifact_blobs", "artifact_sources"];
|
||||
|
||||
pub(super) const IMPORT_PLAN: &[&str] = &["import_plans", "import_plan_applications"];
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "prompt-dependencies-v23";
|
||||
pub(super) const SOURCE: &str = include_str!("prompt_dependencies_v23.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"15799d41e73021386bf1bae5952cbd34df93317cbce1a97fa8f99b3bd15cac64";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.prompt_dependencies_v23",
|
||||
Some(23),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(23),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
-- V23: version-keyed pinned Prompt dependencies (Story 3.16, FR-18).
|
||||
--
|
||||
-- `prompt_dependencies` фиксирует точную опубликованную версию Resource, которую Draft/Prompt
|
||||
-- объявил в `dependencies`, вместе с разрешёнными на момент сохранения метаданными пина
|
||||
-- (digest/kind/mime/source_class/sensitivity). Строки version-keyed: правка зависимости
|
||||
-- требует нового Draft и новой публикации, поэтому уже опубликованная версия не меняется.
|
||||
--
|
||||
-- `prompt_message_resource_refs` хранит объявленные точки вставки: упорядоченный список
|
||||
-- индексов `dependencies` у конкретного сообщения. Отдельная таблица (а не колонка в
|
||||
-- `prompt_messages`) сохраняет уже принятую схему сообщений без изменения её отпечатка.
|
||||
--
|
||||
-- Guard-функция v22 (`crank_reject_published_prompt_version_mutation`) применяется к обеим
|
||||
-- новым таблицам тем же способом, что к arguments/messages: опубликованная версия immutable.
|
||||
|
||||
create table prompt_dependencies (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
dependency_position integer not null,
|
||||
resource_id text not null,
|
||||
resource_version integer not null,
|
||||
digest text not null,
|
||||
kind text not null,
|
||||
mime_type text not null,
|
||||
source_class text not null,
|
||||
sensitivity text not null,
|
||||
constraint prompt_dependencies_pkey primary key (workspace_id, prompt_id, version, dependency_position),
|
||||
constraint prompt_dependencies_version_fkey foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
|
||||
constraint prompt_dependencies_position_check check (dependency_position between 0 and 15),
|
||||
constraint prompt_dependencies_resource_version_check check (resource_version >= 1),
|
||||
constraint prompt_dependencies_kind_check check (kind in ('text', 'json', 'binary')),
|
||||
constraint prompt_dependencies_source_class_check check (source_class in ('static', 'dynamic')),
|
||||
constraint prompt_dependencies_sensitivity_check check (
|
||||
sensitivity in ('public', 'internal', 'secret')
|
||||
),
|
||||
constraint prompt_dependencies_digest_check check (octet_length(digest) between 1 and 256),
|
||||
constraint prompt_dependencies_mime_check check (octet_length(mime_type) between 1 and 255),
|
||||
constraint prompt_dependencies_resource_id_check check (
|
||||
octet_length(resource_id) between 1 and 160
|
||||
)
|
||||
);
|
||||
|
||||
create table prompt_message_resource_refs (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
message_position integer not null,
|
||||
ref_position integer not null,
|
||||
dependency_position integer not null,
|
||||
constraint prompt_message_resource_refs_pkey primary key (
|
||||
workspace_id, prompt_id, version, message_position, ref_position
|
||||
),
|
||||
constraint prompt_message_resource_refs_version_fkey
|
||||
foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
|
||||
constraint prompt_message_resource_refs_message_check check (
|
||||
message_position between 0 and 63
|
||||
),
|
||||
constraint prompt_message_resource_refs_ref_check check (ref_position between 0 and 15),
|
||||
constraint prompt_message_resource_refs_dependency_check check (
|
||||
dependency_position between 0 and 15
|
||||
)
|
||||
);
|
||||
|
||||
create trigger prompt_dependencies_immutable_guard
|
||||
before insert or update or delete on prompt_dependencies
|
||||
for each row
|
||||
execute function crank_reject_published_prompt_version_mutation();
|
||||
|
||||
create trigger prompt_message_resource_refs_immutable_guard
|
||||
before insert or update or delete on prompt_message_resource_refs
|
||||
for each row
|
||||
execute function crank_reject_published_prompt_version_mutation();
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "prompt-publications-v22";
|
||||
pub(super) const SOURCE: &str = include_str!("prompt_publications_v22.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"b330b248f164fc6f3635739668f5ea94dc48f0e84d18f0d3dfceb92ff6c445e7";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.prompt_publications_v22",
|
||||
Some(22),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(22),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
-- V22: immutable Published Prompt Versions и typed exact Prompt bindings Agent
|
||||
-- (Story 3.13, FR-17).
|
||||
--
|
||||
-- `prompt_publications` фиксирует lifecycle-снимок публикации: точная версия,
|
||||
-- name/description/sensitivity на момент publish и `published_at`. Сама
|
||||
-- definition (arguments/messages) остаётся в version-keyed `prompt_arguments` и
|
||||
-- `prompt_messages`; поэтому снимок не дублирует байты, а отдельная guard-функция
|
||||
-- запрещает менять definition уже опубликованной версии. Archive — не revoke:
|
||||
-- immutable строки остаются.
|
||||
--
|
||||
-- `agent_prompt_bindings` — отдельная typed-таблица: строка адресует точную
|
||||
-- Published Prompt Version для точной версии Agent. Composite FK проверяет
|
||||
-- workspace на обоих концах, поэтому `latest`-версия и чужая публикация в
|
||||
-- binding попасть не могут.
|
||||
|
||||
alter table prompts
|
||||
add column latest_published_version integer,
|
||||
add constraint prompts_latest_published_version_check check (
|
||||
latest_published_version is null or latest_published_version >= 1
|
||||
);
|
||||
|
||||
create table prompt_publications (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
name text not null,
|
||||
description text not null,
|
||||
sensitivity text not null,
|
||||
published_at timestamptz not null,
|
||||
constraint prompt_publications_pkey primary key (workspace_id, prompt_id, version),
|
||||
constraint prompt_publications_version_check check (version >= 1),
|
||||
constraint prompt_publications_name_length_check check (
|
||||
octet_length(name) between 1 and 16384
|
||||
),
|
||||
constraint prompt_publications_description_length_check check (
|
||||
octet_length(description) between 1 and 16384
|
||||
),
|
||||
constraint prompt_publications_sensitivity_check check (
|
||||
sensitivity in ('public', 'internal', 'secret')
|
||||
),
|
||||
constraint prompt_publications_prompt_fkey
|
||||
foreign key (workspace_id, prompt_id)
|
||||
references prompts(workspace_id, prompt_id) on delete cascade,
|
||||
constraint prompt_publications_version_fkey
|
||||
foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version)
|
||||
on delete cascade
|
||||
);
|
||||
|
||||
-- Опубликованная definition immutable: guard смотрит и OLD, и NEW ключ строки.
|
||||
-- Удаление допускается только вместе с owning prompt (cascade), потому что archive
|
||||
-- является lifecycle-состоянием, а не удалением снимка.
|
||||
create function crank_reject_published_prompt_version_mutation()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
declare
|
||||
published boolean;
|
||||
owner_present boolean;
|
||||
begin
|
||||
if tg_op in ('UPDATE', 'DELETE') then
|
||||
select exists (
|
||||
select 1 from prompt_publications
|
||||
where workspace_id = old.workspace_id
|
||||
and prompt_id = old.prompt_id
|
||||
and version = old.version
|
||||
), exists (
|
||||
select 1 from prompts
|
||||
where workspace_id = old.workspace_id and prompt_id = old.prompt_id
|
||||
)
|
||||
into published, owner_present;
|
||||
if published and owner_present then
|
||||
raise exception 'published Prompt version is immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op in ('INSERT', 'UPDATE') then
|
||||
select exists (
|
||||
select 1 from prompt_publications
|
||||
where workspace_id = new.workspace_id
|
||||
and prompt_id = new.prompt_id
|
||||
and version = new.version
|
||||
) into published;
|
||||
if published then
|
||||
raise exception 'published Prompt version is immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op = 'DELETE' then
|
||||
return old;
|
||||
end if;
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create function crank_reject_prompt_publication_mutation()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
declare
|
||||
owner_present boolean;
|
||||
begin
|
||||
if tg_op = 'DELETE' then
|
||||
select exists (
|
||||
select 1 from prompts
|
||||
where workspace_id = old.workspace_id and prompt_id = old.prompt_id
|
||||
) into owner_present;
|
||||
if owner_present then
|
||||
raise exception 'published Prompt version is immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
return old;
|
||||
end if;
|
||||
raise exception 'published Prompt version is immutable'
|
||||
using errcode = '23514';
|
||||
end;
|
||||
$$;
|
||||
|
||||
create trigger prompt_arguments_immutable_guard
|
||||
before insert or update or delete on prompt_arguments
|
||||
for each row
|
||||
execute function crank_reject_published_prompt_version_mutation();
|
||||
|
||||
create trigger prompt_messages_immutable_guard
|
||||
before insert or update or delete on prompt_messages
|
||||
for each row
|
||||
execute function crank_reject_published_prompt_version_mutation();
|
||||
|
||||
create trigger prompt_publications_immutable_guard
|
||||
before update or delete on prompt_publications
|
||||
for each row
|
||||
execute function crank_reject_prompt_publication_mutation();
|
||||
|
||||
create table agent_prompt_bindings (
|
||||
workspace_id text not null,
|
||||
agent_id text not null,
|
||||
agent_version integer not null,
|
||||
prompt_id text not null,
|
||||
prompt_version integer not null,
|
||||
constraint agent_prompt_bindings_agent_version_check check (agent_version >= 1),
|
||||
constraint agent_prompt_bindings_prompt_version_check check (prompt_version >= 1),
|
||||
primary key (agent_id, agent_version, prompt_id),
|
||||
constraint agent_prompt_bindings_agent_workspace_fkey
|
||||
foreign key (workspace_id, agent_id)
|
||||
references agents(workspace_id, id) on delete cascade,
|
||||
constraint agent_prompt_bindings_agent_version_fkey
|
||||
foreign key (agent_id, agent_version)
|
||||
references agent_versions(agent_id, version) on delete cascade,
|
||||
constraint agent_prompt_bindings_publication_fkey
|
||||
foreign key (workspace_id, prompt_id, prompt_version)
|
||||
references prompt_publications(workspace_id, prompt_id, version)
|
||||
on delete cascade
|
||||
);
|
||||
|
||||
create function crank_reject_published_agent_prompt_binding_mutation()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
declare
|
||||
bound_status text;
|
||||
begin
|
||||
if tg_op in ('UPDATE', 'DELETE') then
|
||||
select status
|
||||
into bound_status
|
||||
from agent_versions
|
||||
where agent_id = old.agent_id and version = old.agent_version;
|
||||
if bound_status = 'published' then
|
||||
raise exception 'published Agent Prompt bindings are immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op in ('INSERT', 'UPDATE') then
|
||||
select status
|
||||
into bound_status
|
||||
from agent_versions
|
||||
where agent_id = new.agent_id and version = new.agent_version;
|
||||
if bound_status = 'published' then
|
||||
raise exception 'published Agent Prompt bindings are immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op = 'DELETE' then
|
||||
return old;
|
||||
end if;
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create trigger agent_prompt_bindings_immutable_guard
|
||||
before insert or update or delete on agent_prompt_bindings
|
||||
for each row
|
||||
execute function crank_reject_published_agent_prompt_binding_mutation();
|
||||
|
||||
create index agent_prompt_bindings_publication_idx
|
||||
on agent_prompt_bindings (workspace_id, prompt_id, prompt_version);
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "prompts-v21";
|
||||
pub(super) const SOURCE: &str = include_str!("prompts_v21.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"c62717f8eb87b249b7771c74517ce99baeaf2793bfd5fca5d15e8412112bc53e";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.prompts_v21",
|
||||
Some(21),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(21),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
-- V21: typed Prompt Draft aggregate and ordered arguments/messages (Story 3.12).
|
||||
create table prompts (
|
||||
workspace_id text not null references workspaces(id) on delete cascade,
|
||||
prompt_id text not null,
|
||||
name text not null,
|
||||
description text not null,
|
||||
status text not null default 'draft',
|
||||
sensitivity text not null,
|
||||
current_draft_version integer not null default 1,
|
||||
created_at timestamptz not null,
|
||||
updated_at timestamptz not null,
|
||||
constraint prompts_pkey primary key (workspace_id, prompt_id),
|
||||
constraint prompts_id_check check (prompt_id ~ '^prm_[A-Za-z0-9_-]{1,128}$'),
|
||||
constraint prompts_name_length_check check (octet_length(name) between 1 and 16384),
|
||||
constraint prompts_description_length_check check (octet_length(description) between 1 and 16384),
|
||||
constraint prompts_status_check check (status in ('draft', 'published', 'archived')),
|
||||
constraint prompts_sensitivity_check check (sensitivity in ('public', 'internal', 'secret')),
|
||||
constraint prompts_draft_version_check check (current_draft_version >= 1)
|
||||
);
|
||||
|
||||
create table prompt_versions (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
created_at timestamptz not null,
|
||||
constraint prompt_versions_pkey primary key (workspace_id, prompt_id, version),
|
||||
constraint prompt_versions_prompt_fkey foreign key (workspace_id, prompt_id)
|
||||
references prompts(workspace_id, prompt_id) on delete cascade,
|
||||
constraint prompt_versions_version_check check (version >= 1)
|
||||
);
|
||||
|
||||
create table prompt_arguments (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
argument_name text not null,
|
||||
argument_type text not null,
|
||||
required boolean not null,
|
||||
default_value jsonb,
|
||||
enumeration jsonb,
|
||||
position integer not null,
|
||||
constraint prompt_arguments_pkey primary key (workspace_id, prompt_id, version, argument_name),
|
||||
constraint prompt_arguments_version_fkey foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
|
||||
constraint prompt_arguments_type_check check (argument_type in ('string', 'number', 'integer', 'boolean')),
|
||||
constraint prompt_arguments_name_check check (octet_length(argument_name) between 1 and 16384),
|
||||
constraint prompt_arguments_position_check check (position >= 0),
|
||||
constraint prompt_arguments_default_size_check check (default_value is null or octet_length(default_value::text) <= 16384),
|
||||
constraint prompt_arguments_enum_size_check check (
|
||||
enumeration is null or case
|
||||
when jsonb_typeof(enumeration) = 'array'
|
||||
then jsonb_array_length(enumeration) between 1 and 64
|
||||
else false
|
||||
end
|
||||
)
|
||||
);
|
||||
|
||||
create table prompt_messages (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
position integer not null,
|
||||
role text not null,
|
||||
content text not null,
|
||||
constraint prompt_messages_pkey primary key (workspace_id, prompt_id, version, position),
|
||||
constraint prompt_messages_version_fkey foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
|
||||
constraint prompt_messages_position_check check (position between 0 and 63),
|
||||
constraint prompt_messages_role_check check (role in ('system', 'user', 'assistant')),
|
||||
constraint prompt_messages_content_check check (octet_length(content) between 1 and 16384)
|
||||
);
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "resource-drafts-v16";
|
||||
pub(super) const SOURCE: &str = include_str!("resource_drafts_v16.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"0ed07dabd37f97e212923650b80278898c4e9519cee0cda4170f6b2b2a3d92d7";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.resource_drafts",
|
||||
Some(16),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(16),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
-- V16: typed static Resource drafts (Story 3.6, D-15).
|
||||
--
|
||||
-- Байты не хранятся здесь: содержимое версии — это content-addressed blob
|
||||
-- (`artifact_blobs`) и owning-ссылка (`artifact_sources`), поэтому Resource
|
||||
-- участвует в существующем учёте владения и sweep-е (AD-10).
|
||||
-- Filesystem path, raw filename и mutable external reference намеренно
|
||||
-- отсутствуют (D-12).
|
||||
|
||||
create table resources (
|
||||
workspace_id text not null references workspaces(id) on delete cascade,
|
||||
resource_id text not null,
|
||||
uri text not null,
|
||||
name text not null,
|
||||
description text not null default '',
|
||||
status text not null default 'draft',
|
||||
kind text not null,
|
||||
current_draft_version integer not null,
|
||||
created_at timestamptz not null,
|
||||
updated_at timestamptz not null,
|
||||
constraint resources_resource_id_check check (resource_id ~ '^res_[A-Za-z0-9_-]{1,96}$'),
|
||||
constraint resources_uri_len_check check (octet_length(uri) between 10 and 200),
|
||||
constraint resources_name_len_check check (octet_length(name) between 1 and 64),
|
||||
constraint resources_description_len check (octet_length(description) <= 1024),
|
||||
constraint resources_status_check check (status in ('draft', 'published', 'archived')),
|
||||
constraint resources_kind_check check (kind in ('text', 'json', 'binary')),
|
||||
constraint resources_current_version_check check (current_draft_version >= 1),
|
||||
constraint resources_timestamps_check check (updated_at >= created_at),
|
||||
constraint resources_workspace_uri_unique unique (workspace_id, uri),
|
||||
constraint resources_workspace_name_unique unique (workspace_id, name),
|
||||
primary key (workspace_id, resource_id)
|
||||
);
|
||||
|
||||
create table resource_versions (
|
||||
workspace_id text not null,
|
||||
resource_id text not null,
|
||||
version integer not null,
|
||||
kind text not null,
|
||||
mime_type text not null,
|
||||
size_bytes bigint not null,
|
||||
digest text not null,
|
||||
sensitivity text not null,
|
||||
artifact_source_id text not null,
|
||||
created_at timestamptz not null,
|
||||
superseded_at timestamptz null,
|
||||
constraint resource_versions_version_check check (version >= 1),
|
||||
constraint resource_versions_kind_check check (kind in ('text', 'json', 'binary')),
|
||||
constraint resource_versions_mime_type_check check (
|
||||
octet_length(mime_type) between 3 and 255
|
||||
and mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'
|
||||
),
|
||||
constraint resource_versions_size_check check (size_bytes between 1 and 262144),
|
||||
constraint resource_versions_digest_check check (digest ~ '^[0-9a-f]{64}$'),
|
||||
constraint resource_versions_sensitivity_check check (
|
||||
sensitivity in ('public', 'internal', 'secret')
|
||||
),
|
||||
constraint resource_versions_source_id_check check (
|
||||
artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
|
||||
),
|
||||
constraint resource_versions_supersede_check check (
|
||||
superseded_at is null or superseded_at >= created_at
|
||||
),
|
||||
primary key (workspace_id, resource_id, version),
|
||||
constraint resource_versions_resource_fkey foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete cascade,
|
||||
constraint resource_versions_source_fkey foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id)
|
||||
);
|
||||
|
||||
-- Ровно одна текущая черновая версия на Resource: пометка прежней версии
|
||||
-- обязана произойти до вставки новой (D-15 шаг 4), индекс не ослабляется.
|
||||
create unique index resource_versions_current_draft_unique
|
||||
on resource_versions (workspace_id, resource_id)
|
||||
where superseded_at is null;
|
||||
|
||||
create index resources_workspace_created_idx
|
||||
on resources (workspace_id, created_at, resource_id);
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "resource-publications-v17";
|
||||
pub(super) const SOURCE: &str = include_str!("resource_publications_v17.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"eaefc08d25ba5ab92775dd9263ced14d927e28b558444f83ea789f1f0023c092";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.resource_publications",
|
||||
Some(17),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(17),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
Loaded 100 of 357 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user