//! The seam from both sides, with a recording link inside: every `LinkCmd` //! the engine gives becomes the `Session` call of its row in //! `docs/session-seam.md` (table 3.1) and reaches the link as the inner //! `LinkCmd` of the same row; every `LinkEvent` of the link comes back as the //! row of table 3.2 says. `the_teamspeak_session` talks to the `Session` of //! the TeamSpeak side directly. use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::io::AsyncReadExt; use tokio::sync::{broadcast, mpsc}; use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket}; use voelin_model::{ Capabilities, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails, }; use voelin_proto::link::{ CloseReason, Connector, Credential, FlowId, MediaClass, MediaError, MediaPacket, Session, SessionError, }; use voelin_proto::test_util::connect_params; use voelin_proto::v1; use super::*; use crate::files::{DownloadTo, FileEntry, TransferState}; use crate::offline::OfflineMessage; use crate::offline::OfflineMessageInfo; use crate::stream::{OwnStreamEvent, StreamCmd, StreamKind}; use crate::ts_session::LinkConnector; use crate::{BackendInfo, Event, JoinFailure}; const ME: u16 = 7; const LOBBY: u64 = 1; const GAMES: u64 = 2; const WAIT: Duration = Duration::from_secs(10); /// A connection the engine asked the link for. struct Inner { options: ConnectOptions, ctx: LinkCtx, cmds: mpsc::UnboundedReceiver, events: mpsc::UnboundedSender, } /// Hands every connection to the test. struct Recorder(mpsc::UnboundedSender); impl ServerLink for Recorder { fn spawn( &self, options: ConnectOptions, ctx: LinkCtx, cmds: mpsc::UnboundedReceiver, events: mpsc::UnboundedSender, ) { let _ = self.0.send(Inner { options, ctx, cmds, events }); } } fn client(id: u16, name: &str, channel: u64) -> ClientInfo { ClientInfo { id, uid: Some(format!("{name}=")), nickname: name.into(), channel, database_id: Some(1_000 + u64::from(id)), talking: Some(false), ..Default::default() } } /// Two channels; us in the second, alice (8) in the same one, bob (9) in the /// first. fn presence() -> Presence { let channel = |id, order| ChannelInfo { id, name: format!("c{id}"), order, ..Default::default() }; let mut presence = Presence { server_name: "Test Server".into(), server: ServerDetails { name: "Test Server".into(), uid: Some("server=".into()), version: "1.2".into(), ..Default::default() }, ..Default::default() }; presence.channels.insert(LOBBY, channel(LOBBY, 0)); presence.channels.insert(GAMES, channel(GAMES, LOBBY)); for c in [client(ME, "me", GAMES), client(8, "alice", GAMES), client(9, "bob", LOBBY)] { presence.clients.insert(c.id, c); } presence } fn connected(capabilities: Capabilities) -> LinkEvent { LinkEvent::Connected { name: "Test Server".into(), backend: BackendInfo { product: "Fake".into(), version: "1.2".into() }, capabilities, own_client: ME, server_uid: "server=".into(), own_uid: Some("me=".into()), } } /// Every feature a link can have. fn everything() -> Capabilities { Capabilities { streams: true, file_transfer: true, offline_messages: true, ..Default::default() } } async fn within(what: &str, f: impl std::future::Future>) -> T { tokio::time::timeout(WAIT, f) .await .unwrap_or_else(|_| panic!("timed out waiting for {what}")) .unwrap_or_else(|| panic!("{what}: the channel closed")) } /// The engine's side (a `SessionLink` driven with `LinkCmd`s), the link's side /// (what the recorder saw), and the engine's event bus. struct Rig { inner: Inner, cmds: mpsc::UnboundedSender, events: mpsc::UnboundedReceiver, bus: broadcast::Receiver, } 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 { let (conns, mut seen) = mpsc::unbounded_channel(); let mut backends = Backends::empty(); backends.register_local(Arc::new(LinkConnector::any(Arc::new(Recorder(conns))))); let link = SessionLink::new(backends); let ctx = LocalCtx::standalone().link; let bus = ctx.events.subscribe(); let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); 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(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; rig.event(|e| matches!(e, LinkEvent::OwnChannel(_)).then_some(())).await; rig } fn give(&self, cmd: LinkCmd) { self.cmds.send(cmd).expect("the connection listens"); } fn play(&self, event: LinkEvent) { self.inner.events.send(event).expect("the session listens"); } /// The next inner command. async fn inner_cmd(&mut self) -> LinkCmd { within("an inner command", self.inner.cmds.recv()).await } /// The next event `f` picks, skipping the others. async fn event(&mut self, mut f: impl FnMut(LinkEvent) -> Option) -> T { within("an event", async { loop { if let Some(t) = f(self.events.recv().await?) { return Some(t); } } }) .await } /// The next bus event `f` picks, skipping the others. async fn bus(&mut self, mut f: impl FnMut(Event) -> Option) -> T { within("a bus event", async { loop { if let Some(t) = f(self.bus.recv().await.ok()?) { return Some(t); } } }) .await } /// The engine told the link nothing it did not ask for. fn quiet(&mut self) { assert!(self.inner.cmds.try_recv().is_err(), "a command reached the link"); } } fn recorder() -> (Report, Arc>>) { let states = Arc::new(Mutex::new(Vec::new())); let sink = states.clone(); (Arc::new(move |state| sink.lock().unwrap().push(state)), states) } async fn final_state(states: &Arc>>) -> TransferState { for _ in 0..500 { if let Some(last) = states.lock().unwrap().last().filter(|s| s.is_final()) { return last.clone(); } tokio::time::sleep(Duration::from_millis(10)).await; } panic!("the transfer did not end: {:?}", states.lock().unwrap()); } fn remote(channel: u64, password: Option<&str>, path: &str) -> Remote { Remote { channel, password: password.map(str::to_owned), path: path.into() } } fn temp(tag: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("voelin-seam-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); dir } /// 20 ms of CELT, mono, one frame. const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02]; // ---- the engine's side -------------------------------------------------------- #[tokio::test(flavor = "multi_thread")] async fn chat_moves_flags_pokes_and_voice_reach_the_link() { let mut rig = Rig::new(everything()).await; // The link was given the options the session was asked to connect with. assert_eq!( (rig.inner.options.address.as_str(), rig.inner.options.nickname.as_str()), ("fake.test:9987", "tester") ); // SendChat: a channel, the server chat, a client on the server. rig.give(LinkCmd::SendChat(ChatTarget::Channel(GAMES), "hello".into())); let LinkCmd::SendChat(target, text) = rig.inner_cmd().await else { panic!("a chat message") }; assert_eq!((target, text.as_str()), (ChatTarget::Channel(GAMES), "hello")); rig.give(LinkCmd::SendChat(ChatTarget::Server, "to all".into())); let LinkCmd::SendChat(target, text) = rig.inner_cmd().await else { panic!("a chat message") }; assert_eq!((target, text.as_str()), (ChatTarget::Server, "to all")); rig.give(LinkCmd::SendChat(ChatTarget::Private("alice=".into()), "psst".into())); let LinkCmd::SendChat(target, text) = rig.inner_cmd().await else { panic!("a chat message") }; assert_eq!((target, text.as_str()), (ChatTarget::Private("alice=".into()), "psst")); // A channel we are not in is refused by the session, with the words of a // refusal; the link hears nothing. rig.give(LinkCmd::SendChat(ChatTarget::Channel(LOBBY), "elsewhere".into())); let error = rig .event(|e| match e { LinkEvent::Error(text) => Some(text), _ => None, }) .await; assert!(error.starts_with("message: "), "{error}"); // Someone who is not on the server cannot be written to. rig.give(LinkCmd::SendChat(ChatTarget::Private("ghost=".into()), "boo".into())); let error = rig .event(|e| match e { LinkEvent::Error(text) => Some(text), _ => None, }) .await; assert_eq!( error, "private message: the client is not on the server (send an offline message instead)" ); rig.quiet(); // Move: with and without a password. rig.give(LinkCmd::Move(LOBBY, Some("pw".into()))); let LinkCmd::Move(channel, password) = rig.inner_cmd().await else { panic!("a move") }; assert_eq!((channel, password.as_deref()), (LOBBY, Some("pw"))); rig.give(LinkCmd::Move(LOBBY, None)); let LinkCmd::Move(_, password) = rig.inner_cmd().await else { panic!("a move") }; assert_eq!(password, None); // The mute flags. rig.give(LinkCmd::SetInputMuted(true)); assert!(matches!(rig.inner_cmd().await, LinkCmd::SetInputMuted(true))); rig.give(LinkCmd::SetOutputMuted(true)); assert!(matches!(rig.inner_cmd().await, LinkCmd::SetOutputMuted(true))); // A poke. rig.give(LinkCmd::Poke { client: 8, message: "wake up".into() }); let LinkCmd::Poke { client, message } = rig.inner_cmd().await else { panic!("a poke") }; assert_eq!((client, message.as_str()), (8, "wake up")); // Voice: the payload and the codec survive the RTP between. rig.give(LinkCmd::Audio(EncodedVoice { codec: VoiceCodec::Voice, payload: OPUS_20_MS.to_vec(), })); let LinkCmd::Audio(voice) = rig.inner_cmd().await else { panic!("voice") }; assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..])); let stereo = [OPUS_20_MS[0] | 0x04, 1, 2]; rig.give(LinkCmd::Audio(EncodedVoice { codec: VoiceCodec::Music, payload: stereo.to_vec() })); let LinkCmd::Audio(voice) = rig.inner_cmd().await else { panic!("voice") }; assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Music, &stereo[..])); // The end of a transmission is an empty packet, once. rig.give(LinkCmd::Audio(EncodedVoice { codec: VoiceCodec::Voice, payload: Vec::new() })); let LinkCmd::Audio(voice) = rig.inner_cmd().await else { panic!("voice") }; assert!(voice.is_end()); // Streams go to the stream task, in order with everything else. rig.give(LinkCmd::Stream(StreamCmd::Directory(Vec::new()))); assert!(matches!(rig.inner_cmd().await, LinkCmd::Stream(StreamCmd::Directory(_)))); rig.quiet(); } #[tokio::test(flavor = "multi_thread")] async fn files_avatars_and_offline_messages_reach_the_link() { let mut rig = Rig::new(everything()).await; // A listing is answered on the bus, with the engine's request id and the // directory as the server echoes it. rig.give(LinkCmd::ListFiles { request: 5, dir: remote(GAMES, Some("pw"), "/docs/") }); let LinkCmd::ListFiles { request, dir } = rig.inner_cmd().await else { panic!("a listing") }; assert_eq!( (dir.channel, dir.password.as_deref(), dir.path.as_str()), (GAMES, Some("pw"), "/docs/") ); let entry = FileEntry { name: "a.txt".into(), size: 12, modified_s: 1_700_000_000, is_dir: false }; rig.inner.ctx.emit(Event::FileList { session: 0, request, channel: GAMES, path: "/docs".into(), result: Ok(vec![entry.clone()]), }); let listed = rig .bus(|e| match e { Event::FileList { request, channel, path, result, .. } => { Some((request, channel, path, result)) } _ => None, }) .await; assert_eq!(listed, (5, GAMES, "/docs".into(), Ok(vec![entry]))); // A listing that fails says why. rig.give(LinkCmd::ListFiles { request: 6, dir: remote(GAMES, None, "/") }); let LinkCmd::ListFiles { request, .. } = rig.inner_cmd().await else { panic!("a listing") }; rig.inner.ctx.emit(Event::FileList { session: 0, request, channel: GAMES, path: "/".into(), result: Err("no access".into()), }); let failed = rig .bus(|e| match e { Event::FileList { request: 6, result, .. } => Some(result), _ => None, }) .await; assert_eq!(failed, Err("no access".into())); // Delete, rename and create answer with the engine's request id. let done = |rig: &Rig, request, result| { rig.inner.ctx.emit(Event::RequestDone { session: 0, request, result }); }; rig.give(LinkCmd::DeleteFiles { request: Some(7), channel: GAMES, password: Some("pw".into()), paths: vec!["/docs/a.txt".into(), "/b.txt".into()], }); let LinkCmd::DeleteFiles { request: Some(inner), channel, password, paths } = rig.inner_cmd().await else { panic!("a deletion") }; assert_eq!((channel, password.as_deref()), (GAMES, Some("pw"))); assert_eq!(paths, ["/docs/a.txt", "/b.txt"]); done(&rig, inner, Ok(())); assert_eq!( rig.bus(|e| match e { Event::RequestDone { request: 7, result, .. } => Some(result), _ => None, }) .await, Ok(()) ); // Best effort: nobody waits for the answer. rig.give(LinkCmd::DeleteFiles { request: None, channel: GAMES, password: None, paths: vec!["/c.txt".into()], }); // The link is asked like for any other deletion (the session has its own // request ids); nobody listens to the answer. let LinkCmd::DeleteFiles { paths, .. } = rig.inner_cmd().await else { panic!("a best-effort deletion") }; assert_eq!(paths, ["/c.txt"]); rig.give(LinkCmd::RenameFile { request: 8, from: remote(GAMES, Some("pw"), "/docs/a.txt"), to: remote(LOBBY, None, "/moved/b.txt"), }); let LinkCmd::RenameFile { request: inner, from, to } = rig.inner_cmd().await else { panic!("a rename") }; assert_eq!( (from.channel, from.password.as_deref(), from.path.as_str()), (GAMES, Some("pw"), "/docs/a.txt") ); assert_eq!( (to.channel, to.password.as_deref(), to.path.as_str()), (LOBBY, None, "/moved/b.txt") ); done(&rig, inner, Err("exists".into())); assert_eq!( rig.bus(|e| match e { Event::RequestDone { request: 8, result, .. } => Some(result), _ => None, }) .await, Err("exists".into()) ); rig.give(LinkCmd::CreateDirectory { request: 9, dir: remote(GAMES, None, "/new") }); let LinkCmd::CreateDirectory { request: inner, dir } = rig.inner_cmd().await else { panic!("a directory") }; assert_eq!((dir.channel, dir.path.as_str()), (GAMES, "/new")); done(&rig, inner, Ok(())); rig.bus(|e| matches!(e, Event::RequestDone { request: 9, .. }).then_some(())).await; // The avatar. rig.give(LinkCmd::SetAvatarHash { request: Some(10), hash: "abc123".into() }); let LinkCmd::SetAvatarHash { request: Some(inner), hash } = rig.inner_cmd().await else { panic!("an avatar") }; assert_eq!(hash, "abc123"); done(&rig, inner, Ok(())); rig.bus(|e| matches!(e, Event::RequestDone { request: 10, .. }).then_some(())).await; // With no request, a failure is an error of the session. rig.give(LinkCmd::SetAvatarHash { request: None, hash: String::new() }); let LinkCmd::SetAvatarHash { request: Some(inner), .. } = rig.inner_cmd().await else { panic!("an avatar") }; done(&rig, inner, Err("denied".into())); let error = rig .event(|e| match e { LinkEvent::Error(text) => Some(text), _ => None, }) .await; assert_eq!(error, "avatar: denied"); // Offline messages. rig.give(LinkCmd::OfflineList { request: 11 }); let LinkCmd::OfflineList { request } = rig.inner_cmd().await else { panic!("a mailbox list") }; let info = OfflineMessageInfo { id: 3, from_uid: "alice=".into(), subject: "hi".into(), ts_s: 1_700_000_000, read: true, }; rig.inner.ctx.emit(Event::OfflineMessages { session: 0, request, result: Ok(vec![info.clone()]), }); let listed = rig .bus(|e| match e { Event::OfflineMessages { request: 11, result, .. } => Some(result), _ => None, }) .await; assert_eq!(listed, Ok(vec![info])); rig.give(LinkCmd::OfflineGet { request: 12, id: 3 }); let LinkCmd::OfflineGet { request, id } = rig.inner_cmd().await else { panic!("a mail") }; assert_eq!(id, 3); rig.inner.ctx.emit(Event::OfflineMessage { session: 0, request, result: Ok(OfflineMessage { id: 3, from_uid: "alice=".into(), subject: "hi".into(), text: "the text".into(), ts_s: 1_700_000_000, }), }); let mail = rig .bus(|e| match e { Event::OfflineMessage { request: 12, result, .. } => Some(result), _ => None, }) .await; assert_eq!(mail.unwrap().text, "the text"); rig.give(LinkCmd::OfflineAdd { request: 13, to_uid: "alice=".into(), subject: "re".into(), text: "body".into(), }); let LinkCmd::OfflineAdd { request: inner, to_uid, subject, text } = rig.inner_cmd().await else { panic!("a mail to send") }; assert_eq!((to_uid.as_str(), subject.as_str(), text.as_str()), ("alice=", "re", "body")); done(&rig, inner, Ok(())); rig.bus(|e| matches!(e, Event::RequestDone { request: 13, .. }).then_some(())).await; rig.give(LinkCmd::OfflineDelete { request: 14, id: 3 }); let LinkCmd::OfflineDelete { request: inner, id } = rig.inner_cmd().await else { panic!("a mail to delete") }; assert_eq!(id, 3); done(&rig, inner, Ok(())); rig.bus(|e| matches!(e, Event::RequestDone { request: 14, .. }).then_some(())).await; rig.give(LinkCmd::OfflineFlag { request: 15, id: 3, read: true }); let LinkCmd::OfflineFlag { request: inner, id, read } = rig.inner_cmd().await else { panic!("a mail to flag") }; assert_eq!((id, read), (3, true)); done(&rig, inner, Ok(())); rig.bus(|e| matches!(e, Event::RequestDone { request: 15, .. }).then_some(())).await; rig.quiet(); } #[tokio::test(flavor = "multi_thread")] async fn a_file_is_downloaded_through_the_connection_the_link_opens() { let mut rig = Rig::new(everything()).await; let (report, states) = recorder(); rig.give(LinkCmd::Download { transfer: Some(1), file: remote(GAMES, Some("pw"), "/docs/a.txt"), sink: Sink::Memory, report, }); let LinkCmd::OpenRead { file, offset, reply } = rig.inner_cmd().await else { panic!("a connection to read") }; assert_eq!( (file.channel, file.password.as_deref(), file.path.as_str()), (GAMES, Some("pw"), "/docs/a.txt") ); assert_eq!(offset, 0); let _ = reply.send(Ok((5, Box::pin(std::io::Cursor::new(b"hello".to_vec()))))); let TransferState::Done { size, data: Some(data), .. } = final_state(&states).await else { panic!("a download in memory: {:?}", states.lock().unwrap()) }; assert_eq!((size, &*data.0), (5, &b"hello"[..])); { let states = states.lock().unwrap(); assert_eq!(states[0], TransferState::Requested); assert_eq!(states[1], TransferState::Started { size: 5, offset: 0 }); } // A refusal is the transfer's failure, with the link's words. let (report, states) = recorder(); rig.give(LinkCmd::Download { transfer: Some(2), file: remote(GAMES, None, "/gone.txt"), sink: Sink::Memory, report, }); let LinkCmd::OpenRead { reply, .. } = rig.inner_cmd().await else { panic!("a connection") }; let _ = reply.send(Err("file not found".into())); assert_eq!(final_state(&states).await, TransferState::Failed("file not found".into())); // Cancelling ends the copy, and the part file goes. let dir = temp("cancel"); let sink = Sink::from_target(&DownloadTo::Path { path: dir.join("big.bin"), resume: false }); let part = sink.part().unwrap().to_owned(); let (report, states) = recorder(); rig.give(LinkCmd::Download { transfer: Some(3), file: remote(GAMES, None, "/big.bin"), sink, report, }); let LinkCmd::OpenRead { reply, .. } = rig.inner_cmd().await else { panic!("a connection") }; // A file whose bytes do not come: the transfer waits in the middle. let (server, client) = tokio::io::duplex(64); let _ = reply.send(Ok((1 << 20, Box::pin(client)))); for _ in 0..500 { if states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })) { break; } tokio::time::sleep(Duration::from_millis(10)).await; } rig.give(LinkCmd::CancelTransfer(3)); assert_eq!(final_state(&states).await, TransferState::Cancelled); rig.quiet(); drop(server); // The part file was removed (or never made) after the cancel. tokio::time::sleep(Duration::from_millis(100)).await; assert!(!part.exists()); let _ = std::fs::remove_dir_all(dir); } #[tokio::test(flavor = "multi_thread")] async fn a_file_is_uploaded_and_resumed_through_the_connection_the_link_opens() { let mut rig = Rig::new(everything()).await; let dir = temp("upload"); let from = dir.join("up.bin"); std::fs::write(&from, b"0123456789").unwrap(); let (report, states) = recorder(); rig.give(LinkCmd::Upload { transfer: Some(1), file: remote(GAMES, None, "/up.bin"), from: from.clone(), overwrite: true, resume: false, report, }); let LinkCmd::OpenWrite { file, size, overwrite, resume, reply } = rig.inner_cmd().await else { panic!("a connection to write") }; assert_eq!( (file.channel, file.path.as_str(), size, overwrite, resume), (GAMES, "/up.bin", 10, true, false) ); let (server, client) = tokio::io::duplex(1024); let _ = reply.send(Ok((0, Box::pin(client)))); let server = tokio::spawn(async move { let mut server = server; let mut got = Vec::new(); server.read_to_end(&mut got).await.unwrap(); // The server closes the connection once it has everything. drop(server); got }); assert!(matches!(final_state(&states).await, TransferState::Done { size: 10, .. })); assert_eq!(server.await.unwrap(), b"0123456789"); // A resumed upload goes on where the server's copy ends. let (report, states) = recorder(); rig.give(LinkCmd::Upload { transfer: Some(2), file: remote(GAMES, None, "/up.bin"), from, overwrite: false, resume: true, report, }); let LinkCmd::ListFiles { request, dir: listed } = rig.inner_cmd().await else { panic!("the size of the server's copy is asked") }; assert_eq!((listed.channel, listed.path.as_str()), (GAMES, "/")); let entry = FileEntry { name: "up.bin".into(), size: 4, modified_s: 0, is_dir: false }; rig.inner.ctx.emit(Event::FileList { session: 0, request, channel: GAMES, path: "/".into(), result: Ok(vec![entry]), }); let LinkCmd::OpenWrite { resume, reply, .. } = rig.inner_cmd().await else { panic!("a connection to write") }; assert!(resume); let (server, client) = tokio::io::duplex(1024); // The server wants the bytes from where its copy ends. let _ = reply.send(Ok((4, Box::pin(client)))); let server = tokio::spawn(async move { let mut server = server; let mut got = Vec::new(); server.read_to_end(&mut got).await.unwrap(); drop(server); got }); assert!(matches!(final_state(&states).await, TransferState::Done { .. })); assert_eq!(server.await.unwrap(), b"456789"); let started = states.lock().unwrap().iter().find_map(|s| match s { TransferState::Started { size, offset } => Some((*size, *offset)), _ => None, }); assert_eq!(started, Some((10, 4))); // A file that is not there fails before the link is asked. let (report, states) = recorder(); rig.give(LinkCmd::Upload { transfer: None, file: remote(GAMES, None, "/x"), from: dir.join("missing"), overwrite: false, resume: false, report, }); let TransferState::Failed(why) = final_state(&states).await else { panic!("a failure") }; assert!(why.contains("missing"), "{why}"); rig.quiet(); let _ = std::fs::remove_dir_all(dir); } #[tokio::test(flavor = "multi_thread")] async fn what_the_link_reports_comes_back_as_events() { let mut rig = Rig::new(everything()).await; // Chat: our channel, the server chat, a private message. let message = |target: ChatTarget, text: &str| ChatMessage { target, author_name: "alice".into(), author_uid: Some("alice=".into()), author_id: Some(8), text: text.into(), ts_ms: 1_700_000_000_000, via_relay: false, blocked: false, }; rig.play(LinkEvent::Chat(message(ChatTarget::Channel(GAMES), "in the channel"))); rig.play(LinkEvent::Chat(message(ChatTarget::Server, "to the server"))); rig.play(LinkEvent::Chat(message(ChatTarget::Private("alice=".into()), "psst"))); let mut got = Vec::new(); while got.len() < 3 { let chat = rig .event(|e| match e { LinkEvent::Chat(chat) => Some(chat), _ => None, }) .await; got.push(chat); } got.sort_by_key(|m| m.text.clone()); let targets: Vec<_> = got.iter().map(|m| (m.text.as_str(), m.target.clone())).collect(); assert_eq!( targets, [ ("in the channel", ChatTarget::Channel(GAMES)), ("psst", ChatTarget::Private("alice=".into())), ("to the server", ChatTarget::Server), ] ); assert!( got.iter().all(|m| m.author_uid.as_deref() == Some("alice=") && m.author_id == Some(8)) ); assert!(got.iter().all(|m| m.author_name == "alice" && m.ts_ms == 1_700_000_000_000)); // A poke, named by the sender's nickname and unique id. rig.play(LinkEvent::Poke { from: 8, from_uid: Some("alice=".into()), from_name: "alice".into(), message: "wake up".into(), }); let poke = rig .event(|e| match e { LinkEvent::Poke { from, from_uid, from_name, message } => { Some((from, from_uid, from_name, message)) } _ => None, }) .await; assert_eq!(poke, (8, Some("alice=".into()), "alice".into(), "wake up".into())); // A poke from somebody the snapshot does not hold is named all the same. rig.play(LinkEvent::Poke { from: 77, from_uid: Some("hidden=".into()), from_name: "hidden".into(), message: "boo".into(), }); let poke = rig .event(|e| match e { LinkEvent::Poke { from: 77, from_uid, from_name, .. } => Some((from_uid, from_name)), _ => None, }) .await; assert_eq!(poke, (Some("hidden=".into()), "hidden".into())); // Voice: audio from alice's slot, talking from the media. let voice = VoicePacket { talker: TalkerId(8), seq: 513, codec: VoiceCodec::Voice, whisper: false, payload: OPUS_20_MS.to_vec(), }; rig.play(LinkEvent::Audio(voice.clone())); let talking = rig .event(|e| match e { LinkEvent::Talking { client, talking } => Some((client, talking)), _ => None, }) .await; assert_eq!(talking, (8, true)); let heard = rig .event(|e| match e { LinkEvent::Audio(packet) => Some(packet), _ => None, }) .await; assert_eq!(heard, voice); // And silent 400 ms after her last packet. let off = rig .event(|e| match e { LinkEvent::Talking { client, talking } => Some((client, talking)), _ => None, }) .await; assert_eq!(off, (8, false)); // A whisper is marked, the end of a talk arrives empty. rig.play(LinkEvent::Audio(VoicePacket { whisper: true, seq: 514, ..voice.clone() })); let heard = rig .event(|e| match e { LinkEvent::Audio(packet) => Some(packet), _ => None, }) .await; assert!(heard.whisper && heard.seq == 514); rig.play(LinkEvent::Audio(VoicePacket { seq: 515, payload: Vec::new(), ..voice })); let heard = rig .event(|e| match e { LinkEvent::Audio(packet) => Some(packet), _ => None, }) .await; assert!(heard.is_end()); // Streams come through the port. rig.play(LinkEvent::OwnStream(OwnStreamEvent::Live { id: "s1".into(), title: "screen".into(), kind: StreamKind::Screen, })); let own = rig .event(|e| match e { LinkEvent::OwnStream(event) => Some(event), _ => None, }) .await; assert!(matches!(own, OwnStreamEvent::Live { ref id, .. } if id == "s1")); rig.play(LinkEvent::StreamAudio { stream: "s2".into(), time: 960, data: Arc::from(&[1u8, 2][..]), }); let audio = rig .event(|e| match e { LinkEvent::StreamAudio { stream, time, data } => Some((stream, time, data)), _ => None, }) .await; assert_eq!((audio.0.as_str(), audio.1, &*audio.2), ("s2", 960, &[1u8, 2][..])); rig.play(LinkEvent::StreamAudioEnded("s2".into())); let ended = rig .event(|e| match e { LinkEvent::StreamAudioEnded(stream) => Some(stream), _ => None, }) .await; assert_eq!(ended, "s2"); // An error of the link is an error of the session. rig.play(LinkEvent::Error("move refused".into())); let error = rig .event(|e| match e { LinkEvent::Error(text) => Some(text), _ => None, }) .await; assert_eq!(error, "move refused"); } #[tokio::test(flavor = "multi_thread")] async fn a_change_of_presence_is_reported_once_with_the_own_channel() { let mut rig = Rig::new(everything()).await; // The same snapshot again changes nothing. rig.play(LinkEvent::Presence(Box::new(presence()))); // Bob leaves, alice moves, and we move. let mut next = presence(); next.clients.remove(&9); next.clients.get_mut(&8).unwrap().channel = LOBBY; next.clients.get_mut(&ME).unwrap().channel = LOBBY; rig.play(LinkEvent::Presence(Box::new(next.clone()))); let shown = rig .event(|e| match e { LinkEvent::Presence(p) => Some(*p), _ => None, }) .await; assert_eq!(shown.clients.len(), 2); assert_eq!(shown.clients[&8].channel, LOBBY); let own = rig .event(|e| match e { LinkEvent::OwnChannel(c) => Some(c), _ => None, }) .await; assert_eq!(own, LOBBY); } // ---- how a connection ends ------------------------------------------------------ #[tokio::test(flavor = "multi_thread")] async fn a_disconnect_command_ends_the_link_and_reports_no_reason() { let mut rig = Rig::new(everything()).await; rig.give(LinkCmd::Stream(StreamCmd::Shutdown("going".into()))); rig.give(LinkCmd::Disconnect); // The streams hear of their end before the link is told to go. assert!(matches!(rig.inner_cmd().await, LinkCmd::Stream(StreamCmd::Shutdown(_)))); assert!(matches!(rig.inner_cmd().await, LinkCmd::Disconnect)); rig.play(LinkEvent::Disconnected(None)); let reason = rig .event(|e| match e { LinkEvent::Disconnected(reason) => Some(reason), _ => None, }) .await; assert_eq!(reason, None); } #[tokio::test(flavor = "multi_thread")] async fn a_link_that_ends_says_why_or_nothing() { let mut rig = Rig::new(everything()).await; rig.play(LinkEvent::Disconnected(Some("kicked: spam".into()))); let reason = rig .event(|e| match e { LinkEvent::Disconnected(reason) => Some(reason), _ => None, }) .await; assert_eq!(reason.as_deref(), Some("kicked: spam")); let mut rig = Rig::new(everything()).await; rig.play(LinkEvent::Disconnected(None)); let reason = rig .event(|e| match e { LinkEvent::Disconnected(reason) => Some(reason), _ => None, }) .await; assert_eq!(reason, None); } #[tokio::test(flavor = "multi_thread")] async fn a_connect_that_fails_is_a_disconnect_with_the_reason() { let (conns, mut seen) = mpsc::unbounded_channel(); let mut backends = Backends::empty(); backends.register_local(Arc::new(LinkConnector::any(Arc::new(Recorder(conns))))); 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.test:9987", "tester"), ctx, cmd_rx, event_tx); let inner = within("the link to be asked", seen.recv()).await; inner.events.send(LinkEvent::Disconnected(Some("connection refused".into()))).unwrap(); let event = within("the end", events.recv()).await; assert!(matches!(event, LinkEvent::Disconnected(Some(ref why)) if why == "connection refused")); drop(cmd_tx); // No connector for the address's scheme. 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()); link.spawn(ConnectOptions::new("voelin://host", "tester"), ctx, cmd_rx, event_tx); let event = within("the end", events.recv()).await; assert!( matches!(event, LinkEvent::Disconnected(Some(ref why)) if why == "no connector for voelin://host"), "a disconnect with the reason of the failed connect" ); } // ---- the TeamSpeak side alone --------------------------------------------------- /// A `LinkSession` over a recorder, made the way a connector makes it. async fn open(capabilities: Capabilities) -> (Arc, mpsc::Receiver, Inner) { let (conns, mut seen) = mpsc::unbounded_channel(); let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]); let (mut params, _media) = connect_params("ts3server://fake.test?port=9987"); params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() }; params.hello.nickname = "tester".into(); let connecting = tokio::spawn(connector.connect(params)); let inner = within("the link to be asked", seen.recv()).await; inner.events.send(connected(capabilities)).unwrap(); inner.events.send(LinkEvent::Presence(Box::new(presence()))).unwrap(); let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await; (connected.session, connected.pushes, inner) } fn request(op: v1::request::Op) -> v1::request::Op { op } fn subscribe(scope: voelin_model::replica::ScopeId) -> v1::request::Op { request(v1::request::Op::Subscribe(v1::Subscribe { scope: Some(scope.to_proto()), ..Default::default() })) } #[tokio::test(flavor = "multi_thread")] async fn the_welcome_names_the_host_the_user_and_what_the_link_can_do() { let (session, _pushes, inner) = open(everything()).await; assert_eq!(inner.options.address, "fake.test:9987"); assert_eq!(inner.options.nickname, "tester"); let welcome = session.welcome(); // The own user is the own client's database id. assert_eq!(welcome.user_id, 1_007); let host = welcome.host.as_ref().unwrap(); assert_eq!(host.name, "Test Server"); let backend = host.backend.as_ref().unwrap(); assert_eq!( (backend.product.as_str(), backend.version.as_str(), backend.flavor.as_str()), ("Fake", "1.2", "") ); let features = session.features(); for feature in [ "voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel", "files", "files.upload", "mailbox", "streams", "streams.p2p", "streams.audio", "streams.approval", ] { assert!(features.has(feature), "{feature}"); } assert!(!features.has("voice.whisper") && !features.has("chat.typing")); let limits = welcome.limits.as_ref().unwrap(); assert_eq!(limits.max_chat_subscriptions, 16); // A link without files, mail and streams offers none of them. let (plain, _pushes, _inner) = session_of_plain().await; let features = plain.features(); assert!( features.has("chat") && !features.has("files") && !features.has("mailbox") && !features.has("streams") ); } async fn session_of_plain() -> (Arc, mpsc::Receiver, Inner) { open(Capabilities::default()).await } #[tokio::test(flavor = "multi_thread")] async fn a_scope_is_synced_whole_and_then_by_changes_with_growing_revs() { use v1::push::Body; use voelin_model::replica::ScopeId; let (session, mut pushes, _inner) = open(everything()).await; // The server is the only one listed. let listed = session .request(v1::request::Op::List(v1::List { kind: v1::EntityKind::Server as i32, ..Default::default() })) .await .unwrap(); let v1::response::Result::Entities(entities) = listed else { panic!("the servers") }; let [v1::Entity { kind: Some(v1::entity::Kind::Server(server)) }] = entities.items.as_slice() else { panic!("one server") }; assert_eq!( (server.id, server.uid.as_str(), server.name.as_str()), (1, "ts:server=", "Test Server") ); session.request(subscribe(ScopeId::Server(1))).await.unwrap(); let Body::SyncBegin(begin) = next_body(&mut pushes).await else { panic!("a sync begins") }; assert_eq!(begin.mode, v1::SyncMode::Full as i32); let Body::Change(first) = next_body(&mut pushes).await else { panic!("the channels") }; let kinds: Vec<_> = first .put .iter() .filter_map(|e| match &e.kind { Some(v1::entity::Kind::Channel(c)) => Some(c.id), _ => None, }) .collect(); assert!(kinds.contains(&LOBBY) && kinds.contains(&GAMES), "{kinds:?}"); let Body::SyncEnd(end) = next_body(&mut pushes).await else { panic!("a sync ends") }; let cursor = end.cursor.unwrap(); assert_eq!(cursor.rev, first.rev); // A change of the snapshot is a Change with a newer rev. let mut next = presence(); next.channels.get_mut(&LOBBY).unwrap().name = "renamed".into(); _inner.events.send(LinkEvent::Presence(Box::new(next))).unwrap(); let Body::Change(change) = within("a change", async { pushes.recv().await }).await.body.unwrap() else { panic!("a change") }; assert!(change.rev > cursor.rev); assert_eq!(change.put.len(), 1); assert!(change.del.is_empty()); } #[tokio::test(flavor = "multi_thread")] async fn the_first_join_is_the_seat_and_a_move_waits_for_the_link() { let (session, _pushes, mut inner) = open(everything()).await; let join = |channel: u64, password: &str| { request(v1::request::Op::JoinVoice(v1::JoinVoice { server_id: 1, channel_id: channel, password: password.into(), ..Default::default() })) }; // The seat: our voice state, nothing moved. let seat = session.request(join(LOBBY, "")).await.unwrap(); let v1::response::Result::Entities(seat) = seat else { panic!("a voice state") }; let Some(v1::entity::Kind::Voice(voice)) = &seat.items[0].kind else { panic!("a voice state") }; assert_eq!((voice.participant_id, voice.slot, voice.channel_id), (u32::from(ME), 8, GAMES)); assert!(inner.cmds.try_recv().is_err(), "the seat moves nothing"); // A move: the link is asked, and the answer is our voice state in the new channel. let moving = session.request(join(LOBBY, "pw")); let LinkCmd::Move(channel, password) = within("a move", inner.cmds.recv()).await else { panic!("a move") }; assert_eq!((channel, password.as_deref()), (LOBBY, Some("pw"))); let mut next = presence(); next.clients.get_mut(&ME).unwrap().channel = LOBBY; inner.events.send(LinkEvent::Presence(Box::new(next))).unwrap(); let moved = within("the move", async { moving.await.ok() }).await; let v1::response::Result::Entities(moved) = moved else { panic!("a voice state") }; let Some(v1::entity::Kind::Voice(voice)) = &moved.items[0].kind else { panic!("a voice state") }; assert_eq!(voice.channel_id, LOBBY); // A refusal of the link: the code says why. let refused = session.request(join(GAMES, "wrong")); let LinkCmd::Move(..) = within("a move", inner.cmds.recv()).await else { panic!("a move") }; inner.ctx.emit(Event::JoinFailed { session: 0, channel: GAMES, reason: JoinFailure::Password }); let error = within("the refusal", async { Some(refused.await.unwrap_err()) }).await; assert_eq!(error.code(), Some(v1::ErrorCode::Password)); let refused = session.request(join(GAMES, "")); let LinkCmd::Move(..) = within("a move", inner.cmds.recv()).await else { panic!("a move") }; inner.ctx.emit(Event::JoinFailed { session: 0, channel: GAMES, reason: JoinFailure::Full }); let error = within("the refusal", async { Some(refused.await.unwrap_err()) }).await; assert_eq!(error.code(), Some(v1::ErrorCode::Full)); let refused = session.request(join(GAMES, "")); let LinkCmd::Move(..) = within("a move", inner.cmds.recv()).await else { panic!("a move") }; inner.ctx.emit(Event::JoinFailed { session: 0, channel: GAMES, reason: JoinFailure::Other("You are not allowed to join this channel.".into()), }); let error = within("the refusal", async { Some(refused.await.unwrap_err()) }).await; assert_eq!(error.code(), Some(v1::ErrorCode::Forbidden)); assert!(error.to_string().contains("not allowed")); } #[tokio::test(flavor = "multi_thread")] async fn requests_the_link_cannot_do_are_refused_with_the_feature() { let (session, _pushes, mut inner) = open(everything()).await; let error = session .request(request(v1::request::Op::LeaveVoice(v1::LeaveVoice { server_id: 1 }))) .await .unwrap_err(); assert_eq!(error.code(), Some(v1::ErrorCode::Unsupported)); // A message into a voice channel we are not in. let put = |channel_id: u64| { request(v1::request::Op::Put(v1::Put { writes: vec![v1::Write { entity: Some(v1::Entity { kind: Some(v1::entity::Kind::Message(v1::Message { channel_id, text: "hi".into(), ..Default::default() })), }), paths: Vec::new(), }], ..Default::default() })) }; let error = session.request(put(LOBBY)).await.unwrap_err(); assert_eq!(error.code(), Some(v1::ErrorCode::NotInChannel)); // Our own channel's message is answered as written, and handed to the link. let answer = session.request(put(GAMES)).await.unwrap(); let v1::response::Result::Entities(stored) = answer else { panic!("the message") }; let Some(v1::entity::Kind::Message(message)) = &stored.items[0].kind else { panic!("a message") }; assert_eq!((message.text.as_str(), message.channel_id), ("hi", GAMES)); assert!(message.id != 0); assert!(matches!( within("a chat", inner.cmds.recv()).await, LinkCmd::SendChat(ChatTarget::Channel(GAMES), _) )); // A hello is part of connecting. let hello = session.request(request(v1::request::Op::Hello(Default::default()))).await; assert!(matches!(hello, Err(SessionError::Protocol(_)))); // Without the feature, the file browser is refused before the link hears of it. let (plain, _pushes, mut plain_inner) = session_of_plain().await; let list = plain .request(request(v1::request::Op::List(v1::List { kind: v1::EntityKind::File as i32, parent: GAMES, ..Default::default() }))) .await .unwrap_err(); let SessionError::Rejected(error) = list else { panic!("a refusal") }; assert_eq!((error.code(), error.feature.as_str()), (v1::ErrorCode::Unsupported, "files")); assert!(plain_inner.cmds.try_recv().is_err()); } #[tokio::test(flavor = "multi_thread")] async fn media_is_checked_before_it_reaches_the_link() { let (session, _pushes, mut inner) = open(everything()).await; let own = FlowId::new(8, 0); let rtp = |flow: FlowId, payload: &[u8]| { let mut header = voelin_proto::media::RtpHeader::new(111, 0, 0); header.marker = true; let mut out = bytes::BytesMut::new(); header.write(flow, &mut out).unwrap(); out.extend_from_slice(payload); MediaPacket { flow, rtp: out.freeze() } }; assert_eq!( session.send_media(MediaClass::Voice, rtp(own, &OPUS_20_MS)).unwrap(), voelin_proto::link::Sent::Queued ); assert!(matches!(within("voice", inner.cmds.recv()).await, LinkCmd::Audio(_))); // Somebody else's slot, a whisper flow, a class that is not voice. let other = FlowId::new(9, 0); assert!(matches!( session.send_media(MediaClass::Voice, rtp(other, &OPUS_20_MS)), Err(MediaError::NotOwned(_)) )); let whisper = FlowId::new(8, 1); assert!(matches!( session.send_media(MediaClass::Voice, rtp(whisper, &OPUS_20_MS)), Err(MediaError::NotOwned(_)) )); assert!(matches!( session.send_media(MediaClass::Video, rtp(own, &OPUS_20_MS)), Err(MediaError::NotOwned(_)) )); // Over the limit. let big = vec![0u8; voelin_proto::link::MAX_RTP]; assert!(matches!( session.send_media(MediaClass::Voice, rtp(own, &big)), Err(MediaError::TooLarge { .. }) )); assert!(inner.cmds.try_recv().is_err()); // After the end, nothing is sent. session.close(v1::CloseCode::Normal, ""); let _ = within("the disconnect", inner.cmds.recv()).await; inner.events.send(LinkEvent::Disconnected(None)).unwrap(); let reason = session.closed().await; assert_eq!(reason, CloseReason::Local(v1::CloseCode::Normal)); assert!(matches!( session.send_media(MediaClass::Voice, rtp(own, &OPUS_20_MS)), Err(MediaError::Closed) )); } #[tokio::test(flavor = "multi_thread")] async fn a_session_closes_as_the_table_says() { // We close it: a local, normal close. let (session, _pushes, mut inner) = open(everything()).await; session.close(v1::CloseCode::Normal, "bye"); assert!(matches!(within("a disconnect", inner.cmds.recv()).await, LinkCmd::Disconnect)); inner.events.send(LinkEvent::Disconnected(None)).unwrap(); assert_eq!(session.closed().await, CloseReason::Local(v1::CloseCode::Normal)); // The link ends with a reason: the network, with the words. let (session, _pushes, inner) = open(everything()).await; inner.events.send(LinkEvent::Disconnected(Some("server shut down".into()))).unwrap(); assert_eq!(session.closed().await, CloseReason::Network("server shut down".into())); // The link ends unasked and without a reason: a normal close by the host. let (session, _pushes, inner) = open(everything()).await; inner.events.send(LinkEvent::Disconnected(None)).unwrap(); assert_eq!( session.closed().await, CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() } ); // What was asked of a closed session is refused with the reason. let error = session.request(request(v1::request::Op::List(Default::default()))).await.unwrap_err(); assert!(matches!(error, SessionError::Closed(_)), "{error:?}"); } #[tokio::test(flavor = "multi_thread")] async fn a_connect_that_the_link_fails_is_an_error_with_its_reason() { let (conns, mut seen) = mpsc::unbounded_channel(); let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]); let (mut params, _media) = connect_params("ts3server://fake.test"); params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() }; let connecting = tokio::spawn(connector.connect(params)); let inner = within("the link to be asked", seen.recv()).await; inner.events.send(LinkEvent::Disconnected(Some("connection refused".into()))).unwrap(); let Err(error) = connecting.await.expect("the connect task") else { panic!("a failed connect") }; assert!( matches!(&error, SessionError::Closed(CloseReason::Network(why)) if why == "connection refused") ); // A credential that is no TeamSpeak identity is refused before the link is asked. let (params, _media) = connect_params("ts3server://fake.test"); let Err(error) = connector.connect(params).await else { panic!("a refusal") }; assert!(matches!(error, SessionError::Protocol(_)), "{error:?}"); } /// The next push of the session, as its body. async fn next_body(pushes: &mut mpsc::Receiver) -> v1::push::Body { within("a push", pushes.recv()).await.body.expect("a push with a body") } /// A session that is no TeamSpeak one: the engine consumes it as it does /// the TeamSpeak side's, through the registry (the fake host of the protocol /// repository stands for a Voelin host). #[tokio::test(flavor = "multi_thread")] async fn the_engine_consumes_any_session_a_connector_makes() { use v1::entity::Kind; use voelin_proto::test_util::FakeConnector; let connector = FakeConnector::new(); let host = connector.host(); let put = |kind: Kind| host.put(v1::Entity { kind: Some(kind) }).unwrap(); put(Kind::Server(v1::Server { id: 1, name: "Fake Host".into(), uid: "fake-host".into(), default_channel_id: 10, ..Default::default() })); let channel = |id, name: &str, position| v1::Channel { id, server_id: 1, kind: v1::ChannelKind::Voice as i32, name: name.into(), position, ..Default::default() }; put(Kind::Channel(channel(10, "Lobby", 0))); put(Kind::Channel(channel(11, "Games", 1024))); put(Kind::User(v1::User { id: 2, uid: vec![2; 32].into(), uid_kind: v1::IdKind::Voelin as i32, name: "alice".into(), ..Default::default() })); put(Kind::Voice(v1::VoiceState { server_id: 1, participant_id: 50, user_id: 2, channel_id: 11, slot: 90, nick: "alice".into(), ..Default::default() })); let mut backends = Backends::empty(); backends.register(Arc::new(connector.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); async fn event( events: &mut mpsc::UnboundedReceiver, mut f: impl FnMut(LinkEvent) -> Option, ) -> T { within("an event", async { loop { if let Some(t) = f(events.recv().await?) { return Some(t); } } }) .await } let (name, backend, own_client, server_uid) = event(&mut events, |e| match e { LinkEvent::Connected { name, backend, own_client, server_uid, .. } => { Some((name, backend, own_client, server_uid)) } _ => None, }) .await; assert_eq!((name.as_str(), server_uid.as_str()), ("Fake Host", "fake-host")); assert_eq!(backend.product, "voelin-fake"); // The host seated us: its participant id is the client id of the older model. assert_ne!(own_client, 0); let presence = event(&mut events, |e| match e { LinkEvent::Presence(p) => Some(*p), _ => None, }) .await; assert_eq!(presence.server.name, "Fake Host"); assert_eq!(presence.channels.len(), 2); assert_eq!(presence.channels[&11].order, 10, "the order follows the positions"); let alice = &presence.clients[&50]; assert_eq!((alice.nickname.as_str(), alice.channel), ("alice", 11)); assert!(alice.uid.as_deref().is_some_and(|uid| uid.len() == 52), "a Voelin uid is base32"); // A move is a JoinVoice; the host's voice state tells where we are. cmd_tx.send(LinkCmd::Move(11, None)).unwrap(); event(&mut events, |e| match e { LinkEvent::OwnChannel(11) => Some(()), _ => None, }) .await; // Chat in the channel we are in: the host's copy comes back as ours. cmd_tx.send(LinkCmd::SendChat(ChatTarget::Channel(11), "hello host".into())).unwrap(); let chat = event(&mut events, |e| match e { LinkEvent::Chat(chat) => Some(chat), _ => None, }) .await; assert_eq!((chat.text.as_str(), chat.target), ("hello host", ChatTarget::Channel(11))); // The session closes with us. cmd_tx.send(LinkCmd::Disconnect).unwrap(); let reason = event(&mut events, |e| match e { LinkEvent::Disconnected(reason) => Some(reason), _ => None, }) .await; assert_eq!(reason, None); assert_eq!(connector.connects().len(), 1); } /// What the second adapter costs per voice packet (the last row of the risk /// table in `docs/session-seam.md`): every packet is framed as RTP and taken /// apart again on its way, in each direction. A generous bound in a debug /// build; the figures are printed. #[tokio::test(flavor = "multi_thread")] async fn a_voice_packet_costs_microseconds_through_both_adapters() { const PACKETS: usize = 5_000; let mut rig = Rig::new(everything()).await; let started = std::time::Instant::now(); for _ in 0..PACKETS { rig.give(LinkCmd::Audio(EncodedVoice { codec: VoiceCodec::Voice, payload: OPUS_20_MS.to_vec(), })); } for _ in 0..PACKETS { assert!(matches!(rig.inner_cmd().await, LinkCmd::Audio(_))); } let uplink = started.elapsed() / PACKETS as u32; let started = std::time::Instant::now(); for seq in 0..PACKETS { rig.play(LinkEvent::Audio(VoicePacket { talker: TalkerId(8), seq: seq as u16, codec: VoiceCodec::Voice, whisper: false, payload: OPUS_20_MS.to_vec(), })); } let mut heard = 0; while heard < PACKETS { rig.event(|e| matches!(e, LinkEvent::Audio(_)).then_some(())).await; heard += 1; } let downlink = started.elapsed() / PACKETS as u32; eprintln!("voice through both adapters: {uplink:?} per packet up, {downlink:?} down"); assert!(uplink < Duration::from_micros(500), "{uplink:?}"); assert!(downlink < Duration::from_micros(500), "{downlink:?}"); } /// What the stream task reports before the engine has announced the /// connection waits for it (`ts_session/driver.rs`, `Held`): the engine acts /// on a list of streams as soon as it sees one, and has to know it has voice /// by then, as it did when the stream task was not behind a session. #[tokio::test] async fn the_stream_tasks_reports_wait_for_the_engine_to_announce_the_connection() { let mut rig = Rig::new(everything()).await; let listed = || Event::StreamsChanged { session: 0, streams: Vec::new() }; rig.inner.ctx.events.send(listed()).unwrap(); rig.inner.ctx.events.send(Event::Error { session: 0, message: "second".into() }).unwrap(); tokio::time::sleep(Duration::from_millis(100)).await; assert!( !on_the_bus(&mut rig), "the list was passed on before the engine's first stream command" ); // The engine's first stream command comes after it announced the // connection; the reports follow it, in their order. rig.give(LinkCmd::Stream(StreamCmd::Directory(Vec::new()))); assert!(matches!(rig.inner_cmd().await, LinkCmd::Stream(StreamCmd::Directory(_)))); rig.bus(|e| matches!(e, Event::StreamsChanged { .. }).then_some(())).await; rig.bus(|e| matches!(e, Event::Error { message, .. } if message == "second").then_some(())) .await; // Afterwards they go straight through. rig.inner.ctx.events.send(listed()).unwrap(); rig.bus(|e| matches!(e, Event::StreamsChanged { .. }).then_some(())).await; } /// Nobody announces the connection to a session used without an engine: its /// stream reports are held for a while only. #[tokio::test] async fn the_stream_tasks_reports_are_not_held_for_ever() { let mut rig = Rig::new(everything()).await; rig.inner.ctx.events.send(Event::StreamsChanged { session: 0, streams: Vec::new() }).unwrap(); tokio::time::sleep(Duration::from_millis(50)).await; assert!(!on_the_bus(&mut rig), "the list was not held at all"); rig.bus(|e| matches!(e, Event::StreamsChanged { .. }).then_some(())).await; } /// A link without streams has no stream task to hold back: what it puts on /// the bus goes straight through. #[tokio::test] async fn a_link_without_streams_is_not_held_back() { let mut rig = Rig::new(Capabilities::default()).await; rig.inner.ctx.events.send(Event::Error { session: 0, message: "now".into() }).unwrap(); tokio::time::timeout( Duration::from_millis(250), rig.bus(|e| matches!(e, Event::Error { message, .. } if message == "now").then_some(())), ) .await .expect("the report went through at once"); } /// Whether a list of streams is on the engine's bus now. fn on_the_bus(rig: &mut Rig) -> bool { let mut found = false; while let Ok(event) = rig.bus.try_recv() { found |= matches!(event, Event::StreamsChanged { .. }); } found }