use std::path::PathBuf;
use std::sync::{Arc, Mutex, MutexGuard};
use sapphire_framework_server::sync::testing::StubBridge;
use sapphire_framework_server::{AppServer, StatusRow, SyncRuntime};
use sapphire_ipc::{ManagedBy, probe};
use sapphire_sync_cli::{cli, sync};
use sapphire_sync_core::CTX;
use sapphire_sync_core::framework::backend::protocol as proto;
use sapphire_sync_core::framework::ipc::Endpoint;
use sapphire_sync_core::framework::workspace::AppKind;
struct Env {
previous: [(&'static str, Option<std::ffi::OsString>); 4],
}
impl Env {
fn set(root: &std::path::Path) -> Env {
let names = [
"SAPPHIRE_SYNC_CACHE_DIR",
"SAPPHIRE_SYNC_DATA_DIR",
"SAPPHIRE_SYNC_CONFIG_DIR",
"SAPPHIRE_RUNTIME_DIR",
];
let previous = unsafe {
names
.map(|name| (name, std::env::var_os(name)))
.map(|(name, old)| {
std::env::set_var(name, root.join(leaf_of(name)));
(name, old)
})
};
Env { previous }
}
}
fn leaf_of(name: &str) -> &'static str {
match name {
"SAPPHIRE_SYNC_CACHE_DIR" => "cache",
"SAPPHIRE_SYNC_DATA_DIR" => "data",
"SAPPHIRE_SYNC_CONFIG_DIR" => "config",
_ => "run",
}
}
impl Drop for Env {
fn drop(&mut self) {
unsafe {
for (name, value) in &self.previous {
match value {
Some(previous) => std::env::set_var(name, previous),
None => std::env::remove_var(name),
}
}
}
}
}
static ENV_LOCK: Mutex<()> = Mutex::new(());
fn lock_env() -> MutexGuard<'static, ()> {
ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner())
}
async fn wait_until_listening(endpoint: &Endpoint) {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
while !probe(endpoint).await.unwrap_or(false) {
assert!(
tokio::time::Instant::now() < deadline,
"the server never started listening"
);
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
}
fn workspace_root(tmp: &std::path::Path, name: &str) -> PathBuf {
let root = tmp.join(name);
std::fs::create_dir_all(root.join(format!(".{}", CTX.app_name))).unwrap();
root.canonicalize().unwrap()
}
#[tokio::test(flavor = "multi_thread")]
#[allow(clippy::await_holding_lock)]
async fn disable_unregisters_drops_the_row_and_reenables_with_the_same_id() {
let _lock = lock_env();
let tmp = tempfile::tempdir().unwrap();
let _env = Env::set(tmp.path());
CTX.init(AppKind::Server);
let root = workspace_root(tmp.path(), "notes");
let (stub, bridge_client) = StubBridge::start().await;
let runtime = Arc::new(SyncRuntime::new(
&CTX,
bridge_client,
std::env::current_exe().unwrap(),
ManagedBy::Service,
));
let rows = sapphire_sync_server::status_rows(Arc::clone(&runtime));
let rows = Arc::clone(&rows) as Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>;
let server = AppServer::new(&CTX, env!("CARGO_PKG_VERSION"))
.app_api(sapphire_sync_api::API_VERSION)
.sync(Arc::clone(&runtime))
.status_rows(Arc::clone(&rows));
let endpoint = Endpoint::for_app(CTX.app_name).unwrap();
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
let info = sapphire_ipc::ClientInfo {
kind: "test".into(),
version: env!("CARGO_PKG_VERSION").to_owned(),
api: proto::API_VERSION,
app_api: None,
pid: std::process::id(),
};
let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, info)
.await
.unwrap()
.unwrap();
let _: proto::CurrentWorkspace = client
.call(
proto::WORKSPACE_SELECT,
proto::WorkspaceSelectParams { dir: root.clone() },
)
.await
.unwrap();
assert_eq!(rows(), vec![], "an unsynced workspace has no row");
let id = runtime.enable(&root).await.unwrap();
assert_eq!(
rows(),
vec![StatusRow {
name: "notes".into(),
value: format!("synced as {id}, 0 peers"),
}],
"an enabled workspace is one row: name, id, peer count"
);
let code = sync::dispatch(cli::SyncCommand {
command: cli::SyncSubcommand::Disable,
})
.await
.unwrap();
assert_eq!(code, 0, "a successful disable exits 0");
assert_eq!(
stub.seen.lock().expect("stub").unregistrations,
vec![id],
"the disabled workspace is unregistered with the bridge"
);
assert_eq!(
rows(),
vec![],
"the row goes once the runtime no longer syncs the root"
);
let code = sync::dispatch(cli::SyncCommand {
command: cli::SyncSubcommand::Disable,
})
.await
.unwrap();
assert_eq!(code, 0, "an idempotent disable exits 0 too");
assert_eq!(
stub.seen.lock().expect("stub").unregistrations,
vec![id],
"nothing left to unregister"
);
let enabled: proto::SyncEnableResult = client
.call(proto::SYNC_ENABLE, serde_json::json!({}))
.await
.unwrap();
assert_eq!(
enabled.workspace_id, id,
"re-enabling rejoins the same workspace, not a second one"
);
assert_eq!(
rows(),
vec![StatusRow {
name: "notes".into(),
value: format!("synced as {id}, 0 peers"),
}],
"the row is back, same id"
);
std::fs::write(root.join("paper.txt"), "words\n").unwrap();
runtime.scan(&root).await.unwrap();
std::fs::remove_dir_all(root.join(format!(".{}", CTX.app_name))).unwrap();
runtime.scan(&root).await.unwrap();
assert_eq!(
rows(),
vec![StatusRow {
name: "notes".into(),
value: format!("synced as {id}, 0 peers, paused: MarkerMissing"),
}],
"a paused workspace appends the framework's reason"
);
handle.abort();
drop(stub);
drop(_env);
drop(_lock);
}