dope-sys 0.77.0

Typed operating-system call contracts
Documentation
use std::{fmt, os::fd};

use o3::mem::slot;

use crate::thread::{
    Thread,
    signal::{Acquire, CLAIMED, ReleaseFault, Source},
};

#[derive(Debug)]
pub enum Rejected<'a, R> {
    Failed(Acquire),
    Retained {
        cause: Acquire,
        receiver: slot::Occupied<'a, R>,
    },
}

impl<R> From<Acquire> for Rejected<'_, R> {
    fn from(cause: Acquire) -> Self {
        Self::Failed(cause)
    }
}

/// # Safety
/// `is_main` must identify the original thread. Failed acquisition must
/// return a receiver capable of restoring every changed signal policy.
pub unsafe trait Receiver: fmt::Debug + fd::AsFd + Sized {
    /// Returns whether this receiver is being installed on the process's original thread.
    fn is_main() -> bool;

    /// # Safety
    /// Retain exclusive process SIGTERM/SIGINT authority through restoration, including failed acquisition.
    /// Start workers after acquisition and join them before restoration.
    unsafe fn try_new(
        vacant: slot::raw::Vacant<'_, Self>,
    ) -> Result<slot::Occupied<'_, Self>, Rejected<'_, Self>>;
    fn try_wait<B: Thread<Receiver = Self>>(source: &Source<'_, B>) -> Result<(), crate::Errno>;

    /// Restores the previous signal policy, retaining its owner on failure.
    fn restore(&self) -> Result<(), ReleaseFault>;
}

pub(super) fn acquire<R: Receiver>(
    vacant: slot::raw::Vacant<'_, R>,
) -> Result<slot::Occupied<'_, R>, Rejected<'_, R>> {
    if !R::is_main() {
        return Err(Acquire::Thread.into());
    }
    if CLAIMED.replace(true) {
        return Err(Acquire::Busy.into());
    }
    // SAFETY: this original thread holds the process claim through native restoration.
    let acquired = unsafe { R::try_new(vacant) };
    if matches!(acquired, Err(Rejected::Failed(_))) {
        CLAIMED.set(false);
    }
    acquired
}