use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use anyhow::Result;
use serde_json::{Value, json};
use super::app::{PortRequest, PortRow};
use crate::inbox::{self, Op};
use crate::serve::client::{self, Conn};
use crate::serve::forwards::{Added, ForwardRow};
use crate::serve::endpoint;
use crate::serve::proto::Version;
const POLL: Duration = Duration::from_millis(100);
const JOIN_TIMEOUT: Duration = Duration::from_millis(300);
#[derive(Debug, PartialEq)]
pub enum DaemonUpdate {
InboxChanged,
InstancesChanged,
Shown(String),
Ports(Vec<PortRow>),
Status(String),
}
#[derive(Debug, PartialEq)]
enum Cmd {
Inbox(Vec<Op>),
EnsureBridge { instance: String, agent: Option<PathBuf> },
ForwardAdd(PortRequest),
ForwardRm(u64),
}
pub struct DaemonWorker {
tx: Option<Sender<Cmd>>,
updates: Receiver<DaemonUpdate>,
connected: Arc<AtomicBool>,
handle: Option<JoinHandle<()>>,
}
impl DaemonWorker {
pub fn spawn(dir: PathBuf) -> DaemonWorker {
let (tx, rx) = mpsc::channel();
let (utx, updates) = mpsc::channel();
let connected = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&connected);
let handle = std::thread::Builder::new()
.name("tui-daemon".into())
.spawn(move || run(&root_dir(dir), rx, utx, &flag))
.ok();
DaemonWorker { tx: Some(tx), updates, connected, handle }
}
pub fn connected(&self) -> bool {
self.handle.is_some() && self.connected.load(Ordering::Acquire)
}
pub fn apply(&self, ops: Vec<Op>) {
self.send(Cmd::Inbox(ops));
}
pub fn ensure_bridge(&self, instance: String, agent: Option<PathBuf>) {
self.send(Cmd::EnsureBridge { instance, agent });
}
pub fn forward_add(&self, req: PortRequest) {
self.send(Cmd::ForwardAdd(req));
}
pub fn forward_rm(&self, id: u64) {
self.send(Cmd::ForwardRm(id));
}
fn send(&self, cmd: Cmd) {
if let Some(tx) = &self.tx {
let _ = tx.send(cmd);
}
}
pub fn try_recv(&self) -> Option<DaemonUpdate> {
self.updates.try_recv().ok()
}
}
impl Drop for DaemonWorker {
fn drop(&mut self) {
self.tx.take();
if let Some(handle) = self.handle.take() {
let deadline = Instant::now() + JOIN_TIMEOUT;
while !handle.is_finished() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
if handle.is_finished() {
let _ = handle.join();
}
}
}
}
#[derive(Debug, Default)]
struct Backoff {
failures: u32,
}
impl Backoff {
const CAP: Duration = Duration::from_secs(30);
fn next(&mut self) -> Duration {
let delay = match self.failures {
0 => Duration::ZERO,
n => Duration::from_secs(1u64 << (n - 1).min(5)).min(Self::CAP),
};
self.failures = self.failures.saturating_add(1);
delay
}
fn reset(&mut self) {
self.failures = 0;
}
}
fn op_call(op: &Op) -> (&'static str, Value) {
match op {
Op::MarkRead(id) => ("inbox.thread.markRead", json!({ "thread": id })),
Op::MarkNotifyRead => ("inbox.notify.markRead", json!({ "all": true })),
Op::RemoveThread(id) => ("inbox.notify.dismiss", json!({ "thread": id })),
Op::ClearNotify => ("inbox.notify.dismiss", json!({ "all": true })),
Op::Act { thread, action } => ("inbox.thread.act", json!({ "thread": thread, "action": action })),
Op::Reply { thread, text } => ("inbox.thread.reply", json!({ "thread": thread, "text": text })),
Op::MarkDone(id) => ("inbox.thread.done", json!({ "thread": id })),
Op::Reopen(id) => ("inbox.thread.reopen", json!({ "thread": id })),
Op::SaveDraft { thread, message, answers } => (
"inbox.form.saveDraft",
json!({ "thread": thread, "message": message, "answers": inbox::form::partial_json(answers) }),
),
Op::Submit { thread, message, answers } => (
"inbox.form.submit",
json!({ "thread": thread, "message": message, "answers": inbox::form::partial_json(answers) }),
),
}
}
fn ensure_call(instance: &str, agent: Option<&std::path::Path>) -> (&'static str, Value) {
("bridges.ensure", json!({ "instance": instance, "agent": agent.and_then(|p| p.to_str()) }))
}
fn root_dir(dir: PathBuf) -> PathBuf {
dir.canonicalize().or_else(|_| std::path::absolute(&dir)).unwrap_or(dir)
}
fn list_call(dir: &Path) -> (&'static str, Value) {
("forwards.list", json!({ "dir": dir.to_string_lossy() }))
}
fn add_call(dir: &Path, req: &PortRequest) -> (&'static str, Value) {
let params = json!({
"dir": dir.to_string_lossy(),
"instance": (!req.instance.is_empty()).then_some(&req.instance),
"service": req.service,
"address": req.address,
"spec": req.spec,
});
("forwards.add", params)
}
fn rm_call(id: u64) -> (&'static str, Value) {
("forwards.rm", json!({ "id": id }))
}
fn port_rows(result: Value) -> Result<Vec<PortRow>> {
let rows: Vec<ForwardRow> = serde_json::from_value(result)?;
Ok(rows
.into_iter()
.map(|r| PortRow {
id: r.id,
local: r.local,
target: r.target,
process: r.process,
state: r.state,
conns: r.conns,
configured: r.configured,
})
.collect())
}
fn added_status(result: Value) -> String {
match serde_json::from_value::<Added>(result) {
Ok(a) => format!("forwarding {} -> {}", a.local, a.target),
Err(_) => "forwarding".into(),
}
}
fn removed_status(result: &Value) -> String {
let local = result.get("local").and_then(Value::as_str).unwrap_or("forward");
match result.get("configured").and_then(Value::as_bool) {
Some(true) => format!("stopped {local} (forwardPorts: back when its instance restarts)"),
_ => format!("stopped {local}"),
}
}
fn reports(op: &Op, code: &str) -> bool {
!(code == "not-found" && !op.enqueues_event())
}
fn open(after_handoff: bool) -> Result<Conn> {
let dir = endpoint::socket_dir()?;
let waited = after_handoff
.then(|| client::connect_with(&dir, "tui", &Version::current(), client::START_TIMEOUT, &|_, _| Ok(())).ok())
.flatten();
let mut conn = match waited {
Some(conn) => conn,
None => client::connect(&dir, "tui")?,
};
let r = conn.call("subscribe", json!({ "topics": ["inbox", "instances", "forwards"] }))?;
if let Some(e) = r.error {
anyhow::bail!("subscribe: {} ({})", e.message, e.code);
}
Ok(conn)
}
struct Worker<'a> {
dir: &'a Path,
utx: Sender<DaemonUpdate>,
connected: &'a AtomicBool,
conn: Option<Conn>,
backoff: Backoff,
next_attempt: Instant,
after_handoff: bool,
last_error: Option<String>,
down: Option<String>,
}
fn run(dir: &Path, rx: Receiver<Cmd>, utx: Sender<DaemonUpdate>, connected: &AtomicBool) {
let mut w = Worker {
dir,
utx,
connected,
conn: None,
backoff: Backoff::default(),
next_attempt: Instant::now(),
after_handoff: false,
last_error: None,
down: None,
};
loop {
if w.conn.is_none() && Instant::now() >= w.next_attempt {
w.connect();
}
let wait = match w.conn {
Some(_) => Duration::ZERO,
None => w.next_attempt.saturating_duration_since(Instant::now()).min(POLL),
};
match rx.recv_timeout(wait) {
Ok(Cmd::Inbox(ops)) => w.apply(ops),
Ok(Cmd::EnsureBridge { instance, agent }) => w.ensure_bridge(&instance, agent.as_deref()),
Ok(Cmd::ForwardAdd(req)) => w.forward_add(&req),
Ok(Cmd::ForwardRm(id)) => w.forward_rm(id),
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => return,
}
w.listen();
}
}
impl Worker<'_> {
fn send(&self, update: DaemonUpdate) {
let _ = self.utx.send(update);
}
fn connect(&mut self) {
match open(std::mem::take(&mut self.after_handoff)) {
Ok(conn) => {
self.conn = Some(conn);
self.connected.store(true, Ordering::Release);
self.backoff.reset();
self.last_error = None;
self.down = None;
self.send(DaemonUpdate::InboxChanged);
self.fetch_ports();
}
Err(e) => {
self.down = Some(format!("{e:#}"));
let msg = format!("host daemon unavailable: {e:#}");
if self.last_error.as_ref() != Some(&msg) {
self.send(DaemonUpdate::Status(msg.clone()));
self.last_error = Some(msg);
}
if self.backoff.failures == 0 {
self.backoff.next();
}
self.next_attempt = Instant::now() + self.backoff.next();
}
}
}
fn lost(&mut self, after_handoff: bool) {
self.conn = None;
self.connected.store(false, Ordering::Release);
self.send(DaemonUpdate::Ports(Vec::new()));
self.after_handoff = after_handoff;
self.next_attempt = Instant::now() + self.backoff.next();
}
fn listen(&mut self) {
let Some(conn) = self.conn.as_mut() else { return };
let note = match conn.next_notification(POLL) {
Ok(Some(note)) => note,
Ok(None) => return,
Err(_) => return self.lost(false),
};
match note.method.as_str() {
"inbox.changed" => self.send(DaemonUpdate::InboxChanged),
"instances.changed" => self.send(DaemonUpdate::InstancesChanged),
"forwards.changed" => self.fetch_ports(),
"forwards.status" => {
if let Some(line) = note.params.get("line").and_then(Value::as_str) {
self.send(DaemonUpdate::Status(line.to_string()));
}
}
"inbox.shown" => {
if let Some(line) = note.params.get("line").and_then(Value::as_str) {
self.send(DaemonUpdate::Shown(line.to_string()));
}
}
"closing" => {
let handoff = note.params.get("reason").and_then(Value::as_str) == Some("handoff");
self.lost(handoff);
}
_ => {}
}
}
fn ensure_bridge(&mut self, instance: &str, agent: Option<&std::path::Path>) {
let Some(conn) = self.conn.as_mut() else { return };
let (method, params) = ensure_call(instance, agent);
if conn.call(method, params).is_err() {
self.lost(false);
}
}
fn fetch_ports(&mut self) {
let Some(conn) = self.conn.as_mut() else { return };
let (method, params) = list_call(self.dir);
match conn.call(method, params) {
Ok(r) => match (r.result, r.error) {
(_, Some(e)) => self.send(DaemonUpdate::Status(format!("ports: {}", e.message))),
(Some(result), None) => match port_rows(result) {
Ok(rows) => self.send(DaemonUpdate::Ports(rows)),
Err(e) => self.send(DaemonUpdate::Status(format!("ports: {e:#}"))),
},
(None, None) => {}
},
Err(_) => self.lost(false),
}
}
fn forward_add(&mut self, req: &PortRequest) {
let Some(conn) = self.conn.as_mut() else {
let why = self.down.as_deref().unwrap_or("not connected");
return self.send(DaemonUpdate::Status(format!("port forwarding needs the host daemon: {why}")));
};
let (method, params) = add_call(self.dir, req);
match conn.call(method, params) {
Ok(r) => self.send(DaemonUpdate::Status(match (r.result, r.error) {
(_, Some(e)) => e.message,
(result, None) => added_status(result.unwrap_or_default()),
})),
Err(e) => {
self.lost(false);
self.send(DaemonUpdate::Status(format!("port forwarding needs the host daemon: {e:#}")));
}
}
}
fn forward_rm(&mut self, id: u64) {
let Some(conn) = self.conn.as_mut() else { return };
let (method, params) = rm_call(id);
match conn.call(method, params) {
Ok(r) => match (r.result, r.error) {
(_, Some(e)) if e.code == "not-found" => {}
(_, Some(e)) => self.send(DaemonUpdate::Status(e.message)),
(result, None) => self.send(DaemonUpdate::Status(removed_status(&result.unwrap_or_default()))),
},
Err(_) => self.lost(false),
}
}
fn apply(&mut self, ops: Vec<Op>) {
let mut local = Vec::new();
for op in ops {
let Some(conn) = self.conn.as_mut() else {
local.push(op);
continue;
};
let (method, params) = op_call(&op);
match conn.call(method, params) {
Ok(r) => {
if let Some(e) = r.error.filter(|e| reports(&op, &e.code)) {
self.send(DaemonUpdate::Status(format!("inbox not saved: {}", e.message)));
}
}
Err(e) => {
self.lost(false);
if op.enqueues_event() {
self.send(DaemonUpdate::Status(format!("inbox: may not be saved, check the thread: {e:#}")));
} else {
local.push(op);
}
}
}
}
if !local.is_empty() {
if let Err(e) = inbox::store::path().and_then(|p| inbox::ops::apply(&p, &local, "tui")) {
self.send(DaemonUpdate::Status(format!("inbox not saved: {e:#}")));
}
}
self.send(DaemonUpdate::InboxChanged);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ops_map_to_their_api_methods() {
let cases = [
(Op::MarkRead(3), "inbox.thread.markRead", json!({"thread": 3})),
(Op::MarkNotifyRead, "inbox.notify.markRead", json!({"all": true})),
(Op::RemoveThread(4), "inbox.notify.dismiss", json!({"thread": 4})),
(Op::ClearNotify, "inbox.notify.dismiss", json!({"all": true})),
(Op::Act { thread: 5, action: "go".into() }, "inbox.thread.act", json!({"thread": 5, "action": "go"})),
(Op::Reply { thread: 6, text: "hi".into() }, "inbox.thread.reply", json!({"thread": 6, "text": "hi"})),
(Op::MarkDone(7), "inbox.thread.done", json!({"thread": 7})),
(Op::Reopen(8), "inbox.thread.reopen", json!({"thread": 8})),
(
Op::SaveDraft { thread: 9, message: "m".into(), answers: [("q".to_string(), inbox::Answer::Choices(vec!["a".into()]))].into() },
"inbox.form.saveDraft",
json!({"thread": 9, "message": "m", "answers": {"q": ["a"]}}),
),
(
Op::Submit { thread: 9, message: "m".into(), answers: [("q".to_string(), inbox::Answer::Confirm(true))].into() },
"inbox.form.submit",
json!({"thread": 9, "message": "m", "answers": {"q": true}}),
),
];
for (op, method, params) in cases {
assert_eq!(op_call(&op), (method, params), "{op:?}");
}
}
#[test]
fn mapped_calls_match_the_local_path() {
use crate::devsbd::notify::{Level, Record};
use crate::inbox::{Action, Compose, State, ThreadPut, store};
use crate::serve::api::{self, Ctx};
let seed = |path: &std::path::Path| {
let put = ThreadPut {
key: "k".into(),
title: "t".into(),
state: State::NeedsYou,
compose: Some(Compose::default()),
actions: vec![Action { id: "go".into(), label: "Go".into(), ..Action::default() }],
..ThreadPut::default()
};
store::update_at(path, |i| i.put("d-id", "d", 1, put)).unwrap();
let blocks = vec![inbox::Block::Form(inbox::form::tests::mixed())];
let send = inbox::MessageSend { thread: "k".into(), id: "m".into(), blocks };
store::update_at(path, |i| i.send("d-id", 1, send)).unwrap();
let record = Record { level: Level::Info, key: None, link: None, msg: "n".into(), at: 1 };
store::update_at(path, |i| i.push("w-id".into(), "w".into(), record, true)).unwrap();
};
let dir = std::env::temp_dir().join(format!("devsandbox-tui-daemon-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (via_api, via_ops) = (dir.join("api.json"), dir.join("ops.json"));
seed(&via_api);
seed(&via_ops);
let inbox = inbox::ops::load(&via_api).unwrap();
let thread = inbox.threads.iter().find(|t| t.kind == inbox::Kind::Thread).unwrap().id;
let note = inbox.threads.iter().find(|t| t.kind == inbox::Kind::Notify).unwrap().id;
let ops = [
Op::MarkRead(thread),
Op::Act { thread, action: "go".into() },
Op::Reply { thread, text: "hi".into() },
Op::MarkDone(thread),
Op::Reopen(thread),
Op::SaveDraft { thread, message: "m".into(), answers: [("pick".to_string(), inbox::Answer::Choice("a".into()))].into() },
Op::Submit { thread, message: "m".into(), answers: [("note".to_string(), inbox::Answer::Text("hi".into()))].into() },
Op::MarkNotifyRead,
Op::RemoveThread(note),
Op::ClearNotify,
];
for op in &ops {
let (method, params) = op_call(op);
api::call(method, params, &Ctx { inbox: &via_api, client: "tui", bridges: None, forwards: None }).unwrap_or_else(|e| panic!("{op:?}: {e:?}"));
inbox::ops::apply(&via_ops, std::slice::from_ref(op), "tui").unwrap();
}
let strip = |path: &std::path::Path| -> String {
let i = inbox::ops::load(path).unwrap();
let events = inbox::ops::events(path, "d-id").unwrap();
let t: Vec<_> = i.threads.iter().map(|t| (t.id, t.kind, t.state, t.unread, t.feed.iter().map(|f| f.kind.clone()).collect::<Vec<_>>())).collect();
let e: Vec<_> = events.into_iter().map(|(_, e)| (e.kind.as_str().to_string(), e.action, e.text, e.message, e.form, e.answers)).collect();
format!("{t:?} {e:?}")
};
assert_eq!(strip(&via_api), strip(&via_ops));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn commands_map_to_their_api_methods() {
assert_eq!(
ensure_call("web", Some(std::path::Path::new("/tmp/ssh-x/agent.1"))),
("bridges.ensure", json!({"instance": "web", "agent": "/tmp/ssh-x/agent.1"}))
);
assert_eq!(ensure_call("web", None), ("bridges.ensure", json!({"instance": "web", "agent": null})));
let (tx, rx) = mpsc::channel();
let (_utx, updates) = mpsc::channel();
let worker = DaemonWorker { tx: Some(tx), updates, connected: Arc::default(), handle: None };
worker.apply(vec![Op::MarkRead(1)]);
worker.ensure_bridge("web".into(), Some("/a".into()));
assert_eq!(rx.try_recv().unwrap(), Cmd::Inbox(vec![Op::MarkRead(1)]));
assert_eq!(rx.try_recv().unwrap(), Cmd::EnsureBridge { instance: "web".into(), agent: Some("/a".into()) });
}
#[test]
fn ensure_call_is_accepted_by_the_api() {
use crate::serve::api::{self, Bridging, Ctx};
struct Knows;
impl Bridging for Knows {
fn container(&self, _: &str) -> anyhow::Result<Option<String>> {
Ok(Some("devsandbox-web".into()))
}
fn report_agent(&self, _: PathBuf) {}
fn reconcile_now(&self, _: String) -> u64 {
1
}
fn wait_ready(&self, _: &str, _: u64, _: std::time::Duration) -> crate::devsbd::bridge::Readiness {
unreachable!("the dashboard never waits")
}
}
let path = std::env::temp_dir().join(format!("devsandbox-tui-ensure-{}", std::process::id())).join("inbox.json");
let (method, params) = ensure_call("web", Some(std::path::Path::new("/a")));
assert_eq!(api::call(method, params, &Ctx { inbox: &path, client: "tui", bridges: Some(&Knows), forwards: None }), Ok(json!({"ok": true})));
}
fn port_req(instance: &str, service: Option<&str>) -> PortRequest {
PortRequest { instance: instance.into(), service: service.map(String::from), address: None, spec: "8080:3000".into() }
}
#[test]
fn forward_commands_queue_and_map_to_their_api_methods() {
let (tx, rx) = mpsc::channel();
let (_utx, updates) = mpsc::channel();
let worker = DaemonWorker { tx: Some(tx), updates, connected: Arc::default(), handle: None };
worker.forward_add(port_req("web", None));
worker.forward_rm(4);
assert_eq!(rx.try_recv().unwrap(), Cmd::ForwardAdd(port_req("web", None)));
assert_eq!(rx.try_recv().unwrap(), Cmd::ForwardRm(4));
let dir = Path::new("/cfg");
assert_eq!(list_call(dir), ("forwards.list", json!({"dir": "/cfg"})));
assert_eq!(rm_call(4), ("forwards.rm", json!({"id": 4})));
assert_eq!(
add_call(dir, &port_req("web", None)),
(
"forwards.add",
json!({"dir": "/cfg", "instance": "web", "service": null, "address": null, "spec": "8080:3000"})
)
);
assert_eq!(add_call(dir, &port_req("", Some("db"))).1["instance"], Value::Null);
assert!(root_dir(PathBuf::from("rel/dir")).is_absolute());
}
#[test]
fn forward_calls_are_accepted_by_the_api_and_answers_render() {
use crate::serve::api::{self, ApiError, Ctx, Forwarding};
use crate::serve::forwards::{AddRequest, Removed};
struct Fake;
impl Forwarding for Fake {
fn list(&self, dir: Option<PathBuf>) -> Result<Vec<ForwardRow>, ApiError> {
assert_eq!(dir.as_deref(), Some(Path::new("/cfg")));
Ok(vec![ForwardRow {
id: 3,
dir: "/cfg".into(),
local: "127.0.0.1:8080".into(),
target: "web:3000".into(),
process: Some("node (pid 1)".into()),
state: "active".into(),
conns: 2,
configured: true,
}])
}
fn add(&self, req: AddRequest) -> Result<Added, ApiError> {
assert_eq!(req.instance.as_deref(), Some("web"));
Ok(Added { id: 3, local: "127.0.0.1:8080".into(), target: "web:3000".into() })
}
fn rm(&self, _: u64) -> Result<Removed, ApiError> {
Ok(Removed { local: "127.0.0.1:8080".into(), configured: true })
}
}
let path = std::env::temp_dir().join(format!("devsandbox-tui-fwd-{}", std::process::id())).join("inbox.json");
let ctx = Ctx { inbox: &path, client: "tui", bridges: None, forwards: Some(&Fake) };
let dir = Path::new("/cfg");
let (method, params) = list_call(dir);
let rows = port_rows(api::call(method, params, &ctx).unwrap()).unwrap();
assert_eq!(
rows,
[PortRow {
id: 3,
local: "127.0.0.1:8080".into(),
target: "web:3000".into(),
process: Some("node (pid 1)".into()),
state: "active".into(),
conns: 2,
configured: true,
}]
);
let (method, params) = add_call(dir, &port_req("web", None));
assert_eq!(added_status(api::call(method, params, &ctx).unwrap()), "forwarding 127.0.0.1:8080 -> web:3000");
let (method, params) = rm_call(3);
assert_eq!(
removed_status(&api::call(method, params, &ctx).unwrap()),
"stopped 127.0.0.1:8080 (forwardPorts: back when its instance restarts)"
);
assert_eq!(removed_status(&json!({"ok": true, "local": "127.0.0.1:1", "configured": false})), "stopped 127.0.0.1:1");
}
#[test]
fn stale_targets_are_quiet_but_lost_events_are_not() {
assert!(!reports(&Op::MarkRead(1), "not-found"));
assert!(!reports(&Op::RemoveThread(1), "not-found"));
assert!(!reports(&Op::MarkNotifyRead, "not-found"));
assert!(reports(&Op::MarkDone(1), "not-found"));
assert!(reports(&Op::Act { thread: 1, action: "a".into() }, "not-found"));
assert!(reports(&Op::MarkRead(1), "internal"));
assert!(reports(&Op::Reply { thread: 1, text: "x".into() }, "denied"));
}
#[test]
fn backoff_retries_at_once_then_doubles_to_the_cap() {
let mut b = Backoff::default();
let secs: Vec<u64> = (0..9).map(|_| b.next().as_secs()).collect();
assert_eq!(secs, [0, 1, 2, 4, 8, 16, 30, 30, 30]);
b.reset();
assert_eq!(b.next(), Duration::ZERO);
assert_eq!(b.next(), Duration::from_secs(1));
let mut b = Backoff { failures: u32::MAX - 1 };
assert_eq!((b.next(), b.next()), (Backoff::CAP, Backoff::CAP));
}
}