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 sync::{
8 Arc,
9 atomic::{AtomicBool, Ordering},
10 mpsc::{self, RecvTimeoutError, TryRecvError},
11 },
12 thread,
13 time::{Duration, Instant},
14};
15
16use jsonx_lib::Kind;
17
18use crate::{
19 error::{CallError, Error},
20 error_object::ErrorObject,
21 id::Id,
22 link::{Link, Outcome},
23 raw::{Json, Raw},
24};
25
26/// A flag that says a request was cancelled.
27///
28/// A [`Responder`] carries one: the endpoint sets it when the peer cancels
29/// the request (or the connection closes), and the code answering the request
30/// checks it to stop early. Clones share the flag. Setting it by hand is
31/// allowed and only sets the flag.
32///
33/// # Examples
34///
35/// ```
36/// let token = rpc_io::CancelToken::new();
37/// let seen_by_worker = token.clone();
38/// assert!(!seen_by_worker.is_cancelled());
39/// token.cancel();
40/// assert!(seen_by_worker.is_cancelled());
41/// ```
42#[derive(Clone, Debug, Default)]
43pub struct CancelToken(Arc<AtomicBool>);
44
45impl CancelToken {
46 /// A token that is not cancelled.
47 ///
48 /// # Examples
49 ///
50 /// ```
51 /// assert!(!rpc_io::CancelToken::new().is_cancelled());
52 /// ```
53 #[must_use]
54 pub fn new() -> Self {
55 Self::default()
56 }
57
58 /// Sets the flag, for this token and every clone.
59 ///
60 /// # Examples
61 ///
62 /// ```
63 /// let t = rpc_io::CancelToken::new();
64 /// t.cancel();
65 /// t.cancel(); // idempotent
66 /// assert!(t.is_cancelled());
67 /// ```
68 pub fn cancel(&self) {
69 self.0.store(true, Ordering::Release);
70 }
71
72 /// Whether the flag is set.
73 ///
74 /// # Examples
75 ///
76 /// ```
77 /// assert!(!rpc_io::CancelToken::new().is_cancelled());
78 /// ```
79 #[must_use]
80 pub fn is_cancelled(&self) -> bool {
81 self.0.load(Ordering::Acquire)
82 }
83}
84
85/// Outgoing params: `null` means none; arrays and objects are sent; anything
86/// else is refused.
87fn outgoing_params<'a>(params: impl Into<Json<'a>>) -> Result<Option<Json<'a>>, Error> {
88 let params = params.into();
89 match params.kind() {
90 Kind::Null => Ok(None),
91 Kind::Array | Kind::Object => Ok(Some(params)),
92 kind => Err(Error::InvalidParams(kind)),
93 }
94}
95
96/// A handle for talking to the peer: notifications and requests, from any
97/// thread.
98///
99/// Cheap to clone, `Send` and `Sync`. Messages sent from a thread other than
100/// the endpoint's go out at once (one write and flush each); messages sent
101/// from a handler go out with the rest of that turn, before the handler's
102/// response.
103///
104/// # Examples
105///
106/// ```
107/// use std::sync::mpsc;
108/// use jsonx_lib::json;
109/// use rpc_io::{Endpoint, Router};
110///
111/// let (tx, rx) = mpsc::channel::<String>();
112/// let endpoint = Endpoint::new(tx, Router::new(), ());
113/// let peer = endpoint.peer();
114/// std::thread::spawn(move || peer.notify("progress", json!({ "done": 50 })))
115/// .join()
116/// .unwrap()?;
117/// assert_eq!(
118/// rx.try_recv().ok().as_deref(),
119/// Some(r#"{"jsonrpc":"2.0","method":"progress","params":{"done":50}}"#),
120/// );
121/// # Ok::<(), rpc_io::Error>(())
122/// ```
123#[derive(Clone)]
124pub struct Peer {
125 link: Arc<dyn Link>,
126}
127
128impl Peer {
129 pub(crate) fn new(link: Arc<dyn Link>) -> Self {
130 Self { link }
131 }
132
133 /// Sends a notification. `params` may be an array, an object, or `()`
134 /// (`null`) for none.
135 ///
136 /// # Errors
137 ///
138 /// [`Error::InvalidParams`] for other params; [`Error::Closed`] once the
139 /// connection has ended; [`Error::Io`] if writing failed (which closes the
140 /// connection).
141 ///
142 /// # Examples
143 ///
144 /// ```
145 /// use rpc_io::{Endpoint, Error, Router};
146 ///
147 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
148 /// let endpoint = Endpoint::new(tx, Router::new(), ()); // keep it: dropping an endpoint closes it
149 /// let peer = endpoint.peer();
150 /// assert!(peer.notify("exit", ()).is_ok());
151 /// assert!(matches!(peer.notify("bad", 5), Err(Error::InvalidParams(_))));
152 /// ```
153 pub fn notify<'a>(&self, method: &str, params: impl Into<Json<'a>>) -> Result<(), Error> {
154 let params = outgoing_params(params)?;
155 self.link.notify(method, params.as_ref())
156 }
157
158 /// Sends a request and returns the [`Call`] its answer will arrive on. The
159 /// deadline is [`Config::request_timeout`](crate::Config), if set.
160 ///
161 /// # Errors
162 ///
163 /// As [`notify`](Peer::notify).
164 ///
165 /// # Examples
166 ///
167 /// ```
168 /// use rpc_io::{Endpoint, Router};
169 ///
170 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
171 /// let endpoint = Endpoint::new(tx, Router::new(), ()); // keep it: dropping an endpoint closes it
172 /// let peer = endpoint.peer();
173 /// let call = peer.request("workspace/configuration", jsonx_lib::json!({ "items": [] }))?;
174 /// assert_eq!(call.id(), 1);
175 /// assert!(rx.try_recv().is_ok_and(|m| m.starts_with(r#"{"jsonrpc":"2.0","id":1,"#)));
176 /// # Ok::<(), rpc_io::Error>(())
177 /// ```
178 pub fn request<'a>(&self, method: &str, params: impl Into<Json<'a>>) -> Result<Call, Error> {
179 self.send_request(method, params, None)
180 }
181
182 /// Sends a request that times out after `timeout`: its [`Call`] then ends
183 /// with [`CallError::TimedOut`] and the peer is sent the cancel
184 /// notification.
185 ///
186 /// # Errors
187 ///
188 /// As [`notify`](Peer::notify).
189 ///
190 /// # Examples
191 ///
192 /// ```
193 /// use std::time::Duration;
194 /// use rpc_io::{CallError, Endpoint, Router};
195 ///
196 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
197 /// let endpoint = Endpoint::new(tx, Router::new(), ()); // keep it: dropping an endpoint closes it
198 /// let peer = endpoint.peer();
199 /// let call = peer.request_with_timeout("slow", (), Duration::from_millis(10))?;
200 /// assert_eq!(call.wait(), Err(CallError::TimedOut));
201 /// # Ok::<(), rpc_io::Error>(())
202 /// ```
203 pub fn request_with_timeout<'a>(
204 &self,
205 method: &str,
206 params: impl Into<Json<'a>>,
207 timeout: Duration,
208 ) -> Result<Call, Error> {
209 self.send_request(method, params, Some(timeout))
210 }
211
212 fn send_request<'a>(
213 &self,
214 method: &str,
215 params: impl Into<Json<'a>>,
216 timeout: Option<Duration>,
217 ) -> Result<Call, Error> {
218 let params = outgoing_params(params)?;
219 let issued = self.link.request(method, params.as_ref(), timeout)?;
220 Ok(Call {
221 id: issued.id,
222 outcome: issued.outcome,
223 deadline: issued.deadline,
224 link: Arc::clone(&self.link),
225 })
226 }
227
228 /// Whether the connection has ended.
229 ///
230 /// # Examples
231 ///
232 /// ```
233 /// use rpc_io::{Endpoint, Router};
234 ///
235 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
236 /// let mut endpoint = Endpoint::new(tx, Router::new(), ());
237 /// let peer = endpoint.peer();
238 /// endpoint.close();
239 /// assert!(peer.is_closed());
240 /// ```
241 #[must_use]
242 pub fn is_closed(&self) -> bool {
243 self.link.is_closed()
244 }
245}
246
247impl fmt::Debug for Peer {
248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249 f.debug_struct("Peer")
250 .field("closed", &self.is_closed())
251 .finish()
252 }
253}
254
255/// One of our requests, awaiting its answer.
256///
257/// Ends in exactly one outcome: the peer's result, or a [`CallError`]
258/// (rejected, timed out, cancelled, evicted, connection closed). Dropping a
259/// `Call` does not cancel the request; its answer is then discarded.
260///
261/// # Examples
262///
263/// ```
264/// use rpc_io::{CallError, Endpoint, Router};
265///
266/// let (tx, _rx) = std::sync::mpsc::channel::<String>();
267/// let mut endpoint = Endpoint::new(tx, Router::new(), ());
268/// let call = endpoint.peer().request("x", ())?;
269/// // The peer answers through the endpoint:
270/// endpoint.handle(br#"{"jsonrpc":"2.0","id":1,"result":[42]}"#)?;
271/// assert_eq!(call.wait().map(|raw| raw.as_str().to_owned()), Ok("[42]".to_owned()));
272/// # Ok::<(), rpc_io::Error>(())
273/// ```
274pub struct Call {
275 id: u64,
276 outcome: mpsc::Receiver<Outcome>,
277 deadline: Option<Instant>,
278 link: Arc<dyn Link>,
279}
280
281impl Call {
282 /// The request's id on the wire.
283 ///
284 /// # Examples
285 ///
286 /// ```
287 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
288 /// let endpoint = rpc_io::Endpoint::new(tx, rpc_io::Router::new(), ()); // keep it: dropping an endpoint closes it
289 /// let peer = endpoint.peer();
290 /// assert_eq!(peer.request("a", ())?.id(), 1);
291 /// assert_eq!(peer.request("b", ())?.id(), 2);
292 /// # Ok::<(), rpc_io::Error>(())
293 /// ```
294 #[inline]
295 #[must_use]
296 pub const fn id(&self) -> u64 {
297 self.id
298 }
299
300 /// The deadline, if the request has one.
301 ///
302 /// # Examples
303 ///
304 /// ```
305 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
306 /// let endpoint = rpc_io::Endpoint::new(tx, rpc_io::Router::new(), ()); // keep it: dropping an endpoint closes it
307 /// let peer = endpoint.peer();
308 /// assert!(peer.request("a", ())?.deadline().is_none());
309 /// # Ok::<(), rpc_io::Error>(())
310 /// ```
311 #[inline]
312 #[must_use]
313 pub const fn deadline(&self) -> Option<Instant> {
314 self.deadline
315 }
316
317 /// Blocks until the answer arrives or the request ends otherwise.
318 ///
319 /// # Errors
320 ///
321 /// The [`CallError`] the request ended with. On the endpoint's own thread
322 /// (inside a handler) it returns [`CallError::WouldDeadlock`] at once
323 /// unless the outcome is already there: that thread is the one that would
324 /// read the answer.
325 ///
326 /// # Examples
327 ///
328 /// ```
329 /// use rpc_io::{CallError, Endpoint, Router};
330 ///
331 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
332 /// let mut endpoint = Endpoint::new(tx, Router::new(), ());
333 /// let call = endpoint.peer().request("x", ())?;
334 /// endpoint.close();
335 /// assert_eq!(call.wait(), Err(CallError::Closed));
336 /// # Ok::<(), rpc_io::Error>(())
337 /// ```
338 pub fn wait(self) -> Result<Raw<'static>, CallError> {
339 match self.outcome.try_recv() {
340 Ok(outcome) => return outcome,
341 Err(TryRecvError::Disconnected) => return Err(CallError::Closed),
342 Err(TryRecvError::Empty) => {}
343 }
344 if self.link.on_endpoint_thread() {
345 return Err(CallError::WouldDeadlock);
346 }
347 if let Some(deadline) = self.deadline {
348 let left = deadline.saturating_duration_since(Instant::now());
349 match self.outcome.recv_timeout(left) {
350 Ok(outcome) => return outcome,
351 Err(RecvTimeoutError::Disconnected) => return Err(CallError::Closed),
352 // Due: expiring delivers `TimedOut` (or the answer, if it won
353 // the race), so the blocking receive below returns at once.
354 Err(RecvTimeoutError::Timeout) => self.link.expire(),
355 }
356 }
357 self.outcome.recv().unwrap_or(Err(CallError::Closed))
358 }
359
360 /// The outcome if it has arrived, or the call back to try again later.
361 /// Never blocks, so a handler can poll a request it sent earlier.
362 ///
363 /// # Errors
364 ///
365 /// `Err(self)` while the request is still outstanding.
366 ///
367 /// # Examples
368 ///
369 /// ```
370 /// use rpc_io::{Endpoint, Router};
371 ///
372 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
373 /// let mut endpoint = Endpoint::new(tx, Router::new(), ());
374 /// let call = endpoint.peer().request("x", ())?;
375 /// let call = call.try_wait().err().unwrap(); // not answered yet
376 /// endpoint.handle(br#"{"jsonrpc":"2.0","id":1,"result":null}"#)?;
377 /// assert!(call.try_wait().is_ok_and(|outcome| outcome.is_ok()));
378 /// # Ok::<(), rpc_io::Error>(())
379 /// ```
380 pub fn try_wait(self) -> Result<Result<Raw<'static>, CallError>, Call> {
381 if self.deadline.is_some_and(|d| d <= Instant::now()) {
382 self.link.expire();
383 }
384 match self.outcome.try_recv() {
385 Ok(outcome) => Ok(outcome),
386 Err(TryRecvError::Disconnected) => Ok(Err(CallError::Closed)),
387 Err(TryRecvError::Empty) => Err(self),
388 }
389 }
390
391 /// Cancels the request: the peer is sent the cancel notification and the
392 /// outcome becomes [`CallError::Cancelled`]. Returns `false` if the
393 /// request had already ended.
394 ///
395 /// # Examples
396 ///
397 /// ```
398 /// use rpc_io::{CallError, Endpoint, Router};
399 ///
400 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
401 /// let endpoint = Endpoint::new(tx, Router::new(), ()); // keep it: dropping an endpoint closes it
402 /// let peer = endpoint.peer();
403 /// let call = peer.request("slow", ())?;
404 /// assert!(call.cancel());
405 /// let sent: Vec<String> = rx.try_iter().collect();
406 /// assert_eq!(sent[1], r#"{"jsonrpc":"2.0","method":"$/cancelRequest","params":{"id":1}}"#);
407 /// # Ok::<(), rpc_io::Error>(())
408 /// ```
409 pub fn cancel(self) -> bool {
410 self.link.cancel(self.id)
411 }
412
413 /// A handle that can cancel this request from elsewhere (another thread,
414 /// a later handler) while this `Call` waits.
415 ///
416 /// # Examples
417 ///
418 /// ```
419 /// use rpc_io::{CallError, Endpoint, Router};
420 ///
421 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
422 /// let endpoint = Endpoint::new(tx, Router::new(), ()); // keep it: dropping an endpoint closes it
423 /// let peer = endpoint.peer();
424 /// let call = peer.request("slow", ())?;
425 /// let canceller = call.canceller();
426 /// std::thread::spawn(move || canceller.cancel());
427 /// assert_eq!(call.wait(), Err(CallError::Cancelled));
428 /// # Ok::<(), rpc_io::Error>(())
429 /// ```
430 #[must_use]
431 pub fn canceller(&self) -> Canceller {
432 Canceller {
433 id: self.id,
434 link: Arc::clone(&self.link),
435 }
436 }
437}
438
439impl fmt::Debug for Call {
440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441 f.debug_struct("Call")
442 .field("id", &self.id)
443 .field("deadline", &self.deadline)
444 .finish_non_exhaustive()
445 }
446}
447
448/// Cancels one of our requests from anywhere. `Clone`, `Send`, `Sync`.
449///
450/// # Examples
451///
452/// ```
453/// let (tx, _rx) = std::sync::mpsc::channel::<String>();
454/// let endpoint = rpc_io::Endpoint::new(tx, rpc_io::Router::new(), ()); // keep it: dropping an endpoint closes it
455/// let peer = endpoint.peer();
456/// let call = peer.request("slow", ())?;
457/// let canceller = call.canceller();
458/// assert!(canceller.cancel());
459/// assert!(!canceller.cancel()); // already ended
460/// # Ok::<(), rpc_io::Error>(())
461/// ```
462#[derive(Clone)]
463pub struct Canceller {
464 id: u64,
465 link: Arc<dyn Link>,
466}
467
468impl Canceller {
469 /// Cancels the request, as [`Call::cancel`]. Returns `false` if it had
470 /// already ended.
471 ///
472 /// # Examples
473 ///
474 /// ```
475 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
476 /// let endpoint = rpc_io::Endpoint::new(tx, rpc_io::Router::new(), ()); // keep it: dropping an endpoint closes it
477 /// let peer = endpoint.peer();
478 /// let canceller = peer.request("x", ())?.canceller();
479 /// assert!(canceller.cancel());
480 /// # Ok::<(), rpc_io::Error>(())
481 /// ```
482 pub fn cancel(&self) -> bool {
483 self.link.cancel(self.id)
484 }
485
486 /// The id of the request it cancels.
487 ///
488 /// # Examples
489 ///
490 /// ```
491 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
492 /// let endpoint = rpc_io::Endpoint::new(tx, rpc_io::Router::new(), ()); // keep it: dropping an endpoint closes it
493 /// let peer = endpoint.peer();
494 /// let call = peer.request("x", ())?;
495 /// assert_eq!(call.canceller().id(), call.id());
496 /// # Ok::<(), rpc_io::Error>(())
497 /// ```
498 #[must_use]
499 pub const fn id(&self) -> u64 {
500 self.id
501 }
502}
503
504impl fmt::Debug for Canceller {
505 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506 f.debug_struct("Canceller").field("id", &self.id).finish()
507 }
508}
509
510/// The right to answer one deferred request, exactly once.
511///
512/// A handler registered with [`Router::deferred`](crate::Router::deferred)
513/// receives one and may answer at once, keep it in its state and answer from
514/// a later message, or move it to another thread. Answering consumes it; the
515/// answer is sent immediately, from whichever thread answers.
516///
517/// Exactly one response is guaranteed: if the `Responder` is dropped without
518/// answering (a worker returned early, a panic unwound through it), the
519/// request is answered with `INTERNAL_ERROR`. If the peer cancels the
520/// request first, its [`CancelToken`] is set and the cancellation is answered
521/// as [`Cancellation`](crate::Cancellation) says; a later answer returns
522/// [`Error::AlreadyAnswered`] and is not sent.
523///
524/// # Examples
525///
526/// ```
527/// use std::sync::mpsc;
528/// use jsonx_lib::json;
529/// use rpc_io::{Endpoint, Router};
530///
531/// let router = Router::new().deferred("slow", |_, _params, _cx, responder| {
532/// std::thread::spawn(move || {
533/// // ... long work, checking `responder.is_cancelled()` ...
534/// responder.ok(json!("done")).ok();
535/// });
536/// });
537/// let (tx, rx) = mpsc::channel::<String>();
538/// let mut endpoint = Endpoint::new(tx, router, ());
539/// endpoint.handle(br#"{"jsonrpc":"2.0","id":7,"method":"slow"}"#)?;
540/// let reply = rx.recv_timeout(std::time::Duration::from_secs(5)).ok();
541/// assert_eq!(reply.as_deref(), Some(r#"{"jsonrpc":"2.0","id":7,"result":"done"}"#));
542/// # Ok::<(), rpc_io::Error>(())
543/// ```
544pub struct Responder {
545 id: Id<'static>,
546 token: CancelToken,
547 link: Arc<dyn Link>,
548 answered: bool,
549}
550
551impl Responder {
552 pub(crate) fn new(id: Id<'static>, token: CancelToken, link: Arc<dyn Link>) -> Self {
553 Self {
554 id,
555 token,
556 link,
557 answered: false,
558 }
559 }
560
561 /// The id of the request being answered.
562 ///
563 /// # Examples
564 ///
565 /// ```
566 /// use rpc_io::{Endpoint, Router};
567 ///
568 /// let router = Router::new().deferred("m", |_, _, _, responder| {
569 /// assert_eq!(responder.id().as_i64(), Some(3));
570 /// responder.ok(()).ok();
571 /// });
572 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
573 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
574 /// # Ok::<(), rpc_io::Error>(())
575 /// ```
576 #[inline]
577 #[must_use]
578 pub fn id(&self) -> &Id<'static> {
579 &self.id
580 }
581
582 /// A clone of the request's cancellation flag.
583 ///
584 /// # Examples
585 ///
586 /// ```
587 /// use rpc_io::{Endpoint, Router};
588 ///
589 /// let router = Router::new().deferred("m", |_, _, _, responder| {
590 /// assert!(!responder.token().is_cancelled());
591 /// responder.ok(()).ok();
592 /// });
593 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
594 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
595 /// # Ok::<(), rpc_io::Error>(())
596 /// ```
597 #[must_use]
598 pub fn token(&self) -> CancelToken {
599 self.token.clone()
600 }
601
602 /// Whether the peer cancelled the request (or the connection closed).
603 ///
604 /// # Examples
605 ///
606 /// ```
607 /// use rpc_io::{Endpoint, Router};
608 ///
609 /// let router = Router::new().deferred("m", |_, _, _, responder| {
610 /// assert!(!responder.is_cancelled());
611 /// responder.ok(()).ok();
612 /// });
613 /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
614 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
615 /// # Ok::<(), rpc_io::Error>(())
616 /// ```
617 #[must_use]
618 pub fn is_cancelled(&self) -> bool {
619 self.token.is_cancelled()
620 }
621
622 /// A [`Peer`] on the same connection, to send progress or ask questions
623 /// while answering.
624 ///
625 /// # Examples
626 ///
627 /// ```
628 /// use rpc_io::{Endpoint, Router};
629 ///
630 /// let router = Router::new().deferred("m", |_, _, _, responder| {
631 /// responder.peer().notify("progress", ()).ok();
632 /// responder.ok(()).ok();
633 /// });
634 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
635 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
636 /// assert_eq!(rx.try_iter().count(), 2);
637 /// # Ok::<(), rpc_io::Error>(())
638 /// ```
639 #[must_use]
640 pub fn peer(&self) -> Peer {
641 Peer::new(Arc::clone(&self.link))
642 }
643
644 /// Answers with `result`: a value, or an error.
645 ///
646 /// # Errors
647 ///
648 /// [`Error::AlreadyAnswered`] if the peer cancelled the request first;
649 /// [`Error::Closed`] if the connection has ended; [`Error::Io`] if writing
650 /// failed.
651 ///
652 /// # Examples
653 ///
654 /// ```
655 /// use rpc_io::{Endpoint, ErrorObject, Router};
656 ///
657 /// let router = Router::new().deferred("m", |_, _, _, responder| {
658 /// responder.respond(Err::<(), _>(ErrorObject::internal_error("no"))).ok();
659 /// });
660 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
661 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
662 /// assert!(rx.try_recv().is_ok_and(|m| m.contains(r#""error":{"code":-32603"#)));
663 /// # Ok::<(), rpc_io::Error>(())
664 /// ```
665 pub fn respond<'a, J: Into<Json<'a>>>(
666 mut self,
667 result: Result<J, ErrorObject>,
668 ) -> Result<(), Error> {
669 self.answered = true;
670 match result {
671 Ok(value) => self.link.respond(&self.id, Ok(&value.into())),
672 Err(error) => self.link.respond(&self.id, Err(&error)),
673 }
674 }
675
676 /// Answers with a result value.
677 ///
678 /// # Errors
679 ///
680 /// As [`respond`](Responder::respond).
681 ///
682 /// # Examples
683 ///
684 /// ```
685 /// use rpc_io::{Endpoint, Router};
686 ///
687 /// let router = Router::new().deferred("m", |_, _, _, responder| {
688 /// responder.ok(42).ok();
689 /// });
690 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
691 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
692 /// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","id":3,"result":42}"#));
693 /// # Ok::<(), rpc_io::Error>(())
694 /// ```
695 pub fn ok<'a>(self, value: impl Into<Json<'a>>) -> Result<(), Error> {
696 self.respond(Ok(value.into()))
697 }
698
699 /// Answers with an error.
700 ///
701 /// # Errors
702 ///
703 /// As [`respond`](Responder::respond).
704 ///
705 /// # Examples
706 ///
707 /// ```
708 /// use rpc_io::{Endpoint, ErrorObject, Router};
709 ///
710 /// let router = Router::new().deferred("m", |_, _, _, responder| {
711 /// responder.err(ErrorObject::invalid_params("missing `uri`")).ok();
712 /// });
713 /// let (tx, rx) = std::sync::mpsc::channel::<String>();
714 /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
715 /// assert!(rx.try_recv().is_ok_and(|m| m.contains("-32602")));
716 /// # Ok::<(), rpc_io::Error>(())
717 /// ```
718 pub fn err(self, error: ErrorObject) -> Result<(), Error> {
719 self.respond(Err::<(), _>(error))
720 }
721}
722
723impl Drop for Responder {
724 fn drop(&mut self) {
725 if self.answered {
726 return;
727 }
728 let message = if thread::panicking() {
729 "the handler panicked before answering"
730 } else {
731 "the handler dropped the request without answering"
732 };
733 // Already answered (cancelled) or closed: there is no one left to
734 // tell, which is the point of answering here.
735 let _settled = self
736 .link
737 .respond(&self.id, Err(&ErrorObject::internal_error(message)));
738 }
739}
740
741impl fmt::Debug for Responder {
742 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743 f.debug_struct("Responder")
744 .field("id", &self.id)
745 .field("cancelled", &self.is_cancelled())
746 .finish_non_exhaustive()
747 }
748}