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"
//! Generic polling helper used by `wait_for_*` functions.

use std::future::Future;
use std::time::Duration;

use tokio::time::Instant;

use super::error::{Error, Result};

/// Polling settings: defaults 30 s timeout, 1 s interval.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PollOptions {
    /// Give up after this long.
    pub timeout: Duration,
    /// Pause between attempts.
    pub interval: Duration,
}

impl Default for PollOptions {
    fn default() -> Self {
        PollOptions {
            timeout: Duration::from_secs(30),
            interval: Duration::from_secs(1),
        }
    }
}

/// Calls `check` until it returns `Ok(Some(value))`.
///
/// `Ok(None)` and retryable errors keep polling; other errors are returned at once. When the
/// timeout passes, a `TIMEOUT` error named after `operation` is returned (with the last
/// retryable error as its source). The check always runs at least once.
pub async fn poll_until<T, F, Fut>(operation: &str, opts: PollOptions, mut check: F) -> Result<T>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<Option<T>>>,
{
    let deadline = Instant::now() + opts.timeout;
    let mut last_err: Option<Error> = None;
    loop {
        match check().await {
            Ok(Some(value)) => return Ok(value),
            Ok(None) => {}
            Err(err) if err.is_retryable() => last_err = Some(err),
            Err(err) => return Err(err),
        }
        let now = Instant::now();
        if now >= deadline {
            let err = Error::timeout(format!(
                "{operation}: condition not met within {} ms",
                opts.timeout.as_millis()
            ));
            return Err(match last_err {
                Some(cause) => err.with_source(cause),
                None => err,
            });
        }
        tokio::time::sleep(opts.interval.min(deadline - now)).await;
    }
}