Files
VoelinClient/crates/voelin-core/src/link/tests.rs
T
faumarayandClaude Sonnet 5.5 61458df625 Cancel the download test's transfer only once its part file is made
link::tests::a_file_is_downloaded_through_the_connection_the_link_opens waited
for the Started state and then cancelled, expecting the part file to be gone
100 ms later. The download reports Started just before it opens the part file
(files::download, then receive), and the open runs on tokio's blocking pool. A
cancel that arrives in between finds no part file to remove (link cancel()
removes it at once and reports Cancelled), the aborted task cannot stop the
open that is already going on, and the part file is made after the cancel:
`assert!(!part.exists())` failed. It did so in the second of the final runs of
the CI test step in the runner image of this task, and in 10 of 100 runs of
the voelin-core lib tests with three of them at a time and 16 busy loops
beside them on a 32-core machine (none in 200 such runs with this change).

The test now waits for the part file itself, which is what "the transfer
waits in the middle" means, and checks that Started was reported.

This is a real, if small, defect of the product that the test exposed: a
cancel in the moment between Started and the end of the open leaves an empty
`<name>.part` next to the target. It is not fixed here: closing it takes
reporting Started after the open (it also feeds the chat and the preview size
limit) or waiting for the aborted task before the part is removed, which is a
change of the transfer code and not of a test. Recorded in the report of this
branch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 21:41:37 +03:00

2289 lines
80 KiB
Rust

//! 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::ts_session::LinkConnector;
use crate::ts::{ConnectOptions, ServerLink};
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<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
}
/// Hands every connection to the test.
struct Recorder(mpsc::UnboundedSender<Inner>);
impl ServerLink for Recorder {
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
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 {
connected_to(capabilities, BackendInfo { product: "Fake".into(), version: "1.2".into() })
}
fn connected_to(capabilities: Capabilities, backend: BackendInfo) -> LinkEvent {
LinkEvent::Connected {
name: "Test Server".into(),
backend,
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<T>(what: &str, f: impl std::future::Future<Output = Option<T>>) -> 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<LinkCmd>,
events: mpsc::UnboundedReceiver<LinkEvent>,
bus: broadcast::Receiver<Event>,
}
impl Rig {
/// Connect and let the link report its server; the first events are
/// consumed up to the own channel.
async fn new(capabilities: Capabilities) -> Rig {
Rig::connect(connected(capabilities)).await
}
/// A connection to a TeamSpeak 3 server (its session follows our client across
/// the reconnects of the link).
async fn teamspeak(capabilities: Capabilities) -> Rig {
let backend = BackendInfo { product: "TeamSpeak 3".into(), version: "3.13.8".into() };
Rig::connect(connected_to(capabilities, backend)).await
}
async fn connect(connected: LinkEvent) -> Rig {
let (conns, mut seen) = mpsc::unbounded_channel();
let mut backends = Backends::empty();
backends.register_local(Arc::new(LinkConnector::any(Arc::new(Recorder(conns)))));
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(VoiceOptions::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).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<T>(&mut self, mut f: impl FnMut(LinkEvent) -> Option<T>) -> 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<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> 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<Mutex<Vec<TransferState>>>) {
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<Mutex<Vec<TransferState>>>) -> 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, with
// its part file made. `Started` is reported just before the part file is
// opened, and a cancel in between would find nothing to remove while the
// open still goes on, so the part file is what is waited for.
let (server, client) = tokio::io::duplex(64);
let _ = reply.send(Ok((1 << 20, Box::pin(client))));
for _ in 0..500 {
if part.exists() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(part.exists(), "the transfer made its part file: {:?}", states.lock().unwrap());
assert!(states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })));
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(VoiceOptions::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(VoiceOptions::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<dyn Session>, mpsc::Receiver<v1::Push>, 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();
// No limit anything reaches: a private conversation with every client fits.
assert!(limits.max_chat_subscriptions >= 1 << 16, "{limits:?}");
assert!(limits.max_subscriptions > limits.max_chat_subscriptions, "{limits:?}");
// 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<dyn Session>, mpsc::Receiver<v1::Push>, 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>) -> 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(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
async fn event<T>(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
mut f: impl FnMut(LinkEvent) -> Option<T>,
) -> 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/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
}
// ---- the connection across TeamSpeak's own reconnect ------------------------------
/// Our identity again, as the client TeamSpeak's reconnect makes: the same
/// unique id and database id, a client id of its own.
fn reconnected(id: u16, channel: u64) -> ClientInfo {
ClientInfo { id, ..client(ME, "me", channel) }
}
async fn own_channel(rig: &mut Rig) -> u64 {
rig.event(|e| match e {
LinkEvent::OwnChannel(channel) => Some(channel),
_ => None,
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn the_engine_follows_a_reconnect_that_makes_us_another_client() {
let mut rig = Rig::teamspeak(everything()).await;
// The connection comes back as client 21, in the lobby: 7 is gone.
let mut next = presence();
next.clients.remove(&ME);
next.clients.insert(21, reconnected(21, LOBBY));
rig.play(LinkEvent::Presence(Box::new(next)));
assert_eq!(own_channel(&mut rig).await, LOBBY);
// The chat of the channel we are in now reaches us.
rig.play(LinkEvent::Chat(ChatMessage {
target: ChatTarget::Channel(LOBBY),
author_name: "bob".into(),
author_uid: Some("bob=".into()),
author_id: Some(9),
text: "welcome back".into(),
ts_ms: 1_700_000_000_000,
via_relay: false,
blocked: false,
}));
let chat = rig
.event(|e| match e {
LinkEvent::Chat(chat) => Some(chat),
_ => None,
})
.await;
assert_eq!((chat.text.as_str(), chat.target), ("welcome back", ChatTarget::Channel(LOBBY)));
// What we say goes to the channel we are in now, not to the old one.
rig.give(LinkCmd::SendChat(ChatTarget::Channel(LOBBY), "thanks".into()));
let LinkCmd::SendChat(target, text) = rig.inner_cmd().await else { panic!("a chat message") };
assert_eq!((target, text.as_str()), (ChatTarget::Channel(LOBBY), "thanks"));
rig.give(LinkCmd::SendChat(ChatTarget::Channel(GAMES), "stale".into()));
let error = rig
.event(|e| match e {
LinkEvent::Error(text) => Some(text),
_ => None,
})
.await;
assert!(error.starts_with("message: "), "{error}");
// Our voice leaves on the slot of the client we are now, and the flags too.
rig.give(LinkCmd::Audio(EncodedVoice {
codec: VoiceCodec::Voice,
payload: OPUS_20_MS.to_vec(),
}));
assert!(matches!(rig.inner_cmd().await, LinkCmd::Audio(_)));
rig.give(LinkCmd::SetInputMuted(true));
assert!(matches!(rig.inner_cmd().await, LinkCmd::SetInputMuted(true)));
rig.quiet();
}
#[tokio::test(flavor = "multi_thread")]
async fn we_stay_the_client_we_were_while_it_is_there() {
let mut rig = Rig::teamspeak(everything()).await;
// A ghost of the old connection lingers: both clients carry our unique id.
// We stay client 7 (in the games channel), as another client of the same
// identity may be a second connection of ours.
let mut ghost = presence();
ghost.clients.insert(21, reconnected(21, LOBBY));
rig.play(LinkEvent::Presence(Box::new(ghost)));
assert_eq!(own_channel(&mut rig).await, GAMES);
// The ghost goes: we are the one that is left.
let mut gone = presence();
gone.clients.remove(&ME);
gone.clients.insert(21, reconnected(21, LOBBY));
rig.play(LinkEvent::Presence(Box::new(gone)));
assert_eq!(own_channel(&mut rig).await, LOBBY);
rig.give(LinkCmd::Audio(EncodedVoice {
codec: VoiceCodec::Voice,
payload: OPUS_20_MS.to_vec(),
}));
assert!(matches!(rig.inner_cmd().await, LinkCmd::Audio(_)));
}
// ---- chat scopes, private conversations -------------------------------------------
#[tokio::test(flavor = "multi_thread")]
async fn private_messages_from_more_than_16_peers_all_arrive() {
const PEERS: usize = 24;
let mut rig = Rig::new(everything()).await;
for peer in 0..PEERS {
let uid = format!("peer{peer}=");
rig.play(LinkEvent::Chat(ChatMessage {
target: ChatTarget::Private(uid.clone()),
author_name: format!("peer{peer}"),
author_uid: Some(uid),
author_id: None,
text: format!("hello {peer}"),
ts_ms: 1_700_000_000_000 + peer as i64,
via_relay: false,
blocked: false,
}));
}
let mut got = Vec::new();
while got.len() < PEERS {
let chat = rig
.event(|e| match e {
LinkEvent::Chat(chat) => Some(chat),
_ => None,
})
.await;
got.push((chat.text, chat.target));
}
got.sort_by(|a, b| a.0.cmp(&b.0));
let mut want: Vec<_> = (0..PEERS)
.map(|peer| (format!("hello {peer}"), ChatTarget::Private(format!("peer{peer}="))))
.collect();
want.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(got, want);
}
// ---- who is talking ------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
async fn a_talker_the_link_hears_but_does_not_forward_is_shown_as_talking() {
let mut rig = Rig::new(everything()).await;
// A Speex or CELT talker: the link says it talks, and sends no Opus.
rig.play(LinkEvent::Talking { client: 8, talking: true });
let on = rig
.event(|e| match e {
LinkEvent::Talking { client, talking } => Some((client, talking)),
_ => None,
})
.await;
assert_eq!(on, (8, true));
// And it holds for as long as the link says, silence or not.
tokio::time::sleep(Duration::from_millis(700)).await;
rig.play(LinkEvent::Talking { client: 8, talking: false });
let off = rig
.event(|e| match e {
LinkEvent::Talking { client, talking } => Some((client, talking)),
_ => None,
})
.await;
assert_eq!(off, (8, false));
}
// ---- notify ----------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
async fn a_notify_needs_the_control_stream_and_is_run_as_the_request_it_is() {
use v1::request::Op;
let (session, _pushes, mut inner) = open(everything()).await;
// A List and the file transfers have a stream and an answer of their own;
// a Hello is part of connecting.
for op in [
Op::List(v1::List { kind: v1::EntityKind::File as i32, ..Default::default() }),
Op::FileRead(Default::default()),
Op::FileWrite(Default::default()),
Op::Hello(Default::default()),
] {
let error = session.notify(op).unwrap_err();
assert!(matches!(error, SessionError::Protocol(_)), "{error:?}");
}
// An op of the control stream is acted on, answer or not: a poke is a poke.
session
.notify(Op::Signal(v1::Signal {
to: Some(v1::SignalTarget { server_id: 1, participant_id: 8, ..Default::default() }),
body: Some(v1::signal::Body::Poke(v1::Poke { message: "wake up".into() })),
..Default::default()
}))
.unwrap();
let LinkCmd::Poke { client, message } = within("a poke", inner.cmds.recv()).await else {
panic!("a poke")
};
assert_eq!((client, message.as_str()), (8, "wake up"));
// And a closed session refuses it.
session.close(v1::CloseCode::Normal, "");
let _ = within("the disconnect", inner.cmds.recv()).await;
inner.events.send(LinkEvent::Disconnected(None)).unwrap();
let _ = session.closed().await;
let error = session.notify(Op::LeaveVoice(v1::LeaveVoice { server_id: 1 })).unwrap_err();
assert!(matches!(error, SessionError::Closed(_)), "{error:?}");
}
// ---- how a connect ends ------------------------------------------------------------------
/// A connector of the protocol repository's fake host whose sessions answer
/// every `Subscribe` and push nothing: the test pushes the syncs itself.
struct Silent(voelin_proto::test_util::FakeConnector);
impl Connector for Silent {
fn schemes(&self) -> &'static [&'static str] {
self.0.schemes()
}
fn connect(
&self,
params: voelin_proto::link::ConnectParams,
) -> voelin_proto::link::BoxFuture<Result<voelin_proto::link::Connected, SessionError>> {
let connecting = self.0.connect(params);
let fake = self.0.clone();
Box::pin(async move {
let connected = connecting.await?;
if let Some(handle) = fake.last_session() {
handle.script(
voelin_proto::test_util::Script::answer(
"subscribe",
v1::response::Result::Ack(Default::default()),
)
.times(3),
);
}
Ok(connected)
})
}
}
/// A session that ends while the connect waits for the syncs says why it
/// ended: the engine shows the host's words, not a silent disconnect.
#[tokio::test(flavor = "multi_thread")]
async fn a_session_that_ends_during_the_connect_syncs_says_why() {
use voelin_model::replica::ScopeId;
use voelin_proto::v1::push::Body;
let fake = voelin_proto::test_util::FakeConnector::new();
fake.host()
.put(v1::Entity {
kind: Some(v1::entity::Kind::Server(v1::Server {
id: 1,
name: "Fake Host".into(),
uid: "fake-host".into(),
..Default::default()
})),
})
.unwrap();
let mut backends = Backends::empty();
backends.register(Arc::new(Silent(fake.clone())));
let link = SessionLink::new(backends);
let ctx = LocalCtx::standalone().link;
let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
// The three subscriptions are answered; two syncs end, the LIVE one never does.
let handle = loop {
if let Some(handle) = fake.last_session() {
break handle;
}
tokio::time::sleep(Duration::from_millis(2)).await;
};
voelin_proto::test_util::eventually(WAIT, "the three subscriptions", || {
let requests = handle.requests();
let subscribed = requests
.iter()
.filter(|logged| matches!(&logged.request.op, Some(v1::request::Op::Subscribe(_))))
.count();
subscribed == 3
})
.await;
for scope in [ScopeId::Home, ScopeId::Server(1)] {
let proto = Some(scope.to_proto());
let begin = v1::SyncBegin { scope: proto, mode: v1::SyncMode::Full as i32, epoch: 1 };
let end =
v1::SyncEnd { scope: proto, cursor: Some(v1::Cursor { epoch: 1, rev: 1 }), gap: false };
handle.push(v1::Push { body: Some(Body::SyncBegin(begin)) }).unwrap();
handle.push(v1::Push { body: Some(Body::SyncEnd(end)) }).unwrap();
}
// The host ends the session, with a reason.
handle.kill(CloseReason::Network("kicked: spam".into()));
let reason = within("the end", async {
loop {
if let LinkEvent::Disconnected(reason) = events.recv().await? {
return Some(reason);
}
}
})
.await;
assert_eq!(reason.as_deref(), Some("kicked: spam"));
}
/// A link no connector serves: the text shows where, never the channel
/// password that rides in the link.
#[tokio::test(flavor = "multi_thread")]
async fn the_text_of_an_address_nobody_serves_keeps_the_channel_password_out() {
let ctx = LocalCtx::standalone().link;
let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
let link = SessionLink::new(Backends::empty());
let mut options = VoiceOptions::new("ts.example.com:9987", "tester");
options.channel = Some("Raid".into());
options.channel_password = Some("hunter2".into());
link.spawn(options, ctx, cmd_rx, event_tx);
let event = within("the end", events.recv()).await;
let LinkEvent::Disconnected(Some(why)) = event else { panic!("a disconnect with a reason") };
assert!(why.starts_with("no connector for ts3server://ts.example.com"), "{why}");
assert!(!why.contains("hunter2") && !why.contains('?'), "{why}");
}
// ---- a consumer that lags -------------------------------------------------------------------
/// A session whose consumer does not read pushes does not stall the
/// connection: the voice goes on, and once the consumer reads again it gets
/// the scopes it missed in full (`ConnectParams.push_capacity`).
#[tokio::test(flavor = "multi_thread")]
async fn a_consumer_that_lags_loses_the_queue_and_gets_the_scope_again() {
use voelin_model::replica::{Replica, ScopeId};
let (conns, mut seen) = mpsc::unbounded_channel();
let connector = LinkConnector::new(Arc::new(Recorder(conns)), &["ts3server"]);
let (mut params, mut media) = connect_params("ts3server://fake.test?port=9987");
params.credential = Credential::Foreign { kind: "teamspeak", blob: Default::default() };
// The smallest queue there is: 16 pushes.
params.push_capacity = 1;
let connecting = tokio::spawn(connector.connect(params));
let inner = within("the link to be asked", seen.recv()).await;
inner.events.send(connected(everything())).unwrap();
inner.events.send(LinkEvent::Presence(Box::new(presence()))).unwrap();
let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await;
let (session, mut pushes) = (connected.session, connected.pushes);
let server = ScopeId::Server(1);
session.request(subscribe(server)).await.unwrap();
// Far more changes than the queue holds, and nobody reads.
const NAMES: usize = 40;
for i in 0..NAMES {
let mut next = presence();
next.channels.get_mut(&LOBBY).unwrap().name = format!("name{i}");
inner.events.send(LinkEvent::Presence(Box::new(next))).unwrap();
}
// The connection still takes voice from the link while the queue is full.
inner
.events
.send(LinkEvent::Audio(VoicePacket {
talker: TalkerId(8),
seq: 1,
codec: VoiceCodec::Voice,
whisper: false,
payload: OPUS_20_MS.to_vec(),
}))
.unwrap();
let packet = within("the voice", media.recv()).await;
assert_eq!(packet.flow.slot(), 9, "alice's slot");
// The consumer reads at last: what it gets ends with the last state.
let mut replica = Replica::default();
replica.subscribe(server);
let last = format!("name{}", NAMES - 1);
within("the last state", async {
loop {
let push = pushes.recv().await?;
replica.apply_push(&push);
if replica.channel(LOBBY).is_some_and(|channel| channel.name == last) {
return Some(());
}
}
})
.await;
}
/// A scope that needs more frames than the channel holds is sent in bigger
/// chunks, not never: the smallest channel is 16 pushes, of 256 entities.
#[tokio::test(flavor = "multi_thread")]
async fn a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks() {
use voelin_model::replica::{Replica, ScopeId};
const CHANNELS: u64 = 5_000;
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.push_capacity = 1;
let connecting = tokio::spawn(connector.connect(params));
let inner = within("the link to be asked", seen.recv()).await;
inner.events.send(connected(everything())).unwrap();
let mut big = presence();
for id in 100..100 + CHANNELS {
let channel = ChannelInfo { id, name: format!("c{id}"), ..Default::default() };
big.channels.insert(id, channel);
}
inner.events.send(LinkEvent::Presence(Box::new(big))).unwrap();
let connected = within("a session", async { connecting.await.ok().and_then(Result::ok) }).await;
let (session, mut pushes) = (connected.session, connected.pushes);
let server = ScopeId::Server(1);
session.request(subscribe(server)).await.unwrap();
let mut replica = Replica::default();
replica.subscribe(server);
within("the whole scope", async {
loop {
let push = pushes.recv().await?;
replica.apply_push(&push);
if matches!(push.body, Some(v1::push::Body::SyncEnd(_))) {
return Some(());
}
}
})
.await;
// Two of the fixture's channels, and the ones added.
assert_eq!(replica.channels(1).count() as u64, 2 + CHANNELS + 1, "with the server chat");
}
// ---- moves in flight, transfers, nameless pokes, narrowed features --------------
fn join(channel: u64) -> v1::request::Op {
request(v1::request::Op::JoinVoice(v1::JoinVoice {
server_id: 1,
channel_id: channel,
..Default::default()
}))
}
/// The channel of the voice state an answer carries.
fn voice_channel(answer: v1::response::Result) -> u64 {
let v1::response::Result::Entities(entities) = answer else { panic!("a voice state") };
let Some(v1::entity::Kind::Voice(voice)) = &entities.items[0].kind else {
panic!("a voice state")
};
voice.channel_id
}
/// The link reports a snapshot that has us in `channel`.
fn moved_to(inner: &Inner, channel: u64) {
let mut next = presence();
next.clients.get_mut(&ME).unwrap().channel = channel;
inner.events.send(LinkEvent::Presence(Box::new(next))).unwrap();
}
/// A move made while another is on its way is a move: the channel the
/// snapshots show is where we were, not where the first move leaves us. A
/// move into the channel we are in, with none on its way, is answered at once.
#[tokio::test(flavor = "multi_thread")]
async fn a_move_made_while_another_is_on_its_way_reaches_the_link() {
let (session, _pushes, mut inner) = open(everything()).await;
// The seat, then a move into the channel we are in: nothing to ask the link.
assert_eq!(voice_channel(session.request(join(GAMES)).await.unwrap()), GAMES);
let same = within("the answer", async { session.request(join(GAMES)).await.ok() }).await;
assert_eq!(voice_channel(same), GAMES);
assert!(inner.cmds.try_recv().is_err(), "a move into the channel we are in went to the link");
// The link is slow to answer the first move ...
let first = session.request(join(LOBBY));
let LinkCmd::Move(channel, _) = within("a move", inner.cmds.recv()).await else {
panic!("a move")
};
assert_eq!(channel, LOBBY);
// ... and the user changes their mind: back into the channel the snapshots
// still show. The link is asked, or the user stays in the lobby.
let second = session.request(join(GAMES));
let LinkCmd::Move(channel, _) = within("the move back", inner.cmds.recv()).await else {
panic!("the move back")
};
assert_eq!(channel, GAMES);
moved_to(&inner, LOBBY);
let first = within("the first move", async { first.await.ok() }).await;
assert_eq!(voice_channel(first), LOBBY);
moved_to(&inner, GAMES);
let second = within("the move back", async { second.await.ok() }).await;
assert_eq!(voice_channel(second), GAMES);
// Nothing is on its way any more.
let same = within("the answer", async { session.request(join(GAMES)).await.ok() }).await;
assert_eq!(voice_channel(same), GAMES);
assert!(inner.cmds.try_recv().is_err());
}
/// A move back into the channel we never left, after a refused move: the link
/// says nothing to a move into the channel it is in, and the refusal of the
/// first move answers the second.
#[tokio::test(flavor = "multi_thread")]
async fn a_move_back_after_a_refused_move_is_answered_though_the_link_says_nothing() {
let (session, _pushes, mut inner) = open(everything()).await;
session.request(join(GAMES)).await.unwrap();
let refused = session.request(join(LOBBY));
let LinkCmd::Move(..) = within("a move", inner.cmds.recv()).await else { panic!("a move") };
let back = session.request(join(GAMES));
let LinkCmd::Move(..) = within("the move back", inner.cmds.recv()).await else {
panic!("the move back")
};
inner.ctx.emit(Event::JoinFailed { session: 0, channel: LOBBY, reason: JoinFailure::Password });
let error = within("the refusal", async { Some(refused.await.unwrap_err()) }).await;
assert_eq!(error.code(), Some(v1::ErrorCode::Password));
// Answered now, not after the ten seconds of a move that gets no answer.
let back = tokio::time::timeout(Duration::from_secs(2), back).await;
assert_eq!(voice_channel(back.expect("answered at once").unwrap()), GAMES);
}
fn file_path(path: &str) -> v1::FilePath {
v1::FilePath { channel_id: GAMES, path: path.into(), password: String::new() }
}
/// A transfer waits for the server as long as its caller does: the engine
/// puts the deadline on a picture's negotiation and none on a file the user
/// asked for. A caller that gives up takes the link's job with it.
#[tokio::test(start_paused = true)]
async fn a_transfer_waits_for_the_server_for_as_long_as_the_caller_does() {
let (session, _pushes, mut inner) = open(everything()).await;
let long = Duration::from_secs(120);
let read = tokio::spawn(session.read_file(v1::FileRead {
target: Some(v1::file_read::Target::Path(file_path("/a.txt"))),
offset: 0,
length: 0,
}));
let LinkCmd::OpenRead { reply, .. } = within("a read", inner.cmds.recv()).await else {
panic!("a connection to read")
};
tokio::time::sleep(long).await;
assert!(!read.is_finished(), "a read gave up on its own");
let _ = reply.send(Ok((5, Box::pin(std::io::Cursor::new(b"hello".to_vec())))));
let Ok(Ok(download)) = read.await else { panic!("the read opened") };
let sizes: Vec<u64> = download
.head
.items
.iter()
.filter_map(|e| match &e.kind {
Some(v1::entity::Kind::File(file)) => Some(file.size),
_ => None,
})
.collect();
assert_eq!(sizes, [5]);
let write = tokio::spawn(session.write_file(v1::FileWrite {
target: Some(v1::file_write::Target::Path(file_path("/b.txt"))),
size: 3,
offset: 0,
overwrite: true,
..Default::default()
}));
let LinkCmd::OpenWrite { reply, .. } = within("a write", inner.cmds.recv()).await else {
panic!("a connection to write")
};
tokio::time::sleep(long).await;
assert!(!write.is_finished(), "a write gave up on its own");
let (_server, client) = tokio::io::duplex(64);
let _ = reply.send(Ok((0, Box::pin(client))));
assert!(matches!(write.await, Ok(Ok(_))), "the write opened");
// The caller gives up: the link's job is told.
let read = session.read_file(v1::FileRead {
target: Some(v1::file_read::Target::Path(file_path("/c.txt"))),
offset: 0,
length: 0,
});
let LinkCmd::OpenRead { reply, .. } = within("a read", inner.cmds.recv()).await else {
panic!("a connection to read")
};
drop(read);
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(reply.is_closed(), "the link's job outlived its caller");
}
/// A sender with no unique id who is not on the snapshot is named all the
/// same: the name the link gave goes into LIVE as a user of its own.
#[tokio::test(flavor = "multi_thread")]
async fn a_poke_from_a_sender_with_no_unique_id_outside_the_snapshot_is_named() {
let mut rig = Rig::new(everything()).await;
let poke = |name: &str| LinkEvent::Poke {
from: 77,
from_uid: None,
from_name: name.into(),
message: "boo".into(),
};
async fn named(rig: &mut Rig) -> (Option<String>, String) {
rig.event(|e| match e {
LinkEvent::Poke { from: 77, from_uid, from_name, .. } => Some((from_uid, from_name)),
_ => None,
})
.await
}
rig.play(poke("ghost"));
assert_eq!(named(&mut rig).await, (None, "ghost".to_owned()));
// The link gives the client id to whoever connects next: the name follows.
rig.play(poke("ghost two"));
assert_eq!(named(&mut rig).await, (None, "ghost two".to_owned()));
}
async fn event_of<T>(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
mut f: impl FnMut(LinkEvent) -> Option<T>,
) -> T {
within("an event", async {
loop {
if let Some(t) = f(events.recv().await?) {
return Some(t);
}
}
})
.await
}
/// `Server.features` narrows what the host offers (protocol 1.3,
/// `docs/session-seam.md` 4.7), and a `HostUpdate` changes what is narrowed.
#[tokio::test(flavor = "multi_thread")]
async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() {
use v1::entity::Kind;
use voelin_proto::test_util::{FakeConnector, eventually};
let connector = FakeConnector::new();
let host = connector.host();
let put_server = |features: &[&str]| {
let server = v1::Server {
id: 1,
name: "Narrow Host".into(),
uid: "narrow-host".into(),
default_channel_id: 10,
features: features.iter().map(|f| (*f).to_owned()).collect(),
..Default::default()
};
host.put(v1::Entity { kind: Some(Kind::Server(server)) }).unwrap();
};
put_server(&["voice", "chat"]);
let lobby = v1::Channel {
id: 10,
server_id: 1,
kind: v1::ChannelKind::Voice as i32,
name: "Lobby".into(),
..Default::default()
};
host.put(v1::Entity { kind: Some(Kind::Channel(lobby)) }).unwrap();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let link = SessionLink::new(backends);
let ctx = LocalCtx::standalone().link;
let mut bus = ctx.events.subscribe();
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
// The host offers files, the server does not.
let capabilities = event_of(&mut events, |e| match e {
LinkEvent::Connected { capabilities, .. } => Some(capabilities),
_ => None,
})
.await;
assert!(!capabilities.file_transfer, "the server's list leaves files out");
let handle = connector.last_session().expect("a session");
let file_lists = || {
let requests = handle.requests();
requests
.iter()
.filter(|logged| match &logged.request.op {
Some(v1::request::Op::List(list)) => list.kind == v1::EntityKind::File as i32,
_ => false,
})
.count()
};
let ask = |request| {
let dir = remote(10, None, "/");
cmd_tx.send(LinkCmd::ListFiles { request, dir }).unwrap();
};
let refusal = "not offered by this server: files";
let refused =
|event: &Event| matches!(event, Event::FileList { result: Err(why), .. } if why == refusal);
// Refused here: nothing reaches the host.
ask(1);
loop {
let event = within("the refusal", async { bus.recv().await.ok() }).await;
if refused(&event) {
break;
}
}
assert_eq!(file_lists(), 0);
// The server lifts its list (an empty one keeps all the host's): files work.
put_server(&[]);
let mut request = 1;
eventually(WAIT, "a file list to reach the host", || {
request += 1;
ask(request);
file_lists() > 0
})
.await;
// The host narrows what it offers this user. A refusal counts only for a
// request made after the update: the earlier ones were answered by the host's
// wider set (or, before the server lifted its list, refused for that).
let update = v1::HostUpdate { features: vec!["voice".into(), "chat".into()], limits: None };
handle.push(v1::Push { body: Some(v1::push::Body::HostUpdate(update)) }).unwrap();
let after = request;
within("the narrower set to apply", async {
loop {
request += 1;
ask(request);
tokio::time::sleep(Duration::from_millis(20)).await;
while let Ok(event) = bus.try_recv() {
if matches!(&event, Event::FileList { request, .. } if *request > after)
&& refused(&event)
{
return Some(());
}
}
}
})
.await;
}
/// A port that is no port is refused in words, not dropped: the connection
/// would go to another port than the one the bookmark names.
#[tokio::test(flavor = "multi_thread")]
async fn a_bookmark_with_a_port_that_is_no_port_does_not_connect() {
let mut backends = Backends::empty();
let (conns, mut seen) = mpsc::unbounded_channel();
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(VoiceOptions::new("ts.example.com:99999", "tester"), ctx, cmd_rx, event_tx);
let reason = event_of(&mut events, |e| match e {
LinkEvent::Disconnected(reason) => Some(reason),
_ => None,
})
.await;
let reason = reason.expect("a reason");
assert!(reason.contains("65535") && reason.contains("ts.example.com:99999"), "{reason}");
assert!(seen.try_recv().is_err(), "a link was asked to connect anyway");
}