//! The service's client side, shared by proxy-ctl and the app: requests, configuration //! edits made against the revision they read, and the edits both make ([`edits`]). pub mod edits; use anyhow::{Result, bail}; use ps_ipc::transport::{self, Address}; use ps_ipc::{Request, Response}; use serde_json::Value; /// What a configuration edit got back: the new revision, the validator's notes, and the /// error applying it, when it was saved but did not apply. #[derive(Debug, Clone, Default)] pub struct Saved { pub revision: Option, pub issues: Vec, pub apply_error: Option, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Issue { pub severity: String, pub path: String, pub message: String, } impl std::fmt::Display for Issue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}: {}: {}", self.severity, self.path, self.message) } } /// The validator's notes in a response's data. pub fn issues(data: &Value) -> Vec { data["issues"] .as_array() .into_iter() .flatten() .map(|i| Issue { severity: i["severity"].as_str().unwrap_or("").to_owned(), path: i["path"].as_str().unwrap_or("").to_owned(), message: i["message"].as_str().unwrap_or("").to_owned(), }) .collect() } #[derive(Debug, Clone)] pub struct Client { pub addr: Address, } impl Client { pub fn new(addr: Address) -> Self { Self { addr } } /// One request; a refusal is an error carrying the service's words and its notes. pub async fn call(&self, req: Request) -> Result { let resp: Response = transport::call(&self.addr, &req).await?; if !resp.ok { let mut msg = resp.error.unwrap_or_else(|| "failed".into()); for i in issues(&resp.data) { msg.push_str(&format!("\n {i}")); } bail!(msg); } Ok(resp.data) } /// Reads the configuration, lets `edit` change it, and writes it back against the /// revision read; a concurrent change is read again and `edit` made again. pub async fn edit(&self, edit: impl Fn(&mut Value) -> Result<()>) -> Result { for _ in 0..3 { let got = self.call(Request::ConfigGet).await?; let mut config = got["config"].clone(); edit(&mut config)?; match self.call(Request::ConfigSet { config, base: got["revision"].as_u64() }).await { Err(e) if e.to_string().contains("changed since revision") => continue, other => { let r = other?; return Ok(Saved { revision: r["revision"].as_u64(), issues: issues(&r), apply_error: r["error"].as_str().map(str::to_owned), }); } } } bail!("the configuration kept changing; try again") } /// Log lines (every unit's without `unit`) as `(unit, line)`, the last `lines` and, with /// `follow`, each new one, until `each` says stop. pub async fn logs(&self, unit: Option, lines: usize, follow: bool, mut each: impl FnMut(&str, &str) -> bool) -> Result<()> { let mut take = |r: Response| { let one = |l: &Value| (l["unit"].as_str().unwrap_or("").to_owned(), l["line"].as_str().unwrap_or("").to_owned()); match &r.data { Value::Array(ls) => ls.iter().map(one).all(|(u, l)| each(&u, &l)), d if d.is_object() => { let (u, l) = one(d); each(&u, &l) } _ => true, } }; let req = Request::Logs { unit, lines, follow }; if follow { let mut refused = None; transport::stream(&self.addr, &req, |r| { if !r.ok { refused = Some(r.error.unwrap_or_else(|| "failed".into())); return false; } take(r) }) .await?; if let Some(e) = refused { bail!(e); } } else { let r = transport::call(&self.addr, &req).await?; if !r.ok { bail!(r.error.unwrap_or_else(|| "failed".into())); } take(r); } Ok(()) } }