use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::panic::Location;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use crate::task::{Fallible, TaskName};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ProbeId(pub u64);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProbeMeta {
pub name: &'static str,
pub name_type: TypeId,
pub output: &'static str,
pub location: &'static Location<'static>,
pub external: bool,
pub detail: Option<String>,
}
impl ProbeMeta {
#[must_use]
pub fn is<N: TaskName>(&self) -> bool {
self.name_type == TypeId::of::<N>()
}
}
#[derive(Debug)]
pub enum Gate {
Run,
Hold,
Resolve(Payload),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Finish {
Completed,
Resolved,
Dropped,
}
pub trait Controller {
fn start(&self, meta: ProbeMeta) -> ProbeId;
fn gate(&self, id: ProbeId, cx: &mut Context<'_>) -> Gate;
fn complete(&self, id: ProbeId) -> Option<Replace> {
let _ = id;
None
}
fn finish(&self, id: ProbeId, how: Finish);
fn rejected(&self, id: ProbeId, payload: Payload) {
let _ = (id, payload);
}
fn real_timer(&self, component: &'static str) {
let _ = component;
}
}
thread_local! {
static CONTROLLER: RefCell<Option<Rc<dyn Controller>>> = const { RefCell::new(None) };
}
#[must_use = "the controller is removed again when the guard is dropped"]
pub fn install(controller: Rc<dyn Controller>) -> Installed {
let previous = CONTROLLER.with(|slot| slot.borrow_mut().replace(controller));
Installed {
previous,
thread: PhantomData,
}
}
#[must_use = "the controller is removed again when the guard is dropped"]
pub struct Installed {
previous: Option<Rc<dyn Controller>>,
thread: PhantomData<Rc<()>>,
}
impl fmt::Debug for Installed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Installed")
.field("restores_previous", &self.previous.is_some())
.finish()
}
}
impl Drop for Installed {
fn drop(&mut self) {
let previous = self.previous.take();
CONTROLLER.with(|slot| *slot.borrow_mut() = previous);
}
}
pub(crate) fn current() -> Option<Rc<dyn Controller>> {
CONTROLLER.with(|slot| slot.borrow().clone())
}
pub struct Payload {
name: TypeId,
name_str: &'static str,
value: Box<dyn Any + Send>,
}
impl fmt::Debug for Payload {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Payload")
.field("name", &self.name_str)
.finish_non_exhaustive()
}
}
impl Payload {
pub fn new<N: TaskName>(output: N::Output) -> Self {
Self {
name: TypeId::of::<N>(),
name_str: N::NAME,
value: Box::new(output),
}
}
pub fn fail<N: Fallible>(error: N::Err) -> Self {
Self::new::<N>(N::from_err(error))
}
#[must_use]
pub fn name(&self) -> &'static str {
self.name_str
}
#[must_use]
pub fn is<N: TaskName>(&self) -> bool {
self.name == TypeId::of::<N>()
}
pub fn take<N: TaskName>(self) -> Result<N::Output, Payload> {
if !self.is::<N>() {
return Err(self);
}
let Self {
name,
name_str,
value,
} = self;
value
.downcast::<N::Output>()
.map(|output| *output)
.map_err(|value| Payload {
name,
name_str,
value,
})
}
}
type Map<T> = Box<dyn FnOnce(T) -> T>;
pub struct Replace {
name: TypeId,
name_str: &'static str,
map: Box<dyn Any>,
}
impl fmt::Debug for Replace {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Replace")
.field("name", &self.name_str)
.finish_non_exhaustive()
}
}
impl Replace {
pub fn new<N: TaskName>(map: impl FnOnce(N::Output) -> N::Output + 'static) -> Self {
Self {
name: TypeId::of::<N>(),
name_str: N::NAME,
map: Box::new(Box::new(map) as Map<N::Output>),
}
}
#[must_use]
pub fn name(&self) -> &'static str {
self.name_str
}
pub fn apply<N: TaskName>(self, output: N::Output) -> N::Output {
if self.name != TypeId::of::<N>() {
return output;
}
match self.map.downcast::<Map<N::Output>>() {
Ok(map) => map(output),
Err(_) => output,
}
}
}
pub(crate) struct Probe {
location: &'static Location<'static>,
pub(crate) external: bool,
pub(crate) detail: Option<Box<dyn FnOnce() -> String + Send>>,
state: State,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
Unstarted,
Uncontrolled,
Controlled(ProbeId),
Done,
}
impl Probe {
pub(crate) fn new(location: &'static Location<'static>) -> Self {
Self {
location,
external: false,
detail: None,
state: State::Unstarted,
}
}
pub(crate) fn poll<N, F>(
&mut self,
future: Pin<&mut F>,
cx: &mut Context<'_>,
) -> Poll<N::Output>
where
N: TaskName,
F: Future<Output = N::Output>,
{
if self.state == State::Unstarted {
self.state = match current() {
Some(controller) => State::Controlled(controller.start(ProbeMeta {
name: N::NAME,
name_type: TypeId::of::<N>(),
output: std::any::type_name::<N::Output>(),
location: self.location,
external: self.external,
detail: self.detail.take().map(|detail| detail()),
})),
None => State::Uncontrolled,
};
}
let State::Controlled(id) = self.state else {
return future.poll(cx);
};
let Some(controller) = current() else {
self.state = State::Uncontrolled;
return future.poll(cx);
};
match controller.gate(id, cx) {
Gate::Hold => return Poll::Pending,
Gate::Run => {}
Gate::Resolve(payload) => match payload.take::<N>() {
Ok(output) => {
self.state = State::Done;
controller.finish(id, Finish::Resolved);
return Poll::Ready(output);
}
Err(payload) => controller.rejected(id, payload),
},
}
let Poll::Ready(output) = future.poll(cx) else {
return Poll::Pending;
};
let output = match controller.complete(id) {
Some(replace) => replace.apply::<N>(output),
None => output,
};
self.state = State::Done;
controller.finish(id, Finish::Completed);
Poll::Ready(output)
}
pub(crate) fn dropped(&mut self) {
let State::Controlled(id) = self.state else {
return;
};
self.state = State::Done;
if let Some(controller) = current() {
controller.finish(id, Finish::Dropped);
}
}
}