Skip to main content

agent_client_protocol/util/
typed.rs

1//! Utilities for pattern matching on untyped JSON-RPC messages.
2//!
3//! When handling [`UntypedMessage`]s, you can use [`MatchDispatch`] for simple parsing
4//! or [`MatchDispatchFrom`] when you need peer-aware transforms (e.g., unwrapping
5//! proxy envelopes).
6//!
7//! # When to use which
8//!
9//! - **[`MatchDispatchFrom`]**: Preferred over implementing [`HandleDispatchFrom`] directly.
10//!   Use this in connection handlers when you need to match on message types with
11//!   proper peer-aware transforms (e.g., unwrapping `SuccessorMessage` envelopes).
12//!
13//! - **[`MatchDispatch`]**: Use this when you already have an unwrapped message and
14//!   just need to parse it, such as inside a [`MatchDispatchFrom`] callback or when
15//!   processing messages that don't need peer transforms.
16//!
17//! [`HandleDispatchFrom`]: crate::HandleDispatchFrom
18//! [`UntypedMessage`]: crate::UntypedMessage
19
20use crate::{
21    ConnectionTo, Dispatch, HandleDispatchFrom, Handled, JsonRpcNotification, JsonRpcRequest,
22    JsonRpcResponse, Responder, ResponseRouter,
23    role::{HasPeer, Role, handle_incoming_dispatch},
24};
25
26fn preserve_retry(
27    state: Result<Handled<Dispatch>, crate::Error>,
28    prior_retry: bool,
29) -> Result<Handled<Dispatch>, crate::Error> {
30    state.map(|state| match state {
31        Handled::Yes => Handled::Yes,
32        Handled::No { message, retry } => Handled::No {
33            message,
34            retry: prior_retry | retry,
35        },
36    })
37}
38
39/// Role-agnostic helper for pattern-matching on untyped JSON-RPC messages.
40///
41/// Use this when you already have an unwrapped message and just need to parse it,
42/// such as inside a [`MatchDispatchFrom`] callback or when processing messages
43/// that don't need peer transforms.
44///
45/// For connection handlers where you need proper peer-aware transforms,
46/// use [`MatchDispatchFrom`] instead.
47///
48/// # Example
49///
50/// ```
51/// # use agent_client_protocol::Dispatch;
52/// # use agent_client_protocol::v1::schema::{AgentCapabilities, InitializeRequest, InitializeResponse};
53/// # use agent_client_protocol::util::MatchDispatch;
54/// # async fn example(message: Dispatch) -> Result<(), agent_client_protocol::Error> {
55/// MatchDispatch::new(message)
56///     .if_request(|req: InitializeRequest, responder: agent_client_protocol::Responder<InitializeResponse>| async move {
57///         let response = InitializeResponse::new(req.protocol_version)
58///             .agent_capabilities(AgentCapabilities::new());
59///         responder.respond(response)
60///     })
61///     .await
62///     .otherwise(|message| async move {
63///         match message {
64///             Dispatch::Request(_, responder) => {
65///                 responder.respond_with_error(agent_client_protocol::Error::method_not_found())
66///             }
67///             Dispatch::Notification(_) | Dispatch::Response(_, _) => Ok(()),
68///         }
69///     })
70///     .await
71/// # }
72/// ```
73#[must_use]
74#[derive(Debug)]
75pub struct MatchDispatch {
76    state: Result<Handled<Dispatch>, crate::Error>,
77}
78
79impl MatchDispatch {
80    /// Create a new pattern matcher for the given message.
81    pub fn new(message: Dispatch) -> Self {
82        Self {
83            state: Ok(Handled::No {
84                message,
85                retry: false,
86            }),
87        }
88    }
89
90    /// Try to handle the message as a request of type `Req`.
91    ///
92    /// If the message is a request for one of `Req`'s methods, it is parsed and
93    /// `op` is called with the request and a typed responder. If the method
94    /// matches but the params do not parse, matching stops with the parse
95    /// error. Other messages, and messages already handled by a previous call,
96    /// pass through unchanged.
97    pub async fn if_request<Req: JsonRpcRequest, H>(
98        mut self,
99        op: impl AsyncFnOnce(Req, Responder<Req::Response>) -> Result<H, crate::Error>,
100    ) -> Self
101    where
102        H: crate::IntoHandled<(Req, Responder<Req::Response>)>,
103    {
104        if let Ok(Handled::No {
105            message: dispatch,
106            retry,
107        }) = self.state
108        {
109            self.state = match dispatch {
110                Dispatch::Request(untyped_request, untyped_responder) => {
111                    if Req::matches_method(untyped_request.method()) {
112                        match Req::parse_message(untyped_request.method(), untyped_request.params())
113                        {
114                            Ok(typed_request) => {
115                                let typed_responder = untyped_responder.cast();
116                                match op(typed_request, typed_responder).await {
117                                    Ok(result) => match result.into_handled() {
118                                        Handled::Yes => Ok(Handled::Yes),
119                                        Handled::No {
120                                            message: (request, responder),
121                                            retry: request_retry,
122                                        } => match request.to_untyped_message() {
123                                            Ok(untyped) => Ok(Handled::No {
124                                                message: Dispatch::Request(
125                                                    untyped,
126                                                    responder.erase_to_json(),
127                                                ),
128                                                retry: retry | request_retry,
129                                            }),
130                                            Err(err) => Err(err),
131                                        },
132                                    },
133                                    Err(err) => Err(err),
134                                }
135                            }
136                            Err(err) => Err(err),
137                        }
138                    } else {
139                        Ok(Handled::No {
140                            message: Dispatch::Request(untyped_request, untyped_responder),
141                            retry,
142                        })
143                    }
144                }
145                Dispatch::Notification(_) | Dispatch::Response(_, _) => Ok(Handled::No {
146                    message: dispatch,
147                    retry,
148                }),
149            };
150        }
151        self
152    }
153
154    /// Try to handle the message as a notification of type `N`.
155    ///
156    /// If the message is a notification for one of `N`'s methods, it is parsed
157    /// and `op` is called with the notification. If the method matches but the
158    /// params do not parse, matching stops with the parse error. Other
159    /// messages, and messages already handled by a previous call, pass through
160    /// unchanged.
161    pub async fn if_notification<N: JsonRpcNotification, H>(
162        mut self,
163        op: impl AsyncFnOnce(N) -> Result<H, crate::Error>,
164    ) -> Self
165    where
166        H: crate::IntoHandled<N>,
167    {
168        if let Ok(Handled::No {
169            message: dispatch,
170            retry,
171        }) = self.state
172        {
173            self.state = match dispatch {
174                Dispatch::Notification(untyped_notification) => {
175                    if N::matches_method(untyped_notification.method()) {
176                        match N::parse_message(
177                            untyped_notification.method(),
178                            untyped_notification.params(),
179                        ) {
180                            Ok(typed_notification) => match op(typed_notification).await {
181                                Ok(result) => match result.into_handled() {
182                                    Handled::Yes => Ok(Handled::Yes),
183                                    Handled::No {
184                                        message: notification,
185                                        retry: notification_retry,
186                                    } => match notification.to_untyped_message() {
187                                        Ok(untyped) => Ok(Handled::No {
188                                            message: Dispatch::Notification(untyped),
189                                            retry: retry | notification_retry,
190                                        }),
191                                        Err(err) => Err(err),
192                                    },
193                                },
194                                Err(err) => Err(err),
195                            },
196                            Err(err) => Err(err),
197                        }
198                    } else {
199                        Ok(Handled::No {
200                            message: Dispatch::Notification(untyped_notification),
201                            retry,
202                        })
203                    }
204                }
205                Dispatch::Request(_, _) | Dispatch::Response(_, _) => Ok(Handled::No {
206                    message: dispatch,
207                    retry,
208                }),
209            };
210        }
211        self
212    }
213
214    /// Try to handle the message as a typed `Dispatch<R, N>`.
215    ///
216    /// This attempts to parse the message as either request type `R` or notification type `N`,
217    /// providing a typed `Dispatch` to the handler if successful.
218    pub async fn if_dispatch<R: JsonRpcRequest, N: JsonRpcNotification, H>(
219        mut self,
220        op: impl AsyncFnOnce(Dispatch<R, N>) -> Result<H, crate::Error>,
221    ) -> Self
222    where
223        H: crate::IntoHandled<Dispatch<R, N>>,
224    {
225        if let Ok(Handled::No {
226            message: dispatch,
227            retry,
228        }) = self.state
229        {
230            self.state = match dispatch.into_typed_dispatch::<R, N>() {
231                Ok(Ok(typed_dispatch)) => match op(typed_dispatch).await {
232                    Ok(result) => match result.into_handled() {
233                        Handled::Yes => Ok(Handled::Yes),
234                        Handled::No {
235                            message: typed_dispatch,
236                            retry: message_retry,
237                        } => {
238                            let untyped = match typed_dispatch {
239                                Dispatch::Request(request, responder) => {
240                                    match request.to_untyped_message() {
241                                        Ok(untyped) => {
242                                            Dispatch::Request(untyped, responder.erase_to_json())
243                                        }
244                                        Err(err) => return Self { state: Err(err) },
245                                    }
246                                }
247                                Dispatch::Notification(notification) => {
248                                    match notification.to_untyped_message() {
249                                        Ok(untyped) => Dispatch::Notification(untyped),
250                                        Err(err) => return Self { state: Err(err) },
251                                    }
252                                }
253                                Dispatch::Response(result, router) => {
254                                    let method = router.method();
255                                    let untyped_result = match result {
256                                        Ok(response) => match response.into_json(method) {
257                                            Ok(json) => Ok(json),
258                                            Err(err) => return Self { state: Err(err) },
259                                        },
260                                        Err(err) => Err(err),
261                                    };
262                                    Dispatch::Response(untyped_result, router.erase_to_json())
263                                }
264                            };
265                            Ok(Handled::No {
266                                message: untyped,
267                                retry: retry | message_retry,
268                            })
269                        }
270                    },
271                    Err(err) => Err(err),
272                },
273                Ok(Err(dispatch)) => Ok(Handled::No {
274                    message: dispatch,
275                    retry,
276                }),
277                Err(err) => Err(err),
278            };
279        }
280        self
281    }
282
283    /// Try to handle the message as a response to a request of type `Req`.
284    ///
285    /// If the message is a `Response` variant and the method matches `Req`, the handler
286    /// is called with the result (which may be `Ok` or `Err`) and a typed response context.
287    /// Use this when you need to handle both success and error responses.
288    ///
289    /// For handling only successful responses, see [`if_ok_response_to`](Self::if_ok_response_to).
290    pub async fn if_response_to<Req: JsonRpcRequest, H>(
291        mut self,
292        op: impl AsyncFnOnce(
293            Result<Req::Response, crate::Error>,
294            ResponseRouter<Req::Response>,
295        ) -> Result<H, crate::Error>,
296    ) -> Self
297    where
298        H: crate::IntoHandled<(
299                Result<Req::Response, crate::Error>,
300                ResponseRouter<Req::Response>,
301            )>,
302    {
303        if let Ok(Handled::No {
304            message: dispatch,
305            retry,
306        }) = self.state
307        {
308            self.state = match dispatch {
309                Dispatch::Response(result, router) => {
310                    // Check if the request type matches this method
311                    if Req::matches_method(router.method()) {
312                        // Method matches, parse the response
313                        let typed_router: ResponseRouter<Req::Response> = router.cast();
314                        let typed_result = match result {
315                            Ok(value) => Req::Response::from_json(typed_router.method(), value),
316                            Err(err) => Err(err),
317                        };
318
319                        match op(typed_result, typed_router).await {
320                            Ok(handler_result) => match handler_result.into_handled() {
321                                Handled::Yes => Ok(Handled::Yes),
322                                Handled::No {
323                                    message: (result, router),
324                                    retry: response_retry,
325                                } => {
326                                    // Convert typed result back to untyped
327                                    let untyped_result = match result {
328                                        Ok(response) => response.into_json(router.method()),
329                                        Err(err) => Err(err),
330                                    };
331                                    Ok(Handled::No {
332                                        message: Dispatch::Response(
333                                            untyped_result,
334                                            router.erase_to_json(),
335                                        ),
336                                        retry: retry | response_retry,
337                                    })
338                                }
339                            },
340                            Err(err) => Err(err),
341                        }
342                    } else {
343                        // Method doesn't match, return unhandled
344                        Ok(Handled::No {
345                            message: Dispatch::Response(result, router),
346                            retry,
347                        })
348                    }
349                }
350                Dispatch::Request(_, _) | Dispatch::Notification(_) => Ok(Handled::No {
351                    message: dispatch,
352                    retry,
353                }),
354            };
355        }
356        self
357    }
358
359    /// Try to handle the message as a successful response to a request of type `Req`.
360    ///
361    /// If the message is a `Response` variant with an `Ok` result and the method matches `Req`,
362    /// the handler is called with the parsed response and a typed response context.
363    /// Error responses are passed through without calling the handler.
364    ///
365    /// This is a convenience wrapper around [`if_response_to`](Self::if_response_to) for the
366    /// common case where you only care about successful responses.
367    pub async fn if_ok_response_to<Req: JsonRpcRequest, H>(
368        self,
369        op: impl AsyncFnOnce(Req::Response, ResponseRouter<Req::Response>) -> Result<H, crate::Error>,
370    ) -> Self
371    where
372        H: crate::IntoHandled<(Req::Response, ResponseRouter<Req::Response>)>,
373    {
374        self.if_response_to::<Req, _>(async move |result, router| match result {
375            Ok(response) => {
376                let handler_result = op(response, router).await?;
377                match handler_result.into_handled() {
378                    Handled::Yes => Ok(Handled::Yes),
379                    Handled::No {
380                        message: (resp, router),
381                        retry,
382                    } => Ok(Handled::No {
383                        message: (Ok(resp), router),
384                        retry,
385                    }),
386                }
387            }
388            Err(err) => Ok(Handled::No {
389                message: (Err(err), router),
390                retry: false,
391            }),
392        })
393        .await
394    }
395
396    /// Complete matching, returning `Handled::No` if no match was found.
397    ///
398    /// # Errors
399    ///
400    /// Propagates a handler error or a failure to convert between typed and
401    /// untyped messages during an earlier match.
402    pub fn done(self) -> Result<Handled<Dispatch>, crate::Error> {
403        self.state
404    }
405
406    /// Handle messages that didn't match any previous handler.
407    ///
408    /// # Errors
409    ///
410    /// Propagates the error from an earlier match, or from `op` if it runs.
411    pub async fn otherwise(
412        self,
413        op: impl AsyncFnOnce(Dispatch) -> Result<(), crate::Error>,
414    ) -> Result<(), crate::Error> {
415        match self.state {
416            Ok(Handled::Yes) => Ok(()),
417            Ok(Handled::No { message, retry: _ }) => op(message).await,
418            Err(err) => Err(err),
419        }
420    }
421
422    /// Finish matching, answering an unmatched request with a method not
423    /// found error (`-32601`) and ignoring an unmatched notification or
424    /// response.
425    ///
426    /// # Errors
427    ///
428    /// Propagates an error from an earlier match or a failure to queue the
429    /// method-not-found response.
430    pub fn otherwise_ignore(self) -> Result<(), crate::Error> {
431        match self.state {
432            Ok(Handled::No {
433                message: Dispatch::Request(_, responder),
434                retry: _,
435            }) => responder.respond_with_error(crate::Error::method_not_found()),
436            Ok(_) => Ok(()),
437            Err(err) => Err(err),
438        }
439    }
440}
441
442/// Role-aware helper for pattern-matching on untyped JSON-RPC requests.
443///
444/// **Prefer this over implementing [`HandleDispatchFrom`] directly.** This provides
445/// a more ergonomic API for matching on message types in connection handlers.
446///
447/// Use this when you need peer-aware transforms (e.g., unwrapping proxy envelopes)
448/// before parsing messages. For simple parsing without peer awareness (e.g., inside
449/// a callback), use [`MatchDispatch`] instead.
450///
451/// This wraps [`MatchDispatch`] and applies peer-specific message transformations
452/// via `remote_style().handle_incoming_dispatch()` before delegating to `MatchDispatch`
453/// for the actual parsing.
454///
455/// [`HandleDispatchFrom`]: crate::HandleDispatchFrom
456///
457/// # Example
458///
459/// ```
460/// # use agent_client_protocol::Dispatch;
461/// # use agent_client_protocol::v1::schema::{AgentCapabilities, InitializeRequest, InitializeResponse, PromptRequest, PromptResponse, StopReason};
462/// # use agent_client_protocol::util::MatchDispatchFrom;
463/// # async fn example(message: Dispatch, cx: &agent_client_protocol::ConnectionTo<agent_client_protocol::Client>) -> Result<(), agent_client_protocol::Error> {
464/// MatchDispatchFrom::new(message, cx)
465///     .if_request(|req: InitializeRequest, responder: agent_client_protocol::Responder<InitializeResponse>| async move {
466///         // Handle initialization
467///         let response = InitializeResponse::new(req.protocol_version)
468///             .agent_capabilities(AgentCapabilities::new());
469///         responder.respond(response)
470///     })
471///     .await
472///     .if_request(|_req: PromptRequest, responder: agent_client_protocol::Responder<PromptResponse>| async move {
473///         // Handle prompts
474///         responder.respond(PromptResponse::new(StopReason::EndTurn))
475///     })
476///     .await
477///     .otherwise(|message| async move {
478///         // Fallback for unrecognized messages
479///         match message {
480///             Dispatch::Request(_, responder) => responder.respond_with_error(agent_client_protocol::Error::method_not_found()),
481///             Dispatch::Notification(_) | Dispatch::Response(_, _) => Ok(()),
482///         }
483///     })
484///     .await
485/// # }
486/// ```
487#[must_use]
488#[derive(Debug)]
489pub struct MatchDispatchFrom<Counterpart: Role> {
490    state: Result<Handled<Dispatch>, crate::Error>,
491    connection: ConnectionTo<Counterpart>,
492}
493
494impl<Counterpart: Role> MatchDispatchFrom<Counterpart> {
495    /// Create a new pattern matcher for the given untyped request message.
496    pub fn new(message: Dispatch, cx: &ConnectionTo<Counterpart>) -> Self {
497        Self {
498            state: Ok(Handled::No {
499                message,
500                retry: false,
501            }),
502            connection: cx.clone(),
503        }
504    }
505
506    /// Try to handle the message as a request of type `Req`.
507    ///
508    /// If the message is a request for one of `Req`'s methods, it is parsed and
509    /// `op` is called with the request and a typed responder. If the method
510    /// matches but the params do not parse, matching stops with the parse
511    /// error. Other messages, and messages already handled by a previous
512    /// `if_*` call, pass through unchanged.
513    ///
514    /// The handler can return either `()` (which becomes `Handled::Yes`) or an explicit
515    /// `Handled` value to control whether the message should be passed to the next handler.
516    ///
517    /// Returns `self` to allow chaining multiple `if_*` calls.
518    pub async fn if_request<Req: JsonRpcRequest, H>(
519        self,
520        op: impl AsyncFnOnce(Req, Responder<Req::Response>) -> Result<H, crate::Error>,
521    ) -> Self
522    where
523        Counterpart: HasPeer<Counterpart>,
524        H: crate::IntoHandled<(Req, Responder<Req::Response>)>,
525    {
526        let counterpart = self.connection.counterpart();
527        self.if_request_from(counterpart, op).await
528    }
529
530    /// Try to handle the message as a request of type `Req` from a specific peer.
531    ///
532    /// This is similar to [`if_request`](Self::if_request), but first applies peer-specific
533    /// message transformation (e.g., unwrapping `SuccessorMessage` envelopes when receiving
534    /// from an agent via a proxy).
535    ///
536    /// # Parameters
537    ///
538    /// * `peer` - The peer the message is expected to come from
539    /// * `op` - The handler to call if the message matches
540    pub async fn if_request_from<Peer: Role, Req: JsonRpcRequest, H>(
541        mut self,
542        peer: Peer,
543        op: impl AsyncFnOnce(Req, Responder<Req::Response>) -> Result<H, crate::Error>,
544    ) -> Self
545    where
546        Counterpart: HasPeer<Peer>,
547        H: crate::IntoHandled<(Req, Responder<Req::Response>)>,
548    {
549        if let Ok(Handled::No { message, retry }) = self.state {
550            let state = handle_incoming_dispatch(
551                self.connection.counterpart(),
552                peer,
553                message,
554                self.connection.clone(),
555                async |dispatch, _connection| {
556                    // Delegate to MatchDispatch for parsing
557                    MatchDispatch::new(dispatch).if_request(op).await.done()
558                },
559            )
560            .await;
561            self.state = preserve_retry(state, retry);
562        }
563        self
564    }
565
566    /// Try to handle the message as a notification of type `N`.
567    ///
568    /// If the message is a notification for one of `N`'s methods, it is parsed
569    /// and `op` is called with the notification. If the method matches but the
570    /// params do not parse, matching stops with the parse error. Other
571    /// messages, and messages already handled by a previous `if_*` call, pass
572    /// through unchanged.
573    ///
574    /// The handler can return either `()` (which becomes `Handled::Yes`) or an explicit
575    /// `Handled` value to control whether the message should be passed to the next handler.
576    ///
577    /// Returns `self` to allow chaining multiple `if_*` calls.
578    pub async fn if_notification<N: JsonRpcNotification, H>(
579        self,
580        op: impl AsyncFnOnce(N) -> Result<H, crate::Error>,
581    ) -> Self
582    where
583        Counterpart: HasPeer<Counterpart>,
584        H: crate::IntoHandled<N>,
585    {
586        let counterpart = self.connection.counterpart();
587        self.if_notification_from(counterpart, op).await
588    }
589
590    /// Try to handle the message as a notification of type `N` from a specific peer.
591    ///
592    /// This is similar to [`if_notification`](Self::if_notification), but first applies peer-specific
593    /// message transformation (e.g., unwrapping `SuccessorMessage` envelopes when receiving
594    /// from an agent via a proxy).
595    ///
596    /// # Parameters
597    ///
598    /// * `peer` - The peer the message is expected to come from
599    /// * `op` - The handler to call if the message matches
600    pub async fn if_notification_from<Peer: Role, N: JsonRpcNotification, H>(
601        mut self,
602        peer: Peer,
603        op: impl AsyncFnOnce(N) -> Result<H, crate::Error>,
604    ) -> Self
605    where
606        Counterpart: HasPeer<Peer>,
607        H: crate::IntoHandled<N>,
608    {
609        if let Ok(Handled::No { message, retry }) = self.state {
610            let state = handle_incoming_dispatch(
611                self.connection.counterpart(),
612                peer,
613                message,
614                self.connection.clone(),
615                async |dispatch, _connection| {
616                    // Delegate to MatchDispatch for parsing
617                    MatchDispatch::new(dispatch)
618                        .if_notification(op)
619                        .await
620                        .done()
621                },
622            )
623            .await;
624            self.state = preserve_retry(state, retry);
625        }
626        self
627    }
628
629    /// Try to handle the message as a typed `Dispatch<Req, N>` from a specific peer.
630    ///
631    /// This is similar to [`MatchDispatch::if_dispatch`], but first applies peer-specific
632    /// message transformation (e.g., unwrapping `SuccessorMessage` envelopes).
633    ///
634    /// # Parameters
635    ///
636    /// * `peer` - The peer the message is expected to come from
637    /// * `op` - The handler to call if the message matches
638    pub async fn if_dispatch_from<Peer: Role, Req: JsonRpcRequest, N: JsonRpcNotification, H>(
639        mut self,
640        peer: Peer,
641        op: impl AsyncFnOnce(Dispatch<Req, N>) -> Result<H, crate::Error>,
642    ) -> Self
643    where
644        Counterpart: HasPeer<Peer>,
645        H: crate::IntoHandled<Dispatch<Req, N>>,
646    {
647        if let Ok(Handled::No { message, retry }) = self.state {
648            let state = handle_incoming_dispatch(
649                self.connection.counterpart(),
650                peer,
651                message,
652                self.connection.clone(),
653                async |dispatch, _connection| {
654                    // Delegate to MatchDispatch for parsing
655                    MatchDispatch::new(dispatch).if_dispatch(op).await.done()
656                },
657            )
658            .await;
659            self.state = preserve_retry(state, retry);
660        }
661        self
662    }
663
664    /// Try to handle the message as a response to a request of type `Req`.
665    ///
666    /// If the message is a `Response` variant and the method matches `Req`, the handler
667    /// is called with the result (which may be `Ok` or `Err`) and a typed response context.
668    ///
669    /// Unlike requests and notifications, responses don't need peer-specific transforms
670    /// (they don't have the `SuccessorMessage` envelope structure), so this method
671    /// delegates directly to [`MatchDispatch::if_response_to`].
672    pub async fn if_response_to<Req: JsonRpcRequest, H>(
673        mut self,
674        op: impl AsyncFnOnce(
675            Result<Req::Response, crate::Error>,
676            ResponseRouter<Req::Response>,
677        ) -> Result<H, crate::Error>,
678    ) -> Self
679    where
680        H: crate::IntoHandled<(
681                Result<Req::Response, crate::Error>,
682                ResponseRouter<Req::Response>,
683            )>,
684    {
685        if let Ok(Handled::No { message, retry }) = self.state {
686            let state = MatchDispatch::new(message)
687                .if_response_to::<Req, H>(op)
688                .await
689                .done();
690            self.state = preserve_retry(state, retry);
691        }
692        self
693    }
694
695    /// Try to handle the message as a successful response to a request of type `Req`.
696    ///
697    /// If the message is a `Response` variant with an `Ok` result and the method matches `Req`,
698    /// the handler is called with the parsed response and a typed response context.
699    /// Error responses are passed through without calling the handler.
700    ///
701    /// This is a convenience wrapper around [`if_response_to`](Self::if_response_to).
702    pub async fn if_ok_response_to<Req: JsonRpcRequest, H>(
703        self,
704        op: impl AsyncFnOnce(Req::Response, ResponseRouter<Req::Response>) -> Result<H, crate::Error>,
705    ) -> Self
706    where
707        Counterpart: HasPeer<Counterpart>,
708        H: crate::IntoHandled<(Req::Response, ResponseRouter<Req::Response>)>,
709    {
710        let counterpart = self.connection.counterpart();
711        self.if_ok_response_to_from::<Req, Counterpart, H>(counterpart, op)
712            .await
713    }
714
715    /// Try to handle the message as a response to a request of type `Req` from a specific peer.
716    ///
717    /// If the message is a `Response` variant, the method matches `Req`, and the `role_id`
718    /// matches the expected peer, the handler is called with the result and a typed response context.
719    ///
720    /// This is used to filter responses by the peer they came from, which is important
721    /// in proxy scenarios where responses might arrive from multiple peers.
722    pub async fn if_response_to_from<Req: JsonRpcRequest, Peer: Role, H>(
723        mut self,
724        peer: Peer,
725        op: impl AsyncFnOnce(
726            Result<Req::Response, crate::Error>,
727            ResponseRouter<Req::Response>,
728        ) -> Result<H, crate::Error>,
729    ) -> Self
730    where
731        Counterpart: HasPeer<Peer>,
732        H: crate::IntoHandled<(
733                Result<Req::Response, crate::Error>,
734                ResponseRouter<Req::Response>,
735            )>,
736    {
737        if let Ok(Handled::No { message, retry }) = self.state {
738            let state = handle_incoming_dispatch(
739                self.connection.counterpart(),
740                peer,
741                message,
742                self.connection.clone(),
743                async |dispatch, _connection| {
744                    // Delegate to MatchDispatch for parsing
745                    MatchDispatch::new(dispatch)
746                        .if_response_to::<Req, H>(op)
747                        .await
748                        .done()
749                },
750            )
751            .await;
752            self.state = preserve_retry(state, retry);
753        }
754        self
755    }
756
757    /// Try to handle the message as a successful response to a request of type `Req` from a specific peer.
758    ///
759    /// This is a convenience wrapper around [`if_response_to_from`](Self::if_response_to_from)
760    /// for the common case where you only care about successful responses.
761    pub async fn if_ok_response_to_from<Req: JsonRpcRequest, Peer: Role, H>(
762        self,
763        peer: Peer,
764        op: impl AsyncFnOnce(Req::Response, ResponseRouter<Req::Response>) -> Result<H, crate::Error>,
765    ) -> Self
766    where
767        Counterpart: HasPeer<Peer>,
768        H: crate::IntoHandled<(Req::Response, ResponseRouter<Req::Response>)>,
769    {
770        self.if_response_to_from::<Req, _, _>(peer, async move |result, router| match result {
771            Ok(response) => {
772                let handler_result = op(response, router).await?;
773                match handler_result.into_handled() {
774                    Handled::Yes => Ok(Handled::Yes),
775                    Handled::No {
776                        message: (resp, router),
777                        retry,
778                    } => Ok(Handled::No {
779                        message: (Ok(resp), router),
780                        retry,
781                    }),
782                }
783            }
784            Err(err) => Ok(Handled::No {
785                message: (Err(err), router),
786                retry: false,
787            }),
788        })
789        .await
790    }
791
792    /// Complete matching, returning `Handled::No` if no match was found.
793    ///
794    /// # Errors
795    ///
796    /// Propagates any error transforming the peer's message, decoding it, or
797    /// running a matching handler.
798    pub fn done(self) -> Result<Handled<Dispatch>, crate::Error> {
799        match self.state {
800            Ok(Handled::Yes) => Ok(Handled::Yes),
801            Ok(Handled::No { message, retry }) => Ok(Handled::No { message, retry }),
802            Err(err) => Err(err),
803        }
804    }
805
806    /// Handle messages that didn't match any previous `if_*` call.
807    ///
808    /// This is the fallback handler that receives the original untyped message if none
809    /// of the typed handlers matched. You must call this method to complete the pattern
810    /// matching chain and get the final result.
811    ///
812    /// # Errors
813    ///
814    /// Propagates the error from an earlier match, or from `op` if it runs.
815    pub async fn otherwise(
816        self,
817        op: impl AsyncFnOnce(Dispatch) -> Result<(), crate::Error>,
818    ) -> Result<(), crate::Error> {
819        match self.state {
820            Ok(Handled::Yes) => Ok(()),
821            Ok(Handled::No { message, retry: _ }) => op(message).await,
822            Err(err) => Err(err),
823        }
824    }
825
826    /// Handle messages that didn't match any previous `if_*` call.
827    ///
828    /// This is the fallback handler that receives the original untyped message if none
829    /// of the typed handlers matched. You must call this method to complete the pattern
830    /// matching chain and get the final result.
831    ///
832    /// # Errors
833    ///
834    /// Propagates the error from an earlier match, or from `handler` if the
835    /// unmatched dispatch is delegated to it.
836    pub async fn otherwise_delegate(
837        self,
838        mut handler: impl HandleDispatchFrom<Counterpart>,
839    ) -> Result<Handled<Dispatch>, crate::Error> {
840        match self.state? {
841            Handled::Yes => Ok(Handled::Yes),
842            Handled::No {
843                message,
844                retry: outer_retry,
845            } => match handler
846                .handle_dispatch_from(message, self.connection.clone())
847                .await?
848            {
849                Handled::Yes => Ok(Handled::Yes),
850                Handled::No {
851                    message,
852                    retry: inner_retry,
853                } => Ok(Handled::No {
854                    message,
855                    retry: inner_retry | outer_retry,
856                }),
857            },
858        }
859    }
860}