grow-graylog 0.2.0

Rust SDK for Graylog Open by Grow Codes
Documentation
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! Conformance handler for the `core` category: `health ping serverVersion close`.

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;

/// The core operations a `core` scenario drives (SPEC §2.4). Implemented for the service
/// client; tests can supply a fake through [`CoreHandler::with_target`].
#[async_trait]
pub trait CoreTarget: Send + Sync {
    /// Unauthenticated liveness check.
    async fn health(&self) -> Result<HealthStatus>;
    /// Authenticated round trip.
    async fn ping(&self) -> Result<Duration>;
    /// Server version string.
    async fn server_version(&self) -> Result<String>;
    /// Releases the target; idempotent.
    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>;

/// Runs `core` scenarios against a fresh client per scenario.
#[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 {
    /// `factory` builds the client under test (called once per scenario).
    pub fn new(factory: impl Fn() -> Result<Client> + Send + Sync + 'static) -> Self {
        Self::with_target(factory)
    }

    /// Like [`CoreHandler::new`] for any [`CoreTarget`] (a fake in tests, a wrapper, …).
    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;
    }
}