use crate::layer;
use crate::sync::RwLock;
use core::any::TypeId;
use std::{
error, fmt,
marker::PhantomData,
sync::{Arc, Weak},
};
use tracing_core::{
callsite, span,
subscriber::{Interest, Subscriber},
Dispatch, Event, LevelFilter, Metadata,
};
#[derive(Debug)]
pub struct Layer<L, S> {
inner: Arc<RwLock<L>>,
_s: PhantomData<fn(S)>,
}
#[derive(Debug)]
pub struct Handle<L, S> {
inner: Weak<RwLock<L>>,
_s: PhantomData<fn(S)>,
}
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
}
#[derive(Debug)]
enum ErrorKind {
SubscriberGone,
Poisoned,
}
impl<L, S> crate::Layer<S> for Layer<L, S>
where
L: crate::Layer<S> + 'static,
S: Subscriber,
{
fn on_register_dispatch(&self, subscriber: &Dispatch) {
try_lock!(self.inner.read()).on_register_dispatch(subscriber);
}
fn on_layer(&mut self, subscriber: &mut S) {
try_lock!(self.inner.write(), else return).on_layer(subscriber);
}
#[inline]
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
try_lock!(self.inner.read(), else return Interest::sometimes()).register_callsite(metadata)
}
#[inline]
fn enabled(&self, metadata: &Metadata<'_>, ctx: layer::Context<'_, S>) -> bool {
try_lock!(self.inner.read(), else return false).enabled(metadata, ctx)
}
#[inline]
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_new_span(attrs, id, ctx)
}
#[inline]
fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_record(span, values, ctx)
}
#[inline]
fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_follows_from(span, follows, ctx)
}
#[inline]
fn event_enabled(&self, event: &Event<'_>, ctx: layer::Context<'_, S>) -> bool {
try_lock!(self.inner.read(), else return false).event_enabled(event, ctx)
}
#[inline]
fn on_event(&self, event: &Event<'_>, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_event(event, ctx)
}
#[inline]
fn on_enter(&self, id: &span::Id, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_enter(id, ctx)
}
#[inline]
fn on_exit(&self, id: &span::Id, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_exit(id, ctx)
}
#[inline]
fn on_close(&self, id: span::Id, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_close(id, ctx)
}
#[inline]
fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_id_change(old, new, ctx)
}
#[inline]
fn max_level_hint(&self) -> Option<LevelFilter> {
try_lock!(self.inner.read(), else return None).max_level_hint()
}
#[doc(hidden)]
unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
if id == TypeId::of::<layer::NoneLayerMarker>() {
unsafe { return try_lock!(self.inner.read(), else return None).downcast_raw(id) }
}
None
}
}
#[cfg(all(feature = "registry", feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "registry", feature = "std"))))]
impl<S, L> crate::layer::Filter<S> for Layer<L, S>
where
L: crate::layer::Filter<S> + 'static,
S: Subscriber,
{
#[inline]
fn callsite_enabled(&self, metadata: &'static Metadata<'static>) -> Interest {
try_lock!(self.inner.read(), else return Interest::sometimes()).callsite_enabled(metadata)
}
#[inline]
fn enabled(&self, metadata: &Metadata<'_>, ctx: &layer::Context<'_, S>) -> bool {
try_lock!(self.inner.read(), else return false).enabled(metadata, ctx)
}
#[inline]
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_new_span(attrs, id, ctx)
}
#[inline]
fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_record(span, values, ctx)
}
#[inline]
fn on_enter(&self, id: &span::Id, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_enter(id, ctx)
}
#[inline]
fn on_exit(&self, id: &span::Id, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_exit(id, ctx)
}
#[inline]
fn on_close(&self, id: span::Id, ctx: layer::Context<'_, S>) {
try_lock!(self.inner.read()).on_close(id, ctx)
}
#[inline]
fn max_level_hint(&self) -> Option<LevelFilter> {
try_lock!(self.inner.read(), else return None).max_level_hint()
}
}
impl<L, S> Layer<L, S> {
pub fn new(inner: L) -> (Self, Handle<L, S>) {
let this = Self {
inner: Arc::new(RwLock::new(inner)),
_s: PhantomData,
};
let handle = this.handle();
(this, handle)
}
pub fn handle(&self) -> Handle<L, S> {
Handle {
inner: Arc::downgrade(&self.inner),
_s: PhantomData,
}
}
}
impl<L, S> Handle<L, S> {
pub fn reload(&self, new_value: impl Into<L>) -> Result<(), Error> {
self.modify(|layer| {
*layer = new_value.into();
})
}
pub fn modify(&self, f: impl FnOnce(&mut L)) -> Result<(), Error> {
let inner = self.inner.upgrade().ok_or(Error {
kind: ErrorKind::SubscriberGone,
})?;
let mut lock = try_lock!(inner.write(), else return Err(Error::poisoned()));
f(&mut *lock);
drop(lock);
callsite::rebuild_interest_cache();
#[cfg(feature = "tracing-log")]
tracing_log::log::set_max_level(tracing_log::AsLog::as_log(
&crate::filter::LevelFilter::current(),
));
Ok(())
}
pub fn clone_current(&self) -> Option<L>
where
L: Clone,
{
self.with_current(L::clone).ok()
}
pub fn with_current<T>(&self, f: impl FnOnce(&L) -> T) -> Result<T, Error> {
let inner = self.inner.upgrade().ok_or(Error {
kind: ErrorKind::SubscriberGone,
})?;
let inner = try_lock!(inner.read(), else return Err(Error::poisoned()));
Ok(f(&*inner))
}
}
impl<L, S> Clone for Handle<L, S> {
fn clone(&self) -> Self {
Handle {
inner: self.inner.clone(),
_s: PhantomData,
}
}
}
impl Error {
fn poisoned() -> Self {
Self {
kind: ErrorKind::Poisoned,
}
}
pub fn is_poisoned(&self) -> bool {
matches!(self.kind, ErrorKind::Poisoned)
}
pub fn is_dropped(&self) -> bool {
matches!(self.kind, ErrorKind::SubscriberGone)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let msg = match self.kind {
ErrorKind::SubscriberGone => "subscriber no longer exists",
ErrorKind::Poisoned => "lock poisoned",
};
f.pad(msg)
}
}
impl error::Error for Error {}