Skip to main content

mockforge_foundation/
conformance_violations.rs

1//! Server-side conformance violation tracking.
2//!
3//! Issue #79 round 12 — Srikanth's ask: "It would be good if mockforge tui
4//! have a separate section for conformance failures on the incoming
5//! requests to the mockforge server which has spec violation from the
6//! Server Side point of view, that way I can cross check Server Side
7//! Info with our proxy and understand the diff."
8//!
9//! The OpenAPI router already rejects requests that violate the loaded
10//! spec (status 400/422). This module captures every such rejection into
11//! a bounded ring buffer so the TUI / admin API can surface them
12//! without scraping logs.
13//!
14//! Storage is best-effort, in-memory, and bounded — under sustained
15//! WAF / load-test traffic we keep only the most recent N violations.
16
17use chrono::{DateTime, Utc};
18use once_cell::sync::Lazy;
19use parking_lot::Mutex;
20use serde::{Deserialize, Serialize};
21use std::collections::VecDeque;
22use std::sync::atomic::{AtomicU64, Ordering};
23
24/// A single server-side conformance violation captured at the OpenAPI
25/// router. Mirrors `ConformanceViolation` semantics from the bench-side
26/// client validator so consumers can use the same dashboards.
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct ServerConformanceViolation {
29    /// When the request was rejected.
30    pub timestamp: DateTime<Utc>,
31    /// HTTP method (uppercase).
32    pub method: String,
33    /// Spec-template path the request matched (e.g. `/users/{id}`).
34    pub path: String,
35    /// Client IP if available, else `"unknown"`.
36    pub client_ip: String,
37    /// HTTP status the server replied with (typically 400 or 422).
38    pub status: u16,
39    /// Short, human-readable reason — derived from the validator error.
40    pub reason: String,
41    /// Spec category the violation falls into (`"parameters"`,
42    /// `"request-body"`, `"headers"`, etc.). Empty if the validator
43    /// couldn't classify.
44    pub category: String,
45}
46
47const DEFAULT_BUFFER_SIZE: usize = 256;
48
49static VIOLATIONS: Lazy<Mutex<VecDeque<ServerConformanceViolation>>> =
50    Lazy::new(|| Mutex::new(VecDeque::with_capacity(DEFAULT_BUFFER_SIZE)));
51
52/// Lifetime count of violations recorded since process start (Issue #79
53/// round 15). The ring buffer only keeps the most recent
54/// `DEFAULT_BUFFER_SIZE`; this counter answers Srikanth's "I sent 656k
55/// requests but only see 256" — the 256 is the buffer cap, this is the
56/// true total seen.
57static TOTAL_SEEN: AtomicU64 = AtomicU64::new(0);
58
59/// Record a violation. Old entries are dropped when the buffer is full
60/// (FIFO). Cheap enough to call from the hot path — uses a parking_lot
61/// Mutex which is uncontended in steady state.
62pub fn record(violation: ServerConformanceViolation) {
63    TOTAL_SEEN.fetch_add(1, Ordering::Relaxed);
64    let mut buf = VIOLATIONS.lock();
65    if buf.len() == DEFAULT_BUFFER_SIZE {
66        buf.pop_front();
67    }
68    buf.push_back(violation);
69}
70
71/// Snapshot of the buffered violations, newest first.
72pub fn snapshot() -> Vec<ServerConformanceViolation> {
73    let buf = VIOLATIONS.lock();
74    buf.iter().rev().cloned().collect()
75}
76
77/// Number of violations currently buffered (≤ `DEFAULT_BUFFER_SIZE`).
78pub fn len() -> usize {
79    VIOLATIONS.lock().len()
80}
81
82/// Lifetime total of violations recorded since process start, including
83/// ones the ring buffer has since evicted.
84pub fn total_seen() -> u64 {
85    TOTAL_SEEN.load(Ordering::Relaxed)
86}
87
88/// Clear the buffer and reset the lifetime counter. Primarily for tests
89/// and TUI "reset" actions.
90pub fn clear() {
91    VIOLATIONS.lock().clear();
92    TOTAL_SEEN.store(0, Ordering::Relaxed);
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    fn v(method: &str, status: u16) -> ServerConformanceViolation {
100        ServerConformanceViolation {
101            timestamp: Utc::now(),
102            method: method.to_string(),
103            path: "/test".into(),
104            client_ip: "127.0.0.1".into(),
105            status,
106            reason: "test".into(),
107            category: "parameters".into(),
108        }
109    }
110
111    #[test]
112    fn record_and_snapshot_in_lifo_order() {
113        clear();
114        record(v("GET", 400));
115        record(v("POST", 422));
116        let snap = snapshot();
117        assert_eq!(snap.len(), 2);
118        // newest first
119        assert_eq!(snap[0].method, "POST");
120        assert_eq!(snap[1].method, "GET");
121    }
122
123    #[test]
124    fn buffer_drops_oldest_at_capacity() {
125        clear();
126        for i in 0..(DEFAULT_BUFFER_SIZE + 50) {
127            let mut entry = v("GET", 400);
128            entry.reason = format!("{i}");
129            record(entry);
130        }
131        assert_eq!(len(), DEFAULT_BUFFER_SIZE);
132        let snap = snapshot();
133        // newest is the last one we pushed
134        assert_eq!(snap[0].reason, format!("{}", DEFAULT_BUFFER_SIZE + 50 - 1));
135        // oldest still present is index 50 (the first 50 got dropped)
136        assert_eq!(snap[DEFAULT_BUFFER_SIZE - 1].reason, format!("{}", 50));
137    }
138}