use std::future::Future;
use futures::future::select;
use futures::future::Either;
use futures::pin_mut;
use rings_core::lifecycle::StopSource;
use rings_core::lifecycle::StopToken;
use rings_runtime::Drained;
use rings_runtime::Joined;
use rings_runtime::MaybeSend;
use rings_runtime::RuntimeUnavailable;
use rings_runtime::Spawner;
use rings_runtime::TaskSet;
#[derive(Clone, Default)]
pub(crate) struct NodeTasks {
stop: StopSource,
tasks: TaskSet,
}
#[derive(Clone)]
pub(crate) struct NodeSpawner {
tasks: NodeTasks,
spawner: Spawner,
}
impl NodeTasks {
pub(crate) fn new() -> Self {
Self::default()
}
pub(crate) fn spawner(&self) -> Result<NodeSpawner, RuntimeUnavailable> {
Ok(NodeSpawner {
tasks: self.clone(),
spawner: Spawner::current()?,
})
}
pub(crate) fn spawn<F>(&self, task: F) -> Result<Joined<Option<F::Output>>, RuntimeUnavailable>
where
F: Future + MaybeSend + 'static,
F::Output: MaybeSend + 'static,
{
Ok(self.spawner()?.spawn(task))
}
pub(crate) fn stop_token(&self) -> StopToken {
self.stop.token()
}
pub(crate) fn stop(&self) {
self.stop.request_stop();
}
pub(crate) fn drained(&self) -> Drained {
self.tasks.drained()
}
}
impl NodeSpawner {
pub(crate) fn spawn<F>(&self, task: F) -> Joined<Option<F::Output>>
where
F: Future + MaybeSend + 'static,
F::Output: MaybeSend + 'static,
{
let stop = self.tasks.stop.token();
self.tasks.tasks.spawn_with(&self.spawner, async move {
let stopped = stop.stopped();
pin_mut!(task, stopped);
match select(task, stopped).await {
Either::Left((output, _)) => Some(output),
Either::Right(((), _)) => None,
}
})
}
#[cfg(rings_native)]
pub(crate) fn spawn_winding_down<T, F>(&self, task: T) -> Joined<F::Output>
where
T: FnOnce(StopToken) -> F,
F: Future + MaybeSend + 'static,
F::Output: MaybeSend + 'static,
{
self.tasks
.tasks
.spawn_with(&self.spawner, task(self.tasks.stop.token()))
}
}
#[cfg(rings_native)]
pub(crate) async fn wound_down<F, W>(stop: StopToken, task: F, wind_down: W) -> F::Output
where
F: Future,
W: FnOnce(),
{
let stopped = stop.stopped();
pin_mut!(task, stopped);
match select(task, stopped).await {
Either::Left((output, _)) => output,
Either::Right(((), task)) => {
wind_down();
task.await
}
}
}
#[cfg(all(test, rings_native))]
mod test_tasks;