Files
VoelinClient/crates/voelin-core/src/link/fake_tests.rs
T
faumarayandClaude Sonnet 5.5 4bd3d7a971 deps: voelin-identity, voelin-proto and voelin-model at VoelinProtocol c5bb6b9 (Phase 2 task 34)
The three protocol crates move together, as docs/building.md says: the
identity crate depends on voelin-proto of the same revision, so moving it
alone would put two voelin-proto packages in the lock.

c5bb6b9 is the protocol's main with task 34 (open question 10): the provided
KeyStore::sign_out keeps the device key whatever AccountRecord.bound_existing_key
says (only DeviceKeyChoice::Forget deletes it), and the crate gains Adoption,
Release and REVOCATION_KIND_RELEASED. Nothing in the workspace needed a source
change to compile (cargo check --workspace --all-targets --locked is clean on
1.94); the conformance Fixture of voelin-proto now holds an Arc<dyn Backend>,
and FakeHandle implements it, so the two callers build as they were. The
suite still has 17 cases, in the same order, so the two comments that named
the old revision name c5bb6b9.

Cargo.lock: the three source lines only. `cargo update -p ...` also flips
windows-sys 0.52 to 0.61 and itertools 0.14 to 0.13 in unrelated entries;
those are not taken, `--locked` accepts the file without them.
THIRD_PARTY_NOTICES.md regenerated (scripts/notices.sh): unchanged, the
workspace and git crates are not in it.

The voelin-store tests that pinned the old sign-out (a key made for the
account is deleted by Auto) are turned around here, in the same commit,
because they cannot pass with the new trait: the key stays, unbound, and only
Forget deletes it. The rest of the sign-out follow-up (the module documents,
the refusal wording, the new tests) is the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 06:53:29 +03:00

323 lines
11 KiB
Rust

//! The engine's side of the seam against the protocol repository's fake host
//! (`docs/session-seam.md` sections 9.2 and 16): the voice path through a
//! `SessionLink` that talks to a `FakeSession`, and the link conformance
//! suite run against the session the engine's registry hands over.
//!
//! The tests that need only the engine's public API are in
//! `tests/session_fake.rs`; these need what is private to the crate: the
//! `LinkCmd`/`LinkEvent` vocabulary between `session.rs` and `SessionLink`,
//! the registry's `connect` and the context of a connector called outside an
//! engine.
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaClass, MediaPacket, voice_sub};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
use voelin_proto::test_util::{
FAKE_HOST_UID, FakeConnector, FakeHandle, connect_params, eventually,
};
use voelin_proto::v1::{self, entity::Kind};
use super::*;
const WAIT: Duration = Duration::from_secs(10);
/// An Opus frame of 20 ms, mono (TOC `0xf8`), and the same as stereo (`0xfc`).
const MONO: [u8; 3] = [0xf8, 0xff, 0xfe];
const STEREO: [u8; 3] = [0xfc, 0xff, 0xfe];
const ALICE: u32 = 50;
const ALICE_SLOT: u32 = 90;
const BOB: u32 = 51;
const BOB_SLOT: u32 = 91;
fn put(connector: &FakeConnector, kind: Kind) {
connector.host().put(v1::Entity { kind: Some(kind) }).expect("the fake host stores it");
}
/// A host with one server, a lobby, and alice and bob talking in it.
fn host() -> FakeConnector {
let connector = FakeConnector::new();
put(
&connector,
Kind::Server(v1::Server {
id: 1,
name: "Fake Host".into(),
uid: "fake-host".into(),
default_channel_id: 10,
..Default::default()
}),
);
put(
&connector,
Kind::Channel(v1::Channel {
id: 10,
server_id: 1,
kind: v1::ChannelKind::Voice as i32,
name: "Lobby".into(),
..Default::default()
}),
);
for (user, participant, slot, name) in
[(2, ALICE, ALICE_SLOT, "alice"), (3, BOB, BOB_SLOT, "bob")]
{
put(
&connector,
Kind::User(v1::User {
id: user,
uid: vec![user as u8; 32].into(),
uid_kind: v1::IdKind::Voelin as i32,
name: name.into(),
..Default::default()
}),
);
put(
&connector,
Kind::Voice(v1::VoiceState {
server_id: 1,
participant_id: participant,
user_id: user,
channel_id: 10,
slot,
nick: name.into(),
..Default::default()
}),
);
}
connector
}
/// A `SessionLink` over a fake host, driven the way `session.rs` drives it.
struct HostRig {
handle: FakeHandle,
cmds: mpsc::UnboundedSender<LinkCmd>,
events: mpsc::UnboundedReceiver<LinkEvent>,
/// Our participant and voice slot, as the host gave them.
own_client: u16,
own_slot: u32,
/// The clients the link told started talking, in order.
talking: Vec<u16>,
}
/// The next event `f` picks from `events`, skipping the others.
async fn event_of<T>(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
mut f: impl FnMut(LinkEvent) -> Option<T>,
) -> T {
tokio::time::timeout(WAIT, async {
loop {
if let Some(t) = f(events.recv().await.expect("the link lives")) {
return t;
}
}
})
.await
.expect("an event in time")
}
impl HostRig {
async fn connect() -> Self {
let connector = host();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let link = SessionLink::new(backends);
let (cmds, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
let ctx = LocalCtx::standalone().link;
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
let own_client = event_of(&mut events, |e| match e {
LinkEvent::Connected { own_client, .. } => Some(own_client),
_ => None,
})
.await;
event_of(&mut events, |e| matches!(e, LinkEvent::OwnChannel(10)).then_some(())).await;
let own_slot = connector
.host()
.entities(&v1::Scope { kind: v1::ScopeKind::Live as i32, id: 1 })
.into_iter()
.find_map(|e| match e.kind? {
Kind::Voice(v) if v.participant_id == u32::from(own_client) => Some(v.slot),
_ => None,
})
.expect("the host seated us in voice");
let handle = connector.last_session().expect("the connector made a session");
Self { handle, cmds, events, own_client, own_slot, talking: Vec::new() }
}
/// The next voice packet the audio thread would get; who started to talk on
/// the way is kept in `talking`.
async fn audio(&mut self) -> VoicePacket {
let talking = &mut self.talking;
event_of(&mut self.events, |e| match e {
LinkEvent::Talking { client, talking: true } => {
talking.push(client);
None
}
LinkEvent::Audio(packet) => Some(packet),
_ => None,
})
.await
}
fn give(&self, cmd: LinkCmd) {
self.cmds.send(cmd).expect("the link listens");
}
}
/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it.
fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket {
let flow = FlowId::new(slot, sub);
let mut out = bytes::BytesMut::new();
RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960)
.write(flow, &mut out)
.expect("a header");
out.extend_from_slice(payload);
MediaPacket { flow, rtp: out.freeze() }
}
fn voice(payload: &[u8]) -> EncodedVoice {
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
}
/// Our voice leaves as RTP on the slot the host gave us: the sequence counts
/// every packet, the timestamp advances by the duration of the previous one,
/// the marker is on the first packet of a spurt, the end of a spurt is an
/// empty payload sent once, and the SSRC is the flow (protocol section 6).
#[tokio::test(flavor = "multi_thread")]
async fn our_voice_is_rtp_on_the_slot_the_host_gave_us() {
let rig = HostRig::connect().await;
// The fake host loops accepted media back; this test looks at what left.
rig.handle.set_loopback(false);
for n in 1..=3 {
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, n])));
}
rig.give(LinkCmd::Audio(voice(&[])));
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, 9])));
let handle = rig.handle.clone();
eventually(WAIT, "the five packets", || handle.sent_media().len() == 5).await;
let flow = FlowId::new(rig.own_slot, voice_sub::CHANNEL);
let sent = rig.handle.sent_media();
let seen: Vec<_> = sent
.iter()
.map(|(class, packet)| {
let view = RtpView::parse(&packet.rtp).expect("RTP");
assert_eq!(*class, MediaClass::Voice);
assert_eq!(packet.flow, flow);
assert_eq!((view.payload_type(), view.ssrc()), (PT_OPUS, flow.0));
(view.sequence(), view.marker(), view.timestamp(), view.payload().to_vec())
})
.collect();
let ticks = OPUS_20_MS_TICKS;
assert_eq!(
seen,
[
(0, true, 0, vec![0xf8, 0xff, 0xfe, 1]),
(1, false, ticks, vec![0xf8, 0xff, 0xfe, 2]),
(2, false, 2 * ticks, vec![0xf8, 0xff, 0xfe, 3]),
// The end of the spurt: no payload, no marker, once.
(3, false, 3 * ticks, vec![]),
// The next spurt marks its first packet again.
(4, true, 3 * ticks, vec![0xf8, 0xff, 0xfe, 9]),
]
);
}
/// The RTP of other slots becomes the packets of the audio thread: the talker
/// is the participant of the slot, a whisper sub-flow is a whisper, a stereo
/// Opus frame is music, an empty payload ends the spurt; what is no voice of a
/// slot the host told about is dropped.
#[tokio::test(flavor = "multi_thread")]
async fn the_voice_of_other_slots_reaches_the_audio_thread() {
let mut rig = HostRig::connect().await;
let handle = rig.handle.clone();
// A slot nobody has, a probe and feedback: nothing. Then alice, mono.
handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &MONO));
handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) });
handle.inject_media(MediaPacket {
flow: FlowId::FEEDBACK,
rtp: bytes::Bytes::from_static(&[1, 2]),
});
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 5, &MONO));
let packet = rig.audio().await;
assert_eq!(
(packet.talker.0, packet.seq, packet.codec, packet.whisper, packet.payload.as_slice()),
(ALICE as u16, 5, VoiceCodec::Voice, false, MONO.as_slice())
);
// Bob whispers (sub-flow 1) in stereo: music, a whisper.
handle.inject_media(voice_packet(BOB_SLOT, 1, 6, &STEREO));
let packet = rig.audio().await;
assert_eq!(
(packet.talker.0, packet.seq, packet.codec, packet.whisper),
(BOB as u16, 6, VoiceCodec::Music, true)
);
// Alice stops: an empty payload.
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 7, &[]));
let packet = rig.audio().await;
assert_eq!((packet.talker.0, packet.seq, packet.payload.len()), (ALICE as u16, 7, 0));
// Who talks comes from the same packets: alice started, then bob, once each
// (the slot nobody has started nobody).
assert_eq!(rig.talking, [ALICE as u16, BOB as u16]);
}
/// A host whose session loops our own voice back (the fake one does, so that
/// the conformance suite can see media move) does not make the engine play us
/// our own voice or show us as talking: the engine never plays itself.
#[tokio::test(flavor = "multi_thread")]
async fn our_own_voice_coming_back_is_not_played_back() {
let mut rig = HostRig::connect().await;
// The fake host loops accepted media back into the sink (the default).
rig.give(LinkCmd::Audio(voice(&MONO)));
let handle = rig.handle.clone();
eventually(WAIT, "the packet to leave", || handle.sent_media().len() == 1).await;
// A packet of alice behind it: when this one is out, ours has been through.
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &MONO));
let own = rig.own_client;
let mut heard = Vec::new();
while heard.last().is_none_or(|talker| *talker != ALICE as u16) {
heard.push(rig.audio().await.talker.0);
}
assert!(!heard.contains(&own), "the engine played our own voice back: {heard:?}");
}
/// The link conformance suite of the protocol repository against the session
/// the engine's registry hands over: the registry adds nothing to a plain
/// connector's session (`Backends::connect` returns it untouched), so the 17
/// cases pass as they do in the protocol repository, none skipped.
#[tokio::test(flavor = "multi_thread")]
async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
async fn through_the_registry() -> Fixture {
let connector = FakeConnector::new();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let (params, media) = connect_params("fake://conformance");
let local = backends
.connect(params, LocalCtx::standalone())
.await
.unwrap_or_else(|e| panic!("the registry connects: {e}"));
assert_eq!(local.connected.host_uid, FAKE_HOST_UID, "the connector's own answer");
assert!(local.streams.is_none(), "a plain connector has no stream port");
let backend = connector.last_session().expect("the connector made a session");
// The session is the connector's own, so a request id means the same to both.
Fixture {
shared_request_ids: true,
..Fixture::new(local.connected.session, local.connected.pushes, media, backend)
}
}
let report = conformance::run(&through_the_registry).await;
assert_eq!(report.cases.len(), conformance::CASES.len());
assert_eq!(report.cases.len(), 17, "the suite of c5bb6b9 has 17 cases");
assert!(
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
"{:?}",
report.cases
);
}