package calls // Team mode's call stream (GET /m/{sqid}/stream): the signalling channel // a participation's browser listens on, re-decided on standing before // every delivery and at the end of every lease (Home teammode-package.md // §5, "the stream hook"; §7.4: "the signaling socket closed at // Access.Remaining() unless renewed"). // // What a participation stands on: the meeting's host, always (a call // stands on its host, team_host.go), and for a member-kind participation // the member's own standing as well. A guest's own standing is not asked: // once admitted a guest stands on the participation (ruling 14), and the // participation on the host. // // Three answers, as Slides' streams (oficina/slides #33): // // - Member: deliver, and re-decide at the lease's end (never later than // the shortest Remaining, never sooner than a second). Before every // delivery the decision's leases are checked again (Access.State, // which never waits); one that has run out is re-decided first. // - Unknown: hold. The connection stays open and carries nothing but // heartbeat comments; the standing is asked again every // teamStreamHoldRetry. What arrives meanwhile is kept, in order, and // delivered only once a Member answer says it may be — or, past what // the hub's own buffer would keep, the stream ends with lost{buffer} // and the browser resumes, which replays from the ring on standing it // must have again. A Home blip does not drop the call: the media, // which never passes through Calls, carries on, and so does the // browser's stream, which receives its hello and so does not count // the round as a stall. // - NotMember: the end. A host who has left ends the meeting (lost // {ended}); a member who has left is ended by the hub, in its words // (lost{standing}), and the others are told "gone" and close their // connections to them. // // The terminal events the hub raises (lost, ended) are delivered whatever // the answer: they carry no call's content, only that this stream is // over and why. // // What this cannot do, said plainly: Calls signals; it does not carry // media. A connection already established peer to peer, or through the // platform relay on credentials /ice minted (valid for up to three // hours), is not Calls' to cut. Ending a participation tells every other // browser to close its connection to it, which is what stops the media // in practice; a modified client that ignored "gone" could keep a // connection to a colluding peer until its relay credentials expire. import ( "context" "net/http" "time" "amadan.net/oficina/home/roster" "amadan.net/oficina/home/teammode" "amadan.net/oficina/calls/internal/calls/hub" ) var ( // teamStreamHoldRetry is how often a held stream asks again: the // roster's own retry interval. A variable only so a test can shorten // it. teamStreamHoldRetry = roster.RetryAfter // teamStreamRecheckMax caps how long a delivering stream goes before // it re-decides. A lease is never longer than roster.MaximumAge, so // in production this changes nothing; a test shortens it so a lease // measured on a stepped roster clock is re-decided in real time. teamStreamRecheckMax = roster.MaximumAge ) // teamStreamHeld bounds what a held stream keeps: the hub's own buffer // for one subscriber. Past it the stream ends as an overflowing // subscriber does (lost{buffer}), and the browser resumes. const teamStreamHeld = 64 // streamVerdict is one decision's answer. type streamVerdict int const ( streamHolds streamVerdict = iota streamDelivers streamEnds ) // streamDecision is a participation's standing, decided once: what to do, // when to decide again, the leases a delivery rests on, and the event // that ends the stream. type streamDecision struct { verdict streamVerdict renew time.Duration leases []*teammode.Access end hub.Message } // stands reports whether every lease the decision delivers on still // holds. It never waits (Access.State's TryLock), and a lease that has // run out latches, so the stream re-decides before it delivers. func (d streamDecision) stands() bool { if d.verdict != streamDelivers { return false } for _, acc := range d.leases { if acc.State() != roster.Member { return false } } return true } // freshStanding masks the request's own Access, latched when the stream // opened, so that whatever is asked about this person on the stream's // behalf — by the hub's re-derivation included — is asked of the roster // now (memberState falls through to standingOf). A long-lived stream // that kept reading its door-time Access could never renew. func freshStanding(ctx context.Context) context.Context { return context.WithValue(ctx, teamReqKey{}, (*teamReq)(nil)) } // teamStreamDecide decides one participation's stream now, on fresh // Accesses. Standing is read before anything else, and a Member answer // always carries a timer (the Slides and Sheets stream-order lesson, // oficina/slides #33 and oficina/sheets #54): a lease that runs out // after it is read gives a one-second timer, never "delivers, nothing to // renew". func (a *app) teamStreamDecide(ctx context.Context, m Meeting, person Person, sqid, session string, peer hub.PeerID) streamDecision { host := a.hostAccess(ctx, m) switch host.State() { case roster.NotMember: a.endForHost(ctx, m) return streamDecision{verdict: streamEnds, end: hub.Message{Type: hub.TypeLost, Reason: hub.ReasonEnded}} case roster.Unknown: return streamDecision{verdict: streamHolds} } leases := []*teammode.Access{host} id, kind, live := a.hub.LiveKindForSession(sqid, session) if !live || id != peer { // The participation has ended (removed, replaced, left): the hub // has put its terminal event on this stream's subscriber, which // is delivered whatever the answer. Until it is read, nothing // else is. return streamDecision{verdict: streamHolds} } if kind == hub.KindMember { own := a.standingOf(ctx, person.ID) switch own.State() { case roster.Unknown: return streamDecision{verdict: streamHolds} case roster.NotMember: ended, err := a.hub.Recheck(ctx, sqid, session, peer) if err == nil && ended { return streamDecision{verdict: streamEnds, end: hub.Message{Type: hub.TypeLost, Reason: hub.ReasonStanding}} } // Unknown by the time the hub asked, or re-derived as a // guest still holding a grant (§2.4): asked again shortly, // as what it now is. return streamDecision{verdict: streamHolds} } leases = append(leases, own) } left := roster.MaximumAge for _, acc := range leases { left = min(left, acc.Remaining()) } renew := min(left, teamStreamRecheckMax) if left < time.Second { // Member when read, run out since: ask again in a second. renew = time.Second } return streamDecision{verdict: streamDelivers, renew: renew, leases: leases} } // serveTeamStream is serveStream in team mode: the same wire, the same // heartbeat, TTL and shutdown, with every delivery decided on standing // (above). first is what the stream owes before the subscriber's events: // the hello is written at once — it names only this browser's own peer // and the process — and the rest (a resume's roster and replay) waits on // a Member answer like everything else. func (a *app) serveTeamStream(w http.ResponseWriter, r *http.Request, sub *hub.Sub, first []hub.Message, m Meeting, person Person, sqid, session string, peer hub.PeerID) { ctx := freshStanding(r.Context()) rc := http.NewResponseController(w) w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-store") w.Header().Set("X-Accel-Buffering", "no") w.WriteHeader(http.StatusOK) if err := rc.Flush(); err != nil { return } if len(first) > 0 && first[0].Type == hub.TypeHello { if !writeEvent(w, rc, first[0]) { return } first = first[1:] } held := append([]hub.Message(nil), first...) heartbeat := time.NewTicker(a.heartbeatEvery()) defer heartbeat.Stop() ttl := time.NewTimer(a.streamLifeFor(r)) defer ttl.Stop() // again fires when this decision is due to be asked again: at its // lease's end while delivering, after teamStreamHoldRetry while held. // It is set when a decision is made and at no other time, so a // heartbeat or a delivery never postpones it. again := time.NewTimer(time.Hour) defer again.Stop() var d streamDecision decide := func() { d = a.teamStreamDecide(ctx, m, person, sqid, session, peer) wait := teamStreamHoldRetry if d.verdict == streamDelivers { wait = d.renew } // Go 1.23 timers: Reset drops any expiry not yet received. again.Reset(wait) } decide() for { // Deliver what is owed, one stand-check per event. for d.verdict == streamDelivers && len(held) > 0 { if !d.stands() { decide() continue } msg := held[0] held = held[1:] if !writeEvent(w, rc, msg) { return } } if d.verdict == streamEnds { writeEvent(w, rc, d.end) return } select { case <-r.Context().Done(): return case <-a.done: return case <-ttl.C: return case <-heartbeat.C: if !writeRaw(w, rc, ": hb\n\n") { return } case <-again.C: decide() case msg, ok := <-sub.C(): if !ok { return } if msg.Type == hub.TypeLost || msg.Type == hub.TypeEnded { // Terminal for this stream, and no call's content: said // whatever the standing (§4.5's reasons). writeEvent(w, rc, msg) return } if len(held) == 0 && d.stands() { if !writeEvent(w, rc, msg) { return } continue } held = append(held, msg) if len(held) > teamStreamHeld { writeEvent(w, rc, hub.Message{Type: hub.TypeLost, Reason: hub.ReasonBuffer}) return } if d.verdict == streamDelivers { // A lease ran out between decisions: decide before // anything more is delivered. decide() } } } }