From a451f027f3b9ade16b363e6a60509f5106b6e409 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 24 Oct 2026 06:17:16 +0300 Subject: [PATCH] Give the myTeamSpeak account to the TeamSpeak connector, not to the engine Command::SetMytsIdentity and SetMytsData are gone (nothing sent them): the account's proof and what servers are shown of it belong to TeamSpeak, and the engine only forwarded two watch channels through every session to the link's context. TsConnector is public now, with set_myts_identity and set_myts_data; it owns the senders (shared by its clones through its TsLink) and each connection holds them for as long as it runs, so a session outlives its connector as it outlived the engine's loop. Backends::register_teamspeak takes a connector whose clone the application keeps, and Backends::default registers one of its own. LinkCtx, LocalCtx, SessionHandle and Session lose the watches, and the test of the standalone context's senders is a test of the account's: a connection keeps it open. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-core/src/lib.rs | 40 +---- crates/voelin-core/src/link/backends.rs | 32 ++-- crates/voelin-core/src/link/mod.rs | 12 +- crates/voelin-core/src/link/tests.rs | 15 -- crates/voelin-core/src/session.rs | 38 +---- crates/voelin-core/src/ts/mod.rs | 1 + crates/voelin-core/src/ts/ts_link.rs | 161 +++++++++++++++++++- crates/voelin-core/src/ts/ts_session/mod.rs | 54 +++++-- crates/voelin-core/src/ts/voice.rs | 29 ++-- 9 files changed, 242 insertions(+), 140 deletions(-) diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 59343bb..c662c9a 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -72,7 +72,7 @@ use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; -use tokio::sync::{broadcast, mpsc, watch}; +use tokio::sync::{broadcast, mpsc}; pub use voelin_audio::settings::TransmitMode; pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings}; use voelin_model::{ @@ -112,13 +112,6 @@ pub const POKE_MESSAGE_MAX: usize = 100; /// What the UI asks for. #[derive(Clone, Debug)] pub enum Command { - /// Main account proof for every current and future voice connection. - SetMytsIdentity(Option>), - /// What voice servers are shown of the main account (its avatar and - /// badges with their certificates, its User Tag; TeamSpeak 6): sent to - /// every connection that presents the account's myTS ID, once connected - /// and when it changes; cleared on a sign-out. - SetMytsData(Option>), ConnectVoice { session: SessionId, options: Box, @@ -918,8 +911,6 @@ async fn run( // Before any command: a contact set meanwhile would be lost. contacts.load().await; let mut sessions: HashMap = HashMap::new(); - let (myts_identity, _) = watch::channel(None); - let (myts_data, _) = watch::channel(None); let mut current = shared.current(); // Pruning: at start, then hourly (and when the setting changes). let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600)); @@ -964,29 +955,6 @@ async fn run( }, }; let id = match command { - Command::SetMytsIdentity(identity) => { - // Still no account is no change: every notification restarts - // handshakes and sends `updatemytsid` on every connection. Any - // account is (each connection's proof is signed anew). - myts_identity.send_if_modified(|current| { - if current.is_none() && identity.is_none() { - return false; - } - *current = identity; - true - }); - continue; - } - Command::SetMytsData(data) => { - myts_data.send_if_modified(|current| { - if *current == data { - return false; - } - *current = data; - true - }); - continue; - } Command::SetAudioSettings(new) => { settings = (*new).clone(); for s in sessions.values() { @@ -1063,8 +1031,6 @@ async fn run( settings.clone(), engine.clone(), link.clone(), - myts_identity.subscribe(), - myts_data.subscribe(), ); if let Some(profiles) = &srtp_profiles { s.send(Command::SetSrtpProfiles(profiles.clone())); @@ -1143,9 +1109,7 @@ fn command_session(command: &Command) -> SessionId { | Command::DeleteOfflineMessage { session, .. } | Command::SetOfflineMessageRead { session, .. } | Command::CloseSession { session } => *session, - Command::SetMytsIdentity(_) - | Command::SetMytsData(_) - | Command::SetAudioSettings(_) + Command::SetAudioSettings(_) | Command::SetSrtpProfiles(_) | Command::TestMicrophone { .. } | Command::SetSetting { .. } diff --git a/crates/voelin-core/src/link/backends.rs b/crates/voelin-core/src/link/backends.rs index 2a30874..afabc1d 100644 --- a/crates/voelin-core/src/link/backends.rs +++ b/crates/voelin-core/src/link/backends.rs @@ -10,7 +10,7 @@ use std::sync::Arc; -use tokio::sync::{mpsc, watch}; +use tokio::sync::mpsc; use voelin_proto::link::{ AccountAgent, BoxFuture, ConnectParams, Connected, Connector, Connectors, HostIdentity, HostTrust, SessionError, @@ -19,6 +19,7 @@ use voelin_stream::PeerConfig; use super::LinkCtx; use crate::stream::{OwnStreamEvent, StreamCmd}; +use crate::ts::TsConnector; /// The scheme of the TeamSpeak servers a bookmark names without one. pub(crate) const TEAMSPEAK_SCHEME: &str = "ts3server"; @@ -63,19 +64,17 @@ impl StreamPort { #[derive(Clone)] pub(crate) struct LocalCtx { /// The session's side of the engine: its id, event bus, frames and - /// settings, and the account proof watches. + /// settings. pub(crate) link: LinkCtx, /// Open the audio devices (the stream task plays what streams carry). pub(crate) audio: bool, /// Network settings for stream peer connections. pub(crate) stream_peer: PeerConfig, - /// Keeps the senders of `link`'s watches alive when there is no engine. - _keep: Option>, } impl LocalCtx { pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self { - Self { link, audio, stream_peer, _keep: None } + Self { link, audio, stream_peer } } /// A context for a connection made outside an engine (a test or a tool @@ -84,22 +83,13 @@ impl LocalCtx { pub(crate) fn standalone() -> Self { let (events, _) = tokio::sync::broadcast::channel(16); let (frames, _) = tokio::sync::broadcast::channel(16); - let (identity_tx, myts_identity) = watch::channel(None); - let (data_tx, myts_data) = watch::channel(None); let link = LinkCtx { session: 0, events, frames, settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()), - myts_identity, - myts_data, }; - Self { - link, - audio: false, - stream_peer: PeerConfig::default(), - _keep: Some(Arc::new((identity_tx, data_tx))), - } + Self { link, audio: false, stream_peer: PeerConfig::default() } } } @@ -146,7 +136,7 @@ impl Default for Backends { /// `teamspeak://`, and an address without a scheme). fn default() -> Self { let mut backends = Self::empty(); - backends.register_local(Arc::new(crate::ts::ts_session::TsConnector::new())); + backends.register_teamspeak(TsConnector::new()); backends } } @@ -166,6 +156,16 @@ impl Backends { self.locals.push(connector); } + /// Register the TeamSpeak connector for the schemes it names + /// (`ts3server`, `teamspeak`, and addresses without a scheme). + /// [`Backends::default`] registers one of its own; register yours to keep a + /// clone of it, whose [`TsConnector::set_myts_identity`] and + /// [`TsConnector::set_myts_data`] set the main myTeamSpeak account for every + /// connection it makes. + pub fn register_teamspeak(&mut self, connector: TsConnector) { + self.register_local(Arc::new(connector)); + } + /// The device's Voelin account, for the connectors that use it (the QUIC /// connector's certificate, the TeamSpeak connector's myTS ID proof). /// None is the default: nothing uses an account yet. diff --git a/crates/voelin-core/src/link/mod.rs b/crates/voelin-core/src/link/mod.rs index 1acbd29..d617dc8 100644 --- a/crates/voelin-core/src/link/mod.rs +++ b/crates/voelin-core/src/link/mod.rs @@ -84,9 +84,9 @@ //! and changes when the TeamSpeak side leaves: //! //! - Types of the TeamSpeak crates: [`ConnectOptions::identity`] and -//! [`ConnectOptions::client_version`] (`tsclientlib`), and the account -//! proof in [`LinkCtx`] (`myts_identity` of `tsproto`, `myts_data` of -//! `tsclientlib`). +//! [`ConnectOptions::client_version`] (`tsclientlib`). The account proof is +//! no part of the link's context: [`TsConnector`](crate::ts::TsConnector) +//! keeps it. //! - Client ids are TeamSpeak's `u16`: `own_client` of //! [`LinkEvent::Connected`], `from` of [`LinkEvent::Poke`], `client` of //! [`LinkEvent::Talking`] and of [`LinkCmd::Poke`], the `author_id` of a @@ -122,7 +122,7 @@ use std::pin::Pin; use std::sync::Arc; use tokio::io::{AsyncRead, AsyncWrite}; -use tokio::sync::{broadcast, mpsc, oneshot, watch}; +use tokio::sync::{broadcast, mpsc, oneshot}; use voelin_audio::{EncodedVoice, VoicePacket}; use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence}; use voelin_stream::PeerConfig; @@ -199,10 +199,6 @@ pub struct LinkCtx { /// The frames of watched streams (kept off the event bus). pub(crate) frames: broadcast::Sender, pub(crate) settings: SharedSettings, - /// The main account's proof, for every connection ([`crate::Command::SetMytsIdentity`]). - pub(crate) myts_identity: watch::Receiver>>, - /// What the server is shown of the account ([`crate::Command::SetMytsData`]). - pub(crate) myts_data: watch::Receiver>>, } impl LinkCtx { diff --git a/crates/voelin-core/src/link/tests.rs b/crates/voelin-core/src/link/tests.rs index dd6a17d..54d673e 100644 --- a/crates/voelin-core/src/link/tests.rs +++ b/crates/voelin-core/src/link/tests.rs @@ -1308,21 +1308,6 @@ async fn a_session_closes_as_the_table_says() { assert!(matches!(error, SessionError::Closed(_)), "{error:?}"); } -/// A session made through the plain `Connector` interface, outside an engine -/// (the conformance suite does, so does any client of the seam that is no -/// engine), has no engine to hold the account watches the link listens to: -/// the session keeps their senders for as long as it runs. The link ends its -/// connection with "account source closed" when it has lost them. -#[tokio::test(flavor = "multi_thread")] -async fn a_session_made_outside_an_engine_keeps_the_watches_of_its_link_open() { - let (session, _pushes, inner) = open(everything()).await; - // Let the driver start, and the connect that returned drop what it held. - tokio::time::sleep(Duration::from_millis(50)).await; - assert!(inner.ctx.myts_identity.has_changed().is_ok(), "the identity watch lost its sender"); - assert!(inner.ctx.myts_data.has_changed().is_ok(), "the data watch lost its sender"); - drop(session); -} - #[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(); diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 5658df9..a9f2919 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -78,7 +78,6 @@ pub(crate) struct SessionHandle { } impl SessionHandle { - #[allow(clippy::too_many_arguments)] // what the engine hands each session pub fn spawn( id: SessionId, events: broadcast::Sender, @@ -86,23 +85,9 @@ impl SessionHandle { audio_settings: AudioSettings, shared: Shared, link: Arc, - myts_identity: watch::Receiver>>, - myts_data: watch::Receiver>>, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); - tokio::spawn( - Session::new( - id, - events, - frames, - audio_settings, - shared, - link, - myts_identity, - myts_data, - ) - .run(rx), - ); + tokio::spawn(Session::new(id, events, frames, audio_settings, shared, link).run(rx)); Self { tx } } @@ -299,8 +284,6 @@ struct OwnStream { struct Session { /// Starts the voice connections. link: Arc, - myts_identity: watch::Receiver>>, - myts_data: watch::Receiver>>, id: SessionId, events: broadcast::Sender, state: SessionState, @@ -386,7 +369,6 @@ struct Session { } impl Session { - #[allow(clippy::too_many_arguments)] // what the engine hands each session fn new( id: SessionId, events: broadcast::Sender, @@ -394,16 +376,12 @@ impl Session { audio_settings: AudioSettings, shared: Shared, link: Arc, - myts_identity: watch::Receiver>>, - myts_data: watch::Receiver>>, ) -> Self { let (sources_tx, sources_rx) = mpsc::unbounded_channel(); let Shared { settings, history, cache, contacts } = shared; let contacts_rx = Some(contacts.watch()); Self { link, - myts_identity, - myts_data, cache, contacts, contacts_rx, @@ -546,8 +524,6 @@ impl Session { events: self.events.clone(), frames: self.frames.clone(), settings: self.settings.clone(), - myts_identity: self.myts_identity.clone(), - myts_data: self.myts_data.clone(), }; self.link.spawn(options, ctx, cmd_rx, ev_tx); self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e)); @@ -873,9 +849,7 @@ impl Session { self.voice_request(Some(request), LinkCmd::OfflineFlag { request, id, read }); } // Engine-wide. - Command::SetMytsIdentity(_) - | Command::SetMytsData(_) - | Command::CloseSession { .. } + Command::CloseSession { .. } | Command::TestMicrophone { .. } | Command::SetSetting { .. } | Command::ResetSetting { .. } @@ -2276,19 +2250,13 @@ mod banner_tests { cache: SharedCache::new(Cache::new(dir)), contacts: Contacts::new(events.clone(), history), }; - // No myTeamSpeak account; its source stays open, as the engine's does - // (a closed one ends voice connections). - let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe(); - let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe(); let session = Session::new( 1, events, frames, AudioSettings::default(), shared, - Arc::new(crate::TsLink), - myts_identity, - myts_data, + Arc::new(crate::TsLink::new()), ); (session, receiver) } diff --git a/crates/voelin-core/src/ts/mod.rs b/crates/voelin-core/src/ts/mod.rs index f91b271..cdbd450 100644 --- a/crates/voelin-core/src/ts/mod.rs +++ b/crates/voelin-core/src/ts/mod.rs @@ -27,3 +27,4 @@ pub mod versions; mod voice; pub use ts_link::TsLink; +pub use ts_session::TsConnector; diff --git a/crates/voelin-core/src/ts/ts_link.rs b/crates/voelin-core/src/ts/ts_link.rs index 0b5dae7..69d0185 100644 --- a/crates/voelin-core/src/ts/ts_link.rs +++ b/crates/voelin-core/src/ts/ts_link.rs @@ -12,14 +12,108 @@ //! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts` //! of VoelinGateWay. -use tokio::sync::mpsc; +use std::sync::Arc; + +use tokio::sync::{mpsc, watch}; use super::voice; use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink}; +/// The main myTeamSpeak account of an application, as its connections show +/// it to the servers: the proof of the myTS ID, and what servers are shown +/// of it (its avatar and badges with their certificates, its User Tag). +/// +/// The senders live here, one pair for every connection of a [`TsLink`]; each +/// connection watches the pair through [`Watches`], presents the account it +/// finds when it connects, and follows the changes. +pub(crate) struct Account { + identity: watch::Sender>>, + data: watch::Sender>>, +} + +impl Default for Account { + /// No account is signed in. + fn default() -> Self { + Self { identity: watch::Sender::new(None), data: watch::Sender::new(None) } + } +} + +impl Account { + /// The account proof for every current and future connection. Still no + /// account is no change: every notification restarts the handshakes and + /// sends `updatemytsid` on every connection. Any account is (each + /// connection's proof is signed anew). + pub(crate) fn set_identity(&self, identity: Option>) { + self.identity.send_if_modified(|current| { + if current.is_none() && identity.is_none() { + return false; + } + *current = identity; + true + }); + } + + /// What the servers are shown of the account: sent to every connection + /// that presents the account's myTS ID, once connected and when it + /// changes; cleared on a sign-out. The same data is no change. + pub(crate) fn set_data(&self, data: Option>) { + self.data.send_if_modified(|current| { + if *current == data { + return false; + } + *current = data; + true + }); + } + + /// What one connection watches. It keeps the senders alive for as long as + /// it runs: a connection ends with "account source closed" when its + /// watches have lost them, so the account outlives the connector that + /// made the connection. + pub(crate) fn watches(self: &Arc) -> Watches { + Watches { + identity: self.identity.subscribe(), + data: self.data.subscribe(), + _keep: Some(self.clone()), + } + } +} + +/// The account a connection presents and follows ([`Account::watches`]). +pub(crate) struct Watches { + pub(super) identity: watch::Receiver>>, + pub(super) data: watch::Receiver>>, + _keep: Option>, +} + +impl Watches { + /// Watches of senders that someone else keeps (a test's). + #[cfg(test)] + pub(super) fn of( + identity: watch::Receiver>>, + data: watch::Receiver>>, + ) -> Self { + Self { identity, data, _keep: None } + } +} + /// Connects to TeamSpeak 3 and 6 servers. The engine's default link. -#[derive(Clone, Copy, Debug, Default)] -pub struct TsLink; +#[derive(Clone, Default)] +pub struct TsLink { + account: Arc, +} + +impl TsLink { + /// A link that presents no account until it is given one. + pub(crate) fn new() -> Self { + Self::default() + } + + /// The account the link's connections present. + pub(crate) fn account(&self) -> &Arc { + &self.account + } +} impl ServerLink for TsLink { fn spawn( @@ -29,6 +123,65 @@ impl ServerLink for TsLink { cmds: mpsc::UnboundedReceiver, events: mpsc::UnboundedSender, ) { - tokio::spawn(voice::run(options, ctx, cmds, events)); + tokio::spawn(voice::run(options, ctx, self.account.watches(), cmds, events)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A myTS ID's proof (the standard Ed25519 base point as the public key). + fn identity() -> Arc { + let mut private = [0; 32]; + private[0] = 1; + let mut public = [0x66; 32]; + public[0] = 0x58; + Arc::new( + tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(), + ) + } + + /// An account sets what it holds only when it changes: every notification + /// of a watch restarts the handshake of a connection. + #[test] + fn a_watch_hears_of_a_change_and_not_of_the_same_account_again() { + let account = Arc::new(Account::default()); + let mut watches = account.watches(); + // No account, still none: nothing. + account.set_identity(None); + account.set_data(None); + assert!(!watches.identity.has_changed().unwrap()); + assert!(!watches.data.has_changed().unwrap()); + + let proof = identity(); + account.set_identity(Some(proof.clone())); + assert!(watches.identity.borrow_and_update().is_some()); + // An account again is a change (each connection signs its proof anew), the + // same data is none. + account.set_identity(Some(proof)); + assert!(watches.identity.has_changed().unwrap()); + watches.identity.borrow_and_update(); + let data = Arc::new(tsclientlib::MytsData::default()); + account.set_data(Some(data.clone())); + assert!(watches.data.has_changed().unwrap()); + watches.data.borrow_and_update(); + account.set_data(Some(Arc::new(tsclientlib::MytsData::default()))); + assert!(!watches.data.has_changed().unwrap(), "equal data is no change"); + // A sign-out is a change. + account.set_identity(None); + assert!(watches.identity.has_changed().unwrap()); + assert!(watches.identity.borrow_and_update().is_none()); + } + + /// A connection outlives the connector that made it (a session handed out + /// by a connector that was dropped): its watches keep their senders. + #[test] + fn a_connection_keeps_the_account_open_when_its_link_is_gone() { + let link = TsLink::new(); + let watches = link.account().watches(); + drop(link); + assert!(watches.identity.has_changed().is_ok(), "the identity watch lost its sender"); + assert!(watches.data.has_changed().is_ok(), "the data watch lost its sender"); } } diff --git a/crates/voelin-core/src/ts/ts_session/mod.rs b/crates/voelin-core/src/ts/ts_session/mod.rs index 34ab9b4..ea95971 100644 --- a/crates/voelin-core/src/ts/ts_session/mod.rs +++ b/crates/voelin-core/src/ts/ts_session/mod.rs @@ -517,22 +517,55 @@ impl LocalConnector for LinkConnector { /// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`) /// with `tsclientlib`: [`LinkSession`]s over [`TsLink`]. +/// +/// Clones share one account: the main myTeamSpeak account that every +/// connection of the connector presents ([`TsConnector::set_myts_identity`], +/// [`TsConnector::set_myts_data`]), also those made before it was set. +/// Register a connector in the engine's registry with +/// [`Backends::register_teamspeak`] and keep a clone to set the account. #[derive(Clone)] -pub(crate) struct TsConnector(LinkConnector); +pub struct TsConnector { + connector: LinkConnector, + link: Arc, +} + +impl Default for TsConnector { + fn default() -> Self { + Self::new() + } +} impl TsConnector { - pub(crate) fn new() -> Self { - Self(LinkConnector::new(Arc::new(TsLink), &["ts3server", "teamspeak"])) + /// A connector that presents no account until it is given one. + pub fn new() -> Self { + let link = Arc::new(TsLink::new()); + Self { connector: LinkConnector::new(link.clone(), &["ts3server", "teamspeak"]), link } + } + + /// The main account's proof for every current and future connection of + /// this connector (and its clones): a myTS ID signed with the account's + /// key. Connections that are up show the server the new proof, and those + /// that connect later present it from the start; `None` is a sign-out. + pub fn set_myts_identity(&self, identity: Option>) { + self.link.account().set_identity(identity); + } + + /// What servers are shown of the main account: its avatar and badges with + /// their certificates, its User Tag (TeamSpeak 6). It is sent to every + /// connection that presents the account's myTS ID, once connected and when + /// it changes; cleared on a sign-out (`None`). + pub fn set_myts_data(&self, data: Option>) { + self.link.account().set_data(data); } } impl Connector for TsConnector { fn schemes(&self) -> &'static [&'static str] { - self.0.schemes() + self.connector.schemes() } fn connect(&self, params: ConnectParams) -> BoxFuture> { - self.0.connect(params) + self.connector.connect(params) } } @@ -542,7 +575,7 @@ impl LocalConnector for TsConnector { params: ConnectParams, ctx: LocalCtx, ) -> BoxFuture> { - self.0.connect_local(params, ctx) + self.connector.connect_local(params, ctx) } } @@ -706,14 +739,7 @@ async fn connect_link( closed: closed_rx, own_slot, }; - tokio::spawn(async move { - driver.run(cmds_rx).await; - // The context keeps the senders of the account watches that a connection - // made outside an engine has (`LocalCtx::standalone`): the link ends its - // connection when a watch has no sender, so the context lives as long as - // the session does. - drop(ctx); - }); + tokio::spawn(driver.run(cmds_rx)); Ok(LocalConnected { connected: Connected { session: Arc::new(session), diff --git a/crates/voelin-core/src/ts/voice.rs b/crates/voelin-core/src/ts/voice.rs index b6b7055..645f87a 100644 --- a/crates/voelin-core/src/ts/voice.rs +++ b/crates/voelin-core/src/ts/voice.rs @@ -37,6 +37,7 @@ use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, ServerFlavo use voelin_stream::{ClientState, Request, StreamNotification}; use super::book::presence_from_book; +use super::ts_link::Watches; use crate::cache::{self, IMAGE_NEGOTIATION, image_download_time}; use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState}; use crate::link::{BoxDuplex, BoxRead, ConnectOptions, LinkCmd, LinkCtx, LinkEvent, Remote}; @@ -236,10 +237,11 @@ enum Slot { pub(crate) async fn run( options: ConnectOptions, ctx: LinkCtx, + account: Watches, mut commands: mpsc::UnboundedReceiver, events: mpsc::UnboundedSender, ) { - let reason = match run_inner(&options, ctx, &mut commands, &events).await { + let reason = match run_inner(&options, ctx, account, &mut commands, &events).await { Ok(()) => None, Err(e) => Some(e.to_string()), }; @@ -269,6 +271,8 @@ impl Drop for ConnectionStreams { struct Voice { con: Connection, link: LinkCtx, + /// The account this connection presents (and keeps open). + account: Watches, events: mpsc::UnboundedSender, server_uid: String, /// Who is talking: last voice packet per client. @@ -291,6 +295,7 @@ struct Voice { async fn run_inner( options: &ConnectOptions, link: LinkCtx, + account: Watches, commands: &mut mpsc::UnboundedReceiver, events: &mpsc::UnboundedSender, ) -> anyhow::Result<()> { @@ -317,8 +322,8 @@ async fn run_inner( if let Some(token) = &options.token { builder = builder.default_token(token.clone()); } - let mut identity = link.myts_identity.clone(); - let mut data = link.myts_data.clone(); + let mut identity = account.identity.clone(); + let mut data = account.data.clone(); // A changed account invalidates an in-flight handshake. Drop that connection // and take a fresh snapshot before publishing any connected state. let mut con = timeout(Duration::from_secs(30), async { @@ -400,6 +405,7 @@ async fn run_inner( let mut voice = Voice { con, link, + account, events: events.clone(), server_uid, talking: HashMap::new(), @@ -897,8 +903,8 @@ impl Voice { /// gave, when it is for the myTS ID this connection presents; nothing /// without one (signed out). fn myts_wanted(&self) -> tsclientlib::MytsData { - let identity = self.link.myts_identity.borrow(); - let data = self.link.myts_data.borrow(); + let identity = self.account.identity.borrow(); + let data = self.account.data.borrow(); match (identity.as_deref(), data.as_deref()) { (Some(identity), Some(data)) if data.myts_id == identity.id_bytes() => data.clone(), _ => tsclientlib::MytsData::default(), @@ -1732,12 +1738,15 @@ mod account_tests { events, frames: broadcast::channel(1).0, settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()), - myts_identity: watch::channel(Some(Arc::new(identity))).1, - myts_data: watch::channel(Some(Arc::new(data))).1, }; + let account = Watches::of( + watch::channel(Some(Arc::new(identity))).1, + watch::channel(Some(Arc::new(data))).1, + ); Voice { con: Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap(), link, + account, events: mpsc::unbounded_channel().0, server_uid: String::new(), talking: HashMap::new(), @@ -1785,7 +1794,7 @@ mod account_tests { let other = unconnected(&server, account_data(&[2; 33])); assert_eq!(other.myts_wanted(), tsclientlib::MytsData::default()); let mut signed_out = unconnected(&server, account_data(&[1; 33])); - signed_out.link.myts_identity = watch::channel(None).1; + signed_out.account.identity = watch::channel(None).1; assert_eq!(signed_out.myts_wanted(), tsclientlib::MytsData::default()); for voice in [voice, other, signed_out] { timeout(Duration::from_millis(100), shutdown_connection(voice.con)) @@ -1820,14 +1829,14 @@ mod account_tests { events, frames: broadcast::channel(1).0, settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()), - myts_identity: identity, - myts_data: watch::channel(None).1, }; + let watches = Watches::of(identity, watch::channel(None).1); let (_commands, commands) = mpsc::unbounded_channel(); let (events, mut received) = mpsc::unbounded_channel(); let task = tokio::spawn(run( ConnectOptions::new(server.local_addr().unwrap().to_string(), "account-test"), link, + watches, commands, events, ));