Skip to main content

agent_client_protocol_schema/
dispatch.rs

1//! Method-aware parsing of the aggregate protocol enums.
2//!
3//! These helpers select a payload type before deserializing it. They do not
4//! validate JSON-RPC envelopes, track request IDs, or assign JSON-RPC error codes.
5
6use serde::de::DeserializeOwned;
7use serde_json::Value;
8
9/// A failure to select or deserialize a method's payload.
10///
11/// Callers decide how to report this error. For example, a JSON-RPC runtime can
12/// report an invalid request payload as Invalid params, but handle an invalid
13/// response payload locally.
14#[derive(Debug)]
15#[non_exhaustive]
16pub enum MethodDispatchError {
17    /// The method is unknown or its feature is disabled.
18    UnknownMethod {
19        /// The method name supplied by the caller.
20        method: String,
21    },
22    /// The payload could not be deserialized into the selected type.
23    InvalidPayload {
24        /// The method name supplied by the caller.
25        method: String,
26        /// The underlying deserialization error.
27        ///
28        /// Its message can contain input values. Treat it as sensitive.
29        source: serde_json::Error,
30    },
31}
32
33impl std::fmt::Display for MethodDispatchError {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        match self {
36            Self::UnknownMethod { method } => write!(f, "unknown method `{method}`"),
37            Self::InvalidPayload { method, source } => {
38                write!(f, "invalid payload for method `{method}`: {source}")
39            }
40        }
41    }
42}
43
44impl std::error::Error for MethodDispatchError {
45    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
46        match self {
47            Self::UnknownMethod { .. } => None,
48            Self::InvalidPayload { source, .. } => Some(source),
49        }
50    }
51}
52
53pub(crate) fn deserialize<T: DeserializeOwned>(
54    method: &str,
55    payload: Value,
56) -> Result<T, MethodDispatchError> {
57    serde_json::from_value(payload).map_err(|source| MethodDispatchError::InvalidPayload {
58        method: method.to_owned(),
59        source,
60    })
61}
62
63// Keep incoming dispatch and outgoing method names in the same table. The
64// exhaustive match in method() also makes new enum variants require a mapping.
65macro_rules! impl_message_dispatch {
66    (
67        $enum:ident {
68            $( $(#[$meta:meta])* $variant:ident => $method:expr, )*
69        }
70        $(extension $ext_variant:ident($ext_type:ty);)?
71    ) => {
72        impl $enum {
73            /// Returns the corresponding method name.
74            #[must_use]
75            pub fn method(&self) -> &str {
76                match self {
77                    $( $(#[$meta])* Self::$variant(_) => $method, )*
78                    $(Self::$ext_variant(payload) => &payload.method,)?
79                }
80            }
81
82            /// Whether this enum recognizes the method with the enabled Cargo
83            /// features, including extensions when it has an extension variant.
84            ///
85            /// This does not check the peer's advertised capabilities.
86            #[must_use]
87            pub fn supports_method(method: &str) -> bool {
88                match method {
89                    $( $(#[$meta])* m if m == $method => true, )*
90                    _ => impl_message_dispatch!(@extension method $(, $ext_variant)?),
91                }
92            }
93
94            /// Parses parameters selected by the JSON-RPC method name.
95            ///
96            /// Use this instead of the enum's untagged `Deserialize`
97            /// implementation. Untagged deserialization selects by payload
98            /// shape, which can silently select an unrelated variant.
99            ///
100            /// The payload is passed unchanged to the selected type's
101            /// deserializer. In particular, `null` is not converted to `{}`.
102            /// Extension payloads retain their JSON value and method name.
103            ///
104            /// # Errors
105            ///
106            /// Returns [`crate::MethodDispatchError::UnknownMethod`] for an
107            /// unsupported method, or [`crate::MethodDispatchError::InvalidPayload`]
108            /// for a malformed payload.
109            pub fn from_method_and_params(
110                method: &str,
111                params: &serde_json::Value,
112            ) -> Result<Self, crate::MethodDispatchError> {
113                match method {
114                    $( $(#[$meta])* m if m == $method =>
115                        crate::dispatch::deserialize(method, params.clone()).map(Self::$variant), )*
116                    _ => {
117                        $(
118                            if method.starts_with('_') {
119                                return crate::dispatch::deserialize(method, params.clone())
120                                    .map(|mut payload: $ext_type| {
121                                        payload.method = method.into();
122                                        Self::$ext_variant(payload)
123                                    });
124                            }
125                        )?
126                        Err(crate::MethodDispatchError::UnknownMethod {
127                            method: method.to_owned(),
128                        })
129                    }
130                }
131            }
132        }
133    };
134    (@extension $method:ident, $variant:ident) => { $method.starts_with('_') };
135    (@extension $method:ident) => { false };
136}
137
138// A request and its successful response share one method mapping.
139macro_rules! impl_request_dispatch {
140    (
141        $request:ident => $response:ident {
142            $( $(#[$meta:meta])* $req_variant:ident => $resp_variant:ident: $method:expr, )*
143        }
144        extension $ext_req:ident($ext_type:ty) => $ext_resp:ident;
145    ) => {
146        impl_message_dispatch! {
147            $request {
148                $( $(#[$meta])* $req_variant => $method, )*
149            }
150            extension $ext_req($ext_type);
151        }
152
153        impl $response {
154            /// Parses a successful result using the originating request's method.
155            ///
156            /// Responses do not carry a method. The caller must retain it when
157            /// sending the request and supply it here when the response arrives.
158            /// This does not parse JSON-RPC error responses.
159            ///
160            /// Use this instead of the enum's untagged `Deserialize`
161            /// implementation, which can silently select an unrelated variant.
162            /// The result is deserialized unchanged, including `null`.
163            ///
164            /// # Errors
165            ///
166            /// Returns [`crate::MethodDispatchError::UnknownMethod`] for an
167            /// unsupported method, or [`crate::MethodDispatchError::InvalidPayload`]
168            /// for a malformed result.
169            pub fn from_method_and_result(
170                method: &str,
171                result: serde_json::Value,
172            ) -> Result<Self, crate::MethodDispatchError> {
173                match method {
174                    $( $(#[$meta])* m if m == $method =>
175                        crate::dispatch::deserialize(method, result).map(Self::$resp_variant), )*
176                    _ if method.starts_with('_') =>
177                        crate::dispatch::deserialize(method, result).map(Self::$ext_resp),
178                    _ => Err(crate::MethodDispatchError::UnknownMethod {
179                        method: method.to_owned(),
180                    }),
181                }
182            }
183        }
184    };
185}