lumenize 0.2.5

Laravel integration for Claviron hosts, independent of their server boot
use super::*;

#[test]
fn octane_detection_and_explicit_modes_select_execution() {
    use crate::PhpRunner;
    let root = tempfile::tempdir().unwrap();
    let mut plain = Configuration::default();
    plain.prepare_php(root.path()).unwrap();
    assert_eq!(plain.request_mode, Some(PhpRunner::Script));

    std::fs::write(
        root.path().join("composer.json"),
        r#"{"require":{"laravel/framework":"*","laravel/octane":"*"}}"#,
    )
    .unwrap();
    let mut octane = Configuration::default();
    assert_eq!(octane.prepare_php(root.path()).unwrap(), ["Laravel"]);
    assert_eq!(octane.request_mode, Some(PhpRunner::Application));

    let mut explicit_script = Configuration {
        request_mode: Some(PhpRunner::Script),
        ..Default::default()
    };
    explicit_script.prepare_php(root.path()).unwrap();
    assert_eq!(explicit_script.request_mode, Some(PhpRunner::Script));

    let mut explicit_application: Configuration = serde_yaml::from_str("request_mode: application\nphp: {application: {script_path: custom.php, framework: Vanilla}}\n").unwrap();
    std::fs::remove_file(root.path().join("composer.json")).unwrap();
    explicit_application.prepare_php(root.path()).unwrap();
    assert_eq!(explicit_application.request_mode, Some(PhpRunner::Application));
    assert_eq!(
        explicit_application.php["application"]["script_path"],
        "custom.php"
    );
    assert_eq!(explicit_application.php["application"]["framework"], "Vanilla");
}

/// Lumenize's keys and the runner's share one flat file, and a key neither
/// knows is refused rather than ignored.
#[test]
fn a_flat_file_divides_and_a_typo_is_refused() {
    let read: Options = serde_yaml::from_str::<Launch>(
        "orbit: {link: {max_in_flight: 128}}\nfleet_name: example\nphp: {application: {script_path: application.php}}\ncache: {}\nconfig_parser: {max_depth: 8}\n",
    )
    .unwrap()
    .into();
    assert!(read.runner.link_enabled());
    assert_eq!(
        read.runner
            .orbit_config()
            .unwrap()
            .unwrap()
            .link
            .unwrap()
            .max_in_flight,
        Some(128)
    );
    assert_eq!(read.runner.fleet_name.as_deref(), Some("example"));
    assert_eq!(read.configuration.config_parser.max_depth, 8);
    let cache: claviron::cache::CacheConfig =
        serde_yaml::from_value(read.configuration.cache.unwrap()).unwrap();
    assert!(cache.is_empty());

    assert!(serde_yaml::from_str::<Launch>("orbitt: true\n").is_err());
    assert!(serde_yaml::from_str::<Launch>("config_dir: runtime\n").is_err());
}

/// A worker is started with no command line, so what it serves has to
/// survive the envelope — its name included, which it cannot read from an
/// empty command line.
#[test]
fn a_launch_survives_the_envelope() {
    let mut sent: Launch = serde_yaml::from_str(
        "orbit: {link: {}}\nfleet_name: example\nworkers: 2\nrequest_mode: application\nrequests:\n  queue_timeout: 60s\nconfig_path: deployment.yaml\nphp: {application: {script_path: application.php}}\nlogging: {path: logs/system.log}\nbroadcasting: {key: '${APP_KEY}', secret: '${APP_SECRET}'}\n",
    )
    .unwrap();
    let prepared = sent.prepare("example-app".into()).unwrap();
    assert_eq!(prepared.workers, 2);
    let back: Launch = serde_json::from_slice(&prepared.envelope).unwrap();
    assert_eq!(prepared.fleet_name.as_str(), "example");
    assert_eq!(back.runner.name.as_deref(), Some("example-app"));
    assert_eq!(back.runner.workers, None, "a worker starts no workers");
    assert_eq!(back.own.request_mode, Some(crate::PhpRunner::Application));
    assert_eq!(back.own.config_path, Some(PathBuf::from("deployment.yaml")));
    assert_eq!(back.own.broadcasting.unwrap()["secret"], "${APP_SECRET}");
    assert_eq!(back.own.logging.unwrap()["path"], "logs/system.log");
    assert_eq!(
        back.runner.policy().unwrap().requests.queue_timeout,
        Some(std::time::Duration::from_secs(60))
    );
}

#[test]
fn single_system_log_does_not_require_channels_or_another_file() {
    let options: Options = serde_yaml::from_str::<Launch>(
        "logging: {path: logs/system.log, truncate: true}\n",
    )
    .unwrap()
    .into();
    let logging = options.system_log().unwrap().unwrap();
    assert_eq!(logging.path, PathBuf::from("logs/system.log"));
    assert_eq!(logging.format, claviron::logging::SystemLogFormat::Line);
    assert!(logging.truncate_on_startup);
}

#[test]
fn logging_rejects_misspelled_sections_and_non_mappings() {
    for raw in
        ["logging: {system_lgo: {path: logs/system.log}}", "logging: false"]
    {
        let options: Options =
            serde_yaml::from_str::<Launch>(raw).unwrap().into();
        assert!(options.system_log().is_err());
    }
}

#[test]
fn database_launch_survives_workers_without_resolving_environment() {
    let mut launch: Launch = serde_yaml::from_str(
        "orbit: {link: {}}\nfleet_name: example\nworkers: 2\ndatabase:\n  postgres:\n    example:\n      url: '${DATABASE_URL}'\n      pool: {pool_size: 2, idle_size: 0, acquire_timeout: 1s, idle_timeout: 1s, max_lifetime: 1s}\n",
    )
    .unwrap();
    let sent = launch.prepare("example-app".into()).unwrap();
    let received: Launch = serde_json::from_slice(&sent.envelope).unwrap();
    assert_eq!(received.own.database, launch.own.database);
    assert_eq!(
        received.own.database.unwrap()["postgres"]["example"]["url"],
        "${DATABASE_URL}",
    );
}

#[cfg(feature = "postgres")]
#[test]
fn database_section_uses_the_existing_native_schema() {
    let configuration: Configuration = serde_yaml::from_str(
        "database:\n  postgres:\n    example:\n      url: 'postgresql://example@example.test/example?options=-csearch_path%3Dexample'\n      pool: {pool_size: 2, idle_size: 0, acquire_timeout: 1s, idle_timeout: 1s, max_lifetime: 1s}\n",
    )
    .unwrap();
    configuration.validate_database_features().unwrap();
    let config: claviron::db::DbFileConfig =
        serde_yaml::from_value(configuration.database.unwrap()).unwrap();
    let entry = config.postgres.get("example").unwrap();
    assert_eq!(entry.pool.pool_size, 2);
    assert_eq!(
        entry.url.as_ref().unwrap().query(),
        Some("options=-csearch_path%3Dexample")
    );
}

#[test]
fn database_requires_a_mapping_and_selected_backends() {
    let configuration: Configuration =
        serde_yaml::from_str("database: true").unwrap();
    assert!(configuration.validate_database_features().is_err());
    for (backend, enabled) in [
        ("postgres", cfg!(feature = "postgres")),
        ("mysql", cfg!(feature = "mysql")),
        ("sqlite", cfg!(feature = "sqlite")),
    ] {
        let configuration: Configuration =
            serde_yaml::from_str(&format!("database: {{{backend}: {{}}}}"))
                .unwrap();
        assert_eq!(configuration.validate_database_features().is_ok(), enabled);
    }
}

#[test]
fn only_persistent_php_supplies_link_execution_capacity() {
    let raw = "request_mode: application\norbit: {link: {max_queued: 64}}\nphp: {application: {instances: 8}}";
    let read = |yaml: &str| -> Options {
        serde_yaml::from_str::<Launch>(yaml).unwrap().into()
    };
    let options = read(raw);
    options.validate().unwrap();
    assert_eq!(options.link_instances().unwrap(), Some(8));

    for (candidate, diagnostic) in [
        (
            raw.replace("max_queued: 64", "max_in_flight: 8, max_queued: 64"),
            "php.application.instances",
        ),
        (
            raw.replace("instances: 8", "instances: 8, max_queued: 0"),
            "use orbit.link.max_queued",
        ),
    ] {
        let error = read(&candidate).validate().unwrap_err();
        assert!(error.to_string().contains(diagnostic));
    }
    let script = read(
        "request_mode: script\norbit: {link: {max_in_flight: 8, max_queued: 64}}",
    );
    script.validate().unwrap();
    assert_eq!(script.link_instances().unwrap(), None);
}

/// The launch's `redis` section is the Redis provider's whole declaration:
/// it reaches the provider without a `redis.yaml`, and a build without the
/// feature refuses it rather than ignoring it.
#[test]
fn a_redis_section_reaches_the_provider_or_is_refused() {
    let configuration: Configuration = serde_yaml::from_str(
        "redis: {connections: {default: {url: 'redis://127.0.0.1:6379/0'}}}\n",
    )
    .unwrap();
    let checked = configuration.validate_redis_feature();
    #[cfg(not(feature = "redis"))]
    assert_eq!(
        checked.unwrap_err().to_string(),
        "redis requires the redis feature"
    );
    #[cfg(feature = "redis")]
    {
        checked.unwrap();
        let state = claviron::runtime::AppState::standalone(
            "redis-section-test",
            "no-config-dir",
        );
        configuration.register_redis(&state).unwrap();
        let provider = state
            .registry_ref()
            .resolve::<claviron::cache::RedisProvider>()
            .unwrap();
        assert!(provider.has_connection("default"));
    }
}

/// A `tls: true` listener serves the `tls` section's default identity from
/// the store the section names. Prepared again, as a worker's launch is, it
/// holds; a different certificate stated beside the section is refused.
#[cfg(feature = "tls")]
#[test]
fn a_tls_listener_serves_the_sections_default_identity() {
    let mut options: Options = serde_yaml::from_str::<Launch>(
        "listeners: {secure: {transport: tcp, listen: '127.0.0.1:0', protocols: [h1, h2], tls: true}}\ntls: {certstore: {dir: store}, default: {path: servers/app.example.test/fullchain.pem}, certs: [app.example.test]}\n",
    )
    .unwrap()
    .into();
    options.prepare_tls().unwrap();
    let folder = Path::new("store/servers/app.example.test");
    assert_eq!(
        options.runner.tls_cert.as_deref(),
        Some(folder.join("fullchain.pem").as_path())
    );
    assert_eq!(
        options.runner.tls_key.as_deref(),
        Some(folder.join("privkey.pem").as_path())
    );
    options.prepare_tls().unwrap();
    options.runner.tls_cert = Some("elsewhere.pem".into());
    assert!(options.prepare_tls().is_err());
}