rpc_io/handles.rs
1//! Handles onto a running endpoint: [`Peer`] to send, [`Call`] to await an
2//! answer, [`Canceller`] to cancel one, [`Responder`] to answer a deferred
3//! request, and [`CancelToken`] to learn that the peer cancelled it.
4
5use std::{
6 fmt,
7 future::Future,
8 pin::Pin,
9 sync::{
10 Arc,
11 atomic::{AtomicBool, Ordering},
12 },
13 task::{self, Poll},
14 thread,
15 time::{Duration, Instant},
16};
17
18use jsonx_lib::Kind;
19
20use crate::{
21 error::{CallError, Error},
22 error_object::ErrorObject,
23 id::Id,
24 link::{Link, Scope},
25 raw::{Json, Raw},
26 slot::{Outcome, Slot},
27 stats::Stats,
28};
29
30/// A flag that says a request was cancelled.
31///
32/// A [`Responder`] carries one: the endpoint sets it when the peer cancels
33/// the request (or the connection closes), and the code answering the request
34/// checks it to stop early. Clones share the flag. Setting it by hand is
35/// allowed and only sets the flag.
36///
37/// # Examples
38///
39/// ```
40/// let token = rpc_io::CancelToken::new();
41/// let seen_by_worker = token.clone();
42/// assert!(!seen_by_worker.is_cancelled());
43/// token.cancel();
44/// assert!(seen_by_worker.is_cancelled());
45/// ```
46#[derive(Clone, Debug, Default)]
47pub struct CancelToken(Arc<AtomicBool>);
48
49impl CancelToken {
50 /// A token that is not cancelled.
51 ///
52 /// # Examples
53 ///
54 /// ```
55 /// assert!(!rpc_io::CancelToken::new().is_cancelled());
56 /// ```
57 #[must_use]
58 pub fn new() -> Self {
59 Self::default()
60 }
61
62 /// Sets the flag, for this token and every clone.
63 ///
64 /// # Examples
65 ///
66 /// ```
67 /// let t = rpc_io::CancelToken::new();
68 /// t.cancel();
69 /// t.cancel(); // idempotent
70 /// assert!(t.is_cancelled());
71 /// ```
72 pub fn cancel(&self) {
73 self.0.store(true, Ordering::Release);
74 }
75
76 /// Whether the flag is set.
77 ///
78 /// # Examples
79 ///
80 /// ```
81 /// assert!(!rpc_io::CancelToken::new().is_cancelled());
82 /// ```
83 #[must_use]
84 pub fn is_cancelled(&self) -> bool {
85 self.0.load(Ordering::Acquire)
86 }
87}
88
89/// Outgoing params: `null` means none; arrays and objects are sent; anything
90/// else is refused.
91fn outgoing_params<'a>(params: impl Into<Json<'a>>) -> Result<Option<Json<'a>>, Error> {
92 let params = params.into();
93 match params.kind() {
94 Kind::Null => Ok(None),
95 Kind::Array | Kind::Object => Ok(Some(params)),
96 kind => Err(Error::InvalidParams(kind)),
97 }
98}
99
100/// A handle for talking to the peer: notifications and requests, from any
101/// thread.
102///
103/// Cheap to clone, `Send` and `Sync`. Messages sent from a thread other than
104/// the endpoint's go out at once (one write and flush each); messages sent
105/// from a handler go out with the rest of that turn, before the handler's
106/// response.
107///
108/// # Examples
109///
110/// ```
111/// use std::sync::mpsc;
112/// use rpc_io::jsonx::json;
113/// use rpc_io::{Endpoint, Router};
114///
115/// let (tx, rx) = mpsc::channel::<String>();
116/// let endpoint = Endpoint::new(tx, Router::new(), ());
117/// let peer = endpoint.peer();
118/// std::thread::spawn(move || peer.notify("progress", json!({ "done": 50 })))
119/// .join()
120/// .unwrap()?;
121/// assert_eq!(
122/// rx.try_recv().ok().as_deref(),
123/// Some(r#"{"jsonrpc":"2.0","method":"progress","params":{"done":50}}"#),
124/// );
125/// # Ok::<(), rpc_io::Error>(())
126/// ```
127#[derive(Clone)]
128pub struct Peer {
129 link: Arc<dyn Link>,
130}
131
132impl Peer {
133 pub(crate) fn new(link: Arc<dyn Link>) -> Self {
134 Self { link }
135 }
136
137 /// The shared state this peer sends through.
138 pub(crate) fn link(&self) -> &Arc<dyn Link> {
139 &self.link
140 }
141
142 /// Sends a notification. `params` may be an array, an object, or `()`
143 /// (`null`) for none.
144 ///
145 /// # Errors
146 ///
147 /// [`Error::InvalidParams`] for other params; [`Error::Closed`] once the
148 /// connection has ended; [`Error::Io`] if writing failed (which closes the
149 /// connection).
150 ///
151 /// # Examples
152 ///
153 /// ```
154 /// use rpc_io::{Endpoint, Error, Router};
155 ///
156 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
157 /// let endpoint = Endpoint::new(tx, Router::new(), ()); // keep it: dropping an endpoint closes it
158 /// let peer = endpoint.peer();
159 /// assert!(peer.notify("exit", ()).is_ok());
160 /// assert!(matches!(peer.notify("bad", 5), Err(Error::InvalidParams(_))));
161 /// ```
162 pub fn notify<'a>(&self, method: &str, params: impl Into<Json<'a>>) -> Result<(), Error> {
163 let params = outgoing_params(params)?;
164 self.link.notify(method, params.as_ref())
165 }
166
167 /// Sends a request and returns the [`Call`] its answer will arrive on. The
168 /// deadline is [`Config::request_timeout`](crate::Config), if set.
169 ///
170 /// # Errors
171 ///
172 /// As [`notify`](Peer::notify).
173 ///
174 /// # Examples
175 ///
176 /// ```
177 /// use rpc_io::{Endpoint, Router};
178 ///
179 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
180 /// let endpoint = Endpoint::new(tx, Router::new(), ()); // keep it: dropping an endpoint closes it
181 /// let peer = endpoint.peer();
182 /// let call = peer.request("workspace/configuration", rpc_io::jsonx::json!({ "items": [] }))?;
183 /// assert_eq!(call.id(), 1);
184 /// assert!(rx.try_recv().is_ok_and(|m| m.starts_with(r#"{"jsonrpc":"2.0","id":1,"#)));
185 /// # Ok::<(), rpc_io::Error>(())
186 /// ```
187 pub fn request<'a>(&self, method: &str, params: impl Into<Json<'a>>) -> Result<Call, Error> {
188 self.send_request(method, params, None)
189 }
190
191 /// Sends a request that times out after `timeout`: its [`Call`] then ends
192 /// with [`CallError::TimedOut`] and the peer is sent the cancel
193 /// notification.
194 ///
195 /// # Errors
196 ///
197 /// As [`notify`](Peer::notify).
198 ///
199 /// # Examples
200 ///
201 /// ```
202 /// use std::time::Duration;
203 /// use rpc_io::{CallError, Endpoint, Router};
204 ///
205 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
206 /// let endpoint = Endpoint::new(tx, Router::new(), ()); // keep it: dropping an endpoint closes it
207 /// let peer = endpoint.peer();
208 /// let call = peer.request_with_timeout("slow", (), Duration::from_millis(10))?;
209 /// assert_eq!(call.wait(), Err(CallError::TimedOut));
210 /// # Ok::<(), rpc_io::Error>(())
211 /// ```
212 pub fn request_with_timeout<'a>(
213 &self,
214 method: &str,
215 params: impl Into<Json<'a>>,
216 timeout: Duration,
217 ) -> Result<Call, Error> {
218 self.send_request(method, params, Some(timeout))
219 }
220
221 fn send_request<'a>(
222 &self,
223 method: &str,
224 params: impl Into<Json<'a>>,
225 timeout: Option<Duration>,
226 ) -> Result<Call, Error> {
227 let params = outgoing_params(params)?;
228 let issued = self.link.request(method, params.as_ref(), timeout)?;
229 Ok(Call {
230 id: issued.id,
231 outcome: issued.outcome,
232 deadline: issued.deadline,
233 link: Arc::clone(&self.link),
234 detached: false,
235 })
236 }
237
238 /// Whether the connection has ended.
239 ///
240 /// # Examples
241 ///
242 /// ```
243 /// use rpc_io::{Endpoint, Router};
244 ///
245 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
246 /// let mut endpoint = Endpoint::new(tx, Router::new(), ());
247 /// let peer = endpoint.peer();
248 /// endpoint.close();
249 /// assert!(peer.is_closed());
250 /// ```
251 #[must_use]
252 pub fn is_closed(&self) -> bool {
253 self.link.is_closed()
254 }
255
256 /// The connection's counters and gauges; see [`Stats`].
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// use rpc_io::{Endpoint, Router};
262 ///
263 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
264 /// let endpoint = Endpoint::new(tx, Router::<()>::new(), ());
265 /// let peer = endpoint.peer();
266 /// peer.notify("hello", ())?;
267 /// let _call = peer.request("ask", ())?;
268 /// let stats = peer.stats();
269 /// assert_eq!((stats.notifications_out, stats.requests_out, stats.pending), (1, 1, 1));
270 /// # Ok::<(), rpc_io::Error>(())
271 /// ```
272 #[must_use]
273 pub fn stats(&self) -> Stats {
274 self.link.stats()
275 }
276}
277
278impl fmt::Debug for Peer {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 f.debug_struct("Peer")
281 .field("closed", &self.is_closed())
282 .finish()
283 }
284}
285
286/// One of our requests, awaiting its answer.
287///
288/// Ends in exactly one outcome: the peer's result, or a [`CallError`]
289/// (rejected, timed out, cancelled, evicted, connection closed).
290///
291/// Dropping a `Call` before its outcome cancels the request, as
292/// [`cancel`](Call::cancel) does: its pending slot is freed at once and the
293/// peer is sent the cancel notification. That is what a dropped future
294/// means in async code (a `select!` that took another branch), and it keeps
295/// abandoned calls from filling [`Config::max_pending`](crate::Config) and
296/// evicting live ones. To send a request and not wait for its answer, keep
297/// it outstanding with [`detach`](Call::detach), or send a notification.
298///
299/// Wait for it by blocking ([`wait`](Call::wait)), by polling
300/// ([`try_wait`](Call::try_wait)), or by `.await`ing it: `Call` is a
301/// [`Future`] on any executor, woken when the outcome arrives (deadlines
302/// included, which fire on their own; see
303/// [`Config::timer`](crate::Config)). Once the future has returned its
304/// outcome, polling again returns [`CallError::Closed`].
305///
306/// # Examples
307///
308/// ```
309/// use rpc_io::{CallError, Endpoint, Router};
310///
311/// let (tx, _rx) = std::sync::mpsc::channel::<String>();
312/// let mut endpoint = Endpoint::new(tx, Router::new(), ());
313/// let call = endpoint.peer().request("x", ())?;
314/// // The peer answers through the endpoint:
315/// endpoint.handle(br#"{"jsonrpc":"2.0","id":1,"result":[42]}"#)?;
316/// assert_eq!(call.wait().map(|raw| raw.as_str().to_owned()), Ok("[42]".to_owned()));
317/// # Ok::<(), rpc_io::Error>(())
318/// ```
319#[must_use = "dropping a Call cancels the request; call .detach() to let it run"]
320pub struct Call {
321 id: u64,
322 outcome: Arc<Slot>,
323 deadline: Option<Instant>,
324 link: Arc<dyn Link>,
325 /// Kept outstanding when dropped (see `detach`).
326 detached: bool,
327}
328
329impl Call {
330 /// The request's id on the wire.
331 ///
332 /// # Examples
333 ///
334 /// ```
335 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
336 /// let endpoint = rpc_io::Endpoint::new(tx, rpc_io::Router::new(), ()); // keep it: dropping an endpoint closes it
337 /// let peer = endpoint.peer();
338 /// assert_eq!(peer.request("a", ())?.id(), 1);
339 /// assert_eq!(peer.request("b", ())?.id(), 2);
340 /// # Ok::<(), rpc_io::Error>(())
341 /// ```
342 #[inline]
343 #[must_use]
344 pub const fn id(&self) -> u64 {
345 self.id
346 }
347
348 /// The deadline, if the request has one.
349 ///
350 /// # Examples
351 ///
352 /// ```
353 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
354 /// let endpoint = rpc_io::Endpoint::new(tx, rpc_io::Router::new(), ()); // keep it: dropping an endpoint closes it
355 /// let peer = endpoint.peer();
356 /// assert!(peer.request("a", ())?.deadline().is_none());
357 /// # Ok::<(), rpc_io::Error>(())
358 /// ```
359 #[inline]
360 #[must_use]
361 pub const fn deadline(&self) -> Option<Instant> {
362 self.deadline
363 }
364
365 /// Blocks until the answer arrives or the request ends otherwise.
366 ///
367 /// # Errors
368 ///
369 /// The [`CallError`] the request ended with. On the endpoint's own thread
370 /// (inside a handler) it returns [`CallError::WouldDeadlock`] at once
371 /// unless the outcome is already there: that thread is the one that would
372 /// read the answer.
373 ///
374 /// # Examples
375 ///
376 /// ```
377 /// use rpc_io::{CallError, Endpoint, Router};
378 ///
379 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
380 /// let mut endpoint = Endpoint::new(tx, Router::new(), ());
381 /// let call = endpoint.peer().request("x", ())?;
382 /// endpoint.close();
383 /// assert_eq!(call.wait(), Err(CallError::Closed));
384 /// # Ok::<(), rpc_io::Error>(())
385 /// ```
386 pub fn wait(self) -> Result<Raw<'static>, CallError> {
387 if let Some(outcome) = self.outcome.try_take() {
388 return outcome;
389 }
390 if self.link.on_endpoint_thread() {
391 return Err(CallError::WouldDeadlock);
392 }
393 if let Some(deadline) = self.deadline {
394 if let Some(outcome) = self.outcome.wait_until(Some(deadline)) {
395 return outcome;
396 }
397 // Due: expiring delivers `TimedOut` (or the answer, if it won the
398 // race), so the blocking wait below returns at once.
399 self.link.expire();
400 }
401 self.outcome
402 .wait_until(None)
403 .unwrap_or(Err(CallError::Closed))
404 }
405
406 /// The outcome if it has arrived, or the call back to try again later.
407 /// Never blocks, so a handler can poll a request it sent earlier.
408 ///
409 /// # Errors
410 ///
411 /// `Err(self)` while the request is still outstanding.
412 ///
413 /// # Examples
414 ///
415 /// ```
416 /// use rpc_io::{Endpoint, Router};
417 ///
418 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
419 /// let mut endpoint = Endpoint::new(tx, Router::new(), ());
420 /// let call = endpoint.peer().request("x", ())?;
421 /// let call = call.try_wait().err().unwrap(); // not answered yet
422 /// endpoint.handle(br#"{"jsonrpc":"2.0","id":1,"result":null}"#)?;
423 /// assert!(call.try_wait().is_ok_and(|outcome| outcome.is_ok()));
424 /// # Ok::<(), rpc_io::Error>(())
425 /// ```
426 pub fn try_wait(self) -> Result<Result<Raw<'static>, CallError>, Call> {
427 if self.deadline.is_some_and(|d| d <= Instant::now()) {
428 self.link.expire();
429 }
430 match self.outcome.try_take() {
431 Some(outcome) => Ok(outcome),
432 None => Err(self),
433 }
434 }
435
436 /// Lets the request run without a waiter: it stays outstanding until it
437 /// is answered (the answer is then discarded), times out (the peer is
438 /// told to cancel), or is evicted. Dropping the `Call` instead would
439 /// cancel it.
440 ///
441 /// # Examples
442 ///
443 /// ```
444 /// use rpc_io::{Endpoint, Router};
445 ///
446 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
447 /// let endpoint = Endpoint::new(tx, Router::<()>::new(), ());
448 /// endpoint.peer().request("index", ())?.detach();
449 /// assert_eq!(endpoint.stats().pending, 1); // still outstanding
450 /// drop(endpoint.peer().request("cancel me", ())?); // cancelled
451 /// assert_eq!(endpoint.stats().pending, 1);
452 /// assert_eq!(rx.try_iter().count(), 3); // two requests, one cancel
453 /// # Ok::<(), rpc_io::Error>(())
454 /// ```
455 pub fn detach(mut self) {
456 self.detached = true;
457 }
458
459 /// Cancels the request: the peer is sent the cancel notification and the
460 /// outcome becomes [`CallError::Cancelled`]. Returns `false` if the
461 /// request had already ended.
462 ///
463 /// # Examples
464 ///
465 /// ```
466 /// use rpc_io::{CallError, Endpoint, Router};
467 ///
468 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
469 /// let endpoint = Endpoint::new(tx, Router::new(), ()); // keep it: dropping an endpoint closes it
470 /// let peer = endpoint.peer();
471 /// let call = peer.request("slow", ())?;
472 /// assert!(call.cancel());
473 /// let sent: Vec<String> = rx.try_iter().collect();
474 /// assert_eq!(sent[1], r#"{"jsonrpc":"2.0","method":"$/cancelRequest","params":{"id":1}}"#);
475 /// # Ok::<(), rpc_io::Error>(())
476 /// ```
477 pub fn cancel(self) -> bool {
478 self.link.cancel(self.id)
479 }
480
481 /// A handle that can cancel this request from elsewhere (another thread,
482 /// a later handler) while this `Call` waits.
483 ///
484 /// # Examples
485 ///
486 /// ```
487 /// use rpc_io::{CallError, Endpoint, Router};
488 ///
489 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
490 /// let endpoint = Endpoint::new(tx, Router::new(), ()); // keep it: dropping an endpoint closes it
491 /// let peer = endpoint.peer();
492 /// let call = peer.request("slow", ())?;
493 /// let canceller = call.canceller();
494 /// std::thread::spawn(move || canceller.cancel());
495 /// assert_eq!(call.wait(), Err(CallError::Cancelled));
496 /// # Ok::<(), rpc_io::Error>(())
497 /// ```
498 #[must_use]
499 pub fn canceller(&self) -> Canceller {
500 Canceller {
501 id: self.id,
502 link: Arc::clone(&self.link),
503 }
504 }
505}
506
507impl Drop for Call {
508 /// Cancels the request if it has no outcome yet and was not detached.
509 fn drop(&mut self) {
510 if !self.detached && !self.outcome.is_filled() {
511 // `false` when it ended meanwhile: nothing left to cancel.
512 let _cancelled = self.link.cancel(self.id);
513 }
514 }
515}
516
517impl Future for Call {
518 type Output = Outcome;
519
520 /// The outcome once it has arrived.
521 ///
522 /// # Examples
523 ///
524 /// ```
525 /// use std::{future::Future, pin::pin, task::{Context, Poll, Waker}};
526 /// use rpc_io::{Endpoint, Router};
527 ///
528 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
529 /// let mut endpoint = Endpoint::new(tx, Router::new(), ());
530 /// let mut call = pin!(endpoint.peer().request("x", ())?);
531 /// let mut cx = Context::from_waker(Waker::noop());
532 /// assert!(call.as_mut().poll(&mut cx).is_pending());
533 /// endpoint.handle(br#"{"jsonrpc":"2.0","id":1,"result":"yes"}"#)?;
534 /// let Poll::Ready(outcome) = call.as_mut().poll(&mut cx) else { panic!() };
535 /// assert_eq!(outcome.map(|raw| raw.as_str().to_owned()), Ok(r#""yes""#.to_owned()));
536 /// # Ok::<(), rpc_io::Error>(())
537 /// ```
538 fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Outcome> {
539 if self.deadline.is_some_and(|d| d <= Instant::now()) {
540 self.link.expire();
541 }
542 self.outcome.poll(cx)
543 }
544}
545
546impl fmt::Debug for Call {
547 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548 f.debug_struct("Call")
549 .field("id", &self.id)
550 .field("deadline", &self.deadline)
551 .finish_non_exhaustive()
552 }
553}
554
555/// Cancels one of our requests from anywhere. `Clone`, `Send`, `Sync`.
556///
557/// # Examples
558///
559/// ```
560/// let (tx, _rx) = std::sync::mpsc::channel::<String>();
561/// let endpoint = rpc_io::Endpoint::new(tx, rpc_io::Router::new(), ()); // keep it: dropping an endpoint closes it
562/// let peer = endpoint.peer();
563/// let call = peer.request("slow", ())?;
564/// let canceller = call.canceller();
565/// assert!(canceller.cancel());
566/// assert!(!canceller.cancel()); // already ended
567/// # Ok::<(), rpc_io::Error>(())
568/// ```
569#[derive(Clone)]
570pub struct Canceller {
571 id: u64,
572 link: Arc<dyn Link>,
573}
574
575impl Canceller {
576 /// Cancels the request, as [`Call::cancel`]. Returns `false` if it had
577 /// already ended.
578 ///
579 /// # Examples
580 ///
581 /// ```
582 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
583 /// let endpoint = rpc_io::Endpoint::new(tx, rpc_io::Router::new(), ()); // keep it: dropping an endpoint closes it
584 /// let peer = endpoint.peer();
585 /// let call = peer.request("x", ())?;
586 /// let canceller = call.canceller();
587 /// assert!(canceller.cancel());
588 /// # drop(call);
589 /// # Ok::<(), rpc_io::Error>(())
590 /// ```
591 pub fn cancel(&self) -> bool {
592 self.link.cancel(self.id)
593 }
594
595 /// The id of the request it cancels.
596 ///
597 /// # Examples
598 ///
599 /// ```
600 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
601 /// let endpoint = rpc_io::Endpoint::new(tx, rpc_io::Router::new(), ()); // keep it: dropping an endpoint closes it
602 /// let peer = endpoint.peer();
603 /// let call = peer.request("x", ())?;
604 /// assert_eq!(call.canceller().id(), call.id());
605 /// # Ok::<(), rpc_io::Error>(())
606 /// ```
607 #[must_use]
608 pub const fn id(&self) -> u64 {
609 self.id
610 }
611}
612
613impl fmt::Debug for Canceller {
614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615 f.debug_struct("Canceller").field("id", &self.id).finish()
616 }
617}
618
619/// The right to answer one deferred request, exactly once.
620///
621/// A handler registered with [`Router::deferred`](crate::Router::deferred)
622/// receives one and may answer at once, keep it in its state and answer from
623/// a later message, or move it to another thread. Answering consumes it; the
624/// answer is sent immediately, from whichever thread answers.
625///
626/// Exactly one response is guaranteed: if the `Responder` is dropped without
627/// answering (a worker returned early, a panic unwound through it), the
628/// request is answered with `INTERNAL_ERROR`. If the peer cancels the
629/// request first, its [`CancelToken`] is set and the cancellation is answered
630/// as [`Cancellation`](crate::Cancellation) says; a later answer returns
631/// [`Error::AlreadyAnswered`] and is not sent.
632///
633/// # Examples
634///
635/// ```
636/// use std::sync::mpsc;
637/// use rpc_io::jsonx::json;
638/// use rpc_io::{Endpoint, Router};
639///
640/// let router = Router::new().deferred("slow", |_, _params, _cx, responder| {
641/// std::thread::spawn(move || {
642/// // ... long work, checking `responder.is_cancelled()` ...
643/// responder.ok(json!("done")).ok();
644/// });
645/// });
646/// let (tx, rx) = mpsc::channel::<String>();
647/// let mut endpoint = Endpoint::new(tx, router, ());
648/// endpoint.handle(br#"{"jsonrpc":"2.0","id":7,"method":"slow"}"#)?;
649/// let reply = rx.recv_timeout(std::time::Duration::from_secs(5)).ok();
650/// assert_eq!(reply.as_deref(), Some(r#"{"jsonrpc":"2.0","id":7,"result":"done"}"#));
651/// # Ok::<(), rpc_io::Error>(())
652/// ```
653pub struct Responder {
654 id: Id<'static>,
655 /// Which request under `id` this answers (see `Inner::respond_deferred`).
656 serial: u64,
657 token: CancelToken,
658 link: Arc<dyn Link>,
659 answered: bool,
660}
661
662impl Responder {
663 pub(crate) fn new(
664 id: Id<'static>,
665 serial: u64,
666 token: CancelToken,
667 link: Arc<dyn Link>,
668 ) -> Self {
669 Self {
670 id,
671 serial,
672 token,
673 link,
674 answered: false,
675 }
676 }
677
678 /// The scope of the request this answers.
679 pub(crate) fn scope(&self) -> Scope {
680 Scope::Deferred {
681 id: self.id.clone(),
682 serial: self.serial,
683 }
684 }
685
686 /// The id of the request being answered.
687 ///
688 /// # Examples
689 ///
690 /// ```
691 /// use rpc_io::{Endpoint, Router};
692 ///
693 /// let router = Router::new().deferred("m", |_, _, _, responder| {
694 /// assert_eq!(responder.id().as_i64(), Some(3));
695 /// responder.ok(()).ok();
696 /// });
697 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
698 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
699 /// # Ok::<(), rpc_io::Error>(())
700 /// ```
701 #[inline]
702 #[must_use]
703 pub fn id(&self) -> &Id<'static> {
704 &self.id
705 }
706
707 /// A clone of the request's cancellation flag.
708 ///
709 /// # Examples
710 ///
711 /// ```
712 /// use rpc_io::{Endpoint, Router};
713 ///
714 /// let router = Router::new().deferred("m", |_, _, _, responder| {
715 /// assert!(!responder.token().is_cancelled());
716 /// responder.ok(()).ok();
717 /// });
718 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
719 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
720 /// # Ok::<(), rpc_io::Error>(())
721 /// ```
722 #[must_use]
723 pub fn token(&self) -> CancelToken {
724 self.token.clone()
725 }
726
727 /// Whether the peer cancelled the request (or the connection closed).
728 ///
729 /// # Examples
730 ///
731 /// ```
732 /// use rpc_io::{Endpoint, Router};
733 ///
734 /// let router = Router::new().deferred("m", |_, _, _, responder| {
735 /// assert!(!responder.is_cancelled());
736 /// responder.ok(()).ok();
737 /// });
738 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
739 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
740 /// # Ok::<(), rpc_io::Error>(())
741 /// ```
742 #[must_use]
743 pub fn is_cancelled(&self) -> bool {
744 self.token.is_cancelled()
745 }
746
747 /// A [`Peer`] on the same connection, to send progress or ask questions
748 /// while answering.
749 ///
750 /// # Examples
751 ///
752 /// ```
753 /// use rpc_io::{Endpoint, Router};
754 ///
755 /// let router = Router::new().deferred("m", |_, _, _, responder| {
756 /// responder.peer().notify("progress", ()).ok();
757 /// responder.ok(()).ok();
758 /// });
759 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
760 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
761 /// assert_eq!(rx.try_iter().count(), 2);
762 /// # Ok::<(), rpc_io::Error>(())
763 /// ```
764 #[must_use]
765 pub fn peer(&self) -> Peer {
766 Peer::new(Arc::clone(&self.link))
767 }
768
769 /// Answers with `result`: a value, or an error.
770 ///
771 /// # Errors
772 ///
773 /// [`Error::AlreadyAnswered`] if the peer cancelled the request first;
774 /// [`Error::Closed`] if the connection has ended; [`Error::Io`] if writing
775 /// failed.
776 ///
777 /// # Examples
778 ///
779 /// ```
780 /// use rpc_io::{Endpoint, ErrorObject, Router};
781 ///
782 /// let router = Router::new().deferred("m", |_, _, _, responder| {
783 /// responder.respond(Err::<(), _>(ErrorObject::internal_error("no"))).ok();
784 /// });
785 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
786 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
787 /// assert!(rx.try_recv().is_ok_and(|m| m.contains(r#""error":{"code":-32603"#)));
788 /// # Ok::<(), rpc_io::Error>(())
789 /// ```
790 pub fn respond<'a, J: Into<Json<'a>>>(
791 mut self,
792 result: Result<J, ErrorObject>,
793 ) -> Result<(), Error> {
794 self.answered = true;
795 match result {
796 Ok(value) => self.link.respond(&self.id, self.serial, Ok(&value.into())),
797 Err(error) => self.link.respond(&self.id, self.serial, Err(&error)),
798 }
799 }
800
801 /// Answers with a result value.
802 ///
803 /// # Errors
804 ///
805 /// As [`respond`](Responder::respond).
806 ///
807 /// # Examples
808 ///
809 /// ```
810 /// use rpc_io::{Endpoint, Router};
811 ///
812 /// let router = Router::new().deferred("m", |_, _, _, responder| {
813 /// responder.ok(42).ok();
814 /// });
815 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
816 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
817 /// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","id":3,"result":42}"#));
818 /// # Ok::<(), rpc_io::Error>(())
819 /// ```
820 pub fn ok<'a>(self, value: impl Into<Json<'a>>) -> Result<(), Error> {
821 self.respond(Ok(value.into()))
822 }
823
824 /// Answers with an error.
825 ///
826 /// # Errors
827 ///
828 /// As [`respond`](Responder::respond).
829 ///
830 /// # Examples
831 ///
832 /// ```
833 /// use rpc_io::{Endpoint, ErrorObject, Router};
834 ///
835 /// let router = Router::new().deferred("m", |_, _, _, responder| {
836 /// responder.err(ErrorObject::invalid_params("missing `uri`")).ok();
837 /// });
838 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
839 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
840 /// assert!(rx.try_recv().is_ok_and(|m| m.contains("-32602")));
841 /// # Ok::<(), rpc_io::Error>(())
842 /// ```
843 pub fn err(self, error: ErrorObject) -> Result<(), Error> {
844 self.respond(Err::<(), _>(error))
845 }
846}
847
848impl Drop for Responder {
849 fn drop(&mut self) {
850 if self.answered {
851 return;
852 }
853 let message = if thread::panicking() {
854 "the handler panicked before answering"
855 } else {
856 "the handler dropped the request without answering"
857 };
858 // Already answered (cancelled) or closed: there is no one left to
859 // tell, which is the point of answering here.
860 let _settled = self.link.respond(
861 &self.id,
862 self.serial,
863 Err(&ErrorObject::internal_error(message)),
864 );
865 }
866}
867
868impl Responder {
869 /// A [`Notifier`] bound to this request: it sends notifications while
870 /// the request is in flight and refuses once it is answered (through
871 /// this responder, or by the connection) or cancelled by the peer. For a
872 /// stream of notifications that belongs to one request (MCP's
873 /// `subscriptions/listen`).
874 ///
875 /// # Examples
876 ///
877 /// See [`Notifier`].
878 #[must_use]
879 pub fn notifier(&self) -> Notifier {
880 Notifier {
881 peer: self.peer(),
882 scope: self.scope(),
883 }
884 }
885}
886
887/// Notifications that belong to one request: sent only while it is in
888/// flight.
889///
890/// [`notify`](Notifier::notify) refuses with [`Error::AlreadyAnswered`] once
891/// the request is answered or cancelled by the peer, and with
892/// [`Error::Closed`] once the connection closed. The check runs under the
893/// lock the response is written under, so no notification can follow the
894/// response, or a cancellation the endpoint has handled, on the wire. It is
895/// bound to its request, not to the request's id: when the peer reuses the
896/// id for a later request, a notifier of the earlier one still refuses and
897/// never sends for the later one. Made by
898/// [`Responder::notifier`] for a deferred request, or by
899/// [`Context::notifier`](crate::Context::notifier) for the request being
900/// handled. `Clone`, and usable from any thread.
901///
902/// # Examples
903///
904/// ```
905/// use rpc_io::{Config, Endpoint, Error, Notifier, Responder, Router};
906///
907/// let router = Router::new().deferred("subscriptions/listen", |kept: &mut Vec<(Notifier, Responder)>, _, _, responder| {
908/// kept.push((responder.notifier(), responder));
909/// });
910/// let (tx, rx) = std::sync::mpsc::channel::<String>();
911/// let mut endpoint = Endpoint::new(tx, router, Vec::new()).with_config(Config::mcp());
912/// endpoint.handle(br#"{"jsonrpc":"2.0","id":7,"method":"subscriptions/listen"}"#)?;
913/// let (notifier, _responder) = endpoint.state_mut().remove(0);
914/// notifier.notify("notifications/tools/list_changed", ())?;
915/// assert!(rx.try_recv().is_ok_and(|m| m.contains("list_changed")));
916/// // The client cancels the request: the stream is over.
917/// endpoint.handle(br#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":7}}"#)?;
918/// assert!(matches!(notifier.notify("notifications/tools/list_changed", ()), Err(Error::AlreadyAnswered)));
919/// assert!(rx.try_recv().is_err());
920/// # Ok::<(), rpc_io::Error>(())
921/// ```
922#[derive(Clone)]
923pub struct Notifier {
924 peer: Peer,
925 scope: Scope,
926}
927
928impl Notifier {
929 pub(crate) fn new(peer: Peer, scope: Scope) -> Self {
930 Self { peer, scope }
931 }
932
933 /// Sends a notification, as [`Peer::notify`], while the request is in
934 /// flight.
935 ///
936 /// # Errors
937 ///
938 /// [`Error::AlreadyAnswered`] once the request is answered or cancelled;
939 /// otherwise as [`Peer::notify`]. Nothing is sent when it fails.
940 ///
941 /// # Examples
942 ///
943 /// See [`Notifier`].
944 pub fn notify<'a>(&self, method: &str, params: impl Into<Json<'a>>) -> Result<(), Error> {
945 let params = outgoing_params(params)?;
946 self.peer
947 .link()
948 .notify_in(&self.scope, None, method, params.as_ref())
949 }
950}
951
952impl fmt::Debug for Notifier {
953 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
954 f.debug_struct("Notifier").finish_non_exhaustive()
955 }
956}
957
958impl fmt::Debug for Responder {
959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960 f.debug_struct("Responder")
961 .field("id", &self.id)
962 .field("cancelled", &self.is_cancelled())
963 .finish_non_exhaustive()
964 }
965}