package callstest import ( "encoding/json" "fmt" "net/http" "regexp" "strings" "testing" "time" "amadan.net/oficina/calls/protocol" ) // Spec §15.29 (2026-10-28): the per-peer detail written flat, so `carlos // logs` shows it; why a call was relayed; and the automatic report a // struggling client sends without anyone pressing anything. // relayedQuality is a report from the side of a relayed call whose own // network found no public address: a Safari guest, sharing nothing, // receiving a camera and a screen. func relayedQuality(remote string) protocol.QualityReport { q := sampleQuality(remote) q.Client = protocol.ReportClient{App: "web", Version: "47afcb9", Browser: "safari", BrowserVersion: "26.5", OS: "macos", OSVersion: "10.15.7"} p := &q.Peers[0] p.Path = &protocol.Path{Local: "relay", Remote: "srflx", Protocol: "tls"} p.RTT, p.RTTAvg, p.RTTMax = num(310), num(402.5), num(1312) p.JitterAvg, p.JitterMax = num(18), num(96) p.Candidates = &protocol.Candidates{Host: num(2), Relay: num(1), RemoteHost: num(1), RemoteSrflx: num(1), RemoteRelay: num(1), UDPOK: false} p.Out = &protocol.Outbound{ Audio: &protocol.OutStream{Kbps: num(31.5), Packets: num(1500), Lost: num(15), RTT: num(420)}, Video: &protocol.OutStream{Kbps: num(412), Width: num(640), Height: num(360), FPS: num(24), Limit: "bandwidth", LimitedBandwidthSeconds: num(27.5), LimitedCPUSeconds: num(0), Encoder: "hardware", Codec: "h264"}, } p.In = &protocol.Inbound{ Audio: &protocol.InAudio{Kbps: num(30), Packets: num(1480), Lost: num(20), Jitter: num(22), Samples: num(1440000), Concealed: num(14400), JitterBufferMs: num(140)}, Video: &protocol.InVideo{Kbps: num(380), Packets: num(1200), Lost: num(12), Width: num(1280), Height: num(720), FPS: num(12.5), Freezes: num(4), FreezeSeconds: num(6.1), Decoded: num(375), Dropped: num(3), Decoder: "hardware", Codec: "vp8"}, Screen: &protocol.InVideo{Kbps: num(900), Width: num(1920), Height: num(1246), FPS: num(4), Freezes: num(3), FreezeSeconds: num(9), Dropped: num(0), Decoder: "software", Codec: "h264", Stalls: num(1), StallsNoPackets: num(1)}, } p.Events = &protocol.PeerEvents{Reconnecting: num(1), ReconnectingSeconds: num(6.4), AutoRestarts: num(2)} return q } // peerLines are the `calls: quality peer` lines. func (r *reportRig) peerLines(t *testing.T) []map[string]any { t.Helper() return r.reports.lines(t, "calls: quality peer") } func TestTheQualityPeerLineIsFlatAndCarriesTheDetail(t *testing.T) { r := newReportRig(t, "") if err := r.x.ctl.SetRelay(relayContract(t)); err != nil { t.Fatal(err) } if resp, body := r.b.report(r.sqid, "quality", r.tokB, mustJSON(t, relayedQuality(r.peerA))); resp.StatusCode != http.StatusAccepted { t.Fatalf("quality: %d %s", resp.StatusCode, body) } heads := r.reports.lines(t, "calls: quality") lines := r.peerLines(t) if len(heads) != 1 || len(lines) != 1 { t.Fatalf("%d quality lines and %d peer lines, want one of each", len(heads), len(lines)) } head, line := heads[0], lines[0] // The same tags as the head, and the remote peer by its tag: A's, // which is what A's own lines are under. if line["call"] != head["call"] || line["peer"] != head["peer"] || line["level"] != "INFO" { t.Fatalf("peer line tags %v, head %v", line, head) } if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, sampleQuality(r.peerB))); resp.StatusCode != http.StatusAccepted { t.Fatal("A's report") } if tagA := r.reports.lines(t, "calls: quality")[1]["peer"]; line["remote"] != tagA { t.Fatalf("remote = %v, want A's tag %v", line["remote"], tagA) } want := map[string]any{ "pathLocal": "relay", "pathRemote": "srflx", "pathProtocol": "tls", "relayRegion": "eu-west-1", "rtt": 310.0, "rttAvg": 402.5, "rttMax": 1312.0, "jitterAvg": 18.0, "jitterMax": 96.0, "candHost": 2.0, "candRelay": 1.0, "candRemoteHost": 1.0, "candRemoteSrflx": 1.0, "candRemoteRelay": 1.0, "directOk": false, "localDirectOk": false, "udpOk": false, "outAudioKbps": 31.5, "outAudioLossPct": 1.0, "outAudioRtt": 420.0, "outCameraKbps": 412.0, "outCameraWidth": 640.0, "outCameraHeight": 360.0, "outCameraFps": 24.0, "outCameraLimit": "bandwidth", "outCameraLimitedBandwidthSeconds": 27.5, "outCameraLimitedCpuSeconds": 0.0, "outCameraEncoder": "hardware", "outCameraCodec": "h264", "inAudioKbps": 30.0, "inAudioLossPct": 1.3, "inAudioJitter": 22.0, "inAudioConcealedPct": 1.0, "inAudioJitterBufferMs": 140.0, "inCameraKbps": 380.0, "inCameraWidth": 1280.0, "inCameraHeight": 720.0, "inCameraFps": 12.5, "inCameraLossPct": 1.0, "inCameraFreezes": 4.0, "inCameraFreezeSeconds": 6.1, "inCameraDropped": 3.0, "inCameraDecoder": "hardware", "inCameraCodec": "vp8", "inScreenWidth": 1920.0, "inScreenHeight": 1246.0, "inScreenFps": 4.0, "inScreenFreezes": 3.0, "inScreenDecoder": "software", "inScreenStalls": 1.0, "inScreenStallsNoPackets": 1.0, "reconnecting": 1.0, "reconnectingSeconds": 6.4, "autoRestarts": 2.0, } for k, v := range want { if line[k] != v { t.Errorf("peer line %s = %#v, want %#v", k, line[k], v) } } // Flat: nothing nested for carlos to drop, and every key a name // quality-summary's reader takes. key := regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`) for k, v := range line { switch v.(type) { case map[string]any, []any: t.Errorf("peer line member %s is nested: %v", k, v) } if !key.MatchString(k) { t.Errorf("peer line key %q is not letters and digits", k) } } // Not measured is left off, not written as zero. for _, k := range []string{"outScreenKbps", "inScreenKbps0", "candSrflx", "noSound", "outScreenMode"} { if _, ok := line[k]; ok { t.Errorf("peer line has %s, which the report did not measure", k) } } // The head's maxRtt reads the window's highest, not only the latest. if head["maxRtt"] != 1312.0 { t.Errorf("head maxRtt = %v, want the window's 1312", head["maxRtt"]) } r.assertClean(t) } // A report from a client before §15.29 — none of the new members — is // taken as it always was, and its peer line says what it can. func TestAnOldClientsReportStillMakesAPeerLine(t *testing.T) { r := newReportRig(t, "") if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, sampleQuality(r.peerB))); resp.StatusCode != http.StatusAccepted { t.Fatalf("an old client's report: %d", resp.StatusCode) } lines := r.peerLines(t) if len(lines) != 1 { t.Fatalf("%d peer lines", len(lines)) } l := lines[0] if l["pathLocal"] != "srflx" || l["pathRemote"] != "relay" || l["outCameraLimit"] != "bandwidth" || l["inCameraFreezes"] != 2.0 { t.Fatalf("old client's peer line %v", l) } // No relay configured here: the region is not guessed. for _, k := range []string{"relayRegion", "directOk", "candHost", "rttMax", "outCameraEncoder", "autoReport"} { if _, ok := l[k]; ok { t.Errorf("old client's peer line has %s", k) } } if _, ok := r.reports.lines(t, "calls: quality")[0]["autoReport"]; ok { t.Error("a quality line with no auto report says autoReport") } } func TestTheNewMembersAreStrict(t *testing.T) { r := newReportRig(t, "") cases := map[string]func(*protocol.QualityReport){ "an encoder by name": func(q *protocol.QualityReport) { q.Peers[0].Out.Video.Encoder = "VideoToolbox" }, "a codec off the list": func(q *protocol.QualityReport) { q.Peers[0].Out.Video.Codec = "theora" }, "a share mode off the list": func(q *protocol.QualityReport) { q.Peers[0].Out.Screen = &protocol.OutStream{Mode: "fast"} }, "a decoder by name": func(q *protocol.QualityReport) { q.Peers[0].In.Video.Decoder = "libvpx" }, "an inbound codec": func(q *protocol.QualityReport) { q.Peers[0].In.Screen = &protocol.InVideo{Codec: "H264"} }, "an auto report ref": func(q *protocol.QualityReport) { q.AutoReport = "not-a-ref" }, "a lowercase ref": func(q *protocol.QualityReport) { q.AutoReport = "k7q2m9pd" }, "rttMax over its ceiling": func(q *protocol.QualityReport) { q.Peers[0].RTTMax = num(600_001) }, "a negative jitter": func(q *protocol.QualityReport) { q.Peers[0].JitterAvg = num(-1) }, "limited seconds too long": func(q *protocol.QualityReport) { q.Peers[0].Out.Video.LimitedBandwidthSeconds = num(601) }, "a candidate count too big": func(q *protocol.QualityReport) { q.Peers[0].Candidates = &protocol.Candidates{Host: num(2e9)} }, } for name, edit := range cases { q := relayedQuality(r.peerB) edit(&q) r.x.advance(10 * time.Second) if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, q)); resp.StatusCode != http.StatusBadRequest { t.Errorf("%s: %d, want 400", name, resp.StatusCode) } } // And the good values are taken. q := relayedQuality(r.peerB) q.AutoReport = "K7Q2M9PD" q.Peers[0].Out.Screen = &protocol.OutStream{Kbps: num(2400), Mode: "detail", Encoder: "software", Codec: "h264", Limit: "cpu", LimitedCPUSeconds: num(12)} r.x.advance(10 * time.Second) if resp, body := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, q)); resp.StatusCode != http.StatusAccepted { t.Fatalf("a good report: %d %s", resp.StatusCode, body) } head := r.reports.lines(t, "calls: quality")[0] if head["autoReport"] != "K7Q2M9PD" { t.Errorf("head autoReport = %v", head["autoReport"]) } l := r.peerLines(t)[0] if l["outScreenMode"] != "detail" || l["outScreenEncoder"] != "software" || l["outScreenLimit"] != "cpu" || l["outScreenLimitedCpuSeconds"] != 12.0 { t.Errorf("screen fields %v", l) } } // The largest per-peer line the schema allows, every field present and at // its widest, fits the platform's line. func TestTheLargestPeerLineFitsThePlatformsLine(t *testing.T) { r := newReportRig(t, "") if err := r.x.ctl.SetRelay(relayContract(t)); err != nil { t.Fatal(err) } q := largestQuality(r.peerB) if resp, body := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, q)); resp.StatusCode != http.StatusAccepted { t.Fatalf("the largest report: %d %s", resp.StatusCode, body) } lines := strings.Split(strings.TrimSpace(r.reports.String()), "\n") if len(lines) != 1+protocol.MaxQualityPeers { t.Fatalf("%d lines, want the head and %d peer lines", len(lines), protocol.MaxQualityPeers) } widest := 0 for _, l := range lines { widest = max(widest, len(l)) if len(l) > 8192 { t.Fatalf("a line of %d bytes; the platform keeps 8192:\n%.300s", len(l), l) } } peer := r.peerLines(t)[0] if len(peer) < 90 { t.Errorf("the largest peer line has only %d fields", len(peer)) } t.Logf("widest line %d bytes; a peer line %d bytes with %d fields", widest, len(lines[1]), len(peer)) } // largestQuality is the widest report the schema allows: every peer, // every number at its widest, every enum at its longest. func largestQuality(remote string) protocol.QualityReport { big := func() *float64 { return num(123456789.1) } ms := func() *float64 { return num(599999.9) } secs := func() *float64 { return num(599.9) } out := func(mode string) *protocol.OutStream { return &protocol.OutStream{Kbps: num(999999.9), Packets: big(), Lost: big(), RTT: ms(), Jitter: ms(), Limit: "bandwidth", Width: num(16384), Height: num(16384), FPS: num(240), Keyframes: big(), Rebuilds: big(), Reshares: big(), Failures: big(), Damped: big(), EncoderStalls: big(), LimitedBandwidthSeconds: secs(), LimitedCPUSeconds: secs(), Encoder: "software", Codec: "other", Mode: mode} } in := func() *protocol.InVideo { return &protocol.InVideo{Kbps: num(999999.9), Packets: big(), Lost: big(), Jitter: ms(), Freezes: big(), FreezeSeconds: secs(), Decoded: big(), Dropped: big(), Width: num(16384), Height: num(16384), FPS: num(240), Reattaches: big(), Stalls: big(), StallsNoPackets: big(), StallsUndecoded: big(), Decoder: "software", Codec: "other"} } q := sampleQuality(remote) q.AutoReport = "K7Q2M9PD" q.Peers = nil for i := 0; i < protocol.MaxQualityPeers; i++ { q.Peers = append(q.Peers, protocol.PeerQuality{ Peer: protocol.PeerID(fmt.Sprintf("%032x", i)), Path: &protocol.Path{Local: "relay", Remote: "relay", Protocol: "unknown"}, RTT: ms(), RTTAvg: ms(), RTTMax: ms(), JitterAvg: ms(), JitterMax: ms(), Candidates: &protocol.Candidates{Host: big(), Srflx: big(), Prflx: big(), Relay: big(), RemoteHost: big(), RemoteSrflx: big(), RemotePrflx: big(), RemoteRelay: big(), DirectOK: true, LocalDirectOK: true, UDPOK: true}, Out: &protocol.Outbound{Audio: out(""), Video: out(""), Screen: out("balanced")}, In: &protocol.Inbound{ Audio: &protocol.InAudio{Kbps: num(999999.9), Packets: big(), Lost: big(), Jitter: ms(), Samples: big(), Concealed: big(), Inserted: big(), Removed: big(), JitterBufferMs: ms()}, Video: in(), Screen: in(), }, Events: &protocol.PeerEvents{Reconnecting: big(), ReconnectingSeconds: secs(), CantHearSeconds: secs(), NoSound: true, NoSoundFromUs: true, AudioBlocked: true, ScreenStalled: true, AutoRestarts: big(), AutoRebuilds: big()}, }) } return q } // autoBody is an automatic report as a client sends it. func autoBody(t *testing.T, trigger, diagnostics string) []byte { return mustJSON(t, protocol.AutoReport{Trigger: trigger, Diagnostics: diagnostics, Client: protocol.ReportClient{App: "web", Version: "47afcb9", Browser: "safari", BrowserVersion: "26.5", OS: "macos", OSVersion: "10.15.7"}}) } func TestAnAutoReportIsLoggedUnderItsReferenceScrubbedAndWithoutANote(t *testing.T) { r := newReportRig(t, "") diag := fmt.Sprintf("Calls web diagnostics\n## Call\npeer %s: connection connected, ICE connected\nopened %s/m/%s\nfull id %s\n", r.peerA[:6], testOrigin, r.sqid, r.peerA) for len(diag) < 14_000 { diag += "12:00:00.000 screen from " + r.peerA[:6] + " stalled here: no packets arriving\n" } // A client that sent a note anyway: the schema has none, so it is // dropped unread. var withNote map[string]any _ = json.Unmarshal(autoBody(t, "freezes", diag), &withNote) withNote["note"] = "Ana's video froze" resp, body := r.b.report(r.sqid, "auto-report", r.tokB, mustJSON(t, withNote)) if resp.StatusCode != http.StatusOK { t.Fatalf("auto report: %d %s", resp.StatusCode, body) } var receipt protocol.ProblemReceipt if err := json.Unmarshal(body, &receipt); err != nil || !regexp.MustCompile(`^[0-9A-HJKMNP-TV-Z]{8}$`).MatchString(receipt.Ref) { t.Fatalf("receipt %s", body) } heads := r.reports.lines(t, "calls: auto report") if len(heads) != 1 { t.Fatalf("%d auto report lines", len(heads)) } head := heads[0] if head["ref"] != receipt.Ref || head["trigger"] != "freezes" || head["level"] != "WARN" || head["live"] != true || head["browser"] != "safari" { t.Fatalf("auto report head %v", head) } if _, ok := head["note"]; ok { t.Errorf("an auto report head carries a note: %v", head) } if strings.Contains(r.reports.String(), "Ana's video") { t.Error("the note a client added reached the log") } parts := r.reports.lines(t, "calls: auto report diagnostics") if len(parts) < 3 || float64(len(parts)) != head["parts"] { t.Fatalf("%d diagnostics parts, head says %v", len(parts), head["parts"]) } var text strings.Builder for i, p := range parts { if p["ref"] != receipt.Ref || p["part"] != float64(i+1) || p["call"] != head["call"] || p["peer"] != head["peer"] { t.Fatalf("part %d: %v", i+1, p) } text.WriteString(p["text"].(string)) } if !strings.Contains(text.String(), "/m/[meeting]") || !strings.Contains(text.String(), "full id peer:") || strings.Contains(text.String(), r.peerA[:6]) { t.Fatalf("diagnostics not scrubbed:\n%.300s", text.String()) } for _, line := range strings.Split(r.reports.String(), "\n") { if len(line) > 8192 { t.Fatalf("a line of %d bytes", len(line)) } } // Not a problem report: quality-summary tells them apart. if n := len(r.reports.lines(t, "calls: problem report")); n != 0 { t.Errorf("%d problem report lines from an auto report", n) } r.assertClean(t) // The schema: a trigger off the list, a client off the list, the cap. r.x.advance(11 * time.Minute) for name, b := range map[string][]byte{ "no trigger": autoBody(t, "", "x"), "a trigger by name": autoBody(t, "my video froze", "x"), "a bad client": mustJSON(t, protocol.AutoReport{Trigger: "rtt", Client: protocol.ReportClient{App: "Paul's Mac"}}), "not json": []byte("trigger=rtt"), } { r.x.advance(11 * time.Minute) if resp, _ := r.a.report(r.sqid, "auto-report", r.tokA, b); resp.StatusCode != http.StatusBadRequest { t.Errorf("%s: %d, want 400", name, resp.StatusCode) } } r.x.advance(11 * time.Minute) if resp, _ := r.a.report(r.sqid, "auto-report", r.tokA, autoBody(t, "rtt", strings.Repeat("a", 65<<10))); resp.StatusCode != http.StatusRequestEntityTooLarge { t.Errorf("65 KB of diagnostics: %d, want 413", resp.StatusCode) } } func TestAutoReportsAreOneEveryTenMinutesAndThreeACall(t *testing.T) { r := newReportRig(t, "") send := func(c *client, tok string) *http.Response { resp, _ := c.report(r.sqid, "auto-report", tok, autoBody(t, "rtt", "Calls web diagnostics")) return resp } if resp := send(r.a, r.tokA); resp.StatusCode != http.StatusOK { t.Fatalf("the first: %d", resp.StatusCode) } resp := send(r.a, r.tokA) if resp.StatusCode != http.StatusTooManyRequests || resp.Header.Get("Retry-After") == "" { t.Fatalf("a second at once: %d (Retry-After %q), want 429", resp.StatusCode, resp.Header.Get("Retry-After")) } // Per participation: B's are its own. if resp := send(r.b, r.tokB); resp.StatusCode != http.StatusOK { t.Fatalf("B's first, after A's: %d", resp.StatusCode) } r.x.advance(9*time.Minute + 50*time.Second) if resp := send(r.a, r.tokA); resp.StatusCode != http.StatusTooManyRequests { t.Fatalf("nine minutes fifty later: %d, want 429", resp.StatusCode) } // Two minutes idle is longer than the problem limiter's memory; this // limit remembers. r.x.advance(10 * time.Second) if resp := send(r.a, r.tokA); resp.StatusCode != http.StatusOK { t.Fatalf("ten minutes later: %d, want 200", resp.StatusCode) } r.x.advance(10 * time.Minute) if resp := send(r.a, r.tokA); resp.StatusCode != http.StatusOK { t.Fatalf("the third, twenty minutes in: %d", resp.StatusCode) } r.x.advance(time.Hour) if resp := send(r.a, r.tokA); resp.StatusCode != http.StatusTooManyRequests { t.Fatalf("a fourth an hour later: %d, want 429 (three a call)", resp.StatusCode) } if n := len(r.reports.lines(t, "calls: auto report")); n != 4 { t.Fatalf("%d auto reports logged, want A's three and B's one", n) } // Problem reports are the person's, and spend nothing of this. if resp, _ := r.a.report(r.sqid, "problem", r.tokA, mustJSON(t, protocol.ProblemReport{Note: "x", Client: protocol.ReportClient{App: "web"}})); resp.StatusCode != http.StatusOK { t.Fatalf("a problem report after the auto reports ran out: %d", resp.StatusCode) } } func TestAutoReportsNeedTheTokenAndFollowTheKillSwitch(t *testing.T) { r := newReportRig(t, "") if resp, _ := r.a.report(r.sqid, "auto-report", strings.Repeat("0", 32), autoBody(t, "rtt", "x")); resp.StatusCode != http.StatusNotFound { t.Fatalf("a made-up token: %d, want 404", resp.StatusCode) } if resp, _ := r.a.report(r.sqid, "auto-report", r.tokB, autoBody(t, "rtt", "x")); resp.StatusCode != http.StatusNotFound { t.Fatalf("B's token from A's session: %d, want 404", resp.StatusCode) } off := newReportRig(t, "off") for _, token := range []string{off.tokA, ""} { if resp, _ := off.a.report(off.sqid, "auto-report", token, autoBody(t, "freezes", "x")); resp.StatusCode != http.StatusNoContent { t.Fatalf("quality reports off (token %q): %d, want 204", token, resp.StatusCode) } } if n := len(off.reports.lines(t, "calls: auto report")); n != 0 { t.Fatalf("%d auto report lines with reports off", n) } }