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
424 lines
14 KiB
Rust
424 lines
14 KiB
Rust
//! Request-owned Resources trait adapter. Crank remains the only domain executor.
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use crank_core::{CorrelationContext, ExecutionLocale};
|
|
use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext};
|
|
use serde_json::Value;
|
|
|
|
use super::{AppState, rmcp_resources_projection as projection};
|
|
use crate::{
|
|
auth::VerifiedMachineCredential,
|
|
protocol::{
|
|
self, ContinuationSupport, ResourceReadCommand, ResourceTemplatesListError,
|
|
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext,
|
|
},
|
|
};
|
|
|
|
#[derive(Clone)]
|
|
struct ResourceScope {
|
|
workspace_slug: String,
|
|
agent_slug: String,
|
|
credential: VerifiedMachineCredential,
|
|
correlation: CorrelationContext,
|
|
continuation: ContinuationSupport,
|
|
locale: ExecutionLocale,
|
|
revision: String,
|
|
limit: Option<usize>,
|
|
}
|
|
|
|
impl ResourceScope {
|
|
fn new(context: ServiceContext<'_>, revision: &str, limit: Option<usize>) -> Self {
|
|
Self {
|
|
workspace_slug: context.workspace_slug.to_owned(),
|
|
agent_slug: context.agent_slug.to_owned(),
|
|
credential: context.credential.clone(),
|
|
correlation: context.correlation.clone(),
|
|
continuation: context.continuation,
|
|
locale: context.locale,
|
|
revision: revision.to_owned(),
|
|
limit,
|
|
}
|
|
}
|
|
|
|
fn context(&self) -> ServiceContext<'_> {
|
|
ServiceContext {
|
|
workspace_slug: &self.workspace_slug,
|
|
agent_slug: &self.agent_slug,
|
|
credential: &self.credential,
|
|
correlation: &self.correlation,
|
|
continuation: self.continuation,
|
|
locale: self.locale,
|
|
}
|
|
}
|
|
}
|
|
|
|
enum ReplyExtras {
|
|
List(projection::Projection),
|
|
Read(projection::Projection),
|
|
Templates(projection::Projection),
|
|
DomainError(ResourcesOutcome),
|
|
TemplateError(ResourceTemplatesListError),
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct ResourceHandler {
|
|
state: Arc<AppState>,
|
|
reply: Arc<Mutex<Option<ReplyExtras>>>,
|
|
#[cfg(test)]
|
|
domain: Option<Arc<tests::Domain>>,
|
|
}
|
|
|
|
fn internal() -> ErrorData {
|
|
ErrorData::internal_error("resource handler unavailable", None)
|
|
}
|
|
|
|
impl ResourceHandler {
|
|
fn new(state: &Arc<AppState>) -> Self {
|
|
Self {
|
|
state: state.clone(),
|
|
reply: Arc::new(Mutex::new(None)),
|
|
#[cfg(test)]
|
|
domain: None,
|
|
}
|
|
}
|
|
|
|
async fn execute(&self, scope: &ResourceScope, command: ResourcesCommand) -> ResourcesOutcome {
|
|
#[cfg(test)]
|
|
if let Some(domain) = &self.domain {
|
|
return domain.resources(command).await;
|
|
}
|
|
protocol::handle_resources_command(&self.state, scope.context(), &scope.revision, command)
|
|
.await
|
|
}
|
|
|
|
async fn execute_templates(
|
|
&self,
|
|
scope: &ResourceScope,
|
|
command: ResourcesListCommand,
|
|
) -> Result<(Vec<Value>, Option<String>), ResourceTemplatesListError> {
|
|
#[cfg(test)]
|
|
if let Some(domain) = &self.domain {
|
|
return domain.templates(command).await;
|
|
}
|
|
protocol::list_resource_templates(
|
|
&self.state,
|
|
&scope.workspace_slug,
|
|
&scope.agent_slug,
|
|
&scope.revision,
|
|
command,
|
|
)
|
|
.await
|
|
}
|
|
|
|
fn save(&self, extras: ReplyExtras) -> Result<(), ErrorData> {
|
|
let mut slot = self.reply.lock().map_err(|_| internal())?;
|
|
if slot.is_some() {
|
|
return Err(internal());
|
|
}
|
|
*slot = Some(extras);
|
|
Ok(())
|
|
}
|
|
|
|
fn take(&self) -> Option<ReplyExtras> {
|
|
self.reply.lock().ok()?.take()
|
|
}
|
|
|
|
fn scope(context: &RequestContext<RoleServer>) -> Result<ResourceScope, ErrorData> {
|
|
context
|
|
.extensions
|
|
.get::<ResourceScope>()
|
|
.cloned()
|
|
.ok_or_else(internal)
|
|
}
|
|
|
|
fn domain_error(&self, outcome: ResourcesOutcome) -> ErrorData {
|
|
let error = match &outcome {
|
|
ResourcesOutcome::Listed { .. } | ResourcesOutcome::Read { .. } => return internal(),
|
|
ResourcesOutcome::InvalidParams(detail) => {
|
|
ErrorData::invalid_params(detail.clone(), None)
|
|
}
|
|
ResourcesOutcome::NotAvailable => {
|
|
ErrorData::invalid_params("the requested resource is not available", None)
|
|
}
|
|
_ => internal(),
|
|
};
|
|
if self.save(ReplyExtras::DomainError(outcome)).is_err() {
|
|
return internal();
|
|
}
|
|
error
|
|
}
|
|
|
|
fn project_list(
|
|
&self,
|
|
outcome: ResourcesOutcome,
|
|
revision: &str,
|
|
) -> Result<ListResourcesResult, ErrorData> {
|
|
match outcome {
|
|
ResourcesOutcome::Listed {
|
|
resources,
|
|
next_cursor,
|
|
} => {
|
|
let (result, extras) =
|
|
projection::list(&resources, next_cursor, revision).map_err(|_| internal())?;
|
|
self.save(ReplyExtras::List(extras))?;
|
|
Ok(result)
|
|
}
|
|
other => Err(self.domain_error(other)),
|
|
}
|
|
}
|
|
|
|
fn project_read(
|
|
&self,
|
|
outcome: ResourcesOutcome,
|
|
revision: &str,
|
|
) -> Result<ReadResourceResponse, ErrorData> {
|
|
match outcome {
|
|
ResourcesOutcome::Read { contents } => {
|
|
let (result, extras) =
|
|
projection::read(&contents, revision).map_err(|_| internal())?;
|
|
self.save(ReplyExtras::Read(extras))?;
|
|
Ok(result.into())
|
|
}
|
|
other => Err(self.domain_error(other)),
|
|
}
|
|
}
|
|
|
|
fn project_templates(
|
|
&self,
|
|
outcome: Result<(Vec<Value>, Option<String>), ResourceTemplatesListError>,
|
|
revision: &str,
|
|
) -> Result<ListResourceTemplatesResult, ErrorData> {
|
|
match outcome {
|
|
Ok((templates, next_cursor)) => {
|
|
let (result, extras) = projection::templates(&templates, next_cursor, revision)
|
|
.map_err(|_| internal())?;
|
|
self.save(ReplyExtras::Templates(extras))?;
|
|
Ok(result)
|
|
}
|
|
Err(error) => {
|
|
let sdk_error = match error {
|
|
ResourceTemplatesListError::InvalidCursor => {
|
|
ErrorData::invalid_params("invalid resources/templates/list cursor", None)
|
|
}
|
|
ResourceTemplatesListError::Unavailable => internal(),
|
|
};
|
|
self.save(ReplyExtras::TemplateError(error))?;
|
|
Err(sdk_error)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl ServerHandler for ResourceHandler {
|
|
async fn list_resources(
|
|
&self,
|
|
request: Option<PaginatedRequestParams>,
|
|
context: RequestContext<RoleServer>,
|
|
) -> Result<ListResourcesResult, ErrorData> {
|
|
let scope = Self::scope(&context)?;
|
|
let command = ResourcesCommand::List(ResourcesListCommand {
|
|
cursor: request.unwrap_or_default().cursor,
|
|
limit: scope.limit,
|
|
});
|
|
let outcome = self.execute(&scope, command).await;
|
|
let result = self.project_list(outcome, &scope.revision);
|
|
#[cfg(test)]
|
|
super::dispatch_observer::sdk_resources_list_handler_completed();
|
|
result
|
|
}
|
|
|
|
async fn read_resource(
|
|
&self,
|
|
request: ReadResourceRequestParams,
|
|
context: RequestContext<RoleServer>,
|
|
) -> Result<ReadResourceResponse, ErrorData> {
|
|
let scope = Self::scope(&context)?;
|
|
let command = ResourcesCommand::Read(ResourceReadCommand { uri: request.uri });
|
|
let outcome = self.execute(&scope, command).await;
|
|
let result = self.project_read(outcome, &scope.revision);
|
|
#[cfg(test)]
|
|
super::dispatch_observer::sdk_resources_read_handler_completed();
|
|
result
|
|
}
|
|
|
|
async fn list_resource_templates(
|
|
&self,
|
|
request: Option<PaginatedRequestParams>,
|
|
context: RequestContext<RoleServer>,
|
|
) -> Result<ListResourceTemplatesResult, ErrorData> {
|
|
let scope = Self::scope(&context)?;
|
|
let command = ResourcesListCommand {
|
|
cursor: request.unwrap_or_default().cursor,
|
|
limit: scope.limit,
|
|
};
|
|
let outcome = self.execute_templates(&scope, command).await;
|
|
let result = self.project_templates(outcome, &scope.revision);
|
|
#[cfg(test)]
|
|
super::dispatch_observer::sdk_resources_templates_handler_completed();
|
|
result
|
|
}
|
|
}
|
|
|
|
/// Public SDK Peer construction only; the inert seed service closes before domain execution.
|
|
/// shortcut: the closed Peer cannot send callbacks, revisit if Resources require peer messaging.
|
|
async fn request_context(
|
|
handler: &ResourceHandler,
|
|
scope: ResourceScope,
|
|
) -> Result<RequestContext<RoleServer>, ErrorData> {
|
|
let ping =
|
|
serde_json::from_value(serde_json::json!({"jsonrpc":"2.0", "id":1, "method":"ping"}))
|
|
.map_err(|_| internal())?;
|
|
let (transport, receiver) = rmcp::transport::OneshotTransport::<RoleServer>::new(ping);
|
|
let revision =
|
|
serde_json::from_value(Value::String(scope.revision.clone())).map_err(|_| internal())?;
|
|
let info = InitializeRequestParams::new(
|
|
ClientCapabilities::default(),
|
|
Implementation::new("crank-resource-context", "1"),
|
|
)
|
|
.with_protocol_version(revision);
|
|
let mut running = rmcp::service::serve_directly(handler.clone(), transport, Some(info));
|
|
let peer = running.peer().clone();
|
|
running.close().await.map_err(|_| internal())?;
|
|
drop(receiver);
|
|
let mut context = RequestContext::new(RequestId::Number(1), peer);
|
|
context.extensions.insert(scope);
|
|
Ok(context)
|
|
}
|
|
|
|
fn restore_list(
|
|
handler: &ResourceHandler,
|
|
result: Result<ListResourcesResult, ErrorData>,
|
|
) -> ResourcesOutcome {
|
|
match (result, handler.take()) {
|
|
(Ok(result), Some(ReplyExtras::List(extras))) => {
|
|
let cursor = result.next_cursor.clone();
|
|
match projection::serialize(result, extras, "resources") {
|
|
Ok(mut result) => match result["resources"].take() {
|
|
Value::Array(resources) => ResourcesOutcome::Listed {
|
|
resources,
|
|
next_cursor: cursor,
|
|
},
|
|
_ => ResourcesOutcome::CatalogUnavailable,
|
|
},
|
|
Err(_) => ResourcesOutcome::CatalogUnavailable,
|
|
}
|
|
}
|
|
(Err(_), Some(ReplyExtras::DomainError(error))) => error,
|
|
_ => ResourcesOutcome::CatalogUnavailable,
|
|
}
|
|
}
|
|
|
|
fn restore_read(
|
|
handler: &ResourceHandler,
|
|
result: Result<ReadResourceResponse, ErrorData>,
|
|
) -> ResourcesOutcome {
|
|
match (result, handler.take()) {
|
|
(Ok(ReadResourceResponse::Complete(result)), Some(ReplyExtras::Read(extras))) => {
|
|
match projection::serialize(result, extras, "contents") {
|
|
Ok(mut result) => ResourcesOutcome::Read {
|
|
contents: result["contents"].take(),
|
|
},
|
|
Err(_) => ResourcesOutcome::ArtifactUnavailable,
|
|
}
|
|
}
|
|
(Err(_), Some(ReplyExtras::DomainError(error))) => error,
|
|
_ => ResourcesOutcome::ArtifactUnavailable,
|
|
}
|
|
}
|
|
|
|
fn restore_templates(
|
|
handler: &ResourceHandler,
|
|
result: Result<ListResourceTemplatesResult, ErrorData>,
|
|
) -> Result<(Vec<Value>, Option<String>), ResourceTemplatesListError> {
|
|
match (result, handler.take()) {
|
|
(Ok(result), Some(ReplyExtras::Templates(extras))) => {
|
|
let cursor = result.next_cursor.clone();
|
|
let mut result = projection::serialize(result, extras, "resourceTemplates")
|
|
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
|
match result["resourceTemplates"].take() {
|
|
Value::Array(templates) => Ok((templates, cursor)),
|
|
_ => Err(ResourceTemplatesListError::Unavailable),
|
|
}
|
|
}
|
|
(Err(_), Some(ReplyExtras::TemplateError(error))) => Err(error),
|
|
_ => Err(ResourceTemplatesListError::Unavailable),
|
|
}
|
|
}
|
|
|
|
pub(super) async fn handle(
|
|
state: &Arc<AppState>,
|
|
context: ServiceContext<'_>,
|
|
revision: &str,
|
|
command: ResourcesCommand,
|
|
) -> ResourcesOutcome {
|
|
let limit = match &command {
|
|
ResourcesCommand::List(list) => list.limit,
|
|
_ => None,
|
|
};
|
|
let handler = ResourceHandler::new(state);
|
|
let context =
|
|
match request_context(&handler, ResourceScope::new(context, revision, limit)).await {
|
|
Ok(context) => context,
|
|
Err(_) => return ResourcesOutcome::CatalogUnavailable,
|
|
};
|
|
#[cfg(test)]
|
|
super::dispatch_observer::sdk_resources_dispatch_enter();
|
|
match command {
|
|
ResourcesCommand::List(list) => {
|
|
let result = ServerHandler::list_resources(
|
|
&handler,
|
|
Some(PaginatedRequestParams::default().with_cursor(list.cursor)),
|
|
context,
|
|
)
|
|
.await;
|
|
let outcome = restore_list(&handler, result);
|
|
#[cfg(test)]
|
|
super::dispatch_observer::sdk_resources_list_handler_consumed();
|
|
outcome
|
|
}
|
|
ResourcesCommand::Read(read) => {
|
|
let result = ServerHandler::read_resource(
|
|
&handler,
|
|
ReadResourceRequestParams::new(read.uri),
|
|
context,
|
|
)
|
|
.await;
|
|
let outcome = restore_read(&handler, result);
|
|
#[cfg(test)]
|
|
super::dispatch_observer::sdk_resources_read_handler_consumed();
|
|
outcome
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(super) async fn templates(
|
|
state: &Arc<AppState>,
|
|
context: ServiceContext<'_>,
|
|
revision: &str,
|
|
command: ResourcesListCommand,
|
|
) -> Result<(Vec<Value>, Option<String>), ResourceTemplatesListError> {
|
|
let handler = ResourceHandler::new(state);
|
|
let context = request_context(
|
|
&handler,
|
|
ResourceScope::new(context, revision, command.limit),
|
|
)
|
|
.await
|
|
.map_err(|_| ResourceTemplatesListError::Unavailable)?;
|
|
#[cfg(test)]
|
|
super::dispatch_observer::sdk_resources_dispatch_enter();
|
|
let result = ServerHandler::list_resource_templates(
|
|
&handler,
|
|
Some(PaginatedRequestParams::default().with_cursor(command.cursor)),
|
|
context,
|
|
)
|
|
.await;
|
|
let outcome = restore_templates(&handler, result);
|
|
#[cfg(test)]
|
|
super::dispatch_observer::sdk_resources_templates_handler_consumed();
|
|
outcome
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "../rmcp_resources_handler_tests.rs"]
|
|
mod tests;
|