Skip to main content

weirdnet_songnotes/
service.rs

1//! The SongNotes collab protocol, `/songnotes/collab`: what any SongNotes app asks the host of a
2//! project. The collab app serves it on the host; stage apps (drum machine, monitor, controller)
3//! use [`client`] to join, read where they stand, report which app the person is in and read
4//! who else is here.
5//!
6//! A live app re-reads its standing every [`RE_AUTH_MS`], so a role change or a kick reaches it
7//! within that interval. Presence is reported every [`PRESENCE_REFRESH_MS`] and is gone
8//! [`PRESENCE_TTL_MS`] after the last report.
9use crate::session::ConsentRequest;
10use serde::{Deserialize, Serialize};
11use weirdnet_collab::{
12    AuditEntry, AuditKind, ChatItem, ChatMessage, ConsentGrant, Decision, Duration, Effect, Explained, GrantStreams, ProjectId, RecordId, Revocation,
13    RoleId, SignError, Step, StreamId,
14};
15use weirdnet_contacts::UserId;
16use weirdnet_net::Keypair;
17use weirdnet_service::ProtocolId;
18
19/// The protocol id.
20pub const PROTOCOL: &str = "/songnotes/collab";
21/// The protocol version.
22pub const VERSION: u32 = 1;
23/// How often a live app re-reads its standing (the re-authorisation interval).
24pub const RE_AUTH_MS: i64 = 5_000;
25/// How often an app reports that the person is in it.
26pub const PRESENCE_REFRESH_MS: i64 = 20_000;
27/// How long a report counts.
28pub const PRESENCE_TTL_MS: i64 = 60_000;
29const _: () = assert!(RE_AUTH_MS < PRESENCE_REFRESH_MS && PRESENCE_REFRESH_MS < PRESENCE_TTL_MS);
30
31/// The protocol id as a [`ProtocolId`].
32pub fn protocol() -> ProtocolId {
33    ProtocolId::new(PROTOCOL, VERSION).expect("a valid protocol id")
34}
35
36/// Where someone stands in a project.
37#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
38pub enum Standing {
39    /// A member with this role.
40    Member(RoleId),
41    /// Waiting for the host.
42    Pending,
43    /// Not in: never asked, turned away, kicked, or their link was revoked.
44    Out,
45    /// Banned.
46    Banned,
47}
48
49/// Whether the person is using the app or it is in the background.
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
51pub enum Activity {
52    /// In front, in use.
53    Active,
54    /// Open but not in use.
55    Idle,
56}
57
58/// "I am in this app": what an app reports for its person.
59#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60pub struct Here {
61    /// The app, such as `collab` or `drummachine`.
62    pub app: String,
63    /// Active or idle.
64    pub activity: Activity,
65    /// When the report was made (the host's clock when it took it in).
66    pub at_ms: i64,
67    /// The app's network peer id, vouched for by the member's collab app (which knows its local stage apps), so another app can
68    /// tell whom an incoming connection acts for. Reports from before 0.11 have none.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub peer: Option<String>,
71}
72
73/// The permissions [`Req::Peers`] answers for: what an audio owner's app needs to decide who may listen.
74pub const PEER_PERMISSIONS: &[&str] = &[crate::perm::ROUTE_CONNECT];
75
76/// One app of a member and that member's decision for a permission, as the host answers [`Req::Peers`].
77#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
78pub struct PeerRight {
79    /// The app's network peer id ([`Here::peer`]).
80    pub peer: String,
81    /// The member it acts for.
82    pub user: UserId,
83    /// The app's name.
84    pub app: String,
85    /// The member's decision, with the caller as the audio's owner.
86    pub right: Explained,
87}
88
89/// One person as the project shows them.
90#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
91pub struct Person {
92    /// Who.
93    pub user: UserId,
94    /// Their role.
95    pub role: RoleId,
96    /// The apps they are in now, newest report first (empty: offline).
97    pub apps: Vec<Here>,
98}
99
100/// What a member sees of a project.
101#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
102pub struct ProjectView {
103    /// The project.
104    pub project: ProjectId,
105    /// Its title.
106    pub title: String,
107    /// The host.
108    pub host: UserId,
109    /// Where the caller stands.
110    pub standing: Standing,
111    /// The members, the host first.
112    pub people: Vec<Person>,
113    /// The audit entries the caller is part of (all of them for the host), oldest first.
114    pub audit: Vec<AuditEntry>,
115    /// Consent questions waiting for the caller (as the audio's owner).
116    #[serde(default)]
117    pub consent_requests: Vec<ConsentRequest>,
118    /// Live consent grants the caller gave or holds.
119    #[serde(default)]
120    pub grants: Vec<ConsentGrant>,
121    /// The caller's own rights, one decision per permission in the catalog, with the reasons.
122    #[serde(default)]
123    pub rights: Vec<Explained>,
124    /// The host's clock when the view was made.
125    pub at_ms: i64,
126}
127
128impl ProjectView {
129    /// One person.
130    pub fn person(&self, user: &UserId) -> Option<&Person> {
131        self.people.iter().find(|p| &p.user == user)
132    }
133
134    /// The caller's decision for `permission`, if the view has it.
135    pub fn right(&self, permission: &str) -> Option<&Explained> {
136        self.rights.iter().find(|e| e.permission.as_str() == permission)
137    }
138
139    /// Whether every audit entry's signature holds.
140    pub fn audit_verifies(&self) -> bool {
141        self.audit.iter().all(AuditEntry::verify)
142    }
143}
144
145/// A request to the host.
146#[derive(Clone, Debug, Serialize, Deserialize)]
147pub enum Req {
148    /// Redeem this link (its text).
149    Join {
150        /// The link.
151        link: String,
152    },
153    /// Where do I stand?
154    Status {
155        /// The project.
156        project: ProjectId,
157    },
158    /// The project as I may see it. Members only.
159    Sync {
160        /// The project.
161        project: ProjectId,
162    },
163    /// I am in this app. Members only.
164    Here {
165        /// The project.
166        project: ProjectId,
167        /// The app.
168        app: String,
169        /// Active or idle.
170        activity: Activity,
171        /// The app's network peer id, when the caller's collab app reports a stage app it knows ([`Here::peer`]).
172        #[serde(default, skip_serializing_if = "Option::is_none")]
173        peer: Option<String>,
174    },
175    /// Which apps of the members may do `permission` to the caller's audio: one [`PeerRight`] per app that reported its peer
176    /// id. Members only; only for [`PEER_PERMISSIONS`]. The host answers without side effects (no consent question is queued).
177    Peers {
178        /// The project.
179        project: ProjectId,
180        /// The permission.
181        permission: String,
182    },
183    /// May I do `permission` (to `owner`'s audio, optionally one stream)? With `act`, the caller
184    /// is about to do it, so a once-only consent is used up. A "needs consent" answer puts the
185    /// question in the owner's queue. Members only.
186    Can {
187        /// The project.
188        project: ProjectId,
189        /// The permission.
190        permission: String,
191        /// Whose audio, for gated permissions.
192        owner: Option<UserId>,
193        /// Which stream.
194        stream: Option<String>,
195        /// About to do it now.
196        act: bool,
197    },
198    /// A consent the caller (the owner) signed.
199    Grant {
200        /// The grant.
201        grant: ConsentGrant,
202        /// The audit entry the owner signed for it ([`AuditEntry::for_grant`]); with it the grant
203        /// shows in the audit as the owner's act.
204        #[serde(default)]
205        entry: Option<AuditEntry>,
206    },
207    /// The caller (the owner) takes a consent back.
208    Revoke {
209        /// The signed revocation.
210        revocation: Revocation,
211        /// The audit entry the owner signed for it ([`AuditEntry::for_revocation`]).
212        #[serde(default)]
213        entry: Option<AuditEntry>,
214    },
215    /// The caller (the owner) says no to a consent question.
216    Decline {
217        /// The question.
218        request: ConsentRequest,
219    },
220    /// Post to the project chat. The caller must be the message's author. Needs `chat.write`.
221    Say {
222        /// The signed message ([`ChatMessage::sign`]).
223        message: ChatMessage,
224    },
225    /// Add or take back a reaction. Needs `chat.write`.
226    React {
227        /// The project.
228        project: ProjectId,
229        /// The message.
230        message: RecordId,
231        /// The reaction (an emoji or a short word).
232        reaction: String,
233        /// Add (true) or take back.
234        on: bool,
235    },
236    /// Delete a message: your own, or anyone's with `chat.manage`.
237    Unsay {
238        /// The project.
239        project: ProjectId,
240        /// The message.
241        message: RecordId,
242    },
243    /// What changed in the chat after sequence number `since` (0 for all history). Needs
244    /// `chat.read`.
245    Chat {
246        /// The project.
247        project: ProjectId,
248        /// The last sequence number you saw.
249        since: u64,
250    },
251    /// The host's signed certificate of where you stand (C5), for a stage app to enforce on
252    /// its own while the host does not answer.
253    Cert {
254        /// The project.
255        project: ProjectId,
256    },
257    /// The talkback room (C6). Needs `mic.listen` or `mic.talk`.
258    Talk {
259        /// The project.
260        project: ProjectId,
261    },
262    /// "My voice is here": announce or refresh the caller's talkback stream and whether their
263    /// mic is open. Needs `mic.talk`; refresh within [`crate::talk::SPEAKER_TTL_MS`].
264    Mic {
265        /// The project.
266        project: ProjectId,
267        /// The publishing peer.
268        peer: String,
269        /// Where to dial it.
270        addrs: Vec<String>,
271        /// The stream id ([`crate::talk::stream_id`]).
272        stream: String,
273        /// The mic is open.
274        live: bool,
275    },
276    /// Mute or unmute one person (`user`) or everyone but the host (`None`). Needs `mic.manage`.
277    MuteMic {
278        /// The project.
279        project: ProjectId,
280        /// Who; everyone when `None`.
281        user: Option<UserId>,
282        /// Mute (true) or unmute.
283        muted: bool,
284    },
285}
286
287/// The host's answer to a join or status request.
288#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
289pub struct Answer {
290    /// The project.
291    pub project: ProjectId,
292    /// Its title; told only to members and people waiting.
293    pub title: Option<String>,
294    /// Where the caller stands.
295    pub standing: Standing,
296}
297
298/// Chat changes after a sequence number.
299#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
300pub struct ChatPage {
301    /// Changed messages, oldest change first.
302    pub items: Vec<ChatItem>,
303    /// The latest sequence number; pass it as `since` next time.
304    pub seq: u64,
305}
306
307/// A response.
308#[derive(Clone, Debug, Serialize, Deserialize)]
309pub enum Resp {
310    /// To `Join` and `Status`.
311    Answer(Answer),
312    /// To `Sync`.
313    View(Box<ProjectView>),
314    /// To `Here`.
315    Noted,
316    /// To `Can`.
317    Decision(Box<Explained>),
318    /// To `Say`, `React` and `Unsay`: the change's sequence number.
319    Seq(u64),
320    /// To `Chat`.
321    Chat(ChatPage),
322    /// To `Cert`.
323    Cert(Box<crate::stage::Cert>),
324    /// To `Talk`, `Mic` and `MuteMic`.
325    Talk(Box<crate::talk::TalkState>),
326    /// To `Peers`.
327    Peers(Vec<PeerRight>),
328}
329
330/// One audit entry as a line of text; `name` turns an id into how the reader knows them.
331pub fn audit_line(e: &AuditEntry, name: impl Fn(&UserId) -> String) -> String {
332    let by = name(&e.by);
333    match &e.kind {
334        AuditKind::RuleSet { permission, effect, member, role, .. } => {
335            let who = member.as_ref().map(&name).or_else(|| role.as_ref().map(|r| format!("every {r}"))).unwrap_or_else(|| "everyone".into());
336            let verb = if matches!(effect, weirdnet_collab::Effect::Allow) { "allowed" } else { "denied" };
337            format!("{by} {verb} {permission} for {who}")
338        }
339        AuditKind::RuleRemoved { .. } => format!("{by} removed a rule"),
340        AuditKind::RoleChanged { user, from, to } => format!("{by} changed {} from {from} to {to}", name(user)),
341        AuditKind::MemberJoined { user, role, .. } => format!("{} joined as {role}", name(user)),
342        AuditKind::MemberKicked { user } => format!("{by} removed {}", name(user)),
343        AuditKind::MemberBanned { user } => format!("{by} banned {}", name(user)),
344        AuditKind::MemberUnbanned { user } => format!("{by} lifted the ban on {}", name(user)),
345        AuditKind::InviteCreated { role, to, .. } => match to {
346            Some(u) => format!("{by} invited {} as {role}", name(u)),
347            None => format!("{by} made a {role} link"),
348        },
349        AuditKind::InviteRevoked { .. } => format!("{by} revoked a link"),
350        AuditKind::JoinRequested { user, .. } => format!("{} asked to join", name(user)),
351        AuditKind::JoinDenied { user } => format!("{by} turned {} away", name(user)),
352        AuditKind::ConsentGranted { owner, grantee, permission, .. } => format!("{} let {} {permission}", name(owner), name(grantee)),
353        AuditKind::ConsentRevoked { .. } => format!("{by} took back a consent"),
354        AuditKind::SessionOpen { open } => format!("{by} {} the session", if *open { "opened" } else { "closed" }),
355        AuditKind::HostHandedOver { from, left, .. } => {
356            format!("{by} took over as host from {}{}", name(from), if *left { "" } else { " (who could not be reached)" })
357        }
358    }
359}
360
361/// The permissions that govern project chat in SongNotes.
362pub fn chat_perms() -> weirdnet_collab::ChatPerms {
363    use crate::perm::{CHAT_MANAGE, CHAT_READ, CHAT_WRITE};
364    weirdnet_collab::ChatPerms {
365        read: weirdnet_collab::Permission::new(CHAT_READ),
366        write: weirdnet_collab::Permission::new(CHAT_WRITE),
367        manage: weirdnet_collab::Permission::new(CHAT_MANAGE),
368    }
369}
370
371/// The people `text` mentions: each `@word` of at least 4 letters or digits that is the start or
372/// the end of exactly one id in `people`. Each person once, in the order they appear.
373pub fn mentions_in(text: &str, people: &[UserId]) -> Vec<UserId> {
374    let mut out: Vec<UserId> = vec![];
375    for w in text.split('@').skip(1) {
376        let tok: String = w.chars().take_while(|c| c.is_ascii_alphanumeric()).collect();
377        if tok.len() < 4 {
378            continue;
379        }
380        let hits: Vec<&UserId> = people.iter().filter(|u| u.as_str().starts_with(&tok) || u.as_str().ends_with(&tok)).collect();
381        if let [u] = hits.as_slice()
382            && !out.contains(u)
383        {
384            out.push((*u).clone());
385        }
386    }
387    out
388}
389
390/// The owner answers a consent question with yes: a grant signed with `owner`, once or always,
391/// for the stream the question named or (with `all_streams`, or when it named none) all of the
392/// owner's streams in the project. The id is 128 bits from the OS random source.
393pub fn sign_grant(owner: &Keypair, req: &ConsentRequest, how: Duration, all_streams: bool, now: i64) -> Result<ConsentGrant, SignError> {
394    let mut b = [0u8; 16];
395    getrandom::fill(&mut b).expect("the OS random source failed");
396    let id: String = std::iter::once('g').chain(b.iter().flat_map(|x| format!("{x:02x}").chars().collect::<Vec<_>>())).collect();
397    let streams = match (&req.stream, all_streams) {
398        (Some(s), false) => GrantStreams::Only(vec![s.clone()]),
399        _ => GrantStreams::All,
400    };
401    ConsentGrant::sign(owner, &id, &req.requester, &req.project, req.permission.as_str(), streams, how, now)
402}
403
404/// The owner takes a grant back.
405pub fn sign_revocation(owner: &Keypair, grant: &ConsentGrant, now: i64) -> Result<Revocation, SignError> {
406    Revocation::sign(owner, &grant.id, now)
407}
408
409/// A decision in a few words: "allowed", "denied" or "needs NAME's consent".
410pub fn decision_word(d: &Decision, name: impl Fn(&UserId) -> String) -> String {
411    match d {
412        Decision::Allowed => "allowed".into(),
413        Decision::Denied => "denied".into(),
414        Decision::NeedsConsent { owner } => format!("needs {}'s consent", name(owner)),
415    }
416}
417
418/// The reasons behind a decision, one line per step, for a "Why?" panel. The step that decided
419/// names its rule, who set it and when.
420pub fn why_lines(e: &Explained, name: impl Fn(&UserId) -> String) -> Vec<String> {
421    let eff = |x: &Effect| if matches!(x, Effect::Allow) { "allows" } else { "denies" };
422    e.chain
423        .iter()
424        .map(|s| match s {
425            Step::Banned => "banned from the project".into(),
426            Step::NotMember => "not a member".into(),
427            Step::SessionClosed => "the session is closed".into(),
428            Step::MemberRule { rule, effect, set_by, .. } => {
429                format!("a rule for this person {} it (rule {rule}, set by {})", eff(effect), name(set_by))
430            }
431            Step::RoleRule { role, rule, effect, set_by, .. } => {
432                format!("a rule for every {role} {} it (rule {rule}, set by {})", eff(effect), name(set_by))
433            }
434            Step::ExpiredRule { rule } => format!("rule {rule} has expired and was ignored"),
435            Step::RoleDefault { role, granted } => format!("the {role} role {} it by default", if *granted { "has" } else { "does not have" }),
436            Step::OwnAudio => "it is your own audio".into(),
437            Step::Consent { owner, duration, .. } => {
438                format!("{} said yes{}", name(owner), if matches!(duration, Duration::Once) { " once" } else { ", always" })
439            }
440            Step::ConsentMissing { owner } => format!("{} has not said yes", name(owner)),
441            Step::NoOwnerNamed => "no audio owner was named".into(),
442            Step::LocalGate { name: g } => format!("turned on locally ({g})"),
443            Step::DefaultDeny => "nothing allows it".into(),
444        })
445        .collect()
446}
447
448/// The streams a grant covers, in words.
449pub fn streams_word(g: &ConsentGrant) -> String {
450    match &g.streams {
451        GrantStreams::All => "all streams".into(),
452        GrantStreams::Only(v) => v.iter().map(StreamId::to_string).collect::<Vec<_>>().join(", "),
453    }
454}
455
456/// Talking to a host. Each call takes a session from
457/// `weirdnet_service::Client::session::<Req, Resp>(host, &protocol())`.
458pub mod client {
459    use super::*;
460    use weirdnet_service::{ServiceError, Session};
461
462    fn bad(what: &str) -> ServiceError {
463        ServiceError::App { code: "bad-response".into(), message: format!("not {what}") }
464    }
465
466    /// Open a session with `host`.
467    pub async fn open(client: &weirdnet_service::Client, host: &UserId) -> Result<Session<Req, Resp>, ServiceError> {
468        client.session::<Req, Resp>(host.as_str(), &protocol()).await
469    }
470
471    /// Ask to join with `link` (its text).
472    pub async fn join(s: &Session<Req, Resp>, link: &str) -> Result<Answer, ServiceError> {
473        match s.call(&Req::Join { link: link.into() }).await? {
474            Resp::Answer(a) => Ok(a),
475            _ => Err(bad("an answer")),
476        }
477    }
478
479    /// Where you stand.
480    pub async fn status(s: &Session<Req, Resp>, project: &ProjectId) -> Result<Answer, ServiceError> {
481        match s.call(&Req::Status { project: project.clone() }).await? {
482            Resp::Answer(a) => Ok(a),
483            _ => Err(bad("an answer")),
484        }
485    }
486
487    /// The project as you may see it. Call every [`RE_AUTH_MS`] while the app is live.
488    pub async fn sync(s: &Session<Req, Resp>, project: &ProjectId) -> Result<ProjectView, ServiceError> {
489        match s.call(&Req::Sync { project: project.clone() }).await? {
490            Resp::View(v) => Ok(*v),
491            _ => Err(bad("a view")),
492        }
493    }
494
495    /// Report that you are in `app`. Call every [`PRESENCE_REFRESH_MS`].
496    pub async fn here(s: &Session<Req, Resp>, project: &ProjectId, app: &str, activity: Activity) -> Result<(), ServiceError> {
497        here_as(s, project, app, activity, None).await
498    }
499
500    /// [`here`] for a stage app on this machine whose network peer id is `peer` (a collab app reporting the apps it serves).
501    pub async fn here_as(s: &Session<Req, Resp>, project: &ProjectId, app: &str, activity: Activity, peer: Option<&str>) -> Result<(), ServiceError> {
502        match s.call(&Req::Here { project: project.clone(), app: app.into(), activity, peer: peer.map(str::to_string) }).await? {
503            Resp::Noted => Ok(()),
504            _ => Err(bad("noted")),
505        }
506    }
507
508    /// Which members' apps may do `permission` to your audio ([`Req::Peers`]).
509    pub async fn peers(s: &Session<Req, Resp>, project: &ProjectId, permission: &str) -> Result<Vec<PeerRight>, ServiceError> {
510        match s.call(&Req::Peers { project: project.clone(), permission: permission.into() }).await? {
511            Resp::Peers(p) => Ok(p),
512            _ => Err(bad("peers")),
513        }
514    }
515    /// May you do `permission` (to `owner`'s audio, one `stream`)? With `act`, you are about to,
516    /// and a once-only consent is used up. Check this before acting; the answer names its reasons.
517    pub async fn can(
518        s: &Session<Req, Resp>,
519        project: &ProjectId,
520        permission: &str,
521        owner: Option<&UserId>,
522        stream: Option<&str>,
523        act: bool,
524    ) -> Result<Explained, ServiceError> {
525        let req =
526            Req::Can { project: project.clone(), permission: permission.into(), owner: owner.cloned(), stream: stream.map(str::to_string), act };
527        match s.call(&req).await? {
528            Resp::Decision(e) => Ok(*e),
529            _ => Err(bad("a decision")),
530        }
531    }
532
533    /// Hand the host a consent you signed (see [`sign_grant`]).
534    pub async fn grant(s: &Session<Req, Resp>, grant: ConsentGrant, entry: Option<AuditEntry>) -> Result<(), ServiceError> {
535        match s.call(&Req::Grant { grant, entry }).await? {
536            Resp::Noted => Ok(()),
537            _ => Err(bad("noted")),
538        }
539    }
540
541    /// Take a consent back (see [`sign_revocation`]).
542    pub async fn revoke(s: &Session<Req, Resp>, revocation: Revocation, entry: Option<AuditEntry>) -> Result<(), ServiceError> {
543        match s.call(&Req::Revoke { revocation, entry }).await? {
544            Resp::Noted => Ok(()),
545            _ => Err(bad("noted")),
546        }
547    }
548
549    /// Say no to a consent question.
550    pub async fn decline(s: &Session<Req, Resp>, request: ConsentRequest) -> Result<(), ServiceError> {
551        match s.call(&Req::Decline { request }).await? {
552            Resp::Noted => Ok(()),
553            _ => Err(bad("noted")),
554        }
555    }
556    /// Post `text` to the project chat as `me`, mentioning `mentions` (see [`mentions_in`]).
557    /// Returns the message as sent.
558    pub async fn say(
559        s: &Session<Req, Resp>,
560        me: &Keypair,
561        project: &ProjectId,
562        text: &str,
563        mentions: Vec<UserId>,
564        now: i64,
565    ) -> Result<ChatMessage, ServiceError> {
566        let message = ChatMessage::sign(me, project, text, mentions, now).map_err(|e| bad(&e.to_string()))?;
567        match s.call(&Req::Say { message: message.clone() }).await? {
568            Resp::Seq(_) => Ok(message),
569            _ => Err(bad("a sequence number")),
570        }
571    }
572
573    /// Add (`on`) or take back a reaction.
574    pub async fn react(s: &Session<Req, Resp>, project: &ProjectId, message: &RecordId, reaction: &str, on: bool) -> Result<u64, ServiceError> {
575        match s.call(&Req::React { project: project.clone(), message: message.clone(), reaction: reaction.into(), on }).await? {
576            Resp::Seq(n) => Ok(n),
577            _ => Err(bad("a sequence number")),
578        }
579    }
580
581    /// Delete a message.
582    pub async fn unsay(s: &Session<Req, Resp>, project: &ProjectId, message: &RecordId) -> Result<u64, ServiceError> {
583        match s.call(&Req::Unsay { project: project.clone(), message: message.clone() }).await? {
584            Resp::Seq(n) => Ok(n),
585            _ => Err(bad("a sequence number")),
586        }
587    }
588
589    /// The chat changes after `since`.
590    pub async fn chat(s: &Session<Req, Resp>, project: &ProjectId, since: u64) -> Result<ChatPage, ServiceError> {
591        match s.call(&Req::Chat { project: project.clone(), since }).await? {
592            Resp::Chat(p) => Ok(p),
593            _ => Err(bad("chat")),
594        }
595    }
596
597    /// The host's signed certificate of where you stand.
598    pub async fn cert(s: &Session<Req, Resp>, project: &ProjectId) -> Result<crate::stage::Cert, ServiceError> {
599        match s.call(&Req::Cert { project: project.clone() }).await? {
600            Resp::Cert(c) => Ok(*c),
601            _ => Err(bad("a certificate")),
602        }
603    }
604}