feat: unified error type (#308)
* feat: unified error type * fix: use type id to compare transport type
This commit is contained in:
parent
c74b26b3e3
commit
e615300fea
3 changed files with 286 additions and 161 deletions
|
|
@ -3,25 +3,29 @@ use std::borrow::Cow;
|
|||
use thiserror::Error;
|
||||
|
||||
use super::*;
|
||||
use crate::model::{
|
||||
CallToolRequest, CallToolRequestParam, CallToolResult, CancelledNotification,
|
||||
CancelledNotificationParam, ClientInfo, ClientJsonRpcMessage, ClientNotification,
|
||||
ClientRequest, ClientResult, CompleteRequest, CompleteRequestParam, CompleteResult,
|
||||
GetPromptRequest, GetPromptRequestParam, GetPromptResult, InitializeRequest,
|
||||
InitializedNotification, JsonRpcResponse, ListPromptsRequest, ListPromptsResult,
|
||||
ListResourceTemplatesRequest, ListResourceTemplatesResult, ListResourcesRequest,
|
||||
ListResourcesResult, ListToolsRequest, ListToolsResult, PaginatedRequestParam,
|
||||
ProgressNotification, ProgressNotificationParam, ReadResourceRequest, ReadResourceRequestParam,
|
||||
ReadResourceResult, RequestId, RootsListChangedNotification, ServerInfo, ServerJsonRpcMessage,
|
||||
ServerNotification, ServerRequest, ServerResult, SetLevelRequest, SetLevelRequestParam,
|
||||
SubscribeRequest, SubscribeRequestParam, UnsubscribeRequest, UnsubscribeRequestParam,
|
||||
use crate::{
|
||||
model::{
|
||||
CallToolRequest, CallToolRequestParam, CallToolResult, CancelledNotification,
|
||||
CancelledNotificationParam, ClientInfo, ClientJsonRpcMessage, ClientNotification,
|
||||
ClientRequest, ClientResult, CompleteRequest, CompleteRequestParam, CompleteResult,
|
||||
GetPromptRequest, GetPromptRequestParam, GetPromptResult, InitializeRequest,
|
||||
InitializedNotification, JsonRpcResponse, ListPromptsRequest, ListPromptsResult,
|
||||
ListResourceTemplatesRequest, ListResourceTemplatesResult, ListResourcesRequest,
|
||||
ListResourcesResult, ListToolsRequest, ListToolsResult, PaginatedRequestParam,
|
||||
ProgressNotification, ProgressNotificationParam, ReadResourceRequest,
|
||||
ReadResourceRequestParam, ReadResourceResult, RequestId, RootsListChangedNotification,
|
||||
ServerInfo, ServerJsonRpcMessage, ServerNotification, ServerRequest, ServerResult,
|
||||
SetLevelRequest, SetLevelRequestParam, SubscribeRequest, SubscribeRequestParam,
|
||||
UnsubscribeRequest, UnsubscribeRequestParam,
|
||||
},
|
||||
transport::DynamicTransportError,
|
||||
};
|
||||
|
||||
/// It represents the error that may occur when serving the client.
|
||||
///
|
||||
/// if you want to handle the error, you can use `serve_client_with_ct` or `serve_client` with `Result<RunningService<RoleClient, S>, ClientError>`
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ClientInitializeError<E> {
|
||||
pub enum ClientInitializeError {
|
||||
#[error("expect initialized response, but received: {0:?}")]
|
||||
ExpectedInitResponse(Option<ServerJsonRpcMessage>),
|
||||
|
||||
|
|
@ -36,7 +40,7 @@ pub enum ClientInitializeError<E> {
|
|||
|
||||
#[error("Send message error {error}, when {context}")]
|
||||
TransportError {
|
||||
error: E,
|
||||
error: DynamicTransportError,
|
||||
context: Cow<'static, str>,
|
||||
},
|
||||
|
||||
|
|
@ -44,11 +48,23 @@ pub enum ClientInitializeError<E> {
|
|||
Cancelled,
|
||||
}
|
||||
|
||||
impl ClientInitializeError {
|
||||
pub fn transport<T: Transport<RoleClient> + 'static>(
|
||||
error: T::Error,
|
||||
context: impl Into<Cow<'static, str>>,
|
||||
) -> Self {
|
||||
Self::TransportError {
|
||||
error: DynamicTransportError::new::<T, _>(error),
|
||||
context: context.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper function to get the next message from the stream
|
||||
async fn expect_next_message<T, E>(
|
||||
async fn expect_next_message<T>(
|
||||
transport: &mut T,
|
||||
context: &str,
|
||||
) -> Result<ServerJsonRpcMessage, ClientInitializeError<E>>
|
||||
) -> Result<ServerJsonRpcMessage, ClientInitializeError>
|
||||
where
|
||||
T: Transport<RoleClient>,
|
||||
{
|
||||
|
|
@ -59,10 +75,10 @@ where
|
|||
}
|
||||
|
||||
/// Helper function to expect a response from the stream
|
||||
async fn expect_response<T, E>(
|
||||
async fn expect_response<T>(
|
||||
transport: &mut T,
|
||||
context: &str,
|
||||
) -> Result<(ServerResult, RequestId), ClientInitializeError<E>>
|
||||
) -> Result<(ServerResult, RequestId), ClientInitializeError>
|
||||
where
|
||||
T: Transport<RoleClient>,
|
||||
{
|
||||
|
|
@ -86,7 +102,7 @@ impl ServiceRole for RoleClient {
|
|||
type PeerNot = ServerNotification;
|
||||
type Info = ClientInfo;
|
||||
type PeerInfo = ServerInfo;
|
||||
type InitializeError<E> = ClientInitializeError<E>;
|
||||
type InitializeError = ClientInitializeError;
|
||||
const IS_CLIENT: bool = true;
|
||||
}
|
||||
|
||||
|
|
@ -97,10 +113,10 @@ impl<S: Service<RoleClient>> ServiceExt<RoleClient> for S {
|
|||
self,
|
||||
transport: T,
|
||||
ct: CancellationToken,
|
||||
) -> impl Future<Output = Result<RunningService<RoleClient, Self>, ClientInitializeError<E>>> + Send
|
||||
) -> impl Future<Output = Result<RunningService<RoleClient, Self>, ClientInitializeError>> + Send
|
||||
where
|
||||
T: IntoTransport<RoleClient, E, A>,
|
||||
E: std::error::Error + From<std::io::Error> + Send + Sync + 'static,
|
||||
E: std::error::Error + Send + Sync + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
serve_client_with_ct(self, transport, ct)
|
||||
|
|
@ -110,7 +126,7 @@ impl<S: Service<RoleClient>> ServiceExt<RoleClient> for S {
|
|||
pub async fn serve_client<S, T, E, A>(
|
||||
service: S,
|
||||
transport: T,
|
||||
) -> Result<RunningService<RoleClient, S>, ClientInitializeError<E>>
|
||||
) -> Result<RunningService<RoleClient, S>, ClientInitializeError>
|
||||
where
|
||||
S: Service<RoleClient>,
|
||||
T: IntoTransport<RoleClient, E, A>,
|
||||
|
|
@ -123,29 +139,28 @@ pub async fn serve_client_with_ct<S, T, E, A>(
|
|||
service: S,
|
||||
transport: T,
|
||||
ct: CancellationToken,
|
||||
) -> Result<RunningService<RoleClient, S>, ClientInitializeError<E>>
|
||||
) -> Result<RunningService<RoleClient, S>, ClientInitializeError>
|
||||
where
|
||||
S: Service<RoleClient>,
|
||||
T: IntoTransport<RoleClient, E, A>,
|
||||
E: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
tokio::select! {
|
||||
result = serve_client_with_ct_inner(service, transport, ct.clone()) => { result }
|
||||
result = serve_client_with_ct_inner(service, transport.into_transport(), ct.clone()) => { result }
|
||||
_ = ct.cancelled() => {
|
||||
Err(ClientInitializeError::Cancelled)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve_client_with_ct_inner<S, T, E, A>(
|
||||
async fn serve_client_with_ct_inner<S, T>(
|
||||
service: S,
|
||||
transport: T,
|
||||
ct: CancellationToken,
|
||||
) -> Result<RunningService<RoleClient, S>, ClientInitializeError<E>>
|
||||
) -> Result<RunningService<RoleClient, S>, ClientInitializeError>
|
||||
where
|
||||
S: Service<RoleClient>,
|
||||
T: IntoTransport<RoleClient, E, A>,
|
||||
E: std::error::Error + Send + Sync + 'static,
|
||||
T: Transport<RoleClient> + 'static,
|
||||
{
|
||||
let mut transport = transport.into_transport();
|
||||
let id_provider = <Arc<AtomicU32RequestIdProvider>>::default();
|
||||
|
|
@ -164,7 +179,7 @@ where
|
|||
))
|
||||
.await
|
||||
.map_err(|error| ClientInitializeError::TransportError {
|
||||
error,
|
||||
error: DynamicTransportError::new::<T, _>(error),
|
||||
context: "send initialize request".into(),
|
||||
})?;
|
||||
|
||||
|
|
@ -188,13 +203,9 @@ where
|
|||
extensions: Default::default(),
|
||||
}),
|
||||
);
|
||||
transport
|
||||
.send(notification)
|
||||
.await
|
||||
.map_err(|error| ClientInitializeError::TransportError {
|
||||
error,
|
||||
context: "send initialized notification".into(),
|
||||
})?;
|
||||
transport.send(notification).await.map_err(|error| {
|
||||
ClientInitializeError::transport::<T>(error, "send initialized notification")
|
||||
})?;
|
||||
let (peer, peer_rx) = Peer::new(id_provider, Some(initialize_result));
|
||||
Ok(serve_inner(service, transport, peer, peer_rx, ct))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,14 +3,18 @@ use std::borrow::Cow;
|
|||
use thiserror::Error;
|
||||
|
||||
use super::*;
|
||||
use crate::model::{
|
||||
CancelledNotification, CancelledNotificationParam, ClientInfo, ClientJsonRpcMessage,
|
||||
ClientNotification, ClientRequest, ClientResult, CreateMessageRequest,
|
||||
CreateMessageRequestParam, CreateMessageResult, ErrorData, ListRootsRequest, ListRootsResult,
|
||||
LoggingMessageNotification, LoggingMessageNotificationParam, ProgressNotification,
|
||||
ProgressNotificationParam, PromptListChangedNotification, ProtocolVersion,
|
||||
ResourceListChangedNotification, ResourceUpdatedNotification, ResourceUpdatedNotificationParam,
|
||||
ServerInfo, ServerNotification, ServerRequest, ServerResult, ToolListChangedNotification,
|
||||
use crate::{
|
||||
model::{
|
||||
CancelledNotification, CancelledNotificationParam, ClientInfo, ClientJsonRpcMessage,
|
||||
ClientNotification, ClientRequest, ClientResult, CreateMessageRequest,
|
||||
CreateMessageRequestParam, CreateMessageResult, ErrorData, ListRootsRequest,
|
||||
ListRootsResult, LoggingMessageNotification, LoggingMessageNotificationParam,
|
||||
ProgressNotification, ProgressNotificationParam, PromptListChangedNotification,
|
||||
ProtocolVersion, ResourceListChangedNotification, ResourceUpdatedNotification,
|
||||
ResourceUpdatedNotificationParam, ServerInfo, ServerNotification, ServerRequest,
|
||||
ServerResult, ToolListChangedNotification,
|
||||
},
|
||||
transport::DynamicTransportError,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
|
|
@ -26,7 +30,7 @@ impl ServiceRole for RoleServer {
|
|||
type Info = ServerInfo;
|
||||
type PeerInfo = ClientInfo;
|
||||
|
||||
type InitializeError<E> = ServerInitializeError<E>;
|
||||
type InitializeError = ServerInitializeError;
|
||||
const IS_CLIENT: bool = false;
|
||||
}
|
||||
|
||||
|
|
@ -34,7 +38,7 @@ impl ServiceRole for RoleServer {
|
|||
///
|
||||
/// if you want to handle the error, you can use `serve_server_with_ct` or `serve_server` with `Result<RunningService<RoleServer, S>, ServerError>`
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ServerInitializeError<E> {
|
||||
pub enum ServerInitializeError {
|
||||
#[error("expect initialized request, but received: {0:?}")]
|
||||
ExpectedInitializeRequest(Option<ClientJsonRpcMessage>),
|
||||
|
||||
|
|
@ -55,7 +59,7 @@ pub enum ServerInitializeError<E> {
|
|||
|
||||
#[error("Send message error {error}, when {context}")]
|
||||
TransportError {
|
||||
error: E,
|
||||
error: DynamicTransportError,
|
||||
context: Cow<'static, str>,
|
||||
},
|
||||
|
||||
|
|
@ -63,6 +67,17 @@ pub enum ServerInitializeError<E> {
|
|||
Cancelled,
|
||||
}
|
||||
|
||||
impl ServerInitializeError {
|
||||
pub fn transport<T: Transport<RoleServer> + 'static>(
|
||||
error: T::Error,
|
||||
context: impl Into<Cow<'static, str>>,
|
||||
) -> Self {
|
||||
Self::TransportError {
|
||||
error: DynamicTransportError::new::<T, _>(error),
|
||||
context: context.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub type ClientSink = Peer<RoleServer>;
|
||||
|
||||
impl<S: Service<RoleServer>> ServiceExt<RoleServer> for S {
|
||||
|
|
@ -70,7 +85,7 @@ impl<S: Service<RoleServer>> ServiceExt<RoleServer> for S {
|
|||
self,
|
||||
transport: T,
|
||||
ct: CancellationToken,
|
||||
) -> impl Future<Output = Result<RunningService<RoleServer, Self>, ServerInitializeError<E>>> + Send
|
||||
) -> impl Future<Output = Result<RunningService<RoleServer, Self>, ServerInitializeError>> + Send
|
||||
where
|
||||
T: IntoTransport<RoleServer, E, A>,
|
||||
E: std::error::Error + Send + Sync + 'static,
|
||||
|
|
@ -83,7 +98,7 @@ impl<S: Service<RoleServer>> ServiceExt<RoleServer> for S {
|
|||
pub async fn serve_server<S, T, E, A>(
|
||||
service: S,
|
||||
transport: T,
|
||||
) -> Result<RunningService<RoleServer, S>, ServerInitializeError<E>>
|
||||
) -> Result<RunningService<RoleServer, S>, ServerInitializeError>
|
||||
where
|
||||
S: Service<RoleServer>,
|
||||
T: IntoTransport<RoleServer, E, A>,
|
||||
|
|
@ -93,10 +108,10 @@ where
|
|||
}
|
||||
|
||||
/// Helper function to get the next message from the stream
|
||||
async fn expect_next_message<T, E>(
|
||||
async fn expect_next_message<T>(
|
||||
transport: &mut T,
|
||||
context: &str,
|
||||
) -> Result<ClientJsonRpcMessage, ServerInitializeError<E>>
|
||||
) -> Result<ClientJsonRpcMessage, ServerInitializeError>
|
||||
where
|
||||
T: Transport<RoleServer>,
|
||||
{
|
||||
|
|
@ -107,10 +122,10 @@ where
|
|||
}
|
||||
|
||||
/// Helper function to expect a request from the stream
|
||||
async fn expect_request<T, E>(
|
||||
async fn expect_request<T>(
|
||||
transport: &mut T,
|
||||
context: &str,
|
||||
) -> Result<(ClientRequest, RequestId), ServerInitializeError<E>>
|
||||
) -> Result<(ClientRequest, RequestId), ServerInitializeError>
|
||||
where
|
||||
T: Transport<RoleServer>,
|
||||
{
|
||||
|
|
@ -123,10 +138,10 @@ where
|
|||
}
|
||||
|
||||
/// Helper function to expect a notification from the stream
|
||||
async fn expect_notification<T, E>(
|
||||
async fn expect_notification<T>(
|
||||
transport: &mut T,
|
||||
context: &str,
|
||||
) -> Result<ClientNotification, ServerInitializeError<E>>
|
||||
) -> Result<ClientNotification, ServerInitializeError>
|
||||
where
|
||||
T: Transport<RoleServer>,
|
||||
{
|
||||
|
|
@ -142,29 +157,28 @@ pub async fn serve_server_with_ct<S, T, E, A>(
|
|||
service: S,
|
||||
transport: T,
|
||||
ct: CancellationToken,
|
||||
) -> Result<RunningService<RoleServer, S>, ServerInitializeError<E>>
|
||||
) -> Result<RunningService<RoleServer, S>, ServerInitializeError>
|
||||
where
|
||||
S: Service<RoleServer>,
|
||||
T: IntoTransport<RoleServer, E, A>,
|
||||
E: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
tokio::select! {
|
||||
result = serve_server_with_ct_inner(service, transport, ct.clone()) => { result }
|
||||
result = serve_server_with_ct_inner(service, transport.into_transport(), ct.clone()) => { result }
|
||||
_ = ct.cancelled() => {
|
||||
Err(ServerInitializeError::Cancelled)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve_server_with_ct_inner<S, T, E, A>(
|
||||
async fn serve_server_with_ct_inner<S, T>(
|
||||
service: S,
|
||||
transport: T,
|
||||
ct: CancellationToken,
|
||||
) -> Result<RunningService<RoleServer, S>, ServerInitializeError<E>>
|
||||
) -> Result<RunningService<RoleServer, S>, ServerInitializeError>
|
||||
where
|
||||
S: Service<RoleServer>,
|
||||
T: IntoTransport<RoleServer, E, A>,
|
||||
E: std::error::Error + Send + Sync + 'static,
|
||||
T: Transport<RoleServer> + 'static,
|
||||
{
|
||||
let mut transport = transport.into_transport();
|
||||
let id_provider = <Arc<AtomicU32RequestIdProvider>>::default();
|
||||
|
|
@ -196,9 +210,8 @@ where
|
|||
transport
|
||||
.send(ServerJsonRpcMessage::error(e.clone(), id))
|
||||
.await
|
||||
.map_err(|error| ServerInitializeError::TransportError {
|
||||
error,
|
||||
context: "sending error response".into(),
|
||||
.map_err(|error| {
|
||||
ServerInitializeError::transport::<T>(error, "sending error response")
|
||||
})?;
|
||||
return Err(ServerInitializeError::InitializeFailed(e));
|
||||
}
|
||||
|
|
@ -219,9 +232,8 @@ where
|
|||
id,
|
||||
))
|
||||
.await
|
||||
.map_err(|error| ServerInitializeError::TransportError {
|
||||
error,
|
||||
context: "sending initialize response".into(),
|
||||
.map_err(|error| {
|
||||
ServerInitializeError::transport::<T>(error, "sending initialize response")
|
||||
})?;
|
||||
|
||||
// Wait for initialize notification
|
||||
|
|
|
|||
|
|
@ -24,14 +24,14 @@ impl<S, R: ServiceRole> TowerHandler<S, R> {
|
|||
impl<S, R: ServiceRole> Service<R> for TowerHandler<S, R>
|
||||
where
|
||||
S: TowerService<R::PeerReq, Response = R::Resp> + Sync + Send + Clone + 'static,
|
||||
S::Error: Into<crate::Error>,
|
||||
S::Error: Into<crate::ErrorData>,
|
||||
S::Future: Send,
|
||||
{
|
||||
async fn handle_request(
|
||||
&self,
|
||||
request: R::PeerReq,
|
||||
_context: RequestContext<R>,
|
||||
) -> Result<R::Resp, crate::Error> {
|
||||
) -> Result<R::Resp, crate::ErrorData> {
|
||||
let mut service = self.service.clone();
|
||||
poll_fn(|cx| service.poll_ready(cx))
|
||||
.await
|
||||
|
|
@ -44,7 +44,7 @@ where
|
|||
&self,
|
||||
_notification: R::PeerNot,
|
||||
_context: NotificationContext<R>,
|
||||
) -> impl Future<Output = Result<(), crate::Error>> + Send + '_ {
|
||||
) -> impl Future<Output = Result<(), crate::ErrorData>> + Send + '_ {
|
||||
std::future::ready(Ok(()))
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue