mf_engine/util/
validator_cache.rs1use crate::EvaluationError;
2use ahash::HashMap;
3use jsonschema::Validator;
4use serde_json::Value;
5use std::sync::Arc;
6use tokio::sync::RwLock;
7
8#[derive(Clone, Default, Debug)]
9pub struct ValidatorCache {
10 inner: Arc<RwLock<HashMap<u64, Arc<Validator>>>>,
11}
12
13impl ValidatorCache {
14 pub async fn get(
15 &self,
16 key: u64,
17 ) -> Option<Arc<Validator>> {
18 let read = self.inner.read().await;
19 read.get(&key).cloned()
20 }
21
22 pub async fn get_or_insert(
23 &self,
24 key: u64,
25 schema: &Value,
26 ) -> Result<Arc<Validator>, Box<EvaluationError>> {
27 if let Some(v) = self.get(key).await {
28 return Ok(v);
29 }
30
31 let mut w_shared = self.inner.write().await;
32 let validator = Arc::new(jsonschema::draft7::new(&schema)?);
33 w_shared.insert(key, validator.clone());
34
35 Ok(validator)
36 }
37}