Make the TeamSpeak session keep up with a lagging consumer, a reconnect and the contract
The task behind LinkSession (ts_session/driver.rs) is where the review found
five defects, all fixed here:
- It awaited pushes.send() on the bounded push channel, so a consumer that
lagged stalled the voice media and the commands that share the task. It now
never waits: a push that finds the channel full is dropped, its scope is
marked as lagged and sent again whole (SyncBegin .. SyncEnd, all frames or
none) once the channel has room, as ConnectParams.push_capacity documents; a
signal has no scope and is dropped. The functions that only awaited the push
are plain functions now.
- The own client id was the one of the connect for the whole connection, so
after tsclientlib's own reconnect (a new client id, the same unique id) the
own channel, the poke target, the own VoiceState, the author of our messages
and the slot send_media checks were all the old client's. The task now follows
the snapshots: it stays the client it was while that client is there, and
else is the newest client of its unique id; the own client keeps the database
id when an identity is there twice (entities::build), so the user stays the
same; LinkSession.send_media reads the slot from a shared atomic.
- CHAT subscriptions were limited to 16 in process, so private messages from
the 15th peer of a connection were never delivered. The limit is 65,536
(Welcome.limits says so, and the total of subscriptions follows).
- notify accepted List, FileRead and FileWrite and ignored them. Only an op of
the control stream goes without an answer now (a misplaced op is a Protocol
error, as on FakeSession); our mute flags go to the link, and any other op is
run as the request it is. A notify on a session that has closed is refused
also while the task is still on its way out.
- The link's own Talking was dropped, so a talker whose packets TsLink does not
forward as Opus (Speex, CELT) was no longer shown as talking. It goes on as a
Signal{speaking} hint.
The assertion of the Welcome test on the limit follows. The engine side of the
reconnect, the limit and the hint is the next commit.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
080d8873bb
commit
4ddfdef04f
4 files changed
+308
-95
No files matched your search
@@ -1029,7 +1029,9 @@ async fn the_welcome_names_the_host_the_user_and_what_the_link_can_do() {
|
||||
}
|
||||
assert!(!features.has("voice.whisper") && !features.has("chat.typing"));
|
||||
let limits = welcome.limits.as_ref().unwrap();
|
||||
assert_eq!(limits.max_chat_subscriptions, 16);
|
||||
// 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;
|
||||
|
||||
@@ -10,13 +10,15 @@
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tokio::sync::mpsc::error::TrySendError;
|
||||
use tokio::sync::{broadcast, mpsc, oneshot, watch};
|
||||
use tracing::warn;
|
||||
use tracing::{debug, warn};
|
||||
use voelin_audio::EncodedVoice;
|
||||
use voelin_model::replica::{Key, ScopeId};
|
||||
use voelin_model::{ChatMessage, ChatTarget, Presence};
|
||||
use voelin_model::{ChatMessage, ChatTarget, ClientInfo, Presence};
|
||||
use voelin_proto::link::{CloseReason, Download, MediaSink, SessionError, Upload};
|
||||
use voelin_proto::v1::{
|
||||
self, Entity, ErrorCode, entity::Kind, push::Body, request::Op, response::Result as Answer,
|
||||
@@ -41,8 +43,11 @@ const MOVE_TIME: Duration = Duration::from_secs(10);
|
||||
const WINDOW: usize = 50;
|
||||
/// Entities in one `Change` frame of a sync.
|
||||
const SYNC_CHUNK: usize = 256;
|
||||
/// Most CHAT scopes at once (`Limits.max_chat_subscriptions`).
|
||||
pub(super) const MAX_CHAT_SUBSCRIPTIONS: u32 = 16;
|
||||
/// Most CHAT scopes at once (`Limits.max_chat_subscriptions`). The engine
|
||||
/// subscribes the server chat, the channel it is in and one per private
|
||||
/// conversation of the connection, so this is no limit anything reaches: far
|
||||
/// more than there are clients (a client id is 16 bits).
|
||||
pub(super) const MAX_CHAT_SUBSCRIPTIONS: u32 = 1 << 16;
|
||||
/// How long what the stream task reports waits for the engine to have
|
||||
/// announced the connection (see [`Held`]).
|
||||
#[cfg(not(test))]
|
||||
@@ -67,6 +72,8 @@ pub(super) enum Cmd {
|
||||
/// What the connection is, as the link told it.
|
||||
pub(super) struct Config {
|
||||
pub ts6: bool,
|
||||
/// The client id the link named when it connected. We are another client
|
||||
/// after TeamSpeak's own reconnect: see [`Driver::follow_own_client`].
|
||||
pub own_client: u16,
|
||||
pub nickname: String,
|
||||
pub own_uid: Option<String>,
|
||||
@@ -88,6 +95,9 @@ pub(super) struct Parts {
|
||||
pub media: Arc<dyn MediaSink>,
|
||||
pub port: Option<mpsc::UnboundedSender<StreamEvent>>,
|
||||
pub closed: watch::Sender<Option<CloseReason>>,
|
||||
/// The media slot of our client, for the session's `send_media` to check
|
||||
/// (it follows [`Driver::follow_own_client`]).
|
||||
pub own_slot: Arc<AtomicU32>,
|
||||
/// The `Server` entity made of the link's `Connected`.
|
||||
pub server: v1::Server,
|
||||
pub epoch: u64,
|
||||
@@ -150,6 +160,13 @@ pub(super) struct Driver {
|
||||
closing: Option<CloseReason>,
|
||||
/// The receiver of the pushes is gone: nobody is listening any more.
|
||||
gone: bool,
|
||||
/// The client we are in the snapshots (see [`Driver::follow_own_client`]).
|
||||
own_client: u16,
|
||||
own_slot: Arc<AtomicU32>,
|
||||
/// Subscribed scopes whose pushes were dropped because the consumer lags
|
||||
/// (the push channel was full): each is sent again in full as soon as
|
||||
/// the channel has room for it (`ConnectParams.push_capacity`).
|
||||
lagged: HashSet<ScopeId>,
|
||||
|
||||
epoch: u64,
|
||||
rev: u64,
|
||||
@@ -244,9 +261,11 @@ impl Driver {
|
||||
media,
|
||||
port,
|
||||
closed,
|
||||
own_slot,
|
||||
server,
|
||||
epoch,
|
||||
} = parts;
|
||||
let own_client = cfg.own_client;
|
||||
let mut server_layer = Layer::new();
|
||||
let server_entity = entity(Kind::Server(server));
|
||||
if let Some(key) = Key::of(&server_entity) {
|
||||
@@ -281,6 +300,9 @@ impl Driver {
|
||||
closed,
|
||||
closing: None,
|
||||
gone: false,
|
||||
own_client,
|
||||
own_slot,
|
||||
lagged: HashSet::new(),
|
||||
epoch,
|
||||
rev: 1,
|
||||
subs: HashSet::new(),
|
||||
@@ -322,13 +344,13 @@ impl Driver {
|
||||
let mut commands_open = true;
|
||||
// What the link said before the session was handed out.
|
||||
for event in std::mem::take(&mut self.early) {
|
||||
self.event(event).await;
|
||||
self.event(event);
|
||||
}
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
cmd = cmds.recv(), if commands_open => match cmd {
|
||||
Some(cmd) => self.command(cmd).await,
|
||||
Some(cmd) => self.command(cmd),
|
||||
None => {
|
||||
// Every handle is gone: nobody can ask for the end any more.
|
||||
commands_open = false;
|
||||
@@ -340,7 +362,7 @@ impl Driver {
|
||||
self.ended(reason);
|
||||
return;
|
||||
}
|
||||
Some(event) => self.event(event).await,
|
||||
Some(event) => self.event(event),
|
||||
None => {
|
||||
self.ended(None);
|
||||
return;
|
||||
@@ -382,14 +404,75 @@ impl Driver {
|
||||
let _ = self.inner.send(cmd);
|
||||
}
|
||||
|
||||
/// A push to the session; false once nobody listens.
|
||||
async fn push(&mut self, body: Body) {
|
||||
if self.pushes.send(v1::Push { body: Some(body) }).await.is_err() {
|
||||
self.gone = true;
|
||||
/// Put a push on the channel if it has room, without waiting: this task
|
||||
/// also carries the voice media and the commands, and a consumer that
|
||||
/// lags must not stall them. `false` when the push was not put (the
|
||||
/// channel is full, or nobody listens any more, which ends the task).
|
||||
fn try_push(&mut self, push: v1::Push) -> bool {
|
||||
match self.pushes.try_send(push) {
|
||||
Ok(()) => true,
|
||||
Err(TrySendError::Full(_)) => false,
|
||||
Err(TrySendError::Closed(_)) => {
|
||||
self.gone = true;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn notice(&mut self, level: v1::NoticeLevel, text: String) {
|
||||
/// A push that belongs to no scope (a signal): there is nothing to send
|
||||
/// again later, so it is dropped when the channel is full.
|
||||
fn push_signal(&mut self, signal: v1::Signal) {
|
||||
let push = v1::Push { body: Some(Body::Signal(signal)) };
|
||||
if !self.try_push(push) && !self.gone {
|
||||
debug!("a signal was dropped: the session lags");
|
||||
}
|
||||
}
|
||||
|
||||
/// The frames of a sync (or of a change), all or none: a scope is never
|
||||
/// left half sent. When the channel has no room for all of them the scope
|
||||
/// is marked as lagged and sent again, whole, once there is room
|
||||
/// ([`Driver::retry_lagged`]).
|
||||
fn push_scope(&mut self, scope: ScopeId, frames: Vec<v1::Push>) {
|
||||
if self.gone {
|
||||
return;
|
||||
}
|
||||
if self.pushes.capacity() < frames.len() {
|
||||
self.lagged.insert(scope);
|
||||
return;
|
||||
}
|
||||
for frame in frames {
|
||||
if !self.try_push(frame) {
|
||||
// Cannot happen: this task is the only sender and the room
|
||||
// was counted. If it does, the scope is sent again.
|
||||
self.lagged.insert(scope);
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.lagged.remove(&scope);
|
||||
}
|
||||
|
||||
/// Send again, in full, the scopes whose pushes were dropped, as far as
|
||||
/// the channel has room for each (protocol section 5.7: an in-process
|
||||
/// host without a log re-syncs from its state).
|
||||
fn retry_lagged(&mut self) {
|
||||
if self.lagged.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.lagged.retain(|scope| self.subs.contains(scope));
|
||||
let mut scopes: Vec<ScopeId> = self.lagged.iter().copied().collect();
|
||||
scopes.sort_unstable();
|
||||
for scope in scopes {
|
||||
let frames = self.sync_frames(scope, None, 0);
|
||||
if self.pushes.capacity() < frames.len() {
|
||||
// Later scopes wait for this one.
|
||||
return;
|
||||
}
|
||||
debug!(?scope, frames = frames.len(), "the session lagged: the scope is sent again");
|
||||
self.push_scope(scope, frames);
|
||||
}
|
||||
}
|
||||
|
||||
fn notice(&mut self, level: v1::NoticeLevel, text: String) {
|
||||
let signal = v1::Signal {
|
||||
body: Some(SignalBody::Notice(v1::Notice {
|
||||
level: level as i32,
|
||||
@@ -399,14 +482,14 @@ impl Driver {
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(Body::Signal(signal)).await;
|
||||
self.push_signal(signal);
|
||||
}
|
||||
|
||||
// ---- commands ---------------------------------------------------------
|
||||
|
||||
async fn command(&mut self, cmd: Cmd) {
|
||||
fn command(&mut self, cmd: Cmd) {
|
||||
match cmd {
|
||||
Cmd::Request { op, reply } => self.request(op, reply).await,
|
||||
Cmd::Request { op, reply } => self.request(op, reply),
|
||||
Cmd::Notify(op) => self.notify(op),
|
||||
Cmd::Read { request, reply } => self.read(request, reply),
|
||||
Cmd::Write { request, reply } => self.write(request, reply),
|
||||
@@ -427,17 +510,18 @@ impl Driver {
|
||||
self.send_inner(LinkCmd::Disconnect);
|
||||
}
|
||||
|
||||
async fn request(&mut self, op: Op, reply: Reply) {
|
||||
fn request(&mut self, op: Op, reply: Reply) {
|
||||
let answer = match op {
|
||||
Op::Subscribe(subscribe) => self.subscribe(subscribe).await,
|
||||
Op::Subscribe(subscribe) => self.subscribe(subscribe),
|
||||
Op::Unsubscribe(unsubscribe) => {
|
||||
if let Some(scope) = unsubscribe.scope.as_ref().and_then(ScopeId::from_proto) {
|
||||
self.subs.remove(&scope);
|
||||
self.lagged.remove(&scope);
|
||||
}
|
||||
Ok(ack(self.rev))
|
||||
}
|
||||
Op::List(list) => return self.list(list, reply),
|
||||
Op::Put(put) => return self.put(put, reply).await,
|
||||
Op::Put(put) => return self.put(put, reply),
|
||||
Op::Delete(delete) => return self.delete(delete, reply),
|
||||
Op::Signal(signal) => self.signal(signal),
|
||||
Op::JoinVoice(join) => return self.join(join, reply),
|
||||
@@ -450,9 +534,21 @@ impl Driver {
|
||||
let _ = reply.send(answer);
|
||||
}
|
||||
|
||||
/// Fire and forget: our own mute flags. Everything else is ignored.
|
||||
/// Fire and forget (request id 0). Our own mute flags are what the engine
|
||||
/// sends this way; any other op of the control stream is run as the
|
||||
/// request it is, and its answer, or its refusal, is told to nobody.
|
||||
fn notify(&mut self, op: Op) {
|
||||
let Op::Put(put) = op else { return };
|
||||
match op {
|
||||
Op::Put(put) if is_voice_flags(&put) => self.voice_flags(put),
|
||||
op => {
|
||||
let (reply, _) = oneshot::channel();
|
||||
self.request(op, reply);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Our own mute and deafen flags go to the link.
|
||||
fn voice_flags(&mut self, put: v1::Put) {
|
||||
for write in put.writes {
|
||||
let Some(Entity { kind: Some(Kind::Voice(voice)) }) = write.entity else { continue };
|
||||
let mute = path_of("voelin.v1.VoiceState", "self_mute");
|
||||
@@ -469,7 +565,7 @@ impl Driver {
|
||||
|
||||
// ---- subscriptions and syncs -----------------------------------------
|
||||
|
||||
async fn subscribe(&mut self, subscribe: v1::Subscribe) -> Result<Answer, SessionError> {
|
||||
fn subscribe(&mut self, subscribe: v1::Subscribe) -> Result<Answer, SessionError> {
|
||||
let scope = subscribe
|
||||
.scope
|
||||
.as_ref()
|
||||
@@ -492,7 +588,9 @@ impl Driver {
|
||||
}
|
||||
}
|
||||
self.subs.insert(scope);
|
||||
self.sync(scope, subscribe.since.as_ref(), subscribe.limit).await;
|
||||
let frames = self.sync_frames(scope, subscribe.since.as_ref(), subscribe.limit);
|
||||
// Sent now if the channel has room for the whole sync, else as soon as it has.
|
||||
self.push_scope(scope, frames);
|
||||
Ok(ack(self.rev))
|
||||
}
|
||||
|
||||
@@ -520,9 +618,9 @@ impl Driver {
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a scope's sync: its whole state, or (CHAT, with a cursor of this
|
||||
/// connection) the messages after the cursor.
|
||||
async fn sync(&mut self, scope: ScopeId, since: Option<&v1::Cursor>, limit: u32) {
|
||||
/// The frames of a scope's sync: its whole state, or (CHAT, with a cursor
|
||||
/// of this connection) the messages after the cursor.
|
||||
fn sync_frames(&self, scope: ScopeId, since: Option<&v1::Cursor>, limit: u32) -> Vec<v1::Push> {
|
||||
let window = if limit == 0 { WINDOW } else { (limit as usize).min(WINDOW) };
|
||||
let delta = match (scope, since) {
|
||||
(ScopeId::Chat(_), Some(cursor)) => {
|
||||
@@ -552,74 +650,90 @@ impl Driver {
|
||||
};
|
||||
let mode = if delta { v1::SyncMode::Delta } else { v1::SyncMode::Full };
|
||||
let proto = scope.to_proto();
|
||||
self.push(Body::SyncBegin(v1::SyncBegin {
|
||||
let frame = |body| v1::Push { body: Some(body) };
|
||||
let mut frames = Vec::with_capacity(items.len().div_ceil(SYNC_CHUNK) + 2);
|
||||
frames.push(frame(Body::SyncBegin(v1::SyncBegin {
|
||||
scope: Some(proto),
|
||||
mode: mode as i32,
|
||||
epoch: self.epoch,
|
||||
}))
|
||||
.await;
|
||||
})));
|
||||
for chunk in items.chunks(SYNC_CHUNK) {
|
||||
self.push(Body::Change(v1::Change {
|
||||
frames.push(frame(Body::Change(v1::Change {
|
||||
scope: Some(proto),
|
||||
rev: self.rev,
|
||||
put: chunk.to_vec(),
|
||||
del: Vec::new(),
|
||||
}))
|
||||
.await;
|
||||
})));
|
||||
}
|
||||
self.push(Body::SyncEnd(v1::SyncEnd {
|
||||
frames.push(frame(Body::SyncEnd(v1::SyncEnd {
|
||||
scope: Some(proto),
|
||||
cursor: Some(v1::Cursor { epoch: self.epoch, rev: self.rev }),
|
||||
gap: false,
|
||||
}))
|
||||
.await;
|
||||
})));
|
||||
frames
|
||||
}
|
||||
|
||||
/// A change of a scope, pushed to its subscribers (the rev counts either
|
||||
/// way).
|
||||
async fn commit(&mut self, scope: ScopeId, put: Vec<Entity>, del: Vec<Entity>) {
|
||||
/// way). A scope that lags gets nothing now: its state is up to date
|
||||
/// here, and the sync that follows carries the change.
|
||||
fn commit(&mut self, scope: ScopeId, put: Vec<Entity>, del: Vec<Entity>) {
|
||||
if put.is_empty() && del.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.rev += 1;
|
||||
if self.subs.contains(&scope) {
|
||||
self.retry_lagged();
|
||||
if self.subs.contains(&scope) && !self.lagged.contains(&scope) {
|
||||
let change = v1::Change { scope: Some(scope.to_proto()), rev: self.rev, put, del };
|
||||
self.push(Body::Change(change)).await;
|
||||
self.push_scope(scope, vec![v1::Push { body: Some(Body::Change(change)) }]);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- what the link reports -------------------------------------------
|
||||
|
||||
async fn event(&mut self, event: LinkEvent) {
|
||||
fn event(&mut self, event: LinkEvent) {
|
||||
match event {
|
||||
LinkEvent::Connected { .. } => {}
|
||||
LinkEvent::Presence(presence) => self.presence(*presence).await,
|
||||
LinkEvent::Presence(presence) => self.presence(*presence),
|
||||
LinkEvent::OwnChannel(channel) => {
|
||||
self.own_channel = Some(channel);
|
||||
self.settle_moves();
|
||||
}
|
||||
LinkEvent::Chat(message) => self.chat(message).await,
|
||||
LinkEvent::Chat(message) => self.chat(message),
|
||||
LinkEvent::Poke { from, from_uid, from_name, message } => {
|
||||
let (user, _) = self.sender(from_uid.as_deref(), &from_name, Some(from)).await;
|
||||
let (user, _) = self.sender(from_uid.as_deref(), &from_name, Some(from));
|
||||
let signal = v1::Signal {
|
||||
from_user: user,
|
||||
from_participant: u32::from(from),
|
||||
to: Some(v1::SignalTarget {
|
||||
server_id: SERVER_ID,
|
||||
participant_id: u32::from(self.cfg.own_client),
|
||||
participant_id: u32::from(self.own_client),
|
||||
..Default::default()
|
||||
}),
|
||||
body: Some(SignalBody::Poke(v1::Poke { message })),
|
||||
};
|
||||
self.push(Body::Signal(signal)).await;
|
||||
self.push_signal(signal);
|
||||
}
|
||||
LinkEvent::Audio(packet) => {
|
||||
if let Some(rtp) = self.downlink.wrap(&packet, Instant::now()) {
|
||||
self.media.media(rtp);
|
||||
}
|
||||
}
|
||||
// Who is talking is derived from the media (protocol section 6.4).
|
||||
LinkEvent::Talking { .. } => {}
|
||||
// Who is talking is derived from the media (protocol section 6.4), but
|
||||
// the link hears talkers whose packets it does not forward as Opus
|
||||
// (Speex, CELT): for those its word is all there is, and it goes to
|
||||
// the engine as a speaking signal, a hint next to the media.
|
||||
LinkEvent::Talking { client, talking } => {
|
||||
self.push_signal(v1::Signal {
|
||||
from_participant: u32::from(client),
|
||||
body: Some(SignalBody::Speaking(v1::Speaking {
|
||||
server_id: SERVER_ID,
|
||||
participant_id: u32::from(client),
|
||||
on: talking,
|
||||
whisper: false,
|
||||
})),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
LinkEvent::OwnStream(event) => self.stream_event(StreamEvent::OwnStream(event)),
|
||||
LinkEvent::StreamAudio { stream, time, data } => {
|
||||
self.stream_event(StreamEvent::Audio { stream, time, data });
|
||||
@@ -627,7 +741,7 @@ impl Driver {
|
||||
LinkEvent::StreamAudioEnded(stream) => {
|
||||
self.stream_event(StreamEvent::AudioEnded(stream))
|
||||
}
|
||||
LinkEvent::Error(text) => self.notice(v1::NoticeLevel::Error, text).await,
|
||||
LinkEvent::Error(text) => self.notice(v1::NoticeLevel::Error, text),
|
||||
LinkEvent::Disconnected(_) => {}
|
||||
}
|
||||
}
|
||||
@@ -638,11 +752,35 @@ impl Driver {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which client of the snapshots we are. The link names our client id once,
|
||||
/// when it connects, and TeamSpeak's own reconnect (inside the link) gives a
|
||||
/// new one with the same unique id and no word about it. So we stay the
|
||||
/// client we were for as long as it is there, and when it is gone we are a
|
||||
/// client of our unique id (the newest, when there are several: a ghost of
|
||||
/// the old connection may linger). A link that names no unique id leaves us
|
||||
/// the client of the connect.
|
||||
fn follow_own_client(&mut self, presence: &Presence) {
|
||||
let uid = self.cfg.own_uid.as_deref().filter(|uid| !uid.is_empty());
|
||||
let ours = |client: &ClientInfo| match uid {
|
||||
Some(uid) => client.uid.as_deref() == Some(uid),
|
||||
None => client.id == self.own_client,
|
||||
};
|
||||
if presence.clients.get(&self.own_client).is_some_and(ours) {
|
||||
return;
|
||||
}
|
||||
let Some(next) = presence.clients.values().filter(|c| ours(c)).map(|c| c.id).max() else {
|
||||
return;
|
||||
};
|
||||
debug!(from = self.own_client, to = next, "we are another client now");
|
||||
self.own_client = next;
|
||||
self.own_slot.store(entities::slot(next), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A snapshot of the server: the entities of the scopes that changed.
|
||||
async fn presence(&mut self, presence: Presence) {
|
||||
let own = Some(self.cfg.own_client);
|
||||
fn presence(&mut self, presence: Presence) {
|
||||
self.follow_own_client(&presence);
|
||||
let Built { server, live, own_user, by_uid } =
|
||||
entities::build(&presence, self.cfg.ts6, own);
|
||||
entities::build(&presence, self.cfg.ts6, Some(self.own_client));
|
||||
// Clients that left take their talk state with them.
|
||||
for id in self.by_client.keys().filter(|id| !presence.clients.contains_key(id)) {
|
||||
self.downlink.forget(*id);
|
||||
@@ -659,7 +797,7 @@ impl Driver {
|
||||
})
|
||||
.collect();
|
||||
self.by_uid = by_uid;
|
||||
if let Some(own) = presence.clients.get(&self.cfg.own_client) {
|
||||
if let Some(own) = presence.clients.get(&self.own_client) {
|
||||
self.own_channel = Some(own.channel);
|
||||
}
|
||||
if own_user.is_some() {
|
||||
@@ -668,7 +806,7 @@ impl Driver {
|
||||
|
||||
let (put, del) = entities::diff(&self.server, &server);
|
||||
self.server = server;
|
||||
self.commit(ScopeId::Server(SERVER_ID), put, del).await;
|
||||
self.commit(ScopeId::Server(SERVER_ID), put, del);
|
||||
|
||||
let mut live = live;
|
||||
for (id, user) in &self.extras {
|
||||
@@ -677,9 +815,9 @@ impl Driver {
|
||||
}
|
||||
let (put, del) = entities::diff(&self.live, &live);
|
||||
self.live = live;
|
||||
self.commit(ScopeId::Live(SERVER_ID), put, del).await;
|
||||
self.commit(ScopeId::Live(SERVER_ID), put, del);
|
||||
|
||||
self.refresh_home().await;
|
||||
self.refresh_home();
|
||||
self.settle_moves();
|
||||
}
|
||||
|
||||
@@ -716,16 +854,16 @@ impl Driver {
|
||||
}
|
||||
}
|
||||
|
||||
async fn refresh_home(&mut self) {
|
||||
fn refresh_home(&mut self) {
|
||||
let home = self.home_layer();
|
||||
let (put, del) = entities::diff(&self.home, &home);
|
||||
self.home = home;
|
||||
self.commit(ScopeId::Home, put, del).await;
|
||||
self.commit(ScopeId::Home, put, del);
|
||||
}
|
||||
|
||||
/// The user and participant a message or poke is from: a client of the
|
||||
/// snapshot, or a user made up for the sender (put into LIVE first).
|
||||
async fn sender(&mut self, uid: Option<&str>, name: &str, client: Option<u16>) -> (u64, u32) {
|
||||
fn sender(&mut self, uid: Option<&str>, name: &str, client: Option<u16>) -> (u64, u32) {
|
||||
if let Some(uid) = uid.filter(|u| !u.is_empty())
|
||||
&& let Some((user, participant)) = self.by_uid.get(uid).copied()
|
||||
{
|
||||
@@ -738,7 +876,7 @@ impl Driver {
|
||||
}
|
||||
let participant = client.map_or(0, u32::from);
|
||||
match uid.filter(|u| !u.is_empty()) {
|
||||
Some(uid) => (self.extra_user(uid, name).await, participant),
|
||||
Some(uid) => (self.extra_user(uid, name), participant),
|
||||
None if client.is_some() => {
|
||||
// A sender with no unique id: by its client id.
|
||||
let id = ids::synthetic_user(&format!("client:{}", participant));
|
||||
@@ -749,7 +887,7 @@ impl Driver {
|
||||
}
|
||||
|
||||
/// A user for a unique id the snapshot does not hold, put into LIVE.
|
||||
async fn extra_user(&mut self, uid: &str, name: &str) -> u64 {
|
||||
fn extra_user(&mut self, uid: &str, name: &str) -> u64 {
|
||||
let id = ids::synthetic_user(uid);
|
||||
if let std::collections::btree_map::Entry::Vacant(slot) = self.extras.entry(id) {
|
||||
let user = entities::bare_user(uid, name, self.cfg.ts6);
|
||||
@@ -759,7 +897,7 @@ impl Driver {
|
||||
&& !self.live.contains_key(&key)
|
||||
{
|
||||
self.live.insert(key, entity.clone());
|
||||
self.commit(ScopeId::Live(SERVER_ID), vec![entity], Vec::new()).await;
|
||||
self.commit(ScopeId::Live(SERVER_ID), vec![entity], Vec::new());
|
||||
}
|
||||
}
|
||||
id
|
||||
@@ -767,15 +905,14 @@ impl Driver {
|
||||
|
||||
/// A message of the book: kept per channel, and pushed to the channel's
|
||||
/// subscribers.
|
||||
async fn chat(&mut self, message: ChatMessage) {
|
||||
fn chat(&mut self, message: ChatMessage) {
|
||||
let (channel, peer) = match &message.target {
|
||||
ChatTarget::Server => (SERVER_CHAT, None),
|
||||
ChatTarget::Channel(channel) => (*channel, None),
|
||||
ChatTarget::Private(uid) => (ids::dm_channel(uid), Some(uid.clone())),
|
||||
};
|
||||
let (user, _) = self
|
||||
.sender(message.author_uid.as_deref(), &message.author_name, message.author_id)
|
||||
.await;
|
||||
let (user, _) =
|
||||
self.sender(message.author_uid.as_deref(), &message.author_name, message.author_id);
|
||||
if let Some(uid) = peer {
|
||||
// The author is the peer, unless the message is our own echo.
|
||||
let name = if message.author_uid.as_deref() == Some(uid.as_str()) {
|
||||
@@ -783,7 +920,7 @@ impl Driver {
|
||||
} else {
|
||||
""
|
||||
};
|
||||
self.ensure_dm(channel, &uid, name).await;
|
||||
self.ensure_dm(channel, &uid, name);
|
||||
}
|
||||
let id = self.next_message_id();
|
||||
let stored = v1::Message {
|
||||
@@ -800,11 +937,11 @@ impl Driver {
|
||||
author_participant: message.author_id.map_or(0, u32::from),
|
||||
..Default::default()
|
||||
};
|
||||
self.store(channel, stored).await;
|
||||
self.store(channel, stored);
|
||||
}
|
||||
|
||||
/// Remember a message and push it to its channel's subscribers.
|
||||
async fn store(&mut self, channel: u64, mut message: v1::Message) {
|
||||
fn store(&mut self, channel: u64, mut message: v1::Message) {
|
||||
self.rev += 1;
|
||||
message.rev = 0;
|
||||
let rev = self.rev;
|
||||
@@ -813,14 +950,16 @@ impl Driver {
|
||||
while window.len() > WINDOW {
|
||||
window.pop_front();
|
||||
}
|
||||
if self.subs.contains(&ScopeId::Chat(channel)) {
|
||||
let scope = ScopeId::Chat(channel);
|
||||
self.retry_lagged();
|
||||
if self.subs.contains(&scope) && !self.lagged.contains(&scope) {
|
||||
let change = v1::Change {
|
||||
scope: Some(ScopeId::Chat(channel).to_proto()),
|
||||
scope: Some(scope.to_proto()),
|
||||
rev,
|
||||
put: vec![entity(Kind::Message(message))],
|
||||
del: Vec::new(),
|
||||
};
|
||||
self.push(Body::Change(change)).await;
|
||||
self.push_scope(scope, vec![v1::Push { body: Some(Body::Change(change)) }]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -833,16 +972,16 @@ impl Driver {
|
||||
}
|
||||
|
||||
/// The direct-message channel with a peer (made in HOME on first use).
|
||||
async fn ensure_dm(&mut self, channel: u64, uid: &str, name: &str) {
|
||||
fn ensure_dm(&mut self, channel: u64, uid: &str, name: &str) {
|
||||
if self.dms.contains_key(&channel) {
|
||||
return;
|
||||
}
|
||||
let peer = match self.by_uid.get(uid) {
|
||||
Some((user, _)) => *user,
|
||||
None => self.extra_user(uid, name).await,
|
||||
None => self.extra_user(uid, name),
|
||||
};
|
||||
self.dms.insert(channel, (uid.to_owned(), peer));
|
||||
self.refresh_home().await;
|
||||
self.refresh_home();
|
||||
}
|
||||
|
||||
// ---- answers from the link -------------------------------------------
|
||||
@@ -969,16 +1108,15 @@ impl Driver {
|
||||
|
||||
/// Our own voice state: the snapshot's, or what the seat says.
|
||||
fn own_voice(&self) -> Answer {
|
||||
let key =
|
||||
Key::Voice { server_id: SERVER_ID, participant_id: u32::from(self.cfg.own_client) };
|
||||
let key = Key::Voice { server_id: SERVER_ID, participant_id: u32::from(self.own_client) };
|
||||
let voice = match self.live.get(&key) {
|
||||
Some(Entity { kind: Some(Kind::Voice(voice)) }) => voice.clone(),
|
||||
_ => v1::VoiceState {
|
||||
server_id: SERVER_ID,
|
||||
participant_id: u32::from(self.cfg.own_client),
|
||||
participant_id: u32::from(self.own_client),
|
||||
user_id: self.own_user_id(),
|
||||
channel_id: self.own_channel.unwrap_or(0),
|
||||
slot: entities::slot(self.cfg.own_client),
|
||||
slot: entities::slot(self.own_client),
|
||||
nick: self.cfg.nickname.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -993,6 +1131,8 @@ impl Driver {
|
||||
if self.held.as_ref().is_some_and(|held| held.until <= now) {
|
||||
self.announced();
|
||||
}
|
||||
// A consumer that lagged may have room again.
|
||||
self.retry_lagged();
|
||||
let expired: Vec<RequestId> =
|
||||
self.pending.iter().filter(|(_, p)| p.deadline <= now).map(|(id, _)| *id).collect();
|
||||
for id in expired {
|
||||
@@ -1052,7 +1192,7 @@ impl Driver {
|
||||
}
|
||||
}
|
||||
|
||||
async fn put(&mut self, put: v1::Put, reply: Reply) {
|
||||
fn put(&mut self, put: v1::Put, reply: Reply) {
|
||||
let mut writes = put.writes;
|
||||
if writes.len() != 1 {
|
||||
let _ = reply.send(Err(rejected(
|
||||
@@ -1072,18 +1212,18 @@ impl Driver {
|
||||
let _ = reply.send(answer);
|
||||
}
|
||||
Kind::Channel(channel) if channel.kind == v1::ChannelKind::Dm as i32 => {
|
||||
let answer = self.put_dm(channel).await;
|
||||
let answer = self.put_dm(channel);
|
||||
let _ = reply.send(answer);
|
||||
}
|
||||
Kind::Voice(voice) => {
|
||||
// Our own flags, as a request that wants its answer.
|
||||
self.notify(Op::Put(v1::Put {
|
||||
self.voice_flags(v1::Put {
|
||||
writes: vec![v1::Write {
|
||||
entity: Some(entity(Kind::Voice(voice))),
|
||||
paths: write.paths,
|
||||
}],
|
||||
..Default::default()
|
||||
}));
|
||||
});
|
||||
let _ = reply.send(Ok(self.own_voice()));
|
||||
}
|
||||
Kind::User(user) => {
|
||||
@@ -1144,14 +1284,14 @@ impl Driver {
|
||||
rev: self.rev,
|
||||
author_id: self.own_user_id(),
|
||||
ts_ms: now_ms(),
|
||||
author_participant: u32::from(self.cfg.own_client),
|
||||
author_participant: u32::from(self.own_client),
|
||||
..message
|
||||
};
|
||||
Ok(entities_answer(vec![entity(Kind::Message(stored))], self.rev))
|
||||
}
|
||||
|
||||
/// The channel of a direct conversation with a user (made in HOME).
|
||||
async fn put_dm(&mut self, channel: v1::Channel) -> Result<Answer, SessionError> {
|
||||
fn put_dm(&mut self, channel: v1::Channel) -> Result<Answer, SessionError> {
|
||||
let own = self.own_user_id();
|
||||
let Some(peer) = channel.recipients.iter().copied().find(|id| *id != own) else {
|
||||
return Err(rejected(ErrorCode::BadRequest, "a direct channel needs another user"));
|
||||
@@ -1167,7 +1307,7 @@ impl Driver {
|
||||
};
|
||||
let id = ids::dm_channel(&uid);
|
||||
self.dms.entry(id).or_insert((uid, peer));
|
||||
self.refresh_home().await;
|
||||
self.refresh_home();
|
||||
let item = self.home.get(&Key::Channel { id }).cloned().into_iter().collect();
|
||||
Ok(entities_answer(item, self.rev))
|
||||
}
|
||||
@@ -1417,6 +1557,16 @@ impl Driver {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `Put` is made of writes to the voice state only (the flags of a
|
||||
/// fire-and-forget).
|
||||
fn is_voice_flags(put: &v1::Put) -> bool {
|
||||
!put.writes.is_empty()
|
||||
&& put
|
||||
.writes
|
||||
.iter()
|
||||
.all(|write| matches!(write.entity, Some(Entity { kind: Some(Kind::Voice(_)) })))
|
||||
}
|
||||
|
||||
fn reply_to(reply: Option<Reply>, answer: Result<Answer, SessionError>) {
|
||||
if let Some(reply) = reply {
|
||||
let _ = reply.send(answer);
|
||||
|
||||
@@ -282,10 +282,15 @@ pub(crate) fn build(presence: &Presence, ts6: bool, own_client: Option<u16>) ->
|
||||
for info in presence.channel_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, true)));
|
||||
}
|
||||
// The own client first, then by client id.
|
||||
let mut clients: Vec<&ClientInfo> = presence.clients.values().collect();
|
||||
clients.sort_by_key(|client| (Some(client.id) != own_client, client.id));
|
||||
let mut used: HashSet<u64> = HashSet::new();
|
||||
for client in presence.clients.values() {
|
||||
// The same identity twice on a server has one database id: the lower
|
||||
// client id keeps it, the other is a user of its own.
|
||||
for client in clients {
|
||||
// The same identity twice on a server has one database id: the own
|
||||
// client keeps it (it must stay the user we are, also while a ghost of
|
||||
// our old connection lingers), else the lower client id; the other is a
|
||||
// user of its own.
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let mut id = client.database_id.unwrap_or_else(|| {
|
||||
ids::synthetic_user(&uid.map_or_else(|| format!("client:{}", client.id), str::to_owned))
|
||||
@@ -472,6 +477,40 @@ mod tests {
|
||||
assert_eq!((voices, users), (2, 2));
|
||||
}
|
||||
|
||||
/// The own client is the user whose database id the identity has, also when a
|
||||
/// ghost of the old connection (the lower client id) lingers.
|
||||
#[test]
|
||||
fn the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice() {
|
||||
let client = |id| ClientInfo {
|
||||
id,
|
||||
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
|
||||
nickname: format!("n{id}"),
|
||||
database_id: Some(77),
|
||||
..Default::default()
|
||||
};
|
||||
let mut presence = Presence::default();
|
||||
for c in [client(3), client(4)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
let user_of = |built: &Built, client: u32| {
|
||||
let key = Key::Voice { server_id: SERVER_ID, participant_id: client };
|
||||
let Some(Entity { kind: Some(Kind::Voice(voice)) }) = built.live.get(&key) else {
|
||||
panic!("no voice state")
|
||||
};
|
||||
voice.user_id
|
||||
};
|
||||
// Nobody is us: the lower client id keeps it.
|
||||
let built = build(&presence, false, None);
|
||||
assert_eq!(user_of(&built, 3), 77);
|
||||
assert_ne!(user_of(&built, 4), 77);
|
||||
// The later client is us: it keeps it, and the ghost has the made-up id.
|
||||
let built = build(&presence, false, Some(4));
|
||||
assert_eq!(user_of(&built, 4), 77);
|
||||
assert_ne!(user_of(&built, 3), 77);
|
||||
assert_eq!(built.own_user.map(|u| u.id), Some(77));
|
||||
assert_eq!(built.by_uid["uXDkxSZbv0IoA0z/toW3guGpUbI="], (77, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_deletes_by_key_and_puts_what_differs() {
|
||||
let mut presence = Presence::default();
|
||||
|
||||
@@ -23,7 +23,7 @@ mod media;
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -233,7 +233,9 @@ pub(crate) struct LinkSession {
|
||||
features: Features,
|
||||
cmds: mpsc::UnboundedSender<Cmd>,
|
||||
closed: watch::Receiver<Option<CloseReason>>,
|
||||
own_slot: u32,
|
||||
/// The media slot of our client; the driver changes it when we are another
|
||||
/// client after TeamSpeak's own reconnect.
|
||||
own_slot: Arc<AtomicU32>,
|
||||
}
|
||||
|
||||
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> CloseReason {
|
||||
@@ -280,8 +282,25 @@ impl Session for LinkSession {
|
||||
}
|
||||
|
||||
fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> {
|
||||
if placement(&op) == Placement::Invalid {
|
||||
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
|
||||
// Only an op of the control stream can go without an answer: a Hello is
|
||||
// part of connecting, and a List and the file transfers have streams
|
||||
// (and answers) of their own.
|
||||
match placement(&op) {
|
||||
Placement::Control => {}
|
||||
Placement::Invalid => {
|
||||
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
|
||||
}
|
||||
Placement::OwnStream => {
|
||||
return Err(SessionError::Protocol(
|
||||
"a List and the file transfers have a stream and an answer of their own, \
|
||||
they cannot be sent without one"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// The task may be on its way out and not have dropped its queue yet.
|
||||
if self.closed.borrow().is_some() {
|
||||
return Err(SessionError::Closed(closed_reason(&self.closed)));
|
||||
}
|
||||
self.cmds
|
||||
.send(Cmd::Notify(op))
|
||||
@@ -327,7 +346,7 @@ impl Session for LinkSession {
|
||||
// Only our voice to the channel: TeamSpeak whispers and priority voice,
|
||||
// like video, are not offered here.
|
||||
if class != MediaClass::Voice
|
||||
|| flow.slot() != self.own_slot
|
||||
|| flow.slot() != self.own_slot.load(Ordering::Relaxed)
|
||||
|| flow.sub() != voice_sub::CHANNEL
|
||||
{
|
||||
return Err(MediaError::NotOwned(flow));
|
||||
@@ -590,7 +609,8 @@ async fn connect_link(
|
||||
limits: Some(v1::Limits {
|
||||
max_message_chars: 1024,
|
||||
max_page: 100,
|
||||
max_subscriptions: 4,
|
||||
// HOME, SERVER and LIVE, and the chats.
|
||||
max_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS + 3,
|
||||
max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS,
|
||||
max_live_subscriptions: 8,
|
||||
..Default::default()
|
||||
@@ -600,6 +620,7 @@ async fn connect_link(
|
||||
};
|
||||
|
||||
let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
|
||||
let own_slot = Arc::new(AtomicU32::new(entities::slot(joined.own_client)));
|
||||
let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16));
|
||||
let (closed_tx, closed_rx) = watch::channel(None);
|
||||
let (port, streams) = if joined.capabilities.streams {
|
||||
@@ -631,6 +652,7 @@ async fn connect_link(
|
||||
media: params.media.clone(),
|
||||
port,
|
||||
closed: closed_tx,
|
||||
own_slot: own_slot.clone(),
|
||||
server: entities::server(&details, &joined.name, 0),
|
||||
epoch: u64::try_from(now_ms()).unwrap_or(1).max(1),
|
||||
});
|
||||
@@ -639,7 +661,7 @@ async fn connect_link(
|
||||
features: Features::new(features),
|
||||
cmds: cmds_tx,
|
||||
closed: closed_rx,
|
||||
own_slot: entities::slot(joined.own_client),
|
||||
own_slot,
|
||||
};
|
||||
tokio::spawn(driver.run(cmds_rx));
|
||||
Ok(LocalConnected {
|
||||
|
||||
Reference in new issue
Block a user