Skip to main content

redis_tower_commands/
blocking.rs

1//! Blocking Redis commands.
2//!
3//! These commands hold the connection until data arrives or the timeout
4//! expires. They should NOT go through caching layers.
5//!
6//! # Multiplexed clients
7//!
8//! **Do not run blocking commands on a multiplexed client.** A multiplexed
9//! client funnels every caller through one shared connection and one pipeline
10//! worker; a blocking command (`BLPOP`, `BRPOP`, `BLMOVE`,
11//! `BZPOPMIN`/`BZPOPMAX`, or `XREAD`/`XREADGROUP` with `BLOCK`) holds that
12//! worker for its entire wait, stalling every other concurrent caller. Run
13//! blocking commands on a dedicated `RedisConnection` or a pooled connection
14//! instead. Each such command reports `is_blocking() == true`.
15//!
16//! Redis timeout shapes are command-specific: list and sorted-set blockers
17//! return `None`, while `XREAD` / `XREADGROUP` return an empty stream vector.
18//! Cancellation after dispatch also depends on the owning client. A direct
19//! `RedisConnection` or pool member quarantines its socket; an auto-pipeline
20//! worker retains the in-flight batch, consumes its replies for alignment, and
21//! can keep a still-usable socket. Blocking commands should not use that shared
22//! worker in the first place. Keep shutdown cancellation explicit.
23//!
24//! ```
25//! use redis_tower_commands::BLPop;
26//! use redis_tower_core::Command;
27//!
28//! let command = BLPop::new("jobs", 5.0);
29//! assert!(command.is_blocking());
30//! ```
31//!
32//! See the [command cookbook] for isolated blocking sessions.
33//!
34//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#streams-consumer-groups-and-blocking-reads
35
36use crate::CommandArg;
37use bytes::Bytes;
38use redis_tower_core::{Command, Frame, RedisError};
39use redis_tower_protocol::helpers::{array, bulk};
40
41/// BLPOP key \[key ...\] timeout
42///
43/// Blocking left pop. Waits until an element is available or timeout.
44/// Returns `None` on timeout, `Some((key, value))` on success.
45#[derive(Clone)]
46pub struct BLPop {
47    keys: Vec<CommandArg>,
48    timeout: f64,
49}
50
51impl BLPop {
52    /// Block on a single key. Timeout in seconds (0 = block indefinitely).
53    pub fn new(key: impl Into<CommandArg>, timeout: f64) -> Self {
54        Self {
55            keys: vec![key.into()],
56            timeout,
57        }
58    }
59
60    /// Block on multiple keys. Returns from the first key that has data.
61    pub fn keys(keys: impl IntoIterator<Item = impl Into<CommandArg>>, timeout: f64) -> Self {
62        Self {
63            keys: keys.into_iter().map(Into::into).collect(),
64            timeout,
65        }
66    }
67}
68
69impl Command for BLPop {
70    type Response = Option<(Bytes, Bytes)>;
71
72    fn to_frame(&self) -> Frame {
73        let mut args = vec![bulk("BLPOP")];
74        for key in &self.keys {
75            args.push(bulk(key));
76        }
77        args.push(bulk(self.timeout.to_string()));
78        array(args)
79    }
80
81    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
82        parse_key_value_or_null(frame)
83    }
84
85    fn name(&self) -> &str {
86        "BLPOP"
87    }
88
89    fn is_blocking(&self) -> bool {
90        true
91    }
92}
93
94/// BRPOP key \[key ...\] timeout
95///
96/// Blocking right pop. Same as BLPOP but pops from the tail.
97#[derive(Clone)]
98pub struct BRPop {
99    keys: Vec<CommandArg>,
100    timeout: f64,
101}
102
103impl BRPop {
104    /// Create a new [`BRPop`] command.
105    pub fn new(key: impl Into<CommandArg>, timeout: f64) -> Self {
106        Self {
107            keys: vec![key.into()],
108            timeout,
109        }
110    }
111
112    /// Create the [`BRPop`] command for the supplied keys.
113    pub fn keys(keys: impl IntoIterator<Item = impl Into<CommandArg>>, timeout: f64) -> Self {
114        Self {
115            keys: keys.into_iter().map(Into::into).collect(),
116            timeout,
117        }
118    }
119}
120
121impl Command for BRPop {
122    type Response = Option<(Bytes, Bytes)>;
123
124    fn to_frame(&self) -> Frame {
125        let mut args = vec![bulk("BRPOP")];
126        for key in &self.keys {
127            args.push(bulk(key));
128        }
129        args.push(bulk(self.timeout.to_string()));
130        array(args)
131    }
132
133    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
134        parse_key_value_or_null(frame)
135    }
136
137    fn name(&self) -> &str {
138        "BRPOP"
139    }
140
141    fn is_blocking(&self) -> bool {
142        true
143    }
144}
145
146/// BLMOVE source destination LEFT|RIGHT LEFT|RIGHT timeout
147///
148/// Blocking version of LMOVE.
149#[derive(Clone)]
150pub struct BLMove {
151    source: CommandArg,
152    destination: CommandArg,
153    wherefrom: ListDir,
154    whereto: ListDir,
155    timeout: f64,
156}
157
158/// Direction for blocking list move.
159#[derive(Debug, Clone, Copy)]
160pub enum ListDir {
161    /// Select the `Left` mode.
162    Left,
163    /// Select the `Right` mode.
164    Right,
165}
166
167impl ListDir {
168    fn as_str(&self) -> &str {
169        match self {
170            ListDir::Left => "LEFT",
171            ListDir::Right => "RIGHT",
172        }
173    }
174}
175
176impl BLMove {
177    /// Create a new [`BLMove`] command.
178    pub fn new(
179        source: impl Into<CommandArg>,
180        destination: impl Into<CommandArg>,
181        wherefrom: ListDir,
182        whereto: ListDir,
183        timeout: f64,
184    ) -> Self {
185        Self {
186            source: source.into(),
187            destination: destination.into(),
188            wherefrom,
189            whereto,
190            timeout,
191        }
192    }
193}
194
195impl Command for BLMove {
196    type Response = Option<Bytes>;
197
198    fn to_frame(&self) -> Frame {
199        array(vec![
200            bulk("BLMOVE"),
201            bulk(&self.source),
202            bulk(&self.destination),
203            bulk(self.wherefrom.as_str()),
204            bulk(self.whereto.as_str()),
205            bulk(self.timeout.to_string()),
206        ])
207    }
208
209    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
210        match frame {
211            Frame::BulkString(Some(data)) => Ok(Some(data)),
212            Frame::Null | Frame::BulkString(None) | Frame::Array(None) => Ok(None),
213            other => Err(RedisError::UnexpectedResponse {
214                expected: "bulk string or null",
215                actual: format!("{other:?}"),
216            }),
217        }
218    }
219
220    fn name(&self) -> &str {
221        "BLMOVE"
222    }
223
224    fn is_blocking(&self) -> bool {
225        true
226    }
227}
228
229/// BZPOPMIN key \[key ...\] timeout
230///
231/// Blocking pop of the member with the lowest score from sorted sets.
232#[derive(Clone)]
233pub struct BZPopMin {
234    keys: Vec<CommandArg>,
235    timeout: f64,
236}
237
238impl BZPopMin {
239    /// Create a new [`BZPopMin`] command.
240    pub fn new(key: impl Into<CommandArg>, timeout: f64) -> Self {
241        Self {
242            keys: vec![key.into()],
243            timeout,
244        }
245    }
246
247    /// Create the [`BZPopMin`] command for the supplied keys.
248    pub fn keys(keys: impl IntoIterator<Item = impl Into<CommandArg>>, timeout: f64) -> Self {
249        Self {
250            keys: keys.into_iter().map(Into::into).collect(),
251            timeout,
252        }
253    }
254}
255
256impl Command for BZPopMin {
257    type Response = Option<(Bytes, Bytes, f64)>;
258
259    fn to_frame(&self) -> Frame {
260        let mut args = vec![bulk("BZPOPMIN")];
261        for key in &self.keys {
262            args.push(bulk(key));
263        }
264        args.push(bulk(self.timeout.to_string()));
265        array(args)
266    }
267
268    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
269        parse_key_member_score_or_null(frame)
270    }
271
272    fn name(&self) -> &str {
273        "BZPOPMIN"
274    }
275
276    fn is_blocking(&self) -> bool {
277        true
278    }
279}
280
281/// BZPOPMAX key \[key ...\] timeout
282///
283/// Blocking pop of the member with the highest score from sorted sets.
284#[derive(Clone)]
285pub struct BZPopMax {
286    keys: Vec<CommandArg>,
287    timeout: f64,
288}
289
290impl BZPopMax {
291    /// Create a new [`BZPopMax`] command.
292    pub fn new(key: impl Into<CommandArg>, timeout: f64) -> Self {
293        Self {
294            keys: vec![key.into()],
295            timeout,
296        }
297    }
298
299    /// Create the [`BZPopMax`] command for the supplied keys.
300    pub fn keys(keys: impl IntoIterator<Item = impl Into<CommandArg>>, timeout: f64) -> Self {
301        Self {
302            keys: keys.into_iter().map(Into::into).collect(),
303            timeout,
304        }
305    }
306}
307
308impl Command for BZPopMax {
309    type Response = Option<(Bytes, Bytes, f64)>;
310
311    fn to_frame(&self) -> Frame {
312        let mut args = vec![bulk("BZPOPMAX")];
313        for key in &self.keys {
314            args.push(bulk(key));
315        }
316        args.push(bulk(self.timeout.to_string()));
317        array(args)
318    }
319
320    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
321        parse_key_member_score_or_null(frame)
322    }
323
324    fn name(&self) -> &str {
325        "BZPOPMAX"
326    }
327
328    fn is_blocking(&self) -> bool {
329        true
330    }
331}
332
333// -- Response parsing --
334
335/// Parse [key, value] or null (for BLPOP/BRPOP).
336fn parse_key_value_or_null(frame: Frame) -> Result<Option<(Bytes, Bytes)>, RedisError> {
337    match frame {
338        Frame::Null | Frame::Array(None) | Frame::BulkString(None) => Ok(None),
339        Frame::Array(Some(items)) if items.len() == 2 => {
340            let key = extract_bytes(&items[0])?;
341            let value = extract_bytes(&items[1])?;
342            Ok(Some((key, value)))
343        }
344        other => Err(RedisError::UnexpectedResponse {
345            expected: "two-element array or null",
346            actual: format!("{other:?}"),
347        }),
348    }
349}
350
351/// Parse [key, member, score] or null (for BZPOPMIN/BZPOPMAX).
352fn parse_key_member_score_or_null(frame: Frame) -> Result<Option<(Bytes, Bytes, f64)>, RedisError> {
353    match frame {
354        Frame::Null | Frame::Array(None) | Frame::BulkString(None) => Ok(None),
355        Frame::Array(Some(items)) if items.len() == 3 => {
356            let key = extract_bytes(&items[0])?;
357            let member = extract_bytes(&items[1])?;
358            let score = match &items[2] {
359                Frame::BulkString(Some(b)) => {
360                    let s = std::str::from_utf8(b).map_err(|e| RedisError::UnexpectedResponse {
361                        expected: "valid UTF-8 score",
362                        actual: e.to_string(),
363                    })?;
364                    s.parse::<f64>()
365                        .map_err(|e| RedisError::UnexpectedResponse {
366                            expected: "valid f64 score",
367                            actual: e.to_string(),
368                        })?
369                }
370                Frame::Double(d) => *d,
371                other => {
372                    return Err(RedisError::UnexpectedResponse {
373                        expected: "bulk string or double score",
374                        actual: format!("{other:?}"),
375                    });
376                }
377            };
378            Ok(Some((key, member, score)))
379        }
380        other => Err(RedisError::UnexpectedResponse {
381            expected: "three-element array or null",
382            actual: format!("{other:?}"),
383        }),
384    }
385}
386
387fn extract_bytes(frame: &Frame) -> Result<Bytes, RedisError> {
388    match frame {
389        Frame::BulkString(Some(b)) => Ok(b.clone()),
390        other => Err(RedisError::UnexpectedResponse {
391            expected: "bulk string",
392            actual: format!("{other:?}"),
393        }),
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400    use redis_tower_core::Command;
401    use redis_tower_protocol::Frame;
402    use redis_tower_protocol::helpers::{array, bulk};
403
404    #[test]
405    fn blocking_commands_report_is_blocking() {
406        assert!(BLPop::new("k", 0.0).is_blocking());
407        assert!(BRPop::new("k", 0.0).is_blocking());
408        assert!(BZPopMin::new("k", 0.0).is_blocking());
409        assert!(BZPopMax::new("k", 0.0).is_blocking());
410    }
411
412    // -- BLPop --
413
414    #[test]
415    fn blpop_single_key_to_frame() {
416        let cmd = BLPop::new("mylist", 5.0);
417        assert_eq!(
418            cmd.to_frame(),
419            array(vec![bulk("BLPOP"), bulk("mylist"), bulk("5")])
420        );
421    }
422
423    #[test]
424    fn blpop_multiple_keys_to_frame() {
425        let cmd = BLPop::keys(vec!["list1", "list2"], 0.0);
426        assert_eq!(
427            cmd.to_frame(),
428            array(vec![bulk("BLPOP"), bulk("list1"), bulk("list2"), bulk("0")])
429        );
430    }
431
432    #[test]
433    fn blpop_parse_key_value_array() {
434        let cmd = BLPop::new("mylist", 5.0);
435        let frame = Frame::Array(Some(vec![
436            Frame::BulkString(Some(Bytes::from("mylist"))),
437            Frame::BulkString(Some(Bytes::from("value1"))),
438        ]));
439        let result = cmd.parse_response(frame).unwrap();
440        assert_eq!(result, Some((Bytes::from("mylist"), Bytes::from("value1"))));
441    }
442
443    #[test]
444    fn blpop_parse_null_on_timeout() {
445        let cmd = BLPop::new("mylist", 1.0);
446        let result = cmd.parse_response(Frame::Null).unwrap();
447        assert_eq!(result, None);
448    }
449
450    #[test]
451    fn blpop_parse_null_array() {
452        let cmd = BLPop::new("mylist", 1.0);
453        let result = cmd.parse_response(Frame::Array(None)).unwrap();
454        assert_eq!(result, None);
455    }
456
457    #[test]
458    fn blpop_parse_error_on_wrong_array_size() {
459        let cmd = BLPop::new("mylist", 1.0);
460        let frame = Frame::Array(Some(vec![Frame::BulkString(Some(Bytes::from("only_one")))]));
461        assert!(cmd.parse_response(frame).is_err());
462    }
463
464    // -- BRPop --
465
466    #[test]
467    fn brpop_to_frame() {
468        let cmd = BRPop::new("mylist", 10.0);
469        assert_eq!(
470            cmd.to_frame(),
471            array(vec![bulk("BRPOP"), bulk("mylist"), bulk("10")])
472        );
473    }
474
475    #[test]
476    fn brpop_parse_key_value_array() {
477        let cmd = BRPop::new("mylist", 5.0);
478        let frame = Frame::Array(Some(vec![
479            Frame::BulkString(Some(Bytes::from("mylist"))),
480            Frame::BulkString(Some(Bytes::from("tail"))),
481        ]));
482        let result = cmd.parse_response(frame).unwrap();
483        assert_eq!(result, Some((Bytes::from("mylist"), Bytes::from("tail"))));
484    }
485
486    #[test]
487    fn brpop_parse_null_on_timeout() {
488        let cmd = BRPop::new("mylist", 1.0);
489        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
490    }
491
492    // -- BLMove --
493
494    #[test]
495    fn blmove_to_frame() {
496        let cmd = BLMove::new("src", "dst", ListDir::Left, ListDir::Right, 3.0);
497        assert_eq!(
498            cmd.to_frame(),
499            array(vec![
500                bulk("BLMOVE"),
501                bulk("src"),
502                bulk("dst"),
503                bulk("LEFT"),
504                bulk("RIGHT"),
505                bulk("3"),
506            ])
507        );
508    }
509
510    #[test]
511    fn blmove_parse_value() {
512        let cmd = BLMove::new("src", "dst", ListDir::Left, ListDir::Right, 1.0);
513        let frame = Frame::BulkString(Some(Bytes::from("moved")));
514        assert_eq!(
515            cmd.parse_response(frame).unwrap(),
516            Some(Bytes::from("moved"))
517        );
518    }
519
520    #[test]
521    fn blmove_parse_null_on_timeout() {
522        let cmd = BLMove::new("src", "dst", ListDir::Left, ListDir::Right, 1.0);
523        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
524    }
525
526    // -- BZPopMin --
527
528    #[test]
529    fn bzpopmin_to_frame() {
530        let cmd = BZPopMin::new("myzset", 0.0);
531        assert_eq!(
532            cmd.to_frame(),
533            array(vec![bulk("BZPOPMIN"), bulk("myzset"), bulk("0")])
534        );
535    }
536
537    #[test]
538    fn bzpopmin_parse_key_member_score() {
539        let cmd = BZPopMin::new("myzset", 0.0);
540        let frame = Frame::Array(Some(vec![
541            Frame::BulkString(Some(Bytes::from("myzset"))),
542            Frame::BulkString(Some(Bytes::from("member1"))),
543            Frame::BulkString(Some(Bytes::from("1.5"))),
544        ]));
545        let result = cmd.parse_response(frame).unwrap().unwrap();
546        assert_eq!(result.0, Bytes::from("myzset"));
547        assert_eq!(result.1, Bytes::from("member1"));
548        assert!((result.2 - 1.5).abs() < f64::EPSILON);
549    }
550
551    #[test]
552    fn bzpopmin_parse_null_on_timeout() {
553        let cmd = BZPopMin::new("myzset", 1.0);
554        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
555    }
556
557    #[test]
558    fn bzpopmin_parse_double_score() {
559        let cmd = BZPopMin::new("myzset", 0.0);
560        let frame = Frame::Array(Some(vec![
561            Frame::BulkString(Some(Bytes::from("myzset"))),
562            Frame::BulkString(Some(Bytes::from("member1"))),
563            Frame::Double(2.5),
564        ]));
565        let result = cmd.parse_response(frame).unwrap().unwrap();
566        assert!((result.2 - 2.5).abs() < f64::EPSILON);
567    }
568
569    // -- BZPopMax --
570
571    #[test]
572    fn bzpopmax_to_frame() {
573        let cmd = BZPopMax::keys(vec!["zs1", "zs2"], 5.0);
574        assert_eq!(
575            cmd.to_frame(),
576            array(vec![bulk("BZPOPMAX"), bulk("zs1"), bulk("zs2"), bulk("5"),])
577        );
578    }
579
580    #[test]
581    fn bzpopmax_parse_null_on_timeout() {
582        let cmd = BZPopMax::new("myzset", 1.0);
583        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
584    }
585}