Send the beta14 publisher stop reason and verify stream discovery

This commit is contained in:
omar committed 2026-11-27 08:19:09 +03:00
1 parent c27a425680
commit e52db5b112
7 files changed
+237 -21

No files matched your search

+193 -16
View File
@@ -1,10 +1,12 @@
//! Exercise the compiled diagnostic core's real TeamSpeak voice path over stdio.
//! Exercise the compiled diagnostic core's real TeamSpeak voice and stream control paths over stdio.
//! Build with `cargo build --locked -p teamspeach-core --bin teamspeach-core` and set
//! `TEAMSPEACH_QA_CORE` to the absolute path of that disposable core executable.
//! Duplex: `cargo run --locked -p teamspeach-core --example duplex_qa`.
//! Whisper: `cargo run --locked -p teamspeach-core --example duplex_qa -- --whisper`.
//! Stream registration: `cargo run --locked -p teamspeach-core --example duplex_qa -- --stream-lifecycle`.
//! Requires an already running, private TeamSpeak fixture at 127.0.0.1:19987 with
//! an empty default Opus channel (TS6 beta14 for whisper). No server or audio device is started.
//! an empty default Opus channel (TS6 beta14 for whisper and stream registration).
//! No server or audio device is started.
//! Playback timing uses monotonic send and receive observations: stdio PCM
//! events do not carry a timestamp. This is not a device latency test.
@@ -197,6 +199,15 @@ impl Peer {
}
fn request(&mut self, tones: &[Tone; HZ.len()], cmd: &str, args: Value, timeout: Duration) -> Result<Value> {
let mut reply = self.request_reply(tones, cmd, args, timeout, |_| {})?;
if reply["ok"] != true {
return Err(format!("{}: core rejected {cmd}", self.label));
}
Ok(reply.get_mut("result").map(std::mem::take).unwrap_or(Value::Null))
}
fn request_reply(&mut self, tones: &[Tone; HZ.len()], cmd: &str, args: Value, timeout: Duration,
mut inspect: impl FnMut(&Line)) -> Result<Value> {
let deadline = Instant::now() + timeout;
self.request_number += 1;
let id = self.request_number.to_string();
@@ -205,11 +216,9 @@ impl Peer {
loop {
let line = self.read_before(deadline, cmd)?;
if line.value["id"].as_str() == Some(id.as_str()) {
if line.value["ok"] != true {
return Err(format!("{}: core rejected {cmd}", self.label));
}
return Ok(line.value["result"].clone());
return Ok(line.value);
}
inspect(&line);
self.observe(tones, line)?;
}
}
@@ -711,21 +720,22 @@ fn roster_uid(peer: &Peer, client_id: u64, is_self: bool) -> Option<&str> {
})?["uid"].as_str().filter(|uid| !uid.is_empty())
}
fn is_beta14_default(snapshot: &Value) -> bool {
snapshot["server"]["version"].as_str().is_some_and(|version| {
version.starts_with("6.") && version.split(|c: char| !c.is_ascii_alphanumeric())
.any(|part| part.eq_ignore_ascii_case("beta14"))
}) && snapshot["channels"].as_array().is_some_and(|channels| channels.iter().any(|c| {
c["id"] == snapshot["own_channel_id"] && c["is_default"] == true
}))
}
fn exercise_whisper(exe: &Path, root: &Path) -> Result<String> {
let mut qa = Duplex::open(exe, root, WHISPER_TAGS)?;
let a_id = Duplex::connect(&mut qa.a, &qa.tones)?;
let b_id = Duplex::connect(&mut qa.b, &qa.tones)?;
qa.party(a_id, b_id)?;
for peer in [&qa.a, &qa.b] {
let snapshot = &peer.snapshot;
let beta14 = snapshot["server"]["version"].as_str().is_some_and(|version| {
version.starts_with("6.") && version.split(|c: char| !c.is_ascii_alphanumeric())
.any(|part| part.eq_ignore_ascii_case("beta14"))
});
let in_default = snapshot["channels"].as_array().is_some_and(|channels| channels.iter().any(|c| {
c["id"] == snapshot["own_channel_id"] && c["is_default"] == true
}));
if !beta14 || !in_default {
if !is_beta14_default(&peer.snapshot) {
return Err("whisper QA requires the loopback TS6 beta14 default channel".into());
}
}
@@ -800,12 +810,179 @@ fn exercise_whisper(exe: &Path, root: &Path) -> Result<String> {
first.frames, again.frames, voice.frames))
}
fn stream_owner(row: &Value) -> Option<u64> {
row["clid"].as_str()?.parse().ok()
}
fn stream_notification<T>(line: &Line, since: Instant, event: &str,
find: &mut impl FnMut(&Value) -> Option<T>) -> Option<T> {
if line.at < since || line.value["event"] != "stream" || line.value["name"] != event {
return None;
}
// A raw TS notification may have multiple pipe-separated rows.
line.value["items"].as_array()?.iter().find_map(find)
}
fn wait_stream_notification<T>(peer: &mut Peer, tones: &[Tone; HZ.len()], since: Instant,
event: &str, mut find: impl FnMut(&Value) -> Option<T>) -> Result<T> {
let deadline = Instant::now() + CONTROL;
let stage = format!("fresh matching {event}");
loop {
let line = peer.read_before(deadline, &stage)?;
let matched = stream_notification(&line, since, event, &mut find);
peer.observe(tones, line)?;
if let Some(value) = matched {
return Ok(value);
}
}
}
fn require_stream_ack(peer: &Peer, cmd: &str, reply: &Value, target: Option<u64>) -> Result<()> {
let refused = |error: &Value| {
let label = peer.label;
match error["ts_error"]["id"].as_u64() {
Some(2568) => format!("{label}: {cmd}: permission refused (ts_error.id=2568)"),
Some(id) => format!("{label}: {cmd}: server refused (ts_error.id={id})"),
None => format!("{label}: core rejected {cmd}"),
}
};
if reply["ok"] != true {
return Err(refused(&reply["error"]));
}
if let Some(target) = target {
let Some([row]) = reply["result"]["results"].as_array().map(Vec::as_slice) else {
return Err("stream_list: expected one targeted acknowledgement".into());
};
if row["client_id"].as_u64() != Some(target) {
return Err("stream_list: acknowledgement did not match publisher client ID".into());
}
if row["ok"] != true {
return Err(refused(row.get("error").unwrap_or(row)));
}
}
println!("{cmd}: server acknowledged");
Ok(())
}
fn request_stream_event<T>(peer: &mut Peer, tones: &[Tone; HZ.len()], cmd: &str, args: Value,
target: Option<u64>, event: &str, mut find: impl FnMut(&Value) -> Option<T>) -> Result<T> {
peer.pump(tones)?;
let since = Instant::now();
let mut matched = None;
// The notification and command reply are independent and may arrive in either order.
let reply = peer.request_reply(tones, cmd, args, CONTROL, |line| {
if matched.is_none() {
matched = stream_notification(line, since, event, &mut find);
}
})?;
require_stream_ack(peer, cmd, &reply, target)?;
match matched {
Some(value) => Ok(value),
None => wait_stream_notification(peer, tones, since, event, find),
}
}
fn stream_lifecycle(qa: &mut Duplex, name: &str) -> Result<()> {
for peer in [&mut qa.a, &mut qa.b] {
let mute = peer.request(&qa.tones, "set_audio", json!({"input_muted": true, "output_muted": true}), CONTROL)?;
if mute["input_muted"] != true || mute["output_muted"] != true {
return Err(format!("{}: both mutes must be active before connect", peer.label));
}
}
let publisher = Duplex::connect(&mut qa.a, &qa.tones)?;
let observer = Duplex::connect(&mut qa.b, &qa.tones)?;
if publisher == 0 || observer == 0 {
return Err("connect returned a zero client ID".into());
}
qa.party(publisher, observer)?;
if ![&qa.a, &qa.b].into_iter().all(|peer| is_beta14_default(&peer.snapshot)) {
return Err("stream lifecycle QA requires the private loopback TS6 beta14 default channel".into());
}
qa.wait_until("both muted peers and self IDs in both rosters", CONTROL, |qa| {
[(&qa.a, publisher, observer), (&qa.b, observer, publisher)].into_iter().all(|(peer, own, other)| {
peer.snapshot["clients"].as_array().is_some_and(|clients| {
[(own, true), (other, false)].into_iter().all(|(id, is_self)| clients.iter().any(|client| {
client["id"].as_u64() == Some(id) && client["is_self"].as_bool() == Some(is_self)
&& client["input_muted"] == true && client["output_muted"] == true
}))
})
})
})?;
println!("connect: private loopback TS6 beta14; two disposable guests, roster IDs verified, both mutes active");
let stream_id = request_stream_event(&mut qa.a, &qa.tones, "stream_setup", json!({
"name": name, "type": 2, "accessibility": 1, "mode": 1, "bitrate": 1000, "viewer_limit": 0, "audio": false,
}), None, "notifystreamstarted", |row| {
(stream_owner(row) == Some(publisher)).then(|| row["id"].as_str().filter(|id| !id.is_empty()).map(str::to_owned)).flatten()
})?;
println!("publisher: fresh own notifystreamstarted supplied the registered stream ID");
let listed = request_stream_event(&mut qa.b, &qa.tones, "stream_list", json!({"client_id": publisher}),
Some(publisher), "notifystreaminfo", |row| {
(row["id"].as_str() == Some(stream_id.as_str()) && row["name"].as_str() == Some(name)
&& stream_owner(row) == Some(publisher)).then_some(())
});
if listed.is_ok() {
println!("observer: fresh notifystreaminfo matched the exact registered ID, name, and owner");
}
// If discovery failed, still unregister the exact ID before disconnecting.
let stopped = (|| {
let since = Instant::now();
let reply = qa.a.request_reply(&qa.tones, "stream_stop", json!({"stream_id": &stream_id}), CONTROL, |_| {})?;
require_stream_ack(&qa.a, "stream_stop", &reply, None)?;
let matched_by = wait_stream_notification(&mut qa.b, &qa.tones, since, "notifystreamstopped", |row| {
match row.get("id").map(Value::as_str) {
None | Some(Some("")) => (stream_owner(row) == Some(publisher)).then_some("publisher ID"),
Some(Some(id)) => (id == stream_id).then_some("stream ID"),
Some(None) => None,
}
})?;
println!("observer: fresh notifystreamstopped matched by {matched_by}");
Ok(())
})();
match (listed, stopped) {
(Ok(()), result) | (result, Ok(())) => result,
(Err(list), Err(stop)) => Err(format!("{list}; {stop}")),
}
}
fn exercise_stream_lifecycle(exe: &Path, root: &Path) -> Result<String> {
let scratch = root.file_name().and_then(|name| name.to_str()).ok_or("missing QA scratch name")?;
let mut qa = Duplex::open(exe, root, [None; HZ.len()])?;
let result = stream_lifecycle(&mut qa, &format!("Peach stream {scratch}"));
let mut errors = Vec::new();
if let Err(error) = result {
errors.push(error);
}
let mut confirmed = 0;
for peer in [&mut qa.a, &mut qa.b] {
if matches!(peer.state, Some("connecting" | "connected")) {
match Duplex::disconnect(peer, &qa.tones) {
Ok(true) => confirmed += 1,
Ok(false) => {},
Err(error) => errors.push(error),
}
}
}
for peer in [&mut qa.a, &mut qa.b] {
if let Err(error) = peer.shutdown(&qa.tones) {
errors.push(error);
}
}
if !errors.is_empty() {
return Err(errors.join("; "));
}
Ok(format!("Stream registration IPC passed. Both cores shut down; server confirmed {confirmed}/2 disconnects. No media or device audio was used."))
}
fn run() -> Result<String> {
let mut args = std::env::args_os().skip(1);
let exercise = match (args.next(), args.next()) {
(None, None) => exercise,
(Some(flag), None) if flag == "--whisper" => exercise_whisper,
_ => return Err("usage: duplex_qa [--whisper]".into()),
(Some(flag), None) if flag == "--stream-lifecycle" => exercise_stream_lifecycle,
_ => return Err("usage: duplex_qa [--whisper | --stream-lifecycle]".into()),
};
let exe = std::env::var_os("TEAMSPEACH_QA_CORE").map(PathBuf::from)
.filter(|path| path.is_absolute() && path.is_file())
+3 -2
View File
@@ -80,7 +80,8 @@ pub fn publish_stream(a: &crate::protocol::StreamPublishArgs) -> OutCommand {
}
pub fn stop_stream(stream_id: &str) -> OutCommand {
build(StreamVerb::StopStream, &[("id", stream_id)])
// beta14 requires the reason even for a publisher ending its own stream (LEFT = 1).
build(StreamVerb::StopStream, &[("id", stream_id), ("reason", "1")])
}
pub fn respond_stream(stream_id: &str, client_id: u16, decision: bool, offer: &str, message: &str) -> OutCommand {
@@ -366,7 +367,7 @@ mod tests {
assert_eq!(std::str::from_utf8(&content(respond_stream("7", 4, false, "", "not_authorized"))).unwrap(),
"respondjoinstreamrequest id=7 clid=4 decision=0 offer msg=not_authorized");
assert_eq!(std::str::from_utf8(&content(remove_stream_client("7", 4))).unwrap(), "removeclientfromstream id=7 clid=4 reason=4");
assert_eq!(std::str::from_utf8(&content(stop_stream("7"))).unwrap(), "stopstream id=7");
assert_eq!(std::str::from_utf8(&content(stop_stream("7"))).unwrap(), "stopstream id=7 reason=1");
}
#[test]