use std::fmt;
use std::sync::Arc;
use navree_kernel::BoxFuture;
use crate::error::Result;
use crate::exec::ExecContext;
use crate::model::Model;
use crate::record::Record;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ModelEvent {
Retrieved,
Creating,
Created,
Updating,
Updated,
Saving,
Saved,
Deleting,
Deleted,
Trashed,
ForceDeleting,
ForceDeleted,
Restoring,
Restored,
Replicating,
Custom(&'static str),
}
impl ModelEvent {
pub const ALL: [ModelEvent; 15] = [
ModelEvent::Retrieved,
ModelEvent::Saving,
ModelEvent::Creating,
ModelEvent::Created,
ModelEvent::Updating,
ModelEvent::Updated,
ModelEvent::Saved,
ModelEvent::Deleting,
ModelEvent::Deleted,
ModelEvent::Trashed,
ModelEvent::ForceDeleting,
ModelEvent::ForceDeleted,
ModelEvent::Restoring,
ModelEvent::Restored,
ModelEvent::Replicating,
];
pub fn from_name(name: &str) -> Option<ModelEvent> {
ModelEvent::ALL
.into_iter()
.find(|event| event.name() == name)
}
pub fn runs_after_commit(self) -> bool {
matches!(
self,
ModelEvent::Created
| ModelEvent::Updated
| ModelEvent::Saved
| ModelEvent::Deleted
| ModelEvent::Trashed
| ModelEvent::ForceDeleted
| ModelEvent::Restored
)
}
pub fn name(self) -> &'static str {
match self {
ModelEvent::Retrieved => "retrieved",
ModelEvent::Creating => "creating",
ModelEvent::Created => "created",
ModelEvent::Updating => "updating",
ModelEvent::Updated => "updated",
ModelEvent::Saving => "saving",
ModelEvent::Saved => "saved",
ModelEvent::Deleting => "deleting",
ModelEvent::Deleted => "deleted",
ModelEvent::Trashed => "trashed",
ModelEvent::ForceDeleting => "force_deleting",
ModelEvent::ForceDeleted => "force_deleted",
ModelEvent::Restoring => "restoring",
ModelEvent::Restored => "restored",
ModelEvent::Replicating => "replicating",
ModelEvent::Custom(name) => name,
}
}
pub fn is_cancellable(self) -> bool {
matches!(
self,
ModelEvent::Creating
| ModelEvent::Updating
| ModelEvent::Saving
| ModelEvent::Deleting
| ModelEvent::ForceDeleting
| ModelEvent::Restoring
| ModelEvent::Custom(_)
)
}
}
impl fmt::Display for ModelEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Flow {
#[default]
Continue,
Cancel,
}
impl From<()> for Flow {
fn from((): ()) -> Flow {
Flow::Continue
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum HookKind {
#[default]
Behaviour,
TransactionalListener,
Listener,
}
pub trait ModelHook<M: Model>: Send + Sync + 'static {
fn before<'a>(
&'a self,
event: ModelEvent,
ctx: &'a ExecContext,
record: &'a mut Record<M>,
) -> BoxFuture<'a, Result<Flow>> {
let _ = (event, ctx, record);
Box::pin(async { Ok(Flow::Continue) })
}
fn after<'a>(
&'a self,
event: ModelEvent,
ctx: &'a ExecContext,
record: &'a mut Record<M>,
) -> BoxFuture<'a, Result<()>> {
let _ = (event, ctx, record);
Box::pin(async { Ok(()) })
}
fn kind(&self) -> HookKind {
HookKind::Behaviour
}
fn name(&self) -> &'static str {
std::any::type_name::<Self>()
}
}
pub(crate) struct Hooks<M: Model> {
hooks: Vec<Arc<dyn ModelHook<M>>>,
}
impl<M: Model> Hooks<M> {
pub(crate) async fn resolve(ctx: &ExecContext) -> Result<Self> {
let mut hooks = M::hooks();
if M::meta().is_workspace_scoped() {
hooks.insert(0, Arc::new(crate::workspace::WorkspaceHook));
}
let mut fake = None;
if let Some(app) = ctx.app()
&& !crate::factory::quiet::is_active()
{
let registered = app.get_all::<dyn ModelHook<M>>().await.map_err(|error| {
crate::error::OrmError::Hook {
model: M::meta().name().into(),
message: format!("cannot resolve the app's model hooks: {error}"),
}
})?;
hooks.extend(registered);
fake = app.try_get::<crate::events::ModelEventFake>().await;
}
if crate::events::events_are_silenced() {
hooks.retain(|hook| hook.kind() == HookKind::Behaviour);
} else if let Some(fake) = fake {
hooks.retain(|hook| hook.kind() == HookKind::Behaviour);
hooks.push(Arc::new(crate::events::FakeListener(fake)));
}
Ok(Hooks { hooks })
}
pub(crate) fn is_empty(&self) -> bool {
self.hooks.is_empty()
}
pub(crate) async fn before(
&self,
event: ModelEvent,
ctx: &ExecContext,
record: &mut Record<M>,
) -> Result<Flow> {
for hook in &self.hooks {
let flow = crate::events::in_unit_of_work(ctx, hook.before(event, ctx, record)).await?;
if flow == Flow::Cancel {
return Ok(Flow::Cancel);
}
}
Ok(Flow::Continue)
}
pub(crate) async fn after(
&self,
event: ModelEvent,
ctx: &ExecContext,
record: &mut Record<M>,
) -> Result<()> {
let after_commit = if event.runs_after_commit() {
ctx.uow()
} else {
None
};
let mut deferred = Vec::new();
for hook in &self.hooks {
if after_commit.is_some() && hook.kind() == HookKind::Listener {
deferred.push(hook.clone());
continue;
}
crate::events::in_unit_of_work(ctx, hook.after(event, ctx, record)).await?;
}
if let Some(uow) = after_commit
&& !deferred.is_empty()
{
crate::events::after_commit(uow, deferred, event, ctx.clone(), record.clone());
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_ing_events_are_the_cancellable_ones() {
let cancellable: Vec<&str> = ModelEvent::ALL
.into_iter()
.filter(|event| event.is_cancellable())
.map(ModelEvent::name)
.collect();
assert_eq!(
cancellable,
[
"saving",
"creating",
"updating",
"deleting",
"force_deleting",
"restoring"
]
);
assert_eq!(ModelEvent::ForceDeleted.to_string(), "force_deleted");
}
#[test]
fn every_built_in_event_is_found_by_its_name() {
for event in ModelEvent::ALL {
assert_eq!(ModelEvent::from_name(event.name()), Some(event));
}
assert_eq!(Flow::from(()), Flow::Continue);
}
}