use std::collections::VecDeque;
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::time::Duration;
pub const PROTOCOL: u32 = 2;
const RING: usize = 30_000;
const ROWS: usize = 64;
const REPLAY_TIMEOUT: Duration = Duration::from_secs(5);
pub fn socket_path(dir: &Path) -> PathBuf {
dir.join("sock")
}
#[derive(Clone, Debug, PartialEq)]
pub struct CounterId {
pub path: String,
pub baud: u32,
pub version: String,
pub serial_no: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Identity {
pub counters: Vec<CounterId>,
pub spans: Vec<f64>,
}
impl Identity {
pub fn primary(&self) -> Option<&CounterId> {
self.counters.first()
}
pub fn len(&self) -> usize {
self.counters.len()
}
pub fn is_empty(&self) -> bool {
self.counters.is_empty()
}
pub fn serves(&self, device: &str) -> bool {
self.counters.iter().any(|c| c.path == device)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
Sample { who: usize, when: f64, counts: u32 },
Row { who: usize, row: String },
Random { who: usize, hex: String, at: String, suspect: bool },
Counter { who: usize, id: CounterId },
Gone { who: usize },
Live,
}
fn tab(fields: &[&str]) -> String {
let mut s = fields.join("\t");
s.push('\n');
s
}
fn t(v: f64) -> String {
format!("{:.3}", v)
}
fn greeting_for(id: &Identity) -> String {
let spans = id.spans.iter().map(|s| crate::log::g(*s)).collect::<Vec<_>>().join(",");
let mut out = tab(&[
"hello",
&PROTOCOL.to_string(),
&spans,
&id.counters.len().to_string(),
]);
for (i, c) in id.counters.iter().enumerate() {
out.push_str(&tab(&[
"c",
&i.to_string(),
&c.path,
&c.baud.to_string(),
&c.version,
&c.serial_no,
]));
}
out
}
pub struct Server {
listener: UnixListener,
path: PathBuf,
clients: Vec<UnixStream>,
ring: VecDeque<(usize, f64, u32)>,
rows: VecDeque<(usize, String)>,
id: Identity,
greeting: String,
}
impl Server {
pub fn start(dir: &Path, id: &Identity) -> std::io::Result<Server> {
let path = socket_path(dir);
if path.exists() && UnixStream::connect(&path).is_err() {
let _ = std::fs::remove_file(&path);
}
let listener = UnixListener::bind(&path)?;
listener.set_nonblocking(true)?;
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o660));
let greeting = greeting_for(id);
Ok(Server {
listener,
path,
clients: Vec::new(),
ring: VecDeque::with_capacity(RING),
rows: VecDeque::with_capacity(ROWS),
id: id.clone(),
greeting,
})
}
pub fn socket(&self) -> &Path {
&self.path
}
pub fn seed_rows<I: Iterator<Item = (usize, String)>>(&mut self, rows: I) {
for r in rows {
if self.rows.len() == ROWS {
self.rows.pop_front();
}
self.rows.push_back(r);
}
}
pub fn clients(&self) -> usize {
self.clients.len()
}
pub fn accept_pending(&mut self) {
loop {
match self.listener.accept() {
Ok((stream, _)) => {
if let Some(c) = self.greet(stream) {
self.clients.push(c);
}
}
Err(_) => return,
}
}
}
fn greet(&self, stream: UnixStream) -> Option<UnixStream> {
stream.set_nonblocking(false).ok()?;
stream.set_write_timeout(Some(REPLAY_TIMEOUT)).ok()?;
let mut w = &stream;
let mut out = String::with_capacity(self.ring.len() * 24 + 4096);
out.push_str(&self.greeting);
for (who, when, counts) in &self.ring {
out.push_str(&tab(&["s", &who.to_string(), &t(*when), &counts.to_string()]));
}
for (who, r) in &self.rows {
out.push_str(&tab(&["row", &who.to_string(), r]));
}
out.push_str("live\n");
w.write_all(out.as_bytes()).ok()?;
w.flush().ok()?;
stream.set_nonblocking(true).ok()?;
Some(stream)
}
pub fn announce(&mut self, who: usize, id: &CounterId) {
if who < self.id.counters.len() {
self.id.counters[who] = id.clone();
} else {
self.id.counters.resize(who + 1, id.clone());
}
self.greeting = greeting_for(&self.id);
self.publish(&tab(&[
"c",
&who.to_string(),
&id.path,
&id.baud.to_string(),
&id.version,
&id.serial_no,
]));
}
pub fn publish_gone(&mut self, who: usize) {
self.publish(&tab(&["gone", &who.to_string()]));
}
pub fn publish_sample(&mut self, who: usize, when: f64, counts: u32) {
if self.ring.len() == RING {
self.ring.pop_front();
}
self.ring.push_back((who, when, counts));
self.publish(&tab(&["s", &who.to_string(), &t(when), &counts.to_string()]));
}
pub fn publish_row(&mut self, who: usize, row: &str) {
if self.rows.len() == ROWS {
self.rows.pop_front();
}
self.rows.push_back((who, row.to_string()));
self.publish(&tab(&["row", &who.to_string(), row]));
}
pub fn publish_random(&mut self, who: usize, hex: &str, at: &str, suspect: bool) {
self.publish(&tab(&["r", &who.to_string(), hex, at, if suspect { "1" } else { "0" }]));
}
fn publish(&mut self, line: &str) {
let bytes = line.as_bytes();
self.clients.retain_mut(|c| match c.write_all(bytes) {
Ok(()) => true,
Err(_) => false,
});
}
}
impl Drop for Server {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Poll {
Event(Event),
Idle,
Closed,
}
fn would_block(e: &std::io::Error) -> bool {
matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
)
}
pub struct Client {
reader: BufReader<UnixStream>,
pub identity: Identity,
partial: Vec<u8>,
}
impl Client {
pub fn attach(dir: &Path) -> Option<Client> {
Client::connect(&socket_path(dir))
}
pub fn connect(path: &Path) -> Option<Client> {
let stream = UnixStream::connect(path).ok()?;
stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?;
let mut reader = BufReader::new(stream);
let mut line = String::new();
reader.read_line(&mut line).ok()?;
let f: Vec<&str> = line.trim_end().split('\t').collect();
if f.len() < 4 || f[0] != "hello" || f[1].parse::<u32>().ok()? != PROTOCOL {
return None;
}
let spans: Vec<f64> = f[2].split(',').filter_map(|s| s.parse().ok()).collect();
let n: usize = f[3].parse().ok()?;
let mut counters = Vec::with_capacity(n);
for _ in 0..n {
let mut l = String::new();
reader.read_line(&mut l).ok()?;
let g: Vec<&str> = l.trim_end().split('\t').collect();
if g.len() < 6 || g[0] != "c" {
return None;
}
counters.push(CounterId {
path: g[2].to_string(),
baud: g[3].parse().ok()?,
version: g[4].to_string(),
serial_no: g[5].to_string(),
});
}
let identity = Identity { counters, spans };
Some(Client { reader, identity, partial: Vec::new() })
}
pub fn next(&mut self, timeout: Duration) -> Option<Event> {
let _ = self.reader.get_ref().set_read_timeout(Some(timeout));
loop {
let mut line = String::new();
match self.reader.read_line(&mut line) {
Ok(0) | Err(_) => return None,
Ok(_) => {}
}
if let Some(e) = parse(line.trim_end()) {
self.absorb(&e);
return Some(e);
}
}
}
pub fn poll(&mut self, timeout: Duration) -> Poll {
let _ = self.reader.get_ref().set_read_timeout(Some(timeout));
loop {
let mut chunk = Vec::new();
let read = self.reader.read_until(b'\n', &mut chunk);
self.partial.extend_from_slice(&chunk);
match read {
Ok(_) if self.partial.last() == Some(&b'\n') => {}
Ok(_) => return Poll::Closed,
Err(e) if would_block(&e) => return Poll::Idle,
Err(_) => return Poll::Closed,
}
let line = String::from_utf8_lossy(&self.partial).trim_end().to_string();
self.partial.clear();
if let Some(e) = parse(&line) {
self.absorb(&e);
return Poll::Event(e);
}
}
}
fn absorb(&mut self, e: &Event) {
if let Event::Counter { who, id } = e {
if *who < self.identity.counters.len() {
self.identity.counters[*who] = id.clone();
} else {
self.identity.counters.resize(*who + 1, id.clone());
}
}
}
pub fn identity(&self) -> &Identity {
&self.identity
}
}
fn parse(line: &str) -> Option<Event> {
let f: Vec<&str> = line.split('\t').collect();
match *f.first()? {
"s" if f.len() >= 4 => Some(Event::Sample {
who: f[1].parse().ok()?,
when: f[2].parse().ok()?,
counts: f[3].parse().ok()?,
}),
"row" if f.len() >= 3 => Some(Event::Row {
who: f[1].parse().ok()?,
row: f[2..].join("\t"),
}),
"r" if f.len() >= 5 => Some(Event::Random {
who: f[1].parse().ok()?,
hex: f[2].to_string(),
at: f[3].to_string(),
suspect: f[4] == "1",
}),
"c" if f.len() >= 6 => Some(Event::Counter {
who: f[1].parse().ok()?,
id: CounterId {
path: f[2].to_string(),
baud: f[3].parse().ok()?,
version: f[4].to_string(),
serial_no: f[5].to_string(),
},
}),
"gone" if f.len() >= 2 => Some(Event::Gone { who: f[1].parse().ok()? }),
"live" => Some(Event::Live),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn id() -> Identity {
Identity {
counters: vec![CounterId {
path: "/dev/ttyUSB0".into(),
baud: 115200,
version: "GMC-320Re 4.26".into(),
serial_no: "F48824B8207F7E".into(),
}],
spans: vec![3.0, 30.0, 300.0, 3000.0, 30000.0],
}
}
fn pair() -> Identity {
let mut id = id();
id.counters.push(CounterId {
path: "/dev/ttyUSB1".into(),
baud: 115200,
version: "GMC-320Re 4.26".into(),
serial_no: "AA1122BB3344CC".into(),
});
id
}
fn tmp(name: &str) -> PathBuf {
let d = std::env::temp_dir()
.join(format!("radbeeper-test-{}-{}", name, std::process::id()));
let _ = std::fs::create_dir_all(&d);
let _ = std::fs::remove_file(socket_path(&d));
d
}
fn attached(dir: &Path, s: &mut Server) -> Client {
let d = dir.to_path_buf();
let want = s.clients() + 1;
let joining = std::thread::spawn(move || Client::attach(&d));
for _ in 0..500 {
s.accept_pending();
if s.clients() >= want {
break;
}
std::thread::sleep(Duration::from_millis(10));
}
joining.join().unwrap().expect("attached to the server")
}
#[test]
fn polling_tells_a_silence_apart_from_a_closed_socket() {
let dir = tmp("poll-idle");
let mut s = Server::start(&dir, &id()).expect("served");
let mut c = attached(&dir, &mut s);
let mut idle = 0;
for _ in 0..50 {
if c.poll(Duration::from_millis(20)) == Poll::Idle {
idle += 1;
}
}
assert!(idle >= 40, "only {} of 50 wake-ups were quiet", idle);
s.publish_sample(0, 1_700_000_000.5, 12);
let mut got = None;
for _ in 0..50 {
match c.poll(Duration::from_millis(20)) {
Poll::Event(Event::Sample { who, when, counts }) => {
got = Some((who, when, counts));
break;
}
Poll::Idle => continue,
other => panic!("{:?}", other),
}
}
assert_eq!(got, Some((0, 1_700_000_000.5, 12)));
drop(s);
let mut closed = false;
for _ in 0..50 {
if c.poll(Duration::from_millis(20)) == Poll::Closed {
closed = true;
break;
}
}
assert!(closed, "a dropped server ends the feed");
}
#[test]
fn a_timeout_landing_mid_line_keeps_the_line() {
let dir = tmp("poll-partial");
let mut s = Server::start(&dir, &id()).expect("served");
let mut c = attached(&dir, &mut s);
let mut seen: Vec<u32> = Vec::new();
for i in 0..40u32 {
s.publish_sample(0, 1_700_000_000.0 + i as f64, i);
for _ in 0..3 {
if let Poll::Event(Event::Sample { counts, .. }) =
c.poll(Duration::from_millis(1))
{
seen.push(counts);
}
}
}
for _ in 0..200 {
match c.poll(Duration::from_millis(5)) {
Poll::Event(Event::Sample { counts, .. }) => seen.push(counts),
_ => break,
}
}
assert_eq!(seen, (0..40u32).collect::<Vec<u32>>(),
"every sample, once, in order");
}
#[test]
fn a_client_learns_what_the_counter_is_before_any_sample_arrives() {
let dir = tmp("identity");
let mut s = Server::start(&dir, &id()).unwrap();
let c = attached(&dir, &mut s);
assert_eq!(c.identity(), &id());
assert_eq!(c.identity.primary().unwrap().version, "GMC-320Re 4.26");
}
#[test]
fn attaching_late_replays_the_history_before_the_live_line() {
let dir = tmp("replay");
let mut s = Server::start(&dir, &id()).unwrap();
for i in 0..100 {
s.publish_sample(0, 1_000_000.0 + i as f64, i % 7);
}
let mut c = attached(&dir, &mut s);
let mut got = Vec::new();
loop {
match c.next(Duration::from_secs(2)) {
Some(Event::Sample { when, counts, .. }) => got.push((when, counts)),
Some(Event::Live) => break,
Some(_) => {}
None => panic!("the feed ended before the history did"),
}
}
assert_eq!(got.len(), 100, "every sample the server held");
assert_eq!(got[0], (1_000_000.0, 0));
assert_eq!(got[99], (1_000_099.0, 99 % 7));
}
#[test]
fn the_history_stops_at_the_longest_window_it_has_to_fill() {
let dir = tmp("ring");
let mut s = Server::start(&dir, &id()).unwrap();
for i in 0..(RING + 500) {
s.publish_sample(0, i as f64, 1);
}
assert_eq!(s.ring.len(), RING);
assert_eq!(s.ring.front().unwrap().1, 500.0, "the oldest 500 fell off");
}
#[test]
fn what_the_server_publishes_is_what_the_client_receives() {
let dir = tmp("live");
let mut s = Server::start(&dir, &id()).unwrap();
let mut c = attached(&dir, &mut s);
assert_eq!(c.next(Duration::from_secs(2)), Some(Event::Live));
s.publish_sample(0, 1_700_000_000.5, 12);
s.publish_row(0, "2026-09-18 11:00:00\t0.4\t12\t30.0");
s.publish_random(0, "abcd", "11:00:30", true);
assert_eq!(
c.next(Duration::from_secs(2)),
Some(Event::Sample { who: 0, when: 1_700_000_000.5, counts: 12 })
);
assert_eq!(
c.next(Duration::from_secs(2)),
Some(Event::Row { who: 0, row: "2026-09-18 11:00:00\t0.4\t12\t30.0".into() })
);
assert_eq!(
c.next(Duration::from_secs(2)),
Some(Event::Random {
who: 0, hex: "abcd".into(), at: "11:00:30".into(), suspect: true
})
);
}
#[test]
fn a_client_that_went_away_is_dropped_and_the_rest_carry_on() {
let dir = tmp("gone");
let mut s = Server::start(&dir, &id()).unwrap();
let going = attached(&dir, &mut s);
let mut staying = attached(&dir, &mut s);
assert_eq!(s.clients(), 2);
drop(going);
for i in 0..2 {
s.publish_sample(0, i as f64, 3);
}
assert_eq!(s.clients(), 1, "the closed one was dropped");
assert_eq!(staying.next(Duration::from_secs(2)), Some(Event::Live));
assert_eq!(
staying.next(Duration::from_secs(2)),
Some(Event::Sample { who: 0, when: 0.0, counts: 3 })
);
}
#[test]
fn a_stale_socket_from_a_killed_server_is_replaced_not_obeyed() {
let dir = tmp("stale");
let path = socket_path(&dir);
drop(UnixListener::bind(&path).unwrap());
assert!(path.exists(), "the node outlived the server, as after a kill");
assert!(UnixStream::connect(&path).is_err(), "and nothing is behind it");
let s = Server::start(&dir, &id()).expect("bound over the stale node");
assert!(s.socket().exists());
}
#[test]
fn a_second_server_does_not_take_a_socket_that_is_answering() {
let dir = tmp("taken");
let first = Server::start(&dir, &id()).unwrap();
assert!(Server::start(&dir, &id()).is_err(), "the live one keeps it");
assert!(first.socket().exists());
}
#[test]
fn a_pair_of_counters_arrives_as_a_pair_and_stays_told_apart() {
let dir = tmp("pair");
let mut s = Server::start(&dir, &pair()).unwrap();
let mut c = attached(&dir, &mut s);
assert_eq!(c.identity(), &pair());
assert_eq!(c.identity().len(), 2);
assert_eq!(c.identity().counters[1].serial_no, "AA1122BB3344CC");
assert!(c.identity().serves("/dev/ttyUSB1"));
assert_eq!(c.next(Duration::from_secs(2)), Some(Event::Live));
s.publish_sample(1, 10.0, 7);
s.publish_sample(0, 10.5, 3);
assert_eq!(
c.next(Duration::from_secs(2)),
Some(Event::Sample { who: 1, when: 10.0, counts: 7 })
);
assert_eq!(
c.next(Duration::from_secs(2)),
Some(Event::Sample { who: 0, when: 10.5, counts: 3 })
);
}
#[test]
fn attaching_to_nothing_is_a_plain_no() {
let dir = tmp("empty");
assert!(Client::attach(&dir).is_none());
}
}