encore-dev 2.0.0

Rust SDK for Encore applications
Documentation
//! Configs read through a real runtime, built from a runtime config like the
//! daemon's: values, defaults, secret fields, and values changed while the
//! process runs.

use std::sync::Once;
use std::sync::mpsc;
use std::time::Duration;

use encore::config::{Config, ConfigType};
use encore::secrets::Secret;
use encore_runtimecfg::pb;
use serde::Deserialize;
use serde_json::{Value, json};

#[derive(Debug, Deserialize, ConfigType)]
struct Checkout {
    #[config(min = 1, max = 500)]
    max_items: u32,
    #[serde(default)]
    promo: Option<Promo>,
    payment_timeout: encore::config::Duration,
}

#[derive(Debug, Deserialize, ConfigType)]
struct Promo {
    code: String,
    discount: u8,
}

#[derive(Debug, Deserialize, ConfigType)]
struct Flags {
    #[serde(default)]
    new_checkout: bool,
}

#[derive(Deserialize, ConfigType)]
struct Payments {
    stripe: Stripe,
}

#[derive(Deserialize, ConfigType)]
struct Stripe {
    endpoint: String,
    #[config(secret = "StripeKey")]
    api_key: Secret,
}

#[derive(Debug, Deserialize, ConfigType)]
struct Limits {
    #[serde(default = "default_rate")]
    rate: u32,
}

fn default_rate() -> u32 {
    10
}

#[derive(Debug, Deserialize, ConfigType)]
struct Live {
    level: u32,
}

static CHECKOUT: Config<Checkout> = Config::new("checkout");
static FLAGS: Config<Flags> = Config::new("flags").shared();
static PAYMENTS: Config<Payments> = Config::new("payments").global();
/// Declared, but the runtime config has no value for it.
static LIMITS: Config<Limits> = Config::new("limits");
static LIVE: Config<Live> = Config::new("live");

fn schema(value: Value) -> String {
    value.to_string()
}

/// A value given to `service`, the config's own, or for a shared or global
/// config, to every service.
fn app_config(service: Option<&str>, name: &str, schema: String, value: Value) -> pb::AppConfig {
    pb::AppConfig {
        rid: format!("config:{name}"),
        encore_name: name.into(),
        services: vec![service.unwrap_or("*").to_string()],
        json_schema: schema,
        value: serde_json::to_vec(&value).unwrap(),
    }
}

fn live_file() -> std::path::PathBuf {
    std::env::temp_dir().join(format!(
        "encore-sdk-config-test-{}.json",
        std::process::id()
    ))
}

/// Points the runtime at the test's config before anything starts it.
fn setup() {
    static SETUP: Once = Once::new();
    SETUP.call_once(|| {
        let checkout_schema = schema(json!({
            "type": "object",
            "properties": {
                "max_items": {"type": "integer", "minimum": 1, "maximum": 500},
                "promo": {"anyOf": [{"$ref": "#/$defs/Promo"}, {"type": "null"}]},
                "payment_timeout": {"type": "string", "x-encore-format": "duration",
                    "pattern": r"^([0-9]+(\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$"},
            },
            "required": ["max_items", "payment_timeout"],
            "additionalProperties": false,
            "$defs": {"Promo": {
                "type": "object",
                "properties": {"code": {"type": "string"}, "discount": {"type": "integer", "minimum": 0, "maximum": 255}},
                "required": ["code", "discount"],
                "additionalProperties": false,
            }},
        }));
        let payments_schema = schema(json!({
            "type": "object",
            "properties": {"stripe": {"$ref": "#/$defs/Stripe"}},
            "required": ["stripe"],
            "additionalProperties": false,
            "$defs": {"Stripe": {
                "type": "object",
                "properties": {
                    "endpoint": {"type": "string"},
                    "api_key": {"x-encore-secret": "StripeKey"},
                },
                "required": ["endpoint"],
                "additionalProperties": false,
            }},
        }));
        let live_schema = schema(json!({
            "type": "object",
            "properties": {"level": {"type": "integer", "minimum": 0}},
            "required": ["level"],
            "additionalProperties": false,
        }));
        let cfg = pb::RuntimeConfig {
            environment: Some(pb::Environment {
                app_id: "app".into(),
                env_name: "local".into(),
                cloud: pb::environment::Cloud::Local as i32,
                ..Default::default()
            }),
            deployment: Some(pb::Deployment {
                hosted_services: vec![pb::HostedService {
                    name: "orders".into(),
                    ..Default::default()
                }],
                ..Default::default()
            }),
            infra: Some(pb::Infrastructure {
                resources: Some(pb::infrastructure::Resources {
                    app_configs: vec![
                        app_config(
                            Some("orders"),
                            "checkout",
                            checkout_schema,
                            json!({"max_items": 50, "promo": {"code": "FALL26", "discount": 10}, "payment_timeout": "1m30s"}),
                        ),
                        app_config(
                            None,
                            "flags",
                            schema(json!({"type": "object", "properties": {"new_checkout": {"type": "boolean"}}, "additionalProperties": false})),
                            json!({"new_checkout": true}),
                        ),
                        app_config(
                            None,
                            "payments",
                            payments_schema,
                            json!({"stripe": {"endpoint": "https://api.stripe.com"}}),
                        ),
                        app_config(Some("orders"), "live", live_schema, json!({"level": 1})),
                    ],
                    config_source: Some(pb::ConfigSource {
                        source: Some(pb::config_source::Source::File(
                            live_file().to_string_lossy().into_owned(),
                        )),
                    }),
                    app_secrets: vec![pb::AppSecret {
                        rid: "secret:StripeKey".into(),
                        encore_name: "StripeKey".into(),
                        data: Some(pb::SecretData {
                            source: Some(pb::secret_data::Source::Embedded(b"sk_test_123".to_vec())),
                            sub_path: None,
                            encoding: pb::secret_data::Encoding::None as i32,
                        }),
                        services: vec!["*".into()],
                    }],
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        };
        let _ = std::fs::remove_file(live_file());
        // SAFETY: before any thread reads the environment: the first test to get here
        // runs this, and every test comes here first.
        unsafe {
            std::env::set_var(
                "ENCORE_RUNTIME_CONFIG",
                encore_runtimecfg::encoding::encode_env_value(&cfg),
            );
        }
    });
}

#[test]
fn a_config_reads_as_its_type() {
    setup();
    let checkout = CHECKOUT.get();
    assert_eq!(checkout.max_items, 50);
    let promo = checkout.promo.as_ref().unwrap();
    assert_eq!((promo.code.as_str(), promo.discount), ("FALL26", 10));
    assert_eq!(*checkout.payment_timeout, Duration::from_secs(90));
    assert!(FLAGS.get().new_checkout);
    assert_eq!(CHECKOUT.name(), "checkout");
}

#[test]
fn a_snapshot_is_shared_until_the_value_changes() {
    setup();
    let a = CHECKOUT.get();
    let b = CHECKOUT.get();
    assert!(std::ptr::eq(&*a, &*b));
}

#[test]
fn a_config_without_a_value_takes_its_defaults() {
    setup();
    assert_eq!(LIMITS.get().rate, 10);
}

#[test]
fn a_secret_field_reads_the_secret() {
    setup();
    let payments = PAYMENTS.get();
    assert_eq!(payments.stripe.endpoint, "https://api.stripe.com");
    assert_eq!(payments.stripe.api_key.name(), "StripeKey");
    assert_eq!(*payments.stripe.api_key.value(), "sk_test_123");
}

#[test]
fn a_secret_with_no_value_reads_as_empty_locally() {
    setup();
    // Locally a secret lacks a value until it is set, so a read does not fail.
    static MISSING: Secret = Secret::new("NotGiven").global();
    assert_eq!(*MISSING.value(), "");
}

#[test]
fn values_change_while_the_process_runs() {
    setup();
    assert_eq!(LIVE.get().level, 1);
    let (tx, rx) = mpsc::channel();
    let tx = std::sync::Mutex::new(tx);
    LIVE.on_change(move |live| {
        let _ = tx.lock().unwrap().send(live.level);
    });

    let write = |revision: &str, level: Value| {
        encore_appconfig_live_write(revision, level);
    };

    // An invalid value is ignored: the last good one stays.
    write("1", json!(-1));
    std::thread::sleep(Duration::from_millis(1200));
    assert_eq!(LIVE.get().level, 1);
    assert!(rx.try_recv().is_err());

    write("2", json!(7));
    let changed = rx
        .recv_timeout(Duration::from_secs(5))
        .expect("on_change runs");
    assert_eq!(changed, 7);
    assert_eq!(LIVE.get().level, 7);

    // Rapid values: the latest arrives, and no value comes twice.
    for (revision, level) in [("3", 8), ("4", 9), ("5", 10)] {
        write(revision, json!(level));
        std::thread::sleep(Duration::from_millis(300));
    }
    let mut seen = Vec::new();
    while let Ok(level) = rx.recv_timeout(Duration::from_millis(1500)) {
        seen.push(level);
    }
    assert_eq!(seen.last(), Some(&10), "{seen:?}");
    assert!(seen.windows(2).all(|w| w[0] < w[1]), "{seen:?}");
    assert_eq!(LIVE.get().level, 10);
    let _ = std::fs::remove_file(live_file());
}

/// Writes the live file as the daemon does, with only `live`'s value: the
/// others keep theirs.
fn encore_appconfig_live_write(revision: &str, level: Value) {
    let file = json!({
        "revision": revision,
        "configs": [{"name": "live", "service": "orders", "value": {"level": level}}],
    });
    let path = live_file();
    let tmp = path.with_extension("tmp");
    std::fs::write(&tmp, serde_json::to_vec(&file).unwrap()).unwrap();
    std::fs::rename(&tmp, &path).unwrap();
}