use std::{
collections::HashMap,
fmt,
sync::{
Arc, Mutex, MutexGuard, PoisonError,
atomic::{AtomicU64, Ordering},
},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
pub(crate) fn unix_seconds() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_secs())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TaskId(u64);
impl fmt::Display for TaskId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Clone, Default)]
pub struct AsyncTasks {
inner: Arc<Inner>,
}
#[derive(Default)]
struct Inner {
next_id: AtomicU64,
active: Mutex<HashMap<TaskId, Entry>>,
changed: AtomicU64,
}
struct Entry {
name: String,
started: Instant,
}
impl AsyncTasks {
pub fn new() -> Self {
Self::default()
}
fn active(&self) -> MutexGuard<'_, HashMap<TaskId, Entry>> {
self.inner.active.lock().unwrap_or_else(PoisonError::into_inner)
}
#[must_use = "pass this ID to complete(), or the task stays active"]
pub fn add(&self, name: impl Into<String>) -> TaskId {
let entry = Entry { name: name.into(), started: Instant::now() };
let id = TaskId(self.inner.next_id.fetch_add(1, Ordering::Relaxed));
let mut active = self.active();
active.insert(id, entry);
if active.len() == 1 {
self.inner.changed.store(unix_seconds(), Ordering::Relaxed);
}
id
}
pub fn complete(&self, id: TaskId) -> bool {
let mut active = self.active();
let removed = active.remove(&id).is_some();
if removed && active.is_empty() {
self.inner.changed.store(unix_seconds(), Ordering::Relaxed);
}
removed
}
#[cfg(feature = "runtime")]
pub(crate) fn activity(&self) -> (usize, u64) {
let active = self.active();
(active.len(), self.inner.changed.load(Ordering::Relaxed))
}
pub fn track(&self, name: impl Into<String>) -> TaskGuard {
TaskGuard { tasks: self.clone(), id: self.add(name) }
}
pub fn tracked<N, F>(&self, name: N, future: F) -> impl Future<Output = F::Output> + use<N, F>
where
N: Into<String>,
F: Future,
{
let guard = self.track(name);
async move {
let _guard = guard;
future.await
}
}
pub fn active_count(&self) -> usize {
self.active().len()
}
pub fn info(&self) -> TaskInfo {
let now = Instant::now();
let mut running: Vec<RunningTask> = self
.active()
.iter()
.map(|(id, entry)| RunningTask { id: *id, name: entry.name.clone(), duration: now - entry.started })
.collect();
running.sort_by_key(|task| task.id.0);
TaskInfo { running }
}
}
impl fmt::Debug for AsyncTasks {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AsyncTasks").field("active_count", &self.active_count()).finish()
}
}
#[must_use = "the task is completed as soon as the guard is dropped"]
#[derive(Debug)]
pub struct TaskGuard {
tasks: AsyncTasks,
id: TaskId,
}
impl TaskGuard {
pub fn id(&self) -> TaskId {
self.id
}
}
impl Drop for TaskGuard {
fn drop(&mut self) {
self.tasks.complete(self.id);
}
}
#[derive(Clone, Debug)]
pub struct TaskInfo {
running: Vec<RunningTask>,
}
impl TaskInfo {
pub fn active_count(&self) -> usize {
self.running.len()
}
pub fn running(&self) -> &[RunningTask] {
&self.running
}
}
#[derive(Clone, Debug)]
pub struct RunningTask {
id: TaskId,
name: String,
duration: Duration,
}
impl RunningTask {
pub fn id(&self) -> TaskId {
self.id
}
pub fn name(&self) -> &str {
&self.name
}
pub fn duration(&self) -> Duration {
self.duration
}
}
#[cfg(test)]
mod tests {
use super::*;
fn names(tasks: &AsyncTasks) -> Vec<String> {
tasks.info().running().iter().map(|task| task.name().to_owned()).collect()
}
#[test]
fn tasks_are_active_until_completed_once_or_their_guard_is_dropped() {
let tasks = AsyncTasks::new();
let first = tasks.add("first");
let guard = tasks.track("second");
let shared = tasks.clone();
assert_ne!(first, guard.id());
assert_eq!((shared.active_count(), names(&tasks)), (2, vec!["first".to_owned(), "second".to_owned()]));
std::thread::sleep(Duration::from_millis(20));
assert!(tasks.info().running().iter().all(|task| task.duration() >= Duration::from_millis(20)));
assert!(tasks.complete(first));
assert!(!tasks.complete(first), "a second completion finds nothing");
assert_eq!(names(&tasks), ["second"]);
assert!(tasks.complete(guard.id()));
drop(guard);
assert_eq!(tasks.info().active_count(), 0);
}
struct CountsTasks(AsyncTasks);
impl From<CountsTasks> for String {
fn from(name: CountsTasks) -> Self {
let active = name.0.inner.active.try_lock().expect("the registry lock is held during the name conversion");
format!("task number {}", active.len() + 1)
}
}
#[test]
fn name_conversion_runs_outside_the_registry_lock() {
let tasks = AsyncTasks::new();
let _first = tasks.track(CountsTasks(tasks.clone()));
let _second = tasks.add(CountsTasks(tasks.clone()));
assert_eq!(names(&tasks), ["task number 1", "task number 2"]);
}
#[test]
fn guard_completes_its_task_when_the_owner_unwinds() {
let tasks = AsyncTasks::new();
let guard = tasks.track("panics");
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
let _guard = guard;
panic!("the work failed");
}));
assert!(unwound.is_err());
assert_eq!(tasks.active_count(), 0);
}
#[tokio::test]
async fn guard_follows_spawned_work_through_completion_cancellation_and_blocking() {
let tasks = AsyncTasks::new();
let (release, gate) = tokio::sync::oneshot::channel::<()>();
let finishes = tokio::spawn(tasks.tracked("finishes", async move {
let _ = gate.await;
}));
let cancelled = tokio::spawn(tasks.tracked("cancelled", std::future::pending::<()>()));
let guard = tasks.track("blocking");
let (unblock, blocked) = std::sync::mpsc::channel::<()>();
let blocking = tokio::task::spawn_blocking(move || {
let _guard = guard;
let _ = blocked.recv();
});
assert_eq!(tasks.active_count(), 3);
cancelled.abort();
assert!(cancelled.await.unwrap_err().is_cancelled());
assert_eq!(names(&tasks), ["finishes", "blocking"]);
release.send(()).unwrap();
finishes.await.unwrap();
assert_eq!(names(&tasks), ["blocking"]);
unblock.send(()).unwrap();
blocking.await.unwrap();
assert_eq!(tasks.active_count(), 0);
}
}