use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use serde_json::{json, Value};
use super::runner::{CategoryHandler, Scenario, ScenarioSession, StepOutput, Vars};
use crate::core::{Error, HealthStatus, Result};
use crate::GraylogClient as Client;
#[async_trait]
pub trait CoreTarget: Send + Sync {
async fn health(&self) -> Result<HealthStatus>;
async fn ping(&self) -> Result<Duration>;
async fn server_version(&self) -> Result<String>;
async fn close(&self);
}
#[async_trait]
impl CoreTarget for Client {
async fn health(&self) -> Result<HealthStatus> {
Client::health(self).await
}
async fn ping(&self) -> Result<Duration> {
Client::ping(self).await
}
async fn server_version(&self) -> Result<String> {
Client::server_version(self).await
}
async fn close(&self) {
Client::close(self).await
}
}
type Factory = Arc<dyn Fn() -> Result<Box<dyn CoreTarget>> + Send + Sync>;
#[derive(Clone)]
pub struct CoreHandler {
factory: Factory,
}
impl std::fmt::Debug for CoreHandler {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("CoreHandler")
}
}
impl CoreHandler {
pub fn new(factory: impl Fn() -> Result<Client> + Send + Sync + 'static) -> Self {
Self::with_target(factory)
}
pub fn with_target<T, F>(factory: F) -> Self
where
T: CoreTarget + 'static,
F: Fn() -> Result<T> + Send + Sync + 'static,
{
CoreHandler {
factory: Arc::new(move || Ok(Box::new(factory()?) as Box<dyn CoreTarget>)),
}
}
}
struct CoreSession {
client: Box<dyn CoreTarget>,
}
#[async_trait]
impl CategoryHandler for CoreHandler {
fn category(&self) -> &str {
"core"
}
async fn open(&self, _scenario: &Scenario, _vars: &Vars) -> Result<Box<dyn ScenarioSession>> {
Ok(Box::new(CoreSession {
client: (self.factory)()?,
}))
}
}
#[async_trait]
impl ScenarioSession for CoreSession {
async fn run(&mut self, op: &str, _args: &Value, _vars: &Vars) -> Result<StepOutput> {
match op {
"health" => {
let status = self.client.health().await?;
Ok(StepOutput::json(serde_json::to_value(&status)?))
}
"ping" => {
let latency = self.client.ping().await?;
Ok(StepOutput::json(json!(latency.as_secs_f64() * 1000.0)))
}
"serverVersion" => Ok(StepOutput::json(Value::String(
self.client.server_version().await?,
))),
"close" => {
self.client.close().await;
Ok(StepOutput::none())
}
other => Err(Error::unsupported(format!("core: unknown op {other:?}"))),
}
}
async fn close(&mut self) {
self.client.close().await;
}
}