weirdnet-songnotes 0.3.0

SongNotes collaboration: the roles, permissions, links and consent requests for a SongNotes session, built on weirdnet-collab.
Documentation
//! The SongNotes collab protocol, `/songnotes/collab`: what any SongNotes app asks the host of a
//! project. The collab app serves it on the host; stage apps (drum machine, monitor, controller)
//! use [`client`] to join, read where they stand, report which app the person is in and read
//! who else is here.
//!
//! A live app re-reads its standing every [`RE_AUTH_MS`], so a role change or a kick reaches it
//! within that interval. Presence is reported every [`PRESENCE_REFRESH_MS`] and is gone
//! [`PRESENCE_TTL_MS`] after the last report.
use serde::{Deserialize, Serialize};
use weirdnet_collab::{AuditEntry, AuditKind, ProjectId, RoleId};
use weirdnet_contacts::UserId;
use weirdnet_service::ProtocolId;

/// The protocol id.
pub const PROTOCOL: &str = "/songnotes/collab";
/// The protocol version.
pub const VERSION: u32 = 1;
/// How often a live app re-reads its standing (the re-authorisation interval).
pub const RE_AUTH_MS: i64 = 5_000;
/// How often an app reports that the person is in it.
pub const PRESENCE_REFRESH_MS: i64 = 20_000;
/// How long a report counts.
pub const PRESENCE_TTL_MS: i64 = 60_000;
const _: () = assert!(RE_AUTH_MS < PRESENCE_REFRESH_MS && PRESENCE_REFRESH_MS < PRESENCE_TTL_MS);

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

/// Where someone stands in a project.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Standing {
    /// A member with this role.
    Member(RoleId),
    /// Waiting for the host.
    Pending,
    /// Not in: never asked, turned away, kicked, or their link was revoked.
    Out,
    /// Banned.
    Banned,
}

/// Whether the person is using the app or it is in the background.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Activity {
    /// In front, in use.
    Active,
    /// Open but not in use.
    Idle,
}

/// "I am in this app": what an app reports for its person.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Here {
    /// The app, such as `collab` or `drummachine`.
    pub app: String,
    /// Active or idle.
    pub activity: Activity,
    /// When the report was made (the host's clock when it took it in).
    pub at_ms: i64,
}

/// One person as the project shows them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Person {
    /// Who.
    pub user: UserId,
    /// Their role.
    pub role: RoleId,
    /// The apps they are in now, newest report first (empty: offline).
    pub apps: Vec<Here>,
}

/// What a member sees of a project.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectView {
    /// The project.
    pub project: ProjectId,
    /// Its title.
    pub title: String,
    /// The host.
    pub host: UserId,
    /// Where the caller stands.
    pub standing: Standing,
    /// The members, the host first.
    pub people: Vec<Person>,
    /// The audit entries the caller is part of (all of them for the host), oldest first.
    pub audit: Vec<AuditEntry>,
    /// The host's clock when the view was made.
    pub at_ms: i64,
}

impl ProjectView {
    /// One person.
    pub fn person(&self, user: &UserId) -> Option<&Person> {
        self.people.iter().find(|p| &p.user == user)
    }

    /// Whether every audit entry's signature holds.
    pub fn audit_verifies(&self) -> bool {
        self.audit.iter().all(AuditEntry::verify)
    }
}

/// A request to the host.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Req {
    /// Redeem this link (its text).
    Join {
        /// The link.
        link: String,
    },
    /// Where do I stand?
    Status {
        /// The project.
        project: ProjectId,
    },
    /// The project as I may see it. Members only.
    Sync {
        /// The project.
        project: ProjectId,
    },
    /// I am in this app. Members only.
    Here {
        /// The project.
        project: ProjectId,
        /// The app.
        app: String,
        /// Active or idle.
        activity: Activity,
    },
}

/// The host's answer to a join or status request.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Answer {
    /// The project.
    pub project: ProjectId,
    /// Its title; told only to members and people waiting.
    pub title: Option<String>,
    /// Where the caller stands.
    pub standing: Standing,
}

/// A response.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Resp {
    /// To `Join` and `Status`.
    Answer(Answer),
    /// To `Sync`.
    View(Box<ProjectView>),
    /// To `Here`.
    Noted,
}

/// One audit entry as a line of text; `name` turns an id into how the reader knows them.
pub fn audit_line(e: &AuditEntry, name: impl Fn(&UserId) -> String) -> String {
    let by = name(&e.by);
    match &e.kind {
        AuditKind::RuleSet { permission, effect, member, role, .. } => {
            let who = member.as_ref().map(&name).or_else(|| role.as_ref().map(|r| format!("every {r}"))).unwrap_or_else(|| "everyone".into());
            let verb = if matches!(effect, weirdnet_collab::Effect::Allow) { "allowed" } else { "denied" };
            format!("{by} {verb} {permission} for {who}")
        }
        AuditKind::RuleRemoved { .. } => format!("{by} removed a rule"),
        AuditKind::RoleChanged { user, from, to } => format!("{by} changed {} from {from} to {to}", name(user)),
        AuditKind::MemberJoined { user, role, .. } => format!("{} joined as {role}", name(user)),
        AuditKind::MemberKicked { user } => format!("{by} removed {}", name(user)),
        AuditKind::MemberBanned { user } => format!("{by} banned {}", name(user)),
        AuditKind::MemberUnbanned { user } => format!("{by} lifted the ban on {}", name(user)),
        AuditKind::InviteCreated { role, to, .. } => match to {
            Some(u) => format!("{by} invited {} as {role}", name(u)),
            None => format!("{by} made a {role} link"),
        },
        AuditKind::InviteRevoked { .. } => format!("{by} revoked a link"),
        AuditKind::JoinRequested { user, .. } => format!("{} asked to join", name(user)),
        AuditKind::JoinDenied { user } => format!("{by} turned {} away", name(user)),
        AuditKind::ConsentGranted { owner, grantee, permission, .. } => format!("{} let {} {permission}", name(owner), name(grantee)),
        AuditKind::ConsentRevoked { .. } => format!("{by} took back a consent"),
        AuditKind::SessionOpen { open } => format!("{by} {} the session", if *open { "opened" } else { "closed" }),
    }
}

/// Talking to a host. Each call takes a session from
/// `weirdnet_service::Client::session::<Req, Resp>(host, &protocol())`.
pub mod client {
    use super::*;
    use weirdnet_service::{ServiceError, Session};

    fn bad(what: &str) -> ServiceError {
        ServiceError::App { code: "bad-response".into(), message: format!("not {what}") }
    }

    /// Open a session with `host`.
    pub async fn open(client: &weirdnet_service::Client, host: &UserId) -> Result<Session<Req, Resp>, ServiceError> {
        client.session::<Req, Resp>(host.as_str(), &protocol()).await
    }

    /// Ask to join with `link` (its text).
    pub async fn join(s: &Session<Req, Resp>, link: &str) -> Result<Answer, ServiceError> {
        match s.call(&Req::Join { link: link.into() }).await? {
            Resp::Answer(a) => Ok(a),
            _ => Err(bad("an answer")),
        }
    }

    /// Where you stand.
    pub async fn status(s: &Session<Req, Resp>, project: &ProjectId) -> Result<Answer, ServiceError> {
        match s.call(&Req::Status { project: project.clone() }).await? {
            Resp::Answer(a) => Ok(a),
            _ => Err(bad("an answer")),
        }
    }

    /// The project as you may see it. Call every [`RE_AUTH_MS`] while the app is live.
    pub async fn sync(s: &Session<Req, Resp>, project: &ProjectId) -> Result<ProjectView, ServiceError> {
        match s.call(&Req::Sync { project: project.clone() }).await? {
            Resp::View(v) => Ok(*v),
            _ => Err(bad("a view")),
        }
    }

    /// Report that you are in `app`. Call every [`PRESENCE_REFRESH_MS`].
    pub async fn here(s: &Session<Req, Resp>, project: &ProjectId, app: &str, activity: Activity) -> Result<(), ServiceError> {
        match s.call(&Req::Here { project: project.clone(), app: app.into(), activity }).await? {
            Resp::Noted => Ok(()),
            _ => Err(bad("noted")),
        }
    }
}