Skip to main content

halephant_core/clients/
mod.rs

1//! Client registry — tracks every accepted client connection from accept
2//! through cleanup, independent of the server-side connection pool.
3//!
4//! `ClientRegistry` is the source of truth for "who is currently connected
5//! to halephant and what are they doing". It is consumed by:
6//!
7//! - the admin HTTP API (`/admin/clients`) for operator introspection,
8//! - the `halephant.client.connections` observable gauge for dashboards,
9//! - (in a future phase) the checkout wait-queue integration, so the
10//!   per-client state can flip to [`ClientState::Waiting`] while a client
11//!   is blocked on pool capacity.
12//!
13//! Registration is RAII: the proxy task calls [`ClientRegistry::register`]
14//! once, holds the returned [`ClientGuard`] for its entire lifetime, and
15//! the entry is removed when the guard drops. State transitions flow
16//! through `&ClientGuard` so the guard can be passed by reference down
17//! the call stack without ownership gymnastics.
18
19use std::collections::HashMap;
20use std::net::SocketAddr;
21use std::sync::Arc;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::time::Instant;
24
25use parking_lot::Mutex;
26
27// ---------------------------------------------------------------------------
28// Types
29// ---------------------------------------------------------------------------
30
31/// Stable identifier for a client connection within a single halephant
32/// process. Monotonically increasing; wraps after 2^64 connections.
33#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
34pub struct ClientId(u64);
35
36impl ClientId {
37    /// The underlying numeric value. Used for trace span attributes and
38    /// admin JSON output.
39    #[must_use]
40    pub fn as_u64(self) -> u64 {
41        self.0
42    }
43}
44
45impl std::fmt::Display for ClientId {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        self.0.fmt(f)
48    }
49}
50
51/// High-level phase a client is in at a point in time. Used for admin
52/// display and for counting clients by state in the metrics gauge.
53///
54/// `Waiting` and `InTransaction` are defined now but only transitioned to
55/// in later phases — Phase 1 only exercises the `Negotiating → Authenticating
56/// → Idle` path.
57#[derive(Clone, Copy, Debug, Eq, PartialEq)]
58pub enum ClientState {
59    /// Pre-startup: reading the initial message, handling SSL or cancel
60    /// requests.
61    Negotiating,
62    /// SCRAM exchange is in progress.
63    Authenticating,
64    /// Connected and ready; either between transactions (transaction mode)
65    /// or holding an open session (session mode).
66    Idle,
67    /// Actively forwarding inside a transaction. Reserved for Phase 2.
68    InTransaction,
69    /// Blocked on pool checkout waiting for a server connection to become
70    /// available. Reserved for Phase 2.
71    Waiting,
72}
73
74impl ClientState {
75    /// Short lowercase identifier used as a metric attribute value and in
76    /// admin JSON output.
77    #[must_use]
78    pub fn as_str(self) -> &'static str {
79        match self {
80            ClientState::Negotiating => "negotiating",
81            ClientState::Authenticating => "authenticating",
82            ClientState::Idle => "idle",
83            ClientState::InTransaction => "in_transaction",
84            ClientState::Waiting => "waiting",
85        }
86    }
87}
88
89/// Routing intent the client is waiting for while in
90/// [`ClientState::Waiting`]. Surfaced via `/admin/clients` so operators
91/// can see whether a client is blocked on the primary queue or a
92/// replica queue for diagnosis.
93#[derive(Clone, Copy, Debug, Eq, PartialEq)]
94pub enum WaitRole {
95    Primary,
96    Replica,
97}
98
99impl WaitRole {
100    #[must_use]
101    pub fn as_str(self) -> &'static str {
102        match self {
103            WaitRole::Primary => "primary",
104            WaitRole::Replica => "replica",
105        }
106    }
107}
108
109/// The `(database, user, role)` triple a client is blocked on. Only
110/// populated while the client is in [`ClientState::Waiting`]; cleared
111/// on wakeup (whether the wake succeeds or times out).
112#[derive(Clone, Debug)]
113pub struct WaitTarget {
114    pub database: String,
115    pub user: String,
116    pub role: WaitRole,
117}
118
119/// Snapshot of one client's state at a point in time. Returned by
120/// [`ClientRegistry::snapshot`]; consumers serialize it themselves
121/// (admin JSON, metrics attributes) rather than relying on this crate
122/// pulling in serde.
123#[derive(Clone, Debug)]
124pub struct ClientEntry {
125    pub id: ClientId,
126    pub remote: SocketAddr,
127    pub state: ClientState,
128    pub accepted_at: Instant,
129    pub state_since: Instant,
130    pub database: Option<String>,
131    pub user: Option<String>,
132    /// Populated only while `state == Waiting` and cleared on wake.
133    pub waiting_for: Option<WaitTarget>,
134}
135
136// ---------------------------------------------------------------------------
137// Registry
138// ---------------------------------------------------------------------------
139
140/// Central tracker for all accepted client connections. Constructed once
141/// per halephant process and shared via `Arc`.
142pub struct ClientRegistry {
143    next_id: AtomicU64,
144    entries: Mutex<HashMap<ClientId, ClientEntry>>,
145}
146
147impl ClientRegistry {
148    #[must_use]
149    pub fn new() -> Self {
150        Self {
151            next_id: AtomicU64::new(1),
152            entries: Mutex::new(HashMap::new()),
153        }
154    }
155
156    /// Register a newly accepted client and return the RAII guard that
157    /// owns its entry. The initial state is [`ClientState::Negotiating`];
158    /// the caller should transition to [`ClientState::Authenticating`]
159    /// once the startup message has been parsed.
160    pub fn register(self: &Arc<Self>, remote: SocketAddr) -> ClientGuard {
161        let id = ClientId(self.next_id.fetch_add(1, Ordering::Relaxed));
162        let now = Instant::now();
163        let entry = ClientEntry {
164            id,
165            remote,
166            state: ClientState::Negotiating,
167            accepted_at: now,
168            state_since: now,
169            database: None,
170            user: None,
171            waiting_for: None,
172        };
173        {
174            let mut entries = self.entries.lock();
175            entries.insert(id, entry);
176        }
177        ClientGuard {
178            id,
179            registry: Arc::clone(self),
180        }
181    }
182
183    /// Return a clone of every currently-registered client entry. Used
184    /// by the admin `/admin/clients` handler. The lock is held only for
185    /// the duration of the clone.
186    #[must_use]
187    pub fn snapshot(&self) -> Vec<ClientEntry> {
188        let entries = self.entries.lock();
189        entries.values().cloned().collect()
190    }
191
192    /// Total number of currently-registered clients.
193    #[must_use]
194    pub fn count(&self) -> usize {
195        self.entries.lock().len()
196    }
197
198    /// Count clients by state in a single locked pass.
199    ///
200    /// Returns a fixed-size array of `(state, count)` pairs covering
201    /// every [`ClientState`] variant. Used by the
202    /// `halephant.client.connections` observable gauge — reading all
203    /// five buckets from the same snapshot keeps the gauge
204    /// self-consistent and touches the mutex exactly once per
205    /// observation cycle.
206    #[must_use]
207    pub fn counts_by_state(&self) -> [(ClientState, u64); 5] {
208        let entries = self.entries.lock();
209        let mut negotiating = 0u64;
210        let mut authenticating = 0u64;
211        let mut idle = 0u64;
212        let mut in_transaction = 0u64;
213        let mut waiting = 0u64;
214        for entry in entries.values() {
215            match entry.state {
216                ClientState::Negotiating => negotiating += 1,
217                ClientState::Authenticating => authenticating += 1,
218                ClientState::Idle => idle += 1,
219                ClientState::InTransaction => in_transaction += 1,
220                ClientState::Waiting => waiting += 1,
221            }
222        }
223        [
224            (ClientState::Negotiating, negotiating),
225            (ClientState::Authenticating, authenticating),
226            (ClientState::Idle, idle),
227            (ClientState::InTransaction, in_transaction),
228            (ClientState::Waiting, waiting),
229        ]
230    }
231}
232
233impl Default for ClientRegistry {
234    fn default() -> Self {
235        Self::new()
236    }
237}
238
239// ---------------------------------------------------------------------------
240// Guard
241// ---------------------------------------------------------------------------
242
243/// RAII handle held by the proxy task for the lifetime of a client
244/// connection. Mutating methods take `&self` so the guard can be borrowed
245/// down the call stack without propagating `&mut`.
246pub struct ClientGuard {
247    id: ClientId,
248    registry: Arc<ClientRegistry>,
249}
250
251impl ClientGuard {
252    #[must_use]
253    pub fn id(&self) -> ClientId {
254        self.id
255    }
256
257    /// Update the client's state. Records the transition time so
258    /// `state_since` can be reported in admin output.
259    pub fn set_state(&self, state: ClientState) {
260        let mut entries = self.registry.entries.lock();
261        if let Some(entry) = entries.get_mut(&self.id)
262            && entry.state != state
263        {
264            entry.state = state;
265            entry.state_since = Instant::now();
266        }
267    }
268
269    /// Record the database and upstream user for this client, typically
270    /// after parsing the PostgreSQL startup message. Both values are
271    /// exposed in admin output and can be used by trace span recording.
272    pub fn set_database_and_user(&self, database: &str, user: &str) {
273        let mut entries = self.registry.entries.lock();
274        if let Some(entry) = entries.get_mut(&self.id) {
275            entry.database = Some(database.to_owned());
276            entry.user = Some(user.to_owned());
277        }
278    }
279
280    /// Record (or clear) the wait target while this client is blocked
281    /// on a pool checkout. Set to `Some` right before transitioning to
282    /// [`ClientState::Waiting`] and to `None` on wakeup. The field is
283    /// surfaced in `/admin/clients` so operators can see exactly which
284    /// role queue a blocked client is sitting on.
285    pub fn set_waiting_for(&self, target: Option<WaitTarget>) {
286        let mut entries = self.registry.entries.lock();
287        if let Some(entry) = entries.get_mut(&self.id) {
288            entry.waiting_for = target;
289        }
290    }
291}
292
293impl Drop for ClientGuard {
294    fn drop(&mut self) {
295        let mut entries = self.registry.entries.lock();
296        entries.remove(&self.id);
297    }
298}