package calls import ( "bufio" "context" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" "time" "amadan.net/oficina/home/roster" "amadan.net/oficina/home/teammode" "amadan.net/oficina/calls/internal/calls/hub" ) // sseEvent is one event on a call stream; a heartbeat comment is // typ ":". type sseEvent struct { typ string data map[string]any } // callStream is an open GET /m/{sqid}/stream, read on a goroutine. type callStream struct { t *testing.T events chan sseEvent closed chan struct{} cancel context.CancelFunc peer string } // newStreamServer is a real server for f's handler, closed after every // stream the test opens has been cancelled (cleanups run last first, and // Close waits for open requests). func newStreamServer(t *testing.T, f *teamFixture) *httptest.Server { srv := httptest.NewServer(f.handler) t.Cleanup(srv.Close) return srv } // openStream opens a fresh stream for the jar's session against a real // server (an event stream needs one), waits for its hello and returns it. func (f *teamFixture) openStream(srv *httptest.Server, jar map[string]*http.Cookie, sqid string) *callStream { f.t.Helper() s, status := f.tryStream(srv, jar, "/m/"+sqid+"/stream") if status != http.StatusOK { f.t.Fatalf("stream = %d", status) } hello := s.next("hello") s.peer, _ = hello.data["peer"].(string) return s } // tryStream opens path and returns the stream and the status. func (f *teamFixture) tryStream(srv *httptest.Server, jar map[string]*http.Cookie, path string) (*callStream, int) { f.t.Helper() ctx, cancel := context.WithCancel(context.Background()) req, _ := http.NewRequestWithContext(ctx, "GET", srv.URL+path, nil) req.Header.Set("Accept", "text/event-stream") // The instance's own host, as the edge passes it on. req.Host = strings.TrimPrefix(homeTestOrigin, "https://") for _, c := range jar { req.AddCookie(c) } resp, err := srv.Client().Do(req) if err != nil { cancel() f.t.Fatal(err) } s := &callStream{t: f.t, events: make(chan sseEvent, 256), closed: make(chan struct{}), cancel: cancel} f.t.Cleanup(cancel) if resp.StatusCode != http.StatusOK { resp.Body.Close() cancel() return s, resp.StatusCode } go func() { defer close(s.closed) defer resp.Body.Close() r := bufio.NewReader(resp.Body) var typ string for { line, err := r.ReadString('\n') if err != nil { return } line = strings.TrimRight(line, "\n") switch { case strings.HasPrefix(line, ":"): s.events <- sseEvent{typ: ":"} case strings.HasPrefix(line, "event: "): typ = strings.TrimPrefix(line, "event: ") case strings.HasPrefix(line, "data: "): var data map[string]any _ = json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &data) s.events <- sseEvent{typ: typ, data: data} } } }() return s, http.StatusOK } // next waits for the next event of type typ, skipping heartbeats and // anything else, and fails after a few seconds. func (s *callStream) next(typ string) sseEvent { s.t.Helper() deadline := time.After(5 * time.Second) for { select { case e := <-s.events: if e.typ == typ { return e } case <-s.closed: // Whatever was read before the close is still owed. for { select { case e := <-s.events: if e.typ == typ { return e } continue default: } break } s.t.Fatalf("the stream closed waiting for %q", typ) case <-deadline: s.t.Fatalf("no %q within 5 s", typ) } } } // drain reads whatever the stream has already been sent, until it has // been quiet (heartbeats aside) for a moment. func (s *callStream) drain() { quiet := time.NewTimer(100 * time.Millisecond) defer quiet.Stop() for { select { case e := <-s.events: if e.typ != ":" { quiet.Reset(100 * time.Millisecond) } case <-quiet.C: return } } } // quiet fails if anything but heartbeats arrives for d, or the stream // closes, and reports how many heartbeats did. func (s *callStream) quiet(d time.Duration) int { s.t.Helper() beats := 0 deadline := time.After(d) for { select { case e := <-s.events: if e.typ != ":" { s.t.Fatalf("a held stream delivered %q %v", e.typ, e.data) } beats++ case <-s.closed: s.t.Fatal("a held stream closed") case <-deadline: return beats } } } // signal posts one message as jar's session. func (f *teamFixture) signal(jar map[string]*http.Cookie, sqid string, body map[string]any) *httptest.ResponseRecorder { f.t.Helper() raw, _ := json.Marshal(body) saved := f.cookies f.cookies = jar defer func() { f.cookies = saved }() return f.doWith("POST", "/m/"+sqid+"/signal", string(raw), http.Header{"Content-Type": {"application/json"}}) } // join opens a stream and joins: the participation admitted, as a member // (or a guest in a meeting with no waiting room) is. func (f *teamFixture) join(srv *httptest.Server, jar map[string]*http.Cookie, sqid string) *callStream { f.t.Helper() s := f.openStream(srv, jar, sqid) if w := f.signal(jar, sqid, map[string]any{"peer": s.peer, "type": "join"}); w.Code != http.StatusOK { f.t.Fatalf("join = %d %s", w.Code, w.Body.String()) } s.next("roster") return s } // guestJar joins a meeting's link as a named guest and returns their jar. func (f *teamFixture) guestJar(token, name string) map[string]*http.Cookie { f.t.Helper() saved := f.cookies f.cookies = map[string]*http.Cookie{} defer func() { f.cookies = saved }() if w := f.post("/j/"+token+"/guest", "name="+name); w.Code != http.StatusSeeOther { f.t.Fatalf("guest join = %d %s", w.Code, w.Body.String()) } return f.jar() } // fastStreams makes the streams re-decide and beat in milliseconds. func fastStreams(t *testing.T, f *teamFixture) { f.app.heartbeat.Store(int64(20 * time.Millisecond)) holdRetry, recheck := teamStreamHoldRetry, teamStreamRecheckMax teamStreamHoldRetry, teamStreamRecheckMax = 20*time.Millisecond, 40*time.Millisecond t.Cleanup(func() { teamStreamHoldRetry, teamStreamRecheckMax = holdRetry, recheck }) } // A meeting stands on its host. When the roster takes the host off the // team, the call in progress ends for everyone in it (members and guests: // lost{ended}), the meeting is ended and its links revoked, its links // 404 for everyone new, and no grant is minted through them. func TestTeamHostRemovalEndsTheCallAndItsLinks(t *testing.T) { f := newTeamFixture(t) fastStreams(t, f) srv := newStreamServer(t, f) host := teamSubject('h') f.member(host, "member") sqid, token := f.meeting("Host's call") alice := f.jar() f.member(teamSubject('b'), "member") bob := f.jar() gina := f.guestJar(token, "Gina") grants := f.count("guest_grants") aliceS := f.join(srv, alice, sqid) bobS := f.join(srv, bob, sqid) ginaS := f.join(srv, gina, sqid) _ = aliceS f.removed(host) for name, s := range map[string]*callStream{"bob": bobS, "gina": ginaS} { lost := s.next("lost") if lost.data["reason"] != "ended" { t.Fatalf("%s's stream: lost %v, want ended", name, lost.data) } } m := f.meetingRow(sqid) if m.EndedAt == nil || m.EndedBy != hostRemovedActor { t.Fatalf("the meeting was not ended for its host: %+v", m) } if n := f.app.hub.AdmittedCount(sqid); n != 0 { t.Fatalf("the hub still holds %d admitted in the ended call", n) } var live int f.app.db.Writer().QueryRow("SELECT count(*) FROM meeting_links WHERE meeting_id=? AND revoked_at IS NULL", m.ID).Scan(&live) if live != 0 { t.Fatalf("%d links still live", live) } f.cookies = map[string]*http.Cookie{} if w := f.get("/j/" + token); w.Code != http.StatusNotFound { t.Fatalf("a removed host's link = %d", w.Code) } if w := f.post("/j/"+token+"/guest", "name=Late"); w.Code != http.StatusNotFound { t.Fatalf("a removed host's link, as a named guest = %d", w.Code) } if f.count("guest_grants") != grants { t.Fatal("a grant was minted through a removed host's link") } f.cookies = bob if w := f.page("/m/" + sqid + "/join"); w.Code != http.StatusNotFound { t.Fatalf("a member opening the removed host's meeting = %d", w.Code) } if body := f.page("/").Body.String(); !strings.Contains(body, "Ended meetings (1)") { t.Fatalf("the list does not show the meeting ended:\n%s", body) } } // Before anybody touches it, a removed host's meeting is settled where it // is listed: the list shows it ended, never as one that will refuse every // entry. And it is not revived by re-adding the host. func TestTeamListSettlesARemovedHostsMeetings(t *testing.T) { f := newTeamFixture(t) host := teamSubject('o') f.member(host, "member") sqid, _ := f.meeting("Orphaned") f.member(teamSubject('m'), "member") bob := f.jar() f.removed(host) f.cookies = bob if body := f.page("/").Body.String(); !strings.Contains(body, "Ended meetings (1)") { t.Fatalf("the list still offers a removed host's meeting:\n%s", body) } f.dir.Set(host, "member") f.refreshed() if f.meetingRow(sqid).EndedAt == nil { t.Fatal("re-adding the host revived the meeting") } // A meeting whose host stands is untouched by the same listing. f.cookies = bob other, _ := f.meeting("Standing") f.page("/") if f.meetingRow(other).EndedAt != nil { t.Fatal("listing ended a meeting whose host stands") } } // An agent's meeting stands on the agent's operator. func TestTeamAnAgentsMeetingStandsOnItsOperator(t *testing.T) { f := newTeamFixture(t) // Two other people first, so the operator's person id is not the // agent's id. f.member(teamSubject('2'), "member") f.member(teamSubject('3'), "member") op := teamSubject('p') f.member(op, "member") bearer := f.agentToken("maker") w := f.api("POST", "/api/v1/meetings", bearer, `{"title":"By an agent"}`) if w.Code != http.StatusCreated { t.Fatalf("api create = %d", w.Code) } var out struct { Meeting struct{ Sqid string } Link string } json.Unmarshal(w.Body.Bytes(), &out) token := out.Link[strings.LastIndex(out.Link, "/")+1:] f.member(teamSubject('q'), "member") f.removed(op) f.cookies = map[string]*http.Cookie{} if w := f.get("/j/" + token); w.Code != http.StatusNotFound { t.Fatalf("a removed operator's agent's link = %d", w.Code) } if m := f.meetingRow(out.Meeting.Sqid); m.EndedAt == nil { t.Fatal("a removed operator's agent's meeting was not ended") } } // With the host's standing Unknown, nothing new enters — following the // link, joining by name, a fresh stream, an ICE fetch, a signal: each a // retryable 503 — and nothing is ended. The call in progress is held: // its streams stay open, carry heartbeats and deliver nothing. When the // roster is back, the held streams deliver again. func TestTeamHostUnknownRefusesEntriesAndHoldsTheCall(t *testing.T) { f := newTeamFixture(t) fastStreams(t, f) srv := newStreamServer(t, f) f.member(teamSubject('h'), "member") sqid, token := f.meeting("Held") alice := f.jar() f.member(teamSubject('b'), "member") bob := f.jar() gina := f.guestJar(token, "Gina") aliceS := f.join(srv, alice, sqid) bobS := f.join(srv, bob, sqid) ginaS := f.join(srv, gina, sqid) f.member(teamSubject('c'), "member") carol := f.jar() for _, s := range []*callStream{aliceS, bobS, ginaS} { s.drain() } // A visitor who followed the link before the roster went away. f.cookies = map[string]*http.Cookie{} f.page("/j/" + token) visitor := f.jar() f.expired() f.cookies = visitor // The sign-in form under that cookie: a retryable 503 — not "check // your email" with no mail behind it — and no pending row, no mail. retryable(t, "signing in through the link", f.post("/signin", "address=outsider%40example.test")) if n := f.count("pending_joins"); n != 0 { t.Fatalf("a link on an undecidable host wrote %d pending joins", n) } if body := f.mailBody(); body != "" { t.Fatalf("a link on an undecidable host mailed:\n%s", body) } f.cookies = map[string]*http.Cookie{} retryable(t, "following the link", f.page("/j/"+token)) retryable(t, "joining by name", f.post("/j/"+token+"/guest", "name=Late")) if _, status := f.tryStream(srv, carol, "/m/"+sqid+"/stream"); status != http.StatusServiceUnavailable { t.Fatalf("a fresh stream under Unknown = %d", status) } f.cookies = bob retryable(t, "ICE for a member", f.get("/m/"+sqid+"/ice?peer="+bobS.peer)) f.cookies = gina retryable(t, "ICE for a guest", f.get("/m/"+sqid+"/ice?peer="+ginaS.peer)) retryable(t, "a member's chat", f.signal(bob, sqid, map[string]any{"peer": bobS.peer, "type": "chat", "payload": map[string]any{"text": "hello?"}})) retryable(t, "a guest's chat", f.signal(gina, sqid, map[string]any{"peer": ginaS.peer, "type": "chat", "payload": map[string]any{"text": "hello?"}})) // Leaving is always allowed. for _, s := range []*callStream{aliceS, bobS, ginaS} { if beats := s.quiet(200 * time.Millisecond); beats == 0 { t.Fatal("a held stream carried no heartbeat") } } f.app.hub.Tick(context.Background()) if f.meetingRow(sqid).EndedAt != nil { t.Fatal("Unknown ended the meeting") } // A stream that drops while held (its TTL, the network) resumes into // a held stream: its probe says it may, the resume attaches and says // hello, and nothing else is delivered — not even the roster a resume // owes — until standing is known again. bobS.cancel() time.Sleep(50 * time.Millisecond) f.cookies = bob if w := f.get("/m/" + sqid + "/stream?probe=1&peer=" + bobS.peer); w.Code != http.StatusNoContent { t.Fatalf("the resume probe under Unknown = %d %s", w.Code, w.Body.String()) } resumed, status := f.tryStream(srv, bob, "/m/"+sqid+"/stream?peer="+bobS.peer+"&last=%7B%7D") if status != http.StatusOK { t.Fatalf("a resume under Unknown = %d", status) } resumed.next("hello") resumed.quiet(150 * time.Millisecond) f.refreshed() if r := resumed.next("roster"); r.data["roster"] == nil { t.Fatalf("the resume's roster after recovery: %v", r.data) } bobS = resumed if w := f.signal(gina, sqid, map[string]any{"peer": ginaS.peer, "type": "chat", "payload": map[string]any{"text": "back"}}); w.Code != http.StatusOK { t.Fatalf("a guest's chat after recovery = %d %s", w.Code, w.Body.String()) } for name, s := range map[string]*callStream{"alice": aliceS, "bob": bobS} { if chat := s.next("chat"); chat.data["payload"].(map[string]any)["text"] != "back" { t.Fatalf("%s got %v", name, chat.data) } } if w := f.signal(gina, sqid, map[string]any{"peer": ginaS.peer, "type": "leave"}); w.Code != http.StatusOK { t.Fatalf("leave = %d", w.Code) } } // A held stream delivers nothing published while it is held — here, a // chat a guest's request put on the hub after its own gate, as the lease // ran out — and delivers it, in order, once a Member answer says it may. func TestTeamHeldStreamDeliversNothingUntilStandingReturns(t *testing.T) { f := newTeamFixture(t) fastStreams(t, f) srv := newStreamServer(t, f) f.member(teamSubject('h'), "member") sqid, token := f.meeting("Held delivery") alice := f.jar() gina := f.guestJar(token, "Gina") aliceS := f.join(srv, alice, sqid) ginaS := f.join(srv, gina, sqid) aliceS.drain() f.expired() ginaSession := "" for _, c := range gina { if c.Name == f.app.auth.SessionCookie() { ginaSession = hubSessionKey(f.app.hubSalt, sessionSubject(t, f, gina), c.Value) } } for _, text := range []string{"one", "two"} { payload, _ := json.Marshal(map[string]string{"text": text}) if err := f.app.hub.Fanout(context.Background(), sqid, ginaSession, hub.PeerID(ginaS.peer), hub.Message{Type: hub.TypeChat, Payload: payload}); err != nil { t.Fatalf("fan out while held: %v", err) } } aliceS.quiet(150 * time.Millisecond) f.refreshed() for _, want := range []string{"one", "two"} { if chat := aliceS.next("chat"); chat.data["payload"].(map[string]any)["text"] != want { t.Fatalf("caught up out of order: %v", chat.data) } } } // sessionSubject is the session subject a jar's session carries. func sessionSubject(t *testing.T, f *teamFixture, jar map[string]*http.Cookie) string { t.Helper() r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) for _, c := range jar { r.AddCookie(c) } id, ok := f.app.auth.SessionFrom(r) if !ok { t.Fatal("no session in the jar") } return id.Address } // A member the roster removes is ended within the lease, live session // included: their stream is told lost{standing}, the room is told they // have gone, and their next request is signed out. The host and the call // carry on. func TestTeamRemovalEndsAMembersLiveSession(t *testing.T) { f := newTeamFixture(t) fastStreams(t, f) srv := newStreamServer(t, f) f.member(teamSubject('h'), "member") sqid, _ := f.meeting("Ongoing") alice := f.jar() bobSubject := teamSubject('b') f.member(bobSubject, "member") f.signInHome(bobSubject) bob := f.jar() aliceS := f.join(srv, alice, sqid) bobS := f.join(srv, bob, sqid) aliceS.next("peer") f.removed(bobSubject) if lost := bobS.next("lost"); lost.data["reason"] != "standing" { t.Fatalf("the removed member's stream: %v", lost.data) } if gone := aliceS.next("gone"); gone.data["from"] != bobS.peer { t.Fatalf("the room was told %v", gone.data) } f.cookies = bob signedOutRemoved(t, "the removed member's ICE fetch", f.get("/m/"+sqid+"/ice?peer="+bobS.peer)) if f.meetingRow(sqid).EndedAt != nil { t.Fatal("a member's removal ended the host's meeting") } } // The stream-order lesson (oficina/slides #33, oficina/sheets #54): swept // across the lease's end, with a roster clock that ticks on every reading, // a decision is never "delivers, with nothing to renew" — every delivering // answer carries a timer of at least a second — and a lease that ran out // after the decision never stands for a delivery. func TestTeamStreamDecisionNeverDeliversWithoutALease(t *testing.T) { sawDeliver, sawHold := false, false for k := 1; k <= 30; k++ { f := newTeamFixture(t) srv := newStreamServer(t, f) subject := teamSubject('h') p := f.member(subject, "member") sqid, _ := f.meeting("Swept") s := f.join(srv, f.jar(), sqid) m := f.meetingRow(sqid) session := "" for _, c := range f.cookies { if c.Name == f.app.auth.SessionCookie() { session = hubSessionKey(f.app.hubSalt, subject, c.Value) } } f.refreshed() f.dir.SetDown(true) f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) f.clock.SetTick(time.Millisecond) d := f.app.teamStreamDecide(freshStanding(context.Background()), m, p, sqid, session, hub.PeerID(s.peer)) switch d.verdict { case streamDelivers: sawDeliver = true if d.renew < time.Second || len(d.leases) == 0 { t.Fatalf("k=%d: delivers with renew %v on %d leases", k, d.renew, len(d.leases)) } case streamHolds: sawHold = true default: t.Fatalf("k=%d: Unknown ended the stream", k) } f.clock.SetTick(0) f.clock.Step(roster.MaximumAge) if d.stands() { t.Fatalf("k=%d: a lapsed lease still stands for a delivery", k) } s.cancel() } if !sawDeliver || !sawHold { t.Fatalf("the sweep did not cross the lease's end: deliver %v hold %v", sawDeliver, sawHold) } } // A knock's push goes only to people the roster says are Members when it // is sent: never to a removed member, never under Unknown. func TestTeamKnockPushGoesOnlyToCurrentMembers(t *testing.T) { f := newTeamFixture(t) push := &recordingPusher{} f.app.push = push alice := teamSubject('a') f.member(alice, "member") if w := f.json("/native/devices", `{"token":"aa01","platform":"ios"}`); w.Code != http.StatusNoContent { t.Fatalf("alice's device = %d", w.Code) } bob := teamSubject('b') f.member(bob, "member") if w := f.json("/native/devices", `{"token":"bb02","platform":"macos"}`); w.Code != http.StatusNoContent { t.Fatalf("bob's device = %d", w.Code) } f.removed(bob) f.app.knocked("room", nil, "Gina") if got := push.all(); len(got) != 1 || !strings.HasPrefix(got[0], "aa01|") { t.Fatalf("pushed %v, want alice's device only", got) } f.expired() f.app.knocked("room", nil, "Gina") if got := push.all(); len(got) != 1 { t.Fatalf("pushed under Unknown: %v", got) } // No push key: nothing breaks, nothing is sent. f.app.push = nil f.refreshed() f.app.knocked("room", nil, "Gina") } // The drive surface stands on the agent's operator, asked on every // request: removed, the one not-found body; Unknown, a retryable 503; // back on the team, it works again. func TestTeamAgentStandsOnItsOperator(t *testing.T) { f := newTeamFixture(t) op := teamSubject('o') f.member(op, "member") bearer := f.agentToken("bot") if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusOK { t.Fatalf("member's agent = %d", w.Code) } f.member(teamSubject('q'), "member") sqid, _ := f.meeting("Somebody's") // And one already over, which no host check would refuse: only the // gate's own answer for the operator stands between it and a 200. over, _ := f.meeting("Over") if w := f.post("/meetings/"+over+"/end", ""); w.Code != http.StatusSeeOther { t.Fatalf("end = %d", w.Code) } f.expired() if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" || w.Header().Get("Cache-Control") != "no-store" { t.Fatalf("operator Unknown = %d", w.Code) } // An item, too: a meeting another member made. for _, item := range []string{sqid, over} { if w := f.api("GET", "/api/v1/meetings/"+item, bearer, ""); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" || w.Header().Get("Cache-Control") != "no-store" { t.Fatalf("an item under an Unknown operator = %d %s", w.Code, w.Body.String()) } } f.removed(op) if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusNotFound || !strings.Contains(w.Body.String(), "not-found") { t.Fatalf("operator removed = %d %s", w.Code, w.Body.String()) } f.dir.Set(op, "member") f.refreshed() if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusOK { t.Fatalf("operator re-added = %d", w.Code) } } // standingOf for somebody the roster cannot be asked about is NotMember; // for storage that cannot be read, Unknown. func TestTeamStandingOfSomebodyElse(t *testing.T) { f := newTeamFixture(t) p := f.member(teamSubject('s'), "member") if st := f.app.standingOf(context.Background(), p.ID).State(); st != roster.Member { t.Fatalf("a member = %v", st) } if st := f.app.standingOf(context.Background(), 999).State(); st != roster.NotMember { t.Fatalf("nobody = %v", st) } f.app.db.Writer().Exec("ALTER TABLE calls_team_home_persons RENAME TO unreadable") if st := f.app.standingOf(context.Background(), p.ID).State(); st != roster.Unknown { t.Fatalf("unreadable = %v", st) } var acc *teammode.Access if acc.State() != roster.Unknown { t.Fatal("a nil Access is not Unknown") } } // Before anybody has touched it, a removed host's link is already dead: // to a visitor following it (who is shown no title), to a sign-in it // would carry (no pending join is written, so no mail is owed), and the // meeting is ended by the first of them. func TestTeamARemovedHostsLinkIsDeadBeforeAnyoneTouchesIt(t *testing.T) { f := newTeamFixture(t) host := teamSubject('k') f.member(host, "member") sqid, token := f.meeting("Secret title") // A visitor followed the link while the host stood: the join cookie // the sign-in form reads. f.cookies = map[string]*http.Cookie{} if w := f.page("/j/" + token); w.Code != http.StatusOK { t.Fatalf("the link while the host stands = %d", w.Code) } visitor := f.jar() f.removed(host) f.cookies = visitor if w := f.post("/signin", "address=outsider%40example.test"); w.Code != http.StatusSeeOther { t.Fatalf("sign-in = %d", w.Code) } if n := f.count("pending_joins"); n != 0 { t.Fatalf("a removed host's link wrote %d pending joins", n) } f.cookies = map[string]*http.Cookie{} persons := f.count("persons") if w := f.post("/j/"+token+"/guest", "name=Late"); w.Code != http.StatusNotFound { t.Fatalf("a removed host's link, joining by name = %d", w.Code) } if f.count("persons") != persons || f.count("guest_grants") != 0 { t.Fatal("a removed host's link made a guest") } w := f.page("/j/" + token) if w.Code != http.StatusNotFound || strings.Contains(w.Body.String(), "Secret title") { t.Fatalf("a removed host's link = %d", w.Code) } if f.meetingRow(sqid).EndedAt == nil { t.Fatal("following a removed host's link did not end the meeting") } } // The quiet case (spec §2.4's tick): with nobody's stream re-deciding, // the hub's own pass ends a removed host's call, and a member opening // another of that host's meetings, untouched until now, finds it ended. func TestTeamTheTickEndsAQuietCallWhoseHostLeft(t *testing.T) { f := newTeamFixture(t) srv := newStreamServer(t, f) host := teamSubject('t') f.member(host, "member") sqid, token := f.meeting("Quiet") other, _ := f.meeting("Untouched") alice := f.jar() f.member(teamSubject('u'), "member") bob := f.jar() gina := f.guestJar(token, "Gina") f.join(srv, alice, sqid) bobS := f.join(srv, bob, sqid) ginaS := f.join(srv, gina, sqid) f.removed(host) f.app.hub.Tick(context.Background()) for _, s := range []*callStream{bobS, ginaS} { if lost := s.next("lost"); lost.data["reason"] != "ended" { t.Fatalf("after the tick: %v", lost.data) } } f.cookies = bob if w := f.page("/m/" + other + "/join"); w.Code != http.StatusNotFound { t.Fatalf("a removed host's untouched meeting = %d", w.Code) } if f.meetingRow(other).EndedAt == nil { t.Fatal("opening it did not end it") } } // Swept across the lease's end with a roster clock that ticks on every // reading — so that a host asked a moment later can still stand while the // request's own standing has run out — every answer is either what a // member gets or a retryable 503: never "not found", never a 500, and // never a grant for a member who needs none. func TestTeamAnswersAcrossTheLeaseEdgeAreWholeOrRetryable(t *testing.T) { retries := 0 for k := 1; k <= 30; k++ { f := newTeamFixture(t) srv := newStreamServer(t, f) f.member(teamSubject('h'), "member") sqid, token := f.meeting("Edge") host := f.jar() s := f.join(srv, host, sqid) s.drain() f.member(teamSubject('m'), "member") member := f.jar() link, _, _, _ := f.app.store.liveLink(context.Background(), token) edge := func() { f.refreshed() f.dir.SetDown(true) f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond) f.clock.SetTick(time.Millisecond) } check := func(what string, w *httptest.ResponseRecorder, ok ...int) { t.Helper() for _, c := range ok { if w.Code == c { return } } if w.Code == http.StatusServiceUnavailable { retryable(t, what, w) retries++ return } t.Fatalf("k=%d %s = %d %s", k, what, w.Code, w.Body.String()) } f.cookies = member edge() check("the holding screen", f.page("/m/"+sqid+"/join"), http.StatusOK) f.clock.SetTick(0) edge() check("a member follows the link", f.page("/j/"+token), http.StatusSeeOther) f.clock.SetTick(0) f.app.store.writePending(context.Background(), f.personFor(teamSubject('m')).Email, link) edge() check("a member's pending join", f.page("/continue"), http.StatusSeeOther) f.clock.SetTick(0) edge() check("a chat", f.signal(host, sqid, map[string]any{"peer": s.peer, "type": "chat", "payload": map[string]any{"text": "x"}}), http.StatusOK) f.clock.SetTick(0) if n := f.count("guest_grants"); n != 0 { t.Fatalf("k=%d: a member was given %d grants", k, n) } s.cancel() } if retries == 0 { t.Fatal("the sweep never reached the lease's end") } } // A held stream keeps what arrives, in order, but no more than a // subscriber's buffer: past it the stream ends lost{buffer}, and the // browser resumes. func TestTeamHeldStreamEndsPastTheBuffer(t *testing.T) { f := newTeamFixture(t) fastStreams(t, f) srv := newStreamServer(t, f) f.member(teamSubject('h'), "member") sqid, token := f.meeting("Overflow") alice := f.jar() gina := f.guestJar(token, "Gina") aliceS := f.join(srv, alice, sqid) ginaS := f.join(srv, gina, sqid) aliceS.drain() f.expired() session := "" for _, c := range gina { if c.Name == f.app.auth.SessionCookie() { session = hubSessionKey(f.app.hubSalt, sessionSubject(t, f, gina), c.Value) } } payload, _ := json.Marshal(map[string]string{"text": "x"}) for range teamStreamHeld + 2 { f.app.hub.Fanout(context.Background(), sqid, session, hub.PeerID(ginaS.peer), hub.Message{Type: hub.TypeChat, Payload: payload}) // Slowly enough that the stream reads each one off the hub, so // it is the held stream's own bound that is reached, not the // hub's buffer for a subscriber that is not reading. time.Sleep(2 * time.Millisecond) } if lost := aliceS.next("lost"); lost.data["reason"] != "buffer" { t.Fatalf("an overflowing held stream: %v", lost.data) } } // What ends a stream is said at once even while it is held: a second tab // resuming the same participation replaces the held one, which is told so // and closes, rather than holding the news until standing returns. func TestTeamHeldStreamIsToldItWasReplaced(t *testing.T) { f := newTeamFixture(t) fastStreams(t, f) srv := newStreamServer(t, f) f.member(teamSubject('h'), "member") sqid, _ := f.meeting("Replaced") alice := f.jar() first := f.join(srv, alice, sqid) first.drain() f.expired() second, status := f.tryStream(srv, alice, "/m/"+sqid+"/stream?peer="+first.peer+"&last=%7B%7D") if status != http.StatusOK { t.Fatalf("the second tab's resume = %d", status) } second.next("hello") if lost := first.next("lost"); lost.data["reason"] != "replaced" { t.Fatalf("the held stream was told %v", lost.data) } }