Test the engine on the protocol repository's fake host

tests/session_fake.rs runs the engine through Engine::start_with_backends
with a FakeConnector registered, so a session of the engine is a
voelin_proto::link::Session that no TeamSpeak code made. The host is a
FakeHost filled through put; FakeHandle plays the backend of one session.

The scenarios of link_fake.rs move over (presence until the host ends the
session, commands as v1 requests, a sent message and its echo, the dedup of
a message that comes twice, history across the session), and the ones the
v1 path needs are new: how a session ends and the text the user reads, what
a host refuses and the words it says it in, the chat of a channel
subscribed again when we move back (in full: there is no cursor), closed
scopes, a HostUpdate that changes what the engine asks for, offline messages
as Mail, files through read_file and write_file with a resumed upload, file
operations as FileEntry puts and deletes, the media of a session routed to
the talker of its slot, a reconnect that finds the state the first session
left, and a connect that fails.

link_fake.rs keeps the three tests that need the inner link: the stream
commands (they travel on a port a Session has no part in), the order in
which a reconnect shuts the streams and the old connection down, and a link
that keeps talking after its connection was replaced.

One test is ignored with its reason: a v1 host sends the window of a chat
scope again after a reconnect, and the engine stores the copy (the history
merges copies of different sources only). TeamSpeak never replays, so no
host the engine reaches today meets it; docs/session-seam.md will say so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-24 01:15:34 +03:00
1 parent bfc52e2688
commit f9d3f86896
2 files changed
+1396 -276

No files matched your search

+23 -276
View File
@@ -1,22 +1,30 @@
//! 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.
//! gives. These are the tests that need the inner link itself:
//!
//! - the stream commands, which travel on the in-process port of the link
//! and which a `voelin_proto::link::Session` has no part in until the
//! stream task moves (`docs/session-seam.md` sections 6.4 and 9.2);
//! - the order in which a reconnect shuts the streams and the old connection
//! down, which is the order of the one queue `LinkSession` keeps;
//! - a link that keeps talking after the engine replaced its connection,
//! which a closed `FakeSession` cannot do on purpose.
//!
//! Presence, chat, the dedup of a message that comes twice, history, transfers
//! and the rest of what the engine does with a session are tested on the
//! protocol repository's fake host in `session_fake.rs`. 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,
BackendInfo, Command, Engine, Event, History, SessionId, SessionState, VoiceOptions, VoiceState,
};
use voelin_model::{
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
@@ -25,8 +33,6 @@ use voelin_model::{
/// A connection the session asked the link for.
struct Conn {
options: ConnectOptions,
session: SessionId,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
}
@@ -63,13 +69,12 @@ impl FakeLink {
impl ServerLink for FakeLink {
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
_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);
let _ = self.conns.send(Conn { cmds, events });
}
}
@@ -135,15 +140,6 @@ impl Harness {
})
.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 {
@@ -205,17 +201,6 @@ fn presence() -> Presence {
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),
@@ -229,105 +214,11 @@ fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
}
}
/// Connecting, the server's presence, moving, talking, a failing command
/// and the end of the connection, as the session reports them.
/// Stream commands reach a link that has streams in its capabilities, and
/// end with the connection; a link without them is spared. (The rest of what
/// the user asks for is checked on the fake host in `session_fake.rs`.)
#[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));
// Alice talks: a packet of her voice (the session derives who talks). The
// voice comes from the media path and a poke or an error from the push
// path, and the session orders the two paths in no way, so the test waits
// for the talking before it plays the others.
conn.play([voice_of(8)]);
h.next(|e| matches!(e, Event::Talking { client: 8, talking: true, .. }).then_some(())).await;
conn.play([
LinkEvent::Poke {
from: 8,
from_uid: Some("alice=".into()),
from_name: "alice".into(),
message: "wake up".into(),
},
LinkEvent::Error("move refused".into()),
]);
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() {
async fn stream_commands_reach_a_link_with_streams() {
let mut h = Harness::start();
let mut conn = h.connect().await;
conn.play([
@@ -337,38 +228,8 @@ async fn commands_reach_the_link() {
]);
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 engine = h.engine.clone();
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
let error = h
@@ -442,120 +303,6 @@ async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() {
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() {
File diff suppressed because it is too large. Load diff