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