1use 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
21pub(crate) struct Cmd {
23 pub(super) inner: core_cache::Command,
24 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 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 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 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 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 fn reply_keys(mut self) -> Self {
80 self.reply_keys = true;
81 self
82 }
83}
84
85pub(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
117macro_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
158macro_rules! writes {
160 (read) => {
161 false
162 };
163 (write) => {
164 true
165 };
166}
167
168macro_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 (
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
219macro_rules! group {
221 (
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 #[derive(Clone, Copy)]
251 pub struct Commands<'a> {
252 pub(in crate::storage::redis) target: Target<'a>,
253 }
254
255 #[derive(Clone, Copy)]
257 pub struct ReadCommands<'a> {
258 pub(in crate::storage::redis) target: Target<'a>,
259 }
260
261 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 group = generic;
285
286 read fn exists(key: impl ToRedisArgs) -> bool: "EXISTS".key(key);
288 read fn ttl(key: impl ToRedisArgs) -> i64: "TTL".key(key);
291 read fn pttl(key: impl ToRedisArgs) -> i64: "PTTL".key(key);
294 read fn key_type(key: impl ToRedisArgs) -> String: "TYPE".key(key);
297 read fn expire_time(key: impl ToRedisArgs) -> i64: "EXPIRETIME".key(key);
300
301 write fn del(keys: impl ToRedisArgs) -> u64: "DEL".key(keys);
303 write fn unlink(keys: impl ToRedisArgs) -> u64: "UNLINK".key(keys);
306 write fn expire(key: impl ToRedisArgs, seconds: i64) -> bool: "EXPIRE".key(key).arg(seconds);
308 write fn pexpire(key: impl ToRedisArgs, milliseconds: i64) -> bool:
310 "PEXPIRE".key(key).arg(milliseconds);
311 write fn expire_at(key: impl ToRedisArgs, timestamp: i64) -> bool:
314 "EXPIREAT".key(key).arg(timestamp);
315 write fn persist(key: impl ToRedisArgs) -> bool: "PERSIST".key(key);
317 write fn rename(key: impl ToRedisArgs, new_key: impl ToRedisArgs) -> ():
319 "RENAME".key(key).key(new_key);
320 write fn rename_nx(key: impl ToRedisArgs, new_key: impl ToRedisArgs) -> bool:
322 "RENAMENX".key(key).key(new_key);
323 write fn copy(source: impl ToRedisArgs, destination: impl ToRedisArgs) -> bool:
326 "COPY".key(source).key(destination);
327 write fn touch(keys: impl ToRedisArgs) -> u64: "TOUCH".key(keys);
329}
330
331group! {
332 group = string;
334
335 read fn get<RV>(key: impl ToRedisArgs): "GET".key(key);
337 read fn mget<RV>(keys: impl ToRedisArgs): "MGET".key(keys);
339 read fn strlen(key: impl ToRedisArgs) -> u64: "STRLEN".key(key);
341 read fn getrange<RV>(key: impl ToRedisArgs, from: isize, to: isize):
344 "GETRANGE".key(key).arg(from).arg(to);
345
346 write fn set(key: impl ToRedisArgs, value: impl ToRedisArgs) -> (): "SET".key(key).arg(value);
348 write fn set_ex(key: impl ToRedisArgs, value: impl ToRedisArgs, seconds: u64) -> ():
350 "SETEX".key(key).arg(seconds).arg(value);
351 write fn set_nx(key: impl ToRedisArgs, value: impl ToRedisArgs) -> bool:
353 "SETNX".key(key).arg(value);
354 write fn set_options<RV>(key: impl ToRedisArgs, value: impl ToRedisArgs, options: SetOptions):
357 "SET".key(key).arg(value).arg(options);
358 write fn mset(items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> (): "MSET".pairs(items);
360 write fn mset_nx(items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> bool:
363 "MSETNX".pairs(items);
364 write fn get_del<RV>(key: impl ToRedisArgs): "GETDEL".key(key);
366 write fn get_ex<RV>(key: impl ToRedisArgs, expiry: Expiry): "GETEX".key(key).arg(expiry);
368 write fn append(key: impl ToRedisArgs, value: impl ToRedisArgs) -> u64:
370 "APPEND".key(key).arg(value);
371 write fn setrange(key: impl ToRedisArgs, offset: usize, value: impl ToRedisArgs) -> u64:
373 "SETRANGE".key(key).arg(offset).arg(value);
374 write fn incr<D: Increment>(key: impl ToRedisArgs, delta: D) -> D::Reply:
378 "INCRBY".or_float("INCRBYFLOAT", D::FLOAT).key(key).arg(delta);
379 write fn decr(key: impl ToRedisArgs, delta: i64) -> i64: "DECRBY".key(key).arg(delta);
381}
382
383group! {
384 group = bitmap;
386
387 read fn getbit(key: impl ToRedisArgs, offset: u64) -> bool: "GETBIT".key(key).arg(offset);
389 read fn bitcount(key: impl ToRedisArgs) -> u64: "BITCOUNT".key(key);
391 read fn bitcount_range(key: impl ToRedisArgs, start: isize, end: isize) -> u64:
393 "BITCOUNT".key(key).arg(start).arg(end);
394 read fn bitpos(key: impl ToRedisArgs, bit: bool) -> i64: "BITPOS".key(key).arg(bit as u8);
396
397 write fn setbit(key: impl ToRedisArgs, offset: u64, value: bool) -> bool:
399 "SETBIT".key(key).arg(offset).arg(value as u8);
400 write fn bit_and(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
403 "BITOP".arg("AND").key(destination).key(sources);
404 write fn bit_or(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
407 "BITOP".arg("OR").key(destination).key(sources);
408 write fn bit_xor(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
411 "BITOP".arg("XOR").key(destination).key(sources);
412 write fn bit_not(destination: impl ToRedisArgs, source: impl ToRedisArgs) -> u64:
415 "BITOP".arg("NOT").key(destination).key(source);
416}
417
418group! {
419 group = hash;
421
422 read fn hget<RV>(key: impl ToRedisArgs, field: impl ToRedisArgs): "HGET".key(key).arg(field);
424 read fn hmget<RV>(key: impl ToRedisArgs, fields: impl ToRedisArgs):
426 "HMGET".key(key).arg(fields);
427 read fn hgetall<RV>(key: impl ToRedisArgs): "HGETALL".key(key);
429 read fn hexists(key: impl ToRedisArgs, field: impl ToRedisArgs) -> bool:
431 "HEXISTS".key(key).arg(field);
432 read fn hlen(key: impl ToRedisArgs) -> u64: "HLEN".key(key);
434 read fn hkeys<RV>(key: impl ToRedisArgs): "HKEYS".key(key);
436 read fn hvals<RV>(key: impl ToRedisArgs): "HVALS".key(key);
438 read fn hrandfield<RV>(key: impl ToRedisArgs): "HRANDFIELD".key(key);
440
441 write fn hset(key: impl ToRedisArgs, field: impl ToRedisArgs, value: impl ToRedisArgs) -> u64:
443 "HSET".key(key).arg(field).arg(value);
444 write fn hset_multiple(
446 key: impl ToRedisArgs,
447 items: &[(impl ToRedisArgs, impl ToRedisArgs)]
448 ) -> u64: "HSET".key(key).args_of(items);
449 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 write fn hdel(key: impl ToRedisArgs, fields: impl ToRedisArgs) -> u64:
457 "HDEL".key(key).arg(fields);
458 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 group = list;
468
469 read fn lrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
472 "LRANGE".key(key).arg(start).arg(stop);
473 read fn lindex<RV>(key: impl ToRedisArgs, index: isize): "LINDEX".key(key).arg(index);
475 read fn llen(key: impl ToRedisArgs) -> u64: "LLEN".key(key);
477 read fn lpos(key: impl ToRedisArgs, value: impl ToRedisArgs) -> Option<u64>:
479 "LPOS".key(key).arg(value);
480
481 write fn lpush(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
483 "LPUSH".key(key).arg(values);
484 write fn rpush(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
486 "RPUSH".key(key).arg(values);
487 write fn lpush_exists(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
489 "LPUSHX".key(key).arg(values);
490 write fn rpush_exists(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
492 "RPUSHX".key(key).arg(values);
493 write fn lpop<RV>(key: impl ToRedisArgs, count: Option<std::num::NonZeroUsize>):
496 "LPOP".key(key).arg(count.map(std::num::NonZeroUsize::get));
497 write fn rpop<RV>(key: impl ToRedisArgs, count: Option<std::num::NonZeroUsize>):
500 "RPOP".key(key).arg(count.map(std::num::NonZeroUsize::get));
501 write fn lset(key: impl ToRedisArgs, index: isize, value: impl ToRedisArgs) -> ():
503 "LSET".key(key).arg(index).arg(value);
504 write fn ltrim(key: impl ToRedisArgs, start: isize, stop: isize) -> ():
506 "LTRIM".key(key).arg(start).arg(stop);
507 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 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 write fn lrem(key: impl ToRedisArgs, count: isize, value: impl ToRedisArgs) -> u64:
524 "LREM".key(key).arg(count).arg(value);
525 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 group = set;
538
539 read fn smembers<RV>(key: impl ToRedisArgs): "SMEMBERS".key(key);
541 read fn sismember(key: impl ToRedisArgs, member: impl ToRedisArgs) -> bool:
543 "SISMEMBER".key(key).arg(member);
544 read fn smismember(key: impl ToRedisArgs, members: impl ToRedisArgs) -> Vec<bool>:
546 "SMISMEMBER".key(key).arg(members);
547 read fn scard(key: impl ToRedisArgs) -> u64: "SCARD".key(key);
549 read fn srandmember<RV>(key: impl ToRedisArgs): "SRANDMEMBER".key(key);
551 read fn srandmember_multiple<RV>(key: impl ToRedisArgs, count: isize):
554 "SRANDMEMBER".key(key).arg(count);
555 read fn sdiff<RV>(keys: impl ToRedisArgs): "SDIFF".key(keys);
557 read fn sinter<RV>(keys: impl ToRedisArgs): "SINTER".key(keys);
559 read fn sunion<RV>(keys: impl ToRedisArgs): "SUNION".key(keys);
561
562 write fn sadd(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
564 "SADD".key(key).arg(members);
565 write fn srem(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
567 "SREM".key(key).arg(members);
568 write fn spop<RV>(key: impl ToRedisArgs): "SPOP".key(key);
570 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 write fn sdiffstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
580 "SDIFFSTORE".key(destination).key(keys);
581 write fn sinterstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
584 "SINTERSTORE".key(destination).key(keys);
585 write fn sunionstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
588 "SUNIONSTORE".key(destination).key(keys);
589}
590
591group! {
592 group = sorted_set;
594
595 read fn zrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
598 "ZRANGE".key(key).arg(start).arg(stop);
599 read fn zrange_withscores<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
601 "ZRANGE".key(key).arg(start).arg(stop).arg("WITHSCORES");
602 read fn zrevrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
604 "ZREVRANGE".key(key).arg(start).arg(stop);
605 read fn zrevrange_withscores<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
607 "ZREVRANGE".key(key).arg(start).arg(stop).arg("WITHSCORES");
608 read fn zrangebyscore<RV>(key: impl ToRedisArgs, min: impl ToRedisArgs, max: impl ToRedisArgs):
611 "ZRANGEBYSCORE".key(key).arg(min).arg(max);
612 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 read fn zscore(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<f64>:
620 "ZSCORE".key(key).arg(member);
621 read fn zrank(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<u64>:
623 "ZRANK".key(key).arg(member);
624 read fn zrevrank(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<u64>:
626 "ZREVRANK".key(key).arg(member);
627 read fn zcard(key: impl ToRedisArgs) -> u64: "ZCARD".key(key);
629 read fn zcount(key: impl ToRedisArgs, min: impl ToRedisArgs, max: impl ToRedisArgs) -> u64:
631 "ZCOUNT".key(key).arg(min).arg(max);
632 read fn zrandmember<RV>(key: impl ToRedisArgs): "ZRANDMEMBER".key(key);
634
635 write fn zadd(key: impl ToRedisArgs, member: impl ToRedisArgs, score: f64) -> u64:
638 "ZADD".key(key).arg(score).arg(member);
639 write fn zadd_multiple(key: impl ToRedisArgs, items: &[(f64, impl ToRedisArgs)]) -> u64:
642 "ZADD".key(key).args_of(items);
643 write fn zrem(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
645 "ZREM".key(key).arg(members);
646 write fn zincr(key: impl ToRedisArgs, member: impl ToRedisArgs, delta: impl Increment) -> f64:
648 "ZINCRBY".key(key).arg(delta).arg(member);
649 write fn zpopmin<RV>(key: impl ToRedisArgs, count: usize): "ZPOPMIN".key(key).arg(count);
652 write fn zpopmax<RV>(key: impl ToRedisArgs, count: usize): "ZPOPMAX".key(key).arg(count);
655 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 write fn zremrangebyrank(key: impl ToRedisArgs, start: isize, stop: isize) -> u64:
664 "ZREMRANGEBYRANK".key(key).arg(start).arg(stop);
665 write fn zinterstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
668 "ZINTERSTORE".key(destination).numkeys(keys);
669 write fn zunionstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
672 "ZUNIONSTORE".key(destination).numkeys(keys);
673}
674
675group! {
676 group = geo;
678 uses {
679 pub use rs::geo::{Coord, RadiusOptions, RadiusOrder, RadiusSearchResult, Unit};
680 }
681
682 read fn geo_pos<RV>(key: impl ToRedisArgs, members: impl ToRedisArgs):
684 "GEOPOS".key(key).arg(members);
685 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 read fn geo_hash<RV>(key: impl ToRedisArgs, members: impl ToRedisArgs):
694 "GEOHASH".key(key).arg(members);
695 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 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 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 group = stream;
725 uses {
726 pub use rs::streams::{
727 StreamAutoClaimReply, StreamClaimReply, StreamId, StreamInfoStreamReply, StreamKey,
728 StreamMaxlen, StreamPendingReply, StreamRangeReply, StreamReadReply,
729 };
730 }
731
732 read fn xrange<RV>(key: impl ToRedisArgs, start: impl ToRedisArgs, end: impl ToRedisArgs):
735 "XRANGE".key(key).arg(start).arg(end);
736 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 read fn xrevrange<RV>(key: impl ToRedisArgs, end: impl ToRedisArgs, start: impl ToRedisArgs):
745 "XREVRANGE".key(key).arg(end).arg(start);
746 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 read fn xlen(key: impl ToRedisArgs) -> u64: "XLEN".key(key);
755 read fn xread<RV>(keys: impl ToRedisArgs, ids: impl ToRedisArgs):
759 "XREAD".arg("STREAMS").key(keys).arg(ids).reply_keys();
760 read fn xpending<RV>(key: impl ToRedisArgs, group: impl ToRedisArgs):
763 "XPENDING".key(key).arg(group);
764 read fn xinfo_stream<RV>(key: impl ToRedisArgs): "XINFO".arg("STREAM").key(key);
767
768 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 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 write fn xdel(key: impl ToRedisArgs, ids: impl ToRedisArgs) -> u64: "XDEL".key(key).arg(ids);
784 write fn xtrim(key: impl ToRedisArgs, maxlen: StreamMaxlen) -> u64:
787 "XTRIM".key(key).arg(maxlen);
788 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 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 write fn xgroup_destroy(key: impl ToRedisArgs, group: impl ToRedisArgs) -> bool:
803 "XGROUP".arg("DESTROY").key(key).arg(group);
804 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 write fn xack(key: impl ToRedisArgs, group: impl ToRedisArgs, ids: impl ToRedisArgs) -> u64:
818 "XACK".key(key).arg(group).arg(ids);
819 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 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 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 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
858struct 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#[derive(Debug, Clone, Default)]
870pub struct ScanOptions {
871 pattern: Option<String>,
872 count: Option<usize>,
873}
874
875impl ScanOptions {
876 pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
878 self.pattern = Some(pattern.into());
879 self
880 }
881
882 pub fn count(mut self, count: usize) -> Self {
884 self.count = Some(count);
885 self
886 }
887}
888
889#[derive(Clone)]
891enum Scanned {
892 Keys,
893 Elements {
896 operation: &'static str,
897 command: &'static str,
898 key: Vec<u8>,
899 width: usize,
900 },
901}
902
903pub struct Scan<'a, T> {
922 target: Target<'a>,
923 scanned: Scanned,
924 options: ScanOptions,
925 cursor: Option<u64>,
927 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 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 self.cursor = None;
955 return Some(Err(err));
956 }
957 }
958 }
959
960 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 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 values.reverse();
1023 self.batch = values;
1024 Ok(())
1025 }
1026}
1027
1028fn 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
1040macro_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
1066fn 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
1081scans!(generic:
1083 fn scan() = Scanned::Keys;
1085);
1086
1087scans!(hash:
1089 fn hscan(key) = elements("hscan", "HSCAN", key, 2);
1091);
1092
1093scans!(set:
1095 fn sscan(key) = elements("sscan", "SSCAN", key, 1);
1097);
1098
1099scans!(sorted_set:
1101 fn zscan(key) = elements("zscan", "ZSCAN", key, 2);
1103);
1104
1105pub mod pubsub {
1111 use super::*;
1112
1113 #[derive(Clone, Copy)]
1115 pub struct Commands<'a> {
1116 pub(in crate::storage::redis) target: Target<'a>,
1117 }
1118
1119 #[derive(Clone, Copy)]
1121 pub struct ReadCommands<'a> {
1122 pub(in crate::storage::redis) target: Target<'a>,
1123 }
1124
1125 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 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 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 pub async fn subscribe(&self, channels: impl ToRedisArgs) -> Result<Subscription, Error> {
1166 subscribe(self.target, channels, Vec::<Vec<u8>>::new()).await
1167 }
1168
1169 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 pub async fn subscribe(&self, channels: impl ToRedisArgs) -> Result<Subscription, Error> {
1180 subscribe(self.target, channels, Vec::<Vec<u8>>::new()).await
1181 }
1182
1183 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 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 pub struct Subscription {
1204 inner: core_cache::Subscription,
1205 }
1206
1207 impl Subscription {
1208 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 #[derive(Debug, Clone, PartialEq, Eq)]
1220 pub struct Message {
1221 pub channel: String,
1223 pub payload: Vec<u8>,
1225 }
1226
1227 impl Message {
1228 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};