use crate::error::{Error, Result};
use orcher_proto::orcher::v1::{
actor_service_client::ActorServiceClient, ActorHandler, GetStateRequest, GetStateResponse,
HeartbeatRequest, HeartbeatResponse, OperationMode, RegisterHandlersRequest,
RegisterHandlersResponse, SetStateRequest, SetStateResponse, WorkerMetrics, WorkerStatus,
};
use std::collections::HashMap;
use tonic::transport::{Channel, Endpoint};
use tracing::{debug, error, info, warn};
#[derive(Debug, Clone)]
pub struct ActorClient {
client: ActorServiceClient<Channel>,
service_id: String,
registration_id: Option<String>,
}
impl ActorClient {
pub async fn new(server_url: impl Into<String>, service_id: impl Into<String>) -> Result<Self> {
let server_url = server_url.into();
let service_id = service_id.into();
debug!(
server_url = %server_url,
service_id = %service_id,
"Creating actor client"
);
let endpoint = Endpoint::from_shared(server_url.clone()).map_err(|e| {
Error::Worker(crate::error::WorkerError::ConnectionFailed {
url: server_url.clone(),
reason: format!("Invalid server URL: {}", e),
})
})?;
let channel = endpoint.connect().await.map_err(|e| {
Error::Worker(crate::error::WorkerError::ConnectionFailed {
url: server_url.clone(),
reason: format!("Connection failed: {}", e),
})
})?;
let max = orcher_sdk_core::limits::default_max_message_bytes();
let client = ActorServiceClient::new(channel)
.max_decoding_message_size(max)
.max_encoding_message_size(max);
info!(
server_url = %server_url,
service_id = %service_id,
"Actor client connected"
);
Ok(Self {
client,
service_id,
registration_id: None,
})
}
pub async fn register_handlers(
&mut self,
handlers: Vec<ActorHandlerInfo>,
metadata: HashMap<String, String>,
) -> Result<RegisterHandlersResponse> {
info!(
service_id = %self.service_id,
handlers = handlers.len(),
"Registering actor handlers"
);
let proto_handlers: Vec<ActorHandler> = handlers
.into_iter()
.map(|h| ActorHandler {
actor_name: h.actor_name,
operation: h.operation,
mode: h.mode as i32,
metadata: h.metadata,
})
.collect();
let request = RegisterHandlersRequest {
service_id: self.service_id.clone(),
handlers: proto_handlers,
metadata,
};
let response = self
.client
.register_handlers(request)
.await
.map_err(|e| {
error!(
service_id = %self.service_id,
error = %e,
"Failed to register handlers"
);
Error::Worker(crate::error::WorkerError::StartupFailed(format!(
"Failed to register handlers: {}",
e
)))
})?
.into_inner();
if response.success {
self.registration_id = Some(response.registration_id.clone());
info!(
service_id = %self.service_id,
registration_id = %response.registration_id,
handlers_registered = response.handlers_registered,
"Successfully registered handlers"
);
} else {
warn!(
service_id = %self.service_id,
error = %response.error_message,
"Handler registration failed"
);
}
Ok(response)
}
pub async fn heartbeat(
&mut self,
status: WorkerStatus,
metrics: Option<WorkerMetrics>,
) -> Result<HeartbeatResponse> {
let registration_id = self.registration_id.clone().unwrap_or_default();
debug!(
service_id = %self.service_id,
registration_id = %registration_id,
status = ?status,
"Sending heartbeat"
);
let request = HeartbeatRequest {
service_id: self.service_id.clone(),
registration_id,
status: status as i32,
metrics,
};
let response = self
.client
.heartbeat(request)
.await
.map_err(|e| {
error!(
service_id = %self.service_id,
error = %e,
"Heartbeat failed"
);
Error::Worker(crate::error::WorkerError::PollingError(format!(
"Heartbeat failed: {}",
e
)))
})?
.into_inner();
if response.re_register {
warn!(
service_id = %self.service_id,
"Server requested re-registration"
);
self.registration_id = None;
}
debug!(
service_id = %self.service_id,
success = response.success,
re_register = response.re_register,
"Heartbeat response received"
);
Ok(response)
}
pub async fn get_state(
&mut self,
actor_name: impl Into<String>,
key: impl Into<String>,
state_key: impl Into<String>,
execution_id: impl Into<String>,
) -> Result<GetStateResponse> {
let request = GetStateRequest {
actor_name: actor_name.into(),
key: key.into(),
state_key: state_key.into(),
execution_id: execution_id.into(),
};
let response = self
.client
.get_state(request)
.await
.map_err(|e| {
error!(error = %e, "Failed to get state");
Error::Worker(crate::error::WorkerError::PollingError(format!(
"Failed to get state: {}",
e
)))
})?
.into_inner();
Ok(response)
}
pub async fn set_state(
&mut self,
actor_name: impl Into<String>,
key: impl Into<String>,
state_key: impl Into<String>,
value: Vec<u8>,
execution_id: impl Into<String>,
expected_version: Option<String>,
) -> Result<SetStateResponse> {
let request = SetStateRequest {
actor_name: actor_name.into(),
key: key.into(),
state_key: state_key.into(),
value,
execution_id: execution_id.into(),
expected_version: expected_version.unwrap_or_default(),
};
let response = self
.client
.set_state(request)
.await
.map_err(|e| {
error!(error = %e, "Failed to set state");
Error::Worker(crate::error::WorkerError::PollingError(format!(
"Failed to set state: {}",
e
)))
})?
.into_inner();
if !response.success {
warn!(
error = %response.error_message,
"State update failed"
);
}
Ok(response)
}
pub fn service_id(&self) -> &str {
&self.service_id
}
pub fn registration_id(&self) -> Option<&str> {
self.registration_id.as_deref()
}
pub fn is_registered(&self) -> bool {
self.registration_id.is_some()
}
pub async fn poll_operations(
&mut self,
max_operations: u32,
timeout: std::time::Duration,
) -> Result<Vec<orcher_proto::orcher::v1::ActorOperation>> {
debug!(
service_id = %self.service_id,
max_operations = max_operations,
timeout_ms = timeout.as_millis(),
"Polling for actor operations"
);
let request = orcher_proto::orcher::v1::PollActorOperationRequest {
service_id: self.service_id.clone(),
max_operations,
timeout_ms: timeout.as_millis() as u64,
};
let response = self
.client
.poll_actor_operation(request)
.await
.map_err(|e| {
error!(
service_id = %self.service_id,
error = %e,
"Failed to poll for operations"
);
Error::Worker(crate::error::WorkerError::PollingError(format!(
"Failed to poll operations: {}",
e
)))
})?
.into_inner();
if !response.operations.is_empty() {
debug!(
service_id = %self.service_id,
operations = response.operations.len(),
"Received operations from poll"
);
}
Ok(response.operations)
}
pub async fn complete_operation_success(
&mut self,
operation_id: impl Into<String>,
execution_id: impl Into<String>,
result: Vec<u8>,
duration_ms: u64,
) -> Result<()> {
let operation_id = operation_id.into();
let execution_id = execution_id.into();
debug!(
service_id = %self.service_id,
operation_id = %operation_id,
duration_ms = duration_ms,
"Completing operation (success)"
);
let request = orcher_proto::orcher::v1::CompleteActorOperationRequest {
service_id: self.service_id.clone(),
operation_id: operation_id.clone(),
execution_id,
result,
status: orcher_proto::orcher::v1::ExecutionStatus::Success as i32,
error_message: String::new(),
error_code: String::new(),
duration_ms,
};
let response = self
.client
.complete_actor_operation(request)
.await
.map_err(|e| {
error!(
service_id = %self.service_id,
operation_id = %operation_id,
error = %e,
"Failed to complete operation"
);
Error::Worker(crate::error::WorkerError::PollingError(format!(
"Failed to complete operation: {}",
e
)))
})?
.into_inner();
if !response.success {
warn!(
service_id = %self.service_id,
operation_id = %operation_id,
error = %response.error_message,
"Server rejected operation completion"
);
return Err(Error::Worker(crate::error::WorkerError::PollingError(
format!("Failed to complete operation: {}", response.error_message),
)));
}
Ok(())
}
pub async fn complete_operation_error(
&mut self,
operation_id: impl Into<String>,
execution_id: impl Into<String>,
error_message: impl Into<String>,
error_code: impl Into<String>,
duration_ms: u64,
) -> Result<()> {
let operation_id = operation_id.into();
let execution_id = execution_id.into();
let error_message = error_message.into();
let error_code = error_code.into();
warn!(
service_id = %self.service_id,
operation_id = %operation_id,
error_message = %error_message,
error_code = %error_code,
"Completing operation (error)"
);
let request = orcher_proto::orcher::v1::CompleteActorOperationRequest {
service_id: self.service_id.clone(),
operation_id: operation_id.clone(),
execution_id,
result: Vec::new(),
status: orcher_proto::orcher::v1::ExecutionStatus::Error as i32,
error_message,
error_code,
duration_ms,
};
let response = self
.client
.complete_actor_operation(request)
.await
.map_err(|e| {
error!(
service_id = %self.service_id,
operation_id = %operation_id,
error = %e,
"Failed to complete operation"
);
Error::Worker(crate::error::WorkerError::PollingError(format!(
"Failed to complete operation: {}",
e
)))
})?
.into_inner();
if !response.success {
warn!(
service_id = %self.service_id,
operation_id = %operation_id,
error = %response.error_message,
"Server rejected operation completion"
);
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct ActorHandlerInfo {
pub actor_name: String,
pub operation: String,
pub mode: OperationMode,
pub metadata: HashMap<String, String>,
}
impl ActorHandlerInfo {
pub fn new(
actor_name: impl Into<String>,
operation: impl Into<String>,
mode: OperationMode,
) -> Self {
Self {
actor_name: actor_name.into(),
operation: operation.into(),
mode,
metadata: HashMap::new(),
}
}
pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.metadata.insert(key.into(), value.into());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_actor_handler_info_creation() {
let info = ActorHandlerInfo::new("ShoppingCart", "add_item", OperationMode::Exclusive);
assert_eq!(info.actor_name, "ShoppingCart");
assert_eq!(info.operation, "add_item");
assert_eq!(
info.mode as i32,
orcher_proto::orcher::v1::OperationMode::Exclusive as i32
);
assert!(info.metadata.is_empty());
}
#[test]
fn test_actor_handler_info_with_metadata() {
let info = ActorHandlerInfo::new("ShoppingCart", "add_item", OperationMode::Exclusive)
.with_metadata("version", "1.0.0")
.with_metadata("env", "production");
assert_eq!(info.metadata.get("version"), Some(&"1.0.0".to_string()));
assert_eq!(info.metadata.get("env"), Some(&"production".to_string()));
}
}