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"
//! Close callbacks run by `Client::close` (flush batch processors, stop watchers, …).

use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;

use futures::future::BoxFuture;

type CloseFn = Box<dyn FnOnce() -> BoxFuture<'static, ()> + Send>;

/// A set of async close callbacks that run once, in registration order.
#[derive(Default)]
pub struct CloseGroup {
    closed: AtomicBool,
    callbacks: Mutex<Vec<CloseFn>>,
}

impl CloseGroup {
    /// An empty group.
    pub fn new() -> Self {
        CloseGroup::default()
    }

    /// Registers a callback. After [`CloseGroup::close`] ran, the callback runs immediately
    /// in the background (when a tokio runtime is present) so late registrations still stop.
    pub fn register<F>(&self, f: F)
    where
        F: FnOnce() -> BoxFuture<'static, ()> + Send + 'static,
    {
        if self.is_closed() {
            if let Ok(handle) = tokio::runtime::Handle::try_current() {
                handle.spawn(f());
            }
            return;
        }
        self.lock().push(Box::new(f));
    }

    /// Whether `close` has been called.
    pub fn is_closed(&self) -> bool {
        self.closed.load(Ordering::SeqCst)
    }

    /// Runs every callback once; later calls are no-ops.
    pub async fn close(&self) {
        if self.closed.swap(true, Ordering::SeqCst) {
            return;
        }
        let callbacks = std::mem::take(&mut *self.lock());
        for cb in callbacks {
            cb().await;
        }
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<CloseFn>> {
        self.callbacks.lock().unwrap_or_else(|e| e.into_inner())
    }
}

impl fmt::Debug for CloseGroup {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CloseGroup")
            .field("closed", &self.is_closed())
            .field("callbacks", &self.lock().len())
            .finish()
    }
}