use crate::error::types::TaskFailure;
use crate::task::context::TaskContext;
use std::future::Future;
use std::pin::Pin;
pub type BoxTaskFuture = Pin<Box<dyn Future<Output = TaskResult> + Send + 'static>>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TaskResult {
Succeeded,
Cancelled,
Failed(TaskFailure),
}
impl TaskResult {
pub fn is_success(&self) -> bool {
matches!(self, Self::Succeeded)
}
}
pub trait TaskFactory: Send + Sync + 'static {
fn build(&self, ctx: TaskContext) -> BoxTaskFuture;
}
pub trait Service: Send + Sync + 'static {
fn call(&self, ctx: TaskContext) -> BoxTaskFuture;
}
impl<T> TaskFactory for T
where
T: Service,
{
fn build(&self, ctx: TaskContext) -> BoxTaskFuture {
self.call(ctx)
}
}
pub struct ServiceFn<F> {
function: F,
}
impl<F, Fut> Service for ServiceFn<F>
where
F: Fn(TaskContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = TaskResult> + Send + 'static,
{
fn call(&self, ctx: TaskContext) -> BoxTaskFuture {
Box::pin((self.function)(ctx))
}
}
pub fn service_fn<F, Fut>(function: F) -> ServiceFn<F>
where
F: Fn(TaskContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = TaskResult> + Send + 'static,
{
ServiceFn { function }
}