use std::collections::HashMap;
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError, Weak};
use std::time::{Duration, Instant};
use crate::failure::FiberId;
use crate::observability::Span;
use crate::runtime::FiberContext;
const SHARDS: usize = 64;
type Entry = (Weak<FiberContext>, Instant);
type Shard = Mutex<HashMap<FiberId, Entry>>;
static REGISTRY: LazyLock<[Shard; SHARDS]> =
LazyLock::new(|| std::array::from_fn(|_| Mutex::new(HashMap::new())));
fn shard(id: FiberId) -> MutexGuard<'static, HashMap<FiberId, Entry>> {
REGISTRY[(id.as_u64() % SHARDS as u64) as usize]
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn register(ctx: &Arc<FiberContext>) {
let entry = (Arc::downgrade(ctx), Instant::now());
shard(ctx.id()).insert(ctx.id(), entry);
}
pub(crate) fn unregister(id: FiberId) {
shard(id).remove(&id);
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FiberState {
Running,
Interrupting,
Done,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FiberInfo {
pub id: FiberId,
pub parent: Option<FiberId>,
pub children: Vec<FiberId>,
pub state: FiberState,
pub started_at: Instant,
pub age: Duration,
pub spans: Vec<String>,
}
impl FiberInfo {
fn of(ctx: &FiberContext, started_at: Instant) -> Self {
let state = if ctx.is_done() {
FiberState::Done
} else if ctx.is_interrupt_requested() {
FiberState::Interrupting
} else {
FiberState::Running
};
let mut children = ctx.child_ids();
children.sort_unstable();
let spans = std::iter::successors(Span::current_in(ctx), |s| s.parent().cloned())
.map(|s| s.name().to_owned())
.collect();
Self {
id: ctx.id(),
parent: ctx.parent().map(|p| p.id()),
children,
state,
started_at,
age: Instant::now().saturating_duration_since(started_at),
spans,
}
}
pub fn span(&self) -> Option<&str> {
self.spans.first().map(String::as_str)
}
}
pub fn fiber_dump() -> Vec<FiberInfo> {
let mut live = Vec::new();
for shard in REGISTRY.iter() {
let map = shard.lock().unwrap_or_else(PoisonError::into_inner);
live.extend(
map
.values()
.filter_map(|(weak, at)| Some((weak.upgrade()?, *at))),
);
}
let mut out: Vec<FiberInfo> = live
.iter()
.map(|(ctx, at)| FiberInfo::of(ctx, *at))
.collect();
drop(live);
out.sort_unstable_by_key(|f| f.id);
out
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
use super::*;
use crate::{HNil, Never, Runtime, sleep, sync};
fn wait_until(what: &str, mut f: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(10);
while !f() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(1));
}
}
fn find(id: FiberId) -> Option<FiberInfo> {
fiber_dump().into_iter().find(|f| f.id == id)
}
#[test]
fn dump_lists_running_and_drops_finished() {
let (tx, rx) = mpsc::channel();
let running = Runtime::global().fork(
sync::<_, Never, HNil>(move || tx.send(()).unwrap())
.then(sleep(Duration::from_secs(3600)))
.with_span("outer-work")
.with_span("request"),
);
let finished = Runtime::global().fork(sync::<_, Never, HNil>(|| 7_u32));
rx.recv_timeout(Duration::from_secs(10))
.expect("forked fiber never ran");
wait_until("the short fiber to finish", || finished.fiber().is_done());
let info = find(running.fiber().id()).expect("running fiber missing from the dump");
assert_eq!(info.state, FiberState::Running);
assert_eq!(info.parent, None);
assert!(info.children.is_empty());
assert_eq!(info.span(), Some("outer-work"));
assert_eq!(info.spans, ["outer-work", "request"]);
assert!(info.age <= Duration::from_secs(3600));
assert!(
find(finished.fiber().id()).is_none(),
"a finished fiber stays listed"
);
running.interrupt_now();
wait_until("the running fiber to finish", || running.fiber().is_done());
assert!(
find(running.fiber().id()).is_none(),
"an interrupted fiber stays listed"
);
}
#[test]
fn parent_links_follow_fork() {
let (tx, rx) = mpsc::channel();
let parent = Runtime::global().fork(
sleep::<Never, HNil>(Duration::from_secs(3600))
.fork()
.flat_map(move |child| {
tx.send(child.fiber().id()).unwrap();
sleep(Duration::from_secs(3600))
}),
);
let child = rx
.recv_timeout(Duration::from_secs(10))
.expect("parent never forked");
let parent_id = parent.fiber().id();
let p = find(parent_id).expect("parent missing from the dump");
assert_eq!(p.children, [child]);
let c = find(child).expect("child missing from the dump");
assert_eq!(c.parent, Some(parent_id));
assert!(c.started_at >= p.started_at);
assert!(c.spans.is_empty());
parent.interrupt_now();
wait_until("the parent to finish", || parent.fiber().is_done());
let dump = fiber_dump();
assert!(!dump.iter().any(|f| f.id == parent_id || f.id == child));
}
}