sylphx 0.3.6

The Sylphx SDK: one API, one key, every Sylphx service. Generated from the Sylphx schema registry.
Documentation
// @generated by sylphx-gen. Do not edit.
//! Typed app-facing flags. Keep a handle per environment and subject to retain
//! last evaluated values while the API is unreachable.

use std::collections::BTreeMap;

use crate::config::{EvaluateConfigFlagsRequest, EvaluationContext, EvaluationReason};
use crate::runtime::{Client, Transport};
use serde_json::Value;

pub struct Flags<'a, T> {
    client: &'a Client<T>,
    parent: String,
    context: EvaluationContext,
    values: BTreeMap<String, Value>,
}

impl<T: Transport> Client<T> {
    /// Bind typed flags to one environment and subject. Keep the returned handle
    /// for offline values; a fresh handle uses call-site defaults when offline.
    pub fn flags(&self, parent: impl Into<String>, context: EvaluationContext) -> Flags<'_, T> {
        Flags {
            client: self,
            parent: parent.into(),
            context,
            values: BTreeMap::new(),
        }
    }
}

impl<T: Transport> Flags<'_, T> {
    async fn value(&mut self, key: &str) -> Option<Value> {
        let request = EvaluateConfigFlagsRequest {
            parent: self.parent.clone(),
            context: Some(self.context.clone()),
            ..Default::default()
        };
        if let Ok(response) = self.client.config().config_flags().evaluate(request).await {
            self.values = response
                .evaluations
                .into_iter()
                .filter(|e| e.reason != Some(EvaluationReason::NotFound))
                .map(|e| (e.config_flag, e.value))
                .collect();
        }
        self.values.get(key).cloned()
    }

    pub async fn bool(&mut self, key: &str, fallback: bool) -> bool {
        self.value(key)
            .await
            .and_then(|v| v.as_bool())
            .unwrap_or(fallback)
    }

    pub async fn string(&mut self, key: &str, fallback: impl Into<String>) -> String {
        self.value(key)
            .await
            .and_then(|v| v.as_str().map(str::to_owned))
            .unwrap_or_else(|| fallback.into())
    }

    pub async fn number(&mut self, key: &str, fallback: f64) -> f64 {
        self.value(key)
            .await
            .and_then(|v| v.as_f64())
            .unwrap_or(fallback)
    }

    pub async fn json(&mut self, key: &str, fallback: Value) -> Value {
        self.value(key)
            .await
            .filter(|v| !v.is_null())
            .unwrap_or(fallback)
    }
}