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;
pub fn subscribe_method(host: Arc<WorkspaceHost>, router: Router) -> Router {
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) {
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;
};
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");
const DIR_VARS: [&str; 3] = [
"SAPPHIRE_EVENTTEST_CACHE_DIR",
"SAPPHIRE_EVENTTEST_DATA_DIR",
"SAPPHIRE_EVENTTEST_CONFIG_DIR",
];
struct EnvGuard {
previous: [Option<OsString>; 3],
_lock: std::sync::MutexGuard<'static, ()>,
}
impl EnvGuard {
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));
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) {
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),
}
}
}
}
fn init_ctx(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
let guard = EnvGuard::set(lock, tmp);
CTX.init(AppKind::Server);
guard
}
struct Fixture {
_tmp: tempfile::TempDir,
_env: EnvGuard,
ws: PathBuf,
client: Client,
}
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();
tokio::time::timeout(Duration::from_secs(5), events.recv())
.await
.expect("the first event")
.unwrap();
let second = tokio::time::timeout(Duration::from_millis(500), events.recv()).await;
assert!(second.is_err(), "a duplicate event arrived: {second:?}");
}
}