Skip to main content

yo_resp/dispatch/
clients.rs

1//! Every live connection, in one place any thread can read.
2//!
3//! `CLIENT INFO` only ever describes the connection asking, so it could be
4//! answered out of the session and was. `CLIENT LIST` and `CLIENT KILL` are
5//! about the other connections, and on a server with more than one thread the
6//! other connections belong to somebody else: their sessions are inside another
7//! thread's front, which this thread has no borrow of and must never take one
8//! of. So the part of a connection those two commands report is not kept in the
9//! session at all. It is kept here, in a row the connection owns and every
10//! thread can read.
11//!
12//! # Why the row is atomics and not a lock
13//!
14//! A row has exactly one writer, which is the thread the connection is on, and
15//! any number of readers, which is whoever ran `CLIENT LIST`. That is the
16//! cheapest shape a shared thing can have: a relaxed store is an ordinary store
17//! on every machine yo runs on, so the connection pays a store it was paying
18//! anyway and nothing else. A lock per connection would put an atomic exchange
19//! on the command path for a report almost nobody reads.
20//!
21//! The strings are the exception, because a string is not a word. The six of
22//! them sit behind one small lock per row, and it is taken when a name is set,
23//! when a library announces itself, and when a container command records its
24//! subcommand, none of which is a hot path. A plain command stores the index of
25//! its spec in the table and never goes near the lock.
26//!
27//! # Why the rows are a vector
28//!
29//! A connection opening pushes and a connection closing scans for its id and
30//! lifts that row out, keeping the ones behind it in the order they opened in,
31//! which is the order `CLIENT LIST` reports. That is linear in the number of
32//! clients on a disconnect, which sounds worse than it is: the same walk is what
33//! `CLIENT LIST` does, Redis keeps its clients in a list and walks it in the
34//! same places, and a server with ten thousand connections is doing ten thousand
35//! compares on a socket close and nothing on a command.
36//!
37//! # The pause is here too
38//!
39//! `CLIENT PAUSE` is not about one connection and does not touch a row, but it
40//! is the same shape of problem: one connection arms something that every other
41//! connection on every other thread has to see. It is one word on the server,
42//! read once per command, and it lives beside the rows because `CLIENT` is what
43//! writes it and what clears it.
44
45use std::sync::Arc;
46use std::sync::atomic::Ordering::{Acquire, Relaxed, Release};
47use std::sync::atomic::{AtomicI32, AtomicI64, AtomicU32, AtomicU64, AtomicUsize};
48use yo_common::lock::Lock;
49
50/// The bit in [`Client::flags`] for a connection subscribed to anything, which
51/// the report spells `P`.
52pub(super) const SUBSCRIBED: u32 = 1;
53/// A transaction is open, which the report spells `x`.
54pub(super) const IN_MULTI: u32 = 2;
55/// The socket is a Unix socket, which the report spells `U`.
56pub(super) const UNIX: u32 = 4;
57/// `CLIENT NO-EVICT ON`, which the report spells `e`.
58pub(super) const NO_EVICT: u32 = 8;
59/// `CLIENT NO-TOUCH ON`, which the report spells `T`.
60pub(super) const NO_TOUCH: u32 = 16;
61/// Somebody ran `CLIENT KILL` against this connection and the thread that owns
62/// it has not noticed yet.
63///
64/// Not one of the letters. It is in the same word because it is set by another
65/// thread and read by the owner on a path that is already loading this word.
66pub(super) const KILLED: u32 = 32;
67/// The connection sent `MONITOR` and is being fed every command, which the
68/// report spells `O`.
69///
70/// Redis flags a monitor a replica as well and reports only the `O`, because
71/// that is the letter for a replica that is a monitor rather than a real one.
72/// yo has no replicas yet, so the one bit says both things it has to say.
73pub(super) const MONITOR: u32 = 128;
74/// The thread that owns the connection has seen the kill and acted on it.
75///
76/// Set by the owner and read by the owner, so that a connection which cannot be
77/// let go of on the turn it was killed, because commands framed out of its
78/// buffer are still to run, is not counted a second time by the next turn.
79pub(super) const REAPED: u32 = 64;
80
81/// The strings a connection carries, which are the only part of a row that is
82/// not a single word.
83#[derive(Default)]
84pub(super) struct Text {
85    /// Where the client is dialling from, as `ip:port`, or the socket path with
86    /// `:0` after it for a Unix connection, which is Redis's spelling for both.
87    pub(super) peer: Vec<u8>,
88    /// The address on this side, in the same two spellings.
89    pub(super) local: Vec<u8>,
90    /// The name the client gave itself with `CLIENT SETNAME`, empty if none.
91    pub(super) name: Vec<u8>,
92    /// What `CLIENT SETINFO` was told, empty until it is told.
93    pub(super) lib_name: Vec<u8>,
94    pub(super) lib_ver: Vec<u8>,
95    /// The subcommand of the last command, when it had one.
96    pub(super) sub: Vec<u8>,
97}
98
99/// One connection, as everybody except the connection itself sees it.
100///
101/// Built when the connection is accepted and dropped when the last reader lets
102/// go of it, which is why it is behind an [`Arc`] rather than living in the
103/// table: a `CLIENT LIST` copies the handles out under the lock and then formats
104/// them with the lock let go of, and a connection that closes in between leaves
105/// a row that is still readable rather than a dangling one.
106pub struct Client {
107    /// The client id, which is what `CLIENT KILL ID` names and what never comes
108    /// round again.
109    pub(super) id: u64,
110    /// Which connection slot on which thread's front, so that a kill can be
111    /// carried out by the thread that owns it.
112    ///
113    /// The slot is reused and the id is not, which is why whoever acts on this
114    /// pair checks the id back against the front before it does anything.
115    pub(super) conn: AtomicU32,
116    pub(super) thread: AtomicUsize,
117    /// When the connection was accepted, for `age`.
118    pub(super) since_ms: AtomicU64,
119    /// The descriptor number, or minus one when there is no socket, which is
120    /// every embedded caller.
121    pub(super) fd: AtomicI32,
122    /// Everything about the connection that is a string.
123    pub(super) text: Lock<Text>,
124    /// When it last sent a command, for `idle`.
125    pub(super) last_ms: AtomicU64,
126    /// Bytes read off the socket and bytes handed to it.
127    pub(super) net_in: AtomicU64,
128    pub(super) net_out: AtomicU64,
129    /// Commands run for this connection, and reads that carried at least one.
130    ///
131    /// The pair behind `avg-pipeline-len-sum` and `avg-pipeline-len-cnt`, which
132    /// a client divides one by the other to see how deep the pipelining is.
133    pub(super) cmds: AtomicU64,
134    pub(super) reads: AtomicU64,
135    /// Bytes sitting in the read buffer waiting to be framed, and the room after
136    /// them, which are `qbuf` and `qbuf-free`.
137    ///
138    /// The number as of the last read or flush rather than as of this instant,
139    /// which is the only two moments it can change and so the only two worth a
140    /// store.
141    pub(super) qbuf: AtomicU64,
142    pub(super) qbuf_free: AtomicU64,
143    /// The reply buffer's room, the largest it has been at a flush, and what was
144    /// in it at the last flush, which are `rbs`, `rbp` and `obl`.
145    pub(super) rbs: AtomicU64,
146    pub(super) rbp: AtomicU64,
147    pub(super) obl: AtomicU64,
148    /// The bytes of the arguments of the last command, which is `argv-mem`.
149    pub(super) argv_mem: AtomicU64,
150    /// Where in the command table the last command was, or [`u32::MAX`] before
151    /// the connection has sent one.
152    ///
153    /// An index and not a name because an index is a word, and a word is what a
154    /// reader on another thread can take without a lock. The table outlives
155    /// every connection, so the index is good for as long as the row is.
156    pub(super) spec: AtomicU32,
157    /// Whether [`Text::sub`] is worth reading, so that the common case of a
158    /// command with no subcommand never takes the lock.
159    ///
160    /// Released after the subcommand is written and acquired before it is read,
161    /// which is what stops a reader pairing a new command with the subcommand of
162    /// an older one.
163    pub(super) has_sub: AtomicU32,
164    /// Which database, which protocol, and the four counts the report gives a
165    /// field each.
166    pub(super) db: AtomicU32,
167    pub(super) resp: AtomicU32,
168    pub(super) sub: AtomicU32,
169    pub(super) psub: AtomicU32,
170    pub(super) ssub: AtomicU32,
171    pub(super) watch: AtomicU32,
172    /// How many commands are queued behind `MULTI` and how many bytes they hold,
173    /// where minus one is Redis's spelling for no transaction at all.
174    pub(super) multi: AtomicI64,
175    pub(super) multi_mem: AtomicU64,
176    /// The letters, as bits. See the constants at the top of this module.
177    pub(super) flags: AtomicU32,
178}
179
180impl Client {
181    /// A row for a connection that has just been accepted.
182    pub(super) fn new(id: u64) -> Client {
183        Client {
184            id,
185            conn: AtomicU32::new(u32::MAX),
186            thread: AtomicUsize::new(0),
187            since_ms: AtomicU64::new(0),
188            fd: AtomicI32::new(-1),
189            text: Lock::default(),
190            last_ms: AtomicU64::new(0),
191            net_in: AtomicU64::new(0),
192            net_out: AtomicU64::new(0),
193            cmds: AtomicU64::new(0),
194            reads: AtomicU64::new(0),
195            qbuf: AtomicU64::new(0),
196            qbuf_free: AtomicU64::new(0),
197            rbs: AtomicU64::new(0),
198            rbp: AtomicU64::new(0),
199            obl: AtomicU64::new(0),
200            argv_mem: AtomicU64::new(0),
201            spec: AtomicU32::new(u32::MAX),
202            has_sub: AtomicU32::new(0),
203            db: AtomicU32::new(0),
204            resp: AtomicU32::new(2),
205            sub: AtomicU32::new(0),
206            psub: AtomicU32::new(0),
207            ssub: AtomicU32::new(0),
208            watch: AtomicU32::new(0),
209            multi: AtomicI64::new(-1),
210            multi_mem: AtomicU64::new(0),
211            flags: AtomicU32::new(0),
212        }
213    }
214
215    /// Turn one of the flag bits on or off.
216    ///
217    /// A load, a mask and a store rather than a fetch and modify, which is sound
218    /// because the only bit another thread writes is [`KILLED`] and it is only
219    /// ever turned on. The worst a lost update can do is leave a kill to the next
220    /// command, and every path that acts on a kill is one that runs again.
221    pub(super) fn set_flag(&self, bit: u32, on: bool) {
222        let was = self.flags.load(Relaxed);
223        let now = if on { was | bit } else { was & !bit };
224        if now != was {
225            self.flags.store(now, Relaxed);
226        }
227    }
228
229    /// Whether a bit is on.
230    pub(super) fn flag(&self, bit: u32) -> bool {
231        self.flags.load(Relaxed) & bit != 0
232    }
233
234    /// Ask that this connection be closed, and say whether that was news.
235    ///
236    /// Called by whichever thread ran `CLIENT KILL`, which is very often not the
237    /// thread that owns the connection. `Release` so that the owner, which
238    /// acquires the same word, is looking at a row it can act on.
239    pub(super) fn kill(&self) -> bool {
240        let was = self.flags.load(Relaxed);
241        if was & KILLED != 0 {
242            return false;
243        }
244        self.flags.store(was | KILLED, Release);
245        true
246    }
247
248    /// Whether a kill is waiting for the thread that owns this connection.
249    pub(super) fn killed(&self) -> bool {
250        self.flags.load(Acquire) & KILLED != 0
251    }
252
253    /// Note what the last command was.
254    ///
255    /// The index goes in with a `Release` when there is a subcommand, after the
256    /// subcommand itself, so a reader that acquires the pair sees them together.
257    /// A command with no subcommand does not go near the lock and does not need
258    /// the fence.
259    pub(super) fn note_command(&self, at: usize, sub: Option<&[u8]>) {
260        match sub {
261            Some(sub) => {
262                yo_alloc::allow(|| {
263                    let mut text = self.text.lock();
264                    text.sub.clear();
265                    text.sub.extend_from_slice(sub);
266                });
267                self.spec.store(at as u32, Relaxed);
268                self.has_sub.store(1, Release);
269            }
270            None => {
271                self.has_sub.store(0, Relaxed);
272                self.spec.store(at as u32, Relaxed);
273            }
274        }
275    }
276
277    /// Replace one of the strings.
278    pub(super) fn set_text(&self, pick: fn(&mut Text) -> &mut Vec<u8>, value: &[u8]) {
279        yo_alloc::allow(|| {
280            let mut text = self.text.lock();
281            let into = pick(&mut text);
282            into.clear();
283            into.extend_from_slice(value);
284        });
285    }
286}
287
288/// Every connection this server has open.
289///
290/// One list and not one per thread, because the two commands that read it want
291/// all of them in the order they were opened, and because a list per thread
292/// would still need a lock each and would give `CLIENT LIST` an interleaving to
293/// undo.
294#[derive(Default)]
295pub(super) struct Clients {
296    rows: Vec<Arc<Client>>,
297}
298
299impl Clients {
300    /// Take a new connection on.
301    fn add(&mut self, row: &Arc<Client>) {
302        yo_alloc::allow(|| self.rows.push(Arc::clone(row)));
303    }
304
305    /// Let go of one, by the id that never comes round again.
306    fn remove(&mut self, id: u64) {
307        if let Some(at) = self.rows.iter().position(|row| row.id == id) {
308            // In order rather than by swapping the last row in, because `CLIENT
309            // LIST` is read in the order the connections were opened on a real
310            // server and people do read it that way. What that costs over the
311            // swap is a move of the pointers after the hole, which is less than
312            // the scan that found the hole.
313            self.rows.remove(at);
314        }
315    }
316
317    /// How many there are.
318    fn len(&self) -> usize {
319        self.rows.len()
320    }
321}
322
323impl super::Server {
324    /// Take a connection's row into the table.
325    ///
326    /// Called once, by whoever accepted it. A session whose row was never
327    /// registered is one no other thread can see, which is every embedded
328    /// caller and every test that builds a session by hand.
329    pub(crate) fn register_client(&self, row: &Arc<Client>) {
330        row.thread.store(self.my_slot(), Relaxed);
331        self.clients.lock().add(row);
332    }
333
334    /// Take it back out, which is the connection ending.
335    pub(crate) fn forget_client(&self, id: u64) {
336        self.clients.lock().remove(id);
337    }
338
339    /// Copy out a handle to every open connection.
340    ///
341    /// The copy is the point. Formatting a report holds no lock, so a connection
342    /// that opens or closes while `CLIENT LIST` is writing does not hold up the
343    /// thread it is on, and the row of one that closed is still there to be
344    /// read.
345    pub(super) fn client_rows(&self) -> Vec<Arc<Client>> {
346        let rows = self.clients.lock();
347        yo_alloc::allow(|| rows.rows.clone())
348    }
349
350    /// How many connections are open, counted from the table.
351    #[must_use]
352    pub fn client_count(&self) -> usize {
353        self.clients.lock().len()
354    }
355
356    /// Note that `n` more connections have been asked to close.
357    pub(super) fn note_kills(&self, n: usize) {
358        if n != 0 {
359            self.kills.fetch_add(n, Release);
360        }
361    }
362
363    /// Whether any thread has a kill to carry out.
364    ///
365    /// One relaxed load, which is what every turn of every loop pays for a
366    /// command nearly nobody sends.
367    #[must_use]
368    pub fn kills(&self) -> usize {
369        self.kills.load(Acquire)
370    }
371
372    /// Note that one of them has been carried out.
373    pub fn kill_done(&self) {
374        self.kills.fetch_sub(1, Release);
375    }
376
377    /// The rows this thread owns that have been asked to close.
378    pub fn my_kills(&self) -> Vec<(u32, u64)> {
379        let mine = self.my_slot();
380        let rows = self.clients.lock();
381        yo_alloc::allow(|| {
382            rows.rows
383                .iter()
384                .filter(|row| row.thread.load(Relaxed) == mine && row.killed() && !row.flag(REAPED))
385                .inspect(|row| row.set_flag(REAPED, true))
386                .map(|row| (row.conn.load(Relaxed), row.id))
387                .collect()
388        })
389    }
390
391    /// Hold commands until `until_ms`, either all of them or only the writes.
392    ///
393    /// A pause already running is not replaced, it is widened. The later of the
394    /// two deadlines wins and the stricter of the two modes wins, so a client
395    /// that asked for everything to stop cannot have that undone by another
396    /// client asking for only the writes to stop. That is Redis's rule and it is
397    /// the one that makes the command safe to use for a failover, which is what
398    /// it is for.
399    ///
400    /// A pause whose deadline has already gone by counts as no pause, so the
401    /// widening only ever looks at one that is still running.
402    pub fn pause(&self, until_ms: u64, all: bool) {
403        // The deadline shares the word with the mode bit, so it has one bit less
404        // than a `u64` to sit in. A pause of a hundred and forty million years
405        // is the same as one of two hundred and eighty for everybody who has to
406        // live through it.
407        let until_ms = until_ms.min(u64::MAX >> 1);
408        let want = (until_ms << 1) | u64::from(all);
409        let mut have = self.pause.load(Relaxed);
410        loop {
411            let live = have != 0 && (have >> 1) > self.now_ms();
412            let next = if live {
413                ((have >> 1).max(until_ms) << 1) | (have & 1) | u64::from(all)
414            } else {
415                want
416            };
417            match self
418                .pause
419                .compare_exchange_weak(have, next, Release, Relaxed)
420            {
421                Ok(_) => return,
422                Err(seen) => have = seen,
423            }
424        }
425    }
426
427    /// Let everybody go, which is `CLIENT UNPAUSE`.
428    pub fn unpause(&self) {
429        self.pause.store(0, Release);
430    }
431
432    /// Whether commands are being held right now, and whether that is all of
433    /// them.
434    ///
435    /// `None` is the answer on a server nobody has paused, and it costs one
436    /// relaxed load and a test against zero, which is what every command pays.
437    /// The deadline is only read on a server where somebody has.
438    #[must_use]
439    pub fn paused(&self, now_ms: u64) -> Option<bool> {
440        let word = self.pause.load(Relaxed);
441        if word == 0 || (word >> 1) <= now_ms {
442            return None;
443        }
444        Some(word & 1 == 1)
445    }
446
447    /// When the pause runs out, in milliseconds, or zero if none is armed.
448    ///
449    /// Read by a test rather than by the command path, which asks the question
450    /// above instead.
451    #[must_use]
452    pub fn pause_ends(&self) -> u64 {
453        self.pause.load(Relaxed) >> 1
454    }
455}