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