use crate::error::{Error, Result};
use moka::future::Cache;
use orcher_proto::orcher::v1::{
actor_service_client::ActorServiceClient, DeleteStateRequest, GetStateRequest,
ListStateKeysRequest, SetStateRequest,
};
use serde::{de::DeserializeOwned, Serialize};
use std::sync::Arc;
use std::time::Duration;
use tonic::transport::{Channel, Endpoint};
use super::mock::MockStateBackend;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ActorStateClientConfig {
pub server_url: String,
pub timeout: Duration,
pub max_retries: u32,
pub enable_cache: bool,
pub cache_ttl: Duration,
pub max_cache_size: u64,
pub auth_token: Option<String>,
}
impl Default for ActorStateClientConfig {
fn default() -> Self {
Self {
server_url: "http://localhost:8080".to_string(),
timeout: Duration::from_secs(10),
max_retries: 3,
enable_cache: true,
cache_ttl: Duration::from_secs(60),
max_cache_size: 1_000,
auth_token: None,
}
}
}
pub struct ActorStateClient {
backend: StateBackend,
config: ActorStateClientConfig,
cache: Option<Arc<Cache<String, Vec<u8>>>>,
}
enum StateBackend {
Grpc(ActorServiceClient<Channel>),
Mock(MockStateBackend),
}
impl ActorStateClient {
pub async fn new(config: ActorStateClientConfig) -> Result<Self> {
let endpoint = Endpoint::from_shared(config.server_url.clone())
.map_err(|e| Error::Network(format!("Invalid server URL: {}", e)))?
.timeout(config.timeout)
.connect_timeout(Duration::from_secs(5));
let channel = endpoint
.connect()
.await
.map_err(|e| Error::Network(format!("Failed to connect to server: {}", e)))?;
let max = orcher_sdk_core::limits::default_max_message_bytes();
let grpc_client = ActorServiceClient::new(channel)
.max_decoding_message_size(max)
.max_encoding_message_size(max);
let cache = if config.enable_cache {
Some(Arc::new(
Cache::builder()
.max_capacity(config.max_cache_size)
.time_to_live(config.cache_ttl)
.build(),
))
} else {
None
};
Ok(Self {
backend: StateBackend::Grpc(grpc_client),
config,
cache,
})
}
pub fn new_mock() -> Self {
Self {
backend: StateBackend::Mock(MockStateBackend::new()),
config: ActorStateClientConfig::default(),
cache: None, }
}
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::Grpc(client) => {
let request = tonic::Request::new(GetStateRequest {
actor_name: actor_name.to_string(),
key: key.to_string(),
state_key: state_key.to_string(),
execution_id: execution_id.to_string(),
});
let mut grpc_client = client.clone();
let response = grpc_client
.get_state(request)
.await
.map_err(|e| Error::Network(format!("gRPC GetState failed: {}", e)))?;
let state_response = response.into_inner();
if !state_response.exists || state_response.value.is_empty() {
return Ok(None);
}
state_response.value
}
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),
}
}
};
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::Grpc(client) => {
let request = tonic::Request::new(GetStateRequest {
actor_name: actor_name.to_string(),
key: key.to_string(),
state_key: state_key.to_string(),
execution_id: execution_id.to_string(),
});
let mut grpc_client = client.clone();
let response = grpc_client
.get_state(request)
.await
.map_err(|e| Error::Network(format!("gRPC GetState failed: {}", e)))?;
let state_response = response.into_inner();
let version = state_response.version.clone();
if !state_response.exists || state_response.value.is_empty() {
return Ok((None, version));
}
let value = serde_json::from_slice(&state_response.value).map_err(|e| {
Error::Serialization(format!("Failed to deserialize state: {}", e))
})?;
Ok((Some(value), version))
}
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())),
}
}
}
}
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::Grpc(client) => {
let request = tonic::Request::new(SetStateRequest {
actor_name: actor_name.to_string(),
key: key.to_string(),
state_key: state_key.to_string(),
value: value_bytes.clone(),
execution_id: execution_id.to_string(),
expected_version: expected_version.unwrap_or("").to_string(),
});
let mut grpc_client = client.clone();
let response = grpc_client
.set_state(request)
.await
.map_err(|e| Error::Network(format!("gRPC SetState failed: {}", e)))?;
let set_response = response.into_inner();
if !set_response.success {
return Err(Error::Actor(format!(
"Failed to set state: {}",
set_response.error_message
)));
}
}
StateBackend::Mock(mock) => {
let storage_key = format!("actor:{}:{}:{}", actor_name, key, state_key);
mock.set(&storage_key, value_bytes.clone()).await;
}
}
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::Grpc(client) => {
let request = tonic::Request::new(DeleteStateRequest {
actor_name: actor_name.to_string(),
key: key.to_string(),
state_key: state_key.to_string(),
execution_id: execution_id.to_string(),
});
let mut grpc_client = client.clone();
let response = grpc_client
.delete_state(request)
.await
.map_err(|e| Error::Network(format!("gRPC DeleteState failed: {}", e)))?;
let delete_response = response.into_inner();
Ok(delete_response.existed)
}
StateBackend::Mock(mock) => {
let storage_key = format!("actor:{}:{}:{}", actor_name, key, state_key);
Ok(mock.delete(&storage_key).await)
}
}
}
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::Grpc(client) => {
let request = tonic::Request::new(ListStateKeysRequest {
actor_name: actor_name.to_string(),
key: key.to_string(),
execution_id: execution_id.to_string(),
prefix: prefix.unwrap_or_default().to_string(),
});
let mut grpc_client = client.clone();
let response = grpc_client
.list_state_keys(request)
.await
.map_err(|e| Error::Network(format!("gRPC ListStateKeys failed: {}", e)))?;
let list_response = response.into_inner();
Ok(list_response.keys)
}
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)
}
}
}
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::Grpc(client) => StateBackend::Grpc(client.clone()),
StateBackend::Mock(mock) => StateBackend::Mock(mock.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_eq!(config.server_url, "http://localhost:8080");
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 {
server_url: "http://localhost:9999".to_string(),
timeout: Duration::from_secs(5),
enable_cache: false,
..Default::default()
};
assert_eq!(config.server_url, "http://localhost:9999");
assert!(!config.enable_cache);
}
}