1#[cfg(debug_assertions)]
25use std::collections::HashMap;
26#[cfg(debug_assertions)]
27use std::sync::atomic::AtomicU64;
28use std::sync::{
29 Mutex, OnceLock,
30 atomic::{AtomicBool, Ordering},
31};
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
39#[repr(u8)]
40pub enum ValidationSeverity {
41 Verbose = 0,
43 Info = 1,
45 Warning = 2,
47 Error = 3,
49 Fatal = 4,
51}
52
53impl ValidationSeverity {
54 pub fn as_str(self) -> &'static str {
56 match self {
57 Self::Verbose => "VERBOSE",
58 Self::Info => "INFO",
59 Self::Warning => "WARNING",
60 Self::Error => "ERROR",
61 Self::Fatal => "FATAL",
62 }
63 }
64}
65
66pub type ValidationCallback = fn(ValidationSeverity, &str, &str);
70
71struct ValidationState {
72 enabled: AtomicBool,
73 min_severity: Mutex<ValidationSeverity>,
74 callback: Mutex<Option<ValidationCallback>>,
75 #[cfg(debug_assertions)]
76 counters: Mutex<HashMap<String, AtomicU64>>,
77}
78
79static STATE: OnceLock<ValidationState> = OnceLock::new();
80
81fn state() -> &'static ValidationState {
82 STATE.get_or_init(|| ValidationState {
83 #[cfg(debug_assertions)]
84 enabled: AtomicBool::new(true),
85 #[cfg(not(debug_assertions))]
86 enabled: AtomicBool::new(false),
87 min_severity: Mutex::new(ValidationSeverity::Verbose),
88 callback: Mutex::new(None),
89 #[cfg(debug_assertions)]
90 counters: Mutex::new(HashMap::new()),
91 })
92}
93
94pub struct Validation;
98
99impl Validation {
100 pub fn enable(on: bool) {
102 state().enabled.store(on, Ordering::Release);
103 }
104
105 pub fn is_enabled() -> bool {
107 state().enabled.load(Ordering::Acquire)
108 }
109
110 pub fn init_from_env() {
113 if std::env::var("OA_VK_VALIDATION")
114 .map(|v| !matches!(v.as_str(), "" | "0" | "false" | "no" | "off"))
115 .unwrap_or(false)
116 {
117 Self::enable(true);
118 }
119 if let Ok(sev) = std::env::var("OA_VALIDATION_SEVERITY") {
120 let parsed = match sev.to_ascii_uppercase().as_str() {
121 "VERBOSE" => Some(ValidationSeverity::Verbose),
122 "INFO" => Some(ValidationSeverity::Info),
123 "WARNING" | "WARN" => Some(ValidationSeverity::Warning),
124 "ERROR" => Some(ValidationSeverity::Error),
125 "FATAL" => Some(ValidationSeverity::Fatal),
126 _ => None,
127 };
128 if let Some(s) = parsed {
129 Self::set_min_severity(s);
130 }
131 }
132 }
133
134 pub fn set_min_severity(sev: ValidationSeverity) {
137 *state().min_severity.lock().unwrap() = sev;
138 }
139
140 pub fn get_min_severity() -> ValidationSeverity {
142 *state().min_severity.lock().unwrap()
143 }
144
145 pub fn set_callback(cb: Option<ValidationCallback>) {
148 *state().callback.lock().unwrap() = cb;
149 }
150
151 pub fn report(sev: ValidationSeverity, component: &str, message: &str) -> crate::Result<()> {
156 let s = state();
157 if !s.enabled.load(Ordering::Acquire) {
158 return Ok(());
159 }
160 if sev < *s.min_severity.lock().unwrap() {
161 return Ok(());
162 }
163 let cb = *s.callback.lock().unwrap();
164 if let Some(f) = cb {
165 f(sev, component, message);
166 } else {
167 eprintln!("[OA {}] {}: {}", sev.as_str(), component, message);
168 }
169 if sev >= ValidationSeverity::Error {
170 return Err(crate::core::error::Error::invalid_argument(format!(
171 "validation error [{component}]: {message}"
172 )));
173 }
174 Ok(())
175 }
176
177 #[cfg(debug_assertions)]
181 pub fn incr_counter(name: &str) {
182 let s = state();
183 let mut map = s.counters.lock().unwrap();
184 map
185 .entry(name.to_owned())
186 .or_insert_with(|| AtomicU64::new(0))
187 .fetch_add(1, Ordering::Relaxed);
188 }
189
190 #[cfg(not(debug_assertions))]
191 pub fn incr_counter(_name: &str) {}
192
193 #[cfg(debug_assertions)]
195 pub fn get_counter(name: &str) -> u64 {
196 state()
197 .counters
198 .lock()
199 .unwrap()
200 .get(name)
201 .map(|c| c.load(Ordering::Relaxed))
202 .unwrap_or(0)
203 }
204
205 #[cfg(not(debug_assertions))]
206 pub fn get_counter(_name: &str) -> u64 {
207 0
208 }
209
210 #[cfg(debug_assertions)]
212 pub fn reset_counters() {
213 state().counters.lock().unwrap().clear();
214 }
215
216 #[cfg(not(debug_assertions))]
217 pub fn reset_counters() {}
218}
219
220#[macro_export]
237macro_rules! oa_validate {
238 ($cond:expr, $sev:expr, $comp:expr, $($arg:tt)*) => {
239 #[cfg(any(debug_assertions, feature = "oa-enable-validation"))]
240 {
241 if $crate::Validation::is_enabled() && !($cond) {
242 let msg = format!($($arg)*);
243 $crate::Validation::report($sev, $comp, &msg)?;
244 }
245 }
246 };
247}
248
249#[macro_export]
254macro_rules! oa_warn_perf {
255 ($cond:expr, $($arg:tt)*) => {
256 #[cfg(any(debug_assertions, feature = "oa-enable-validation"))]
257 {
258 if $crate::Validation::is_enabled() && ($cond) {
259 let msg = format!($($arg)*);
260 let _ = $crate::Validation::report(
261 $crate::ValidationSeverity::Warning, "Core", &msg);
262 }
263 }
264 };
265}