use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, LazyLock};
use futures_util::future::BoxFuture;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use super::{PendingStart, Run};
use crate::queue::Queueable;
use crate::{Error, Result};
pub trait Workflow: Queueable {
const NAME: &'static str;
type Output: Serialize + DeserializeOwned + Send + 'static;
#[must_use]
fn queue() -> Option<&'static str> {
None
}
fn handle(self, run: &Run) -> impl Future<Output = Result<Self::Output>> + Send;
fn failed(self, error: &Error) -> impl Future<Output = Result<()>> + Send {
let _ = error;
async { Ok(()) }
}
#[track_caller]
fn start(self) -> PendingStart<Self> {
PendingStart::new(self)
}
}
#[doc(hidden)]
#[diagnostic::on_unimplemented(
message = "`{Self}` isn't a workflow's return type",
label = "return `laravel::Result<T>`, where `T` serializes",
note = "the run keeps what `handle` returns as its output, so `T` must be `Serialize` and `Deserialize`"
)]
pub trait __WorkflowResult {
type Output: Serialize + DeserializeOwned + Send + 'static;
fn into_result(self) -> Result<Self::Output>;
}
impl __WorkflowResult for () {
type Output = ();
fn into_result(self) -> Result<()> {
Ok(())
}
}
impl<T: Serialize + DeserializeOwned + Send + 'static> __WorkflowResult for Result<T> {
type Output = T;
fn into_result(self) -> Result<T> {
self
}
}
type Advance = fn(Value, Arc<Run>) -> BoxFuture<'static, Result<BoxFuture<'static, Result<String>>>>;
type Failed = for<'a> fn(Value, &'a Error) -> BoxFuture<'a, Result<()>>;
#[doc(hidden)]
#[derive(Debug)]
pub struct __Registration {
name: &'static str,
type_name: fn() -> &'static str,
advance: Advance,
failed: Failed,
}
impl __Registration {
#[must_use]
pub const fn new<W: Workflow>() -> Self {
Self {
name: W::NAME,
type_name: std::any::type_name::<W>,
advance: advance::<W>,
failed: failed::<W>,
}
}
pub(super) fn find(name: &str) -> Result<&'static Self> {
registry().get(name).copied().ok_or_else(|| {
crate::error::fail(format!(
"no workflow named `{name}` is registered: was it renamed, or removed, after the run started?"
))
})
}
pub(super) const fn name(&self) -> &'static str {
self.name
}
pub(crate) fn advance(
&self,
input: Value,
run: Arc<Run>,
) -> BoxFuture<'static, Result<BoxFuture<'static, Result<String>>>> {
(self.advance)(input, run)
}
pub(super) fn failed<'a>(&self, input: Value, error: &'a Error) -> BoxFuture<'a, Result<()>> {
(self.failed)(input, error)
}
}
inventory::collect!(__Registration);
fn advance<W: Workflow>(input: Value, run: Arc<Run>) -> BoxFuture<'static, Result<BoxFuture<'static, Result<String>>>> {
Box::pin(async move {
let workflow = restore::<W>(input).await?;
Ok(Box::pin(crate::errors::panic::catch(async move {
let output = workflow.handle(&run).await?;
Ok(serde_json::to_string(&output)?)
})) as BoxFuture<'static, Result<String>>)
})
}
fn failed<'a, W: Workflow>(input: Value, error: &'a Error) -> BoxFuture<'a, Result<()>> {
Box::pin(async move { restore::<W>(input).await?.failed(error).await })
}
async fn restore<W: Workflow>(input: Value) -> Result<W> {
W::__restore(input)
.await
.map_err(|error| crate::queue::restore_error("workflow", W::NAME, error))
}
fn registry() -> &'static HashMap<&'static str, &'static __Registration> {
static REGISTRY: LazyLock<HashMap<&'static str, &'static __Registration>> = LazyLock::new(|| {
inventory::iter::<__Registration>
.into_iter()
.map(|registration| (registration.name, registration))
.collect()
});
®ISTRY
}
pub(super) fn check_names() -> Result<(), String> {
crate::queue::duplicate_names(
"workflows",
"#[workflow(name = \"..\")]",
inventory::iter::<__Registration>
.into_iter()
.map(|registration| (registration.name, (registration.type_name)())),
)
}