perimeterx-fastly-enforcer 2.2.2

PerimeterX Fastly Compute@Edge Rust Enforcer
Documentation
use crate::px_error;
use fastly::kv_store::KVStoreError;
use fastly::KVStore;

/// Extension trait that exposes a [`fastly::ConfigStore`]-compatible `get`
/// API on [`fastly::KVStore`].
///
/// The enforcer was originally written against `ConfigStore`, whose
/// `get(&self, key: &str) -> Option<String>` signature is convenient at the
/// call site. After migrating to `KVStore` (which only offers `lookup`,
/// returning a `Result<LookupResponse, KVStoreError>`), this trait keeps the
/// existing call sites unchanged.
pub trait KVStoreGetExt {
    /// Look up `key` and return its value as a UTF-8 `String`.
    ///
    /// Returns `None` when:
    ///   * the key does not exist (`KVStoreError::ItemNotFound`),
    ///   * the lookup fails for any other reason, or
    ///   * the stored bytes are not valid UTF-8.
    ///
    /// Non-`ItemNotFound` errors and UTF-8 decoding failures are logged via
    /// `px_error!` so configuration problems remain observable.
    fn get(&self, key: &str) -> Option<String>;
}

impl KVStoreGetExt for KVStore {
    fn get(&self, key: &str) -> Option<String> {
        match self.lookup(key) {
            Ok(mut response) => match String::from_utf8(response.take_body_bytes()) {
                Ok(value) => Some(value),
                Err(e) => {
                    px_error!("KVStore value for key {:?} is not valid UTF-8: {}", key, e);
                    None
                }
            },
            Err(KVStoreError::ItemNotFound) => None,
            Err(e) => {
                px_error!("KVStore lookup failed for key {:?}: {:?}", key, e);
                None
            }
        }
    }
}