use std::path::Path;
use std::time::Duration;
use serde_json::json;
use crate::boundary::dispatch::Deps;
use crate::boundary::reply::{Place, Placed};
use crate::bz_host::far::{TOOL, machines, split};
use crate::config_edit::brazen::{BzOutcome, ProviderRow, ProviderRowView, provider_rows};
use crate::registry::mailbox::{Call, Capture};
use crate::registry::{Client, tools};
const WAITS: u32 = 120;
const TICK: Duration = Duration::from_millis(25);
pub(crate) fn named(deps: &Deps, workspace: &Path, provider: &str) -> Option<Place> {
let registered = machines(&deps.state_root, &crate::naming::leaf(workspace));
split(provider, ®istered).map(|(row, client)| Place { client, row })
}
fn advertises(deps: &Deps, client: &str) -> bool {
Client::parse(client).is_ok_and(|client| {
tools::read(&deps.state_root, &client)
.iter()
.any(|tool| tool.name == TOOL)
})
}
pub(crate) fn judged(
deps: &Deps,
workspace: &Path,
mut rows: Vec<ProviderRow>,
names: &[&str],
) -> Vec<ProviderRow> {
if rows.is_empty() {
return rows;
}
for name in names {
let far = named(deps, workspace, name).is_some_and(|at| advertises(deps, &at.client));
if far && !rows.iter().any(|row| row.name == *name) {
rows.push(ProviderRow {
name: (*name).to_owned(),
protocol: String::new(),
auth: String::new(),
credential: String::new(),
effort: false,
priority: false,
tools: None,
device: String::new(),
});
}
}
rows
}
fn asked(deps: &Deps, now: i64, clients: &[String], line: &[&str]) -> Vec<(String, Capture)> {
let (mail, by) = (&deps.caller.mailbox, deps.caller.client.name());
let mut open: Vec<(Call, Option<String>, Option<Capture>)> = clients
.iter()
.map(|client| {
let call = Call {
client: client.clone(),
tool: TOOL.to_owned(),
input: json!({ "args": line }),
cwd: None,
};
let invocation = mail.serving(client).then(|| mail.post(now, &by, &call));
(call, invocation, None)
})
.collect();
for _ in 0..WAITS {
for (call, invocation, got) in open.iter_mut().filter(|(_, _, got)| got.is_none()) {
*got = invocation
.as_deref()
.and_then(|id| mail.collect(now, &by, id, None).ok())
.and_then(|standing| standing.capture);
if let Some(fresh) = got.as_ref() {
mail.remember(now, call, fresh);
}
}
if open
.iter()
.all(|(_, invocation, got)| invocation.is_none() || got.is_some())
{
break;
}
std::thread::sleep(TICK);
}
open.into_iter()
.filter_map(|(call, _, got)| {
let got = got.or_else(|| mail.known(now, &call))?;
Some((call.client, got))
})
.collect()
}
pub(crate) fn rows(
deps: &Deps,
now: i64,
workspace: &Path,
line: &[&str],
) -> Vec<Placed<ProviderRowView>> {
let hosts: Vec<String> = machines(&deps.state_root, &crate::naming::leaf(workspace))
.into_iter()
.filter(|client| advertises(deps, client))
.collect();
asked(deps, now, &hosts, line)
.into_iter()
.flat_map(|(client, capture)| {
provider_rows(&capture.stdout).into_iter().map(move |row| {
let name = format!("{}@{client}", row.name);
let at = Some(Place {
client: client.clone(),
row: row.name.clone(),
});
let row = ProviderRow { name, ..row }.view();
Placed { row, at }
})
})
.collect()
}
pub(crate) fn run(deps: &Deps, now: i64, client: &str, line: &[&str]) -> Result<BzOutcome, String> {
if !advertises(deps, client) {
return Err(format!(
"client {client:?} advertises no tool {TOOL:?} right now"
));
}
let mail = &deps.caller.mailbox;
let parked = mail.serving(client);
let (_, capture) = asked(deps, now, &[client.to_owned()], line)
.pop()
.ok_or_else(|| {
if parked {
format!(
"client {client:?} did not answer within {} seconds",
(TICK * WAITS).as_secs()
)
} else if mail.busy(now, client) {
format!(
"client {client:?} is busy with another call, and it has not answered \
this read before — ask again when that call ends"
)
} else {
format!(
"client {client:?} is not there right now — it is asleep, or gone; \
/clients says when it last connected"
)
}
})?;
Ok(BzOutcome {
success: capture.exit_code == 0,
stdout: capture.stdout,
stderr: capture.stderr,
})
}
#[cfg(test)]
mod tests;