redup-bootstrap 0.3.3

Ядро платформы: инстанс службы, модули, жизненный цикл, здоровье и телеметрия.
Documentation
//! Сценарные тесты зависимостей на уровне инстанса: матрица «режим наблюдения × инициализация».

mod common;

use std::error::Error;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;

use common::Events;
use redup_abstractions::{DependencyRole, Phase};
use redup_bootstrap::{
    Builder, Context, CustomProbe, Init, Instance, Module, ModuleError, Service, async_trait,
};
use redup_config::Config;

type TestResult<T> = std::result::Result<T, Box<dyn Error>>;

/// Настройки модуля, который полагается на соседа: секция без полей.
#[derive(Debug, Clone, Default, PartialEq, Config)]
struct WatcherSettings {}

/// Что тест сообщает модулю о соседе: доступен ли он и разрешена ли инициализация.
struct Neighbour {
    available: AtomicBool,
    allowed: AtomicBool,
    initializations: AtomicUsize,
    checks: AtomicUsize,
}

impl Neighbour {
    fn new(available: bool, allowed: bool) -> Self {
        Self {
            available: AtomicBool::new(available),
            allowed: AtomicBool::new(allowed),
            initializations: AtomicUsize::new(0),
            checks: AtomicUsize::new(0),
        }
    }

    fn checks(&self) -> usize {
        self.checks.load(Ordering::SeqCst)
    }

    fn initializations(&self) -> usize {
        self.initializations.load(Ordering::SeqCst)
    }
}

/// Модуль с критической зависимостью: зонд читает признак доступности, инициализация ждёт разрешения.
struct Watcher;

#[async_trait]
impl Module for Watcher {
    const NAME: &'static str = "Watcher";
    type Config = WatcherSettings;
    type Args = Arc<Neighbour>;

    async fn create(
        _: WatcherSettings,
        neighbour: Arc<Neighbour>,
        ctx: &mut Context<'_>,
    ) -> Result<Self, ModuleError> {
        let health = ctx.health();
        let probe = Arc::clone(&neighbour);
        let init = Arc::clone(&neighbour);
        let dependency = ctx
            .dependency("neighbour")
            .probe(CustomProbe::new(move |attempt| {
                let probe = Arc::clone(&probe);
                async move {
                    probe.checks.fetch_add(1, Ordering::SeqCst);
                    tokio::select! {
                        _ = attempt.token().cancelled() => Err("the attempt is cancelled".into()),
                        _ = tokio::task::yield_now() => Ok(probe.available.load(Ordering::SeqCst)),
                    }
                }
            }))
            .init(Init::once(move || {
                let init = Arc::clone(&init);
                async move {
                    init.initializations.fetch_add(1, Ordering::SeqCst);
                    while !init.allowed.load(Ordering::SeqCst) {
                        tokio::time::sleep(Duration::from_millis(10)).await;
                    }
                    Ok(())
                }
            }))
            .start()?;
        health.track(&dependency, DependencyRole::Critical);
        health.set(Phase::Serving);
        Ok(Self)
    }
}

/// Даёт фоновым задачам время отреагировать: 200 мс виртуального времени.
async fn settle() {
    for _ in 0..8 {
        tokio::time::advance(Duration::from_millis(25)).await;
        tokio::task::yield_now().await;
    }
}

/// Запущенный инстанс с одним модулем `Watcher`; режим наблюдения — `mode` или умолчание.
async fn watching(mode: Option<&str>, neighbour: Arc<Neighbour>) -> TestResult<Instance> {
    let mode = mode.map_or(String::new(), |mode| format!("    mode: {mode}\n"));
    let yaml =
        format!("bootstrap:\n  rest: ~\n  watchers:\n{mode}    pullDelay: 50ms\nwatcher: {{}}\n");
    let (_directory, source) = Events::source(&yaml)?;
    let mut builder = Builder::new(&source, Service::new("trial", "0.0.0"))?;
    builder.add::<Watcher>(neighbour).await?;
    let mut instance = builder.build();
    instance.start().await?;
    Ok(instance)
}

#[tokio::test(start_paused = true)]
async fn full_follows_the_neighbour_the_whole_time() -> TestResult<()> {
    let neighbour = Arc::new(Neighbour::new(false, false));
    let instance = watching(Some("full"), Arc::clone(&neighbour)).await?;
    settle().await;
    assert_eq!(instance.snapshot().readiness(), Phase::Starting);

    neighbour.allowed.store(true, Ordering::SeqCst);
    settle().await;
    assert_eq!(
        instance.snapshot().readiness(),
        Phase::Starting,
        "the neighbour is down"
    );

    neighbour.available.store(true, Ordering::SeqCst);
    settle().await;
    assert_eq!(instance.snapshot().readiness(), Phase::Serving);

    neighbour.available.store(false, Ordering::SeqCst);
    settle().await;
    assert_eq!(instance.snapshot().readiness(), Phase::NotServing);

    neighbour.available.store(true, Ordering::SeqCst);
    settle().await;
    assert_eq!(instance.snapshot().readiness(), Phase::Serving);
    assert_eq!(neighbour.initializations(), 1);
    Ok(())
}

#[tokio::test(start_paused = true)]
async fn startup_stops_after_the_first_success() -> TestResult<()> {
    let neighbour = Arc::new(Neighbour::new(false, true));
    let instance = watching(Some("startup"), Arc::clone(&neighbour)).await?;
    settle().await;
    assert_eq!(instance.snapshot().readiness(), Phase::Starting);

    neighbour.available.store(true, Ordering::SeqCst);
    settle().await;
    assert_eq!(instance.snapshot().readiness(), Phase::Serving);
    let checks = neighbour.checks();

    neighbour.available.store(false, Ordering::SeqCst);
    settle().await;
    assert_eq!(
        instance.snapshot().readiness(),
        Phase::Serving,
        "the stopped probe no longer gates"
    );
    assert!(neighbour.checks() - checks <= 1, "the probe keeps polling");
    Ok(())
}

#[tokio::test(start_paused = true)]
async fn startup_then_observe_only_reports_after_the_first_success() -> TestResult<()> {
    let neighbour = Arc::new(Neighbour::new(false, true));
    let instance = watching(Some("startupThenObserve"), Arc::clone(&neighbour)).await?;
    settle().await;
    assert_eq!(instance.snapshot().readiness(), Phase::Starting);

    neighbour.available.store(true, Ordering::SeqCst);
    settle().await;
    assert_eq!(instance.snapshot().readiness(), Phase::Serving);

    neighbour.available.store(false, Ordering::SeqCst);
    settle().await;
    assert_eq!(
        instance.snapshot().readiness(),
        Phase::Serving,
        "an observation does not gate"
    );
    Ok(())
}

#[tokio::test(start_paused = true)]
async fn placebo_runs_the_initialization_and_ignores_the_neighbour() -> TestResult<()> {
    let neighbour = Arc::new(Neighbour::new(false, false));
    let instance = watching(Some("placebo"), Arc::clone(&neighbour)).await?;
    settle().await;
    assert_eq!(
        instance.snapshot().readiness(),
        Phase::Starting,
        "the initialization gates"
    );

    neighbour.allowed.store(true, Ordering::SeqCst);
    settle().await;
    assert_eq!(instance.snapshot().readiness(), Phase::Serving);
    assert_eq!(neighbour.checks(), 0, "the probe is stubbed");
    assert_eq!(neighbour.initializations(), 1);
    Ok(())
}

#[tokio::test(start_paused = true)]
async fn once_probes_once_and_never_gates() -> TestResult<()> {
    let neighbour = Arc::new(Neighbour::new(false, false));
    let instance = watching(Some("once"), Arc::clone(&neighbour)).await?;
    settle().await;
    assert_eq!(
        instance.snapshot().readiness(),
        Phase::Starting,
        "the initialization gates"
    );

    neighbour.allowed.store(true, Ordering::SeqCst);
    settle().await;
    assert_eq!(
        instance.snapshot().readiness(),
        Phase::Serving,
        "a failed probe does not gate"
    );
    assert_eq!(neighbour.checks(), 1, "the probe runs once");

    neighbour.available.store(true, Ordering::SeqCst);
    settle().await;
    assert_eq!(neighbour.checks(), 1, "the probe is released");
    Ok(())
}

#[tokio::test(start_paused = true)]
async fn once_is_the_default_mode() -> TestResult<()> {
    let neighbour = Arc::new(Neighbour::new(false, true));
    let instance = watching(None, Arc::clone(&neighbour)).await?;
    settle().await;

    assert_eq!(instance.snapshot().readiness(), Phase::Serving);
    assert_eq!(neighbour.checks(), 1, "the probe runs once by default");
    Ok(())
}