cbtop/adversarial/
resources.rs1use std::time::{Duration, Instant};
4
5use super::{AdversarialError, AdversarialResult, ResourceUsage};
6
7#[derive(Debug, Clone)]
9pub struct BitFlipInjector {
10 pub seed: u64,
12 pub flip_count: usize,
14}
15
16impl Default for BitFlipInjector {
17 fn default() -> Self {
18 Self {
19 seed: 42,
20 flip_count: 1,
21 }
22 }
23}
24
25impl BitFlipInjector {
26 pub fn new(seed: u64, flip_count: usize) -> Self {
28 Self { seed, flip_count }
29 }
30
31 pub fn inject(&self, data: &[u8]) -> Vec<u8> {
33 let mut result = data.to_vec();
34 if result.is_empty() {
35 return result;
36 }
37
38 let mut rng_state = self.seed;
40 for _ in 0..self.flip_count {
41 rng_state = rng_state
43 .wrapping_mul(6364136223846793005)
44 .wrapping_add(1442695040888963407);
45
46 let byte_idx = (rng_state as usize) % result.len();
47 let bit_idx = ((rng_state >> 32) as usize) % 8;
48
49 result[byte_idx] ^= 1 << bit_idx;
50 }
51
52 result
53 }
54
55 pub fn inject_floats(&self, data: &[f32]) -> Vec<f32> {
57 let bytes: Vec<u8> = data.iter().flat_map(|f| f.to_le_bytes()).collect();
59
60 let corrupted = self.inject(&bytes);
61
62 corrupted
63 .as_chunks::<4>()
64 .0
65 .iter()
66 .map(|chunk| f32::from_le_bytes(*chunk))
67 .collect()
68 }
69}
70
71#[derive(Debug, Clone)]
73pub struct ResourceLimiter {
74 pub max_stack_depth: usize,
76 pub max_memory_bytes: usize,
78 pub timeout: Duration,
80 current_depth: usize,
82 current_memory: usize,
84 start_time: Option<Instant>,
86}
87
88impl Default for ResourceLimiter {
89 fn default() -> Self {
90 Self {
91 max_stack_depth: 1000,
92 max_memory_bytes: 1024 * 1024 * 1024, timeout: Duration::from_secs(60),
94 current_depth: 0,
95 current_memory: 0,
96 start_time: None,
97 }
98 }
99}
100
101impl ResourceLimiter {
102 pub fn new() -> Self {
104 Self::default()
105 }
106
107 pub fn with_max_depth(mut self, max_depth: usize) -> Self {
109 self.max_stack_depth = max_depth;
110 self
111 }
112
113 pub fn with_max_memory(mut self, max_bytes: usize) -> Self {
115 self.max_memory_bytes = max_bytes;
116 self
117 }
118
119 pub fn with_timeout(mut self, timeout: Duration) -> Self {
121 self.timeout = timeout;
122 self
123 }
124
125 pub fn start_operation(&mut self) {
127 self.start_time = Some(Instant::now());
128 }
129
130 pub fn check_timeout(&self, operation: &str) -> AdversarialResult<()> {
132 if let Some(start) = self.start_time {
133 let elapsed = start.elapsed();
134 if elapsed > self.timeout {
135 return Err(AdversarialError::Timeout {
136 operation: operation.to_string(),
137 elapsed,
138 limit: self.timeout,
139 });
140 }
141 }
142 Ok(())
143 }
144
145 pub fn enter_recursion(&mut self) -> AdversarialResult<()> {
147 self.current_depth += 1;
148 if self.current_depth > self.max_stack_depth {
149 return Err(AdversarialError::StackOverflow {
150 depth: self.current_depth,
151 max_depth: self.max_stack_depth,
152 });
153 }
154 Ok(())
155 }
156
157 pub fn exit_recursion(&mut self) {
159 if self.current_depth > 0 {
160 self.current_depth -= 1;
161 }
162 }
163
164 pub fn request_memory(&mut self, bytes: usize) -> AdversarialResult<()> {
166 let new_total = self.current_memory.saturating_add(bytes);
167 if new_total > self.max_memory_bytes {
168 return Err(AdversarialError::ResourceExhausted {
169 resource: format!(
170 "memory: requested {bytes} bytes, would exceed limit of {} bytes",
171 self.max_memory_bytes
172 ),
173 });
174 }
175 self.current_memory = new_total;
176 Ok(())
177 }
178
179 pub fn release_memory(&mut self, bytes: usize) {
181 self.current_memory = self.current_memory.saturating_sub(bytes);
182 }
183
184 pub fn usage(&self) -> ResourceUsage {
186 ResourceUsage {
187 stack_depth: self.current_depth,
188 memory_bytes: self.current_memory,
189 elapsed: self.start_time.map(|s| s.elapsed()),
190 }
191 }
192
193 pub fn reset(&mut self) {
195 self.current_depth = 0;
196 self.current_memory = 0;
197 self.start_time = None;
198 }
199}
200
201#[derive(Debug, Clone)]
203pub struct CancellationToken {
204 cancelled: std::sync::Arc<std::sync::atomic::AtomicBool>,
205}
206
207impl Default for CancellationToken {
208 fn default() -> Self {
209 Self::new()
210 }
211}
212
213impl CancellationToken {
214 pub fn new() -> Self {
216 Self {
217 cancelled: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
218 }
219 }
220
221 pub fn cancel(&self) {
223 self.cancelled
224 .store(true, std::sync::atomic::Ordering::SeqCst);
225 }
226
227 pub fn is_cancelled(&self) -> bool {
229 self.cancelled.load(std::sync::atomic::Ordering::SeqCst)
230 }
231
232 pub fn check(&self, operation: &str) -> AdversarialResult<()> {
234 if self.is_cancelled() {
235 return Err(AdversarialError::Cancelled {
236 operation: operation.to_string(),
237 });
238 }
239 Ok(())
240 }
241
242 pub fn clone_token(&self) -> Self {
244 Self {
245 cancelled: std::sync::Arc::clone(&self.cancelled),
246 }
247 }
248}
249
250#[derive(Debug, Clone)]
252pub struct RecoveryHandler<S: Clone> {
253 checkpoint: Option<S>,
255}
256
257impl<S: Clone> Default for RecoveryHandler<S> {
258 fn default() -> Self {
259 Self::new()
260 }
261}
262
263impl<S: Clone> RecoveryHandler<S> {
264 pub fn new() -> Self {
266 Self { checkpoint: None }
267 }
268
269 pub fn checkpoint(&mut self, state: S) {
271 self.checkpoint = Some(state);
272 }
273
274 pub fn recover(&self) -> AdversarialResult<S> {
276 self.checkpoint
277 .clone()
278 .ok_or_else(|| AdversarialError::RecoveryFailed {
279 original_error: "unknown".to_string(),
280 recovery_error: "no checkpoint available".to_string(),
281 })
282 }
283
284 pub fn try_with_recovery<F, T, E>(&self, operation: F) -> AdversarialResult<T>
286 where
287 F: FnOnce() -> Result<T, E>,
288 E: std::fmt::Display,
289 {
290 match operation() {
291 Ok(result) => Ok(result),
292 Err(e) => Err(AdversarialError::RecoveryFailed {
293 original_error: e.to_string(),
294 recovery_error: if self.checkpoint.is_some() {
295 "operation failed, checkpoint available".to_string()
296 } else {
297 "operation failed, no checkpoint".to_string()
298 },
299 }),
300 }
301 }
302
303 pub fn has_checkpoint(&self) -> bool {
305 self.checkpoint.is_some()
306 }
307}