Skip to main content

sew_call_client/gateway/
mod.rs

1//! The call socket: one gateway connection opened with the call credential.
2//!
3//! - **Connect** `GET <door>/api/v1/gateway?v=1&encoding=json` with `Authorization: Bearer
4//!   sewcc_…` on the upgrade (K2's lane needs it), then IDENTIFY with the same token.
5//! - **READY** of a call socket is `{v, session_id, user: {id}, install_id, call_keys,
6//!   recording, recording_controls}`; a full READY (a `sews_` session in tests) is read the
7//!   same way. `session_id` is the join's `e2ee.gateway_session`; `recording` (Sew 0.7.3) is the
8//!   call channel's active recording as the member sees it, `null` for none;
9//!   `recording_controls` is the member's Record and Stop in the call's room from a server that
10//!   computes them, `null` until the member is connected there (absent: an older server).
11//! - **Delivered** (and the only dispatches passed on, whatever the server sends):
12//!   `call_keys_delivered`, `voice_server_updated`, `voice_state_updated`, (Sew 0.7.3) the
13//!   member's own `recording_updated`, `media_policy_updated` and the member's own
14//!   `recording_controls_updated`. Everything else is dropped and counted (defence in depth;
15//!   the server filters too).
16//! - **Ops sent**: HEARTBEAT, IDENTIFY once, RESUME after a drop, REAUTH with the renewed token
17//!   of the same credential (the `session_id` stays). Nothing else.
18//! - **Closes**: `4011` (credential revoked: the call is over for this engine; since Sew 0.7.2 its
19//!   text names why, `sew_proto::voice::call_close`, [`SocketClosed::Ended`]), `4004`
20//!   (authentication failed), `4001`/`4002`/`4012` are final. `op 7` or `4007`/`4009` start a new
21//!   session (a fresh IDENTIFY; the key session re-binds with the `state` route). Anything else
22//!   reconnects with backoff and RESUMEs.
23
24use std::fmt;
25use std::net::SocketAddr;
26use std::pin::Pin;
27use std::sync::Arc;
28use std::sync::atomic::{AtomicU64, Ordering};
29use std::task::{Context, Poll};
30use std::time::Duration;
31
32use futures_util::{SinkExt as _, StreamExt as _};
33use serde::Deserialize;
34use serde_json::Value;
35use sew_proto::e2ee::{CallKeysMessage, ReadyCallKeys};
36use sew_proto::gateway::client::{
37    ClientInfo, ClientOp, GatewayAuth, IdentifyRequest, ReauthRequest, ResumeRequest,
38};
39use sew_proto::gateway::{Frame, Opcode};
40use sew_proto::id::Id;
41use sew_proto::recording::{
42    Recording, RecordingControls, RecordingControlsUpdated, RecordingUpdated,
43};
44use sew_proto::voice::{MediaPolicy, VoiceServerUpdated, VoiceStateUpdated, call_close};
45use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
46use tokio::net::TcpStream;
47use tokio::sync::mpsc;
48use tokio_tungstenite::WebSocketStream;
49use tokio_tungstenite::tungstenite::Message;
50use tokio_tungstenite::tungstenite::client::IntoClientRequest as _;
51use tokio_tungstenite::tungstenite::http::HeaderValue;
52use tokio_tungstenite::tungstenite::protocol::CloseFrame;
53use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
54use url::Url;
55
56use crate::e2ee::credential::SharedBearer;
57
58/// The dispatch types a call socket passes on.
59pub const CALL_SOCKET_EVENTS: &[&str] = &[
60    "call_keys_delivered",
61    "voice_server_updated",
62    "voice_state_updated",
63    "recording_updated",
64    "media_policy_updated",
65    "recording_controls_updated",
66];
67
68/// Connect and handshake timeout.
69pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
70/// First reconnect wait; doubles to [`RECONNECT_MAX`], plus up to 25% jitter.
71pub const RECONNECT_BASE: Duration = Duration::from_millis(250);
72/// Longest reconnect wait.
73pub const RECONNECT_MAX: Duration = Duration::from_secs(5);
74/// After `4008` (rate limited): at least this long (Sew's rule for clients).
75pub const RATE_LIMITED_MIN: Duration = Duration::from_secs(5);
76
77/// What the socket tells its owner.
78#[derive(Debug, Clone)]
79#[non_exhaustive]
80pub enum SocketEvent {
81    /// A new gateway session (the first IDENTIFY, or after the server refused a RESUME).
82    Ready(Box<CallReadyInfo>),
83    /// The session resumed: missed dispatches follow.
84    Resumed,
85    /// `call_keys_delivered`.
86    CallKeys(Box<CallKeysMessage>),
87    /// `voice_server_updated` (a move or a token re-issue).
88    VoiceServerUpdated(Box<VoiceServerUpdated>),
89    /// `voice_state_updated` of the call's channel.
90    VoiceStateUpdated(Box<VoiceStateUpdated>),
91    /// `recording_updated`: a recording as this member sees it (its own `my_consent`, the
92    /// prompt while it has not answered). On a full session's socket it may be another
93    /// channel's: the engine keeps only its call channel's.
94    RecordingUpdated(Box<Recording>),
95    /// `media_policy_updated`: the client media policy changed (layer hints, video on or
96    /// off).
97    MediaPolicyUpdated(Box<MediaPolicy>),
98    /// `recording_controls_updated`: the member's own Record and Stop in the room they are in
99    /// changed (a server that computes them). The engine keeps only its call channel's.
100    RecordingControls(Box<RecordingControlsUpdated>),
101    /// The socket is gone for good.
102    Closed(SocketClosed),
103}
104
105/// What a READY carried (the call socket's minimal READY or a full one).
106#[derive(Clone)]
107#[non_exhaustive]
108pub struct CallReadyInfo {
109    /// The join's `e2ee.gateway_session`.
110    pub session_id: String,
111    /// The member (`user.id` or `member.id`).
112    pub member_id: Option<Id>,
113    /// The install (`install.id` of a full READY; the call socket's READY carries `install_id`).
114    pub install_id: Option<Id>,
115    /// The trust anchors (`call_keys`), when the READY has them.
116    pub call_keys: Option<ReadyCallKeys>,
117    /// The call channel's active recording (`CallReady.recording`, Sew 0.7.3): `None` when the
118    /// READY has no `recording` field (an older Sew, or a full READY), `Some(None)` when it
119    /// says none is active.
120    pub recording: Option<Option<Recording>>,
121    /// The member's Record and Stop in the call's room (`CallReady.recording_controls`):
122    /// `None` when the READY has no such field (an older Sew, or a full READY), `Some(None)`
123    /// when the server computes them but has no value yet (the member is not connected in the
124    /// room yet), `Some(Some(..))` with the value.
125    pub recording_controls: Option<Option<RecordingControls>>,
126}
127
128impl fmt::Debug for CallReadyInfo {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        f.debug_struct("CallReadyInfo")
131            .field("member_id", &self.member_id)
132            .field("install_id", &self.install_id)
133            .field("call_keys", &self.call_keys.is_some())
134            .field(
135                "recording",
136                &self.recording.as_ref().map(|r| r.as_ref().map(|r| r.id)),
137            )
138            .field("recording_controls", &self.recording_controls)
139            .finish_non_exhaustive()
140    }
141}
142
143/// Why the socket ended for good.
144#[derive(Debug, Clone, PartialEq, Eq)]
145#[non_exhaustive]
146pub enum SocketClosed {
147    /// `4011` with a close text that names no reason: the credential was revoked by a Sew
148    /// older than 0.7.2, or another socket took this credential over.
149    Revoked,
150    /// `4011` whose close text names why the credential ended (Sew 0.7.2,
151    /// [`sew_proto::voice::call_close`]): `reason` is Sew's voice leave reason as it arrived
152    /// (`perms_lost`, `removed_from_space`, `replaced` for a swap, …; `session_revoked` for a
153    /// sign-out, `account_removed` for a deactivation).
154    Ended {
155        /// The reason.
156        reason: String,
157    },
158    /// `4004`: the credential was refused.
159    AuthenticationFailed,
160    /// A protocol error (`4001`, `4002`, `4012`).
161    Protocol(u16),
162    /// [`CallSocket::close`].
163    Closed,
164}
165
166#[derive(Debug)]
167enum Cmd {
168    Reauth,
169    Close,
170    /// The device's network changed: drop the connection now and RESUME on a new one.
171    Reconnect,
172}
173
174/// Counters (no content).
175#[derive(Debug, Default)]
176#[non_exhaustive]
177pub struct SocketCounters {
178    /// Dispatches passed on.
179    pub passed: AtomicU64,
180    /// Dispatches dropped (not one of the three types).
181    pub dropped: AtomicU64,
182    /// Reconnects.
183    pub reconnects: AtomicU64,
184    /// New sessions (IDENTIFYs).
185    pub identifies: AtomicU64,
186}
187
188/// A running call socket. Dropping it closes the socket.
189pub struct CallSocket {
190    cmd: mpsc::UnboundedSender<Cmd>,
191    counters: Arc<SocketCounters>,
192}
193
194impl fmt::Debug for CallSocket {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        f.debug_struct("CallSocket")
197            .field("counters", &self.counters)
198            .finish()
199    }
200}
201
202impl Drop for CallSocket {
203    fn drop(&mut self) {
204        let _ = self.cmd.send(Cmd::Close);
205    }
206}
207
208impl CallSocket {
209    /// Opens the socket to `api_base` with the live bearer; events arrive on the returned
210    /// receiver (the first is `Ready`, or `Closed`).
211    pub fn open(
212        api_base: &Url,
213        bearer: SharedBearer,
214        tls: Arc<rustls::ClientConfig>,
215    ) -> Result<(CallSocket, mpsc::Receiver<SocketEvent>), SocketError> {
216        let url = gateway_url(api_base)?;
217        let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
218        let (ev_tx, ev_rx) = mpsc::channel(256);
219        let counters = Arc::new(SocketCounters::default());
220        let task = Task {
221            url,
222            bearer,
223            tls,
224            cmd: cmd_rx,
225            events: ev_tx,
226            counters: counters.clone(),
227            session: None,
228            seq: 0,
229            now: false,
230        };
231        tokio::spawn(task.run());
232        Ok((
233            CallSocket {
234                cmd: cmd_tx,
235                counters,
236            },
237            ev_rx,
238        ))
239    }
240
241    /// Sends REAUTH with the bearer's current token (after a renewal).
242    pub fn reauth(&self) {
243        let _ = self.cmd.send(Cmd::Reauth);
244    }
245
246    /// The device's network changed (`Call::network_changed`): drops the connection
247    /// without waiting for it to time out and reconnects at once on the current network with
248    /// RESUME (missed dispatches are replayed). A no-op once closed.
249    pub fn reconnect(&self) {
250        let _ = self.cmd.send(Cmd::Reconnect);
251    }
252
253    /// Closes the socket.
254    pub fn close(&self) {
255        let _ = self.cmd.send(Cmd::Close);
256    }
257
258    /// The counters.
259    pub fn counters(&self) -> &SocketCounters {
260        &self.counters
261    }
262}
263
264/// Why a socket could not be opened.
265#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
266#[non_exhaustive]
267pub enum SocketError {
268    /// The door is not an `http(s)` URL.
269    #[error("api_base must be an http(s) URL")]
270    BadBase,
271}
272
273/// `ws(s)://<door>/api/v1/gateway?v=1&encoding=json` (no compression).
274pub fn gateway_url(api_base: &Url) -> Result<Url, SocketError> {
275    let mut u = crate::e2ee::transport::join(api_base, sew_proto::routes::GATEWAY);
276    let scheme = match api_base.scheme() {
277        "http" => "ws",
278        "https" => "wss",
279        _ => return Err(SocketError::BadBase),
280    };
281    u.set_scheme(scheme).map_err(|()| SocketError::BadBase)?;
282    u.set_query(Some("v=1&encoding=json"));
283    Ok(u)
284}
285
286enum Stream {
287    Plain(TcpStream),
288    Tls(Box<tokio_rustls::client::TlsStream<TcpStream>>),
289}
290
291impl AsyncRead for Stream {
292    fn poll_read(
293        self: Pin<&mut Self>,
294        cx: &mut Context<'_>,
295        buf: &mut ReadBuf<'_>,
296    ) -> Poll<std::io::Result<()>> {
297        match self.get_mut() {
298            Stream::Plain(s) => Pin::new(s).poll_read(cx, buf),
299            Stream::Tls(s) => Pin::new(s.as_mut()).poll_read(cx, buf),
300        }
301    }
302}
303
304impl AsyncWrite for Stream {
305    fn poll_write(
306        self: Pin<&mut Self>,
307        cx: &mut Context<'_>,
308        buf: &[u8],
309    ) -> Poll<std::io::Result<usize>> {
310        match self.get_mut() {
311            Stream::Plain(s) => Pin::new(s).poll_write(cx, buf),
312            Stream::Tls(s) => Pin::new(s.as_mut()).poll_write(cx, buf),
313        }
314    }
315
316    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
317        match self.get_mut() {
318            Stream::Plain(s) => Pin::new(s).poll_flush(cx),
319            Stream::Tls(s) => Pin::new(s.as_mut()).poll_flush(cx),
320        }
321    }
322
323    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
324        match self.get_mut() {
325            Stream::Plain(s) => Pin::new(s).poll_shutdown(cx),
326            Stream::Tls(s) => Pin::new(s.as_mut()).poll_shutdown(cx),
327        }
328    }
329}
330
331type Ws = WebSocketStream<Stream>;
332
333async fn connect(
334    url: &Url,
335    bearer: &SharedBearer,
336    tls_cfg: &Arc<rustls::ClientConfig>,
337) -> Result<Ws, String> {
338    let fut = async {
339        let tls = url.scheme() == "wss";
340        let host = url.host_str().ok_or("no host")?.to_owned();
341        let port = url.port_or_known_default().ok_or("no port")?;
342        let bare = host
343            .trim_start_matches('[')
344            .trim_end_matches(']')
345            .to_owned();
346        let addr: SocketAddr = tokio::net::lookup_host((bare.as_str(), port))
347            .await
348            .map_err(|e| format!("resolve: {e}"))?
349            .next()
350            .ok_or("resolve: no address")?;
351        let tcp = TcpStream::connect(addr)
352            .await
353            .map_err(|e| format!("connect: {e}"))?;
354        let _ = tcp.set_nodelay(true);
355        let stream = if tls {
356            let name = rustls::pki_types::ServerName::try_from(bare.clone())
357                .map_err(|e| format!("tls server name: {e}"))?;
358            let s = tokio_rustls::TlsConnector::from(tls_cfg.clone())
359                .connect(name, tcp)
360                .await
361                .map_err(|e| format!("tls handshake: {e}"))?;
362            Stream::Tls(Box::new(s))
363        } else {
364            Stream::Plain(tcp)
365        };
366        let mut req = url
367            .as_str()
368            .into_client_request()
369            .map_err(|e| format!("request: {e}"))?;
370        let token = bearer.get();
371        let mut auth = HeaderValue::from_str(&format!("Bearer {}", token.expose()))
372            .map_err(|_| "bearer is not a header value".to_owned())?;
373        auth.set_sensitive(true);
374        req.headers_mut().insert(http::header::AUTHORIZATION, auth);
375        req.headers_mut().insert(
376            http::header::USER_AGENT,
377            HeaderValue::from_static(crate::USER_AGENT),
378        );
379        let mut cfg = WebSocketConfig::default();
380        cfg.max_message_size = Some(16 << 20);
381        cfg.max_frame_size = Some(16 << 20);
382        let (ws, _) = tokio_tungstenite::client_async_with_config(req, stream, Some(cfg))
383            .await
384            .map_err(|e| format!("websocket handshake: {e}"))?;
385        Ok(ws)
386    };
387    match tokio::time::timeout(CONNECT_TIMEOUT, fut).await {
388        Ok(r) => r,
389        Err(_) => Err("connect timed out".to_owned()),
390    }
391}
392
393/// The client name the socket identifies with.
394pub fn client_info() -> ClientInfo {
395    ClientInfo {
396        name: "sew-call-client".to_owned(),
397        version: env!("CARGO_PKG_VERSION").to_owned(),
398    }
399}
400
401#[derive(Deserialize)]
402struct ReadyWire {
403    session_id: String,
404    #[serde(default)]
405    user: Option<IdOnly>,
406    #[serde(default)]
407    member: Option<IdOnly>,
408    #[serde(default)]
409    install: Option<IdOnly>,
410    /// The call socket's READY (`CallReady.install_id`).
411    #[serde(default)]
412    install_id: Option<Id>,
413    #[serde(default)]
414    call_keys: Option<ReadyCallKeys>,
415}
416
417#[derive(Deserialize)]
418struct IdOnly {
419    id: Id,
420}
421
422/// Reads a READY body (minimal or full).
423pub fn parse_ready(d: &Value) -> Option<CallReadyInfo> {
424    let w: ReadyWire = serde_json::from_value(d.clone()).ok()?;
425    // Only a call socket's READY says which recording its call has (a full READY's
426    // `recordings` is every room's); `null` there means none.
427    let recording = match (&w.user, d.get("recording")) {
428        (Some(_), Some(Value::Null)) => Some(None),
429        (Some(_), Some(r)) => Some(Some(serde_json::from_value::<Recording>(r.clone()).ok()?)),
430        _ => None,
431    };
432    // Likewise its `recording_controls`: absent from an older server, `null` before the member
433    // is connected in the room.
434    let recording_controls = match (&w.user, d.get("recording_controls")) {
435        (Some(_), Some(Value::Null)) => Some(None),
436        (Some(_), Some(c)) => Some(Some(
437            serde_json::from_value::<RecordingControls>(c.clone()).ok()?,
438        )),
439        _ => None,
440    };
441    Some(CallReadyInfo {
442        session_id: w.session_id,
443        member_id: w.user.or(w.member).map(|m| m.id),
444        install_id: w.install_id.or(w.install.map(|i| i.id)),
445        call_keys: w.call_keys,
446        recording,
447        recording_controls,
448    })
449}
450
451/// The event a dispatch becomes, or `None` (dropped).
452pub fn filter_dispatch(t: &str, d: &Value) -> Option<SocketEvent> {
453    match t {
454        "call_keys_delivered" => serde_json::from_value::<CallKeysMessage>(d.clone())
455            .ok()
456            .map(|m| SocketEvent::CallKeys(Box::new(m))),
457        "voice_server_updated" => serde_json::from_value::<VoiceServerUpdated>(d.clone())
458            .ok()
459            .map(|m| SocketEvent::VoiceServerUpdated(Box::new(m))),
460        "voice_state_updated" => serde_json::from_value::<VoiceStateUpdated>(d.clone())
461            .ok()
462            .map(|m| SocketEvent::VoiceStateUpdated(Box::new(m))),
463        "recording_updated" => serde_json::from_value::<RecordingUpdated>(d.clone())
464            .ok()
465            .map(|m| SocketEvent::RecordingUpdated(Box::new(m.recording))),
466        "media_policy_updated" => serde_json::from_value::<MediaPolicy>(d.clone())
467            .ok()
468            .map(|m| SocketEvent::MediaPolicyUpdated(Box::new(m))),
469        "recording_controls_updated" => {
470            serde_json::from_value::<RecordingControlsUpdated>(d.clone())
471                .ok()
472                .map(|m| SocketEvent::RecordingControls(Box::new(m)))
473        }
474        _ => None,
475    }
476}
477
478enum Outcome {
479    /// Reconnect after this long and RESUME (or IDENTIFY when there is no session).
480    Retry(Duration),
481    /// The session is gone: IDENTIFY again after this long.
482    NewSession(Duration),
483    /// Final.
484    Final(SocketClosed),
485}
486
487/// What a close frame (`None`: none) means.
488fn frame_outcome(f: Option<&CloseFrame>, backoff: Duration) -> Outcome {
489    match f {
490        Some(f) => close_outcome(Some(u16::from(f.code)), f.reason.as_str(), backoff),
491        None => close_outcome(None, "", backoff),
492    }
493}
494
495fn close_outcome(code: Option<u16>, text: &str, backoff: Duration) -> Outcome {
496    match code {
497        Some(4011) => Outcome::Final(match call_close::reason_of(text) {
498            Some(reason) => SocketClosed::Ended { reason },
499            None => SocketClosed::Revoked,
500        }),
501        Some(4004) => Outcome::Final(SocketClosed::AuthenticationFailed),
502        Some(c @ (4001 | 4002 | 4012)) => Outcome::Final(SocketClosed::Protocol(c)),
503        Some(4007 | 4009) => Outcome::NewSession(backoff),
504        Some(4008) => Outcome::Retry(backoff.max(RATE_LIMITED_MIN)),
505        _ => Outcome::Retry(backoff),
506    }
507}
508
509fn jitter(d: Duration) -> Duration {
510    let ms = d.as_millis() as u64;
511    Duration::from_millis(ms + rand::random::<u64>() % (ms / 4 + 1))
512}
513
514struct Task {
515    url: Url,
516    bearer: SharedBearer,
517    tls: Arc<rustls::ClientConfig>,
518    cmd: mpsc::UnboundedReceiver<Cmd>,
519    events: mpsc::Sender<SocketEvent>,
520    counters: Arc<SocketCounters>,
521    session: Option<String>,
522    seq: u64,
523    /// Reconnect without waiting (a network change).
524    now: bool,
525}
526
527impl Task {
528    async fn run(mut self) {
529        let mut backoff = RECONNECT_BASE;
530        loop {
531            let outcome = match connect(&self.url, &self.bearer, &self.tls).await {
532                Ok(ws) => {
533                    let o = self.serve(ws, &mut backoff).await;
534                    self.counters.reconnects.fetch_add(1, Ordering::Relaxed);
535                    o
536                }
537                Err(e) => {
538                    tracing::debug!(target: "sew_call_client::socket", error = %e, "call socket connect failed");
539                    Outcome::Retry(backoff)
540                }
541            };
542            let wait = match outcome {
543                Outcome::Final(why) => {
544                    let _ = self.events.send(SocketEvent::Closed(why)).await;
545                    return;
546                }
547                Outcome::Retry(w) => w,
548                Outcome::NewSession(w) => {
549                    self.session = None;
550                    self.seq = 0;
551                    w
552                }
553            };
554            backoff = (backoff * 2).min(RECONNECT_MAX);
555            if self.now {
556                // A network change: straight back, from the shortest backoff.
557                self.now = false;
558                backoff = RECONNECT_BASE;
559                continue;
560            }
561            tokio::select! {
562                _ = tokio::time::sleep(jitter(wait)) => {}
563                c = self.cmd.recv() => match c {
564                    Some(Cmd::Reauth) => {}
565                    Some(Cmd::Reconnect) => backoff = RECONNECT_BASE,
566                    Some(Cmd::Close) | None => {
567                        let _ = self.events.send(SocketEvent::Closed(SocketClosed::Closed)).await;
568                        return;
569                    }
570                },
571            }
572        }
573    }
574
575    async fn send(ws: &mut Ws, op: &ClientOp) -> Result<(), ()> {
576        let frame = op.encode();
577        let text = serde_json::to_string(&frame).map_err(|_| ())?;
578        ws.send(Message::text(text)).await.map_err(|_| ())
579    }
580
581    /// One connection, until it ends.
582    async fn serve(&mut self, mut ws: Ws, backoff: &mut Duration) -> Outcome {
583        // HELLO first.
584        let hello = tokio::time::timeout(CONNECT_TIMEOUT, ws.next()).await;
585        let interval = match hello {
586            Ok(Some(Ok(Message::Text(t)))) => match serde_json::from_str::<Frame>(t.as_str()) {
587                Ok(f) if f.op == Opcode::Hello.as_u8() => {
588                    f.d.get("heartbeat_interval_ms")
589                        .and_then(Value::as_u64)
590                        .unwrap_or(30_000)
591                }
592                _ => return Outcome::Retry(*backoff),
593            },
594            Ok(Some(Ok(Message::Close(f)))) => {
595                return frame_outcome(f.as_ref(), *backoff);
596            }
597            _ => return Outcome::Retry(*backoff),
598        };
599        let token = self.bearer.get().expose().to_owned();
600        let first = match &self.session {
601            Some(sid) => ClientOp::Resume(ResumeRequest {
602                auth: GatewayAuth::Token(token),
603                session_id: sid.clone(),
604                seq: self.seq,
605            }),
606            None => ClientOp::Identify(IdentifyRequest {
607                auth: GatewayAuth::Token(token),
608                client: client_info(),
609                capabilities: 0,
610            }),
611        };
612        if Self::send(&mut ws, &first).await.is_err() {
613            return Outcome::Retry(*backoff);
614        }
615        let mut beat = tokio::time::interval(Duration::from_millis(interval.max(1_000)));
616        beat.tick().await;
617        let mut acked = true;
618        loop {
619            tokio::select! {
620                _ = beat.tick() => {
621                    if !acked {
622                        // A zombie connection: drop it and resume.
623                        let _ = ws.close(None).await;
624                        return Outcome::Retry(*backoff);
625                    }
626                    acked = false;
627                    let s = (self.seq > 0).then_some(self.seq);
628                    if Self::send(&mut ws, &ClientOp::Heartbeat(s)).await.is_err() {
629                        return Outcome::Retry(*backoff);
630                    }
631                }
632                c = self.cmd.recv() => match c {
633                    Some(Cmd::Reauth) => {
634                        let token = self.bearer.get().expose().to_owned();
635                        if Self::send(&mut ws, &ClientOp::Reauth(ReauthRequest { token })).await.is_err() {
636                            return Outcome::Retry(*backoff);
637                        }
638                    }
639                    Some(Cmd::Reconnect) => {
640                        // The old network's connection may be dead: no close handshake.
641                        drop(ws);
642                        self.now = true;
643                        return Outcome::Retry(RECONNECT_BASE);
644                    }
645                    Some(Cmd::Close) | None => {
646                        let _ = ws.close(None).await;
647                        return Outcome::Final(SocketClosed::Closed);
648                    }
649                },
650                m = ws.next() => {
651                    let text = match m {
652                        Some(Ok(Message::Text(t))) => t,
653                        Some(Ok(Message::Close(f))) => {
654                            return frame_outcome(f.as_ref(), *backoff);
655                        }
656                        Some(Ok(_)) => continue,
657                        Some(Err(_)) | None => return Outcome::Retry(*backoff),
658                    };
659                    let frames: Vec<Frame> = match serde_json::Deserializer::from_str(text.as_str())
660                        .into_iter::<Frame>()
661                        .collect::<Result<Vec<_>, _>>()
662                    {
663                        Ok(f) => f,
664                        Err(_) => return Outcome::Retry(*backoff),
665                    };
666                    for f in frames {
667                        if f.op == Opcode::HeartbeatAck.as_u8() {
668                            acked = true;
669                        }
670                        if let Some(o) = self.on_frame(f, backoff).await {
671                            let _ = ws.close(None).await;
672                            return o;
673                        }
674                    }
675                    if self.events.is_closed() {
676                        let _ = ws.close(None).await;
677                        return Outcome::Final(SocketClosed::Closed);
678                    }
679                }
680            }
681        }
682    }
683
684    /// Handles one frame; `Some` ends the connection.
685    async fn on_frame(&mut self, f: Frame, backoff: &mut Duration) -> Option<Outcome> {
686        let op = Opcode::from_u8(f.op)?;
687        match op {
688            Opcode::HeartbeatAck => None,
689            Opcode::Reconnect => {
690                let after = f.d.get("after_ms").and_then(Value::as_u64).unwrap_or(0);
691                Some(Outcome::Retry(Duration::from_millis(after)))
692            }
693            Opcode::InvalidSession => {
694                let resumable =
695                    f.d.get("resumable")
696                        .and_then(Value::as_bool)
697                        .unwrap_or(false);
698                if resumable {
699                    Some(Outcome::Retry(*backoff))
700                } else {
701                    Some(Outcome::NewSession(*backoff))
702                }
703            }
704            Opcode::Dispatch => {
705                if let Some(s) = f.s {
706                    self.seq = self.seq.max(s);
707                }
708                let t = f.t.as_deref()?;
709                match t {
710                    "ready" => {
711                        let Some(info) = parse_ready(&f.d) else {
712                            return Some(Outcome::NewSession(*backoff));
713                        };
714                        self.session = Some(info.session_id.clone());
715                        self.counters.identifies.fetch_add(1, Ordering::Relaxed);
716                        *backoff = RECONNECT_BASE;
717                        let _ = self.events.send(SocketEvent::Ready(Box::new(info))).await;
718                        None
719                    }
720                    "resumed" => {
721                        *backoff = RECONNECT_BASE;
722                        let _ = self.events.send(SocketEvent::Resumed).await;
723                        None
724                    }
725                    _ => {
726                        match filter_dispatch(t, &f.d) {
727                            Some(ev) => {
728                                self.counters.passed.fetch_add(1, Ordering::Relaxed);
729                                let _ = self.events.send(ev).await;
730                            }
731                            None => {
732                                self.counters.dropped.fetch_add(1, Ordering::Relaxed);
733                            }
734                        }
735                        None
736                    }
737                }
738            }
739            _ => None,
740        }
741    }
742}
743
744#[cfg(test)]
745mod tests {
746    use super::*;
747
748    #[test]
749    fn gateway_url_follows_the_door() {
750        let u = gateway_url(&Url::parse("https://example.com/_k2/voice/sew/").unwrap()).unwrap();
751        assert_eq!(
752            u.as_str(),
753            "wss://example.com/_k2/voice/sew/api/v1/gateway?v=1&encoding=json"
754        );
755        let u = gateway_url(&Url::parse("http://127.0.0.1:8470").unwrap()).unwrap();
756        assert_eq!(
757            u.as_str(),
758            "ws://127.0.0.1:8470/api/v1/gateway?v=1&encoding=json"
759        );
760    }
761
762    #[test]
763    fn only_four_dispatch_types_pass() {
764        let msg = serde_json::json!({"id": "1", "channel_id": "2"});
765        for t in [
766            "message_created",
767            "presence_updated",
768            "ready",
769            "typing_started",
770        ] {
771            assert!(filter_dispatch(t, &msg).is_none(), "{t} must be dropped");
772        }
773        let vs = serde_json::json!({"member_id": "7"});
774        assert!(matches!(
775            filter_dispatch("voice_state_updated", &vs),
776            Some(SocketEvent::VoiceStateUpdated(_))
777        ));
778        let rec = serde_json::json!({"recording": recording_json()});
779        match filter_dispatch("recording_updated", &rec) {
780            Some(SocketEvent::RecordingUpdated(r)) => {
781                assert_eq!(r.id, Id::new(77).unwrap());
782                assert_eq!(r.my_consent, Some(sew_proto::recording::Consent::Pending));
783            }
784            other => panic!("recording_updated: {other:?}"),
785        }
786        let hint = serde_json::json!({
787            "max_width": 640, "max_height": 360, "max_fps": 30,
788            "layers": [{"rid": "q", "height": 180, "max_kbps": 150}]
789        });
790        let policy = serde_json::json!({
791            "tier": "constrained", "video_enabled": true, "e2ee": "required",
792            "audio_codecs": ["opus"], "codecs": ["vp8", "h264"], "backup_codec": false,
793            "camera": hint, "screen": hint, "dynacast": true, "adaptive_stream": true
794        });
795        match filter_dispatch("media_policy_updated", &policy) {
796            Some(SocketEvent::MediaPolicyUpdated(m)) => {
797                assert_eq!(m.tier, sew_proto::voice::MediaTier::Constrained);
798                assert_eq!(m.camera.layers.len(), 1);
799            }
800            other => panic!("media_policy_updated: {other:?}"),
801        }
802    }
803
804    fn recording_json() -> Value {
805        serde_json::json!({
806            "id": "77", "channel_id": "2002", "state": "recording", "started_by": "1001",
807            "started_at": "2026-11-04T10:00:00Z", "auto": false, "message_id": "88",
808            "mixed": false, "audio_keep_days": 30, "max_duration_ms": 14400000,
809            "participants": [], "my_consent": "pending"
810        })
811    }
812
813    #[test]
814    fn a_call_ready_says_which_recording_its_call_has() {
815        let base = serde_json::json!({"v": 1, "session_id": "gw_3", "user": {"id": "42"}});
816        // An older Sew: no field, nothing known.
817        assert_eq!(parse_ready(&base).unwrap().recording, None);
818        let mut none = base.clone();
819        none["recording"] = Value::Null;
820        assert_eq!(parse_ready(&none).unwrap().recording, Some(None));
821        let mut some = base;
822        some["recording"] = recording_json();
823        let r = parse_ready(&some).unwrap().recording.unwrap().unwrap();
824        assert_eq!(r.channel_id, Id::new(2002).unwrap());
825        // A full READY's `recording` field (it has none) is not read as the call's.
826        let full =
827            serde_json::json!({"session_id": "gw_4", "member": {"id": "42"}, "recording": null});
828        assert_eq!(parse_ready(&full).unwrap().recording, None);
829    }
830
831    #[test]
832    fn a_call_ready_says_whether_the_server_computes_controls() {
833        let base = serde_json::json!({"v": 1, "session_id": "gw_5", "user": {"id": "42"}});
834        // An older server: no field.
835        assert_eq!(parse_ready(&base).unwrap().recording_controls, None);
836        // A server that computes them, before the member is connected in the room.
837        let mut none = base.clone();
838        none["recording_controls"] = Value::Null;
839        assert_eq!(parse_ready(&none).unwrap().recording_controls, Some(None));
840        // A value, with the capacity hint.
841        let mut some = base.clone();
842        some["recording_controls"] = serde_json::json!({
843            "can_record": true, "can_stop": false, "rev": 41,
844            "record_unavailable": "recording_capacity"
845        });
846        let c = parse_ready(&some)
847            .unwrap()
848            .recording_controls
849            .unwrap()
850            .unwrap();
851        assert!(c.can_record && !c.can_stop);
852        assert_eq!(c.rev, 41);
853        assert_eq!(
854            c.record_unavailable,
855            Some(sew_proto::recording::RecordUnavailable::RecordingCapacity)
856        );
857        // A value without the hint or `rev` still reads.
858        let mut bare = base;
859        bare["recording_controls"] = serde_json::json!({"can_record": false, "can_stop": true});
860        let c = parse_ready(&bare)
861            .unwrap()
862            .recording_controls
863            .unwrap()
864            .unwrap();
865        assert_eq!((c.can_record, c.can_stop, c.rev), (false, true, 0));
866        assert_eq!(c.record_unavailable, None);
867        // A full READY's field of that name is not the call's.
868        let full = serde_json::json!({
869            "session_id": "gw_6", "member": {"id": "42"}, "recording_controls": null
870        });
871        assert_eq!(parse_ready(&full).unwrap().recording_controls, None);
872    }
873
874    #[test]
875    fn recording_controls_updated_passes() {
876        assert!(CALL_SOCKET_EVENTS.contains(&"recording_controls_updated"));
877        let d = serde_json::json!({
878            "channel_id": "2002", "can_record": false, "can_stop": true, "rev": 7
879        });
880        match filter_dispatch("recording_controls_updated", &d) {
881            Some(SocketEvent::RecordingControls(u)) => {
882                assert_eq!(u.channel_id, Id::new(2002).unwrap());
883                assert_eq!(u.call_id, None);
884                assert_eq!((u.can_record, u.can_stop, u.rev), (false, true, 7));
885                assert_eq!(u.record_unavailable, None);
886            }
887            other => panic!("recording_controls_updated: {other:?}"),
888        }
889        let dm = serde_json::json!({
890            "channel_id": "2002", "call_id": "3003", "can_record": true, "can_stop": false,
891            "rev": 8, "record_unavailable": "recorder_unavailable"
892        });
893        match filter_dispatch("recording_controls_updated", &dm) {
894            Some(SocketEvent::RecordingControls(u)) => {
895                assert_eq!(u.call_id, Id::new(3003));
896                assert_eq!(
897                    u.record_unavailable,
898                    Some(sew_proto::recording::RecordUnavailable::RecorderUnavailable)
899                );
900            }
901            other => panic!("recording_controls_updated (DM): {other:?}"),
902        }
903        // A body that is not one is dropped, as any other.
904        assert!(
905            filter_dispatch(
906                "recording_controls_updated",
907                &serde_json::json!({"can_record": true})
908            )
909            .is_none()
910        );
911    }
912
913    #[test]
914    fn minimal_ready_is_read() {
915        let d = serde_json::json!({"v": 1, "session_id": "gw_1", "user": {"id": "42"}});
916        let r = parse_ready(&d).unwrap();
917        assert_eq!(r.session_id, "gw_1");
918        assert_eq!(r.member_id, Id::new(42));
919        assert!(r.call_keys.is_none());
920        assert!(r.install_id.is_none());
921    }
922
923    #[test]
924    fn call_ready_install_id_is_read() {
925        // The call socket's READY carries `install_id` (and `call_keys`) at the top.
926        let d = serde_json::json!({
927            "v": 1, "session_id": "gw_2", "user": {"id": "42"}, "install_id": "9001"
928        });
929        let r = parse_ready(&d).unwrap();
930        assert_eq!(r.install_id, Id::new(9001));
931        assert_eq!(r.member_id, Id::new(42));
932    }
933
934    #[test]
935    fn closes_map_to_outcomes() {
936        let b = Duration::from_millis(100);
937        // Sew 0.7.1's text (and a takeover's) names no reason.
938        assert!(matches!(
939            close_outcome(Some(4011), "session_revoked", b),
940            Outcome::Final(SocketClosed::Revoked)
941        ));
942        assert!(matches!(
943            close_outcome(Some(4004), "", b),
944            Outcome::Final(SocketClosed::AuthenticationFailed)
945        ));
946        assert!(matches!(
947            close_outcome(Some(4009), "", b),
948            Outcome::NewSession(_)
949        ));
950        assert!(
951            matches!(close_outcome(Some(4008), "", b), Outcome::Retry(d) if d >= RATE_LIMITED_MIN)
952        );
953        assert!(matches!(close_outcome(Some(1006), "", b), Outcome::Retry(d) if d == b));
954        assert!(matches!(frame_outcome(None, b), Outcome::Retry(d) if d == b));
955    }
956
957    #[test]
958    fn a_4011_keeps_the_reason_sew_gave() {
959        // Sew 0.7.2: the close text of a call socket names why its credential ended.
960        let b = Duration::from_millis(100);
961        for (text, want) in [
962            ("call_ended:perms_lost", "perms_lost"),
963            ("call_ended:removed_from_space", "removed_from_space"),
964            ("call_ended:timed_out", "timed_out"),
965            ("call_ended:channel_archived", "channel_archived"),
966            ("call_ended:removed_by_moderator", "removed_by_moderator"),
967            ("call_ended:device_revoked", "device_revoked"),
968            ("call_ended:session_revoked", "session_revoked"),
969            ("call_ended:replaced", "replaced"),
970            ("signed_out", "session_revoked"),
971            ("deactivated", "account_removed"),
972        ] {
973            match close_outcome(Some(4011), text, b) {
974                Outcome::Final(SocketClosed::Ended { reason }) => assert_eq!(reason, want),
975                _ => panic!("{text}: not an ended close"),
976            }
977        }
978        let f = CloseFrame {
979            code: 4011.into(),
980            reason: "call_ended:perms_lost".into(),
981        };
982        assert!(matches!(
983            frame_outcome(Some(&f), b),
984            Outcome::Final(SocketClosed::Ended { reason }) if reason == "perms_lost"
985        ));
986        // Another code with the same text is not an end.
987        assert!(matches!(
988            close_outcome(Some(4004), "call_ended:perms_lost", b),
989            Outcome::Final(SocketClosed::AuthenticationFailed)
990        ));
991    }
992}