use crate::error::Error;
use crate::payload::Payload;
use crate::task::RetryPolicy;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub type TaskHandlerFn = Arc<
dyn Fn(crate::TaskContext, Payload) -> BoxFuture<'static, Result<Payload, Error>> + Send + Sync,
>;
pub type WorkflowHandlerFn = Arc<
dyn Fn(crate::WorkflowContext, Payload) -> BoxFuture<'static, Result<Payload, Error>>
+ Send
+ Sync,
>;
pub type UpdateHandlerFn = Arc<
dyn Fn(crate::WorkflowContext, Payload) -> BoxFuture<'static, Result<Payload, Error>>
+ Send
+ Sync,
>;
pub type ActorHandlerFn = Arc<
dyn Fn(crate::actor::ActorContext, Vec<u8>) -> BoxFuture<'static, Result<Vec<u8>, Error>>
+ Send
+ Sync,
>;
#[cfg(feature = "auto-register")]
pub type TaskRegistrationFn = fn(&mut crate::worker::Registry);
#[cfg(feature = "auto-register")]
#[derive(Clone, Copy)]
pub struct TaskRegistration {
pub register_fn: TaskRegistrationFn,
}
#[cfg(feature = "auto-register")]
inventory::collect!(TaskRegistration);
#[cfg(feature = "auto-register")]
impl TaskRegistration {
pub const fn new(register_fn: TaskRegistrationFn) -> Self {
Self { register_fn }
}
pub fn register(&self, registry: &mut crate::worker::Registry) {
(self.register_fn)(registry);
}
}
#[cfg(feature = "auto-register")]
impl std::fmt::Debug for TaskRegistration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TaskRegistration")
.field("register_fn", &"<function>")
.finish()
}
}
#[cfg(feature = "auto-register")]
pub type WorkflowRegistrationFn = fn(&mut crate::worker::Registry);
#[cfg(feature = "auto-register")]
#[derive(Clone, Copy)]
pub struct WorkflowRegistration {
pub register_fn: WorkflowRegistrationFn,
}
#[cfg(feature = "auto-register")]
inventory::collect!(WorkflowRegistration);
#[cfg(feature = "auto-register")]
impl WorkflowRegistration {
pub const fn new(register_fn: WorkflowRegistrationFn) -> Self {
Self { register_fn }
}
pub fn register(&self, registry: &mut crate::worker::Registry) {
(self.register_fn)(registry);
}
}
#[cfg(feature = "auto-register")]
impl std::fmt::Debug for WorkflowRegistration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WorkflowRegistration")
.field("register_fn", &"<function>")
.finish()
}
}
#[cfg(feature = "auto-register")]
pub type UpdateRegistrationFn = fn(&mut crate::worker::Registry);
#[cfg(feature = "auto-register")]
#[derive(Clone, Copy)]
pub struct UpdateRegistration {
pub register_fn: UpdateRegistrationFn,
}
#[cfg(feature = "auto-register")]
inventory::collect!(UpdateRegistration);
#[cfg(feature = "auto-register")]
impl UpdateRegistration {
pub const fn new(register_fn: UpdateRegistrationFn) -> Self {
Self { register_fn }
}
pub fn register(&self, registry: &mut crate::worker::Registry) {
(self.register_fn)(registry);
}
}
#[cfg(feature = "auto-register")]
impl std::fmt::Debug for UpdateRegistration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UpdateRegistration")
.field("register_fn", &"<function>")
.finish()
}
}
#[derive(Clone)]
pub struct ActorHandlerRegistration {
pub actor_name: &'static str,
pub operation_name: &'static str,
pub mode: crate::actor::types::OperationMode,
pub handler: ActorHandlerFn,
}
impl std::fmt::Debug for ActorHandlerRegistration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ActorHandlerRegistration")
.field("actor_name", &self.actor_name)
.field("operation_name", &self.operation_name)
.field("mode", &self.mode)
.field("handler", &"<function>")
.finish()
}
}
#[derive(Clone, Debug)]
pub struct TaskMetadata {
pub description: Option<String>,
pub timeout_seconds: Option<u64>,
pub heartbeat_timeout_seconds: Option<u64>,
pub retry_policy: Option<RetryPolicy>,
pub namespace: Option<String>,
pub version: Option<String>,
pub task_queue: Option<String>,
pub priority: Option<u8>,
pub max_concurrent: Option<u32>,
pub rate_limit: Option<u32>,
pub idempotency_key: Option<String>,
}
#[derive(Clone, Debug)]
pub struct WorkflowMetadata {
pub description: Option<String>,
pub version: String,
pub timeout_seconds: Option<u64>,
pub tags: Vec<String>,
pub namespace: Option<String>,
pub task_queue: Option<String>,
pub max_concurrent_steps: Option<u32>,
pub max_concurrent_executions: Option<u32>,
pub cron_schedule: Option<String>,
pub auto_heartbeat: bool,
pub heartbeat_interval_seconds: Option<u64>,
pub on_timeout: Option<String>,
pub retry_policy: Option<RetryPolicy>,
}
static TASK_RETRY_POLICIES: std::sync::OnceLock<
std::sync::RwLock<std::collections::HashMap<String, RetryPolicy>>,
> = std::sync::OnceLock::new();
fn task_retry_registry(
) -> &'static std::sync::RwLock<std::collections::HashMap<String, RetryPolicy>> {
TASK_RETRY_POLICIES.get_or_init(|| std::sync::RwLock::new(std::collections::HashMap::new()))
}
#[derive(Debug, Clone, Copy, Default)]
pub struct DeclaredTaskLimits {
pub timeout_secs: Option<u64>,
pub heartbeat_timeout_secs: Option<u64>,
}
static TASK_LIMITS: std::sync::OnceLock<
std::sync::RwLock<std::collections::HashMap<String, DeclaredTaskLimits>>,
> = std::sync::OnceLock::new();
fn task_limits_registry(
) -> &'static std::sync::RwLock<std::collections::HashMap<String, DeclaredTaskLimits>> {
TASK_LIMITS.get_or_init(|| std::sync::RwLock::new(std::collections::HashMap::new()))
}
pub fn register_task_limits(name: impl Into<String>, limits: DeclaredTaskLimits) {
if limits.timeout_secs.is_none() && limits.heartbeat_timeout_secs.is_none() {
return;
}
if let Ok(mut map) = task_limits_registry().write() {
map.insert(name.into(), limits);
}
}
pub fn task_limits(name: &str) -> Option<DeclaredTaskLimits> {
task_limits_registry().read().ok()?.get(name).copied()
}
pub fn register_task_retry_policy(name: impl Into<String>, policy: Option<RetryPolicy>) {
if let Some(policy) = policy {
if let Ok(mut map) = task_retry_registry().write() {
map.insert(name.into(), policy);
}
}
}
pub fn task_retry_policy(name: &str) -> Option<RetryPolicy> {
task_retry_registry().read().ok()?.get(name).cloned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_retry_policy_default() {
let policy = RetryPolicy::default();
assert_eq!(policy.max_attempts, 3);
assert_eq!(policy.initial_interval, std::time::Duration::from_secs(1));
assert_eq!(policy.max_interval, std::time::Duration::from_secs(60));
assert_eq!(policy.backoff_coefficient, 2.0);
}
#[test]
fn test_task_metadata() {
let metadata = TaskMetadata {
description: Some("Test task".to_string()),
timeout_seconds: Some(120),
heartbeat_timeout_seconds: Some(30),
retry_policy: Some(RetryPolicy::default()),
namespace: Some("default".to_string()),
version: Some("1.0.0".to_string()),
task_queue: Some("workers".to_string()),
priority: Some(50),
max_concurrent: Some(10),
rate_limit: Some(100),
idempotency_key: Some("task-{id}".to_string()),
};
assert_eq!(metadata.description, Some("Test task".to_string()));
assert_eq!(metadata.timeout_seconds, Some(120));
assert_eq!(metadata.heartbeat_timeout_seconds, Some(30));
assert!(metadata.retry_policy.is_some());
assert_eq!(metadata.task_queue, Some("workers".to_string()));
assert_eq!(metadata.priority, Some(50));
assert_eq!(metadata.max_concurrent, Some(10));
assert_eq!(metadata.rate_limit, Some(100));
}
#[test]
fn test_workflow_metadata() {
let metadata = WorkflowMetadata {
description: Some("Test workflow".to_string()),
version: "1.0.0".to_string(),
timeout_seconds: Some(600),
tags: vec!["test".to_string(), "demo".to_string()],
namespace: Some("default".to_string()),
task_queue: Some("orders".to_string()),
max_concurrent_steps: Some(10),
max_concurrent_executions: Some(5),
cron_schedule: Some("0 0 * * *".to_string()),
auto_heartbeat: true,
heartbeat_interval_seconds: Some(30),
on_timeout: Some("cancel".to_string()),
retry_policy: Some(RetryPolicy::default()),
};
assert_eq!(metadata.version, "1.0.0");
assert_eq!(metadata.tags.len(), 2);
assert!(metadata.tags.contains(&"test".to_string()));
assert_eq!(metadata.task_queue, Some("orders".to_string()));
assert_eq!(metadata.max_concurrent_executions, Some(5));
assert_eq!(metadata.cron_schedule, Some("0 0 * * *".to_string()));
assert!(metadata.auto_heartbeat);
assert_eq!(metadata.heartbeat_interval_seconds, Some(30));
}
#[cfg(feature = "auto-register")]
#[test]
fn test_global_registry_available() {
use crate::worker::registry::GLOBAL_REGISTRY;
let registry = GLOBAL_REGISTRY.read().unwrap();
println!(
"✅ Global registry available with {} tasks and {} workflows",
registry.task_count(),
registry.workflow_count()
);
}
}