| 1 | package callscore |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "slices" |
| 10 | "sort" |
| 11 | "sync" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/calls/protocol" |
| 15 | ) |
| 16 | |
| 17 | // Event crosses the native bridge as JSON. Message is a server envelope; |
| 18 | // snapshot events carry authoritative local state. Media never crosses it. |
| 19 | type Event struct { |
| 20 | Info *Info `json:"info,omitempty"` |
| 21 | Type string `json:"type"` |
| 22 | State *Snapshot `json:"state,omitempty"` |
| 23 | Message *protocol.Message `json:"message,omitempty"` |
| 24 | ICE *ICEServers `json:"ice,omitempty"` |
| 25 | Signal *protocol.Signal `json:"signal,omitempty"` |
| 26 | } |
| 27 | type Snapshot struct { |
| 28 | Phase string `json:"phase"` |
| 29 | Peer protocol.PeerID `json:"peer"` |
| 30 | Boot string `json:"boot"` |
| 31 | Reason string `json:"reason,omitempty"` |
| 32 | Peers []protocol.RosterPeer `json:"peers"` |
| 33 | Waiting []protocol.RosterPeer `json:"waiting"` |
| 34 | } |
| 35 | |
| 36 | type lane struct { |
| 37 | queue chan protocol.Signal |
| 38 | ctx context.Context |
| 39 | cancel context.CancelFunc |
| 40 | } |
| 41 | |
| 42 | // Room is single-use. Callbacks are serialized and must return promptly. A host |
| 43 | // should enqueue them on its UI executor, never perform media work inline. |
| 44 | type Room struct { |
| 45 | mu sync.Mutex |
| 46 | emitMu sync.Mutex |
| 47 | t *transport |
| 48 | callback func(Event) |
| 49 | ctx context.Context |
| 50 | cancel context.CancelFunc |
| 51 | wg sync.WaitGroup |
| 52 | started bool |
| 53 | stopped bool |
| 54 | state Snapshot |
| 55 | last map[protocol.PeerID]uint64 |
| 56 | seq map[protocol.PeerID]uint64 |
| 57 | lanes map[protocol.PeerID]*lane |
| 58 | blocked map[protocol.PeerID]bool |
| 59 | iceWake chan struct{} |
| 60 | // media is this client's own microphone and camera, as the host last |
| 61 | // set it (§15.19). It outlives a fresh join: a restart does not |
| 62 | // unmute anybody. |
| 63 | media protocol.MediaState |
| 64 | // plainScreen: the server refused a report naming stalled screens |
| 65 | // (it predates §15.21), so reports go without them. |
| 66 | plainScreen bool |
| 67 | // plainHearing: the server refused a report saying who this client |
| 68 | // hears (it predates §15.24), so reports go without the key, and the |
| 69 | // people on new clients fall back to their own evidence about us. |
| 70 | plainHearing bool |
| 71 | // plainVideo: the server refused a report carrying §15.30's video |
| 72 | // asks — one from before it — so they are left out from then on. |
| 73 | plainVideo bool |
| 74 | // report is the latest hello's report token (spec §15.26): a resumed |
| 75 | // hello carries the same one, a fresh participation a new one. Kept |
| 76 | // past Close, for the after-call window (report.go). |
| 77 | report string |
| 78 | } |
| 79 | |
| 80 | func New(origin, room string, authenticated *http.Client, callback func(Event)) (*Room, error) { |
| 81 | t, err := newTransport(origin, room, authenticated) |
| 82 | if err != nil { |
| 83 | return nil, err |
| 84 | } |
| 85 | if callback == nil { |
| 86 | return nil, errors.New("a room event handler is required") |
| 87 | } |
| 88 | ctx, cancel := context.WithCancel(context.Background()) |
| 89 | return &Room{t: t, callback: callback, ctx: ctx, cancel: cancel, state: Snapshot{Phase: "ready", Peers: []protocol.RosterPeer{}, Waiting: []protocol.RosterPeer{}}, media: protocol.MediaState{Hearing: []protocol.PeerID{}}, last: map[protocol.PeerID]uint64{}, seq: map[protocol.PeerID]uint64{}, lanes: map[protocol.PeerID]*lane{}, blocked: map[protocol.PeerID]bool{}, iceWake: make(chan struct{}, 1)}, nil |
| 90 | } |
| 91 | func (r *Room) emit(e Event) { r.emitMu.Lock(); defer r.emitMu.Unlock(); r.callback(e) } |
| 92 | func (r *Room) snapshotLocked() Snapshot { |
| 93 | s := r.state |
| 94 | s.Peers = append([]protocol.RosterPeer{}, s.Peers...) |
| 95 | s.Waiting = append([]protocol.RosterPeer{}, s.Waiting...) |
| 96 | return s |
| 97 | } |
| 98 | func (r *Room) Snapshot() Snapshot { r.mu.Lock(); defer r.mu.Unlock(); return r.snapshotLocked() } |
| 99 | |
| 100 | // ShareLink asks the server for a current invitation using this session's |
| 101 | // authority. It is blocking and belongs on the host's background executor. |
| 102 | func (r *Room) ShareLink() (string, error) { return r.t.shareLink(r.ctx) } |
| 103 | func (r *Room) publish() { s := r.Snapshot(); r.emit(Event{Type: "state", State: &s}) } |
| 104 | func (r *Room) Start() error { |
| 105 | r.mu.Lock() |
| 106 | if r.started || r.stopped { |
| 107 | r.mu.Unlock() |
| 108 | return errors.New("room already started or closed") |
| 109 | } |
| 110 | r.started = true |
| 111 | r.state.Phase = "connecting" |
| 112 | r.wg.Add(2) |
| 113 | r.mu.Unlock() |
| 114 | r.publish() |
| 115 | go func() { defer r.wg.Done(); r.streamLoop() }() |
| 116 | go func() { defer r.wg.Done(); r.iceLoop() }() |
| 117 | return nil |
| 118 | } |
| 119 | |
| 120 | // Close cancels all network work and waits for callbacks to finish. Do not call |
| 121 | // it from a callback. Leave attempts the departure before closing. |
| 122 | func (r *Room) Close() { |
| 123 | r.mu.Lock() |
| 124 | r.stopped = true |
| 125 | r.cancel() |
| 126 | r.mu.Unlock() |
| 127 | r.wg.Wait() |
| 128 | } |
| 129 | func (r *Room) Leave() { |
| 130 | r.mu.Lock() |
| 131 | peer := r.state.Peer |
| 132 | r.mu.Unlock() |
| 133 | if peer != "" { |
| 134 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 135 | _ = r.t.post(ctx, protocol.Signal{Peer: peer, Type: protocol.TypeLeave}) |
| 136 | cancel() |
| 137 | } |
| 138 | r.terminal("left") |
| 139 | r.Close() |
| 140 | } |
| 141 | func (r *Room) terminal(reason string) { |
| 142 | r.mu.Lock() |
| 143 | if r.stopped { |
| 144 | r.mu.Unlock() |
| 145 | return |
| 146 | } |
| 147 | r.stopped = true |
| 148 | r.state.Phase = "ended" |
| 149 | r.state.Reason = reason |
| 150 | r.state.Peers = []protocol.RosterPeer{} |
| 151 | r.state.Waiting = []protocol.RosterPeer{} |
| 152 | r.cancel() |
| 153 | r.mu.Unlock() |
| 154 | r.publish() |
| 155 | } |
| 156 | func (r *Room) fresh() { |
| 157 | r.mu.Lock() |
| 158 | r.state = Snapshot{Phase: "connecting", Peers: []protocol.RosterPeer{}, Waiting: []protocol.RosterPeer{}} |
| 159 | r.last = map[protocol.PeerID]uint64{} |
| 160 | r.seq = map[protocol.PeerID]uint64{} |
| 161 | for _, l := range r.lanes { |
| 162 | l.cancel() |
| 163 | } |
| 164 | r.lanes = map[protocol.PeerID]*lane{} |
| 165 | r.blocked = map[protocol.PeerID]bool{} |
| 166 | r.mu.Unlock() |
| 167 | r.publish() |
| 168 | } |
| 169 | func (r *Room) streamLoop() { |
| 170 | if info, err := r.t.info(r.ctx); err == nil { |
| 171 | r.emit(Event{Type: "info", Info: &info}) |
| 172 | } |
| 173 | |
| 174 | delay := 500 * time.Millisecond |
| 175 | // A fresh open refused with 409 means this session already holds a |
| 176 | // participation in the room. For an app that is its own ghost: the |
| 177 | // previous run of the app (quit, crashed, relaunched by an update) |
| 178 | // whose participation is still inside its thirty-second resume |
| 179 | // window. The session is the app's alone, so it takes its own place |
| 180 | // back, once, rather than ending the call as "open elsewhere" before |
| 181 | // it began. A second instance that really is elsewhere is told |
| 182 | // lost{replaced} on its own stream, and does not take it back. |
| 183 | tookOver := false |
| 184 | for r.ctx.Err() == nil { |
| 185 | r.mu.Lock() |
| 186 | peer := r.state.Peer |
| 187 | q := url.Values{} |
| 188 | if peer != "" { |
| 189 | b, _ := json.Marshal(r.last) |
| 190 | q.Set("peer", string(peer)) |
| 191 | q.Set("last", string(b)) |
| 192 | } |
| 193 | r.mu.Unlock() |
| 194 | began := time.Now() |
| 195 | streamCtx, streamCancel := context.WithTimeout(r.ctx, 6*time.Minute) |
| 196 | res, err := r.t.request(streamCtx, http.MethodGet, "stream", q, nil) |
| 197 | if err == nil { |
| 198 | err = readEvents(res.Body, r.receive) |
| 199 | res.Body.Close() |
| 200 | } |
| 201 | streamCancel() |
| 202 | if r.ctx.Err() != nil { |
| 203 | return |
| 204 | } |
| 205 | var refusal *HTTPError |
| 206 | if errors.As(err, &refusal) { |
| 207 | switch refusal.Status { |
| 208 | case 410: |
| 209 | reason := refusal.Reason |
| 210 | if reason == "" { |
| 211 | reason = "expired" |
| 212 | } |
| 213 | r.terminal(reason) |
| 214 | return |
| 215 | case 409: |
| 216 | if peer == "" && !tookOver { |
| 217 | tookOver = true |
| 218 | if r.t.takeover(r.ctx) == nil { |
| 219 | continue |
| 220 | } |
| 221 | } |
| 222 | r.terminal("replaced") |
| 223 | return |
| 224 | case 401, 403, 302, 303, 307, 308: |
| 225 | r.terminal("signin") |
| 226 | return |
| 227 | case 404: |
| 228 | if peer != "" { |
| 229 | r.fresh() |
| 230 | delay = 500 * time.Millisecond |
| 231 | continue |
| 232 | } |
| 233 | r.terminal("unavailable") |
| 234 | return |
| 235 | case 400, 406: |
| 236 | r.terminal("protocol") |
| 237 | return |
| 238 | } |
| 239 | } |
| 240 | r.mu.Lock() |
| 241 | r.state.Phase = "reconnecting" |
| 242 | r.mu.Unlock() |
| 243 | r.publish() |
| 244 | if time.Since(began) > 5*time.Second { |
| 245 | delay = 500 * time.Millisecond |
| 246 | } |
| 247 | if !pause(r.ctx, delay) { |
| 248 | return |
| 249 | } |
| 250 | delay = min(delay*2, 10*time.Second) |
| 251 | } |
| 252 | } |
| 253 | func pause(ctx context.Context, d time.Duration) bool { |
| 254 | timer := time.NewTimer(d) |
| 255 | defer timer.Stop() |
| 256 | select { |
| 257 | case <-ctx.Done(): |
| 258 | return false |
| 259 | case <-timer.C: |
| 260 | return true |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // SetMedia records this client's own microphone and camera state and, |
| 265 | // once admitted, reports it (§15.19). Before admission there is nobody |
| 266 | // to tell; the roster that admits this client is compared against it |
| 267 | // and the report goes then, as it does after every resume and restart. |
| 268 | func (r *Room) SetMedia(muted, cameraOff bool) error { |
| 269 | r.mu.Lock() |
| 270 | if r.media.Muted == muted && r.media.CameraOff == cameraOff { |
| 271 | r.mu.Unlock() |
| 272 | return nil |
| 273 | } |
| 274 | r.media.Muted, r.media.CameraOff = muted, cameraOff |
| 275 | r.mu.Unlock() |
| 276 | return r.reportMedia() |
| 277 | } |
| 278 | |
| 279 | // SetNoSoundFrom records which peers this client is receiving silence |
| 280 | // from (spec §15.20) and reports it with the rest of its media state. |
| 281 | // Only peers in the current roster other than this client are kept, in |
| 282 | // roster order, so the report is stable and bounded; an empty list is |
| 283 | // the ordinary report. A native app is never refused playback by an |
| 284 | // autoplay policy, so audioBlocked is never set from here. |
| 285 | func (r *Room) SetNoSoundFrom(peers []protocol.PeerID) error { |
| 286 | want := make(map[protocol.PeerID]bool, len(peers)) |
| 287 | for _, p := range peers { |
| 288 | want[p] = true |
| 289 | } |
| 290 | r.mu.Lock() |
| 291 | var next []protocol.PeerID |
| 292 | for _, p := range r.state.Peers { |
| 293 | if p.Peer != r.state.Peer && want[p.Peer] && len(next) < protocol.MaxNoSoundFrom { |
| 294 | next = append(next, p.Peer) |
| 295 | } |
| 296 | } |
| 297 | if (protocol.MediaState{NoSoundFrom: next}).Equal(protocol.MediaState{NoSoundFrom: r.media.NoSoundFrom}) { |
| 298 | r.mu.Unlock() |
| 299 | return nil |
| 300 | } |
| 301 | r.media.NoSoundFrom = next |
| 302 | r.mu.Unlock() |
| 303 | return r.reportMedia() |
| 304 | } |
| 305 | |
| 306 | // SetScreenStalled records whose shared screen has stopped moving here |
| 307 | // (spec §15.21) and reports it with the rest of this client's media |
| 308 | // state, exactly as SetNoSoundFrom does its list: roster peers only, in |
| 309 | // roster order, bounded, and an empty list the ordinary report. |
| 310 | func (r *Room) SetScreenStalled(peers []protocol.PeerID) error { |
| 311 | want := make(map[protocol.PeerID]bool, len(peers)) |
| 312 | for _, p := range peers { |
| 313 | want[p] = true |
| 314 | } |
| 315 | r.mu.Lock() |
| 316 | var next []protocol.PeerID |
| 317 | for _, p := range r.state.Peers { |
| 318 | if p.Peer != r.state.Peer && want[p.Peer] && len(next) < protocol.MaxScreenStalled { |
| 319 | next = append(next, p.Peer) |
| 320 | } |
| 321 | } |
| 322 | if (protocol.MediaState{ScreenStalled: next}).Equal(protocol.MediaState{ScreenStalled: r.media.ScreenStalled}) { |
| 323 | r.mu.Unlock() |
| 324 | return nil |
| 325 | } |
| 326 | r.media.ScreenStalled = next |
| 327 | r.mu.Unlock() |
| 328 | return r.reportMedia() |
| 329 | } |
| 330 | |
| 331 | // SetHearing records which peers this client is actually receiving and |
| 332 | // playing audio from (spec §15.24) and reports it with the rest of its |
| 333 | // media state. Roster peers only, in roster order, bounded, exactly as |
| 334 | // SetNoSoundFrom keeps its list — except that empty is not absent here: |
| 335 | // this client always says who it hears, and "nobody yet" is [] on the |
| 336 | // wire, so the people it has not yet heard know to wait for it rather |
| 337 | // than fall back to guessing. |
| 338 | func (r *Room) SetHearing(peers []protocol.PeerID) error { |
| 339 | want := make(map[protocol.PeerID]bool, len(peers)) |
| 340 | for _, p := range peers { |
| 341 | want[p] = true |
| 342 | } |
| 343 | r.mu.Lock() |
| 344 | next := []protocol.PeerID{} |
| 345 | for _, p := range r.state.Peers { |
| 346 | if p.Peer != r.state.Peer && want[p.Peer] && len(next) < protocol.MaxHearing { |
| 347 | next = append(next, p.Peer) |
| 348 | } |
| 349 | } |
| 350 | if (protocol.MediaState{Hearing: next}).Equal(protocol.MediaState{Hearing: r.media.Hearing}) { |
| 351 | r.mu.Unlock() |
| 352 | return nil |
| 353 | } |
| 354 | r.media.Hearing = next |
| 355 | r.mu.Unlock() |
| 356 | return r.reportMedia() |
| 357 | } |
| 358 | |
| 359 | // SetVideo records what this client, as a receiver, asks each sender for |
| 360 | // (spec §15.30) and reports it with the rest of its media state. Roster |
| 361 | // peers other than this client only, at most protocol.MaxVideo, and only |
| 362 | // the levels the wire has: an entry for "normal", or for anything else, is |
| 363 | // dropped, because normal is the absence of an entry. |
| 364 | func (r *Room) SetVideo(asks map[protocol.PeerID]protocol.VideoLevel) error { |
| 365 | r.mu.Lock() |
| 366 | var next map[protocol.PeerID]protocol.VideoLevel |
| 367 | for _, p := range r.state.Peers { |
| 368 | level, ok := asks[p.Peer] |
| 369 | if p.Peer == r.state.Peer || !ok || !slices.Contains(protocol.VideoLevels, level) || len(next) >= protocol.MaxVideo { |
| 370 | continue |
| 371 | } |
| 372 | if next == nil { |
| 373 | next = map[protocol.PeerID]protocol.VideoLevel{} |
| 374 | } |
| 375 | next[p.Peer] = level |
| 376 | } |
| 377 | if (protocol.MediaState{Video: next}).Equal(protocol.MediaState{Video: r.media.Video}) { |
| 378 | r.mu.Unlock() |
| 379 | return nil |
| 380 | } |
| 381 | r.media.Video = next |
| 382 | r.mu.Unlock() |
| 383 | return r.reportMedia() |
| 384 | } |
| 385 | |
| 386 | func (r *Room) reportMedia() error { |
| 387 | r.mu.Lock() |
| 388 | report := r.state.Phase == "admitted" && !r.stopped |
| 389 | r.mu.Unlock() |
| 390 | if !report { |
| 391 | return nil |
| 392 | } |
| 393 | return r.sendMedia() |
| 394 | } |
| 395 | |
| 396 | func (r *Room) sendMedia() error { |
| 397 | r.mu.Lock() |
| 398 | b, err := json.Marshal(r.wireMediaLocked()) |
| 399 | r.mu.Unlock() |
| 400 | if err != nil { |
| 401 | return err |
| 402 | } |
| 403 | return r.Send(protocol.TypeMedia, "", 0, string(b)) |
| 404 | } |
| 405 | |
| 406 | // wireMediaLocked is the report as this server will take it: the host's |
| 407 | // state without the keys an older server has refused. |
| 408 | func (r *Room) wireMediaLocked() protocol.MediaState { |
| 409 | report := r.media |
| 410 | if r.plainScreen { |
| 411 | // A server from before §15.21 refuses the key; everything else |
| 412 | // in the report still matters. |
| 413 | report.ScreenStalled = nil |
| 414 | } |
| 415 | if r.plainHearing { |
| 416 | report.Hearing = nil |
| 417 | } |
| 418 | if r.plainVideo { |
| 419 | report.Video = nil |
| 420 | } |
| 421 | return report |
| 422 | } |
| 423 | |
| 424 | // refusedExtras is a server from before §15.30, §15.24 or §15.21 refusing a |
| 425 | // media report because of a key it does not know: the newest key goes |
| 426 | // first — §15.30's video asks when the report had any, then hearing, which |
| 427 | // every report from this core carries — and the report is |
| 428 | // sent again without it; a second refusal, of a report naming stalled |
| 429 | // screens, takes those off too. From then on reports go without them, so |
| 430 | // a mute is never lost to an old server. Without hearing, the people on |
| 431 | // new clients fall back to their own evidence that they can be heard |
| 432 | // (§15.24); without screenStalled the sharer recovers on its own watchdog. |
| 433 | func (r *Room) refusedExtras(s protocol.Signal) bool { |
| 434 | var sent protocol.MediaState |
| 435 | if json.Unmarshal(s.Payload, &sent) != nil { |
| 436 | return false |
| 437 | } |
| 438 | r.mu.Lock() |
| 439 | dropped := false |
| 440 | if len(sent.Video) > 0 && !r.plainVideo { |
| 441 | r.plainVideo = true |
| 442 | dropped = true |
| 443 | } else if sent.Hearing != nil && !r.plainHearing { |
| 444 | r.plainHearing = true |
| 445 | dropped = true |
| 446 | } else if len(sent.ScreenStalled) > 0 && !r.plainScreen { |
| 447 | r.plainScreen = true |
| 448 | dropped = true |
| 449 | } |
| 450 | r.mu.Unlock() |
| 451 | if dropped { |
| 452 | go func() { _ = r.sendMedia() }() |
| 453 | } |
| 454 | return dropped |
| 455 | } |
| 456 | |
| 457 | // mediaStaleLocked says whether the hub's record of this client — its |
| 458 | // own entry in the roster just applied — differs from what the host last |
| 459 | // set, or is missing, which is how a fresh participation, a restarted |
| 460 | // server, or a report lost while the stream was down all look. |
| 461 | func (r *Room) mediaStaleLocked() bool { |
| 462 | for _, p := range r.state.Peers { |
| 463 | if p.Peer == r.state.Peer { |
| 464 | return p.Media == nil || !p.Media.Equal(r.wireMediaLocked()) |
| 465 | } |
| 466 | } |
| 467 | return false |
| 468 | } |
| 469 | |
| 470 | // applyMediaLocked is a `media` event: one peer's new state, replacing |
| 471 | // its roster entry's pointer rather than writing through it, because |
| 472 | // snapshots already handed out share the old one. |
| 473 | func (r *Room) applyMediaLocked(m protocol.Message) { |
| 474 | var next protocol.MediaState |
| 475 | if m.From == "" || json.Unmarshal(m.Payload, &next) != nil { |
| 476 | return |
| 477 | } |
| 478 | for i, p := range r.state.Peers { |
| 479 | if p.Peer == m.From { |
| 480 | r.state.Peers[i].Media = &next |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | func (r *Room) generationLocked(peer protocol.PeerID) uint64 { |
| 486 | for _, p := range r.state.Peers { |
| 487 | if p.Peer == peer { |
| 488 | return p.Gen |
| 489 | } |
| 490 | } |
| 491 | return 0 |
| 492 | } |
| 493 | func targeted(typ string) bool { |
| 494 | return typ == protocol.TypeOffer || typ == protocol.TypeAnswer || typ == protocol.TypeCandidate |
| 495 | } |
| 496 | |
| 497 | func (r *Room) receive(m protocol.Message) error { |
| 498 | r.mu.Lock() |
| 499 | if r.stopped { |
| 500 | r.mu.Unlock() |
| 501 | return context.Canceled |
| 502 | } |
| 503 | join, ice, reset, report := false, false, protocol.PeerID(""), false |
| 504 | switch m.Type { |
| 505 | case protocol.TypeHello: |
| 506 | join = r.state.Peer == "" |
| 507 | r.state.Peer = m.Peer |
| 508 | r.state.Boot = m.Boot |
| 509 | if m.Report != "" { |
| 510 | r.report = m.Report |
| 511 | } |
| 512 | if join { |
| 513 | r.state.Phase = "joining" |
| 514 | } |
| 515 | case protocol.TypeRoster: |
| 516 | if m.Roster == nil { |
| 517 | r.mu.Unlock() |
| 518 | return errors.New("missing roster") |
| 519 | } |
| 520 | for _, p := range m.Roster.Peers { |
| 521 | if p.Gen > r.generationLocked(p.Peer) { |
| 522 | delete(r.blocked, p.Peer) |
| 523 | } |
| 524 | } |
| 525 | for _, p := range r.state.Peers { |
| 526 | present := false |
| 527 | for _, next := range m.Roster.Peers { |
| 528 | if next.Peer == p.Peer { |
| 529 | present = true |
| 530 | } |
| 531 | } |
| 532 | if !present { |
| 533 | r.dropLaneLocked(p.Peer) |
| 534 | } |
| 535 | } |
| 536 | r.state.Peers = append([]protocol.RosterPeer{}, m.Roster.Peers...) |
| 537 | r.state.Waiting = append([]protocol.RosterPeer{}, m.Roster.Waiting...) |
| 538 | r.state.Phase = "admitted" |
| 539 | ice = true |
| 540 | report = r.mediaStaleLocked() |
| 541 | case protocol.TypePeer: |
| 542 | if m.Roster != nil { |
| 543 | for _, p := range m.Roster.Peers { |
| 544 | r.upsertLocked(p) |
| 545 | } |
| 546 | } |
| 547 | case protocol.TypeGone: |
| 548 | r.state.Peers = without(r.state.Peers, m.From) |
| 549 | r.dropLaneLocked(m.From) |
| 550 | case protocol.TypeKnock: |
| 551 | r.state.Waiting = without(r.state.Waiting, m.From) |
| 552 | r.state.Waiting = append(r.state.Waiting, protocol.RosterPeer{Peer: m.From, Name: m.Name, Kind: "guest"}) |
| 553 | case protocol.TypeKnockGone: |
| 554 | r.state.Waiting = without(r.state.Waiting, m.From) |
| 555 | case protocol.TypeState: |
| 556 | if m.Waiting { |
| 557 | r.state.Phase = "waiting" |
| 558 | } |
| 559 | case protocol.TypeFull: |
| 560 | if r.state.Phase != "admitted" { |
| 561 | r.state.Phase = "full" |
| 562 | } |
| 563 | case protocol.TypePair: |
| 564 | for i, p := range r.state.Peers { |
| 565 | if p.Peer == m.Peer && m.Gen > p.Gen { |
| 566 | r.state.Peers[i].Gen = m.Gen |
| 567 | delete(r.blocked, m.Peer) |
| 568 | } |
| 569 | } |
| 570 | case protocol.TypeMedia: |
| 571 | r.applyMediaLocked(m) |
| 572 | case protocol.TypeGap: |
| 573 | reset = m.From |
| 574 | case protocol.TypeLost: |
| 575 | r.mu.Unlock() |
| 576 | if m.Reason == protocol.ReasonBuffer { |
| 577 | return errors.New("resume required") |
| 578 | } |
| 579 | r.terminal(string(m.Reason)) |
| 580 | return context.Canceled |
| 581 | default: |
| 582 | if targeted(m.Type) { |
| 583 | gen := r.generationLocked(m.From) |
| 584 | if m.Seq == 0 || m.Seq <= r.last[m.From] { |
| 585 | r.mu.Unlock() |
| 586 | return nil |
| 587 | } |
| 588 | r.last[m.From] = m.Seq |
| 589 | if gen == 0 || m.Gen < gen { |
| 590 | r.mu.Unlock() |
| 591 | return nil |
| 592 | } |
| 593 | if m.Gen > gen { |
| 594 | for i, p := range r.state.Peers { |
| 595 | if p.Peer == m.From { |
| 596 | r.state.Peers[i].Gen = m.Gen |
| 597 | } |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | } |
| 602 | r.mu.Unlock() |
| 603 | r.publish() |
| 604 | r.emit(Event{Type: "message", Message: &m}) |
| 605 | if join { |
| 606 | if err := r.Send(protocol.TypeJoin, "", 0, ""); err != nil { |
| 607 | return err |
| 608 | } |
| 609 | } |
| 610 | if ice { |
| 611 | select { |
| 612 | case r.iceWake <- struct{}{}: |
| 613 | default: |
| 614 | } |
| 615 | } |
| 616 | if reset != "" { |
| 617 | _ = r.Send(protocol.TypeReset, string(reset), 0, "") |
| 618 | } |
| 619 | if report { |
| 620 | _ = r.sendMedia() |
| 621 | } |
| 622 | return nil |
| 623 | } |
| 624 | func without(peers []protocol.RosterPeer, id protocol.PeerID) []protocol.RosterPeer { |
| 625 | out := make([]protocol.RosterPeer, 0, len(peers)) |
| 626 | for _, p := range peers { |
| 627 | if p.Peer != id { |
| 628 | out = append(out, p) |
| 629 | } |
| 630 | } |
| 631 | return out |
| 632 | } |
| 633 | func (r *Room) upsertLocked(p protocol.RosterPeer) { |
| 634 | r.state.Peers = without(r.state.Peers, p.Peer) |
| 635 | r.state.Peers = append(r.state.Peers, p) |
| 636 | sort.Slice(r.state.Peers, func(i, j int) bool { return r.state.Peers[i].Peer < r.state.Peers[j].Peer }) |
| 637 | } |
| 638 | |
| 639 | // Send enqueues without blocking the UI. expectedGen prevents a late native |
| 640 | // media callback from being relabelled as part of a replacement connection. |
| 641 | func (r *Room) Send(typ, to string, expectedGen uint64, payload string) error { |
| 642 | r.mu.Lock() |
| 643 | defer r.mu.Unlock() |
| 644 | if r.stopped || !r.started || r.state.Peer == "" { |
| 645 | return errors.New("room is not connected") |
| 646 | } |
| 647 | switch typ { |
| 648 | case protocol.TypeJoin, protocol.TypeAdmit, protocol.TypeReset, protocol.TypeChat, protocol.TypeShare, protocol.TypeMedia, protocol.TypeOffer, protocol.TypeAnswer, protocol.TypeCandidate: |
| 649 | default: |
| 650 | return errors.New("unsupported room command") |
| 651 | } |
| 652 | target := protocol.PeerID(to) |
| 653 | s := protocol.Signal{Peer: r.state.Peer, Type: typ, To: target} |
| 654 | if payload != "" { |
| 655 | if !json.Valid([]byte(payload)) { |
| 656 | return errors.New("invalid signal payload") |
| 657 | } |
| 658 | s.Payload = json.RawMessage(payload) |
| 659 | } |
| 660 | if targeted(typ) { |
| 661 | gen := r.generationLocked(target) |
| 662 | if target == r.state.Peer || gen == 0 || gen != expectedGen || r.blocked[target] { |
| 663 | return errors.New("peer connection is no longer current") |
| 664 | } |
| 665 | s.Gen = gen |
| 666 | s.Seq = r.seq[target] + 1 |
| 667 | } |
| 668 | b, err := json.Marshal(s) |
| 669 | if err != nil || len(b) > 64*1024 { |
| 670 | return errors.New("signal exceeds Calls' message limit") |
| 671 | } |
| 672 | laneKey := target |
| 673 | if typ == protocol.TypeReset { |
| 674 | if r.generationLocked(target) == 0 { |
| 675 | return errors.New("peer is no longer present") |
| 676 | } |
| 677 | laneKey = "" |
| 678 | } |
| 679 | l := r.lanes[laneKey] |
| 680 | if l == nil { |
| 681 | if len(r.lanes) >= 17 { |
| 682 | return errors.New("too many signaling destinations") |
| 683 | } |
| 684 | ctx, cancel := context.WithCancel(r.ctx) |
| 685 | l = &lane{queue: make(chan protocol.Signal, 64), ctx: ctx, cancel: cancel} |
| 686 | r.lanes[laneKey] = l |
| 687 | r.wg.Add(1) |
| 688 | go func() { defer r.wg.Done(); r.sendLoop(l) }() |
| 689 | } |
| 690 | select { |
| 691 | case l.queue <- s: |
| 692 | if targeted(typ) { |
| 693 | r.seq[target] = s.Seq |
| 694 | } |
| 695 | return nil |
| 696 | default: |
| 697 | return errors.New("signaling queue is full") |
| 698 | } |
| 699 | } |
| 700 | func (r *Room) current(s protocol.Signal) bool { |
| 701 | r.mu.Lock() |
| 702 | defer r.mu.Unlock() |
| 703 | return !r.stopped && s.Peer == r.state.Peer && (!targeted(s.Type) || (r.generationLocked(s.To) == s.Gen && !r.blocked[s.To])) |
| 704 | } |
| 705 | func (r *Room) sendLoop(l *lane) { |
| 706 | // Cancellation removes this lane under mu before any new Send can use it. |
| 707 | // Report every accepted chat still waiting in its queue; the UI has already |
| 708 | // cleared the composer and must retain a visible failure instead of losing it. |
| 709 | defer func() { |
| 710 | for { |
| 711 | select { |
| 712 | case s := <-l.queue: |
| 713 | if s.Type == protocol.TypeChat { |
| 714 | r.emit(Event{Type: "send-failed", Signal: &s}) |
| 715 | } |
| 716 | default: |
| 717 | return |
| 718 | } |
| 719 | } |
| 720 | }() |
| 721 | for { |
| 722 | if l.ctx.Err() != nil { |
| 723 | return |
| 724 | } |
| 725 | select { |
| 726 | case <-l.ctx.Done(): |
| 727 | return |
| 728 | case s := <-l.queue: |
| 729 | ctx, cancel := context.WithTimeout(l.ctx, 30*time.Second) |
| 730 | delay := 500 * time.Millisecond |
| 731 | accepted := false |
| 732 | for r.current(s) { |
| 733 | err := r.t.post(ctx, s) |
| 734 | if err == nil { |
| 735 | accepted = true |
| 736 | break |
| 737 | } |
| 738 | var refusal *HTTPError |
| 739 | if errors.As(err, &refusal) { |
| 740 | if refusal.Status == 429 { |
| 741 | delay = max(delay, refusal.RetryAfter) |
| 742 | } else if refusal.Status < 500 { |
| 743 | if refusal.Status == 400 && s.Type == protocol.TypeMedia && r.refusedExtras(s) { |
| 744 | break |
| 745 | } |
| 746 | if refusal.Status == 401 || refusal.Status == 403 || refusal.Status == 302 || refusal.Status == 303 { |
| 747 | r.terminal("signin") |
| 748 | } |
| 749 | if refusal.Status == 409 && targeted(s.Type) { |
| 750 | r.resetAfterFailure(s) |
| 751 | } |
| 752 | break |
| 753 | } |
| 754 | } |
| 755 | if !pause(ctx, delay) { |
| 756 | if l.ctx.Err() == nil && targeted(s.Type) { |
| 757 | r.resetAfterFailure(s) |
| 758 | } |
| 759 | break |
| 760 | } |
| 761 | delay = min(delay*2, 5*time.Second) |
| 762 | } |
| 763 | cancel() |
| 764 | // Chat is not echoed by the hub. Report the HTTP outcome, not |
| 765 | // merely queue acceptance, so native clients can show sent lines |
| 766 | // and make failures visible without claiming delivery to peers. |
| 767 | if s.Type == protocol.TypeChat { |
| 768 | typ := "send-failed" |
| 769 | if accepted { |
| 770 | typ = "sent" |
| 771 | } |
| 772 | r.emit(Event{Type: typ, Signal: &s}) |
| 773 | } |
| 774 | } |
| 775 | } |
| 776 | } |
| 777 | func (r *Room) iceLoop() { |
| 778 | var timer *time.Timer |
| 779 | var tick <-chan time.Time |
| 780 | defer func() { |
| 781 | if timer != nil { |
| 782 | timer.Stop() |
| 783 | } |
| 784 | }() |
| 785 | for { |
| 786 | select { |
| 787 | case <-r.ctx.Done(): |
| 788 | return |
| 789 | case <-r.iceWake: |
| 790 | case <-tick: |
| 791 | } |
| 792 | s := r.Snapshot() |
| 793 | if s.Phase != "admitted" { |
| 794 | continue |
| 795 | } |
| 796 | ice, err := r.t.ice(r.ctx, s.Peer) |
| 797 | next := time.Minute |
| 798 | if err == nil { |
| 799 | if r.Snapshot().Peer != s.Peer { |
| 800 | continue |
| 801 | } |
| 802 | r.emit(Event{Type: "ice", ICE: &ice}) |
| 803 | if ice.RenewAt == 0 { |
| 804 | tick = nil |
| 805 | if timer != nil { |
| 806 | timer.Stop() |
| 807 | } |
| 808 | continue |
| 809 | } |
| 810 | next = max(time.Until(time.Unix(ice.RenewAt, 0)), time.Second) |
| 811 | } else { |
| 812 | r.emit(Event{Type: "ice-unavailable"}) |
| 813 | } |
| 814 | if timer == nil { |
| 815 | timer = time.NewTimer(next) |
| 816 | } else { |
| 817 | timer.Reset(next) |
| 818 | } |
| 819 | tick = timer.C |
| 820 | } |
| 821 | } |
| 822 | |
| 823 | func (r *Room) dropLaneLocked(peer protocol.PeerID) { |
| 824 | if l := r.lanes[peer]; l != nil { |
| 825 | l.cancel() |
| 826 | delete(r.lanes, peer) |
| 827 | } |
| 828 | delete(r.last, peer) |
| 829 | delete(r.seq, peer) |
| 830 | delete(r.blocked, peer) |
| 831 | } |
| 832 | func (r *Room) resetAfterFailure(s protocol.Signal) { |
| 833 | r.mu.Lock() |
| 834 | if r.stopped || r.state.Peer != s.Peer || r.generationLocked(s.To) != s.Gen { |
| 835 | r.mu.Unlock() |
| 836 | return |
| 837 | } |
| 838 | r.blocked[s.To] = true |
| 839 | r.mu.Unlock() |
| 840 | // The control lane has the same retry/deadline contract as other sends; |
| 841 | // it can overtake the discarded old-generation target queue. |
| 842 | _ = r.Send(protocol.TypeReset, string(s.To), 0, "") |
| 843 | } |
| 844 | |