Files
client/native/tests/connections.rs
bit9992 f403dd5fcf
android-ci / android-arm64 (push) Successful in 15m1s
Keep capture frame rejection separate from permit revocation
2026-11-14 09:45:55 +03:00

146 lines
7.9 KiB
Rust

use std::{path::PathBuf, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}, time::Duration};
use teamspeach_core::{audio::CapturedFrame, protocol::{Command, ErrorCode}, vad::GateMode};
use teamspeach_native::app::connections::{ConnectionError, ConnectionEvent, ConnectionManager, InputConfiguration, SessionKey};
static NEXT: AtomicU64 = AtomicU64::new(0);
struct Profile(PathBuf);
impl Profile {
fn new() -> Self {
Self(std::env::temp_dir().join(format!("teamspeach-manager-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))))
}
}
impl Drop for Profile { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } }
#[derive(Default)]
struct Observed {
profiles: Vec<(SessionKey, String, String)>,
failures: Vec<String>,
callback_threads: Vec<std::thread::ThreadId>,
}
fn manager(profile: &Profile) -> (ConnectionManager, Arc<Mutex<Observed>>) {
let events = Arc::new(Mutex::new(Observed::default()));
let observed = events.clone();
let manager = ConnectionManager::start(profile.0.clone(), Arc::new(move |event| {
let mut observed = observed.lock().unwrap();
observed.callback_threads.push(std::thread::current().id());
match event {
ConnectionEvent::Control { key, value } if value["event"] == "profile" => {
observed.profiles.push((key, value["uid"].as_str().unwrap().into(), value["nickname"].as_str().unwrap().into()));
}
ConnectionEvent::Failure { error, .. } => observed.failures.push(error.to_string()),
_ => {}
}
})).unwrap();
(manager, events)
}
#[tokio::test(flavor = "current_thread")]
async fn two_offline_cores_share_identity_and_drain_events_without_ui_reads() {
tokio::time::timeout(Duration::from_secs(60), async {
let profile = Profile::new();
let (manager, events) = manager(&profile);
// The watch receiver is intentionally never polled. It must not backpressure services.
let _stalled_ui = manager.subscribe();
let first = manager.create().await.unwrap();
let second = manager.create().await.unwrap();
let created = manager.request(&first, Command::ProfileCreate { nickname: "Native owner".into() }).await.unwrap();
let uid = created["uid"].as_str().unwrap();
assert_eq!(manager.request(&second, Command::ProfileGet).await.unwrap()["uid"], uid);
// More events than a core's control queue: a demand-driven manager would disconnect here.
for i in 0..1030 {
let key = if i % 2 == 0 { &first } else { &second };
manager.request(key, Command::Rename { nickname: format!("Native {i}") }).await.unwrap();
}
{
let observed = events.lock().unwrap();
assert_eq!(observed.profiles.len(), 1031);
assert!(observed.profiles.iter().all(|(_, actual, _)| actual == uid));
assert!(observed.profiles.iter().any(|(key, _, _)| key.connection_id == first.connection_id));
assert!(observed.profiles.iter().any(|(key, _, _)| key.connection_id == second.connection_id));
assert!(observed.callback_threads.iter().all(|thread| *thread != std::thread::current().id()));
assert!(observed.failures.is_empty(), "{:?}", observed.failures);
}
assert_eq!(manager.request(&first, Command::ProfileGet).await.unwrap()["nickname"], "Native 1029");
manager.shutdown().await.unwrap();
for slot in [1, 2] {
let slot = profile.0.join("connections").join(slot.to_string());
assert!(!slot.join("identity.json").exists());
assert!(!slot.join("identities.json").exists());
}
// Explicit shutdown joined cores and released shared profile/slot locks.
let (again, _) = self::manager(&profile);
let key = again.create().await.unwrap();
assert_eq!(again.request(&key, Command::ProfileGet).await.unwrap()["uid"], uid);
again.shutdown().await.unwrap();
}).await.expect("offline manager must not depend on rendering");
}
#[tokio::test(flavor = "current_thread")]
async fn restart_invalidates_keys_and_keeps_other_identity_live() {
let profile = Profile::new();
let (manager, _) = manager(&profile);
let first = manager.create().await.unwrap();
let second = manager.create().await.unwrap();
let uid = manager.request(&first, Command::ProfileCreate { nickname: "Restart owner".into() }).await.unwrap()["uid"].clone();
let mut current = first.clone();
for _ in 0..10 {
current = manager.restart(&current).await.unwrap();
assert!(matches!(manager.request(&first, Command::ProfileGet).await, Err(ConnectionError::TargetChanged)));
assert_eq!(manager.request(&second, Command::ProfileGet).await.unwrap()["uid"], uid);
}
assert_eq!(current.connection_id, first.connection_id);
assert_eq!(current.session, first.session + 10);
let mut invalid = current.clone();
invalid.generation += 1;
assert!(matches!(manager.view(&invalid).await, Err(ConnectionError::TargetChanged)));
assert!(matches!(manager.set_input(Some(&invalid), InputConfiguration::default()).await, Err(ConnectionError::TargetChanged)));
assert_eq!(manager.snapshot().viewed_id.as_deref(), Some(first.connection_id.as_str()));
manager.shutdown().await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn tab_order_slot_reuse_and_last_tab_are_not_lexical() {
let profile = Profile::new();
let (manager, _) = manager(&profile);
let first = manager.create().await.unwrap();
let second = manager.create().await.unwrap();
let third = manager.create().await.unwrap();
manager.view(&second).await.unwrap();
assert_eq!(manager.snapshot().input_id.as_deref(), Some(first.connection_id.as_str()));
manager.close(&second).await.unwrap();
assert_eq!(manager.snapshot().viewed_id.as_deref(), Some(third.connection_id.as_str()));
let mut temporary = manager.create().await.unwrap();
assert_eq!(manager.snapshot().get(&temporary.connection_id).unwrap().slot, 2);
while temporary.connection_id != "c10" {
manager.close(&temporary).await.unwrap();
temporary = manager.create().await.unwrap();
}
manager.view(&first).await.unwrap();
manager.close(&first).await.unwrap();
assert_eq!(manager.snapshot().viewed_id.as_deref(), Some("c3"));
assert_eq!(manager.snapshot().connections.iter().map(|entry| entry.key.connection_id.as_str()).collect::<Vec<_>>(), vec!["c3", "c10"]);
assert!(matches!(manager.request(&second, Command::ProfileGet).await, Err(ConnectionError::Closed)));
manager.close(&third).await.unwrap();
assert!(matches!(manager.close(&temporary).await, Err(ConnectionError::LastConnection)));
for _ in 1..8 { manager.create().await.unwrap(); }
assert!(matches!(manager.create().await, Err(ConnectionError::TooManyConnections)));
manager.shutdown().await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn offline_input_waits_for_real_validation_and_never_grants_capture() {
let profile = Profile::new();
let (manager, events) = manager(&profile);
let key = manager.create().await.unwrap();
let invalid = InputConfiguration { vad: Some(GateMode::VolumeGate { level_db: f32::NAN }), ..Default::default() };
assert!(matches!(manager.set_input(Some(&key), invalid).await,
Err(ConnectionError::Core(error)) if error.code == ErrorCode::BadRequest));
assert!(manager.snapshot().capture.is_none());
assert!(manager.set_input(Some(&key), InputConfiguration::default()).await.unwrap().is_none());
assert!(events.lock().unwrap().callback_threads.len() > 0);
assert_eq!(manager.push_audio(&key, CapturedFrame { pcm: [1; 960], captured_at: std::time::Instant::now(),
connection_generation: key.generation, capture_epoch: 1, whisper: None }), teamspeach_native::app::connections::CaptureIngress::PermitRevoked);
manager.invalidate_audio();
manager.shutdown().await.unwrap();
}