pub mod log_level;
pub mod metric;
pub mod posture;
pub mod prometheus;
pub mod registry;
pub mod runtime_metrics;
pub mod tracing;
pub use log_level::LogLevel;
pub use metric::*;
pub use registry::*;
pub use tracing::*;
use std::any::Any;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::Instant;
use crate::failure::Cause;
use crate::kernel::{Effect, ExitKind, Instr, MaskOp, erase_exit, sync, unerase_exit};
use crate::runtime::{FiberContext, FiberRef};
pub(crate) fn observe_exit_with_fiber<A, E, R>(
eff: Effect<A, E, R>,
f: impl FnOnce(&Result<A, Cause<E>>, &Arc<FiberContext>) + Send + 'static,
) -> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
Effect::from_instr(Instr::WithFiber(Box::new(move |_, fiber| {
let m = fiber.mask();
let fiber = Arc::clone(fiber);
Instr::Mask(
Box::new(Instr::Fold(
Box::new(Instr::Mask(Box::new(eff.into_instr()), MaskOp::Set(m))),
Box::new(move |exit| {
let exit = unerase_exit::<A, E>(exit);
Instr::Sync(Box::new(move |_| {
f(&exit, &fiber);
Instr::Pure(erase_exit(exit))
}))
}),
)),
MaskOp::Inc,
)
})))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SpanId(pub u64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TraceId(pub u128);
static NEXT_SPAN: AtomicU64 = AtomicU64::new(1);
fn splitmix(mut z: u64) -> u64 {
z = z.wrapping_add(0x9E37_79B9_7F4A_7C15);
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
struct SpanInner {
id: SpanId,
trace_id: TraceId,
parent: Option<Span>,
name: Arc<str>,
attributes: Vec<(String, String)>,
start: Instant,
extension: OnceLock<Box<dyn Any + Send + Sync>>,
}
#[derive(Clone)]
pub struct Span {
inner: Arc<SpanInner>,
}
impl std::fmt::Debug for Span {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Span")
.field("id", &self.inner.id)
.field("trace_id", &self.inner.trace_id)
.field("parent", &self.inner.parent.as_ref().map(Span::id))
.field("name", &self.inner.name)
.field("attributes", &self.inner.attributes)
.finish()
}
}
impl Span {
fn new(
name: Arc<str>,
attributes: Vec<(String, String)>,
parent: Option<Span>,
start: Instant,
) -> Self {
let n = NEXT_SPAN.fetch_add(1, Ordering::Relaxed);
let trace_id = match &parent {
Some(p) => p.trace_id(),
None => TraceId((u128::from(splitmix(n)) << 64 | u128::from(splitmix(!n))) | 1),
};
Self {
inner: Arc::new(SpanInner {
id: SpanId(n),
trace_id,
parent,
name,
attributes,
start,
extension: OnceLock::new(),
}),
}
}
pub fn fiber_ref() -> &'static FiberRef<Option<Span>> {
static CURRENT: OnceLock<FiberRef<Option<Span>>> = OnceLock::new();
CURRENT.get_or_init(|| FiberRef::new(None))
}
pub fn hook_ref() -> &'static FiberRef<Option<Arc<dyn SpanHook>>> {
static HOOK: OnceLock<FiberRef<Option<Arc<dyn SpanHook>>>> = OnceLock::new();
HOOK.get_or_init(|| FiberRef::new(None))
}
pub fn current<E: Send + 'static, R: Send + Sync + 'static>() -> Effect<Option<Span>, E, R> {
Self::fiber_ref().get()
}
pub fn current_in(fiber: &FiberContext) -> Option<Span> {
Self::fiber_ref().get_in(fiber)
}
pub fn id(&self) -> SpanId {
self.inner.id
}
pub fn trace_id(&self) -> TraceId {
self.inner.trace_id
}
pub fn parent(&self) -> Option<&Span> {
self.inner.parent.as_ref()
}
pub fn name(&self) -> &str {
&self.inner.name
}
pub fn attributes(&self) -> &[(String, String)] {
&self.inner.attributes
}
pub fn start(&self) -> Instant {
self.inner.start
}
pub fn extension<T: Any>(&self) -> Option<&T> {
self
.inner
.extension
.get()
.and_then(|b| b.downcast_ref::<T>())
}
pub fn set_extension<T: Any + Send + Sync>(&self, value: T) -> bool {
self.inner.extension.set(Box::new(value)).is_ok()
}
}
pub trait SpanHook: Send + Sync + 'static {
fn on_start(&self, _span: &Span) {}
fn on_end(&self, _span: &Span, _end: Instant, _exit: ExitKind) {}
}
impl<A, E, R> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
pub fn with_span(self, name: impl Into<Arc<str>>) -> Self {
self.with_span_attrs(name, std::iter::empty::<(String, String)>())
}
pub fn with_span_attrs<K: Into<String>, V: Into<String>>(
self,
name: impl Into<Arc<str>>,
attributes: impl IntoIterator<Item = (K, V)>,
) -> Self {
let name = name.into();
let attributes: Vec<(String, String)> = attributes
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect();
Self::from_instr(Instr::WithFiber(Box::new(move |_, fiber| {
let parent = Span::current_in(fiber);
let hook = Span::hook_ref().get_in(fiber);
let span = Span::new(name, attributes, parent, fiber.executor().now());
let start = {
let (hook, span) = (hook.clone(), span.clone());
sync::<(), E, R>(move || {
if let Some(h) = &hook {
h.on_start(&span);
}
})
};
let body = start.then(Span::fiber_ref().locally(Some(span.clone()), self));
observe_exit_with_fiber(body, move |exit, fiber| {
if let Some(h) = &hook {
h.on_end(&span, fiber.executor().now(), ExitKind::of_result(exit));
}
})
.into_instr()
})))
}
pub fn with_span_hook(self, hook: Arc<dyn SpanHook>) -> Self {
Span::hook_ref().locally(Some(hook), self)
}
pub fn tag_metrics(self, key: impl Into<String>, value: impl Into<String>) -> Self {
let tag = [(key.into(), value.into())];
Self::from_instr(Instr::WithFiber(Box::new(move |_, fiber| {
let tags = MetricRegistry::fiber_tags();
let merged = merge_tags(&tags.get_in(fiber), &tag);
tags.locally(merged, self).into_instr()
})))
}
}