subc-daemon 0.54.22

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
use super::*;
use std::{
    future::{poll_fn, Future},
    pin::pin,
    task::Poll,
};

struct Blocked {
    released: Mutex<bool>,
    wake: Condvar,
    entered: tokio::sync::Semaphore,
}

impl Blocked {
    fn wait(&self) {
        let guard = self.released.lock().unwrap();
        self.entered.add_permits(1);
        drop(self.wake.wait_while(guard, |released| !*released).unwrap());
    }

    fn release(&self) {
        *self.released.lock().unwrap() = true;
        self.wake.notify_all();
    }
}

struct Release(Arc<Blocked>);

impl Drop for Release {
    fn drop(&mut self) {
        self.0.release();
    }
}

#[tokio::test]
async fn panicking_checks_do_not_remove_lane_workers() {
    let lane = PeerIdentityLane::start();
    for _ in 0..WORKERS {
        let result = lane
            .run_with_admission(Instant::now() + BUDGET, Admission::Wait, || {
                panic!("a panicking native check")
            })
            .await;
        assert_eq!(result, Err::<(), _>(PeerIdentityError::CheckFailed));
    }
    assert_eq!(lane.run(|| 42).await, Some(42), "workers remain available");
}

#[tokio::test]
async fn expired_popped_job_does_not_count_as_a_second_stuck_worker() {
    let lane = PeerIdentityLane::start();
    let blocked = || {
        Arc::new(Blocked {
            released: Mutex::new(false),
            wake: Condvar::new(),
            entered: tokio::sync::Semaphore::new(0),
        })
    };
    let hung = blocked();
    let other = blocked();
    let popped = blocked();
    let _release = [
        Release(hung.clone()),
        Release(other.clone()),
        Release(popped.clone()),
    ];

    let mut hung_job = pin!(lane.run({
        let hung = hung.clone();
        move || hung.wait()
    }));
    let mut other_job = pin!(
        lane.run_until(Instant::now() + std::time::Duration::from_secs(5), {
            let other = other.clone();
            move || other.wait()
        })
    );
    poll_fn(|cx| {
        assert!(hung_job.as_mut().poll(cx).is_pending());
        assert!(other_job.as_mut().poll(cx).is_pending());
        Poll::Ready(())
    })
    .await;
    for blocker in [&hung, &other] {
        tokio::time::timeout(BUDGET, blocker.entered.acquire())
            .await
            .unwrap()
            .unwrap()
            .forget();
    }
    let deadline = Instant::now() + BUDGET;
    lane.shared.0.lock().unwrap().queue.push_back(Job {
        deadline,
        work: Box::new(|| {}),
        after_pop: Some(Box::new({
            let popped = popped.clone();
            move || popped.wait()
        })),
    });

    tokio::time::sleep_until(deadline.into()).await;
    assert_eq!(lane.stuck_slots(), 1, "only the first worker is hung");
    other.release();
    tokio::time::timeout(BUDGET, popped.entered.acquire())
        .await
        .unwrap()
        .unwrap()
        .forget();
    // The other worker popped an expired job but has not started its next
    // iteration. A new admission must not count that worker as stuck.
    let mut fresh = pin!(lane.run_with_admission(Instant::now() + BUDGET, Admission::Wait, || 42));
    poll_fn(|cx| {
        assert_eq!(
            fresh.as_mut().poll(cx),
            Poll::Pending,
            "fresh work should be admitted, not refused as busy"
        );
        Poll::Ready(())
    })
    .await;
    popped.release();
    assert_eq!(fresh.await, Ok(42));
}

#[tokio::test]
async fn two_stuck_threads_refuse_immediately_and_serve_after_release() {
    let lane = PeerIdentityLane::start();
    let blocked = Arc::new(Blocked {
        released: Mutex::new(false),
        wake: Condvar::new(),
        entered: tokio::sync::Semaphore::new(0),
    });
    let _release = Release(blocked.clone());
    let block = || {
        let blocked = blocked.clone();
        move || {
            blocked.wait();
            7
        }
    };
    let entered = async {
        tokio::time::timeout(BUDGET, blocked.entered.acquire_many(2))
            .await
            .expect("both OS threads started")
            .unwrap()
            .forget();
    };
    let (first, second, ()) = tokio::join!(lane.run(block()), lane.run(block()), entered);
    assert_eq!((first, second), (None, None));
    assert_eq!(lane.stuck_slots(), 2);

    let mut refused = pin!(lane.run(|| panic!("a refused job cannot run")));
    poll_fn(|cx| {
        assert_eq!(refused.as_mut().poll(cx), Poll::Ready(None::<()>));
        Poll::Ready(())
    })
    .await;
    let mut waiting = pin!(lane.run_with_admission(
        Instant::now() + BUDGET,
        Admission::Wait,
        || { panic!("a refused job cannot run") }
    ));
    poll_fn(|cx| {
        assert_eq!(
            waiting.as_mut().poll(cx),
            Poll::Ready(Err::<(), _>(PeerIdentityError::Busy))
        );
        Poll::Ready(())
    })
    .await;

    blocked.release();
    tokio::time::timeout(BUDGET, async {
        while lane.stuck_slots() == 2 {
            tokio::task::yield_now().await;
        }
        assert_eq!(lane.run(|| 42).await, Some(42));
    })
    .await
    .expect("lane returns to service after native call returns");
}