use std::any::type_name;
use std::collections::HashMap;
use std::future::Future;
use std::sync::LazyLock;
use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::fake::Dispatched;
use super::queueable::ModelRows;
use super::{Batch, MissingModels, Queueable};
use crate::context::{Context, Internals};
use crate::errors::panic;
use crate::{Error, Result};
pub trait Callback: Queueable {
const NAME: &'static str;
const FAIL_WHEN_MISSING_MODELS: bool = false;
}
pub trait Then: Callback {
#[doc(hidden)]
fn then(self, batch: &Batch) -> impl Future<Output = Result<()>> + Send;
}
pub trait Catch: Callback {
#[doc(hidden)]
fn catch(self, batch: Option<&Batch>, error: &Error) -> impl Future<Output = Result<()>> + Send;
}
pub trait ChainCatch: Catch {}
pub trait Finally: Callback {
#[doc(hidden)]
fn finally(self, batch: &Batch) -> impl Future<Output = Result<()>> + Send;
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EncodedCallback {
pub(crate) callback: String,
pub(crate) data: Value,
#[serde(skip)]
pub(crate) dispatched: Dispatched,
}
impl EncodedCallback {
#[expect(
clippy::needless_pass_by_value,
reason = "a chain or batch takes the callback, and only its payload outlives it"
)]
pub fn new<C: Callback>(callback: C) -> Result<Self> {
let mut rows = ModelRows::new();
let data = super::queueable::store("callback", C::NAME, &callback, &mut rows)?;
Ok(Self {
callback: C::NAME.to_owned(),
data,
dispatched: Dispatched::new(rows),
})
}
pub(crate) async fn call(&self, point: Point<'_>, context: &Context) {
if let Err(error) = self.run(point).await {
context.report(error);
}
}
pub async fn run(&self, point: Point<'_>) -> Result<()> {
let called = match registry().get(self.callback.as_str()) {
Some(registration) => registration.call(self.data.clone(), point),
None => Err(crate::error::fail(format!(
"no callback named `{}` is registered: was it renamed, or removed, after it was dispatched?",
self.callback
))),
};
match called {
Ok(future) => panic::catch(future).await,
Err(error) => Err(error),
}
}
}
#[derive(Clone, Copy)]
pub enum Point<'a> {
Then(&'a Batch),
Catch(Option<&'a Batch>, &'a Error),
Finally(&'a Batch),
}
impl<'a> std::fmt::Debug for Point<'a> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("Point").finish_non_exhaustive()
}
}
type OnBatch = for<'a> fn(Value, &'a Batch) -> BoxFuture<'a, Result<()>>;
type OnCatch = for<'a> fn(Value, Option<&'a Batch>, &'a Error) -> BoxFuture<'a, Result<()>>;
#[doc(hidden)]
#[derive(Debug)]
pub struct __CallbackRegistration {
name: &'static str,
type_name: fn() -> &'static str,
then: Option<OnBatch>,
catch: Option<OnCatch>,
finally: Option<OnBatch>,
}
impl __CallbackRegistration {
#[must_use]
pub const fn new<C: Callback>() -> Self {
Self {
name: C::NAME,
type_name: type_name::<C>,
then: None,
catch: None,
finally: None,
}
}
#[must_use]
pub const fn then<C: Then>(mut self) -> Self {
self.then = Some(then::<C>);
self
}
#[must_use]
pub const fn catch<C: Catch>(mut self) -> Self {
self.catch = Some(catch::<C>);
self
}
#[must_use]
pub const fn finally<C: Finally>(mut self) -> Self {
self.finally = Some(finally::<C>);
self
}
fn call<'a>(&self, data: Value, point: Point<'a>) -> Result<BoxFuture<'a, Result<()>>> {
let (method, called) = match point {
Point::Then(batch) => ("then", self.then.map(|then| then(data, batch))),
Point::Catch(batch, error) => ("catch", self.catch.map(|catch| catch(data, batch, error))),
Point::Finally(batch) => ("finally", self.finally.map(|finally| finally(data, batch))),
};
called.ok_or_else(|| crate::error::fail(format!("the callback `{}` has no `{method}` method", self.name)))
}
}
inventory::collect!(__CallbackRegistration);
fn then<C: Then>(data: Value, batch: &Batch) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
match restore_unless_missing::<C>(data).await? {
Some(callback) => callback.then(batch).await,
None => Ok(()),
}
})
}
fn catch<'a, C: Catch>(data: Value, batch: Option<&'a Batch>, error: &'a Error) -> BoxFuture<'a, Result<()>> {
Box::pin(async move {
match restore_unless_missing::<C>(data).await? {
Some(callback) => callback.catch(batch, error).await,
None => Ok(()),
}
})
}
fn finally<C: Finally>(data: Value, batch: &Batch) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
match restore_unless_missing::<C>(data).await? {
Some(callback) => callback.finally(batch).await,
None => Ok(()),
}
})
}
async fn restore_unless_missing<C: Callback>(data: Value) -> Result<Option<C>> {
match restore::<C>(data).await {
Ok(callback) => Ok(Some(callback)),
Err(error) if error.is::<MissingModels>() && !C::FAIL_WHEN_MISSING_MODELS => {
crate::foundation::telemetry::logging(
&error,
|| tracing::info!(target: "laravel::queue", callback = C::NAME, %error, "Skipped a callback whose models are gone"),
);
Ok(None)
}
Err(error) => Err(error),
}
}
pub(crate) async fn restore<C: Callback>(data: Value) -> Result<C> {
C::__restore(data)
.await
.map_err(|error| super::queueable::restore_error("callback", C::NAME, error))
}
fn registry() -> &'static HashMap<&'static str, &'static __CallbackRegistration> {
static REGISTRY: LazyLock<HashMap<&'static str, &'static __CallbackRegistration>> = LazyLock::new(|| {
inventory::iter::<__CallbackRegistration>
.into_iter()
.map(|registration| (registration.name, registration))
.collect()
});
®ISTRY
}
pub(crate) fn check_names() -> Result<(), String> {
super::job::duplicate_names(
"callbacks",
"#[callback(name = \"..\")]",
inventory::iter::<__CallbackRegistration>
.into_iter()
.map(|registration| (registration.name, (registration.type_name)())),
)
}