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::{
ConfigKind, Fetch, IdentityOn, IdentityReq, PendingDone, PendingSessionRm, PendingSignal, PortRequest, PortRow,
};
use super::prompt::PromptAction;
use crate::serve::verbs_client::identity::{self, Ask, Group, Scope};
use crate::build_log::Tail;
use crate::config::SandboxText;
use crate::inbox::{self, Op};
use crate::broker::asks;
use crate::serve::api::{AccessRequest, InstancesList};
use crate::serve::client::{self, Conn};
use crate::serve::forwards::{Added, ForwardRow};
use crate::serve::endpoint;
use crate::serve::proto::{Response, Version};
use crate::serve::snapshots::SnapshotMachine;
use super::remote::{Route, split};
const POLL: Duration = Duration::from_millis(100);
const JOIN_TIMEOUT: Duration = Duration::from_millis(300);
#[derive(Debug)]
pub enum DaemonUpdate {
InboxChanged,
InstancesChanged,
Snapshot(InstancesList, Vec<SnapshotMachine>),
Down(String),
Shown(String),
Ports(Vec<PortRow>),
Status(String),
Logs { container: String, body: String },
Config { kind: ConfigKind, name: String, text: Result<SandboxText, String> },
Inspect { container: String, body: String },
Sessions { instance: String, lines: Result<Vec<String>, String> },
BuildLog { instance: String, read: Result<Option<Tail>, String> },
Signalled(String),
Renamed(String),
ProfileSet(String),
Done { status: String, failed: bool, report: bool },
IdentityOffer { groups: Vec<Group>, asked: bool },
Identity { outcome: Result<String, String>, then: Option<PromptAction> },
AccessPending(Vec<AccessRequest>),
}
#[derive(Debug, PartialEq)]
enum Cmd {
Inbox(Vec<Op>),
ForwardAdd(PortRequest),
ForwardRm(u64),
MachineSet { name: String, agent: bool },
Cancel(String),
Fetch(Fetch, Route),
BuildLog(String),
Signal(PendingSignal),
SessionRm(PendingSessionRm, Route),
Rename { instance: String, new_name: String },
SetProfile { instance: String, profile: String },
Done(PendingDone),
Identity(IdentityReq),
AccessDecide { request: String, answer: asks::Answer },
}
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), &connect, 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 forward_add(&self, req: PortRequest) {
self.send(Cmd::ForwardAdd(req));
}
pub fn forward_rm(&self, id: u64) {
self.send(Cmd::ForwardRm(id));
}
pub fn machine_set(&self, name: String, agent: bool) {
self.send(Cmd::MachineSet { name, agent });
}
pub fn cancel(&self, instance: String) {
self.send(Cmd::Cancel(instance));
}
pub fn fetch(&self, fetch: Fetch, route: Route) {
self.send(Cmd::Fetch(fetch, route));
}
pub fn build_log(&self, id: String) {
self.send(Cmd::BuildLog(id));
}
pub fn signal(&self, sig: PendingSignal) {
self.send(Cmd::Signal(sig));
}
pub fn session_rm(&self, rm: PendingSessionRm, route: Route) {
self.send(Cmd::SessionRm(rm, route));
}
pub fn rename(&self, instance: String, new_name: String) {
self.send(Cmd::Rename { instance, new_name });
}
pub fn set_profile(&self, instance: String, profile: String) {
self.send(Cmd::SetProfile { instance, profile });
}
pub fn set_done(&self, req: PendingDone) {
self.send(Cmd::Done(req));
}
pub fn identity(&self, req: IdentityReq) {
self.send(Cmd::Identity(req));
}
pub fn access_decide(&self, request: String, answer: asks::Answer) {
self.send(Cmd::AccessDecide { request, answer });
}
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) }),
),
}
}
pub(super) fn root_dir(dir: PathBuf) -> PathBuf {
dir.canonicalize().or_else(|_| std::path::absolute(&dir)).unwrap_or(dir)
}
fn on_machine((method, mut params): (&'static str, Value), machine: Option<&str>) -> (&'static str, Value) {
if let (Some(m), Some(obj)) = (machine, params.as_object_mut()) {
obj.insert("machine".into(), m.into());
}
(method, params)
}
fn cancel_call(key: &str) -> (&'static str, Value) {
let (machine, instance) = split(key);
on_machine(("instances.cancel", json!({ "instance": instance })), machine)
}
fn cancel_status(instance: &str, r: Response) -> String {
match (r.result, r.error) {
(_, Some(e)) => format!("cancel {instance}: {}", e.message),
(result, None) => match result.as_ref().and_then(|v| v.get("pid")).and_then(Value::as_u64) {
Some(pid) => format!("cancelling {instance} (SIGINT to pid {pid})"),
None => format!("cancelling {instance}"),
},
}
}
#[derive(Debug, PartialEq)]
enum Answer {
Ok(Value),
Refused(String),
Unreachable(String),
}
impl Answer {
fn from_response(r: Response) -> Answer {
match (r.result, r.error) {
(_, Some(e)) => Answer::Refused(e.message),
(result, None) => Answer::Ok(result.unwrap_or(Value::Null)),
}
}
fn parse<T: serde::de::DeserializeOwned>(self, what: &str) -> Result<T, String> {
match self {
Answer::Ok(v) => serde_json::from_value(v).map_err(|e| format!("{what}: unexpected answer: {e}")),
Answer::Refused(msg) | Answer::Unreachable(msg) => Err(msg),
}
}
}
fn needs_serve(what: &str, why: Option<&str>) -> String {
match why {
Some(why) => format!("{what}: needs devsandbox serve ({why})"),
None => format!("{what}: needs devsandbox serve"),
}
}
fn fetch_call(root: &Path, fetch: &Fetch, route: &Route) -> (&'static str, (&'static str, Value)) {
match fetch {
Fetch::Logs { container } => {
let (machine, container) = split(container);
let call = ("containers.logs", json!({ "container": container, "lines": super::app::LOG_LINES }));
("logs", on_machine(call, machine))
}
Fetch::Inspect { container } => {
let (machine, container) = split(container);
("inspect", on_machine(("containers.inspect", json!({ "container": container })), machine))
}
Fetch::Config { kind, name } => {
let method = match kind {
ConfigKind::Sandbox => "sandboxes.get",
ConfigKind::Service => "services.get",
};
let (machine, name) = split(name);
let root = match (machine, &route.root) {
(Some(_), Some(remote)) => remote.clone(),
_ => root.to_string_lossy().into_owned(),
};
("config", on_machine((method, json!({ "root": root, "name": name })), machine))
}
Fetch::Sessions { instance } => {
let (machine, instance) = split(instance);
let root = match (machine, &route.root) {
(Some(_), Some(remote)) => remote.clone(),
_ => root.to_string_lossy().into_owned(),
};
("attach", on_machine(("sessions.list", json!({ "root": root, "instance": instance })), machine))
}
}
}
fn fetch_update(fetch: Fetch, answer: Answer) -> DaemonUpdate {
let body = |answer: Answer, f: fn(Value) -> String| match answer {
Answer::Ok(v) => f(v),
Answer::Refused(msg) | Answer::Unreachable(msg) => msg,
};
match fetch {
Fetch::Logs { container } => DaemonUpdate::Logs { container, body: body(answer, logs_body) },
Fetch::Inspect { container } => DaemonUpdate::Inspect { container, body: body(answer, inspect_body) },
Fetch::Config { kind: ConfigKind::Sandbox, name } => {
DaemonUpdate::Config { kind: ConfigKind::Sandbox, name, text: answer.parse("config") }
}
Fetch::Config { kind: ConfigKind::Service, name } => {
let text = answer.parse::<crate::serve::api::ServiceConfig>("config").map(|s| SandboxText {
resolved: s.original.clone(),
original: s.original,
hash: String::new(),
});
DaemonUpdate::Config { kind: ConfigKind::Service, name, text }
}
Fetch::Sessions { instance } => {
let lines = match answer {
Answer::Refused(msg) => Err(format!("attach: {msg}")),
answer => answer.parse::<crate::serve::api::SessionsList>("attach").map(|s| s.sessions),
};
DaemonUpdate::Sessions { instance, lines }
}
}
}
fn logs_body(result: Value) -> String {
let text = result.get("text").and_then(Value::as_str).unwrap_or_default();
if text.trim().is_empty() { "(no log output)".to_string() } else { text.to_string() }
}
fn inspect_body(result: Value) -> String {
serde_json::to_string_pretty(&result).unwrap_or_else(|e| format!("cannot format inspect JSON: {e}"))
}
fn build_log_call(key: &str) -> (&'static str, Value) {
let (machine, instance) = split(key);
let call = ("instances.buildLog", json!({ "instance": instance, "lines": super::app::BUILD_LOG_LINES, "ansi": true }));
on_machine(call, machine)
}
fn signal_call(sig: &PendingSignal) -> (&'static str, Value) {
let (machine, instance) = split(&sig.instance);
let call = ("instances.signal", json!({ "instance": instance, "pid": sig.pid, "signal": sig.signal.wire() }));
on_machine(call, machine)
}
fn signal_status(sig: &PendingSignal, answer: Answer) -> String {
match answer {
Answer::Ok(_) => format!("sent {} to pid {}", sig.signal.name(), sig.pid),
Answer::Refused(msg) => format!("{}: {msg}", sig.signal.name()),
Answer::Unreachable(line) => line,
}
}
fn session_rm_call(root: &Path, rm: &PendingSessionRm, route: &Route) -> (&'static str, Value) {
let (machine, instance) = split(&rm.instance);
let root = match (machine, &route.root) {
(Some(_), Some(remote)) => remote.clone(),
_ => root.to_string_lossy().into_owned(),
};
on_machine(("sessions.rm", json!({ "root": root, "instance": instance, "id": rm.id })), machine)
}
fn session_rm_status(rm: &PendingSessionRm, answer: Answer) -> String {
match answer {
Answer::Ok(_) => format!("ended session {} in {}", rm.id, rm.instance),
Answer::Refused(msg) => format!("end session: {msg}"),
Answer::Unreachable(line) => line,
}
}
fn rename_call(key: &str, new_name: &str) -> (&'static str, Value) {
let (machine, instance) = split(key);
on_machine(("instances.rename", json!({ "instance": instance, "newName": new_name })), machine)
}
fn rename_status(instance: &str, new_name: &str, answer: Answer) -> String {
match answer {
Answer::Ok(v) => {
let renamed = v.get("instance").and_then(Value::as_str).unwrap_or(new_name);
format!("renamed {instance} -> {renamed}")
}
Answer::Refused(msg) => format!("rename failed: {msg}"),
Answer::Unreachable(line) => line,
}
}
fn set_profile_call(key: &str, profile: &str) -> (&'static str, Value) {
let (machine, instance) = split(key);
on_machine(("instances.setProfile", json!({ "instance": instance, "profile": profile })), machine)
}
fn set_profile_status(instance: &str, profile: &str, answer: Answer) -> String {
match answer {
Answer::Ok(v) => format!("{instance}: profile {}", v.get("profile").and_then(Value::as_str).unwrap_or(profile)),
Answer::Refused(msg) => format!("profile failed: {msg}"),
Answer::Unreachable(line) => line,
}
}
fn done_call(req: &PendingDone) -> (&'static str, Value) {
let (machine, instance) = split(&req.instance);
on_machine(("instances.done", json!({ "instance": instance, "done": req.done })), machine)
}
fn done_status(req: &PendingDone, answer: Answer) -> (String, bool) {
let verb = if req.done { "done" } else { "undone" };
match answer {
Answer::Ok(v) if v.get("warning").is_some_and(Value::is_string) => {
(format!("marked {} done; {}", req.instance, v["warning"].as_str().unwrap_or_default()), true)
}
Answer::Ok(_) if req.done => (format!("marked {} done", req.instance), false),
Answer::Ok(_) => (format!("marked {} not done", req.instance), false),
Answer::Refused(msg) => (format!("{verb}: {msg}"), true),
Answer::Unreachable(line) => (line, true),
}
}
fn identity_ask(dir: &Path, route: &Route, scope: Scope) -> Option<Ask> {
let root = match (&route.machine, &route.root) {
(None, _) => dir.to_path_buf(),
(Some(_), Some(root)) => PathBuf::from(root),
(Some(_), None) => return None,
};
Some(Ask { root, machine: route.machine.clone(), scope })
}
fn identity_outcome(done: Result<()>, said: Vec<String>) -> Result<String, String> {
done.map_err(|e| format!("{e:#}"))?;
Ok(said.iter().flat_map(|s| s.lines()).map(str::trim).filter(|l| !l.is_empty()).collect::<Vec<_>>().join("; "))
}
fn access_decide_call(request: &str, answer: asks::Answer) -> (&'static str, Value) {
("access.decide", json!({ "request": request, "answer": answer.marker() }))
}
fn access_decide_status(request: &str, answer: asks::Answer, reply: Answer) -> String {
#[derive(serde::Deserialize)]
struct Decided {
request: AccessRequest,
}
match reply {
Answer::Refused(msg) => format!("{request}: {msg}"),
reply => match reply.parse::<Decided>("access") {
Ok(d) => crate::commands::access::decided_line(&d.request, answer),
Err(line) => line,
},
}
}
fn access_requests(reply: Answer) -> Result<Vec<AccessRequest>, String> {
#[derive(serde::Deserialize)]
struct Pending {
requests: Vec<AccessRequest>,
}
match reply {
Answer::Refused(msg) => Err(format!("access: {msg}")),
reply => reply.parse::<Pending>("access").map(|p| p.requests),
}
}
fn list_call(dir: &Path) -> (&'static str, Value) {
("forwards.list", json!({ "dir": dir.to_string_lossy(), "machines": true }))
}
fn add_call(dir: &Path, req: &PortRequest) -> (&'static str, Value) {
let dir = match (&req.machine, &req.root) {
(Some(_), Some(root)) => root.clone(),
_ => dir.to_string_lossy().into_owned(),
};
let mut params = json!({
"dir": dir,
"instance": (!req.instance.is_empty()).then_some(&req.instance),
"service": req.service,
"address": req.address,
"spec": req.spec,
});
if let Some(machine) = &req.machine {
params["machine"] = json!(machine);
}
("forwards.add", params)
}
fn rm_call(id: u64) -> (&'static str, Value) {
("forwards.rm", json!({ "id": id }))
}
fn machine_set_call(name: &str, agent: bool) -> (&'static str, Value) {
("machines.set", json!({ "name": name, "agent": agent }))
}
fn machine_set_status(name: &str, agent: bool) -> String {
format!("{name}: agent {}", if agent { "on" } else { "off" })
}
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,
open: r.open,
machine: r.machine,
})
.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())
}
type Connector = dyn Fn(bool) -> Result<Conn>;
fn connect(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();
match waited {
Some(conn) => Ok(conn),
None => client::connect(&dir, "tui"),
}
}
fn watch_call(dir: &Path) -> (&'static str, Value) {
("instances.watch", json!({ "dir": dir.to_string_lossy(), "machines": true }))
}
fn open(connect: &Connector, dir: &Path, after_handoff: bool) -> Result<Conn> {
let mut conn = connect(after_handoff)?;
let r = conn.call("subscribe", json!({ "topics": ["inbox", "instances", "forwards", "opens", "access"] }))?;
if let Some(e) = r.error {
anyhow::bail!("subscribe: {} ({})", e.message, e.code);
}
let (method, params) = watch_call(dir);
let r = conn.call(method, params)?;
if let Some(e) = r.error {
anyhow::bail!("{method}: {} ({})", e.message, e.code);
}
Ok(conn)
}
fn snapshot_update(mut params: Value) -> DaemonUpdate {
let machines = params.as_object_mut().and_then(|o| o.remove("machines")).unwrap_or(Value::Null);
let machines = match machines {
Value::Null => Ok(Vec::new()),
v => serde_json::from_value::<Vec<SnapshotMachine>>(v),
};
match (serde_json::from_value::<InstancesList>(params), machines) {
(Ok(list), Ok(machines)) => DaemonUpdate::Snapshot(list, machines),
(Err(e), _) | (_, Err(e)) => DaemonUpdate::Status(format!("bad instances.snapshot: {e}")),
}
}
fn line_update(method: &str, params: &Value) -> Option<DaemonUpdate> {
let line = params.get("line").and_then(Value::as_str)?.to_string();
match method {
"inbox.shown" => Some(DaemonUpdate::Shown(line)),
"forwards.status" | "opens.done" => Some(DaemonUpdate::Status(line)),
_ => None,
}
}
struct Worker<'a> {
dir: &'a Path,
connector: &'a Connector,
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, connector: &Connector, rx: Receiver<Cmd>, utx: Sender<DaemonUpdate>, connected: &AtomicBool) {
let mut w = Worker {
dir,
connector,
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::ForwardAdd(req)) => w.forward_add(&req),
Ok(Cmd::ForwardRm(id)) => w.forward_rm(id),
Ok(Cmd::MachineSet { name, agent }) => w.machine_set(&name, agent),
Ok(Cmd::Cancel(instance)) => w.cancel(&instance),
Ok(Cmd::Fetch(fetch, route)) => w.fetch(fetch, &route),
Ok(Cmd::BuildLog(id)) => w.build_log(id),
Ok(Cmd::Signal(sig)) => w.signal(sig),
Ok(Cmd::SessionRm(rm, route)) => w.session_rm(rm, &route),
Ok(Cmd::Rename { instance, new_name }) => w.rename(&instance, &new_name),
Ok(Cmd::SetProfile { instance, profile }) => w.set_profile(&instance, &profile),
Ok(Cmd::Done(req)) => w.set_done(req),
Ok(Cmd::Identity(req)) => w.identity(req),
Ok(Cmd::AccessDecide { request, answer }) => w.access_decide(&request, answer),
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(self.connector, self.dir, 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();
self.fetch_access();
}
Err(e) => {
self.down = Some(format!("{e:#}"));
self.send(DaemonUpdate::Down(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.send(DaemonUpdate::AccessPending(Vec::new()));
self.send(DaemonUpdate::Down("connection lost".into()));
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.snapshot" => self.send(snapshot_update(note.params)),
"instances.changed" => self.send(DaemonUpdate::InstancesChanged),
"forwards.changed" => self.fetch_ports(),
"access.changed" => self.fetch_access(),
"forwards.status" | "opens.done" | "inbox.shown" => {
if let Some(update) = line_update(¬e.method, ¬e.params) {
self.send(update);
}
}
"closing" => {
let handoff = note.params.get("reason").and_then(Value::as_str) == Some("handoff");
self.lost(handoff);
}
_ => {}
}
}
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 fetch_access(&mut self) {
if self.conn.is_none() {
return;
}
let reply = self.one_shot("access", ("access.pending", json!({})));
match access_requests(reply) {
Ok(list) => self.send(DaemonUpdate::AccessPending(list)),
Err(line) => self.send(DaemonUpdate::Status(line)),
}
}
fn access_decide(&mut self, request: &str, answer: asks::Answer) {
let reply = self.one_shot("access", access_decide_call(request, answer));
self.send(DaemonUpdate::Status(access_decide_status(request, answer, reply)));
}
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 machine_set(&mut self, name: &str, agent: bool) {
let Some(conn) = self.conn.as_mut() else {
let line = needs_serve(&machine_set_status(name, agent), self.down.as_deref());
return self.send(DaemonUpdate::Status(line));
};
let (method, params) = machine_set_call(name, agent);
match conn.call(method, params) {
Ok(r) => match r.error {
Some(e) => self.send(DaemonUpdate::Status(e.message)),
None => self.send(DaemonUpdate::Status(machine_set_status(name, agent))),
},
Err(_) => self.lost(false),
}
}
fn cancel(&mut self, instance: &str) {
let Some(conn) = self.conn.as_mut() else {
let line = match &self.down {
Some(why) => format!("cancel {instance}: needs devsandbox serve ({why})"),
None => format!("cancel {instance}: needs devsandbox serve"),
};
return self.send(DaemonUpdate::Status(line));
};
let (method, params) = cancel_call(instance);
match conn.call(method, params) {
Ok(r) => self.send(DaemonUpdate::Status(cancel_status(instance, r))),
Err(e) => {
self.lost(false);
self.send(DaemonUpdate::Status(format!("cancel {instance}: needs devsandbox serve ({e:#})")));
}
}
}
fn one_shot(&mut self, what: &str, (method, params): (&str, Value)) -> Answer {
let Some(conn) = self.conn.as_mut() else {
return Answer::Unreachable(needs_serve(what, self.down.as_deref()));
};
match conn.call(method, params) {
Ok(r) => Answer::from_response(r),
Err(e) => {
self.lost(false);
Answer::Unreachable(needs_serve(what, Some(&format!("{e:#}"))))
}
}
}
fn fetch(&mut self, fetch: Fetch, route: &Route) {
let (what, call) = fetch_call(self.dir, &fetch, route);
let answer = self.one_shot(what, call);
self.send(fetch_update(fetch, answer));
}
fn build_log(&mut self, instance: String) {
let read = self.one_shot("build log", build_log_call(&instance)).parse("build log");
self.send(DaemonUpdate::BuildLog { instance, read });
}
fn signal(&mut self, sig: PendingSignal) {
let answer = self.one_shot(sig.signal.name(), signal_call(&sig));
self.send(DaemonUpdate::Signalled(signal_status(&sig, answer)));
}
fn session_rm(&mut self, rm: PendingSessionRm, route: &Route) {
let answer = self.one_shot("end session", session_rm_call(self.dir, &rm, route));
self.send(DaemonUpdate::Signalled(session_rm_status(&rm, answer)));
}
fn rename(&mut self, instance: &str, new_name: &str) {
let answer = self.one_shot("rename", rename_call(instance, new_name));
self.send(DaemonUpdate::Renamed(rename_status(instance, new_name, answer)));
}
fn set_profile(&mut self, instance: &str, profile: &str) {
let answer = self.one_shot("profile", set_profile_call(instance, profile));
self.send(DaemonUpdate::ProfileSet(set_profile_status(instance, profile, answer)));
}
fn set_done(&mut self, req: PendingDone) {
let what = if req.done { "done" } else { "undone" };
let answer = self.one_shot(what, done_call(&req));
let (status, failed) = done_status(&req, answer);
self.send(DaemonUpdate::Done { status, failed, report: req.report });
}
fn identity(&mut self, req: IdentityReq) {
let dir = self.dir.to_path_buf();
let down = self.down.clone();
let mut broke = false;
let conn = &mut self.conn;
let mut call = |method: &str, params: Value| -> Result<Response> {
let Some(c) = conn.as_mut() else { anyhow::bail!("{}", needs_serve("config", down.as_deref())) };
c.call(method, params).inspect_err(|_| {
*conn = None;
broke = true;
})
};
let update = match req {
IdentityReq::Offer { routes, asked } => {
let asks = routes.iter().filter_map(|r| identity_ask(&dir, r, Scope::All)).collect();
DaemonUpdate::IdentityOffer { groups: identity::gather(asks, &mut call), asked }
}
IdentityReq::Answer { choice, on, then } => {
let groups = match on {
IdentityOn::Groups(groups) => groups,
IdentityOn::Notes { route, ids } => {
identity::gather(identity_ask(&dir, &route, Scope::Ids(ids)).into_iter().collect(), &mut call)
}
};
let mut said = Vec::new();
let done = identity::answer(&groups, choice, &mut call, &mut |line: &str| said.push(line.to_string()));
DaemonUpdate::Identity { outcome: identity_outcome(done, said), then }
}
};
if broke {
self.lost(false);
}
self.send(update);
}
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, access: None, host: 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() {
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.cancel("web".into());
assert_eq!(rx.try_recv().unwrap(), Cmd::Inbox(vec![Op::MarkRead(1)]));
assert_eq!(rx.try_recv().unwrap(), Cmd::Cancel("web".into()));
}
fn port_req(instance: &str, service: Option<&str>) -> PortRequest {
PortRequest { instance: instance.into(), service: service.map(String::from), spec: "8080:3000".into(), ..Default::default() }
}
fn remote_req(instance: &str, service: Option<&str>) -> PortRequest {
PortRequest { machine: Some("box".into()), root: Some("/r/one".into()), ..port_req(instance, service) }
}
#[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", "machines": true})));
assert_eq!(rm_call(4), ("forwards.rm", json!({"id": 4})));
worker.machine_set("box".into(), true);
assert_eq!(rx.try_recv().unwrap(), Cmd::MachineSet { name: "box".into(), agent: true });
assert_eq!(machine_set_call("box", true), ("machines.set", json!({"name": "box", "agent": true})));
assert_eq!(machine_set_call("box", false).1["agent"], json!(false));
assert_eq!(machine_set_status("box", true), "box: agent on");
assert_eq!(machine_set_status("box", false), "box: agent off");
assert_eq!(
needs_serve(&machine_set_status("box", true), Some("no socket")),
"box: agent on: needs devsandbox serve (no socket)"
);
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_eq!(
add_call(dir, &remote_req("web", Some("db"))),
(
"forwards.add",
json!({"dir": "/r/one", "instance": "web", "service": "db", "address": null, "spec": "8080:3000", "machine": "box"})
)
);
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>, machines: bool) -> Result<Vec<ForwardRow>, ApiError> {
assert_eq!(dir.as_deref(), Some(Path::new("/cfg")));
assert!(machines);
let remote = ForwardRow {
id: 4,
dir: "/r/one".into(),
local: "127.0.0.1:8081".into(),
target: "box/web:3000".into(),
process: None,
state: "connecting".into(),
conns: 0,
configured: false,
open: false,
machine: Some("box".into()),
};
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,
open: false,
machine: None,
}, remote])
}
fn add(&self, req: AddRequest) -> Result<Added, ApiError> {
assert_eq!(req.instance.as_deref(), Some("web"));
if let Some(m) = &req.machine {
assert_eq!((m.as_str(), req.dir.as_path()), ("box", Path::new("/r/one")));
return Ok(Added { id: 4, local: "127.0.0.1:8081".into(), target: "box/web:3000".into() });
}
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), access: None, host: None };
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,
open: false,
machine: None,
},
PortRow {
id: 4,
local: "127.0.0.1:8081".into(),
target: "box/web:3000".into(),
process: None,
state: "connecting".into(),
conns: 0,
configured: false,
open: false,
machine: Some("box".into()),
},
]
);
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) = add_call(dir, &remote_req("web", None));
assert_eq!(added_status(api::call(method, params, &ctx).unwrap()), "forwarding 127.0.0.1:8081 -> box/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 cancel_queues_maps_to_the_api_and_answers_render() {
use crate::serve::api::{self, CancelParams};
use crate::serve::proto::ErrorBody;
let (tx, rx) = mpsc::channel();
let (_utx, updates) = mpsc::channel();
let worker = DaemonWorker { tx: Some(tx), updates, connected: Arc::default(), handle: None };
worker.cancel("web-2".into());
assert_eq!(rx.try_recv().unwrap(), Cmd::Cancel("web-2".into()));
let (method, params) = cancel_call("web-2");
assert_eq!((method, ¶ms), ("instances.cancel", &json!({"instance": "web-2"})));
let parsed: CancelParams = api::parse(params).unwrap();
assert_eq!(parsed.instance, "web-2");
let ok = |v: Value| Response { id: Some(1), result: Some(v), error: None };
let err = |code: &str, message: &str| Response {
id: Some(1),
result: None,
error: Some(ErrorBody { code: code.into(), message: message.into(), data: None }),
};
assert_eq!(cancel_status("web-2", ok(json!({"ok": true, "pid": 42}))), "cancelling web-2 (SIGINT to pid 42)");
assert_eq!(
cancel_status("web-2", err("invalid", "`web-2` is not building any more")),
"cancel web-2: `web-2` is not building any more"
);
assert_eq!(cancel_status("x", err("not-found", "no instance `x`")), "cancel x: no instance `x`");
}
fn sig(pid: &str) -> PendingSignal {
PendingSignal { instance: "web-2".into(), pid: pid.into(), signal: super::super::app::Signal::Term }
}
fn rm(instance: &str) -> PendingSessionRm {
PendingSessionRm { instance: instance.into(), id: "1790000000-a1b2".into() }
}
fn response(result: Option<Value>, error: Option<(&str, &str)>) -> Response {
use crate::serve::proto::ErrorBody;
let error = error.map(|(code, message)| ErrorBody { code: code.into(), message: message.into(), data: None });
Response { id: Some(1), result, error }
}
#[test]
fn one_shot_requests_queue_as_their_commands() {
let (tx, rx) = mpsc::channel();
let (_utx, updates) = mpsc::channel();
let worker = DaemonWorker { tx: Some(tx), updates, connected: Arc::default(), handle: None };
let logs = Fetch::Logs { container: "devsandbox-web".into() };
let done = PendingDone { instance: "web".into(), done: true, report: false };
worker.fetch(logs.clone(), Route::default());
worker.build_log("id0".into());
worker.signal(sig("42"));
worker.session_rm(rm("web-2"), Route::default());
worker.rename("a".into(), "b".into());
worker.set_profile("box/a".into(), "work".into());
worker.set_done(done.clone());
assert_eq!(rx.try_recv().unwrap(), Cmd::Fetch(logs, Route::default()));
assert_eq!(rx.try_recv().unwrap(), Cmd::BuildLog("id0".into()));
assert_eq!(rx.try_recv().unwrap(), Cmd::Signal(sig("42")));
assert_eq!(rx.try_recv().unwrap(), Cmd::SessionRm(rm("web-2"), Route::default()));
assert_eq!(rx.try_recv().unwrap(), Cmd::Rename { instance: "a".into(), new_name: "b".into() });
assert_eq!(rx.try_recv().unwrap(), Cmd::SetProfile { instance: "box/a".into(), profile: "work".into() });
assert_eq!(rx.try_recv().unwrap(), Cmd::Done(done));
}
#[test]
fn identity_requests_queue_ask_and_report() {
let (tx, rx) = mpsc::channel();
let (_utx, updates) = mpsc::channel();
let worker = DaemonWorker { tx: Some(tx), updates, connected: Arc::default(), handle: None };
let offer = IdentityReq::Offer { routes: vec![Route::default()], asked: true };
worker.identity(offer.clone());
assert_eq!(rx.try_recv().unwrap(), Cmd::Identity(offer));
let dir = Path::new("/cfg");
let here = identity_ask(dir, &Route::default(), Scope::All).unwrap();
assert_eq!((here.root.as_path(), here.machine, here.scope), (dir, None, Scope::All));
let remote = Route { machine: Some("box".into()), root: Some("/r/one".into()) };
let there = identity_ask(dir, &remote, Scope::Ids(vec!["a".into()])).unwrap();
assert_eq!((there.root.as_path(), there.machine.as_deref()), (Path::new("/r/one"), Some("box")));
assert_eq!(identity_ask(dir, &Route { machine: Some("box".into()), root: None }, Scope::All), None);
let said = vec!["updated devsandboxes.toml (1 edit)".to_string(), "x.yaml: make these edits:\n a\n b".to_string()];
assert_eq!(identity_outcome(Ok(()), said), Ok("updated devsandboxes.toml (1 edit); x.yaml: make these edits:; a; b".into()));
assert_eq!(identity_outcome(Ok(()), Vec::new()), Ok(String::new()));
assert_eq!(identity_outcome(Err(anyhow::anyhow!("x changed")), Vec::new()), Err("x changed".into()));
}
#[test]
fn one_shot_calls_name_their_methods_and_params() {
let root = Path::new("/cfg");
let fetch = |f: Fetch| fetch_call(root, &f, &Route::default());
assert_eq!(
fetch(Fetch::Logs { container: "devsandbox-web".into() }),
("logs", ("containers.logs", json!({"container": "devsandbox-web", "lines": 50})))
);
assert_eq!(
fetch(Fetch::Inspect { container: "devsandbox-web".into() }),
("inspect", ("containers.inspect", json!({"container": "devsandbox-web"})))
);
assert_eq!(
fetch(Fetch::Config { kind: ConfigKind::Sandbox, name: "web".into() }),
("config", ("sandboxes.get", json!({"root": "/cfg", "name": "web"})))
);
assert_eq!(
fetch(Fetch::Config { kind: ConfigKind::Service, name: "db".into() }),
("config", ("services.get", json!({"root": "/cfg", "name": "db"})))
);
assert_eq!(
fetch(Fetch::Sessions { instance: "web-2".into() }),
("attach", ("sessions.list", json!({"root": "/cfg", "instance": "web-2"})))
);
assert_eq!(build_log_call("id0"), ("instances.buildLog", json!({"instance": "id0", "lines": 500, "ansi": true})));
assert_eq!(
signal_call(&PendingSignal { signal: super::super::app::Signal::Kill, ..sig("42") }),
("instances.signal", json!({"instance": "web-2", "pid": "42", "signal": "KILL"}))
);
assert_eq!(
session_rm_call(root, &rm("web-2"), &Route::default()),
("sessions.rm", json!({"root": "/cfg", "instance": "web-2", "id": "1790000000-a1b2"}))
);
assert_eq!(session_rm_status(&rm("web-2"), Answer::Ok(json!({"ok": true}))), "ended session 1790000000-a1b2 in web-2");
assert_eq!(session_rm_status(&rm("web-2"), Answer::Refused("no session".into())), "end session: no session");
assert_eq!(rename_call("a", "b"), ("instances.rename", json!({"instance": "a", "newName": "b"})));
assert_eq!(
done_call(&PendingDone { instance: "a".into(), done: false, report: true }),
("instances.done", json!({"instance": "a", "done": false}))
);
}
#[test]
fn remote_targets_carry_their_machine() {
let root = Path::new("/cfg");
let remote = Route { machine: Some("box".into()), root: Some("/r/one".into()) };
assert_eq!(
fetch_call(root, &Fetch::Config { kind: ConfigKind::Sandbox, name: "box/web".into() }, &remote),
("config", ("sandboxes.get", json!({"root": "/r/one", "name": "web", "machine": "box"})))
);
assert_eq!(
fetch_call(root, &Fetch::Config { kind: ConfigKind::Service, name: "box/db".into() }, &remote).1,
("services.get", json!({"root": "/r/one", "name": "db", "machine": "box"}))
);
assert_eq!(
fetch_call(root, &Fetch::Logs { container: "box/devsandbox-web".into() }, &Route::default()).1,
("containers.logs", json!({"container": "devsandbox-web", "lines": 50, "machine": "box"}))
);
assert_eq!(
fetch_call(root, &Fetch::Inspect { container: "box/devsandbox-web".into() }, &Route::default()).1,
("containers.inspect", json!({"container": "devsandbox-web", "machine": "box"}))
);
assert_eq!(
fetch_call(root, &Fetch::Sessions { instance: "box/web-2".into() }, &remote).1,
("sessions.list", json!({"root": "/r/one", "instance": "web-2", "machine": "box"}))
);
assert_eq!(
session_rm_call(root, &rm("box/web-2"), &remote),
("sessions.rm", json!({"root": "/r/one", "instance": "web-2", "id": "1790000000-a1b2", "machine": "box"}))
);
assert_eq!(cancel_call("box/web-2"), ("instances.cancel", json!({"instance": "web-2", "machine": "box"})));
assert_eq!(build_log_call("box/id0").1, json!({"instance": "id0", "lines": 500, "ansi": true, "machine": "box"}));
assert_eq!(signal_call(&sig("42")).1["machine"], Value::Null, "local");
let remote_sig = PendingSignal { instance: "box/web-2".into(), ..sig("42") };
assert_eq!(signal_call(&remote_sig).1, json!({"instance": "web-2", "pid": "42", "signal": "TERM", "machine": "box"}));
assert_eq!(rename_call("box/a", "b").1, json!({"instance": "a", "newName": "b", "machine": "box"}));
assert_eq!(set_profile_call("a", "work"), ("instances.setProfile", json!({"instance": "a", "profile": "work"})));
assert_eq!(set_profile_call("box/a", "work").1, json!({"instance": "a", "profile": "work", "machine": "box"}));
let done = PendingDone { instance: "box/a".into(), done: true, report: false };
assert_eq!(done_call(&done).1, json!({"instance": "a", "done": true, "machine": "box"}));
}
#[test]
fn one_shot_calls_are_accepted_by_the_api() {
use crate::serve::api::{self, Ctx};
let dir = std::env::temp_dir().join(format!("devsandbox-tui-oneshot-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join(crate::config::CONFIG_FILE),
"[sandbox.web]\nimage = \"alpine\"\n[services.db]\nimage = \"postgres\"\n",
)
.unwrap();
let inbox = dir.join("inbox.json");
let ctx = Ctx { inbox: &inbox, client: "tui", bridges: None, forwards: None, access: None, host: None };
let ask = |(method, params): (&str, Value)| match api::call(method, params, &ctx) {
Ok(v) => Answer::Ok(v),
Err(e) => Answer::Refused(e.message),
};
let (_, call) = fetch_call(&dir, &Fetch::Config { kind: ConfigKind::Sandbox, name: "web".into() }, &Route::default());
let update = fetch_update(Fetch::Config { kind: ConfigKind::Sandbox, name: "web".into() }, ask(call));
let DaemonUpdate::Config { kind: ConfigKind::Sandbox, name, text: Ok(text) } = update else { panic!("{update:?}") };
assert_eq!((name.as_str(), text.original.as_str()), ("web", "image = \"alpine\"\n"));
assert!(!text.hash.is_empty());
let service = Fetch::Config { kind: ConfigKind::Service, name: "db".into() };
let (_, call) = fetch_call(&dir, &service, &Route::default());
let DaemonUpdate::Config { kind: ConfigKind::Service, name, text } = fetch_update(service, ask(call)) else { panic!() };
assert_eq!(name, "db");
assert_eq!(
text,
Ok(SandboxText {
original: "image = \"postgres\"\n".into(),
resolved: "image = \"postgres\"\n".into(),
hash: String::new()
})
);
let unknown = Fetch::Config { kind: ConfigKind::Sandbox, name: "nope".into() };
let (_, call) = fetch_call(&dir, &unknown, &Route::default());
let DaemonUpdate::Config { text: Err(msg), .. } = fetch_update(unknown, ask(call)) else { panic!() };
assert!(msg.contains("no sandbox `nope`"), "{msg}");
let not_ours = Fetch::Logs { container: "web".into() };
let (_, call) = fetch_call(&dir, ¬_ours, &Route::default());
let DaemonUpdate::Logs { body, .. } = fetch_update(not_ours, ask(call)) else { panic!() };
assert!(body.contains("not a devsandbox container"), "{body}");
let (_, call) = fetch_call(&dir, &Fetch::Inspect { container: "web".into() }, &Route::default());
assert!(matches!(ask(call), Answer::Refused(m) if m.contains("not a devsandbox container")));
assert!(matches!(ask(signal_call(&sig("0"))), Answer::Refused(m) if m.contains("`pid` must be a process id")));
let bad = PendingSessionRm { id: "x".into(), ..rm("web-2") };
assert!(matches!(ask(session_rm_call(&dir, &bad, &Route::default())), Answer::Refused(m) if m.contains("bad session id `x`")));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn one_shot_answers_render() {
assert_eq!(Answer::from_response(response(Some(json!({"ok": true})), None)), Answer::Ok(json!({"ok": true})));
assert_eq!(Answer::from_response(response(None, None)), Answer::Ok(Value::Null));
assert_eq!(Answer::from_response(response(None, Some(("not-found", "no instance `x`")))), Answer::Refused("no instance `x`".into()));
assert_eq!(needs_serve("logs", Some("refused")), "logs: needs devsandbox serve (refused)");
assert_eq!(needs_serve("logs", None), "logs: needs devsandbox serve");
let down = || Answer::Unreachable(needs_serve("x", Some("down")));
let logs = |a| match fetch_update(Fetch::Logs { container: "devsandbox-a".into() }, a) {
DaemonUpdate::Logs { container, body } if container == "devsandbox-a" => body,
other => panic!("{other:?}"),
};
assert_eq!(logs(Answer::Ok(json!({"text": "l1\nl2\n"}))), "l1\nl2\n");
assert_eq!(logs(Answer::Ok(json!({"text": " \n"}))), "(no log output)");
assert_eq!(logs(Answer::Refused("No such container".into())), "No such container");
assert_eq!(logs(down()), "x: needs devsandbox serve (down)");
let inspect = |a| match fetch_update(Fetch::Inspect { container: "devsandbox-a".into() }, a) {
DaemonUpdate::Inspect { body, .. } => body,
other => panic!("{other:?}"),
};
let raw = r#"[{"Id":"abc","State":{"Running":true}}]"#;
assert_eq!(inspect(Answer::Ok(serde_json::from_str(raw).unwrap())), crate::commands::inspect::pretty_inspect(raw));
assert_eq!(inspect(down()), "x: needs devsandbox serve (down)");
let config = |a| match fetch_update(Fetch::Config { kind: ConfigKind::Sandbox, name: "web".into() }, a) {
DaemonUpdate::Config { text, .. } => text,
other => panic!("{other:?}"),
};
assert_eq!(config(down()), Err("x: needs devsandbox serve (down)".into()));
assert!(config(Answer::Ok(json!({"surprise": 1}))).unwrap_err().starts_with("config: unexpected answer"));
let sessions = |a| match fetch_update(Fetch::Sessions { instance: "box/web".into() }, a) {
DaemonUpdate::Sessions { instance, lines } if instance == "box/web" => lines,
other => panic!("{other:?}"),
};
assert_eq!(sessions(Answer::Ok(json!({"sessions": ["a running detached t sh"]}))), Ok(vec!["a running detached t sh".into()]));
assert_eq!(sessions(Answer::Refused("no instance `web`".into())), Err("attach: no instance `web`".into()));
assert_eq!(sessions(down()), Err("x: needs devsandbox serve (down)".into()));
assert!(sessions(Answer::Ok(json!({}))).unwrap_err().starts_with("attach: unexpected answer"));
let read = |a: Answer| a.parse::<Option<Tail>>("build log");
assert_eq!(read(Answer::Ok(Value::Null)), Ok(None));
assert_eq!(read(Answer::Ok(json!({"text": "x", "cut": true}))), Ok(Some(Tail { text: "x".into(), cut: true })));
assert_eq!(read(Answer::Refused("no instance `id0`".into())), Err("no instance `id0`".into()));
assert_eq!(signal_status(&sig("42"), Answer::Ok(json!({"ok": true}))), "sent SIGTERM to pid 42");
assert_eq!(signal_status(&sig("42"), Answer::Refused("no instance `web-2`".into())), "SIGTERM: no instance `web-2`");
assert_eq!(signal_status(&sig("42"), down()), "x: needs devsandbox serve (down)");
assert_eq!(rename_status("a", " b ", Answer::Ok(json!({"instance": "b"}))), "renamed a -> b");
assert_eq!(rename_status("a", "b", Answer::Refused("`b` is taken".into())), "rename failed: `b` is taken");
assert_eq!(rename_status("a", "b", down()), "x: needs devsandbox serve (down)");
assert_eq!(set_profile_status("box/a", "work", Answer::Ok(json!({"instance": "a", "profile": "work"}))), "box/a: profile work");
assert_eq!(set_profile_status("a", "x", Answer::Refused("`x` isn't allowed".into())), "profile failed: `x` isn't allowed");
assert_eq!(set_profile_status("a", "work", down()), "x: needs devsandbox serve (down)");
let done = |done| PendingDone { instance: "a".into(), done, report: true };
let ok = || Answer::Ok(json!({"instance": "a", "done": true}));
assert_eq!(done_status(&done(true), ok()), ("marked a done".into(), false));
assert_eq!(done_status(&done(false), ok()), ("marked a not done".into(), false));
let warned = Answer::Ok(json!({"instance": "a", "done": true, "warning": "cannot fetch lap/a back: no link"}));
assert_eq!(done_status(&done(true), warned), ("marked a done; cannot fetch lap/a back: no link".into(), true), "shown even unasked");
assert_eq!(done_status(&done(false), Answer::Refused("no instance `a`".into())), ("undone: no instance `a`".into(), true));
assert_eq!(done_status(&done(true), down()), ("x: needs devsandbox serve (down)".into(), true));
}
#[test]
fn access_calls_and_their_lines() {
assert_eq!(
access_decide_call("R-1", asks::Answer::Instance),
("access.decide", json!({"request": "R-1", "answer": "instance"}))
);
let request = json!({
"id": "R-1", "instance": "web-1", "instance_id": "i1", "sandbox": "web", "credential": "github-work",
"kind": "github", "scope": "pr.write", "repo": null, "method": "POST", "route": "/x",
"opened_at": 1, "held": true, "waiting": 1,
});
let line = access_decide_status("R-1", asks::Answer::Deny, Answer::Ok(json!({"request": request.clone()})));
assert_eq!(line, "denied R-1: `web-1` `github-work` pr.write, kept until `devsandbox access revoke R-1`");
assert_eq!(access_decide_status("R-1", asks::Answer::Once, Answer::Refused("no pending request `R-1`".into())), "R-1: no pending request `R-1`");
assert_eq!(access_decide_status("R-1", asks::Answer::Once, Answer::Unreachable("access: needs devsandbox serve".into())), "access: needs devsandbox serve");
let listed = access_requests(Answer::Ok(json!({"requests": [request]}))).unwrap();
assert_eq!((listed.len(), listed[0].id.as_str()), (1, "R-1"));
assert_eq!(access_requests(Answer::Refused("this daemon brokers no credentials".into())), Err("access: this daemon brokers no credentials".into()));
}
#[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 the_worker_watches_its_root_and_again_after_a_reconnect() {
use crate::serve::daemon::tests::{opts, scratch, spawn_daemon};
let sock = scratch("tui-watch");
let root = scratch("tui-watch-root");
std::fs::create_dir_all(&root).unwrap();
let o = opts(1, 2000);
let version = o.version.clone();
let daemon = spawn_daemon(&sock, o);
let (tx, rx) = mpsc::channel();
let (utx, updates) = mpsc::channel();
let (s, r) = (sock.clone(), root.clone());
let ver = version.clone();
let worker = std::thread::spawn(move || {
let connector = move |_| client::connect_with(&s, "tui", &ver, Duration::from_secs(5), &|_, _| Ok(()));
run(&r, &connector, rx, utx, &AtomicBool::new(false));
});
let next = |want: fn(&DaemonUpdate) -> bool| -> DaemonUpdate {
loop {
let u = updates.recv_timeout(Duration::from_secs(10)).expect("no update");
if want(&u) {
return u;
}
}
};
let is_snapshot = |u: &DaemonUpdate| matches!(u, DaemonUpdate::Snapshot(..));
let DaemonUpdate::Snapshot(first, machines) = next(is_snapshot) else { unreachable!() };
assert_eq!(first.snapshot.runtime_name, "Disk", "a new watch's first push");
assert!(machines.is_empty(), "a machines watch, none registered");
let mut other = client::connect_with(&sock, "test", &version, Duration::from_secs(5), &|_, _| Ok(())).unwrap();
assert!(other.call("shutdown", json!({})).unwrap().error.is_none());
drop(other);
let _ = daemon.join();
let DaemonUpdate::Down(_) = next(|u| matches!(u, DaemonUpdate::Down(_))) else { unreachable!() };
let daemon = spawn_daemon(&sock, opts(1, 2000));
let DaemonUpdate::Snapshot(again, _) = next(is_snapshot) else { unreachable!() };
assert_eq!(again.snapshot.runtime_name, "Disk", "watched again");
drop(tx);
worker.join().unwrap();
let _ = daemon.join();
let _ = std::fs::remove_dir_all(&sock);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn snapshot_pushes_parse_or_say_why() {
let wire = json!({
"dir": "/cfg", "instances": [], "sandboxes": [], "services": [], "sandbox_count": 2,
"runtime_name": "docker", "runtime_version": "24", "error": null,
"thread_children": {"d-id": {"k": "web-k"}},
});
let DaemonUpdate::Snapshot(list, machines) = snapshot_update(wire) else { panic!("not parsed") };
assert!(machines.is_empty());
assert_eq!(list.snapshot.sandbox_count, 2);
assert_eq!(list.snapshot.depth, crate::snapshot::Depth::Disk, "absent: disk");
assert_eq!(list.thread_children["d-id"]["k"], "web-k");
let DaemonUpdate::Status(line) = snapshot_update(json!([1])) else { panic!("parsed") };
assert!(line.starts_with("bad instances.snapshot"), "{line}");
assert_eq!(watch_call(Path::new("/cfg")), ("instances.watch", json!({"dir": "/cfg", "machines": true})));
let federated = json!({
"dir": "/cfg", "instances": [], "sandboxes": [], "services": [], "sandbox_count": 0,
"runtime_name": "docker", "runtime_version": null, "error": null,
"machines": [{"name": "box", "kind": "ssh", "target": "me@box", "state": "unreachable", "error": "refused",
"version": null, "runtime": null, "command": null, "agent": false}],
});
let DaemonUpdate::Snapshot(_, machines) = snapshot_update(federated) else { panic!("not parsed") };
assert_eq!((machines[0].name.as_str(), machines[0].error.as_deref()), ("box", Some("refused")));
}
#[test]
fn line_notifications_are_status_lines() {
use crate::open::{OpenDone, Outcome};
let done = OpenDone { instance: "web".into(), url: "https://x".into(), profile: None, outcome: Outcome::Failed("no display on this host".into()) };
let params = serde_json::to_value(crate::serve::opens::DoneParams::new(&done)).unwrap();
let status = |m: &str, p: &Value| match line_update(m, p) {
Some(DaemonUpdate::Status(l)) => Some(format!("status {l}")),
Some(DaemonUpdate::Shown(l)) => Some(format!("shown {l}")),
_ => None,
};
assert_eq!(status("opens.done", ¶ms).as_deref(), Some("status web: open failed: no display on this host"));
assert_eq!(status("forwards.status", &json!({"line": "3000: refused"})).as_deref(), Some("status 3000: refused"));
assert_eq!(status("inbox.shown", &json!({"instance": "a", "line": "a: hi"})).as_deref(), Some("shown a: hi"));
assert_eq!(status("opens.done", &json!({})), None, "no line");
assert_eq!(status("instances.changed", &json!({"line": "x"})), None);
}
#[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));
}
}