subc-daemon 0.56.20

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
//! Fault injection for the dedicated daemon fixture executable.

use super::{Hooks, PathBuf};
use std::{io, path::Path, sync::Arc, time::Duration};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

impl Hooks {
    pub(crate) fn for_test_binary() -> Self {
        let freeze_gate = std::env::var_os("SUBC_TEST_UPGRADE_FREEZE_GATE").map(PathBuf::from);
        Self {
            #[cfg(target_os = "macos")]
            enabled: true,
            #[cfg(target_os = "macos")]
            team: std::env::var("SUBC_TEST_UPGRADE_TEAM_ID").ok(),
            exec_path: std::env::var_os("SUBC_TEST_UPGRADE_EXEC_PATH").map(PathBuf::from),
            write_failure: std::env::var_os("SUBC_TEST_UPGRADE_HANDOVER_WRITE_FAILURE")
                .is_some()
                .into(),
            corrupt_hmac: std::env::var_os("SUBC_TEST_UPGRADE_CORRUPT_HMAC").is_some(),
            receipt_gate: std::env::var_os("SUBC_TEST_UPGRADE_RECEIPT_GATE").map(PathBuf::from),
            notice_failure: std::env::var("SUBC_TEST_UPGRADE_NOTICE_FAILURE").ok(),
            refusal_writer_gate: freeze_gate.clone().map(Arc::new),
            freeze_gate,
            pause_local_listener: std::env::var_os("SUBC_TEST_RESUME_PAUSE_LOCAL_LISTENER")
                .is_some(),
            resume_bind_gate: std::env::var_os("SUBC_TEST_RESUME_BIND_GATE").map(PathBuf::from),
            boot_hash_gate: std::env::var_os("SUBC_TEST_UPGRADE_BOOT_HASH_GATE").map(PathBuf::from),
        }
    }
}

/// How long a fixture gate waits for the test to release it. A gate that gives
/// up fails the upgrade step with an error naming the gate, so a test that
/// never released it reads that error instead of a generic timeout. No test
/// waits for a gate to give up, so the budget only has to outlast a starved
/// test task: on a slow CI runner the upgrade cases took about six times their
/// usual time, and 20 s was not enough.
const GATE_WAIT: Duration = Duration::from_secs(60);

fn gate_gave_up(phase: u8, error: io::Error) -> io::Error {
    let error = if matches!(
        error.kind(),
        io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
    ) {
        io::Error::new(
            io::ErrorKind::TimedOut,
            format!(
                "upgrade fixture gate {phase} was not released within {} s",
                GATE_WAIT.as_secs()
            ),
        )
    } else {
        io::Error::new(
            error.kind(),
            format!("upgrade fixture gate {phase} failed: {error}"),
        )
    };
    tracing::warn!(phase, %error, "upgrade fixture gate gave up");
    error
}

pub(crate) async fn wait_at_gate(path: &Path, phase: u8) -> io::Result<()> {
    tracing::info!(phase, "upgrade fixture gate waiting");
    let waited = tokio::time::timeout(GATE_WAIT, async {
        let mut stream = tokio::net::UnixStream::connect(path).await?;
        stream.write_u8(phase).await?;
        stream.read_u8().await?;
        Ok(())
    })
    .await;
    match waited {
        Ok(Ok(())) => Ok(()),
        Ok(Err(error)) => Err(gate_gave_up(phase, error)),
        Err(_) => Err(gate_gave_up(
            phase,
            io::Error::from(io::ErrorKind::TimedOut),
        )),
    }
}

pub(crate) fn wait_at_gate_blocking(path: &Path, phase: u8) -> io::Result<()> {
    use std::io::{Read, Write};

    tracing::info!(phase, "upgrade fixture gate waiting");
    let wait = || -> io::Result<()> {
        let mut stream = std::os::unix::net::UnixStream::connect(path)?;
        stream.set_read_timeout(Some(GATE_WAIT))?;
        stream.set_write_timeout(Some(GATE_WAIT))?;
        stream.write_all(&[phase])?;
        stream.read_exact(&mut [0])
    };
    wait().map_err(|error| gate_gave_up(phase, error))
}