stratum-node-config 0.1.0-alpha.4

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
Documentation
//! Schema walk, serialised schema shape and the seed document.

use stratum_node_config::{schema, ApplyClass, ConfigDocument, ValueType, SCHEMA_VERSION};

#[test]
fn every_field_is_documented_valid_by_default_and_classified() {
    let mut paths = Vec::new();
    for field in schema().fields() {
        let path = field.path();
        assert!(
            !field.description().trim().is_empty(),
            "{path}: empty description"
        );
        assert!(
            !field.description().contains('\n'),
            "{path}: description must be one paragraph"
        );
        assert!(
            field.validate(&field.default_value()).is_ok(),
            "{path}: default fails its own validation: {:?}",
            field.validate(&field.default_value())
        );
        assert!(
            matches!(
                field.apply_class(),
                ApplyClass::Live | ApplyClass::Restart | ApplyClass::Redeploy
            ),
            "{path}: apply class"
        );
        assert_eq!(
            format!("{}.{}", field.section(), field.key()),
            path,
            "{path}: section and key"
        );
        assert!(!paths.contains(&path), "{path}: duplicate path");
        paths.push(path);
    }
    assert_eq!(paths.len(), schema().fields().len(), "exact size");
}

#[test]
fn step_one_field_set_and_classes() {
    let got: Vec<(&str, ApplyClass)> = schema()
        .fields()
        .map(|f| (f.path(), f.apply_class()))
        .collect();
    assert_eq!(
        got,
        [
            ("node.name", ApplyClass::Live),
            ("node.canonical_origin", ApplyClass::Redeploy),
            ("listen.address", ApplyClass::Restart),
            ("storage.state_dir", ApplyClass::Restart),
            ("storage.backup_dir", ApplyClass::Restart),
            ("backup.age_recipients", ApplyClass::Live),
            ("secrets.pod_admin_key_ref", ApplyClass::Restart),
            ("federation.egress_enabled", ApplyClass::Live),
            ("membership.max_tenants", ApplyClass::Live),
            ("membership.invitations_enabled", ApplyClass::Live),
            ("membership.invitation_ttl_secs", ApplyClass::Live),
            ("membership.removal_grace_days", ApplyClass::Live),
            ("limits.max_body_bytes", ApplyClass::Restart),
            ("limits.max_outstanding_challenges", ApplyClass::Live),
            ("limits.max_pod_body_bytes", ApplyClass::Live),
            ("limits.admission_requests_per_minute", ApplyClass::Live),
            ("limits.min_pod_free_bytes", ApplyClass::Live),
            ("limits.pod_bytes_per_tenant", ApplyClass::Live),
            ("limits.job_max_cpus", ApplyClass::Live),
            ("limits.job_max_memory_bytes", ApplyClass::Live),
            ("limits.job_max_pids", ApplyClass::Live),
            ("limits.job_max_tmp_bytes", ApplyClass::Live),
            ("limits.job_max_timeout_secs", ApplyClass::Live),
            ("runner.max_concurrent_jobs", ApplyClass::Live),
        ],
        "field set"
    );
    let secrets: Vec<&str> = schema()
        .fields()
        .filter(|f| f.is_secret_ref())
        .map(stratum_node_config::FieldDescriptor::path)
        .collect();
    assert_eq!(secrets, ["secrets.pod_admin_key_ref"], "secret fields");
}

#[test]
fn apply_classes_are_ordered_by_strictness() {
    assert!(ApplyClass::Live < ApplyClass::Restart, "live < restart");
    assert!(
        ApplyClass::Restart < ApplyClass::Redeploy,
        "restart < redeploy"
    );
}

#[test]
fn schema_serialises_for_the_http_endpoint() {
    let json = serde_json::to_value(schema()).expect("schema serialises");
    assert_eq!(json["schema_version"], SCHEMA_VERSION, "version");
    let fields = json["fields"].as_array().expect("fields array");
    assert_eq!(fields.len(), schema().fields().len(), "field count");
    let body = fields
        .iter()
        .find(|f| f["path"] == "limits.max_body_bytes")
        .expect("max_body_bytes present");
    assert_eq!(
        body,
        &serde_json::json!({
            "path": "limits.max_body_bytes",
            "type": {"kind": "integer", "min": 1024, "max": 1_048_576},
            "default": 262_144,
            "description": schema().field("limits.max_body_bytes").expect("field").description(),
            "apply_class": "restart",
        }),
        "integer field shape"
    );
    let secret = fields
        .iter()
        .find(|f| f["path"] == "secrets.pod_admin_key_ref")
        .expect("secret present");
    assert_eq!(secret["type"]["kind"], "secret_ref", "secret kind");
    let list = fields
        .iter()
        .find(|f| f["path"] == "backup.age_recipients")
        .expect("list present");
    assert_eq!(list["type"]["kind"], "string_list", "list kind");
    assert_eq!(list["default"], serde_json::json!([]), "list default");
}

#[test]
fn value_types_match_the_brief() {
    let ty = |p: &str| schema().field(p).expect("field").value_type();
    assert_eq!(ty("node.name"), ValueType::String, "node.name");
    assert_eq!(
        ty("federation.egress_enabled"),
        ValueType::Boolean,
        "egress"
    );
    assert_eq!(
        ty("limits.max_outstanding_challenges"),
        ValueType::Integer { min: 1, max: 64 },
        "challenges"
    );
    assert_eq!(
        ty("backup.age_recipients"),
        ValueType::StringList,
        "recipients"
    );
    assert_eq!(
        ty("secrets.pod_admin_key_ref"),
        ValueType::SecretRef,
        "secret"
    );
    assert_eq!(
        ty("membership.max_tenants"),
        ValueType::Integer {
            min: 1,
            max: 10_000
        },
        "tenants"
    );
    assert_eq!(
        ty("membership.invitations_enabled"),
        ValueType::Boolean,
        "invitations"
    );
    assert_eq!(
        ty("membership.invitation_ttl_secs"),
        ValueType::Integer {
            min: 60,
            max: 2_592_000
        },
        "ttl"
    );
    assert_eq!(
        ty("limits.max_pod_body_bytes"),
        ValueType::Integer {
            min: 1024,
            max: 52_428_800
        },
        "pod body"
    );
    assert_eq!(
        ty("limits.admission_requests_per_minute"),
        ValueType::Integer { min: 1, max: 6000 },
        "admission rate"
    );
    assert_eq!(
        ty("limits.min_pod_free_bytes"),
        ValueType::Integer {
            min: 0,
            max: i64::MAX
        },
        "free bytes"
    );
    assert_eq!(
        ty("membership.removal_grace_days"),
        ValueType::Integer { min: 0, max: 3650 },
        "removal grace"
    );
    assert_eq!(
        ty("limits.pod_bytes_per_tenant"),
        ValueType::Integer {
            min: 0,
            max: i64::MAX
        },
        "pod quota"
    );
    assert!(schema().field("node.nope").is_none(), "unknown path");
}

#[test]
fn seed_parses_validates_and_equals_the_defaults() {
    let seed = schema().seed_text();
    let doc = ConfigDocument::parse(&seed).expect("seed must validate");
    assert_eq!(doc.text(), seed, "text kept verbatim");
    for field in schema().fields() {
        assert_eq!(
            doc.value(field.path()),
            Some(&field.default_value()),
            "{}: seed value is not the default",
            field.path()
        );
    }
    // Defaults filled for an otherwise empty document give the same values.
    let minimal = ConfigDocument::parse("schema_version = 1\n").expect("minimal document");
    assert_eq!(minimal.config(), doc.config(), "seed equals defaults");
    assert_eq!(minimal.public_hash(), doc.public_hash(), "same public hash");
}

#[test]
fn seed_lists_every_field_with_its_description_above_it() {
    let seed = schema().seed_text();
    for field in schema().fields() {
        let assignment = format!("\n{} = {}\n", field.key(), field.default_value());
        let at = seed
            .find(&assignment)
            .unwrap_or_else(|| panic!("{}: assignment missing from seed", field.path()));
        let above: String = seed[..at]
            .lines()
            .rev()
            .take_while(|l| l.starts_with('#'))
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .map(|l| l.trim_start_matches('#').trim())
            .collect::<Vec<_>>()
            .join(" ");
        let expected = format!(
            "{} Apply class: {}.",
            field
                .description()
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" "),
            field.apply_class()
        );
        assert_eq!(above, expected, "{}: comment above field", field.path());
    }
    assert!(
        seed.lines().all(|l| l.chars().count() <= 79),
        "seed lines wrap at 79 columns"
    );
}

#[test]
fn seed_is_deterministic() {
    assert_eq!(
        schema().seed_text(),
        schema().seed_text(),
        "same seed twice"
    );
}