sapphire_framework_server/
events.rs1use 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
13pub fn subscribe_method(host: Arc<WorkspaceHost>, router: Router) -> Router {
29 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 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 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 const DIR_VARS: [&str; 3] = [
89 "SAPPHIRE_EVENTTEST_CACHE_DIR",
90 "SAPPHIRE_EVENTTEST_DATA_DIR",
91 "SAPPHIRE_EVENTTEST_CONFIG_DIR",
92 ];
93
94 struct EnvGuard {
100 previous: [Option<OsString>; 3],
101 _lock: std::sync::MutexGuard<'static, ()>,
102 }
103
104 impl EnvGuard {
105 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 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 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 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 struct Fixture {
152 _tmp: tempfile::TempDir,
153 _env: EnvGuard,
154 ws: PathBuf,
155 client: Client,
156 }
157
158 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(¤t), 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 tokio::time::timeout(Duration::from_secs(5), events.recv())
321 .await
322 .expect("the first event")
323 .unwrap();
324 let second = tokio::time::timeout(Duration::from_millis(500), events.recv()).await;
326 assert!(second.is_err(), "a duplicate event arrived: {second:?}");
327 }
328}