use std::any::Any;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use futures::FutureExt;
use navree_db::Uow;
use crate::exec::ExecContext;
use crate::hooks::{ModelEvent, ModelHook};
use crate::model::{Model, PrimaryKey};
use crate::record::Record;
mod dispatch;
mod fake;
mod listener;
mod observer;
mod record;
pub use dispatch::Dispatch;
pub(crate) use fake::FakeListener;
pub use fake::{FiredEvent, ModelEventFake};
pub(crate) use listener::ClosureListener;
pub use observer::{Observer, ObserverHook};
tokio::task_local! {
static SILENCED: ();
}
pub async fn without_events<F: Future>(future: F) -> F::Output {
SILENCED.scope((), future).await
}
pub fn events_are_silenced() -> bool {
SILENCED.try_with(|()| ()).is_ok()
}
pub(crate) async fn in_unit_of_work<F: Future>(ctx: &ExecContext, future: F) -> F::Output {
match ctx.uow() {
Some(uow) if !Uow::current().is_some_and(|current| current.same_as(uow)) => {
uow.scope(future).await
}
_ => future.await,
}
}
pub(crate) fn after_commit<M: Model>(
uow: &Uow,
hooks: Vec<Arc<dyn ModelHook<M>>>,
event: ModelEvent,
ctx: ExecContext,
snapshot: Record<M>,
) {
uow.after_commit(move || {
Box::pin(async move {
let mut snapshot = snapshot;
for hook in hooks {
let outcome = AssertUnwindSafe(hook.after(event, &ctx, &mut snapshot))
.catch_unwind()
.await;
let failure = match outcome {
Ok(Ok(())) => continue,
Ok(Err(error)) => ListenerFailed::error::<M>(event, &snapshot, error),
Err(panic) => ListenerFailed::panic::<M>(event, &snapshot, &*panic),
};
failure.report(&ctx).await;
}
})
});
}
#[derive(Debug, thiserror::Error)]
#[error("a {model} listener of `{event}` (record {key}) failed after the commit: {message}")]
pub(crate) struct ListenerFailed {
model: &'static str,
event: &'static str,
key: String,
message: String,
#[source]
source: Option<crate::error::OrmError>,
}
impl ListenerFailed {
fn error<M: Model>(
event: ModelEvent,
record: &Record<M>,
error: crate::error::OrmError,
) -> Self {
ListenerFailed {
model: M::meta().name(),
event: event.name(),
key: record.key().to_key_string(),
message: error.to_string(),
source: Some(error),
}
}
fn panic<M: Model>(event: ModelEvent, record: &Record<M>, panic: &(dyn Any + Send)) -> Self {
ListenerFailed {
model: M::meta().name(),
event: event.name(),
key: record.key().to_key_string(),
message: format!("it panicked: {}", panic_message(panic)),
source: None,
}
}
pub(crate) async fn report(&self, ctx: &ExecContext) {
tracing::error!(
target: "navree_orm::events",
model = self.model,
event = self.event,
key = %self.key,
error = %self.message,
"a model listener failed after the commit"
);
if let Some(app) = ctx.app() {
navree_telemetry::Telemetry::from_app(app)
.await
.report_exception(self);
}
}
}
fn panic_message(panic: &(dyn Any + Send)) -> String {
if let Some(text) = panic.downcast_ref::<&str>() {
(*text).to_owned()
} else if let Some(text) = panic.downcast_ref::<String>() {
text.clone()
} else {
"a non-text panic payload".to_owned()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn silence_lasts_as_long_as_the_future() {
assert!(!events_are_silenced());
without_events(async {
assert!(events_are_silenced());
without_events(async { assert!(events_are_silenced()) }).await;
assert!(events_are_silenced());
})
.await;
assert!(!events_are_silenced());
}
#[test]
fn panic_messages_are_read_from_text_payloads() {
assert_eq!(panic_message(&"boom"), "boom");
assert_eq!(panic_message(&String::from("bang")), "bang");
assert_eq!(panic_message(&7_u8), "a non-text panic payload");
}
}