use std::io::{Read, Write};
use std::os::unix::net::UnixStream;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
use super::mux::{self, Conn, Mux};
use super::control::{self, Request, Response, Status};
use super::proto::caps;
use super::{notify, proto, relay_mode, BIN};
use crate::runtime::backend;
use crate::state::{Instance, State};
pub struct Bridge {
child: Arc<Mutex<Child>>,
done: Arc<AtomicBool>,
mismatch: Arc<AtomicBool>,
handshake: mpsc::Receiver<Result<(), String>>,
forward: Arc<OnceLock<Forward>>,
container: String,
}
struct Forward {
mux: Arc<Mux>,
peer_caps: u32,
}
impl Bridge {
pub fn outcome(&self, timeout: Duration) -> Option<Result<(), String>> {
self.handshake.recv_timeout(timeout).ok()
}
pub fn is_done(&self) -> bool {
self.done.load(Ordering::Relaxed)
}
pub fn is_mismatch(&self) -> bool {
self.mismatch.load(Ordering::Relaxed)
}
#[allow(dead_code)] pub fn peer_caps(&self) -> Option<u32> {
self.forward.get().map(|f| f.peer_caps)
}
#[allow(dead_code)] pub fn connect(
&self,
conn: impl Into<Conn>,
host: &str,
port: u16,
on_close: impl FnOnce(String) + Send + 'static,
) -> std::io::Result<u32> {
let Some(forward) = self.forward.get() else {
let kind = if self.is_done() {
std::io::ErrorKind::BrokenPipe
} else {
std::io::ErrorKind::NotConnected
};
let msg = if self.is_done() { "bridge is not running" } else { "bridge handshake not done" };
return Err(std::io::Error::new(kind, msg));
};
if self.is_done() {
return Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "bridge is not running"));
}
if forward.peer_caps & caps::TCP_FORWARD == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
format!("helper in {} is outdated (no port forwarding): restart the instance", self.container),
));
}
forward.mux.connect(conn, host, port, on_close)
}
}
impl Drop for Bridge {
fn drop(&mut self) {
let mut child = self.child.lock().unwrap();
let _ = child.kill();
let _ = child.wait();
}
}
const MAX_AGENTS: usize = 8;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct AgentCandidates {
recent: Vec<PathBuf>,
}
impl AgentCandidates {
pub fn report(&mut self, path: PathBuf) {
self.recent.retain(|p| *p != path);
self.recent.insert(0, path);
self.recent.truncate(MAX_AGENTS);
}
pub fn pick(&self, fallback: Option<PathBuf>, live: impl Fn(&Path) -> bool) -> Option<PathBuf> {
self.recent.iter().cloned().chain(fallback).find(|p| live(p))
}
}
static AGENTS: Mutex<AgentCandidates> = Mutex::new(AgentCandidates { recent: Vec::new() });
pub fn report_agent(path: PathBuf) {
AGENTS.lock().unwrap_or_else(|e| e.into_inner()).report(path);
}
pub fn own_agent() -> Option<PathBuf> {
std::env::var_os("SSH_AUTH_SOCK").filter(|s| !s.is_empty()).map(PathBuf::from)
}
fn agent_live(path: &Path) -> bool {
UnixStream::connect(path).is_ok()
}
fn host_agent() -> Option<PathBuf> {
let candidates = AGENTS.lock().unwrap_or_else(|e| e.into_inner()).clone();
candidates.pick(own_agent(), agent_live)
}
pub fn has_host_agent() -> bool {
host_agent().is_some()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Notification {
pub instance: String,
pub instance_id: String,
pub message: notify::Message,
}
pub type Sink = Arc<dyn Fn(Notification) -> Result<(), String> + Send + Sync>;
pub type ControlHandler = Arc<dyn Fn(&str, &Request) -> Response + Send + Sync>;
pub type FollowHandler = Arc<dyn Fn(&str, &Request, &mut dyn Write) + Send + Sync>;
#[derive(Clone)]
struct Services {
instance: String,
instance_id: String,
sink: Sink,
control: ControlHandler,
follow: FollowHandler,
handlers: Arc<AtomicUsize>,
}
impl Services {
fn new(instance: String, instance_id: String, sink: Sink, control: ControlHandler) -> Services {
let follow: FollowHandler = Arc::new(dispatch_follow);
Services { instance, instance_id, sink, control, follow, handlers: Arc::default() }
}
}
const MAX_HANDLERS: usize = 8;
struct HandlerSlot(Arc<AtomicUsize>);
impl HandlerSlot {
fn acquire(count: &Arc<AtomicUsize>) -> Option<HandlerSlot> {
count
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < MAX_HANDLERS).then_some(n + 1))
.ok()
.map(|_| HandlerSlot(Arc::clone(count)))
}
}
impl Drop for HandlerSlot {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::AcqRel);
}
}
fn own_caps(has_agent: bool, has_sink: bool) -> u32 {
let agent = if has_agent { caps::SSH_AGENT } else { 0 };
let sink = if has_sink { caps::NOTIFY | caps::CONTROL } else { 0 };
agent | sink
}
const CONTROL_READ_TIMEOUT: Duration = Duration::from_secs(30);
const FOLLOW_WRITE_TIMEOUT: Duration = Duration::from_secs(60);
fn dispatch_control(key: &str, req: &Request) -> Response {
use crate::commands::dispatch;
static LOCK: Mutex<()> = Mutex::new(());
let _in_flight = InFlight::enter();
if !writes_state(req.op) || !dispatch::declares_dispatcher(key) {
return dispatch::handle(key, req);
}
let _serial = LOCK.lock().unwrap_or_else(|e| e.into_inner());
dispatch::handle(key, req)
}
fn dispatch_follow(key: &str, req: &Request, out: &mut dyn Write) {
let _in_flight = InFlight::enter();
crate::commands::dispatch::follow(key, req, out)
}
static CONTROL_IN_FLIGHT: AtomicUsize = AtomicUsize::new(0);
pub fn control_in_flight() -> usize {
CONTROL_IN_FLIGHT.load(Ordering::Acquire)
}
struct InFlight;
impl InFlight {
fn enter() -> InFlight {
CONTROL_IN_FLIGHT.fetch_add(1, Ordering::AcqRel);
InFlight
}
}
impl Drop for InFlight {
fn drop(&mut self) {
CONTROL_IN_FLIGHT.fetch_sub(1, Ordering::AcqRel);
}
}
fn writes_state(op: crate::devsbd::control::Op) -> bool {
use crate::devsbd::control::Op;
matches!(op, Op::Ensure | Op::Stop | Op::Rm | Op::Done)
}
const NOTIFY_SLACK: usize = 1024;
const NOTIFY_READ_TIMEOUT: Duration = Duration::from_secs(30);
const NOTIFY_REPLY_BAD: &[u8] = b"bad record";
fn open_stream(
channel: u8,
agent: Option<&impl Fn() -> Option<PathBuf>>,
services: Option<&Services>,
) -> Option<Conn> {
let handler: fn(UnixStream, &Services) = match channel {
proto::channel::SSH_AGENT => return UnixStream::connect(agent?()?).ok().map(Into::into),
proto::channel::NOTIFY => handle_notify,
proto::channel::CONTROL => handle_control,
_ => return None,
};
let to = services?.clone();
let slot = HandlerSlot::acquire(&to.handlers)?;
let (ours, theirs) = UnixStream::pair().ok()?;
std::thread::spawn(move || {
let _slot = slot;
handler(ours, &to)
});
Some(theirs.into())
}
fn handle_control(mut conn: UnixStream, to: &Services) {
let _ = conn.set_read_timeout(Some(CONTROL_READ_TIMEOUT));
let mut buf = Vec::new();
if (&conn).take(control::MAX_REQUEST as u64 + 1).read_to_end(&mut buf).is_err() {
return;
}
let resp = if buf.len() > control::MAX_REQUEST {
Response::new(Status::Usage, format!("request longer than {} bytes", control::MAX_REQUEST))
} else {
match std::str::from_utf8(&buf).map_err(|e| e.to_string()).and_then(control::decode_request) {
Ok(req) if req.op == control::Op::Subscribe => {
let _ = conn.set_write_timeout(Some(FOLLOW_WRITE_TIMEOUT));
return (to.follow)(&to.instance, &req, &mut conn);
}
Ok(req) => (to.control)(&to.instance, &req),
Err(e) => Response::new(Status::Usage, format!("bad request: {e}")),
}
};
let _ = conn.write_all(control::encode_response(&resp).as_bytes());
}
fn handle_notify(mut conn: UnixStream, to: &Services) {
let _ = conn.set_read_timeout(Some(NOTIFY_READ_TIMEOUT));
let limit = notify::MAX_RECORD + NOTIFY_SLACK;
let mut buf = Vec::new();
if (&conn).take(limit as u64 + 1).read_to_end(&mut buf).is_err() || buf.len() > limit {
return;
}
let decoded = std::str::from_utf8(&buf).map_err(|e| e.to_string()).and_then(notify::decode);
let Ok(message) = decoded else {
let _ = conn.write_all(NOTIFY_REPLY_BAD);
return;
};
let n = Notification {
instance: to.instance.clone(),
instance_id: to.instance_id.clone(),
message,
};
if (to.sink)(n).is_ok() {
let _ = conn.write_all(notify::REPLY_OK);
}
}
fn spawn_managed(
key: &str,
info: &Instance,
with_agent: bool,
sink: Option<&Sink>,
observe: Observer,
) -> Option<Bridge> {
let hash = info.devsbd_arch.and_then(super::hash).unwrap_or_default();
let notify = sink.map(|s| {
Services::new(
key.to_string(),
info.instance_id.clone(),
Arc::clone(s),
Arc::new(dispatch_control),
)
});
if with_agent {
spawn_observed(&info.container, hash, Some(host_agent), notify, Some(observe))
} else {
let none: Option<fn() -> Option<PathBuf>> = None;
spawn_observed(&info.container, hash, none, notify, Some(observe))
}
}
pub fn spawn_for(container: &str, hash: &str, with_agent: bool) -> Option<Bridge> {
if with_agent {
spawn_with(container, hash, Some(host_agent), None)
} else {
let none: Option<fn() -> Option<PathBuf>> = None;
spawn_with(container, hash, none, None)
}
}
fn spawn_with(
container: &str,
hash: &str,
agent: Option<impl Fn() -> Option<PathBuf> + Send + 'static>,
notify: Option<Services>,
) -> Option<Bridge> {
spawn_observed(container, hash, agent, notify, None)
}
type Observer = Box<dyn Fn(BridgeStatus) + Send>;
fn spawn_observed(
container: &str,
hash: &str,
agent: Option<impl Fn() -> Option<PathBuf> + Send + 'static>,
notify: Option<Services>,
observe: Option<Observer>,
) -> Option<Bridge> {
let observe = move |s: BridgeStatus| {
if let Some(o) = &observe {
o(s)
}
};
let mut child = Command::new(backend().bin())
.args(["exec", "-i", "-u", "root", container, BIN, "bridge"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.ok()?;
let mut stdin = child.stdin.take()?;
let mut stdout = child.stdout.take()?;
let mut stderr = child.stderr.take()?;
let child = Arc::new(Mutex::new(child));
let done = Arc::new(AtomicBool::new(false));
let mismatch = Arc::new(AtomicBool::new(false));
let (tx, handshake) = mpsc::channel();
let hash = hash.to_string();
let container = container.to_string();
let finished = Arc::clone(&done);
let hs_mismatch = Arc::clone(&mismatch);
let forward = Arc::new(OnceLock::new());
let hs_forward = Arc::clone(&forward);
let bridge_container = container.clone();
let timed_out = Arc::new(AtomicBool::new(false));
let bridged = Arc::new(AtomicBool::new(false));
{
let child = Arc::clone(&child);
let timed_out = Arc::clone(&timed_out);
let bridged = Arc::clone(&bridged);
std::thread::spawn(move || {
std::thread::sleep(HANDSHAKE_TIMEOUT);
if !bridged.load(Ordering::Relaxed) {
timed_out.store(true, Ordering::Relaxed);
let _ = child.lock().unwrap().kill();
}
});
}
let hs_child = Arc::clone(&child);
std::thread::spawn(move || {
let mut daemon_caps = 0;
let result = proto::handshake(&mut stdout, &mut stdin, &hash, 0).map(|peer| daemon_caps = peer.caps).map_err(|e| {
if timed_out.load(Ordering::Relaxed) {
return "helper handshake timed out".to_string();
}
if let Some(vm) = proto::version_mismatch(&e) {
hs_mismatch.store(true, Ordering::Relaxed);
return mismatch_message(&container, vm);
}
let mut msg = String::new();
if e.kind() == std::io::ErrorKind::UnexpectedEof {
let _ = std::io::Read::read_to_string(&mut stderr, &mut msg);
if let Ok(status) = hs_child.lock().unwrap().wait() {
if status.code() == Some(proto::MISMATCH_EXIT) {
hs_mismatch.store(true, Ordering::Relaxed);
}
}
}
match msg.trim() {
"" => e.to_string(),
m => m.trim_start_matches("devsbd: ").to_string(),
}
});
let ok = result.is_ok();
bridged.store(ok, Ordering::Relaxed);
if let Err(e) = &result {
let why = e.clone();
let _ = tx.send(result);
finished.store(true, Ordering::Relaxed);
observe(BridgeStatus::Failed(why));
return;
}
{
let mux = Mux::new(stdin);
let has_agent = agent.as_ref().and_then(|a| a()).is_some();
let _ = mux.send(&proto::Frame::Caps(own_caps(has_agent, notify.is_some())));
let _ = hs_forward.set(Forward { mux: Arc::clone(&mux), peer_caps: daemon_caps });
observe(BridgeStatus::Ready);
let _ = tx.send(result);
let dead_child = Arc::clone(&hs_child);
mux.keepalive(mux::KEEPALIVE_INTERVAL, mux::KEEPALIVE_TIMEOUT, move || {
let _ = dead_child.lock().unwrap().kill();
});
mux.serve(stdout, move |_, channel| open_stream(channel, agent.as_ref(), notify.as_ref()));
}
finished.store(true, Ordering::Relaxed);
observe(BridgeStatus::Failed("the bridge ended (container stopped or helper gone)".into()));
});
Some(Bridge { child, done, mismatch, handshake, forward, container: bridge_container })
}
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
fn mismatch_message(container: &str, vm: &proto::VersionMismatch) -> String {
if vm.peer < vm.ours {
format!(
"helper in {container} is outdated (protocol {}, need {}): restart the instance",
vm.peer, vm.ours
)
} else {
format!(
"this devsandbox is older than the helper in {container} (protocol {}, need {})",
vm.peer, vm.ours
)
}
}
const RETRY: Duration = Duration::from_secs(10);
const MISMATCH_RETRY: Duration = Duration::from_secs(300);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Retry {
Spawn,
Keep,
Respawn,
}
fn retry_decision(entry: Option<(bool, bool, Duration)>, urgent: bool) -> Retry {
match entry {
None => Retry::Spawn,
Some((true, ..)) if urgent => Retry::Respawn,
Some((true, mismatch, since)) => {
let gap = if mismatch { MISMATCH_RETRY } else { RETRY };
if since >= gap { Retry::Respawn } else { Retry::Keep }
}
Some((false, ..)) => Retry::Keep,
}
}
fn wanted(helper: bool, relay: bool, host_agent: bool, has_sink: bool) -> Option<bool> {
let with_agent = host_agent && relay;
(with_agent || (has_sink && helper)).then_some(with_agent)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BridgeStatus {
Pending,
Ready,
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Readiness {
pub ready: bool,
pub error: Option<String>,
}
impl Readiness {
fn ready() -> Readiness {
Readiness { ready: true, error: None }
}
fn not(why: impl Into<String>) -> Readiness {
Readiness { ready: false, error: Some(why.into()) }
}
}
#[derive(Debug, Default)]
struct Board {
handled: u64,
next_id: u64,
bridges: HashMap<String, (u64, BridgeStatus)>,
}
#[derive(Clone, Default)]
pub struct BridgeBoard {
inner: Arc<(Mutex<Board>, Condvar)>,
tickets: Arc<std::sync::atomic::AtomicU64>,
}
impl BridgeBoard {
pub fn ticket(&self) -> u64 {
self.tickets.fetch_add(1, Ordering::AcqRel) + 1
}
fn update(&self, f: impl FnOnce(&mut Board)) {
let (lock, cvar) = &*self.inner;
f(&mut lock.lock().unwrap_or_else(|e| e.into_inner()));
cvar.notify_all();
}
fn spawning(&self, container: &str) -> Observer {
let mut id = 0;
self.update(|b| {
b.next_id += 1;
id = b.next_id;
b.bridges.insert(container.to_string(), (id, BridgeStatus::Pending));
});
let (board, container) = (self.clone(), container.to_string());
Box::new(move |status| {
board.update(|b| {
if let Some(entry) = b.bridges.get_mut(&container).filter(|(at, _)| *at == id) {
entry.1 = status;
}
})
})
}
fn set(&self, container: &str, status: BridgeStatus) {
self.update(|b| {
b.next_id += 1;
let id = b.next_id;
b.bridges.insert(container.to_string(), (id, status));
});
}
fn retain(&self, keep: &[String]) {
self.update(|b| b.bridges.retain(|c, _| keep.contains(c)));
}
fn handled(&self, ticket: u64) {
self.update(|b| b.handled = b.handled.max(ticket));
}
pub fn wait(&self, container: &str, ticket: u64, timeout: Duration) -> Readiness {
let (lock, cvar) = &*self.inner;
let guard = lock.lock().unwrap_or_else(|e| e.into_inner());
let (guard, _) = cvar
.wait_timeout_while(guard, timeout, |b| verdict(b, container, ticket).is_none())
.unwrap_or_else(|e| e.into_inner());
verdict(&guard, container, ticket).unwrap_or_else(|| timed_out(&guard, ticket, timeout))
}
}
fn verdict(b: &Board, container: &str, ticket: u64) -> Option<Readiness> {
if b.handled < ticket {
return None;
}
match b.bridges.get(container).map(|(_, s)| s) {
None => Some(Readiness::not("the host daemon keeps no bridge for it (not running, or no helper)")),
Some(BridgeStatus::Pending) => None,
Some(BridgeStatus::Ready) => Some(Readiness::ready()),
Some(BridgeStatus::Failed(why)) => Some(Readiness::not(why.clone())),
}
}
fn timed_out(b: &Board, ticket: u64, waited: Duration) -> Readiness {
let secs = waited.as_secs_f64();
if b.handled < ticket {
Readiness::not(format!("the host daemon didn't get to it within {secs}s (container runtime slow?)"))
} else {
Readiness::not(format!("the helper handshake didn't finish within {secs}s"))
}
}
#[derive(Default)]
pub struct Bridges {
live: HashMap<String, (Bridge, Instant, bool)>,
sink: Option<Sink>,
board: BridgeBoard,
}
impl Bridges {
pub fn reconcile(&mut self, running: &[&str], urgent: &[String]) {
self.live.retain(|c, _| running.contains(&c.as_str()));
let host_agent = has_host_agent();
if !host_agent && self.sink.is_none() {
self.live.clear();
self.board.retain(&[]);
return;
}
let Ok(state) = State::load() else { return };
let mut keep = Vec::new();
for (key, info) in &state.instances {
if !running.contains(&info.container.as_str()) {
continue;
}
let helper = info.devsbd_arch.is_some();
let Some(with_agent) = wanted(helper, relay_mode(info), host_agent, self.sink.is_some()) else {
continue;
};
keep.push(info.container.clone());
let entry = self
.live
.get(&info.container)
.filter(|(.., agent)| *agent == with_agent)
.map(|(b, at, _)| (b.is_done(), b.is_mismatch(), at.elapsed()));
if retry_decision(entry, urgent.contains(&info.container)) != Retry::Keep {
self.live.remove(&info.container);
let healed;
let info = match helper.then(|| crate::devsbd::ensure_recorded(key, info, true)).flatten() {
Some(arch) if Some(arch) != info.devsbd_arch => {
healed = Instance { devsbd_arch: Some(arch), ..info.clone() };
&healed
}
_ => info,
};
let observe = self.board.spawning(&info.container);
match spawn_managed(key, info, with_agent, self.sink.as_ref(), observe) {
Some(b) => {
self.live.insert(info.container.clone(), (b, Instant::now(), with_agent));
}
None => self.board.set(
&info.container,
BridgeStatus::Failed(format!("cannot run `{} exec` for the bridge", backend().bin())),
),
}
}
}
self.live.retain(|c, _| keep.contains(c));
self.board.retain(&keep);
}
pub fn spawn_worker(sink: Option<Option<OnShown>>, board: BridgeBoard) -> BridgeWorker {
let sink = sink.map(|on_shown| -> Sink {
let limit = Mutex::new(super::desktop::RateLimit::default());
Arc::new(move |n: Notification| {
let shown = apply_message(n)?;
let Some((instance, shown)) = shown else { return Ok(()) };
if let Some(popup) = shown.popup {
let allowed = limit
.lock()
.unwrap_or_else(|e| e.into_inner())
.allow(&instance, popup.key.as_deref(), Instant::now());
if allowed {
super::desktop::notify_desktop(&instance, &popup);
}
}
if let Some(on_shown) = &on_shown {
on_shown(&instance, shown.line);
}
Ok(())
})
});
let (tx, rx) = mpsc::channel::<(Vec<String>, Vec<(String, u64)>)>();
let handle = std::thread::spawn(move || {
let mut bridges = Bridges { sink, board, ..Bridges::default() };
while let Ok((mut running, mut urgent)) = rx.recv() {
while let Ok((next, more)) = rx.try_recv() {
running = next;
urgent.extend(more);
}
let refs: Vec<&str> = running.iter().map(String::as_str).collect();
let containers: Vec<String> = urgent.iter().map(|(c, _)| c.clone()).collect();
bridges.reconcile(&refs, &containers);
if let Some(ticket) = urgent.iter().map(|(_, t)| *t).max() {
bridges.board.handled(ticket);
}
}
});
BridgeWorker { tx: Some(tx), handle: Some(handle) }
}
}
pub type OnShown = Box<dyn Fn(&str, String) + Send + Sync>;
fn apply_message(n: Notification) -> Result<Option<(String, crate::inbox::Shown)>, String> {
use crate::commands::dispatch;
let threaded = !matches!(n.message, notify::Message::Notify(_));
let declares = threaded && dispatch::declares_inbox(&n.instance);
let action = crate::inbox::decide(&n.instance, declares, n.message);
let shown = crate::inbox::store::path()
.and_then(|path| crate::inbox::ops::sink(&path, &n.instance_id, &n.instance, action))
.map_err(|e| format!("{e:#}"))?;
Ok(shown.map(|shown| (n.instance, shown)))
}
pub struct BridgeWorker {
tx: Option<mpsc::Sender<(Vec<String>, Vec<(String, u64)>)>>,
handle: Option<std::thread::JoinHandle<()>>,
}
impl BridgeWorker {
pub fn send(&self, running: Vec<String>, urgent: Vec<(String, u64)>) {
if let Some(tx) = &self.tx {
let _ = tx.send((running, urgent));
}
}
}
impl Drop for BridgeWorker {
fn drop(&mut self) {
self.tx.take();
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::devsbd::{hash, install, start_daemon};
use std::process::Command;
fn ok(cmd: &mut Command) -> bool {
matches!(cmd.output(), Ok(o) if o.status.success())
}
#[test]
fn only_state_writing_ops_take_the_control_lock() {
use crate::devsbd::control::Op;
let locked: Vec<Op> = Op::ALL.into_iter().filter(|op| writes_state(*op)).collect();
assert_eq!(locked, [Op::Ensure, Op::Stop, Op::Rm, Op::Done]);
}
#[test]
fn retry_policy() {
assert_eq!(retry_decision(None, false), Retry::Spawn);
let (zero, day) = (Duration::ZERO, Duration::from_secs(86_400));
assert_eq!(retry_decision(Some((false, false, zero)), false), Retry::Keep);
assert_eq!(retry_decision(Some((false, false, day)), false), Retry::Keep);
assert_eq!(retry_decision(Some((true, false, zero)), false), Retry::Keep);
assert_eq!(retry_decision(Some((true, false, RETRY)), false), Retry::Respawn);
assert_eq!(retry_decision(Some((true, true, RETRY)), false), Retry::Keep);
assert_eq!(retry_decision(Some((true, true, MISMATCH_RETRY)), false), Retry::Respawn);
assert_eq!(retry_decision(None, true), Retry::Spawn);
assert_eq!(retry_decision(Some((true, false, zero)), true), Retry::Respawn);
assert_eq!(retry_decision(Some((true, true, zero)), true), Retry::Respawn);
assert_eq!(retry_decision(Some((false, false, zero)), true), Retry::Keep);
}
#[test]
fn board_verdict_waits_for_the_ticket_then_the_handshake() {
let board = BridgeBoard::default();
let t = board.ticket();
let at = |b: &BridgeBoard| verdict(&b.inner.0.lock().unwrap(), "c", t);
board.set("c", BridgeStatus::Ready);
assert_eq!(at(&board), None);
let observe = board.spawning("c");
board.handled(t);
assert_eq!(at(&board), None, "pending");
observe(BridgeStatus::Failed("helper in c is outdated".into()));
assert_eq!(at(&board), Some(Readiness::not("helper in c is outdated")));
let fresh = board.spawning("c");
observe(BridgeStatus::Ready);
assert_eq!(at(&board), None, "stale observer ignored");
fresh(BridgeStatus::Ready);
assert_eq!(at(&board), Some(Readiness::ready()));
board.retain(&[]);
assert!(!at(&board).unwrap().ready);
let t2 = board.ticket();
assert!(t2 > t);
board.handled(t2);
board.handled(t);
assert_eq!(board.inner.0.lock().unwrap().handled, t2);
}
#[test]
fn board_wait_wakes_on_news_and_times_out_with_a_reason() {
let board = BridgeBoard::default();
let t = board.ticket();
let short = Duration::from_millis(30);
assert!(board.wait("c", t, short).error.unwrap().contains("didn't get to it"));
let observe = board.spawning("c");
board.handled(t);
assert!(board.wait("c", t, short).error.unwrap().contains("handshake didn't finish"));
let started = Instant::now();
let waiter = {
let board = board.clone();
std::thread::spawn(move || board.wait("c", t, Duration::from_secs(10)))
};
std::thread::sleep(Duration::from_millis(50));
observe(BridgeStatus::Ready);
assert_eq!(waiter.join().unwrap(), Readiness::ready());
assert!(started.elapsed() < Duration::from_secs(5), "woken, not timed out");
}
#[test]
fn agent_candidates_are_newest_first_deduped_and_bounded() {
let mut c = AgentCandidates::default();
c.report("/a".into());
c.report("/b".into());
c.report("/a".into());
assert_eq!(c.recent, [PathBuf::from("/a"), PathBuf::from("/b")], "a repeat moves to the front");
for i in 0..20 {
c.report(format!("/n{i}").into());
}
assert_eq!(c.recent.len(), MAX_AGENTS);
assert_eq!(c.recent[0], PathBuf::from("/n19"));
assert!(!c.recent.contains(&PathBuf::from("/a")), "the oldest is forgotten");
}
#[test]
fn agent_pick_takes_the_first_live_one_then_the_fallback() {
let live = |names: &'static [&'static str]| move |p: &Path| names.iter().any(|n| p == Path::new(n));
let mut c = AgentCandidates::default();
assert_eq!(c.pick(Some("/env".into()), live(&["/env"])), Some("/env".into()));
assert_eq!(c.pick(Some("/env".into()), live(&[])), None);
assert_eq!(c.pick(None, live(&["/env"])), None);
c.report("/old".into());
c.report("/new".into());
assert_eq!(c.pick(Some("/env".into()), live(&["/old", "/new", "/env"])), Some("/new".into()));
assert_eq!(c.pick(Some("/env".into()), live(&["/old", "/env"])), Some("/old".into()));
assert_eq!(c.pick(Some("/env".into()), live(&["/env"])), Some("/env".into()));
assert_eq!(c.pick(Some("/env".into()), live(&[])), None);
}
#[test]
fn agent_live_needs_a_listening_socket() {
let dir = std::env::temp_dir().join(format!("devsbd-agentlive-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let sock = dir.join("agent.sock");
assert!(!agent_live(&sock), "missing");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
assert!(agent_live(&sock), "listening");
drop(listener);
let deadline = std::time::Instant::now() + Duration::from_secs(2);
while agent_live(&sock) && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
assert!(!agent_live(&sock), "a leftover socket file is dead");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn caps_advertise_notify_and_control_only_with_a_sink() {
const SERVED: u32 = caps::NOTIFY | caps::CONTROL;
assert_eq!(own_caps(false, false), 0);
assert_eq!(own_caps(true, false), caps::SSH_AGENT);
assert_eq!(own_caps(false, true), SERVED);
assert_eq!(own_caps(true, true), caps::SSH_AGENT | SERVED);
}
fn services_with(
instance: &str,
control: ControlHandler,
accept: bool,
) -> (Services, mpsc::Receiver<Notification>) {
let (tx, rx) = mpsc::channel();
let tx = Mutex::new(tx);
let sink: Sink = Arc::new(move |n| {
if !accept {
return Err("store is unhappy".into());
}
let _ = tx.lock().unwrap().send(n);
Ok(())
});
(Services::new(instance.into(), format!("{instance}-id"), sink, control), rx)
}
fn services(instance: &str, control: ControlHandler) -> (Services, mpsc::Receiver<Notification>) {
services_with(instance, control, true)
}
fn no_control() -> ControlHandler {
Arc::new(|_: &str, _: &Request| panic!("control handler called"))
}
#[test]
fn wanted_bridges() {
for helper in [false, true] {
assert_eq!(wanted(helper, false, true, false), None);
assert_eq!(wanted(helper, false, false, false), None);
}
assert_eq!(wanted(true, true, true, false), Some(true));
assert_eq!(wanted(true, true, false, false), None);
assert_eq!(wanted(true, false, false, true), Some(false));
assert_eq!(wanted(true, true, false, true), Some(false));
assert_eq!(wanted(true, false, true, true), Some(false));
assert_eq!(wanted(true, true, true, true), Some(true));
assert_eq!(wanted(false, false, true, true), None);
}
fn notify_pair() -> (Arc<Mux>, mpsc::Receiver<Notification>) {
service_pair_with(no_control(), true)
}
fn service_pair(control: ControlHandler) -> (Arc<Mux>, mpsc::Receiver<Notification>) {
service_pair_with(control, true)
}
fn service_pair_with(
control: ControlHandler,
accept: bool,
) -> (Arc<Mux>, mpsc::Receiver<Notification>) {
let (d_r, h_w) = std::io::pipe().unwrap();
let (h_r, d_w) = std::io::pipe().unwrap();
let daemon = Mux::new(d_w);
let host = Mux::new(h_w);
let (to, rx) = services_with("web-1", control, accept);
let d = Arc::clone(&daemon);
std::thread::spawn(move || d.serve(d_r, |_, _| None));
std::thread::spawn(move || {
let none: Option<fn() -> Option<PathBuf>> = None;
host.serve(h_r, move |_, ch| open_stream(ch, none.as_ref(), Some(&to)))
});
(daemon, rx)
}
fn send_notify(daemon: &Arc<Mux>, stream: u32, bytes: &[u8]) -> Vec<u8> {
send_on(daemon, stream, proto::channel::NOTIFY, bytes)
}
fn send_on(daemon: &Arc<Mux>, stream: u32, channel: u8, bytes: &[u8]) -> Vec<u8> {
let (mut ours, theirs) = UnixStream::pair().unwrap();
ours.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
daemon.attach(stream, theirs, Some(channel)).unwrap();
daemon.send(&proto::Frame::Data { stream, bytes: bytes.to_vec() }).unwrap();
daemon.send(&proto::Frame::Eof { stream }).unwrap();
let mut reply = Vec::new();
ours.read_to_end(&mut reply).unwrap();
reply
}
#[test]
fn notify_stream_replies_ok_and_delivers() {
let (daemon, rx) = notify_pair();
let message = notify::Message::Notify(notify::Record {
level: notify::Level::Warn,
key: Some("pr-1".into()),
link: None,
msg: "PR 1\nneeds you".into(),
at: 7,
});
let reply = send_notify(&daemon, 1, notify::encode(&message).as_bytes());
assert!(reply.starts_with(notify::REPLY_OK), "reply: {reply:?}");
let got = rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(
got,
Notification { instance: "web-1".into(), instance_id: "web-1-id".into(), message }
);
}
#[test]
fn thread_stream_replies_ok_and_delivers() {
let (daemon, rx) = notify_pair();
let message = notify::Message::ThreadPut {
at: 7,
key: "pr-1".into(),
body: r#"{"key":"pr-1"}"#.into(),
};
let reply = send_notify(&daemon, 1, notify::encode(&message).as_bytes());
assert!(reply.starts_with(notify::REPLY_OK), "reply: {reply:?}");
let got = rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(got.message, message);
}
#[test]
fn bad_or_oversized_notify_gets_no_ok_and_is_not_delivered() {
let (daemon, rx) = notify_pair();
let reply = send_notify(&daemon, 1, b"garbage");
assert!(!reply.starts_with(notify::REPLY_OK), "reply: {reply:?}");
let big = vec![b'x'; notify::MAX_RECORD + NOTIFY_SLACK + 1];
let reply = send_notify(&daemon, 3, &big);
assert!(reply.is_empty(), "oversized: closed without a reply");
assert!(rx.recv_timeout(Duration::from_millis(200)).is_err(), "nothing delivered");
}
#[test]
fn a_failing_sink_gets_no_ok() {
let (daemon, _rx) = service_pair_with(no_control(), false);
let message = notify::Message::Notify(notify::Record {
level: notify::Level::Info,
key: None,
link: None,
msg: "m".into(),
at: 1,
});
let reply = send_notify(&daemon, 1, notify::encode(&message).as_bytes());
assert!(reply.is_empty(), "reply: {reply:?}");
}
#[test]
fn sink_less_refuses_notify_and_control() {
let none: Option<fn() -> Option<PathBuf>> = None;
assert!(open_stream(proto::channel::NOTIFY, none.as_ref(), None).is_none());
assert!(open_stream(proto::channel::CONTROL, none.as_ref(), None).is_none());
assert!(open_stream(proto::channel::SSH_AGENT, none.as_ref(), None).is_none());
}
#[test]
fn handler_slots_bound_notify_and_control_opens() {
let (to, _rx) = services("web-1", no_control());
let held: Vec<_> = (0..MAX_HANDLERS).map(|_| HandlerSlot::acquire(&to.handlers).unwrap()).collect();
let none: Option<fn() -> Option<PathBuf>> = None;
assert!(open_stream(proto::channel::NOTIFY, none.as_ref(), Some(&to)).is_none());
assert!(open_stream(proto::channel::CONTROL, none.as_ref(), Some(&to)).is_none());
assert_eq!(to.handlers.load(Ordering::Acquire), MAX_HANDLERS);
drop(held);
assert_eq!(to.handlers.load(Ordering::Acquire), 0);
let conn = open_stream(proto::channel::NOTIFY, none.as_ref(), Some(&to));
assert!(conn.is_some());
drop(conn);
let mut freed = false;
for _ in 0..100 {
if to.handlers.load(Ordering::Acquire) == 0 {
freed = true;
break;
}
std::thread::sleep(Duration::from_millis(10));
}
assert!(freed, "handler thread released its slot");
}
#[test]
fn control_stream_runs_the_handler_and_replies() {
let (tx, calls) = mpsc::channel();
let tx = Mutex::new(tx);
let control: ControlHandler = Arc::new(move |key: &str, req: &Request| {
let _ = tx.lock().unwrap().send((key.to_string(), req.clone()));
Response::new(Status::Ok, "web-pr-1")
});
let (daemon, _notes) = service_pair(control);
let req = Request {
sandbox: Some("web".into()),
key: Some("pr-1".into()),
..Request::new(control::Op::Ensure)
};
let reply = send_on(&daemon, 1, proto::channel::CONTROL, control::encode_request(&req).as_bytes());
assert_eq!(reply, b"status ok\nbody web-pr-1\n");
assert_eq!(calls.recv_timeout(Duration::from_secs(5)).unwrap(), ("web-1".to_string(), req));
let reply = send_on(&daemon, 3, proto::channel::CONTROL, b"op boot\n");
let resp = control::decode_response(std::str::from_utf8(&reply).unwrap()).unwrap();
assert_eq!(resp.status, Status::Usage);
assert!(resp.body.contains("bad op"), "{}", resp.body);
let big = vec![b'x'; control::MAX_REQUEST + 1];
let reply = send_on(&daemon, 5, proto::channel::CONTROL, &big);
assert!(std::str::from_utf8(&reply).unwrap().starts_with("status usage\n"));
assert!(calls.recv_timeout(Duration::from_millis(200)).is_err(), "handler not called");
}
#[test]
fn worker_coalesces_and_joins() {
let worker = Bridges::spawn_worker(None, BridgeBoard::default());
for i in 0..100 {
worker.send(vec![format!("devsandbox-c{i}")], vec![(format!("devsandbox-c{i}"), i)]);
}
drop(worker);
}
#[test_utils::docker_test(helper)]
fn relays_host_agent_into_container_with_docker() -> Result<(), &'static str> {
if !ok(Command::new("ssh-agent").arg("-h")) && !ok(Command::new("which").arg("ssh-agent")) {
return Err("no host ssh-agent");
}
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let tmp = std::env::temp_dir().join(format!("devsbd-relay-{stamp}"));
std::fs::create_dir_all(&tmp).unwrap();
let sock = tmp.join("agent.sock");
let key = tmp.join("id");
let name = format!("devsandbox-relay-test-{stamp}");
let mut agent = Command::new("ssh-agent").arg("-D").arg("-a").arg(&sock).stdout(Stdio::null()).spawn().unwrap();
let cleanup = || {
let _ = agent.kill();
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
let _ = std::fs::remove_dir_all(&tmp);
};
crate::test_support::with_cleanup(cleanup, || {
for _ in 0..100 {
if sock.exists() {
break;
}
std::thread::sleep(Duration::from_millis(20));
}
assert!(ok(Command::new("ssh-keygen")
.args(["-q", "-t", "ed25519", "-N", "", "-C", "devsbd-relay-test", "-f"])
.arg(&key)));
assert!(ok(Command::new("ssh-add").arg(&key).env("SSH_AUTH_SOCK", &sock)));
assert!(ok(Command::new("docker").args(["run", "-d", "--name", &name, "alpine:3.20", "sleep", "300"])));
if !ok(Command::new("docker").args(["exec", &name, "apk", "add", "--no-cache", "-q", "openssh-client-default"])) {
return Err("apk add failed (no network?)");
}
let arch = install(&name, None).unwrap();
let bridge = || {
let agent_path = sock.clone();
spawn_with(&name, hash(arch).unwrap(), Some(move || Some(agent_path.clone())), None).unwrap()
};
let ssh_add = || {
Command::new("docker")
.args(["exec", "-e", "SSH_AUTH_SOCK=/run/devsandbox/ssh-agent.sock", &name, "ssh-add", "-l"])
.stdout(Stdio::piped())
.spawn()
.unwrap()
};
let list = || String::from_utf8_lossy(&ssh_add().wait_with_output().unwrap().stdout).into_owned();
let pidfile = || {
let out = Command::new("docker").args(["exec", &name, "cat", "/run/devsandbox/devsbd.pid"]).output().unwrap();
String::from_utf8_lossy(&out.stdout).trim().to_string()
};
let boot = bridge();
assert_eq!(boot.outcome(Duration::from_secs(10)), Some(Ok(())), "self-started daemon");
assert!(list().contains("devsbd-relay-test"), "via self-started daemon");
drop(boot);
start_daemon(&name);
let early = ssh_add();
std::thread::sleep(Duration::from_millis(300));
let long = bridge();
let out = String::from_utf8_lossy(&early.wait_with_output().unwrap().stdout).into_owned();
assert!(out.contains("devsbd-relay-test"), "held client: {out}");
assert_eq!(long.outcome(Duration::from_secs(5)), Some(Ok(())));
let short = bridge();
assert_eq!(short.outcome(Duration::from_secs(5)), Some(Ok(())));
assert!(list().contains("devsbd-relay-test"), "via newest bridge");
drop(short);
let mut fell_back = false;
for _ in 0..50 {
if list().contains("devsbd-relay-test") {
fell_back = true;
break;
}
std::thread::sleep(Duration::from_millis(100));
}
assert!(fell_back, "daemon fell back to the older bridge");
assert!(!long.is_done());
let old = pidfile();
let old_pid = old.split_whitespace().next().unwrap().to_string();
let fake = format!("printf '{old_pid} outdated\\n' > /run/devsandbox/devsbd.pid");
assert!(ok(Command::new("docker").args(["exec", &name, "sh", "-c", &fake])));
start_daemon(&name);
let mut replaced = false;
for _ in 0..50 {
let now = pidfile();
if !now.is_empty() && !now.starts_with(&format!("{old_pid} ")) {
assert!(now.ends_with(hash(arch).unwrap()), "{now}");
replaced = true;
break;
}
std::thread::sleep(Duration::from_millis(100));
}
assert!(replaced, "new daemon took over");
for _ in 0..50 {
if long.is_done() {
break;
}
std::thread::sleep(Duration::from_millis(100));
}
assert!(long.is_done(), "old daemon's bridge ended");
let fresh = bridge();
assert_eq!(fresh.outcome(Duration::from_secs(5)), Some(Ok(())));
assert!(list().contains("devsbd-relay-test"), "via new daemon");
let before = pidfile();
start_daemon(&name);
std::thread::sleep(Duration::from_millis(300));
assert_eq!(pidfile(), before);
drop(fresh);
let killed = "kill $(cut -d' ' -f1 /run/devsandbox/devsbd.pid)";
assert!(ok(Command::new("docker").args(["exec", &name, "sh", "-c", killed])));
let revived = bridge();
assert_eq!(revived.outcome(Duration::from_secs(10)), Some(Ok(())), "revived daemon");
assert!(list().contains("devsbd-relay-test"), "via revived daemon");
Ok(())
})
}
#[test_utils::docker_test(helper)]
fn agent_less_bridge_does_not_steal_agent_routing_with_docker() -> Result<(), &'static str> {
if !ok(Command::new("ssh-agent").arg("-h")) && !ok(Command::new("which").arg("ssh-agent")) {
return Err("no host ssh-agent");
}
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let tmp = std::env::temp_dir().join(format!("devsbd-agentroute-{stamp}"));
std::fs::create_dir_all(&tmp).unwrap();
let sock = tmp.join("agent.sock");
let key = tmp.join("id");
let name = format!("devsandbox-agentroute-test-{stamp}");
let mut agent = Command::new("ssh-agent").arg("-D").arg("-a").arg(&sock).stdout(Stdio::null()).spawn().unwrap();
let cleanup = || {
let _ = agent.kill();
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
let _ = std::fs::remove_dir_all(&tmp);
};
crate::test_support::with_cleanup(cleanup, || {
for _ in 0..100 {
if sock.exists() {
break;
}
std::thread::sleep(Duration::from_millis(20));
}
assert!(ok(Command::new("ssh-keygen")
.args(["-q", "-t", "ed25519", "-N", "", "-C", "devsbd-agentroute", "-f"])
.arg(&key)));
assert!(ok(Command::new("ssh-add").arg(&key).env("SSH_AUTH_SOCK", &sock)));
assert!(ok(Command::new("docker").args(["run", "-d", "--name", &name, "alpine:3.20", "sleep", "300"])));
if !ok(Command::new("docker").args(["exec", &name, "apk", "add", "--no-cache", "-q", "openssh-client-default"])) {
return Err("apk add failed (no network?)");
}
let arch = install(&name, None).unwrap();
start_daemon(&name);
let list = || {
let out = Command::new("docker")
.args(["exec", "-e", "SSH_AUTH_SOCK=/run/devsandbox/ssh-agent.sock", &name, "ssh-add", "-l"])
.output()
.unwrap();
String::from_utf8_lossy(&out.stdout).into_owned()
};
let agent_path = sock.clone();
let agent_bridge = spawn_with(&name, hash(arch).unwrap(), Some(move || Some(agent_path.clone())), None).unwrap();
assert_eq!(agent_bridge.outcome(Duration::from_secs(10)), Some(Ok(())), "agent bridge");
assert!(list().contains("devsbd-agentroute"), "via agent bridge");
let mut port_bridges = Vec::new();
for round in 0..6 {
let outputs = std::thread::scope(|s| {
let clients: Vec<_> = (0..12)
.map(|i| {
let list = &list;
s.spawn(move || {
std::thread::sleep(Duration::from_millis(15 * i));
list()
})
})
.collect();
let none: Option<fn() -> Option<PathBuf>> = None;
let port_bridge = spawn_with(&name, hash(arch).unwrap(), none, None).unwrap();
assert_eq!(port_bridge.outcome(Duration::from_secs(10)), Some(Ok(())), "agent-less bridge");
port_bridges.push(port_bridge);
clients.into_iter().map(|c| c.join().unwrap()).collect::<Vec<_>>()
});
for (i, out) in outputs.iter().enumerate() {
assert!(out.contains("devsbd-agentroute"), "round {round} client {i}: agent-less bridge stole routing: {out:?}");
}
}
assert!(list().contains("devsbd-agentroute"), "agent-less bridge stole routing");
Ok(())
})
}
#[test_utils::docker_test(helper)]
fn delivers_container_notify_to_the_sink_with_docker() -> Result<(), &'static str> {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let name = format!("devsandbox-notify-test-{stamp}");
let cleanup = || {
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
};
crate::test_support::with_cleanup(cleanup, || {
assert!(ok(Command::new("docker").args(["run", "-d", "--name", &name, "alpine:3.20", "sleep", "300"])));
let arch = install(&name, None).unwrap();
start_daemon(&name);
let (to, rx) = services("notify-test", no_control());
let none: Option<fn() -> Option<PathBuf>> = None;
let bridge = spawn_with(&name, hash(arch).unwrap(), none, Some(to)).unwrap();
assert_eq!(bridge.outcome(Duration::from_secs(10)), Some(Ok(())), "bridge handshake");
assert!(ok(Command::new("docker").args(["exec", &name, BIN, "notify", "--key", "k", "hello"])));
let got = rx.recv_timeout(Duration::from_secs(15)).expect("notification delivered");
assert_eq!(got.instance, "notify-test");
assert_eq!(
got.message,
notify::Message::Notify(notify::Record {
level: notify::Level::Info,
key: Some("k".into()),
link: None,
msg: "hello".into(),
at: got.message.at(),
})
);
let list = format!("ls -A {}", notify::OUTBOX);
let mut empty = false;
for _ in 0..50 {
let out = Command::new("docker").args(["exec", &name, "sh", "-c", &list]).output().unwrap();
if out.status.success() && out.stdout.is_empty() {
empty = true;
break;
}
std::thread::sleep(Duration::from_millis(100));
}
assert!(empty, "outbox drained");
Ok(())
})
}
#[test_utils::docker_test(helper)]
fn coalesces_queued_thread_puts_with_docker() -> Result<(), &'static str> {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let name = format!("devsandbox-thread-test-{stamp}");
let cleanup = || {
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
};
crate::test_support::with_cleanup(cleanup, || {
assert!(ok(Command::new("docker").args(["run", "-d", "--name", &name, "alpine:3.20", "sleep", "300"])));
let arch = install(&name, None).unwrap();
start_daemon(&name);
let put = |title: &str| {
let json = format!(r#"{{"key":"pr-1","title":"{title}","state":"active"}}"#);
ok(Command::new("docker").args(["exec", &name, BIN, "thread", "put", "--json", &json]))
};
assert!(put("first"));
assert!(put("second"));
assert!(ok(Command::new("docker").args(["exec", &name, BIN, "notify", "--key", "pr-1", "hello"])));
let count = format!("ls -A {} | wc -l", notify::OUTBOX);
let out = Command::new("docker").args(["exec", &name, "sh", "-c", &count]).output().unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "2", "the first put was replaced");
let (to, rx) = services("thread-test", no_control());
let none: Option<fn() -> Option<PathBuf>> = None;
let bridge = spawn_with(&name, hash(arch).unwrap(), none, Some(to)).unwrap();
assert_eq!(bridge.outcome(Duration::from_secs(10)), Some(Ok(())), "bridge handshake");
let first = rx.recv_timeout(Duration::from_secs(15)).expect("put delivered");
match first.message {
notify::Message::ThreadPut { key, body, .. } => {
assert_eq!(key, "pr-1");
assert!(body.contains("second"), "the newest put won: {body}");
}
other => panic!("expected a thread put, got {other:?}"),
}
let second = rx.recv_timeout(Duration::from_secs(15)).expect("notify delivered");
assert!(matches!(second.message, notify::Message::Notify(_)), "{:?}", second.message);
assert!(rx.recv_timeout(Duration::from_secs(2)).is_err(), "exactly one put arrived");
Ok(())
})
}
#[test_utils::docker_test(helper)]
fn coalesces_queued_thread_sends_with_docker() -> Result<(), &'static str> {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let name = format!("devsandbox-send-test-{stamp}");
let cleanup = || {
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
};
crate::test_support::with_cleanup(cleanup, || {
assert!(ok(Command::new("docker").args(["run", "-d", "--name", &name, "alpine:3.20", "sleep", "300"])));
let arch = install(&name, None).unwrap();
start_daemon(&name);
let devsbd = |args: &[&str]| Command::new("docker").args(["exec", &name, BIN]).args(args).output().unwrap();
let features = devsbd(&["features"]);
assert!(String::from_utf8_lossy(&features.stdout).lines().any(|l| l == "thread-send"), "{features:?}");
let put = r#"{"key":"pr-1","title":"PR 1","state":"active"}"#;
assert!(devsbd(&["thread", "put", "--json", put]).status.success());
let send = |id: &str, text: &str| {
let json = format!(r#"{{"thread":"pr-1","id":"{id}","blocks":[{{"type":"markdown","text":"{text}"}}]}}"#);
devsbd(&["thread", "send", "--json", &json])
};
assert!(send("a", "a1").status.success());
assert!(send("b", "b1").status.success());
assert!(send("a", "a2").status.success());
assert!(devsbd(&["thread", "withdraw", "pr-1", "b"]).status.success());
let bad = send("Bad", "x");
assert_eq!(bad.status.code(), Some(2), "{bad:?}");
assert!(String::from_utf8_lossy(&bad.stderr).contains("bad id `Bad`"), "{bad:?}");
let count = format!("ls -A {} | wc -l", notify::OUTBOX);
let out = Command::new("docker").args(["exec", &name, "sh", "-c", &count]).output().unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "3", "put, send a, withdraw b");
let (to, rx) = services("send-test", no_control());
let none: Option<fn() -> Option<PathBuf>> = None;
let bridge = spawn_with(&name, hash(arch).unwrap(), none, Some(to)).unwrap();
assert_eq!(bridge.outcome(Duration::from_secs(10)), Some(Ok(())), "bridge handshake");
let mut got = Vec::new();
for _ in 0..3 {
got.push(rx.recv_timeout(Duration::from_secs(15)).expect("record delivered").message);
}
assert!(matches!(&got[0], notify::Message::ThreadPut { key, .. } if key == "pr-1"), "{got:?}");
assert!(
matches!(&got[1], notify::Message::ThreadSend { key, id, body, .. } if key == "pr-1" && id == "a" && body.contains("a2")),
"a's newest body, ahead of b: {got:?}"
);
assert!(matches!(&got[2], notify::Message::ThreadWithdraw { id, .. } if id == "b"), "{got:?}");
assert!(rx.recv_timeout(Duration::from_secs(2)).is_err(), "nothing else arrived");
Ok(())
})
}
#[test_utils::docker_test(helper)]
fn serves_container_control_requests_with_docker() -> Result<(), &'static str> {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let name = format!("devsandbox-control-test-{stamp}");
let cleanup = || {
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
};
crate::test_support::with_cleanup(cleanup, || {
assert!(ok(Command::new("docker").args(["run", "-d", "--name", &name, "alpine:3.20", "sleep", "300"])));
let arch = install(&name, None).unwrap();
start_daemon(&name);
let ensure = || Command::new("docker").args(["exec", &name, BIN, "ensure", "web", "--key", "pr-1"]).output().unwrap();
let out = ensure();
assert_eq!(out.status.code(), Some(control::EXIT_NO_HOST), "{out:?}");
assert!(String::from_utf8_lossy(&out.stderr).contains("no host connected"), "{out:?}");
let (tx, calls) = mpsc::channel();
let tx = Mutex::new(tx);
let control: ControlHandler = Arc::new(move |key: &str, req: &Request| {
let _ = tx.lock().unwrap().send((key.to_string(), req.clone()));
Response::new(Status::Ok, "web-pr-1")
});
let (to, _notes) = services("control-test", control);
let none: Option<fn() -> Option<PathBuf>> = None;
let bridge = spawn_with(&name, hash(arch).unwrap(), none, Some(to)).unwrap();
assert_eq!(bridge.outcome(Duration::from_secs(10)), Some(Ok(())), "bridge handshake");
let mut out = ensure();
for _ in 0..50 {
if out.status.code() != Some(control::EXIT_NO_HOST) {
break;
}
std::thread::sleep(Duration::from_millis(100));
out = ensure();
}
assert_eq!(out.status.code(), Some(0), "{out:?}");
assert_eq!(String::from_utf8_lossy(&out.stdout), "web-pr-1\n");
let (key, req) = calls.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(key, "control-test");
assert_eq!((req.op, req.sandbox.as_deref(), req.key.as_deref()), (control::Op::Ensure, Some("web"), Some("pr-1")));
let out = Command::new("docker").args(["exec", &name, BIN, "ensure", "web"]).output().unwrap();
assert_eq!(out.status.code(), Some(control::EXIT_USAGE), "{out:?}");
assert!(calls.recv_timeout(Duration::from_millis(200)).is_err());
drop(bridge);
let mut code = None;
for _ in 0..50 {
code = ensure().status.code();
if code == Some(control::EXIT_NO_HOST) {
break;
}
std::thread::sleep(Duration::from_millis(100));
}
assert_eq!(code, Some(control::EXIT_NO_HOST), "after the bridge ended");
Ok(())
})
}
#[test]
fn follow_stream_runs_the_follow_handler() {
let (d_r, h_w) = std::io::pipe().unwrap();
let (h_r, d_w) = std::io::pipe().unwrap();
let daemon = Mux::new(d_w);
let host = Mux::new(h_w);
let (mut to, _rx) = services("web-1", no_control());
to.follow = Arc::new(|key: &str, req: &Request, out: &mut dyn Write| {
let _ = write!(out, "status ok\nbody \n{key} {}\n", req.key.as_deref().unwrap_or("-"));
});
let d = Arc::clone(&daemon);
std::thread::spawn(move || d.serve(d_r, |_, _| None));
std::thread::spawn(move || {
let none: Option<fn() -> Option<PathBuf>> = None;
host.serve(h_r, move |_, ch| open_stream(ch, none.as_ref(), Some(&to)))
});
let reply = send_on(&daemon, 1, proto::channel::CONTROL, b"op events-follow\nkey pr-1\n");
assert_eq!(reply, b"status ok\nbody \nweb-1 pr-1\n");
}
fn host_reply(path: &Path, owner: &str, text: &str) {
use crate::inbox::{store, Compose, State as TState, ThreadPut};
store::update_at(path, |i| {
let find = |i: &crate::inbox::Inbox| i.threads.iter().find(|t| t.owner == owner).map(|t| t.id);
if find(i).is_none() {
let put = ThreadPut {
key: "pr-1".into(),
title: "PR 1".into(),
state: TState::NeedsYou,
compose: Some(Compose::default()),
..ThreadPut::default()
};
i.put(owner, owner, 1, put);
}
let id = find(i).unwrap();
i.apply(&crate::inbox::Op::Reply { thread: id, text: text.into() }, 2, "tui");
})
.unwrap();
}
fn follower(name: &str) -> (std::process::Child, mpsc::Receiver<String>) {
use std::io::BufRead;
let mut child = Command::new("docker")
.args(["exec", name, BIN, "events", "--follow"])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let stdout = child.stdout.take().unwrap();
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
for line in std::io::BufReader::new(stdout).lines().map_while(Result::ok) {
let _ = tx.send(line);
}
});
(child, rx)
}
fn next_event(rx: &mpsc::Receiver<String>) -> Option<String> {
loop {
let line = rx.recv_timeout(Duration::from_secs(15)).ok()?;
if line != control::FOLLOW_PING_LINE {
return Some(line);
}
}
}
fn exit_within(child: &mut std::process::Child, secs: u64) -> Option<i32> {
let deadline = Instant::now() + Duration::from_secs(secs);
while Instant::now() < deadline {
if let Some(status) = child.try_wait().unwrap() {
return status.code();
}
std::thread::sleep(Duration::from_millis(100));
}
let _ = child.kill();
None
}
#[test_utils::docker_test(helper)]
fn follows_events_with_docker() -> Result<(), &'static str> {
use crate::commands::dispatch::{follow_events, Followers};
const OWNER: &str = "follow-owner";
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let name = format!("devsandbox-follow-test-{stamp}");
let dir = std::env::temp_dir().join(format!("devsandbox-follow-docker-{stamp}"));
let path = dir.join("inbox.json");
let cleanup = || {
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
let _ = std::fs::remove_dir_all(&dir);
};
crate::test_support::with_cleanup(cleanup, || {
assert!(ok(Command::new("docker").args(["run", "-d", "--name", &name, "alpine:3.20", "sleep", "300"])));
let arch = install(&name, None).unwrap();
start_daemon(&name);
host_reply(&path, OWNER, "before");
let followers = Arc::new(Followers::new());
let bridge_for = || {
let control: ControlHandler = Arc::new(|_: &str, _: &Request| Response::new(Status::Ok, "[]"));
let (mut to, _notes) = services("follow-test", control);
let (path, followers) = (path.clone(), Arc::clone(&followers));
to.follow = Arc::new(move |_: &str, req: &Request, out: &mut dyn Write| {
let ping = Duration::from_secs(1);
if let Err(resp) = follow_events(&path, OWNER, req.key.as_deref(), out, &followers, ping) {
let _ = out.write_all(control::encode_response(&resp).as_bytes());
}
});
let none: Option<fn() -> Option<PathBuf>> = None;
let bridge = spawn_with(&name, hash(arch).unwrap(), none, Some(to)).unwrap();
assert_eq!(bridge.outcome(Duration::from_secs(10)), Some(Ok(())), "bridge handshake");
let ls = || Command::new("docker").args(["exec", &name, BIN, "ls"]).output().unwrap().status.code();
let mut code = ls();
for _ in 0..50 {
if code == Some(0) {
break;
}
std::thread::sleep(Duration::from_millis(100));
code = ls();
}
assert_eq!(code, Some(0), "control routable");
bridge
};
let text = |line: &str| -> String {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
v["text"].as_str().unwrap_or_default().to_string()
};
let bridge = bridge_for();
let (mut first, first_rx) = follower(&name);
assert_eq!(next_event(&first_rx).map(|l| text(&l)).as_deref(), Some("before"), "pending first");
host_reply(&path, OWNER, "after");
assert_eq!(next_event(&first_rx).map(|l| text(&l)).as_deref(), Some("after"), "enqueued on the host");
let ping = first_rx.recv_timeout(Duration::from_secs(5)).expect("a ping");
assert_eq!(ping, control::FOLLOW_PING_LINE);
let (mut second, second_rx) = follower(&name);
assert_eq!(next_event(&first_rx).as_deref(), Some(control::FOLLOW_REPLACED_LINE));
assert_eq!(exit_within(&mut first, 10), Some(0), "replaced exits 0");
assert_eq!(next_event(&second_rx).map(|l| text(&l)).as_deref(), Some("before"));
assert_eq!(next_event(&second_rx).map(|l| text(&l)).as_deref(), Some("after"));
drop(bridge);
assert_eq!(exit_within(&mut second, 20), Some(control::EXIT_NO_HOST), "bridge gone");
let _bridge = bridge_for();
let (mut third, third_rx) = follower(&name);
assert_eq!(next_event(&third_rx).map(|l| text(&l)).as_deref(), Some("before"));
let kill = "kill $(cut -d' ' -f1 /run/devsandbox/devsbd.pid)";
assert!(ok(Command::new("docker").args(["exec", &name, "sh", "-c", kill])));
assert_eq!(exit_within(&mut third, 20), Some(control::EXIT_NO_HOST), "daemon killed");
Ok(())
})
}
#[test_utils::docker_test(helper)]
fn forwards_a_connect_to_a_loopback_server_with_docker() -> Result<(), &'static str> {
use std::io::{Read, Write};
use std::os::unix::net::UnixStream;
use std::sync::mpsc;
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let name = format!("devsandbox-forward-test-{stamp}");
let serve = "busybox nc -lk -s 127.0.0.1 -p 8080 -e cat";
let cleanup = || {
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
};
crate::test_support::with_cleanup(cleanup, || {
assert!(ok(Command::new("docker").args(["run", "-d", "--name", &name, "alpine:3.20", "sh", "-c", serve])));
let arch = install(&name, None).unwrap();
start_daemon(&name);
let none: Option<fn() -> Option<PathBuf>> = None;
let bridge = spawn_with(&name, hash(arch).unwrap(), none, None).unwrap();
assert_eq!(bridge.outcome(Duration::from_secs(10)), Some(Ok(())), "bridge handshake");
assert_eq!(bridge.peer_caps(), Some(caps::TCP_FORWARD), "daemon advertises TCP_FORWARD");
let mut round_tripped = false;
for _ in 0..30 {
let (mut ours, theirs) = UnixStream::pair().unwrap();
ours.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let (tx, closed) = mpsc::channel();
let Ok(_id) = bridge.connect(theirs, "127.0.0.1", 8080, move |r| {
let _ = tx.send(r);
}) else {
std::thread::sleep(Duration::from_millis(200));
continue;
};
ours.write_all(b"ping\n").unwrap();
let mut buf = [0u8; 5];
match ours.read_exact(&mut buf) {
Ok(()) if &buf == b"ping\n" => {
round_tripped = true;
break;
}
_ => {
let _ = closed.recv_timeout(Duration::from_secs(1));
std::thread::sleep(Duration::from_millis(200));
}
}
}
assert!(round_tripped, "loopback echo did not round-trip through the forward");
let (_ours, theirs) = UnixStream::pair().unwrap();
let (tx, closed) = mpsc::channel();
bridge.connect(theirs, "127.0.0.1", 9, move |r| {
let _ = tx.send(r);
})
.unwrap();
let reason = closed.recv_timeout(Duration::from_secs(10)).unwrap();
assert!(reason.contains("refused"), "closed port reason: {reason:?}");
Ok(())
})
}
}