1use crate::CommandArg;
24use bytes::Bytes;
25use redis_tower_core::{Command, Frame, RedisError};
26use redis_tower_protocol::helpers::{array, bulk};
27
28#[derive(Clone)]
33pub struct Publish {
34 channel: CommandArg,
35 message: CommandArg,
36}
37
38impl Publish {
39 pub fn new(channel: impl Into<CommandArg>, message: impl Into<CommandArg>) -> Self {
41 Self {
42 channel: channel.into(),
43 message: message.into(),
44 }
45 }
46}
47
48impl Command for Publish {
49 type Response = i64;
50
51 fn to_frame(&self) -> Frame {
52 array(vec![
53 bulk("PUBLISH"),
54 bulk(&self.channel),
55 bulk(&self.message),
56 ])
57 }
58
59 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
60 match frame {
61 Frame::Integer(n) => Ok(n),
62 other => Err(RedisError::UnexpectedResponse {
63 expected: "integer",
64 actual: format!("{other:?}"),
65 }),
66 }
67 }
68
69 fn name(&self) -> &str {
70 "PUBLISH"
71 }
72}
73
74#[derive(Clone)]
79pub struct SPublish {
80 channel: CommandArg,
81 message: CommandArg,
82}
83
84impl SPublish {
85 pub fn new(channel: impl Into<CommandArg>, message: impl Into<CommandArg>) -> Self {
87 Self {
88 channel: channel.into(),
89 message: message.into(),
90 }
91 }
92}
93
94impl Command for SPublish {
95 type Response = i64;
96
97 fn to_frame(&self) -> Frame {
98 array(vec![
99 bulk("SPUBLISH"),
100 bulk(&self.channel),
101 bulk(&self.message),
102 ])
103 }
104
105 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
106 match frame {
107 Frame::Integer(n) => Ok(n),
108 other => Err(RedisError::UnexpectedResponse {
109 expected: "integer",
110 actual: format!("{other:?}"),
111 }),
112 }
113 }
114
115 fn name(&self) -> &str {
116 "SPUBLISH"
117 }
118}
119
120#[derive(Clone)]
127pub struct PubSubChannels {
128 pattern: Option<CommandArg>,
129}
130
131impl PubSubChannels {
132 pub fn new() -> Self {
134 Self { pattern: None }
135 }
136
137 pub fn with_pattern(pattern: impl Into<CommandArg>) -> Self {
139 Self {
140 pattern: Some(pattern.into()),
141 }
142 }
143}
144
145impl Default for PubSubChannels {
146 fn default() -> Self {
147 Self::new()
148 }
149}
150
151impl Command for PubSubChannels {
152 type Response = Vec<Bytes>;
153
154 fn to_frame(&self) -> Frame {
155 let mut args = vec![bulk("PUBSUB"), bulk("CHANNELS")];
156 if let Some(ref pat) = self.pattern {
157 args.push(bulk(pat));
158 }
159 array(args)
160 }
161
162 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
163 match frame {
164 Frame::Array(Some(frames)) => {
165 let mut channels = Vec::with_capacity(frames.len());
166 for f in frames {
167 match f {
168 Frame::BulkString(Some(data)) => channels.push(data),
169 other => {
170 return Err(RedisError::UnexpectedResponse {
171 expected: "bulk string",
172 actual: format!("{other:?}"),
173 });
174 }
175 }
176 }
177 Ok(channels)
178 }
179 Frame::Array(None) => Ok(Vec::new()),
180 other => Err(RedisError::UnexpectedResponse {
181 expected: "array",
182 actual: format!("{other:?}"),
183 }),
184 }
185 }
186
187 fn name(&self) -> &str {
188 "PUBSUB CHANNELS"
189 }
190}
191
192#[derive(Clone)]
198pub struct PubSubNumSub {
199 channels: Vec<CommandArg>,
200}
201
202impl PubSubNumSub {
203 pub fn new() -> Self {
205 Self {
206 channels: Vec::new(),
207 }
208 }
209
210 pub fn with_channels(channels: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
212 Self {
213 channels: channels.into_iter().map(|c| c.into()).collect(),
214 }
215 }
216}
217
218impl Default for PubSubNumSub {
219 fn default() -> Self {
220 Self::new()
221 }
222}
223
224impl Command for PubSubNumSub {
225 type Response = Vec<(Bytes, i64)>;
226
227 fn to_frame(&self) -> Frame {
228 let mut args = vec![bulk("PUBSUB"), bulk("NUMSUB")];
229 for ch in &self.channels {
230 args.push(bulk(ch));
231 }
232 array(args)
233 }
234
235 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
236 match frame {
237 Frame::Array(Some(frames)) => {
239 if frames.len() % 2 != 0 {
240 return Err(RedisError::UnexpectedResponse {
241 expected: "even number of elements",
242 actual: format!("array of length {}", frames.len()),
243 });
244 }
245 let mut result = Vec::with_capacity(frames.len() / 2);
246 let mut iter = frames.into_iter();
247 while let (Some(ch), Some(count)) = (iter.next(), iter.next()) {
248 let channel = match ch {
249 Frame::BulkString(Some(data)) => data,
250 other => {
251 return Err(RedisError::UnexpectedResponse {
252 expected: "bulk string (channel name)",
253 actual: format!("{other:?}"),
254 });
255 }
256 };
257 let n = match count {
258 Frame::Integer(n) => n,
259 other => {
260 return Err(RedisError::UnexpectedResponse {
261 expected: "integer (subscriber count)",
262 actual: format!("{other:?}"),
263 });
264 }
265 };
266 result.push((channel, n));
267 }
268 Ok(result)
269 }
270 Frame::Array(None) => Ok(Vec::new()),
271 Frame::Map(pairs) => {
273 let mut result = Vec::with_capacity(pairs.len());
274 for (k, v) in pairs {
275 let channel = match k {
276 Frame::BulkString(Some(data)) => data,
277 other => {
278 return Err(RedisError::UnexpectedResponse {
279 expected: "bulk string (channel name)",
280 actual: format!("{other:?}"),
281 });
282 }
283 };
284 let n = match v {
285 Frame::Integer(n) => n,
286 other => {
287 return Err(RedisError::UnexpectedResponse {
288 expected: "integer (subscriber count)",
289 actual: format!("{other:?}"),
290 });
291 }
292 };
293 result.push((channel, n));
294 }
295 Ok(result)
296 }
297 other => Err(RedisError::UnexpectedResponse {
298 expected: "array or map",
299 actual: format!("{other:?}"),
300 }),
301 }
302 }
303
304 fn name(&self) -> &str {
305 "PUBSUB NUMSUB"
306 }
307}
308
309#[derive(Clone)]
314pub struct PubSubNumPat;
315
316impl PubSubNumPat {
317 pub fn new() -> Self {
319 Self
320 }
321}
322
323impl Default for PubSubNumPat {
324 fn default() -> Self {
325 Self::new()
326 }
327}
328
329impl Command for PubSubNumPat {
330 type Response = i64;
331
332 fn to_frame(&self) -> Frame {
333 array(vec![bulk("PUBSUB"), bulk("NUMPAT")])
334 }
335
336 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
337 match frame {
338 Frame::Integer(n) => Ok(n),
339 other => Err(RedisError::UnexpectedResponse {
340 expected: "integer",
341 actual: format!("{other:?}"),
342 }),
343 }
344 }
345
346 fn name(&self) -> &str {
347 "PUBSUB NUMPAT"
348 }
349}
350
351#[derive(Clone)]
358pub struct PubSubShardChannels {
359 pattern: Option<CommandArg>,
360}
361
362impl PubSubShardChannels {
363 pub fn new() -> Self {
365 Self { pattern: None }
366 }
367
368 pub fn with_pattern(pattern: impl Into<CommandArg>) -> Self {
370 Self {
371 pattern: Some(pattern.into()),
372 }
373 }
374}
375
376impl Default for PubSubShardChannels {
377 fn default() -> Self {
378 Self::new()
379 }
380}
381
382impl Command for PubSubShardChannels {
383 type Response = Vec<Bytes>;
384
385 fn to_frame(&self) -> Frame {
386 let mut args = vec![bulk("PUBSUB"), bulk("SHARDCHANNELS")];
387 if let Some(ref pat) = self.pattern {
388 args.push(bulk(pat));
389 }
390 array(args)
391 }
392
393 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
394 match frame {
395 Frame::Array(Some(frames)) => {
396 let mut channels = Vec::with_capacity(frames.len());
397 for f in frames {
398 match f {
399 Frame::BulkString(Some(data)) => channels.push(data),
400 other => {
401 return Err(RedisError::UnexpectedResponse {
402 expected: "bulk string",
403 actual: format!("{other:?}"),
404 });
405 }
406 }
407 }
408 Ok(channels)
409 }
410 Frame::Array(None) => Ok(Vec::new()),
411 other => Err(RedisError::UnexpectedResponse {
412 expected: "array",
413 actual: format!("{other:?}"),
414 }),
415 }
416 }
417
418 fn name(&self) -> &str {
419 "PUBSUB SHARDCHANNELS"
420 }
421}
422
423#[derive(Clone)]
429pub struct PubSubShardNumSub {
430 channels: Vec<CommandArg>,
431}
432
433impl PubSubShardNumSub {
434 pub fn new() -> Self {
436 Self {
437 channels: Vec::new(),
438 }
439 }
440
441 pub fn with_channels(channels: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
443 Self {
444 channels: channels.into_iter().map(|c| c.into()).collect(),
445 }
446 }
447}
448
449impl Default for PubSubShardNumSub {
450 fn default() -> Self {
451 Self::new()
452 }
453}
454
455impl Command for PubSubShardNumSub {
456 type Response = Vec<(Bytes, i64)>;
457
458 fn to_frame(&self) -> Frame {
459 let mut args = vec![bulk("PUBSUB"), bulk("SHARDNUMSUB")];
460 for ch in &self.channels {
461 args.push(bulk(ch));
462 }
463 array(args)
464 }
465
466 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
467 match frame {
468 Frame::Array(Some(frames)) => {
470 if frames.len() % 2 != 0 {
471 return Err(RedisError::UnexpectedResponse {
472 expected: "even number of elements",
473 actual: format!("array of length {}", frames.len()),
474 });
475 }
476 let mut result = Vec::with_capacity(frames.len() / 2);
477 let mut iter = frames.into_iter();
478 while let (Some(ch), Some(count)) = (iter.next(), iter.next()) {
479 let channel = match ch {
480 Frame::BulkString(Some(data)) => data,
481 other => {
482 return Err(RedisError::UnexpectedResponse {
483 expected: "bulk string (channel name)",
484 actual: format!("{other:?}"),
485 });
486 }
487 };
488 let n = match count {
489 Frame::Integer(n) => n,
490 other => {
491 return Err(RedisError::UnexpectedResponse {
492 expected: "integer (subscriber count)",
493 actual: format!("{other:?}"),
494 });
495 }
496 };
497 result.push((channel, n));
498 }
499 Ok(result)
500 }
501 Frame::Array(None) => Ok(Vec::new()),
502 Frame::Map(pairs) => {
504 let mut result = Vec::with_capacity(pairs.len());
505 for (k, v) in pairs {
506 let channel = match k {
507 Frame::BulkString(Some(data)) => data,
508 other => {
509 return Err(RedisError::UnexpectedResponse {
510 expected: "bulk string (channel name)",
511 actual: format!("{other:?}"),
512 });
513 }
514 };
515 let n = match v {
516 Frame::Integer(n) => n,
517 other => {
518 return Err(RedisError::UnexpectedResponse {
519 expected: "integer (subscriber count)",
520 actual: format!("{other:?}"),
521 });
522 }
523 };
524 result.push((channel, n));
525 }
526 Ok(result)
527 }
528 other => Err(RedisError::UnexpectedResponse {
529 expected: "array or map",
530 actual: format!("{other:?}"),
531 }),
532 }
533 }
534
535 fn name(&self) -> &str {
536 "PUBSUB SHARDNUMSUB"
537 }
538}
539
540#[derive(Clone)]
544pub struct PubSubHelp;
545
546impl PubSubHelp {
547 pub fn new() -> Self {
549 Self
550 }
551}
552
553impl Default for PubSubHelp {
554 fn default() -> Self {
555 Self::new()
556 }
557}
558
559impl Command for PubSubHelp {
560 type Response = Vec<Bytes>;
561
562 fn to_frame(&self) -> Frame {
563 array(vec![bulk("PUBSUB"), bulk("HELP")])
564 }
565
566 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
567 crate::help::parse_help_lines(frame)
568 }
569
570 fn name(&self) -> &str {
571 "PUBSUB HELP"
572 }
573
574 fn idempotent(&self) -> bool {
575 true
576 }
577}
578
579#[cfg(test)]
580mod tests {
581 use super::*;
582
583 #[test]
584 fn publish_frame() {
585 let cmd = Publish::new("news", "hello");
586 assert_eq!(
587 cmd.to_frame(),
588 array(vec![bulk("PUBLISH"), bulk("news"), bulk("hello")])
589 );
590 assert_eq!(cmd.name(), "PUBLISH");
591 }
592
593 #[test]
594 fn publish_parse_response() {
595 let cmd = Publish::new("news", "hello");
596 let frame = Frame::Integer(3);
597 assert_eq!(cmd.parse_response(frame).unwrap(), 3);
598 }
599
600 #[test]
601 fn spublish_frame() {
602 let cmd = SPublish::new("news", "hello");
603 assert_eq!(
604 cmd.to_frame(),
605 array(vec![bulk("SPUBLISH"), bulk("news"), bulk("hello")])
606 );
607 assert_eq!(cmd.name(), "SPUBLISH");
608 }
609
610 #[test]
611 fn pubsub_channels_no_pattern() {
612 let cmd = PubSubChannels::new();
613 assert_eq!(
614 cmd.to_frame(),
615 array(vec![bulk("PUBSUB"), bulk("CHANNELS")])
616 );
617 assert_eq!(cmd.name(), "PUBSUB CHANNELS");
618 }
619
620 #[test]
621 fn pubsub_channels_with_pattern() {
622 let cmd = PubSubChannels::with_pattern("news.*");
623 assert_eq!(
624 cmd.to_frame(),
625 array(vec![bulk("PUBSUB"), bulk("CHANNELS"), bulk("news.*")])
626 );
627 }
628
629 #[test]
630 fn pubsub_channels_parse_response() {
631 let cmd = PubSubChannels::new();
632 let frame = Frame::Array(Some(vec![
633 Frame::BulkString(Some(Bytes::from("ch1"))),
634 Frame::BulkString(Some(Bytes::from("ch2"))),
635 ]));
636 let resp = cmd.parse_response(frame).unwrap();
637 assert_eq!(resp, vec![Bytes::from("ch1"), Bytes::from("ch2")]);
638 }
639
640 #[test]
641 fn pubsub_channels_parse_empty() {
642 let cmd = PubSubChannels::new();
643 let frame = Frame::Array(Some(vec![]));
644 assert!(cmd.parse_response(frame).unwrap().is_empty());
645 }
646
647 #[test]
648 fn pubsub_numsub_no_channels() {
649 let cmd = PubSubNumSub::new();
650 assert_eq!(cmd.to_frame(), array(vec![bulk("PUBSUB"), bulk("NUMSUB")]));
651 assert_eq!(cmd.name(), "PUBSUB NUMSUB");
652 }
653
654 #[test]
655 fn pubsub_numsub_with_channels() {
656 let cmd = PubSubNumSub::with_channels(["ch1", "ch2"]);
657 assert_eq!(
658 cmd.to_frame(),
659 array(vec![
660 bulk("PUBSUB"),
661 bulk("NUMSUB"),
662 bulk("ch1"),
663 bulk("ch2"),
664 ])
665 );
666 }
667
668 #[test]
669 fn pubsub_numsub_parse_resp2() {
670 let cmd = PubSubNumSub::with_channels(["ch1", "ch2"]);
671 let frame = Frame::Array(Some(vec![
672 Frame::BulkString(Some(Bytes::from("ch1"))),
673 Frame::Integer(5),
674 Frame::BulkString(Some(Bytes::from("ch2"))),
675 Frame::Integer(0),
676 ]));
677 let resp = cmd.parse_response(frame).unwrap();
678 assert_eq!(resp, vec![(Bytes::from("ch1"), 5), (Bytes::from("ch2"), 0)]);
679 }
680
681 #[test]
682 fn pubsub_numsub_parse_resp3_map() {
683 let cmd = PubSubNumSub::with_channels(["ch1"]);
684 let frame = Frame::Map(vec![(
685 Frame::BulkString(Some(Bytes::from("ch1"))),
686 Frame::Integer(3),
687 )]);
688 let resp = cmd.parse_response(frame).unwrap();
689 assert_eq!(resp, vec![(Bytes::from("ch1"), 3)]);
690 }
691
692 #[test]
693 fn pubsub_numsub_parse_odd_length_error() {
694 let cmd = PubSubNumSub::new();
695 let frame = Frame::Array(Some(vec![Frame::BulkString(Some(Bytes::from("ch1")))]));
696 assert!(cmd.parse_response(frame).is_err());
697 }
698
699 #[test]
700 fn pubsub_numpat_frame() {
701 let cmd = PubSubNumPat::new();
702 assert_eq!(cmd.to_frame(), array(vec![bulk("PUBSUB"), bulk("NUMPAT")]));
703 assert_eq!(cmd.name(), "PUBSUB NUMPAT");
704 }
705
706 #[test]
707 fn pubsub_numpat_parse_response() {
708 let cmd = PubSubNumPat::new();
709 let frame = Frame::Integer(7);
710 assert_eq!(cmd.parse_response(frame).unwrap(), 7);
711 }
712
713 #[test]
714 fn pubsub_shard_channels_no_pattern() {
715 let cmd = PubSubShardChannels::new();
716 assert_eq!(
717 cmd.to_frame(),
718 array(vec![bulk("PUBSUB"), bulk("SHARDCHANNELS")])
719 );
720 assert_eq!(cmd.name(), "PUBSUB SHARDCHANNELS");
721 }
722
723 #[test]
724 fn pubsub_shard_channels_with_pattern() {
725 let cmd = PubSubShardChannels::with_pattern("shard.*");
726 assert_eq!(
727 cmd.to_frame(),
728 array(vec![bulk("PUBSUB"), bulk("SHARDCHANNELS"), bulk("shard.*"),])
729 );
730 }
731
732 #[test]
733 fn pubsub_shard_channels_parse_response() {
734 let cmd = PubSubShardChannels::new();
735 let frame = Frame::Array(Some(vec![Frame::BulkString(Some(Bytes::from("sc1")))]));
736 let resp = cmd.parse_response(frame).unwrap();
737 assert_eq!(resp, vec![Bytes::from("sc1")]);
738 }
739
740 #[test]
741 fn pubsub_shard_numsub_no_channels() {
742 let cmd = PubSubShardNumSub::new();
743 assert_eq!(
744 cmd.to_frame(),
745 array(vec![bulk("PUBSUB"), bulk("SHARDNUMSUB")])
746 );
747 assert_eq!(cmd.name(), "PUBSUB SHARDNUMSUB");
748 }
749
750 #[test]
751 fn pubsub_shard_numsub_with_channels() {
752 let cmd = PubSubShardNumSub::with_channels(["sc1", "sc2"]);
753 assert_eq!(
754 cmd.to_frame(),
755 array(vec![
756 bulk("PUBSUB"),
757 bulk("SHARDNUMSUB"),
758 bulk("sc1"),
759 bulk("sc2"),
760 ])
761 );
762 }
763
764 #[test]
765 fn pubsub_shard_numsub_parse_resp2() {
766 let cmd = PubSubShardNumSub::with_channels(["sc1"]);
767 let frame = Frame::Array(Some(vec![
768 Frame::BulkString(Some(Bytes::from("sc1"))),
769 Frame::Integer(2),
770 ]));
771 let resp = cmd.parse_response(frame).unwrap();
772 assert_eq!(resp, vec![(Bytes::from("sc1"), 2)]);
773 }
774
775 #[test]
776 fn pubsub_shard_numsub_parse_resp3_map() {
777 let cmd = PubSubShardNumSub::with_channels(["sc1"]);
778 let frame = Frame::Map(vec![(
779 Frame::BulkString(Some(Bytes::from("sc1"))),
780 Frame::Integer(4),
781 )]);
782 let resp = cmd.parse_response(frame).unwrap();
783 assert_eq!(resp, vec![(Bytes::from("sc1"), 4)]);
784 }
785
786 #[test]
787 fn pubsub_help_to_frame() {
788 let cmd = PubSubHelp::new();
789 assert_eq!(cmd.to_frame(), array(vec![bulk("PUBSUB"), bulk("HELP")]));
790 assert!(cmd.idempotent());
791 }
792
793 #[test]
794 fn pubsub_help_parse_lines() {
795 let cmd = PubSubHelp::new();
796 let reply = array(vec![bulk("PUBSUB <subcommand>"), bulk("CHANNELS")]);
797 let lines = cmd.parse_response(reply).unwrap();
798 assert_eq!(lines.len(), 2);
799 assert_eq!(&lines[1][..], b"CHANNELS");
800 }
801}