Skip to main content

rustfs_utils/
logging.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16use std::sync::OnceLock;
17use std::sync::atomic::{AtomicU64, Ordering};
18
19/// Bounds a repetitive diagnostic without changing its underlying counters.
20/// Each emitted event includes the number suppressed since the previous one.
21pub struct LogThrottle {
22    interval_ms: u64,
23    last_ms: AtomicU64,
24    suppressed: AtomicU64,
25}
26
27impl LogThrottle {
28    pub const fn new(interval_ms: u64) -> Self {
29        Self {
30            interval_ms,
31            last_ms: AtomicU64::new(u64::MAX),
32            suppressed: AtomicU64::new(0),
33        }
34    }
35
36    pub fn claim(&self) -> Option<u64> {
37        static ANCHOR: OnceLock<std::time::Instant> = OnceLock::new();
38        let now = ANCHOR.get_or_init(std::time::Instant::now).elapsed().as_millis();
39        self.claim_at(u64::try_from(now).unwrap_or(u64::MAX - 1))
40    }
41
42    fn claim_at(&self, now: u64) -> Option<u64> {
43        let last = self.last_ms.load(Ordering::Relaxed);
44        if (last == u64::MAX || now.saturating_sub(last) >= self.interval_ms)
45            && self
46                .last_ms
47                .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
48                .is_ok()
49        {
50            Some(self.suppressed.swap(0, Ordering::Relaxed))
51        } else {
52            self.suppressed.fetch_add(1, Ordering::Relaxed);
53            None
54        }
55    }
56}
57
58#[derive(Clone, Copy)]
59pub struct MaskedAccessKey<'a>(pub &'a str);
60
61impl fmt::Display for MaskedAccessKey<'_> {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        let value = self.0;
64        if value.is_empty() {
65            return Ok(());
66        }
67
68        let chars: Vec<char> = value.chars().collect();
69        match chars.len() {
70            0 => Ok(()),
71            1..=4 => f.write_str("***"),
72            5..=8 => write!(f, "{}***{}", chars[0], chars[chars.len() - 1]),
73            len => {
74                for ch in &chars[..4] {
75                    write!(f, "{ch}")?;
76                }
77                f.write_str("***")?;
78                for ch in &chars[len - 4..] {
79                    write!(f, "{ch}")?;
80                }
81                Ok(())
82            }
83        }
84    }
85}
86
87impl fmt::Debug for MaskedAccessKey<'_> {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        fmt::Display::fmt(self, f)
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::{LogThrottle, MaskedAccessKey};
96
97    #[test]
98    fn log_throttle_emits_once_per_interval_and_reports_suppression() {
99        let throttle = LogThrottle::new(5_000);
100        assert_eq!(throttle.claim_at(0), Some(0));
101        assert_eq!(throttle.claim_at(1), None);
102        assert_eq!(throttle.claim_at(4_999), None);
103        assert_eq!(throttle.claim_at(5_000), Some(2));
104        assert_eq!(throttle.claim_at(5_001), None);
105    }
106
107    #[test]
108    fn log_throttle_allows_only_one_concurrent_claim() {
109        let throttle = LogThrottle::new(5_000);
110        let reported = std::thread::scope(|scope| {
111            let threads: Vec<_> = (0..16).map(|_| scope.spawn(|| throttle.claim_at(0))).collect();
112            let emitted: Vec<_> = threads
113                .into_iter()
114                .filter_map(|thread| thread.join().expect("claim worker"))
115                .collect();
116            assert_eq!(emitted.len(), 1);
117            emitted[0]
118        });
119        assert_eq!(reported + throttle.claim_at(5_000).expect("next window"), 15);
120    }
121
122    #[test]
123    fn masks_short_values() {
124        assert_eq!(MaskedAccessKey("").to_string(), "");
125        assert_eq!(MaskedAccessKey("a").to_string(), "***");
126        assert_eq!(MaskedAccessKey("abcd").to_string(), "***");
127        assert_eq!(MaskedAccessKey("abcde").to_string(), "a***e");
128        assert_eq!(MaskedAccessKey("abcdefgh").to_string(), "a***h");
129    }
130
131    #[test]
132    fn masks_long_values() {
133        assert_eq!(MaskedAccessKey("AKIAIOSFODNN7EXAMPLE").to_string(), "AKIA***MPLE");
134        assert_eq!(format!("{:?}", MaskedAccessKey("keystone:user-1234")), "keys***1234");
135    }
136}