encore-dev 2.0.0-alpha.17

Rust SDK for Encore applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
//! The command groups: one module per Redis data type, each holding the
//! commands on it in three forms — `Commands`, which run now; `ReadCommands`,
//! the ones that only read; and `Queue`, which adds them to a pipeline or a
//! transaction.
//!
//! All three come from one list per group, below. A command is written once:
//! whether it reads or writes, its name and parameters, and the Redis command
//! it builds, with the arguments that are keys marked as such. Encore's parser
//! holds the same list (`RS_TABLES.families` in `encore_parser`), which is how
//! it knows what each call needs to be granted; a test there reads this file
//! and fails when the two differ.

use std::marker::PhantomData;

use encore_sdk_core::cache::{self as core_cache, redis as rs};

use super::types::{FromRedisValue, Increment, ToRedisArgs, Value};
use super::{redis_err, Target};
use crate::error::{ErrCode, Error};

/// A command being built: the arguments in order, the keys among them marked.
pub(crate) struct Cmd {
    pub(super) inner: core_cache::Command,
    /// Whether the reply names keys, which then carry the database's prefix.
    pub(super) reply_keys: bool,
}

impl Cmd {
    fn new(operation: &'static str, name: &'static str, write: bool) -> Self {
        Self::from_core(core_cache::Command::new(operation, name, write))
    }

    pub(super) fn from_core(inner: core_cache::Command) -> Self {
        Self {
            inner,
            reply_keys: false,
        }
    }

    /// Appends one or more keys.
    fn key(mut self, key: impl ToRedisArgs) -> Self {
        for key in key.to_redis_args() {
            self.inner = self.inner.key(key);
        }
        self
    }

    /// Appends one or more arguments that are not keys.
    fn arg(mut self, arg: impl ToRedisArgs) -> Self {
        for arg in arg.to_redis_args() {
            self.inner = self.inner.arg(arg);
        }
        self
    }

    /// Has the command be `name`, its floating-point counterpart, when the
    /// amount it adds is a float. Comes before the arguments.
    fn or_float(self, name: &'static str, float: bool) -> Self {
        if float {
            Self::new(self.inner.operation(), name, self.inner.is_write())
        } else {
            self
        }
    }

    /// Appends keys preceded by how many there are, as the commands that take
    /// a variable number of keys before their other arguments want them.
    fn numkeys(mut self, keys: impl ToRedisArgs) -> Self {
        let keys = keys.to_redis_args();
        self.inner = self.inner.arg(keys.len().to_string());
        for key in keys {
            self.inner = self.inner.key(key);
        }
        self
    }

    /// Marks the reply as naming keys: a stream read's, which says which
    /// stream each entry came from.
    fn reply_keys(mut self) -> Self {
        self.reply_keys = true;
        self
    }
}

/// Removes the database's key prefix from the stream names in a stream read's
/// reply, which is a list of (or a map from) stream name to entries.
pub(super) fn strip_reply_keys(reply: &mut Value, prefix: Option<&str>) {
    let Some(prefix) = prefix else {
        return;
    };
    let strip = |name: &mut Value| {
        if let Value::BulkString(bytes) = name {
            if bytes.starts_with(prefix.as_bytes()) {
                bytes.drain(..prefix.len());
            }
        }
    };
    match reply {
        Value::Array(streams) => {
            for stream in streams {
                if let Value::Array(parts) = stream {
                    if let Some(name) = parts.first_mut() {
                        strip(name);
                    }
                }
            }
        }
        Value::Map(streams) => {
            for (name, _) in streams {
                strip(name);
            }
        }
        _ => {}
    }
}

/// One method, in the form `$form` asks for. A command that writes has no
/// `read` form.
macro_rules! method {
    (run $mode:ident; $(#[$doc:meta])* fn $name:ident<RV>($($arg:ident: $ty:ty),*) [$cmd:expr]) => {
        $(#[$doc])*
        pub async fn $name<RV: FromRedisValue>(&self, $($arg: $ty),*) -> Result<RV, Error> {
            self.target.run($cmd).await
        }
    };
    (run $mode:ident; $(#[$doc:meta])* fn $name:ident($($arg:ident: $ty:ty),*) -> $ret:ty [$cmd:expr]) => {
        $(#[$doc])*
        pub async fn $name(&self, $($arg: $ty),*) -> Result<$ret, Error> {
            self.target.run($cmd).await
        }
    };
    (run $mode:ident; $(#[$doc:meta])* fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),*) -> $ret:ty [$cmd:expr]) => {
        $(#[$doc])*
        pub async fn $name<$param: $bound>(&self, $($arg: $ty),*) -> Result<$ret, Error> {
            self.target.run($cmd).await
        }
    };
    (read read; $($method:tt)*) => {
        method!(run read; $($method)*);
    };
    (read write; $($method:tt)*) => {};
    (queue $mode:ident; $(#[$doc:meta])* fn $name:ident $(<RV>)? ($($arg:ident: $ty:ty),*) $(-> $ret:ty)? [$cmd:expr]) => {
        $(#[$doc])*
        pub fn $name(&mut self, $($arg: $ty),*) -> &mut Self {
            self.queue.push($cmd);
            self
        }
    };
    (queue $mode:ident; $(#[$doc:meta])* fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),*) -> $ret:ty [$cmd:expr]) => {
        $(#[$doc])*
        pub fn $name<$param: $bound>(&mut self, $($arg: $ty),*) -> &mut Self {
            self.queue.push($cmd);
            self
        }
    };
}

/// Whether a command of mode `$mode` writes.
macro_rules! writes {
    (read) => {
        false
    };
    (write) => {
        true
    };
}

/// A group's commands, each in the form `$form` asks for.
macro_rules! methods {
    ($form:ident;) => {};
    (
        $form:ident;
        $(#[$doc:meta])*
        $mode:ident fn $name:ident<RV>($($arg:ident: $ty:ty),* $(,)?):
            $wire:literal $(.$part:ident($($value:expr),*))*;
        $($rest:tt)*
    ) => {
        method!(
            $form $mode;
            $(#[$doc])*
            fn $name<RV>($($arg: $ty),*)
            [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
        );
        methods!($form; $($rest)*);
    };
    (
        $form:ident;
        $(#[$doc:meta])*
        $mode:ident fn $name:ident($($arg:ident: $ty:ty),* $(,)?) -> $ret:ty:
            $wire:literal $(.$part:ident($($value:expr),*))*;
        $($rest:tt)*
    ) => {
        method!(
            $form $mode;
            $(#[$doc])*
            fn $name($($arg: $ty),*) -> $ret
            [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
        );
        methods!($form; $($rest)*);
    };
    // A command generic over one of its parameters, which its reply follows.
    (
        $form:ident;
        $(#[$doc:meta])*
        $mode:ident fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),* $(,)?) -> $ret:ty:
            $wire:literal $(.$part:ident($($value:expr),*))*;
        $($rest:tt)*
    ) => {
        method!(
            $form $mode;
            $(#[$doc])*
            fn $name<$param: $bound>($($arg: $ty),*) -> $ret
            [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
        );
        methods!($form; $($rest)*);
    };
}

/// A command group: a module holding its three forms.
macro_rules! group {
    // Without types of its own to re-export.
    (
        $(#[$doc:meta])*
        group = $group:ident;
        $(#[$first:meta])*
        $mode:ident fn $($commands:tt)*
    ) => {
        group! {
            $(#[$doc])*
            group = $group;
            uses {}
            $(#[$first])*
            $mode fn $($commands)*
        }
    };
    (
        $(#[$doc:meta])*
        group = $group:ident;
        uses { $($uses:item)* }
        $($commands:tt)*
    ) => {
        $(#[$doc])*
        pub mod $group {
            #[allow(unused_imports)]
            use super::*;

            $($uses)*

            /// The group's commands, run as they are called.
            #[derive(Clone, Copy)]
            pub struct Commands<'a> {
                pub(in crate::storage::redis) target: Target<'a>,
            }

            /// The group's commands that only read.
            #[derive(Clone, Copy)]
            pub struct ReadCommands<'a> {
                pub(in crate::storage::redis) target: Target<'a>,
            }

            /// The group's commands, queued on a pipeline or a transaction.
            /// What each replies is read from `exec`, in the order queued.
            pub struct Queue<'a> {
                pub(in crate::storage::redis) queue: &'a mut crate::storage::redis::Queued,
            }

            impl Commands<'_> {
                methods!(run; $($commands)*);
            }

            impl ReadCommands<'_> {
                methods!(read; $($commands)*);
            }

            impl Queue<'_> {
                methods!(queue; $($commands)*);
            }
        }
    };
}

group! {
    /// Commands that work on a key of any type.
    group = generic;

    /// Whether the key exists.
    read fn exists(key: impl ToRedisArgs) -> bool: "EXISTS".key(key);
    /// The seconds until the key expires: -1 if it never does, -2 if it does
    /// not exist.
    read fn ttl(key: impl ToRedisArgs) -> i64: "TTL".key(key);
    /// The milliseconds until the key expires: -1 if it never does, -2 if it
    /// does not exist.
    read fn pttl(key: impl ToRedisArgs) -> i64: "PTTL".key(key);
    /// The type of the value at the key: `string`, `list`, `set`, `zset`,
    /// `hash`, `stream`, or `none` if it does not exist.
    read fn key_type(key: impl ToRedisArgs) -> String: "TYPE".key(key);
    /// The Unix time, in seconds, the key expires at: -1 if it never does, -2
    /// if it does not exist.
    read fn expire_time(key: impl ToRedisArgs) -> i64: "EXPIRETIME".key(key);

    /// Deletes the keys, returning how many existed.
    write fn del(keys: impl ToRedisArgs) -> u64: "DEL".key(keys);
    /// Deletes the keys, reclaiming their memory in the background. Returns
    /// how many existed.
    write fn unlink(keys: impl ToRedisArgs) -> u64: "UNLINK".key(keys);
    /// Has the key expire in `seconds`. `false` if it does not exist.
    write fn expire(key: impl ToRedisArgs, seconds: i64) -> bool: "EXPIRE".key(key).arg(seconds);
    /// Has the key expire in `milliseconds`. `false` if it does not exist.
    write fn pexpire(key: impl ToRedisArgs, milliseconds: i64) -> bool:
        "PEXPIRE".key(key).arg(milliseconds);
    /// Has the key expire at a Unix time, in seconds. `false` if it does not
    /// exist.
    write fn expire_at(key: impl ToRedisArgs, timestamp: i64) -> bool:
        "EXPIREAT".key(key).arg(timestamp);
    /// Removes the key's expiry. `false` if it had none, or does not exist.
    write fn persist(key: impl ToRedisArgs) -> bool: "PERSIST".key(key);
    /// Renames the key, replacing `new_key` if it exists.
    write fn rename(key: impl ToRedisArgs, new_key: impl ToRedisArgs) -> ():
        "RENAME".key(key).key(new_key);
    /// Renames the key unless `new_key` exists. `false` if it does.
    write fn rename_nx(key: impl ToRedisArgs, new_key: impl ToRedisArgs) -> bool:
        "RENAMENX".key(key).key(new_key);
    /// Copies the value at `source` to `destination`. `false` if `destination`
    /// exists.
    write fn copy(source: impl ToRedisArgs, destination: impl ToRedisArgs) -> bool:
        "COPY".key(source).key(destination);
    /// Marks the keys as used just now, returning how many exist.
    write fn touch(keys: impl ToRedisArgs) -> u64: "TOUCH".key(keys);
}

group! {
    /// Commands on strings, which is what a plain value is.
    group = string;

    /// The value at the key. Read as an `Option` to tell a missing key apart.
    read fn get<RV>(key: impl ToRedisArgs): "GET".key(key);
    /// The values at the keys, in order, each missing one as `None`.
    read fn mget<RV>(keys: impl ToRedisArgs): "MGET".key(keys);
    /// The length of the value at the key, in bytes.
    read fn strlen(key: impl ToRedisArgs) -> u64: "STRLEN".key(key);
    /// The part of the value from byte `from` to byte `to`, inclusive.
    /// Negative offsets count from the end.
    read fn getrange<RV>(key: impl ToRedisArgs, from: isize, to: isize):
        "GETRANGE".key(key).arg(from).arg(to);

    /// Sets the key to the value.
    write fn set(key: impl ToRedisArgs, value: impl ToRedisArgs) -> (): "SET".key(key).arg(value);
    /// Sets the key to the value, expiring in `seconds`.
    write fn set_ex(key: impl ToRedisArgs, value: impl ToRedisArgs, seconds: u64) -> ():
        "SETEX".key(key).arg(seconds).arg(value);
    /// Sets the key to the value unless the key exists. `false` if it does.
    write fn set_nx(key: impl ToRedisArgs, value: impl ToRedisArgs) -> bool:
        "SETNX".key(key).arg(value);
    /// Sets the key to the value as `options` say: only if it exists or does
    /// not, with an expiry, returning the old value.
    write fn set_options<RV>(key: impl ToRedisArgs, value: impl ToRedisArgs, options: SetOptions):
        "SET".key(key).arg(value).arg(options);
    /// Sets each key to its value, all at once.
    write fn mset(items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> (): "MSET".pairs(items);
    /// Sets each key to its value unless any of the keys exists. `false` if
    /// one does, in which case none is set.
    write fn mset_nx(items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> bool:
        "MSETNX".pairs(items);
    /// The value at the key, which is deleted.
    write fn get_del<RV>(key: impl ToRedisArgs): "GETDEL".key(key);
    /// The value at the key, whose expiry is set as `expiry` says.
    write fn get_ex<RV>(key: impl ToRedisArgs, expiry: Expiry): "GETEX".key(key).arg(expiry);
    /// Appends to the value at the key, returning its new length.
    write fn append(key: impl ToRedisArgs, value: impl ToRedisArgs) -> u64:
        "APPEND".key(key).arg(value);
    /// Overwrites the value from byte `offset`, returning its new length.
    write fn setrange(key: impl ToRedisArgs, offset: usize, value: impl ToRedisArgs) -> u64:
        "SETRANGE".key(key).arg(offset).arg(value);
    /// Adds `delta` to the number at the key, returning the result. A missing
    /// key counts as 0. An integer `delta` is `INCRBY`, replying an `i64`; a
    /// float is `INCRBYFLOAT`, replying an `f64`.
    write fn incr<D: Increment>(key: impl ToRedisArgs, delta: D) -> D::Reply:
        "INCRBY".or_float("INCRBYFLOAT", D::FLOAT).key(key).arg(delta);
    /// Subtracts `delta` from the integer at the key, returning the result.
    write fn decr(key: impl ToRedisArgs, delta: i64) -> i64: "DECRBY".key(key).arg(delta);
}

group! {
    /// Commands on the bits of a string.
    group = bitmap;

    /// The bit at `offset`.
    read fn getbit(key: impl ToRedisArgs, offset: u64) -> bool: "GETBIT".key(key).arg(offset);
    /// How many bits are set.
    read fn bitcount(key: impl ToRedisArgs) -> u64: "BITCOUNT".key(key);
    /// How many bits are set from byte `start` to byte `end`, inclusive.
    read fn bitcount_range(key: impl ToRedisArgs, start: isize, end: isize) -> u64:
        "BITCOUNT".key(key).arg(start).arg(end);
    /// The position of the first bit that is `bit`, or -1 if there is none.
    read fn bitpos(key: impl ToRedisArgs, bit: bool) -> i64: "BITPOS".key(key).arg(bit as u8);

    /// Sets the bit at `offset`, returning what it was.
    write fn setbit(key: impl ToRedisArgs, offset: u64, value: bool) -> bool:
        "SETBIT".key(key).arg(offset).arg(value as u8);
    /// Stores the AND of the sources at `destination`, returning its length in
    /// bytes.
    write fn bit_and(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
        "BITOP".arg("AND").key(destination).key(sources);
    /// Stores the OR of the sources at `destination`, returning its length in
    /// bytes.
    write fn bit_or(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
        "BITOP".arg("OR").key(destination).key(sources);
    /// Stores the XOR of the sources at `destination`, returning its length in
    /// bytes.
    write fn bit_xor(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
        "BITOP".arg("XOR").key(destination).key(sources);
    /// Stores the inverse of the source at `destination`, returning its length
    /// in bytes.
    write fn bit_not(destination: impl ToRedisArgs, source: impl ToRedisArgs) -> u64:
        "BITOP".arg("NOT").key(destination).key(source);
}

group! {
    /// Commands on hashes: a key holding fields, each with a value.
    group = hash;

    /// The value of a field.
    read fn hget<RV>(key: impl ToRedisArgs, field: impl ToRedisArgs): "HGET".key(key).arg(field);
    /// The values of the fields, in order, each missing one as `None`.
    read fn hmget<RV>(key: impl ToRedisArgs, fields: impl ToRedisArgs):
        "HMGET".key(key).arg(fields);
    /// Every field and its value: read as a map, or a `Vec` of pairs.
    read fn hgetall<RV>(key: impl ToRedisArgs): "HGETALL".key(key);
    /// Whether the field exists.
    read fn hexists(key: impl ToRedisArgs, field: impl ToRedisArgs) -> bool:
        "HEXISTS".key(key).arg(field);
    /// How many fields the hash has.
    read fn hlen(key: impl ToRedisArgs) -> u64: "HLEN".key(key);
    /// The names of the fields.
    read fn hkeys<RV>(key: impl ToRedisArgs): "HKEYS".key(key);
    /// The values of the fields.
    read fn hvals<RV>(key: impl ToRedisArgs): "HVALS".key(key);
    /// The name of a field chosen at random.
    read fn hrandfield<RV>(key: impl ToRedisArgs): "HRANDFIELD".key(key);

    /// Sets a field, returning 1 if it is new and 0 if it was replaced.
    write fn hset(key: impl ToRedisArgs, field: impl ToRedisArgs, value: impl ToRedisArgs) -> u64:
        "HSET".key(key).arg(field).arg(value);
    /// Sets several fields, returning how many are new.
    write fn hset_multiple(
        key: impl ToRedisArgs,
        items: &[(impl ToRedisArgs, impl ToRedisArgs)]
    ) -> u64: "HSET".key(key).args_of(items);
    /// Sets a field unless it exists. `false` if it does.
    write fn hset_nx(
        key: impl ToRedisArgs,
        field: impl ToRedisArgs,
        value: impl ToRedisArgs
    ) -> bool: "HSETNX".key(key).arg(field).arg(value);
    /// Deletes the fields, returning how many existed.
    write fn hdel(key: impl ToRedisArgs, fields: impl ToRedisArgs) -> u64:
        "HDEL".key(key).arg(fields);
    /// Adds `delta` to the number in a field, returning the result. An
    /// integer `delta` is `HINCRBY`, replying an `i64`; a float is
    /// `HINCRBYFLOAT`, replying an `f64`.
    write fn hincr<D: Increment>(key: impl ToRedisArgs, field: impl ToRedisArgs, delta: D) -> D::Reply:
        "HINCRBY".or_float("HINCRBYFLOAT", D::FLOAT).key(key).arg(field).arg(delta);
}

group! {
    /// Commands on lists.
    group = list;

    /// The elements from index `start` to index `stop`, inclusive. Negative
    /// indexes count from the end: `0, -1` is the whole list.
    read fn lrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
        "LRANGE".key(key).arg(start).arg(stop);
    /// The element at an index.
    read fn lindex<RV>(key: impl ToRedisArgs, index: isize): "LINDEX".key(key).arg(index);
    /// How many elements the list has.
    read fn llen(key: impl ToRedisArgs) -> u64: "LLEN".key(key);
    /// The index of the first element equal to `value`.
    read fn lpos(key: impl ToRedisArgs, value: impl ToRedisArgs) -> Option<u64>:
        "LPOS".key(key).arg(value);

    /// Prepends the values, returning the list's new length.
    write fn lpush(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
        "LPUSH".key(key).arg(values);
    /// Appends the values, returning the list's new length.
    write fn rpush(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
        "RPUSH".key(key).arg(values);
    /// Prepends the values if the list exists, returning its length.
    write fn lpush_exists(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
        "LPUSHX".key(key).arg(values);
    /// Appends the values if the list exists, returning its length.
    write fn rpush_exists(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
        "RPUSHX".key(key).arg(values);
    /// Removes and returns the first element, or with `count` that many, as a
    /// list.
    write fn lpop<RV>(key: impl ToRedisArgs, count: Option<std::num::NonZeroUsize>):
        "LPOP".key(key).arg(count.map(std::num::NonZeroUsize::get));
    /// Removes and returns the last element, or with `count` that many, as a
    /// list.
    write fn rpop<RV>(key: impl ToRedisArgs, count: Option<std::num::NonZeroUsize>):
        "RPOP".key(key).arg(count.map(std::num::NonZeroUsize::get));
    /// Replaces the element at an index.
    write fn lset(key: impl ToRedisArgs, index: isize, value: impl ToRedisArgs) -> ():
        "LSET".key(key).arg(index).arg(value);
    /// Keeps only the elements from index `start` to index `stop`, inclusive.
    write fn ltrim(key: impl ToRedisArgs, start: isize, stop: isize) -> ():
        "LTRIM".key(key).arg(start).arg(stop);
    /// Inserts the value before the first element equal to `pivot`, returning
    /// the list's new length, or -1 if there is no such element.
    write fn linsert_before(
        key: impl ToRedisArgs,
        pivot: impl ToRedisArgs,
        value: impl ToRedisArgs
    ) -> i64: "LINSERT".key(key).arg("BEFORE").arg(pivot).arg(value);
    /// Inserts the value after the first element equal to `pivot`, returning
    /// the list's new length, or -1 if there is no such element.
    write fn linsert_after(
        key: impl ToRedisArgs,
        pivot: impl ToRedisArgs,
        value: impl ToRedisArgs
    ) -> i64: "LINSERT".key(key).arg("AFTER").arg(pivot).arg(value);
    /// Removes elements equal to `value`: the first `count` of them, the last
    /// `-count` if it is negative, or all if it is 0. Returns how many.
    write fn lrem(key: impl ToRedisArgs, count: isize, value: impl ToRedisArgs) -> u64:
        "LREM".key(key).arg(count).arg(value);
    /// Moves an element from one end of `source` to one end of `destination`,
    /// returning it.
    write fn lmove<RV>(
        source: impl ToRedisArgs,
        destination: impl ToRedisArgs,
        from: Direction,
        to: Direction
    ): "LMOVE".key(source).key(destination).arg(from).arg(to);
}

group! {
    /// Commands on sets.
    group = set;

    /// Every member.
    read fn smembers<RV>(key: impl ToRedisArgs): "SMEMBERS".key(key);
    /// Whether the value is a member.
    read fn sismember(key: impl ToRedisArgs, member: impl ToRedisArgs) -> bool:
        "SISMEMBER".key(key).arg(member);
    /// Whether each of the values is a member, in order.
    read fn smismember(key: impl ToRedisArgs, members: impl ToRedisArgs) -> Vec<bool>:
        "SMISMEMBER".key(key).arg(members);
    /// How many members the set has.
    read fn scard(key: impl ToRedisArgs) -> u64: "SCARD".key(key);
    /// A member chosen at random.
    read fn srandmember<RV>(key: impl ToRedisArgs): "SRANDMEMBER".key(key);
    /// `count` distinct members chosen at random, or with a negative `count`
    /// that many, possibly repeated.
    read fn srandmember_multiple<RV>(key: impl ToRedisArgs, count: isize):
        "SRANDMEMBER".key(key).arg(count);
    /// The members of the first set that are in none of the others.
    read fn sdiff<RV>(keys: impl ToRedisArgs): "SDIFF".key(keys);
    /// The members that are in every one of the sets.
    read fn sinter<RV>(keys: impl ToRedisArgs): "SINTER".key(keys);
    /// The members that are in any of the sets.
    read fn sunion<RV>(keys: impl ToRedisArgs): "SUNION".key(keys);

    /// Adds the members, returning how many are new.
    write fn sadd(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
        "SADD".key(key).arg(members);
    /// Removes the members, returning how many there were.
    write fn srem(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
        "SREM".key(key).arg(members);
    /// Removes and returns a member chosen at random.
    write fn spop<RV>(key: impl ToRedisArgs): "SPOP".key(key);
    /// Moves a member from one set to another. `false` if it is not in
    /// `source`.
    write fn smove(
        source: impl ToRedisArgs,
        destination: impl ToRedisArgs,
        member: impl ToRedisArgs
    ) -> bool: "SMOVE".key(source).key(destination).arg(member);
    /// Stores [`Commands::sdiff`] of the sets at `destination`, returning its
    /// size.
    write fn sdiffstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
        "SDIFFSTORE".key(destination).key(keys);
    /// Stores [`Commands::sinter`] of the sets at `destination`, returning its
    /// size.
    write fn sinterstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
        "SINTERSTORE".key(destination).key(keys);
    /// Stores [`Commands::sunion`] of the sets at `destination`, returning its
    /// size.
    write fn sunionstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
        "SUNIONSTORE".key(destination).key(keys);
}

group! {
    /// Commands on sorted sets: members ordered by a score.
    group = sorted_set;

    /// The members ranked `start` to `stop`, inclusive, lowest score first.
    /// Negative ranks count from the highest: `0, -1` is every member.
    read fn zrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
        "ZRANGE".key(key).arg(start).arg(stop);
    /// [`Commands::zrange`], each member with its score.
    read fn zrange_withscores<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
        "ZRANGE".key(key).arg(start).arg(stop).arg("WITHSCORES");
    /// The members ranked `start` to `stop`, inclusive, highest score first.
    read fn zrevrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
        "ZREVRANGE".key(key).arg(start).arg(stop);
    /// [`Commands::zrevrange`], each member with its score.
    read fn zrevrange_withscores<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
        "ZREVRANGE".key(key).arg(start).arg(stop).arg("WITHSCORES");
    /// The members with a score from `min` to `max`, lowest first. A bound is
    /// a number, `"-inf"` or `"+inf"`, or exclusive as `"(1.5"`.
    read fn zrangebyscore<RV>(key: impl ToRedisArgs, min: impl ToRedisArgs, max: impl ToRedisArgs):
        "ZRANGEBYSCORE".key(key).arg(min).arg(max);
    /// [`Commands::zrangebyscore`], each member with its score.
    read fn zrangebyscore_withscores<RV>(
        key: impl ToRedisArgs,
        min: impl ToRedisArgs,
        max: impl ToRedisArgs
    ): "ZRANGEBYSCORE".key(key).arg(min).arg(max).arg("WITHSCORES");
    /// A member's score.
    read fn zscore(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<f64>:
        "ZSCORE".key(key).arg(member);
    /// A member's rank, lowest score first, from 0.
    read fn zrank(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<u64>:
        "ZRANK".key(key).arg(member);
    /// A member's rank, highest score first, from 0.
    read fn zrevrank(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<u64>:
        "ZREVRANK".key(key).arg(member);
    /// How many members the set has.
    read fn zcard(key: impl ToRedisArgs) -> u64: "ZCARD".key(key);
    /// How many members have a score from `min` to `max`.
    read fn zcount(key: impl ToRedisArgs, min: impl ToRedisArgs, max: impl ToRedisArgs) -> u64:
        "ZCOUNT".key(key).arg(min).arg(max);
    /// A member chosen at random.
    read fn zrandmember<RV>(key: impl ToRedisArgs): "ZRANDMEMBER".key(key);

    /// Adds a member with a score, or updates its score. Returns 1 if it is
    /// new.
    write fn zadd(key: impl ToRedisArgs, member: impl ToRedisArgs, score: f64) -> u64:
        "ZADD".key(key).arg(score).arg(member);
    /// Adds several members, each given as `(score, member)`, returning how
    /// many are new.
    write fn zadd_multiple(key: impl ToRedisArgs, items: &[(f64, impl ToRedisArgs)]) -> u64:
        "ZADD".key(key).args_of(items);
    /// Removes the members, returning how many there were.
    write fn zrem(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
        "ZREM".key(key).arg(members);
    /// Adds `delta` to a member's score, returning the result.
    write fn zincr(key: impl ToRedisArgs, member: impl ToRedisArgs, delta: impl Increment) -> f64:
        "ZINCRBY".key(key).arg(delta).arg(member);
    /// Removes and returns the `count` members with the lowest scores, each
    /// with its score.
    write fn zpopmin<RV>(key: impl ToRedisArgs, count: usize): "ZPOPMIN".key(key).arg(count);
    /// Removes and returns the `count` members with the highest scores, each
    /// with its score.
    write fn zpopmax<RV>(key: impl ToRedisArgs, count: usize): "ZPOPMAX".key(key).arg(count);
    /// Removes the members with a score from `min` to `max`, returning how
    /// many.
    write fn zrembyscore(
        key: impl ToRedisArgs,
        min: impl ToRedisArgs,
        max: impl ToRedisArgs
    ) -> u64: "ZREMRANGEBYSCORE".key(key).arg(min).arg(max);
    /// Removes the members ranked `start` to `stop`, returning how many.
    write fn zremrangebyrank(key: impl ToRedisArgs, start: isize, stop: isize) -> u64:
        "ZREMRANGEBYRANK".key(key).arg(start).arg(stop);
    /// Stores at `destination` the members in every one of the sets, their
    /// scores summed. Returns its size.
    write fn zinterstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
        "ZINTERSTORE".key(destination).numkeys(keys);
    /// Stores at `destination` the members in any of the sets, their scores
    /// summed. Returns its size.
    write fn zunionstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
        "ZUNIONSTORE".key(destination).numkeys(keys);
}

group! {
    /// Commands on geospatial indexes.
    group = geo;
    uses {
        pub use rs::geo::{Coord, RadiusOptions, RadiusOrder, RadiusSearchResult, Unit};
    }

    /// The positions of the members, each missing one as `None`.
    read fn geo_pos<RV>(key: impl ToRedisArgs, members: impl ToRedisArgs):
        "GEOPOS".key(key).arg(members);
    /// The distance between two members.
    read fn geo_dist(
        key: impl ToRedisArgs,
        from: impl ToRedisArgs,
        to: impl ToRedisArgs,
        unit: Unit
    ) -> Option<f64>: "GEODIST".key(key).arg(from).arg(to).arg(unit);
    /// The geohash of each member.
    read fn geo_hash<RV>(key: impl ToRedisArgs, members: impl ToRedisArgs):
        "GEOHASH".key(key).arg(members);
    /// The members within `radius` of a position.
    read fn geo_radius<RV>(
        key: impl ToRedisArgs,
        longitude: f64,
        latitude: f64,
        radius: f64,
        unit: Unit,
        options: RadiusOptions
    ): "GEORADIUS_RO".key(key).arg(longitude).arg(latitude).arg(radius).arg(unit).arg(options);
    /// The members within `radius` of another member.
    read fn geo_radius_by_member<RV>(
        key: impl ToRedisArgs,
        member: impl ToRedisArgs,
        radius: f64,
        unit: Unit,
        options: RadiusOptions
    ): "GEORADIUSBYMEMBER_RO".key(key).arg(member).arg(radius).arg(unit).arg(options);

    /// Adds a member at a position, or moves it there. Returns 1 if it is new.
    write fn geo_add(
        key: impl ToRedisArgs,
        longitude: f64,
        latitude: f64,
        member: impl ToRedisArgs
    ) -> u64: "GEOADD".key(key).arg(longitude).arg(latitude).arg(member);
}

group! {
    /// Commands on streams.
    group = stream;
    uses {
        pub use rs::streams::{
            StreamAutoClaimReply, StreamClaimReply, StreamId, StreamInfoStreamReply, StreamKey,
            StreamMaxlen, StreamPendingReply, StreamRangeReply, StreamReadReply,
        };
    }

    /// The entries with an id from `start` to `end`, oldest first. `"-"` and
    /// `"+"` are the lowest and highest ids. Read as a [`StreamRangeReply`].
    read fn xrange<RV>(key: impl ToRedisArgs, start: impl ToRedisArgs, end: impl ToRedisArgs):
        "XRANGE".key(key).arg(start).arg(end);
    /// [`Commands::xrange`], at most `count` entries.
    read fn xrange_count<RV>(
        key: impl ToRedisArgs,
        start: impl ToRedisArgs,
        end: impl ToRedisArgs,
        count: usize
    ): "XRANGE".key(key).arg(start).arg(end).arg("COUNT").arg(count);
    /// The entries with an id from `end` down to `start`, newest first.
    read fn xrevrange<RV>(key: impl ToRedisArgs, end: impl ToRedisArgs, start: impl ToRedisArgs):
        "XREVRANGE".key(key).arg(end).arg(start);
    /// [`Commands::xrevrange`], at most `count` entries.
    read fn xrevrange_count<RV>(
        key: impl ToRedisArgs,
        end: impl ToRedisArgs,
        start: impl ToRedisArgs,
        count: usize
    ): "XREVRANGE".key(key).arg(end).arg(start).arg("COUNT").arg(count);
    /// How many entries the stream has.
    read fn xlen(key: impl ToRedisArgs) -> u64: "XLEN".key(key);
    /// The entries after an id in each of the streams, `ids` giving the id for
    /// each of `keys` in order. Returns at once with what is there. Read as a
    /// [`StreamReadReply`].
    read fn xread<RV>(keys: impl ToRedisArgs, ids: impl ToRedisArgs):
        "XREAD".arg("STREAMS").key(keys).arg(ids).reply_keys();
    /// A summary of the entries a consumer group has been given and not
    /// acknowledged. Read as a [`StreamPendingReply`].
    read fn xpending<RV>(key: impl ToRedisArgs, group: impl ToRedisArgs):
        "XPENDING".key(key).arg(group);
    /// What the server knows about the stream. Read as a
    /// [`StreamInfoStreamReply`].
    read fn xinfo_stream<RV>(key: impl ToRedisArgs): "XINFO".arg("STREAM").key(key);

    /// Appends an entry with the given fields, returning its id. Pass `"*"`
    /// as the id to have the server choose it.
    write fn xadd<RV>(
        key: impl ToRedisArgs,
        id: impl ToRedisArgs,
        items: &[(impl ToRedisArgs, impl ToRedisArgs)]
    ): "XADD".key(key).arg(id).args_of(items);
    /// [`Commands::xadd`], trimming the stream to a maximum length.
    write fn xadd_maxlen<RV>(
        key: impl ToRedisArgs,
        maxlen: StreamMaxlen,
        id: impl ToRedisArgs,
        items: &[(impl ToRedisArgs, impl ToRedisArgs)]
    ): "XADD".key(key).arg(maxlen).arg(id).args_of(items);
    /// Deletes the entries with the given ids, returning how many existed.
    write fn xdel(key: impl ToRedisArgs, ids: impl ToRedisArgs) -> u64: "XDEL".key(key).arg(ids);
    /// Trims the stream to a maximum length, returning how many entries were
    /// removed.
    write fn xtrim(key: impl ToRedisArgs, maxlen: StreamMaxlen) -> u64:
        "XTRIM".key(key).arg(maxlen);
    /// Creates a consumer group that starts reading after `id`: `"$"` for only
    /// new entries, `"0"` for all. The stream must exist.
    write fn xgroup_create(
        key: impl ToRedisArgs,
        group: impl ToRedisArgs,
        id: impl ToRedisArgs
    ) -> (): "XGROUP".arg("CREATE").key(key).arg(group).arg(id);
    /// [`Commands::xgroup_create`], creating the stream if it does not exist.
    write fn xgroup_create_mkstream(
        key: impl ToRedisArgs,
        group: impl ToRedisArgs,
        id: impl ToRedisArgs
    ) -> (): "XGROUP".arg("CREATE").key(key).arg(group).arg(id).arg("MKSTREAM");
    /// Deletes a consumer group. `false` if there was none.
    write fn xgroup_destroy(key: impl ToRedisArgs, group: impl ToRedisArgs) -> bool:
        "XGROUP".arg("DESTROY").key(key).arg(group);
    /// Reads entries as `consumer` of a group: `">"` as the id for the ones
    /// no consumer has been given yet. At most `count` per stream. A write: it
    /// records them as given to the consumer. Read as a [`StreamReadReply`].
    write fn xread_group<RV>(
        group: impl ToRedisArgs,
        consumer: impl ToRedisArgs,
        keys: impl ToRedisArgs,
        ids: impl ToRedisArgs,
        count: Option<usize>
    ): "XREADGROUP".arg("GROUP").arg(group).arg(consumer).arg(count.map(|n| ("COUNT", n)))
        .arg("STREAMS").key(keys).arg(ids).reply_keys();
    /// Acknowledges entries a consumer group was given, returning how many
    /// were pending.
    write fn xack(key: impl ToRedisArgs, group: impl ToRedisArgs, ids: impl ToRedisArgs) -> u64:
        "XACK".key(key).arg(group).arg(ids);
    /// Takes over pending entries that have been idle for `min_idle_ms`, for
    /// `consumer`. Read as a [`StreamClaimReply`].
    write fn xclaim<RV>(
        key: impl ToRedisArgs,
        group: impl ToRedisArgs,
        consumer: impl ToRedisArgs,
        min_idle_ms: u64,
        ids: impl ToRedisArgs
    ): "XCLAIM".key(key).arg(group).arg(consumer).arg(min_idle_ms).arg(ids);
    /// Takes over the pending entries from id `start` that have been idle for
    /// `min_idle_ms`, for `consumer`. Read as a [`StreamAutoClaimReply`].
    write fn xautoclaim<RV>(
        key: impl ToRedisArgs,
        group: impl ToRedisArgs,
        consumer: impl ToRedisArgs,
        min_idle_ms: u64,
        start: impl ToRedisArgs
    ): "XAUTOCLAIM".key(key).arg(group).arg(consumer).arg(min_idle_ms).arg(start);
}

impl Cmd {
    /// Appends pairs whose first halves are keys: `MSET`'s.
    fn pairs(mut self, items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> Self {
        for (key, value) in items {
            self = self.key(Raw(key)).arg(Raw(value));
        }
        self
    }

    /// Appends pairs that are not keys, each half an argument of its own:
    /// fields and values, scores and members.
    fn args_of(mut self, items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> Self {
        for (first, second) in items {
            self = self.arg(Raw(first)).arg(Raw(second));
        }
        self
    }
}

/// A borrowed argument, which the conversion trait is not implemented for by
/// itself: only for a reference to something `redis` converts.
struct Raw<'a, T>(&'a T);

impl<T: ToRedisArgs> ToRedisArgs for Raw<'_, T> {
    fn write_redis_args<W: ?Sized + rs::RedisWrite>(&self, out: &mut W) {
        self.0.write_redis_args(out)
    }
}

/// What a scan looks through, and how much at a time.
#[derive(Debug, Clone, Default)]
pub struct ScanOptions {
    pattern: Option<String>,
    count: Option<usize>,
}

impl ScanOptions {
    /// Only what matches a glob-style pattern: `user:*`.
    pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
        self.pattern = Some(pattern.into());
        self
    }

    /// A hint for how many elements to look at per round trip.
    pub fn count(mut self, count: usize) -> Self {
        self.count = Some(count);
        self
    }
}

/// What a [`Scan`] walks: the keys of the database, or the elements of one key.
#[derive(Clone)]
enum Scanned {
    Keys,
    /// The elements of the key, which come `width` values to an element: a
    /// member alone, or a field with its value, a member with its score.
    Elements {
        operation: &'static str,
        command: &'static str,
        key: Vec<u8>,
        width: usize,
    },
}

/// An iteration over the keys of a database, or the elements of one key, a
/// batch per round trip.
///
/// ```no_run
/// # use encore::storage::redis::{Database, ScanOptions};
/// # static SESSIONS: Database = Database::new("sessions");
/// # async fn example() -> Result<(), encore::Error> {
/// let mut keys = SESSIONS.generic().scan::<String>(ScanOptions::default().pattern("user:*"));
/// while let Some(key) = keys.next().await {
///     let key = key?;
/// }
/// # Ok(())
/// # }
/// ```
///
/// As with Redis's own `SCAN`, an element present for the whole iteration is
/// returned at least once — possibly more — and one added or removed during it
/// may or may not be.
pub struct Scan<'a, T> {
    target: Target<'a>,
    scanned: Scanned,
    options: ScanOptions,
    /// `None` once the server has said there is no more.
    cursor: Option<u64>,
    /// The batch being handed out, last element first.
    batch: Vec<Value>,
    item: PhantomData<fn() -> T>,
}

impl<'a, T: FromRedisValue> Scan<'a, T> {
    fn new(target: Target<'a>, scanned: Scanned, options: ScanOptions) -> Self {
        Self {
            target,
            scanned,
            options,
            cursor: Some(0),
            batch: Vec::new(),
            item: PhantomData,
        }
    }

    /// The next element, or `None` when the iteration is done.
    pub async fn next(&mut self) -> Option<Result<T, Error>> {
        loop {
            if let Some(value) = self.batch.pop() {
                return Some(T::from_redis_value(value));
            }
            let cursor = self.cursor?;
            if let Err(err) = self.fetch(cursor).await {
                // An iteration that failed is over: asking again would repeat
                // the request that failed.
                self.cursor = None;
                return Some(Err(err));
            }
        }
    }

    /// Fetches the batch at `cursor`.
    async fn fetch(&mut self, cursor: u64) -> Result<(), Error> {
        let prefix = self.target.client()?.key_prefix().map(str::to_owned);
        let mut cmd = match &self.scanned {
            Scanned::Keys => core_cache::Command::new("scan", "SCAN", false),
            Scanned::Elements {
                operation,
                command,
                key,
                ..
            } => core_cache::Command::new(operation, *command, false).key(key.as_slice()),
        }
        .arg(cursor.to_string());

        // Keys are scanned across the whole server, so the pattern has to
        // select this database's: its prefix, then what was asked for.
        let pattern = match (&self.scanned, &prefix, &self.options.pattern) {
            (Scanned::Keys, Some(prefix), pattern) => Some(format!(
                "{}{}",
                escape_glob(prefix),
                pattern.as_deref().unwrap_or("*")
            )),
            (_, _, pattern) => pattern.clone(),
        };
        if let Some(pattern) = pattern {
            cmd = cmd.arg("MATCH").arg(pattern);
        }
        if let Some(count) = self.options.count {
            cmd = cmd.arg("COUNT").arg(count.to_string());
        }

        let reply = self.target.reply(&cmd).await.map_err(redis_err)?;
        let (next, mut values): (u64, Vec<Value>) = FromRedisValue::from_redis_value(reply)?;
        self.cursor = (next != 0).then_some(next);

        match &self.scanned {
            Scanned::Keys => {
                if let Some(prefix) = &prefix {
                    for value in &mut values {
                        if let Value::BulkString(key) = value {
                            if key.starts_with(prefix.as_bytes()) {
                                key.drain(..prefix.len());
                            }
                        }
                    }
                }
            }
            Scanned::Elements { width, .. } if *width > 1 => {
                if values.len() % width != 0 {
                    return Err(Error::new(
                        ErrCode::Internal,
                        "the scan's reply does not divide into elements",
                    ));
                }
                values = values
                    .chunks(*width)
                    .map(|element| Value::Array(element.to_vec()))
                    .collect();
            }
            Scanned::Elements { .. } => {}
        }
        // Handed out from the end, so the first is last.
        values.reverse();
        self.batch = values;
        Ok(())
    }
}

/// `text` with the characters a glob pattern gives meaning to escaped.
fn escape_glob(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        if matches!(c, '*' | '?' | '[' | ']' | '\\') {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// The scans, on both forms that run commands. Written out rather than listed
/// with the group's commands: they return an iteration, not a reply.
macro_rules! scans {
    ($group:ident: $($(#[$doc:meta])* fn $name:ident($($key:ident)?) = $scanned:expr;)*) => {
        scans!(@on $group, Commands: $($(#[$doc])* fn $name($($key)?) = $scanned;)*);
        scans!(@on $group, ReadCommands: $($(#[$doc])* fn $name($($key)?) = $scanned;)*);
    };
    (
        @on $group:ident, $form:ident:
        $($(#[$doc:meta])* fn $name:ident($($key:ident)?) = $scanned:expr;)*
    ) => {
        impl<'a> $group::$form<'a> {
            $(
                $(#[$doc])*
                pub fn $name<T: FromRedisValue>(
                    &self,
                    $($key: impl ToRedisArgs,)?
                    options: ScanOptions,
                ) -> Scan<'a, T> {
                    Scan::new(self.target, $scanned, options)
                }
            )*
        }
    };
}

/// The scan of one key's elements.
fn elements(
    operation: &'static str,
    command: &'static str,
    key: impl ToRedisArgs,
    width: usize,
) -> Scanned {
    Scanned::Elements {
        operation,
        command,
        key: key.to_redis_args().into_iter().next().unwrap_or_default(),
        width,
    }
}

// command: read generic scan
scans!(generic:
    /// Iterates over the database's keys.
    fn scan() = Scanned::Keys;
);

// command: read hash hscan
scans!(hash:
    /// Iterates over the hash's fields, each a `(field, value)` pair.
    fn hscan(key) = elements("hscan", "HSCAN", key, 2);
);

// command: read set sscan
scans!(set:
    /// Iterates over the set's members.
    fn sscan(key) = elements("sscan", "SSCAN", key, 1);
);

// command: read sorted_set zscan
scans!(sorted_set:
    /// Iterates over the sorted set's members, each a `(member, score)` pair.
    fn zscan(key) = elements("zscan", "ZSCAN", key, 2);
);

/// Publishing to channels, and subscribing to them.
///
/// This is Redis's own channel messaging, where a message reaches whoever is
/// subscribed at that moment and nobody else. For messages that are kept until
/// they are handled, use [`crate::pubsub`].
pub mod pubsub {
    use super::*;

    /// The group's commands, run as they are called.
    #[derive(Clone, Copy)]
    pub struct Commands<'a> {
        pub(in crate::storage::redis) target: Target<'a>,
    }

    /// The group's commands that only read: subscribing.
    #[derive(Clone, Copy)]
    pub struct ReadCommands<'a> {
        pub(in crate::storage::redis) target: Target<'a>,
    }

    /// The group's commands, queued on a pipeline or a transaction.
    pub struct Queue<'a> {
        pub(in crate::storage::redis) queue: &'a mut crate::storage::redis::Queued,
    }

    fn publish(channel: impl ToRedisArgs, message: impl ToRedisArgs) -> Cmd {
        // A channel is prefixed like a key, so only this database's
        // subscribers hear it.
        Cmd::new("publish", "PUBLISH", true)
            .key(channel)
            .arg(message)
    }

    async fn subscribe(
        target: Target<'_>,
        channels: impl ToRedisArgs,
        patterns: impl ToRedisArgs,
    ) -> Result<Subscription, Error> {
        let inner = target
            .client()?
            .subscribe(&channels.to_redis_args(), &patterns.to_redis_args())
            .await
            .map_err(redis_err)?;
        Ok(Subscription { inner })
    }

    impl Commands<'_> {
        // command: write pubsub publish
        /// Publishes a message to a channel, returning how many subscribers
        /// received it.
        pub async fn publish(
            &self,
            channel: impl ToRedisArgs,
            message: impl ToRedisArgs,
        ) -> Result<u64, Error> {
            self.target.run(publish(channel, message)).await
        }

        // command: read pubsub subscribe
        /// Subscribes to one or more channels, on a connection of its own.
        pub async fn subscribe(&self, channels: impl ToRedisArgs) -> Result<Subscription, Error> {
            subscribe(self.target, channels, Vec::<Vec<u8>>::new()).await
        }

        // command: read pubsub psubscribe
        /// Subscribes to the channels matching one or more glob-style
        /// patterns, on a connection of its own.
        pub async fn psubscribe(&self, patterns: impl ToRedisArgs) -> Result<Subscription, Error> {
            subscribe(self.target, Vec::<Vec<u8>>::new(), patterns).await
        }
    }

    impl ReadCommands<'_> {
        /// See [`Commands::subscribe`].
        pub async fn subscribe(&self, channels: impl ToRedisArgs) -> Result<Subscription, Error> {
            subscribe(self.target, channels, Vec::<Vec<u8>>::new()).await
        }

        /// See [`Commands::psubscribe`].
        pub async fn psubscribe(&self, patterns: impl ToRedisArgs) -> Result<Subscription, Error> {
            subscribe(self.target, Vec::<Vec<u8>>::new(), patterns).await
        }
    }

    impl Queue<'_> {
        /// See [`Commands::publish`].
        pub fn publish(
            &mut self,
            channel: impl ToRedisArgs,
            message: impl ToRedisArgs,
        ) -> &mut Self {
            self.queue.push(publish(channel, message));
            self
        }
    }

    /// An open subscription. Dropping it closes its connection, which
    /// unsubscribes.
    pub struct Subscription {
        inner: core_cache::Subscription,
    }

    impl Subscription {
        /// The next message, or `None` once the connection has closed.
        pub async fn next(&mut self) -> Option<Message> {
            let message = self.inner.next().await?;
            Some(Message {
                channel: String::from_utf8_lossy(&message.channel).into_owned(),
                payload: message.payload,
            })
        }
    }

    /// A message received on a [`Subscription`].
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct Message {
        /// The channel it was published to.
        pub channel: String,
        /// What was published, as it was sent.
        pub payload: Vec<u8>,
    }

    impl Message {
        /// The payload, converted.
        pub fn payload<T: FromRedisValue>(&self) -> Result<T, Error> {
            T::from_redis_value(Value::BulkString(self.payload.clone()))
        }
    }
}

use rs::{Direction, Expiry, SetOptions};