Skip to main content

agent_client_protocol/concepts/
cancellation.rs

1//! Request cancellation with `$/cancel_request`.
2//!
3//! The SDK exposes the ACP `$/cancel_request` protocol-level notification:
4//! either side may send it to ask the peer to cancel one outstanding JSON-RPC
5//! request by ID.
6//!
7//! Cancellation is **cooperative**. A peer may ignore `$/cancel_request`, may
8//! finish with normal data, or may respond to the original request with
9//! [`Error::request_cancelled`] (`-32800`). The requesting side always
10//! receives a response to the original request; cancellation only changes
11//! *which* response that is. Unhandled notifications are ignored by the SDK
12//! so peers that do not support cancellation simply will not act on it.
13//!
14//! # Cancelling outgoing requests
15//!
16//! To cancel a request sent through [`ConnectionTo::send_request`], keep the
17//! returned [`SentRequest`] and call [`cancel`][`SentRequest::cancel`] on it:
18//!
19//! ```
20//! # use agent_client_protocol::{ConnectionTo, Error, UntypedRole};
21//! # use agent_client_protocol_test::MyRequest;
22//! # async fn example(cx: ConnectionTo<UntypedRole>) -> Result<(), Error> {
23//! let request = cx.send_request(MyRequest {});
24//! request.cancel()?;
25//!
26//! // The peer still responds to the request: with normal data if it raced
27//! // ahead, or with the standard cancellation error.
28//! let result = request.block_task().await;
29//! # let _ = result;
30//! # Ok(())
31//! # }
32//! ```
33//!
34//! The [`SentRequest`] remembers the peer and any proxy wrapping used for the
35//! original request, so this also works for requests sent through
36//! [`ConnectionTo::send_request_to`].
37//!
38//! Dropping a [`SentRequest`] before the SDK receives a response also sends
39//! `$/cancel_request`. This covers abandoned request handles and futures. For a
40//! request whose eventual response should be ignored, but which should continue
41//! running on the peer, call [`detach`][`SentRequest::detach`] instead; the
42//! eventual response is discarded, but no cancellation is sent. The peer is
43//! still expected to answer the JSON-RPC request eventually; use a notification
44//! instead when no response is expected at all. Once the SDK routes a response
45//! for the request, automatic cancellation is disarmed: the peer has already
46//! answered, even if caller code has not yet consumed the handle with
47//! [`block_task`], [`on_receiving_result`], or [`forward_response_to`], and even
48//! if a dispatch handler claimed the response.
49//!
50//! # Handling cancellation of incoming requests
51//!
52//! For incoming requests, get the request-local cancellation marker from the
53//! [`Responder`]. This keeps cancellation handling next to the request work it
54//! controls:
55//!
56//! ```
57//! # use agent_client_protocol::{ConnectionTo, Error, Responder, UntypedRole};
58//! # use agent_client_protocol_test::{MyRequest, MyResponse};
59//! # async fn example(request: MyRequest, responder: Responder<MyResponse>, cx: ConnectionTo<UntypedRole>) -> Result<(), Error> {
60//! # async fn run_request(_request: MyRequest) -> Result<MyResponse, Error> { todo!() }
61//! let cancellation = responder.cancellation();
62//!
63//! cx.spawn(async move {
64//!     let response = cancellation.run_until_cancelled(run_request(request)).await;
65//!     responder.respond_with_result(response)
66//! })?;
67//! # Ok(())
68//! # }
69//! ```
70//!
71//! [`run_until_cancelled`] is the simple path for handlers that should stop
72//! work and reply with the standard cancellation error as soon as cancellation
73//! is requested; it drops the work future when cancellation wins. If the
74//! handler needs cleanup, partial results, or custom cancellation behavior,
75//! use [`cancelled`][`RequestCancellation::cancelled`] or
76//! [`is_cancelled`][`RequestCancellation::is_cancelled`] directly inside the
77//! request work instead.
78//!
79//! Cancellation markers are only updated when the connection can process the
80//! incoming `$/cancel_request` notification. Long-running handlers should
81//! return quickly and move work into [`ConnectionTo::spawn`], [`SentRequest`]
82//! callbacks, or another task; see the [ordering](super::ordering) chapter.
83//!
84//! # Proxies
85//!
86//! When proxying with [`forward_response_to`], the SDK observes the upstream
87//! [`Responder`] cancellation marker and forwards cancellation to the
88//! downstream request automatically. The downstream response (normal data or a
89//! cancellation error) is still forwarded back upstream.
90//!
91//! Because cancellation propagates per hop this way, the raw notification is
92//! never tunneled across hops: [`ConnectionTo::send_proxied_message_to`] drops
93//! `$/cancel_request` notifications rather than forwarding a `requestId` that
94//! was allocated on a different connection and would be meaningless to the
95//! next peer.
96//!
97//! ## Custom methods on proxies
98//!
99//! A proxy that intercepts a method with its own handler decides what
100//! cancellation means for it. The SDK always records the cancellation on the
101//! request's [`Responder`] marker before the handler chain runs; what happens
102//! next is up to the handler that owns the request:
103//!
104//! - **Handle locally**: react to [`Responder::cancellation`] like any
105//!   request handler (ignore it, finish early, or respond with
106//!   [`Error::request_cancelled`]).
107//! - **Forward and propagate**: use [`forward_response_to`], or, when the
108//!   forwarding needs custom logic (rewriting the request, post-processing
109//!   the result), register the upstream marker explicitly with
110//!   [`forward_cancellation_from`] before consuming the handle:
111//!
112//! ```
113//! # use agent_client_protocol::{ConnectionTo, Error, Responder, UntypedRole};
114//! # use agent_client_protocol_test::{MyRequest, MyResponse};
115//! # async fn example(request: MyRequest, responder: Responder<MyResponse>, backend: ConnectionTo<UntypedRole>) -> Result<(), Error> {
116//! backend
117//!     .send_request(request)
118//!     .forward_cancellation_from(responder.cancellation())
119//!     .on_receiving_result(async move |result| {
120//!         // Custom result handling before responding upstream.
121//!         responder.respond_with_result(result)
122//!     })?;
123//! # Ok(())
124//! # }
125//! ```
126//!
127//! - **Absorb**: consume the handle without registering the marker
128//!   ([`on_receiving_result`] or [`block_task`] alone); the upstream marker is
129//!   still set, but nothing is sent downstream and the request runs to
130//!   completion there.
131//! - **Custom routing**: claim the `$/cancel_request` notification itself in a
132//!   handler (user handlers run before the generic forwarding fallbacks) and
133//!   translate it manually when you control the relevant hop-local request IDs.
134//!
135//! # Low-level access
136//!
137//! Register [`CancelRequestNotification`] (or [`ProtocolLevelNotification`])
138//! directly only when you need low-level access to cancellation notifications,
139//! such as custom routing or protocol tracing:
140//!
141//! ```
142//! # use agent_client_protocol::{ConnectionTo, Error, UntypedRole};
143//! use agent_client_protocol::schema::v1::CancelRequestNotification;
144//!
145//! # fn example() {
146//! let builder = UntypedRole.builder().on_receive_notification(
147//!     async |cancel: CancelRequestNotification, _cx: ConnectionTo<UntypedRole>| {
148//!         // Mark the matching in-flight operation cancelled.
149//!         let _request_id = cancel.request_id;
150//!         Ok(())
151//!     },
152//!     agent_client_protocol::on_receive_notification!(),
153//! );
154//! # let _ = builder;
155//! # }
156//! ```
157//!
158//! Such a handler observes cancellation notifications but does not replace
159//! the built-in handling: the SDK updates the [`Responder`] cancellation
160//! markers for every incoming `$/cancel_request` before the handler chain
161//! runs, even when a handler claims the notification.
162//!
163//! If you are implementing custom routing and already know the JSON-RPC request
164//! ID on the peer connection you are targeting, use
165//! [`ConnectionTo::send_cancel_request_to`]. Most code should use
166//! [`SentRequest::cancel`] instead, because the request handle already knows the
167//! correct peer, request ID, and proxy wrapping.
168//!
169//! [`block_task`]: crate::SentRequest::block_task
170//! [`on_receiving_result`]: crate::SentRequest::on_receiving_result
171//! [`forward_response_to`]: crate::SentRequest::forward_response_to
172//! [`run_until_cancelled`]: crate::RequestCancellation::run_until_cancelled
173//! [`RequestCancellation`]: crate::RequestCancellation
174//! [`RequestCancellation::cancelled`]: crate::RequestCancellation::cancelled
175//! [`RequestCancellation::is_cancelled`]: crate::RequestCancellation::is_cancelled
176//! [`ConnectionTo::send_request`]: crate::ConnectionTo::send_request
177//! [`ConnectionTo::send_request_to`]: crate::ConnectionTo::send_request_to
178//! [`ConnectionTo::send_proxied_message_to`]: crate::ConnectionTo::send_proxied_message_to
179//! [`ConnectionTo::spawn`]: crate::ConnectionTo::spawn
180//! [`SentRequest`]: crate::SentRequest
181//! [`SentRequest::cancel`]: crate::SentRequest::cancel
182//! [`SentRequest::detach`]: crate::SentRequest::detach
183//! [`forward_cancellation_from`]: crate::SentRequest::forward_cancellation_from
184//! [`ConnectionTo::send_cancel_request_to`]: crate::ConnectionTo::send_cancel_request_to
185//! [`Responder::cancellation`]: crate::Responder::cancellation
186//! [`Responder`]: crate::Responder
187//! [`Error::request_cancelled`]: crate::Error::request_cancelled
188//! [`CancelRequestNotification`]: crate::schema::v1::CancelRequestNotification
189//! [`ProtocolLevelNotification`]: crate::schema::v1::ProtocolLevelNotification