| 1 | package calls |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "log/slog" |
| 10 | "math" |
| 11 | "net/http" |
| 12 | "reflect" |
| 13 | "regexp" |
| 14 | "slices" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "sync" |
| 18 | "time" |
| 19 | "unicode/utf8" |
| 20 | |
| 21 | "github.com/go-chi/chi/v5" |
| 22 | |
| 23 | "amadan.net/oficina/calls/internal/calls/hub" |
| 24 | "amadan.net/oficina/calls/protocol" |
| 25 | ) |
| 26 | |
| 27 | // Quality and problem reports, spec §15.26 (Paul's ruling, 2026-10-03). |
| 28 | // |
| 29 | // Two endpoints, both authorized by the report token a client was given |
| 30 | // in its hello (hub/report.go), presented by the session it was given to, |
| 31 | // for the room it was given for — during the participation and for ten |
| 32 | // minutes after it ends: |
| 33 | // |
| 34 | // - POST /m/{sqid}/quality: the automatic report, every thirty seconds |
| 35 | // and once at leave. A fixed schema (protocol/quality.go), validated |
| 36 | // strictly, re-encoded from what was validated, and written as one |
| 37 | // `calls: quality` line. CALLS_QUALITY_REPORTS=off answers 204 before |
| 38 | // anything else is looked at, and a client that is answered 204 stops |
| 39 | // sending for the rest of the call. |
| 40 | // - POST /m/{sqid}/problem: "Report a problem". The person's note and |
| 41 | // their client's call diagnostics, written as one `calls: problem |
| 42 | // report` line and as many `calls: problem report diagnostics` lines as |
| 43 | // the diagnostics need, under a reference the client shows. |
| 44 | // - POST /m/{sqid}/auto-report: the same diagnostics, sent by the client |
| 45 | // itself when its call is struggling (spec §15.29, 2026-10-28), with |
| 46 | // no note, under a reference of its own; one every ten minutes and |
| 47 | // three in all per participation, and off with the kill switch. |
| 48 | // |
| 49 | // Each quality report is also written as one `calls: quality peer` line |
| 50 | // per remote peer, flat: `carlos logs` prints a line's top-level fields |
| 51 | // and drops anything nested, so the per-peer detail in `report` is |
| 52 | // readable afterwards only from these (§15.29). |
| 53 | // |
| 54 | // Neither touches the database: the log is the only store. Neither log |
| 55 | // line carries the meeting's sqid, a peer id, a person, an email, a name |
| 56 | // or an address; the call and the participation are named only by the |
| 57 | // hub's random tags. |
| 58 | |
| 59 | const ( |
| 60 | // reportTokenHeader carries the token: a header rather than a body |
| 61 | // member so the body stays exactly the schema. |
| 62 | reportTokenHeader = "X-Calls-Report" |
| 63 | // maxReportBuckets bounds both report limiters' maps, as |
| 64 | // maxSignalBuckets does the signal limiter's. |
| 65 | maxReportBuckets = 4096 |
| 66 | // diagnosticsChunk is how much escaped diagnostics text goes in one |
| 67 | // log line. The platform keeps 8 KB of a line and truncates the rest |
| 68 | // (carlos/platform internal/activator/backend_exec.go execLogLineMax), |
| 69 | // so a chunk leaves room for the line's own fields. |
| 70 | diagnosticsChunk = 6000 |
| 71 | ) |
| 72 | |
| 73 | var ( |
| 74 | reportTokenPattern = regexp.MustCompile(`^[0-9a-f]{32}$`) |
| 75 | reportRefPattern = regexp.MustCompile(`^[0-9A-HJKMNP-TV-Z]{8}$`) |
| 76 | regionPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`) |
| 77 | versionPattern = regexp.MustCompile(`^[0-9A-Za-z][0-9A-Za-z.+-]{0,23}$`) |
| 78 | numericVersion = regexp.MustCompile(`^[0-9]{1,4}([._][0-9]{1,6}){0,3}$`) |
| 79 | |
| 80 | reportApps = []string{"web", "mac", "iphone", "ipad"} |
| 81 | reportBrowsers = []string{"chrome", "safari", "firefox", "edge", "other"} |
| 82 | reportOSes = []string{"macos", "ios", "ipados", "windows", "linux", "android", "chromeos", "other"} |
| 83 | ) |
| 84 | |
| 85 | // qualityReportsOn is the kill switch: CALLS_QUALITY_REPORTS=off turns the |
| 86 | // automatic reports off. Anything else, including unset, is on. |
| 87 | func qualityReportsOn(v string) bool { |
| 88 | return !strings.EqualFold(strings.TrimSpace(v), "off") |
| 89 | } |
| 90 | |
| 91 | // reporter resolves the request's report token, or answers 404 itself. |
| 92 | func (a *app) reporter(w http.ResponseWriter, r *http.Request) (hub.Reporter, string, bool) { |
| 93 | sqid := chi.URLParam(r, "sqid") |
| 94 | token := r.Header.Get(reportTokenHeader) |
| 95 | session, ok := a.sessionKey(r) |
| 96 | if !ok || !validSqid(sqid) || !reportTokenPattern.MatchString(token) { |
| 97 | streamJSON(w, http.StatusNotFound, map[string]any{"error": "not-found"}) |
| 98 | return hub.Reporter{}, "", false |
| 99 | } |
| 100 | rep, ok := a.hub.Reporter(sqid, session, token) |
| 101 | if !ok { |
| 102 | streamJSON(w, http.StatusNotFound, map[string]any{"error": "not-found"}) |
| 103 | return hub.Reporter{}, "", false |
| 104 | } |
| 105 | return rep, sqid, true |
| 106 | } |
| 107 | |
| 108 | // readReport reads a body up to limit, answering 413 or 400 itself. |
| 109 | func readReport(w http.ResponseWriter, r *http.Request, limit int64) ([]byte, bool) { |
| 110 | r.Body = http.MaxBytesReader(w, r.Body, limit) |
| 111 | raw, err := io.ReadAll(r.Body) |
| 112 | if err != nil { |
| 113 | var tooBig *http.MaxBytesError |
| 114 | if errors.As(err, &tooBig) { |
| 115 | streamJSON(w, http.StatusRequestEntityTooLarge, map[string]any{"error": "too-large"}) |
| 116 | } else { |
| 117 | streamJSON(w, http.StatusBadRequest, map[string]any{"error": "bad-request"}) |
| 118 | } |
| 119 | return nil, false |
| 120 | } |
| 121 | return raw, true |
| 122 | } |
| 123 | |
| 124 | func rateRefused(w http.ResponseWriter, retry time.Duration) { |
| 125 | w.Header().Set("Retry-After", strconv.Itoa(int(retry.Seconds())+1)) |
| 126 | streamJSON(w, http.StatusTooManyRequests, map[string]any{"error": "rate"}) |
| 127 | } |
| 128 | |
| 129 | // quality is POST /m/{sqid}/quality. |
| 130 | func (a *app) quality(w http.ResponseWriter, r *http.Request) { |
| 131 | if !a.cfg.qualityReports { |
| 132 | w.WriteHeader(http.StatusNoContent) |
| 133 | return |
| 134 | } |
| 135 | rep, _, ok := a.reporter(w, r) |
| 136 | if !ok { |
| 137 | return |
| 138 | } |
| 139 | if allowed, retry := a.qualityLimiter.allow(rep.PeerTag, a.store.now()); !allowed { |
| 140 | rateRefused(w, retry) |
| 141 | return |
| 142 | } |
| 143 | raw, ok := readReport(w, r, protocol.MaxQualityBody) |
| 144 | if !ok { |
| 145 | return |
| 146 | } |
| 147 | q, ok := validateQuality(raw) |
| 148 | if !ok { |
| 149 | streamJSON(w, http.StatusBadRequest, map[string]any{"error": "bad-request"}) |
| 150 | return |
| 151 | } |
| 152 | a.logQuality(rep, q) |
| 153 | w.WriteHeader(http.StatusAccepted) |
| 154 | } |
| 155 | |
| 156 | // problem is POST /m/{sqid}/problem. |
| 157 | func (a *app) problem(w http.ResponseWriter, r *http.Request) { |
| 158 | rep, sqid, ok := a.reporter(w, r) |
| 159 | if !ok { |
| 160 | return |
| 161 | } |
| 162 | if allowed, retry := a.problemLimiter.allow(rep.PeerTag, a.store.now()); !allowed { |
| 163 | rateRefused(w, retry) |
| 164 | return |
| 165 | } |
| 166 | raw, ok := readReport(w, r, protocol.MaxProblemBody) |
| 167 | if !ok { |
| 168 | return |
| 169 | } |
| 170 | p, ok := validateProblem(raw) |
| 171 | if !ok { |
| 172 | streamJSON(w, http.StatusBadRequest, map[string]any{"error": "bad-request"}) |
| 173 | return |
| 174 | } |
| 175 | ref := newReportRef() |
| 176 | a.logProblem(rep, sqid, ref, p) |
| 177 | streamJSON(w, http.StatusOK, map[string]any{"ref": ref}) |
| 178 | } |
| 179 | |
| 180 | // autoReport is POST /m/{sqid}/auto-report (spec §15.29): the client's |
| 181 | // own "Report a problem" when its call is struggling. Authorized, sized |
| 182 | // and scrubbed as a problem report is; switched off with the quality |
| 183 | // reports, because nobody asked for it; and limited to one every ten |
| 184 | // minutes and three in all per participation. |
| 185 | func (a *app) autoReport(w http.ResponseWriter, r *http.Request) { |
| 186 | if !a.cfg.qualityReports { |
| 187 | w.WriteHeader(http.StatusNoContent) |
| 188 | return |
| 189 | } |
| 190 | rep, sqid, ok := a.reporter(w, r) |
| 191 | if !ok { |
| 192 | return |
| 193 | } |
| 194 | // Refused before the body is read when the participation has none to |
| 195 | // spend; spent only once the report is taken, so a refused body does |
| 196 | // not use up one of the call's three. |
| 197 | if allowed, retry := a.autoGate.check(rep.PeerTag, a.store.now()); !allowed { |
| 198 | rateRefused(w, retry) |
| 199 | return |
| 200 | } |
| 201 | raw, ok := readReport(w, r, protocol.MaxProblemBody) |
| 202 | if !ok { |
| 203 | return |
| 204 | } |
| 205 | p, ok := validateAuto(raw) |
| 206 | if !ok { |
| 207 | streamJSON(w, http.StatusBadRequest, map[string]any{"error": "bad-request"}) |
| 208 | return |
| 209 | } |
| 210 | if allowed, retry := a.autoGate.allow(rep.PeerTag, a.store.now()); !allowed { |
| 211 | rateRefused(w, retry) // another got there while this one was read |
| 212 | return |
| 213 | } |
| 214 | ref := newReportRef() |
| 215 | a.logAuto(rep, sqid, ref, p) |
| 216 | streamJSON(w, http.StatusOK, map[string]any{"ref": ref}) |
| 217 | } |
| 218 | |
| 219 | // validateAuto takes a trigger the schema names and the client as every |
| 220 | // report does. A note, if a client sent one, is not a member of the |
| 221 | // schema and is dropped unread. |
| 222 | func validateAuto(raw []byte) (protocol.AutoReport, bool) { |
| 223 | var p protocol.AutoReport |
| 224 | if !utf8.Valid(raw) || json.Unmarshal(raw, &p) != nil { |
| 225 | return p, false |
| 226 | } |
| 227 | if !slices.Contains(protocol.AutoTriggers, p.Trigger) || !validClient(&p.Client) { |
| 228 | return p, false |
| 229 | } |
| 230 | return p, true |
| 231 | } |
| 232 | |
| 233 | // autoReportGate is the automatic report's limit, per participation tag: |
| 234 | // one every AutoReportEveryMinutes, and AutoReportsPerCall in all. Not a |
| 235 | // token bucket, because the bucket forgets a key idle for a minute and |
| 236 | // this has to remember one for the length of a call. Bounded: past |
| 237 | // maxKeys the entry sent longest ago goes. |
| 238 | type autoReportGate struct { |
| 239 | mu sync.Mutex |
| 240 | maxKeys int |
| 241 | sent map[string]autoSent |
| 242 | } |
| 243 | |
| 244 | type autoSent struct { |
| 245 | n int |
| 246 | last time.Time |
| 247 | } |
| 248 | |
| 249 | func newAutoReportGate(maxKeys int) *autoReportGate { |
| 250 | return &autoReportGate{maxKeys: maxKeys, sent: map[string]autoSent{}} |
| 251 | } |
| 252 | |
| 253 | // check says whether key may send one now, spending nothing, or how |
| 254 | // long until it may. |
| 255 | func (g *autoReportGate) check(key string, now time.Time) (bool, time.Duration) { |
| 256 | g.mu.Lock() |
| 257 | defer g.mu.Unlock() |
| 258 | return g.mayLocked(key, now) |
| 259 | } |
| 260 | |
| 261 | func (g *autoReportGate) mayLocked(key string, now time.Time) (bool, time.Duration) { |
| 262 | every := protocol.AutoReportEveryMinutes * time.Minute |
| 263 | e, found := g.sent[key] |
| 264 | if found && e.n >= protocol.AutoReportsPerCall { |
| 265 | // A tag lives one participation, so "never again" is honest; the |
| 266 | // header says the longest a client would wait anyway. |
| 267 | return false, every |
| 268 | } |
| 269 | if found && now.Sub(e.last) < every { |
| 270 | return false, every - now.Sub(e.last) |
| 271 | } |
| 272 | return true, 0 |
| 273 | } |
| 274 | |
| 275 | // allow spends one of key's reports, or says how long until the next. |
| 276 | func (g *autoReportGate) allow(key string, now time.Time) (bool, time.Duration) { |
| 277 | g.mu.Lock() |
| 278 | defer g.mu.Unlock() |
| 279 | if ok, retry := g.mayLocked(key, now); !ok { |
| 280 | return false, retry |
| 281 | } |
| 282 | e, found := g.sent[key] |
| 283 | if !found && len(g.sent) >= g.maxKeys { |
| 284 | var oldest string |
| 285 | var at time.Time |
| 286 | for k, v := range g.sent { |
| 287 | if oldest == "" || v.last.Before(at) { |
| 288 | oldest, at = k, v.last |
| 289 | } |
| 290 | } |
| 291 | delete(g.sent, oldest) |
| 292 | } |
| 293 | g.sent[key] = autoSent{n: e.n + 1, last: now} |
| 294 | return true, 0 |
| 295 | } |
| 296 | |
| 297 | // validateQuality is the strict half: the schema's types (a mistyped |
| 298 | // member fails the decode), its enums, its bounds and its version. A |
| 299 | // member the schema does not name is ignored, never logged: the log line |
| 300 | // is re-encoded from this value, not from the request's bytes. |
| 301 | func validateQuality(raw []byte) (protocol.QualityReport, bool) { |
| 302 | var q protocol.QualityReport |
| 303 | if !utf8.Valid(raw) || json.Unmarshal(raw, &q) != nil { |
| 304 | return q, false |
| 305 | } |
| 306 | if q.V != protocol.QualityVersion || q.Seconds == nil || *q.Seconds <= 0 { |
| 307 | return q, false |
| 308 | } |
| 309 | if !validClient(&q.Client) { |
| 310 | return q, false |
| 311 | } |
| 312 | if d := q.Devices; d != nil && (!enumOrEmpty(d.Input, protocol.DeviceKinds) || !enumOrEmpty(d.Output, protocol.DeviceKinds)) { |
| 313 | return q, false |
| 314 | } |
| 315 | if e := q.Events; e != nil && !enumOrEmpty(e.VideoSetting, protocol.VideoSettings) { |
| 316 | return q, false |
| 317 | } |
| 318 | if h := q.Host; h != nil && !enumOrEmpty(h.Thermal, protocol.ThermalStates) { |
| 319 | return q, false |
| 320 | } |
| 321 | if len(q.Peers) > protocol.MaxQualityPeers { |
| 322 | return q, false |
| 323 | } |
| 324 | seen := map[protocol.PeerID]bool{} |
| 325 | for i := range q.Peers { |
| 326 | p := &q.Peers[i] |
| 327 | if !validPeerID(p.Peer) || seen[p.Peer] { |
| 328 | return q, false |
| 329 | } |
| 330 | seen[p.Peer] = true |
| 331 | if p.Path != nil && (!enumOrEmpty(p.Path.Local, protocol.CandidateKinds) || |
| 332 | !enumOrEmpty(p.Path.Remote, protocol.CandidateKinds) || !enumOrEmpty(p.Path.Protocol, protocol.PathProtocols)) { |
| 333 | return q, false |
| 334 | } |
| 335 | if p.Out != nil { |
| 336 | for _, s := range []*protocol.OutStream{p.Out.Audio, p.Out.Video, p.Out.Screen} { |
| 337 | if s != nil && (!enumOrEmpty(s.Limit, protocol.QualityLimits) || !enumOrEmpty(s.Encoder, protocol.CoderKinds) || |
| 338 | !enumOrEmpty(s.Codec, protocol.Codecs) || !enumOrEmpty(s.Mode, protocol.ShareModes)) { |
| 339 | return q, false |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | if p.In != nil { |
| 344 | for _, v := range []*protocol.InVideo{p.In.Video, p.In.Screen} { |
| 345 | if v != nil && (!enumOrEmpty(v.Decoder, protocol.CoderKinds) || !enumOrEmpty(v.Codec, protocol.Codecs)) { |
| 346 | return q, false |
| 347 | } |
| 348 | } |
| 349 | } |
| 350 | if e := p.Events; e != nil && (!levelSeconds(e.AskedSeconds) || !levelSeconds(e.SentSeconds)) { |
| 351 | return q, false |
| 352 | } |
| 353 | } |
| 354 | if q.AutoReport != "" && !reportRefPattern.MatchString(q.AutoReport) { |
| 355 | return q, false |
| 356 | } |
| 357 | // Every number, wherever it is: finite, non-negative, under its |
| 358 | // ceiling, and rounded to a tenth for the line. |
| 359 | if !boundNumbers(reflect.ValueOf(&q).Elem(), "") { |
| 360 | return q, false |
| 361 | } |
| 362 | return q, true |
| 363 | } |
| 364 | |
| 365 | // levelSeconds is §15.30's seconds-at-each-level: absent, or exactly one |
| 366 | // number for each level, none of them null (boundNumbers checks the rest). |
| 367 | func levelSeconds(v []*float64) bool { |
| 368 | if v == nil { |
| 369 | return true |
| 370 | } |
| 371 | if len(v) != protocol.VideoLevelCount { |
| 372 | return false |
| 373 | } |
| 374 | for _, x := range v { |
| 375 | if x == nil { |
| 376 | return false |
| 377 | } |
| 378 | } |
| 379 | return true |
| 380 | } |
| 381 | |
| 382 | func validClient(c *protocol.ReportClient) bool { |
| 383 | if !slices.Contains(reportApps, c.App) { |
| 384 | return false |
| 385 | } |
| 386 | if c.Version != "" && !versionPattern.MatchString(c.Version) { |
| 387 | return false |
| 388 | } |
| 389 | if !enumOrEmpty(c.Browser, reportBrowsers) || !enumOrEmpty(c.OS, reportOSes) { |
| 390 | return false |
| 391 | } |
| 392 | if c.BrowserVersion != "" && !numericVersion.MatchString(c.BrowserVersion) { |
| 393 | return false |
| 394 | } |
| 395 | if c.OSVersion != "" && !numericVersion.MatchString(c.OSVersion) { |
| 396 | return false |
| 397 | } |
| 398 | return true |
| 399 | } |
| 400 | |
| 401 | func enumOrEmpty(v string, allowed []string) bool { return v == "" || slices.Contains(allowed, v) } |
| 402 | |
| 403 | // numberCeiling is a number's bound, by its JSON name. |
| 404 | func numberCeiling(name string) float64 { |
| 405 | switch name { |
| 406 | case "seconds", "reconnectingSeconds", "cantHearSeconds", "freezeSeconds", |
| 407 | "limitedBandwidthSeconds", "limitedCpuSeconds", |
| 408 | "askedSeconds", "sentSeconds": |
| 409 | return protocol.MaxQualitySeconds |
| 410 | case "rtt", "jitter", "jitterBufferMs", "rttAvg", "rttMax", "jitterAvg", "jitterMax": |
| 411 | return protocol.MaxQualityMillis |
| 412 | case "kbps": |
| 413 | return protocol.MaxQualityKbps |
| 414 | case "width", "height": |
| 415 | return protocol.MaxQualityPixels |
| 416 | case "procCpuPct": |
| 417 | return protocol.MaxQualityCPUPct |
| 418 | case "procMemMB": |
| 419 | return protocol.MaxQualityMemMB |
| 420 | case "sysLoad1": |
| 421 | return protocol.MaxQualityLoad |
| 422 | case "fps": |
| 423 | return protocol.MaxQualityFPS |
| 424 | } |
| 425 | return protocol.MaxQualityCount |
| 426 | } |
| 427 | |
| 428 | // boundNumbers walks the report and checks every *float64 against its |
| 429 | // ceiling, rounding each to one decimal place. |
| 430 | func boundNumbers(v reflect.Value, name string) bool { |
| 431 | switch v.Kind() { |
| 432 | case reflect.Pointer: |
| 433 | if v.IsNil() { |
| 434 | return true |
| 435 | } |
| 436 | if f, ok := v.Interface().(*float64); ok { |
| 437 | x := *f |
| 438 | if math.IsNaN(x) || math.IsInf(x, 0) || x < 0 || x > numberCeiling(name) { |
| 439 | return false |
| 440 | } |
| 441 | *f = math.Round(x*10) / 10 |
| 442 | return true |
| 443 | } |
| 444 | return boundNumbers(v.Elem(), name) |
| 445 | case reflect.Struct: |
| 446 | t := v.Type() |
| 447 | for i := 0; i < v.NumField(); i++ { |
| 448 | tag, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",") |
| 449 | if !boundNumbers(v.Field(i), tag) { |
| 450 | return false |
| 451 | } |
| 452 | } |
| 453 | case reflect.Slice: |
| 454 | for i := 0; i < v.Len(); i++ { |
| 455 | if !boundNumbers(v.Index(i), name) { |
| 456 | return false |
| 457 | } |
| 458 | } |
| 459 | } |
| 460 | return true |
| 461 | } |
| 462 | |
| 463 | // validateProblem bounds the note (characters) and the whole body (bytes, |
| 464 | // by the reader), and the client as the quality report does. |
| 465 | func validateProblem(raw []byte) (protocol.ProblemReport, bool) { |
| 466 | var p protocol.ProblemReport |
| 467 | if !utf8.Valid(raw) || json.Unmarshal(raw, &p) != nil { |
| 468 | return p, false |
| 469 | } |
| 470 | if utf8.RuneCountInString(p.Note) > protocol.MaxProblemNote || !validClient(&p.Client) { |
| 471 | return p, false |
| 472 | } |
| 473 | return p, true |
| 474 | } |
| 475 | |
| 476 | // logQuality writes the one `calls: quality` line. The top level carries |
| 477 | // what the platform can filter on (carlos logs --field): the tags, the |
| 478 | // client, and a few headline numbers; `report` is the rest, as validated, |
| 479 | // with each remote peer's id replaced by its tag. |
| 480 | func (a *app) logQuality(rep hub.Reporter, q protocol.QualityReport) { |
| 481 | sum := summarize(q) |
| 482 | for i := range q.Peers { |
| 483 | q.Peers[i].Peer = protocol.PeerID(tagOrUnknown(rep, q.Peers[i].Peer)) |
| 484 | } |
| 485 | // `report` is what the head's own fields do not say about the whole |
| 486 | // call from here. Each remote peer's part is its own `calls: quality |
| 487 | // peer` line (§15.29), not a member of this one: carlos prints neither |
| 488 | // a nested member nor more than 8 KB of a line, and four peers' |
| 489 | // detail would be both. |
| 490 | body := struct { |
| 491 | Seconds *float64 `json:"seconds"` |
| 492 | Final bool `json:"final,omitempty"` |
| 493 | Devices *protocol.Devices `json:"devices,omitempty"` |
| 494 | Events *protocol.CallEvents `json:"events,omitempty"` |
| 495 | }{q.Seconds, q.Final, q.Devices, q.Events} |
| 496 | attrs := append(clientAttrs(rep, q.Client), |
| 497 | slog.Bool("final", q.Final), |
| 498 | slog.Float64("seconds", *q.Seconds), |
| 499 | slog.Int("remotes", len(q.Peers)), |
| 500 | slog.Bool("relay", sum.relay), |
| 501 | slog.Float64("maxLossPct", sum.lossPct), |
| 502 | slog.Float64("maxRtt", sum.rtt), |
| 503 | slog.Float64("freezes", sum.freezes), |
| 504 | slog.Float64("reconnecting", sum.reconnecting), |
| 505 | ) |
| 506 | // The screen's headline, only what happened: `carlos logs` prints the |
| 507 | // top-level fields and leaves `report` out, so these are what shows a |
| 508 | // screen recovery loop without anyone sending a problem report |
| 509 | // (2026-10-21). |
| 510 | for _, f := range sum.screen { |
| 511 | if f.v > 0 { |
| 512 | attrs = append(attrs, slog.Float64(f.name, f.v)) |
| 513 | } |
| 514 | } |
| 515 | if q.AutoReport != "" { |
| 516 | attrs = append(attrs, slog.String("autoReport", q.AutoReport)) |
| 517 | } |
| 518 | // §15.30's, the same way: how long this client asked someone for less |
| 519 | // video, how long it sent someone less, and the person's own setting. |
| 520 | for _, f := range sum.video { |
| 521 | if f.v > 0 { |
| 522 | attrs = append(attrs, slog.Float64(f.name, f.v)) |
| 523 | } |
| 524 | } |
| 525 | if q.Events != nil && q.Events.VideoSetting != "" { |
| 526 | attrs = append(attrs, slog.String("videoSetting", q.Events.VideoSetting)) |
| 527 | } |
| 528 | // The machine itself (§15.30, 2026-10-29), on the head line where |
| 529 | // carlos logs shows it: what the client measured, and nothing else. |
| 530 | if h := q.Host; h != nil { |
| 531 | for _, f := range []struct { |
| 532 | name string |
| 533 | v *float64 |
| 534 | }{{"procCpuPct", h.ProcCPUPct}, {"procMemMB", h.ProcMemMB}, {"sysLoad1", h.SysLoad1}} { |
| 535 | if f.v != nil { |
| 536 | attrs = append(attrs, slog.Float64(f.name, *f.v)) |
| 537 | } |
| 538 | } |
| 539 | if h.Thermal != "" { |
| 540 | attrs = append(attrs, slog.String("thermal", h.Thermal)) |
| 541 | } |
| 542 | if h.LowPower != nil { |
| 543 | attrs = append(attrs, slog.Bool("lowPower", *h.LowPower)) |
| 544 | } |
| 545 | } |
| 546 | attrs = append(attrs, slog.Any("report", body)) |
| 547 | a.reportLog.LogAttrs(context.Background(), slog.LevelInfo, "calls: quality", attrs...) |
| 548 | region := a.relayRegionName() |
| 549 | for _, p := range q.Peers { |
| 550 | a.reportLog.LogAttrs(context.Background(), slog.LevelInfo, "calls: quality peer", peerAttrs(rep, p, region)...) |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | // relayRegionName is the relay's region for a line whose path went |
| 555 | // through it: known while one region is configured, which is all a |
| 556 | // relayed path can have used. With several, the client's candidate says |
| 557 | // nothing the schema carries about which, and the field is left off. |
| 558 | func (a *app) relayRegionName() string { |
| 559 | regions := a.relayRegions() |
| 560 | if len(regions) != 1 || !regionPattern.MatchString(regions[0].Region) { |
| 561 | return "" |
| 562 | } |
| 563 | return regions[0].Region |
| 564 | } |
| 565 | |
| 566 | // peerAttrs is one `calls: quality peer` line (spec §15.29): one remote |
| 567 | // peer's part of a report, flattened into scalar fields so that `carlos |
| 568 | // logs`, which prints a line's top level and nothing nested, shows all of |
| 569 | // it. Every field is one the report validated — an enum, a bounded |
| 570 | // number, a boolean — under a fixed name; a part the client did not |
| 571 | // measure is left off, never written as zero. `p.Peer` is already the |
| 572 | // remote peer's tag. The names are camelCase letters and digits only, |
| 573 | // because quality-summary reads carlos's key=value records by them. |
| 574 | func peerAttrs(rep hub.Reporter, p protocol.PeerQuality, region string) []slog.Attr { |
| 575 | attrs := []slog.Attr{slog.String("call", rep.CallTag), slog.String("peer", rep.PeerTag), slog.String("remote", string(p.Peer))} |
| 576 | num := func(name string, v *float64) { |
| 577 | if v != nil { |
| 578 | attrs = append(attrs, slog.Float64(name, *v)) |
| 579 | } |
| 580 | } |
| 581 | str := func(name, v string) { |
| 582 | if v != "" { |
| 583 | attrs = append(attrs, slog.String(name, v)) |
| 584 | } |
| 585 | } |
| 586 | flag := func(name string, v bool) { |
| 587 | if v { |
| 588 | attrs = append(attrs, slog.Bool(name, true)) |
| 589 | } |
| 590 | } |
| 591 | pct := func(name string, part, whole *float64, withPart bool) { |
| 592 | if part == nil || whole == nil { |
| 593 | return |
| 594 | } |
| 595 | n := *whole |
| 596 | if withPart { |
| 597 | n += *part |
| 598 | } |
| 599 | if n > 0 { |
| 600 | attrs = append(attrs, slog.Float64(name, math.Round(1000**part/n)/10)) |
| 601 | } |
| 602 | } |
| 603 | if path := p.Path; path != nil { |
| 604 | str("pathLocal", path.Local) |
| 605 | str("pathRemote", path.Remote) |
| 606 | str("pathProtocol", path.Protocol) |
| 607 | if path.Local == "relay" || path.Remote == "relay" { |
| 608 | str("relayRegion", region) |
| 609 | } |
| 610 | } |
| 611 | num("rtt", p.RTT) |
| 612 | num("rttAvg", p.RTTAvg) |
| 613 | num("rttMax", p.RTTMax) |
| 614 | num("jitterAvg", p.JitterAvg) |
| 615 | num("jitterMax", p.JitterMax) |
| 616 | if c := p.Candidates; c != nil { |
| 617 | num("candHost", c.Host) |
| 618 | num("candSrflx", c.Srflx) |
| 619 | num("candPrflx", c.Prflx) |
| 620 | num("candRelay", c.Relay) |
| 621 | num("candRemoteHost", c.RemoteHost) |
| 622 | num("candRemoteSrflx", c.RemoteSrflx) |
| 623 | num("candRemotePrflx", c.RemotePrflx) |
| 624 | num("candRemoteRelay", c.RemoteRelay) |
| 625 | // Present means measured, so false is said, not left off. |
| 626 | attrs = append(attrs, slog.Bool("directOk", c.DirectOK), slog.Bool("localDirectOk", c.LocalDirectOK), slog.Bool("udpOk", c.UDPOK)) |
| 627 | } |
| 628 | if o := p.Out; o != nil { |
| 629 | if s := o.Audio; s != nil { |
| 630 | num("outAudioKbps", s.Kbps) |
| 631 | pct("outAudioLossPct", s.Lost, s.Packets, false) |
| 632 | num("outAudioRtt", s.RTT) |
| 633 | } |
| 634 | for _, v := range []struct { |
| 635 | pre string |
| 636 | s *protocol.OutStream |
| 637 | }{{"outCamera", o.Video}, {"outScreen", o.Screen}} { |
| 638 | s := v.s |
| 639 | if s == nil { |
| 640 | continue |
| 641 | } |
| 642 | num(v.pre+"Kbps", s.Kbps) |
| 643 | num(v.pre+"Width", s.Width) |
| 644 | num(v.pre+"Height", s.Height) |
| 645 | num(v.pre+"Fps", s.FPS) |
| 646 | pct(v.pre+"LossPct", s.Lost, s.Packets, false) |
| 647 | str(v.pre+"Limit", s.Limit) |
| 648 | num(v.pre+"LimitedBandwidthSeconds", s.LimitedBandwidthSeconds) |
| 649 | num(v.pre+"LimitedCpuSeconds", s.LimitedCPUSeconds) |
| 650 | str(v.pre+"Encoder", s.Encoder) |
| 651 | str(v.pre+"Codec", s.Codec) |
| 652 | str(v.pre+"Mode", s.Mode) |
| 653 | num(v.pre+"Keyframes", s.Keyframes) |
| 654 | num(v.pre+"Rebuilds", s.Rebuilds) |
| 655 | num(v.pre+"Reshares", s.Reshares) |
| 656 | num(v.pre+"Failures", s.Failures) |
| 657 | num(v.pre+"Damped", s.Damped) |
| 658 | num(v.pre+"EncoderStalls", s.EncoderStalls) |
| 659 | } |
| 660 | } |
| 661 | if in := p.In; in != nil { |
| 662 | if a := in.Audio; a != nil { |
| 663 | num("inAudioKbps", a.Kbps) |
| 664 | pct("inAudioLossPct", a.Lost, a.Packets, true) |
| 665 | num("inAudioJitter", a.Jitter) |
| 666 | pct("inAudioConcealedPct", a.Concealed, a.Samples, false) |
| 667 | num("inAudioJitterBufferMs", a.JitterBufferMs) |
| 668 | } |
| 669 | for _, v := range []struct { |
| 670 | pre string |
| 671 | s *protocol.InVideo |
| 672 | }{{"inCamera", in.Video}, {"inScreen", in.Screen}} { |
| 673 | s := v.s |
| 674 | if s == nil { |
| 675 | continue |
| 676 | } |
| 677 | num(v.pre+"Kbps", s.Kbps) |
| 678 | num(v.pre+"Width", s.Width) |
| 679 | num(v.pre+"Height", s.Height) |
| 680 | num(v.pre+"Fps", s.FPS) |
| 681 | pct(v.pre+"LossPct", s.Lost, s.Packets, true) |
| 682 | num(v.pre+"Freezes", s.Freezes) |
| 683 | num(v.pre+"FreezeSeconds", s.FreezeSeconds) |
| 684 | num(v.pre+"Decoded", s.Decoded) |
| 685 | num(v.pre+"Dropped", s.Dropped) |
| 686 | str(v.pre+"Decoder", s.Decoder) |
| 687 | str(v.pre+"Codec", s.Codec) |
| 688 | num(v.pre+"Reattaches", s.Reattaches) |
| 689 | num(v.pre+"Stalls", s.Stalls) |
| 690 | num(v.pre+"StallsNoPackets", s.StallsNoPackets) |
| 691 | num(v.pre+"StallsUndecoded", s.StallsUndecoded) |
| 692 | } |
| 693 | } |
| 694 | if e := p.Events; e != nil { |
| 695 | num("reconnecting", e.Reconnecting) |
| 696 | num("reconnectingSeconds", e.ReconnectingSeconds) |
| 697 | num("cantHearSeconds", e.CantHearSeconds) |
| 698 | flag("noSound", e.NoSound) |
| 699 | flag("noSoundFromUs", e.NoSoundFromUs) |
| 700 | flag("audioBlocked", e.AudioBlocked) |
| 701 | flag("screenStalled", e.ScreenStalled) |
| 702 | num("autoRestarts", e.AutoRestarts) |
| 703 | num("autoRebuilds", e.AutoRebuilds) |
| 704 | // §15.30: seconds at each level below normal, asked of them and |
| 705 | // sent to them, flattened, only those that were not zero. |
| 706 | levels := [protocol.VideoLevelCount]string{"Reduced", "Minimal", "Audio"} |
| 707 | for i, name := range levels { |
| 708 | if i < len(e.AskedSeconds) && e.AskedSeconds[i] != nil && *e.AskedSeconds[i] > 0 { |
| 709 | num("asked"+name, e.AskedSeconds[i]) |
| 710 | } |
| 711 | if i < len(e.SentSeconds) && e.SentSeconds[i] != nil && *e.SentSeconds[i] > 0 { |
| 712 | num("sent"+name, e.SentSeconds[i]) |
| 713 | } |
| 714 | } |
| 715 | } |
| 716 | return attrs |
| 717 | } |
| 718 | |
| 719 | func clientAttrs(rep hub.Reporter, c protocol.ReportClient) []slog.Attr { |
| 720 | attrs := []slog.Attr{slog.String("call", rep.CallTag), slog.String("peer", rep.PeerTag), slog.String("app", c.App)} |
| 721 | for _, kv := range [][2]string{{"version", c.Version}, {"browser", c.Browser}, {"browserVersion", c.BrowserVersion}, {"os", c.OS}, {"osVersion", c.OSVersion}} { |
| 722 | if kv[1] != "" { |
| 723 | attrs = append(attrs, slog.String(kv[0], kv[1])) |
| 724 | } |
| 725 | } |
| 726 | return attrs |
| 727 | } |
| 728 | |
| 729 | func tagOrUnknown(rep hub.Reporter, id protocol.PeerID) string { |
| 730 | if tag, ok := rep.Peers[id]; ok { |
| 731 | return tag |
| 732 | } |
| 733 | return "unknown" |
| 734 | } |
| 735 | |
| 736 | type qualitySummary struct { |
| 737 | relay bool |
| 738 | lossPct, rtt, freezes, reconnecting float64 |
| 739 | screen []screenHead |
| 740 | video []screenHead |
| 741 | } |
| 742 | |
| 743 | // screenHead is one of the quality line's screen fields. |
| 744 | type screenHead struct { |
| 745 | name string |
| 746 | v float64 |
| 747 | } |
| 748 | |
| 749 | // summarize is the line's headline: whether any connection went through |
| 750 | // the relay, the worst inbound loss as a percentage of packets, the worst |
| 751 | // round trip, the freezes and the "Reconnecting…" notices. |
| 752 | func summarize(q protocol.QualityReport) qualitySummary { |
| 753 | var s qualitySummary |
| 754 | val := func(p *float64) float64 { |
| 755 | if p == nil { |
| 756 | return 0 |
| 757 | } |
| 758 | return *p |
| 759 | } |
| 760 | loss := func(packets, lost *float64) { |
| 761 | n, l := val(packets), val(lost) |
| 762 | if n+l > 0 { |
| 763 | s.lossPct = max(s.lossPct, math.Round(1000*l/(n+l))/10) |
| 764 | } |
| 765 | } |
| 766 | if q.Events != nil { |
| 767 | s.reconnecting += val(q.Events.Reconnecting) |
| 768 | } |
| 769 | var stalls, noPackets, undecoded, reported, reattaches float64 |
| 770 | var keyframes, rebuilds, reshares, failures, damped, encoderStalls float64 |
| 771 | for _, p := range q.Peers { |
| 772 | if p.In != nil && p.In.Screen != nil { |
| 773 | v := p.In.Screen |
| 774 | stalls += val(v.Stalls) |
| 775 | noPackets += val(v.StallsNoPackets) |
| 776 | undecoded += val(v.StallsUndecoded) |
| 777 | reattaches += val(v.Reattaches) |
| 778 | } |
| 779 | if p.Events != nil && p.Events.ScreenStalled { |
| 780 | reported++ |
| 781 | } |
| 782 | if p.Out != nil && p.Out.Screen != nil { |
| 783 | o := p.Out.Screen |
| 784 | keyframes += val(o.Keyframes) |
| 785 | rebuilds += val(o.Rebuilds) |
| 786 | reshares += val(o.Reshares) |
| 787 | failures += val(o.Failures) |
| 788 | damped += val(o.Damped) |
| 789 | encoderStalls += val(o.EncoderStalls) |
| 790 | } |
| 791 | } |
| 792 | // A client from before the counts says only that a report was out. |
| 793 | s.screen = []screenHead{ |
| 794 | {"screenStalls", max(stalls, reported)}, {"screenStallsNoPackets", noPackets}, |
| 795 | {"screenStallsUndecoded", undecoded}, {"screenReattaches", reattaches}, |
| 796 | {"screenKeyframes", keyframes}, {"screenRebuilds", rebuilds}, {"screenReshares", reshares}, |
| 797 | {"screenFailures", failures}, {"screenDamped", damped}, {"screenEncoderStalls", encoderStalls}, |
| 798 | } |
| 799 | var asked, sent float64 |
| 800 | for _, p := range q.Peers { |
| 801 | if e := p.Events; e != nil { |
| 802 | for _, x := range e.AskedSeconds { |
| 803 | asked += val(x) |
| 804 | } |
| 805 | for _, x := range e.SentSeconds { |
| 806 | sent += val(x) |
| 807 | } |
| 808 | } |
| 809 | } |
| 810 | s.video = []screenHead{{"videoAsked", math.Round(asked*10) / 10}, {"videoSent", math.Round(sent*10) / 10}} |
| 811 | for _, p := range q.Peers { |
| 812 | if p.Path != nil && (p.Path.Local == "relay" || p.Path.Remote == "relay") { |
| 813 | s.relay = true |
| 814 | } |
| 815 | s.rtt = max(s.rtt, val(p.RTT), val(p.RTTMax)) |
| 816 | if p.In != nil { |
| 817 | if p.In.Audio != nil { |
| 818 | loss(p.In.Audio.Packets, p.In.Audio.Lost) |
| 819 | } |
| 820 | for _, v := range []*protocol.InVideo{p.In.Video, p.In.Screen} { |
| 821 | if v != nil { |
| 822 | loss(v.Packets, v.Lost) |
| 823 | s.freezes += val(v.Freezes) |
| 824 | } |
| 825 | } |
| 826 | } |
| 827 | if p.Out != nil { |
| 828 | for _, o := range []*protocol.OutStream{p.Out.Audio, p.Out.Video, p.Out.Screen} { |
| 829 | if o != nil { |
| 830 | s.rtt = max(s.rtt, val(o.RTT)) |
| 831 | } |
| 832 | } |
| 833 | } |
| 834 | if p.Events != nil { |
| 835 | s.reconnecting += val(p.Events.Reconnecting) |
| 836 | } |
| 837 | } |
| 838 | return s |
| 839 | } |
| 840 | |
| 841 | // logProblem writes the report: one head line with the note, and the |
| 842 | // diagnostics in as many lines as they take, each under the reference. |
| 843 | func (a *app) logProblem(rep hub.Reporter, sqid, ref string, p protocol.ProblemReport) { |
| 844 | scrub := scrubber(rep, sqid) |
| 845 | attrs := append([]slog.Attr{slog.String("ref", ref)}, clientAttrs(rep, p.Client)...) |
| 846 | attrs = append(attrs, slog.Bool("live", rep.Live), slog.String("note", scrub(p.Note))) |
| 847 | a.logDiagnostics(rep, ref, "calls: problem report", attrs, scrub(p.Diagnostics)) |
| 848 | } |
| 849 | |
| 850 | // logAuto writes an automatic report (spec §15.29) as logProblem writes a |
| 851 | // problem report, under its own messages, with the rule that fired in |
| 852 | // place of a note: nobody typed anything. |
| 853 | func (a *app) logAuto(rep hub.Reporter, sqid, ref string, p protocol.AutoReport) { |
| 854 | scrub := scrubber(rep, sqid) |
| 855 | attrs := append([]slog.Attr{slog.String("ref", ref)}, clientAttrs(rep, p.Client)...) |
| 856 | attrs = append(attrs, slog.Bool("live", rep.Live), slog.String("trigger", p.Trigger)) |
| 857 | a.logDiagnostics(rep, ref, "calls: auto report", attrs, scrub(p.Diagnostics)) |
| 858 | } |
| 859 | |
| 860 | // logDiagnostics writes a head line, msg, with attrs and how many parts |
| 861 | // follow, and the diagnostics as `<msg> diagnostics` lines of at most |
| 862 | // diagnosticsChunk escaped bytes each. |
| 863 | func (a *app) logDiagnostics(rep hub.Reporter, ref, msg string, attrs []slog.Attr, diagnostics string) { |
| 864 | chunks := chunkEscaped(diagnostics, diagnosticsChunk) |
| 865 | attrs = append(attrs, slog.Int("parts", len(chunks))) |
| 866 | a.reportLog.LogAttrs(context.Background(), slog.LevelWarn, msg, attrs...) |
| 867 | for i, c := range chunks { |
| 868 | a.reportLog.LogAttrs(context.Background(), slog.LevelWarn, msg+" diagnostics", |
| 869 | slog.String("ref", ref), slog.String("call", rep.CallTag), slog.String("peer", rep.PeerTag), |
| 870 | slog.Int("part", i+1), slog.Int("of", len(chunks)), slog.String("text", c)) |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | // scrubber cleans a report's text of what the client could not know to |
| 875 | // leave out: every peer id this call has held, in full or as the |
| 876 | // six-character prefix the diagnostics use, becomes "peer:<tag>", and the |
| 877 | // meeting's sqid becomes "[meeting]". A client already writes "peer |
| 878 | // abc123" for a person instead of their name; device names stay, which |
| 879 | // the spec says. |
| 880 | func scrubber(rep hub.Reporter, sqid string) func(string) string { |
| 881 | return func(s string) string { |
| 882 | s = strings.ReplaceAll(s, sqid, "[meeting]") |
| 883 | for id, tag := range rep.Peers { |
| 884 | s = strings.ReplaceAll(s, string(id), "peer:"+tag) |
| 885 | } |
| 886 | for id, tag := range rep.Peers { |
| 887 | s = strings.ReplaceAll(s, string(id)[:6], "peer:"+tag) |
| 888 | } |
| 889 | return s |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | // chunkEscaped splits s into pieces whose JSON-escaped length is at most |
| 894 | // limit bytes, never inside a rune. |
| 895 | func chunkEscaped(s string, limit int) []string { |
| 896 | if s == "" { |
| 897 | return nil |
| 898 | } |
| 899 | var out []string |
| 900 | var b strings.Builder |
| 901 | size := 0 |
| 902 | for _, r := range s { |
| 903 | enc, _ := json.Marshal(string(r)) |
| 904 | n := len(enc) - 2 |
| 905 | if size+n > limit && b.Len() > 0 { |
| 906 | out = append(out, b.String()) |
| 907 | b.Reset() |
| 908 | size = 0 |
| 909 | } |
| 910 | b.WriteRune(r) |
| 911 | size += n |
| 912 | } |
| 913 | if b.Len() > 0 { |
| 914 | out = append(out, b.String()) |
| 915 | } |
| 916 | return out |
| 917 | } |
| 918 | |
| 919 | // refAlphabet is Crockford's: no I, L, O or U, so a reference read aloud |
| 920 | // or copied by hand comes back the same. |
| 921 | const refAlphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" |
| 922 | |
| 923 | // newReportRef is a problem report's reference: eight characters, forty |
| 924 | // random bits. |
| 925 | func newReportRef() string { |
| 926 | b := make([]byte, 8) |
| 927 | if _, err := rand.Read(b); err != nil { |
| 928 | panic(err) |
| 929 | } |
| 930 | for i := range b { |
| 931 | b[i] = refAlphabet[int(b[i])%len(refAlphabet)] |
| 932 | } |
| 933 | return string(b) |
| 934 | } |
| 935 | |