radio-cli 0.14.0

A lightweight terminal radio and podcast player
Documentation
use crate::error::{DomainError, ErrorCode};
use anyhow::{Context, Result, bail};
use fs2::FileExt;
use std::{
    fs::{File, OpenOptions},
    io::Read,
    path::Path,
    process::{Child, Command, ExitStatus, Stdio},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    thread,
    time::{Duration, Instant},
};

pub struct MediaLock {
    _file: File,
}

/// Linux must also reap media when the owning frontend is killed abruptly.
pub fn owned_child(command: &mut Command) -> &mut Command {
    #[cfg(target_os = "linux")]
    {
        use std::os::unix::process::CommandExt;
        let parent = std::process::id();
        // Only async-signal-safe operations run between fork and exec.
        unsafe {
            command.pre_exec(move || {
                if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) < 0 {
                    return Err(std::io::Error::last_os_error());
                }
                if libc::getppid() != parent as libc::pid_t {
                    libc::_exit(1);
                }
                Ok(())
            });
        }
    }
    command
}
// Linux ties PDEATHSIG to the spawning thread. Spawn through a persistent
// supervisor so returning a child from a short-lived task does not kill it.
pub fn spawn_owned(command: Command) -> std::io::Result<Child> {
    type Request = (Command, std::sync::mpsc::SyncSender<std::io::Result<Child>>);
    static SPAWNER: std::sync::OnceLock<std::sync::mpsc::Sender<Request>> =
        std::sync::OnceLock::new();
    let sender = SPAWNER.get_or_init(|| {
        let (sender, receiver) = std::sync::mpsc::channel::<Request>();
        thread::Builder::new()
            .name("radio-process-spawner".into())
            .spawn(move || {
                for (mut command, reply) in receiver {
                    let child = owned_child(&mut command).spawn();
                    if let Err(error) = reply.send(child)
                        && let Ok(mut child) = error.0
                    {
                        let _ = child.kill();
                        let _ = child.wait();
                    }
                }
            })
            .expect("cannot start process supervisor");
        sender
    });
    let (reply, result) = std::sync::mpsc::sync_channel(1);
    sender
        .send((command, reply))
        .map_err(|_| std::io::Error::other("process supervisor stopped"))?;
    result
        .recv()
        .map_err(|_| std::io::Error::other("process supervisor stopped"))?
}

impl MediaLock {
    pub fn acquire(dir: &Path) -> Result<Self> {
        let file = OpenOptions::new()
            .create(true)
            .truncate(false)
            .read(true)
            .write(true)
            .open(dir.join("media.lock"))?;
        file.try_lock_exclusive()
            .context(DomainError::new(ErrorCode::MediaBusy))?;
        Ok(Self { _file: file })
    }
}

impl Drop for MediaLock {
    fn drop(&mut self) {
        // A concurrent fork may briefly inherit the open description before
        // exec closes it. Explicitly unlock when the last owner finishes;
        // unrelated children must not prolong the media-session lifetime.
        let _ = fs2::FileExt::unlock(&self._file);
    }
}

pub fn drain(mut reader: impl Read + Send + 'static, cap: usize) -> thread::JoinHandle<Vec<u8>> {
    thread::spawn(move || {
        let mut result = Vec::new();
        let mut buf = [0u8; 4096];
        while let Ok(n) = reader.read(&mut buf) {
            if n == 0 {
                break;
            }
            let room = cap.saturating_sub(result.len());
            result.extend_from_slice(&buf[..n.min(room)]);
        }
        result
    })
}

pub fn wait_until(child: &mut Child, timeout: Duration, stop: &AtomicBool) -> Result<ExitStatus> {
    let deadline = Instant::now() + timeout;
    loop {
        if let Some(status) = child.try_wait()? {
            return Ok(status);
        }
        let cancelled = stop.load(Ordering::Relaxed);
        if cancelled || Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            let code = if cancelled {
                ErrorCode::Cancelled
            } else {
                ErrorCode::ProcessTimeout
            };
            bail!(DomainError::new(code));
        }
        thread::sleep(Duration::from_millis(30));
    }
}

pub fn output(command: &mut Command, timeout: Duration, stop: &Arc<AtomicBool>) -> Result<Vec<u8>> {
    use std::os::fd::OwnedFd;
    use std::os::unix::{net::UnixStream, process::CommandExt};

    // Separate read endpoints let us drain output without ever waiting for
    // EOF from an orphaned descendant that inherited a write endpoint.
    let (mut stdout, out) = UnixStream::pair()?;
    let (mut stderr, err) = UnixStream::pair()?;
    stdout.set_nonblocking(true)?;
    stderr.set_nonblocking(true)?;
    command
        .process_group(0)
        .stdin(Stdio::null())
        .stdout(Stdio::from(OwnedFd::from(out)))
        .stderr(Stdio::from(OwnedFd::from(err)));
    let configured = std::mem::replace(command, Command::new("unused"));
    let program = configured.get_program().to_string_lossy().into_owned();
    let mut child = spawn_owned(configured)
        .context(DomainError::new(ErrorCode::MissingDependency).with("program", program))?;
    let deadline = Instant::now() + timeout;
    let mut data = Vec::new();
    let mut error = Vec::new();
    let result = (|| -> Result<ExitStatus> {
        loop {
            let (out_eof, out_read) = read_available(&mut stdout, &mut data, 256 * 1024)?;
            let (err_eof, err_read) = read_available(&mut stderr, &mut error, 16 * 1024)?;
            if out_eof
                && err_eof
                && let Some(status) = child.try_wait()?
            {
                return Ok(status);
            }
            if stop.load(Ordering::Relaxed) {
                bail!(DomainError::new(ErrorCode::Cancelled));
            }
            if Instant::now() >= deadline {
                bail!(DomainError::new(ErrorCode::ProcessTimeout));
            }
            if !out_read && !err_read {
                thread::sleep(Duration::from_millis(10));
            }
        }
    })();
    if result.is_err() {
        // We have not reaped the group leader, so its ID cannot be reused.
        unsafe {
            libc::kill(-(child.id() as i32), libc::SIGKILL);
        }
        // A wrapper may have moved itself out of the original process group.
        let _ = child.kill();
        let _ = child.wait();
    }
    let status = result?;
    if !status.success() {
        bail!(DomainError::new(ErrorCode::ProcessFailed).with(
            "reason",
            crate::clean_text(&String::from_utf8_lossy(&error))
        ));
    }
    Ok(data)
}

fn read_available(
    reader: &mut impl Read,
    result: &mut Vec<u8>,
    cap: usize,
) -> std::io::Result<(bool, bool)> {
    let mut buf = [0; 8192];
    match reader.read(&mut buf) {
        Ok(0) => Ok((true, false)),
        Ok(n) => {
            result.extend_from_slice(&buf[..n.min(cap.saturating_sub(result.len()))]);
            Ok((false, true))
        }
        Err(e)
            if matches!(
                e.kind(),
                std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
            ) =>
        {
            Ok((false, false))
        }
        Err(e) => Err(e),
    }
}

/// Desktop applications launched by the opener may outlive the radio process.
pub(crate) fn open_directory(
    mut command: Command,
    timeout: Duration,
    stop: &AtomicBool,
) -> Result<()> {
    command
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    let program = command.get_program().to_string_lossy().into_owned();
    let mut child = spawn_owned(command)
        .context(DomainError::new(ErrorCode::MissingDependency).with("program", program))?;
    let status = wait_until(&mut child, timeout, stop)?;
    if !status.success() {
        bail!(DomainError::new(ErrorCode::ProcessFailed).with("reason", status.to_string()));
    }
    Ok(())
}

/// A cancellable task whose blocking I/O never holds up the media owner.
/// Dropping it cancels subprocesses and ignores any late network result.
pub struct Background<T> {
    cancel: Arc<AtomicBool>,
    result: std::sync::mpsc::Receiver<Result<T>>,
}
impl<T: Send + 'static> Background<T> {
    pub fn start(
        name: &str,
        work: impl FnOnce(Arc<AtomicBool>) -> Result<T> + Send + 'static,
    ) -> Result<Self> {
        let cancel = Arc::new(AtomicBool::new(false));
        let flag = cancel.clone();
        let (sender, result) = std::sync::mpsc::sync_channel(1);
        thread::Builder::new().name(name.into()).spawn(move || {
            let _ = sender.send(work(flag));
        })?;
        Ok(Self { cancel, result })
    }
    pub fn poll(&self) -> Option<Result<T>> {
        match self.result.try_recv() {
            Ok(value) => Some(value),
            Err(std::sync::mpsc::TryRecvError::Empty) => None,
            Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(Err(anyhow::anyhow!(
                DomainError::new(ErrorCode::BackgroundFailed)
            ))),
        }
    }

    pub(crate) fn cancel(&self) {
        self.cancel.store(true, Ordering::Relaxed);
    }
}
impl<T> Drop for Background<T> {
    fn drop(&mut self) {
        self.cancel.store(true, Ordering::Relaxed);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn inherited_output_is_bounded_for_probes_and_detached_for_openers() {
        let stop = Arc::default();
        let timeout = Duration::from_millis(150);
        let command = || {
            let mut cmd = Command::new("sh");
            cmd.args(["-c", "sleep 2 & exit 0"]);
            cmd
        };
        let start = Instant::now();
        let err = output(&mut command(), timeout, &stop).unwrap_err();
        assert_eq!(
            err.downcast_ref::<DomainError>().unwrap().code,
            ErrorCode::ProcessTimeout
        );
        open_directory(command(), timeout, &stop).unwrap();
        assert!(start.elapsed() < Duration::from_secs(1));
    }

    #[test]
    fn stopping_a_running_child_reports_cancellation() {
        let mut child = Command::new("sleep").arg("30").spawn().unwrap();
        let error =
            wait_until(&mut child, Duration::from_secs(10), &AtomicBool::new(true)).unwrap_err();
        assert_eq!(
            error.downcast_ref::<DomainError>().unwrap().code,
            ErrorCode::Cancelled
        );
        assert!(child.try_wait().unwrap().is_some());
    }
}