use crate::models::{Checkpoint, WorkflowState};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum StateStoreError {
#[error("Database error: {0}")]
Database(String),
#[error("Serialization error: {0}")]
Serialization(String),
#[error("Not found: {0}")]
NotFound(String),
#[error("Invalid state: {0}")]
InvalidState(String),
#[error("Connection error: {0}")]
Connection(String),
#[error("Configuration error: {0}")]
Configuration(String),
#[error("Other error: {0}")]
Other(String),
}
impl From<sqlx::Error> for StateStoreError {
fn from(err: sqlx::Error) -> Self {
match err {
sqlx::Error::RowNotFound => StateStoreError::NotFound("Row not found".to_string()),
sqlx::Error::PoolTimedOut => StateStoreError::Connection("Connection pool timed out".to_string()),
_ => StateStoreError::Database(err.to_string()),
}
}
}
impl From<serde_json::Error> for StateStoreError {
fn from(err: serde_json::Error) -> Self {
StateStoreError::Serialization(err.to_string())
}
}
pub type StateStoreResult<T> = Result<T, StateStoreError>;
#[async_trait]
pub trait StateStore: Send + Sync {
async fn save_workflow_state(&self, state: &WorkflowState) -> StateStoreResult<()>;
async fn load_workflow_state(&self, id: &uuid::Uuid) -> StateStoreResult<WorkflowState>;
async fn load_workflow_state_by_workflow_id(&self, workflow_id: &str) -> StateStoreResult<WorkflowState>;
async fn list_active_workflows(&self) -> StateStoreResult<Vec<WorkflowState>>;
async fn create_checkpoint(&self, checkpoint: &Checkpoint) -> StateStoreResult<()>;
async fn get_latest_checkpoint(&self, workflow_state_id: &uuid::Uuid) -> StateStoreResult<Option<Checkpoint>>;
async fn restore_from_checkpoint(&self, checkpoint_id: &uuid::Uuid) -> StateStoreResult<WorkflowState>;
async fn delete_old_states(&self, older_than: DateTime<Utc>) -> StateStoreResult<u64>;
async fn cleanup_old_checkpoints(&self, workflow_state_id: &uuid::Uuid, keep_count: usize) -> StateStoreResult<u64>;
async fn health_check(&self) -> StateStoreResult<()>;
}