#![forbid(unsafe_code)]
use std::io::{Read, Write};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::time::{Duration, Instant};
use cksk::{Show, BOARDS};
use serde::Deserialize;
const DEFAULT_GATUS_URL: &str = "https://status.example.com/api/v1/endpoints/statuses";
const MAGIC: &[u8; 8] = b"NIXLOCK1";
const MIN_FRAME_INTERVAL: Duration = Duration::from_millis(200);
const MAX_FRAME_INTERVAL: Duration = Duration::from_secs(1);
const INITIAL_BACKOFF: Duration = Duration::from_millis(250);
const MAX_BACKOFF: Duration = Duration::from_secs(5);
#[derive(Debug, Default, Deserialize)]
struct FileConfig {
gatus_url: Option<String>,
socket_path: Option<String>,
host_feed: Option<String>,
}
fn config_base() -> Option<std::path::PathBuf> {
std::env::var("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.or_else(|_| std::env::var("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
.ok()
}
fn config_path() -> Option<std::path::PathBuf> {
let base = config_base()?;
let fresh = base.join("cksk").join("config.json");
if fresh.exists() {
return Some(fresh);
}
let legacy = base.join("nixwatch-frames").join("config.json");
if legacy.exists() {
return Some(legacy);
}
Some(fresh)
}
fn load_file_config() -> FileConfig {
let Some(path) = config_path() else {
return FileConfig::default();
};
let Ok(bytes) = std::fs::read(&path) else {
return FileConfig::default();
};
match serde_json::from_slice(&bytes) {
Ok(cfg) => cfg,
Err(e) => {
eprintln!("cksk: {}: {e} (ignoring)", path.display());
FileConfig::default()
}
}
}
fn resolve_gatus_url(file: &FileConfig) -> String {
file.gatus_url
.clone()
.or_else(|| std::env::var("GATUS_URL").ok())
.unwrap_or_else(|| DEFAULT_GATUS_URL.to_string())
}
struct Resolved {
gatus_url: String,
socket_path: PathBuf,
host_feed: Option<String>,
}
fn resolve_config() -> Resolved {
let file = load_file_config();
let gatus_url = resolve_gatus_url(&file);
let socket_path = file
.socket_path
.map(PathBuf::from)
.or_else(|| std::env::var_os("CLCK_SOCKET").map(PathBuf::from))
.or_else(|| std::env::var_os("NIXLOCK_SOCKET").map(PathBuf::from))
.or_else(|| {
std::env::var_os("XDG_RUNTIME_DIR").map(|d| {
let dir = PathBuf::from(d);
let fresh = dir.join("clck.sock");
if fresh.exists() {
fresh
} else {
dir.join("nixlock.sock")
}
})
})
.unwrap_or_else(|| {
eprintln!(
"cksk: no socket_path configured and $XDG_RUNTIME_DIR is unset -- \
cannot locate clck's kiosk socket"
);
std::process::exit(1);
});
Resolved {
gatus_url,
socket_path,
host_feed: file.host_feed,
}
}
fn arg(flag: &str) -> Option<String> {
let a: Vec<String> = std::env::args().collect();
a.iter()
.position(|x| x == flag)
.and_then(|i| a.get(i + 1).cloned())
}
fn main() {
if std::env::args().any(|arg| arg == "--version" || arg == "-V") {
println!("cksk {}", env!("CARGO_PKG_VERSION"));
return;
}
if let Some(out) = arg("--dump") {
let file = load_file_config();
let gatus_url = resolve_gatus_url(&file);
let source = arg("--source").unwrap_or(gatus_url);
let screen = arg("--screen").unwrap_or_else(|| "overview".to_string());
if !BOARDS.iter().any(|b| b.id == screen) {
let ids: Vec<&str> = BOARDS.iter().map(|b| b.id).collect();
eprintln!(
"cksk: unknown --screen {screen}; one of: {}",
ids.join(", ")
);
std::process::exit(2);
}
let feed = arg("--feed").or(file.host_feed);
let show = Show::with_feed(source, feed);
let (w, h) = (1920u32, 1080u32);
let pm = show
.render_screen(&screen, w, h)
.expect("Show::render_screen returns Some for a nonzero size");
pm.save_png(&out).expect("save png");
eprintln!("cksk: dumped {screen} {w}x{h} -> {out}");
return;
}
let resolved = resolve_config();
eprintln!(
"cksk: gatus_url={} socket={}",
resolved.gatus_url,
resolved.socket_path.display()
);
let show = Show::with_feed(resolved.gatus_url, resolved.host_feed);
run_client(&resolved.socket_path, &show);
}
fn run_client(socket_path: &std::path::Path, show: &Show) {
run_client_with(socket_path, show, std::thread::sleep, |_, _| false);
}
fn run_client_with<S, F>(
socket_path: &std::path::Path,
show: &Show,
mut sleep: S,
mut stop_after: F,
) where
S: FnMut(Duration),
F: FnMut(usize, RetryReason) -> bool,
{
let mut backoff = INITIAL_BACKOFF;
let mut attempts = 0usize;
loop {
let reason = match connect_and_stream(socket_path, show) {
Ok(Exit::GeometryPending) => {
eprintln!("cksk: clck kiosk geometry is not configured yet (0x0); reconnecting");
RetryReason::GeometryPending
}
Ok(Exit::Disconnected) => {
eprintln!("cksk: disconnected from clck; reconnecting");
backoff = INITIAL_BACKOFF; RetryReason::Disconnected
}
Err(e) => {
eprintln!("cksk: connect to {} failed: {e}", socket_path.display());
RetryReason::ConnectFailed
}
};
attempts += 1;
if stop_after(attempts, reason) {
return;
}
sleep(backoff);
backoff = (backoff * 2).min(MAX_BACKOFF);
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum RetryReason {
GeometryPending,
Disconnected,
ConnectFailed,
}
enum Exit {
GeometryPending,
Disconnected,
}
fn connect_and_stream(socket_path: &std::path::Path, show: &Show) -> std::io::Result<Exit> {
let mut stream = UnixStream::connect(socket_path)?;
let mut hello = [0u8; 20]; stream.read_exact(&mut hello)?;
if &hello[0..8] != MAGIC {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"HELLO magic mismatch -- not clck's kiosk socket",
));
}
let width = u32::from_le_bytes(hello[8..12].try_into().unwrap());
let height = u32::from_le_bytes(hello[12..16].try_into().unwrap());
let scale = u32::from_le_bytes(hello[16..20].try_into().unwrap());
eprintln!("cksk: connected; kiosk geometry {width}x{height} (scale {scale})");
if width == 0 || height == 0 {
return Ok(Exit::GeometryPending);
}
let mut last_version = None::<u64>;
let mut last_sent = Instant::now() - MAX_FRAME_INTERVAL; loop {
let version = show.version();
let due = last_sent.elapsed() >= MAX_FRAME_INTERVAL;
let refreshed = last_version != Some(version);
if due || refreshed {
let now_secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let Some(pm) = show.render_current(width, height, now_secs) else {
std::thread::sleep(MIN_FRAME_INTERVAL);
continue;
};
if let Err(e) = write_frame(&mut stream, width, height, pm.data()) {
eprintln!("cksk: write failed: {e}");
return Ok(Exit::Disconnected);
}
last_version = Some(version);
last_sent = Instant::now();
}
std::thread::sleep(MIN_FRAME_INTERVAL);
}
}
fn write_frame(
stream: &mut UnixStream,
width: u32,
height: u32,
rgba: &[u8],
) -> std::io::Result<()> {
stream.write_all(&width.to_le_bytes())?;
stream.write_all(&height.to_le_bytes())?;
stream.write_all(rgba)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::net::Shutdown;
use std::os::unix::net::UnixListener;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
fn write_hello(stream: &mut UnixStream, width: u32, height: u32, scale: u32) {
stream.write_all(MAGIC).unwrap();
stream.write_all(&width.to_le_bytes()).unwrap();
stream.write_all(&height.to_le_bytes()).unwrap();
stream.write_all(&scale.to_le_bytes()).unwrap();
}
#[test]
fn zero_geometry_reconnects_then_streams_after_surface_configuration() {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let test_dir =
std::env::temp_dir().join(format!("cksk-startup-race-{}-{nonce}", std::process::id()));
fs::create_dir_all(&test_dir).unwrap();
let socket_path = test_dir.join("clck.sock");
let source_path = test_dir.join("gatus.json");
fs::write(&source_path, b"[]").unwrap();
let listener = UnixListener::bind(&socket_path).unwrap();
let received_frame = Arc::new(AtomicBool::new(false));
let server_received_frame = Arc::clone(&received_frame);
let server = thread::spawn(move || {
let (mut before_configure, _) = listener.accept().unwrap();
write_hello(&mut before_configure, 0, 0, 0);
drop(before_configure);
let (mut after_configure, _) = listener.accept().unwrap();
let (width, height) = (64u32, 32u32);
write_hello(&mut after_configure, width, height, 1);
let mut header = [0u8; 8];
after_configure.read_exact(&mut header).unwrap();
assert_eq!(u32::from_le_bytes(header[0..4].try_into().unwrap()), width);
assert_eq!(u32::from_le_bytes(header[4..8].try_into().unwrap()), height);
let mut rgba = vec![0u8; width as usize * height as usize * 4];
after_configure.read_exact(&mut rgba).unwrap();
assert!(
rgba.iter().any(|byte| *byte != 0),
"renderer sent an empty frame"
);
server_received_frame.store(true, Ordering::SeqCst);
after_configure.shutdown(Shutdown::Both).unwrap();
});
let show = Show::new(source_path.to_string_lossy().into_owned());
let mut retries = Vec::new();
let mut sleeps = Vec::new();
run_client_with(
&socket_path,
&show,
|duration| sleeps.push(duration),
|attempt, reason| {
retries.push(reason);
attempt >= 2
},
);
server.join().unwrap();
assert!(received_frame.load(Ordering::SeqCst));
assert_eq!(
retries,
vec![RetryReason::GeometryPending, RetryReason::Disconnected]
);
assert_eq!(sleeps, vec![INITIAL_BACKOFF]);
fs::remove_dir_all(test_dir).unwrap();
}
}