The engine's voice source is now a voelin_proto::link::Session obtained from a registry of connectors (docs/session-seam.md, slice 1): - link::Backends keeps the plain connectors of voelin_proto::link::Connectors and the in-process ones that also hand the engine a port for TeamSpeak 6 streams; the scheme of the address picks the connector, an address without one is a TeamSpeak bookmark. - link::SessionLink is the engine's ServerLink. session.rs is unchanged and still speaks LinkCmd and LinkEvent; SessionLink runs the connect sequence (List the server, subscribe HOME, SERVER and LIVE, take the seat), keeps a voelin_model::replica::Replica, projects it into the client's older model (link/project.rs, the fix-ups F1 to F10), frames voice as RTP and derives who talks from the media (link/media.rs), and turns every command into the Session call of its row. Transfers copy through read_file and write_file. - ts_session makes a TeamSpeak connection a Session: LinkSession over any ServerLink translates the link's commands, events and presence snapshots to v1 entities, pushes, answers and RTP; TsConnector makes them for ts3server:// and teamspeak:// addresses with TsLink inside, and LinkConnector for the link of Engine::start_with_link. - voice.rs opens the transfer connection itself for the new OpenRead and OpenWrite commands; files::download and upload are generic over the stream. - Engine::start_with_backends is new; start_with and start_with_link go through the registry. tests/link_fake.rs runs through both adapters; its fixtures are normalised as the design says (an order chain, database ids, talking from media, the server named, channel chat for the channel we are in), and the request id the link sees is the session's own. New unit tests cover every row of the mapping with a recording link, the TeamSpeak session on its own, media framing both ways, the talk tracker, the close table, the error texts, the backend and capability tables, the connect parameters, and the presence round trip on book fixtures and generated presences. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
606 lines
20 KiB
Rust
606 lines
20 KiB
Rust
//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each
|
|
//! connection the test asks for to the test, which plays the server by
|
|
//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session
|
|
//! gives. Presence, chat, the dedup of a message that comes twice, history
|
|
//! and the end of a connection are the session's own behaviour; nothing here
|
|
//! needs a TeamSpeak server or a TeamSpeak type.
|
|
|
|
use std::sync::Arc;
|
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
|
|
|
use tokio::sync::{broadcast, mpsc};
|
|
use voelin_audio::{TalkerId, VoiceCodec, VoicePacket};
|
|
use voelin_core::history::MessageSource;
|
|
use voelin_core::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink};
|
|
use voelin_core::settings::Settings;
|
|
use voelin_core::stream::{StreamCmd, StreamSetup};
|
|
use voelin_core::{
|
|
BackendInfo, Command, Engine, Event, History, HistoryMessage, HistorySource, SessionId,
|
|
SessionState, Source, VoiceOptions, VoiceState,
|
|
};
|
|
use voelin_model::{
|
|
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
|
|
ServerDetails,
|
|
};
|
|
|
|
/// A connection the session asked the link for.
|
|
struct Conn {
|
|
options: ConnectOptions,
|
|
session: SessionId,
|
|
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
|
events: mpsc::UnboundedSender<LinkEvent>,
|
|
}
|
|
|
|
impl Conn {
|
|
/// Play `script`, the server's side, in order.
|
|
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
|
|
for event in script {
|
|
self.events.send(event).expect("the session listens");
|
|
}
|
|
}
|
|
|
|
/// The next command the session gave.
|
|
async fn cmd(&mut self) -> LinkCmd {
|
|
tokio::time::timeout(Duration::from_secs(10), self.cmds.recv())
|
|
.await
|
|
.expect("a command in time")
|
|
.expect("the session keeps the connection")
|
|
}
|
|
}
|
|
|
|
/// Hands every connection to the test.
|
|
struct FakeLink {
|
|
conns: mpsc::UnboundedSender<Conn>,
|
|
}
|
|
|
|
impl FakeLink {
|
|
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
|
|
let (conns, rx) = mpsc::unbounded_channel();
|
|
(Self { conns }, rx)
|
|
}
|
|
}
|
|
|
|
impl ServerLink for FakeLink {
|
|
fn spawn(
|
|
&self,
|
|
options: ConnectOptions,
|
|
ctx: LinkCtx,
|
|
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
|
events: mpsc::UnboundedSender<LinkEvent>,
|
|
) {
|
|
let conn = Conn { options, session: ctx.session(), cmds, events };
|
|
let _ = self.conns.send(conn);
|
|
}
|
|
}
|
|
|
|
const SESSION: SessionId = 1;
|
|
const SERVER_UID: &str = "fake-server=";
|
|
const ME: u16 = 7;
|
|
const ME_UID: &str = "me=";
|
|
const LOBBY: ChannelId = 1;
|
|
const GAMES: ChannelId = 2;
|
|
|
|
struct Harness {
|
|
engine: Engine,
|
|
events: broadcast::Receiver<Event>,
|
|
conns: mpsc::UnboundedReceiver<Conn>,
|
|
}
|
|
|
|
impl Harness {
|
|
fn start() -> Self {
|
|
let (link, conns) = FakeLink::new();
|
|
let engine =
|
|
Engine::start_with_link(Settings::in_memory(), History::in_memory(), Arc::new(link));
|
|
let events = engine.subscribe();
|
|
Self { engine, events, conns }
|
|
}
|
|
|
|
/// Ask for a voice connection and take it from the link.
|
|
async fn connect(&mut self) -> Conn {
|
|
let options = VoiceOptions::new("fake.test:9987", "tester");
|
|
self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
|
|
tokio::time::timeout(Duration::from_secs(10), self.conns.recv())
|
|
.await
|
|
.expect("the session spawns the link")
|
|
.expect("the link lives")
|
|
}
|
|
|
|
/// The next event `f` picks, skipping the others.
|
|
async fn next<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> T {
|
|
tokio::time::timeout(Duration::from_secs(10), async {
|
|
loop {
|
|
if let Some(t) = f(self.events.recv().await.expect("engine events")) {
|
|
return t;
|
|
}
|
|
}
|
|
})
|
|
.await
|
|
.expect("event in time")
|
|
}
|
|
|
|
/// The next state of the session that `ok` accepts.
|
|
async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState {
|
|
self.next(|e| match e {
|
|
Event::State { state, .. } if ok(&state) => Some(state),
|
|
_ => None,
|
|
})
|
|
.await
|
|
}
|
|
|
|
/// The next live chat message.
|
|
async fn chat(&mut self) -> ChatMessage {
|
|
self.next(|e| match e {
|
|
Event::Chat { message, .. } => Some(message),
|
|
_ => None,
|
|
})
|
|
.await
|
|
}
|
|
|
|
/// The messages stored for `target`, oldest first.
|
|
async fn stored(&self, target: ChatTarget) -> Vec<HistoryMessage> {
|
|
self.engine
|
|
.history()
|
|
.page(SERVER_UID, &target, Default::default(), false)
|
|
.await
|
|
.expect("the history")
|
|
}
|
|
}
|
|
|
|
fn now_ms() -> i64 {
|
|
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64
|
|
}
|
|
|
|
fn capabilities(streams: bool) -> Capabilities {
|
|
Capabilities { streams, file_transfer: true, ..Default::default() }
|
|
}
|
|
|
|
fn backend() -> BackendInfo {
|
|
BackendInfo { product: "Fake".into(), version: "1.2".into() }
|
|
}
|
|
|
|
fn connected(streams: bool) -> LinkEvent {
|
|
LinkEvent::Connected {
|
|
name: "Fake Server".into(),
|
|
backend: backend(),
|
|
capabilities: capabilities(streams),
|
|
own_client: ME,
|
|
server_uid: SERVER_UID.into(),
|
|
own_uid: Some(ME_UID.into()),
|
|
}
|
|
}
|
|
|
|
/// A client as a TeamSpeak link reports one: with its database id, and not
|
|
/// talking (who talks comes from the media, which the session derives).
|
|
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
|
|
ClientInfo {
|
|
id,
|
|
uid: Some(format!("{nickname}=")),
|
|
nickname: nickname.into(),
|
|
channel,
|
|
talking: Some(false),
|
|
database_id: Some(1_000 + u64::from(id)),
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
/// Two channels, three clients; we are in the second channel. The shape is
|
|
/// what a TeamSpeak link reports: sibling channels form an order chain, the
|
|
/// server is named and has its unique id.
|
|
fn presence() -> Presence {
|
|
let channel =
|
|
|id, name: &str, order| ChannelInfo { id, name: name.into(), order, ..Default::default() };
|
|
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
|
|
presence.server = ServerDetails {
|
|
name: "Fake Server".into(),
|
|
uid: Some(SERVER_UID.into()),
|
|
version: backend().version,
|
|
..Default::default()
|
|
};
|
|
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby", 0));
|
|
presence.channels.insert(GAMES, channel(GAMES, "Games", LOBBY));
|
|
let me = ClientInfo { uid: Some(ME_UID.into()), ..client(ME, "tester", GAMES) };
|
|
for c in [me, client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
|
|
presence.clients.insert(c.id, c);
|
|
}
|
|
presence
|
|
}
|
|
|
|
/// One packet of voice from `talker`: what the session derives talking from.
|
|
fn voice_of(talker: u16) -> LinkEvent {
|
|
LinkEvent::Audio(VoicePacket {
|
|
talker: TalkerId(talker),
|
|
seq: 1,
|
|
codec: VoiceCodec::Voice,
|
|
whisper: false,
|
|
payload: vec![1, 2, 3],
|
|
})
|
|
}
|
|
|
|
fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
|
|
ChatMessage {
|
|
target: ChatTarget::Channel(GAMES),
|
|
author_name: author.into(),
|
|
author_uid: Some(format!("{author}=")),
|
|
author_id: None,
|
|
text: text.into(),
|
|
ts_ms,
|
|
via_relay: false,
|
|
blocked: false,
|
|
}
|
|
}
|
|
|
|
/// Connecting, the server's presence, moving, talking, a failing command
|
|
/// and the end of the connection, as the session reports them.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn presence_follows_the_link_until_it_disconnects() {
|
|
let mut h = Harness::start();
|
|
let conn = h.connect().await;
|
|
// What the link was given.
|
|
assert_eq!(
|
|
(conn.options.address.as_str(), conn.options.nickname.as_str()),
|
|
("fake.test:9987", "tester")
|
|
);
|
|
assert_eq!(conn.session, SESSION);
|
|
h.state(|s| s.voice == VoiceState::Connecting).await;
|
|
|
|
conn.play([
|
|
connected(false),
|
|
LinkEvent::Presence(Box::new(presence())),
|
|
LinkEvent::OwnChannel(GAMES),
|
|
]);
|
|
// In the order the session tells them: the server, its presence, our channel.
|
|
let (name, info, caps) = h
|
|
.next(|e| match e {
|
|
Event::ServerInfo { name, backend, capabilities, .. } => {
|
|
Some((name, backend, capabilities))
|
|
}
|
|
_ => None,
|
|
})
|
|
.await;
|
|
assert_eq!((name.as_str(), info.label().as_str()), ("Fake Server", "Fake 1.2"));
|
|
assert_eq!(caps, capabilities(false));
|
|
let shown = h
|
|
.next(|e| match e {
|
|
Event::Presence { presence, .. } if !presence.clients.is_empty() => Some(presence),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
assert_eq!(*shown, presence());
|
|
let state = h.state(|s| s.own_channel == Some(GAMES)).await;
|
|
assert_eq!(state.voice, VoiceState::Connected);
|
|
assert_eq!(state.own_client, Some(ME));
|
|
assert_eq!(state.server_uid.as_deref(), Some(SERVER_UID));
|
|
assert_eq!(state.presence_source, Some(Source::Voice));
|
|
|
|
conn.play([
|
|
// Alice talks: a packet of her voice (the session derives who talks).
|
|
voice_of(8),
|
|
LinkEvent::Poke {
|
|
from: 8,
|
|
from_uid: Some("alice=".into()),
|
|
from_name: "alice".into(),
|
|
message: "wake up".into(),
|
|
},
|
|
LinkEvent::Error("move refused".into()),
|
|
]);
|
|
h.next(|e| matches!(e, Event::Talking { client: 8, talking: true, .. }).then_some(())).await;
|
|
let poke = h
|
|
.next(|e| match e {
|
|
Event::Poke { from_name, message, blocked, .. } => Some((from_name, message, blocked)),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
assert_eq!(poke, ("alice".into(), "wake up".into(), false));
|
|
let error = h
|
|
.next(|e| match e {
|
|
Event::Error { message, .. } => Some(message),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
assert_eq!(error, "move refused");
|
|
|
|
// The link ends the connection: the session forgets what it showed.
|
|
conn.play([LinkEvent::Disconnected(Some("server shut down".into()))]);
|
|
let state = h.state(|s| s.voice == VoiceState::Disconnected).await;
|
|
assert_eq!((state.own_channel, state.own_client), (None, None));
|
|
let error = h
|
|
.next(|e| match e {
|
|
Event::Error { message, .. } => Some(message),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
assert_eq!(error, "voice: server shut down");
|
|
let state = h.state(|s| s.presence_source.is_none()).await;
|
|
assert_eq!(state.voice, VoiceState::Disconnected);
|
|
let shown = h
|
|
.next(|e| match e {
|
|
Event::Presence { presence, .. } => Some(presence),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
assert!(shown.clients.is_empty() && shown.channels.is_empty());
|
|
}
|
|
|
|
/// What the user asks for reaches the link; streams only where the link's
|
|
/// capabilities say it has them.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn commands_reach_the_link() {
|
|
let mut h = Harness::start();
|
|
let mut conn = h.connect().await;
|
|
conn.play([
|
|
connected(false),
|
|
LinkEvent::Presence(Box::new(presence())),
|
|
LinkEvent::OwnChannel(GAMES),
|
|
]);
|
|
h.state(|s| s.own_channel == Some(GAMES)).await;
|
|
|
|
let engine = h.engine.clone();
|
|
engine.send(Command::SendChat {
|
|
session: SESSION,
|
|
target: ChatTarget::Channel(GAMES),
|
|
text: "hello".into(),
|
|
});
|
|
let LinkCmd::SendChat(target, text) = conn.cmd().await else { panic!("a chat message") };
|
|
assert_eq!((target, text.as_str()), (ChatTarget::Channel(GAMES), "hello"));
|
|
engine.send(Command::MoveToChannel {
|
|
session: SESSION,
|
|
channel: LOBBY,
|
|
password: Some("pw".into()),
|
|
});
|
|
let LinkCmd::Move(channel, password) = conn.cmd().await else { panic!("a move") };
|
|
assert_eq!((channel, password.as_deref()), (LOBBY, Some("pw")));
|
|
engine.send(Command::SetInputMuted { session: SESSION, muted: true });
|
|
assert!(matches!(conn.cmd().await, LinkCmd::SetInputMuted(true)));
|
|
assert!(h.state(|s| s.input_muted).await.input_muted);
|
|
engine.send(Command::Poke { session: SESSION, client: 8, message: "hi".into() });
|
|
assert!(matches!(conn.cmd().await, LinkCmd::Poke { client: 8, .. }));
|
|
engine.send(Command::ListFiles {
|
|
session: SESSION,
|
|
request: 5,
|
|
channel: GAMES,
|
|
password: None,
|
|
path: "/docs/".into(),
|
|
});
|
|
let LinkCmd::ListFiles { dir, .. } = conn.cmd().await else { panic!("a file list") };
|
|
// The request id is the session's own: the link gets one of its making.
|
|
assert_eq!((dir.channel, dir.path.as_str()), (GAMES, "/docs/"));
|
|
|
|
// No streams in the capabilities: the session refuses them itself.
|
|
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
|
|
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
|
|
let error = h
|
|
.next(|e| match e {
|
|
Event::Error { message, .. } => Some(message),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
assert!(error.contains("streams"), "{error}");
|
|
assert!(conn.cmds.try_recv().is_err(), "nothing reached the link");
|
|
|
|
// A link with streams: stream commands go to it, and end with the connection.
|
|
let mut with_streams = {
|
|
let link_engine = h.engine.clone();
|
|
link_engine.send(Command::ConnectVoice {
|
|
session: SESSION,
|
|
options: Box::new(VoiceOptions::new("fake.test:9987", "tester")),
|
|
});
|
|
h.conns.recv().await.expect("the second connection")
|
|
};
|
|
// The replaced connection is told to go.
|
|
assert!(matches!(conn.cmd().await, LinkCmd::Disconnect));
|
|
with_streams.play([connected(true)]);
|
|
h.next(|e| match e {
|
|
Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
// A connection with streams is given the (empty) stream directory first.
|
|
let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else {
|
|
panic!("the stream directory")
|
|
};
|
|
assert!(directory.is_empty());
|
|
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
|
|
let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else {
|
|
panic!("a stream start")
|
|
};
|
|
assert_eq!((setup.name.as_str(), auto_accept), ("screen", true));
|
|
engine.send(Command::StopStream { session: SESSION });
|
|
assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop)));
|
|
engine.send(Command::DisconnectVoice { session: SESSION });
|
|
assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect));
|
|
}
|
|
|
|
/// A reconnect ends the streams of the connection it replaces through that
|
|
/// connection, before the connection itself: the old link is given
|
|
/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its
|
|
/// connection on `Disconnect` (the TeamSpeak one stops reading commands
|
|
/// there) relies on this order for the streams to hear of their end.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() {
|
|
let mut h = Harness::start();
|
|
let mut old = h.connect().await;
|
|
old.play([
|
|
connected(true),
|
|
LinkEvent::Presence(Box::new(presence())),
|
|
LinkEvent::OwnChannel(GAMES),
|
|
]);
|
|
h.state(|s| s.own_channel == Some(GAMES)).await;
|
|
let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else {
|
|
panic!("the stream directory")
|
|
};
|
|
assert!(directory.is_empty());
|
|
|
|
// Connecting again replaces the connection.
|
|
let _new = h.connect().await;
|
|
let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else {
|
|
panic!("the streams end first")
|
|
};
|
|
assert_eq!(reason, "voice reconnecting");
|
|
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
|
|
}
|
|
|
|
/// A message we send is stored at once; the server's copy of it merges
|
|
/// into the same row, and is shown (once).
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn a_sent_message_and_its_echo_are_one_message() {
|
|
let mut h = Harness::start();
|
|
let mut conn = h.connect().await;
|
|
conn.play([
|
|
connected(false),
|
|
LinkEvent::Presence(Box::new(presence())),
|
|
LinkEvent::OwnChannel(GAMES),
|
|
]);
|
|
h.state(|s| s.own_channel == Some(GAMES)).await;
|
|
|
|
h.engine.send(Command::SendChat {
|
|
session: SESSION,
|
|
target: ChatTarget::Channel(GAMES),
|
|
text: "hello".into(),
|
|
});
|
|
assert!(matches!(conn.cmd().await, LinkCmd::SendChat(..)));
|
|
// The server sends it back to everyone in the channel, to us too.
|
|
let mut echo = message("tester", "hello", now_ms());
|
|
echo.author_uid = Some(ME_UID.into());
|
|
echo.author_id = Some(ME);
|
|
conn.play([LinkEvent::Chat(echo.clone())]);
|
|
let shown = h.chat().await;
|
|
assert_eq!((shown.author_name.as_str(), shown.text.as_str()), ("tester", "hello"));
|
|
|
|
// A marker: what comes next is the next message, not a second "hello".
|
|
conn.play([LinkEvent::Chat(message("alice", "marker", now_ms()))]);
|
|
assert_eq!(h.chat().await.text, "marker");
|
|
let rows = h.stored(ChatTarget::Channel(GAMES)).await;
|
|
let texts: Vec<_> = rows.iter().map(|m| m.message.text.as_str()).collect();
|
|
assert_eq!(texts, ["hello", "marker"]);
|
|
assert_eq!(rows[0].source, MessageSource::Local);
|
|
}
|
|
|
|
/// A message that comes twice (the server's and a relay's copy, with the
|
|
/// relay's `[nick] ` prefix) is shown once.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn a_message_that_comes_twice_is_shown_once() {
|
|
let mut h = Harness::start();
|
|
let conn = h.connect().await;
|
|
h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) });
|
|
conn.play([
|
|
connected(false),
|
|
LinkEvent::Presence(Box::new(presence())),
|
|
LinkEvent::OwnChannel(GAMES),
|
|
]);
|
|
h.state(|s| s.own_channel == Some(GAMES)).await;
|
|
|
|
let t = now_ms();
|
|
let mut relayed = message("alice", "[alice] gg everyone", t + 300);
|
|
relayed.via_relay = true;
|
|
conn.play([
|
|
LinkEvent::Chat(message("alice", "gg everyone", t)),
|
|
LinkEvent::Chat(relayed),
|
|
// The same words much later are another message.
|
|
LinkEvent::Chat(message("alice", "gg everyone", t + 10_000)),
|
|
LinkEvent::Chat(message("bob", "gg everyone", t + 10_100)),
|
|
]);
|
|
let shown: Vec<_> = {
|
|
let mut shown = Vec::new();
|
|
while shown.len() < 3 {
|
|
shown.push(h.chat().await);
|
|
}
|
|
shown
|
|
};
|
|
let who: Vec<_> = shown.iter().map(|m| (m.author_name.as_str(), m.ts_ms)).collect();
|
|
assert_eq!(who, [("alice", t), ("alice", t + 10_000), ("bob", t + 10_100)]);
|
|
}
|
|
|
|
/// Stored messages come back when a chat opens, also after the connection
|
|
/// is gone; the server's id keys them.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn history_is_kept_across_the_connection() {
|
|
let mut h = Harness::start();
|
|
let conn = h.connect().await;
|
|
conn.play([
|
|
connected(false),
|
|
LinkEvent::Presence(Box::new(presence())),
|
|
LinkEvent::OwnChannel(GAMES),
|
|
]);
|
|
h.state(|s| s.own_channel == Some(GAMES)).await;
|
|
let t = now_ms();
|
|
conn.play([
|
|
LinkEvent::Chat(message("alice", "first", t)),
|
|
LinkEvent::Chat(message("bob", "second", t + 1_000)),
|
|
// A private message to us is stored under its peer, not the channel.
|
|
LinkEvent::Chat(ChatMessage {
|
|
target: ChatTarget::Private("alice=".into()),
|
|
..message("alice", "psst", t + 2_000)
|
|
}),
|
|
]);
|
|
for _ in 0..3 {
|
|
h.chat().await;
|
|
}
|
|
conn.play([LinkEvent::Disconnected(None)]);
|
|
h.state(|s| s.voice == VoiceState::Disconnected).await;
|
|
|
|
h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) });
|
|
// The stored page (the live batches of the messages came before).
|
|
let messages = h
|
|
.next(|e| match e {
|
|
Event::ChatHistory { messages, source: HistorySource::Local, .. } => Some(messages),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
let texts: Vec<_> = messages.iter().map(|m| m.message.text.as_str()).collect();
|
|
assert_eq!(texts, ["first", "second"]);
|
|
let private = h.stored(ChatTarget::Private("alice=".into())).await;
|
|
assert_eq!(private.len(), 1);
|
|
assert_eq!(private[0].message.text, "psst");
|
|
}
|
|
|
|
/// Events of a connection the session replaced do not reach it.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn a_replaced_connection_is_ignored() {
|
|
let mut h = Harness::start();
|
|
let mut old = h.connect().await;
|
|
old.play([
|
|
connected(false),
|
|
LinkEvent::Presence(Box::new(presence())),
|
|
LinkEvent::OwnChannel(GAMES),
|
|
]);
|
|
h.state(|s| s.own_channel == Some(GAMES)).await;
|
|
|
|
let new = h.connect().await;
|
|
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
|
|
// The old connection winds down, and says more than it should.
|
|
let mut stale = presence();
|
|
stale.clients.insert(10, client(10, "ghost", LOBBY));
|
|
old.play([
|
|
LinkEvent::Presence(Box::new(stale)),
|
|
LinkEvent::Chat(message("ghost", "boo", now_ms())),
|
|
LinkEvent::Disconnected(None),
|
|
]);
|
|
let mut fresh = presence();
|
|
fresh.clients.remove(&9);
|
|
// A link that says we are in the lobby shows us in the lobby.
|
|
fresh.clients.get_mut(&ME).expect("we are on the server").channel = LOBBY;
|
|
new.play([
|
|
connected(false),
|
|
LinkEvent::Presence(Box::new(fresh.clone())),
|
|
LinkEvent::OwnChannel(LOBBY),
|
|
]);
|
|
// Only the new connection's presence is shown (nobody else has 2 clients).
|
|
let shown = h
|
|
.next(|e| match e {
|
|
Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => {
|
|
Some(presence)
|
|
}
|
|
_ => None,
|
|
})
|
|
.await;
|
|
assert_eq!(*shown, fresh);
|
|
let state = h.state(|s| s.own_channel == Some(LOBBY)).await;
|
|
assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count");
|
|
// Channel chat reaches the channel we are in (the lobby, now).
|
|
new.play([LinkEvent::Chat(ChatMessage {
|
|
target: ChatTarget::Channel(LOBBY),
|
|
..message("alice", "hello", now_ms())
|
|
})]);
|
|
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
|
|
}
|