use crate::error::{Error, Result};
use moka::future::Cache;
use serde::{de::DeserializeOwned, Serialize};
use std::sync::Arc;
use std::time::Duration;
use super::mock::MockStateBackend;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ActorStateClientConfig {
pub enable_cache: bool,
pub cache_ttl: Duration,
pub max_cache_size: u64,
}
impl Default for ActorStateClientConfig {
fn default() -> Self {
Self {
enable_cache: true,
cache_ttl: Duration::from_secs(60),
max_cache_size: 1_000,
}
}
}
pub struct ActorStateClient {
backend: StateBackend,
config: ActorStateClientConfig,
cache: Option<Arc<Cache<String, Vec<u8>>>>,
}
enum StateBackend {
Mock(MockStateBackend),
#[cfg(feature = "auto-register")]
Host(orcher_sdk_core::Host),
}
impl ActorStateClient {
pub fn new_mock() -> Self {
Self {
backend: StateBackend::Mock(MockStateBackend::new()),
config: ActorStateClientConfig::default(),
cache: None, }
}
#[cfg(feature = "auto-register")]
pub(crate) fn from_host(host: orcher_sdk_core::Host) -> Self {
let config = ActorStateClientConfig::default();
let cache = config.enable_cache.then(|| {
Arc::new(
Cache::builder()
.max_capacity(config.max_cache_size)
.time_to_live(config.cache_ttl)
.build(),
)
});
Self {
backend: StateBackend::Host(host),
config,
cache,
}
}
pub fn new_mock_with_backend(backend: MockStateBackend) -> Self {
Self {
backend: StateBackend::Mock(backend),
config: ActorStateClientConfig::default(),
cache: None,
}
}
pub async fn get_state<T>(
&self,
actor_name: &str,
key: &str,
state_key: &str,
_execution_id: &str,
) -> Result<Option<T>>
where
T: DeserializeOwned,
{
let cache_key = format!("{}:{}:{}", actor_name, key, state_key);
if let Some(cache) = &self.cache {
if let Some(cached_bytes) = cache.get(&cache_key).await {
return match serde_json::from_slice(&cached_bytes) {
Ok(value) => Ok(Some(value)),
Err(e) => Err(Error::Serialization(format!(
"Failed to deserialize cached state: {}",
e
))),
};
}
}
let value_bytes = match &self.backend {
StateBackend::Mock(mock) => {
let storage_key = format!("actor:{}:{}:{}", actor_name, key, state_key);
match mock.get(&storage_key).await {
Some(bytes) => bytes,
None => return Ok(None),
}
}
#[cfg(feature = "auto-register")]
StateBackend::Host(host) => {
let scope = orcher_sdk_core::StateScope::new(actor_name, key, _execution_id);
match host
.get_actor_state(&scope, state_key)
.await
.map_err(|e| Error::Network(format!("GetState failed: {e}")))?
{
Some(stored) if !stored.value.is_empty() => stored.value,
_ => return Ok(None),
}
}
};
if let Some(cache) = &self.cache {
cache.insert(cache_key, value_bytes.clone()).await;
}
serde_json::from_slice(&value_bytes)
.map(Some)
.map_err(|e| Error::Serialization(format!("Failed to deserialize state: {}", e)))
}
pub async fn get_state_with_version<T>(
&self,
actor_name: &str,
key: &str,
state_key: &str,
_execution_id: &str,
) -> Result<(Option<T>, String)>
where
T: DeserializeOwned,
{
match &self.backend {
StateBackend::Mock(mock) => {
let storage_key = format!("actor:{}:{}:{}", actor_name, key, state_key);
match mock.get(&storage_key).await {
Some(bytes) => {
let value = serde_json::from_slice(&bytes).map_err(|e| {
Error::Serialization(format!("Failed to deserialize state: {}", e))
})?;
Ok((Some(value), String::new()))
}
None => Ok((None, String::new())),
}
}
#[cfg(feature = "auto-register")]
StateBackend::Host(host) => {
let scope = orcher_sdk_core::StateScope::new(actor_name, key, _execution_id);
match host
.get_actor_state(&scope, state_key)
.await
.map_err(|e| Error::Network(format!("GetState failed: {e}")))?
{
Some(stored) if !stored.value.is_empty() => {
let value = serde_json::from_slice(&stored.value).map_err(|e| {
Error::Serialization(format!("Failed to deserialize state: {}", e))
})?;
Ok((Some(value), stored.version))
}
Some(stored) => Ok((None, stored.version)),
None => Ok((None, String::new())),
}
}
}
}
pub async fn set_state<T>(
&self,
actor_name: &str,
key: &str,
state_key: &str,
value: &T,
_execution_id: &str,
_expected_version: Option<&str>,
) -> Result<()>
where
T: Serialize,
{
let cache_key = format!("{}:{}:{}", actor_name, key, state_key);
let value_bytes = serde_json::to_vec(value)
.map_err(|e| Error::Serialization(format!("Failed to serialize state: {}", e)))?;
match &self.backend {
StateBackend::Mock(mock) => {
let storage_key = format!("actor:{}:{}:{}", actor_name, key, state_key);
mock.set(&storage_key, value_bytes.clone()).await;
}
#[cfg(feature = "auto-register")]
StateBackend::Host(host) => {
let scope = orcher_sdk_core::StateScope::new(actor_name, key, _execution_id);
host.set_actor_state(&scope, state_key, value_bytes.clone(), _expected_version)
.await
.map_err(|e| Error::Actor(format!("Failed to set state: {e}")))?;
}
}
if let Some(cache) = &self.cache {
cache.insert(cache_key, value_bytes).await;
}
Ok(())
}
pub async fn delete_state(
&self,
actor_name: &str,
key: &str,
state_key: &str,
_execution_id: &str,
) -> Result<bool> {
let cache_key = format!("{}:{}:{}", actor_name, key, state_key);
if let Some(cache) = &self.cache {
cache.remove(&cache_key).await;
}
match &self.backend {
StateBackend::Mock(mock) => {
let storage_key = format!("actor:{}:{}:{}", actor_name, key, state_key);
Ok(mock.delete(&storage_key).await)
}
#[cfg(feature = "auto-register")]
StateBackend::Host(host) => {
let scope = orcher_sdk_core::StateScope::new(actor_name, key, _execution_id);
host.delete_actor_state(&scope, state_key)
.await
.map_err(|e| Error::Network(format!("DeleteState failed: {e}")))
}
}
}
pub async fn list_state_keys(
&self,
actor_name: &str,
key: &str,
_execution_id: &str,
prefix: Option<&str>,
) -> Result<Vec<String>> {
match &self.backend {
StateBackend::Mock(mock) => {
let prefix_str = format!("actor:{}:{}:{}", actor_name, key, prefix.unwrap_or(""));
let keys = mock.list_keys(&prefix_str).await;
let state_keys = keys
.into_iter()
.filter_map(|k| {
k.strip_prefix(&format!("actor:{}:{}:", actor_name, key))
.map(|s| s.to_string())
})
.collect();
Ok(state_keys)
}
#[cfg(feature = "auto-register")]
StateBackend::Host(host) => {
let scope = orcher_sdk_core::StateScope::new(actor_name, key, _execution_id);
host.actor_state_keys(&scope, prefix.unwrap_or_default())
.await
.map_err(|e| Error::Network(format!("ListStateKeys failed: {e}")))
}
}
}
pub async fn clear_cache(&self) {
if let Some(cache) = &self.cache {
cache.invalidate_all();
}
}
pub async fn invalidate_cache(&self, actor_name: &str, key: &str, state_key: &str) {
if let Some(cache) = &self.cache {
let cache_key = format!("{}:{}:{}", actor_name, key, state_key);
cache.remove(&cache_key).await;
}
}
}
impl Clone for ActorStateClient {
fn clone(&self) -> Self {
Self {
backend: match &self.backend {
StateBackend::Mock(mock) => StateBackend::Mock(mock.clone()),
#[cfg(feature = "auto-register")]
StateBackend::Host(host) => StateBackend::Host(host.clone()),
},
config: self.config.clone(),
cache: self.cache.clone(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_default() {
let config = ActorStateClientConfig::default();
assert!(config.enable_cache);
}
#[test]
fn test_cache_key_format() {
let cache_key = format!("{}:{}:{}", "ShoppingCart", "user-123", "cart");
assert_eq!(cache_key, "ShoppingCart:user-123:cart");
}
#[tokio::test]
async fn test_client_config() {
let config = ActorStateClientConfig {
enable_cache: false,
cache_ttl: Duration::from_secs(5),
..Default::default()
};
assert_eq!(config.cache_ttl, Duration::from_secs(5));
assert!(!config.enable_cache);
}
}