fix: allow TUI exit when server hangs

Restore terminal state before client teardown and bound IPC worker joining to a 25 ms grace period. A worker stuck in an in-flight server request is detached and exits after the request returns and observes cancellation.

Tests: cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features; cargo test --workspace --all-targets --all-features; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features; default/no-default/backend feature checks.
This commit is contained in:
Dandaedre 2026-10-15 22:16:38 +02:00
parent acb0f609cb
commit a6d9dc558f
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
3 changed files with 93 additions and 13 deletions

View File

@ -358,9 +358,9 @@ new-stream policy is `restore`.
Plan `fader_master serve`, `tui`, `validate --config PATH`, `devices`, `status`, and `profile switch ID`. Run one server per user/runtime namespace with an owned Unix socket and lock; TUI disconnect must not stop MIDI control. No network listener. Bound IPC message size and queue sizes, enforce socket permissions/peer identity, negotiate protocol version, use request IDs and revisioned snapshots, and resnapshot after missed deltas. Length-prefixed UTF-8 TOML messages reuse Serde schemas initially; cap frames before allocation.
The TUI owns blocking IPC on a joined background thread. Its render/input thread
reads a shared local snapshot only, applies optimistic volume/mute changes, and
queues work without waiting for a socket response. Pending volume work is
The TUI owns blocking IPC on a background thread. Its render/input thread reads
a shared local snapshot only, applies optimistic volume/mute changes, and queues
work without waiting for a socket response. Pending volume work is
latest-value-per-object; mute presses remain a bounded FIFO. Confirmed snapshots
replace the local base and retain optimistic overlays until observation settles
them. Poll quickly while writes are pending, slowly while idle, and resnapshot
@ -370,6 +370,12 @@ transport failures, surface the connection error inside the terminal, and keep
retrying so starting or restarting the server reconnects without restarting the
TUI.
Quit and terminal restoration are local operations. Terminal state is restored
before client teardown; teardown requests worker cancellation and joins within a
short grace period, but detaches a worker whose in-flight server request remains
wedged. That worker exits after the request returns and observes cancellation,
so a crashed or hung server can never trap the terminal in raw mode.
Mixer-object snapshots also aggregate pickup state across configured physical
volume bindings. They expose `unavailable`, `waiting`, `tracking`, or `mixed`;
controls are instantiated from the profile before discovery so the first live

View File

@ -252,9 +252,11 @@ Dependencies: M3, M2; may proceed after the fake-adapter slice.
burst sends its first in-flight and final buffered values only, stale edits
resnapshot and retry, rapid mute presses remain ordered, and server dispatch
uses bounded backpressure rather than failing on a merely busy worker.
A joined TUI client thread owns IPC, publishes optimistic shared snapshots,
polls at 20 ms while pending and 250 ms while idle, and retains a bounded
128-edge mute FIFO. The live server uses the tested 256-command coalescing
A TUI client thread owns IPC, publishes optimistic shared snapshots, polls at
20 ms while pending and 250 ms while idle, and retains a bounded 128-edge mute
FIFO. Quit restores the terminal before teardown; cooperative workers join in
a short grace period, while a worker stuck in a server request is detached so
it cannot block exit. The live server uses the tested 256-command coalescing
queue ahead of a one-slot Pulse command lane, an independent 256-event
snapshot lane, and a batch event drain. Matching Pulse subscription echoes
retain the originating operation so confirmed writes do not repeatedly re-arm

View File

@ -7,7 +7,10 @@ pub use theme::ThemeName;
use std::{
collections::{BTreeMap, VecDeque},
io,
sync::{Arc, Condvar, Mutex},
sync::{
Arc, Condvar, Mutex,
mpsc::{self, Receiver, RecvTimeoutError},
},
thread::{self, JoinHandle},
time::Duration,
};
@ -27,6 +30,7 @@ const VOLUME_STEP: f64 = 0.05;
const REFRESH_INTERVAL: Duration = Duration::from_millis(100);
const CLIENT_IDLE_REFRESH: Duration = Duration::from_millis(250);
const CLIENT_PENDING_REFRESH: Duration = Duration::from_millis(20);
const CLIENT_SHUTDOWN_GRACE: Duration = Duration::from_millis(25);
const MAX_BUFFERED_MUTE_EDGES: usize = 128;
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
@ -390,6 +394,7 @@ struct BufferedState {
pub struct BufferedMixerClient {
shared: Arc<(Mutex<BufferedState>, Condvar)>,
worker: Option<JoinHandle<()>>,
worker_done: Receiver<()>,
}
impl BufferedMixerClient {
@ -420,10 +425,15 @@ impl BufferedMixerClient {
Condvar::new(),
));
let worker_shared = Arc::clone(&shared);
let worker = thread::spawn(move || client_loop(&mut client, initial, &worker_shared));
let (done_sender, worker_done) = mpsc::sync_channel(1);
let worker = thread::spawn(move || {
client_loop(&mut client, initial, &worker_shared);
let _ = done_sender.send(());
});
Ok(Self {
shared,
worker: Some(worker),
worker_done,
})
}
@ -578,7 +588,16 @@ impl Drop for BufferedMixerClient {
wake.notify_one();
}
if let Some(worker) = self.worker.take() {
let _ = worker.join();
match self.worker_done.recv_timeout(CLIENT_SHUTDOWN_GRACE) {
Ok(()) | Err(RecvTimeoutError::Disconnected) => {
let _ = worker.join();
}
Err(RecvTimeoutError::Timeout) => {
// A wedged server request must not keep the terminal in raw mode.
// Dropping the handle detaches the worker; it observes `shutdown`
// and exits if the request ever returns.
}
}
}
}
}
@ -758,10 +777,11 @@ pub fn run_live_with_theme(
theme: ThemeName,
) -> io::Result<()> {
let client = BufferedMixerClient::spawn(client)?;
let mut app = LiveTui::with_theme(client, theme)?;
let mut terminal = ratatui::init();
with_terminal_restore(ratatui::restore, || {
LiveTui::with_theme(client, theme)?.run(&mut terminal)
})
let result = with_terminal_restore(ratatui::restore, || app.run(&mut terminal));
drop(app);
result
}
/// Retains the original preview example without opening audio or IPC.
@ -2817,7 +2837,13 @@ impl MixerClient for DemoClient {
#[cfg(test)]
mod tests {
use std::{sync::Mutex, time::Instant};
use std::{
sync::{
Mutex,
atomic::{AtomicBool, Ordering},
},
time::Instant,
};
use super::*;
@ -4019,6 +4045,52 @@ mod tests {
assert!(*attempts.lock().unwrap() >= 2);
}
#[test]
fn buffered_client_drop_does_not_wait_for_a_hung_server_request() {
struct HungClient {
entered: Arc<AtomicBool>,
}
impl MixerClient for HungClient {
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
self.entered.store(true, Ordering::Release);
thread::sleep(Duration::from_millis(300));
Err(io::Error::new(io::ErrorKind::TimedOut, "server hung"))
}
fn set_volume(
&mut self,
_: MixerObjectId,
_: f64,
_: u64,
) -> io::Result<MixerSnapshot> {
unreachable!()
}
fn toggle_mute(&mut self, _: MixerObjectId, _: u64) -> io::Result<MixerSnapshot> {
unreachable!()
}
}
let entered = Arc::new(AtomicBool::new(false));
let client = BufferedMixerClient::spawn(HungClient {
entered: Arc::clone(&entered),
})
.unwrap();
let deadline = Instant::now() + Duration::from_secs(1);
while !entered.load(Ordering::Acquire) {
assert!(
Instant::now() < deadline,
"worker did not start its request"
);
thread::yield_now();
}
let started = Instant::now();
drop(client);
assert!(started.elapsed() < Duration::from_millis(75));
}
#[test]
fn buffered_action_resnapshots_and_retries_a_stale_revision() {
struct RevisionClient {