use crate::error::{Failure, Result};
use std::sync::Arc;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio_util::sync::CancellationToken;
pub const MAX_PERMITS: usize = 32;
static CEILING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
pub fn declare_ceiling(permits: usize) {
CEILING.store(permits, std::sync::atomic::Ordering::Relaxed);
}
#[must_use]
pub fn ceiling() -> usize {
match CEILING.load(std::sync::atomic::Ordering::Relaxed) {
0 => MAX_PERMITS,
settled => settled,
}
}
pub fn admissible(permits: usize) -> Result<usize> {
if permits == 0 {
return Err(Failure::usage(
"concurrency.none_admitted",
"a ceiling of zero admits no work at all",
)
.with_hint("ask for at least one simultaneous part"));
}
let ceiling = ceiling();
if permits > ceiling {
return Err(
Failure::usage("concurrency.above_ceiling", permits.to_string())
.with_detail("detail", permits.to_string())
.with_detail("ceiling", ceiling.to_string())
.with_hint(format!("ask for at most {ceiling}")),
);
}
Ok(permits)
}
#[must_use]
pub fn permits_for_host() -> usize {
std::thread::available_parallelism()
.map_or(1, std::num::NonZeroUsize::get)
.min(ceiling())
}
#[derive(Debug)]
pub struct Licence(#[allow(dead_code)] OwnedSemaphorePermit);
#[derive(Debug, Clone)]
pub struct Gate {
semaphore: Arc<Semaphore>,
permits: usize,
}
impl Gate {
pub fn new(permits: usize) -> Result<Self> {
let permits = admissible(permits)?;
Ok(Self {
semaphore: Arc::new(Semaphore::new(permits)),
permits,
})
}
pub fn for_host(configured: Option<usize>) -> Result<Self> {
Self::new(configured.unwrap_or_else(permits_for_host))
}
#[must_use]
pub const fn permits(&self) -> usize {
self.permits
}
#[must_use]
pub fn available(&self) -> usize {
self.semaphore.available_permits()
}
pub async fn acquire(&self, token: &CancellationToken) -> Result<Licence> {
let semaphore = Arc::clone(&self.semaphore);
tokio::select! {
() = token.cancelled() => Err(Failure::interrupted(
"interrupted.waiting_for_admission",
"the invocation was stopped while waiting to start a part of the work",
)),
permit = semaphore.acquire_owned() => permit.map(Licence).map_err(|error| {
Failure::limit(
"concurrency.gate_closed",
"the admission gate was closed before the work started",
)
.with_cause(error.to_string())
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_admitted_domain_is_decided_in_one_place() {
assert_eq!(admissible(1).expect("legal"), 1);
assert_eq!(admissible(MAX_PERMITS).expect("legal"), MAX_PERMITS);
let none = admissible(0).expect_err("zero admits no work");
assert_eq!(none.code(), "concurrency.none_admitted");
assert_eq!(none.exit_number().code(), 2);
let above = admissible(MAX_PERMITS + 1).expect_err("above the ceiling");
assert_eq!(above.code(), "concurrency.above_ceiling");
assert_eq!(above.exit_number().code(), 2);
}
#[test]
fn a_gate_that_admits_nothing_is_refused_rather_than_built() {
let failure = Gate::new(0).expect_err("must refuse");
assert_eq!(failure.code(), "concurrency.none_admitted");
assert_eq!(failure.exit_number().code(), 2);
}
#[test]
fn a_ceiling_above_the_declared_one_is_refused() {
let failure = Gate::new(MAX_PERMITS + 1).expect_err("must refuse");
assert_eq!(failure.code(), "concurrency.above_ceiling");
}
#[test]
fn the_host_ceiling_never_exceeds_the_declared_one() {
assert!(permits_for_host() >= 1);
assert!(permits_for_host() <= MAX_PERMITS);
assert!(Gate::for_host(None).is_ok());
}
#[test]
fn a_configured_ceiling_outranks_the_host() {
let gate = Gate::for_host(Some(3)).expect("legal");
assert_eq!(gate.permits(), 3);
}
#[tokio::test]
async fn the_gate_never_admits_more_than_its_licences() {
let gate = Gate::new(2).expect("legal");
let token = CancellationToken::new();
let first = gate.acquire(&token).await.expect("free");
let second = gate.acquire(&token).await.expect("free");
assert_eq!(gate.available(), 0);
let waited =
tokio::time::timeout(std::time::Duration::from_millis(50), gate.acquire(&token)).await;
assert!(waited.is_err(), "the third part must be made to wait");
drop(first);
drop(second);
assert_eq!(gate.available(), 2);
}
#[tokio::test]
async fn a_licence_returns_to_the_gate_when_the_part_finishes() {
let gate = Gate::new(1).expect("legal");
let token = CancellationToken::new();
{
let _licence = gate.acquire(&token).await.expect("free");
assert_eq!(gate.available(), 0);
}
assert_eq!(gate.available(), 1);
gate.acquire(&token).await.expect("free again");
}
#[tokio::test]
async fn a_stopped_invocation_never_waits_for_a_licence() {
let gate = Gate::new(1).expect("legal");
let token = CancellationToken::new();
let _held = gate.acquire(&token).await.expect("free");
token.cancel();
let failure = gate.acquire(&token).await.expect_err("must not wait");
assert_eq!(failure.category(), crate::error::Category::Interrupted);
assert_eq!(failure.exit_number().code(), 130);
}
}