Skip to main content

sapphire_framework_server/
events.rs

1//! `workspace.subscribe` and the pump that turns backend events into notifications.
2
3use std::collections::HashSet;
4use std::sync::{Arc, Mutex};
5
6use sapphire_backend::protocol as proto;
7use sapphire_backend::protocol::Ack;
8use sapphire_ipc::{PeerHandle, Router, RpcError};
9use tokio::sync::broadcast::error::RecvError;
10
11use crate::host::WorkspaceHost;
12
13/// Add `workspace.subscribe` to `router`.
14///
15/// The method subscribes the client to the host's events — the current workspace's, and
16/// after a switch the next one's (#215) — and spawns a task that forwards each event to
17/// that client as a `workspace.event` notification, naming the root it came from. The task
18/// stops when the client disconnects — `PeerHandle::notify` fails once the connection is
19/// gone — so a client that comes and goes does not leak tasks.
20///
21/// Subscribing twice from the same connection still acknowledges, but starts no second
22/// pump, so a client cannot double its own event stream. Subscribing needs no workspace:
23/// a client may subscribe before the first one is selected.
24///
25/// A subscriber that falls more than the event capacity (128) behind loses the events in
26/// between and gets a warning in the server log: treat an event as "something happened,
27/// re-read", not as the change itself.
28pub fn subscribe_method(host: Arc<WorkspaceHost>, router: Router) -> Router {
29    // Which clients already have a pump. A client that subscribes twice must not receive
30    // two copies of every event.
31    let active: Arc<Mutex<HashSet<u32>>> = Arc::new(Mutex::new(HashSet::new()));
32
33    router.method(proto::SUBSCRIBE, move |ctx| {
34        let host = Arc::clone(&host);
35        let active = Arc::clone(&active);
36        async move {
37            let key = ctx.peer.client().pid;
38            if !active.lock().expect("subscription set").insert(key) {
39                // Already pumping for this client.
40                return serde_json::to_value(Ack {}).map_err(|e| RpcError::internal(e.to_string()));
41            }
42
43            let mut events = host.subscribe();
44            let peer: PeerHandle = ctx.peer.clone();
45            tokio::spawn(async move {
46                loop {
47                    match events.recv().await {
48                        Ok((ws, event)) => {
49                            let params = proto::EventParams { ws, event };
50                            let Ok(value) = serde_json::to_value(params) else {
51                                continue;
52                            };
53                            // A failure here means the client is gone.
54                            if peer.notify(proto::EVENT, value).await.is_err() {
55                                break;
56                            }
57                        }
58                        Err(RecvError::Lagged(missed)) => {
59                            tracing::warn!(missed, "a subscriber fell behind and lost events");
60                        }
61                        Err(RecvError::Closed) => break,
62                    }
63                }
64                active.lock().expect("subscription set").remove(&key);
65            });
66
67            serde_json::to_value(Ack {}).map_err(|e| RpcError::internal(e.to_string()))
68        }
69    })
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use sapphire_backend::BackendEvent;
76    use sapphire_backend::protocol as proto;
77    use sapphire_ipc::{Client, ClientInfo, Connection, ManagedBy, ServerInfo, serve};
78    use sapphire_workspace::{AppContext, AppKind};
79    use std::ffi::OsString;
80    use std::path::PathBuf;
81    use std::time::Duration;
82
83    use crate::test_support;
84
85    static CTX: AppContext = AppContext::new("sapphire-eventtest");
86
87    /// The env vars `init_ctx` writes, in the order the guard restores them.
88    const DIR_VARS: [&str; 3] = [
89        "SAPPHIRE_EVENTTEST_CACHE_DIR",
90        "SAPPHIRE_EVENTTEST_DATA_DIR",
91        "SAPPHIRE_EVENTTEST_CONFIG_DIR",
92    ];
93
94    /// Point the context's directories at `tmp` and restore the previous values (present
95    /// or absent) when dropped — including while unwinding from a panic. Without the
96    /// unconditional restore, a panicking assertion would leave the variables pointing at
97    /// a temp directory the test then deletes, and the context of a later test would
98    /// resolve into the void.
99    struct EnvGuard {
100        previous: [Option<OsString>; 3],
101        _lock: std::sync::MutexGuard<'static, ()>,
102    }
103
104    impl EnvGuard {
105        /// Write the three directory vars while holding the environment lock.
106        fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
107            let previous = DIR_VARS.map(std::env::var_os);
108            let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
109            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
110            // the process environment in this test binary — the `host` and `handlers`
111            // modules' tests share the same lock — and it is held until `drop` has
112            // restored the old values.
113            for (name, dir) in DIR_VARS.iter().zip(dirs) {
114                test_support::set(name, &dir);
115            }
116            EnvGuard {
117                previous,
118                _lock: lock,
119            }
120        }
121    }
122
123    impl Drop for EnvGuard {
124        fn drop(&mut self) {
125            // SAFETY: `self._lock` still serialises the environment; it is dropped only
126            // after this method returns.
127            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
128                match previous.take() {
129                    Some(value) => unsafe { std::env::set_var(name, value) },
130                    None => test_support::remove(name),
131                }
132            }
133        }
134    }
135
136    /// Point the context's directories at a scratch location. The static context is
137    /// first-writer-wins, so whichever test initialises it first fixes the directories
138    /// for the whole binary; every test therefore holds the env lock for its entire body
139    /// (see [`Fixture`]).
140    fn init_ctx(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
141        let guard = EnvGuard::set(lock, tmp);
142        CTX.init(AppKind::Server);
143        guard
144    }
145
146    /// Everything one test needs, held for the test's whole body.
147    ///
148    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
149    /// environment lock is still held: a sibling test that wakes on the lock must never
150    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
151    struct Fixture {
152        _tmp: tempfile::TempDir,
153        _env: EnvGuard,
154        ws: PathBuf,
155        client: Client,
156    }
157
158    /// A server carrying `workspace.subscribe` over an in-process connection, plus a
159    /// workspace root to use.
160    ///
161    /// The caller must keep the fixture (and with it the environment lock) alive for the
162    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
163    /// other test that would re-point the context's directories must wait.
164    async fn fixture() -> Fixture {
165        let lock = test_support::lock();
166        let tmp = tempfile::tempdir().unwrap();
167        let _env = init_ctx(lock, tmp.path());
168        let root = tmp.path().join("ws");
169        std::fs::create_dir_all(root.join(".sapphire-eventtest")).unwrap();
170        let ws = root.canonicalize().unwrap();
171
172        let host = Arc::new(WorkspaceHost::new(&CTX));
173        let current = Arc::new(crate::current::Current::new(
174            &CTX,
175            Arc::clone(&host),
176            None,
177            crate::selection::SelectionFile::at(tmp.path().join("workspace.toml")),
178        ));
179        current.select(&ws).await.unwrap();
180        let router = Arc::new(subscribe_method(
181            host,
182            crate::current::current_methods(Arc::clone(&current), crate::workspace_router(current)),
183        ));
184        let (client_conn, server_conn) = Connection::pair();
185        tokio::spawn(async move {
186            let info = ServerInfo {
187                version: "0.0.0".into(),
188                api: sapphire_backend::protocol::API_VERSION,
189                app_api: None,
190                pid: std::process::id(),
191                managed_by: ManagedBy::Spawned,
192            };
193            let _ = serve(server_conn, router, "sapphire-eventtest", info).await;
194        });
195        let client_info = ClientInfo {
196            kind: "test".into(),
197            version: "0.0.0".into(),
198            api: sapphire_backend::protocol::API_VERSION,
199            app_api: None,
200            pid: std::process::id(),
201        };
202        let (client, _) = Client::handshake(client_conn, "sapphire-eventtest", client_info)
203            .await
204            .unwrap();
205        Fixture {
206            _tmp: tmp,
207            _env,
208            ws,
209            client,
210        }
211    }
212
213    #[tokio::test]
214    async fn a_subscriber_sees_a_write_by_another_caller() {
215        let f = fixture().await;
216        let mut events = f.client.notifications();
217
218        let _: proto::Ack = f
219            .client
220            .call(proto::SUBSCRIBE, serde_json::json!({}))
221            .await
222            .unwrap();
223        let _: proto::Ack = f
224            .client
225            .call(
226                proto::WRITE_FILE,
227                proto::ContentParams {
228                    path: PathBuf::from("a.md"),
229                    content: "x".into(),
230                },
231            )
232            .await
233            .unwrap();
234
235        let notification = tokio::time::timeout(Duration::from_secs(5), events.recv())
236            .await
237            .expect("an event within five seconds")
238            .unwrap();
239        assert_eq!(notification.method, proto::EVENT);
240        let params: proto::EventParams = serde_json::from_value(notification.params).unwrap();
241        assert_eq!(params.ws, f.ws);
242        assert!(
243            matches!(params.event, BackendEvent::FileChanged { .. }),
244            "{:?}",
245            params.event
246        );
247    }
248
249    #[tokio::test]
250    async fn a_subscription_follows_a_switch_to_another_workspace() {
251        let f = fixture().await;
252        let other = f._tmp.path().join("other");
253        std::fs::create_dir_all(other.join(".sapphire-eventtest")).unwrap();
254        let other = other.canonicalize().unwrap();
255        let mut events = f.client.notifications();
256        let _: proto::Ack = f
257            .client
258            .call(proto::SUBSCRIBE, serde_json::json!({}))
259            .await
260            .unwrap();
261        let _: proto::CurrentWorkspace = f
262            .client
263            .call(
264                proto::WORKSPACE_SELECT,
265                proto::WorkspaceSelectParams { dir: other.clone() },
266            )
267            .await
268            .unwrap();
269        let _: proto::Ack = f
270            .client
271            .call(
272                proto::WRITE_FILE,
273                proto::ContentParams {
274                    path: PathBuf::from("b.md"),
275                    content: "y".into(),
276                },
277            )
278            .await
279            .unwrap();
280        let notification = tokio::time::timeout(Duration::from_secs(5), events.recv())
281            .await
282            .expect("an event within five seconds")
283            .unwrap();
284        let params: proto::EventParams = serde_json::from_value(notification.params).unwrap();
285        assert_eq!(
286            params.ws, other,
287            "the event names the workspace it came from"
288        );
289    }
290
291    #[tokio::test]
292    async fn subscribing_twice_does_not_duplicate_events() {
293        let f = fixture().await;
294        let mut events = f.client.notifications();
295
296        let _: proto::Ack = f
297            .client
298            .call(proto::SUBSCRIBE, serde_json::json!({}))
299            .await
300            .unwrap();
301        let _: proto::Ack = f
302            .client
303            .call(proto::SUBSCRIBE, serde_json::json!({}))
304            .await
305            .unwrap();
306
307        let _: proto::Ack = f
308            .client
309            .call(
310                proto::WRITE_FILE,
311                proto::ContentParams {
312                    path: PathBuf::from("a.md"),
313                    content: "x".into(),
314                },
315            )
316            .await
317            .unwrap();
318
319        // One event arrives …
320        tokio::time::timeout(Duration::from_secs(5), events.recv())
321            .await
322            .expect("the first event")
323            .unwrap();
324        // … and no second copy of it.
325        let second = tokio::time::timeout(Duration::from_millis(500), events.recv()).await;
326        assert!(second.is_err(), "a duplicate event arrived: {second:?}");
327    }
328}