use std::time::Duration;
use serde_json::{json, Value};
use crate::client::AgentClient;
use crate::error::Result;
use super::result::{AgentResult, AgentStatus};
use super::stream::AgentStream;
const POLL_INTERVAL: Duration = Duration::from_millis(500);
#[derive(Clone)]
pub struct AgentHandle {
client: AgentClient,
execution_id: String,
}
impl AgentHandle {
pub fn new(client: AgentClient, execution_id: impl Into<String>) -> Self {
Self {
client,
execution_id: execution_id.into(),
}
}
#[must_use]
pub fn execution_id(&self) -> &str {
&self.execution_id
}
pub async fn status(&self) -> Result<AgentStatus> {
let value = self.client.get_status(&self.execution_id).await?;
Ok(AgentStatus::from_response(
self.execution_id.clone(),
&value,
))
}
pub async fn join(&self) -> Result<AgentResult> {
loop {
let status = self.status().await?;
if status.is_terminal() {
return Ok(AgentResult::from_status(status));
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
pub async fn stream(&self) -> Result<AgentStream> {
let response = self.client.stream(&self.execution_id).await?;
Ok(AgentStream::new(response))
}
pub async fn respond(&self, body: &Value) -> Result<()> {
self.client.respond(&self.execution_id, body).await
}
pub async fn approve(&self) -> Result<()> {
self.respond(&approve_payload()).await
}
pub async fn reject(&self, reason: &str) -> Result<()> {
self.respond(&reject_payload(reason)).await
}
pub async fn stop(&self) -> Result<()> {
self.client.stop(&self.execution_id).await
}
}
fn approve_payload() -> Value {
json!({ "approved": true })
}
fn reject_payload(reason: &str) -> Value {
json!({ "approved": false, "reason": reason })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::ApiClient;
use crate::Configuration;
fn test_client() -> AgentClient {
let config = Configuration::new("http://localhost:8080/api");
let api = ApiClient::new(config).unwrap();
AgentClient::new(api)
}
#[test]
fn agent_handle_exposes_its_execution_id() {
let handle = AgentHandle::new(test_client(), "exec-123");
assert_eq!(handle.execution_id(), "exec-123");
}
#[test]
fn approve_payload_has_expected_shape() {
let payload = approve_payload();
assert_eq!(payload, json!({ "approved": true }));
}
#[test]
fn reject_payload_has_expected_shape() {
let payload = reject_payload("needs a manager");
assert_eq!(
payload,
json!({ "approved": false, "reason": "needs a manager" })
);
}
#[test]
fn reject_payload_carries_the_exact_reason_given() {
let payload = reject_payload("amount over threshold");
assert_eq!(payload["reason"], "amount over threshold");
}
}