From 226933fcdc54bfa7179021ddbea9052e17a7ddf3 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 24 Oct 2026 02:02:39 +0300 Subject: [PATCH] Run the link conformance subset and the session scenarios on both TeamSpeak servers ts_session/live_tests.rs (VOELIN_LIVE=1, the development servers) holds the TeamSpeak Session tests of docs/session-seam.md section 9.3, made through TsConnector's plain Connector interface: - the conformance suite of the protocol repository, every case listed with what a TeamSpeak session does with it: two pass (welcome_matches_features, close_ends_the_session), four are skipped for a feature the session lacks (chat.edit, chat chat.history, idempotency), and the rest do not apply; a case the suite gains fails until it is listed; - what the suite cannot reach: an own-channel message answered and pushed to the other session and back, the PASSWORD and FULL refusals of a move, a poke between two sessions, voice RTP from one slot to the other session's media sink (marker, order, an empty payload at the end), and a channel file written with write_file and read back from an offset with read_file. Two tests, ignored by default, run the cases that do not apply and watch each fail; the reason in the table is what the case did when it was run. scripts/it-smoke.sh runs the module before its engine stage. Co-Authored-By: Claude Sonnet 5.5 --- .../voelin-core/src/ts_session/live_tests.rs | 814 ++++++++++++++++++ crates/voelin-core/src/ts_session/mod.rs | 2 + scripts/it-smoke.sh | 3 + 3 files changed, 819 insertions(+) create mode 100644 crates/voelin-core/src/ts_session/live_tests.rs diff --git a/crates/voelin-core/src/ts_session/live_tests.rs b/crates/voelin-core/src/ts_session/live_tests.rs new file mode 100644 index 0000000..45abc4c --- /dev/null +++ b/crates/voelin-core/src/ts_session/live_tests.rs @@ -0,0 +1,814 @@ +//! The TeamSpeak `Session` against the development servers +//! (`dev/docker-compose.yml`; `docs/session-seam.md` sections 9.3 and 16). +//! Runs only with `VOELIN_LIVE=1`: +//! +//! ```text +//! VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1 +//! ``` +//! +//! Two kinds of test, each on TeamSpeak 3 and on TeamSpeak 6: +//! +//! - the link conformance suite of the protocol repository, the cases that +//! apply to a TeamSpeak session, with the verdict of every case asserted +//! and the reason of every case that cannot pass or cannot run in +//! [`EXPECTED`]; +//! - what the suite cannot reach, as a session of its own does it: a message +//! in the own channel answered, then pushed to the other session and back to +//! ours, the refusals of a move, a poke between two sessions, voice RTP from +//! one session's slot to the other's media sink, and a channel file written +//! and read back from an offset. +//! +//! The sessions are made by [`TsConnector`] through the plain `Connector` +//! interface, as a client of the seam outside an engine would make them. + +use std::collections::BTreeMap; +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; + +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::sync::mpsc; +use voelin_proto::link::{Connector, FlowId, MediaClass, MediaPacket, voice_sub}; +use voelin_proto::media::payload::PT_OPUS; +use voelin_proto::media::{RtpHeader, RtpView}; +use voelin_proto::test_util::conformance::{self, Fixture, Verdict}; +use voelin_proto::test_util::{FakeConnector, MediaReceiver, media_channel}; +use voelin_proto::v1::request::Op; +use voelin_proto::v1::{self, entity::Kind}; + +use super::*; + +fn live() -> bool { + std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1") +} + +/// How long a test waits for the server. +const WAIT: Duration = Duration::from_secs(20); + +async fn within(what: &str, future: impl Future) -> T { + match tokio::time::timeout(WAIT, future).await { + Ok(value) => value, + Err(_) => panic!("timed out after {WAIT:?} waiting for {what}"), + } +} + +/// A development server: where to connect, and how to ask it as the admin. +#[derive(Clone, Copy)] +struct Dev { + name: &'static str, + voice: &'static str, + ssh: bool, + query: &'static str, +} + +const TS3: Dev = Dev { name: "ts3", voice: "127.0.0.1:9987", ssh: false, query: "127.0.0.1:10011" }; +const TS6: Dev = Dev { name: "ts6", voice: "127.0.0.1:9988", ssh: true, query: "127.0.0.1:10022" }; + +impl Dev { + fn query(&self) -> voelin_query::Connect { + voelin_query::Connect { + transport: if self.ssh { + voelin_query::Transport::Ssh + } else { + voelin_query::Transport::Raw + }, + addr: self.query.into(), + user: "serveradmin".into(), + secret: Some("voelin-dev-admin".into()), + server_port: Some(9987), + server_id: None, + line: voelin_query::LineOptions { rate_limit: None, ..Default::default() }, + } + } + + /// A nickname no other client of this run has. + fn nick(&self, role: &str) -> String { + static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = COUNT.fetch_add(1, Ordering::Relaxed); + format!("{role}-{}-{n}", std::process::id() % 10_000) + } +} + +/// A TeamSpeak session as a client of the seam sees it: made by the +/// connector, with its push channel and media sink. +async fn session( + dev: &Dev, + options: &ConnectOptions, +) -> (Arc, mpsc::Receiver, MediaReceiver) { + let (sink, media) = media_channel(); + let params = connect_params(options, sink, &Backends::empty()).expect("connect parameters"); + let connected = + within(&format!("a connection to {}", dev.name), TsConnector::new().connect(params)) + .await + .unwrap_or_else(|e| panic!("{} did not connect: {e}", dev.name)); + (connected.session, connected.pushes, media) +} + +/// A client of the TeamSpeak session that has done what an engine does after +/// it connects (`docs/session-seam.md` 4.2, without the replica): the server +/// listed, HOME, SERVER and LIVE subscribed and synced, a seat in voice. +struct Client { + session: Arc, + pushes: mpsc::Receiver, + media: MediaReceiver, + server: u64, + default_channel: u64, + /// Our seat in voice (participant, slot, channel). + seat: v1::VoiceState, + /// The voice states of the server, as the pushes told them. + voices: BTreeMap, +} + +fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope { + v1::Scope { kind: kind as i32, id } +} + +impl Client { + async fn connect(dev: &Dev, nick: &str) -> Self { + Self::connect_with(dev, ConnectOptions::new(dev.voice, nick)).await + } + + async fn connect_with(dev: &Dev, options: ConnectOptions) -> Self { + let (session, pushes, media) = session(dev, &options).await; + let mut client = Self { + session, + pushes, + media, + server: 0, + default_channel: 0, + seat: v1::VoiceState::default(), + voices: BTreeMap::new(), + }; + let list = Op::List(v1::List { kind: v1::EntityKind::Server as i32, ..Default::default() }); + let Answer::Entities(servers) = client.ask(list).await.expect("the server list") else { + panic!("the server list is not entities") + }; + let server = servers + .items + .iter() + .find_map(|e| match &e.kind { + Some(Kind::Server(server)) => Some(server.clone()), + _ => None, + }) + .expect("the host lists its server"); + client.server = server.id; + client.default_channel = server.default_channel_id; + for scope in [ + scope(v1::ScopeKind::Home, 0), + scope(v1::ScopeKind::Server, server.id), + scope(v1::ScopeKind::Live, server.id), + ] { + client.subscribe(scope).await; + } + client.seat = client.join(client.default_channel, "").await.expect("a seat in voice"); + client.settle().await; + client + } + + /// A request, answered within [`WAIT`]. + async fn ask(&self, op: Op) -> Result { + within("an answer", self.session.request(op)).await + } + + /// Subscribe `scope` and take its sync off the push channel. + async fn subscribe(&mut self, scope: v1::Scope) { + let op = Op::Subscribe(v1::Subscribe { scope: Some(scope), ..Default::default() }); + self.ask(op).await.expect("a subscription"); + self.until("the end of the sync", |push| match &push.body { + Some(v1::push::Body::SyncEnd(end)) if end.scope == Some(scope) => Some(()), + _ => None, + }) + .await; + } + + /// `JoinVoice`: our seat, or why not. + async fn join(&self, channel: u64, password: &str) -> Result { + let join = v1::JoinVoice { + server_id: self.server, + channel_id: channel, + password: password.into(), + ..Default::default() + }; + match self.ask(Op::JoinVoice(join)).await? { + Answer::Entities(entities) => entities + .items + .into_iter() + .find_map(|e| match e.kind { + Some(Kind::Voice(voice)) => Some(voice), + _ => None, + }) + .ok_or_else(|| SessionError::Protocol("no voice state in the answer".into())), + other => Err(SessionError::Protocol(format!("unexpected answer {other:?}"))), + } + } + + /// Keep track of what a push says about the server and its voice states. + fn absorb(&mut self, push: &v1::Push) { + let Some(v1::push::Body::Change(change)) = &push.body else { return }; + for entity in &change.put { + match &entity.kind { + Some(Kind::Voice(voice)) => { + self.voices.insert(voice.participant_id, voice.clone()); + } + Some(Kind::Server(server)) if server.default_channel_id != 0 => { + self.default_channel = server.default_channel_id; + } + _ => {} + } + } + for entity in &change.del { + if let Some(Kind::Voice(voice)) = &entity.kind { + self.voices.remove(&voice.participant_id); + } + } + } + + /// The next push `f` picks, skipping (and keeping track of) the others. + async fn until(&mut self, what: &str, mut f: impl FnMut(&v1::Push) -> Option) -> T { + within(what, async { + loop { + let push = self.pushes.recv().await.expect("the session lives"); + self.absorb(&push); + if let Some(t) = f(&push) { + return t; + } + } + }) + .await + } + + /// Wait until the host shows our seat in LIVE: the first snapshot of the + /// TeamSpeak link may come after the session was handed out, so the syncs + /// can be empty and the voice states follow as changes. The seat then + /// names the channel we are in. + async fn settle(&mut self) { + let participant = self.seat.participant_id; + within("our voice state to appear", async { + while !self.voices.contains_key(&participant) { + let push = self.pushes.recv().await.expect("the session lives"); + self.absorb(&push); + } + }) + .await; + self.seat = self.voices[&participant].clone(); + } + + /// The next message `Change` of the CHAT scope of `channel` with `text`. + async fn message(&mut self, channel: u64, text: &str) -> v1::Message { + let chat = Some(scope(v1::ScopeKind::Chat, channel)); + self.until(&format!("the message {text:?}"), |push| match &push.body { + Some(v1::push::Body::Change(change)) if change.scope == chat => { + change.put.iter().find_map(|e| match &e.kind { + Some(Kind::Message(message)) if message.text == text => Some(message.clone()), + _ => None, + }) + } + _ => None, + }) + .await + } + + async fn close(self) { + self.session.close(v1::CloseCode::Normal, ""); + within("the session to close", self.session.closed()).await; + } +} + +// ---- the conformance suite ---------------------------------------------------- + +/// What a case is expected to do against a TeamSpeak session, and why. +enum Expect { + /// Every assertion of the case holds. + Passes, + /// The session lacks the feature the case needs (`Verdict::Skipped`). + Skipped(&'static str), + /// The case does not apply: it cannot run, or cannot pass, for this reason + /// (`cases_that_do_not_apply_fail` runs them and watches them fail). + NotRun(&'static str), +} +use Expect::{NotRun, Passes, Skipped}; + +/// Every case of the suite of the protocol repository at `c8e0e5a`, in its +/// order, with what a TeamSpeak session does with it. A case the suite gains +/// fails `the_suite_is_known` until it is listed here. +/// +/// The suite is written for a backend that is a `FakeHost`. A case that needs +/// the backend gets the `FakeHandle` of an unrelated fake host, so the cases +/// that hold, kill or read it, or push into it, cannot run against a session of +/// a TeamSpeak server; the others write to places a TeamSpeak server does not +/// have (the suite's channels, a server with another id, `ScheduledEvent`, +/// `Emoji`, attachments). Each reason is what the case did when it was run. +const EXPECTED: [(&str, Expect); 17] = [ + ("welcome_matches_features", Passes), + ( + "subscribe_syncs_the_scope", + NotRun("writes to channel 4001: rejected (NotFound) no such channel"), + ), + ( + "subscribe_resumes_from_a_cursor", + NotRun("writes to channel 4002: rejected (NotFound) no such channel"), + ), + ( + "put_answers_entities_and_pushes_the_change_with_the_same_rev", + NotRun("writes to channel 4003: rejected (NotFound) no such channel"), + ), + ( + "delete_answers_an_ack_and_pushes_the_removal", + NotRun( + "writes to channel 4004 first (no such channel); and TeamSpeak cannot delete a message, \ + where the case needs only `chat`, not `chat.delete` (P8)", + ), + ), + ( + "a_key_names_an_entity_without_its_server", + NotRun( + "rejected (NotFound) no such server; and it creates a ScheduledEvent and an Emoji, \ + which TeamSpeak lacks, though it needs no feature (P8)", + ), + ), + ("a_stale_rev_conflicts_and_a_patch_writes_only_its_paths", Skipped("chat.edit")), + ("requests_apply_in_the_order_they_were_issued", Skipped("chat.edit")), + ("list_pages_history", Skipped("chat.history")), + ( + "cancel_before_apply_is_cancelled", + NotRun("holds the unrelated fake host, so the request is answered while it \"holds\""), + ), + ("idempotency_keys_apply_a_put_once", Skipped("idempotency")), + ( + "notifications_are_fire_and_forget", + NotRun("reads the request log of the unrelated fake host: the notification never arrives"), + ), + ( + "renew_account_follows_the_feature", + NotRun("pushes a HostUpdate into the unrelated fake session's closed push channel"), + ), + ( + "media_loops_back", + NotRun( + "a TeamSpeak server does not return a client's own voice: the packet never loops back", + ), + ), + ( + "files_round_trip", + NotRun( + "writes an AttachmentSlot: rejected (Unsupported) attachments are not offered; \ + TeamSpeak has channel files, and the case needs `files`, not `chat.attachments` (P8)", + ), + ), + ("close_ends_the_session", Passes), + ( + "the_backend_can_end_the_session", + NotRun( + "kills the unrelated fake session, so closed() of this one never resolves; and a \ + kick is Network(text), not Remote{KICKED}, until H1", + ), + ), +]; + +/// A fixture on a TeamSpeak session. The suite wants a `FakeHandle` on the +/// backend behind the session; a TeamSpeak server has none, so it gets the one +/// of an unrelated fake host, which the cases that are run never touch. +async fn fixture(dev: Dev) -> Fixture { + let (session, pushes, media) = + session(&dev, &ConnectOptions::new(dev.voice, dev.nick("conf"))).await; + let unrelated = FakeConnector::new(); + let (params, _media) = voelin_proto::test_util::connect_params("fake://unrelated"); + unrelated.connect(params).await.expect("a fake session"); + let backend = unrelated.last_session().expect("a fake session"); + Fixture::new(session, pushes, media, backend) +} + +fn the_suite_is_known() { + let known: Vec<_> = EXPECTED.iter().map(|(name, _)| *name).collect(); + let cases: Vec<_> = conformance::CASES.iter().map(|case| case.name).collect(); + assert_eq!(known, cases, "the suite changed: list the new cases in EXPECTED"); +} + +/// The cases that apply run and pass, the ones that need a feature the session +/// lacks are skipped, and the rest are not run (their reason is in +/// [`EXPECTED`]). +async fn conformance_subset(dev: Dev) { + the_suite_is_known(); + let harness = move || fixture(dev); + let (mut passed, mut skipped) = (0, 0); + for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) { + match expect { + Passes => { + let verdict = conformance::run_case(&harness, case).await; + assert_eq!(verdict, Verdict::Passed, "{name} on {}", dev.name); + passed += 1; + } + Skipped(feature) => { + let verdict = conformance::run_case(&harness, case).await; + assert_eq!(verdict, Verdict::Skipped(feature), "{name} on {}", dev.name); + skipped += 1; + } + NotRun(reason) => eprintln!("{} {name}: not run: {reason}", dev.name), + } + } + assert_eq!((passed, skipped), (2, 4)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_conformance_subset() { + if live() { + conformance_subset(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_conformance_subset() { + if live() { + conformance_subset(TS6).await; + } +} + +// ---- what the suite cannot reach ---------------------------------------------- + +/// A message in the own channel is answered with the message as written, and +/// pushed to the CHAT scope of every session in the channel: to the other one +/// as a `Change`, and back to ours (the ids agree only with the native +/// session of H1: the answer has a local id, the echo the one of the +/// `Change`). +async fn chat_in_the_own_channel(dev: Dev) { + let mut a = Client::connect(&dev, &dev.nick("chat-a")).await; + let mut b = Client::connect(&dev, &dev.nick("chat-b")).await; + assert_eq!(a.seat.channel_id, b.seat.channel_id, "both sessions are in the default channel"); + let channel = a.seat.channel_id; + a.subscribe(scope(v1::ScopeKind::Chat, channel)).await; + b.subscribe(scope(v1::ScopeKind::Chat, channel)).await; + + let text = format!("live-chat-{}", std::process::id()); + let message = v1::Message { channel_id: channel, text: text.clone(), ..Default::default() }; + let write = v1::Write { + entity: Some(v1::Entity { kind: Some(Kind::Message(message)) }), + paths: Vec::new(), + }; + let put = Op::Put(v1::Put { writes: vec![write], ..Default::default() }); + let Answer::Entities(answer) = a.ask(put).await.expect("the message is accepted") else { + panic!("a message is answered with entities") + }; + let written = match &answer.items[..] { + [v1::Entity { kind: Some(Kind::Message(message)) }] => message.clone(), + other => panic!("one message expected, got {other:?}"), + }; + assert_eq!((written.channel_id, written.text.as_str()), (channel, text.as_str())); + + let heard = b.message(channel, &text).await; + assert_ne!(heard.id, 0); + assert_eq!(heard.channel_id, channel); + // And ours, back from the server: the same words, once. + let echo = a.message(channel, &text).await; + assert_ne!(echo.id, 0); + a.close().await; + b.close().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_chat_in_the_own_channel() { + if live() { + chat_in_the_own_channel(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_chat_in_the_own_channel() { + if live() { + chat_in_the_own_channel(TS6).await; + } +} + +/// A move into a channel with a password or without room is refused with the +/// code the seam names: `PASSWORD` and `FULL`. +async fn refused_moves(dev: Dev) { + use voelin_query::{Command as Query, QueryClient}; + let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login"); + let tag = std::process::id() % 10_000; + let create = |name: &str| { + Query::new("channelcreate") + .arg("channel_name", format!("{name}-{tag}")) + .arg("channel_flag_semi_permanent", 1) + }; + let locked = + admin.send(&create("seam-locked").arg("channel_password", "secret")).await.unwrap()[0] + .parse::("cid") + .unwrap(); + let full = create("seam-full") + .arg("channel_maxclients", 0) + .arg("channel_flag_maxclients_unlimited", 0); + let full = admin.send(&full).await.unwrap()[0].parse::("cid").unwrap(); + // A key for the Normal group, which has to keep to passwords and limits. + let token = group_token(&admin, "Normal").await; + + let check = { + let token = token.clone(); + tokio::spawn(async move { + let mut options = ConnectOptions::new(dev.voice, dev.nick("moves")); + options.token = Some(token); + let client = Client::connect_with(&dev, options).await; + let code = |result: Result| match result { + Err(SessionError::Rejected(error)) => error.code(), + other => panic!("expected a refusal, got {other:?}"), + }; + assert_eq!(code(client.join(locked, "").await), v1::ErrorCode::Password); + assert_eq!(code(client.join(locked, "wrong").await), v1::ErrorCode::Password); + let seat = client.join(locked, "secret").await.expect("the right password"); + assert_eq!(seat.channel_id, locked); + assert_eq!(code(client.join(full, "").await), v1::ErrorCode::Full); + client.close().await; + }) + }; + let result = check.await; + // Clean up before reporting a failure; the key is gone once used. + let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await; + for cid in [locked, full] { + admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap(); + } + if let Err(error) = result { + std::panic::resume_unwind(error.into_panic()); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_refused_moves() { + if live() { + refused_moves(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_refused_moves() { + if live() { + refused_moves(TS6).await; + } +} + +/// A poke is a `Signal` to a participant: the other session gets it, with +/// the participant and the words of the sender. +async fn poke_between_sessions(dev: Dev) { + let a = Client::connect(&dev, &dev.nick("poke-a")).await; + let mut b = Client::connect(&dev, &dev.nick("poke-b")).await; + let text = format!("live-poke-{}", std::process::id()); + let target = v1::SignalTarget { + server_id: a.server, + participant_id: b.seat.participant_id, + ..Default::default() + }; + let signal = v1::Signal { + to: Some(target), + body: Some(v1::signal::Body::Poke(v1::Poke { message: text.clone() })), + ..Default::default() + }; + a.ask(Op::Signal(signal)).await.expect("the poke is accepted"); + let from = b + .until("the poke", |push| match &push.body { + Some(v1::push::Body::Signal(signal)) => match &signal.body { + Some(v1::signal::Body::Poke(poke)) if poke.message == text => { + Some(signal.from_participant) + } + _ => None, + }, + _ => None, + }) + .await; + assert_eq!(from, a.seat.participant_id); + a.close().await; + b.close().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_poke_between_sessions() { + if live() { + poke_between_sessions(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_poke_between_sessions() { + if live() { + poke_between_sessions(TS6).await; + } +} + +/// One frame of Opus (20 ms, mono, fullband). +const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe]; + +fn rtp(flow: FlowId, sequence: u16, marker: bool, payload: &[u8]) -> MediaPacket { + let mut header = RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960); + header.marker = marker; + let mut out = bytes::BytesMut::new(); + header.write(flow, &mut out).expect("a header"); + out.extend_from_slice(payload); + MediaPacket { flow, rtp: out.freeze() } +} + +/// Voice sent on our slot arrives on the sender's slot at the other session's +/// media sink: the frames in order (the sequence is TeamSpeak's packet id, so +/// it only has to count up), the marker on the first, and an empty payload at +/// the end. +async fn voice_between_sessions(dev: Dev) { + let a = Client::connect(&dev, &dev.nick("voice-a")).await; + let mut b = Client::connect(&dev, &dev.nick("voice-b")).await; + assert_eq!(a.seat.channel_id, b.seat.channel_id); + let flow = FlowId::new(a.seat.slot, voice_sub::CHANNEL); + for n in 0..5u8 { + let frame = [0xf8, 0xff, 0xfe, n]; + let packet = rtp(flow, u16::from(n), n == 0, &frame); + a.session.send_media(MediaClass::Voice, packet).expect("our own slot"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + a.session.send_media(MediaClass::Voice, rtp(flow, 5, false, &[])).expect("the end"); + + let mut heard = Vec::new(); + while let Some(packet) = b.media.recv_within(Duration::from_secs(5)).await { + let view = RtpView::parse(&packet.rtp).expect("RTP"); + heard.push((packet.flow, view.sequence(), view.marker(), view.payload().to_vec())); + if view.payload().is_empty() { + break; + } + } + assert!(heard.len() >= 2, "{heard:?}"); + assert!(heard.iter().all(|(heard_flow, ..)| *heard_flow == flow), "{heard:?}"); + let (_, _, first_marker, first_payload) = &heard[0]; + assert!(*first_marker, "the first packet of the spurt carries the marker: {heard:?}"); + assert_eq!(&first_payload[..3], &OPUS[..], "{heard:?}"); + let (end_flow, _, end_marker, end_payload) = heard.last().expect("an end"); + assert!( + end_payload.is_empty() && !*end_marker, + "the spurt ends with an empty payload: {heard:?}" + ); + assert_eq!(*end_flow, flow); + let sequences: Vec<_> = heard.iter().map(|(_, sequence, ..)| *sequence).collect(); + assert!( + sequences.windows(2).all(|pair| pair[1] == pair[0].wrapping_add(1)), + "the sequence counts up by one: {sequences:?}" + ); + // Voice on a slot that is not ours is refused before it reaches the server. + let other = FlowId::new(a.seat.slot + 1000, voice_sub::CHANNEL); + assert!(a.session.send_media(MediaClass::Voice, rtp(other, 0, true, &OPUS)).is_err()); + a.close().await; + b.close().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_voice_between_sessions() { + if live() { + voice_between_sessions(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_voice_between_sessions() { + if live() { + voice_between_sessions(TS6).await; + } +} + +/// A channel file written with `write_file` and read back from an offset with +/// `read_file`: the head names the file and its size, the body starts where +/// the offset says. +async fn channel_file_from_an_offset(dev: Dev) { + use voelin_query::{Command as Query, QueryClient}; + // Guests may not upload: a key for the Server Admin group. + let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login"); + let token = group_token(&admin, "Server Admin").await; + let check = tokio::spawn({ + let token = token.clone(); + async move { channel_file_with_a_key(dev, token).await } + }); + let result = check.await; + let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await; + if let Err(error) = result { + std::panic::resume_unwind(error.into_panic()); + } +} + +/// A one-time key for the server group `name` (a template group, type 1). +async fn group_token(admin: &voelin_query::QueryClient, name: &str) -> String { + use voelin_query::Command as Query; + let groups = admin.send(&Query::new("servergrouplist")).await.unwrap(); + let group = groups + .iter() + .find(|g| g.get("name") == Some(name) && g.get("type") == Some("1")) + .and_then(|g| g.parse::("sgid")) + .unwrap_or_else(|| panic!("a {name} server group")); + let key = + Query::new("privilegekeyadd").arg("tokentype", 0).arg("tokenid1", group).arg("tokenid2", 0); + admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned() +} + +async fn channel_file_with_a_key(dev: Dev, token: String) { + let mut options = ConnectOptions::new(dev.voice, dev.nick("files")); + options.token = Some(token); + let a = Client::connect_with(&dev, options).await; + let channel = a.seat.channel_id; + let name = format!("seam-{}.bin", std::process::id()); + let path = format!("/{name}"); + let data: Vec = (0..3_000usize).map(|i| (i * 7 % 251) as u8).collect(); + let target = v1::FilePath { channel_id: channel, path: path.clone(), password: String::new() }; + + let write = v1::FileWrite { + target: Some(v1::file_write::Target::Path(target.clone())), + size: data.len() as u64, + offset: 0, + overwrite: true, + sha256: Default::default(), + }; + let mut upload = + within("the upload to open", a.session.write_file(write)).await.expect("an upload"); + upload.body.write_all(&data).await.expect("the body"); + upload.body.shutdown().await.expect("the end of the body"); + let stored = within("the server to keep it", upload.done).await.expect("the file is stored"); + assert!( + stored.items.iter().any(|e| matches!(&e.kind, Some(Kind::File(f)) if f.name == name)), + "{stored:?}" + ); + + let read = v1::FileRead { + target: Some(v1::file_read::Target::Path(target.clone())), + offset: 1_000, + length: 0, + }; + let mut download = + within("the download to open", a.session.read_file(read)).await.expect("a download"); + let size = download.head.items.iter().find_map(|e| match &e.kind { + Some(Kind::File(file)) => Some(file.size), + _ => None, + }); + assert_eq!(size, Some(3_000), "{:?}", download.head); + let mut body = Vec::new(); + within("the body", download.body.read_to_end(&mut body)).await.expect("the body"); + assert_eq!(body, data[1_000..], "the body starts at the offset"); + + // Clean up what we put on the server. + let key = v1::FileEntry { channel_id: channel, path: "/".into(), name, ..Default::default() }; + let delete = Op::Delete(v1::Delete { + keys: vec![v1::Entity { kind: Some(Kind::File(key)) }], + ..Default::default() + }); + let _ = a.ask(delete).await; + a.close().await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_channel_file_from_an_offset() { + if live() { + channel_file_from_an_offset(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_channel_file_from_an_offset() { + if live() { + channel_file_from_an_offset(TS6).await; + } +} + +// ---- the cases that do not apply ---------------------------------------------- + +/// The cases of [`EXPECTED`] that do not apply fail against a session of a +/// TeamSpeak server, each with a panic of its own (its first line is printed): +/// the reasons of the table are what they did when they were run. A case that +/// passes one day (with the native session of H1) is to be moved to `Passes`. +/// +/// Ignored by default: the cases that wait for a backend that is not there +/// take their three seconds each. +async fn cases_that_do_not_apply_fail(dev: Dev) { + for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) { + let NotRun(reason) = expect else { continue }; + let harness = move || async move { + let mut fixture = fixture(dev).await; + fixture.step = Duration::from_secs(3); + fixture + }; + match tokio::spawn(async move { conformance::run_case(&harness, case).await }).await { + Err(error) if error.is_panic() => { + let payload = error.into_panic(); + let message = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned())) + .unwrap_or_default(); + let first = message.lines().next().unwrap_or_default(); + eprintln!("{} {name}: failed as expected ({reason}): {first}", dev.name); + } + other => panic!("{name} on {} was expected to fail, and: {other:?}", dev.name), + } + } +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"] +async fn ts3_cases_that_do_not_apply_fail() { + if live() { + cases_that_do_not_apply_fail(TS3).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"] +async fn ts6_cases_that_do_not_apply_fail() { + if live() { + cases_that_do_not_apply_fail(TS6).await; + } +} diff --git a/crates/voelin-core/src/ts_session/mod.rs b/crates/voelin-core/src/ts_session/mod.rs index 9558a50..994b9c9 100644 --- a/crates/voelin-core/src/ts_session/mod.rs +++ b/crates/voelin-core/src/ts_session/mod.rs @@ -19,6 +19,8 @@ mod driver; pub(crate) mod entities; pub(crate) mod ids; +#[cfg(test)] +mod live_tests; mod media; use std::pin::Pin; diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index fa6054f..466ae84 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -533,6 +533,9 @@ for svc in "${SERVERS[@]}"; do fi done +log "TeamSpeak session (voelin-core ts_session) against both servers: link conformance subset, chat, refused moves, poke, voice, files" +VOELIN_LIVE=1 cargo test --quiet -p voelin-core --lib ts_session::live_tests -- --test-threads=1 2>&1 | grep -E "test result|panicked|timed out" || fail "TeamSpeak session tests failed" + log "engine (voelin-core) against both servers, media pipeline through TS6" VOELIN_LIVE=1 cargo test --quiet -p voelin-core --features media-desktop --test live --test stream_live --test media_live 2>&1 | grep -E "test result|panicked|timed out" || fail "engine tests failed"