use std::collections::{BTreeSet, HashMap};
use std::fs::{File, TryLockError};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::Shutdown;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use super::api::{self, Topic};
use super::endpoint::{self, Listener, Stream};
use super::forwards::{self, Registry};
use super::host::{Host, Waker};
use super::idle::{self, Decision, Holders};
use super::proto::{self, HelloParams, HelloResult, Notification, Request, Response, Version};
use crate::inbox::ops;
const TICK: Duration = Duration::from_millis(100);
pub const DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
const LOCK_WAIT: Duration = Duration::from_secs(10);
const LOCK_POLL: Duration = Duration::from_millis(50);
const WATCH: Duration = Duration::from_millis(500);
const WRITE_TIMEOUT: Duration = Duration::from_secs(5);
pub struct Options {
pub version: Version,
pub keep_alive: bool,
pub idle_timeout: Duration,
pub host: bool,
pub inbox: Option<PathBuf>,
}
impl Options {
pub fn new(keep_alive: bool) -> Self {
Self { version: Version::current(), keep_alive, idle_timeout: idle::IDLE_TIMEOUT, host: true, inbox: None }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Exit {
AlreadyRunning,
Idle,
Handoff,
Shutdown,
}
pub fn serve(socket_dir: Option<PathBuf>, keep_alive: bool) -> Result<()> {
let dir = match socket_dir {
Some(dir) => dir,
None => endpoint::socket_dir()?,
};
let config = crate::daemon_config::load().unwrap_or_else(|e| {
log(&format!("warning: {e:#}; using defaults"));
Default::default()
});
let opts = Options::new(keep_alive || config.serve.keep_alive);
match run(&dir, &opts)? {
Exit::AlreadyRunning => {}
Exit::Idle => log("idle, exiting"),
Exit::Handoff => log("handed off to a newer version, exiting"),
Exit::Shutdown => log("shutdown requested, exiting"),
}
Ok(())
}
pub fn run(dir: &Path, opts: &Options) -> Result<Exit> {
endpoint::ensure_private_dir(dir)?;
let Some(_lock) = acquire_lock(dir)? else {
return Ok(Exit::AlreadyRunning);
};
let inbox = match &opts.inbox {
Some(path) => path.clone(),
None => crate::inbox::store::path()?,
};
let listener = Listener::bind(dir)?;
log(&format!(
"listening on {} (pid {}, version {} build {}{})",
endpoint::socket_path(dir).display(),
std::process::id(),
opts.version.semver,
opts.version.build,
if opts.keep_alive { ", keep-alive" } else { "" },
));
let shared = Arc::new(Shared::new(opts.version.clone(), inbox));
let registry = if opts.host {
let shared = Arc::clone(&shared);
let store = super::forward_store::path()?;
Some(Registry::spawn(log, store, Box::new(move |event| shared.publish_forwards(event))))
} else {
None
};
if let Some(registry) = ®istry {
let _ = shared.forwards.set(registry.handle());
}
let host = opts.host.then(|| {
let shared = Arc::clone(&shared);
let sync = registry.as_ref().map(Registry::handle);
Host::start(
log,
Box::new(move |instance: &str, line: String| shared.publish_shown(instance, line)),
Box::new(move |running: &[String]| {
if let Some(sync) = &sync {
sync.sync(running.to_vec());
}
}),
)
});
if let Some(host) = &host {
let _ = shared.bridges.set(host.waker());
}
let watcher = Watcher::spawn(&shared, host.as_ref().map(Host::changes));
let mut next_conn = 0u64;
let exit = loop {
if let Some(exit) = *shared.stop.lock().unwrap() {
break exit;
}
let now = Instant::now();
let holders = shared.holders(host.as_ref(), registry.as_ref());
if holders.any() {
*shared.idle_since.lock().unwrap() = now;
}
let idle_since = *shared.idle_since.lock().unwrap();
if idle::decide(&holders, idle_since, now, opts.keep_alive, opts.idle_timeout) == Decision::Exit {
break Exit::Idle;
}
match listener.accept_timeout(TICK) {
Ok(Some(stream)) => {
next_conn += 1;
shared.spawn_conn(next_conn, stream);
}
Ok(None) => {}
Err(e) => {
log(&format!("accept failed: {e}"));
std::thread::sleep(TICK);
}
}
};
listener.remove();
shared.close();
shared.publish_closing(match exit {
Exit::Handoff => "handoff",
Exit::Shutdown => "shutdown",
_ => "idle",
});
shared.drain(DRAIN_TIMEOUT);
drop(watcher);
drop(host);
drop(registry);
Ok(exit)
}
fn acquire_lock(dir: &Path) -> Result<Option<File>> {
let path = endpoint::lock_path(dir);
let file = File::options()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(&path)
.with_context(|| format!("cannot open {}", path.display()))?;
let deadline = Instant::now() + LOCK_WAIT;
loop {
match file.try_lock() {
Ok(()) => return Ok(Some(file)),
Err(TryLockError::WouldBlock) => {}
Err(TryLockError::Error(e)) => return Err(e).with_context(|| format!("cannot lock {}", path.display())),
}
if endpoint::connect(dir).is_ok() {
return Ok(None);
}
if Instant::now() >= deadline {
bail!(
"{} is locked but nothing answers on {}",
path.display(),
endpoint::socket_path(dir).display()
);
}
std::thread::sleep(LOCK_POLL);
}
}
struct Shared {
version: Version,
inbox: PathBuf,
conns: Mutex<HashMap<u64, ConnEntry>>,
inbox_generation: AtomicU64,
idle_since: Mutex<Instant>,
stop: Mutex<Option<Exit>>,
closed: (Mutex<bool>, Condvar),
bridges: OnceLock<Waker>,
forwards: OnceLock<forwards::Handle>,
}
impl Shared {
fn new(version: Version, inbox: PathBuf) -> Self {
Self {
version,
inbox,
conns: Mutex::new(HashMap::new()),
inbox_generation: AtomicU64::new(0),
idle_since: Mutex::new(Instant::now()),
stop: Mutex::new(None),
closed: (Mutex::new(false), Condvar::new()),
bridges: OnceLock::new(),
forwards: OnceLock::new(),
}
}
fn holders(&self, host: Option<&Host>, registry: Option<&Registry>) -> Holders {
let clients = self.conns.lock().unwrap().len();
let forwards = registry.map_or(0, Registry::active);
let Some(host) = host else { return Holders { clients, forwards, ..Default::default() } };
Holders {
clients,
forwards,
live_instances: host.live_instances(),
control: host.control(),
autostart: host.autostarting(),
..Default::default()
}
}
fn spawn_conn(self: &Arc<Self>, id: u64, stream: Stream) {
let (Ok(clone), Ok(writer), Ok(ctl)) = (stream.try_clone(), stream.try_clone(), stream.try_clone()) else {
return;
};
let _ = stream.set_write_timeout(Some(WRITE_TIMEOUT));
let out = Arc::new(Outbox::new(writer, ctl));
self.conns.lock().unwrap().insert(id, ConnEntry { stream: clone, out: Arc::clone(&out) });
let shared = Arc::clone(self);
let spawned = std::thread::Builder::new().name(format!("serve-conn-{id}")).spawn(move || {
serve_conn(id, stream, &shared, out);
shared.conns.lock().unwrap().remove(&id);
*shared.idle_since.lock().unwrap() = Instant::now();
});
if spawned.is_err() {
self.conns.lock().unwrap().remove(&id);
}
}
fn close(&self) {
let (lock, cvar) = &self.closed;
*lock.lock().unwrap() = true;
cvar.notify_all();
}
fn begin_stop(&self, exit: Exit) {
self.stop.lock().unwrap().get_or_insert(exit);
let (lock, cvar) = &self.closed;
let guard = lock.lock().unwrap();
let _ = cvar.wait_timeout_while(guard, Duration::from_secs(2), |closed| !*closed);
}
fn publish(&self, topic: Topic, set: impl Fn(&mut Pending)) {
for conn in self.conns.lock().unwrap().values() {
conn.out.post(|p| {
let subscribed = p.topics.contains(&topic);
if subscribed {
set(p);
}
subscribed
});
}
}
fn publish_shown(&self, instance: &str, line: String) {
self.publish(Topic::Inbox, |p| p.shown = Some((instance.to_string(), line.clone())));
}
fn publish_forwards(&self, event: forwards::Event) {
match event {
forwards::Event::Changed => self.publish(Topic::Forwards, |p| p.forwards = true),
forwards::Event::Status(line) => self.publish(Topic::Forwards, |p| p.forwards_status = Some(line.clone())),
}
}
fn publish_closing(&self, reason: &'static str) {
for conn in self.conns.lock().unwrap().values() {
conn.out.post(|p| {
let subscribed = !p.topics.is_empty();
if subscribed {
p.closing = Some(reason);
}
subscribed
});
}
}
fn drain(&self, timeout: Duration) {
for conn in self.conns.lock().unwrap().values() {
let _ = conn.stream.shutdown(Shutdown::Read);
}
let deadline = Instant::now() + timeout;
while !self.conns.lock().unwrap().is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
}
}
struct ConnEntry {
stream: Stream,
out: Arc<Outbox>,
}
struct Outbox {
writer: Mutex<Stream>,
ctl: Stream,
pending: Mutex<Pending>,
wake: Condvar,
}
#[derive(Default)]
struct Pending {
topics: BTreeSet<Topic>,
inbox: Option<u64>,
shown: Option<(String, String)>,
instances: bool,
forwards: bool,
forwards_status: Option<String>,
closing: Option<&'static str>,
closed: bool,
}
impl Pending {
fn any(&self) -> bool {
self.inbox.is_some()
|| self.shown.is_some()
|| self.instances
|| self.forwards
|| self.forwards_status.is_some()
|| self.closing.is_some()
}
fn take(&mut self) -> Vec<Notification> {
let mut out = Vec::new();
if let Some(generation) = self.inbox.take() {
out.push(Notification { method: "inbox.changed".into(), params: json!({ "generation": generation }) });
}
if let Some((instance, line)) = self.shown.take() {
out.push(Notification { method: "inbox.shown".into(), params: json!({ "instance": instance, "line": line }) });
}
if std::mem::take(&mut self.instances) {
out.push(Notification { method: "instances.changed".into(), params: json!({}) });
}
if std::mem::take(&mut self.forwards) {
out.push(Notification { method: "forwards.changed".into(), params: json!({}) });
}
if let Some(line) = self.forwards_status.take() {
out.push(Notification { method: "forwards.status".into(), params: json!({ "line": line }) });
}
if let Some(reason) = self.closing.take() {
out.push(Notification { method: "closing".into(), params: json!({ "reason": reason }) });
}
out
}
}
impl Outbox {
fn new(writer: Stream, ctl: Stream) -> Self {
Self { writer: Mutex::new(writer), ctl, pending: Mutex::new(Pending::default()), wake: Condvar::new() }
}
fn send(&self, msg: &impl serde::Serialize) -> std::io::Result<()> {
let mut line = serde_json::to_vec(msg)?;
line.push(b'\n');
let mut writer = self.writer.lock().unwrap_or_else(|e| e.into_inner());
writer.write_all(&line)?;
writer.flush()
}
fn post(&self, f: impl FnOnce(&mut Pending) -> bool) {
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
if f(&mut pending) {
self.wake.notify_all();
}
}
}
fn notifier(out: &Outbox) {
loop {
let (notes, closed) = {
let mut p = out.pending.lock().unwrap_or_else(|e| e.into_inner());
while !p.any() && !p.closed {
p = out.wake.wait(p).unwrap_or_else(|e| e.into_inner());
}
(p.take(), p.closed)
};
for note in ¬es {
if out.send(note).is_err() {
let _ = out.ctl.shutdown(Shutdown::Both);
return;
}
}
if closed {
return;
}
}
}
struct Watcher {
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
impl Watcher {
fn spawn(shared: &Arc<Shared>, instances: Option<Arc<AtomicU64>>) -> Self {
let stop = Arc::new(AtomicBool::new(false));
let thread = {
let (shared, stop) = (Arc::clone(shared), Arc::clone(&stop));
std::thread::Builder::new().name("serve-watch".into()).spawn(move || watch(&shared, instances, &stop))
};
let thread = thread.map_err(|e| log(&format!("cannot start the notification thread: {e}"))).ok();
Self { stop, thread }
}
}
impl Drop for Watcher {
fn drop(&mut self) {
self.stop.store(true, Ordering::SeqCst);
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
fn watch(shared: &Shared, instances: Option<Arc<AtomicU64>>, stop: &AtomicBool) {
let mut seen = ops::generation();
let mut stamp = ops::stamp(&shared.inbox);
let instances_now = || instances.as_ref().map_or(0, |c| c.load(Ordering::Acquire));
let mut instances_seen = instances_now();
while !stop.load(Ordering::SeqCst) {
let generation = ops::wait_changed(seen, WATCH);
let now = ops::stamp(&shared.inbox);
if generation != seen || now != stamp {
(seen, stamp) = (generation, now);
let g = shared.inbox_generation.fetch_add(1, Ordering::SeqCst) + 1;
shared.publish(Topic::Inbox, |p| p.inbox = Some(g));
}
let n = instances_now();
if n != instances_seen {
instances_seen = n;
shared.publish(Topic::Instances, |p| p.instances = true);
}
}
}
struct ConnState {
id: u64,
client: String,
audit: String,
out: Arc<Outbox>,
notifier: Option<JoinHandle<()>>,
}
impl ConnState {
fn label(&self) -> String {
match self.client.as_str() {
"" => format!("connection {}", self.id),
client => format!("connection {} ({client})", self.id),
}
}
}
fn serve_conn(id: u64, stream: Stream, shared: &Shared, out: Arc<Outbox>) {
let mut conn = ConnState { id, client: String::new(), audit: api::audit_client(""), out, notifier: None };
let mut reader = BufReader::new(stream);
loop {
let mut line = Vec::new();
match (&mut reader).take(proto::MAX_LINE).read_until(b'\n', &mut line) {
Ok(0) | Err(_) => break,
Ok(_) => {}
}
let too_long = !line.ends_with(b"\n") && line.len() as u64 >= proto::MAX_LINE;
let response = if too_long {
Response::err(None, "invalid", "request line too long")
} else if line.trim_ascii().is_empty() {
continue;
} else {
handle(&line, shared, &mut conn)
};
if conn.out.send(&response).is_err() || too_long {
break;
}
}
conn.out.post(|p| {
p.closed = true;
true
});
if let Some(t) = conn.notifier.take() {
let _ = t.join();
}
}
fn handle(line: &[u8], shared: &Shared, conn: &mut ConnState) -> Response {
let req: Request = match serde_json::from_slice(line) {
Ok(req) => req,
Err(e) => return Response::err(None, "invalid", format!("not a request: {e}")),
};
let answer = match req.method.as_str() {
"hello" => return hello(req.id, req.params, shared, conn),
"subscribe" => subscribe(req.params, conn, true),
"unsubscribe" => subscribe(req.params, conn, false),
"shutdown" => {
log(&format!("{}: shutdown requested", conn.label()));
shared.begin_stop(Exit::Shutdown);
Ok(json!({ "ok": true }))
}
method => {
let bridges = shared.bridges.get().map(|w| w as &dyn api::Bridging);
let forwards = shared.forwards.get().map(|h| h as &dyn api::Forwarding);
api::call(method, req.params, &api::Ctx { inbox: &shared.inbox, client: &conn.audit, bridges, forwards })
}
};
match answer {
Ok(result) => Response::ok(req.id, result),
Err(e) => {
if e.code == "internal" {
log(&format!("{}: {}: {}", conn.label(), req.method, e.message));
}
Response::err(req.id, e.code, e.message)
}
}
}
fn subscribe(params: Value, conn: &mut ConnState, on: bool) -> Result<Value, api::ApiError> {
let topics = api::topics(params)?;
if on && conn.notifier.is_none() {
let out = Arc::clone(&conn.out);
let spawned = std::thread::Builder::new().name(format!("serve-notify-{}", conn.id)).spawn(move || notifier(&out));
conn.notifier = Some(spawned.map_err(|e| api::ApiError::internal(e.into()))?);
}
conn.out.post(|p| {
for topic in topics {
if on {
p.topics.insert(topic);
} else {
p.topics.remove(&topic);
match topic {
Topic::Inbox => {
p.inbox = None;
p.shown = None;
}
Topic::Instances => p.instances = false,
Topic::Forwards => {
p.forwards = false;
p.forwards_status = None;
}
}
}
}
false
});
Ok(json!({ "ok": true }))
}
fn hello(id: Option<u64>, params: Value, shared: &Shared, conn: &mut ConnState) -> Response {
let params: HelloParams = match serde_json::from_value(params) {
Ok(p) => p,
Err(e) => return Response::err(id, "invalid", format!("bad hello params: {e}")),
};
conn.client.clone_from(¶ms.client);
conn.audit = api::audit_client(¶ms.client);
let client = Version { semver: params.version, build: params.build };
let handoff = client.is_newer_than(&shared.version);
if handoff {
log(&format!(
"client `{}` has version {} build {}: handing off",
params.client, client.semver, client.build
));
shared.begin_stop(Exit::Handoff);
}
let result = HelloResult {
version: shared.version.semver.clone(),
build: shared.version.build,
protocol: proto::PROTOCOL,
handoff,
};
Response::ok(id, serde_json::to_value(result).unwrap_or(Value::Null))
}
pub(super) fn log(msg: &str) {
let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
eprintln!("[{secs}] devsandbox serve: {msg}");
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::serve::client::{self, Hello};
pub(crate) fn scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("dsv-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
dir
}
pub(crate) fn opts(build: u64, idle_ms: u64) -> Options {
Options {
version: Version { semver: "0.6.0".into(), build },
keep_alive: false,
idle_timeout: Duration::from_millis(idle_ms),
host: false,
inbox: Some(std::env::temp_dir().join(format!("dsv-inbox-{}", std::process::id())).join("inbox.json")),
}
}
pub(crate) fn spawn_daemon(dir: &Path, opts: Options) -> std::thread::JoinHandle<Result<Exit>> {
let dir = dir.to_owned();
std::thread::spawn(move || run(&dir, &opts))
}
fn v(build: u64) -> Version {
Version { semver: "0.6.0".into(), build }
}
fn hello_at(dir: &Path, version: &Version) -> (Stream, Hello) {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
if let Ok(stream) = endpoint::connect(dir) {
let mut stream = stream;
let hello = client::hello(&mut stream, version, "test").unwrap();
return (stream, hello);
}
assert!(Instant::now() < deadline, "daemon never listened");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn concurrent_starts_have_one_winner_and_all_clients_reach_it() {
let dir = scratch("race");
let daemons: Vec<_> = (0..8).map(|_| spawn_daemon(&dir, opts(1, 300))).collect();
let clients: Vec<_> = (0..8)
.map(|_| {
let dir = dir.clone();
std::thread::spawn(move || hello_at(&dir, &v(1)).1)
})
.collect();
for c in clients {
match c.join().unwrap() {
Hello::Ready(result) => assert_eq!(result.build, 1),
other => panic!("{other:?}"),
}
}
let mut exits: Vec<_> = daemons.into_iter().map(|d| d.join().unwrap().unwrap()).collect();
exits.sort_by_key(|e| *e != Exit::Idle);
assert_eq!(exits[0], Exit::Idle);
assert!(exits[1..].iter().all(|e| *e == Exit::AlreadyRunning), "{exits:?}");
assert!(!endpoint::socket_path(&dir).exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn newer_hello_hands_off_drains_and_exits() {
let dir = scratch("handoff");
let daemon = spawn_daemon(&dir, opts(1, 60_000));
let (mut idle_client, equal) = hello_at(&dir, &v(1));
assert!(matches!(equal, Hello::Ready(_)), "{equal:?}");
let (_older_conn, older) = hello_at(&dir, &Version { semver: "0.5.9".into(), build: 9 });
assert!(matches!(older, Hello::Ready(_)), "{older:?}");
let started = Instant::now();
let (_newer_conn, newer) = hello_at(&dir, &v(2));
assert!(matches!(newer, Hello::Handoff), "{newer:?}");
assert!(endpoint::connect(&dir).is_err());
assert_eq!(daemon.join().unwrap().unwrap(), Exit::Handoff);
assert!(started.elapsed() < DRAIN_TIMEOUT);
let mut buf = [0u8; 1];
assert_eq!(idle_client.read(&mut buf).unwrap(), 0);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn unknown_methods_and_garbage_get_errors_with_ids() {
let dir = scratch("unknown");
let daemon = spawn_daemon(&dir, opts(1, 200));
let (stream, _) = hello_at(&dir, &v(1));
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut writer = stream;
let mut ask = |line: &str| {
writer.write_all(format!("{line}\n").as_bytes()).unwrap();
let mut out = String::new();
reader.read_line(&mut out).unwrap();
serde_json::from_str::<Value>(&out).unwrap()
};
let r = ask(r#"{"id":7,"method":"inbox.poll.vote"}"#);
assert_eq!(r["id"], 7);
assert_eq!(r["error"]["code"], "unknown-method");
let r = ask("not json");
assert_eq!(r["error"]["code"], "invalid");
let r = ask(r#"{"id":8,"method":"hello","params":{"nope":1}}"#);
assert_eq!((r["id"].as_u64(), r["error"]["code"].as_str()), (Some(8), Some("invalid")));
drop(ask);
drop(writer);
drop(reader);
assert_eq!(daemon.join().unwrap().unwrap(), Exit::Idle);
let _ = std::fs::remove_dir_all(&dir);
}
fn connect(dir: &Path) -> client::Conn {
client::connect_with(dir, "test", &v(1), client::START_TIMEOUT, &|_, _| Ok(())).unwrap()
}
fn note(path: &Path, msg: &str) {
use crate::devsbd::notify::{Level, Record};
let record = Record { level: Level::Info, key: None, link: None, msg: msg.into(), at: 1 };
crate::inbox::store::update_at(path, |i| i.push("w-id".into(), "w".into(), record, true)).unwrap();
}
fn drain_notes(conn: &mut client::Conn, wait: Duration) {
while conn.next_notification(wait).unwrap().is_some() {}
}
#[test]
fn subscribers_hear_inbox_changes_between_responses() {
let dir = scratch("notify");
let store = scratch("notify-store").join("inbox.json");
let daemon = spawn_daemon(&dir, Options { inbox: Some(store.clone()), ..opts(1, 200) });
let mut conn = connect(&dir);
assert_eq!(conn.daemon.protocol, proto::PROTOCOL);
let r = conn.call("subscribe", json!({"topics": ["nope"]})).unwrap();
assert_eq!(r.error.unwrap().code, "invalid");
let r = conn.call("subscribe", json!({"topics": ["inbox"]})).unwrap();
assert_eq!(r.result, Some(json!({"ok": true})));
drain_notes(&mut conn, Duration::from_millis(200));
note(&store, "one");
let n = conn.next_notification(Duration::from_secs(3)).unwrap().expect("no inbox.changed");
assert_eq!(n.method, "inbox.changed");
assert!(n.params["generation"].as_u64().unwrap() >= 1, "{n:?}");
drain_notes(&mut conn, Duration::from_millis(100));
note(&store, "two");
std::thread::sleep(Duration::from_millis(300));
let r = conn.call("inbox.threads.list", json!({"view": "all"})).unwrap();
assert_eq!(r.result.unwrap().as_array().unwrap().len(), 2);
let n = conn.next_notification(Duration::ZERO).unwrap().expect("not set aside by call");
assert_eq!(n.method, "inbox.changed");
let r = conn.call("inbox.thread.get", json!({"thread": 999})).unwrap();
assert_eq!(r.error.unwrap().code, "not-found");
let r = conn.call("unsubscribe", json!({"topics": ["inbox"]})).unwrap();
assert!(r.error.is_none());
drain_notes(&mut conn, Duration::ZERO);
note(&store, "three");
assert!(conn.next_notification(Duration::from_millis(800)).unwrap().is_none());
drop(conn);
assert_eq!(daemon.join().unwrap().unwrap(), Exit::Idle);
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(store.parent().unwrap());
}
fn wait_for(conn: &mut client::Conn, method: &str) -> Notification {
let deadline = Instant::now() + Duration::from_secs(3);
loop {
let left = deadline.saturating_duration_since(Instant::now());
let n = conn.next_notification(left).unwrap().unwrap_or_else(|| panic!("no {method}"));
if n.method == method {
return n;
}
}
}
#[test]
fn two_dashboards_hear_one_write() {
let dir = scratch("two");
let store = scratch("two-store").join("inbox.json");
let daemon = spawn_daemon(&dir, Options { inbox: Some(store.clone()), ..opts(1, 200) });
let (mut a, mut b) = (connect(&dir), connect(&dir));
for conn in [&mut a, &mut b] {
conn.call("subscribe", json!({"topics": ["inbox"]})).unwrap();
}
note(&store, "one");
let id = ops::load(&store).unwrap().threads[0].id;
drain_notes(&mut a, Duration::from_millis(700));
drain_notes(&mut b, Duration::ZERO);
let r = a.call("inbox.thread.markRead", json!({ "thread": id })).unwrap();
assert!(r.error.is_none(), "{r:?}");
wait_for(&mut a, "inbox.changed");
wait_for(&mut b, "inbox.changed");
drop((a, b));
assert_eq!(daemon.join().unwrap().unwrap(), Exit::Idle);
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(store.parent().unwrap());
}
#[test]
fn shown_lines_reach_inbox_subscribers_latest_first() {
use std::os::unix::net::UnixStream;
let shared = Arc::new(Shared::new(v(1), scratch("shown-store").join("inbox.json")));
let mut clients = Vec::new();
for (id, topics) in [(1, json!(["inbox"])), (2, json!(["inbox"])), (3, json!(["instances"]))] {
let (server, client) = UnixStream::pair().unwrap();
shared.spawn_conn(id, server);
let mut reader = BufReader::new(client.try_clone().unwrap());
let mut writer = client;
writeln!(writer, "{}", json!({"id": 1, "method": "subscribe", "params": {"topics": topics}})).unwrap();
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"], json!({"ok": true}));
reader.get_ref().set_read_timeout(Some(Duration::from_secs(3))).unwrap();
clients.push((reader, writer));
}
shared.publish_shown("disp", "disp: first".into());
shared.publish_shown("disp", "disp: second".into());
for (reader, _) in &mut clients[..2] {
let last = loop {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let n: Value = serde_json::from_str(&line).unwrap();
assert_eq!(n["method"], "inbox.shown", "{n}");
assert_eq!(n["params"]["instance"], "disp");
if n["params"]["line"] == "disp: second" {
break n;
}
assert_eq!(n["params"]["line"], "disp: first");
};
assert!(last.get("id").is_none());
}
let (reader, _) = &mut clients[2];
reader.get_ref().set_read_timeout(Some(Duration::from_millis(300))).unwrap();
let mut line = String::new();
assert!(reader.read_line(&mut line).is_err() || line.is_empty(), "{line}");
}
fn subscribed(shared: &Arc<Shared>, id: u64, topics: Value) -> BufReader<std::os::unix::net::UnixStream> {
let (server, client) = std::os::unix::net::UnixStream::pair().unwrap();
shared.spawn_conn(id, server);
let mut reader = BufReader::new(client.try_clone().unwrap());
let mut writer = client;
writeln!(writer, "{}", json!({"id": 1, "method": "subscribe", "params": {"topics": topics}})).unwrap();
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"], json!({"ok": true}));
reader.get_ref().set_read_timeout(Some(Duration::from_secs(3))).unwrap();
reader
}
#[test]
fn forwards_subscribers_hear_changes_and_status_lines() {
let shared = Arc::new(Shared::new(v(1), scratch("fwd-store").join("inbox.json")));
let mut fwd = subscribed(&shared, 1, json!(["forwards"]));
let mut other = subscribed(&shared, 2, json!(["inbox", "instances"]));
shared.publish_forwards(forwards::Event::Changed);
let mut line = String::new();
fwd.read_line(&mut line).unwrap();
let n: Value = serde_json::from_str(&line).unwrap();
assert_eq!((n["method"].as_str(), &n["params"]), (Some("forwards.changed"), &json!({})));
shared.publish_forwards(forwards::Event::Status("3000: connection refused".into()));
line.clear();
fwd.read_line(&mut line).unwrap();
let n: Value = serde_json::from_str(&line).unwrap();
assert_eq!(n["method"], "forwards.status");
assert_eq!(n["params"]["line"], "3000: connection refused");
other.get_ref().set_read_timeout(Some(Duration::from_millis(300))).unwrap();
line.clear();
assert!(other.read_line(&mut line).is_err() || line.is_empty(), "{line}");
}
#[test]
fn active_forwards_are_holders() {
let shared = Shared::new(v(1), scratch("fwd-hold").join("inbox.json"));
let registry = Registry::spawn(|_| {}, scratch("fwd-hold-store").join("forwards.toml"), Box::new(|_| {}));
assert_eq!(shared.holders(None, Some(®istry)), Holders::default());
let dir = scratch("fwd-hold-root");
std::fs::create_dir_all(&dir).unwrap();
let req = forwards::AddRequest {
dir: dir.clone(),
instance: None,
service: Some("db".into()),
bind: std::net::Ipv4Addr::LOCALHOST.into(),
host_port: crate::devsbd::forward::HostPort::Prefer(0),
container_port: 5432,
};
let h = registry.handle();
let added = api::Forwarding::add(&h, req).unwrap();
api::Forwarding::list(&h, None).unwrap();
let holders = shared.holders(None, Some(®istry));
assert_eq!(holders, Holders { forwards: 1, ..Default::default() });
assert!(holders.any());
api::Forwarding::rm(&h, added.id).unwrap();
api::Forwarding::list(&h, None).unwrap();
assert!(!shared.holders(None, Some(®istry)).any());
drop(registry);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn subscribers_get_a_closing_hint_on_handoff() {
let dir = scratch("closing");
let daemon = spawn_daemon(&dir, opts(1, 60_000));
let mut conn = connect(&dir);
conn.call("subscribe", json!({"topics": ["inbox", "instances"]})).unwrap();
let (_newer, h) = hello_at(&dir, &v(2));
assert!(matches!(h, Hello::Handoff));
let closing = loop {
let n = conn.next_notification(Duration::from_secs(3)).unwrap().expect("no closing hint");
if n.method == "closing" {
break n;
}
};
assert_eq!(closing.params["reason"], "handoff");
assert_eq!(daemon.join().unwrap().unwrap(), Exit::Handoff);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn shutdown_answers_drains_and_exits() {
let dir = scratch("shutdown");
let daemon = spawn_daemon(&dir, Options { keep_alive: true, ..opts(1, 50) });
let mut sub = connect(&dir);
sub.call("subscribe", json!({"topics": ["instances"]})).unwrap();
let (mut idle_client, _) = hello_at(&dir, &v(1));
let started = Instant::now();
let mut conn = connect(&dir);
let r = conn.call("shutdown", json!({})).unwrap();
assert_eq!(r.result, Some(json!({"ok": true})), "{r:?}");
assert!(endpoint::connect(&dir).is_err());
let closing = wait_for(&mut sub, "closing");
assert_eq!(closing.params, json!({"reason": "shutdown"}));
assert_eq!(daemon.join().unwrap().unwrap(), Exit::Shutdown);
assert!(started.elapsed() < DRAIN_TIMEOUT);
let mut buf = [0u8; 1];
assert_eq!(idle_client.read(&mut buf).unwrap(), 0);
assert!(!endpoint::socket_path(&dir).exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn npm_typings_match_every_notification() {
use crate::serve::dts;
let mut p = Pending {
inbox: Some(1),
shown: Some(("disp".into(), "disp: hi".into())),
instances: true,
forwards: true,
forwards_status: Some("forwarding".into()),
closing: Some("idle"),
..Pending::default()
};
let notes = p.take();
assert_eq!(notes.len(), 6, "a Pending flag isn't covered here");
for n in notes {
let ty = dts::prop_type("ApiEvents", &n.method)
.unwrap_or_else(|| panic!("index.d.ts `ApiEvents` lacks `'{}'`", n.method));
if ty == "{}" {
assert_eq!(n.params, json!({}), "{}", n.method);
} else {
dts::assert_matches(&ty, &n.params);
}
}
}
#[test]
fn a_connected_client_holds_and_keep_alive_never_idles() {
let dir = scratch("hold");
let daemon = spawn_daemon(&dir, opts(1, 150));
let (conn, _) = hello_at(&dir, &v(1));
std::thread::sleep(Duration::from_millis(500));
assert!(!daemon.is_finished(), "exited while a client was connected");
drop(conn);
assert_eq!(daemon.join().unwrap().unwrap(), Exit::Idle);
let keep = Options { keep_alive: true, ..opts(1, 50) };
let daemon = spawn_daemon(&dir, keep);
let _ = hello_at(&dir, &v(1));
std::thread::sleep(Duration::from_millis(400));
assert!(!daemon.is_finished(), "keep-alive daemon idled out");
let (_c, h) = hello_at(&dir, &v(2));
assert!(matches!(h, Hello::Handoff));
assert_eq!(daemon.join().unwrap().unwrap(), Exit::Handoff);
let _ = std::fs::remove_dir_all(&dir);
}
}