1use std::marker::PhantomData;
16
17use encore_sdk_core::cache::{self as core_cache, redis as rs};
18
19use super::types::{
20 FromRedisValue, Increment, Popped, PoppedMany, PoppedScored, PoppedScoredMany, ToRedisArgs,
21 Value,
22};
23use super::{redis_err, Target};
24use crate::error::{ErrCode, Error};
25
26pub(crate) struct Cmd {
28 pub(super) inner: core_cache::Command,
29}
30
31impl Cmd {
32 fn new(operation: &'static str, name: &'static str, write: bool) -> Self {
33 Self::from_core(core_cache::Command::new(operation, name, write))
34 }
35
36 pub(super) fn from_core(inner: core_cache::Command) -> Self {
37 Self { inner }
38 }
39
40 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
78macro_rules! method {
81 (run $mode:ident; $(#[$doc:meta])* fn $name:ident<RV>($($arg:ident: $ty:ty),*) [$cmd:expr]) => {
82 $(#[$doc])*
83 pub async fn $name<RV: FromRedisValue>(&self, $($arg: $ty),*) -> Result<RV, Error> {
84 self.target.run($cmd).await
85 }
86 };
87 (run $mode:ident; $(#[$doc:meta])* fn $name:ident($($arg:ident: $ty:ty),*) -> $ret:ty [$cmd:expr]) => {
88 $(#[$doc])*
89 pub async fn $name(&self, $($arg: $ty),*) -> Result<$ret, Error> {
90 self.target.run($cmd).await
91 }
92 };
93 (run $mode:ident; $(#[$doc:meta])* fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),*) -> $ret:ty [$cmd:expr]) => {
94 $(#[$doc])*
95 pub async fn $name<$param: $bound>(&self, $($arg: $ty),*) -> Result<$ret, Error> {
96 self.target.run($cmd).await
97 }
98 };
99 (read read; $($method:tt)*) => {
100 method!(run read; $($method)*);
101 };
102 (read write; $($method:tt)*) => {};
103 (@unqueued queue $mode:ident; $($method:tt)*) => {};
105 (@unqueued $form:ident $mode:ident; $($method:tt)*) => {
106 method!($form $mode; $($method)*);
107 };
108 (queue $mode:ident; $(#[$doc:meta])* fn $name:ident $(<RV>)? ($($arg:ident: $ty:ty),*) $(-> $ret:ty)? [$cmd:expr]) => {
109 $(#[$doc])*
110 pub fn $name(&mut self, $($arg: $ty),*) -> &mut Self {
111 self.queue.push($cmd);
112 self
113 }
114 };
115 (queue $mode:ident; $(#[$doc:meta])* fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),*) -> $ret:ty [$cmd:expr]) => {
116 $(#[$doc])*
117 pub fn $name<$param: $bound>(&mut self, $($arg: $ty),*) -> &mut Self {
118 self.queue.push($cmd);
119 self
120 }
121 };
122}
123
124macro_rules! writes {
126 (read) => {
127 false
128 };
129 (write) => {
130 true
131 };
132}
133
134macro_rules! methods {
136 ($form:ident;) => {};
137 (
139 $form:ident;
140 $(#[$doc:meta])*
141 blocking $mode:ident fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),* $(,)?) -> $ret:ty:
142 $wire:literal $(.$part:ident($($value:expr),*))*;
143 $($rest:tt)*
144 ) => {
145 method!(
146 @unqueued $form $mode;
147 $(#[$doc])*
148 fn $name<$param: $bound>($($arg: $ty),*) -> $ret
149 [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
150 );
151 methods!($form; $($rest)*);
152 };
153 (
154 $form:ident;
155 $(#[$doc:meta])*
156 blocking $mode:ident fn $name:ident<RV>($($arg:ident: $ty:ty),* $(,)?):
157 $wire:literal $(.$part:ident($($value:expr),*))*;
158 $($rest:tt)*
159 ) => {
160 method!(
161 @unqueued $form $mode;
162 $(#[$doc])*
163 fn $name<RV>($($arg: $ty),*)
164 [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
165 );
166 methods!($form; $($rest)*);
167 };
168 (
169 $form:ident;
170 $(#[$doc:meta])*
171 $mode:ident fn $name:ident<RV>($($arg:ident: $ty:ty),* $(,)?):
172 $wire:literal $(.$part:ident($($value:expr),*))*;
173 $($rest:tt)*
174 ) => {
175 method!(
176 $form $mode;
177 $(#[$doc])*
178 fn $name<RV>($($arg: $ty),*)
179 [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
180 );
181 methods!($form; $($rest)*);
182 };
183 (
184 $form:ident;
185 $(#[$doc:meta])*
186 $mode:ident fn $name:ident($($arg:ident: $ty:ty),* $(,)?) -> $ret:ty:
187 $wire:literal $(.$part:ident($($value:expr),*))*;
188 $($rest:tt)*
189 ) => {
190 method!(
191 $form $mode;
192 $(#[$doc])*
193 fn $name($($arg: $ty),*) -> $ret
194 [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
195 );
196 methods!($form; $($rest)*);
197 };
198 (
200 $form:ident;
201 $(#[$doc:meta])*
202 $mode:ident fn $name:ident<$param:ident: $bound:ident>($($arg:ident: $ty:ty),* $(,)?) -> $ret:ty:
203 $wire:literal $(.$part:ident($($value:expr),*))*;
204 $($rest:tt)*
205 ) => {
206 method!(
207 $form $mode;
208 $(#[$doc])*
209 fn $name<$param: $bound>($($arg: $ty),*) -> $ret
210 [Cmd::new(stringify!($name), $wire, writes!($mode))$(.$part($($value),*))*]
211 );
212 methods!($form; $($rest)*);
213 };
214}
215
216macro_rules! group {
218 (
220 $(#[$doc:meta])*
221 group = $group:ident;
222 $(#[$first:meta])*
223 $mode:ident fn $($commands:tt)*
224 ) => {
225 group! {
226 $(#[$doc])*
227 group = $group;
228 uses {}
229 $(#[$first])*
230 $mode fn $($commands)*
231 }
232 };
233 (
234 $(#[$doc:meta])*
235 group = $group:ident;
236 uses { $($uses:item)* }
237 $($commands:tt)*
238 ) => {
239 $(#[$doc])*
240 pub mod $group {
241 #[allow(unused_imports)]
242 use super::*;
243
244 $($uses)*
245
246 #[derive(Clone, Copy)]
248 pub struct Commands<'a> {
249 pub(in crate::storage::redis) target: Target<'a>,
250 }
251
252 #[derive(Clone, Copy)]
254 pub struct ReadCommands<'a> {
255 pub(in crate::storage::redis) target: Target<'a>,
256 }
257
258 pub struct Queue<'a> {
261 pub(in crate::storage::redis) queue: &'a mut crate::storage::redis::Queued,
262 }
263
264 impl Commands<'_> {
265 methods!(run; $($commands)*);
266 }
267
268 impl ReadCommands<'_> {
269 methods!(read; $($commands)*);
270 }
271
272 impl Queue<'_> {
273 methods!(queue; $($commands)*);
274 }
275 }
276 };
277}
278
279group! {
280 group = generic;
282
283 read fn exists(key: impl ToRedisArgs) -> bool: "EXISTS".key(key);
285 read fn ttl(key: impl ToRedisArgs) -> i64: "TTL".key(key);
288 read fn pttl(key: impl ToRedisArgs) -> i64: "PTTL".key(key);
291 read fn key_type(key: impl ToRedisArgs) -> String: "TYPE".key(key);
294 read fn expire_time(key: impl ToRedisArgs) -> i64: "EXPIRETIME".key(key);
297
298 write fn del(keys: impl ToRedisArgs) -> u64: "DEL".key(keys);
300 write fn unlink(keys: impl ToRedisArgs) -> u64: "UNLINK".key(keys);
303 write fn expire(key: impl ToRedisArgs, seconds: i64) -> bool: "EXPIRE".key(key).arg(seconds);
305 write fn pexpire(key: impl ToRedisArgs, milliseconds: i64) -> bool:
307 "PEXPIRE".key(key).arg(milliseconds);
308 write fn expire_at(key: impl ToRedisArgs, timestamp: i64) -> bool:
311 "EXPIREAT".key(key).arg(timestamp);
312 write fn persist(key: impl ToRedisArgs) -> bool: "PERSIST".key(key);
314 write fn rename(key: impl ToRedisArgs, new_key: impl ToRedisArgs) -> ():
316 "RENAME".key(key).key(new_key);
317 write fn rename_nx(key: impl ToRedisArgs, new_key: impl ToRedisArgs) -> bool:
319 "RENAMENX".key(key).key(new_key);
320 write fn copy(source: impl ToRedisArgs, destination: impl ToRedisArgs) -> bool:
323 "COPY".key(source).key(destination);
324 write fn touch(keys: impl ToRedisArgs) -> u64: "TOUCH".key(keys);
326}
327
328group! {
329 group = string;
331
332 read fn get<RV>(key: impl ToRedisArgs): "GET".key(key);
334 read fn mget<RV>(keys: impl ToRedisArgs): "MGET".key(keys);
336 read fn strlen(key: impl ToRedisArgs) -> u64: "STRLEN".key(key);
338 read fn getrange<RV>(key: impl ToRedisArgs, from: isize, to: isize):
341 "GETRANGE".key(key).arg(from).arg(to);
342
343 write fn set(key: impl ToRedisArgs, value: impl ToRedisArgs) -> (): "SET".key(key).arg(value);
345 write fn set_ex(key: impl ToRedisArgs, value: impl ToRedisArgs, seconds: u64) -> ():
347 "SETEX".key(key).arg(seconds).arg(value);
348 write fn set_nx(key: impl ToRedisArgs, value: impl ToRedisArgs) -> bool:
350 "SETNX".key(key).arg(value);
351 write fn set_options<RV>(key: impl ToRedisArgs, value: impl ToRedisArgs, options: SetOptions):
354 "SET".key(key).arg(value).arg(options);
355 write fn mset(items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> (): "MSET".pairs(items);
357 write fn mset_nx(items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> bool:
360 "MSETNX".pairs(items);
361 write fn get_del<RV>(key: impl ToRedisArgs): "GETDEL".key(key);
363 write fn get_ex<RV>(key: impl ToRedisArgs, expiry: Expiry): "GETEX".key(key).arg(expiry);
365 write fn append(key: impl ToRedisArgs, value: impl ToRedisArgs) -> u64:
367 "APPEND".key(key).arg(value);
368 write fn setrange(key: impl ToRedisArgs, offset: usize, value: impl ToRedisArgs) -> u64:
370 "SETRANGE".key(key).arg(offset).arg(value);
371 write fn incr<D: Increment>(key: impl ToRedisArgs, delta: D) -> D::Reply:
375 "INCRBY".or_float("INCRBYFLOAT", D::FLOAT).key(key).arg(delta);
376 write fn decr(key: impl ToRedisArgs, delta: i64) -> i64: "DECRBY".key(key).arg(delta);
378}
379
380group! {
381 group = bitmap;
383 uses {
384 pub use super::bitfield::{
385 BitOffset, Bitfield, BitfieldRo, Overflow, QueuedBitfield, QueuedBitfieldRo,
386 };
387 }
388
389 read fn getbit(key: impl ToRedisArgs, offset: u64) -> bool: "GETBIT".key(key).arg(offset);
391 read fn bitcount(key: impl ToRedisArgs) -> u64: "BITCOUNT".key(key);
393 read fn bitcount_range(key: impl ToRedisArgs, start: isize, end: isize) -> u64:
395 "BITCOUNT".key(key).arg(start).arg(end);
396 read fn bitpos(key: impl ToRedisArgs, bit: bool) -> i64: "BITPOS".key(key).arg(bit as u8);
398
399 write fn setbit(key: impl ToRedisArgs, offset: u64, value: bool) -> bool:
401 "SETBIT".key(key).arg(offset).arg(value as u8);
402 write fn bit_and(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
405 "BITOP".arg("AND").key(destination).key(sources);
406 write fn bit_or(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
409 "BITOP".arg("OR").key(destination).key(sources);
410 write fn bit_xor(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> u64:
413 "BITOP".arg("XOR").key(destination).key(sources);
414 write fn bit_not(destination: impl ToRedisArgs, source: impl ToRedisArgs) -> u64:
417 "BITOP".arg("NOT").key(destination).key(source);
418}
419
420group! {
421 group = hash;
423
424 read fn hget<RV>(key: impl ToRedisArgs, field: impl ToRedisArgs): "HGET".key(key).arg(field);
426 read fn hmget<RV>(key: impl ToRedisArgs, fields: impl ToRedisArgs):
428 "HMGET".key(key).arg(fields);
429 read fn hgetall<RV>(key: impl ToRedisArgs): "HGETALL".key(key);
431 read fn hexists(key: impl ToRedisArgs, field: impl ToRedisArgs) -> bool:
433 "HEXISTS".key(key).arg(field);
434 read fn hlen(key: impl ToRedisArgs) -> u64: "HLEN".key(key);
436 read fn hkeys<RV>(key: impl ToRedisArgs): "HKEYS".key(key);
438 read fn hvals<RV>(key: impl ToRedisArgs): "HVALS".key(key);
440 read fn hrandfield<RV>(key: impl ToRedisArgs): "HRANDFIELD".key(key);
442
443 write fn hset(key: impl ToRedisArgs, field: impl ToRedisArgs, value: impl ToRedisArgs) -> u64:
445 "HSET".key(key).arg(field).arg(value);
446 write fn hset_multiple(
448 key: impl ToRedisArgs,
449 items: &[(impl ToRedisArgs, impl ToRedisArgs)]
450 ) -> u64: "HSET".key(key).args_of(items);
451 write fn hset_nx(
453 key: impl ToRedisArgs,
454 field: impl ToRedisArgs,
455 value: impl ToRedisArgs
456 ) -> bool: "HSETNX".key(key).arg(field).arg(value);
457 write fn hdel(key: impl ToRedisArgs, fields: impl ToRedisArgs) -> u64:
459 "HDEL".key(key).arg(fields);
460 write fn hincr<D: Increment>(key: impl ToRedisArgs, field: impl ToRedisArgs, delta: D) -> D::Reply:
464 "HINCRBY".or_float("HINCRBYFLOAT", D::FLOAT).key(key).arg(field).arg(delta);
465}
466
467group! {
468 group = list;
470
471 read fn lrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
474 "LRANGE".key(key).arg(start).arg(stop);
475 read fn lindex<RV>(key: impl ToRedisArgs, index: isize): "LINDEX".key(key).arg(index);
477 read fn llen(key: impl ToRedisArgs) -> u64: "LLEN".key(key);
479 read fn lpos(key: impl ToRedisArgs, value: impl ToRedisArgs) -> Option<u64>:
481 "LPOS".key(key).arg(value);
482
483 write fn lpush(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
485 "LPUSH".key(key).arg(values);
486 write fn rpush(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
488 "RPUSH".key(key).arg(values);
489 write fn lpush_exists(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
491 "LPUSHX".key(key).arg(values);
492 write fn rpush_exists(key: impl ToRedisArgs, values: impl ToRedisArgs) -> u64:
494 "RPUSHX".key(key).arg(values);
495 write fn lpop<RV>(key: impl ToRedisArgs, count: Option<std::num::NonZeroUsize>):
498 "LPOP".key(key).arg(count.map(std::num::NonZeroUsize::get));
499 write fn rpop<RV>(key: impl ToRedisArgs, count: Option<std::num::NonZeroUsize>):
502 "RPOP".key(key).arg(count.map(std::num::NonZeroUsize::get));
503 write fn lset(key: impl ToRedisArgs, index: isize, value: impl ToRedisArgs) -> ():
505 "LSET".key(key).arg(index).arg(value);
506 write fn ltrim(key: impl ToRedisArgs, start: isize, stop: isize) -> ():
508 "LTRIM".key(key).arg(start).arg(stop);
509 write fn linsert_before(
512 key: impl ToRedisArgs,
513 pivot: impl ToRedisArgs,
514 value: impl ToRedisArgs
515 ) -> i64: "LINSERT".key(key).arg("BEFORE").arg(pivot).arg(value);
516 write fn linsert_after(
519 key: impl ToRedisArgs,
520 pivot: impl ToRedisArgs,
521 value: impl ToRedisArgs
522 ) -> i64: "LINSERT".key(key).arg("AFTER").arg(pivot).arg(value);
523 write fn lrem(key: impl ToRedisArgs, count: isize, value: impl ToRedisArgs) -> u64:
526 "LREM".key(key).arg(count).arg(value);
527 write fn lmove<RV>(
530 source: impl ToRedisArgs,
531 destination: impl ToRedisArgs,
532 from: Direction,
533 to: Direction
534 ): "LMOVE".key(source).key(destination).arg(from).arg(to);
535
536 blocking write fn blpop<V: FromRedisValue>(keys: impl ToRedisArgs, timeout: f64) -> Option<Popped<V>>:
540 "BLPOP".key(keys).arg(timeout);
541 blocking write fn brpop<V: FromRedisValue>(keys: impl ToRedisArgs, timeout: f64) -> Option<Popped<V>>:
543 "BRPOP".key(keys).arg(timeout);
544 blocking write fn blmove<RV>(
548 source: impl ToRedisArgs,
549 destination: impl ToRedisArgs,
550 from: Direction,
551 to: Direction,
552 timeout: f64
553 ): "BLMOVE".key(source).key(destination).arg(from).arg(to).arg(timeout);
554 blocking write fn blmpop<V: FromRedisValue>(
558 timeout: f64,
559 keys: impl ToRedisArgs,
560 from: Direction,
561 count: usize
562 ) -> Option<PoppedMany<V>>:
563 "BLMPOP".arg(timeout).numkeys(keys).arg(from).arg("COUNT").arg(count);
564}
565
566group! {
567 group = set;
569
570 read fn smembers<RV>(key: impl ToRedisArgs): "SMEMBERS".key(key);
572 read fn sismember(key: impl ToRedisArgs, member: impl ToRedisArgs) -> bool:
574 "SISMEMBER".key(key).arg(member);
575 read fn smismember(key: impl ToRedisArgs, members: impl ToRedisArgs) -> Vec<bool>:
577 "SMISMEMBER".key(key).arg(members);
578 read fn scard(key: impl ToRedisArgs) -> u64: "SCARD".key(key);
580 read fn srandmember<RV>(key: impl ToRedisArgs): "SRANDMEMBER".key(key);
582 read fn srandmember_multiple<RV>(key: impl ToRedisArgs, count: isize):
585 "SRANDMEMBER".key(key).arg(count);
586 read fn sdiff<RV>(keys: impl ToRedisArgs): "SDIFF".key(keys);
588 read fn sinter<RV>(keys: impl ToRedisArgs): "SINTER".key(keys);
590 read fn sunion<RV>(keys: impl ToRedisArgs): "SUNION".key(keys);
592
593 write fn sadd(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
595 "SADD".key(key).arg(members);
596 write fn srem(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
598 "SREM".key(key).arg(members);
599 write fn spop<RV>(key: impl ToRedisArgs): "SPOP".key(key);
601 write fn smove(
604 source: impl ToRedisArgs,
605 destination: impl ToRedisArgs,
606 member: impl ToRedisArgs
607 ) -> bool: "SMOVE".key(source).key(destination).arg(member);
608 write fn sdiffstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
611 "SDIFFSTORE".key(destination).key(keys);
612 write fn sinterstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
615 "SINTERSTORE".key(destination).key(keys);
616 write fn sunionstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
619 "SUNIONSTORE".key(destination).key(keys);
620}
621
622group! {
623 group = sorted_set;
625
626 read fn zrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
629 "ZRANGE".key(key).arg(start).arg(stop);
630 read fn zrange_withscores<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
632 "ZRANGE".key(key).arg(start).arg(stop).arg("WITHSCORES");
633 read fn zrevrange<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
635 "ZREVRANGE".key(key).arg(start).arg(stop);
636 read fn zrevrange_withscores<RV>(key: impl ToRedisArgs, start: isize, stop: isize):
638 "ZREVRANGE".key(key).arg(start).arg(stop).arg("WITHSCORES");
639 read fn zrangebyscore<RV>(key: impl ToRedisArgs, min: impl ToRedisArgs, max: impl ToRedisArgs):
642 "ZRANGEBYSCORE".key(key).arg(min).arg(max);
643 read fn zrangebyscore_withscores<RV>(
645 key: impl ToRedisArgs,
646 min: impl ToRedisArgs,
647 max: impl ToRedisArgs
648 ): "ZRANGEBYSCORE".key(key).arg(min).arg(max).arg("WITHSCORES");
649 read fn zscore(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<f64>:
651 "ZSCORE".key(key).arg(member);
652 read fn zrank(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<u64>:
654 "ZRANK".key(key).arg(member);
655 read fn zrevrank(key: impl ToRedisArgs, member: impl ToRedisArgs) -> Option<u64>:
657 "ZREVRANK".key(key).arg(member);
658 read fn zcard(key: impl ToRedisArgs) -> u64: "ZCARD".key(key);
660 read fn zcount(key: impl ToRedisArgs, min: impl ToRedisArgs, max: impl ToRedisArgs) -> u64:
662 "ZCOUNT".key(key).arg(min).arg(max);
663 read fn zrandmember<RV>(key: impl ToRedisArgs): "ZRANDMEMBER".key(key);
665
666 write fn zadd(key: impl ToRedisArgs, member: impl ToRedisArgs, score: f64) -> u64:
669 "ZADD".key(key).arg(score).arg(member);
670 write fn zadd_multiple(key: impl ToRedisArgs, items: &[(f64, impl ToRedisArgs)]) -> u64:
673 "ZADD".key(key).args_of(items);
674 write fn zrem(key: impl ToRedisArgs, members: impl ToRedisArgs) -> u64:
676 "ZREM".key(key).arg(members);
677 write fn zincr(key: impl ToRedisArgs, member: impl ToRedisArgs, delta: impl Increment) -> f64:
679 "ZINCRBY".key(key).arg(delta).arg(member);
680 write fn zpopmin<RV>(key: impl ToRedisArgs, count: usize): "ZPOPMIN".key(key).arg(count);
683 write fn zpopmax<RV>(key: impl ToRedisArgs, count: usize): "ZPOPMAX".key(key).arg(count);
686 write fn zrembyscore(
689 key: impl ToRedisArgs,
690 min: impl ToRedisArgs,
691 max: impl ToRedisArgs
692 ) -> u64: "ZREMRANGEBYSCORE".key(key).arg(min).arg(max);
693 write fn zremrangebyrank(key: impl ToRedisArgs, start: isize, stop: isize) -> u64:
695 "ZREMRANGEBYRANK".key(key).arg(start).arg(stop);
696 write fn zinterstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
699 "ZINTERSTORE".key(destination).numkeys(keys);
700 write fn zunionstore(destination: impl ToRedisArgs, keys: impl ToRedisArgs) -> u64:
703 "ZUNIONSTORE".key(destination).numkeys(keys);
704
705 blocking write fn bzpopmin<M: FromRedisValue>(keys: impl ToRedisArgs, timeout: f64) -> Option<PoppedScored<M>>:
710 "BZPOPMIN".key(keys).arg(timeout);
711 blocking write fn bzpopmax<M: FromRedisValue>(keys: impl ToRedisArgs, timeout: f64) -> Option<PoppedScored<M>>:
713 "BZPOPMAX".key(keys).arg(timeout);
714 blocking write fn bzmpop_min<M: FromRedisValue>(
719 timeout: f64,
720 keys: impl ToRedisArgs,
721 count: usize
722 ) -> Option<PoppedScoredMany<M>>:
723 "BZMPOP".arg(timeout).numkeys(keys).arg("MIN").arg("COUNT").arg(count);
724 blocking write fn bzmpop_max<M: FromRedisValue>(
726 timeout: f64,
727 keys: impl ToRedisArgs,
728 count: usize
729 ) -> Option<PoppedScoredMany<M>>:
730 "BZMPOP".arg(timeout).numkeys(keys).arg("MAX").arg("COUNT").arg(count);
731}
732
733group! {
734 group = geo;
736 uses {
737 pub use rs::geo::{Coord, RadiusOptions, RadiusOrder, RadiusSearchResult, Unit};
738 }
739
740 read fn geo_pos<RV>(key: impl ToRedisArgs, members: impl ToRedisArgs):
742 "GEOPOS".key(key).arg(members);
743 read fn geo_dist(
745 key: impl ToRedisArgs,
746 from: impl ToRedisArgs,
747 to: impl ToRedisArgs,
748 unit: Unit
749 ) -> Option<f64>: "GEODIST".key(key).arg(from).arg(to).arg(unit);
750 read fn geo_hash<RV>(key: impl ToRedisArgs, members: impl ToRedisArgs):
752 "GEOHASH".key(key).arg(members);
753 read fn geo_radius<RV>(
755 key: impl ToRedisArgs,
756 longitude: f64,
757 latitude: f64,
758 radius: f64,
759 unit: Unit,
760 options: RadiusOptions
761 ): "GEORADIUS_RO".key(key).arg(longitude).arg(latitude).arg(radius).arg(unit).arg(options);
762 read fn geo_radius_by_member<RV>(
764 key: impl ToRedisArgs,
765 member: impl ToRedisArgs,
766 radius: f64,
767 unit: Unit,
768 options: RadiusOptions
769 ): "GEORADIUSBYMEMBER_RO".key(key).arg(member).arg(radius).arg(unit).arg(options);
770
771 write fn geo_add(
773 key: impl ToRedisArgs,
774 longitude: f64,
775 latitude: f64,
776 member: impl ToRedisArgs
777 ) -> u64: "GEOADD".key(key).arg(longitude).arg(latitude).arg(member);
778}
779
780group! {
781 group = stream;
783 uses {
784 pub use rs::streams::{
785 StreamAutoClaimReply, StreamClaimReply, StreamId, StreamInfoStreamReply, StreamKey,
786 StreamMaxlen, StreamPendingReply, StreamRangeReply, StreamReadReply,
787 };
788 }
789
790 read fn xrange<RV>(key: impl ToRedisArgs, start: impl ToRedisArgs, end: impl ToRedisArgs):
793 "XRANGE".key(key).arg(start).arg(end);
794 read fn xrange_count<RV>(
796 key: impl ToRedisArgs,
797 start: impl ToRedisArgs,
798 end: impl ToRedisArgs,
799 count: usize
800 ): "XRANGE".key(key).arg(start).arg(end).arg("COUNT").arg(count);
801 read fn xrevrange<RV>(key: impl ToRedisArgs, end: impl ToRedisArgs, start: impl ToRedisArgs):
803 "XREVRANGE".key(key).arg(end).arg(start);
804 read fn xrevrange_count<RV>(
806 key: impl ToRedisArgs,
807 end: impl ToRedisArgs,
808 start: impl ToRedisArgs,
809 count: usize
810 ): "XREVRANGE".key(key).arg(end).arg(start).arg("COUNT").arg(count);
811 read fn xlen(key: impl ToRedisArgs) -> u64: "XLEN".key(key);
813 read fn xread<RV>(keys: impl ToRedisArgs, ids: impl ToRedisArgs):
817 "XREAD".arg("STREAMS").key(keys).arg(ids);
818 read fn xpending<RV>(key: impl ToRedisArgs, group: impl ToRedisArgs):
821 "XPENDING".key(key).arg(group);
822 read fn xinfo_stream<RV>(key: impl ToRedisArgs): "XINFO".arg("STREAM").key(key);
825
826 write fn xadd<RV>(
829 key: impl ToRedisArgs,
830 id: impl ToRedisArgs,
831 items: &[(impl ToRedisArgs, impl ToRedisArgs)]
832 ): "XADD".key(key).arg(id).args_of(items);
833 write fn xadd_maxlen<RV>(
835 key: impl ToRedisArgs,
836 maxlen: StreamMaxlen,
837 id: impl ToRedisArgs,
838 items: &[(impl ToRedisArgs, impl ToRedisArgs)]
839 ): "XADD".key(key).arg(maxlen).arg(id).args_of(items);
840 write fn xdel(key: impl ToRedisArgs, ids: impl ToRedisArgs) -> u64: "XDEL".key(key).arg(ids);
842 write fn xtrim(key: impl ToRedisArgs, maxlen: StreamMaxlen) -> u64:
845 "XTRIM".key(key).arg(maxlen);
846 write fn xgroup_create(
849 key: impl ToRedisArgs,
850 group: impl ToRedisArgs,
851 id: impl ToRedisArgs
852 ) -> (): "XGROUP".arg("CREATE").key(key).arg(group).arg(id);
853 write fn xgroup_create_mkstream(
855 key: impl ToRedisArgs,
856 group: impl ToRedisArgs,
857 id: impl ToRedisArgs
858 ) -> (): "XGROUP".arg("CREATE").key(key).arg(group).arg(id).arg("MKSTREAM");
859 write fn xgroup_destroy(key: impl ToRedisArgs, group: impl ToRedisArgs) -> bool:
861 "XGROUP".arg("DESTROY").key(key).arg(group);
862 write fn xread_group<RV>(
866 group: impl ToRedisArgs,
867 consumer: impl ToRedisArgs,
868 keys: impl ToRedisArgs,
869 ids: impl ToRedisArgs,
870 count: Option<usize>
871 ): "XREADGROUP".arg("GROUP").arg(group).arg(consumer).arg(count.map(|n| ("COUNT", n)))
872 .arg("STREAMS").key(keys).arg(ids);
873 write fn xack(key: impl ToRedisArgs, group: impl ToRedisArgs, ids: impl ToRedisArgs) -> u64:
876 "XACK".key(key).arg(group).arg(ids);
877 write fn xclaim<RV>(
880 key: impl ToRedisArgs,
881 group: impl ToRedisArgs,
882 consumer: impl ToRedisArgs,
883 min_idle_ms: u64,
884 ids: impl ToRedisArgs
885 ): "XCLAIM".key(key).arg(group).arg(consumer).arg(min_idle_ms).arg(ids);
886 write fn xautoclaim<RV>(
889 key: impl ToRedisArgs,
890 group: impl ToRedisArgs,
891 consumer: impl ToRedisArgs,
892 min_idle_ms: u64,
893 start: impl ToRedisArgs
894 ): "XAUTOCLAIM".key(key).arg(group).arg(consumer).arg(min_idle_ms).arg(start);
895
896 blocking read fn xread_block<RV>(
900 keys: impl ToRedisArgs,
901 ids: impl ToRedisArgs,
902 block: std::time::Duration,
903 count: Option<usize>
904 ): "XREAD".arg(count.map(|n| ("COUNT", n))).arg("BLOCK").arg(block.as_millis() as u64)
905 .arg("STREAMS").key(keys).arg(ids);
906 blocking write fn xread_group_block<RV>(
910 group: impl ToRedisArgs,
911 consumer: impl ToRedisArgs,
912 keys: impl ToRedisArgs,
913 ids: impl ToRedisArgs,
914 block: std::time::Duration,
915 count: Option<usize>
916 ): "XREADGROUP".arg("GROUP").arg(group).arg(consumer).arg(count.map(|n| ("COUNT", n)))
917 .arg("BLOCK").arg(block.as_millis() as u64).arg("STREAMS").key(keys).arg(ids);
918}
919
920group! {
921 group = hyperloglog;
924
925 read fn pfcount(keys: impl ToRedisArgs) -> u64: "PFCOUNT".key(keys);
928
929 write fn pfadd(key: impl ToRedisArgs, elements: impl ToRedisArgs) -> bool:
931 "PFADD".key(key).arg(elements);
932 write fn pfmerge(destination: impl ToRedisArgs, sources: impl ToRedisArgs) -> ():
934 "PFMERGE".key(destination).key(sources);
935}
936
937impl Cmd {
938 fn pairs(mut self, items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> Self {
940 for (key, value) in items {
941 self = self.key(Raw(key)).arg(Raw(value));
942 }
943 self
944 }
945
946 fn args_of(mut self, items: &[(impl ToRedisArgs, impl ToRedisArgs)]) -> Self {
949 for (first, second) in items {
950 self = self.arg(Raw(first)).arg(Raw(second));
951 }
952 self
953 }
954}
955
956struct Raw<'a, T>(&'a T);
959
960impl<T: ToRedisArgs> ToRedisArgs for Raw<'_, T> {
961 fn write_redis_args<W: ?Sized + rs::RedisWrite>(&self, out: &mut W) {
962 self.0.write_redis_args(out)
963 }
964}
965
966#[derive(Debug, Clone, Default)]
968pub struct ScanOptions {
969 pattern: Option<String>,
970 count: Option<usize>,
971}
972
973impl ScanOptions {
974 pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
976 self.pattern = Some(pattern.into());
977 self
978 }
979
980 pub fn count(mut self, count: usize) -> Self {
982 self.count = Some(count);
983 self
984 }
985}
986
987#[derive(Clone)]
989enum Scanned {
990 Keys,
991 Elements {
994 operation: &'static str,
995 command: &'static str,
996 key: Vec<u8>,
997 width: usize,
998 },
999}
1000
1001pub struct Scan<'a, T> {
1020 target: Target<'a>,
1021 scanned: Scanned,
1022 options: ScanOptions,
1023 cursor: Option<u64>,
1025 batch: Vec<Value>,
1027 item: PhantomData<fn() -> T>,
1028}
1029
1030impl<'a, T: FromRedisValue> Scan<'a, T> {
1031 fn new(target: Target<'a>, scanned: Scanned, options: ScanOptions) -> Self {
1032 Self {
1033 target,
1034 scanned,
1035 options,
1036 cursor: Some(0),
1037 batch: Vec::new(),
1038 item: PhantomData,
1039 }
1040 }
1041
1042 pub async fn next(&mut self) -> Option<Result<T, Error>> {
1044 loop {
1045 if let Some(value) = self.batch.pop() {
1046 return Some(T::from_redis_value(value));
1047 }
1048 let cursor = self.cursor?;
1049 if let Err(err) = self.fetch(cursor).await {
1050 self.cursor = None;
1053 return Some(Err(err));
1054 }
1055 }
1056 }
1057
1058 async fn fetch(&mut self, cursor: u64) -> Result<(), Error> {
1060 let prefix = self.target.client()?.key_prefix().map(str::to_owned);
1061 let mut cmd = match &self.scanned {
1062 Scanned::Keys => core_cache::Command::new("scan", "SCAN", false),
1063 Scanned::Elements {
1064 operation,
1065 command,
1066 key,
1067 ..
1068 } => core_cache::Command::new(operation, *command, false).key(key.as_slice()),
1069 }
1070 .arg(cursor.to_string());
1071
1072 let pattern = match (&self.scanned, &prefix, &self.options.pattern) {
1075 (Scanned::Keys, Some(prefix), pattern) => Some(format!(
1076 "{}{}",
1077 escape_glob(prefix),
1078 pattern.as_deref().unwrap_or("*")
1079 )),
1080 (_, _, pattern) => pattern.clone(),
1081 };
1082 if let Some(pattern) = pattern {
1083 cmd = cmd.arg("MATCH").arg(pattern);
1084 }
1085 if let Some(count) = self.options.count {
1086 cmd = cmd.arg("COUNT").arg(count.to_string());
1087 }
1088
1089 let reply = self.target.reply(&cmd).await.map_err(redis_err)?;
1090 let (next, mut values): (u64, Vec<Value>) = FromRedisValue::from_redis_value(reply)?;
1091 self.cursor = (next != 0).then_some(next);
1092
1093 match &self.scanned {
1094 Scanned::Keys => {
1095 if let Some(prefix) = &prefix {
1096 for value in &mut values {
1097 if let Value::BulkString(key) = value {
1098 if key.starts_with(prefix.as_bytes()) {
1099 key.drain(..prefix.len());
1100 }
1101 }
1102 }
1103 }
1104 }
1105 Scanned::Elements { width, .. } if *width > 1 => {
1106 if values.len() % width != 0 {
1107 return Err(Error::new(
1108 ErrCode::Internal,
1109 "scan reply has an unexpected number of elements",
1110 ));
1111 }
1112 values = values
1113 .chunks(*width)
1114 .map(|element| Value::Array(element.to_vec()))
1115 .collect();
1116 }
1117 Scanned::Elements { .. } => {}
1118 }
1119 values.reverse();
1121 self.batch = values;
1122 Ok(())
1123 }
1124}
1125
1126fn escape_glob(text: &str) -> String {
1128 let mut out = String::with_capacity(text.len());
1129 for c in text.chars() {
1130 if matches!(c, '*' | '?' | '[' | ']' | '\\') {
1131 out.push('\\');
1132 }
1133 out.push(c);
1134 }
1135 out
1136}
1137
1138macro_rules! scans {
1141 ($group:ident: $($(#[$doc:meta])* fn $name:ident($($key:ident)?) = $scanned:expr;)*) => {
1142 scans!(@on $group, Commands: $($(#[$doc])* fn $name($($key)?) = $scanned;)*);
1143 scans!(@on $group, ReadCommands: $($(#[$doc])* fn $name($($key)?) = $scanned;)*);
1144 };
1145 (
1146 @on $group:ident, $form:ident:
1147 $($(#[$doc:meta])* fn $name:ident($($key:ident)?) = $scanned:expr;)*
1148 ) => {
1149 impl<'a> $group::$form<'a> {
1150 $(
1151 $(#[$doc])*
1152 pub fn $name<T: FromRedisValue>(
1153 &self,
1154 $($key: impl ToRedisArgs,)?
1155 options: ScanOptions,
1156 ) -> Scan<'a, T> {
1157 Scan::new(self.target, $scanned, options)
1158 }
1159 )*
1160 }
1161 };
1162}
1163
1164fn elements(
1166 operation: &'static str,
1167 command: &'static str,
1168 key: impl ToRedisArgs,
1169 width: usize,
1170) -> Scanned {
1171 Scanned::Elements {
1172 operation,
1173 command,
1174 key: key.to_redis_args().into_iter().next().unwrap_or_default(),
1175 width,
1176 }
1177}
1178
1179scans!(generic:
1181 fn scan() = Scanned::Keys;
1183);
1184
1185scans!(hash:
1187 fn hscan(key) = elements("hscan", "HSCAN", key, 2);
1189);
1190
1191scans!(set:
1193 fn sscan(key) = elements("sscan", "SSCAN", key, 1);
1195);
1196
1197scans!(sorted_set:
1199 fn zscan(key) = elements("zscan", "ZSCAN", key, 2);
1201);
1202
1203mod bitfield {
1206 use super::*;
1207 use crate::storage::redis::Queued;
1208
1209 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1212 pub enum BitOffset {
1213 Bit(u64),
1214 Multiple(u64),
1215 }
1216
1217 impl From<u64> for BitOffset {
1218 fn from(bit: u64) -> Self {
1219 BitOffset::Bit(bit)
1220 }
1221 }
1222
1223 impl std::fmt::Display for BitOffset {
1224 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1225 match self {
1226 BitOffset::Bit(n) => write!(f, "{n}"),
1227 BitOffset::Multiple(n) => write!(f, "#{n}"),
1228 }
1229 }
1230 }
1231
1232 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1235 pub enum Overflow {
1236 Wrap,
1238 Sat,
1240 Fail,
1242 }
1243
1244 macro_rules! gets {
1246 () => {
1247 pub fn get(mut self, ty: &str, offset: impl Into<BitOffset>) -> Self {
1250 self.cmd = self.cmd.arg("GET").arg(ty).arg(offset.into().to_string());
1251 self
1252 }
1253 };
1254 }
1255
1256 macro_rules! sets {
1258 () => {
1259 gets!();
1260
1261 pub fn set(mut self, ty: &str, offset: impl Into<BitOffset>, value: i64) -> Self {
1264 self.cmd = self
1265 .cmd
1266 .arg("SET")
1267 .arg(ty)
1268 .arg(offset.into().to_string())
1269 .arg(value);
1270 self
1271 }
1272
1273 pub fn incr_by(
1276 mut self,
1277 ty: &str,
1278 offset: impl Into<BitOffset>,
1279 increment: i64,
1280 ) -> Self {
1281 self.cmd = self
1282 .cmd
1283 .arg("INCRBY")
1284 .arg(ty)
1285 .arg(offset.into().to_string())
1286 .arg(increment);
1287 self
1288 }
1289
1290 pub fn overflow(mut self, mode: Overflow) -> Self {
1293 let mode = match mode {
1294 Overflow::Wrap => "WRAP",
1295 Overflow::Sat => "SAT",
1296 Overflow::Fail => "FAIL",
1297 };
1298 self.cmd = self.cmd.arg("OVERFLOW").arg(mode);
1299 self
1300 }
1301 };
1302 }
1303
1304 pub struct Bitfield<'a> {
1308 pub(super) target: Target<'a>,
1309 pub(super) cmd: Cmd,
1310 }
1311
1312 impl Bitfield<'_> {
1313 sets!();
1314
1315 pub async fn invoke(self) -> Result<Vec<Option<i64>>, Error> {
1318 self.target.run(self.cmd).await
1319 }
1320 }
1321
1322 pub struct BitfieldRo<'a> {
1324 pub(super) target: Target<'a>,
1325 pub(super) cmd: Cmd,
1326 }
1327
1328 impl BitfieldRo<'_> {
1329 gets!();
1330
1331 pub async fn invoke(self) -> Result<Vec<Option<i64>>, Error> {
1333 self.target.run(self.cmd).await
1334 }
1335 }
1336
1337 pub struct QueuedBitfield<'a> {
1339 pub(super) queue: &'a mut Queued,
1340 pub(super) cmd: Cmd,
1341 }
1342
1343 impl QueuedBitfield<'_> {
1344 sets!();
1345
1346 pub fn queue(self) {
1348 self.queue.push(self.cmd);
1349 }
1350 }
1351
1352 pub struct QueuedBitfieldRo<'a> {
1354 pub(super) queue: &'a mut Queued,
1355 pub(super) cmd: Cmd,
1356 }
1357
1358 impl QueuedBitfieldRo<'_> {
1359 gets!();
1360
1361 pub fn queue(self) {
1363 self.queue.push(self.cmd);
1364 }
1365 }
1366
1367 fn bitfield(key: impl ToRedisArgs) -> Cmd {
1368 Cmd::new("bitfield", "BITFIELD", true).key(key)
1369 }
1370
1371 fn bitfield_ro(key: impl ToRedisArgs) -> Cmd {
1372 Cmd::new("bitfield_ro", "BITFIELD_RO", false).key(key)
1373 }
1374
1375 impl<'a> super::bitmap::Commands<'a> {
1378 pub fn bitfield(&self, key: impl ToRedisArgs) -> Bitfield<'a> {
1382 Bitfield {
1383 target: self.target,
1384 cmd: bitfield(key),
1385 }
1386 }
1387
1388 pub fn bitfield_ro(&self, key: impl ToRedisArgs) -> BitfieldRo<'a> {
1390 BitfieldRo {
1391 target: self.target,
1392 cmd: bitfield_ro(key),
1393 }
1394 }
1395 }
1396
1397 impl<'a> super::bitmap::ReadCommands<'a> {
1398 pub fn bitfield_ro(&self, key: impl ToRedisArgs) -> BitfieldRo<'a> {
1401 BitfieldRo {
1402 target: self.target,
1403 cmd: bitfield_ro(key),
1404 }
1405 }
1406 }
1407
1408 impl super::bitmap::Queue<'_> {
1409 pub fn bitfield(&mut self, key: impl ToRedisArgs) -> QueuedBitfield<'_> {
1412 QueuedBitfield {
1413 queue: self.queue,
1414 cmd: bitfield(key),
1415 }
1416 }
1417
1418 pub fn bitfield_ro(&mut self, key: impl ToRedisArgs) -> QueuedBitfieldRo<'_> {
1420 QueuedBitfieldRo {
1421 queue: self.queue,
1422 cmd: bitfield_ro(key),
1423 }
1424 }
1425 }
1426}
1427
1428pub mod pubsub {
1434 use super::*;
1435
1436 #[derive(Clone, Copy)]
1438 pub struct Commands<'a> {
1439 pub(in crate::storage::redis) target: Target<'a>,
1440 }
1441
1442 #[derive(Clone, Copy)]
1444 pub struct ReadCommands<'a> {
1445 pub(in crate::storage::redis) target: Target<'a>,
1446 }
1447
1448 pub struct Queue<'a> {
1450 pub(in crate::storage::redis) queue: &'a mut crate::storage::redis::Queued,
1451 }
1452
1453 fn publish(channel: impl ToRedisArgs, message: impl ToRedisArgs) -> Cmd {
1454 Cmd::new("publish", "PUBLISH", true)
1457 .key(channel)
1458 .arg(message)
1459 }
1460
1461 async fn subscribe(
1462 target: Target<'_>,
1463 channels: impl ToRedisArgs,
1464 patterns: impl ToRedisArgs,
1465 ) -> Result<Subscription, Error> {
1466 let inner = target
1467 .client()?
1468 .subscribe(&channels.to_redis_args(), &patterns.to_redis_args())
1469 .await
1470 .map_err(redis_err)?;
1471 Ok(Subscription { inner })
1472 }
1473
1474 impl Commands<'_> {
1475 pub async fn publish(
1479 &self,
1480 channel: impl ToRedisArgs,
1481 message: impl ToRedisArgs,
1482 ) -> Result<u64, Error> {
1483 self.target.run(publish(channel, message)).await
1484 }
1485
1486 pub async fn subscribe(&self, channels: impl ToRedisArgs) -> Result<Subscription, Error> {
1489 subscribe(self.target, channels, Vec::<Vec<u8>>::new()).await
1490 }
1491
1492 pub async fn psubscribe(&self, patterns: impl ToRedisArgs) -> Result<Subscription, Error> {
1496 subscribe(self.target, Vec::<Vec<u8>>::new(), patterns).await
1497 }
1498 }
1499
1500 impl ReadCommands<'_> {
1501 pub async fn subscribe(&self, channels: impl ToRedisArgs) -> Result<Subscription, Error> {
1503 subscribe(self.target, channels, Vec::<Vec<u8>>::new()).await
1504 }
1505
1506 pub async fn psubscribe(&self, patterns: impl ToRedisArgs) -> Result<Subscription, Error> {
1508 subscribe(self.target, Vec::<Vec<u8>>::new(), patterns).await
1509 }
1510 }
1511
1512 impl Queue<'_> {
1513 pub fn publish(
1515 &mut self,
1516 channel: impl ToRedisArgs,
1517 message: impl ToRedisArgs,
1518 ) -> &mut Self {
1519 self.queue.push(publish(channel, message));
1520 self
1521 }
1522 }
1523
1524 pub struct Subscription {
1527 inner: core_cache::Subscription,
1528 }
1529
1530 impl Subscription {
1531 pub async fn next(&mut self) -> Option<Message> {
1533 let message = self.inner.next().await?;
1534 Some(Message {
1535 channel: String::from_utf8_lossy(&message.channel).into_owned(),
1536 payload: message.payload,
1537 })
1538 }
1539 }
1540
1541 #[derive(Debug, Clone, PartialEq, Eq)]
1543 pub struct Message {
1544 pub channel: String,
1546 pub payload: Vec<u8>,
1548 }
1549
1550 impl Message {
1551 pub fn payload<T: FromRedisValue>(&self) -> Result<T, Error> {
1553 T::from_redis_value(Value::BulkString(self.payload.clone()))
1554 }
1555 }
1556}
1557
1558use rs::{Direction, Expiry, SetOptions};