use std::fmt::Write as _;
use std::io::{BufRead as _, BufReader, Read as _, Write as _};
use std::net::{Ipv4Addr, SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
pub(crate) mod cli;
pub(crate) mod install;
pub(crate) mod link;
pub(crate) mod target;
pub(crate) const VERSION: u64 = 1;
const MAX_LINE: u64 = 1 << 20;
const PING_TIMEOUT: Duration = Duration::from_millis(800);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
const SEND_TIMEOUT: Duration = Duration::from_secs(5);
pub(crate) fn root() -> PathBuf {
root_from(std::env::var(SESSIONS_DIR_VAR).ok(), crate::workspace_paths::data_dir)
}
pub(crate) const SESSIONS_DIR_VAR: &str = "PLANNOTATOR_TUI_SESSIONS_DIR";
pub(crate) fn root_from(env: Option<String>, data_dir: impl FnOnce() -> PathBuf) -> PathBuf {
match env.map(|dir| dir.trim().to_owned()).filter(|dir| !dir.is_empty()) {
Some(dir) => PathBuf::from(dir),
None => data_dir().join("clients").join("plannotator-tui").join("sessions"),
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub(crate) struct PiEntry {
pub(crate) v: u64,
pub(crate) host: String,
pub(crate) id: String,
pub(crate) pid: u32,
pub(crate) cwd: PathBuf,
#[serde(default)]
pub(crate) name: Option<String>,
#[serde(default)]
pub(crate) transcript: Option<PathBuf>,
pub(crate) port: u16,
pub(crate) token: String,
#[serde(default)]
pub(crate) busy: bool,
#[serde(default)]
pub(crate) updated: u64,
#[serde(skip)]
pub(crate) path: PathBuf,
}
impl PiEntry {
pub(crate) fn label(&self) -> String {
match self.name.as_deref().map(str::trim).filter(|name| !name.is_empty()) {
Some(name) => name.to_owned(),
None => self.id.chars().take(8).collect(),
}
}
fn read(path: &Path) -> Option<Self> {
let text = std::fs::read_to_string(path).ok()?;
let mut entry: Self = serde_json::from_str(&text).ok()?;
(entry.v == VERSION && entry.host == "pi").then(|| {
entry.path = path.to_path_buf();
entry
})
}
}
pub(crate) fn pi_entries(root: &Path) -> Vec<PiEntry> {
let Ok(dir) = std::fs::read_dir(root.join("pi")) else { return Vec::new() };
let mut entries: Vec<PiEntry> = dir
.filter_map(Result::ok)
.map(|item| item.path())
.filter(|path| path.extension().is_some_and(|ext| ext == "json"))
.filter_map(|path| PiEntry::read(&path))
.collect();
entries.sort_by_key(|entry| entry.updated);
entries
}
pub(crate) fn live_entry_for_pid(root: &Path, pid: u32) -> Option<PiEntry> {
pi_entries(root).into_iter().rev().filter(|entry| entry.pid == pid).find_map(alive)
}
pub(crate) fn live_entry_for_transcript(root: &Path, transcript: &Path, pid: Option<u32>) -> Option<PiEntry> {
let real = |path: &Path| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let wanted = real(transcript);
pi_entries(root)
.into_iter()
.rev()
.filter(|entry| pid.is_none_or(|pid| entry.pid == pid))
.filter(|entry| entry.transcript.as_deref().is_some_and(|path| real(path) == wanted))
.find_map(alive)
}
#[derive(Debug, Deserialize)]
pub(crate) struct TreePosition {
pub(crate) tip: String,
#[serde(default)]
pub(crate) leaf: Option<String>,
}
pub(crate) fn tree_position(entry: &PiEntry) -> Option<TreePosition> {
serde_json::from_str(&std::fs::read_to_string(&entry.path).ok()?).ok()
}
pub(crate) fn live_pi_sessions(root: &Path) -> Vec<PiEntry> {
pi_entries(root).into_iter().filter_map(alive).collect()
}
fn alive(mut entry: PiEntry) -> Option<PiEntry> {
match request(entry.port, &json!({"v": VERSION, "token": entry.token, "op": "ping"}), PING_TIMEOUT) {
Ok(reply) if field(&reply, "ok") == true => {
entry.busy = field(&reply, "busy").as_bool().unwrap_or(entry.busy);
if let Some(name) = field(&reply, "name").as_str() {
entry.name = Some(name.to_owned());
}
Some(entry)
}
Err(err) if err.kind() == std::io::ErrorKind::ConnectionRefused => {
let _ = std::fs::remove_file(&entry.path);
None
}
_ => None,
}
}
pub(crate) fn request(port: u16, body: &Value, timeout: Duration) -> std::io::Result<Value> {
let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
let mut stream = TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT.max(timeout))?;
stream.set_read_timeout(Some(timeout))?;
stream.set_write_timeout(Some(timeout))?;
let mut line = serde_json::to_vec(body)?;
line.push(b'\n');
stream.write_all(&line)?;
let mut reply = String::new();
BufReader::new((&stream).take(MAX_LINE)).read_line(&mut reply)?;
serde_json::from_str(&reply).map_err(std::io::Error::other)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Disposition {
Started,
Queued,
}
#[derive(Debug)]
pub(crate) enum SendError {
Gone,
Failed(String),
}
pub(crate) fn send(entry: &PiEntry, text: &str) -> Result<Disposition, SendError> {
match send_once(entry, text) {
Err(SendError::Failed(code)) if code.starts_with("bad_token") => {
let fresh = PiEntry::read(&entry.path).ok_or(SendError::Gone)?;
send_once(&fresh, text)
}
other => other,
}
}
fn send_once(entry: &PiEntry, text: &str) -> Result<Disposition, SendError> {
let body = json!({
"v": VERSION,
"token": entry.token,
"op": "send",
"text": text,
"deliver": "auto",
"source": "plannotator-tui",
});
let reply = match request(entry.port, &body, SEND_TIMEOUT) {
Ok(reply) => reply,
Err(err) if err.kind() == std::io::ErrorKind::ConnectionRefused => {
let _ = std::fs::remove_file(&entry.path);
return Err(SendError::Gone);
}
Err(err) => return Err(SendError::Failed(format!("no answer from Pi: {err}"))),
};
if field(&reply, "ok") == true {
return Ok(match field(&reply, "disposition").as_str() {
Some("queued") => Disposition::Queued,
_ => Disposition::Started,
});
}
let code = field(&reply, "code").as_str().unwrap_or("failed");
Err(SendError::Failed(match field(&reply, "message").as_str() {
Some(message) => format!("{code}: {message}"),
None => code.to_owned(),
}))
}
pub(crate) fn field<'a>(value: &'a Value, key: &str) -> &'a Value {
value.get(key).unwrap_or(&Value::Null)
}
pub(crate) fn token() -> std::io::Result<String> {
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).map_err(|err| std::io::Error::other(err.to_string()))?;
Ok(bytes.iter().fold(String::with_capacity(64), |mut hex, b| {
let _ = write!(hex, "{b:02x}");
hex
}))
}
pub(crate) fn write_entry(path: &Path, value: &Value) -> std::io::Result<()> {
let dir = path.parent().ok_or_else(|| std::io::Error::other("entry has no folder"))?;
create_private_dir(dir)?;
let tmp = dir.join(format!(".{}.tmp", path.file_name().and_then(|n| n.to_str()).unwrap_or("entry")));
{
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let mut file = options.open(&tmp)?;
file.write_all(&serde_json::to_vec_pretty(value)?)?;
}
std::fs::rename(&tmp, path)
}
fn create_private_dir(dir: &Path) -> std::io::Result<()> {
let root = dir.parent().unwrap_or(dir);
for dir in [root, dir] {
if dir.is_dir() {
continue;
}
std::fs::create_dir_all(dir)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
}
}
Ok(())
}
pub(crate) fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
}
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
pub(crate) fn write_test_entry(root: &Path, id: &str, pid: u32, running: bool) {
let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind");
let port = listener.local_addr().expect("addr").port();
if running {
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let mut line = String::new();
let _ = BufReader::new(&stream).read_line(&mut line);
let _ = (&stream).write_all(b"{\"ok\":true}\n");
}
});
}
let entry = json!({ "v": VERSION, "host": "pi", "id": id, "pid": pid, "cwd": "/w",
"port": port, "token": "t", "updated": now_ms() });
write_entry(&root.join("pi").join(format!("{id}-{pid}.json")), &entry).expect("entry");
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::indexing_slicing, clippy::panic, reason = "tests assert by panicking")]
mod tests;