redup-bootstrap 0.2.0

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

mod common;

use std::error::Error;
use std::sync::Arc;

use common::{Alpha, Behaviour, Events, locked};
use redup_bootstrap::{Builder, Context, Link, Module, ModuleError, Service, async_trait};
use redup_config::Config;

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

/// Потребитель поставщика `Conditional`: запоминает, включён ли поставщик.
struct Consumer;

#[async_trait]
impl Module for Consumer {
    const NAME: &'static str = "Consumer";
    type Config = redup_bootstrap::NoSettings;
    type Args = (Link<Conditional>, Arc<std::sync::atomic::AtomicBool>);

    async fn create(
        _: redup_bootstrap::NoSettings,
        (provider, on): (Link<Conditional>, Arc<std::sync::atomic::AtomicBool>),
        _: &mut Context<'_>,
    ) -> Result<Self, ModuleError> {
        on.store(provider.is_on(), std::sync::atomic::Ordering::SeqCst);
        Ok(Self)
    }
}

/// Модуль, который не работает без поставщика `Conditional`.
struct Requirer;

#[async_trait]
impl Module for Requirer {
    const NAME: &'static str = "Requirer";
    type Config = redup_bootstrap::NoSettings;
    type Args = Link<Conditional>;

    async fn create(
        _: redup_bootstrap::NoSettings,
        provider: Link<Conditional>,
        _: &mut Context<'_>,
    ) -> Result<Self, ModuleError> {
        provider.required()?;
        Ok(Self)
    }
}

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

/// Модуль, включённый только при своей секции.
struct Conditional;

#[async_trait]
impl Module for Conditional {
    const NAME: &'static str = "Conditional";
    type Config = Settings;
    type Args = Arc<std::sync::Mutex<String>>;

    async fn create(
        config: Settings,
        mode: Arc<std::sync::Mutex<String>>,
        _: &mut Context<'_>,
    ) -> Result<Self, ModuleError> {
        *locked(&mode) = config.mode;
        Ok(Self)
    }
}

#[tokio::test]
async fn link_points_to_the_enabled_provider() -> TestResult<()> {
    let on = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let (_directory, source) = Events::source("settings:\n  mode: on\n")?;
    let mut builder = Builder::new(&source, Service::new("trial", "0.0.0"))?;
    let provider = builder
        .add::<Conditional>(Arc::new(std::sync::Mutex::new(String::new())))
        .await?;
    builder.add::<Consumer>((provider, Arc::clone(&on))).await?;

    assert!(on.load(std::sync::atomic::Ordering::SeqCst));
    Ok(())
}

#[tokio::test]
async fn link_is_empty_when_the_provider_is_off() -> TestResult<()> {
    let on = Arc::new(std::sync::atomic::AtomicBool::new(true));
    let mut builder = Builder::new(&Events::none()?.1, Service::new("trial", "0.0.0"))?;
    let provider = builder
        .optional::<Conditional>(Arc::new(std::sync::Mutex::new(String::new())))
        .await?;
    builder.add::<Consumer>((provider, Arc::clone(&on))).await?;

    assert!(!on.load(std::sync::atomic::Ordering::SeqCst));
    Ok(())
}

#[tokio::test]
async fn required_link_to_off_provider_fails_the_build_naming_both() -> TestResult<()> {
    let mut builder = Builder::new(&Events::none()?.1, Service::new("trial", "0.0.0"))?;
    let provider = builder
        .optional::<Conditional>(Arc::new(std::sync::Mutex::new(String::new())))
        .await?;

    let error = builder
        .add::<Requirer>(provider)
        .await
        .err()
        .ok_or("the module was created")?;

    assert_eq!(
        error.to_string(),
        "module 'Requirer' failed to be created: module 'Conditional' is off: its configuration \
         section is absent or null, but another module requires it"
    );
    Ok(())
}

#[tokio::test]
async fn optional_module_turns_on_with_its_section() -> TestResult<()> {
    let off = Arc::new(std::sync::Mutex::new(String::new()));
    let mut builder = Builder::new(&Events::none()?.1, Service::new("trial", "0.0.0"))?;
    let link = builder.optional::<Conditional>(Arc::clone(&off)).await?;
    assert!(!link.is_on());
    assert!(locked(&off).is_empty(), "an off module is not created");

    let on = Arc::new(std::sync::Mutex::new(String::new()));
    let (_directory, source) = Events::source("settings:\n  mode: quiet\n")?;
    let mut builder = Builder::new(&source, Service::new("trial", "0.0.0"))?;
    let link = builder.optional::<Conditional>(Arc::clone(&on)).await?;
    assert!(link.is_on());
    assert_eq!(&*locked(&on), "quiet");
    Ok(())
}

#[tokio::test]
async fn null_section_turns_the_optional_module_off() -> TestResult<()> {
    let (_directory, source) = Events::source("settings: ~\n")?;
    let mut builder = Builder::new(&source, Service::new("trial", "0.0.0"))?;
    let link = builder
        .optional::<Conditional>(Arc::new(std::sync::Mutex::new(String::new())))
        .await?;

    assert!(!link.is_on());
    Ok(())
}

#[tokio::test]
async fn module_name_cannot_repeat() -> TestResult<()> {
    let events = Events::default();
    let mut builder = Builder::new(&Events::none()?.1, Service::new("trial", "0.0.0"))?;
    builder
        .add::<Alpha>(Arc::new(Behaviour::new(&events)))
        .await?;

    let error = builder
        .add::<Alpha>(Arc::new(Behaviour::new(&events)))
        .await
        .err()
        .ok_or("the module was added twice")?;

    assert_eq!(
        error.to_string(),
        "module name 'Alpha' is declared twice in the instance"
    );
    Ok(())
}

#[tokio::test]
async fn platform_configuration_is_validated() -> TestResult<()> {
    let (_directory, source) = Events::source("bootstrap:\n  watchers:\n    mode: never\n")?;

    let error = Builder::new(&source, Service::new("trial", "0.0.0"))
        .err()
        .ok_or("the configuration is accepted")?;

    let text = error.to_string();
    assert!(
        text.starts_with("the configuration of the platform is rejected"),
        "{text}"
    );
    assert!(text.contains("never"), "{text}");
    Ok(())
}

#[tokio::test]
async fn instance_is_started_once() -> TestResult<()> {
    let events = Events::default();
    let mut builder = Builder::new(
        &Events::source("bootstrap:\n  rest: ~\n")?.1,
        Service::new("trial", "0.0.0"),
    )?;
    builder
        .add::<Alpha>(Arc::new(Behaviour::new(&events)))
        .await?;
    let mut instance = builder.build();
    instance.start().await?;
    instance.stop().await;

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

    assert_eq!(
        error.to_string(),
        "the instance cannot be started in its current state"
    );
    Ok(())
}