redup-bootstrap 0.3.3

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

mod common;

use std::error::Error;
use std::process::ExitCode;
use std::sync::Arc;
use std::time::Duration;

use common::{Behaviour, Events};
use redup_abstractions::Phase;
use redup_bootstrap::{Level, State};

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

#[tokio::test]
async fn points_run_in_build_order_and_stop_in_reverse_order() -> TestResult<()> {
    let events = Events::default();
    let mut instance = Events::assemble(
        &Events::none()?.1,
        &[
            (0, Arc::new(Behaviour::new(&events))),
            (1, Arc::new(Behaviour::new(&events))),
        ],
    )
    .await?;

    instance.start().await?;
    instance.stop().await;

    let events = events.get();
    let starts: Vec<&String> = events
        .iter()
        .filter(|event| event.ends_with(": start"))
        .collect();
    let stops: Vec<&String> = events
        .iter()
        .filter(|event| event.contains(": stop"))
        .collect();
    assert_eq!(starts, ["Alpha: start", "Bravo: start"]);
    assert_eq!(
        stops,
        [
            "Bravo: stop (token cancelled)",
            "Alpha: stop (token cancelled)"
        ]
    );
    assert_eq!(
        events
            .iter()
            .filter(|event| event.starts_with("Bravo: stop"))
            .count(),
        1
    );
    assert_eq!(
        events
            .iter()
            .filter(|event| event.starts_with("Alpha: stop"))
            .count(),
        1
    );
    assert_eq!(instance.state(), State::Stopped);
    Ok(())
}

#[tokio::test(start_paused = true)]
async fn drain_is_parallel_and_bounded_by_one_timeout() -> TestResult<()> {
    let events = Events::default();
    let (_directory, source) =
        Events::source("bootstrap:\n  control:\n    drainTimeout: 300ms\n  rest: ~\n")?;
    let alpha = Arc::new(Behaviour::new(&events).drain_for(Duration::from_millis(100)));
    let bravo = Arc::new(Behaviour::new(&events).drain_for(Duration::from_secs(1)));
    let mut instance = Events::assemble(&source, &[(0, alpha), (1, bravo)]).await?;
    instance.start().await?;

    let before = tokio::time::Instant::now();
    instance.stop().await;
    let elapsed = before.elapsed();

    assert!(elapsed >= Duration::from_millis(300), "elapsed {elapsed:?}");
    assert!(elapsed < Duration::from_secs(1), "elapsed {elapsed:?}");
    let events = events.get();
    assert!(common::has(&events, "Alpha: drained"), "{events:?}");
    assert!(!common::has(&events, "Bravo: drained"), "{events:?}");
    assert_eq!(instance.state(), State::Stopped);
    Ok(())
}

#[tokio::test]
async fn errors_in_drain_and_stop_do_not_break_the_stop() -> TestResult<()> {
    let events = Events::default();
    let alpha = Arc::new(Behaviour::new(&events).failing_drain());
    let bravo = Arc::new(Behaviour::new(&events).failing_stop());
    let mut instance = Events::assemble(&Events::none()?.1, &[(0, alpha), (1, bravo)]).await?;
    instance.start().await?;

    instance.stop().await;

    let events = events.get();
    for point in ["Alpha: drain", "Bravo: drain", "Bravo: stop", "Alpha: stop"] {
        assert!(
            events.iter().any(|event| event.starts_with(point)),
            "{point} missing: {events:?}"
        );
    }
    assert_eq!(instance.state(), State::Stopped);
    Ok(())
}

#[tokio::test]
async fn failed_start_stops_created_modules_and_names_the_module() -> TestResult<()> {
    let events = Events::default();
    let bravo = Arc::new(Behaviour::new(&events).failing_start());
    let mut instance = Events::assemble(
        &Events::none()?.1,
        &[(0, Arc::new(Behaviour::new(&events))), (1, bravo)],
    )
    .await?;

    let error = instance.start().await.err().ok_or("the instance started")?;

    assert_eq!(
        error.to_string(),
        "module 'Bravo' failed to start: start failed"
    );
    let events = events.get();
    assert!(common::has(&events, "Alpha: start"), "{events:?}");
    assert!(!common::has(&events, "Bravo: drain"), "{events:?}");
    let stops: Vec<String> = events
        .iter()
        .filter(|event| event.contains(": stop"))
        .cloned()
        .collect();
    assert_eq!(
        stops,
        [
            "Bravo: stop (token cancelled)",
            "Alpha: stop (token cancelled)"
        ]
    );
    assert_eq!(instance.state(), State::Failed);
    Ok(())
}

#[tokio::test]
async fn panic_in_start_is_reported_as_the_module_error() -> TestResult<()> {
    let events = Events::default();
    let alpha = Arc::new(Behaviour::new(&events).panicking_start());
    let mut instance = Events::assemble(&Events::none()?.1, &[(0, alpha)]).await?;

    let error = instance.start().await.err().ok_or("the instance started")?;

    assert_eq!(
        error.to_string(),
        "module 'Alpha' failed to start: the module panicked: boom"
    );
    assert_eq!(instance.state(), State::Failed);
    Ok(())
}

#[tokio::test]
async fn token_is_live_during_drain_and_cancelled_before_stop() -> TestResult<()> {
    let events = Events::default();
    let alpha = Arc::new(Behaviour::new(&events).drain_for(Duration::from_millis(20)));
    let mut instance = Events::assemble(&Events::none()?.1, &[(0, Arc::clone(&alpha))]).await?;
    instance.start().await?;
    let token = alpha.token().ok_or("the module was not created")?;
    assert!(!token.is_cancelled());

    instance.stop().await;

    assert!(token.is_cancelled());
    let events = events.get();
    assert!(common::has(&events, "Alpha: drain"), "{events:?}");
    assert!(
        common::has(&events, "Alpha: stop (token cancelled)"),
        "{events:?}"
    );
    Ok(())
}

#[tokio::test]
async fn readiness_and_liveness_follow_modules() -> TestResult<()> {
    for (alpha_phase, bravo_phase, readiness, liveness) in [
        (
            Phase::Serving,
            Phase::Serving,
            Phase::Serving,
            Phase::Serving,
        ),
        (
            Phase::Serving,
            Phase::NotServing,
            Phase::NotServing,
            Phase::Serving,
        ),
        (
            Phase::Serving,
            Phase::Starting,
            Phase::Starting,
            Phase::Serving,
        ),
        (Phase::Serving, Phase::Failed, Phase::Failed, Phase::Failed),
    ] {
        let events = Events::default();
        let alpha = Arc::new(Behaviour::new(&events).with_health(alpha_phase));
        let bravo = Arc::new(Behaviour::new(&events).with_health(bravo_phase));
        let mut instance = Events::assemble(&Events::none()?.1, &[(0, alpha), (1, bravo)]).await?;
        assert_eq!(instance.snapshot().readiness(), Phase::NotServing);
        instance.start().await?;

        let snapshot = instance.snapshot();
        assert_eq!(
            snapshot.readiness(),
            readiness,
            "phases {alpha_phase:?} and {bravo_phase:?}"
        );
        assert_eq!(
            snapshot.liveness(),
            liveness,
            "phases {alpha_phase:?} and {bravo_phase:?}"
        );
        instance.stop().await;
    }
    Ok(())
}

#[tokio::test]
async fn module_without_health_counts_as_serving() -> TestResult<()> {
    let events = Events::default();
    let mut instance = Events::assemble(
        &Events::none()?.1,
        &[(0, Arc::new(Behaviour::new(&events)))],
    )
    .await?;
    instance.start().await?;

    let snapshot = instance.snapshot();
    assert_eq!(snapshot.readiness(), Phase::Serving);
    assert_eq!(snapshot.modules()[0].name(), "Alpha");
    assert_eq!(snapshot.modules()[0].phase(), Phase::Serving);
    Ok(())
}

#[tokio::test]
async fn readiness_falls_at_once_when_stopping_while_liveness_stays() -> TestResult<()> {
    let events = Events::default();
    let (_directory, source) = Events::source(
        "bootstrap:\n  control:\n    drainTimeout: 5s\n  rest:\n    host: 127.0.0.1\n    port: 0\n",
    )?;
    let alpha = Arc::new(
        Behaviour::new(&events)
            .with_health(Phase::Serving)
            .drain_for(Duration::from_millis(600)),
    );
    let mut instance = Events::assemble(&source, &[(0, alpha)]).await?;
    instance.start().await?;
    let address = instance.address().ok_or("the listener is not started")?;
    let ready = common::get(address, "/readyz").await?;
    assert_eq!((ready.status, ready.body.as_str()), (200, "Success"));

    let stopping = tokio::spawn(async move { instance.stop().await });
    let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
    loop {
        match common::get(address, "/readyz").await {
            Ok(reply) if reply.status == 503 => {
                assert_eq!(reply.body, "Failed");
                break;
            }
            Ok(_) => {}
            Err(error) if stopping.is_finished() => {
                return Err(
                    format!("readiness did not fall before the listener stopped: {error}").into(),
                );
            }
            Err(_) => {}
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "readiness did not fall in time"
        );
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    let live = common::get(address, "/livez").await?;
    assert_eq!((live.status, live.body.as_str()), (200, "Success"));

    stopping.await?;
    Ok(())
}

#[tokio::test]
async fn fatal_report_stops_the_instance_with_code_one() -> TestResult<()> {
    let events = Events::default();
    let behaviour = Behaviour::new(&events).fatal_on_start("the persistent state is inconsistent");
    let instance = Events::assemble(&Events::none()?.1, &[(0, Arc::new(behaviour))]).await?;
    let mut capture = instance.logging().capture(Level::Fatal);

    let code = instance.run().await;

    assert_eq!(code, ExitCode::from(1));
    let message = tokio::time::timeout(Duration::from_secs(5), capture.next())
        .await
        .map_err(|_| "the fatal record is not written in time")?
        .ok_or("no fatal record")?;
    assert_eq!(message.level(), Level::Fatal);
    assert!(
        message.message().contains("fatal report"),
        "{}",
        message.message()
    );
    assert!(
        !events.get().iter().any(|event| event.contains(": drain")),
        "a fatal report must not drain: {:?}",
        events.get()
    );
    assert!(
        events.get().iter().any(|event| event.contains(": stop")),
        "modules must be stopped: {:?}",
        events.get()
    );
    Ok(())
}