simulcrypt 0.2.0

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
//! `tokio::spawn` that does not let a panic in a background task go unnoticed.

use std::future::Future;

use tokio::task::AbortHandle;

/// Spawns `fut` as a background task and returns an `AbortHandle` to cancel it - like plain
/// `tokio::spawn`, but also logs via `tracing::error!` when the task ends with a panic. Otherwise a
/// panic in a task such as the ECMG driver loop or the EMMG accept loop only lands in stderr
/// through tokio's default panic hook: the CAS channel silently goes quiet, with no trace in
/// `tracing` or `Simulcrypt::status()`.
pub fn spawn_supervised<F>(name: impl Into<String>, fut: F) -> AbortHandle
where
    F: Future<Output = ()> + Send + 'static,
{
    let name = name.into();
    let handle = tokio::spawn(fut);
    let abort_handle = handle.abort_handle();

    tokio::spawn(async move {
        match handle.await {
            Ok(()) => {}
            // Cancelled explicitly (e.g. `Drop for Service`) - expected, not an error.
            Err(join_error) if join_error.is_cancelled() => {}
            Err(join_error) => {
                tracing::error!(
                    task = %name,
                    error = %join_error,
                    "background task panicked"
                );
            }
        }
    });

    abort_handle
}

#[cfg(test)]
mod tests {
    use std::sync::{
        Arc,
        atomic::{
            AtomicBool,
            Ordering,
        },
    };

    use super::*;

    #[tokio::test]
    async fn spawn_supervised_returns_working_abort_handle() {
        let started = Arc::new(AtomicBool::new(false));
        let started_task = Arc::clone(&started);

        let abort_handle = spawn_supervised("test", async move {
            started_task.store(true, Ordering::SeqCst);
            std::future::pending::<()>().await;
        });

        tokio::task::yield_now().await;
        assert!(started.load(Ordering::SeqCst), "task must actually run");

        abort_handle.abort();
        tokio::task::yield_now().await;
        assert!(abort_handle.is_finished(), "aborted task must stop");
    }

    #[tokio::test]
    async fn spawn_supervised_survives_a_panicking_task() {
        // The log itself is not checked (that would tie the test to `tracing` subscriber details) -
        // only that a panicking task neither brings down the caller nor poisons the runtime for
        // other tasks.
        let abort_handle = spawn_supervised("test", async {
            panic!("simulated task panic");
        });

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        assert!(
            abort_handle.is_finished(),
            "the panicked task must be observably finished, not stuck"
        );

        // The runtime is still alive and schedules other tasks as usual.
        tokio::task::yield_now().await;
    }
}