1use std::fmt;
35use std::sync::atomic::{AtomicU64, Ordering};
36use std::sync::{Mutex, MutexGuard, PoisonError};
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
44pub enum WarningSeverity {
45 Info,
47 Low,
49 Medium,
51 High,
53 Critical,
55}
56
57impl fmt::Display for WarningSeverity {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 match self {
60 Self::Info => f.write_str("INFO"),
61 Self::Low => f.write_str("LOW"),
62 Self::Medium => f.write_str("MEDIUM"),
63 Self::High => f.write_str("HIGH"),
64 Self::Critical => f.write_str("CRITICAL"),
65 }
66 }
67}
68
69#[derive(Debug, Clone)]
75pub struct ExtensionWarning {
76 pub code: &'static str,
78
79 pub severity: WarningSeverity,
81
82 pub message: String,
84
85 pub cwe: Option<u32>,
88}
89
90impl fmt::Display for ExtensionWarning {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 write!(f, "[{}] {}: {}", self.severity, self.code, self.message)?;
93 if let Some(cwe) = self.cwe {
94 write!(f, " (CWE-{cwe})")?;
95 }
96 Ok(())
97 }
98}
99
100pub struct WarningCollector {
127 warnings: Mutex<Vec<ExtensionWarning>>,
128 limit: usize,
130 dropped: AtomicU64,
132}
133
134pub const DEFAULT_MAX_WARNINGS: usize = 10_000;
143
144impl WarningCollector {
145 #[must_use]
151 pub const fn new() -> Self {
152 Self::with_limit(DEFAULT_MAX_WARNINGS)
153 }
154
155 #[must_use]
157 pub const fn with_limit(limit: usize) -> Self {
158 Self {
159 warnings: Mutex::new(Vec::new()),
160 limit,
161 dropped: AtomicU64::new(0),
162 }
163 }
164
165 #[must_use]
168 pub fn dropped(&self) -> u64 {
169 self.dropped.load(Ordering::Relaxed)
170 }
171
172 fn lock(&self) -> MutexGuard<'_, Vec<ExtensionWarning>> {
176 self.warnings.lock().unwrap_or_else(PoisonError::into_inner)
177 }
178
179 pub fn emit(&self, warning: ExtensionWarning) {
182 let mut list = self.lock();
183 if list.len() < self.limit {
184 list.push(warning);
185 } else {
186 self.dropped.fetch_add(1, Ordering::Relaxed);
189 }
190 drop(list);
191 }
192
193 #[must_use]
195 pub fn len(&self) -> usize {
196 self.lock().len()
197 }
198
199 #[must_use]
201 pub fn is_empty(&self) -> bool {
202 self.len() == 0
203 }
204
205 #[must_use]
207 pub fn snapshot(&self) -> Vec<ExtensionWarning> {
208 self.lock().clone()
209 }
210
211 pub fn drain(&self) -> Vec<ExtensionWarning> {
216 let mut list = self.lock();
217 self.dropped.store(0, Ordering::Relaxed);
218 std::mem::take(&mut *list)
219 }
220
221 pub fn clear(&self) {
223 let mut list = self.lock();
224 self.dropped.store(0, Ordering::Relaxed);
225 list.clear();
226 }
227}
228
229impl Default for WarningCollector {
230 fn default() -> Self {
231 Self::new()
232 }
233}
234
235const _: () = {
239 const fn assert_send_sync<T: Send + Sync>() {}
240 assert_send_sync::<WarningCollector>();
241};
242
243impl core::fmt::Debug for WarningCollector {
244 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
245 let guard = match self.warnings.try_lock() {
249 Ok(guard) => Ok(guard),
250 Err(std::sync::TryLockError::Poisoned(poisoned)) => Ok(poisoned.into_inner()),
251 Err(std::sync::TryLockError::WouldBlock) => Err(()),
252 };
253 match guard {
254 Ok(warnings) => f
255 .debug_struct("WarningCollector")
256 .field("warnings", &*warnings)
257 .field("limit", &self.limit)
258 .field("dropped", &self.dropped())
259 .finish(),
260 Err(()) => f
261 .debug_struct("WarningCollector")
262 .field("warnings", &"<locked>")
263 .field("limit", &self.limit)
264 .field("dropped", &self.dropped())
265 .finish(),
266 }
267 }
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273
274 fn warning(code: &'static str, severity: WarningSeverity) -> ExtensionWarning {
275 ExtensionWarning {
276 code,
277 severity,
278 message: String::new(),
279 cwe: None,
280 }
281 }
282
283 #[test]
287 fn a_poisoned_lock_does_not_lose_warnings() {
288 let c = WarningCollector::new();
289 c.emit(warning("BEFORE", WarningSeverity::Low));
290 let poisoner = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
291 let _guard = c.warnings.lock();
292 panic!("poison the collector's lock");
293 }));
294 assert!(poisoner.is_err());
295 assert!(c.warnings.is_poisoned());
296
297 c.emit(warning("AFTER", WarningSeverity::High));
298 assert!(format!("{c:?}").contains("AFTER"), "Debug reads through it");
299 assert_eq!(c.len(), 2);
300 assert!(!c.is_empty());
301 let codes: Vec<_> = c.snapshot().iter().map(|w| w.code).collect();
302 assert_eq!(codes, ["BEFORE", "AFTER"]);
303 assert_eq!(c.drain().len(), 2);
304 c.emit(warning("AGAIN", WarningSeverity::Info));
305 c.clear();
306 assert!(c.is_empty());
307 }
308
309 #[test]
310 fn severities_order_from_info_to_critical() {
311 use WarningSeverity::{Critical, High, Info, Low, Medium};
312 assert!(Info < Low && Low < Medium && Medium < High && High < Critical);
313 let mut shuffled = [High, Info, Critical, Low, Medium];
314 shuffled.sort();
315 assert_eq!(shuffled, [Info, Low, Medium, High, Critical]);
316 assert_eq!([Low, Critical, Medium].iter().max(), Some(&Critical));
317 }
318
319 #[test]
320 fn severity_display() {
321 assert_eq!(WarningSeverity::Info.to_string(), "INFO");
322 assert_eq!(WarningSeverity::Low.to_string(), "LOW");
323 assert_eq!(WarningSeverity::Medium.to_string(), "MEDIUM");
324 assert_eq!(WarningSeverity::High.to_string(), "HIGH");
325 assert_eq!(WarningSeverity::Critical.to_string(), "CRITICAL");
326 }
327
328 #[test]
329 fn warning_display_without_cwe() {
330 let w = ExtensionWarning {
331 code: "TEST_WARN",
332 severity: WarningSeverity::Medium,
333 message: "something happened".into(),
334 cwe: None,
335 };
336 assert_eq!(w.to_string(), "[MEDIUM] TEST_WARN: something happened");
337 }
338
339 #[test]
340 fn warning_display_with_cwe() {
341 let w = ExtensionWarning {
342 code: "TLS_NO_VERIFY",
343 severity: WarningSeverity::High,
344 message: "TLS verification disabled".into(),
345 cwe: Some(295),
346 };
347 assert_eq!(
348 w.to_string(),
349 "[HIGH] TLS_NO_VERIFY: TLS verification disabled (CWE-295)"
350 );
351 }
352
353 #[test]
354 fn collector_emit_and_drain() {
355 let c = WarningCollector::new();
356 assert!(c.is_empty());
357 assert_eq!(c.len(), 0);
358
359 c.emit(ExtensionWarning {
360 code: "A",
361 severity: WarningSeverity::Low,
362 message: "first".into(),
363 cwe: None,
364 });
365 c.emit(ExtensionWarning {
366 code: "B",
367 severity: WarningSeverity::High,
368 message: "second".into(),
369 cwe: Some(200),
370 });
371
372 assert_eq!(c.len(), 2);
373 assert!(!c.is_empty());
374
375 let warnings = c.drain();
376 assert_eq!(warnings.len(), 2);
377 assert_eq!(warnings[0].code, "A");
378 assert_eq!(warnings[1].code, "B");
379
380 assert!(c.is_empty());
382 }
383
384 #[test]
385 fn collector_snapshot_does_not_clear() {
386 let c = WarningCollector::new();
387 c.emit(ExtensionWarning {
388 code: "X",
389 severity: WarningSeverity::Info,
390 message: "test".into(),
391 cwe: None,
392 });
393
394 let snap = c.snapshot();
395 assert_eq!(snap.len(), 1);
396 assert_eq!(c.len(), 1);
398 }
399
400 #[test]
401 fn collector_clear() {
402 let c = WarningCollector::new();
403 c.emit(ExtensionWarning {
404 code: "Y",
405 severity: WarningSeverity::Critical,
406 message: "urgent".into(),
407 cwe: Some(798),
408 });
409 assert_eq!(c.len(), 1);
410
411 c.clear();
412 assert!(c.is_empty());
413 }
414
415 #[test]
416 fn collector_default() {
417 let c = WarningCollector::default();
418 assert!(c.is_empty());
419 }
420
421 #[test]
422 fn collector_is_send_sync() {
423 fn assert_send_sync<T: Send + Sync>() {}
424 assert_send_sync::<WarningCollector>();
425 }
426
427 #[test]
428 fn severity_clone_eq_hash() {
429 use std::collections::HashSet;
430
431 let s1 = WarningSeverity::High;
432 let s2 = s1;
433 assert_eq!(s1, s2);
434 let mut set = HashSet::new();
435 set.insert(WarningSeverity::Low);
436 set.insert(WarningSeverity::High);
437 assert_eq!(set.len(), 2);
438 }
439
440 #[test]
441 fn collector_drain_returns_in_order() {
442 let c = WarningCollector::new();
443 for i in 0..10 {
444 c.emit(ExtensionWarning {
445 code: "SEQ",
446 severity: WarningSeverity::Info,
447 message: format!("msg-{i}"),
448 cwe: None,
449 });
450 }
451 let warnings = c.drain();
452 assert_eq!(warnings.len(), 10);
453 for (i, w) in warnings.iter().enumerate() {
454 assert_eq!(w.message, format!("msg-{i}"));
455 }
456 }
457
458 #[test]
459 fn collector_clear_then_emit() {
460 let c = WarningCollector::new();
461 c.emit(ExtensionWarning {
462 code: "A",
463 severity: WarningSeverity::Low,
464 message: "first".into(),
465 cwe: None,
466 });
467 c.clear();
468 c.emit(ExtensionWarning {
469 code: "B",
470 severity: WarningSeverity::High,
471 message: "second".into(),
472 cwe: None,
473 });
474 let warnings = c.drain();
475 assert_eq!(warnings.len(), 1);
476 assert_eq!(warnings[0].code, "B");
477 }
478
479 #[test]
480 fn warning_clone() {
481 let w = ExtensionWarning {
482 code: "TEST",
483 severity: WarningSeverity::Critical,
484 message: "important".into(),
485 cwe: Some(798),
486 };
487 let w2 = w.clone();
488 assert_eq!(w.code, w2.code);
489 assert_eq!(w.severity, w2.severity);
490 assert_eq!(w.message, w2.message);
491 assert_eq!(w.cwe, w2.cwe);
492 }
493
494 #[test]
495 fn warning_debug_contains_fields() {
496 let w = ExtensionWarning {
497 code: "DBG",
498 severity: WarningSeverity::Medium,
499 message: "test debug".into(),
500 cwe: Some(100),
501 };
502 let debug = format!("{w:?}");
503 assert!(debug.contains("DBG"));
504 assert!(debug.contains("Medium"));
505 assert!(debug.contains("test debug"));
506 assert!(debug.contains("100"));
507 }
508
509 #[test]
510 fn snapshot_after_drain_is_empty() {
511 let c = WarningCollector::new();
512 c.emit(ExtensionWarning {
513 code: "X",
514 severity: WarningSeverity::Info,
515 message: "test".into(),
516 cwe: None,
517 });
518 let _ = c.drain();
519 let snap = c.snapshot();
520 assert!(snap.is_empty());
521 }
522
523 #[test]
524 fn multiple_drains_second_is_empty() {
525 let c = WarningCollector::new();
526 c.emit(ExtensionWarning {
527 code: "X",
528 severity: WarningSeverity::Info,
529 message: "test".into(),
530 cwe: None,
531 });
532 let first = c.drain();
533 assert_eq!(first.len(), 1);
534 let second = c.drain();
535 assert!(second.is_empty());
536 }
537 #[test]
540 fn a_full_collector_counts_instead_of_growing() {
541 let c = WarningCollector::with_limit(3);
542 for i in 0..10 {
543 c.emit(warning(
544 if i < 3 { "KEPT" } else { "LOST" },
545 WarningSeverity::Low,
546 ));
547 }
548 assert_eq!(c.len(), 3);
549 assert_eq!(c.dropped(), 7);
550 assert!(c.snapshot().iter().all(|w| w.code == "KEPT"));
551 assert!(format!("{c:?}").contains("dropped: 7"));
552 assert_eq!(c.drain().len(), 3);
553 assert_eq!(c.dropped(), 0, "draining resets the count");
554 c.emit(warning("AGAIN", WarningSeverity::Low));
555 assert_eq!((c.len(), c.dropped()), (1, 0));
556 let full = WarningCollector::with_limit(0);
557 full.emit(warning("X", WarningSeverity::Info));
558 assert_eq!((full.len(), full.dropped()), (0, 1));
559 full.clear();
560 assert_eq!(full.dropped(), 0);
561 }
562
563 #[test]
564 fn the_default_collector_keeps_the_documented_number() {
565 let c = WarningCollector::new();
566 for _ in 0..DEFAULT_MAX_WARNINGS + 5 {
567 c.emit(warning("W", WarningSeverity::Info));
568 }
569 assert_eq!(c.len(), DEFAULT_MAX_WARNINGS);
570 assert_eq!(c.dropped(), 5);
571 }
572}