//! Runtime implementations for synchronous and asynchronous workers

pub mod async_worker;
pub mod buffer_pool;
pub mod sync_worker;
pub mod worker_manager;

pub use async_worker::AsyncWorker;
pub use buffer_pool::{BufferPool, PooledBuffer};
pub use sync_worker::SyncWorker;
pub use worker_manager::WorkerManager;

pub(crate) fn effective_max_requests(
    config: &crate::config::ServerConfig,
    worker_id: u32,
) -> Option<usize> {
    let max = config.max_requests?;
    let jitter = config.max_requests_jitter.unwrap_or(0);
    if jitter == 0 {
        return Some(max);
    }

    let jitter = jitter.min(max);
    let seed = {
        use std::time::{SystemTime, UNIX_EPOCH};
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos() as u64;
        (std::process::id() as u64) ^ (worker_id as u64) ^ now
    };

    // xorshift64: simple, fast, no extra dependency
    let mut x = seed ^ 0x9e3779b97f4a7c15;
    x ^= x << 13;
    x ^= x >> 7;
    x ^= x << 17;

    let delta = (x % (jitter as u64 + 1)) as usize;
    Some(max.saturating_sub(jitter) + delta)
}
