use crate::thread_manager::{DynamicPoolManager, DynamicRunner};
use crate::worker;
use crossbeam_channel::{unbounded, Receiver, Sender};
use lazy_static::lazy_static;
use lightproc::lightproc::LightProc;
use lightproc::proc_stack::ProcStack;
use lightproc::recoverable_handle::RecoverableHandle;
use once_cell::sync::{Lazy, OnceCell};
use std::future::Future;
use std::iter::Iterator;
use std::sync::Arc;
use std::time::Duration;
use std::{env, thread};
use tracing::trace;
pub fn spawn<F, T>(future: F, stack: ProcStack) -> RecoverableHandle<T>
where
F: Future<Output = T> + Send + 'static,
T: Send + 'static,
{
let (task, handle) = LightProc::recoverable(future, worker::schedule, stack);
task.schedule();
handle
}
pub fn spawn_blocking<F, R>(future: F, stack: ProcStack) -> RecoverableHandle<R>
where
F: Future<Output = R> + Send + 'static,
R: Send + 'static,
{
let (task, handle) = LightProc::recoverable(future, schedule, stack);
task.schedule();
handle
}
#[inline]
pub fn get() -> &'static Pool {
&*POOL
}
impl Pool {
pub fn spawn<F, T>(&self, future: F, stack: ProcStack) -> RecoverableHandle<T>
where
F: Future<Output = T> + Send + 'static,
T: Send + 'static,
{
let _child_id = stack.get_pid() as u64;
let _parent_id = worker::get_proc_stack(|t| t.get_pid() as u64).unwrap_or(0);
let (task, handle) = LightProc::recoverable(future, worker::schedule, stack);
task.schedule();
handle
}
}
pub(crate) fn schedule(t: LightProc) {
if let Err(err) = POOL.sender.try_send(t) {
POOL.sender.send(err.into_inner()).unwrap();
}
DYNAMIC_POOL_MANAGER.get().unwrap().increment_frequency();
}
#[inline]
fn low_watermark() -> &'static u64 {
lazy_static! {
static ref LOW_WATERMARK: u64 = {
env::var_os("BASTION_BLOCKING_THREADS")
.map(|x| x.to_str().unwrap().parse::<u64>().unwrap())
.unwrap_or(DEFAULT_LOW_WATERMARK)
};
}
&*LOW_WATERMARK
}
const DEFAULT_LOW_WATERMARK: u64 = 2;
#[derive(Debug)]
pub struct Pool {
sender: Sender<LightProc>,
receiver: Receiver<LightProc>,
}
struct AsyncRunner {
#[cfg(feature = "tokio-runtime")]
runtime_handle: tokio::runtime::Handle,
}
impl DynamicRunner for AsyncRunner {
fn run_static(&self, park_timeout: Duration) -> ! {
loop {
for task in &POOL.receiver {
trace!("static: running task");
self.run(task);
}
trace!("static: empty queue, parking with timeout");
thread::park_timeout(park_timeout);
}
}
fn run_dynamic(&self, parker: &dyn Fn()) -> ! {
loop {
while let Ok(task) = POOL.receiver.try_recv() {
trace!("dynamic thread: running task");
self.run(task);
}
trace!(
"dynamic thread: parking - {:?}",
std::thread::current().id()
);
parker();
}
}
fn run_standalone(&self) {
while let Ok(task) = POOL.receiver.try_recv() {
self.run(task);
}
trace!("standalone thread: quitting.");
}
}
impl AsyncRunner {
fn run(&self, task: LightProc) {
#[cfg(feature = "tokio-runtime")]
{
self.runtime_handle.spawn_blocking(|| task.run());
}
#[cfg(not(feature = "tokio-runtime"))]
{
task.run();
}
}
}
static DYNAMIC_POOL_MANAGER: OnceCell<DynamicPoolManager> = OnceCell::new();
static POOL: Lazy<Pool> = Lazy::new(|| {
#[cfg(feature = "tokio-runtime")]
{
let runner = Arc::new(AsyncRunner {
runtime_handle: tokio::runtime::Handle::current(),
});
DYNAMIC_POOL_MANAGER
.set(DynamicPoolManager::new(*low_watermark() as usize, runner))
.expect("couldn't create dynamic pool manager");
}
#[cfg(not(feature = "tokio-runtime"))]
{
let runner = Arc::new(AsyncRunner {});
DYNAMIC_POOL_MANAGER
.set(DynamicPoolManager::new(*low_watermark() as usize, runner))
.expect("couldn't create dynamic pool manager");
}
DYNAMIC_POOL_MANAGER
.get()
.expect("couldn't get static pool manager")
.initialize();
let (sender, receiver) = unbounded();
Pool { sender, receiver }
});