diff --git a/crates/voelin-core/src/link/tests.rs b/crates/voelin-core/src/link/tests.rs index b64780e..782ea6f 100644 --- a/crates/voelin-core/src/link/tests.rs +++ b/crates/voelin-core/src/link/tests.rs @@ -94,9 +94,13 @@ fn presence() -> Presence { } fn connected(capabilities: Capabilities) -> LinkEvent { + connected_to(capabilities, BackendInfo { product: "Fake".into(), version: "1.2".into() }) +} + +fn connected_to(capabilities: Capabilities, backend: BackendInfo) -> LinkEvent { LinkEvent::Connected { name: "Test Server".into(), - backend: BackendInfo { product: "Fake".into(), version: "1.2".into() }, + backend, capabilities, own_client: ME, server_uid: "server=".into(), @@ -134,6 +138,17 @@ impl Rig { /// Connect and let the link report its server; the first events are /// consumed up to the own channel. async fn new(capabilities: Capabilities) -> Rig { + Rig::connect(connected(capabilities)).await + } + + /// A connection to a TeamSpeak 3 server (its session follows our client across + /// the reconnects of the link). + async fn teamspeak(capabilities: Capabilities) -> Rig { + let backend = BackendInfo { product: "TeamSpeak 3".into(), version: "3.13.8".into() }; + Rig::connect(connected_to(capabilities, backend)).await + } + + async fn connect(connected: LinkEvent) -> Rig { let (conns, mut seen) = mpsc::unbounded_channel(); let mut backends = Backends::empty(); backends.register_local(Arc::new(LinkConnector::any(Arc::new(Recorder(conns))))); @@ -144,7 +159,7 @@ impl Rig { let (event_tx, events) = mpsc::unbounded_channel(); link.spawn(ConnectOptions::new("fake.test:9987", "tester"), ctx, cmd_rx, event_tx); let inner = within("the link to be asked", seen.recv()).await; - inner.events.send(connected(capabilities)).unwrap(); + inner.events.send(connected).unwrap(); inner.events.send(LinkEvent::Presence(Box::new(presence()))).unwrap(); let mut rig = Rig { inner, cmds: cmd_tx, events, bus }; rig.event(|e| matches!(e, LinkEvent::Connected { .. }).then_some(())).await; @@ -1539,3 +1554,368 @@ fn on_the_bus(rig: &mut Rig) -> bool { } found } + +// ---- the connection across TeamSpeak's own reconnect ------------------------------ + +/// Our identity again, as the client TeamSpeak's reconnect makes: the same +/// unique id and database id, a client id of its own. +fn reconnected(id: u16, channel: u64) -> ClientInfo { + ClientInfo { id, ..client(ME, "me", channel) } +} + +async fn own_channel(rig: &mut Rig) -> u64 { + rig.event(|e| match e { + LinkEvent::OwnChannel(channel) => Some(channel), + _ => None, + }) + .await +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_engine_follows_a_reconnect_that_makes_us_another_client() { + let mut rig = Rig::teamspeak(everything()).await; + // The connection comes back as client 21, in the lobby: 7 is gone. + let mut next = presence(); + next.clients.remove(&ME); + next.clients.insert(21, reconnected(21, LOBBY)); + rig.play(LinkEvent::Presence(Box::new(next))); + assert_eq!(own_channel(&mut rig).await, LOBBY); + + // The chat of the channel we are in now reaches us. + rig.play(LinkEvent::Chat(ChatMessage { + target: ChatTarget::Channel(LOBBY), + author_name: "bob".into(), + author_uid: Some("bob=".into()), + author_id: Some(9), + text: "welcome back".into(), + ts_ms: 1_700_000_000_000, + via_relay: false, + blocked: false, + })); + let chat = rig + .event(|e| match e { + LinkEvent::Chat(chat) => Some(chat), + _ => None, + }) + .await; + assert_eq!((chat.text.as_str(), chat.target), ("welcome back", ChatTarget::Channel(LOBBY))); + + // What we say goes to the channel we are in now, not to the old one. + rig.give(LinkCmd::SendChat(ChatTarget::Channel(LOBBY), "thanks".into())); + let LinkCmd::SendChat(target, text) = rig.inner_cmd().await else { panic!("a chat message") }; + assert_eq!((target, text.as_str()), (ChatTarget::Channel(LOBBY), "thanks")); + rig.give(LinkCmd::SendChat(ChatTarget::Channel(GAMES), "stale".into())); + let error = rig + .event(|e| match e { + LinkEvent::Error(text) => Some(text), + _ => None, + }) + .await; + assert!(error.starts_with("message: "), "{error}"); + // Our voice leaves on the slot of the client we are now, and the flags too. + rig.give(LinkCmd::Audio(EncodedVoice { + codec: VoiceCodec::Voice, + payload: OPUS_20_MS.to_vec(), + })); + assert!(matches!(rig.inner_cmd().await, LinkCmd::Audio(_))); + rig.give(LinkCmd::SetInputMuted(true)); + assert!(matches!(rig.inner_cmd().await, LinkCmd::SetInputMuted(true))); + rig.quiet(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn we_stay_the_client_we_were_while_it_is_there() { + let mut rig = Rig::teamspeak(everything()).await; + // A ghost of the old connection lingers: both clients carry our unique id. + // We stay client 7 (in the games channel), as another client of the same + // identity may be a second connection of ours. + let mut ghost = presence(); + ghost.clients.insert(21, reconnected(21, LOBBY)); + rig.play(LinkEvent::Presence(Box::new(ghost))); + assert_eq!(own_channel(&mut rig).await, GAMES); + + // The ghost goes: we are the one that is left. + let mut gone = presence(); + gone.clients.remove(&ME); + gone.clients.insert(21, reconnected(21, LOBBY)); + rig.play(LinkEvent::Presence(Box::new(gone))); + assert_eq!(own_channel(&mut rig).await, LOBBY); + rig.give(LinkCmd::Audio(EncodedVoice { + codec: VoiceCodec::Voice, + payload: OPUS_20_MS.to_vec(), + })); + assert!(matches!(rig.inner_cmd().await, LinkCmd::Audio(_))); +} + +// ---- chat scopes, private conversations ------------------------------------------- + +#[tokio::test(flavor = "multi_thread")] +async fn private_messages_from_more_than_16_peers_all_arrive() { + const PEERS: usize = 24; + let mut rig = Rig::new(everything()).await; + for peer in 0..PEERS { + let uid = format!("peer{peer}="); + rig.play(LinkEvent::Chat(ChatMessage { + target: ChatTarget::Private(uid.clone()), + author_name: format!("peer{peer}"), + author_uid: Some(uid), + author_id: None, + text: format!("hello {peer}"), + ts_ms: 1_700_000_000_000 + peer as i64, + via_relay: false, + blocked: false, + })); + } + let mut got = Vec::new(); + while got.len() < PEERS { + let chat = rig + .event(|e| match e { + LinkEvent::Chat(chat) => Some(chat), + _ => None, + }) + .await; + got.push((chat.text, chat.target)); + } + got.sort_by(|a, b| a.0.cmp(&b.0)); + let mut want: Vec<_> = (0..PEERS) + .map(|peer| (format!("hello {peer}"), ChatTarget::Private(format!("peer{peer}=")))) + .collect(); + want.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(got, want); +} + +// ---- who is talking ------------------------------------------------------------------ + +#[tokio::test(flavor = "multi_thread")] +async fn a_talker_the_link_hears_but_does_not_forward_is_shown_as_talking() { + let mut rig = Rig::new(everything()).await; + // A Speex or CELT talker: the link says it talks, and sends no Opus. + rig.play(LinkEvent::Talking { client: 8, talking: true }); + let on = rig + .event(|e| match e { + LinkEvent::Talking { client, talking } => Some((client, talking)), + _ => None, + }) + .await; + assert_eq!(on, (8, true)); + // And it holds for as long as the link says, silence or not. + tokio::time::sleep(Duration::from_millis(700)).await; + rig.play(LinkEvent::Talking { client: 8, talking: false }); + let off = rig + .event(|e| match e { + LinkEvent::Talking { client, talking } => Some((client, talking)), + _ => None, + }) + .await; + assert_eq!(off, (8, false)); +} + +// ---- notify ---------------------------------------------------------------------------- + +#[tokio::test(flavor = "multi_thread")] +async fn a_notify_needs_the_control_stream_and_is_run_as_the_request_it_is() { + use v1::request::Op; + let (session, _pushes, mut inner) = open(everything()).await; + // A List and the file transfers have a stream and an answer of their own; + // a Hello is part of connecting. + for op in [ + Op::List(v1::List { kind: v1::EntityKind::File as i32, ..Default::default() }), + Op::FileRead(Default::default()), + Op::FileWrite(Default::default()), + Op::Hello(Default::default()), + ] { + let error = session.notify(op).unwrap_err(); + assert!(matches!(error, SessionError::Protocol(_)), "{error:?}"); + } + // An op of the control stream is acted on, answer or not: a poke is a poke. + session + .notify(Op::Signal(v1::Signal { + to: Some(v1::SignalTarget { server_id: 1, participant_id: 8, ..Default::default() }), + body: Some(v1::signal::Body::Poke(v1::Poke { message: "wake up".into() })), + ..Default::default() + })) + .unwrap(); + let LinkCmd::Poke { client, message } = within("a poke", inner.cmds.recv()).await else { + panic!("a poke") + }; + assert_eq!((client, message.as_str()), (8, "wake up")); + // And a closed session refuses it. + session.close(v1::CloseCode::Normal, ""); + let _ = within("the disconnect", inner.cmds.recv()).await; + inner.events.send(LinkEvent::Disconnected(None)).unwrap(); + let _ = session.closed().await; + let error = session.notify(Op::LeaveVoice(v1::LeaveVoice { server_id: 1 })).unwrap_err(); + assert!(matches!(error, SessionError::Closed(_)), "{error:?}"); +} + +// ---- how a connect ends ------------------------------------------------------------------ + +/// A connector of the protocol repository's fake host whose sessions answer +/// every `Subscribe` and push nothing: the test pushes the syncs itself. +struct Silent(voelin_proto::test_util::FakeConnector); + +impl Connector for Silent { + fn schemes(&self) -> &'static [&'static str] { + self.0.schemes() + } + + fn connect( + &self, + params: voelin_proto::link::ConnectParams, + ) -> voelin_proto::link::BoxFuture> { + let connecting = self.0.connect(params); + let fake = self.0.clone(); + Box::pin(async move { + let connected = connecting.await?; + if let Some(handle) = fake.last_session() { + handle.script( + voelin_proto::test_util::Script::answer( + "subscribe", + v1::response::Result::Ack(Default::default()), + ) + .times(3), + ); + } + Ok(connected) + }) + } +} + +/// A session that ends while the connect waits for the syncs says why it +/// ended: the engine shows the host's words, not a silent disconnect. +#[tokio::test(flavor = "multi_thread")] +async fn a_session_that_ends_during_the_connect_syncs_says_why() { + use voelin_model::replica::ScopeId; + use voelin_proto::v1::push::Body; + let fake = voelin_proto::test_util::FakeConnector::new(); + fake.host() + .put(v1::Entity { + kind: Some(v1::entity::Kind::Server(v1::Server { + id: 1, + name: "Fake Host".into(), + uid: "fake-host".into(), + ..Default::default() + })), + }) + .unwrap(); + let mut backends = Backends::empty(); + backends.register(Arc::new(Silent(fake.clone()))); + let link = SessionLink::new(backends); + let ctx = LocalCtx::standalone().link; + let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel(); + let (event_tx, mut events) = mpsc::unbounded_channel(); + link.spawn(ConnectOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx); + + // The three subscriptions are answered; two syncs end, the LIVE one never does. + let handle = loop { + if let Some(handle) = fake.last_session() { + break handle; + } + tokio::time::sleep(Duration::from_millis(2)).await; + }; + voelin_proto::test_util::eventually(WAIT, "the three subscriptions", || { + handle + .requests() + .iter() + .filter(|logged| matches!(&logged.request.op, Some(v1::request::Op::Subscribe(_)))) + .count() == 3 + }) + .await; + for scope in [ScopeId::Home, ScopeId::Server(1)] { + let proto = Some(scope.to_proto()); + let begin = v1::SyncBegin { scope: proto, mode: v1::SyncMode::Full as i32, epoch: 1 }; + let end = + v1::SyncEnd { scope: proto, cursor: Some(v1::Cursor { epoch: 1, rev: 1 }), gap: false }; + handle.push(v1::Push { body: Some(Body::SyncBegin(begin)) }).unwrap(); + handle.push(v1::Push { body: Some(Body::SyncEnd(end)) }).unwrap(); + } + // The host ends the session, with a reason. + handle.kill(CloseReason::Network("kicked: spam".into())); + let reason = within("the end", async { + loop { + if let LinkEvent::Disconnected(reason) = events.recv().await? { + return Some(reason); + } + } + }) + .await; + assert_eq!(reason.as_deref(), Some("kicked: spam")); +} + +/// A link no connector serves: the text shows where, never the channel +/// password that rides in the link. +#[tokio::test(flavor = "multi_thread")] +async fn the_text_of_an_address_nobody_serves_keeps_the_channel_password_out() { + let ctx = LocalCtx::standalone().link; + let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel(); + let (event_tx, mut events) = mpsc::unbounded_channel(); + let link = SessionLink::new(Backends::empty()); + let mut options = ConnectOptions::new("ts.example.com:9987", "tester"); + options.channel = Some("Raid".into()); + options.channel_password = Some("hunter2".into()); + link.spawn(options, ctx, cmd_rx, event_tx); + let event = within("the end", events.recv()).await; + let LinkEvent::Disconnected(Some(why)) = event else { panic!("a disconnect with a reason") }; + assert!(why.starts_with("no connector for ts3server://ts.example.com"), "{why}"); + assert!(!why.contains("hunter2") && !why.contains('?'), "{why}"); +} + +// ---- a consumer that lags ------------------------------------------------------------------- + +/// A session whose consumer does not read pushes does not stall the +/// connection: the voice goes on, and once the consumer reads again it gets +/// the scopes it missed in full (`ConnectParams.push_capacity`). +#[tokio::test(flavor = "multi_thread")] +async fn a_consumer_that_lags_loses_the_queue_and_gets_the_scope_again() { + use voelin_model::replica::{Replica, ScopeId}; + let (conns, mut seen) = mpsc::unbounded_channel(); + let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]); + let (mut params, mut media) = connect_params("ts3server://fake.test?port=9987"); + params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() }; + // The smallest queue there is: 16 pushes. + params.push_capacity = 1; + let connecting = tokio::spawn(connector.connect(params)); + let inner = within("the link to be asked", seen.recv()).await; + inner.events.send(connected(everything())).unwrap(); + inner.events.send(LinkEvent::Presence(Box::new(presence()))).unwrap(); + let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await; + let (session, mut pushes) = (connected.session, connected.pushes); + + let server = ScopeId::Server(1); + session.request(subscribe(server)).await.unwrap(); + // Far more changes than the queue holds, and nobody reads. + const NAMES: usize = 40; + for i in 0..NAMES { + let mut next = presence(); + next.channels.get_mut(&LOBBY).unwrap().name = format!("name{i}"); + inner.events.send(LinkEvent::Presence(Box::new(next))).unwrap(); + } + // The connection still takes voice from the link while the queue is full. + inner + .events + .send(LinkEvent::Audio(VoicePacket { + talker: TalkerId(8), + seq: 1, + codec: VoiceCodec::Voice, + whisper: false, + payload: OPUS_20_MS.to_vec(), + })) + .unwrap(); + let packet = within("the voice", media.recv()).await; + assert_eq!(packet.flow.slot(), 9, "alice's slot"); + + // The consumer reads at last: what it gets ends with the last state. + let mut replica = Replica::default(); + replica.subscribe(server); + let last = format!("name{}", NAMES - 1); + within("the last state", async { + loop { + let push = pushes.recv().await?; + replica.apply_push(&push); + if replica.channel(LOBBY).is_some_and(|channel| channel.name == last) { + return Some(()); + } + } + }) + .await; +}