weirdnet-songnotes 0.11.0

SongNotes collaboration: the roles, permissions, links and consent requests for a SongNotes session, built on weirdnet-collab.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! A live session between stage apps: one host holds the state (a song, a mix: bytes the app
//! defines) and members read it. Members are read-only in the first release, so the host refuses
//! every edit a member proposes. The host keeps a standby handover signed to the next member, who
//! takes over if the host can no longer be reached; a host that leaves on purpose hands over at
//! once. A kicked or banned member's next request is refused, which ends its session.
//!
//! [`Live`] is the state machine with no I/O: the host answers [`LiveReq`]s with
//! [`Live::handle`], and a member asks [`Live::next_call`] what to send and gives the answer to
//! [`Live::on_answer`]. [`service`] serves it and calls it on `/songnotes/live` over
//! weirdnet-service; tests can wire nodes together in memory instead.
use crate::link::JoinLink;
use crate::perm::PROJECT_EDIT;
use crate::service::Standing;
use crate::session::{Joined, Session, SessionError};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use weirdnet_collab::{Handover, HandoverKind, Project, ProjectId, RoleId};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;

/// The protocol name.
pub const LIVE_PROTOCOL: &str = "/songnotes/live";
/// The protocol version.
pub const LIVE_VERSION: u32 = 1;
/// How often a member asks the host for news.
pub const PULL_MS: i64 = 500;
/// A member who asked within this long counts as online.
pub const ONLINE_MS: i64 = 5_000;
/// After this long without an answer from the host, the standby handover is used.
pub const HOST_LOST_MS: i64 = 6_000;
/// How often the successor gets a fresh copy of the project, besides on every change.
pub const KIT_MS: i64 = 4_000;
/// The largest state the host serves.
pub const MAX_STATE: usize = 8 << 20;

/// What a member (or a would-be member) asks the host.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum LiveReq {
    /// Use a link (its text).
    Join {
        /// The link.
        link: String,
    },
    /// News since revision `since`. Also says the caller is here, in `app`, reachable at `addrs`.
    Pull {
        /// The project.
        project: ProjectId,
        /// The last revision the caller has.
        since: u64,
        /// The app the caller is in.
        app: String,
        /// The caller's direct addresses, for the next host to be found.
        addrs: Vec<String>,
    },
    /// Propose an edit (refused in the first release: members are read-only).
    Propose {
        /// The project.
        project: ProjectId,
        /// The edit, in the app's own encoding.
        edit: Vec<u8>,
    },
    /// The caller is leaving (it stays a member).
    Leave {
        /// The project.
        project: ProjectId,
    },
    /// The host is leaving and hands the session to the callee.
    TakeOver {
        /// The handover, signed by the host to the callee.
        handover: Handover,
        /// The host's copy of the project.
        project: Box<Project>,
        /// The state.
        state: Vec<u8>,
        /// Its revision.
        rev: u64,
    },
}

/// One person, as the host shows them to members.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LivePerson {
    /// Who.
    pub user: UserId,
    /// Their role.
    pub role: RoleId,
    /// The app they are in, if they asked recently.
    pub app: Option<String>,
    /// Whether they asked within [`ONLINE_MS`] (the host always is).
    pub online: bool,
    /// Their direct addresses, as they gave them.
    pub addrs: Vec<String>,
}

/// The host's news for a member.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Feed {
    /// The project.
    pub project: ProjectId,
    /// The host.
    pub host: UserId,
    /// The caller's role.
    pub role: RoleId,
    /// The state's revision.
    pub rev: u64,
    /// The state, if it changed since the caller's revision.
    pub state: Option<Vec<u8>>,
    /// Everyone in the session, the host first.
    pub people: Vec<LivePerson>,
    /// The standby handover, so every member knows who hosts next.
    pub standby: Option<Handover>,
    /// The project, for the successor only, so it can take over.
    pub kit: Option<Box<Project>>,
}

/// The host's answer.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum LiveResp {
    /// Where the caller stands (the answer to `Join`, and to `Pull` while waiting).
    Standing(Standing),
    /// News.
    Feed(Box<Feed>),
    /// The host left; this handover names who hosts now.
    Moved(Handover),
    /// Done.
    Done,
}

/// How a call failed, as the member's driver saw it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Failure {
    /// The host answered with a refusal code (`not-member`, `banned`, `read-only`, ...).
    Refused(String),
    /// The host could not be reached.
    Unreachable,
}

/// Something the app should show.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LiveEvent {
    /// The host let you in, with this role.
    Joined(RoleId),
    /// You wait for the host to let you in.
    Waiting,
    /// The state changed to this revision.
    Updated(u64),
    /// You are the host now.
    BecameHost,
    /// Someone else hosts now.
    HostMoved(UserId),
    /// The session ended for you (`not-member`: removed; `banned`; `out`: turned away; ...).
    Ended(String),
}

struct Seen {
    at: i64,
    app: String,
    addrs: Vec<String>,
    kit_at: i64,
    kit_rev: u64,
}

struct Hosting {
    session: Session,
    state: Vec<u8>,
    rev: u64,
    seen: BTreeMap<UserId, Seen>,
    standby: Option<Handover>,
    moved: Option<Handover>,
    kit_rev: u64,
}

struct Membership {
    project: ProjectId,
    host: UserId,
    link: Option<JoinLink>,
    role: Option<RoleId>,
    rev: u64,
    state: Option<Vec<u8>>,
    people: Vec<LivePerson>,
    standby: Option<Handover>,
    kit: Option<Project>,
    last_ok: i64,
}

enum Mode {
    Idle,
    Host(Box<Hosting>),
    Member(Box<Membership>),
    Ended(String),
}

/// One node's side of a live session.
pub struct Live {
    key: Keypair,
    me: UserId,
    app: String,
    addrs: Vec<String>,
    mode: Mode,
}

fn code(e: &SessionError) -> String {
    use weirdnet_collab::{Error as C, InviteError as I};
    match e {
        SessionError::WrongProject => "wrong-project".into(),
        SessionError::Collab(C::NotMember) => "not-member".into(),
        SessionError::Collab(C::Invite(i)) => match i {
            I::Expired => "expired",
            I::UsedUp => "used-up",
            I::Revoked => "revoked",
            I::Banned => "banned",
            I::Unknown => "unknown-invite",
            I::NotAddressee => "not-for-you",
            _ => "refused",
        }
        .into(),
        SessionError::Collab(C::BadSignature) => "bad-signature".into(),
        _ => "refused".into(),
    }
}

impl Live {
    /// A node with `key`, in `app` (such as `drummachine`), doing nothing yet.
    pub fn new(key: Keypair, app: &str) -> Live {
        Live { me: UserId::of_keypair(&key), key, app: app.into(), addrs: vec![], mode: Mode::Idle }
    }

    /// This node's user id.
    pub fn me(&self) -> &UserId {
        &self.me
    }

    /// Say which direct addresses this node has (sent to the host, and put in links).
    pub fn set_addrs(&mut self, addrs: Vec<String>) {
        self.addrs = addrs;
    }

    /// Host a new session `id` (standalone host mode) with this state.
    pub fn host(&mut self, id: &str, state: Vec<u8>, now: i64) -> Result<(), SessionError> {
        let session = Session::standalone(id, self.key.clone(), now)?;
        self.mode = Mode::Host(Box::new(Hosting { session, state, rev: 1, seen: BTreeMap::new(), standby: None, moved: None, kit_rev: 1 }));
        Ok(())
    }

    /// Ask to join with `link` (it must name its host).
    pub fn join(&mut self, link: JoinLink, now: i64) -> Result<(), String> {
        let host = link.host.clone().ok_or("the link does not name a host")?;
        if host == self.me {
            return Err("that is your own session".into());
        }
        self.mode = Mode::Member(Box::new(Membership {
            project: link.project.clone(),
            host,
            link: Some(link),
            role: None,
            rev: 0,
            state: None,
            people: vec![],
            standby: None,
            kit: None,
            last_ok: now,
        }));
        Ok(())
    }

    /// Whether this node hosts the session.
    pub fn is_host(&self) -> bool {
        matches!(&self.mode, Mode::Host(h) if h.moved.is_none())
    }

    /// Whether this node is in a session (hosting, joined or waiting).
    pub fn active(&self) -> bool {
        matches!(&self.mode, Mode::Member(_)) || self.is_host()
    }

    /// Why the session ended, if it did.
    pub fn ended(&self) -> Option<&str> {
        if let Mode::Ended(r) = &self.mode { Some(r) } else { None }
    }

    /// The project, if in one.
    pub fn project(&self) -> Option<&ProjectId> {
        match &self.mode {
            Mode::Host(h) => Some(h.session.project().id()),
            Mode::Member(m) => Some(&m.project),
            _ => None,
        }
    }

    /// Who hosts.
    pub fn host_id(&self) -> Option<&UserId> {
        match &self.mode {
            Mode::Host(_) => Some(&self.me),
            Mode::Member(m) => Some(&m.host),
            _ => None,
        }
    }

    /// Your role (the host role when hosting; `None` while waiting).
    pub fn role(&self) -> Option<RoleId> {
        match &self.mode {
            Mode::Host(h) => h.session.project().member(&self.me).map(|m| m.role.clone()),
            Mode::Member(m) => m.role.clone(),
            _ => None,
        }
    }

    /// The state and its revision as this node has it.
    pub fn state(&self) -> Option<(&[u8], u64)> {
        match &self.mode {
            Mode::Host(h) => Some((&h.state, h.rev)),
            Mode::Member(m) => m.state.as_deref().map(|s| (s, m.rev)),
            _ => None,
        }
    }

    /// As host: a new state. Returns its revision (`None` if not hosting or too large).
    pub fn publish(&mut self, state: Vec<u8>) -> Option<u64> {
        let Mode::Host(h) = &mut self.mode else { return None };
        if h.moved.is_some() || state.len() > MAX_STATE {
            return None;
        }
        if h.state != state {
            h.state = state;
            h.rev += 1;
        }
        Some(h.rev)
    }

    /// As host: a Viewer link that needs your approval, naming you and your addresses.
    pub fn share_link(&mut self, now: i64) -> Result<JoinLink, SessionError> {
        let addrs = self.addrs.clone();
        let Mode::Host(h) = &mut self.mode else { return Err(SessionError::Collab(weirdnet_collab::Error::NotOwner)) };
        Ok(h.session.quick_link(now)?.with_addrs(addrs))
    }

    /// As host: the session, to make other links, approve, kick or ban.
    pub fn session_mut(&mut self) -> Option<&mut Session> {
        match &mut self.mode {
            Mode::Host(h) => Some(&mut h.session),
            _ => None,
        }
    }

    /// As host: people waiting to be let in.
    pub fn pending(&self) -> Vec<UserId> {
        match &self.mode {
            Mode::Host(h) => h.session.pending(),
            _ => vec![],
        }
    }

    /// Everyone in the session, the host first.
    pub fn people(&self, now: i64) -> Vec<LivePerson> {
        match &self.mode {
            Mode::Host(h) => Self::roster(h, &self.me, &self.app, &self.addrs, now),
            Mode::Member(m) => m.people.clone(),
            _ => vec![],
        }
    }

    /// The addresses a person gave, from the last roster.
    pub fn addrs_of(&self, user: &UserId) -> Vec<String> {
        self.people(0).into_iter().find(|p| &p.user == user).map(|p| p.addrs).unwrap_or_default()
    }

    /// Who takes over if the host goes (from the standby handover).
    pub fn successor(&self) -> Option<&UserId> {
        match &self.mode {
            Mode::Host(h) => h.standby.as_ref().map(|s| &s.to),
            Mode::Member(m) => m.standby.as_ref().map(|s| &s.to),
            _ => None,
        }
    }

    fn roster(h: &Hosting, me: &UserId, app: &str, addrs: &[String], now: i64) -> Vec<LivePerson> {
        let p = h.session.project();
        let mut v: Vec<_> = p.members().collect();
        v.sort_by_key(|m| (m.user != *me, m.joined_ms, m.user.clone()));
        v.into_iter()
            .map(|m| {
                let seen = h.seen.get(&m.user);
                let mine = m.user == *me;
                LivePerson {
                    user: m.user.clone(),
                    role: m.role.clone(),
                    app: if mine { Some(app.into()) } else { seen.map(|s| s.app.clone()) },
                    online: mine || seen.is_some_and(|s| now - s.at <= ONLINE_MS),
                    addrs: if mine { addrs.to_vec() } else { seen.map(|s| s.addrs.clone()).unwrap_or_default() },
                }
            })
            .collect()
    }

    // ---- the host side ----------------------------------------------------------------------

    /// As host, answer `who`. A refusal is a short code. A member asking a node that hosts
    /// nothing gets `not-host`.
    pub fn handle(&mut self, who: &UserId, req: LiveReq, now: i64) -> Result<LiveResp, String> {
        if let LiveReq::TakeOver { handover, project, state, rev } = req {
            return self.take_over(who, handover, *project, state, rev, now);
        }
        let Mode::Host(h) = &mut self.mode else { return Err("not-host".into()) };
        if let Some(m) = &h.moved {
            return Ok(LiveResp::Moved(m.clone()));
        }
        let project = h.session.project();
        let standing = |p: &Project| {
            if p.is_banned(who) {
                Standing::Banned
            } else if let Some(m) = p.member(who) {
                Standing::Member(m.role.clone())
            } else if p.pending().iter().any(|r| &r.user == who) {
                Standing::Pending
            } else {
                Standing::Out
            }
        };
        match req {
            LiveReq::Join { link } => {
                let link: JoinLink = link.parse().map_err(|_| "bad-link".to_string())?;
                match h.session.join(&link, who, now) {
                    Ok(Joined::Member(r)) => Ok(LiveResp::Standing(Standing::Member(r))),
                    Ok(Joined::Pending) => Ok(LiveResp::Standing(Standing::Pending)),
                    Err(e) => match standing(h.session.project()) {
                        s @ (Standing::Member(_) | Standing::Pending) => Ok(LiveResp::Standing(s)),
                        _ => Err(code(&e)),
                    },
                }
            }
            LiveReq::Pull { project: pid, since, app, addrs } => {
                if &pid != project.id() {
                    return Err("wrong-project".into());
                }
                let role = match standing(project) {
                    Standing::Member(r) => r,
                    Standing::Pending => return Ok(LiveResp::Standing(Standing::Pending)),
                    Standing::Banned => return Err("banned".into()),
                    Standing::Out => return Err("not-member".into()),
                };
                let app: String = app.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').take(40).collect();
                let addrs: Vec<String> = addrs.into_iter().filter(|a| a.len() <= 256).take(8).collect();
                let seen = h.seen.entry(who.clone()).or_insert(Seen { at: now, app: app.clone(), addrs: vec![], kit_at: 0, kit_rev: 0 });
                seen.at = now;
                seen.app = app;
                seen.addrs = addrs;
                let successor = h.standby.as_ref().is_some_and(|s| &s.to == who);
                let kit = if successor && (now - seen.kit_at >= KIT_MS || seen.kit_rev != h.kit_rev) {
                    seen.kit_at = now;
                    seen.kit_rev = h.kit_rev;
                    Some(Box::new(h.session.project().clone()))
                } else {
                    None
                };
                Ok(LiveResp::Feed(Box::new(Feed {
                    project: pid,
                    host: self.me.clone(),
                    role,
                    rev: h.rev,
                    state: (since != h.rev).then(|| h.state.clone()),
                    people: Self::roster(h, &self.me, &self.app, &self.addrs, now),
                    standby: h.standby.clone(),
                    kit,
                })))
            }
            LiveReq::Propose { project: pid, .. } => {
                if &pid != project.id() || !matches!(standing(project), Standing::Member(_)) {
                    return Err("not-member".into());
                }
                if !h.session.can(who, PROJECT_EDIT, now) {
                    return Err("not-allowed".into());
                }
                // co-editing is a later release: the host is the only editor
                Err("read-only".into())
            }
            LiveReq::Leave { project: pid } => {
                if &pid == project.id() {
                    h.seen.remove(who);
                }
                Ok(LiveResp::Done)
            }
            LiveReq::TakeOver { .. } => unreachable!("handled above"),
        }
    }

    fn take_over(&mut self, who: &UserId, h: Handover, project: Project, state: Vec<u8>, rev: u64, now: i64) -> Result<LiveResp, String> {
        let Mode::Member(m) = &self.mode else { return Err("not-member".into()) };
        if &h.from != who || h.from != m.host || h.to != self.me || project.id() != &m.project || state.len() > MAX_STATE {
            return Err("bad-handover".into());
        }
        let mut session = Session::resume(project, self.key.clone());
        session.accept_handover(&h, now).map_err(|e| code(&e))?;
        self.mode = Mode::Host(Box::new(Hosting { session, state, rev, seen: BTreeMap::new(), standby: None, moved: None, kit_rev: 1 }));
        Ok(LiveResp::Done)
    }

    /// As host, keep the standby handover pointing at the first online member (by join time),
    /// and as a member, use the standby handover once the host is lost. Call it every
    /// [`PULL_MS`].
    pub fn tick(&mut self, now: i64) -> Option<LiveEvent> {
        match &mut self.mode {
            Mode::Host(h) if h.moved.is_none() => {
                let p = h.session.project();
                let mut cands: Vec<_> =
                    p.members().filter(|m| m.user != self.me && h.seen.get(&m.user).is_some_and(|s| now - s.at <= ONLINE_MS)).collect();
                cands.sort_by_key(|m| (m.joined_ms, m.user.clone()));
                let next = cands.first().map(|m| m.user.clone());
                if h.standby.as_ref().map(|s| &s.to) != next.as_ref() {
                    h.standby = next.and_then(|to| h.session.hand_over(&to, HandoverKind::Standby, now).ok());
                    h.kit_rev += 1;
                }
                // a change in the project (a join, a kick) goes to the successor soon
                let marker = p.audit().entries().len() as u64;
                if h.kit_rev < marker {
                    h.kit_rev = marker;
                }
                None
            }
            Mode::Member(m) if m.role.is_some() && now - m.last_ok > HOST_LOST_MS => {
                let s = m.standby.clone()?;
                if s.from != m.host {
                    return None;
                }
                if s.to == self.me {
                    let kit = m.kit.take()?;
                    let mut session = Session::resume(kit, self.key.clone());
                    if session.accept_handover(&s, now).is_err() {
                        return None;
                    }
                    let (state, rev) = (m.state.take().unwrap_or_default(), m.rev);
                    self.mode = Mode::Host(Box::new(Hosting { session, state, rev, seen: BTreeMap::new(), standby: None, moved: None, kit_rev: 1 }));
                    Some(LiveEvent::BecameHost)
                } else {
                    m.host = s.to.clone();
                    m.last_ok = now;
                    Some(LiveEvent::HostMoved(s.to))
                }
            }
            _ => None,
        }
    }

    // ---- the member side --------------------------------------------------------------------

    /// What to send to whom next, as a member: a `Join` until the host answers, then `Pull`s.
    pub fn next_call(&self) -> Option<(UserId, LiveReq)> {
        let Mode::Member(m) = &self.mode else { return None };
        let req = match (&m.link, &m.role) {
            (Some(l), None) => LiveReq::Join { link: l.to_string() },
            _ => LiveReq::Pull { project: m.project.clone(), since: m.rev, app: self.app.clone(), addrs: self.addrs.clone() },
        };
        Some((m.host.clone(), req))
    }

    /// Ask the host to apply an edit (refused while members are read-only).
    pub fn propose(&self, edit: Vec<u8>) -> Option<(UserId, LiveReq)> {
        let Mode::Member(m) = &self.mode else { return None };
        Some((m.host.clone(), LiveReq::Propose { project: m.project.clone(), edit }))
    }

    /// Take the host's answer to [`Live::next_call`].
    pub fn on_answer(&mut self, r: Result<LiveResp, Failure>, now: i64) -> Option<LiveEvent> {
        let me = self.me.clone();
        let Mode::Member(m) = &mut self.mode else { return None };
        match r {
            Ok(LiveResp::Standing(Standing::Member(role))) => {
                m.last_ok = now;
                m.link = None;
                m.role = Some(role.clone());
                Some(LiveEvent::Joined(role))
            }
            Ok(LiveResp::Standing(Standing::Pending)) => {
                m.last_ok = now;
                m.link = None;
                Some(LiveEvent::Waiting)
            }
            Ok(LiveResp::Standing(s)) => {
                let why = if s == Standing::Banned { "banned" } else { "out" };
                self.mode = Mode::Ended(why.into());
                Some(LiveEvent::Ended(why.into()))
            }
            Ok(LiveResp::Feed(f)) => {
                let f = *f;
                m.last_ok = now;
                let first = m.role.is_none();
                m.role = Some(f.role.clone());
                m.people = f.people;
                m.standby = f.standby.filter(|s| s.verify() && s.from == m.host);
                if let Some(k) = f.kit {
                    m.kit = Some(*k);
                }
                if m.standby.as_ref().is_none_or(|s| s.to != me) {
                    m.kit = None;
                }
                if let Some(s) = f.state {
                    m.state = Some(s);
                    m.rev = f.rev;
                    return Some(LiveEvent::Updated(f.rev));
                }
                first.then_some(LiveEvent::Joined(f.role))
            }
            Ok(LiveResp::Moved(h)) => {
                if !h.verify() || h.from != m.host {
                    return None;
                }
                m.last_ok = now;
                if h.to == me {
                    // the TakeOver comes (or came) on its own; wait for it
                    return None;
                }
                m.host = h.to.clone();
                Some(LiveEvent::HostMoved(h.to))
            }
            Ok(LiveResp::Done) => None,
            Err(Failure::Refused(c)) if c == "read-only" || c == "not-allowed" => None,
            Err(Failure::Refused(c)) if c == "not-host" => None,
            Err(Failure::Refused(c)) => {
                self.mode = Mode::Ended(c.clone());
                Some(LiveEvent::Ended(c))
            }
            Err(Failure::Unreachable) => None,
        }
    }

    /// Leave. A host hands the session to its successor: send the returned `TakeOver` to them;
    /// it then answers members with `Moved` until the app stops it. A member sends `Leave`.
    pub fn leave(&mut self, now: i64) -> Option<(UserId, LiveReq)> {
        match std::mem::replace(&mut self.mode, Mode::Idle) {
            Mode::Host(mut h) if h.moved.is_none() => {
                let to = h.standby.as_ref().map(|s| s.to.clone())?;
                let ho = h.session.hand_over(&to, HandoverKind::Leave, now).ok()?;
                let req =
                    LiveReq::TakeOver { handover: ho.clone(), project: Box::new(h.session.project().clone()), state: h.state.clone(), rev: h.rev };
                h.moved = Some(ho);
                self.mode = Mode::Host(h);
                Some((to, req))
            }
            Mode::Member(m) => Some((m.host.clone(), LiveReq::Leave { project: m.project })),
            other => {
                self.mode = other;
                None
            }
        }
    }
}

/// `/songnotes/live` as a protocol id.
pub fn protocol() -> weirdnet_service::ProtocolId {
    weirdnet_service::ProtocolId::new(LIVE_PROTOCOL, LIVE_VERSION).expect("a valid protocol id")
}

/// Serving [`Live`] on weirdnet-service.
pub mod service {
    use super::*;
    use std::sync::{Arc, Mutex};
    use weirdnet_service::{Access, Admitted, Authorize, Caller, Service, ServiceError};

    /// Milliseconds since the epoch.
    pub fn now_ms() -> i64 {
        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
    }

    /// The service: every request goes to [`Live::handle`] as the transport-proven caller.
    pub struct LiveService(pub Arc<Mutex<Live>>);

    impl Service for LiveService {
        type Request = LiveReq;
        type Response = LiveResp;

        fn access(&self, r: &LiveReq) -> Access {
            Access::new(match r {
                LiveReq::Join { .. } => "live.join",
                LiveReq::Pull { .. } => "live.pull",
                LiveReq::Propose { .. } => "live.propose",
                LiveReq::Leave { .. } => "live.leave",
                LiveReq::TakeOver { .. } => "live.take-over",
            })
        }

        async fn call(&self, who: Admitted, r: LiveReq) -> Result<LiveResp, ServiceError> {
            let user = UserId::parse(who.user.as_deref().unwrap_or_default()).map_err(|_| ServiceError::Refused { reason: "unknown-peer".into() })?;
            let mut live = self.0.lock().unwrap_or_else(|e| e.into_inner());
            live.handle(&user, r, now_ms()).map_err(|c| ServiceError::App { code: c.clone(), message: c })
        }
    }

    /// Admits any peer whose id is a user id; [`Live::handle`] decides the rest.
    pub fn authorizer() -> impl Authorize {
        move |caller: &Caller, _: &Access| {
            UserId::parse(&caller.peer).map_err(|_| ServiceError::Refused { reason: "unknown-peer".into() })?;
            Ok(Admitted::new(caller.peer.clone()).with_user(caller.peer.clone()))
        }
    }

    /// Send `req` to `to` and turn the outcome into what [`Live::on_answer`] takes.
    pub async fn call(client: &weirdnet_service::Client, to: &UserId, req: &LiveReq) -> Result<LiveResp, Failure> {
        let s = client.session::<LiveReq, LiveResp>(to.as_str(), &protocol()).await.map_err(fail)?;
        s.call(req).await.map_err(fail)
    }

    fn fail(e: ServiceError) -> Failure {
        match e {
            ServiceError::App { code, .. } => Failure::Refused(code),
            ServiceError::Refused { reason } => Failure::Refused(reason),
            _ => Failure::Unreachable,
        }
    }
}