cacp_events/lib.rs
1//! A channel-based [`Client`](cacp::Client) for [`cacp`].
2//!
3//! A frontend already has an event loop. [`channel`] hands it one instead of a
4//! trait to implement: a [`Client`](cacp::Client) to give [`spawn`](cacp::spawn),
5//! and the [`Events`] stream every call from the agent arrives on.
6//!
7//! Anything you do not match on is declined with `method not found`, exactly as
8//! an unimplemented [`Client`](cacp::Client) method would be — so a consumer
9//! that ignores an [`Event`] is indistinguishable on the wire from one that
10//! never served that method. Declare what you do serve in
11//! [`ClientCapabilities`](proto::ClientCapabilities), as ever.
12//!
13//! Notifications arrive in wire order. A request is dispatched on its own task,
14//! so it can reach the stream just after a notification that followed it on the
15//! wire.
16//!
17//! ```no_run
18//! use cacp_events::Event;
19//!
20//! # async fn run() -> cacp::Result<()> {
21//! let (client, mut events) = cacp_events::channel();
22//! let (_agent, _child) = cacp::spawn(&mut tokio::process::Command::new("my-agent"), client, None)?;
23//!
24//! while let Some(event) = events.recv().await {
25//! match event {
26//! Event::Update(notification) => println!("{:?}", notification.update),
27//! Event::Permission(request, reply) => reply.send(
28//! cacp::schema::RequestPermissionResponse::selected(
29//! request.options[0].option_id.clone(),
30//! ),
31//! ),
32//! _ => {}
33//! }
34//! }
35//! # Ok(()) }
36//! ```
37
38pub use event::Event;
39pub use reply::Reply;
40use std::sync::Arc;
41use tokio::sync::{mpsc, oneshot};
42
43mod client;
44mod event;
45mod reply;
46
47/// Every call the agent makes, in one stream.
48pub type Events = mpsc::UnboundedReceiver<Event>;
49
50/// A [`Client`](cacp::Client) that forwards its calls to an [`Events`] stream.
51pub struct Channel(mpsc::UnboundedSender<Event>);
52
53/// A client to hand to [`spawn`](cacp::spawn), and the stream its calls arrive
54/// on.
55pub fn channel() -> (Arc<Channel>, Events) {
56 // Unbounded: `session_update` is awaited by the read loop, so backpressure
57 // here would stall the responses the consumer's own calls are waiting on.
58 let (tx, rx) = mpsc::unbounded_channel();
59 (Arc::new(Channel(tx)), rx)
60}
61
62impl Channel {
63 /// Queue a request and wait on the consumer. A dropped [`Reply`] — or a
64 /// dropped [`Events`] — declines it.
65 pub(crate) async fn ask<T>(&self, event: impl FnOnce(Reply<T>) -> Event) -> proto::Result<T> {
66 let (tx, rx) = oneshot::channel();
67 self.0
68 .send(event(Reply(tx)))
69 .map_err(|_| proto::Error::method_not_found())?;
70 rx.await
71 .unwrap_or_else(|_| Err(proto::Error::method_not_found()))
72 }
73
74 pub(crate) fn tell(&self, event: Event) {
75 let _ = self.0.send(event);
76 }
77}