use futures_util::future::BoxFuture;
use std::sync::Arc;
pub trait Trigger: Send + Sync {
fn run(
&self,
connection: crate::connection::AnyConnection,
) -> impl std::future::Future<Output = Result<(), anyhow::Error>> + Send;
}
pub trait DynTrigger: Send + Sync {
fn run(
&self,
connection: crate::connection::AnyConnection,
) -> BoxFuture<'_, Result<(), anyhow::Error>>;
}
impl<T: Trigger + ?Sized> DynTrigger for T {
fn run(
&self,
connection: crate::connection::AnyConnection,
) -> BoxFuture<'_, Result<(), anyhow::Error>> {
Box::pin(async move { self.run(connection).await })
}
}
pub struct TriggerRunner {
pub triggers: Vec<Arc<dyn DynTrigger>>,
}
impl std::fmt::Debug for TriggerRunner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TriggerRunner")
.field("triggers_count", &self.triggers.len())
.finish()
}
}
impl TriggerRunner {
pub fn new(triggers: Vec<Arc<dyn DynTrigger>>) -> Self {
Self { triggers }
}
pub fn start(&self, connection: &crate::connection::AnyConnection) {
for trigger in &self.triggers {
let conn = connection.clone();
let tr = trigger.clone();
crate::spawn_task(async move {
if let Err(e) = tr.run(conn).await {
tracing::error!("Trigger execution failed: {:?}", e);
}
});
}
}
}