CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 37m50s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 2s
CI / Deploy (pull_request) Skipped
329 lines
12 KiB
Rust
329 lines
12 KiB
Rust
//! Synthetic domain replies exercise the real trait/restore path, not wire producer coverage.
|
|
use super::*;
|
|
use serde_json::json;
|
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
|
|
|
|
type TemplateReply = Result<(Vec<Value>, Option<String>), ResourceTemplatesListError>;
|
|
|
|
#[derive(Default)]
|
|
pub(super) struct Domain {
|
|
outcome: Mutex<Option<ResourcesOutcome>>,
|
|
templates: Mutex<Option<TemplateReply>>,
|
|
calls: AtomicUsize,
|
|
pending: bool,
|
|
started: tokio::sync::Notify,
|
|
release: tokio::sync::Notify,
|
|
dropped: AtomicBool,
|
|
finished: AtomicBool,
|
|
}
|
|
struct DropWitness<'a>(&'a AtomicBool);
|
|
impl Drop for DropWitness<'_> {
|
|
fn drop(&mut self) {
|
|
self.0.store(true, SeqCst);
|
|
}
|
|
}
|
|
impl Domain {
|
|
pub(super) async fn resources(&self, command: ResourcesCommand) -> ResourcesOutcome {
|
|
self.calls.fetch_add(1, SeqCst);
|
|
match command {
|
|
ResourcesCommand::List(list) => {
|
|
assert_eq!(list.limit, Some(7));
|
|
assert_eq!(list.cursor.as_deref(), Some("opaque"));
|
|
}
|
|
ResourcesCommand::Read(read) => assert_eq!(read.uri, "crank://read"),
|
|
}
|
|
let _guard = DropWitness(&self.dropped);
|
|
if self.pending {
|
|
self.started.notify_one();
|
|
self.release.notified().await;
|
|
}
|
|
self.finished.store(true, SeqCst);
|
|
self.outcome
|
|
.lock()
|
|
.unwrap()
|
|
.take()
|
|
.expect("exactly one domain execution")
|
|
}
|
|
pub(super) async fn templates(
|
|
&self,
|
|
command: ResourcesListCommand,
|
|
) -> Result<(Vec<Value>, Option<String>), ResourceTemplatesListError> {
|
|
self.calls.fetch_add(1, SeqCst);
|
|
assert_eq!(command.limit, Some(7));
|
|
assert_eq!(command.cursor.as_deref(), Some("opaque"));
|
|
self.templates
|
|
.lock()
|
|
.unwrap()
|
|
.take()
|
|
.expect("exactly one template execution")
|
|
}
|
|
}
|
|
fn scope(revision: &str) -> ResourceScope {
|
|
ResourceScope {
|
|
workspace_slug: "fresh-workspace".into(),
|
|
agent_slug: "fresh-agent".into(),
|
|
credential: VerifiedMachineCredential {
|
|
machine_access_mode: crank_core::MachineAccessMode::StaticAgentKey,
|
|
max_security_level: crank_core::OperationSecurityLevel::Standard,
|
|
scopes: vec![crank_core::PlatformApiKeyScope::Read],
|
|
platform_api_key_id: Some("fresh-key".into()),
|
|
},
|
|
correlation: CorrelationContext::generate(),
|
|
continuation: ContinuationSupport::from_supported(false),
|
|
locale: ExecutionLocale::En,
|
|
revision: revision.into(),
|
|
limit: Some(7),
|
|
}
|
|
}
|
|
async fn state() -> Arc<AppState> {
|
|
crank_test_support::postgres_schema_url_for_task("resources_handler_local", "t_b2b08b44").await;
|
|
super::super::rmcp_tools_tests::test_state().await
|
|
}
|
|
fn handler(state: &Arc<AppState>, outcome: ResourcesOutcome) -> ResourceHandler {
|
|
let mut handler = ResourceHandler::new(state);
|
|
handler.domain = Some(Arc::new(Domain {
|
|
outcome: Mutex::new(Some(outcome)),
|
|
..Default::default()
|
|
}));
|
|
handler
|
|
}
|
|
fn page() -> Option<PaginatedRequestParams> {
|
|
Some(PaginatedRequestParams::default().with_cursor(Some("opaque".into())))
|
|
}
|
|
async fn context(handler: &ResourceHandler, revision: &str) -> RequestContext<RoleServer> {
|
|
let context = request_context(handler, scope(revision)).await.unwrap();
|
|
// Closed Peer and released seed handler ownership independently witness bootstrap cleanup.
|
|
assert!(context.peer.is_transport_closed());
|
|
assert_eq!(Arc::strong_count(&handler.reply), 1);
|
|
assert_eq!(handler.domain.as_ref().unwrap().calls.load(SeqCst), 0);
|
|
assert_eq!(
|
|
ResourceHandler::scope(&context)
|
|
.unwrap()
|
|
.credential
|
|
.platform_api_key_id
|
|
.as_ref()
|
|
.map(|id| id.as_str()),
|
|
Some("fresh-key")
|
|
);
|
|
context
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn rmcp_resources_trait_lossless_populated_results() {
|
|
let state = state().await;
|
|
for revision in ["2025-11-25", "2026-07-28"] {
|
|
let raw = vec![
|
|
json!({"uri":"crank://a", "name":"a", "description":null, "annotations":{"arbitrary":[null,{"nested":true}]}, "icons":{"not":"an SDK icon array"}, "x": [1,null]}),
|
|
json!({"uri":"crank://b","name":"b"}),
|
|
];
|
|
let h = handler(
|
|
&state,
|
|
ResourcesOutcome::Listed {
|
|
resources: raw.clone(),
|
|
next_cursor: Some("next".into()),
|
|
},
|
|
);
|
|
let c = context(&h, revision).await;
|
|
let mut result = ServerHandler::list_resources(&h, page(), c).await.unwrap();
|
|
// Mutating a known field demonstrates the actual typed result is consumed, not old success.
|
|
result.resources[0].title = Some("from-sdk-result".into());
|
|
result.next_cursor = Some("typed-cursor".into());
|
|
match restore_list(&h, Ok(result)) {
|
|
ResourcesOutcome::Listed {
|
|
resources,
|
|
next_cursor,
|
|
} => {
|
|
let mut expected = raw;
|
|
expected[0]["title"] = json!("from-sdk-result");
|
|
assert_eq!(resources, expected);
|
|
assert_eq!(next_cursor.as_deref(), Some("typed-cursor"));
|
|
}
|
|
_ => panic!("list restore failed"),
|
|
}
|
|
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
|
let text = serde_json::to_string_pretty(&json!({"exact":true})).unwrap();
|
|
let raw = json!([{"uri":"crank://text", "text":text, "mimeType":null, "annotations": [null,42], "x":null}, {"uri":"crank://blob", "blob":"AAEC/w==", "icons":false}]);
|
|
let h = handler(
|
|
&state,
|
|
ResourcesOutcome::Read {
|
|
contents: raw.clone(),
|
|
},
|
|
);
|
|
let c = context(&h, revision).await;
|
|
let result =
|
|
ServerHandler::read_resource(&h, ReadResourceRequestParams::new("crank://read"), c)
|
|
.await;
|
|
match restore_read(&h, result) {
|
|
ResourcesOutcome::Read { contents } => assert_eq!(contents, raw),
|
|
_ => panic!("read restore failed"),
|
|
}
|
|
let raw = vec![
|
|
json!({"uriTemplate":"crank://{id}", "name":"template", "parameters":{"id":{"type":"string","default":null}}, "annotations":false, "icons":[{"unknown":null}], "description":null, "x":{"nested":[null]}}),
|
|
];
|
|
let mut h = ResourceHandler::new(&state);
|
|
h.domain = Some(Arc::new(Domain {
|
|
templates: Mutex::new(Some(Ok((raw.clone(), Some("next".into()))))),
|
|
..Default::default()
|
|
}));
|
|
let c = context(&h, revision).await;
|
|
let result = ServerHandler::list_resource_templates(&h, page(), c).await;
|
|
let (actual, cursor) = restore_templates(&h, result).ok().unwrap();
|
|
assert_eq!(actual, raw);
|
|
assert_eq!(cursor.as_deref(), Some("next"));
|
|
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn rmcp_resources_trait_errors_and_broken_projection_fail_closed() {
|
|
let state = state().await;
|
|
let contract = crate::tool_error::control_tool_error_contract(
|
|
crate::tool_error::McpControlError::CatalogRevisionChanged,
|
|
"request",
|
|
"trace",
|
|
ExecutionLocale::En,
|
|
);
|
|
for outcome in [
|
|
ResourcesOutcome::InvalidParams("exact detail".into()),
|
|
ResourcesOutcome::NotAvailable,
|
|
ResourcesOutcome::CatalogUnavailable,
|
|
ResourcesOutcome::ArtifactUnavailable,
|
|
ResourcesOutcome::ExecutionError(contract.clone()),
|
|
] {
|
|
let expected = std::mem::discriminant(&outcome);
|
|
let h = handler(&state, outcome);
|
|
let c = context(&h, "2026-07-28").await;
|
|
let result =
|
|
ServerHandler::read_resource(&h, ReadResourceRequestParams::new("crank://read"), c)
|
|
.await;
|
|
assert!(result.is_err());
|
|
let actual = restore_read(&h, result);
|
|
assert_eq!(std::mem::discriminant(&actual), expected);
|
|
match actual {
|
|
ResourcesOutcome::ExecutionError(actual) => assert_eq!(actual, contract),
|
|
ResourcesOutcome::InvalidParams(detail) => assert_eq!(detail, "exact detail"),
|
|
_ => {}
|
|
}
|
|
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
|
}
|
|
for error in [
|
|
ResourceTemplatesListError::InvalidCursor,
|
|
ResourceTemplatesListError::Unavailable,
|
|
] {
|
|
let expected = std::mem::discriminant(&error);
|
|
let mut h = ResourceHandler::new(&state);
|
|
h.domain = Some(Arc::new(Domain {
|
|
templates: Mutex::new(Some(Err(error))),
|
|
..Default::default()
|
|
}));
|
|
let c = context(&h, "2026-07-28").await;
|
|
let result = ServerHandler::list_resource_templates(&h, page(), c).await;
|
|
assert!(result.is_err());
|
|
assert_eq!(
|
|
std::mem::discriminant(&restore_templates(&h, result).err().unwrap()),
|
|
expected
|
|
);
|
|
}
|
|
let h = handler(
|
|
&state,
|
|
ResourcesOutcome::Listed {
|
|
resources: vec![json!({"name":"missing-required-uri"})],
|
|
next_cursor: None,
|
|
},
|
|
);
|
|
let c = context(&h, "2026-07-28").await;
|
|
let result = ServerHandler::list_resources(&h, page(), c).await;
|
|
assert!(result.is_err());
|
|
assert!(matches!(
|
|
restore_list(&h, result),
|
|
ResourcesOutcome::CatalogUnavailable
|
|
));
|
|
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
|
|
let h = handler(
|
|
&state,
|
|
ResourcesOutcome::Listed {
|
|
resources: vec![json!({"uri":"crank://a","name":"a"})],
|
|
next_cursor: None,
|
|
},
|
|
);
|
|
let mut c = context(&h, "2026-07-28").await;
|
|
c.extensions = Default::default();
|
|
assert!(ServerHandler::list_resources(&h, page(), c).await.is_err());
|
|
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 0);
|
|
let c = context(&h, "2026-07-28").await;
|
|
let mut result = ServerHandler::list_resources(&h, page(), c).await.unwrap();
|
|
result.resources.clear();
|
|
assert!(matches!(
|
|
restore_list(&h, Ok(result)),
|
|
ResourcesOutcome::CatalogUnavailable
|
|
));
|
|
// An impossible domain variant or unpaired SDK Err cannot become a saved success.
|
|
let h = handler(
|
|
&state,
|
|
ResourcesOutcome::Read {
|
|
contents: json!([]),
|
|
},
|
|
);
|
|
let c = context(&h, "2026-07-28").await;
|
|
let result = ServerHandler::list_resources(&h, page(), c).await;
|
|
assert!(result.is_err());
|
|
assert!(matches!(
|
|
restore_list(&h, result),
|
|
ResourcesOutcome::CatalogUnavailable
|
|
));
|
|
assert!(matches!(
|
|
restore_read(&h, Err(internal())),
|
|
ResourcesOutcome::ArtifactUnavailable
|
|
));
|
|
let h = handler(
|
|
&state,
|
|
ResourcesOutcome::Listed {
|
|
resources: vec![
|
|
json!({"uri":"crank://a","name":"a","x":1}),
|
|
json!({"uri":"crank://b","name":"b","x":2}),
|
|
],
|
|
next_cursor: None,
|
|
},
|
|
);
|
|
let c = context(&h, "2026-07-28").await;
|
|
let mut result = ServerHandler::list_resources(&h, page(), c).await.unwrap();
|
|
result.resources.swap(0, 1);
|
|
assert!(matches!(
|
|
restore_list(&h, Ok(result)),
|
|
ResourcesOutcome::CatalogUnavailable
|
|
));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn rmcp_resources_parent_drop_releases_domain_future_without_detached_execution() {
|
|
let state = state().await;
|
|
let mut h = ResourceHandler::new(&state);
|
|
let domain = Arc::new(Domain {
|
|
pending: true,
|
|
..Default::default()
|
|
});
|
|
h.domain = Some(domain.clone());
|
|
let c = context(&h, "2026-07-28").await;
|
|
let mut parent = Box::pin(ServerHandler::read_resource(
|
|
&h,
|
|
ReadResourceRequestParams::new("crank://read"),
|
|
c,
|
|
));
|
|
tokio::select! { _ = &mut parent => panic!("domain should be waiting"), _ = domain.started.notified() => {} }
|
|
assert!(!domain.dropped.load(SeqCst));
|
|
drop(parent);
|
|
assert!(
|
|
domain.dropped.load(SeqCst),
|
|
"owned domain future must be dropped synchronously"
|
|
);
|
|
domain.release.notify_one();
|
|
tokio::task::yield_now().await;
|
|
assert!(
|
|
!domain.finished.load(SeqCst),
|
|
"no detached future may resume execution"
|
|
);
|
|
assert!(h.take().is_none());
|
|
assert_eq!(domain.calls.load(SeqCst), 1);
|
|
assert_eq!(Arc::strong_count(&domain), 2);
|
|
}
|