Skip to main content

everruns_durable/persistence/
store.rs

1//! Store trait definitions: focused traits plus the `WorkflowEventStore` umbrella
2
3use std::time::Duration;
4
5use async_trait::async_trait;
6use chrono::{DateTime, Utc};
7use serde::{Deserialize, Serialize};
8use uuid::Uuid;
9
10use crate::UpdateField;
11use crate::workflow::{ActivityOptions, WorkflowEvent};
12
13/// Default snapshot interval: save a snapshot every N events.
14/// Configurable via `DURABLE_SNAPSHOT_INTERVAL` env var.
15pub const DEFAULT_SNAPSHOT_INTERVAL: i32 = 1000;
16
17/// Read snapshot interval from env, falling back to default.
18pub fn snapshot_interval_from_env() -> i32 {
19    std::env::var("DURABLE_SNAPSHOT_INTERVAL")
20        .ok()
21        .and_then(|v| v.parse().ok())
22        .unwrap_or(DEFAULT_SNAPSHOT_INTERVAL)
23}
24
25/// Default max pending (unclaimed) tasks per workflow.
26/// Prevents a single workflow from flooding the queue.
27pub const DEFAULT_MAX_PENDING_TASKS_PER_WORKFLOW: u32 = 100;
28
29/// Default max pending standalone tasks (generic queue).
30/// Prevents unbounded queue growth when no workflow limits apply.
31pub const DEFAULT_MAX_PENDING_STANDALONE_TASKS: u32 = 10_000;
32
33/// Workers with no heartbeat within this many seconds are considered stale.
34/// Used by get_system_health, list_workers, and reclaim_stale_tasks (stale worker cleanup).
35pub const WORKER_HEARTBEAT_TIMEOUT_SECS: i64 = 60;
36
37/// Read max pending tasks per workflow from env, falling back to default.
38pub fn max_pending_tasks_per_workflow_from_env() -> u32 {
39    std::env::var("DURABLE_MAX_PENDING_TASKS_PER_WORKFLOW")
40        .ok()
41        .and_then(|v| v.parse().ok())
42        .unwrap_or(DEFAULT_MAX_PENDING_TASKS_PER_WORKFLOW)
43}
44
45/// Error type for store operations
46#[derive(Debug, thiserror::Error)]
47pub enum StoreError {
48    /// Workflow not found
49    #[error("workflow not found: {0}")]
50    WorkflowNotFound(Uuid),
51
52    /// Task not found
53    #[error("task not found: {0}")]
54    TaskNotFound(Uuid),
55
56    /// Task not owned by the worker (was reclaimed)
57    #[error("task {0} not owned by worker (was reclaimed or already completed)")]
58    TaskNotOwned(Uuid),
59
60    /// Circuit breaker not found
61    #[error("circuit breaker not found: {0}")]
62    CircuitBreakerNotFound(String),
63
64    /// Schedule not found
65    #[error("schedule not found: {0}")]
66    ScheduleNotFound(Uuid),
67
68    /// Schedule execution not found
69    #[error("schedule execution not found: {0}")]
70    ScheduleExecutionNotFound(Uuid),
71
72    /// Schedule limit exceeded
73    #[error("schedule limit exceeded: {current}/{limit} schedules")]
74    ScheduleLimitExceeded { current: u32, limit: u32 },
75
76    /// Task queue limit exceeded (per-workflow pending task cap)
77    #[error(
78        "task queue limit exceeded for workflow {workflow_id}: {current}/{limit} pending tasks"
79    )]
80    TaskQueueLimitExceeded {
81        workflow_id: Uuid,
82        current: u32,
83        limit: u32,
84    },
85
86    /// Standalone task queue limit exceeded (global cap)
87    #[error("standalone task queue limit exceeded: {current}/{limit} pending tasks")]
88    StandaloneTaskQueueLimitExceeded { current: u32, limit: u32 },
89
90    /// Invalid cron expression
91    #[error("invalid cron expression: {0}")]
92    InvalidCronExpression(String),
93
94    /// Cron interval too short
95    #[error("cron interval too short: {actual}s < {minimum}s minimum")]
96    CronIntervalTooShort { actual: u64, minimum: u64 },
97
98    /// Concurrency conflict (optimistic locking failed)
99    #[error("concurrency conflict: expected sequence {expected}, got {actual}")]
100    ConcurrencyConflict { expected: i32, actual: i32 },
101
102    /// Database error
103    #[error("database error: {0}")]
104    Database(String),
105
106    /// Serialization error
107    #[error("serialization error: {0}")]
108    Serialization(String),
109}
110
111/// Workflow status
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "snake_case")]
114pub enum WorkflowStatus {
115    /// Workflow created but not started
116    Pending,
117
118    /// Workflow is running
119    Running,
120
121    /// Workflow completed successfully
122    Completed,
123
124    /// Workflow failed
125    Failed,
126
127    /// Workflow was cancelled
128    Cancelled,
129
130    /// Workflow continued as a new workflow (history rolled over)
131    ContinuedAsNew,
132}
133
134impl WorkflowStatus {
135    /// Check if this status is terminal (workflow has ended)
136    pub fn is_terminal(&self) -> bool {
137        matches!(
138            self,
139            Self::Completed | Self::Failed | Self::Cancelled | Self::ContinuedAsNew
140        )
141    }
142}
143
144impl std::fmt::Display for WorkflowStatus {
145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146        match self {
147            Self::Pending => write!(f, "pending"),
148            Self::Running => write!(f, "running"),
149            Self::Completed => write!(f, "completed"),
150            Self::Failed => write!(f, "failed"),
151            Self::Cancelled => write!(f, "cancelled"),
152            Self::ContinuedAsNew => write!(f, "continued_as_new"),
153        }
154    }
155}
156
157/// Task status in the queue
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(rename_all = "snake_case")]
160pub enum TaskStatus {
161    Pending,
162    Claimed,
163    Completed,
164    Failed,
165    Dead,
166    Cancelled,
167}
168
169/// Definition of a task to be enqueued.
170/// When `workflow_id` is `None`, this is a standalone (generic queue) task
171/// that runs independently of any workflow.
172#[derive(Debug, Clone)]
173pub struct TaskDefinition {
174    pub workflow_id: Option<Uuid>,
175    pub activity_id: String,
176    pub activity_type: String,
177    pub input: serde_json::Value,
178    pub options: ActivityOptions,
179}
180
181/// A task that has been claimed by a worker
182#[derive(Debug, Clone, Default)]
183pub struct ClaimedTask {
184    pub id: Uuid,
185    pub workflow_id: Option<Uuid>,
186    pub activity_id: String,
187    pub activity_type: String,
188    pub input: serde_json::Value,
189    pub options: ActivityOptions,
190    pub attempt: u32,
191    pub max_attempts: u32,
192    /// Status of the task's workflow, read in the same statement as the
193    /// claim, so a worker can skip work for a cancelled or finished workflow
194    /// without a second read. `None` for standalone tasks.
195    pub workflow_status: Option<WorkflowStatus>,
196}
197
198/// Response from heartbeat operation
199#[derive(Debug, Clone)]
200pub struct HeartbeatResponse {
201    /// Whether the heartbeat was accepted
202    pub accepted: bool,
203
204    /// Whether cancellation was requested
205    pub should_cancel: bool,
206}
207
208/// What the registry tells a worker in reply to its heartbeat.
209#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
210pub struct WorkerHeartbeat {
211    /// The worker is draining (an operator drained it, or it is shutting
212    /// down): the queue hands it no new tasks, so it should stop claiming.
213    /// False for a worker the registry does not know.
214    pub draining: bool,
215}
216
217/// Outcome of failing a task
218#[derive(Debug, Clone)]
219pub enum TaskFailureOutcome {
220    /// Task will be retried
221    WillRetry { next_attempt: u32, delay: Duration },
222
223    /// Task moved to dead letter queue
224    MovedToDlq,
225
226    /// Task completed (no more retries, workflow notified)
227    ExhaustedRetries,
228}
229
230/// Information about a task that was marked as dead during stale reclamation.
231#[derive(Debug, Clone)]
232pub struct DeadTaskInfo {
233    pub task_id: Uuid,
234    pub workflow_id: Option<Uuid>,
235    pub activity_id: String,
236    pub activity_type: String,
237    /// Serialized task input, so the application can recover its own context.
238    pub input: serde_json::Value,
239    pub last_error: Option<String>,
240}
241
242/// Information about a task that the no-progress guard sealed during stale
243/// reclamation: its workflow recorded no new event across `N` consecutive
244/// recoveries, so retrying it again would only crash-loop (EVE-534).
245///
246/// A sealed task is terminal and non-retryable: the reclaim path marks it dead
247/// (routing it to the DLQ) instead of returning it to `pending`. What a seal
248/// means to the application (a user-facing event, a status change) is decided
249/// by the consumer of [`ReclaimResult::sealed_tasks`].
250#[derive(Debug, Clone)]
251pub struct SealedTaskInfo {
252    pub task_id: Uuid,
253    pub workflow_id: Option<Uuid>,
254    pub activity_id: String,
255    pub activity_type: String,
256    /// The task's serialized input, so consumers can recover their own context
257    /// for whatever a seal means to them.
258    pub input: serde_json::Value,
259    /// Stable seal-reason wire string (always `"no_progress"` here: the reclaim
260    /// path's only seal is the no-progress guard).
261    pub reason: String,
262    /// Number of consecutive no-progress recoveries that triggered the seal.
263    pub no_progress_count: u32,
264}
265
266/// Default number of consecutive no-progress recoveries before a task is sealed.
267/// Override with `DURABLE_NO_PROGRESS_SEAL_THRESHOLD`; see
268/// [`no_progress_seal_threshold_from_env`]. EVE-534.
269pub const DEFAULT_NO_PROGRESS_SEAL_THRESHOLD: u32 = 3;
270
271/// Read the no-progress seal threshold from the environment, falling back to
272/// [`DEFAULT_NO_PROGRESS_SEAL_THRESHOLD`]. A value of 0 is coerced to 1 so the
273/// guard can never be disabled into an infinite crash-loop.
274pub fn no_progress_seal_threshold_from_env() -> u32 {
275    std::env::var("DURABLE_NO_PROGRESS_SEAL_THRESHOLD")
276        .ok()
277        .and_then(|v| v.parse::<u32>().ok())
278        .unwrap_or(DEFAULT_NO_PROGRESS_SEAL_THRESHOLD)
279        .max(1)
280}
281
282/// Result of stale task reclamation.
283#[derive(Debug, Clone, Default)]
284pub struct ReclaimResult {
285    /// Tasks that were reclaimed (returned to pending for retry).
286    pub reclaimed_ids: Vec<Uuid>,
287    /// Tasks that were marked as dead (exhausted all retries).
288    pub dead_tasks: Vec<DeadTaskInfo>,
289    /// Tasks that were sealed for making no forward progress across repeated
290    /// recoveries (EVE-534). These are terminal/non-retryable (routed to DLQ).
291    pub sealed_tasks: Vec<SealedTaskInfo>,
292}
293
294/// Filter for listing workers
295#[derive(Debug, Clone, Default)]
296pub struct WorkerFilter {
297    pub status: Option<String>,
298    pub worker_group: Option<String>,
299}
300
301impl WorkerFilter {
302    pub fn active() -> Self {
303        Self {
304            status: Some("active".to_string()),
305            worker_group: None,
306        }
307    }
308}
309
310/// Filter for listing workflows
311#[derive(Debug, Clone, Default)]
312pub struct WorkflowFilter {
313    pub status: Option<WorkflowStatus>,
314    pub workflow_type: Option<String>,
315}
316
317/// Filter for listing tasks
318#[derive(Debug, Clone, Default)]
319pub struct TaskFilter {
320    pub status: Option<TaskStatus>,
321    pub activity_type: Option<String>,
322    pub workflow_id: Option<Uuid>,
323    /// When true, only return standalone tasks (workflow_id IS NULL)
324    pub standalone_only: bool,
325}
326
327/// Task information for listing
328#[derive(Debug, Clone)]
329pub struct TaskInfo {
330    pub id: Uuid,
331    pub workflow_id: Option<Uuid>,
332    pub activity_id: String,
333    pub activity_type: String,
334    pub status: TaskStatus,
335    pub priority: i32,
336    pub attempt: u32,
337    pub max_attempts: u32,
338    pub claimed_by: Option<String>,
339    pub last_error: Option<String>,
340    pub created_at: DateTime<Utc>,
341    pub claimed_at: Option<DateTime<Utc>>,
342    /// The task queue it was enqueued to; `None` is the default queue.
343    pub queue: Option<String>,
344}
345
346/// Extended workflow information with timestamps
347#[derive(Debug, Clone)]
348pub struct WorkflowInfoExtended {
349    pub id: Uuid,
350    pub workflow_type: String,
351    pub status: WorkflowStatus,
352    pub input: serde_json::Value,
353    pub result: Option<serde_json::Value>,
354    pub error: Option<crate::workflow::WorkflowError>,
355    pub created_at: DateTime<Utc>,
356    pub started_at: Option<DateTime<Utc>>,
357    pub completed_at: Option<DateTime<Utc>>,
358    /// If this workflow continued as a new workflow, the ID of the new workflow
359    pub continued_as_new_id: Option<Uuid>,
360}
361
362/// System health summary
363#[derive(Debug, Clone)]
364pub struct SystemHealth {
365    pub total_workers: usize,
366    pub active_workers: usize,
367    pub workers_accepting: usize,
368    pub total_capacity: usize,
369    pub current_load: usize,
370    pub pending_tasks: usize,
371    pub claimed_tasks: usize,
372    pub completed_tasks: usize,
373    pub failed_tasks: usize,
374    /// Cumulative: tasks that have ever been started (claimed_at IS NOT NULL)
375    pub started_tasks: usize,
376    pub running_workflows: usize,
377    pub pending_workflows: usize,
378    pub completed_workflows: usize,
379    pub failed_workflows: usize,
380    /// Cumulative: workflows that have ever been started (started_at IS NOT NULL)
381    pub started_workflows: usize,
382    pub dlq_size: usize,
383}
384
385/// Workflow event info for API responses
386#[derive(Debug, Clone)]
387pub struct WorkflowEventInfo {
388    pub id: i64,
389    pub workflow_id: Uuid,
390    pub sequence_num: i32,
391    pub event_type: String,
392    pub event_data: serde_json::Value,
393    pub created_at: DateTime<Utc>,
394}
395
396/// Helper to get event type name
397pub fn event_type_name(event: &WorkflowEvent) -> &'static str {
398    match event {
399        WorkflowEvent::WorkflowStarted { .. } => "workflow_started",
400        WorkflowEvent::WorkflowCompleted { .. } => "workflow_completed",
401        WorkflowEvent::WorkflowFailed { .. } => "workflow_failed",
402        WorkflowEvent::WorkflowCancelled { .. } => "workflow_cancelled",
403        WorkflowEvent::ActivityScheduled { .. } => "activity_scheduled",
404        WorkflowEvent::ActivityStarted { .. } => "activity_started",
405        WorkflowEvent::ActivityCompleted { .. } => "activity_completed",
406        WorkflowEvent::ActivityFailed { .. } => "activity_failed",
407        WorkflowEvent::ActivityTimedOut { .. } => "activity_timed_out",
408        WorkflowEvent::ActivityCancelled { .. } => "activity_cancelled",
409        WorkflowEvent::TimerStarted { .. } => "timer_started",
410        WorkflowEvent::TimerFired { .. } => "timer_fired",
411        WorkflowEvent::TimerCancelled { .. } => "timer_cancelled",
412        WorkflowEvent::ChildWorkflowStarted { .. } => "child_workflow_started",
413        WorkflowEvent::ChildWorkflowCompleted { .. } => "child_workflow_completed",
414        WorkflowEvent::ChildWorkflowFailed { .. } => "child_workflow_failed",
415    }
416}
417
418/// Worker information
419#[derive(Debug, Clone)]
420pub struct WorkerInfo {
421    pub id: String,
422    pub worker_group: Option<String>,
423    pub activity_types: Vec<String>,
424    pub max_concurrency: u32,
425    pub current_load: u32,
426    pub status: String,
427    pub accepting_tasks: bool,
428    pub backpressure_reason: Option<String>,
429    pub started_at: DateTime<Utc>,
430    pub last_heartbeat_at: DateTime<Utc>,
431    pub hostname: Option<String>,
432    pub version: Option<String>,
433    pub metadata: Option<serde_json::Value>,
434    /// Total tasks completed by this worker
435    pub tasks_completed: u64,
436    /// Total tasks failed by this worker
437    pub tasks_failed: u64,
438    /// Average task duration in milliseconds
439    pub avg_task_duration_ms: Option<u64>,
440}
441
442impl WorkerInfo {
443    /// An active worker that accepts `activity_types`, ready for
444    /// [`WorkerRegistry::register_worker`].
445    ///
446    /// Both stores hand tasks only to a registered worker that is not
447    /// draining, so register before claiming.
448    ///
449    /// ```
450    /// use everruns_durable::{InMemoryWorkflowEventStore, TaskQueue, WorkerInfo, WorkerRegistry};
451    ///
452    /// # #[tokio::main]
453    /// # async fn main() -> Result<(), everruns_durable::StoreError> {
454    /// let store = InMemoryWorkflowEventStore::new();
455    /// store.register_worker(WorkerInfo::new("worker-1", ["send_email"])).await?;
456    /// let claimed = store.claim_task("worker-1", &["send_email".into()], 10).await?;
457    /// assert!(claimed.is_empty()); // registered, nothing queued yet
458    /// # Ok(()) }
459    /// ```
460    pub fn new<I, S>(id: impl Into<String>, activity_types: I) -> Self
461    where
462        I: IntoIterator<Item = S>,
463        S: Into<String>,
464    {
465        let now = Utc::now();
466        Self {
467            id: id.into(),
468            worker_group: None,
469            activity_types: activity_types.into_iter().map(Into::into).collect(),
470            max_concurrency: 10,
471            current_load: 0,
472            status: "active".to_string(),
473            accepting_tasks: true,
474            backpressure_reason: None,
475            started_at: now,
476            last_heartbeat_at: now,
477            hostname: None,
478            version: None,
479            metadata: None,
480            tasks_completed: 0,
481            tasks_failed: 0,
482            avg_task_duration_ms: None,
483        }
484    }
485
486    /// The worker/control-plane contract version the worker speaks, when it
487    /// said so at registration.
488    pub fn protocol_version(&self) -> Option<u32> {
489        self.metadata_field(WORKER_META_PROTOCOL_VERSION)?
490            .as_u64()
491            .and_then(|version| u32::try_from(version).ok())
492    }
493
494    /// When the worker started draining, for a draining worker.
495    pub fn draining_since(&self) -> Option<DateTime<Utc>> {
496        self.metadata_time(WORKER_META_DRAINING_SINCE)
497    }
498
499    /// The worker's latest report on its own setup
500    /// ([`WorkerRegistry::record_worker_checks`]) and when it arrived.
501    pub fn self_checks(&self) -> Option<(&serde_json::Value, DateTime<Utc>)> {
502        let checks = self.metadata_field(WORKER_META_SELF_CHECKS)?;
503        Some((checks, self.metadata_time(WORKER_META_SELF_CHECKED_AT)?))
504    }
505
506    fn metadata_field(&self, key: &str) -> Option<&serde_json::Value> {
507        self.metadata.as_ref()?.get(key)
508    }
509
510    fn metadata_time(&self, key: &str) -> Option<DateTime<Utc>> {
511        let value = self.metadata_field(key)?.as_str()?;
512        DateTime::parse_from_rfc3339(value)
513            .ok()
514            .map(|at| at.with_timezone(&Utc))
515    }
516}
517
518// Keys the registry keeps in `WorkerInfo::metadata`. Read them through the
519// `WorkerInfo` accessors above.
520pub(crate) const WORKER_META_PROTOCOL_VERSION: &str = "protocol_version";
521pub(crate) const WORKER_META_DRAINING_SINCE: &str = "draining_since";
522pub(crate) const WORKER_META_SELF_CHECKS: &str = "self_checks";
523pub(crate) const WORKER_META_SELF_CHECKED_AT: &str = "self_checked_at";
524
525/// Snapshot of total system worker capacity for fair-share claiming.
526#[derive(Debug, Clone, Default)]
527pub struct CapacitySnapshot {
528    /// Total available slots across all active, accepting workers
529    pub total_available: u32,
530    /// Number of active workers that are accepting tasks
531    pub active_workers: u32,
532}
533
534/// Filter for listing DLQ entries
535#[derive(Debug, Clone, Default)]
536pub struct DlqFilter {
537    pub workflow_id: Option<Uuid>,
538    pub activity_type: Option<String>,
539}
540
541/// Pagination parameters
542#[derive(Debug, Clone)]
543pub struct Pagination {
544    pub offset: u32,
545    pub limit: u32,
546}
547
548impl Default for Pagination {
549    fn default() -> Self {
550        Self {
551            offset: 0,
552            limit: 100,
553        }
554    }
555}
556
557/// Dead letter queue entry
558#[derive(Debug, Clone)]
559pub struct DlqEntry {
560    pub id: Uuid,
561    pub original_task_id: Uuid,
562    pub workflow_id: Option<Uuid>,
563    pub activity_id: String,
564    pub activity_type: String,
565    pub input: serde_json::Value,
566    pub attempts: u32,
567    pub last_error: String,
568    pub error_history: Vec<String>,
569    pub dead_at: DateTime<Utc>,
570}
571
572/// Trace context for distributed tracing
573#[derive(Debug, Clone, Serialize, Deserialize)]
574pub struct TraceContext {
575    pub trace_id: String,
576    pub span_id: String,
577    pub trace_flags: u8,
578}
579
580/// Workflow information stored in the database
581#[derive(Debug, Clone)]
582pub struct WorkflowInfo {
583    pub id: Uuid,
584    pub workflow_type: String,
585    pub status: WorkflowStatus,
586    pub input: serde_json::Value,
587    pub result: Option<serde_json::Value>,
588    pub error: Option<crate::workflow::WorkflowError>,
589    /// If this workflow continued as a new workflow, the ID of the new workflow
590    pub continued_as_new_id: Option<Uuid>,
591}
592
593/// A snapshot of serialized workflow state at a specific event sequence.
594///
595/// Used to checkpoint replay: instead of replaying all events from sequence 0,
596/// the engine loads the latest snapshot and replays only events after it.
597#[derive(Debug, Clone)]
598pub struct WorkflowSnapshot {
599    /// The workflow this snapshot belongs to
600    pub workflow_id: Uuid,
601
602    /// The event sequence number at which this snapshot was taken.
603    /// When restoring, events with sequence_num > this value are replayed.
604    pub sequence_num: i32,
605
606    /// Serialized workflow state (opaque bytes, typically JSON)
607    pub snapshot_data: Vec<u8>,
608
609    /// When the snapshot was created
610    pub created_at: DateTime<Utc>,
611}
612
613/// Workflow lifecycle and the append-only event log.
614///
615/// Covers workflow creation and status, optimistic-concurrency event appends,
616/// replay loads, replay snapshots, terminal transitions (fail, cancel,
617/// continue-as-new) and the atomic new-run claim. This is the core of the
618/// engine: anything that executes or replays a workflow needs it.
619///
620/// Every method must be implemented explicitly except the derived ones
621/// (`count_events`, `count_events_after`, `load_events_after`), which are
622/// correct but materialize history; stores should override them for efficiency.
623#[async_trait]
624pub trait EventLog: Send + Sync + 'static {
625    /// Create a new workflow instance
626    async fn create_workflow(
627        &self,
628        workflow_id: Uuid,
629        workflow_type: &str,
630        input: serde_json::Value,
631        trace_context: Option<&TraceContext>,
632    ) -> Result<(), StoreError>;
633
634    /// Get workflow status
635    async fn get_workflow_status(&self, workflow_id: Uuid) -> Result<WorkflowStatus, StoreError>;
636
637    /// Get full workflow info
638    async fn get_workflow_info(&self, workflow_id: Uuid) -> Result<WorkflowInfo, StoreError>;
639
640    /// Append events to a workflow (with optimistic concurrency)
641    ///
642    /// Returns the new sequence number after appending.
643    async fn append_events(
644        &self,
645        workflow_id: Uuid,
646        expected_sequence: i32,
647        events: Vec<WorkflowEvent>,
648    ) -> Result<i32, StoreError>;
649
650    /// Load all events for a workflow (for replay)
651    async fn load_events(&self, workflow_id: Uuid)
652    -> Result<Vec<(i32, WorkflowEvent)>, StoreError>;
653
654    /// Count events for a workflow without materializing the replay payload.
655    ///
656    /// Used to reject oversized full-history replays before fetching event data.
657    async fn count_events(&self, workflow_id: Uuid) -> Result<usize, StoreError> {
658        Ok(self.load_events(workflow_id).await?.len())
659    }
660
661    /// Count events after a given sequence number without materializing them.
662    ///
663    /// Used to reject oversized snapshot-based replays before fetching event data.
664    async fn count_events_after(
665        &self,
666        workflow_id: Uuid,
667        after_sequence: i32,
668    ) -> Result<usize, StoreError> {
669        Ok(self
670            .load_events_after(workflow_id, after_sequence)
671            .await?
672            .len())
673    }
674
675    /// Load events for a workflow starting after a given sequence number.
676    ///
677    /// Used for snapshot-based replay: load only events after the snapshot point.
678    async fn load_events_after(
679        &self,
680        workflow_id: Uuid,
681        after_sequence: i32,
682    ) -> Result<Vec<(i32, WorkflowEvent)>, StoreError> {
683        // Derived: filter from load_events (implementations should override for efficiency)
684        let all = self.load_events(workflow_id).await?;
685        Ok(all
686            .into_iter()
687            .filter(|(seq, _)| *seq > after_sequence)
688            .collect())
689    }
690
691    /// Save a workflow state snapshot at the given sequence number.
692    ///
693    /// The snapshot_data is opaque bytes (typically JSON-serialized workflow state).
694    /// Implementations should use UPSERT semantics for idempotency.
695    async fn save_snapshot(
696        &self,
697        workflow_id: Uuid,
698        sequence_num: i32,
699        snapshot_data: Vec<u8>,
700    ) -> Result<(), StoreError>;
701
702    /// Load the latest snapshot for a workflow, if any.
703    ///
704    /// Returns None if no snapshots exist for this workflow.
705    async fn load_latest_snapshot(
706        &self,
707        workflow_id: Uuid,
708    ) -> Result<Option<WorkflowSnapshot>, StoreError>;
709
710    /// Delete all snapshots for a workflow (cleanup on workflow deletion).
711    async fn delete_snapshots(&self, workflow_id: Uuid) -> Result<(), StoreError>;
712
713    /// Update workflow status
714    async fn update_workflow_status(
715        &self,
716        workflow_id: Uuid,
717        status: WorkflowStatus,
718        result: Option<serde_json::Value>,
719        error: Option<crate::workflow::WorkflowError>,
720    ) -> Result<(), StoreError>;
721
722    /// Atomically transition a running workflow to failed.
723    ///
724    /// Returns true only to the caller that won the terminal transition. This
725    /// elects one owner for external terminal lifecycle effects when a worker
726    /// failure races stale-task reclamation.
727    async fn try_fail_workflow(
728        &self,
729        workflow_id: Uuid,
730        error: crate::workflow::WorkflowError,
731    ) -> Result<bool, StoreError>;
732
733    /// Atomically start a new run of a long-lived workflow, unless one is
734    /// already active.
735    ///
736    /// A workflow instance can be reused for successive runs (for example one
737    /// per inbound request). This transitions it from any terminal status (or
738    /// pending) back to Running and clears its result, error and timestamps.
739    /// Returns true if the claim succeeded, false if a run is still active:
740    /// the workflow is Running or one of its tasks is claimed by a worker.
741    ///
742    /// Also cancels any stale pending tasks left by the previous run, in the
743    /// same atomic operation. Safe under horizontal scaling: only one caller
744    /// wins the claim.
745    async fn try_start_new_run(&self, workflow_id: Uuid) -> Result<bool, StoreError>;
746
747    /// Cancel a workflow
748    async fn cancel_workflow(&self, workflow_id: Uuid) -> Result<(), StoreError>;
749
750    /// Continue a workflow as a new workflow (history rollover).
751    ///
752    /// Creates a new workflow from the given snapshot state, marks the old
753    /// workflow as `ContinuedAsNew` with a reference to the new workflow,
754    /// and archives (deletes) old event history and snapshots.
755    ///
756    /// Returns the new workflow ID.
757    async fn continue_as_new(
758        &self,
759        old_workflow_id: Uuid,
760        workflow_type: &str,
761        input: serde_json::Value,
762        snapshot_data: Vec<u8>,
763    ) -> Result<Uuid, StoreError>;
764}
765
766/// Activity task queue: enqueue, claim, heartbeat and settle tasks.
767///
768/// Needed by workers (claim/heartbeat/complete/fail), by the engine that
769/// schedules activities (enqueue, cancel pending) and by the stale-task
770/// reaper (`reclaim_stale_tasks`). `fail_task` is derived from
771/// `fail_task_with_retry`; everything else must be implemented explicitly.
772#[async_trait]
773pub trait TaskQueue: Send + Sync + 'static {
774    /// Enqueue an activity task
775    async fn enqueue_task(&self, task: TaskDefinition) -> Result<Uuid, StoreError>;
776
777    /// Claim tasks of the default queue for execution; see
778    /// [`claim_queue_tasks`](Self::claim_queue_tasks).
779    async fn claim_task(
780        &self,
781        worker_id: &str,
782        activity_types: &[String],
783        max_tasks: usize,
784    ) -> Result<Vec<ClaimedTask>, StoreError> {
785        self.claim_queue_tasks(worker_id, None, activity_types, max_tasks)
786            .await
787    }
788
789    /// Claim up to `max_tasks` pending tasks of `activity_types` from one
790    /// task queue: the named one, or the default queue for `None`
791    /// ([`ActivityOptions::queue`](crate::ActivityOptions::queue)). A claim
792    /// never takes another queue's tasks.
793    ///
794    /// Uses SELECT FOR UPDATE SKIP LOCKED for efficient concurrent claiming.
795    async fn claim_queue_tasks(
796        &self,
797        worker_id: &str,
798        queue: Option<&str>,
799        activity_types: &[String],
800        max_tasks: usize,
801    ) -> Result<Vec<ClaimedTask>, StoreError>;
802
803    /// Record task heartbeat
804    async fn heartbeat_task(
805        &self,
806        task_id: Uuid,
807        worker_id: &str,
808        details: Option<serde_json::Value>,
809    ) -> Result<HeartbeatResponse, StoreError>;
810
811    /// Complete a task successfully
812    ///
813    /// The worker_id must match the worker that claimed the task.
814    /// Returns `StoreError::TaskNotOwned` if the task was reclaimed by another worker.
815    /// This prevents duplicate next activity scheduling when a task is reclaimed
816    /// due to heartbeat timeout while the original worker is still completing it.
817    async fn complete_task(
818        &self,
819        task_id: Uuid,
820        worker_id: &str,
821        result: serde_json::Value,
822    ) -> Result<(), StoreError>;
823
824    /// Fail a task using its normal retry policy.
825    async fn fail_task(
826        &self,
827        task_id: Uuid,
828        error: &str,
829    ) -> Result<TaskFailureOutcome, StoreError> {
830        self.fail_task_with_retry(task_id, error, true).await
831    }
832
833    /// Fail a task, optionally bypassing retries for deterministic failures.
834    async fn fail_task_with_retry(
835        &self,
836        task_id: Uuid,
837        error: &str,
838        retryable: bool,
839    ) -> Result<TaskFailureOutcome, StoreError>;
840
841    /// Cancel all pending (unclaimed) tasks for a workflow.
842    ///
843    /// Returns the number of tasks cancelled. Does NOT affect claimed or
844    /// completed tasks — only pending ones still in the queue.
845    async fn cancel_pending_tasks_for_workflow(&self, workflow_id: Uuid)
846    -> Result<u64, StoreError>;
847
848    /// Get task info by ID
849    async fn get_task(&self, task_id: Uuid) -> Result<TaskInfo, StoreError>;
850
851    /// Find and reclaim stale tasks (no heartbeat)
852    async fn reclaim_stale_tasks(
853        &self,
854        stale_threshold: Duration,
855    ) -> Result<ReclaimResult, StoreError>;
856
857    /// List tasks with filtering and pagination
858    async fn list_tasks(
859        &self,
860        filter: TaskFilter,
861        pagination: Pagination,
862    ) -> Result<Vec<TaskInfo>, StoreError>;
863}
864
865/// Worker registration, liveness and capacity.
866///
867/// Needed by workers (register, heartbeat, capacity snapshot for fair-share
868/// claiming, deregister) and by operators (list, drain, resume). A worker
869/// process needs only `TaskQueue + WorkerRegistry`.
870#[async_trait]
871pub trait WorkerRegistry: Send + Sync + 'static {
872    /// Register a worker
873    async fn register_worker(&self, worker: WorkerInfo) -> Result<(), StoreError>;
874
875    /// Update worker heartbeat and load, and report whether it is draining
876    async fn worker_heartbeat(
877        &self,
878        worker_id: &str,
879        current_load: usize,
880        accepting_tasks: bool,
881    ) -> Result<WorkerHeartbeat, StoreError>;
882
883    /// Get all active workers
884    async fn list_workers(&self, filter: WorkerFilter) -> Result<Vec<WorkerInfo>, StoreError>;
885
886    /// Deregister a worker and reclaim all tasks claimed by it
887    /// Returns the number of tasks that were reclaimed
888    async fn deregister_worker(&self, worker_id: &str) -> Result<usize, StoreError>;
889
890    /// Get a snapshot of total system worker capacity.
891    /// Used by workers to compute fair-share claim limits.
892    async fn get_capacity_snapshot(&self) -> Result<CapacitySnapshot, StoreError>;
893
894    /// Drain a worker (set status to draining, stop accepting new tasks)
895    async fn drain_worker(&self, worker_id: &str) -> Result<(), StoreError>;
896
897    /// Resume a draining worker (set status back to active, start accepting new tasks)
898    async fn resume_worker(&self, worker_id: &str) -> Result<(), StoreError>;
899
900    /// Keep the worker's report on its own setup (egress proxy reachable,
901    /// control-plane connection encrypted, ...), replacing the previous one.
902    /// Operators read it back through [`WorkerInfo::self_checks`]. A store
903    /// with no operator view may keep nothing.
904    async fn record_worker_checks(
905        &self,
906        worker_id: &str,
907        checks: serde_json::Value,
908    ) -> Result<(), StoreError> {
909        let _ = (worker_id, checks);
910        Ok(())
911    }
912}
913
914/// Dead letter queue for tasks that exhausted their retries.
915///
916/// Needed by the task-failure path (`move_to_dlq`) and by operators who
917/// inspect and requeue dead tasks.
918#[async_trait]
919pub trait DeadLetters: Send + Sync + 'static {
920    /// Move task to DLQ
921    async fn move_to_dlq(
922        &self,
923        task_id: Uuid,
924        error_history: Vec<String>,
925    ) -> Result<(), StoreError>;
926
927    /// Requeue task from DLQ
928    async fn requeue_from_dlq(&self, dlq_id: Uuid) -> Result<Uuid, StoreError>;
929
930    /// List DLQ entries
931    async fn list_dlq(
932        &self,
933        filter: DlqFilter,
934        pagination: Pagination,
935    ) -> Result<Vec<DlqEntry>, StoreError>;
936}
937
938/// Persistent circuit breaker state shared across workers.
939///
940/// Backs `DistributedCircuitBreaker` in `reliability/` and the admin
941/// force-open/close operations. Not yet wired into production call paths.
942#[async_trait]
943pub trait CircuitBreakers: Send + Sync + 'static {
944    /// Create a circuit breaker
945    async fn create_circuit_breaker(
946        &self,
947        key: &str,
948        config: &crate::reliability::CircuitBreakerConfig,
949    ) -> Result<(), StoreError>;
950
951    /// Get circuit breaker state
952    async fn get_circuit_breaker(
953        &self,
954        key: &str,
955    ) -> Result<Option<CircuitBreakerState>, StoreError>;
956
957    /// Update circuit breaker state
958    async fn update_circuit_breaker(
959        &self,
960        key: &str,
961        state: crate::reliability::CircuitState,
962        failure_count: u32,
963        success_count: u32,
964    ) -> Result<(), StoreError>;
965
966    /// List all circuit breakers
967    async fn list_circuit_breakers(&self) -> Result<Vec<CircuitBreakerState>, StoreError>;
968
969    /// Force a circuit breaker to open (admin operation)
970    async fn force_open_circuit_breaker(&self, key: &str) -> Result<(), StoreError>;
971
972    /// Force a circuit breaker to close (admin operation)
973    async fn force_close_circuit_breaker(&self, key: &str) -> Result<(), StoreError>;
974
975    /// Delete a circuit breaker (reset to default)
976    async fn delete_circuit_breaker(&self, key: &str) -> Result<(), StoreError>;
977}
978
979/// Cron/interval schedules, their executions and scheduler instances.
980///
981/// Needed by the `DurableScheduler` component (claim due schedules, record
982/// executions, instance heartbeats) and by the schedule management API.
983#[async_trait]
984pub trait Schedules: Send + Sync + 'static {
985    /// Pool whose schedule configuration joins a host command transaction.
986    fn schedule_transaction_pool(&self) -> Option<sqlx::PgPool> {
987        None
988    }
989
990    /// Create a new schedule
991    async fn create_schedule(&self, schedule: CreateScheduleRow) -> Result<Uuid, StoreError>;
992
993    /// Get a schedule by ID
994    async fn get_schedule(&self, id: Uuid) -> Result<ScheduleRow, StoreError>;
995
996    /// List schedules with filtering and pagination
997    async fn list_schedules(
998        &self,
999        filter: ScheduleFilter,
1000        pagination: Pagination,
1001    ) -> Result<Vec<ScheduleRow>, StoreError>;
1002
1003    /// Count schedules matching filter
1004    async fn count_schedules(&self, filter: ScheduleFilter) -> Result<u64, StoreError>;
1005
1006    /// Update a schedule
1007    async fn update_schedule(&self, id: Uuid, _update: UpdateSchedule) -> Result<(), StoreError>;
1008
1009    /// Delete a schedule
1010    async fn delete_schedule(&self, id: Uuid) -> Result<(), StoreError>;
1011
1012    /// Claim due schedules for processing (uses SKIP LOCKED for multi-instance)
1013    /// Returns schedules with next_trigger_at <= now
1014    async fn claim_due_schedules(
1015        &self,
1016        scheduler_id: &str,
1017        limit: u32,
1018    ) -> Result<Vec<ScheduleRow>, StoreError>;
1019
1020    /// Update next trigger time after successful trigger
1021    async fn update_next_trigger(&self, id: Uuid, _next: DateTime<Utc>) -> Result<(), StoreError>;
1022
1023    /// Skip a schedule trigger (e.g., max_concurrent reached)
1024    async fn skip_schedule_trigger(&self, id: Uuid) -> Result<(), StoreError>;
1025
1026    /// Release a claimed schedule (e.g., on scheduler shutdown)
1027    async fn release_schedule(&self, id: Uuid) -> Result<(), StoreError>;
1028
1029    /// Create a schedule execution record
1030    async fn create_schedule_execution(
1031        &self,
1032        schedule_id: Uuid,
1033        scheduled_at: DateTime<Utc>,
1034    ) -> Result<Uuid, StoreError>;
1035
1036    /// Get a schedule execution by ID
1037    async fn get_schedule_execution(&self, id: Uuid) -> Result<ScheduleExecutionRow, StoreError>;
1038
1039    /// Complete a schedule execution successfully
1040    async fn complete_schedule_execution(
1041        &self,
1042        execution_id: Uuid,
1043        target_id: Uuid,
1044        is_workflow: bool,
1045    ) -> Result<(), StoreError>;
1046
1047    /// Fail a schedule execution
1048    async fn fail_schedule_execution(
1049        &self,
1050        execution_id: Uuid,
1051        error: &str,
1052    ) -> Result<(), StoreError>;
1053
1054    /// Skip a schedule execution
1055    async fn skip_schedule_execution(
1056        &self,
1057        execution_id: Uuid,
1058        reason: &str,
1059    ) -> Result<(), StoreError>;
1060
1061    /// List executions for a schedule
1062    async fn list_schedule_executions(
1063        &self,
1064        filter: ScheduleExecutionFilter,
1065        pagination: Pagination,
1066    ) -> Result<Vec<ScheduleExecutionRow>, StoreError>;
1067
1068    /// Count running executions for a schedule (for max_concurrent check)
1069    async fn count_running_executions(&self, schedule_id: Uuid) -> Result<u32, StoreError>;
1070
1071    /// Whether the task this schedule last enqueued is still waiting to be
1072    /// claimed. The scheduler skips a trigger while it is, so a schedule
1073    /// nothing claims holds one pending task instead of one per trigger.
1074    async fn last_scheduled_task_pending(&self, schedule_id: Uuid) -> Result<bool, StoreError>;
1075
1076    /// Get schedule statistics
1077    async fn get_schedule_stats(&self, schedule_id: Uuid) -> Result<ScheduleStats, StoreError>;
1078
1079    /// Register a scheduler instance
1080    async fn register_scheduler_instance(
1081        &self,
1082        instance: SchedulerInstanceInfo,
1083    ) -> Result<(), StoreError>;
1084
1085    /// Update scheduler instance heartbeat
1086    async fn heartbeat_scheduler_instance(
1087        &self,
1088        instance_id: &str,
1089        schedules_processed: u64,
1090    ) -> Result<(), StoreError>;
1091
1092    /// List scheduler instances
1093    async fn list_scheduler_instances(&self) -> Result<Vec<SchedulerInstanceInfo>, StoreError>;
1094
1095    /// Deregister a scheduler instance
1096    async fn deregister_scheduler_instance(&self, instance_id: &str) -> Result<(), StoreError>;
1097}
1098
1099/// Read-mostly dashboard and admin queries across workflows and system health.
1100///
1101/// Needed by the HTTP API and operator tooling. Workers and the engine do not
1102/// need it. It requires [`EventLog`] because `get_workflow_events` and `count_workflow_events` have derived
1103/// defaults over `EventLog::load_events`; stores should override them.
1104#[async_trait]
1105pub trait DurableAdmin: EventLog + Send + Sync + 'static {
1106    /// Count active (non-terminal) workflows
1107    async fn count_active_workflows(&self) -> Result<i64, StoreError>;
1108
1109    /// List workflows with filtering and pagination
1110    async fn list_workflows(
1111        &self,
1112        filter: WorkflowFilter,
1113        pagination: Pagination,
1114    ) -> Result<Vec<WorkflowInfoExtended>, StoreError>;
1115
1116    /// Direct lookup of a single workflow by id, returning the same
1117    /// `WorkflowInfoExtended` shape as `list_workflows`. Returns `Ok(None)`
1118    /// when the workflow does not exist.
1119    ///
1120    /// EVE-455: API handlers must use this method instead of scanning the
1121    /// first page of `list_workflows`, which silently returns 404 for any
1122    /// workflow older than the page once a deployment crosses the page
1123    /// limit. Implementations must do a direct id lookup.
1124    async fn get_workflow_extended(
1125        &self,
1126        workflow_id: Uuid,
1127    ) -> Result<Option<WorkflowInfoExtended>, StoreError>;
1128
1129    /// Get workflow events
1130    async fn get_workflow_events(
1131        &self,
1132        workflow_id: Uuid,
1133    ) -> Result<Vec<WorkflowEventInfo>, StoreError> {
1134        // Derived from load_events
1135        let events = self.load_events(workflow_id).await?;
1136        Ok(events
1137            .into_iter()
1138            .map(|(seq, event)| WorkflowEventInfo {
1139                id: seq as i64, // Use sequence as id fallback
1140                workflow_id,
1141                sequence_num: seq,
1142                event_type: event_type_name(&event).to_string(),
1143                event_data: serde_json::to_value(&event).unwrap_or_default(),
1144                created_at: Utc::now(), // Not available in base events
1145            })
1146            .collect())
1147    }
1148
1149    /// Count workflow events without materializing them.
1150    /// Uses SELECT COUNT(*) in PostgreSQL; falls back to load_events().len() by default.
1151    async fn count_workflow_events(&self, workflow_id: Uuid) -> Result<i64, StoreError> {
1152        let events = self.load_events(workflow_id).await?;
1153        Ok(events.len() as i64)
1154    }
1155
1156    /// Get system health summary
1157    async fn get_system_health(&self) -> Result<SystemHealth, StoreError>;
1158}
1159
1160/// Umbrella for a complete durable store.
1161///
1162/// Combines every focused store trait. It is blanket-implemented for any type
1163/// that implements all of them, so `Arc<dyn WorkflowEventStore>` and
1164/// `T: WorkflowEventStore` keep working and the supertrait methods are callable
1165/// through it. Consumers that need only a slice should bound on the focused
1166/// trait instead: a worker needs `TaskQueue + WorkerRegistry`.
1167pub trait WorkflowEventStore:
1168    EventLog
1169    + TaskQueue
1170    + WorkerRegistry
1171    + DeadLetters
1172    + CircuitBreakers
1173    + Schedules
1174    + DurableAdmin
1175    + Send
1176    + Sync
1177    + 'static
1178{
1179}
1180
1181impl<T> WorkflowEventStore for T where
1182    T: EventLog
1183        + TaskQueue
1184        + WorkerRegistry
1185        + DeadLetters
1186        + CircuitBreakers
1187        + Schedules
1188        + DurableAdmin
1189        + Send
1190        + Sync
1191        + 'static
1192{
1193}
1194
1195/// Circuit breaker state
1196#[derive(Debug, Clone)]
1197pub struct CircuitBreakerState {
1198    pub key: String,
1199    pub state: crate::reliability::CircuitState,
1200    pub failure_count: u32,
1201    pub success_count: u32,
1202    pub last_failure_at: Option<chrono::DateTime<chrono::Utc>>,
1203    pub opened_at: Option<chrono::DateTime<chrono::Utc>>,
1204    pub half_open_at: Option<chrono::DateTime<chrono::Utc>>,
1205    pub updated_at: chrono::DateTime<chrono::Utc>,
1206}
1207
1208// =========================================================================
1209// Schedule Types
1210// =========================================================================
1211
1212/// Target type for a schedule
1213#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1214#[serde(rename_all = "snake_case")]
1215pub enum ScheduleTargetType {
1216    Workflow,
1217    Activity,
1218}
1219
1220impl std::fmt::Display for ScheduleTargetType {
1221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1222        match self {
1223            Self::Workflow => write!(f, "workflow"),
1224            Self::Activity => write!(f, "activity"),
1225        }
1226    }
1227}
1228
1229/// Schedule execution status
1230#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1231#[serde(rename_all = "snake_case")]
1232pub enum ScheduleExecutionStatus {
1233    Pending,
1234    Running,
1235    Completed,
1236    Failed,
1237    Skipped,
1238}
1239
1240impl std::fmt::Display for ScheduleExecutionStatus {
1241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1242        match self {
1243            Self::Pending => write!(f, "pending"),
1244            Self::Running => write!(f, "running"),
1245            Self::Completed => write!(f, "completed"),
1246            Self::Failed => write!(f, "failed"),
1247            Self::Skipped => write!(f, "skipped"),
1248        }
1249    }
1250}
1251
1252/// Schedule row from database
1253#[derive(Debug, Clone)]
1254pub struct ScheduleRow {
1255    pub id: Uuid,
1256    pub name: String,
1257    pub description: Option<String>,
1258    pub cron_expression: String,
1259    pub timezone: String,
1260    pub target_type: ScheduleTargetType,
1261    pub target_name: String,
1262    pub target_input: serde_json::Value,
1263    pub enabled: bool,
1264    pub max_concurrent: Option<u32>,
1265    pub catch_up_missed: bool,
1266    pub max_catch_up: Option<u32>,
1267    pub retry_policy: Option<serde_json::Value>,
1268    pub last_triggered_at: Option<DateTime<Utc>>,
1269    pub next_trigger_at: Option<DateTime<Utc>>,
1270    pub claimed_by: Option<String>,
1271    pub claimed_at: Option<DateTime<Utc>>,
1272    pub created_at: DateTime<Utc>,
1273    pub updated_at: DateTime<Utc>,
1274}
1275
1276/// Input for creating a schedule
1277#[derive(Debug, Clone)]
1278pub struct CreateScheduleRow {
1279    pub name: String,
1280    pub description: Option<String>,
1281    pub cron_expression: String,
1282    pub timezone: String,
1283    pub target_type: ScheduleTargetType,
1284    pub target_name: String,
1285    pub target_input: serde_json::Value,
1286    pub enabled: bool,
1287    pub max_concurrent: Option<u32>,
1288    pub catch_up_missed: bool,
1289    pub max_catch_up: Option<u32>,
1290    pub retry_policy: Option<serde_json::Value>,
1291    pub next_trigger_at: Option<DateTime<Utc>>,
1292}
1293
1294/// Input for updating a schedule
1295#[derive(Debug, Clone, Default)]
1296pub struct UpdateSchedule {
1297    pub name: Option<String>,
1298    pub description: UpdateField<String>,
1299    pub cron_expression: Option<String>,
1300    pub timezone: Option<String>,
1301    pub target_type: Option<ScheduleTargetType>,
1302    pub target_name: Option<String>,
1303    pub target_input: Option<serde_json::Value>,
1304    pub enabled: Option<bool>,
1305    pub max_concurrent: UpdateField<u32>,
1306    pub catch_up_missed: Option<bool>,
1307    pub max_catch_up: UpdateField<u32>,
1308    pub retry_policy: UpdateField<serde_json::Value>,
1309    pub next_trigger_at: UpdateField<DateTime<Utc>>,
1310}
1311
1312/// Filter for listing schedules
1313#[derive(Debug, Clone, Default)]
1314pub struct ScheduleFilter {
1315    pub enabled: Option<bool>,
1316    pub target_type: Option<ScheduleTargetType>,
1317}
1318
1319/// Schedule execution row from database
1320#[derive(Debug, Clone)]
1321pub struct ScheduleExecutionRow {
1322    pub id: Uuid,
1323    pub schedule_id: Uuid,
1324    pub scheduled_at: DateTime<Utc>,
1325    pub started_at: DateTime<Utc>,
1326    pub completed_at: Option<DateTime<Utc>>,
1327    pub status: ScheduleExecutionStatus,
1328    pub workflow_id: Option<Uuid>,
1329    pub task_id: Option<Uuid>,
1330    pub error: Option<String>,
1331    pub duration_ms: Option<i32>,
1332    pub created_at: DateTime<Utc>,
1333}
1334
1335/// Schedule statistics
1336#[derive(Debug, Clone, Default)]
1337pub struct ScheduleStats {
1338    pub total_executions: u64,
1339    pub successful_executions: u64,
1340    pub failed_executions: u64,
1341    pub skipped_executions: u64,
1342    pub avg_duration_ms: Option<u64>,
1343    pub last_execution_status: Option<ScheduleExecutionStatus>,
1344}
1345
1346/// Filter for listing schedule executions
1347#[derive(Debug, Clone, Default)]
1348pub struct ScheduleExecutionFilter {
1349    pub schedule_id: Option<Uuid>,
1350    pub status: Option<ScheduleExecutionStatus>,
1351}
1352
1353/// Scheduler instance info
1354#[derive(Debug, Clone)]
1355pub struct SchedulerInstanceInfo {
1356    pub instance_id: String,
1357    pub started_at: DateTime<Utc>,
1358    pub last_heartbeat_at: DateTime<Utc>,
1359    pub schedules_processed: u64,
1360    pub hostname: Option<String>,
1361    pub version: Option<String>,
1362}