weirdnet-contacts 0.1.0

A contact book for Weirdnet apps: trusted and blocked identities, presence with privacy rules (base to everyone, detail to trusted contacts), signed text direct messages with delivery state and an offline queue, and contact links, served over weirdnet-service.
Documentation
//! The contacts service: what another node may ask of yours.
use crate::book::ContactState;
use crate::contacts::{Contacts, Receipt};
use crate::id::UserId;
use crate::message::{Message, MessageId};
use crate::presence::PresenceView;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use weirdnet_net::{Message as NetMessage, Node};
use weirdnet_service::net::Server;
use weirdnet_service::{Access, Admitted, Authorize, Caller, ProtocolId, Service, ServiceError, SessionOptions};

/// The protocol id.
pub const PROTOCOL: &str = "/weirdnet/contacts";
/// The protocol version.
pub const VERSION: u32 = 1;

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

/// A request from another node.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Req {
    /// Hand over a message the caller signed.
    Deliver(Message),
    /// Ask for the messages you wrote to the caller after `since_ms`.
    Pull {
        /// The newest time the caller already has.
        since_ms: i64,
    },
    /// Ask what you show the caller of your presence.
    Presence,
    /// Tell you the caller read these messages of yours.
    Read {
        /// The message ids.
        ids: Vec<MessageId>,
    },
}

/// The answer.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Resp {
    /// A delivered message was taken in.
    Ack(Receipt),
    /// Messages for a pull.
    Messages(Vec<Message>),
    /// Presence as the caller may see it (`None`: blocked).
    Presence(Option<PresenceView>),
    /// Read receipts applied.
    Done(usize),
}

/// The service over your [`Contacts`].
pub struct ContactsService(pub Arc<Contacts>);

fn app(code: &str) -> ServiceError {
    ServiceError::App { code: code.into(), message: code.into() }
}

/// The authorization hook: a blocked or banned caller is refused before anything runs. The
/// caller is the peer the transport proved.
pub fn authorizer(contacts: Arc<Contacts>) -> impl Authorize {
    move |caller: &Caller, _access: &Access| {
        let user = UserId::parse(&caller.peer).map_err(|_| ServiceError::Refused { reason: "unknown-peer".into() })?;
        if contacts.state_of(&user) == ContactState::Blocked {
            return Err(ServiceError::Refused { reason: "blocked".into() });
        }
        Ok(Admitted::new(caller.peer.clone()).with_user(caller.peer.clone()))
    }
}

impl Service for ContactsService {
    type Request = Req;
    type Response = Resp;

    fn access(&self, request: &Req) -> Access {
        Access::new(match request {
            Req::Deliver(_) => "contacts.deliver",
            Req::Pull { .. } => "contacts.pull",
            Req::Presence => "contacts.presence",
            Req::Read { .. } => "contacts.read",
        })
    }

    async fn call(&self, who: Admitted, request: Req) -> Result<Resp, ServiceError> {
        let peer = UserId::parse(&who.peer).map_err(|_| app("unknown-peer"))?;
        match request {
            Req::Deliver(m) => {
                if m.from != peer {
                    return Err(app("wrong-sender"));
                }
                self.0.receive(m, crate::contacts::now_ms()).map(Resp::Ack).map_err(|r| app(&r.to_string()))
            }
            Req::Pull { since_ms } => Ok(Resp::Messages(self.0.messages_since(&peer, since_ms))),
            Req::Presence => Ok(Resp::Presence(self.0.presence_for(&peer))),
            Req::Read { ids } => Ok(Resp::Done(self.0.read_by(&peer, &ids))),
        }
    }
}

/// Serve `contacts` on `node` at [`protocol`]. Dropping the returned [`Server`] stops serving.
pub fn serve<Q: NetMessage, R: NetMessage>(node: &Arc<Node<Q, R>>, contacts: Arc<Contacts>) -> Result<Server, ServiceError> {
    let opts = SessionOptions::default();
    Server::builder(node).service(&protocol(), Arc::new(ContactsService(contacts.clone())), Arc::new(authorizer(contacts)), opts).start()
}