|
| 1 | +//! Evaluation context for predicates and extractors. |
| 2 | +//! |
| 3 | +//! [`EvalContext`] is a type-map that allows predicates and extractors to share |
| 4 | +//! computed values during a single evaluation phase. This avoids redundant |
| 5 | +//! expensive operations (e.g., deserializing a protobuf body into a |
| 6 | +//! `DynamicMessage`) when multiple predicates or extractors need the same data. |
| 7 | +//! |
| 8 | +//! ## Usage |
| 9 | +//! |
| 10 | +//! ```rust |
| 11 | +//! use hitbox_core::EvalContext; |
| 12 | +//! |
| 13 | +//! struct ParsedProto(String); |
| 14 | +//! |
| 15 | +//! let mut ctx = EvalContext::new(); |
| 16 | +//! ctx.insert(ParsedProto("hello".into())); |
| 17 | +//! |
| 18 | +//! assert!(ctx.contains::<ParsedProto>()); |
| 19 | +//! assert_eq!(ctx.get::<ParsedProto>().unwrap().0, "hello"); |
| 20 | +//! ``` |
| 21 | +//! |
| 22 | +//! ## Lifecycle |
| 23 | +//! |
| 24 | +//! An `EvalContext` is created inside each `cache_policy` implementation: |
| 25 | +//! one for the request phase (shared by request predicates and extractors) |
| 26 | +//! and another for the response phase (used by response predicates). |
| 27 | +
|
| 28 | +use std::any::{Any, TypeId}; |
| 29 | +use std::collections::HashMap; |
| 30 | + |
| 31 | +/// A type-map for sharing computed values across predicates and extractors. |
| 32 | +/// |
| 33 | +/// Each value is keyed by its concrete type (`TypeId`), so only one value |
| 34 | +/// of each type can be stored. Use newtype wrappers to store multiple |
| 35 | +/// values of the same underlying type. |
| 36 | +/// |
| 37 | +/// # Thread Safety |
| 38 | +/// |
| 39 | +/// `EvalContext` is `Send + Sync` because all stored values must be |
| 40 | +/// `Send + Sync + 'static`. It is passed as `&mut EvalContext` through |
| 41 | +/// the evaluation chain, which is always sequential. |
| 42 | +pub struct EvalContext { |
| 43 | + map: HashMap<TypeId, Box<dyn Any + Send + Sync>>, |
| 44 | +} |
| 45 | + |
| 46 | +impl EvalContext { |
| 47 | + /// Creates an empty evaluation context. |
| 48 | + pub fn new() -> Self { |
| 49 | + Self { |
| 50 | + map: HashMap::new(), |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /// Inserts a value into the context. |
| 55 | + /// |
| 56 | + /// If a value of this type already exists, it is replaced and the old |
| 57 | + /// value is returned. |
| 58 | + pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> { |
| 59 | + self.map |
| 60 | + .insert(TypeId::of::<T>(), Box::new(val)) |
| 61 | + .and_then(|boxed| boxed.downcast().ok().map(|b| *b)) |
| 62 | + } |
| 63 | + |
| 64 | + /// Returns a reference to a value of the given type, if present. |
| 65 | + pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> { |
| 66 | + self.map |
| 67 | + .get(&TypeId::of::<T>()) |
| 68 | + .and_then(|boxed| boxed.downcast_ref()) |
| 69 | + } |
| 70 | + |
| 71 | + /// Returns a mutable reference to a value of the given type, if present. |
| 72 | + pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> { |
| 73 | + self.map |
| 74 | + .get_mut(&TypeId::of::<T>()) |
| 75 | + .and_then(|boxed| boxed.downcast_mut()) |
| 76 | + } |
| 77 | + |
| 78 | + /// Returns a mutable reference to a value of the given type, inserting |
| 79 | + /// a default computed by `f` if not present. |
| 80 | + /// |
| 81 | + /// This is the primary method for expensive lazy initialization: |
| 82 | + /// |
| 83 | + /// ```ignore |
| 84 | + /// let msg = ctx.get_or_insert_with(|| { |
| 85 | + /// ParsedProto(DynamicMessage::decode(descriptor, body_bytes).unwrap()) |
| 86 | + /// }); |
| 87 | + /// ``` |
| 88 | + pub fn get_or_insert_with<T: Send + Sync + 'static>( |
| 89 | + &mut self, |
| 90 | + f: impl FnOnce() -> T, |
| 91 | + ) -> &mut T { |
| 92 | + self.map |
| 93 | + .entry(TypeId::of::<T>()) |
| 94 | + .or_insert_with(|| Box::new(f())) |
| 95 | + .downcast_mut() |
| 96 | + .expect("type mismatch in EvalContext (this is a bug)") |
| 97 | + } |
| 98 | + |
| 99 | + /// Returns `true` if the context contains a value of the given type. |
| 100 | + pub fn contains<T: Send + Sync + 'static>(&self) -> bool { |
| 101 | + self.map.contains_key(&TypeId::of::<T>()) |
| 102 | + } |
| 103 | + |
| 104 | + /// Removes and returns a value of the given type, if present. |
| 105 | + pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> { |
| 106 | + self.map |
| 107 | + .remove(&TypeId::of::<T>()) |
| 108 | + .and_then(|boxed| boxed.downcast().ok().map(|b| *b)) |
| 109 | + } |
| 110 | +} |
| 111 | + |
| 112 | +impl Default for EvalContext { |
| 113 | + fn default() -> Self { |
| 114 | + Self::new() |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +impl std::fmt::Debug for EvalContext { |
| 119 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 120 | + f.debug_struct("EvalContext") |
| 121 | + .field("entries", &self.map.len()) |
| 122 | + .finish() |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +#[cfg(test)] |
| 127 | +mod tests { |
| 128 | + use super::*; |
| 129 | + |
| 130 | + struct StringValue(String); |
| 131 | + struct Counter(u32); |
| 132 | + |
| 133 | + #[test] |
| 134 | + fn test_insert_and_get() { |
| 135 | + let mut ctx = EvalContext::new(); |
| 136 | + ctx.insert(StringValue("hello".into())); |
| 137 | + |
| 138 | + assert!(ctx.contains::<StringValue>()); |
| 139 | + assert_eq!(ctx.get::<StringValue>().unwrap().0, "hello"); |
| 140 | + } |
| 141 | + |
| 142 | + #[test] |
| 143 | + fn test_insert_replaces_and_returns_old() { |
| 144 | + let mut ctx = EvalContext::new(); |
| 145 | + assert!(ctx.insert(Counter(1)).is_none()); |
| 146 | + let old = ctx.insert(Counter(2)); |
| 147 | + assert_eq!(old.unwrap().0, 1); |
| 148 | + assert_eq!(ctx.get::<Counter>().unwrap().0, 2); |
| 149 | + } |
| 150 | + |
| 151 | + #[test] |
| 152 | + fn test_get_mut() { |
| 153 | + let mut ctx = EvalContext::new(); |
| 154 | + ctx.insert(Counter(0)); |
| 155 | + ctx.get_mut::<Counter>().unwrap().0 += 1; |
| 156 | + assert_eq!(ctx.get::<Counter>().unwrap().0, 1); |
| 157 | + } |
| 158 | + |
| 159 | + #[test] |
| 160 | + fn test_get_or_insert_with() { |
| 161 | + let mut ctx = EvalContext::new(); |
| 162 | + |
| 163 | + // First call inserts |
| 164 | + let val = ctx.get_or_insert_with(|| Counter(42)); |
| 165 | + assert_eq!(val.0, 42); |
| 166 | + |
| 167 | + // Second call returns existing |
| 168 | + let val = ctx.get_or_insert_with(|| Counter(99)); |
| 169 | + assert_eq!(val.0, 42); |
| 170 | + } |
| 171 | + |
| 172 | + #[test] |
| 173 | + fn test_remove() { |
| 174 | + let mut ctx = EvalContext::new(); |
| 175 | + ctx.insert(Counter(10)); |
| 176 | + let removed = ctx.remove::<Counter>(); |
| 177 | + assert_eq!(removed.unwrap().0, 10); |
| 178 | + assert!(!ctx.contains::<Counter>()); |
| 179 | + } |
| 180 | + |
| 181 | + #[test] |
| 182 | + fn test_missing_type_returns_none() { |
| 183 | + let ctx = EvalContext::new(); |
| 184 | + assert!(ctx.get::<Counter>().is_none()); |
| 185 | + } |
| 186 | + |
| 187 | + #[test] |
| 188 | + fn test_multiple_types() { |
| 189 | + let mut ctx = EvalContext::new(); |
| 190 | + ctx.insert(StringValue("a".into())); |
| 191 | + ctx.insert(Counter(1)); |
| 192 | + |
| 193 | + assert_eq!(ctx.get::<StringValue>().unwrap().0, "a"); |
| 194 | + assert_eq!(ctx.get::<Counter>().unwrap().0, 1); |
| 195 | + } |
| 196 | + |
| 197 | + #[test] |
| 198 | + fn test_default() { |
| 199 | + let ctx = EvalContext::default(); |
| 200 | + assert!(!ctx.contains::<Counter>()); |
| 201 | + } |
| 202 | +} |
0 commit comments