sew-call-client 0.9.6

Sew's native voice engine: LiveKit-protocol signalling and reconnect against Sew's media server, str0m transport with TURN over UDP, TCP and TLS (relay-only when asked), MLS call keys with the mandatory E2EE checks over the call credential and the call socket, the device store, and the kessel-audio bridge.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
//! The call socket: one gateway connection opened with the call credential.
//!
//! - **Connect** `GET <door>/api/v1/gateway?v=1&encoding=json` with `Authorization: Bearer
//!   sewcc_…` on the upgrade (K2's lane needs it), then IDENTIFY with the same token.
//! - **READY** of a call socket is `{v, session_id, user: {id}, install_id, call_keys,
//!   recording, recording_controls}`; a full READY (a `sews_` session in tests) is read the
//!   same way. `session_id` is the join's `e2ee.gateway_session`; `recording` (Sew 0.7.3) is the
//!   call channel's active recording as the member sees it, `null` for none;
//!   `recording_controls` is the member's Record and Stop in the call's room from a server that
//!   computes them, `null` until the member is connected there (absent: an older server).
//! - **Delivered** (and the only dispatches passed on, whatever the server sends):
//!   `call_keys_delivered`, `voice_server_updated`, `voice_state_updated`, (Sew 0.7.3) the
//!   member's own `recording_updated`, `media_policy_updated` and the member's own
//!   `recording_controls_updated`. Everything else is dropped and counted (defence in depth;
//!   the server filters too).
//! - **Ops sent**: HEARTBEAT, IDENTIFY once, RESUME after a drop, REAUTH with the renewed token
//!   of the same credential (the `session_id` stays). Nothing else.
//! - **Closes**: `4011` (credential revoked: the call is over for this engine; since Sew 0.7.2 its
//!   text names why, `sew_proto::voice::call_close`, [`SocketClosed::Ended`]), `4004`
//!   (authentication failed), `4001`/`4002`/`4012` are final. `op 7` or `4007`/`4009` start a new
//!   session (a fresh IDENTIFY; the key session re-binds with the `state` route). Anything else
//!   reconnects with backoff and RESUMEs.

use std::fmt;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;

use futures_util::{SinkExt as _, StreamExt as _};
use serde::Deserialize;
use serde_json::Value;
use sew_proto::e2ee::{CallKeysMessage, ReadyCallKeys};
use sew_proto::gateway::client::{
    ClientInfo, ClientOp, GatewayAuth, IdentifyRequest, ReauthRequest, ResumeRequest,
};
use sew_proto::gateway::{Frame, Opcode};
use sew_proto::id::Id;
use sew_proto::recording::{
    Recording, RecordingControls, RecordingControlsUpdated, RecordingUpdated,
};
use sew_proto::voice::{MediaPolicy, VoiceServerUpdated, VoiceStateUpdated, call_close};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest as _;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::protocol::CloseFrame;
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
use url::Url;

use crate::e2ee::credential::SharedBearer;

/// The dispatch types a call socket passes on.
pub const CALL_SOCKET_EVENTS: &[&str] = &[
    "call_keys_delivered",
    "voice_server_updated",
    "voice_state_updated",
    "recording_updated",
    "media_policy_updated",
    "recording_controls_updated",
];

/// Connect and handshake timeout.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// First reconnect wait; doubles to [`RECONNECT_MAX`], plus up to 25% jitter.
pub const RECONNECT_BASE: Duration = Duration::from_millis(250);
/// Longest reconnect wait.
pub const RECONNECT_MAX: Duration = Duration::from_secs(5);
/// After `4008` (rate limited): at least this long (Sew's rule for clients).
pub const RATE_LIMITED_MIN: Duration = Duration::from_secs(5);

/// What the socket tells its owner.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SocketEvent {
    /// A new gateway session (the first IDENTIFY, or after the server refused a RESUME).
    Ready(Box<CallReadyInfo>),
    /// The session resumed: missed dispatches follow.
    Resumed,
    /// `call_keys_delivered`.
    CallKeys(Box<CallKeysMessage>),
    /// `voice_server_updated` (a move or a token re-issue).
    VoiceServerUpdated(Box<VoiceServerUpdated>),
    /// `voice_state_updated` of the call's channel.
    VoiceStateUpdated(Box<VoiceStateUpdated>),
    /// `recording_updated`: a recording as this member sees it (its own `my_consent`, the
    /// prompt while it has not answered). On a full session's socket it may be another
    /// channel's: the engine keeps only its call channel's.
    RecordingUpdated(Box<Recording>),
    /// `media_policy_updated`: the client media policy changed (layer hints, video on or
    /// off).
    MediaPolicyUpdated(Box<MediaPolicy>),
    /// `recording_controls_updated`: the member's own Record and Stop in the room they are in
    /// changed (a server that computes them). The engine keeps only its call channel's.
    RecordingControls(Box<RecordingControlsUpdated>),
    /// The socket is gone for good.
    Closed(SocketClosed),
}

/// What a READY carried (the call socket's minimal READY or a full one).
#[derive(Clone)]
#[non_exhaustive]
pub struct CallReadyInfo {
    /// The join's `e2ee.gateway_session`.
    pub session_id: String,
    /// The member (`user.id` or `member.id`).
    pub member_id: Option<Id>,
    /// The install (`install.id` of a full READY; the call socket's READY carries `install_id`).
    pub install_id: Option<Id>,
    /// The trust anchors (`call_keys`), when the READY has them.
    pub call_keys: Option<ReadyCallKeys>,
    /// The call channel's active recording (`CallReady.recording`, Sew 0.7.3): `None` when the
    /// READY has no `recording` field (an older Sew, or a full READY), `Some(None)` when it
    /// says none is active.
    pub recording: Option<Option<Recording>>,
    /// The member's Record and Stop in the call's room (`CallReady.recording_controls`):
    /// `None` when the READY has no such field (an older Sew, or a full READY), `Some(None)`
    /// when the server computes them but has no value yet (the member is not connected in the
    /// room yet), `Some(Some(..))` with the value.
    pub recording_controls: Option<Option<RecordingControls>>,
}

impl fmt::Debug for CallReadyInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CallReadyInfo")
            .field("member_id", &self.member_id)
            .field("install_id", &self.install_id)
            .field("call_keys", &self.call_keys.is_some())
            .field(
                "recording",
                &self.recording.as_ref().map(|r| r.as_ref().map(|r| r.id)),
            )
            .field("recording_controls", &self.recording_controls)
            .finish_non_exhaustive()
    }
}

/// Why the socket ended for good.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SocketClosed {
    /// `4011` with a close text that names no reason: the credential was revoked by a Sew
    /// older than 0.7.2, or another socket took this credential over.
    Revoked,
    /// `4011` whose close text names why the credential ended (Sew 0.7.2,
    /// [`sew_proto::voice::call_close`]): `reason` is Sew's voice leave reason as it arrived
    /// (`perms_lost`, `removed_from_space`, `replaced` for a swap, …; `session_revoked` for a
    /// sign-out, `account_removed` for a deactivation).
    Ended {
        /// The reason.
        reason: String,
    },
    /// `4004`: the credential was refused.
    AuthenticationFailed,
    /// A protocol error (`4001`, `4002`, `4012`).
    Protocol(u16),
    /// [`CallSocket::close`].
    Closed,
}

#[derive(Debug)]
enum Cmd {
    Reauth,
    Close,
    /// The device's network changed: drop the connection now and RESUME on a new one.
    Reconnect,
}

/// Counters (no content).
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct SocketCounters {
    /// Dispatches passed on.
    pub passed: AtomicU64,
    /// Dispatches dropped (not one of the three types).
    pub dropped: AtomicU64,
    /// Reconnects.
    pub reconnects: AtomicU64,
    /// New sessions (IDENTIFYs).
    pub identifies: AtomicU64,
}

/// A running call socket. Dropping it closes the socket.
pub struct CallSocket {
    cmd: mpsc::UnboundedSender<Cmd>,
    counters: Arc<SocketCounters>,
}

impl fmt::Debug for CallSocket {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CallSocket")
            .field("counters", &self.counters)
            .finish()
    }
}

impl Drop for CallSocket {
    fn drop(&mut self) {
        let _ = self.cmd.send(Cmd::Close);
    }
}

impl CallSocket {
    /// Opens the socket to `api_base` with the live bearer; events arrive on the returned
    /// receiver (the first is `Ready`, or `Closed`).
    pub fn open(
        api_base: &Url,
        bearer: SharedBearer,
        tls: Arc<rustls::ClientConfig>,
    ) -> Result<(CallSocket, mpsc::Receiver<SocketEvent>), SocketError> {
        let url = gateway_url(api_base)?;
        let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
        let (ev_tx, ev_rx) = mpsc::channel(256);
        let counters = Arc::new(SocketCounters::default());
        let task = Task {
            url,
            bearer,
            tls,
            cmd: cmd_rx,
            events: ev_tx,
            counters: counters.clone(),
            session: None,
            seq: 0,
            now: false,
        };
        tokio::spawn(task.run());
        Ok((
            CallSocket {
                cmd: cmd_tx,
                counters,
            },
            ev_rx,
        ))
    }

    /// Sends REAUTH with the bearer's current token (after a renewal).
    pub fn reauth(&self) {
        let _ = self.cmd.send(Cmd::Reauth);
    }

    /// The device's network changed (`Call::network_changed`): drops the connection
    /// without waiting for it to time out and reconnects at once on the current network with
    /// RESUME (missed dispatches are replayed). A no-op once closed.
    pub fn reconnect(&self) {
        let _ = self.cmd.send(Cmd::Reconnect);
    }

    /// Closes the socket.
    pub fn close(&self) {
        let _ = self.cmd.send(Cmd::Close);
    }

    /// The counters.
    pub fn counters(&self) -> &SocketCounters {
        &self.counters
    }
}

/// Why a socket could not be opened.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SocketError {
    /// The door is not an `http(s)` URL.
    #[error("api_base must be an http(s) URL")]
    BadBase,
}

/// `ws(s)://<door>/api/v1/gateway?v=1&encoding=json` (no compression).
pub fn gateway_url(api_base: &Url) -> Result<Url, SocketError> {
    let mut u = crate::e2ee::transport::join(api_base, sew_proto::routes::GATEWAY);
    let scheme = match api_base.scheme() {
        "http" => "ws",
        "https" => "wss",
        _ => return Err(SocketError::BadBase),
    };
    u.set_scheme(scheme).map_err(|()| SocketError::BadBase)?;
    u.set_query(Some("v=1&encoding=json"));
    Ok(u)
}

enum Stream {
    Plain(TcpStream),
    Tls(Box<tokio_rustls::client::TlsStream<TcpStream>>),
}

impl AsyncRead for Stream {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        match self.get_mut() {
            Stream::Plain(s) => Pin::new(s).poll_read(cx, buf),
            Stream::Tls(s) => Pin::new(s.as_mut()).poll_read(cx, buf),
        }
    }
}

impl AsyncWrite for Stream {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        match self.get_mut() {
            Stream::Plain(s) => Pin::new(s).poll_write(cx, buf),
            Stream::Tls(s) => Pin::new(s.as_mut()).poll_write(cx, buf),
        }
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        match self.get_mut() {
            Stream::Plain(s) => Pin::new(s).poll_flush(cx),
            Stream::Tls(s) => Pin::new(s.as_mut()).poll_flush(cx),
        }
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        match self.get_mut() {
            Stream::Plain(s) => Pin::new(s).poll_shutdown(cx),
            Stream::Tls(s) => Pin::new(s.as_mut()).poll_shutdown(cx),
        }
    }
}

type Ws = WebSocketStream<Stream>;

async fn connect(
    url: &Url,
    bearer: &SharedBearer,
    tls_cfg: &Arc<rustls::ClientConfig>,
) -> Result<Ws, String> {
    let fut = async {
        let tls = url.scheme() == "wss";
        let host = url.host_str().ok_or("no host")?.to_owned();
        let port = url.port_or_known_default().ok_or("no port")?;
        let bare = host
            .trim_start_matches('[')
            .trim_end_matches(']')
            .to_owned();
        let addr: SocketAddr = tokio::net::lookup_host((bare.as_str(), port))
            .await
            .map_err(|e| format!("resolve: {e}"))?
            .next()
            .ok_or("resolve: no address")?;
        let tcp = TcpStream::connect(addr)
            .await
            .map_err(|e| format!("connect: {e}"))?;
        let _ = tcp.set_nodelay(true);
        let stream = if tls {
            let name = rustls::pki_types::ServerName::try_from(bare.clone())
                .map_err(|e| format!("tls server name: {e}"))?;
            let s = tokio_rustls::TlsConnector::from(tls_cfg.clone())
                .connect(name, tcp)
                .await
                .map_err(|e| format!("tls handshake: {e}"))?;
            Stream::Tls(Box::new(s))
        } else {
            Stream::Plain(tcp)
        };
        let mut req = url
            .as_str()
            .into_client_request()
            .map_err(|e| format!("request: {e}"))?;
        let token = bearer.get();
        let mut auth = HeaderValue::from_str(&format!("Bearer {}", token.expose()))
            .map_err(|_| "bearer is not a header value".to_owned())?;
        auth.set_sensitive(true);
        req.headers_mut().insert(http::header::AUTHORIZATION, auth);
        req.headers_mut().insert(
            http::header::USER_AGENT,
            HeaderValue::from_static(crate::USER_AGENT),
        );
        let mut cfg = WebSocketConfig::default();
        cfg.max_message_size = Some(16 << 20);
        cfg.max_frame_size = Some(16 << 20);
        let (ws, _) = tokio_tungstenite::client_async_with_config(req, stream, Some(cfg))
            .await
            .map_err(|e| format!("websocket handshake: {e}"))?;
        Ok(ws)
    };
    match tokio::time::timeout(CONNECT_TIMEOUT, fut).await {
        Ok(r) => r,
        Err(_) => Err("connect timed out".to_owned()),
    }
}

/// The client name the socket identifies with.
pub fn client_info() -> ClientInfo {
    ClientInfo {
        name: "sew-call-client".to_owned(),
        version: env!("CARGO_PKG_VERSION").to_owned(),
    }
}

#[derive(Deserialize)]
struct ReadyWire {
    session_id: String,
    #[serde(default)]
    user: Option<IdOnly>,
    #[serde(default)]
    member: Option<IdOnly>,
    #[serde(default)]
    install: Option<IdOnly>,
    /// The call socket's READY (`CallReady.install_id`).
    #[serde(default)]
    install_id: Option<Id>,
    #[serde(default)]
    call_keys: Option<ReadyCallKeys>,
}

#[derive(Deserialize)]
struct IdOnly {
    id: Id,
}

/// Reads a READY body (minimal or full).
pub fn parse_ready(d: &Value) -> Option<CallReadyInfo> {
    let w: ReadyWire = serde_json::from_value(d.clone()).ok()?;
    // Only a call socket's READY says which recording its call has (a full READY's
    // `recordings` is every room's); `null` there means none.
    let recording = match (&w.user, d.get("recording")) {
        (Some(_), Some(Value::Null)) => Some(None),
        (Some(_), Some(r)) => Some(Some(serde_json::from_value::<Recording>(r.clone()).ok()?)),
        _ => None,
    };
    // Likewise its `recording_controls`: absent from an older server, `null` before the member
    // is connected in the room.
    let recording_controls = match (&w.user, d.get("recording_controls")) {
        (Some(_), Some(Value::Null)) => Some(None),
        (Some(_), Some(c)) => Some(Some(
            serde_json::from_value::<RecordingControls>(c.clone()).ok()?,
        )),
        _ => None,
    };
    Some(CallReadyInfo {
        session_id: w.session_id,
        member_id: w.user.or(w.member).map(|m| m.id),
        install_id: w.install_id.or(w.install.map(|i| i.id)),
        call_keys: w.call_keys,
        recording,
        recording_controls,
    })
}

/// The event a dispatch becomes, or `None` (dropped).
pub fn filter_dispatch(t: &str, d: &Value) -> Option<SocketEvent> {
    match t {
        "call_keys_delivered" => serde_json::from_value::<CallKeysMessage>(d.clone())
            .ok()
            .map(|m| SocketEvent::CallKeys(Box::new(m))),
        "voice_server_updated" => serde_json::from_value::<VoiceServerUpdated>(d.clone())
            .ok()
            .map(|m| SocketEvent::VoiceServerUpdated(Box::new(m))),
        "voice_state_updated" => serde_json::from_value::<VoiceStateUpdated>(d.clone())
            .ok()
            .map(|m| SocketEvent::VoiceStateUpdated(Box::new(m))),
        "recording_updated" => serde_json::from_value::<RecordingUpdated>(d.clone())
            .ok()
            .map(|m| SocketEvent::RecordingUpdated(Box::new(m.recording))),
        "media_policy_updated" => serde_json::from_value::<MediaPolicy>(d.clone())
            .ok()
            .map(|m| SocketEvent::MediaPolicyUpdated(Box::new(m))),
        "recording_controls_updated" => {
            serde_json::from_value::<RecordingControlsUpdated>(d.clone())
                .ok()
                .map(|m| SocketEvent::RecordingControls(Box::new(m)))
        }
        _ => None,
    }
}

enum Outcome {
    /// Reconnect after this long and RESUME (or IDENTIFY when there is no session).
    Retry(Duration),
    /// The session is gone: IDENTIFY again after this long.
    NewSession(Duration),
    /// Final.
    Final(SocketClosed),
}

/// What a close frame (`None`: none) means.
fn frame_outcome(f: Option<&CloseFrame>, backoff: Duration) -> Outcome {
    match f {
        Some(f) => close_outcome(Some(u16::from(f.code)), f.reason.as_str(), backoff),
        None => close_outcome(None, "", backoff),
    }
}

fn close_outcome(code: Option<u16>, text: &str, backoff: Duration) -> Outcome {
    match code {
        Some(4011) => Outcome::Final(match call_close::reason_of(text) {
            Some(reason) => SocketClosed::Ended { reason },
            None => SocketClosed::Revoked,
        }),
        Some(4004) => Outcome::Final(SocketClosed::AuthenticationFailed),
        Some(c @ (4001 | 4002 | 4012)) => Outcome::Final(SocketClosed::Protocol(c)),
        Some(4007 | 4009) => Outcome::NewSession(backoff),
        Some(4008) => Outcome::Retry(backoff.max(RATE_LIMITED_MIN)),
        _ => Outcome::Retry(backoff),
    }
}

fn jitter(d: Duration) -> Duration {
    let ms = d.as_millis() as u64;
    Duration::from_millis(ms + rand::random::<u64>() % (ms / 4 + 1))
}

struct Task {
    url: Url,
    bearer: SharedBearer,
    tls: Arc<rustls::ClientConfig>,
    cmd: mpsc::UnboundedReceiver<Cmd>,
    events: mpsc::Sender<SocketEvent>,
    counters: Arc<SocketCounters>,
    session: Option<String>,
    seq: u64,
    /// Reconnect without waiting (a network change).
    now: bool,
}

impl Task {
    async fn run(mut self) {
        let mut backoff = RECONNECT_BASE;
        loop {
            let outcome = match connect(&self.url, &self.bearer, &self.tls).await {
                Ok(ws) => {
                    let o = self.serve(ws, &mut backoff).await;
                    self.counters.reconnects.fetch_add(1, Ordering::Relaxed);
                    o
                }
                Err(e) => {
                    tracing::debug!(target: "sew_call_client::socket", error = %e, "call socket connect failed");
                    Outcome::Retry(backoff)
                }
            };
            let wait = match outcome {
                Outcome::Final(why) => {
                    let _ = self.events.send(SocketEvent::Closed(why)).await;
                    return;
                }
                Outcome::Retry(w) => w,
                Outcome::NewSession(w) => {
                    self.session = None;
                    self.seq = 0;
                    w
                }
            };
            backoff = (backoff * 2).min(RECONNECT_MAX);
            if self.now {
                // A network change: straight back, from the shortest backoff.
                self.now = false;
                backoff = RECONNECT_BASE;
                continue;
            }
            tokio::select! {
                _ = tokio::time::sleep(jitter(wait)) => {}
                c = self.cmd.recv() => match c {
                    Some(Cmd::Reauth) => {}
                    Some(Cmd::Reconnect) => backoff = RECONNECT_BASE,
                    Some(Cmd::Close) | None => {
                        let _ = self.events.send(SocketEvent::Closed(SocketClosed::Closed)).await;
                        return;
                    }
                },
            }
        }
    }

    async fn send(ws: &mut Ws, op: &ClientOp) -> Result<(), ()> {
        let frame = op.encode();
        let text = serde_json::to_string(&frame).map_err(|_| ())?;
        ws.send(Message::text(text)).await.map_err(|_| ())
    }

    /// One connection, until it ends.
    async fn serve(&mut self, mut ws: Ws, backoff: &mut Duration) -> Outcome {
        // HELLO first.
        let hello = tokio::time::timeout(CONNECT_TIMEOUT, ws.next()).await;
        let interval = match hello {
            Ok(Some(Ok(Message::Text(t)))) => match serde_json::from_str::<Frame>(t.as_str()) {
                Ok(f) if f.op == Opcode::Hello.as_u8() => {
                    f.d.get("heartbeat_interval_ms")
                        .and_then(Value::as_u64)
                        .unwrap_or(30_000)
                }
                _ => return Outcome::Retry(*backoff),
            },
            Ok(Some(Ok(Message::Close(f)))) => {
                return frame_outcome(f.as_ref(), *backoff);
            }
            _ => return Outcome::Retry(*backoff),
        };
        let token = self.bearer.get().expose().to_owned();
        let first = match &self.session {
            Some(sid) => ClientOp::Resume(ResumeRequest {
                auth: GatewayAuth::Token(token),
                session_id: sid.clone(),
                seq: self.seq,
            }),
            None => ClientOp::Identify(IdentifyRequest {
                auth: GatewayAuth::Token(token),
                client: client_info(),
                capabilities: 0,
            }),
        };
        if Self::send(&mut ws, &first).await.is_err() {
            return Outcome::Retry(*backoff);
        }
        let mut beat = tokio::time::interval(Duration::from_millis(interval.max(1_000)));
        beat.tick().await;
        let mut acked = true;
        loop {
            tokio::select! {
                _ = beat.tick() => {
                    if !acked {
                        // A zombie connection: drop it and resume.
                        let _ = ws.close(None).await;
                        return Outcome::Retry(*backoff);
                    }
                    acked = false;
                    let s = (self.seq > 0).then_some(self.seq);
                    if Self::send(&mut ws, &ClientOp::Heartbeat(s)).await.is_err() {
                        return Outcome::Retry(*backoff);
                    }
                }
                c = self.cmd.recv() => match c {
                    Some(Cmd::Reauth) => {
                        let token = self.bearer.get().expose().to_owned();
                        if Self::send(&mut ws, &ClientOp::Reauth(ReauthRequest { token })).await.is_err() {
                            return Outcome::Retry(*backoff);
                        }
                    }
                    Some(Cmd::Reconnect) => {
                        // The old network's connection may be dead: no close handshake.
                        drop(ws);
                        self.now = true;
                        return Outcome::Retry(RECONNECT_BASE);
                    }
                    Some(Cmd::Close) | None => {
                        let _ = ws.close(None).await;
                        return Outcome::Final(SocketClosed::Closed);
                    }
                },
                m = ws.next() => {
                    let text = match m {
                        Some(Ok(Message::Text(t))) => t,
                        Some(Ok(Message::Close(f))) => {
                            return frame_outcome(f.as_ref(), *backoff);
                        }
                        Some(Ok(_)) => continue,
                        Some(Err(_)) | None => return Outcome::Retry(*backoff),
                    };
                    let frames: Vec<Frame> = match serde_json::Deserializer::from_str(text.as_str())
                        .into_iter::<Frame>()
                        .collect::<Result<Vec<_>, _>>()
                    {
                        Ok(f) => f,
                        Err(_) => return Outcome::Retry(*backoff),
                    };
                    for f in frames {
                        if f.op == Opcode::HeartbeatAck.as_u8() {
                            acked = true;
                        }
                        if let Some(o) = self.on_frame(f, backoff).await {
                            let _ = ws.close(None).await;
                            return o;
                        }
                    }
                    if self.events.is_closed() {
                        let _ = ws.close(None).await;
                        return Outcome::Final(SocketClosed::Closed);
                    }
                }
            }
        }
    }

    /// Handles one frame; `Some` ends the connection.
    async fn on_frame(&mut self, f: Frame, backoff: &mut Duration) -> Option<Outcome> {
        let op = Opcode::from_u8(f.op)?;
        match op {
            Opcode::HeartbeatAck => None,
            Opcode::Reconnect => {
                let after = f.d.get("after_ms").and_then(Value::as_u64).unwrap_or(0);
                Some(Outcome::Retry(Duration::from_millis(after)))
            }
            Opcode::InvalidSession => {
                let resumable =
                    f.d.get("resumable")
                        .and_then(Value::as_bool)
                        .unwrap_or(false);
                if resumable {
                    Some(Outcome::Retry(*backoff))
                } else {
                    Some(Outcome::NewSession(*backoff))
                }
            }
            Opcode::Dispatch => {
                if let Some(s) = f.s {
                    self.seq = self.seq.max(s);
                }
                let t = f.t.as_deref()?;
                match t {
                    "ready" => {
                        let Some(info) = parse_ready(&f.d) else {
                            return Some(Outcome::NewSession(*backoff));
                        };
                        self.session = Some(info.session_id.clone());
                        self.counters.identifies.fetch_add(1, Ordering::Relaxed);
                        *backoff = RECONNECT_BASE;
                        let _ = self.events.send(SocketEvent::Ready(Box::new(info))).await;
                        None
                    }
                    "resumed" => {
                        *backoff = RECONNECT_BASE;
                        let _ = self.events.send(SocketEvent::Resumed).await;
                        None
                    }
                    _ => {
                        match filter_dispatch(t, &f.d) {
                            Some(ev) => {
                                self.counters.passed.fetch_add(1, Ordering::Relaxed);
                                let _ = self.events.send(ev).await;
                            }
                            None => {
                                self.counters.dropped.fetch_add(1, Ordering::Relaxed);
                            }
                        }
                        None
                    }
                }
            }
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn gateway_url_follows_the_door() {
        let u = gateway_url(&Url::parse("https://example.com/_k2/voice/sew/").unwrap()).unwrap();
        assert_eq!(
            u.as_str(),
            "wss://example.com/_k2/voice/sew/api/v1/gateway?v=1&encoding=json"
        );
        let u = gateway_url(&Url::parse("http://127.0.0.1:8470").unwrap()).unwrap();
        assert_eq!(
            u.as_str(),
            "ws://127.0.0.1:8470/api/v1/gateway?v=1&encoding=json"
        );
    }

    #[test]
    fn only_four_dispatch_types_pass() {
        let msg = serde_json::json!({"id": "1", "channel_id": "2"});
        for t in [
            "message_created",
            "presence_updated",
            "ready",
            "typing_started",
        ] {
            assert!(filter_dispatch(t, &msg).is_none(), "{t} must be dropped");
        }
        let vs = serde_json::json!({"member_id": "7"});
        assert!(matches!(
            filter_dispatch("voice_state_updated", &vs),
            Some(SocketEvent::VoiceStateUpdated(_))
        ));
        let rec = serde_json::json!({"recording": recording_json()});
        match filter_dispatch("recording_updated", &rec) {
            Some(SocketEvent::RecordingUpdated(r)) => {
                assert_eq!(r.id, Id::new(77).unwrap());
                assert_eq!(r.my_consent, Some(sew_proto::recording::Consent::Pending));
            }
            other => panic!("recording_updated: {other:?}"),
        }
        let hint = serde_json::json!({
            "max_width": 640, "max_height": 360, "max_fps": 30,
            "layers": [{"rid": "q", "height": 180, "max_kbps": 150}]
        });
        let policy = serde_json::json!({
            "tier": "constrained", "video_enabled": true, "e2ee": "required",
            "audio_codecs": ["opus"], "codecs": ["vp8", "h264"], "backup_codec": false,
            "camera": hint, "screen": hint, "dynacast": true, "adaptive_stream": true
        });
        match filter_dispatch("media_policy_updated", &policy) {
            Some(SocketEvent::MediaPolicyUpdated(m)) => {
                assert_eq!(m.tier, sew_proto::voice::MediaTier::Constrained);
                assert_eq!(m.camera.layers.len(), 1);
            }
            other => panic!("media_policy_updated: {other:?}"),
        }
    }

    fn recording_json() -> Value {
        serde_json::json!({
            "id": "77", "channel_id": "2002", "state": "recording", "started_by": "1001",
            "started_at": "2026-11-04T10:00:00Z", "auto": false, "message_id": "88",
            "mixed": false, "audio_keep_days": 30, "max_duration_ms": 14400000,
            "participants": [], "my_consent": "pending"
        })
    }

    #[test]
    fn a_call_ready_says_which_recording_its_call_has() {
        let base = serde_json::json!({"v": 1, "session_id": "gw_3", "user": {"id": "42"}});
        // An older Sew: no field, nothing known.
        assert_eq!(parse_ready(&base).unwrap().recording, None);
        let mut none = base.clone();
        none["recording"] = Value::Null;
        assert_eq!(parse_ready(&none).unwrap().recording, Some(None));
        let mut some = base;
        some["recording"] = recording_json();
        let r = parse_ready(&some).unwrap().recording.unwrap().unwrap();
        assert_eq!(r.channel_id, Id::new(2002).unwrap());
        // A full READY's `recording` field (it has none) is not read as the call's.
        let full =
            serde_json::json!({"session_id": "gw_4", "member": {"id": "42"}, "recording": null});
        assert_eq!(parse_ready(&full).unwrap().recording, None);
    }

    #[test]
    fn a_call_ready_says_whether_the_server_computes_controls() {
        let base = serde_json::json!({"v": 1, "session_id": "gw_5", "user": {"id": "42"}});
        // An older server: no field.
        assert_eq!(parse_ready(&base).unwrap().recording_controls, None);
        // A server that computes them, before the member is connected in the room.
        let mut none = base.clone();
        none["recording_controls"] = Value::Null;
        assert_eq!(parse_ready(&none).unwrap().recording_controls, Some(None));
        // A value, with the capacity hint.
        let mut some = base.clone();
        some["recording_controls"] = serde_json::json!({
            "can_record": true, "can_stop": false, "rev": 41,
            "record_unavailable": "recording_capacity"
        });
        let c = parse_ready(&some)
            .unwrap()
            .recording_controls
            .unwrap()
            .unwrap();
        assert!(c.can_record && !c.can_stop);
        assert_eq!(c.rev, 41);
        assert_eq!(
            c.record_unavailable,
            Some(sew_proto::recording::RecordUnavailable::RecordingCapacity)
        );
        // A value without the hint or `rev` still reads.
        let mut bare = base;
        bare["recording_controls"] = serde_json::json!({"can_record": false, "can_stop": true});
        let c = parse_ready(&bare)
            .unwrap()
            .recording_controls
            .unwrap()
            .unwrap();
        assert_eq!((c.can_record, c.can_stop, c.rev), (false, true, 0));
        assert_eq!(c.record_unavailable, None);
        // A full READY's field of that name is not the call's.
        let full = serde_json::json!({
            "session_id": "gw_6", "member": {"id": "42"}, "recording_controls": null
        });
        assert_eq!(parse_ready(&full).unwrap().recording_controls, None);
    }

    #[test]
    fn recording_controls_updated_passes() {
        assert!(CALL_SOCKET_EVENTS.contains(&"recording_controls_updated"));
        let d = serde_json::json!({
            "channel_id": "2002", "can_record": false, "can_stop": true, "rev": 7
        });
        match filter_dispatch("recording_controls_updated", &d) {
            Some(SocketEvent::RecordingControls(u)) => {
                assert_eq!(u.channel_id, Id::new(2002).unwrap());
                assert_eq!(u.call_id, None);
                assert_eq!((u.can_record, u.can_stop, u.rev), (false, true, 7));
                assert_eq!(u.record_unavailable, None);
            }
            other => panic!("recording_controls_updated: {other:?}"),
        }
        let dm = serde_json::json!({
            "channel_id": "2002", "call_id": "3003", "can_record": true, "can_stop": false,
            "rev": 8, "record_unavailable": "recorder_unavailable"
        });
        match filter_dispatch("recording_controls_updated", &dm) {
            Some(SocketEvent::RecordingControls(u)) => {
                assert_eq!(u.call_id, Id::new(3003));
                assert_eq!(
                    u.record_unavailable,
                    Some(sew_proto::recording::RecordUnavailable::RecorderUnavailable)
                );
            }
            other => panic!("recording_controls_updated (DM): {other:?}"),
        }
        // A body that is not one is dropped, as any other.
        assert!(
            filter_dispatch(
                "recording_controls_updated",
                &serde_json::json!({"can_record": true})
            )
            .is_none()
        );
    }

    #[test]
    fn minimal_ready_is_read() {
        let d = serde_json::json!({"v": 1, "session_id": "gw_1", "user": {"id": "42"}});
        let r = parse_ready(&d).unwrap();
        assert_eq!(r.session_id, "gw_1");
        assert_eq!(r.member_id, Id::new(42));
        assert!(r.call_keys.is_none());
        assert!(r.install_id.is_none());
    }

    #[test]
    fn call_ready_install_id_is_read() {
        // The call socket's READY carries `install_id` (and `call_keys`) at the top.
        let d = serde_json::json!({
            "v": 1, "session_id": "gw_2", "user": {"id": "42"}, "install_id": "9001"
        });
        let r = parse_ready(&d).unwrap();
        assert_eq!(r.install_id, Id::new(9001));
        assert_eq!(r.member_id, Id::new(42));
    }

    #[test]
    fn closes_map_to_outcomes() {
        let b = Duration::from_millis(100);
        // Sew 0.7.1's text (and a takeover's) names no reason.
        assert!(matches!(
            close_outcome(Some(4011), "session_revoked", b),
            Outcome::Final(SocketClosed::Revoked)
        ));
        assert!(matches!(
            close_outcome(Some(4004), "", b),
            Outcome::Final(SocketClosed::AuthenticationFailed)
        ));
        assert!(matches!(
            close_outcome(Some(4009), "", b),
            Outcome::NewSession(_)
        ));
        assert!(
            matches!(close_outcome(Some(4008), "", b), Outcome::Retry(d) if d >= RATE_LIMITED_MIN)
        );
        assert!(matches!(close_outcome(Some(1006), "", b), Outcome::Retry(d) if d == b));
        assert!(matches!(frame_outcome(None, b), Outcome::Retry(d) if d == b));
    }

    #[test]
    fn a_4011_keeps_the_reason_sew_gave() {
        // Sew 0.7.2: the close text of a call socket names why its credential ended.
        let b = Duration::from_millis(100);
        for (text, want) in [
            ("call_ended:perms_lost", "perms_lost"),
            ("call_ended:removed_from_space", "removed_from_space"),
            ("call_ended:timed_out", "timed_out"),
            ("call_ended:channel_archived", "channel_archived"),
            ("call_ended:removed_by_moderator", "removed_by_moderator"),
            ("call_ended:device_revoked", "device_revoked"),
            ("call_ended:session_revoked", "session_revoked"),
            ("call_ended:replaced", "replaced"),
            ("signed_out", "session_revoked"),
            ("deactivated", "account_removed"),
        ] {
            match close_outcome(Some(4011), text, b) {
                Outcome::Final(SocketClosed::Ended { reason }) => assert_eq!(reason, want),
                _ => panic!("{text}: not an ended close"),
            }
        }
        let f = CloseFrame {
            code: 4011.into(),
            reason: "call_ended:perms_lost".into(),
        };
        assert!(matches!(
            frame_outcome(Some(&f), b),
            Outcome::Final(SocketClosed::Ended { reason }) if reason == "perms_lost"
        ));
        // Another code with the same text is not an end.
        assert!(matches!(
            close_outcome(Some(4004), "call_ended:perms_lost", b),
            Outcome::Final(SocketClosed::AuthenticationFailed)
        ));
    }
}