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