use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard};
use std::time::{Duration, Instant};
use crate::error::{ClientError, code_name};
const PERIOD: Duration = Duration::from_secs(10);
pub(crate) struct ClientLog {
entries: Mutex<HashMap<(String, tonic::Code), Entry>>,
}
struct Entry {
last: Instant,
skipped: u64,
}
impl ClientLog {
pub(crate) fn new() -> Self {
Self {
entries: Mutex::new(HashMap::new()),
}
}
pub(crate) fn failed(&self, method: &str, error: &ClientError) {
let code = error.code();
let skipped = {
let mut entries = lock(&self.entries);
let now = Instant::now();
match entries.get_mut(&(method.to_owned(), code)) {
Some(entry) if now.duration_since(entry.last) < PERIOD => {
entry.skipped = entry.skipped.saturating_add(1);
return;
}
Some(entry) => {
entry.last = now;
entry.skipped = 0;
0
}
None => {
entries.insert(
(method.to_owned(), code),
Entry {
last: now,
skipped: 0,
},
);
0
}
}
};
tracing::warn!(
method,
code = code_name(code),
reason = error.reason(),
path = error.path(),
skipped,
"an outgoing gRPC call failed"
);
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}