test(M4.4): exercise a real Pulse daemon

Add opt-in fixtures that isolate control to a uniquely named silent paplay stream, verify worker and independent-client convergence plus stream churn, and explicitly gate disruptive PipeWire restart/resnapshot coverage. Detect failed or terminated Pulse contexts while polling.

Tests: cargo test -p volume_lib --all-targets --all-features; cargo clippy -p volume_lib --all-targets --all-features -- -D warnings; cargo check -p volume_lib --all-targets --no-default-features; cargo test --locked -p volume_lib --test pulse_daemon --all-features real_stream_commands_external_edits_and_churn_converge -- --ignored --nocapture (PipeWire 1.6.9)
This commit is contained in:
Dandaedre 2026-10-14 22:18:22 +02:00
parent ce31b6b0fb
commit ef4b63d4f8
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
2 changed files with 373 additions and 0 deletions

View File

@ -140,6 +140,12 @@ impl PulseClient {
};
let deadline = Instant::now() + timeout;
while notifications.borrow().is_empty() {
match self.context.get_state() {
State::Failed | State::Terminated => {
return Err(PulseError::ContextState(self.context.get_state()));
}
_ => {}
}
if Instant::now() >= deadline {
return Ok(None);
}

367
sound/tests/pulse_daemon.rs Normal file
View File

@ -0,0 +1,367 @@
#![cfg(feature = "pulse")]
use std::{
collections::BTreeMap,
io,
process::{Child, Command, Stdio},
sync::mpsc::RecvTimeoutError,
thread,
time::{Duration, Instant},
};
use fader_core::{
AdapterCommand, AdapterEvent, BackendEpoch, ChannelGains, Gain, MetadataField, Mute,
OperationId, StreamHandle,
};
use volume_lib::{PulseClient, PulseWorker, RetrySchedule, WorkerEvent};
const EVENT_TIMEOUT: Duration = Duration::from_secs(8);
const FIXTURE_GAIN_TOLERANCE: f64 = 0.001;
struct SilentPlayback {
child: Child,
}
impl SilentPlayback {
fn spawn(name: &str) -> io::Result<Self> {
let child = Command::new("paplay")
.args([
"--raw",
"--rate=48000",
"--format=s16le",
"--channels=2",
&format!("--client-name={name}"),
&format!("--stream-name={name}"),
&format!("--property=application.name={name}"),
"/dev/zero",
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;
Ok(Self { child })
}
}
impl Drop for SilentPlayback {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
#[derive(Default)]
struct Observations {
matching: BTreeMap<StreamHandle, bool>,
}
impl Observations {
fn record_metadata(
&mut self,
stream: StreamHandle,
metadata: &fader_core::StreamMetadata,
fixture_name: &str,
) {
self.matching.insert(
stream,
metadata.value(MetadataField::ApplicationName) == Some(fixture_name),
);
}
fn is_fixture(&self, stream: StreamHandle) -> bool {
self.matching.get(&stream).copied().unwrap_or(false)
}
}
fn receive_until<T>(
worker: &PulseWorker,
observations: &mut Observations,
fixture_name: &str,
mut select: impl FnMut(&WorkerEvent, &Observations) -> Option<T>,
) -> T {
let deadline = Instant::now() + EVENT_TIMEOUT;
loop {
let remaining = deadline
.checked_duration_since(Instant::now())
.expect("timed out waiting for Pulse fixture event");
let event = worker
.receive_timeout(remaining)
.expect("Pulse worker disconnected before the expected fixture event");
println!("fixture event: {event:?}");
if let WorkerEvent::StreamMetadata {
stream, metadata, ..
} = &event
{
observations.record_metadata(*stream, metadata, fixture_name);
}
if let WorkerEvent::Disconnected { message, .. } = &event {
panic!("Pulse worker disconnected during fixture: {message}");
}
if let Some(value) = select(&event, observations) {
return value;
}
}
}
fn wait_for_fixture_stream(
worker: &PulseWorker,
observations: &mut Observations,
fixture_name: &str,
) -> (StreamHandle, ChannelGains, Mute) {
receive_until(
worker,
observations,
fixture_name,
|event, observations| match event {
WorkerEvent::Adapter(AdapterEvent::Observed {
stream,
channels,
muted,
..
}) if observations.is_fixture(*stream) => Some((*stream, channels.clone(), *muted)),
_ => None,
},
)
}
fn wait_for_operation(
worker: &PulseWorker,
observations: &mut Observations,
fixture_name: &str,
expected: OperationId,
) -> (ChannelGains, Mute) {
receive_until(worker, observations, fixture_name, |event, _| match event {
WorkerEvent::Adapter(AdapterEvent::Observed {
channels,
muted,
operation: Some(operation),
..
}) if *operation == expected => Some((channels.clone(), *muted)),
_ => None,
})
}
fn wait_for_external_state(
worker: &PulseWorker,
observations: &mut Observations,
fixture_name: &str,
handle: StreamHandle,
gain: Gain,
muted: Mute,
) {
receive_until(worker, observations, fixture_name, |event, _| match event {
WorkerEvent::Adapter(AdapterEvent::Observed {
stream,
channels,
muted: actual_mute,
operation: None,
}) if *stream == handle
&& *actual_mute == muted
&& (channels.maximum().get() - gain.get()).abs() <= FIXTURE_GAIN_TOLERANCE =>
{
Some(())
}
_ => None,
});
}
fn equal_channels(count: usize, gain: Gain) -> ChannelGains {
ChannelGains::new(vec![gain; count]).expect("fixture stream has at least one channel")
}
/// Opt-in: creates and controls only a uniquely named silent playback stream.
#[test]
#[ignore = "requires a live PulseAudio-compatible daemon and paplay"]
fn real_stream_commands_external_edits_and_churn_converge() {
let fixture_name = format!("fader-master-fixture-{}", std::process::id());
let mut playback = SilentPlayback::spawn(&fixture_name).expect("spawn silent paplay fixture");
let mut worker = PulseWorker::spawn(BackendEpoch::new(1), 512);
let mut observations = Observations::default();
let (handle, initial_channels, _) =
wait_for_fixture_stream(&worker, &mut observations, &fixture_name);
let worker_gain = Gain::new(0.35).unwrap();
worker
.try_submit(AdapterCommand::SetVolume {
operation: OperationId::new(1),
stream: handle,
channels: equal_channels(initial_channels.as_slice().len(), worker_gain),
})
.expect("queue fixture worker volume");
let (channels, _) = wait_for_operation(
&worker,
&mut observations,
&fixture_name,
OperationId::new(1),
);
assert!((channels.maximum().get() - worker_gain.get()).abs() <= FIXTURE_GAIN_TOLERANCE);
worker
.try_submit(AdapterCommand::SetMute {
operation: OperationId::new(2),
stream: handle,
muted: Mute::Muted,
})
.expect("queue fixture worker mute");
let (_, muted) = wait_for_operation(
&worker,
&mut observations,
&fixture_name,
OperationId::new(2),
);
assert_eq!(muted, Mute::Muted);
let mut external = PulseClient::connect().expect("connect independent external client");
let index = u32::try_from(handle.backend_id()).expect("Pulse index fits u32");
let external_gain = Gain::new(0.65).unwrap();
let current = external
.stream(index)
.expect("read fixture from external client");
external
.set_volume(
index,
&equal_channels(current.channels.as_slice().len(), external_gain),
)
.expect("external fixture volume write");
external
.set_mute(index, Mute::Unmuted)
.expect("external fixture unmute");
wait_for_external_state(
&worker,
&mut observations,
&fixture_name,
handle,
external_gain,
Mute::Unmuted,
);
drop(playback);
receive_until(
&worker,
&mut observations,
&fixture_name,
|event, _| match event {
WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream }) if *stream == handle => {
Some(())
}
_ => None,
},
);
playback = SilentPlayback::spawn(&fixture_name).expect("respawn silent paplay fixture");
let (replacement, _, _) = wait_for_fixture_stream(&worker, &mut observations, &fixture_name);
assert_ne!(replacement, handle);
drop(playback);
assert!(worker.shutdown());
assert!(!worker.event_overflowed());
}
/// Opt-in and disruptive: restarts the current user's PipeWire audio services.
#[test]
#[ignore = "set FADER_MASTER_RESTART_PIPEWIRE=1; interrupts desktop audio"]
fn pipewire_restart_disconnects_and_a_new_epoch_resnapshots() {
assert_eq!(
std::env::var("FADER_MASTER_RESTART_PIPEWIRE").as_deref(),
Ok("1"),
"set FADER_MASTER_RESTART_PIPEWIRE=1 to acknowledge desktop audio interruption"
);
let mut worker = PulseWorker::spawn(BackendEpoch::new(20), 512);
wait_for_snapshot(&worker);
let status = Command::new("systemctl")
.args([
"--user",
"restart",
"pipewire.service",
"pipewire-pulse.service",
"wireplumber.service",
])
.status()
.expect("run systemctl user restart");
assert!(status.success(), "PipeWire user-service restart failed");
wait_for_disconnect(&worker);
assert!(worker.shutdown());
let mut retries = RetrySchedule::new(100, 1_000);
let deadline = Instant::now() + Duration::from_secs(10);
let mut epoch = BackendEpoch::new(21);
loop {
thread::sleep(Duration::from_millis(retries.next_delay_ms()));
let mut replacement = PulseWorker::spawn(epoch, 512);
match wait_for_ready_or_disconnect(&replacement) {
true => {
wait_for_snapshot_end(&replacement);
assert!(replacement.shutdown());
break;
}
false => {
assert!(replacement.shutdown());
assert!(
Instant::now() < deadline,
"PipeWire did not recover in time"
);
epoch = epoch.checked_next().expect("fixture epoch space");
}
}
}
}
fn wait_for_snapshot(worker: &PulseWorker) {
assert!(wait_for_ready_or_disconnect(worker));
wait_for_snapshot_end(worker);
}
fn wait_for_ready_or_disconnect(worker: &PulseWorker) -> bool {
let deadline = Instant::now() + EVENT_TIMEOUT;
loop {
let remaining = deadline
.checked_duration_since(Instant::now())
.expect("timed out waiting for Pulse readiness");
match worker.receive_timeout(remaining) {
Ok(WorkerEvent::Ready { .. }) => return true,
Ok(WorkerEvent::Disconnected { message, .. }) => {
println!("fixture reconnect attempt failed: {message}");
return false;
}
Ok(event) => println!("fixture readiness event: {event:?}"),
Err(error) => panic!("Pulse readiness channel failed: {error}"),
}
}
}
fn wait_for_snapshot_end(worker: &PulseWorker) {
let deadline = Instant::now() + EVENT_TIMEOUT;
loop {
let remaining = deadline
.checked_duration_since(Instant::now())
.expect("timed out waiting for Pulse snapshot end");
match worker.receive_timeout(remaining) {
Ok(WorkerEvent::SnapshotEnd(_)) => return,
Ok(WorkerEvent::Disconnected { message, .. }) => {
panic!("Pulse disconnected during snapshot: {message}");
}
Ok(event) => println!("fixture snapshot event: {event:?}"),
Err(error) => panic!("Pulse snapshot channel failed: {error}"),
}
}
}
fn wait_for_disconnect(worker: &PulseWorker) {
let deadline = Instant::now() + EVENT_TIMEOUT;
loop {
let remaining = deadline
.checked_duration_since(Instant::now())
.expect("timed out waiting for daemon disconnect");
match worker.receive_timeout(remaining) {
Ok(WorkerEvent::Disconnected { message, .. }) => {
println!("fixture observed expected disconnect: {message}");
return;
}
Ok(event) => println!("fixture pre-disconnect event: {event:?}"),
Err(RecvTimeoutError::Timeout) => panic!("daemon restart produced no disconnect"),
Err(RecvTimeoutError::Disconnected) => {
panic!("worker exited without a Disconnected diagnostic")
}
}
}
}