weirdnet-songnotes 0.9.0

SongNotes collaboration: the roles, permissions, links and consent requests for a SongNotes session, built on weirdnet-collab.
Documentation
//! SongNotes apps on one machine (C5): a registry the apps find each other through, and the
//! local control channel `/songnotes/local` a stage app uses to get the fresh view and certificate from
//! the collab app, to open it at a panel and to push its status.
//!
//! The registry is a folder of one JSON file per running app instance, under the user's
//! runtime folder (`$SONGNOTES_REGISTRY`, else `$DRUMMACHINE_REGISTRY`, else
//! `$XDG_RUNTIME_DIR/songnotes/instances`), made owner-only. Only the user's own processes can
//! write there, so the control channel trusts exactly the peers listed in it. The user's
//! identity key stays in the collab app: a stage app runs under its own instance key, and the
//! collab app speaks to hosts for it. The drum machine's instance entries (P6e) live in the same
//! folder and read as entries here (fields this module does not know are ignored).
use serde::{Deserialize, Serialize};
use std::fs;
use std::future::Future;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use weirdnet_service::{Access, Admitted, Authorize, Caller, ProtocolId, Service, ServiceError};

/// The protocol id.
pub const PROTOCOL: &str = "/songnotes/local";
/// The protocol version.
pub const VERSION: u32 = 1;
/// The collab app's name in the registry.
pub const COLLAB_APP: &str = "collab";

/// The protocol id as a [`ProtocolId`].
pub fn protocol() -> ProtocolId {
    ProtocolId::new(PROTOCOL, VERSION).expect("a valid protocol id")
}

/// One running app instance.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
    /// Its instance id (unique on the machine).
    pub instance: String,
    /// The app (`collab`, `drummachine`, `monitor`, `controller`); empty for older entries.
    #[serde(default)]
    pub app: String,
    /// Its process.
    pub pid: u32,
    /// Its node's peer id.
    pub peer: String,
    /// Its node's listen addresses.
    #[serde(default)]
    pub addrs: Vec<String>,
    /// When it started, ms since the epoch.
    #[serde(default)]
    pub since_ms: u64,
}

/// Whether process `pid` is running (Linux and Android look in `/proc`; elsewhere assumed).
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 }
}

/// The registry folder.
#[derive(Clone, Debug)]
pub struct Registry {
    dir: PathBuf,
}

/// An entry that is removed when dropped.
#[derive(Debug)]
pub struct Registered {
    path: PathBuf,
}

impl Drop for Registered {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

impl Registry {
    /// The default folder (see the module docs).
    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")
    }

    /// The registry in `dir`, created owner-only.
    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() })
    }

    /// The folder.
    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// Writes `entry` atomically; the guard removes it.
    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 })
    }

    /// The entries of running processes (an entry whose process ended is skipped).
    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
    }

    /// The running instances of `app`.
    pub fn of_app(&self, app: &str) -> Vec<Entry> {
        self.list().into_iter().filter(|e| e.app == app).collect()
    }

    /// Whether `peer` is one of the user's running app instances.
    pub fn trusts(&self, peer: &str) -> bool {
        self.list().iter().any(|e| e.peer == peer)
    }
}

/// A request on the local control channel.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Req {
    /// Open this `weirdnet-songnotes://` link (a panel, or a join link) and come to the front.
    Open {
        /// The link's text.
        link: String,
    },
    /// "I am here": the fresh view of `project` for this machine's user, with the host's
    /// certificate. The collab app asks the host (or answers itself if it hosts) and reports the
    /// app's presence to the host. A stage app calls this every `RE_AUTH_MS`.
    View {
        /// The project.
        project: String,
        /// The asking app (its presence is reported as this name).
        app: String,
        /// Active or idle.
        activity: crate::Activity,
    },
    /// "This is what I show": a stage app's one-line status for a project.
    Status {
        /// The app.
        app: String,
        /// The project.
        project: String,
        /// The line.
        line: String,
    },
    /// "Is someone talking?" in `project`: whether talkback is audible on this machine now, for
    /// ducking the music. A stage app may poll it every few hundred ms.
    Talking {
        /// The project.
        project: String,
    },
}

/// An answer.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Resp {
    /// Done.
    Done,
    /// Not done, and why.
    Refused(String),
    /// The answer to [`Req::View`].
    View(Box<LocalView>),
    /// The answer to [`Req::Talking`].
    Talking(bool),
}

/// The answer to [`Req::View`]: who this machine's user is, the host's fresh view and a
/// certificate for offline use.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LocalView {
    /// This machine's user.
    pub me: crate::UserId,
    /// The host's view, just fetched.
    pub view: crate::ProjectView,
    /// The host's certificate for `me`.
    pub cert: Option<crate::stage::Cert>,
}

/// Serves the control channel: requests from peers in `registry` go to `handle`.
pub struct ControlService<F> {
    registry: Registry,
    handle: F,
}

impl<F, Fut> ControlService<F>
where
    F: Fn(String, Req) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Resp> + Send,
{
    /// The service; `handle` gets the caller's peer id and the request.
    pub fn new(registry: Registry, handle: F) -> Arc<Self> {
        Arc::new(ControlService { registry, handle })
    }
}

impl<F, Fut> Service for ControlService<F>
where
    F: Fn(String, Req) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Resp> + Send,
{
    type Request = Req;
    type Response = Resp;

    fn access(&self, r: &Req) -> Access {
        Access::new(match r {
            Req::Open { .. } => "local.open",
            Req::View { .. } => "local.view",
            Req::Status { .. } => "local.status",
            Req::Talking { .. } => "local.talking",
        })
    }

    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).await)
    }
}

/// Admits any peer (the service checks the registry).
pub fn authorizer() -> impl Authorize {
    move |caller: &Caller, _: &Access| Ok(Admitted::new(caller.peer.clone()).with_user(caller.peer.clone()))
}

/// Asks the collab app at `entry` to open `link`.
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
}

/// Asks the collab app at `entry` for the fresh view of `project` (and reports `app` there).
pub async fn view_from(
    client: &weirdnet_service::Client,
    entry: &Entry,
    project: &str,
    app: &str,
    activity: crate::Activity,
) -> Result<LocalView, ServiceError> {
    let s = client.session::<Req, Resp>(&entry.peer, &protocol()).await?;
    match s.call(&Req::View { project: project.into(), app: app.into(), activity }).await? {
        Resp::View(v) => Ok(*v),
        Resp::Refused(why) => Err(ServiceError::Refused { reason: why }),
        Resp::Done | Resp::Talking(_) => Err(ServiceError::Refused { reason: "unexpected".into() }),
    }
}

/// Asks the collab app at `entry` whether talkback is audible now in `project` (for ducking).
pub async fn talking(client: &weirdnet_service::Client, entry: &Entry, project: &str) -> Result<bool, ServiceError> {
    let s = client.session::<Req, Resp>(&entry.peer, &protocol()).await?;
    match s.call(&Req::Talking { project: project.into() }).await? {
        Resp::Talking(on) => Ok(on),
        Resp::Refused(why) => Err(ServiceError::Refused { reason: why }),
        _ => Err(ServiceError::Refused { reason: "unexpected".into() }),
    }
}

/// Pushes a status line to the collab app at `entry`.
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();
        // a drum machine instance entry (P6e) has more fields and no app
        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();
        // ended processes are only detected where /proc exists (Linux, Android)
        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);
    }
}