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