use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use weirdnet_service::{Access, Admitted, Authorize, Caller, ProtocolId, Service, ServiceError};
pub const PROTOCOL: &str = "/songnotes/local";
pub const VERSION: u32 = 1;
pub const COLLAB_APP: &str = "collab";
pub fn protocol() -> ProtocolId {
ProtocolId::new(PROTOCOL, VERSION).expect("a valid protocol id")
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
pub instance: String,
#[serde(default)]
pub app: String,
pub pid: u32,
pub peer: String,
#[serde(default)]
pub addrs: Vec<String>,
#[serde(default)]
pub since_ms: u64,
}
pub fn process_alive(pid: u32) -> bool {
let proc = Path::new("/proc");
if proc.join("self").exists() { proc.join(pid.to_string()).exists() } else { true }
}
#[derive(Clone, Debug)]
pub struct Registry {
dir: PathBuf,
}
#[derive(Debug)]
pub struct Registered {
path: PathBuf,
}
impl Drop for Registered {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}
impl Registry {
pub fn default_dir() -> PathBuf {
for v in ["SONGNOTES_REGISTRY", "DRUMMACHINE_REGISTRY"] {
if let Some(d) = std::env::var_os(v) {
return PathBuf::from(d);
}
}
if let Some(d) = std::env::var_os("XDG_RUNTIME_DIR") {
return PathBuf::from(d).join("songnotes").join("instances");
}
let user = std::env::var("USER").unwrap_or_else(|_| "user".into());
std::env::temp_dir().join(format!("songnotes-{user}")).join("instances")
}
pub fn open(dir: &Path) -> io::Result<Registry> {
fs::create_dir_all(dir)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
}
Ok(Registry { dir: dir.to_path_buf() })
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn register(&self, entry: &Entry) -> io::Result<Registered> {
let name: String = entry.instance.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect();
let path = self.dir.join(format!("{name}.json"));
let tmp = self.dir.join(format!(".{name}.tmp"));
fs::write(&tmp, serde_json::to_vec_pretty(entry).map_err(io::Error::other)?)?;
fs::rename(&tmp, &path)?;
Ok(Registered { path })
}
pub fn list(&self) -> Vec<Entry> {
let mut out = Vec::new();
let Ok(rd) = fs::read_dir(&self.dir) else { return out };
for e in rd.flatten() {
let p = e.path();
if p.extension().is_none_or(|x| x != "json") {
continue;
}
if let Some(entry) = fs::read(&p).ok().and_then(|b| serde_json::from_slice::<Entry>(&b).ok())
&& process_alive(entry.pid)
{
out.push(entry);
}
}
out.sort_by(|a, b| a.since_ms.cmp(&b.since_ms).then(a.instance.cmp(&b.instance)));
out
}
pub fn of_app(&self, app: &str) -> Vec<Entry> {
self.list().into_iter().filter(|e| e.app == app).collect()
}
pub fn trusts(&self, peer: &str) -> bool {
self.list().iter().any(|e| e.peer == peer)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Req {
Open {
link: String,
},
Status {
app: String,
project: String,
line: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Resp {
Done,
Refused(String),
}
pub struct ControlService<F> {
registry: Registry,
handle: F,
}
impl<F: Fn(&str, Req) -> Resp + Send + Sync + 'static> ControlService<F> {
pub fn new(registry: Registry, handle: F) -> Arc<Self> {
Arc::new(ControlService { registry, handle })
}
}
impl<F: Fn(&str, Req) -> Resp + Send + Sync + 'static> Service for ControlService<F> {
type Request = Req;
type Response = Resp;
fn access(&self, r: &Req) -> Access {
Access::new(match r {
Req::Open { .. } => "local.open",
Req::Status { .. } => "local.status",
})
}
async fn call(&self, who: Admitted, r: Req) -> Result<Resp, ServiceError> {
let peer = who.user.unwrap_or_default();
if !self.registry.trusts(&peer) {
return Err(ServiceError::Refused { reason: "not-local".into() });
}
Ok((self.handle)(&peer, r))
}
}
pub fn authorizer() -> impl Authorize {
move |caller: &Caller, _: &Access| Ok(Admitted::new(caller.peer.clone()).with_user(caller.peer.clone()))
}
pub async fn open_in(client: &weirdnet_service::Client, entry: &Entry, link: &str) -> Result<Resp, ServiceError> {
let s = client.session::<Req, Resp>(&entry.peer, &protocol()).await?;
s.call(&Req::Open { link: link.into() }).await
}
pub async fn push_status(client: &weirdnet_service::Client, entry: &Entry, app: &str, project: &str, line: &str) -> Result<Resp, ServiceError> {
let s = client.session::<Req, Resp>(&entry.peer, &protocol()).await?;
s.call(&Req::Status { app: app.into(), project: project.into(), line: line.into() }).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_registry_lists_running_apps_and_reads_drum_machine_entries() {
let d = std::env::temp_dir().join(format!("sn-local-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
let r = Registry::open(&d).unwrap();
let e = Entry { instance: "collab-1".into(), app: COLLAB_APP.into(), pid: std::process::id(), peer: "p1".into(), addrs: vec![], since_ms: 1 };
let g = r.register(&e).unwrap();
fs::write(d.join("dm.json"), format!(r#"{{"instance":"dm-1","role":"Instance","pid":{},"peer":"p2","addrs":[],"project":null,"output":"Device","ports":[],"output_latency":0,"sample_rate":48000,"since_ms":2}}"#, std::process::id())).unwrap();
let gone = Entry { instance: "old".into(), pid: u32::MAX - 1, peer: "p3".into(), ..e.clone() };
let _g3 = r.register(&gone).unwrap();
let checks = Path::new("/proc/self").exists();
assert_eq!(r.list().len(), if checks { 2 } else { 3 });
assert!(r.of_app(COLLAB_APP).contains(&e));
assert!(r.trusts("p1") && r.trusts("p2") && (checks != r.trusts("p3")));
drop(_g3);
drop(g);
assert!(r.of_app(COLLAB_APP).is_empty());
let _ = fs::remove_dir_all(&d);
}
}