Skip to main content

codewhale_runtime/
runtime_control.rs

1/// Selected frontend facts passed by the canonical CLI in memory.
2#[derive(Debug, Clone, PartialEq, Eq)]
3pub enum RuntimeControlFrontend {
4    Stdio,
5    Socket { path: Option<std::path::PathBuf> },
6    Http,
7    Acp { model: String },
8}
9
10/// One bounded blocking boundary for held filesystem/process identity work.
11/// The worker retains its permit and captured handles if the waiter cancels.
12#[cfg(any(unix, windows))]
13pub async fn owner_work<T, F>(work: F) -> anyhow::Result<T>
14where
15    T: Send + 'static,
16    F: FnOnce() -> anyhow::Result<T> + Send + 'static,
17{
18    #[cfg(any(test, feature = "test-support"))]
19    let env_ticket = crate::test_support::env_scope_ticket();
20    static SLOTS: std::sync::OnceLock<std::sync::Arc<tokio::sync::Semaphore>> =
21        std::sync::OnceLock::new();
22    const PERMIT_WAIT: std::time::Duration = std::time::Duration::from_secs(60);
23    let slots = SLOTS
24        .get_or_init(|| std::sync::Arc::new(tokio::sync::Semaphore::new(4)))
25        .clone();
26    if slots.available_permits() == 0 {
27        tracing::warn!(
28            target: "turn",
29            "owner_work is waiting: all 4 blocking slots are held by earlier jobs"
30        );
31    }
32    let permit = tokio::time::timeout(PERMIT_WAIT, slots.acquire_owned())
33        .await
34        .map_err(|_| {
35            anyhow::anyhow!(
36                "blocking work is queued behind earlier jobs that have not finished within {}s",
37                PERMIT_WAIT.as_secs()
38            )
39        })??;
40    tokio::task::spawn_blocking(move || {
41        #[cfg(any(test, feature = "test-support"))]
42        let _membership = crate::test_support::join_env_scope(env_ticket);
43        let _permit = permit;
44        work()
45    })
46    .await
47    .map_err(anyhow::Error::from)?
48}