oficina / meet Public

Clone
git clone https://amadan.net/oficina/meet

Plain git — no account needed to clone.

Download

Download this file

1package calls
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "net/http"
8 "net/http/httptest"
9 "strings"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/home/roster"
14 "amadan.net/oficina/home/teammode"
15
16 "amadan.net/oficina/calls/internal/calls/hub"
17)
18
19// sseEvent is one event on a call stream; a heartbeat comment is
20// typ ":".
21type sseEvent struct {
22 typ string
23 data map[string]any
24}
25
26// callStream is an open GET /m/{sqid}/stream, read on a goroutine.
27type callStream struct {
28 t *testing.T
29 events chan sseEvent
30 closed chan struct{}
31 cancel context.CancelFunc
32 peer string
33}
34
35// newStreamServer is a real server for f's handler, closed after every
36// stream the test opens has been cancelled (cleanups run last first, and
37// Close waits for open requests).
38func newStreamServer(t *testing.T, f *teamFixture) *httptest.Server {
39 srv := httptest.NewServer(f.handler)
40 t.Cleanup(srv.Close)
41 return srv
42}
43
44// openStream opens a fresh stream for the jar's session against a real
45// server (an event stream needs one), waits for its hello and returns it.
46func (f *teamFixture) openStream(srv *httptest.Server, jar map[string]*http.Cookie, sqid string) *callStream {
47 f.t.Helper()
48 s, status := f.tryStream(srv, jar, "/m/"+sqid+"/stream")
49 if status != http.StatusOK {
50 f.t.Fatalf("stream = %d", status)
51 }
52 hello := s.next("hello")
53 s.peer, _ = hello.data["peer"].(string)
54 return s
55}
56
57// tryStream opens path and returns the stream and the status.
58func (f *teamFixture) tryStream(srv *httptest.Server, jar map[string]*http.Cookie, path string) (*callStream, int) {
59 f.t.Helper()
60 ctx, cancel := context.WithCancel(context.Background())
61 req, _ := http.NewRequestWithContext(ctx, "GET", srv.URL+path, nil)
62 req.Header.Set("Accept", "text/event-stream")
63 // The instance's own host, as the edge passes it on.
64 req.Host = strings.TrimPrefix(homeTestOrigin, "https://")
65 for _, c := range jar {
66 req.AddCookie(c)
67 }
68 resp, err := srv.Client().Do(req)
69 if err != nil {
70 cancel()
71 f.t.Fatal(err)
72 }
73 s := &callStream{t: f.t, events: make(chan sseEvent, 256), closed: make(chan struct{}), cancel: cancel}
74 f.t.Cleanup(cancel)
75 if resp.StatusCode != http.StatusOK {
76 resp.Body.Close()
77 cancel()
78 return s, resp.StatusCode
79 }
80 go func() {
81 defer close(s.closed)
82 defer resp.Body.Close()
83 r := bufio.NewReader(resp.Body)
84 var typ string
85 for {
86 line, err := r.ReadString('\n')
87 if err != nil {
88 return
89 }
90 line = strings.TrimRight(line, "\n")
91 switch {
92 case strings.HasPrefix(line, ":"):
93 s.events <- sseEvent{typ: ":"}
94 case strings.HasPrefix(line, "event: "):
95 typ = strings.TrimPrefix(line, "event: ")
96 case strings.HasPrefix(line, "data: "):
97 var data map[string]any
98 _ = json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &data)
99 s.events <- sseEvent{typ: typ, data: data}
100 }
101 }
102 }()
103 return s, http.StatusOK
104}
105
106// next waits for the next event of type typ, skipping heartbeats and
107// anything else, and fails after a few seconds.
108func (s *callStream) next(typ string) sseEvent {
109 s.t.Helper()
110 deadline := time.After(5 * time.Second)
111 for {
112 select {
113 case e := <-s.events:
114 if e.typ == typ {
115 return e
116 }
117 case <-s.closed:
118 // Whatever was read before the close is still owed.
119 for {
120 select {
121 case e := <-s.events:
122 if e.typ == typ {
123 return e
124 }
125 continue
126 default:
127 }
128 break
129 }
130 s.t.Fatalf("the stream closed waiting for %q", typ)
131 case <-deadline:
132 s.t.Fatalf("no %q within 5 s", typ)
133 }
134 }
135}
136
137// drain reads whatever the stream has already been sent, until it has
138// been quiet (heartbeats aside) for a moment.
139func (s *callStream) drain() {
140 quiet := time.NewTimer(100 * time.Millisecond)
141 defer quiet.Stop()
142 for {
143 select {
144 case e := <-s.events:
145 if e.typ != ":" {
146 quiet.Reset(100 * time.Millisecond)
147 }
148 case <-quiet.C:
149 return
150 }
151 }
152}
153
154// quiet fails if anything but heartbeats arrives for d, or the stream
155// closes, and reports how many heartbeats did.
156func (s *callStream) quiet(d time.Duration) int {
157 s.t.Helper()
158 beats := 0
159 deadline := time.After(d)
160 for {
161 select {
162 case e := <-s.events:
163 if e.typ != ":" {
164 s.t.Fatalf("a held stream delivered %q %v", e.typ, e.data)
165 }
166 beats++
167 case <-s.closed:
168 s.t.Fatal("a held stream closed")
169 case <-deadline:
170 return beats
171 }
172 }
173}
174
175// signal posts one message as jar's session.
176func (f *teamFixture) signal(jar map[string]*http.Cookie, sqid string, body map[string]any) *httptest.ResponseRecorder {
177 f.t.Helper()
178 raw, _ := json.Marshal(body)
179 saved := f.cookies
180 f.cookies = jar
181 defer func() { f.cookies = saved }()
182 return f.doWith("POST", "/m/"+sqid+"/signal", string(raw), http.Header{"Content-Type": {"application/json"}})
183}
184
185// join opens a stream and joins: the participation admitted, as a member
186// (or a guest in a meeting with no waiting room) is.
187func (f *teamFixture) join(srv *httptest.Server, jar map[string]*http.Cookie, sqid string) *callStream {
188 f.t.Helper()
189 s := f.openStream(srv, jar, sqid)
190 if w := f.signal(jar, sqid, map[string]any{"peer": s.peer, "type": "join"}); w.Code != http.StatusOK {
191 f.t.Fatalf("join = %d %s", w.Code, w.Body.String())
192 }
193 s.next("roster")
194 return s
195}
196
197// guestJar joins a meeting's link as a named guest and returns their jar.
198func (f *teamFixture) guestJar(token, name string) map[string]*http.Cookie {
199 f.t.Helper()
200 saved := f.cookies
201 f.cookies = map[string]*http.Cookie{}
202 defer func() { f.cookies = saved }()
203 if w := f.post("/j/"+token+"/guest", "name="+name); w.Code != http.StatusSeeOther {
204 f.t.Fatalf("guest join = %d %s", w.Code, w.Body.String())
205 }
206 return f.jar()
207}
208
209// fastStreams makes the streams re-decide and beat in milliseconds.
210func fastStreams(t *testing.T, f *teamFixture) {
211 f.app.heartbeat.Store(int64(20 * time.Millisecond))
212 holdRetry, recheck := teamStreamHoldRetry, teamStreamRecheckMax
213 teamStreamHoldRetry, teamStreamRecheckMax = 20*time.Millisecond, 40*time.Millisecond
214 t.Cleanup(func() { teamStreamHoldRetry, teamStreamRecheckMax = holdRetry, recheck })
215}
216
217// A meeting stands on its host. When the roster takes the host off the
218// team, the call in progress ends for everyone in it (members and guests:
219// lost{ended}), the meeting is ended and its links revoked, its links
220// 404 for everyone new, and no grant is minted through them.
221func TestTeamHostRemovalEndsTheCallAndItsLinks(t *testing.T) {
222 f := newTeamFixture(t)
223 fastStreams(t, f)
224 srv := newStreamServer(t, f)
225 host := teamSubject('h')
226 f.member(host, "member")
227 sqid, token := f.meeting("Host's call")
228 alice := f.jar()
229 f.member(teamSubject('b'), "member")
230 bob := f.jar()
231 gina := f.guestJar(token, "Gina")
232 grants := f.count("guest_grants")
233 aliceS := f.join(srv, alice, sqid)
234 bobS := f.join(srv, bob, sqid)
235 ginaS := f.join(srv, gina, sqid)
236 _ = aliceS
237
238 f.removed(host)
239 for name, s := range map[string]*callStream{"bob": bobS, "gina": ginaS} {
240 lost := s.next("lost")
241 if lost.data["reason"] != "ended" {
242 t.Fatalf("%s's stream: lost %v, want ended", name, lost.data)
243 }
244 }
245 m := f.meetingRow(sqid)
246 if m.EndedAt == nil || m.EndedBy != hostRemovedActor {
247 t.Fatalf("the meeting was not ended for its host: %+v", m)
248 }
249 if n := f.app.hub.AdmittedCount(sqid); n != 0 {
250 t.Fatalf("the hub still holds %d admitted in the ended call", n)
251 }
252 var live int
253 f.app.db.Writer().QueryRow("SELECT count(*) FROM meeting_links WHERE meeting_id=? AND revoked_at IS NULL", m.ID).Scan(&live)
254 if live != 0 {
255 t.Fatalf("%d links still live", live)
256 }
257 f.cookies = map[string]*http.Cookie{}
258 if w := f.get("/j/" + token); w.Code != http.StatusNotFound {
259 t.Fatalf("a removed host's link = %d", w.Code)
260 }
261 if w := f.post("/j/"+token+"/guest", "name=Late"); w.Code != http.StatusNotFound {
262 t.Fatalf("a removed host's link, as a named guest = %d", w.Code)
263 }
264 if f.count("guest_grants") != grants {
265 t.Fatal("a grant was minted through a removed host's link")
266 }
267 f.cookies = bob
268 if w := f.page("/m/" + sqid + "/join"); w.Code != http.StatusNotFound {
269 t.Fatalf("a member opening the removed host's meeting = %d", w.Code)
270 }
271 if body := f.page("/").Body.String(); !strings.Contains(body, "Ended meetings (1)") {
272 t.Fatalf("the list does not show the meeting ended:\n%s", body)
273 }
274}
275
276// Before anybody touches it, a removed host's meeting is settled where it
277// is listed: the list shows it ended, never as one that will refuse every
278// entry. And it is not revived by re-adding the host.
279func TestTeamListSettlesARemovedHostsMeetings(t *testing.T) {
280 f := newTeamFixture(t)
281 host := teamSubject('o')
282 f.member(host, "member")
283 sqid, _ := f.meeting("Orphaned")
284 f.member(teamSubject('m'), "member")
285 bob := f.jar()
286 f.removed(host)
287 f.cookies = bob
288 if body := f.page("/").Body.String(); !strings.Contains(body, "Ended meetings (1)") {
289 t.Fatalf("the list still offers a removed host's meeting:\n%s", body)
290 }
291 f.dir.Set(host, "member")
292 f.refreshed()
293 if f.meetingRow(sqid).EndedAt == nil {
294 t.Fatal("re-adding the host revived the meeting")
295 }
296 // A meeting whose host stands is untouched by the same listing.
297 f.cookies = bob
298 other, _ := f.meeting("Standing")
299 f.page("/")
300 if f.meetingRow(other).EndedAt != nil {
301 t.Fatal("listing ended a meeting whose host stands")
302 }
303}
304
305// An agent's meeting stands on the agent's operator.
306func TestTeamAnAgentsMeetingStandsOnItsOperator(t *testing.T) {
307 f := newTeamFixture(t)
308 // Two other people first, so the operator's person id is not the
309 // agent's id.
310 f.member(teamSubject('2'), "member")
311 f.member(teamSubject('3'), "member")
312 op := teamSubject('p')
313 f.member(op, "member")
314 bearer := f.agentToken("maker")
315 w := f.api("POST", "/api/v1/meetings", bearer, `{"title":"By an agent"}`)
316 if w.Code != http.StatusCreated {
317 t.Fatalf("api create = %d", w.Code)
318 }
319 var out struct {
320 Meeting struct{ Sqid string }
321 Link string
322 }
323 json.Unmarshal(w.Body.Bytes(), &out)
324 token := out.Link[strings.LastIndex(out.Link, "/")+1:]
325 f.member(teamSubject('q'), "member")
326 f.removed(op)
327 f.cookies = map[string]*http.Cookie{}
328 if w := f.get("/j/" + token); w.Code != http.StatusNotFound {
329 t.Fatalf("a removed operator's agent's link = %d", w.Code)
330 }
331 if m := f.meetingRow(out.Meeting.Sqid); m.EndedAt == nil {
332 t.Fatal("a removed operator's agent's meeting was not ended")
333 }
334}
335
336// With the host's standing Unknown, nothing new enters — following the
337// link, joining by name, a fresh stream, an ICE fetch, a signal: each a
338// retryable 503 — and nothing is ended. The call in progress is held:
339// its streams stay open, carry heartbeats and deliver nothing. When the
340// roster is back, the held streams deliver again.
341func TestTeamHostUnknownRefusesEntriesAndHoldsTheCall(t *testing.T) {
342 f := newTeamFixture(t)
343 fastStreams(t, f)
344 srv := newStreamServer(t, f)
345 f.member(teamSubject('h'), "member")
346 sqid, token := f.meeting("Held")
347 alice := f.jar()
348 f.member(teamSubject('b'), "member")
349 bob := f.jar()
350 gina := f.guestJar(token, "Gina")
351 aliceS := f.join(srv, alice, sqid)
352 bobS := f.join(srv, bob, sqid)
353 ginaS := f.join(srv, gina, sqid)
354 f.member(teamSubject('c'), "member")
355 carol := f.jar()
356 for _, s := range []*callStream{aliceS, bobS, ginaS} {
357 s.drain()
358 }
359
360 // A visitor who followed the link before the roster went away.
361 f.cookies = map[string]*http.Cookie{}
362 f.page("/j/" + token)
363 visitor := f.jar()
364 f.expired()
365 f.cookies = visitor
366 // The sign-in form under that cookie: a retryable 503 — not "check
367 // your email" with no mail behind it — and no pending row, no mail.
368 retryable(t, "signing in through the link", f.post("/signin", "address=outsider%40example.test"))
369 if n := f.count("pending_joins"); n != 0 {
370 t.Fatalf("a link on an undecidable host wrote %d pending joins", n)
371 }
372 if body := f.mailBody(); body != "" {
373 t.Fatalf("a link on an undecidable host mailed:\n%s", body)
374 }
375 f.cookies = map[string]*http.Cookie{}
376 retryable(t, "following the link", f.page("/j/"+token))
377 retryable(t, "joining by name", f.post("/j/"+token+"/guest", "name=Late"))
378 if _, status := f.tryStream(srv, carol, "/m/"+sqid+"/stream"); status != http.StatusServiceUnavailable {
379 t.Fatalf("a fresh stream under Unknown = %d", status)
380 }
381 f.cookies = bob
382 retryable(t, "ICE for a member", f.get("/m/"+sqid+"/ice?peer="+bobS.peer))
383 f.cookies = gina
384 retryable(t, "ICE for a guest", f.get("/m/"+sqid+"/ice?peer="+ginaS.peer))
385 retryable(t, "a member's chat", f.signal(bob, sqid, map[string]any{"peer": bobS.peer, "type": "chat", "payload": map[string]any{"text": "hello?"}}))
386 retryable(t, "a guest's chat", f.signal(gina, sqid, map[string]any{"peer": ginaS.peer, "type": "chat", "payload": map[string]any{"text": "hello?"}}))
387 // Leaving is always allowed.
388 for _, s := range []*callStream{aliceS, bobS, ginaS} {
389 if beats := s.quiet(200 * time.Millisecond); beats == 0 {
390 t.Fatal("a held stream carried no heartbeat")
391 }
392 }
393 f.app.hub.Tick(context.Background())
394 if f.meetingRow(sqid).EndedAt != nil {
395 t.Fatal("Unknown ended the meeting")
396 }
397 // A stream that drops while held (its TTL, the network) resumes into
398 // a held stream: its probe says it may, the resume attaches and says
399 // hello, and nothing else is delivered — not even the roster a resume
400 // owes — until standing is known again.
401 bobS.cancel()
402 time.Sleep(50 * time.Millisecond)
403 f.cookies = bob
404 if w := f.get("/m/" + sqid + "/stream?probe=1&peer=" + bobS.peer); w.Code != http.StatusNoContent {
405 t.Fatalf("the resume probe under Unknown = %d %s", w.Code, w.Body.String())
406 }
407 resumed, status := f.tryStream(srv, bob, "/m/"+sqid+"/stream?peer="+bobS.peer+"&last=%7B%7D")
408 if status != http.StatusOK {
409 t.Fatalf("a resume under Unknown = %d", status)
410 }
411 resumed.next("hello")
412 resumed.quiet(150 * time.Millisecond)
413
414 f.refreshed()
415 if r := resumed.next("roster"); r.data["roster"] == nil {
416 t.Fatalf("the resume's roster after recovery: %v", r.data)
417 }
418 bobS = resumed
419 if w := f.signal(gina, sqid, map[string]any{"peer": ginaS.peer, "type": "chat", "payload": map[string]any{"text": "back"}}); w.Code != http.StatusOK {
420 t.Fatalf("a guest's chat after recovery = %d %s", w.Code, w.Body.String())
421 }
422 for name, s := range map[string]*callStream{"alice": aliceS, "bob": bobS} {
423 if chat := s.next("chat"); chat.data["payload"].(map[string]any)["text"] != "back" {
424 t.Fatalf("%s got %v", name, chat.data)
425 }
426 }
427 if w := f.signal(gina, sqid, map[string]any{"peer": ginaS.peer, "type": "leave"}); w.Code != http.StatusOK {
428 t.Fatalf("leave = %d", w.Code)
429 }
430}
431
432// A held stream delivers nothing published while it is held — here, a
433// chat a guest's request put on the hub after its own gate, as the lease
434// ran out — and delivers it, in order, once a Member answer says it may.
435func TestTeamHeldStreamDeliversNothingUntilStandingReturns(t *testing.T) {
436 f := newTeamFixture(t)
437 fastStreams(t, f)
438 srv := newStreamServer(t, f)
439 f.member(teamSubject('h'), "member")
440 sqid, token := f.meeting("Held delivery")
441 alice := f.jar()
442 gina := f.guestJar(token, "Gina")
443 aliceS := f.join(srv, alice, sqid)
444 ginaS := f.join(srv, gina, sqid)
445 aliceS.drain()
446
447 f.expired()
448 ginaSession := ""
449 for _, c := range gina {
450 if c.Name == f.app.auth.SessionCookie() {
451 ginaSession = hubSessionKey(f.app.hubSalt, sessionSubject(t, f, gina), c.Value)
452 }
453 }
454 for _, text := range []string{"one", "two"} {
455 payload, _ := json.Marshal(map[string]string{"text": text})
456 if err := f.app.hub.Fanout(context.Background(), sqid, ginaSession, hub.PeerID(ginaS.peer), hub.Message{Type: hub.TypeChat, Payload: payload}); err != nil {
457 t.Fatalf("fan out while held: %v", err)
458 }
459 }
460 aliceS.quiet(150 * time.Millisecond)
461 f.refreshed()
462 for _, want := range []string{"one", "two"} {
463 if chat := aliceS.next("chat"); chat.data["payload"].(map[string]any)["text"] != want {
464 t.Fatalf("caught up out of order: %v", chat.data)
465 }
466 }
467}
468
469// sessionSubject is the session subject a jar's session carries.
470func sessionSubject(t *testing.T, f *teamFixture, jar map[string]*http.Cookie) string {
471 t.Helper()
472 r := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
473 for _, c := range jar {
474 r.AddCookie(c)
475 }
476 id, ok := f.app.auth.SessionFrom(r)
477 if !ok {
478 t.Fatal("no session in the jar")
479 }
480 return id.Address
481}
482
483// A member the roster removes is ended within the lease, live session
484// included: their stream is told lost{standing}, the room is told they
485// have gone, and their next request is signed out. The host and the call
486// carry on.
487func TestTeamRemovalEndsAMembersLiveSession(t *testing.T) {
488 f := newTeamFixture(t)
489 fastStreams(t, f)
490 srv := newStreamServer(t, f)
491 f.member(teamSubject('h'), "member")
492 sqid, _ := f.meeting("Ongoing")
493 alice := f.jar()
494 bobSubject := teamSubject('b')
495 f.member(bobSubject, "member")
496 f.signInHome(bobSubject)
497 bob := f.jar()
498 aliceS := f.join(srv, alice, sqid)
499 bobS := f.join(srv, bob, sqid)
500 aliceS.next("peer")
501
502 f.removed(bobSubject)
503 if lost := bobS.next("lost"); lost.data["reason"] != "standing" {
504 t.Fatalf("the removed member's stream: %v", lost.data)
505 }
506 if gone := aliceS.next("gone"); gone.data["from"] != bobS.peer {
507 t.Fatalf("the room was told %v", gone.data)
508 }
509 f.cookies = bob
510 signedOutRemoved(t, "the removed member's ICE fetch", f.get("/m/"+sqid+"/ice?peer="+bobS.peer))
511 if f.meetingRow(sqid).EndedAt != nil {
512 t.Fatal("a member's removal ended the host's meeting")
513 }
514}
515
516// The stream-order lesson (oficina/slides #33, oficina/sheets #54): swept
517// across the lease's end, with a roster clock that ticks on every reading,
518// a decision is never "delivers, with nothing to renew" — every delivering
519// answer carries a timer of at least a second — and a lease that ran out
520// after the decision never stands for a delivery.
521func TestTeamStreamDecisionNeverDeliversWithoutALease(t *testing.T) {
522 sawDeliver, sawHold := false, false
523 for k := 1; k <= 30; k++ {
524 f := newTeamFixture(t)
525 srv := newStreamServer(t, f)
526 subject := teamSubject('h')
527 p := f.member(subject, "member")
528 sqid, _ := f.meeting("Swept")
529 s := f.join(srv, f.jar(), sqid)
530 m := f.meetingRow(sqid)
531 session := ""
532 for _, c := range f.cookies {
533 if c.Name == f.app.auth.SessionCookie() {
534 session = hubSessionKey(f.app.hubSalt, subject, c.Value)
535 }
536 }
537 f.refreshed()
538 f.dir.SetDown(true)
539 f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond)
540 f.clock.SetTick(time.Millisecond)
541 d := f.app.teamStreamDecide(freshStanding(context.Background()), m, p, sqid, session, hub.PeerID(s.peer))
542 switch d.verdict {
543 case streamDelivers:
544 sawDeliver = true
545 if d.renew < time.Second || len(d.leases) == 0 {
546 t.Fatalf("k=%d: delivers with renew %v on %d leases", k, d.renew, len(d.leases))
547 }
548 case streamHolds:
549 sawHold = true
550 default:
551 t.Fatalf("k=%d: Unknown ended the stream", k)
552 }
553 f.clock.SetTick(0)
554 f.clock.Step(roster.MaximumAge)
555 if d.stands() {
556 t.Fatalf("k=%d: a lapsed lease still stands for a delivery", k)
557 }
558 s.cancel()
559 }
560 if !sawDeliver || !sawHold {
561 t.Fatalf("the sweep did not cross the lease's end: deliver %v hold %v", sawDeliver, sawHold)
562 }
563}
564
565// A knock's push goes only to people the roster says are Members when it
566// is sent: never to a removed member, never under Unknown.
567func TestTeamKnockPushGoesOnlyToCurrentMembers(t *testing.T) {
568 f := newTeamFixture(t)
569 push := &recordingPusher{}
570 f.app.push = push
571 alice := teamSubject('a')
572 f.member(alice, "member")
573 if w := f.json("/native/devices", `{"token":"aa01","platform":"ios"}`); w.Code != http.StatusNoContent {
574 t.Fatalf("alice's device = %d", w.Code)
575 }
576 bob := teamSubject('b')
577 f.member(bob, "member")
578 if w := f.json("/native/devices", `{"token":"bb02","platform":"macos"}`); w.Code != http.StatusNoContent {
579 t.Fatalf("bob's device = %d", w.Code)
580 }
581 f.removed(bob)
582 f.app.knocked("room", nil, "Gina")
583 if got := push.all(); len(got) != 1 || !strings.HasPrefix(got[0], "aa01|") {
584 t.Fatalf("pushed %v, want alice's device only", got)
585 }
586 f.expired()
587 f.app.knocked("room", nil, "Gina")
588 if got := push.all(); len(got) != 1 {
589 t.Fatalf("pushed under Unknown: %v", got)
590 }
591 // No push key: nothing breaks, nothing is sent.
592 f.app.push = nil
593 f.refreshed()
594 f.app.knocked("room", nil, "Gina")
595}
596
597// The drive surface stands on the agent's operator, asked on every
598// request: removed, the one not-found body; Unknown, a retryable 503;
599// back on the team, it works again.
600func TestTeamAgentStandsOnItsOperator(t *testing.T) {
601 f := newTeamFixture(t)
602 op := teamSubject('o')
603 f.member(op, "member")
604 bearer := f.agentToken("bot")
605 if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusOK {
606 t.Fatalf("member's agent = %d", w.Code)
607 }
608 f.member(teamSubject('q'), "member")
609 sqid, _ := f.meeting("Somebody's")
610 // And one already over, which no host check would refuse: only the
611 // gate's own answer for the operator stands between it and a 200.
612 over, _ := f.meeting("Over")
613 if w := f.post("/meetings/"+over+"/end", ""); w.Code != http.StatusSeeOther {
614 t.Fatalf("end = %d", w.Code)
615 }
616 f.expired()
617 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" {
618 t.Fatalf("operator Unknown = %d", w.Code)
619 }
620 // An item, too: a meeting another member made.
621 for _, item := range []string{sqid, over} {
622 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" {
623 t.Fatalf("an item under an Unknown operator = %d %s", w.Code, w.Body.String())
624 }
625 }
626 f.removed(op)
627 if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusNotFound || !strings.Contains(w.Body.String(), "not-found") {
628 t.Fatalf("operator removed = %d %s", w.Code, w.Body.String())
629 }
630 f.dir.Set(op, "member")
631 f.refreshed()
632 if w := f.api("GET", "/api/v1/meetings", bearer, ""); w.Code != http.StatusOK {
633 t.Fatalf("operator re-added = %d", w.Code)
634 }
635}
636
637// standingOf for somebody the roster cannot be asked about is NotMember;
638// for storage that cannot be read, Unknown.
639func TestTeamStandingOfSomebodyElse(t *testing.T) {
640 f := newTeamFixture(t)
641 p := f.member(teamSubject('s'), "member")
642 if st := f.app.standingOf(context.Background(), p.ID).State(); st != roster.Member {
643 t.Fatalf("a member = %v", st)
644 }
645 if st := f.app.standingOf(context.Background(), 999).State(); st != roster.NotMember {
646 t.Fatalf("nobody = %v", st)
647 }
648 f.app.db.Writer().Exec("ALTER TABLE calls_team_home_persons RENAME TO unreadable")
649 if st := f.app.standingOf(context.Background(), p.ID).State(); st != roster.Unknown {
650 t.Fatalf("unreadable = %v", st)
651 }
652 var acc *teammode.Access
653 if acc.State() != roster.Unknown {
654 t.Fatal("a nil Access is not Unknown")
655 }
656}
657
658// Before anybody has touched it, a removed host's link is already dead:
659// to a visitor following it (who is shown no title), to a sign-in it
660// would carry (no pending join is written, so no mail is owed), and the
661// meeting is ended by the first of them.
662func TestTeamARemovedHostsLinkIsDeadBeforeAnyoneTouchesIt(t *testing.T) {
663 f := newTeamFixture(t)
664 host := teamSubject('k')
665 f.member(host, "member")
666 sqid, token := f.meeting("Secret title")
667 // A visitor followed the link while the host stood: the join cookie
668 // the sign-in form reads.
669 f.cookies = map[string]*http.Cookie{}
670 if w := f.page("/j/" + token); w.Code != http.StatusOK {
671 t.Fatalf("the link while the host stands = %d", w.Code)
672 }
673 visitor := f.jar()
674 f.removed(host)
675 f.cookies = visitor
676 if w := f.post("/signin", "address=outsider%40example.test"); w.Code != http.StatusSeeOther {
677 t.Fatalf("sign-in = %d", w.Code)
678 }
679 if n := f.count("pending_joins"); n != 0 {
680 t.Fatalf("a removed host's link wrote %d pending joins", n)
681 }
682 f.cookies = map[string]*http.Cookie{}
683 persons := f.count("persons")
684 if w := f.post("/j/"+token+"/guest", "name=Late"); w.Code != http.StatusNotFound {
685 t.Fatalf("a removed host's link, joining by name = %d", w.Code)
686 }
687 if f.count("persons") != persons || f.count("guest_grants") != 0 {
688 t.Fatal("a removed host's link made a guest")
689 }
690 w := f.page("/j/" + token)
691 if w.Code != http.StatusNotFound || strings.Contains(w.Body.String(), "Secret title") {
692 t.Fatalf("a removed host's link = %d", w.Code)
693 }
694 if f.meetingRow(sqid).EndedAt == nil {
695 t.Fatal("following a removed host's link did not end the meeting")
696 }
697}
698
699// The quiet case (spec §2.4's tick): with nobody's stream re-deciding,
700// the hub's own pass ends a removed host's call, and a member opening
701// another of that host's meetings, untouched until now, finds it ended.
702func TestTeamTheTickEndsAQuietCallWhoseHostLeft(t *testing.T) {
703 f := newTeamFixture(t)
704 srv := newStreamServer(t, f)
705 host := teamSubject('t')
706 f.member(host, "member")
707 sqid, token := f.meeting("Quiet")
708 other, _ := f.meeting("Untouched")
709 alice := f.jar()
710 f.member(teamSubject('u'), "member")
711 bob := f.jar()
712 gina := f.guestJar(token, "Gina")
713 f.join(srv, alice, sqid)
714 bobS := f.join(srv, bob, sqid)
715 ginaS := f.join(srv, gina, sqid)
716 f.removed(host)
717 f.app.hub.Tick(context.Background())
718 for _, s := range []*callStream{bobS, ginaS} {
719 if lost := s.next("lost"); lost.data["reason"] != "ended" {
720 t.Fatalf("after the tick: %v", lost.data)
721 }
722 }
723 f.cookies = bob
724 if w := f.page("/m/" + other + "/join"); w.Code != http.StatusNotFound {
725 t.Fatalf("a removed host's untouched meeting = %d", w.Code)
726 }
727 if f.meetingRow(other).EndedAt == nil {
728 t.Fatal("opening it did not end it")
729 }
730}
731
732// Swept across the lease's end with a roster clock that ticks on every
733// reading — so that a host asked a moment later can still stand while the
734// request's own standing has run out — every answer is either what a
735// member gets or a retryable 503: never "not found", never a 500, and
736// never a grant for a member who needs none.
737func TestTeamAnswersAcrossTheLeaseEdgeAreWholeOrRetryable(t *testing.T) {
738 retries := 0
739 for k := 1; k <= 30; k++ {
740 f := newTeamFixture(t)
741 srv := newStreamServer(t, f)
742 f.member(teamSubject('h'), "member")
743 sqid, token := f.meeting("Edge")
744 host := f.jar()
745 s := f.join(srv, host, sqid)
746 s.drain()
747 f.member(teamSubject('m'), "member")
748 member := f.jar()
749 link, _, _, _ := f.app.store.liveLink(context.Background(), token)
750 edge := func() {
751 f.refreshed()
752 f.dir.SetDown(true)
753 f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Millisecond)
754 f.clock.SetTick(time.Millisecond)
755 }
756 check := func(what string, w *httptest.ResponseRecorder, ok ...int) {
757 t.Helper()
758 for _, c := range ok {
759 if w.Code == c {
760 return
761 }
762 }
763 if w.Code == http.StatusServiceUnavailable {
764 retryable(t, what, w)
765 retries++
766 return
767 }
768 t.Fatalf("k=%d %s = %d %s", k, what, w.Code, w.Body.String())
769 }
770 f.cookies = member
771 edge()
772 check("the holding screen", f.page("/m/"+sqid+"/join"), http.StatusOK)
773 f.clock.SetTick(0)
774 edge()
775 check("a member follows the link", f.page("/j/"+token), http.StatusSeeOther)
776 f.clock.SetTick(0)
777 f.app.store.writePending(context.Background(), f.personFor(teamSubject('m')).Email, link)
778 edge()
779 check("a member's pending join", f.page("/continue"), http.StatusSeeOther)
780 f.clock.SetTick(0)
781 edge()
782 check("a chat", f.signal(host, sqid, map[string]any{"peer": s.peer, "type": "chat", "payload": map[string]any{"text": "x"}}), http.StatusOK)
783 f.clock.SetTick(0)
784 if n := f.count("guest_grants"); n != 0 {
785 t.Fatalf("k=%d: a member was given %d grants", k, n)
786 }
787 s.cancel()
788 }
789 if retries == 0 {
790 t.Fatal("the sweep never reached the lease's end")
791 }
792}
793
794// A held stream keeps what arrives, in order, but no more than a
795// subscriber's buffer: past it the stream ends lost{buffer}, and the
796// browser resumes.
797func TestTeamHeldStreamEndsPastTheBuffer(t *testing.T) {
798 f := newTeamFixture(t)
799 fastStreams(t, f)
800 srv := newStreamServer(t, f)
801 f.member(teamSubject('h'), "member")
802 sqid, token := f.meeting("Overflow")
803 alice := f.jar()
804 gina := f.guestJar(token, "Gina")
805 aliceS := f.join(srv, alice, sqid)
806 ginaS := f.join(srv, gina, sqid)
807 aliceS.drain()
808 f.expired()
809 session := ""
810 for _, c := range gina {
811 if c.Name == f.app.auth.SessionCookie() {
812 session = hubSessionKey(f.app.hubSalt, sessionSubject(t, f, gina), c.Value)
813 }
814 }
815 payload, _ := json.Marshal(map[string]string{"text": "x"})
816 for range teamStreamHeld + 2 {
817 f.app.hub.Fanout(context.Background(), sqid, session, hub.PeerID(ginaS.peer), hub.Message{Type: hub.TypeChat, Payload: payload})
818 // Slowly enough that the stream reads each one off the hub, so
819 // it is the held stream's own bound that is reached, not the
820 // hub's buffer for a subscriber that is not reading.
821 time.Sleep(2 * time.Millisecond)
822 }
823 if lost := aliceS.next("lost"); lost.data["reason"] != "buffer" {
824 t.Fatalf("an overflowing held stream: %v", lost.data)
825 }
826}
827
828// What ends a stream is said at once even while it is held: a second tab
829// resuming the same participation replaces the held one, which is told so
830// and closes, rather than holding the news until standing returns.
831func TestTeamHeldStreamIsToldItWasReplaced(t *testing.T) {
832 f := newTeamFixture(t)
833 fastStreams(t, f)
834 srv := newStreamServer(t, f)
835 f.member(teamSubject('h'), "member")
836 sqid, _ := f.meeting("Replaced")
837 alice := f.jar()
838 first := f.join(srv, alice, sqid)
839 first.drain()
840 f.expired()
841 second, status := f.tryStream(srv, alice, "/m/"+sqid+"/stream?peer="+first.peer+"&last=%7B%7D")
842 if status != http.StatusOK {
843 t.Fatalf("the second tab's resume = %d", status)
844 }
845 second.next("hello")
846 if lost := first.next("lost"); lost.data["reason"] != "replaced" {
847 t.Fatalf("the held stream was told %v", lost.data)
848 }
849}
850