Skip to main content

encore/storage/redis/
commands.rs

1//! The command groups: one module per Redis data type, each holding the
2//! commands on it in three forms — `Commands`, which run now; `ReadCommands`,
3//! the ones that only read; and `Queue`, which adds them to a pipeline or a
4//! transaction.
5//!
6//! All three come from one list per group, below. A command is written once:
7//! whether it reads or writes, its name and parameters, and the Redis command
8//! it builds, with the arguments that are keys marked as such. A `blocking`
9//! command, which waits for something to pop, has no `Queue` form: it would
10//! hold up the batch's connection. Encore's parser
11//! holds the same list (`RS_TABLES.families` in `encore_parser`), which is how
12//! it knows what each call needs to be granted; a test there reads this file
13//! and fails when the two differ.
14
15use std::marker::PhantomData;
16
17use encore_sdk_core::cache::{self as core_cache, redis as rs};
18
19use super::types::{
20    FromRedisValue, Increment, Popped, PoppedMany, PoppedScored, PoppedScoredMany, ToRedisArgs,
21    Value,
22};
23use super::{redis_err, Target};
24use crate::error::{ErrCode, Error};
25
26/// A command being built: the arguments in order, the keys among them marked.
27pub(crate) struct Cmd {
28    pub(super) inner: core_cache::Command,
29}
30
31impl Cmd {
32    fn new(operation: &'static str, name: &'static str, write: bool) -> Self {
33        Self::from_core(core_cache::Command::new(operation, name, write))
34    }
35
36    pub(super) fn from_core(inner: core_cache::Command) -> Self {
37        Self { inner }
38    }
39
40    /// Appends one or more keys.
41    fn key(mut self, key: impl ToRedisArgs) -> Self {
42        for key in key.to_redis_args() {
43            self.inner = self.inner.key(key);
44        }
45        self
46    }
47
48    /// Appends one or more arguments that are not keys.
49    fn arg(mut self, arg: impl ToRedisArgs) -> Self {
50        for arg in arg.to_redis_args() {
51            self.inner = self.inner.arg(arg);
52        }
53        self
54    }
55
56    /// Has the command be `name`, its floating-point counterpart, when the
57    /// amount it adds is a float. Comes before the arguments.
58    fn or_float(self, name: &'static str, float: bool) -> Self {
59        if float {
60            Self::new(self.inner.operation(), name, self.inner.is_write())
61        } else {
62            self
63        }
64    }
65
66    /// Appends keys preceded by how many there are, as the commands that take
67    /// a variable number of keys before their other arguments want them.
68    fn numkeys(mut self, keys: impl ToRedisArgs) -> Self {
69        let keys = keys.to_redis_args();
70        self.inner = self.inner.arg(keys.len().to_string());
71        for key in keys {
72            self.inner = self.inner.key(key);
73        }
74        self
75    }
76}
77
78/// One method, in the form `$form` asks for. A command that writes has no
79/// `read` form.
80macro_rules! method {
81    (run $mode:ident; $(#[$doc:meta])* fn $name:ident<RV>($($arg:ident: $ty:ty),*) [$cmd:expr]) => {
82        $(#[$doc])*
83        pub async fn $name<RV: FromRedisValue>(&self, $($arg: $ty),*) -> Result<RV, Error> {
84            self.target.run($cmd).await
85        }
86    };
87    (run $mode:ident; $(#[$doc:meta])* fn $name:ident($($arg:ident: $ty:ty),*) -> $ret:ty [$cmd:expr]) => {
88        $(#[$doc])*
89        pub async fn $name(&self, $($arg: $ty),*) -> Result<$ret, Error> {
90            self.target.run($cmd).await
91        }
92    };
93    (run $mode:ident; $(#[$doc:meta])* fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),*) -> $ret:ty [$cmd:expr]) => {
94        $(#[$doc])*
95        pub async fn $name<$param: $bound>(&self, $($arg: $ty),*) -> Result<$ret, Error> {
96            self.target.run($cmd).await
97        }
98    };
99    (read read; $($method:tt)*) => {
100        method!(run read; $($method)*);
101    };
102    (read write; $($method:tt)*) => {};
103    // A blocking command has no queue form.
104    (@unqueued queue $mode:ident; $($method:tt)*) => {};
105    (@unqueued $form:ident $mode:ident; $($method:tt)*) => {
106        method!($form $mode; $($method)*);
107    };
108    (queue $mode:ident; $(#[$doc:meta])* fn $name:ident $(<RV>)? ($($arg:ident: $ty:ty),*) $(-> $ret:ty)? [$cmd:expr]) => {
109        $(#[$doc])*
110        pub fn $name(&mut self, $($arg: $ty),*) -> &mut Self {
111            self.queue.push($cmd);
112            self
113        }
114    };
115    (queue $mode:ident; $(#[$doc:meta])* fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),*) -> $ret:ty [$cmd:expr]) => {
116        $(#[$doc])*
117        pub fn $name<$param: $bound>(&mut self, $($arg: $ty),*) -> &mut Self {
118            self.queue.push($cmd);
119            self
120        }
121    };
122}
123
124/// Whether a command of mode `$mode` writes.
125macro_rules! writes {
126    (read) => {
127        false
128    };
129    (write) => {
130        true
131    };
132}
133
134/// A group's commands, each in the form `$form` asks for.
135macro_rules! methods {
136    ($form:ident;) => {};
137    // A blocking command: a read or a write, with no queue form.
138    (
139        $form:ident;
140        $(#[$doc:meta])*
141        blocking $mode:ident fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),* $(,)?) -> $ret:ty:
142            $wire:literal $(.$part:ident($($value:expr),*))*;
143        $($rest:tt)*
144    ) => {
145        method!(
146            @unqueued $form $mode;
147            $(#[$doc])*
148            fn $name<$param: $bound>($($arg: $ty),*) -> $ret
149            [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
150        );
151        methods!($form; $($rest)*);
152    };
153    (
154        $form:ident;
155        $(#[$doc:meta])*
156        blocking $mode:ident fn $name:ident<RV>($($arg:ident: $ty:ty),* $(,)?):
157            $wire:literal $(.$part:ident($($value:expr),*))*;
158        $($rest:tt)*
159    ) => {
160        method!(
161            @unqueued $form $mode;
162            $(#[$doc])*
163            fn $name<RV>($($arg: $ty),*)
164            [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
165        );
166        methods!($form; $($rest)*);
167    };
168    (
169        $form:ident;
170        $(#[$doc:meta])*
171        $mode:ident fn $name:ident<RV>($($arg:ident: $ty:ty),* $(,)?):
172            $wire:literal $(.$part:ident($($value:expr),*))*;
173        $($rest:tt)*
174    ) => {
175        method!(
176            $form $mode;
177            $(#[$doc])*
178            fn $name<RV>($($arg: $ty),*)
179            [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
180        );
181        methods!($form; $($rest)*);
182    };
183    (
184        $form:ident;
185        $(#[$doc:meta])*
186        $mode:ident fn $name:ident($($arg:ident: $ty:ty),* $(,)?) -> $ret:ty:
187            $wire:literal $(.$part:ident($($value:expr),*))*;
188        $($rest:tt)*
189    ) => {
190        method!(
191            $form $mode;
192            $(#[$doc])*
193            fn $name($($arg: $ty),*) -> $ret
194            [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
195        );
196        methods!($form; $($rest)*);
197    };
198    // A command generic over one of its parameters, which its reply follows.
199    (
200        $form:ident;
201        $(#[$doc:meta])*
202        $mode:ident fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),* $(,)?) -> $ret:ty:
203            $wire:literal $(.$part:ident($($value:expr),*))*;
204        $($rest:tt)*
205    ) => {
206        method!(
207            $form $mode;
208            $(#[$doc])*
209            fn $name<$param: $bound>($($arg: $ty),*) -> $ret
210            [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
211        );
212        methods!($form; $($rest)*);
213    };
214}
215
216/// A command group: a module holding its three forms.
217macro_rules! group {
218    // Without types of its own to re-export.
219    (
220        $(#[$doc:meta])*
221        group = $group:ident;
222        $(#[$first:meta])*
223        $mode:ident fn $($commands:tt)*
224    ) => {
225        group! {
226            $(#[$doc])*
227            group = $group;
228            uses {}
229            $(#[$first])*
230            $mode fn $($commands)*
231        }
232    };
233    (
234        $(#[$doc:meta])*
235        group = $group:ident;
236        uses { $($uses:item)* }
237        $($commands:tt)*
238    ) => {
239        $(#[$doc])*
240        pub mod $group {
241            #[allow(unused_imports)]
242            use super::*;
243
244            $($uses)*
245
246            /// The group's commands, run as they are called.
247            #[derive(Clone, Copy)]
248            pub struct Commands<'a> {
249                pub(in crate::storage::redis) target: Target<'a>,
250            }
251
252            /// The group's commands that only read.
253            #[derive(Clone, Copy)]
254            pub struct ReadCommands<'a> {
255                pub(in crate::storage::redis) target: Target<'a>,
256            }
257
258            /// The group's commands, queued on a pipeline or a transaction.
259            /// What each replies is read from `exec`, in the order queued.
260            pub struct Queue<'a> {
261                pub(in crate::storage::redis) queue: &'a mut crate::storage::redis::Queued,
262            }
263
264            impl Commands<'_> {
265                methods!(run; $($commands)*);
266            }
267
268            impl ReadCommands<'_> {
269                methods!(read; $($commands)*);
270            }
271
272            impl Queue<'_> {
273                methods!(queue; $($commands)*);
274            }
275        }
276    };
277}
278
279group! {
280    /// Commands that work on a key of any type.
281    group = generic;
282
283    /// Whether the key exists.
284    read fn exists(key: impl ToRedisArgs) -> bool: "EXISTS".key(key);
285    /// The seconds until the key expires: -1 if it never does, -2 if it does
286    /// not exist.
287    read fn ttl(key: impl ToRedisArgs) -> i64: "TTL".key(key);
288    /// The milliseconds until the key expires: -1 if it never does, -2 if it
289    /// does not exist.
290    read fn pttl(key: impl ToRedisArgs) -> i64: "PTTL".key(key);
291    /// The type of the value at the key: `string`, `list`, `set`, `zset`,
292    /// `hash`, `stream`, or `none` if it does not exist.
293    read fn key_type(key: impl ToRedisArgs) -> String: "TYPE".key(key);
294    /// The Unix time, in seconds, the key expires at: -1 if it never does, -2
295    /// if it does not exist.
296    read fn expire_time(key: impl ToRedisArgs) -> i64: "EXPIRETIME".key(key);
297
298    /// Deletes the keys, returning how many existed.
299    write fn del(keys: impl ToRedisArgs) -> u64: "DEL".key(keys);
300    /// Deletes the keys, reclaiming their memory in the background. Returns
301    /// how many existed.
302    write fn unlink(keys: impl ToRedisArgs) -> u64: "UNLINK".key(keys);
303    /// Has the key expire in `seconds`. `false` if it does not exist.
304    write fn expire(key: impl ToRedisArgs, seconds: i64) -> bool: "EXPIRE".key(key).arg(seconds);
305    /// Has the key expire in `milliseconds`. `false` if it does not exist.
306    write fn pexpire(key: impl ToRedisArgs, milliseconds: i64) -> bool:
307        "PEXPIRE".key(key).arg(milliseconds);
308    /// Has the key expire at a Unix time, in seconds. `false` if it does not
309    /// exist.
310    write fn expire_at(key: impl ToRedisArgs, timestamp: i64) -> bool:
311        "EXPIREAT".key(key).arg(timestamp);
312    /// Removes the key's expiry. `false` if it had none, or does not exist.
313    write fn persist(key: impl ToRedisArgs) -> bool: "PERSIST".key(key);
314    /// Renames the key, replacing `new_key` if it exists.
315    write fn rename(key: impl ToRedisArgs, new_key: impl ToRedisArgs) -> ():
316        "RENAME".key(key).key(new_key);
317    /// Renames the key unless `new_key` exists. `false` if it does.
318    write fn rename_nx(key: impl ToRedisArgs, new_key: impl ToRedisArgs) -> bool:
319        "RENAMENX".key(key).key(new_key);
320    /// Copies the value at `source` to `destination`. `false` if `destination`
321    /// exists.
322    write fn copy(source: impl ToRedisArgs, destination: impl ToRedisArgs) -> bool:
323        "COPY".key(source).key(destination);
324    /// Marks the keys as used just now, returning how many exist.
325    write fn touch(keys: impl ToRedisArgs) -> u64: "TOUCH".key(keys);
326}
327
328group! {
329    /// Commands on strings, which is what a plain value is.
330    group = string;
331
332    /// The value at the key. Read as an `Option` to tell a missing key apart.
333    read fn get<RV>(key: impl ToRedisArgs): "GET".key(key);
334    /// The values at the keys, in order, each missing one as `None`.
335    read fn mget<RV>(keys: impl ToRedisArgs): "MGET".key(keys);
336    /// The length of the value at the key, in bytes.
337    read fn strlen(key: impl ToRedisArgs) -> u64: "STRLEN".key(key);
338    /// The part of the value from byte `from` to byte `to`, inclusive.
339    /// Negative offsets count from the end.
340    read fn getrange<RV>(key: impl ToRedisArgs, from: isize, to: isize):
341        "GETRANGE".key(key).arg(from).arg(to);
342
343    /// Sets the key to the value.
344    write fn set(key: impl ToRedisArgs, value: impl ToRedisArgs) -> (): "SET".key(key).arg(value);
345    /// Sets the key to the value, expiring in `seconds`.
346    write fn set_ex(key: impl ToRedisArgs, value: impl ToRedisArgs, seconds: u64) -> ():
347        "SETEX".key(key).arg(seconds).arg(value);
348    /// Sets the key to the value unless the key exists. `false` if it does.
349    write fn set_nx(key: impl ToRedisArgs, value: impl ToRedisArgs) -> bool:
350        "SETNX".key(key).arg(value);
351    /// Sets the key to the value as `options` say: only if it exists or does
352    /// not, with an expiry, returning the old value.
353    write fn set_options<RV>(key: impl ToRedisArgs, value: impl ToRedisArgs, options: SetOptions):
354        "SET".key(key).arg(value).arg(options);
355    /// Sets each key to its value, all at once.
356    write fn mset(items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> (): "MSET".pairs(items);
357    /// Sets each key to its value unless any of the keys exists. `false` if
358    /// one does, in which case none is set.
359    write fn mset_nx(items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> bool:
360        "MSETNX".pairs(items);
361    /// The value at the key, which is deleted.
362    write fn get_del<RV>(key: impl ToRedisArgs): "GETDEL".key(key);
363    /// The value at the key, whose expiry is set as `expiry` says.
364    write fn get_ex<RV>(key: impl ToRedisArgs, expiry: Expiry): "GETEX".key(key).arg(expiry);
365    /// Appends to the value at the key, returning its new length.
366    write fn append(key: impl ToRedisArgs, value: impl ToRedisArgs) -> u64:
367        "APPEND".key(key).arg(value);
368    /// Overwrites the value from byte `offset`, returning its new length.
369    write fn setrange(key: impl ToRedisArgs, offset: usize, value: impl ToRedisArgs) -> u64:
370        "SETRANGE".key(key).arg(offset).arg(value);
371    /// Adds `delta` to the number at the key, returning the result. A missing
372    /// key counts as 0. An integer `delta` is `INCRBY`, replying an `i64`; a
373    /// float is `INCRBYFLOAT`, replying an `f64`.
374    write fn incr<D: Increment>(key: impl ToRedisArgs, delta: D) -> D::Reply:
375        "INCRBY".or_float("INCRBYFLOAT", D::FLOAT).key(key).arg(delta);
376    /// Subtracts `delta` from the integer at the key, returning the result.
377    write fn decr(key: impl ToRedisArgs, delta: i64) -> i64: "DECRBY".key(key).arg(delta);
378}
379
380group! {
381    /// Commands on the bits of a string.
382    group = bitmap;
383    uses {
384        pub use super::bitfield::{
385            BitOffset, Bitfield, BitfieldRo, Overflow, QueuedBitfield, QueuedBitfieldRo,
386        };
387    }
388
389    /// The bit at `offset`.
390    read fn getbit(key: impl ToRedisArgs, offset: u64) -> bool: "GETBIT".key(key).arg(offset);
391    /// How many bits are set.
392    read fn bitcount(key: impl ToRedisArgs) -> u64: "BITCOUNT".key(key);
393    /// How many bits are set from byte `start` to byte `end`, inclusive.
394    read fn bitcount_range(key: impl ToRedisArgs, start: isize, end: isize) -> u64:
395        "BITCOUNT".key(key).arg(start).arg(end);
396    /// The position of the first bit that is `bit`, or -1 if there is none.
397    read fn bitpos(key: impl ToRedisArgs, bit: bool) -> i64: "BITPOS".key(key).arg(bit as u8);
398
399    /// Sets the bit at `offset`, returning what it was.
400    write fn setbit(key: impl ToRedisArgs, offset: u64, value: bool) -> bool:
401        "SETBIT".key(key).arg(offset).arg(value as u8);
402    /// Stores the AND of the sources at `destination`, returning its length in
403    /// bytes.
404    write fn bit_and(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
405        "BITOP".arg("AND").key(destination).key(sources);
406    /// Stores the OR of the sources at `destination`, returning its length in
407    /// bytes.
408    write fn bit_or(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
409        "BITOP".arg("OR").key(destination).key(sources);
410    /// Stores the XOR of the sources at `destination`, returning its length in
411    /// bytes.
412    write fn bit_xor(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
413        "BITOP".arg("XOR").key(destination).key(sources);
414    /// Stores the inverse of the source at `destination`, returning its length
415    /// in bytes.
416    write fn bit_not(destination: impl ToRedisArgs, source: impl ToRedisArgs) -> u64:
417        "BITOP".arg("NOT").key(destination).key(source);
418}
419
420group! {
421    /// Commands on hashes: a key holding fields, each with a value.
422    group = hash;
423
424    /// The value of a field.
425    read fn hget<RV>(key: impl ToRedisArgs, field: impl ToRedisArgs): "HGET".key(key).arg(field);
426    /// The values of the fields, in order, each missing one as `None`.
427    read fn hmget<RV>(key: impl ToRedisArgs, fields: impl ToRedisArgs):
428        "HMGET".key(key).arg(fields);
429    /// Every field and its value: read as a map, or a `Vec` of pairs.
430    read fn hgetall<RV>(key: impl ToRedisArgs): "HGETALL".key(key);
431    /// Whether the field exists.
432    read fn hexists(key: impl ToRedisArgs, field: impl ToRedisArgs) -> bool:
433        "HEXISTS".key(key).arg(field);
434    /// How many fields the hash has.
435    read fn hlen(key: impl ToRedisArgs) -> u64: "HLEN".key(key);
436    /// The names of the fields.
437    read fn hkeys<RV>(key: impl ToRedisArgs): "HKEYS".key(key);
438    /// The values of the fields.
439    read fn hvals<RV>(key: impl ToRedisArgs): "HVALS".key(key);
440    /// The name of a field chosen at random.
441    read fn hrandfield<RV>(key: impl ToRedisArgs): "HRANDFIELD".key(key);
442
443    /// Sets a field, returning 1 if it is new and 0 if it was replaced.
444    write fn hset(key: impl ToRedisArgs, field: impl ToRedisArgs, value: impl ToRedisArgs) -> u64:
445        "HSET".key(key).arg(field).arg(value);
446    /// Sets several fields, returning how many are new.
447    write fn hset_multiple(
448        key: impl ToRedisArgs,
449        items: &[(impl ToRedisArgs, impl ToRedisArgs)]
450    ) -> u64: "HSET".key(key).args_of(items);
451    /// Sets a field unless it exists. `false` if it does.
452    write fn hset_nx(
453        key: impl ToRedisArgs,
454        field: impl ToRedisArgs,
455        value: impl ToRedisArgs
456    ) -> bool: "HSETNX".key(key).arg(field).arg(value);
457    /// Deletes the fields, returning how many existed.
458    write fn hdel(key: impl ToRedisArgs, fields: impl ToRedisArgs) -> u64:
459        "HDEL".key(key).arg(fields);
460    /// Adds `delta` to the number in a field, returning the result. An
461    /// integer `delta` is `HINCRBY`, replying an `i64`; a float is
462    /// `HINCRBYFLOAT`, replying an `f64`.
463    write fn hincr<D: Increment>(key: impl ToRedisArgs, field: impl ToRedisArgs, delta: D) -> D::Reply:
464        "HINCRBY".or_float("HINCRBYFLOAT", D::FLOAT).key(key).arg(field).arg(delta);
465}
466
467group! {
468    /// Commands on lists.
469    group = list;
470
471    /// The elements from index `start` to index `stop`, inclusive. Negative
472    /// indexes count from the end: `0, -1` is the whole list.
473    read fn lrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
474        "LRANGE".key(key).arg(start).arg(stop);
475    /// The element at an index.
476    read fn lindex<RV>(key: impl ToRedisArgs, index: isize): "LINDEX".key(key).arg(index);
477    /// How many elements the list has.
478    read fn llen(key: impl ToRedisArgs) -> u64: "LLEN".key(key);
479    /// The index of the first element equal to `value`.
480    read fn lpos(key: impl ToRedisArgs, value: impl ToRedisArgs) -> Option<u64>:
481        "LPOS".key(key).arg(value);
482
483    /// Prepends the values, returning the list's new length.
484    write fn lpush(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
485        "LPUSH".key(key).arg(values);
486    /// Appends the values, returning the list's new length.
487    write fn rpush(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
488        "RPUSH".key(key).arg(values);
489    /// Prepends the values if the list exists, returning its length.
490    write fn lpush_exists(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
491        "LPUSHX".key(key).arg(values);
492    /// Appends the values if the list exists, returning its length.
493    write fn rpush_exists(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
494        "RPUSHX".key(key).arg(values);
495    /// Removes and returns the first element, or with `count` that many, as a
496    /// list.
497    write fn lpop<RV>(key: impl ToRedisArgs, count: Option<std::num::NonZeroUsize>):
498        "LPOP".key(key).arg(count.map(std::num::NonZeroUsize::get));
499    /// Removes and returns the last element, or with `count` that many, as a
500    /// list.
501    write fn rpop<RV>(key: impl ToRedisArgs, count: Option<std::num::NonZeroUsize>):
502        "RPOP".key(key).arg(count.map(std::num::NonZeroUsize::get));
503    /// Replaces the element at an index.
504    write fn lset(key: impl ToRedisArgs, index: isize, value: impl ToRedisArgs) -> ():
505        "LSET".key(key).arg(index).arg(value);
506    /// Keeps only the elements from index `start` to index `stop`, inclusive.
507    write fn ltrim(key: impl ToRedisArgs, start: isize, stop: isize) -> ():
508        "LTRIM".key(key).arg(start).arg(stop);
509    /// Inserts the value before the first element equal to `pivot`, returning
510    /// the list's new length, or -1 if there is no such element.
511    write fn linsert_before(
512        key: impl ToRedisArgs,
513        pivot: impl ToRedisArgs,
514        value: impl ToRedisArgs
515    ) -> i64: "LINSERT".key(key).arg("BEFORE").arg(pivot).arg(value);
516    /// Inserts the value after the first element equal to `pivot`, returning
517    /// the list's new length, or -1 if there is no such element.
518    write fn linsert_after(
519        key: impl ToRedisArgs,
520        pivot: impl ToRedisArgs,
521        value: impl ToRedisArgs
522    ) -> i64: "LINSERT".key(key).arg("AFTER").arg(pivot).arg(value);
523    /// Removes elements equal to `value`: the first `count` of them, the last
524    /// `-count` if it is negative, or all if it is 0. Returns how many.
525    write fn lrem(key: impl ToRedisArgs, count: isize, value: impl ToRedisArgs) -> u64:
526        "LREM".key(key).arg(count).arg(value);
527    /// Moves an element from one end of `source` to one end of `destination`,
528    /// returning it.
529    write fn lmove<RV>(
530        source: impl ToRedisArgs,
531        destination: impl ToRedisArgs,
532        from: Direction,
533        to: Direction
534    ): "LMOVE".key(source).key(destination).arg(from).arg(to);
535
536    /// Removes and returns the first element of the first of `keys` that has
537    /// one, with its key, waiting up to `timeout` seconds for one to be
538    /// pushed: 0 waits for ever. `None` once the timeout passes.
539    blocking write fn blpop<V: FromRedisValue>(keys: impl ToRedisArgs, timeout: f64) -> Option<Popped<V>>:
540        "BLPOP".key(keys).arg(timeout);
541    /// [`Commands::blpop`], from the end of the list.
542    blocking write fn brpop<V: FromRedisValue>(keys: impl ToRedisArgs, timeout: f64) -> Option<Popped<V>>:
543        "BRPOP".key(keys).arg(timeout);
544    /// [`Commands::lmove`], waiting up to `timeout` seconds for `source` to
545    /// have an element: 0 waits for ever. A nil reply, which reads as `None`,
546    /// once the timeout passes.
547    blocking write fn blmove<RV>(
548        source: impl ToRedisArgs,
549        destination: impl ToRedisArgs,
550        from: Direction,
551        to: Direction,
552        timeout: f64
553    ): "BLMOVE".key(source).key(destination).arg(from).arg(to).arg(timeout);
554    /// Removes and returns up to `count` elements from one end of the first
555    /// of `keys` that has any, with its key, waiting up to `timeout`
556    /// seconds for one: 0 waits for ever. `None` once the timeout passes.
557    blocking write fn blmpop<V: FromRedisValue>(
558        timeout: f64,
559        keys: impl ToRedisArgs,
560        from: Direction,
561        count: usize
562    ) -> Option<PoppedMany<V>>:
563        "BLMPOP".arg(timeout).numkeys(keys).arg(from).arg("COUNT").arg(count);
564}
565
566group! {
567    /// Commands on sets.
568    group = set;
569
570    /// Every member.
571    read fn smembers<RV>(key: impl ToRedisArgs): "SMEMBERS".key(key);
572    /// Whether the value is a member.
573    read fn sismember(key: impl ToRedisArgs, member: impl ToRedisArgs) -> bool:
574        "SISMEMBER".key(key).arg(member);
575    /// Whether each of the values is a member, in order.
576    read fn smismember(key: impl ToRedisArgs, members: impl ToRedisArgs) -> Vec<bool>:
577        "SMISMEMBER".key(key).arg(members);
578    /// How many members the set has.
579    read fn scard(key: impl ToRedisArgs) -> u64: "SCARD".key(key);
580    /// A member chosen at random.
581    read fn srandmember<RV>(key: impl ToRedisArgs): "SRANDMEMBER".key(key);
582    /// `count` distinct members chosen at random, or with a negative `count`
583    /// that many, possibly repeated.
584    read fn srandmember_multiple<RV>(key: impl ToRedisArgs, count: isize):
585        "SRANDMEMBER".key(key).arg(count);
586    /// The members of the first set that are in none of the others.
587    read fn sdiff<RV>(keys: impl ToRedisArgs): "SDIFF".key(keys);
588    /// The members that are in every one of the sets.
589    read fn sinter<RV>(keys: impl ToRedisArgs): "SINTER".key(keys);
590    /// The members that are in any of the sets.
591    read fn sunion<RV>(keys: impl ToRedisArgs): "SUNION".key(keys);
592
593    /// Adds the members, returning how many are new.
594    write fn sadd(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
595        "SADD".key(key).arg(members);
596    /// Removes the members, returning how many there were.
597    write fn srem(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
598        "SREM".key(key).arg(members);
599    /// Removes and returns a member chosen at random.
600    write fn spop<RV>(key: impl ToRedisArgs): "SPOP".key(key);
601    /// Moves a member from one set to another. `false` if it is not in
602    /// `source`.
603    write fn smove(
604        source: impl ToRedisArgs,
605        destination: impl ToRedisArgs,
606        member: impl ToRedisArgs
607    ) -> bool: "SMOVE".key(source).key(destination).arg(member);
608    /// Stores [`Commands::sdiff`] of the sets at `destination`, returning its
609    /// size.
610    write fn sdiffstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
611        "SDIFFSTORE".key(destination).key(keys);
612    /// Stores [`Commands::sinter`] of the sets at `destination`, returning its
613    /// size.
614    write fn sinterstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
615        "SINTERSTORE".key(destination).key(keys);
616    /// Stores [`Commands::sunion`] of the sets at `destination`, returning its
617    /// size.
618    write fn sunionstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
619        "SUNIONSTORE".key(destination).key(keys);
620}
621
622group! {
623    /// Commands on sorted sets: members ordered by a score.
624    group = sorted_set;
625
626    /// The members ranked `start` to `stop`, inclusive, lowest score first.
627    /// Negative ranks count from the highest: `0, -1` is every member.
628    read fn zrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
629        "ZRANGE".key(key).arg(start).arg(stop);
630    /// [`Commands::zrange`], each member with its score.
631    read fn zrange_withscores<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
632        "ZRANGE".key(key).arg(start).arg(stop).arg("WITHSCORES");
633    /// The members ranked `start` to `stop`, inclusive, highest score first.
634    read fn zrevrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
635        "ZREVRANGE".key(key).arg(start).arg(stop);
636    /// [`Commands::zrevrange`], each member with its score.
637    read fn zrevrange_withscores<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
638        "ZREVRANGE".key(key).arg(start).arg(stop).arg("WITHSCORES");
639    /// The members with a score from `min` to `max`, lowest first. A bound is
640    /// a number, `"-inf"` or `"+inf"`, or exclusive as `"(1.5"`.
641    read fn zrangebyscore<RV>(key: impl ToRedisArgs, min: impl ToRedisArgs, max: impl ToRedisArgs):
642        "ZRANGEBYSCORE".key(key).arg(min).arg(max);
643    /// [`Commands::zrangebyscore`], each member with its score.
644    read fn zrangebyscore_withscores<RV>(
645        key: impl ToRedisArgs,
646        min: impl ToRedisArgs,
647        max: impl ToRedisArgs
648    ): "ZRANGEBYSCORE".key(key).arg(min).arg(max).arg("WITHSCORES");
649    /// A member's score.
650    read fn zscore(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<f64>:
651        "ZSCORE".key(key).arg(member);
652    /// A member's rank, lowest score first, from 0.
653    read fn zrank(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<u64>:
654        "ZRANK".key(key).arg(member);
655    /// A member's rank, highest score first, from 0.
656    read fn zrevrank(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<u64>:
657        "ZREVRANK".key(key).arg(member);
658    /// How many members the set has.
659    read fn zcard(key: impl ToRedisArgs) -> u64: "ZCARD".key(key);
660    /// How many members have a score from `min` to `max`.
661    read fn zcount(key: impl ToRedisArgs, min: impl ToRedisArgs, max: impl ToRedisArgs) -> u64:
662        "ZCOUNT".key(key).arg(min).arg(max);
663    /// A member chosen at random.
664    read fn zrandmember<RV>(key: impl ToRedisArgs): "ZRANDMEMBER".key(key);
665
666    /// Adds a member with a score, or updates its score. Returns 1 if it is
667    /// new.
668    write fn zadd(key: impl ToRedisArgs, member: impl ToRedisArgs, score: f64) -> u64:
669        "ZADD".key(key).arg(score).arg(member);
670    /// Adds several members, each given as `(score, member)`, returning how
671    /// many are new.
672    write fn zadd_multiple(key: impl ToRedisArgs, items: &[(f64, impl ToRedisArgs)]) -> u64:
673        "ZADD".key(key).args_of(items);
674    /// Removes the members, returning how many there were.
675    write fn zrem(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
676        "ZREM".key(key).arg(members);
677    /// Adds `delta` to a member's score, returning the result.
678    write fn zincr(key: impl ToRedisArgs, member: impl ToRedisArgs, delta: impl Increment) -> f64:
679        "ZINCRBY".key(key).arg(delta).arg(member);
680    /// Removes and returns the `count` members with the lowest scores, each
681    /// with its score.
682    write fn zpopmin<RV>(key: impl ToRedisArgs, count: usize): "ZPOPMIN".key(key).arg(count);
683    /// Removes and returns the `count` members with the highest scores, each
684    /// with its score.
685    write fn zpopmax<RV>(key: impl ToRedisArgs, count: usize): "ZPOPMAX".key(key).arg(count);
686    /// Removes the members with a score from `min` to `max`, returning how
687    /// many.
688    write fn zrembyscore(
689        key: impl ToRedisArgs,
690        min: impl ToRedisArgs,
691        max: impl ToRedisArgs
692    ) -> u64: "ZREMRANGEBYSCORE".key(key).arg(min).arg(max);
693    /// Removes the members ranked `start` to `stop`, returning how many.
694    write fn zremrangebyrank(key: impl ToRedisArgs, start: isize, stop: isize) -> u64:
695        "ZREMRANGEBYRANK".key(key).arg(start).arg(stop);
696    /// Stores at `destination` the members in every one of the sets, their
697    /// scores summed. Returns its size.
698    write fn zinterstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
699        "ZINTERSTORE".key(destination).numkeys(keys);
700    /// Stores at `destination` the members in any of the sets, their scores
701    /// summed. Returns its size.
702    write fn zunionstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
703        "ZUNIONSTORE".key(destination).numkeys(keys);
704
705    /// Removes and returns the lowest scored member of the first of `keys`
706    /// that has one, with its key and score, waiting up to `timeout`
707    /// seconds for one to be added: 0 waits for ever. `None` once the timeout
708    /// passes.
709    blocking write fn bzpopmin<M: FromRedisValue>(keys: impl ToRedisArgs, timeout: f64) -> Option<PoppedScored<M>>:
710        "BZPOPMIN".key(keys).arg(timeout);
711    /// [`Commands::bzpopmin`], the highest scored member.
712    blocking write fn bzpopmax<M: FromRedisValue>(keys: impl ToRedisArgs, timeout: f64) -> Option<PoppedScored<M>>:
713        "BZPOPMAX".key(keys).arg(timeout);
714    /// Removes and returns up to `count` of the lowest scored members of the
715    /// first of `keys` that has any, with its key and their scores, waiting up
716    /// to `timeout` seconds for one: 0 waits for ever. `None` once the timeout
717    /// passes.
718    blocking write fn bzmpop_min<M: FromRedisValue>(
719        timeout: f64,
720        keys: impl ToRedisArgs,
721        count: usize
722    ) -> Option<PoppedScoredMany<M>>:
723        "BZMPOP".arg(timeout).numkeys(keys).arg("MIN").arg("COUNT").arg(count);
724    /// [`Commands::bzmpop_min`], the highest scored members.
725    blocking write fn bzmpop_max<M: FromRedisValue>(
726        timeout: f64,
727        keys: impl ToRedisArgs,
728        count: usize
729    ) -> Option<PoppedScoredMany<M>>:
730        "BZMPOP".arg(timeout).numkeys(keys).arg("MAX").arg("COUNT").arg(count);
731}
732
733group! {
734    /// Commands on geospatial indexes.
735    group = geo;
736    uses {
737        pub use rs::geo::{Coord, RadiusOptions, RadiusOrder, RadiusSearchResult, Unit};
738    }
739
740    /// The positions of the members, each missing one as `None`.
741    read fn geo_pos<RV>(key: impl ToRedisArgs, members: impl ToRedisArgs):
742        "GEOPOS".key(key).arg(members);
743    /// The distance between two members.
744    read fn geo_dist(
745        key: impl ToRedisArgs,
746        from: impl ToRedisArgs,
747        to: impl ToRedisArgs,
748        unit: Unit
749    ) -> Option<f64>: "GEODIST".key(key).arg(from).arg(to).arg(unit);
750    /// The geohash of each member.
751    read fn geo_hash<RV>(key: impl ToRedisArgs, members: impl ToRedisArgs):
752        "GEOHASH".key(key).arg(members);
753    /// The members within `radius` of a position.
754    read fn geo_radius<RV>(
755        key: impl ToRedisArgs,
756        longitude: f64,
757        latitude: f64,
758        radius: f64,
759        unit: Unit,
760        options: RadiusOptions
761    ): "GEORADIUS_RO".key(key).arg(longitude).arg(latitude).arg(radius).arg(unit).arg(options);
762    /// The members within `radius` of another member.
763    read fn geo_radius_by_member<RV>(
764        key: impl ToRedisArgs,
765        member: impl ToRedisArgs,
766        radius: f64,
767        unit: Unit,
768        options: RadiusOptions
769    ): "GEORADIUSBYMEMBER_RO".key(key).arg(member).arg(radius).arg(unit).arg(options);
770
771    /// Adds a member at a position, or moves it there. Returns 1 if it is new.
772    write fn geo_add(
773        key: impl ToRedisArgs,
774        longitude: f64,
775        latitude: f64,
776        member: impl ToRedisArgs
777    ) -> u64: "GEOADD".key(key).arg(longitude).arg(latitude).arg(member);
778}
779
780group! {
781    /// Commands on streams.
782    group = stream;
783    uses {
784        pub use rs::streams::{
785            StreamAutoClaimReply, StreamClaimReply, StreamId, StreamInfoStreamReply, StreamKey,
786            StreamMaxlen, StreamPendingReply, StreamRangeReply, StreamReadReply,
787        };
788    }
789
790    /// The entries with an id from `start` to `end`, oldest first. `"-"` and
791    /// `"+"` are the lowest and highest ids. Read as a [`StreamRangeReply`].
792    read fn xrange<RV>(key: impl ToRedisArgs, start: impl ToRedisArgs, end: impl ToRedisArgs):
793        "XRANGE".key(key).arg(start).arg(end);
794    /// [`Commands::xrange`], at most `count` entries.
795    read fn xrange_count<RV>(
796        key: impl ToRedisArgs,
797        start: impl ToRedisArgs,
798        end: impl ToRedisArgs,
799        count: usize
800    ): "XRANGE".key(key).arg(start).arg(end).arg("COUNT").arg(count);
801    /// The entries with an id from `end` down to `start`, newest first.
802    read fn xrevrange<RV>(key: impl ToRedisArgs, end: impl ToRedisArgs, start: impl ToRedisArgs):
803        "XREVRANGE".key(key).arg(end).arg(start);
804    /// [`Commands::xrevrange`], at most `count` entries.
805    read fn xrevrange_count<RV>(
806        key: impl ToRedisArgs,
807        end: impl ToRedisArgs,
808        start: impl ToRedisArgs,
809        count: usize
810    ): "XREVRANGE".key(key).arg(end).arg(start).arg("COUNT").arg(count);
811    /// How many entries the stream has.
812    read fn xlen(key: impl ToRedisArgs) -> u64: "XLEN".key(key);
813    /// The entries after an id in each of the streams, `ids` giving the id for
814    /// each of `keys` in order. Returns at once with what is there. Read as a
815    /// [`StreamReadReply`].
816    read fn xread<RV>(keys: impl ToRedisArgs, ids: impl ToRedisArgs):
817        "XREAD".arg("STREAMS").key(keys).arg(ids);
818    /// A summary of the entries a consumer group has been given and not
819    /// acknowledged. Read as a [`StreamPendingReply`].
820    read fn xpending<RV>(key: impl ToRedisArgs, group: impl ToRedisArgs):
821        "XPENDING".key(key).arg(group);
822    /// What the server knows about the stream. Read as a
823    /// [`StreamInfoStreamReply`].
824    read fn xinfo_stream<RV>(key: impl ToRedisArgs): "XINFO".arg("STREAM").key(key);
825
826    /// Appends an entry with the given fields, returning its id. Pass `"*"`
827    /// as the id to have the server choose it.
828    write fn xadd<RV>(
829        key: impl ToRedisArgs,
830        id: impl ToRedisArgs,
831        items: &[(impl ToRedisArgs, impl ToRedisArgs)]
832    ): "XADD".key(key).arg(id).args_of(items);
833    /// [`Commands::xadd`], trimming the stream to a maximum length.
834    write fn xadd_maxlen<RV>(
835        key: impl ToRedisArgs,
836        maxlen: StreamMaxlen,
837        id: impl ToRedisArgs,
838        items: &[(impl ToRedisArgs, impl ToRedisArgs)]
839    ): "XADD".key(key).arg(maxlen).arg(id).args_of(items);
840    /// Deletes the entries with the given ids, returning how many existed.
841    write fn xdel(key: impl ToRedisArgs, ids: impl ToRedisArgs) -> u64: "XDEL".key(key).arg(ids);
842    /// Trims the stream to a maximum length, returning how many entries were
843    /// removed.
844    write fn xtrim(key: impl ToRedisArgs, maxlen: StreamMaxlen) -> u64:
845        "XTRIM".key(key).arg(maxlen);
846    /// Creates a consumer group that starts reading after `id`: `"$"` for only
847    /// new entries, `"0"` for all. The stream must exist.
848    write fn xgroup_create(
849        key: impl ToRedisArgs,
850        group: impl ToRedisArgs,
851        id: impl ToRedisArgs
852    ) -> (): "XGROUP".arg("CREATE").key(key).arg(group).arg(id);
853    /// [`Commands::xgroup_create`], creating the stream if it does not exist.
854    write fn xgroup_create_mkstream(
855        key: impl ToRedisArgs,
856        group: impl ToRedisArgs,
857        id: impl ToRedisArgs
858    ) -> (): "XGROUP".arg("CREATE").key(key).arg(group).arg(id).arg("MKSTREAM");
859    /// Deletes a consumer group. `false` if there was none.
860    write fn xgroup_destroy(key: impl ToRedisArgs, group: impl ToRedisArgs) -> bool:
861        "XGROUP".arg("DESTROY").key(key).arg(group);
862    /// Reads entries as `consumer` of a group: `">"` as the id for the ones
863    /// no consumer has been given yet. At most `count` per stream. A write: it
864    /// records them as given to the consumer. Read as a [`StreamReadReply`].
865    write fn xread_group<RV>(
866        group: impl ToRedisArgs,
867        consumer: impl ToRedisArgs,
868        keys: impl ToRedisArgs,
869        ids: impl ToRedisArgs,
870        count: Option<usize>
871    ): "XREADGROUP".arg("GROUP").arg(group).arg(consumer).arg(count.map(|n| ("COUNT", n)))
872        .arg("STREAMS").key(keys).arg(ids);
873    /// Acknowledges entries a consumer group was given, returning how many
874    /// were pending.
875    write fn xack(key: impl ToRedisArgs, group: impl ToRedisArgs, ids: impl ToRedisArgs) -> u64:
876        "XACK".key(key).arg(group).arg(ids);
877    /// Takes over pending entries that have been idle for `min_idle_ms`, for
878    /// `consumer`. Read as a [`StreamClaimReply`].
879    write fn xclaim<RV>(
880        key: impl ToRedisArgs,
881        group: impl ToRedisArgs,
882        consumer: impl ToRedisArgs,
883        min_idle_ms: u64,
884        ids: impl ToRedisArgs
885    ): "XCLAIM".key(key).arg(group).arg(consumer).arg(min_idle_ms).arg(ids);
886    /// Takes over the pending entries from id `start` that have been idle for
887    /// `min_idle_ms`, for `consumer`. Read as a [`StreamAutoClaimReply`].
888    write fn xautoclaim<RV>(
889        key: impl ToRedisArgs,
890        group: impl ToRedisArgs,
891        consumer: impl ToRedisArgs,
892        min_idle_ms: u64,
893        start: impl ToRedisArgs
894    ): "XAUTOCLAIM".key(key).arg(group).arg(consumer).arg(min_idle_ms).arg(start);
895
896    /// [`Commands::xread`], waiting up to `block` for an entry if there is
897    /// none yet: zero waits for ever. At most `count` entries per stream. A
898    /// nil reply, which reads as `None`, once the wait passes.
899    blocking read fn xread_block<RV>(
900        keys: impl ToRedisArgs,
901        ids: impl ToRedisArgs,
902        block: std::time::Duration,
903        count: Option<usize>
904    ): "XREAD".arg(count.map(|n| ("COUNT", n))).arg("BLOCK").arg(block.as_millis() as u64)
905        .arg("STREAMS").key(keys).arg(ids);
906    /// [`Commands::xread_group`], waiting up to `block` for an entry if there
907    /// is none yet: zero waits for ever. A nil reply, which reads as `None`,
908    /// once the wait passes.
909    blocking write fn xread_group_block<RV>(
910        group: impl ToRedisArgs,
911        consumer: impl ToRedisArgs,
912        keys: impl ToRedisArgs,
913        ids: impl ToRedisArgs,
914        block: std::time::Duration,
915        count: Option<usize>
916    ): "XREADGROUP".arg("GROUP").arg(group).arg(consumer).arg(count.map(|n| ("COUNT", n)))
917        .arg("BLOCK").arg(block.as_millis() as u64).arg("STREAMS").key(keys).arg(ids);
918}
919
920group! {
921    /// Commands on HyperLogLogs: estimates of how many distinct elements were
922    /// added, in a fixed amount of memory.
923    group = hyperloglog;
924
925    /// The estimated number of distinct elements added to the keys, counted
926    /// as their union.
927    read fn pfcount(keys: impl ToRedisArgs) -> u64: "PFCOUNT".key(keys);
928
929    /// Adds the elements, returning whether the estimate changed.
930    write fn pfadd(key: impl ToRedisArgs, elements: impl ToRedisArgs) -> bool:
931        "PFADD".key(key).arg(elements);
932    /// Stores at `destination` the union of itself and the sources.
933    write fn pfmerge(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> ():
934        "PFMERGE".key(destination).key(sources);
935}
936
937impl Cmd {
938    /// Appends pairs whose first halves are keys: `MSET`'s.
939    fn pairs(mut self, items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> Self {
940        for (key, value) in items {
941            self = self.key(Raw(key)).arg(Raw(value));
942        }
943        self
944    }
945
946    /// Appends pairs that are not keys, each half an argument of its own:
947    /// fields and values, scores and members.
948    fn args_of(mut self, items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> Self {
949        for (first, second) in items {
950            self = self.arg(Raw(first)).arg(Raw(second));
951        }
952        self
953    }
954}
955
956/// A borrowed argument, which the conversion trait is not implemented for by
957/// itself: only for a reference to something `redis` converts.
958struct Raw<'a, T>(&'a T);
959
960impl<T: ToRedisArgs> ToRedisArgs for Raw<'_, T> {
961    fn write_redis_args<W: ?Sized + rs::RedisWrite>(&self, out: &mut W) {
962        self.0.write_redis_args(out)
963    }
964}
965
966/// What a scan looks through, and how much at a time.
967#[derive(Debug, Clone, Default)]
968pub struct ScanOptions {
969    pattern: Option<String>,
970    count: Option<usize>,
971}
972
973impl ScanOptions {
974    /// Only what matches a glob-style pattern: `user:*`.
975    pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
976        self.pattern = Some(pattern.into());
977        self
978    }
979
980    /// A hint for how many elements to look at per round trip.
981    pub fn count(mut self, count: usize) -> Self {
982        self.count = Some(count);
983        self
984    }
985}
986
987/// What a [`Scan`] walks: the keys of the database, or the elements of one key.
988#[derive(Clone)]
989enum Scanned {
990    Keys,
991    /// The elements of the key, which come `width` values to an element: a
992    /// member alone, or a field with its value, a member with its score.
993    Elements {
994        operation: &'static str,
995        command: &'static str,
996        key: Vec<u8>,
997        width: usize,
998    },
999}
1000
1001/// An iteration over the keys of a database, or the elements of one key, a
1002/// batch per round trip.
1003///
1004/// ```no_run
1005/// # use encore::storage::redis::{Database, ScanOptions};
1006/// # static SESSIONS: Database = Database::new("sessions");
1007/// # async fn example() -> Result<(), encore::Error> {
1008/// let mut keys = SESSIONS.generic().scan::<String>(ScanOptions::default().pattern("user:*"));
1009/// while let Some(key) = keys.next().await {
1010///     let key = key?;
1011/// }
1012/// # Ok(())
1013/// # }
1014/// ```
1015///
1016/// As with Redis's own `SCAN`, an element present for the whole iteration is
1017/// returned at least once — possibly more — and one added or removed during it
1018/// may or may not be.
1019pub struct Scan<'a, T> {
1020    target: Target<'a>,
1021    scanned: Scanned,
1022    options: ScanOptions,
1023    /// `None` once the server has said there is no more.
1024    cursor: Option<u64>,
1025    /// The batch being handed out, last element first.
1026    batch: Vec<Value>,
1027    item: PhantomData<fn() -> T>,
1028}
1029
1030impl<'a, T: FromRedisValue> Scan<'a, T> {
1031    fn new(target: Target<'a>, scanned: Scanned, options: ScanOptions) -> Self {
1032        Self {
1033            target,
1034            scanned,
1035            options,
1036            cursor: Some(0),
1037            batch: Vec::new(),
1038            item: PhantomData,
1039        }
1040    }
1041
1042    /// The next element, or `None` when the iteration is done.
1043    pub async fn next(&mut self) -> Option<Result<T, Error>> {
1044        loop {
1045            if let Some(value) = self.batch.pop() {
1046                return Some(T::from_redis_value(value));
1047            }
1048            let cursor = self.cursor?;
1049            if let Err(err) = self.fetch(cursor).await {
1050                // An iteration that failed is over: asking again would repeat
1051                // the request that failed.
1052                self.cursor = None;
1053                return Some(Err(err));
1054            }
1055        }
1056    }
1057
1058    /// Fetches the batch at `cursor`.
1059    async fn fetch(&mut self, cursor: u64) -> Result<(), Error> {
1060        let prefix = self.target.client()?.key_prefix().map(str::to_owned);
1061        let mut cmd = match &self.scanned {
1062            Scanned::Keys => core_cache::Command::new("scan", "SCAN", false),
1063            Scanned::Elements {
1064                operation,
1065                command,
1066                key,
1067                ..
1068            } => core_cache::Command::new(operation, *command, false).key(key.as_slice()),
1069        }
1070        .arg(cursor.to_string());
1071
1072        // Keys are scanned across the whole server, so the pattern has to
1073        // select this database's: its prefix, then what was asked for.
1074        let pattern = match (&self.scanned, &prefix, &self.options.pattern) {
1075            (Scanned::Keys, Some(prefix), pattern) => Some(format!(
1076                "{}{}",
1077                escape_glob(prefix),
1078                pattern.as_deref().unwrap_or("*")
1079            )),
1080            (_, _, pattern) => pattern.clone(),
1081        };
1082        if let Some(pattern) = pattern {
1083            cmd = cmd.arg("MATCH").arg(pattern);
1084        }
1085        if let Some(count) = self.options.count {
1086            cmd = cmd.arg("COUNT").arg(count.to_string());
1087        }
1088
1089        let reply = self.target.reply(&cmd).await.map_err(redis_err)?;
1090        let (next, mut values): (u64, Vec<Value>) = FromRedisValue::from_redis_value(reply)?;
1091        self.cursor = (next != 0).then_some(next);
1092
1093        match &self.scanned {
1094            Scanned::Keys => {
1095                if let Some(prefix) = &prefix {
1096                    for value in &mut values {
1097                        if let Value::BulkString(key) = value {
1098                            if key.starts_with(prefix.as_bytes()) {
1099                                key.drain(..prefix.len());
1100                            }
1101                        }
1102                    }
1103                }
1104            }
1105            Scanned::Elements { width, .. } if *width > 1 => {
1106                if values.len() % width != 0 {
1107                    return Err(Error::new(
1108                        ErrCode::Internal,
1109                        "the scan's reply does not divide into elements",
1110                    ));
1111                }
1112                values = values
1113                    .chunks(*width)
1114                    .map(|element| Value::Array(element.to_vec()))
1115                    .collect();
1116            }
1117            Scanned::Elements { .. } => {}
1118        }
1119        // Handed out from the end, so the first is last.
1120        values.reverse();
1121        self.batch = values;
1122        Ok(())
1123    }
1124}
1125
1126/// `text` with the characters a glob pattern gives meaning to escaped.
1127fn escape_glob(text: &str) -> String {
1128    let mut out = String::with_capacity(text.len());
1129    for c in text.chars() {
1130        if matches!(c, '*' | '?' | '[' | ']' | '\\') {
1131            out.push('\\');
1132        }
1133        out.push(c);
1134    }
1135    out
1136}
1137
1138/// The scans, on both forms that run commands. Written out rather than listed
1139/// with the group's commands: they return an iteration, not a reply.
1140macro_rules! scans {
1141    ($group:ident: $($(#[$doc:meta])* fn $name:ident($($key:ident)?) = $scanned:expr;)*) => {
1142        scans!(@on $group, Commands: $($(#[$doc])* fn $name($($key)?) = $scanned;)*);
1143        scans!(@on $group, ReadCommands: $($(#[$doc])* fn $name($($key)?) = $scanned;)*);
1144    };
1145    (
1146        @on $group:ident, $form:ident:
1147        $($(#[$doc:meta])* fn $name:ident($($key:ident)?) = $scanned:expr;)*
1148    ) => {
1149        impl<'a> $group::$form<'a> {
1150            $(
1151                $(#[$doc])*
1152                pub fn $name<T: FromRedisValue>(
1153                    &self,
1154                    $($key: impl ToRedisArgs,)?
1155                    options: ScanOptions,
1156                ) -> Scan<'a, T> {
1157                    Scan::new(self.target, $scanned, options)
1158                }
1159            )*
1160        }
1161    };
1162}
1163
1164/// The scan of one key's elements.
1165fn elements(
1166    operation: &'static str,
1167    command: &'static str,
1168    key: impl ToRedisArgs,
1169    width: usize,
1170) -> Scanned {
1171    Scanned::Elements {
1172        operation,
1173        command,
1174        key: key.to_redis_args().into_iter().next().unwrap_or_default(),
1175        width,
1176    }
1177}
1178
1179// command: read generic scan
1180scans!(generic:
1181    /// Iterates over the database's keys.
1182    fn scan() = Scanned::Keys;
1183);
1184
1185// command: read hash hscan
1186scans!(hash:
1187    /// Iterates over the hash's fields, each a `(field, value)` pair.
1188    fn hscan(key) = elements("hscan", "HSCAN", key, 2);
1189);
1190
1191// command: read set sscan
1192scans!(set:
1193    /// Iterates over the set's members.
1194    fn sscan(key) = elements("sscan", "SSCAN", key, 1);
1195);
1196
1197// command: read sorted_set zscan
1198scans!(sorted_set:
1199    /// Iterates over the sorted set's members, each a `(member, score)` pair.
1200    fn zscan(key) = elements("zscan", "ZSCAN", key, 2);
1201);
1202
1203/// `BITFIELD`: integers of any width up to 64 bits, read and written at any
1204/// bit offset of a string.
1205mod bitfield {
1206    use super::*;
1207    use crate::storage::redis::Queued;
1208
1209    /// Where a bitfield integer starts: at a bit, or at a multiple of its
1210    /// type's width (`#2` of a `u8` is bit 16).
1211    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1212    pub enum BitOffset {
1213        Bit(u64),
1214        Multiple(u64),
1215    }
1216
1217    impl From<u64> for BitOffset {
1218        fn from(bit: u64) -> Self {
1219            BitOffset::Bit(bit)
1220        }
1221    }
1222
1223    impl std::fmt::Display for BitOffset {
1224        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1225            match self {
1226                BitOffset::Bit(n) => write!(f, "{n}"),
1227                BitOffset::Multiple(n) => write!(f, "#{n}"),
1228            }
1229        }
1230    }
1231
1232    /// What a `set` or `incr_by` that leaves its type's range does, from the
1233    /// [`Bitfield::overflow`] that says so on.
1234    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1235    pub enum Overflow {
1236        /// Wraps around, as integer arithmetic does: the default.
1237        Wrap,
1238        /// Stops at the type's smallest or largest value.
1239        Sat,
1240        /// Leaves the value as it was, and replies `None` for the operation.
1241        Fail,
1242    }
1243
1244    /// The operations every bitfield has.
1245    macro_rules! gets {
1246        () => {
1247            /// Reads the integer of type `ty` (`"u8"`, `"i5"`; up to `"i64"` and
1248            /// `"u63"`) at `offset`.
1249            pub fn get(mut self, ty: &str, offset: impl Into<BitOffset>) -> Self {
1250                self.cmd = self.cmd.arg("GET").arg(ty).arg(offset.into().to_string());
1251                self
1252            }
1253        };
1254    }
1255
1256    /// The operations of a bitfield that writes.
1257    macro_rules! sets {
1258        () => {
1259            gets!();
1260
1261            /// Sets the integer of type `ty` at `offset` to `value`, replying
1262            /// what it was.
1263            pub fn set(mut self, ty: &str, offset: impl Into<BitOffset>, value: i64) -> Self {
1264                self.cmd = self
1265                    .cmd
1266                    .arg("SET")
1267                    .arg(ty)
1268                    .arg(offset.into().to_string())
1269                    .arg(value);
1270                self
1271            }
1272
1273            /// Adds `increment` to the integer of type `ty` at `offset`, replying
1274            /// what it is then.
1275            pub fn incr_by(
1276                mut self,
1277                ty: &str,
1278                offset: impl Into<BitOffset>,
1279                increment: i64,
1280            ) -> Self {
1281                self.cmd = self
1282                    .cmd
1283                    .arg("INCRBY")
1284                    .arg(ty)
1285                    .arg(offset.into().to_string())
1286                    .arg(increment);
1287                self
1288            }
1289
1290            /// What the `set`s and `incr_by`s after this do when they leave
1291            /// their type's range.
1292            pub fn overflow(mut self, mode: Overflow) -> Self {
1293                let mode = match mode {
1294                    Overflow::Wrap => "WRAP",
1295                    Overflow::Sat => "SAT",
1296                    Overflow::Fail => "FAIL",
1297                };
1298                self.cmd = self.cmd.arg("OVERFLOW").arg(mode);
1299                self
1300            }
1301        };
1302    }
1303
1304    /// The operations on a string's bitfield integers, made by
1305    /// [`bitmap::Commands::bitfield`](super::bitmap::Commands::bitfield):
1306    /// sent in order, as one command, by [`Bitfield::invoke`].
1307    pub struct Bitfield<'a> {
1308        pub(super) target: Target<'a>,
1309        pub(super) cmd: Cmd,
1310    }
1311
1312    impl Bitfield<'_> {
1313        sets!();
1314
1315        /// Runs the operations, replying one value per `get`, `set` and
1316        /// `incr_by`, in order: `None` for one an [`Overflow::Fail`] stopped.
1317        pub async fn invoke(self) -> Result<Vec<Option<i64>>, Error> {
1318            self.target.run(self.cmd).await
1319        }
1320    }
1321
1322    /// [`Bitfield`] that only reads (`BITFIELD_RO`), made by `bitfield_ro`.
1323    pub struct BitfieldRo<'a> {
1324        pub(super) target: Target<'a>,
1325        pub(super) cmd: Cmd,
1326    }
1327
1328    impl BitfieldRo<'_> {
1329        gets!();
1330
1331        /// Runs the reads, replying one value per `get`, in order.
1332        pub async fn invoke(self) -> Result<Vec<Option<i64>>, Error> {
1333            self.target.run(self.cmd).await
1334        }
1335    }
1336
1337    /// A [`Bitfield`] being queued on a pipeline or a transaction.
1338    pub struct QueuedBitfield<'a> {
1339        pub(super) queue: &'a mut Queued,
1340        pub(super) cmd: Cmd,
1341    }
1342
1343    impl QueuedBitfield<'_> {
1344        sets!();
1345
1346        /// Queues the operations, as one command.
1347        pub fn queue(self) {
1348            self.queue.push(self.cmd);
1349        }
1350    }
1351
1352    /// A [`BitfieldRo`] being queued on a pipeline or a transaction.
1353    pub struct QueuedBitfieldRo<'a> {
1354        pub(super) queue: &'a mut Queued,
1355        pub(super) cmd: Cmd,
1356    }
1357
1358    impl QueuedBitfieldRo<'_> {
1359        gets!();
1360
1361        /// Queues the reads, as one command.
1362        pub fn queue(self) {
1363            self.queue.push(self.cmd);
1364        }
1365    }
1366
1367    fn bitfield(key: impl ToRedisArgs) -> Cmd {
1368        Cmd::new("bitfield", "BITFIELD", true).key(key)
1369    }
1370
1371    fn bitfield_ro(key: impl ToRedisArgs) -> Cmd {
1372        Cmd::new("bitfield_ro", "BITFIELD_RO", false).key(key)
1373    }
1374
1375    // command: write bitmap bitfield
1376    // command: read bitmap bitfield_ro
1377    impl<'a> super::bitmap::Commands<'a> {
1378        /// Integers of any width up to 64 bits, read and written at any bit
1379        /// offset of the string: add the operations, then
1380        /// [`Bitfield::invoke`].
1381        pub fn bitfield(&self, key: impl ToRedisArgs) -> Bitfield<'a> {
1382            Bitfield {
1383                target: self.target,
1384                cmd: bitfield(key),
1385            }
1386        }
1387
1388        /// [`Commands::bitfield`](Self::bitfield) that only reads.
1389        pub fn bitfield_ro(&self, key: impl ToRedisArgs) -> BitfieldRo<'a> {
1390            BitfieldRo {
1391                target: self.target,
1392                cmd: bitfield_ro(key),
1393            }
1394        }
1395    }
1396
1397    impl<'a> super::bitmap::ReadCommands<'a> {
1398        /// Integers of any width up to 64 bits, read at any bit offset of the
1399        /// string: add the reads, then [`BitfieldRo::invoke`].
1400        pub fn bitfield_ro(&self, key: impl ToRedisArgs) -> BitfieldRo<'a> {
1401            BitfieldRo {
1402                target: self.target,
1403                cmd: bitfield_ro(key),
1404            }
1405        }
1406    }
1407
1408    impl super::bitmap::Queue<'_> {
1409        /// Queues a [`Bitfield`]: add the operations, then
1410        /// [`QueuedBitfield::queue`].
1411        pub fn bitfield(&mut self, key: impl ToRedisArgs) -> QueuedBitfield<'_> {
1412            QueuedBitfield {
1413                queue: self.queue,
1414                cmd: bitfield(key),
1415            }
1416        }
1417
1418        /// Queues a [`BitfieldRo`].
1419        pub fn bitfield_ro(&mut self, key: impl ToRedisArgs) -> QueuedBitfieldRo<'_> {
1420            QueuedBitfieldRo {
1421                queue: self.queue,
1422                cmd: bitfield_ro(key),
1423            }
1424        }
1425    }
1426}
1427
1428/// Publishing to channels, and subscribing to them.
1429///
1430/// This is Redis's own channel messaging, where a message reaches whoever is
1431/// subscribed at that moment and nobody else. For messages that are kept until
1432/// they are handled, use [`crate::pubsub`].
1433pub mod pubsub {
1434    use super::*;
1435
1436    /// The group's commands, run as they are called.
1437    #[derive(Clone, Copy)]
1438    pub struct Commands<'a> {
1439        pub(in crate::storage::redis) target: Target<'a>,
1440    }
1441
1442    /// The group's commands that only read: subscribing.
1443    #[derive(Clone, Copy)]
1444    pub struct ReadCommands<'a> {
1445        pub(in crate::storage::redis) target: Target<'a>,
1446    }
1447
1448    /// The group's commands, queued on a pipeline or a transaction.
1449    pub struct Queue<'a> {
1450        pub(in crate::storage::redis) queue: &'a mut crate::storage::redis::Queued,
1451    }
1452
1453    fn publish(channel: impl ToRedisArgs, message: impl ToRedisArgs) -> Cmd {
1454        // A channel is prefixed like a key, so only this database's
1455        // subscribers hear it.
1456        Cmd::new("publish", "PUBLISH", true)
1457            .key(channel)
1458            .arg(message)
1459    }
1460
1461    async fn subscribe(
1462        target: Target<'_>,
1463        channels: impl ToRedisArgs,
1464        patterns: impl ToRedisArgs,
1465    ) -> Result<Subscription, Error> {
1466        let inner = target
1467            .client()?
1468            .subscribe(&channels.to_redis_args(), &patterns.to_redis_args())
1469            .await
1470            .map_err(redis_err)?;
1471        Ok(Subscription { inner })
1472    }
1473
1474    impl Commands<'_> {
1475        // command: write pubsub publish
1476        /// Publishes a message to a channel, returning how many subscribers
1477        /// received it.
1478        pub async fn publish(
1479            &self,
1480            channel: impl ToRedisArgs,
1481            message: impl ToRedisArgs,
1482        ) -> Result<u64, Error> {
1483            self.target.run(publish(channel, message)).await
1484        }
1485
1486        // command: read pubsub subscribe
1487        /// Subscribes to one or more channels, on a connection of its own.
1488        pub async fn subscribe(&self, channels: impl ToRedisArgs) -> Result<Subscription, Error> {
1489            subscribe(self.target, channels, Vec::<Vec<u8>>::new()).await
1490        }
1491
1492        // command: read pubsub psubscribe
1493        /// Subscribes to the channels matching one or more glob-style
1494        /// patterns, on a connection of its own.
1495        pub async fn psubscribe(&self, patterns: impl ToRedisArgs) -> Result<Subscription, Error> {
1496            subscribe(self.target, Vec::<Vec<u8>>::new(), patterns).await
1497        }
1498    }
1499
1500    impl ReadCommands<'_> {
1501        /// See [`Commands::subscribe`].
1502        pub async fn subscribe(&self, channels: impl ToRedisArgs) -> Result<Subscription, Error> {
1503            subscribe(self.target, channels, Vec::<Vec<u8>>::new()).await
1504        }
1505
1506        /// See [`Commands::psubscribe`].
1507        pub async fn psubscribe(&self, patterns: impl ToRedisArgs) -> Result<Subscription, Error> {
1508            subscribe(self.target, Vec::<Vec<u8>>::new(), patterns).await
1509        }
1510    }
1511
1512    impl Queue<'_> {
1513        /// See [`Commands::publish`].
1514        pub fn publish(
1515            &mut self,
1516            channel: impl ToRedisArgs,
1517            message: impl ToRedisArgs,
1518        ) -> &mut Self {
1519            self.queue.push(publish(channel, message));
1520            self
1521        }
1522    }
1523
1524    /// An open subscription. Dropping it closes its connection, which
1525    /// unsubscribes.
1526    pub struct Subscription {
1527        inner: core_cache::Subscription,
1528    }
1529
1530    impl Subscription {
1531        /// The next message, or `None` once the connection has closed.
1532        pub async fn next(&mut self) -> Option<Message> {
1533            let message = self.inner.next().await?;
1534            Some(Message {
1535                channel: String::from_utf8_lossy(&message.channel).into_owned(),
1536                payload: message.payload,
1537            })
1538        }
1539    }
1540
1541    /// A message received on a [`Subscription`].
1542    #[derive(Debug, Clone, PartialEq, Eq)]
1543    pub struct Message {
1544        /// The channel it was published to.
1545        pub channel: String,
1546        /// What was published, as it was sent.
1547        pub payload: Vec<u8>,
1548    }
1549
1550    impl Message {
1551        /// The payload, converted.
1552        pub fn payload<T: FromRedisValue>(&self) -> Result<T, Error> {
1553            T::from_redis_value(Value::BulkString(self.payload.clone()))
1554        }
1555    }
1556}
1557
1558use rs::{Direction, Expiry, SetOptions};