rave_engine 0.8.0

A secure and efficient JSON Schema validation and Rhai script execution engine
Documentation
use chrono::Utc;
use hdi::prelude::{ExternResult, Timestamp};
use hdk::time::sys_time;

#[derive(Debug, Clone, Copy)]
pub enum TimeProvider {
    Holochain,
    System,
}

impl TimeProvider {
    fn get_current_time(&self) -> ExternResult<Timestamp> {
        match self {
            Self::Holochain => sys_time(),
            Self::System => {
                let now = Utc::now();
                Ok(Timestamp::from_micros(now.timestamp_micros()))
            }
        }
    }
}

pub struct ResourceMonitor {
    execution_time: Timestamp,
    recursion_depth: u32,
    operation_count: u64,
    start_time: Timestamp,
    max_operations: u64,
    max_recursion_depth: u32,
}

impl ResourceMonitor {
    pub fn new(
        time_provider: TimeProvider,
        max_operations: u64,
        max_recursion_depth: u32,
    ) -> ExternResult<Self> {
        Ok(Self {
            execution_time: time_provider.get_current_time()?,
            recursion_depth: 0,
            operation_count: 0,
            start_time: time_provider.get_current_time()?,
            max_operations,
            max_recursion_depth,
        })
    }

    pub fn check_operation_limit(&self) -> Result<(), String> {
        if self.operation_count > self.max_operations {
            return Err(format!(
                "Operation limit exceeded: {} operations",
                self.operation_count
            ));
        }
        Ok(())
    }

    pub fn increment_operation_count(&mut self) -> Result<(), String> {
        self.operation_count += 1;
        self.check_operation_limit()
    }
}

impl Clone for ResourceMonitor {
    fn clone(&self) -> Self {
        Self {
            execution_time: self.execution_time,
            recursion_depth: self.recursion_depth,
            operation_count: self.operation_count,
            start_time: self.start_time,
            max_operations: self.max_operations,
            max_recursion_depth: self.max_recursion_depth,
        }
    }
}