use std::path::Path;
use anyhow::Result;
use config::Config;
use store::Store;
use transport::iroh::Endpoint;
use crate::commands::broker;
pub(crate) fn format_watch_event(ev: &ipc::WatchEvent) -> String {
format!(
"{} handle={} folder={}",
ev.event_type,
ev.handle.as_deref().unwrap_or("-"),
ev.folder.as_deref().unwrap_or("-"),
)
}
pub(crate) async fn run(
cfg: &Config,
endpoint: Option<&Endpoint>,
device: Option<&str>,
config_path: Option<&Path>,
store: &Store,
) -> Result<()> {
if let Some(ep) = endpoint {
return super::watch_hub::run(cfg, ep).await;
}
#[cfg(feature = "tui")]
{
return run_tui_brokered(cfg, device, config_path, store).await;
}
#[cfg(not(feature = "tui"))]
run_plain_brokered(cfg, device, config_path, store).await
}
#[cfg(not(feature = "tui"))]
async fn run_plain_brokered(
cfg: &Config,
device: Option<&str>,
config_path: Option<&Path>,
_store: &Store,
) -> Result<()> {
use futures::StreamExt as _;
let mut framed = broker::connect(cfg, device, config_path).await?;
broker::send_frame(&mut framed, &ipc::BrokerRequest::Watch).await?;
let ctrl_c = tokio::signal::ctrl_c();
tokio::pin!(ctrl_c);
loop {
tokio::select! {
frame = framed.next() => match frame {
None => break,
Some(Err(e)) => { tracing::warn!("watch stream error: {e}"); break; }
Some(Ok(bytes)) => {
let resp: ipc::BrokerResponse = serde_json::from_slice(&bytes)?;
match resp {
ipc::BrokerResponse::WatchEvent(ev) => {
crate::output::line(&format_watch_event(&ev))?;
}
ipc::BrokerResponse::Error(msg) => {
return Err(anyhow::anyhow!("broker watch error: {msg}"));
}
_ => {}
}
}
},
_ = &mut ctrl_c => break,
}
}
Ok(())
}
#[cfg(feature = "tui")]
async fn run_tui_brokered(
cfg: &Config,
device: Option<&str>,
config_path: Option<&Path>,
store: &Store,
) -> Result<()> {
use futures::StreamExt as _;
let mut framed = broker::connect(cfg, device, config_path).await?;
broker::send_frame(&mut framed, &ipc::BrokerRequest::Watch).await?;
let ctrl_c = tokio::signal::ctrl_c();
tokio::pin!(ctrl_c);
loop {
tokio::select! {
frame = framed.next() => match frame {
None => break,
Some(Err(e)) => { tracing::warn!("watch stream error: {e}"); break; }
Some(Ok(bytes)) => {
let resp: ipc::BrokerResponse = serde_json::from_slice(&bytes)?;
match resp {
ipc::BrokerResponse::WatchEvent(ev) => {
crate::output::line(&format_watch_event(&ev))?;
}
ipc::BrokerResponse::Error(msg) => {
return Err(anyhow::anyhow!("broker watch error: {msg}"));
}
_ => {}
}
}
},
_ = &mut ctrl_c => break,
}
}
let _ = store; Ok(())
}