Skip to main content

no_mistakes_postgres_engine/
hooks.rs

1//! Inverted runtime hooks for `no-mistakes-postgres-engine`.
2
3use std::sync::{Arc, OnceLock};
4
5pub trait MetricsObserver: Send + Sync {
6    fn increment(&self, metric: &'static str, amount: u64);
7    fn verbose(&self) -> bool;
8}
9
10pub trait EngineHooks: Send + Sync {
11    fn current_observer(&self) -> Option<Arc<dyn MetricsObserver>>;
12    fn has_matching_disable_directive(&self, source: &str, line: u32, rule_id: &str) -> bool;
13}
14
15static REGISTERED_HOOKS: OnceLock<&'static dyn EngineHooks> = OnceLock::new();
16
17/// Register process-wide PostgreSQL engine hooks (first registration wins).
18///
19/// The `no-mistakes` crate registers hooks at load time. Standalone consumers
20/// that rely on invocation metrics or inline disable-directive suppression
21/// should register hooks before calling engine entrypoints.
22pub fn register_hooks(hooks: &'static dyn EngineHooks) {
23    let _ = REGISTERED_HOOKS.set(hooks);
24}
25
26/// Return the active invocation metrics observer from registered hooks, if any.
27pub fn current_observer() -> Option<Arc<dyn MetricsObserver>> {
28    current_observer_with(REGISTERED_HOOKS.get().copied())
29}
30
31/// Check whether `source` suppresses `rule_id` at 1-based `line` via registered hooks.
32///
33/// Returns `false` when no hooks have been registered via [`register_hooks`].
34pub fn has_matching_disable_directive(source: &str, line: u32, rule_id: &str) -> bool {
35    has_matching_disable_directive_with(REGISTERED_HOOKS.get().copied(), source, line, rule_id)
36}
37
38fn current_observer_with(hooks: Option<&dyn EngineHooks>) -> Option<Arc<dyn MetricsObserver>> {
39    hooks.and_then(EngineHooks::current_observer)
40}
41
42fn has_matching_disable_directive_with(
43    hooks: Option<&dyn EngineHooks>,
44    source: &str,
45    line: u32,
46    rule_id: &str,
47) -> bool {
48    hooks.is_some_and(|hooks| hooks.has_matching_disable_directive(source, line, rule_id))
49}
50
51#[cfg(test)]
52pub(crate) mod test_observer;
53#[cfg(test)]
54mod tests;