Skip to main content

redis_tower_commands/
bloom.rs

1//! RedisBloom Bloom-filter and Cuckoo-filter commands.
2//!
3//! Available with the `bloom` feature (included by `stack`) and requiring the
4//! RedisBloom module on the server. Add/existence commands return booleans or
5//! boolean vectors; reserve/info/dump commands have command-specific typed
6//! replies.
7//!
8//! ```
9//! use redis_tower_commands::BfAdd;
10//! use redis_tower_core::Command;
11//!
12//! let command = BfAdd::new("seen", "item:1");
13//! assert_eq!(command.name(), "BF.ADD");
14//! ```
15//!
16//! See the [command cookbook] for feature and server prerequisites.
17//!
18//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#feature-gated-and-versioned-families
19
20use crate::CommandArg;
21use bytes::Bytes;
22use redis_tower_core::{Command, Frame, RedisError};
23use redis_tower_protocol::helpers::{array, bulk};
24
25// ---------------------------------------------------------------------------
26// Helper: parse an array of integers as Vec<bool>
27// ---------------------------------------------------------------------------
28
29fn parse_bool_array(frame: Frame) -> Result<Vec<bool>, RedisError> {
30    match frame {
31        Frame::Array(Some(frames)) => frames
32            .into_iter()
33            .map(|f| match f {
34                Frame::Integer(n) => Ok(n != 0),
35                Frame::Boolean(b) => Ok(b),
36                other => Err(RedisError::UnexpectedResponse {
37                    expected: "integer or boolean",
38                    actual: format!("{other:?}"),
39                }),
40            })
41            .collect(),
42        other => Err(RedisError::UnexpectedResponse {
43            expected: "array",
44            actual: format!("{other:?}"),
45        }),
46    }
47}
48
49// ===========================================================================
50// Bloom filter commands
51// ===========================================================================
52
53/// BF.ADD key item
54///
55/// Adds an item to the Bloom filter at `key`. Returns `true` if the item was
56/// newly added, `false` if it may have existed previously.
57#[derive(Clone)]
58pub struct BfAdd {
59    key: CommandArg,
60    item: CommandArg,
61}
62
63impl BfAdd {
64    /// Create a new [`BfAdd`] command.
65    pub fn new(key: impl Into<CommandArg>, item: impl Into<CommandArg>) -> Self {
66        Self {
67            key: key.into(),
68            item: item.into(),
69        }
70    }
71}
72
73impl Command for BfAdd {
74    type Response = bool;
75
76    fn to_frame(&self) -> Frame {
77        array(vec![bulk("BF.ADD"), bulk(&self.key), bulk(&self.item)])
78    }
79
80    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
81        match frame {
82            Frame::Integer(n) => Ok(n != 0),
83            Frame::Boolean(b) => Ok(b),
84            other => Err(RedisError::UnexpectedResponse {
85                expected: "integer or boolean",
86                actual: format!("{other:?}"),
87            }),
88        }
89    }
90
91    fn name(&self) -> &str {
92        "BF.ADD"
93    }
94}
95
96/// BF.EXISTS key item
97///
98/// Checks whether an item may exist in the Bloom filter at `key`.
99#[derive(Clone)]
100pub struct BfExists {
101    key: CommandArg,
102    item: CommandArg,
103}
104
105impl BfExists {
106    /// Create a new [`BfExists`] command.
107    pub fn new(key: impl Into<CommandArg>, item: impl Into<CommandArg>) -> Self {
108        Self {
109            key: key.into(),
110            item: item.into(),
111        }
112    }
113}
114
115impl Command for BfExists {
116    type Response = bool;
117
118    fn to_frame(&self) -> Frame {
119        array(vec![bulk("BF.EXISTS"), bulk(&self.key), bulk(&self.item)])
120    }
121
122    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
123        match frame {
124            Frame::Integer(n) => Ok(n != 0),
125            Frame::Boolean(b) => Ok(b),
126            other => Err(RedisError::UnexpectedResponse {
127                expected: "integer or boolean",
128                actual: format!("{other:?}"),
129            }),
130        }
131    }
132
133    fn name(&self) -> &str {
134        "BF.EXISTS"
135    }
136
137    fn idempotent(&self) -> bool {
138        true
139    }
140}
141
142/// BF.MADD key item \[item ...\]
143///
144/// Adds one or more items to the Bloom filter at `key`. Returns a vector of
145/// booleans indicating whether each item was newly added.
146#[derive(Clone)]
147pub struct BfMAdd {
148    key: CommandArg,
149    items: Vec<CommandArg>,
150}
151
152impl BfMAdd {
153    /// Create a new [`BfMAdd`] command.
154    pub fn new(
155        key: impl Into<CommandArg>,
156        items: impl IntoIterator<Item = impl Into<CommandArg>>,
157    ) -> Self {
158        Self {
159            key: key.into(),
160            items: items.into_iter().map(Into::into).collect(),
161        }
162    }
163}
164
165impl Command for BfMAdd {
166    type Response = Vec<bool>;
167
168    fn to_frame(&self) -> Frame {
169        let mut args = vec![bulk("BF.MADD"), bulk(&self.key)];
170        for item in &self.items {
171            args.push(bulk(item));
172        }
173        array(args)
174    }
175
176    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
177        parse_bool_array(frame)
178    }
179
180    fn name(&self) -> &str {
181        "BF.MADD"
182    }
183}
184
185/// BF.MEXISTS key item \[item ...\]
186///
187/// Checks whether one or more items may exist in the Bloom filter at `key`.
188#[derive(Clone)]
189pub struct BfMExists {
190    key: CommandArg,
191    items: Vec<CommandArg>,
192}
193
194impl BfMExists {
195    /// Create a new [`BfMExists`] command.
196    pub fn new(
197        key: impl Into<CommandArg>,
198        items: impl IntoIterator<Item = impl Into<CommandArg>>,
199    ) -> Self {
200        Self {
201            key: key.into(),
202            items: items.into_iter().map(Into::into).collect(),
203        }
204    }
205}
206
207impl Command for BfMExists {
208    type Response = Vec<bool>;
209
210    fn to_frame(&self) -> Frame {
211        let mut args = vec![bulk("BF.MEXISTS"), bulk(&self.key)];
212        for item in &self.items {
213            args.push(bulk(item));
214        }
215        array(args)
216    }
217
218    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
219        parse_bool_array(frame)
220    }
221
222    fn name(&self) -> &str {
223        "BF.MEXISTS"
224    }
225
226    fn idempotent(&self) -> bool {
227        true
228    }
229}
230
231/// BF.RESERVE key error_rate capacity \[EXPANSION expansion\] \[NONSCALING\]
232///
233/// Creates an empty Bloom filter with the given error rate and initial
234/// capacity.
235#[derive(Clone)]
236pub struct BfReserve {
237    key: CommandArg,
238    error_rate: f64,
239    capacity: i64,
240    expansion: Option<i64>,
241    nonscaling: bool,
242}
243
244impl BfReserve {
245    /// Create a new [`BfReserve`] command.
246    pub fn new(key: impl Into<CommandArg>, error_rate: f64, capacity: i64) -> Self {
247        Self {
248            key: key.into(),
249            error_rate,
250            capacity,
251            expansion: None,
252            nonscaling: false,
253        }
254    }
255
256    /// Set the expansion factor for sub-filters.
257    pub fn expansion(mut self, expansion: i64) -> Self {
258        self.expansion = Some(expansion);
259        self
260    }
261
262    /// Prevent the filter from scaling (no additional sub-filters).
263    pub fn nonscaling(mut self) -> Self {
264        self.nonscaling = true;
265        self
266    }
267}
268
269impl Command for BfReserve {
270    type Response = ();
271
272    fn to_frame(&self) -> Frame {
273        let mut args = vec![
274            bulk("BF.RESERVE"),
275            bulk(&self.key),
276            bulk(self.error_rate.to_string()),
277            bulk(self.capacity.to_string()),
278        ];
279        if let Some(exp) = self.expansion {
280            args.push(bulk("EXPANSION"));
281            args.push(bulk(exp.to_string()));
282        }
283        if self.nonscaling {
284            args.push(bulk("NONSCALING"));
285        }
286        array(args)
287    }
288
289    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
290        match frame {
291            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
292            other => Err(RedisError::UnexpectedResponse {
293                expected: "OK",
294                actual: format!("{other:?}"),
295            }),
296        }
297    }
298
299    fn name(&self) -> &str {
300        "BF.RESERVE"
301    }
302}
303
304/// BF.INFO key
305///
306/// Returns information about the Bloom filter at `key` as a raw Frame
307/// (key-value pairs).
308#[derive(Clone)]
309pub struct BfInfo {
310    key: CommandArg,
311}
312
313impl BfInfo {
314    /// Create a new [`BfInfo`] command.
315    pub fn new(key: impl Into<CommandArg>) -> Self {
316        Self { key: key.into() }
317    }
318}
319
320impl Command for BfInfo {
321    type Response = Frame;
322
323    fn to_frame(&self) -> Frame {
324        array(vec![bulk("BF.INFO"), bulk(&self.key)])
325    }
326
327    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
328        Ok(frame)
329    }
330
331    fn name(&self) -> &str {
332        "BF.INFO"
333    }
334
335    fn idempotent(&self) -> bool {
336        true
337    }
338}
339
340/// BF.INSERT key \[CAPACITY cap\] \[ERROR error\] \[EXPANSION exp\]
341/// \[NOCREATE\] \[NONSCALING\] ITEMS item \[item ...\]
342///
343/// Adds one or more items to a Bloom filter, creating it if it does not exist.
344/// Supports builder-style configuration.
345#[derive(Clone)]
346pub struct BfInsert {
347    key: CommandArg,
348    capacity: Option<i64>,
349    error: Option<f64>,
350    expansion: Option<i64>,
351    nocreate: bool,
352    nonscaling: bool,
353    items: Vec<CommandArg>,
354}
355
356impl BfInsert {
357    /// Create a new [`BfInsert`] command.
358    pub fn new(
359        key: impl Into<CommandArg>,
360        items: impl IntoIterator<Item = impl Into<CommandArg>>,
361    ) -> Self {
362        Self {
363            key: key.into(),
364            capacity: None,
365            error: None,
366            expansion: None,
367            nocreate: false,
368            nonscaling: false,
369            items: items.into_iter().map(Into::into).collect(),
370        }
371    }
372
373    /// Set the desired capacity for auto-created filters.
374    pub fn capacity(mut self, cap: i64) -> Self {
375        self.capacity = Some(cap);
376        self
377    }
378
379    /// Set the desired error rate for auto-created filters.
380    pub fn error(mut self, error: f64) -> Self {
381        self.error = Some(error);
382        self
383    }
384
385    /// Set the expansion factor for auto-created filters.
386    pub fn expansion(mut self, exp: i64) -> Self {
387        self.expansion = Some(exp);
388        self
389    }
390
391    /// Do not create the filter if it does not exist.
392    pub fn nocreate(mut self) -> Self {
393        self.nocreate = true;
394        self
395    }
396
397    /// Prevent the auto-created filter from scaling.
398    pub fn nonscaling(mut self) -> Self {
399        self.nonscaling = true;
400        self
401    }
402}
403
404impl Command for BfInsert {
405    type Response = Vec<bool>;
406
407    fn to_frame(&self) -> Frame {
408        let mut args = vec![bulk("BF.INSERT"), bulk(&self.key)];
409        if let Some(cap) = self.capacity {
410            args.push(bulk("CAPACITY"));
411            args.push(bulk(cap.to_string()));
412        }
413        if let Some(err) = self.error {
414            args.push(bulk("ERROR"));
415            args.push(bulk(err.to_string()));
416        }
417        if let Some(exp) = self.expansion {
418            args.push(bulk("EXPANSION"));
419            args.push(bulk(exp.to_string()));
420        }
421        if self.nocreate {
422            args.push(bulk("NOCREATE"));
423        }
424        if self.nonscaling {
425            args.push(bulk("NONSCALING"));
426        }
427        args.push(bulk("ITEMS"));
428        for item in &self.items {
429            args.push(bulk(item));
430        }
431        array(args)
432    }
433
434    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
435        parse_bool_array(frame)
436    }
437
438    fn name(&self) -> &str {
439        "BF.INSERT"
440    }
441}
442
443// ===========================================================================
444// Cuckoo filter commands
445// ===========================================================================
446
447/// CF.ADD key item
448///
449/// Adds an item to the Cuckoo filter at `key`. Returns `true` if the item was
450/// successfully added.
451#[derive(Clone)]
452pub struct CfAdd {
453    key: CommandArg,
454    item: CommandArg,
455}
456
457impl CfAdd {
458    /// Create a new [`CfAdd`] command.
459    pub fn new(key: impl Into<CommandArg>, item: impl Into<CommandArg>) -> Self {
460        Self {
461            key: key.into(),
462            item: item.into(),
463        }
464    }
465}
466
467impl Command for CfAdd {
468    type Response = bool;
469
470    fn to_frame(&self) -> Frame {
471        array(vec![bulk("CF.ADD"), bulk(&self.key), bulk(&self.item)])
472    }
473
474    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
475        match frame {
476            Frame::Integer(n) => Ok(n != 0),
477            Frame::Boolean(b) => Ok(b),
478            other => Err(RedisError::UnexpectedResponse {
479                expected: "integer or boolean",
480                actual: format!("{other:?}"),
481            }),
482        }
483    }
484
485    fn name(&self) -> &str {
486        "CF.ADD"
487    }
488}
489
490/// CF.ADDNX key item
491///
492/// Adds an item to the Cuckoo filter only if it does not already exist.
493/// Returns `true` if the item was added, `false` if it may already exist.
494#[derive(Clone)]
495pub struct CfAddNx {
496    key: CommandArg,
497    item: CommandArg,
498}
499
500impl CfAddNx {
501    /// Create a new [`CfAddNx`] command.
502    pub fn new(key: impl Into<CommandArg>, item: impl Into<CommandArg>) -> Self {
503        Self {
504            key: key.into(),
505            item: item.into(),
506        }
507    }
508}
509
510impl Command for CfAddNx {
511    type Response = bool;
512
513    fn to_frame(&self) -> Frame {
514        array(vec![bulk("CF.ADDNX"), bulk(&self.key), bulk(&self.item)])
515    }
516
517    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
518        match frame {
519            Frame::Integer(n) => Ok(n != 0),
520            Frame::Boolean(b) => Ok(b),
521            other => Err(RedisError::UnexpectedResponse {
522                expected: "integer or boolean",
523                actual: format!("{other:?}"),
524            }),
525        }
526    }
527
528    fn name(&self) -> &str {
529        "CF.ADDNX"
530    }
531}
532
533/// CF.EXISTS key item
534///
535/// Checks whether an item may exist in the Cuckoo filter at `key`.
536#[derive(Clone)]
537pub struct CfExists {
538    key: CommandArg,
539    item: CommandArg,
540}
541
542impl CfExists {
543    /// Create a new [`CfExists`] command.
544    pub fn new(key: impl Into<CommandArg>, item: impl Into<CommandArg>) -> Self {
545        Self {
546            key: key.into(),
547            item: item.into(),
548        }
549    }
550}
551
552impl Command for CfExists {
553    type Response = bool;
554
555    fn to_frame(&self) -> Frame {
556        array(vec![bulk("CF.EXISTS"), bulk(&self.key), bulk(&self.item)])
557    }
558
559    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
560        match frame {
561            Frame::Integer(n) => Ok(n != 0),
562            Frame::Boolean(b) => Ok(b),
563            other => Err(RedisError::UnexpectedResponse {
564                expected: "integer or boolean",
565                actual: format!("{other:?}"),
566            }),
567        }
568    }
569
570    fn name(&self) -> &str {
571        "CF.EXISTS"
572    }
573
574    fn idempotent(&self) -> bool {
575        true
576    }
577}
578
579/// CF.MEXISTS key item \[item ...\]
580///
581/// Checks whether one or more items may exist in the Cuckoo filter at `key`.
582#[derive(Clone)]
583pub struct CfMExists {
584    key: CommandArg,
585    items: Vec<CommandArg>,
586}
587
588impl CfMExists {
589    /// Create a new [`CfMExists`] command.
590    pub fn new(
591        key: impl Into<CommandArg>,
592        items: impl IntoIterator<Item = impl Into<CommandArg>>,
593    ) -> Self {
594        Self {
595            key: key.into(),
596            items: items.into_iter().map(Into::into).collect(),
597        }
598    }
599}
600
601impl Command for CfMExists {
602    type Response = Vec<bool>;
603
604    fn to_frame(&self) -> Frame {
605        let mut args = vec![bulk("CF.MEXISTS"), bulk(&self.key)];
606        for item in &self.items {
607            args.push(bulk(item));
608        }
609        array(args)
610    }
611
612    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
613        parse_bool_array(frame)
614    }
615
616    fn name(&self) -> &str {
617        "CF.MEXISTS"
618    }
619
620    fn idempotent(&self) -> bool {
621        true
622    }
623}
624
625/// CF.DEL key item
626///
627/// Deletes an item from the Cuckoo filter at `key`. Returns `true` if the
628/// item was found and deleted, `false` otherwise.
629#[derive(Clone)]
630pub struct CfDel {
631    key: CommandArg,
632    item: CommandArg,
633}
634
635impl CfDel {
636    /// Create a new [`CfDel`] command.
637    pub fn new(key: impl Into<CommandArg>, item: impl Into<CommandArg>) -> Self {
638        Self {
639            key: key.into(),
640            item: item.into(),
641        }
642    }
643}
644
645impl Command for CfDel {
646    type Response = bool;
647
648    fn to_frame(&self) -> Frame {
649        array(vec![bulk("CF.DEL"), bulk(&self.key), bulk(&self.item)])
650    }
651
652    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
653        match frame {
654            Frame::Integer(n) => Ok(n != 0),
655            Frame::Boolean(b) => Ok(b),
656            other => Err(RedisError::UnexpectedResponse {
657                expected: "integer or boolean",
658                actual: format!("{other:?}"),
659            }),
660        }
661    }
662
663    fn name(&self) -> &str {
664        "CF.DEL"
665    }
666}
667
668/// CF.COUNT key item
669///
670/// Returns the number of times an item may be in the Cuckoo filter.
671#[derive(Clone)]
672pub struct CfCount {
673    key: CommandArg,
674    item: CommandArg,
675}
676
677impl CfCount {
678    /// Create a new [`CfCount`] command.
679    pub fn new(key: impl Into<CommandArg>, item: impl Into<CommandArg>) -> Self {
680        Self {
681            key: key.into(),
682            item: item.into(),
683        }
684    }
685}
686
687impl Command for CfCount {
688    type Response = i64;
689
690    fn to_frame(&self) -> Frame {
691        array(vec![bulk("CF.COUNT"), bulk(&self.key), bulk(&self.item)])
692    }
693
694    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
695        match frame {
696            Frame::Integer(n) => Ok(n),
697            other => Err(RedisError::UnexpectedResponse {
698                expected: "integer",
699                actual: format!("{other:?}"),
700            }),
701        }
702    }
703
704    fn name(&self) -> &str {
705        "CF.COUNT"
706    }
707
708    fn idempotent(&self) -> bool {
709        true
710    }
711}
712
713/// CF.RESERVE key capacity \[BUCKETSIZE size\] \[MAXITERATIONS iter\]
714/// \[EXPANSION exp\]
715///
716/// Creates an empty Cuckoo filter with the given capacity.
717#[derive(Clone)]
718pub struct CfReserve {
719    key: CommandArg,
720    capacity: i64,
721    bucketsize: Option<i64>,
722    maxiterations: Option<i64>,
723    expansion: Option<i64>,
724}
725
726impl CfReserve {
727    /// Create a new [`CfReserve`] command.
728    pub fn new(key: impl Into<CommandArg>, capacity: i64) -> Self {
729        Self {
730            key: key.into(),
731            capacity,
732            bucketsize: None,
733            maxiterations: None,
734            expansion: None,
735        }
736    }
737
738    /// Set the number of items per bucket.
739    pub fn bucketsize(mut self, size: i64) -> Self {
740        self.bucketsize = Some(size);
741        self
742    }
743
744    /// Set the maximum number of cuckoo kicks before declaring failure.
745    pub fn maxiterations(mut self, iter: i64) -> Self {
746        self.maxiterations = Some(iter);
747        self
748    }
749
750    /// Set the expansion factor when the filter is full.
751    pub fn expansion(mut self, exp: i64) -> Self {
752        self.expansion = Some(exp);
753        self
754    }
755}
756
757impl Command for CfReserve {
758    type Response = ();
759
760    fn to_frame(&self) -> Frame {
761        let mut args = vec![
762            bulk("CF.RESERVE"),
763            bulk(&self.key),
764            bulk(self.capacity.to_string()),
765        ];
766        if let Some(bs) = self.bucketsize {
767            args.push(bulk("BUCKETSIZE"));
768            args.push(bulk(bs.to_string()));
769        }
770        if let Some(mi) = self.maxiterations {
771            args.push(bulk("MAXITERATIONS"));
772            args.push(bulk(mi.to_string()));
773        }
774        if let Some(exp) = self.expansion {
775            args.push(bulk("EXPANSION"));
776            args.push(bulk(exp.to_string()));
777        }
778        array(args)
779    }
780
781    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
782        match frame {
783            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
784            other => Err(RedisError::UnexpectedResponse {
785                expected: "OK",
786                actual: format!("{other:?}"),
787            }),
788        }
789    }
790
791    fn name(&self) -> &str {
792        "CF.RESERVE"
793    }
794}
795
796/// CF.INFO key
797///
798/// Returns information about the Cuckoo filter at `key` as a raw Frame.
799#[derive(Clone)]
800pub struct CfInfo {
801    key: CommandArg,
802}
803
804impl CfInfo {
805    /// Create a new [`CfInfo`] command.
806    pub fn new(key: impl Into<CommandArg>) -> Self {
807        Self { key: key.into() }
808    }
809}
810
811impl Command for CfInfo {
812    type Response = Frame;
813
814    fn to_frame(&self) -> Frame {
815        array(vec![bulk("CF.INFO"), bulk(&self.key)])
816    }
817
818    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
819        Ok(frame)
820    }
821
822    fn name(&self) -> &str {
823        "CF.INFO"
824    }
825
826    fn idempotent(&self) -> bool {
827        true
828    }
829}
830
831/// CF.INSERT key \[CAPACITY cap\] \[NOCREATE\] ITEMS item \[item ...\]
832///
833/// Adds one or more items to a Cuckoo filter, creating it if it does not
834/// exist. Returns a vector of booleans.
835#[derive(Clone)]
836pub struct CfInsert {
837    key: CommandArg,
838    capacity: Option<i64>,
839    nocreate: bool,
840    items: Vec<CommandArg>,
841}
842
843impl CfInsert {
844    /// Create a new [`CfInsert`] command.
845    pub fn new(
846        key: impl Into<CommandArg>,
847        items: impl IntoIterator<Item = impl Into<CommandArg>>,
848    ) -> Self {
849        Self {
850            key: key.into(),
851            capacity: None,
852            nocreate: false,
853            items: items.into_iter().map(Into::into).collect(),
854        }
855    }
856
857    /// Set the desired capacity for auto-created filters.
858    pub fn capacity(mut self, cap: i64) -> Self {
859        self.capacity = Some(cap);
860        self
861    }
862
863    /// Do not create the filter if it does not exist.
864    pub fn nocreate(mut self) -> Self {
865        self.nocreate = true;
866        self
867    }
868}
869
870impl Command for CfInsert {
871    type Response = Vec<bool>;
872
873    fn to_frame(&self) -> Frame {
874        let mut args = vec![bulk("CF.INSERT"), bulk(&self.key)];
875        if let Some(cap) = self.capacity {
876            args.push(bulk("CAPACITY"));
877            args.push(bulk(cap.to_string()));
878        }
879        if self.nocreate {
880            args.push(bulk("NOCREATE"));
881        }
882        args.push(bulk("ITEMS"));
883        for item in &self.items {
884            args.push(bulk(item));
885        }
886        array(args)
887    }
888
889    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
890        parse_bool_array(frame)
891    }
892
893    fn name(&self) -> &str {
894        "CF.INSERT"
895    }
896}
897
898/// CF.INSERTNX key \[CAPACITY cap\] \[NOCREATE\] ITEMS item \[item ...\]
899///
900/// Adds one or more items to a Cuckoo filter only if they do not already
901/// exist, creating the filter if needed. Returns a vector of booleans.
902#[derive(Clone)]
903pub struct CfInsertNx {
904    key: CommandArg,
905    capacity: Option<i64>,
906    nocreate: bool,
907    items: Vec<CommandArg>,
908}
909
910impl CfInsertNx {
911    /// Create a new [`CfInsertNx`] command.
912    pub fn new(
913        key: impl Into<CommandArg>,
914        items: impl IntoIterator<Item = impl Into<CommandArg>>,
915    ) -> Self {
916        Self {
917            key: key.into(),
918            capacity: None,
919            nocreate: false,
920            items: items.into_iter().map(Into::into).collect(),
921        }
922    }
923
924    /// Set the desired capacity for auto-created filters.
925    pub fn capacity(mut self, cap: i64) -> Self {
926        self.capacity = Some(cap);
927        self
928    }
929
930    /// Do not create the filter if it does not exist.
931    pub fn nocreate(mut self) -> Self {
932        self.nocreate = true;
933        self
934    }
935}
936
937impl Command for CfInsertNx {
938    type Response = Vec<bool>;
939
940    fn to_frame(&self) -> Frame {
941        let mut args = vec![bulk("CF.INSERTNX"), bulk(&self.key)];
942        if let Some(cap) = self.capacity {
943            args.push(bulk("CAPACITY"));
944            args.push(bulk(cap.to_string()));
945        }
946        if self.nocreate {
947            args.push(bulk("NOCREATE"));
948        }
949        args.push(bulk("ITEMS"));
950        for item in &self.items {
951            args.push(bulk(item));
952        }
953        array(args)
954    }
955
956    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
957        parse_bool_array(frame)
958    }
959
960    fn name(&self) -> &str {
961        "CF.INSERTNX"
962    }
963}
964
965// ---------------------------------------------------------------------------
966// Cardinality and chunked dump/restore (filter migration)
967// ---------------------------------------------------------------------------
968
969/// Parse a `BF.SCANDUMP` / `CF.SCANDUMP` reply: a two-element array of the next
970/// iterator (`0` when the dump is complete) and the binary chunk for this step.
971fn parse_scandump(frame: Frame) -> Result<(u64, Bytes), RedisError> {
972    match frame {
973        Frame::Array(Some(items)) if items.len() == 2 => {
974            let mut it = items.into_iter();
975            let iterator = match it.next() {
976                Some(Frame::Integer(n)) => n as u64,
977                other => {
978                    return Err(RedisError::UnexpectedResponse {
979                        expected: "integer iterator",
980                        actual: format!("{other:?}"),
981                    });
982                }
983            };
984            let chunk = match it.next() {
985                Some(Frame::BulkString(Some(data))) => data,
986                Some(Frame::BulkString(None)) | Some(Frame::Null) => Bytes::new(),
987                other => {
988                    return Err(RedisError::UnexpectedResponse {
989                        expected: "bulk chunk",
990                        actual: format!("{other:?}"),
991                    });
992                }
993            };
994            Ok((iterator, chunk))
995        }
996        other => Err(RedisError::UnexpectedResponse {
997            expected: "two-element array",
998            actual: format!("{other:?}"),
999        }),
1000    }
1001}
1002
1003/// BF.CARD key
1004///
1005/// Returns the cardinality of the Bloom filter at `key` -- the number of items
1006/// that have been added. Returns `0` if the key does not exist.
1007#[derive(Clone)]
1008pub struct BfCard {
1009    key: CommandArg,
1010}
1011
1012impl BfCard {
1013    /// Create a new [`BfCard`] command.
1014    pub fn new(key: impl Into<CommandArg>) -> Self {
1015        Self { key: key.into() }
1016    }
1017}
1018
1019impl Command for BfCard {
1020    type Response = i64;
1021
1022    fn to_frame(&self) -> Frame {
1023        array(vec![bulk("BF.CARD"), bulk(&self.key)])
1024    }
1025
1026    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1027        match frame {
1028            Frame::Integer(n) => Ok(n),
1029            other => Err(RedisError::UnexpectedResponse {
1030                expected: "integer",
1031                actual: format!("{other:?}"),
1032            }),
1033        }
1034    }
1035
1036    fn name(&self) -> &str {
1037        "BF.CARD"
1038    }
1039
1040    fn idempotent(&self) -> bool {
1041        true
1042    }
1043}
1044
1045/// BF.SCANDUMP key iterator
1046///
1047/// Begins or continues an incremental save of the Bloom filter at `key`. Start
1048/// with iterator `0`; each call returns `(next_iterator, chunk)`. A returned
1049/// iterator of `0` signals the dump is complete. Replay the chunks into another
1050/// server with [`BfLoadChunk`] to migrate a filter.
1051///
1052/// # Example
1053///
1054/// ```no_run
1055/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1056/// use redis_tower_commands::{BfLoadChunk, BfScanDump};
1057/// use redis_tower_core::RedisConnection;
1058///
1059/// let mut src = RedisConnection::connect("127.0.0.1:6379").await?;
1060/// let mut dst = RedisConnection::connect("127.0.0.1:6380").await?;
1061///
1062/// let mut iter = 0;
1063/// loop {
1064///     let (next, chunk) = src.execute(BfScanDump::new("filter", iter)).await?;
1065///     if next == 0 {
1066///         break;
1067///     }
1068///     dst.execute(BfLoadChunk::new("filter", next, chunk)).await?;
1069///     iter = next;
1070/// }
1071/// # Ok(())
1072/// # }
1073/// ```
1074#[derive(Clone)]
1075pub struct BfScanDump {
1076    key: CommandArg,
1077    iterator: u64,
1078}
1079
1080impl BfScanDump {
1081    /// Create a new [`BfScanDump`] command.
1082    pub fn new(key: impl Into<CommandArg>, iterator: u64) -> Self {
1083        Self {
1084            key: key.into(),
1085            iterator,
1086        }
1087    }
1088}
1089
1090impl Command for BfScanDump {
1091    type Response = (u64, Bytes);
1092
1093    fn to_frame(&self) -> Frame {
1094        array(vec![
1095            bulk("BF.SCANDUMP"),
1096            bulk(&self.key),
1097            bulk(self.iterator.to_string()),
1098        ])
1099    }
1100
1101    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1102        parse_scandump(frame)
1103    }
1104
1105    fn name(&self) -> &str {
1106        "BF.SCANDUMP"
1107    }
1108
1109    fn idempotent(&self) -> bool {
1110        true
1111    }
1112}
1113
1114/// BF.LOADCHUNK key iterator data
1115///
1116/// Restores a chunk previously produced by [`BfScanDump`]. Call once per chunk,
1117/// in iteration order, to rebuild a Bloom filter on another server.
1118#[derive(Clone)]
1119pub struct BfLoadChunk {
1120    key: CommandArg,
1121    iterator: u64,
1122    data: Bytes,
1123}
1124
1125impl BfLoadChunk {
1126    /// Create a new [`BfLoadChunk`] command.
1127    pub fn new(key: impl Into<CommandArg>, iterator: u64, data: impl Into<Bytes>) -> Self {
1128        Self {
1129            key: key.into(),
1130            iterator,
1131            data: data.into(),
1132        }
1133    }
1134}
1135
1136impl Command for BfLoadChunk {
1137    type Response = ();
1138
1139    fn to_frame(&self) -> Frame {
1140        array(vec![
1141            bulk("BF.LOADCHUNK"),
1142            bulk(&self.key),
1143            bulk(self.iterator.to_string()),
1144            bulk(self.data.as_ref()),
1145        ])
1146    }
1147
1148    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1149        match frame {
1150            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1151            other => Err(RedisError::UnexpectedResponse {
1152                expected: "OK",
1153                actual: format!("{other:?}"),
1154            }),
1155        }
1156    }
1157
1158    fn name(&self) -> &str {
1159        "BF.LOADCHUNK"
1160    }
1161}
1162
1163/// CF.SCANDUMP key iterator
1164///
1165/// The Cuckoo-filter counterpart of [`BfScanDump`]. Start with iterator `0`;
1166/// each call returns `(next_iterator, chunk)`, with a returned iterator of `0`
1167/// marking the end. Restore with [`CfLoadChunk`].
1168#[derive(Clone)]
1169pub struct CfScanDump {
1170    key: CommandArg,
1171    iterator: u64,
1172}
1173
1174impl CfScanDump {
1175    /// Create a new [`CfScanDump`] command.
1176    pub fn new(key: impl Into<CommandArg>, iterator: u64) -> Self {
1177        Self {
1178            key: key.into(),
1179            iterator,
1180        }
1181    }
1182}
1183
1184impl Command for CfScanDump {
1185    type Response = (u64, Bytes);
1186
1187    fn to_frame(&self) -> Frame {
1188        array(vec![
1189            bulk("CF.SCANDUMP"),
1190            bulk(&self.key),
1191            bulk(self.iterator.to_string()),
1192        ])
1193    }
1194
1195    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1196        parse_scandump(frame)
1197    }
1198
1199    fn name(&self) -> &str {
1200        "CF.SCANDUMP"
1201    }
1202
1203    fn idempotent(&self) -> bool {
1204        true
1205    }
1206}
1207
1208/// CF.LOADCHUNK key iterator data
1209///
1210/// Restores a chunk previously produced by [`CfScanDump`]. Call once per chunk,
1211/// in iteration order, to rebuild a Cuckoo filter on another server.
1212#[derive(Clone)]
1213pub struct CfLoadChunk {
1214    key: CommandArg,
1215    iterator: u64,
1216    data: Bytes,
1217}
1218
1219impl CfLoadChunk {
1220    /// Create a new [`CfLoadChunk`] command.
1221    pub fn new(key: impl Into<CommandArg>, iterator: u64, data: impl Into<Bytes>) -> Self {
1222        Self {
1223            key: key.into(),
1224            iterator,
1225            data: data.into(),
1226        }
1227    }
1228}
1229
1230impl Command for CfLoadChunk {
1231    type Response = ();
1232
1233    fn to_frame(&self) -> Frame {
1234        array(vec![
1235            bulk("CF.LOADCHUNK"),
1236            bulk(&self.key),
1237            bulk(self.iterator.to_string()),
1238            bulk(self.data.as_ref()),
1239        ])
1240    }
1241
1242    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1243        match frame {
1244            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1245            other => Err(RedisError::UnexpectedResponse {
1246                expected: "OK",
1247                actual: format!("{other:?}"),
1248            }),
1249        }
1250    }
1251
1252    fn name(&self) -> &str {
1253        "CF.LOADCHUNK"
1254    }
1255}
1256
1257#[cfg(test)]
1258mod tests {
1259    use super::*;
1260    use redis_tower_core::Command;
1261    use redis_tower_protocol::Frame;
1262    use redis_tower_protocol::helpers::{array, bulk};
1263
1264    #[test]
1265    fn idempotency_flags() {
1266        // Read-only commands are safe to retry.
1267        assert!(BfExists::new("k", "i").idempotent());
1268        // Mutating commands keep the default (false).
1269        assert!(!BfAdd::new("k", "i").idempotent());
1270    }
1271
1272    #[test]
1273    fn bf_card_to_frame() {
1274        assert_eq!(
1275            BfCard::new("k").to_frame(),
1276            array(vec![bulk("BF.CARD"), bulk("k")])
1277        );
1278        assert!(BfCard::new("k").idempotent());
1279    }
1280
1281    #[test]
1282    fn bf_card_parse_integer() {
1283        assert_eq!(
1284            BfCard::new("k").parse_response(Frame::Integer(3)).unwrap(),
1285            3
1286        );
1287    }
1288
1289    #[test]
1290    fn bf_scandump_to_frame_and_idempotent() {
1291        assert_eq!(
1292            BfScanDump::new("k", 0).to_frame(),
1293            array(vec![bulk("BF.SCANDUMP"), bulk("k"), bulk("0")])
1294        );
1295        assert!(BfScanDump::new("k", 0).idempotent());
1296    }
1297
1298    #[test]
1299    fn cf_scandump_to_frame() {
1300        assert_eq!(
1301            CfScanDump::new("k", 5).to_frame(),
1302            array(vec![bulk("CF.SCANDUMP"), bulk("k"), bulk("5")])
1303        );
1304        assert!(CfScanDump::new("k", 5).idempotent());
1305    }
1306
1307    #[test]
1308    fn scandump_parse_iterator_and_chunk() {
1309        let frame = array(vec![Frame::Integer(7), bulk("chunkdata")]);
1310        let (iter, data) = parse_scandump(frame).unwrap();
1311        assert_eq!(iter, 7);
1312        assert_eq!(&data[..], b"chunkdata");
1313    }
1314
1315    #[test]
1316    fn scandump_parse_complete_empty_chunk() {
1317        let frame = array(vec![Frame::Integer(0), Frame::BulkString(None)]);
1318        let (iter, data) = parse_scandump(frame).unwrap();
1319        assert_eq!(iter, 0);
1320        assert!(data.is_empty());
1321    }
1322
1323    #[test]
1324    fn bf_loadchunk_to_frame() {
1325        let cmd = BfLoadChunk::new("k", 7, Bytes::from_static(b"chunkdata"));
1326        assert_eq!(
1327            cmd.to_frame(),
1328            array(vec![
1329                bulk("BF.LOADCHUNK"),
1330                bulk("k"),
1331                bulk("7"),
1332                bulk("chunkdata"),
1333            ])
1334        );
1335    }
1336
1337    #[test]
1338    fn cf_loadchunk_to_frame() {
1339        let cmd = CfLoadChunk::new("k", 7, Bytes::from_static(b"data"));
1340        assert_eq!(
1341            cmd.to_frame(),
1342            array(vec![
1343                bulk("CF.LOADCHUNK"),
1344                bulk("k"),
1345                bulk("7"),
1346                bulk("data"),
1347            ])
1348        );
1349    }
1350}