use crate::config::ApprovalConfig; use crate::telegram::{Telegram, Verdict}; use anyhow::{anyhow, Context, Result}; use serde_json::{json, Value}; use std::future::Future; use std::pin::Pin; use std::time::{Duration, Instant}; /// Shows a prompt and waits for its verdict: via this broker's own bot, or /// via the gateway that owns the shared one. pub enum Approver { Direct { tg: Telegram, host: String }, Gateway(GatewayClient), } pub struct GatewayClient { http: reqwest::Client, url: String, token: String, } impl Approver { pub fn new(cfg: &ApprovalConfig, host: &str) -> Result { Ok(match cfg { ApprovalConfig::Telegram(t) => { Approver::Direct { tg: Telegram::new(t)?, host: host.to_string() } } ApprovalConfig::Gateway(g) => Approver::Gateway(GatewayClient { http: reqwest::Client::builder().timeout(Duration::from_secs(40)).build()?, url: g.url.trim_end_matches('/').to_string(), token: std::fs::read_to_string(&g.token_file) .with_context(|| format!("reading {}", g.token_file.display()))? .trim() .to_string(), }), }) } /// `body` is the prompt without its "🔑 host:" header; the gateway adds /// that itself, from the token. pub async fn ask( &self, body: &str, timeout: Duration, gone: Pin<&mut impl Future>, ) -> Result { match self { Approver::Direct { tg, host } => tg.ask(&format!("🔑 {host}: {body}"), timeout, gone).await, Approver::Gateway(g) => g.ask(body, timeout, gone).await, } } } impl GatewayClient { async fn ask( &self, body: &str, timeout: Duration, mut gone: Pin<&mut impl Future>, ) -> Result { let resp: Value = self .http .post(format!("{}/ask", self.url)) .bearer_auth(&self.token) .json(&json!({ "text": body, "timeout_secs": timeout.as_secs() })) .send() .await .and_then(|r| r.error_for_status()) .map_err(|e| anyhow!("gateway: {}", e.without_url()))? .json() .await .map_err(|e| anyhow!("gateway: {}", e.without_url()))?; let id = resp["id"].as_str().ok_or_else(|| anyhow!("gateway returned no id"))?.to_string(); // The gateway expires the prompt itself; this only bounds a gateway // that stopped answering. let give_up = Instant::now() + timeout + Duration::from_secs(30); while Instant::now() < give_up { let polled = tokio::select! { biased; _ = gone.as_mut() => { let _ = self .http .delete(format!("{}/ask/{id}", self.url)) .bearer_auth(&self.token) .send() .await; return Ok(Verdict::Cancelled); } r = self.status(&id) => r, }; match polled { Ok(Some(v)) => return Ok(v), Ok(None) => {} Err(e) => { eprintln!("{e:#}"); tokio::time::sleep(Duration::from_secs(2)).await; } } } Ok(Verdict::Expired) } /// None while pending. async fn status(&self, id: &str) -> Result> { let resp = self .http .get(format!("{}/ask/{id}?wait=25", self.url)) .bearer_auth(&self.token) .send() .await .map_err(|e| anyhow!("gateway: {}", e.without_url()))?; // A restarted gateway has forgotten the prompt. if resp.status() == reqwest::StatusCode::NOT_FOUND { return Ok(Some(Verdict::Expired)); } let v: Value = resp .error_for_status() .map_err(|e| anyhow!("gateway: {}", e.without_url()))? .json() .await .map_err(|e| anyhow!("gateway: {}", e.without_url()))?; match v["status"].as_str() { Some("pending") => Ok(None), _ => Ok(Some(serde_json::from_value(v["status"].clone())?)), } } }