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 and ordered
81//! [`SentRequest`] callbacks should return quickly and move work into
82//! [`ConnectionTo::spawn`] or another task; see the
83//! [ordering](super::ordering) chapter.
84//!
85//! # Proxies
86//!
87//! When proxying with [`forward_response_to`], the SDK observes the upstream
88//! [`Responder`] cancellation marker and forwards cancellation to the
89//! downstream request automatically. The downstream response (normal data or a
90//! cancellation error) is still forwarded back upstream.
91//!
92//! Because cancellation propagates per hop this way, the raw notification is
93//! never tunneled across hops: [`ConnectionTo::send_proxied_message_to`] drops
94//! `$/cancel_request` notifications rather than forwarding a `requestId` that
95//! was allocated on a different connection and would be meaningless to the
96//! next peer.
97//!
98//! ## Custom methods on proxies
99//!
100//! A proxy that intercepts a method with its own handler decides what
101//! cancellation means for it. The SDK always records the cancellation on the
102//! request's [`Responder`] marker before the handler chain runs; what happens
103//! next is up to the handler that owns the request:
104//!
105//! - **Handle locally**: react to [`Responder::cancellation`] like any
106//!   request handler (ignore it, finish early, or respond with
107//!   [`Error::request_cancelled`]).
108//! - **Forward and propagate**: use [`forward_response_to`], or, when the
109//!   forwarding needs custom logic (rewriting the request, post-processing
110//!   the result), register the upstream marker explicitly with
111//!   [`forward_cancellation_from`] before consuming the handle:
112//!
113//! ```
114//! # use agent_client_protocol::{ConnectionTo, Error, Responder, UntypedRole};
115//! # use agent_client_protocol_test::{MyRequest, MyResponse};
116//! # async fn example(request: MyRequest, responder: Responder<MyResponse>, backend: ConnectionTo<UntypedRole>) -> Result<(), Error> {
117//! backend
118//!     .send_request(request)
119//!     .forward_cancellation_from(responder.cancellation())
120//!     .on_receiving_result(async move |result| {
121//!         // Custom result handling before responding upstream.
122//!         responder.respond_with_result(result)
123//!     })?;
124//! # Ok(())
125//! # }
126//! ```
127//!
128//! - **Absorb**: consume the handle without registering the marker
129//!   ([`on_receiving_result`] or [`block_task`] alone); the upstream marker is
130//!   still set, but nothing is sent downstream and the request runs to
131//!   completion there.
132//! - **Custom routing**: claim the `$/cancel_request` notification itself in a
133//!   handler (user handlers run before the generic forwarding fallbacks) and
134//!   translate it manually when you control the relevant hop-local request IDs.
135//!
136//! # Low-level access
137//!
138//! Register [`CancelRequestNotification`] (or [`ProtocolLevelNotification`])
139//! directly only when you need low-level access to cancellation notifications,
140//! such as custom routing or protocol tracing:
141//!
142//! ```
143//! # use agent_client_protocol::{ConnectionTo, Error, UntypedRole};
144//! use agent_client_protocol::schema::v1::CancelRequestNotification;
145//!
146//! # fn example() {
147//! let builder = UntypedRole.builder().on_receive_notification(
148//!     async |cancel: CancelRequestNotification, _cx: ConnectionTo<UntypedRole>| {
149//!         // Mark the matching in-flight operation cancelled.
150//!         let _request_id = cancel.request_id;
151//!         Ok(())
152//!     },
153//!     agent_client_protocol::on_receive_notification!(),
154//! );
155//! # let _ = builder;
156//! # }
157//! ```
158//!
159//! Such a handler observes cancellation notifications but does not replace
160//! the built-in handling: the SDK updates the [`Responder`] cancellation
161//! markers for every incoming `$/cancel_request` before the handler chain
162//! runs, even when a handler claims the notification.
163//!
164//! If you are implementing custom routing and already know the JSON-RPC request
165//! ID on the peer connection you are targeting, use
166//! [`ConnectionTo::send_cancel_request_to`]. Most code should use
167//! [`SentRequest::cancel`] instead, because the request handle already knows the
168//! correct peer, request ID, and proxy wrapping.
169//!
170//! [`block_task`]: crate::SentRequest::block_task
171//! [`on_receiving_result`]: crate::SentRequest::on_receiving_result
172//! [`forward_response_to`]: crate::SentRequest::forward_response_to
173//! [`run_until_cancelled`]: crate::RequestCancellation::run_until_cancelled
174//! [`RequestCancellation`]: crate::RequestCancellation
175//! [`RequestCancellation::cancelled`]: crate::RequestCancellation::cancelled
176//! [`RequestCancellation::is_cancelled`]: crate::RequestCancellation::is_cancelled
177//! [`ConnectionTo::send_request`]: crate::ConnectionTo::send_request
178//! [`ConnectionTo::send_request_to`]: crate::ConnectionTo::send_request_to
179//! [`ConnectionTo::send_proxied_message_to`]: crate::ConnectionTo::send_proxied_message_to
180//! [`ConnectionTo::spawn`]: crate::ConnectionTo::spawn
181//! [`SentRequest`]: crate::SentRequest
182//! [`SentRequest::cancel`]: crate::SentRequest::cancel
183//! [`SentRequest::detach`]: crate::SentRequest::detach
184//! [`forward_cancellation_from`]: crate::SentRequest::forward_cancellation_from
185//! [`ConnectionTo::send_cancel_request_to`]: crate::ConnectionTo::send_cancel_request_to
186//! [`Responder::cancellation`]: crate::Responder::cancellation
187//! [`Responder`]: crate::Responder
188//! [`Error::request_cancelled`]: crate::Error::request_cancelled
189//! [`CancelRequestNotification`]: crate::schema::v1::CancelRequestNotification
190//! [`ProtocolLevelNotification`]: crate::schema::v1::ProtocolLevelNotification