Skip to main content

pg_bus/
stats.rs

1//! Counters for one process's bus, for metrics and debugging. Each counts
2//! from when the bus started.
3
4use std::sync::Mutex;
5use std::sync::atomic::{AtomicU64, Ordering};
6
7use crate::Position;
8
9/// A snapshot of [`Bus::stats`](crate::Bus::stats).
10#[derive(Debug, Clone, PartialEq)]
11pub struct Stats {
12    /// Subscriptions alive in this process.
13    pub subscribers: usize,
14    /// The last position the listener read.
15    pub listener_position: Position,
16    /// Messages the listener read and handed to this process's subscribers.
17    pub delivered: u64,
18    /// Queries the listener ran: backlog reads and waiting-message checks.
19    pub listener_queries: u64,
20    /// Times the listener's connection was established again.
21    pub listener_reconnects: u64,
22    /// Subscription catch-ups answered from the recent ring.
23    pub catch_ups_from_memory: u64,
24    /// Subscription catch-ups that read the backlog table.
25    pub catch_ups_from_database: u64,
26    /// Times a subscriber fell behind the live feed and caught up instead.
27    pub lagged: u64,
28    /// Messages a subscription skipped because they came out of order.
29    /// Always 0 unless something is wrong; logged as an error when not.
30    pub out_of_order: u64,
31}
32
33#[derive(Default)]
34pub(crate) struct Counters {
35    pub(crate) delivered: AtomicU64,
36    pub(crate) listener_queries: AtomicU64,
37    pub(crate) listener_reconnects: AtomicU64,
38    pub(crate) catch_ups_from_memory: AtomicU64,
39    pub(crate) catch_ups_from_database: AtomicU64,
40    pub(crate) lagged: AtomicU64,
41    pub(crate) out_of_order: AtomicU64,
42    pub(crate) listener_position: Mutex<Option<Position>>,
43}
44
45impl Counters {
46    pub(crate) fn add(counter: &AtomicU64, n: u64) {
47        counter.fetch_add(n, Ordering::Relaxed);
48    }
49
50    pub(crate) fn snapshot(&self, subscribers: usize, start: Position) -> Stats {
51        let get = |c: &AtomicU64| c.load(Ordering::Relaxed);
52        Stats {
53            subscribers,
54            listener_position: self
55                .listener_position
56                .lock()
57                .unwrap_or_else(|e| e.into_inner())
58                .unwrap_or(start),
59            delivered: get(&self.delivered),
60            listener_queries: get(&self.listener_queries),
61            listener_reconnects: get(&self.listener_reconnects),
62            catch_ups_from_memory: get(&self.catch_ups_from_memory),
63            catch_ups_from_database: get(&self.catch_ups_from_database),
64            lagged: get(&self.lagged),
65            out_of_order: get(&self.out_of_order),
66        }
67    }
68}