use std::path::Path;
use std::sync::Arc;
use sapphire_sync_core::framework::server::{StatusRow, SyncRuntime, SyncStatus};
pub fn status_rows(runtime: Arc<SyncRuntime>) -> Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync> {
Arc::new(move || {
tokio::task::block_in_place(|| {
let handle = tokio::runtime::Handle::current();
let mut roots = handle.block_on(runtime.roots());
roots.sort();
let bridge = (!runtime.is_connected()).then(|| StatusRow {
name: "bridge".to_owned(),
value: "not connected; reconnecting".to_owned(),
});
bridge
.into_iter()
.chain(roots.iter().filter_map(|root| {
let status = handle.block_on(runtime.status(root));
status.enabled.then(|| row_for(root, &status))
}))
.collect()
})
})
}
fn row_for(root: &Path, status: &SyncStatus) -> StatusRow {
let name = root
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| root.display().to_string());
let id = status
.workspace_id
.map(|id| id.to_string())
.unwrap_or_else(|| "-".into());
let mut value = format!("synced as {id}, {}", peers_text(status.peers));
if let Some(paused) = &status.paused {
value.push_str(&format!(", paused: {paused}"));
}
StatusRow { name, value }
}
fn peers_text(peers: usize) -> String {
format!("{peers} peer{}", if peers == 1 { "" } else { "s" })
}
#[cfg(test)]
mod tests {
use super::*;
use sapphire_sync_core::CTX;
use sapphire_sync_core::framework::ipc::ManagedBy;
use sapphire_sync_core::framework::server::BridgeConnector;
#[tokio::test(flavor = "multi_thread")]
async fn a_runtime_without_its_bridge_says_so_first() {
let runtime = Arc::new(SyncRuntime::connecting(
&CTX,
BridgeConnector::new(|| async { Ok(None) }),
"/bin/true".into(),
ManagedBy::Service,
));
runtime.connect().await.unwrap();
let rows = status_rows(runtime)();
assert_eq!(rows.len(), 1, "{rows:?}");
assert_eq!(rows[0].name, "bridge");
assert_eq!(rows[0].value, "not connected; reconnecting");
}
}