//! The engine on the protocol repository's fake host: `Engine::start_with_backends` //! with a `FakeConnector` (scheme `fake`) registered, so a session of the //! engine is a `voelin_proto::link::Session` that no TeamSpeak code made //! (`docs/session-seam.md` section 9.2). //! //! The host is a `FakeHost` filled through `FakeHost::put` (it stores what a //! client cannot set, such as the author of a message); `FakeHandle` plays the //! backend of one session: pushes, media, scripted answers, held requests and //! kills, and the log of every request the host received. Presence, chat, the //! dedup of a message that comes twice, history, transfers, offline messages, //! the features of a host, a reconnect and the media of a session are the //! engine's own behaviour; nothing here needs a TeamSpeak server or a //! TeamSpeak type, except `a_teamspeak_identity_that_cannot_be_read_is_refused_without_the_key`, //! which runs the engine's own TeamSpeak connector up to its refusal of an //! identity. use std::path::PathBuf; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use bytes::BytesMut; use tokio::io::AsyncWriteExt; use tokio::sync::broadcast; use voelin_core::history::MessageSource; use voelin_core::settings::Settings; use voelin_core::{ Backends, Command, DownloadTo, Engine, Event, History, HistoryMessage, HistorySource, IdentityBlob, JoinFailure, SessionId, SessionState, Source, TransferState, VoiceOptions, VoiceState, }; use voelin_model::{ChatMessage, ChatTarget, Presence}; use voelin_proto::link::{CloseReason, Connector, FlowId, MediaPacket, SessionError, voice_sub}; use voelin_proto::media::RtpHeader; use voelin_proto::media::payload::PT_OPUS; use voelin_proto::test_util::{ DEFAULT_FEATURES, FakeConnector, FakeHandle, FakeHost, Logged, Script, connect_params, eventually, }; use voelin_proto::v1::{self, entity::Kind, push, request::Op, response}; const SESSION: SessionId = 1; const SERVER: u64 = 1; const LOBBY: u64 = 10; const GAMES: u64 = 11; const SERVER_CHAT: u64 = 20; /// The host's name for the server: `Server.uid` (a Voelin host has no `ts:`). const SERVER_UID: &str = "fake-host"; /// The user and the participant the fake host gives the first session. const ME_USER: u64 = 1; const ME: u32 = 1; const ALICE_USER: u64 = 2; const ALICE: u32 = 50; const ALICE_SLOT: u32 = 90; const BOB_USER: u64 = 3; const BOB: u32 = 51; const BOB_SLOT: u32 = 91; /// How long a test waits for the engine or the host. const WAIT: Duration = Duration::from_secs(20); fn now_ms() -> i64 { SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64 } fn entity(kind: Kind) -> v1::Entity { v1::Entity { kind: Some(kind) } } fn user(id: u64, name: &str) -> Kind { Kind::User(v1::User { id, uid: vec![id as u8; 32].into(), uid_kind: v1::IdKind::Voelin as i32, name: name.into(), ..Default::default() }) } fn voice(participant: u32, user_id: u64, nick: &str, channel: u64, slot: u32) -> Kind { Kind::Voice(v1::VoiceState { server_id: SERVER, participant_id: participant, user_id, channel_id: channel, slot, nick: nick.into(), ..Default::default() }) } fn channel(id: u64, name: &str, position: i64, kind: v1::ChannelKind) -> Kind { Kind::Channel(v1::Channel { id, server_id: SERVER, kind: kind as i32, name: name.into(), position, ..Default::default() }) } /// A message of `author` (a user the host knows), as the host stores it. fn message(channel: u64, author: (u64, u32, &str), text: &str, ts_ms: i64) -> Kind { Kind::Message(v1::Message { channel_id: channel, author_id: author.0, author_participant: author.1, author_name: author.2.into(), text: text.into(), ts_ms, ..Default::default() }) } const ALICE_AUTHOR: (u64, u32, &str) = (ALICE_USER, ALICE, "alice"); const BOB_AUTHOR: (u64, u32, &str) = (BOB_USER, BOB, "bob"); /// A host with a server, a lobby and a games channel, a server chat, us (user /// 1, seated by `JoinVoice` where the server's default channel is: games), /// alice in games and bob in the lobby. fn connector() -> FakeConnector { let connector = FakeConnector::new(); let host = connector.host(); let mut welcome = host.welcome(); let info = welcome.host.as_mut().expect("the fake host names itself"); info.backend = Some(v1::BackendInfo { product: "Fake".into(), version: "1.2".into(), ..Default::default() }); host.set_welcome(welcome); let put = |kind: Kind| host.put(entity(kind)).expect("the fake host stores it"); put(Kind::Server(v1::Server { id: SERVER, name: "Fake Host".into(), uid: SERVER_UID.into(), default_channel_id: GAMES, ..Default::default() })); put(channel(LOBBY, "Lobby", 0, v1::ChannelKind::Voice)); put(channel(GAMES, "Games", 1024, v1::ChannelKind::Voice)); put(channel(SERVER_CHAT, "Server chat", 0, v1::ChannelKind::ServerChat)); put(user(ME_USER, "tester")); put(user(ALICE_USER, "alice")); put(user(BOB_USER, "bob")); put(voice(ALICE, ALICE_USER, "alice", GAMES, ALICE_SLOT)); put(voice(BOB, BOB_USER, "bob", LOBBY, BOB_SLOT)); connector } /// The engine, the connector it uses and the events it reports. struct Harness { engine: Engine, events: broadcast::Receiver, connector: FakeConnector, /// The latest state and presence the test has seen go by. state: SessionState, presence: Arc, } impl Harness { fn start() -> Self { Self::on(connector()) } fn on(connector: FakeConnector) -> Self { let mut backends = Backends::empty(); backends.register(Arc::new(connector.clone())); Self::with_backends(backends, connector) } /// The engine on `backends`; `connector` is the fake host the test may /// have registered in them (a test that registers none leaves it unused). fn with_backends(backends: Backends, connector: FakeConnector) -> Self { let engine = Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends); let events = engine.subscribe(); Self { engine, events, connector, state: SessionState::default(), presence: Arc::new(Presence::default()), } } /// The unique id the engine shows for the participant `client`. fn uid_of(&self, client: u32) -> String { let shown = self.presence.clients.get(&(client as u16)); shown.and_then(|c| c.uid.clone()).expect("the client is on the last presence") } fn host(&self) -> FakeHost { self.connector.host() } /// Ask for a voice connection to the fake host. fn ask_connect(&self) { let options = VoiceOptions::new("fake://host", "tester"); self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); } /// Connect, and wait until the engine shows us in a channel. Returns the /// host's handle on the session that was made. async fn connect(&mut self) -> FakeHandle { self.ask_connect(); self.state(|s| s.voice == VoiceState::Connected && s.own_channel.is_some()).await; self.connector.last_session().expect("the connector made a session") } /// The next event `f` picks, skipping the others. async fn next(&mut self, mut f: impl FnMut(Event) -> Option) -> T { tokio::time::timeout(WAIT, async { loop { let event = self.events.recv().await.expect("engine events"); match &event { Event::State { state, .. } => self.state = state.clone(), Event::Presence { presence, .. } => self.presence = presence.clone(), _ => {} } if let Some(t) = f(event) { return t; } } }) .await .expect("event in time") } /// The next state of the session that `ok` accepts. async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState { self.next(|e| match e { Event::State { state, .. } if ok(&state) => Some(state), _ => None, }) .await } /// The next live chat message. async fn chat(&mut self) -> ChatMessage { self.next(|e| match e { Event::Chat { message, .. } => Some(message), _ => None, }) .await } /// The next error the engine reports. async fn error(&mut self) -> String { self.next(|e| match e { Event::Error { message, .. } => Some(message), _ => None, }) .await } /// The messages stored for `target`, oldest first. async fn stored(&self, target: ChatTarget) -> Vec { self.engine .history() .page(SERVER_UID, &target, Default::default(), false) .await .expect("the history") } /// Wait until the engine has applied everything the host pushed before /// now: a notice is told after the pushes before it. async fn synced(&mut self, handle: &FakeHandle) { notice(handle, "sync marker"); assert_eq!(self.error().await, "sync marker"); } } /// The host tells the session an error notice. fn notice(handle: &FakeHandle, text: &str) { let notice = v1::Notice { level: v1::NoticeLevel::Error as i32, text: text.into(), ..Default::default() }; signal(handle, 0, 0, v1::signal::Body::Notice(notice)); } fn signal(handle: &FakeHandle, from_user: u64, from_participant: u32, body: v1::signal::Body) { let signal = v1::Signal { from_user, from_participant, body: Some(body), ..Default::default() }; handle .push(v1::Push { body: Some(push::Body::Signal(signal)) }) .expect("the push channel has room"); } fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope { v1::Scope { kind: kind as i32, id } } /// A voice packet of `slot` on sub-flow `sub`, as a host delivers it. fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket { let flow = FlowId::new(slot, sub); let mut out = BytesMut::new(); RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960) .write(flow, &mut out) .expect("a header"); out.extend_from_slice(payload); MediaPacket { flow, rtp: out.freeze() } } /// An Opus frame (20 ms, mono, fullband). const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe]; /// The requests the host received after the first `skip` of its log. fn requests_after(handle: &FakeHandle, skip: usize) -> Vec { handle.requests().into_iter().skip(skip).collect() } /// Wait until a request after the first `skip` matches `f`; return it. async fn request_after( handle: &FakeHandle, skip: usize, what: &str, f: impl Fn(&Op) -> bool, ) -> Logged { eventually(WAIT, what, || { requests_after(handle, skip).iter().any(|l| l.request.op.as_ref().is_some_and(&f)) }) .await; requests_after(handle, skip) .into_iter() .find(|l| l.request.op.as_ref().is_some_and(&f)) .expect("the request that was seen") } /// The one message a `Put` writes. fn written_message(op: &Op) -> Option<&v1::Message> { let Op::Put(put) = op else { return None }; match put.writes.first()?.entity.as_ref()?.kind.as_ref()? { Kind::Message(message) => Some(message), _ => None, } } fn list_of(kind: v1::EntityKind) -> impl Fn(&Op) -> bool { move |op| matches!(op, Op::List(list) if list.kind == kind as i32) } fn entities(items: Vec) -> response::Result { response::Result::Entities(v1::Entities { items: items.into_iter().map(entity).collect(), ..Default::default() }) } /// Connecting, the host's presence, talking, a poke, a notice and the end of /// the session, as the engine reports them. #[tokio::test(flavor = "multi_thread")] async fn presence_follows_the_host_until_it_ends() { let mut h = Harness::start(); h.ask_connect(); h.state(|s| s.voice == VoiceState::Connecting).await; // In the order the engine tells them: the server, its presence, our channel. let (name, info, caps) = h .next(|e| match e { Event::ServerInfo { name, backend, capabilities, .. } => { Some((name, backend, capabilities)) } _ => None, }) .await; assert_eq!((name.as_str(), info.label().as_str()), ("Fake Host", "Fake 1.2")); // `files` is offered, `mailbox` is not, and no session has streams yet. assert!(caps.file_transfer && !caps.offline_messages && !caps.streams, "{caps:?}"); // The server's details come with its first presence; its unique id is the // host's name for it. let details = h .next(|e| match e { Event::ServerDetails { details, .. } => Some(details), _ => None, }) .await; assert_eq!(details.uid.as_deref(), Some(SERVER_UID)); let shown = h .next(|e| match e { Event::Presence { presence, .. } if presence.clients.len() == 3 => Some(presence), _ => None, }) .await; assert_eq!(shown.server_name, "Fake Host"); let channels: Vec<_> = shown.channels.values().map(|c| (c.id, c.name.as_str(), c.order)).collect(); // The server chat is no channel of the tree; siblings form an order chain. assert_eq!(channels, [(LOBBY, "Lobby", 0), (GAMES, "Games", LOBBY)]); let clients: Vec<_> = shown.clients.values().map(|c| (c.id, c.nickname.as_str(), c.channel)).collect(); let (me, alice, bob) = (ME as u16, ALICE as u16, BOB as u16); assert_eq!(clients, [(me, "tester", GAMES), (alice, "alice", GAMES), (bob, "bob", LOBBY)]); // A Voelin user's unique id is shown as the base32 of its 32 bytes (here the // user's id, 32 times: `user`). assert_eq!(h.uid_of(ME), "aeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaq"); assert_eq!(h.uid_of(ALICE), "aibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaiba"); assert_eq!(h.uid_of(BOB), "ambqgaydambqgaydambqgaydambqgaydambqgaydambqgaydambq"); let state = h.state(|s| s.own_channel == Some(GAMES)).await; assert_eq!(state.voice, VoiceState::Connected); assert_eq!(state.own_client, Some(me)); assert_eq!(state.server_uid.as_deref(), Some(SERVER_UID)); assert_eq!(state.presence_source, Some(Source::Voice)); let handle = h.connector.last_session().expect("a session"); // Alice talks: the engine derives it from the media the session delivers. handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &OPUS)); h.next(|e| { matches!(e, Event::Talking { client, talking: true, .. } if client == alice).then_some(()) }) .await; // A poke names its sender from the host's participant and user. let poke = v1::signal::Body::Poke(v1::Poke { message: "wake up".into() }); signal(&handle, ALICE_USER, ALICE, poke); let poke = h .next(|e| match e { Event::Poke { from, from_uid, from_name, message, blocked, .. } => { Some((from, from_uid.is_some(), from_name, message, blocked)) } _ => None, }) .await; assert_eq!(poke, (alice, true, "alice".into(), "wake up".into(), false)); // An error notice of the host is an error of the session. notice(&handle, "move refused"); assert_eq!(h.error().await, "move refused"); // The host ends the session: the engine forgets what it showed. handle.kill(CloseReason::Network("server shut down".into())); let state = h.state(|s| s.voice == VoiceState::Disconnected).await; assert_eq!((state.own_channel, state.own_client), (None, None)); assert_eq!(h.error().await, "voice: server shut down"); let state = h.state(|s| s.presence_source.is_none()).await; assert_eq!(state.voice, VoiceState::Disconnected); let shown = h .next(|e| match e { Event::Presence { presence, .. } => Some(presence), _ => None, }) .await; assert!(shown.clients.is_empty() && shown.channels.is_empty()); } /// How a host ends a session is how the user is told: a close code with a /// reason, an idle timeout, and the user's own wish. #[tokio::test(flavor = "multi_thread")] async fn the_way_a_session_ends_is_the_text_the_user_reads() { let kicked = v1::CloseCode::Kicked as u64; let cases = [ (CloseReason::Remote { code: kicked, reason: "bye".into() }, Some("voice: bye")), (CloseReason::TimedOut, Some("voice: timed out")), (CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() }, None), ]; for (reason, text) in cases { let mut h = Harness::start(); let handle = h.connect().await; handle.kill(reason.clone()); h.state(|s| s.voice == VoiceState::Disconnected).await; match text { Some(text) => assert_eq!(h.error().await, text, "{reason:?}"), None => { // Nothing to say: the next thing the engine tells is the empty presence. h.next(|e| match e { Event::Error { message, .. } => panic!("an error for {reason:?}: {message}"), Event::Presence { presence, .. } if presence.clients.is_empty() => Some(()), _ => None, }) .await; } } } // The user's own wish closes the session towards the host: `Local(Normal)`. let mut h = Harness::start(); let handle = h.connect().await; h.engine.send(Command::DisconnectVoice { session: SESSION }); h.state(|s| s.voice == VoiceState::Disconnected).await; eventually(WAIT, "the host to see the close", || handle.close_reason().is_some()).await; assert_eq!(handle.close_reason(), Some(CloseReason::Local(v1::CloseCode::Normal))); } /// What the user asks for reaches the host, as the v1 requests of the /// translation table. #[tokio::test(flavor = "multi_thread")] async fn commands_reach_the_host_as_requests() { let mut h = Harness::start(); let handle = h.connect().await; let before = handle.requests().len(); h.engine.send(Command::SendChat { session: SESSION, target: ChatTarget::Channel(GAMES), text: "hello".into(), }); let put = request_after(&handle, before, "the chat message", |op| written_message(op).is_some()) .await; let sent = put.request.op.as_ref().and_then(written_message).expect("a message"); assert_eq!((sent.channel_id, sent.text.as_str()), (GAMES, "hello")); // The host does not offer `chat.bbcode`. assert_eq!(sent.format, v1::TextFormat::Markdown as i32); h.engine.send(Command::MoveToChannel { session: SESSION, channel: LOBBY, password: Some("pw".into()), }); let join = request_after(&handle, before, "the move", |op| matches!(op, Op::JoinVoice(_))).await; let Some(Op::JoinVoice(join)) = join.request.op else { unreachable!() }; assert_eq!((join.server_id, join.channel_id, join.password.as_str()), (SERVER, LOBBY, "pw")); // The host's voice state is where we are. h.state(|s| s.own_channel == Some(LOBBY)).await; // Our own flags are fire and forget: a notification (id 0) that patches // one leaf of the voice state. h.engine.send(Command::SetInputMuted { session: SESSION, muted: true }); h.engine.send(Command::SetOutputMuted { session: SESSION, muted: true }); assert!(h.state(|s| s.input_muted && s.output_muted).await.input_muted); for path in ["self_mute", "self_deaf"] { // The leaf path of the flag, as the protocol writes it. let leaf = v1::Write::patch(entity(voice(ME, ME_USER, "", 0, 0)), [path]).unwrap().paths; let flag = request_after( &handle, before, path, |op| matches!(op, Op::Put(put) if put.writes.iter().any(|w| w.paths == leaf)), ) .await; assert_eq!(flag.request.id, 0, "{path} is a notification"); let Some(Op::Put(put)) = flag.request.op else { unreachable!() }; let Some(Kind::Voice(state)) = put.writes[0].entity.as_ref().and_then(|e| e.kind.clone()) else { panic!("a voice state") }; assert_eq!((state.server_id, state.participant_id), (SERVER, ME)); assert_eq!(state.self_mute, path == "self_mute"); assert_eq!(state.self_deaf, path == "self_deaf"); } h.engine.send(Command::Poke { session: SESSION, client: ALICE as u16, message: "hi".into() }); let poke = request_after(&handle, before, "the poke", |op| matches!(op, Op::Signal(_))).await; let Some(Op::Signal(signal)) = poke.request.op else { unreachable!() }; let to = signal.to.expect("a target"); assert_eq!((to.server_id, to.participant_id), (SERVER, ALICE)); assert!(matches!(signal.body, Some(v1::signal::Body::Poke(p)) if p.message == "hi")); // The fake refuses the path of a file list; the test scripts the answer. let file = |name: &str, size: u64, is_dir: bool| { Kind::File(v1::FileEntry { channel_id: GAMES, path: "/docs".into(), name: name.into(), size, modified_ms: 3_000, is_dir, ..Default::default() }) }; let listing = entities(vec![file("a.txt", 5, false), file("sub", 0, true)]); handle.script(Script::answer("list", listing).once()); h.engine.send(Command::ListFiles { session: SESSION, request: 5, channel: GAMES, password: None, path: "/docs/".into(), }); let (request, channel, listed) = h .next(|e| match e { Event::FileList { request, channel, result, .. } => Some((request, channel, result)), _ => None, }) .await; assert_eq!((request, channel), (5, GAMES)); let listed: Vec<_> = listed .expect("a listing") .into_iter() .map(|f| (f.name, f.size, f.modified_s, f.is_dir)) .collect(); assert_eq!(listed, [("a.txt".to_owned(), 5, 3, false), ("sub".to_owned(), 0, 3, true)]); let list = request_after(&handle, before, "the file list", list_of(v1::EntityKind::File)).await; let Some(Op::List(list)) = list.request.op else { unreachable!() }; assert_eq!((list.parent, list.path.as_str()), (GAMES, "/docs/")); } /// A host that offers no streams is not asked for one: the engine refuses /// `StartStream` itself, with an error, before any request leaves. (The other /// local refusal of a missing feature, the file list, is in /// `a_host_update_changes_what_the_engine_asks_for`.) #[tokio::test(flavor = "multi_thread")] async fn a_host_without_streams_is_not_asked_for_one() { let mut h = Harness::start(); let handle = h.connect().await; let count = handle.requests().len(); let setup = voelin_core::stream::StreamSetup { name: "screen".into(), ..Default::default() }; h.engine.send(Command::StartStream { session: SESSION, setup, auto_accept: true }); let error = h.error().await; assert!(error.contains("streams"), "{error}"); assert_eq!(handle.requests().len(), count, "nothing reached the host"); } /// A request the host refuses is told in the host's words, with the label the /// user knows it by; a refused move says why. #[tokio::test(flavor = "multi_thread")] async fn what_the_host_refuses_is_told_in_its_words() { let mut h = Harness::start(); let handle = h.connect().await; handle.script(Script::error("put", v1::ErrorCode::Forbidden, "you cannot talk here").once()); h.engine.send(Command::SendChat { session: SESSION, target: ChatTarget::Channel(GAMES), text: "hi".into(), }); assert_eq!(h.error().await, "message: you cannot talk here"); handle.script(Script::error("signal", v1::ErrorCode::NotFound, "no such client").once()); h.engine.send(Command::Poke { session: SESSION, client: ALICE as u16, message: "hi".into() }); assert_eq!(h.error().await, "poke: no such client"); // A private message to somebody who is not on the server is told without a request. let count = handle.requests().len(); h.engine.send(Command::SendChat { session: SESSION, target: ChatTarget::Private("nobody=".into()), text: "psst".into(), }); assert!(h.error().await.starts_with("private message: the client is not on the server")); assert_eq!(handle.requests().len(), count); let refusals = [ (v1::ErrorCode::Password, "wrong password", JoinFailure::Password), (v1::ErrorCode::Full, "the channel is full", JoinFailure::Full), (v1::ErrorCode::Forbidden, "not allowed", JoinFailure::Other("not allowed".into())), ]; for (code, text, expected) in refusals { handle.script(Script::error("join_voice", code, text).once()); h.engine.send(Command::MoveToChannel { session: SESSION, channel: LOBBY, password: None }); let (channel, reason) = h .next(|e| match e { Event::JoinFailed { channel, reason, .. } => Some((channel, reason)), _ => None, }) .await; assert_eq!((channel, reason), (LOBBY, expected)); } // A refused move moved nothing: the host's voice state is where it was, and // so is the engine's. h.synced(&handle).await; assert_eq!(h.state.own_channel, Some(GAMES)); let seat = h.host().entities(&scope(v1::ScopeKind::Live, SERVER)).into_iter().find_map(|e| { match e.kind? { Kind::Voice(v) if v.participant_id == ME => Some(v.channel_id), _ => None, } }); assert_eq!(seat, Some(GAMES)); } /// A message we send is stored at once; the host's copy of it merges into /// the same row, and is shown (once). #[tokio::test(flavor = "multi_thread")] async fn a_sent_message_and_its_echo_are_one_message() { let mut h = Harness::start(); let handle = h.connect().await; h.engine.send(Command::SendChat { session: SESSION, target: ChatTarget::Channel(GAMES), text: "hello".into(), }); // The host stores it and pushes its `Change` to everyone who watches the // channel, us too. let shown = h.chat().await; assert_eq!((shown.author_name.as_str(), shown.text.as_str()), ("tester", "hello")); let stored = handle .requests() .iter() .filter_map(|l| l.request.op.as_ref().and_then(written_message).map(|m| m.text.clone())) .collect::>(); assert_eq!(stored, ["hello"]); // A marker: what comes next is the next message, not a second "hello". h.host().put(entity(message(GAMES, ALICE_AUTHOR, "marker", now_ms()))).unwrap(); assert_eq!(h.chat().await.text, "marker"); let rows = h.stored(ChatTarget::Channel(GAMES)).await; let texts: Vec<_> = rows.iter().map(|m| m.message.text.as_str()).collect(); assert_eq!(texts, ["hello", "marker"]); assert_eq!(rows[0].source, MessageSource::Local); } /// A message that comes twice (the host's and a relay's copy, with the /// relay's `[nick] ` prefix) is shown once. #[tokio::test(flavor = "multi_thread")] async fn a_message_that_comes_twice_is_shown_once() { let mut h = Harness::start(); let _handle = h.connect().await; h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) }); let t = now_ms(); let host = h.host(); let relayed = Kind::Message(v1::Message { flags: v1::MessageFlag::Relayed as u32, ..match message(GAMES, ALICE_AUTHOR, "[alice] gg everyone", t + 300) { Kind::Message(m) => m, _ => unreachable!(), } }); for kind in [ message(GAMES, ALICE_AUTHOR, "gg everyone", t), relayed, // The same words much later are another message. message(GAMES, ALICE_AUTHOR, "gg everyone", t + 10_000), message(GAMES, BOB_AUTHOR, "gg everyone", t + 10_100), ] { host.put(entity(kind)).unwrap(); } let mut shown = Vec::new(); while shown.len() < 3 { shown.push(h.chat().await); } let who: Vec<_> = shown.iter().map(|m| (m.author_name.as_str(), m.ts_ms)).collect(); assert_eq!(who, [("alice", t), ("alice", t + 10_000), ("bob", t + 10_100)]); assert!(!shown[0].via_relay); } /// Stored messages come back when a chat opens, also after the session is /// gone; the host's id of the server keys them, and a private message is /// stored under its peer. #[tokio::test(flavor = "multi_thread")] async fn history_is_kept_across_the_session() { let mut h = Harness::start(); let _handle = h.connect().await; // The direct-message channel is in HOME: the engine subscribes it when it // appears, and the peer is the other recipient. let alice_uid = h.uid_of(ALICE); let host = h.host(); let dm = host .put(entity(Kind::Channel(v1::Channel { server_id: 0, kind: v1::ChannelKind::Dm as i32, recipients: vec![ME_USER, ALICE_USER], ..Default::default() }))) .unwrap(); let Some(Kind::Channel(dm)) = dm.kind else { panic!("a channel") }; let t = now_ms(); for kind in [ message(GAMES, ALICE_AUTHOR, "first", t), message(GAMES, BOB_AUTHOR, "second", t + 1_000), // A private message to us is stored under its peer, not the channel. message(dm.id, ALICE_AUTHOR, "psst", t + 2_000), ] { host.put(entity(kind)).unwrap(); } let mut texts = Vec::new(); while texts.len() < 3 { texts.push(h.chat().await.text); } texts.sort(); assert_eq!(texts, ["first", "psst", "second"]); h.engine.send(Command::DisconnectVoice { session: SESSION }); h.state(|s| s.voice == VoiceState::Disconnected).await; h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) }); // The stored page (the live batches of the messages came before). let messages = h .next(|e| match e { Event::ChatHistory { messages, source: HistorySource::Local, .. } => Some(messages), _ => None, }) .await; let texts: Vec<_> = messages.iter().map(|m| m.message.text.as_str()).collect(); assert_eq!(texts, ["first", "second"]); let private = h.stored(ChatTarget::Private(alice_uid)).await; assert_eq!(private.len(), 1); assert_eq!(private[0].message.text, "psst"); } /// Moving away from a channel and back gives the channel's chat again: the /// scope is subscribed in full (there is no cursor to keep, `docs/session-seam.md` /// section 13), and a message is shown once however often its scope is synced. #[tokio::test(flavor = "multi_thread")] async fn the_chat_of_a_channel_is_resubscribed_when_we_move_back() { let mut h = Harness::start(); let handle = h.connect().await; let host = h.host(); let t = now_ms(); let subscriptions = |handle: &FakeHandle| { handle .subscriptions() .into_iter() .filter(|s| s.kind == v1::ScopeKind::Chat as i32) .collect::>() }; // The server chat and our channel's chat. eventually(WAIT, "the chat subscriptions", || subscriptions(&handle).len() == 2).await; let chats: Vec = subscriptions(&handle).iter().map(|s| s.id).collect(); assert_eq!(chats, [GAMES, SERVER_CHAT]); // Two messages more than `Dedup`'s 4 s apart, so that the copy of "before" // that the second sync brings is not one `Dedup` would still recognise: it // is the `seen` set of `SessionLink` that has to drop it. host.put(entity(message(GAMES, ALICE_AUTHOR, "before", t))).unwrap(); assert_eq!(h.chat().await.text, "before"); host.put(entity(message(GAMES, ALICE_AUTHOR, "before too", t + 10_000))).unwrap(); assert_eq!(h.chat().await.text, "before too"); h.engine.send(Command::MoveToChannel { session: SESSION, channel: LOBBY, password: None }); h.state(|s| s.own_channel == Some(LOBBY)).await; eventually(WAIT, "the lobby's chat instead of the games'", || { let chats: Vec = subscriptions(&handle).iter().map(|s| s.id).collect(); chats == [LOBBY, SERVER_CHAT] }) .await; // Said while we were away: nobody of ours listens to the games chat. host.put(entity(message(GAMES, BOB_AUTHOR, "while away", t + 30_000))).unwrap(); h.engine.send(Command::MoveToChannel { session: SESSION, channel: GAMES, password: None }); h.state(|s| s.own_channel == Some(GAMES)).await; assert_eq!(h.chat().await.text, "while away", "the missed message, and not 'before' again"); // Both subscriptions of the games chat were full syncs: no cursor. let subscribes: Vec<_> = handle .requests() .into_iter() .filter_map(|l| match l.request.op { Some(Op::Subscribe(s)) if s.scope == Some(scope(v1::ScopeKind::Chat, GAMES)) => Some(s), _ => None, }) .collect(); assert_eq!(subscribes.len(), 2, "{subscribes:?}"); assert!(subscribes.iter().all(|s| s.since.is_none()), "{subscribes:?}"); } /// A scope the host closes: a closed chat is nothing to tell; a closed /// server or live scope is an error and an empty presence. #[tokio::test(flavor = "multi_thread")] async fn a_scope_the_host_closes_is_told_only_where_it_matters() { let mut h = Harness::start(); let handle = h.connect().await; let closed = |scope| v1::ScopeClosed { scope: Some(scope), code: v1::ErrorCode::Forbidden as i32, message: "you lost the right to see it".into(), }; let push = |closed| v1::Push { body: Some(push::Body::ScopeClosed(closed)) }; // A chat scope: unsubscribed, nothing reported. What comes next is the // notice, not an error of the scope. handle.push(push(closed(scope(v1::ScopeKind::Chat, GAMES)))).unwrap(); notice(&handle, "after the chat scope"); assert_eq!(h.error().await, "after the chat scope"); // The live scope: the participants are gone from view. handle.push(push(closed(scope(v1::ScopeKind::Live, SERVER)))).unwrap(); assert_eq!(h.error().await, "you lost the right to see it"); let shown = h .next(|e| match e { Event::Presence { presence, .. } if presence.clients.is_empty() => Some(presence), _ => None, }) .await; assert!(shown.clients.is_empty()); } /// What a host offers can change under a session (`HostUpdate`): the engine /// refuses a request its host no longer offers, without asking it, and takes /// it up again when the host offers it again. #[tokio::test(flavor = "multi_thread")] async fn a_host_update_changes_what_the_engine_asks_for() { let mut h = Harness::start(); let handle = h.connect().await; let update = |features: Vec| v1::Push { body: Some(push::Body::HostUpdate(v1::HostUpdate { features, limits: None })), }; let without_files: Vec = DEFAULT_FEATURES .iter() .filter(|f| !f.starts_with("files")) .map(|f| (*f).to_owned()) .collect(); handle.push(update(without_files)).unwrap(); h.synced(&handle).await; let count = handle.requests().len(); let list = |request| Command::ListFiles { session: SESSION, request, channel: GAMES, password: None, path: "/".into(), }; h.engine.send(list(1)); let result = h .next(|e| match e { Event::FileList { request: 1, result, .. } => Some(result), _ => None, }) .await; assert_eq!(result.unwrap_err(), "not offered by this server: files"); assert_eq!(handle.requests().len(), count, "refused before it reached the host"); let mut all: Vec = DEFAULT_FEATURES.iter().map(|f| (*f).to_owned()).collect(); all.push("mailbox".into()); handle.push(update(all)).unwrap(); h.synced(&handle).await; handle.script(Script::answer("list", entities(vec![])).once()); h.engine.send(list(2)); let result = h .next(|e| match e { Event::FileList { request: 2, result, .. } => Some(result), _ => None, }) .await; assert_eq!(result.unwrap(), []); // And the offline messages the host now has. handle.script(Script::answer("list", entities(vec![])).once()); h.engine.send(Command::ListOfflineMessages { session: SESSION, request: 3 }); let result = h .next(|e| match e { Event::OfflineMessages { request: 3, result, .. } => Some(result), _ => None, }) .await; assert!(result.unwrap().is_empty()); } fn mail(id: u64, from: &str, subject: &str, text: &str, ts_ms: i64) -> Kind { Kind::Mail(v1::Mail { id, from_uid: from.into(), subject: subject.into(), text: text.into(), ts_ms, ..Default::default() }) } /// Offline messages are `Mail`; the fake host stores none, so the answers are /// scripted, and the requests are what the host received. #[tokio::test(flavor = "multi_thread")] async fn offline_messages_are_mail() { let connector = connector(); let mut features: Vec = DEFAULT_FEATURES.iter().map(|f| (*f).to_owned()).collect(); features.push("mailbox".into()); connector.host().set_features(features); let mut h = Harness::on(connector); let handle = h.connect().await; let before = handle.requests().len(); // Without a mailbox the engine would have refused; with one it asks. handle.script(Script::new("list", |op| { let Op::List(list) = op else { return Err(SessionError::Protocol("not a list".into())) }; Ok(match list.ids.as_slice() { [] => entities(vec![mail(7, "carol=", "hello", "", 1_234_000)]), _ => entities(vec![mail(7, "carol=", "hello", "the whole text", 1_234_000)]), }) })); h.engine.send(Command::ListOfflineMessages { session: SESSION, request: 1 }); let listed = h .next(|e| match e { Event::OfflineMessages { request: 1, result, .. } => Some(result), _ => None, }) .await .expect("the list"); assert_eq!(listed.len(), 1); let info = &listed[0]; assert_eq!( (info.id, info.from_uid.as_str(), info.subject.as_str(), info.ts_s, info.read), (7, "carol=", "hello", 1_234, false) ); h.engine.send(Command::GetOfflineMessage { session: SESSION, request: 2, id: 7 }); let got = h .next(|e| match e { Event::OfflineMessage { request: 2, result, .. } => Some(result), _ => None, }) .await .expect("the message"); assert_eq!((got.id, got.text.as_str(), got.ts_s), (7, "the whole text", 1_234)); let get = request_after(&handle, before, "the get", |op| matches!(op, Op::List(l) if l.ids == [7])) .await; let Some(Op::List(get)) = get.request.op else { unreachable!() }; assert_eq!(get.kind, v1::EntityKind::Mail as i32); // Write, flag and delete: the requests the host received. handle.script(Script::answer("put", entities(vec![mail(0, "", "", "", 0)])).times(2)); handle.script(Script::answer("delete", response::Result::Ack(v1::Ack { rev: 0 })).once()); h.engine.send(Command::SendOfflineMessage { session: SESSION, request: 3, to_uid: "dave=".into(), subject: "re".into(), text: "see you".into(), }); h.engine.send(Command::SetOfflineMessageRead { session: SESSION, request: 4, id: 7, read: true, }); h.engine.send(Command::DeleteOfflineMessage { session: SESSION, request: 5, id: 7 }); let mut done = Vec::new(); while done.len() < 3 { let (request, result) = h .next(|e| match e { Event::RequestDone { request, result, .. } => Some((request, result)), _ => None, }) .await; assert_eq!(result, Ok(()), "request {request}"); done.push(request); } done.sort(); assert_eq!(done, [3, 4, 5]); let mails: Vec<_> = requests_after(&handle, before) .into_iter() .filter_map(|l| match l.request.op { Some(Op::Put(put)) => put.writes.into_iter().next(), _ => None, }) .filter_map(|w| match w.entity?.kind? { Kind::Mail(mail) => { Some((mail.id, mail.to_uid, mail.subject, mail.text, mail.read, w.paths)) } _ => None, }) .collect(); // Only the `read` leaf of the flagged mail is written. let read_leaf = v1::Write::patch(entity(mail(7, "", "", "", 0)), ["read"]).unwrap().paths; assert_eq!( mails, [ (0, "dave=".into(), "re".into(), "see you".into(), false, vec![]), (7, String::new(), String::new(), String::new(), true, read_leaf), ] ); let delete = request_after(&handle, before, "the delete", |op| matches!(op, Op::Delete(_))).await; let Some(Op::Delete(delete)) = delete.request.op else { unreachable!() }; assert!(matches!(delete.keys[0].kind, Some(Kind::Mail(ref m)) if m.id == 7)); // A host without a mailbox is not asked. let mut plain = Harness::start(); let plain_handle = plain.connect().await; let count = plain_handle.requests().len(); plain.engine.send(Command::ListOfflineMessages { session: SESSION, request: 9 }); let result = plain .next(|e| match e { Event::OfflineMessages { request: 9, result, .. } => Some(result), _ => None, }) .await; assert_eq!(result.unwrap_err(), "not offered by this server: mailbox"); assert_eq!(plain_handle.requests().len(), count); } fn temp_dir(tag: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("voelin-session-fake-{}-{tag}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); dir } fn pattern(len: usize) -> Vec { (0..len).map(|i| (i * 7 % 251) as u8).collect() } async fn transfer_done(h: &mut Harness, id: u64) -> TransferState { h.next(|e| match e { Event::Transfer { transfer, state, .. } if transfer == id && state.is_final() => { Some(state) } _ => None, }) .await } /// A file goes up through `write_file` and comes back through `read_file`, /// byte for byte; a resumed upload goes on where the host's copy ends. #[tokio::test(flavor = "multi_thread")] async fn files_go_through_read_file_and_write_file() { let mut h = Harness::start(); let handle = h.connect().await; let dir = temp_dir("transfers"); let data = pattern(3_000); let local = dir.join("up.bin"); std::fs::write(&local, &data).unwrap(); let upload = |transfer, path: &str, resume| Command::UploadFile { session: SESSION, transfer, channel: GAMES, password: None, path: path.into(), from: local.clone(), overwrite: false, resume, }; h.engine.send(upload(1, "/docs/up.bin", false)); assert!(matches!(transfer_done(&mut h, 1).await, TransferState::Done { size: 3_000, .. })); let write = request_after(&handle, 0, "the file write", |op| matches!(op, Op::FileWrite(_))).await; let Some(Op::FileWrite(write)) = write.request.op else { unreachable!() }; assert_eq!((write.size, write.offset, write.overwrite), (3_000, 0, false)); let Some(v1::file_write::Target::Path(path)) = write.target else { panic!("a path") }; assert_eq!((path.channel_id, path.path.as_str()), (GAMES, "/docs/up.bin")); h.engine.send(Command::DownloadFile { session: SESSION, transfer: 2, channel: GAMES, password: None, path: "/docs/up.bin".into(), to: DownloadTo::Memory, }); let TransferState::Done { size, data: Some(bytes), .. } = transfer_done(&mut h, 2).await else { panic!("a finished download") }; assert_eq!((size, &*bytes.0), (3_000, data.as_slice())); let read = request_after(&handle, 0, "the file read", |op| matches!(op, Op::FileRead(_))).await; let Some(Op::FileRead(read)) = read.request.op else { unreachable!() }; assert_eq!(read.offset, 0); // A file that is not there fails with the host's words. h.engine.send(Command::DownloadFile { session: SESSION, transfer: 3, channel: GAMES, password: None, path: "/docs/missing.bin".into(), to: DownloadTo::Memory, }); assert_eq!(transfer_done(&mut h, 3).await, TransferState::Failed("no such file".into())); // An upload that was interrupted left 1,000 bytes with the host (written // by another session of it, and dropped before it was shut down). let other = h.connector.connect(connect_params("fake://other").0).await.expect("a session"); let mut partial = other .session .write_file(v1::FileWrite { target: Some(v1::file_write::Target::Path(v1::FilePath { channel_id: GAMES, path: "/docs/big.bin".into(), password: String::new(), })), size: 3_000, offset: 0, overwrite: false, sha256: Default::default(), }) .await .expect("an upload"); partial.body.write_all(&data[..1_000]).await.unwrap(); drop(partial); // The host's listing of the directory shows the partial size, as a host that // keeps partial files does (the fake refuses the path of a `List`). let size_of_copy = Kind::File(v1::FileEntry { channel_id: GAMES, path: "/docs".into(), name: "big.bin".into(), size: 1_000, ..Default::default() }); handle.script(Script::answer("list", entities(vec![size_of_copy])).once()); h.engine.send(upload(4, "/docs/big.bin", true)); assert!(matches!(transfer_done(&mut h, 4).await, TransferState::Done { size: 3_000, .. })); let writes: Vec<_> = handle .requests() .into_iter() .filter_map(|l| match l.request.op { Some(Op::FileWrite(w)) => Some((w.offset, w.size)), _ => None, }) .collect(); assert_eq!(writes, [(0, 3_000), (1_000, 3_000)]); h.engine.send(Command::DownloadFile { session: SESSION, transfer: 5, channel: GAMES, password: None, path: "/docs/big.bin".into(), to: DownloadTo::Memory, }); let TransferState::Done { data: Some(bytes), .. } = transfer_done(&mut h, 5).await else { panic!("a finished download") }; assert_eq!(&*bytes.0, data.as_slice(), "the resumed file is whole"); let _ = std::fs::remove_dir_all(dir); } /// File operations of the voice session are `Put` and `Delete` of `FileEntry` /// keys; the answers (scripted: the fake stores no `FileEntry`) end the /// requests the user made. #[tokio::test(flavor = "multi_thread")] async fn file_operations_are_puts_and_deletes_of_file_entries() { let mut h = Harness::start(); let handle = h.connect().await; let before = handle.requests().len(); handle.script(Script::answer("put", entities(vec![])).times(2)); handle.script(Script::answer("delete", response::Result::Ack(v1::Ack { rev: 0 })).once()); h.engine.send(Command::CreateDirectory { session: SESSION, request: 1, channel: GAMES, password: Some("pw".into()), path: "/docs/new".into(), }); h.engine.send(Command::RenameFile { session: SESSION, request: 2, channel: GAMES, password: None, from: "/docs/a.txt".into(), to: "/other/b.txt".into(), to_channel: Some((LOBBY, Some("lobby pw".into()))), }); h.engine.send(Command::DeleteFiles { session: SESSION, request: 3, channel: GAMES, password: None, paths: vec!["/docs/a.txt".into()], }); let mut done = Vec::new(); while done.len() < 3 { let (request, result) = h .next(|e| match e { Event::RequestDone { request, result, .. } => Some((request, result)), _ => None, }) .await; assert_eq!(result, Ok(()), "request {request}"); done.push(request); } done.sort(); assert_eq!(done, [1, 2, 3]); let files: Vec = requests_after(&handle, before) .into_iter() .flat_map(|l| match l.request.op { Some(Op::Put(put)) => put.writes.into_iter().filter_map(|w| w.entity).collect(), Some(Op::Delete(delete)) => delete.keys, _ => vec![], }) .filter_map(|e| match e.kind? { Kind::File(file) => Some(file), _ => None, }) .collect(); let key = |f: &v1::FileEntry| { (f.channel_id, f.path.clone(), f.name.clone(), f.is_dir, f.password.clone()) }; let made = files.iter().find(|f| f.is_dir).expect("the new directory"); assert_eq!(key(made), (GAMES, "/docs".into(), "new".into(), true, "pw".into())); let moved = files.iter().find(|f| f.from_channel_id != 0).expect("the rename"); assert_eq!(key(moved), (LOBBY, "/other".into(), "b.txt".into(), false, "lobby pw".into())); assert_eq!((moved.from_channel_id, moved.from_path.as_str()), (GAMES, "/docs/a.txt")); let deleted = files.iter().find(|f| !f.is_dir && f.from_channel_id == 0 && f.name == "a.txt"); assert_eq!( deleted.map(key), Some((GAMES, "/docs".into(), "a.txt".into(), false, String::new())) ); } /// The media a session delivers to the engine's sink: who talks, and when /// they stop; what comes from a slot nobody has is dropped; a whisper is a /// talker too. #[tokio::test(flavor = "multi_thread")] async fn media_routes_to_the_talker_of_its_slot() { let mut h = Harness::start(); let handle = h.connect().await; let (alice, bob) = (ALICE as u16, BOB as u16); // Nobody has this slot: nothing is shown. Bob's whisper is shown (sub-flow 1). handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &OPUS)); handle.inject_media(voice_packet(BOB_SLOT, 1, 1, &OPUS)); let first = h .next(|e| match e { Event::Talking { client, talking, .. } => Some((client, talking)), _ => None, }) .await; assert_eq!(first, (bob, true), "the unknown slot was not shown"); // Alice talks for a moment and stops: 400 ms of silence end the talking. let started = tokio::time::Instant::now(); handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &OPUS)); h.next(|e| { matches!(e, Event::Talking { client, talking: true, .. } if client == alice).then_some(()) }) .await; h.next(|e| { matches!(e, Event::Talking { client, talking: false, .. } if client == alice).then_some(()) }) .await; assert!(started.elapsed() >= Duration::from_millis(400), "{:?}", started.elapsed()); // Feedback and probe flows are no voice. handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) }); handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 2, &OPUS)); h.next(|e| { matches!(e, Event::Talking { client, talking: true, .. } if client == alice).then_some(()) }) .await; } /// A second `ConnectVoice` replaces the session: the host sees the first one /// closed, the second finds the state the first left (a message said while we /// were away comes), and the participant of the second session is another one. /// /// What this proves about the replay is narrow: the one message seen before /// the disconnect is not shown again because `Dedup` still holds it (it is the /// newest message the engine saw, and `Dedup` keeps the messages up to 4 s /// older than the last one it was asked about), so the copy the host's sync /// brings is dropped. A replayed message older than that is shown again, and /// every replayed message is stored again: the two ignored tests below pin /// both (F3, `docs/session-seam.md` 16.5). #[tokio::test(flavor = "multi_thread")] async fn a_reconnect_finds_the_state_the_first_session_left() { let mut h = Harness::start(); let first = h.connect().await; let host = h.host(); let t = now_ms(); host.put(entity(message(GAMES, ALICE_AUTHOR, "before", t))).unwrap(); assert_eq!(h.chat().await.text, "before"); // Away, and a message is said that nobody of ours hears live. h.engine.send(Command::DisconnectVoice { session: SESSION }); h.state(|s| s.voice == VoiceState::Disconnected).await; eventually(WAIT, "the host to see the first session closed", || first.close_reason().is_some()) .await; assert_eq!(first.close_reason(), Some(CloseReason::Local(v1::CloseCode::Normal))); host.put(entity(message(GAMES, BOB_AUTHOR, "while away", t + 30_000))).unwrap(); let second = h.connect().await; assert_eq!(h.connector.connects().len(), 2); assert_eq!(h.connector.sessions().len(), 2); // The window of the CHAT scope comes again, "before" with it. It is not // shown only because `Dedup` still holds it, the newest message seen; a // message older than `Dedup`'s 4 s would be shown (the ignored tests below). assert_eq!(h.chat().await.text, "while away"); assert_eq!(h.state.own_client, Some(second.participant_id() as u16)); assert_ne!(second.participant_id(), first.participant_id()); // The first session's seat is gone from the host, ours is the only one. let seats: Vec = host .entities(&scope(v1::ScopeKind::Live, SERVER)) .into_iter() .filter_map(|e| match e.kind? { Kind::Voice(v) => Some(v.participant_id), _ => None, }) .collect(); assert!(!seats.contains(&first.participant_id()), "{seats:?}"); assert!(seats.contains(&second.participant_id()), "{seats:?}"); // (That the history has each message once, and that a replayed message // older than `Dedup`'s 4 s is not shown again, are the business of the // ignored tests below.) } /// Asking to connect while connected replaces the session at once: the host /// sees the old session closed by us, and the engine follows the new one. #[tokio::test(flavor = "multi_thread")] async fn connecting_while_connected_replaces_the_session() { let mut h = Harness::start(); let first = h.connect().await; h.ask_connect(); let connector = h.connector.clone(); eventually(WAIT, "the second session", || connector.sessions().len() == 2).await; let second = connector.last_session().expect("a second session"); assert_ne!(second.participant_id(), first.participant_id()); h.state(|s| s.own_client == Some(second.participant_id() as u16)).await; eventually(WAIT, "the first session to be closed", || first.close_reason().is_some()).await; assert_eq!(first.close_reason(), Some(CloseReason::Local(v1::CloseCode::Normal))); assert!(second.close_reason().is_none(), "the new session is open"); } /// What a host that sends the window of a CHAT scope again makes of a /// reconnect. Two messages more than `Dedup`'s 4 s apart are said and seen, /// the session ends, a third is said while we are away, and a second session /// connects. Returns the harness and the texts the engine showed as live chat /// messages from the second connect until the third had come, and what was /// still to come when a notice that the host told after them arrived. /// /// The window is replayed oldest first (by id), so "while away" is its last /// message, and whatever precedes it in the result is a replayed message that /// the engine showed again. async fn a_reconnect_to_a_host_that_replays() -> (Harness, Vec) { let mut h = Harness::start(); let first = h.connect().await; let host = h.host(); let t = now_ms(); host.put(entity(message(GAMES, ALICE_AUTHOR, "first", t))).unwrap(); host.put(entity(message(GAMES, ALICE_AUTHOR, "second", t + 10_000))).unwrap(); assert_eq!(h.chat().await.text, "first"); assert_eq!(h.chat().await.text, "second"); h.engine.send(Command::DisconnectVoice { session: SESSION }); h.state(|s| s.voice == VoiceState::Disconnected).await; eventually(WAIT, "the host to see the first session closed", || first.close_reason().is_some()) .await; host.put(entity(message(GAMES, BOB_AUTHOR, "while away", t + 30_000))).unwrap(); let second = h.connect().await; let mut shown = Vec::new(); while shown.last().map(String::as_str) != Some("while away") { shown.push(h.chat().await.text); } // Everything the host's sync had to say is behind us; a notice it tells now // comes after whatever the engine still reports. notice(&second, "sync marker"); loop { let more = h .next(|e| match e { Event::Chat { message, .. } => Some(Some(message.text)), Event::Error { message, .. } if message == "sync marker" => Some(None), _ => None, }) .await; match more { Some(text) => shown.push(text), None => return (h, shown), } } } /// The messages a host sends again when a session reconnects are not shown /// again: the engine shows "while away" and nothing else. /// /// Known limit, found by this test and left for the resume of /// `docs/session-seam.md` (H8, 16.5): the engine is told every message of a /// replayed window again (`seen` in `SessionLink` is per connection), and /// `Dedup` in `session.rs` drops one only while an equal message (target, /// author, text, a timestamp within 2 s) is still held, and it holds the /// messages up to 4 s older than the last one it was asked about. "second", /// the newest message seen before the disconnect, is held and its replay is /// dropped; "first", 10 s older, is not, and is shown again as a live /// `Event::Chat` (this test sees `["first", "while away"]`). The one message /// of `a_reconnect_finds_the_state_the_first_session_left` is inside the /// window, which is all that test proves. TeamSpeak never replays, so no host /// the engine reaches today meets this; a `voelin://` host will. #[tokio::test(flavor = "multi_thread")] #[ignore = "known limit: a v1 host's replay after a reconnect is shown again (docs/session-seam.md 16.5)"] async fn a_message_the_host_sends_again_after_a_reconnect_is_not_shown_again() { let (_h, shown) = a_reconnect_to_a_host_that_replays().await; assert_eq!(shown, ["while away"]); } /// The messages a host sends again when a session reconnects are one message /// each in the history. /// /// Known limit, found by this test and left for the same resume (H8, 16.5): /// the engine stores every message it is told, shown or not (`store_live` runs /// before `Dedup`), and the store merges copies that come from different /// sources only, so a replay over the same source is a second row, whether /// `Dedup` hid the copy from the display or not (this test sees `["first", /// "first", "second", "second", "while away"]`). A `ChatMessage` does not carry /// the host's message id that would let the store merge them. #[tokio::test(flavor = "multi_thread")] #[ignore = "known limit: a v1 host's replay after a reconnect is stored twice (docs/session-seam.md 16.5)"] async fn a_message_the_host_sends_again_after_a_reconnect_is_stored_once() { let (h, _) = a_reconnect_to_a_host_that_replays().await; // The history thread takes its jobs in order: every row the engine was told // to write before it showed "while away" is written when this page is read. let rows = h.stored(ChatTarget::Channel(GAMES)).await; let texts: Vec<_> = rows.iter().map(|m| m.message.text.as_str()).collect(); assert_eq!(texts, ["first", "second", "while away"]); } /// A connect that fails is a disconnect with the reason the connector gave. #[tokio::test(flavor = "multi_thread")] async fn a_connect_that_fails_says_why_and_the_next_one_works() { let connector = connector(); connector.fail_next(|| SessionError::Protocol("the host is down".into())); let mut h = Harness::on(connector); h.ask_connect(); let state = h.state(|s| s.voice == VoiceState::Disconnected).await; assert_eq!((state.own_channel, state.own_client), (None, None)); assert_eq!(h.error().await, "voice: the host is down"); // The connector is asked again, and now the host is up. let handle = h.connect().await; assert_eq!(h.connector.connects().len(), 2); assert!(handle.close_reason().is_none()); let first = &h.connector.connects()[0]; assert_eq!(first.address, "fake://host"); assert_eq!(first.hello.nickname, "tester"); } /// A TeamSpeak identity that holds no JSON is refused with its reason before a /// connector is asked for anything: an empty credential blob would ask a /// TeamSpeak connector to make an identity up, which only `identity: None` may. #[tokio::test(flavor = "multi_thread")] async fn a_teamspeak_identity_without_json_is_refused_and_no_session_is_made() { let mut h = Harness::start(); let mut options = VoiceOptions::new("fake://host", "tester"); options.identity = Some(IdentityBlob::teamspeak("uid=", 8, "")); h.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); let state = h.state(|s| s.voice == VoiceState::Disconnected).await; assert_eq!((state.own_channel, state.own_client), (None, None)); assert_eq!(h.error().await, "voice: the TeamSpeak identity cannot be read: it is empty"); assert!(h.connector.connects().is_empty(), "the connector was asked to connect"); assert!(h.connector.last_session().is_none(), "a session was made"); // Without an identity the connector is asked as usual. let handle = h.connect().await; assert!(handle.close_reason().is_none()); assert_eq!(h.connector.connects().len(), 1); } /// A TeamSpeak identity whose key does not import ends the connect with words /// that say where the JSON is wrong and never show the key: the JSON reader's /// own message quotes it, and the text is the reason of the disconnect, the /// `Error` event and the status line the UI makes of it. This is the one test /// of the file that runs the engine's own TeamSpeak connector /// (`Backends::default()`): the refusal is that connector's and comes before /// any network. #[tokio::test(flavor = "multi_thread")] async fn a_teamspeak_identity_that_cannot_be_read_is_refused_without_the_key() { let mut json = serde_json::to_value(tsclientlib::Identity::create()).unwrap(); let key = json["key"].as_str().unwrap().to_owned(); // The key lost its last two characters. let cut = key[..key.len() - 2].to_owned(); json["key"] = cut.clone().into(); let mut options = VoiceOptions::new("ts3server://127.0.0.1:9", "tester"); options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json.to_string())); let mut h = Harness::with_backends(Backends::default(), FakeConnector::new()); h.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); let state = h.state(|s| s.voice == VoiceState::Disconnected).await; assert_eq!((state.own_channel, state.own_client), (None, None)); let error = h.error().await; assert!( error.starts_with( "voice: the TeamSpeak identity cannot be read: not an identity at line 1, column " ), "{error}" ); // Nothing the engine reported afterwards holds a piece of the key either. let mut shown = vec![error]; while let Ok(Ok(event)) = tokio::time::timeout(Duration::from_millis(300), h.events.recv()).await { shown.push(format!("{event:?}")); } for text in &shown { for piece in cut.as_bytes().windows(8) { let piece = std::str::from_utf8(piece).unwrap(); assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key"); } } }