Skip to main content

redis_tower_commands/
scripting.rs

1//! Lua scripts and Redis Functions.
2//!
3//! [`Eval`] / [`EvalSha`] and function calls can return any RESP shape, so
4//! their response is a raw `Frame`. Declare every key with `.key(...)` so
5//! Cluster routing and Redis's key-access rules remain correct; ordinary
6//! arguments belong in `.arg(...)`.
7//!
8//! ```
9//! use redis_tower_commands::Eval;
10//! use redis_tower_core::Command;
11//!
12//! let command = Eval::new("return redis.call('GET', KEYS[1])")
13//!     .key("{account}:name");
14//! assert_eq!(command.name(), "EVAL");
15//! ```
16//!
17//! See the [command cookbook] for raw response normalization and same-slot
18//! requirements.
19//!
20//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#raw-custom-and-module-replies
21
22use crate::CommandArg;
23use bytes::Bytes;
24use redis_tower_core::{Command, Frame, RedisError};
25use redis_tower_protocol::helpers::{array, bulk};
26use sha1::{Digest, Sha1};
27
28use crate::server::FlushMode;
29
30// ---------------------------------------------------------------------------
31// EVAL
32// ---------------------------------------------------------------------------
33
34/// EVAL script numkeys [key ...] [arg ...]
35///
36/// Evaluates a Lua script server-side. Returns `Frame` directly because Lua
37/// scripts can produce any response type.
38#[derive(Clone)]
39pub struct Eval {
40    script: CommandArg,
41    keys: Vec<CommandArg>,
42    args: Vec<CommandArg>,
43}
44
45impl Eval {
46    /// Create a new [`Eval`] command.
47    pub fn new(script: impl Into<CommandArg>) -> Self {
48        Self {
49            script: script.into(),
50            keys: Vec::new(),
51            args: Vec::new(),
52        }
53    }
54
55    /// Add a key argument (populates KEYS table in Lua).
56    pub fn key(mut self, key: impl Into<CommandArg>) -> Self {
57        self.keys.push(key.into());
58        self
59    }
60
61    /// Add a regular argument (populates ARGV table in Lua).
62    pub fn arg(mut self, arg: impl Into<CommandArg>) -> Self {
63        self.args.push(arg.into());
64        self
65    }
66}
67
68impl Command for Eval {
69    type Response = Frame;
70
71    fn to_frame(&self) -> Frame {
72        let mut parts = vec![
73            bulk("EVAL"),
74            bulk(&self.script),
75            bulk(self.keys.len().to_string()),
76        ];
77        for k in &self.keys {
78            parts.push(bulk(k));
79        }
80        for a in &self.args {
81            parts.push(bulk(a));
82        }
83        array(parts)
84    }
85
86    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
87        Ok(frame)
88    }
89
90    fn name(&self) -> &str {
91        "EVAL"
92    }
93}
94
95// ---------------------------------------------------------------------------
96// EVALSHA
97// ---------------------------------------------------------------------------
98
99/// EVALSHA sha1 numkeys [key ...] [arg ...]
100///
101/// Evaluates a cached Lua script by its SHA1 digest. Returns `Frame` directly.
102#[derive(Clone)]
103pub struct EvalSha {
104    sha1: String,
105    keys: Vec<CommandArg>,
106    args: Vec<CommandArg>,
107}
108
109impl EvalSha {
110    /// Create a new [`EvalSha`] command.
111    pub fn new(sha1: impl Into<String>) -> Self {
112        Self {
113            sha1: sha1.into(),
114            keys: Vec::new(),
115            args: Vec::new(),
116        }
117    }
118
119    /// Add a key argument (populates KEYS table in Lua).
120    pub fn key(mut self, key: impl Into<CommandArg>) -> Self {
121        self.keys.push(key.into());
122        self
123    }
124
125    /// Add a regular argument (populates ARGV table in Lua).
126    pub fn arg(mut self, arg: impl Into<CommandArg>) -> Self {
127        self.args.push(arg.into());
128        self
129    }
130}
131
132impl Command for EvalSha {
133    type Response = Frame;
134
135    fn to_frame(&self) -> Frame {
136        let mut parts = vec![
137            bulk("EVALSHA"),
138            bulk(self.sha1.as_str()),
139            bulk(self.keys.len().to_string()),
140        ];
141        for k in &self.keys {
142            parts.push(bulk(k));
143        }
144        for a in &self.args {
145            parts.push(bulk(a));
146        }
147        array(parts)
148    }
149
150    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
151        Ok(frame)
152    }
153
154    fn name(&self) -> &str {
155        "EVALSHA"
156    }
157}
158
159// ---------------------------------------------------------------------------
160// EVAL_RO
161// ---------------------------------------------------------------------------
162
163/// EVAL_RO script numkeys [key ...] [arg ...]
164///
165/// Read-only variant of EVAL. Evaluates a Lua script server-side, rejecting any
166/// write commands. Returns `Frame` directly.
167#[derive(Clone)]
168pub struct EvalRo {
169    script: CommandArg,
170    keys: Vec<CommandArg>,
171    args: Vec<CommandArg>,
172}
173
174impl EvalRo {
175    /// Create a new [`EvalRo`] command.
176    pub fn new(script: impl Into<CommandArg>) -> Self {
177        Self {
178            script: script.into(),
179            keys: Vec::new(),
180            args: Vec::new(),
181        }
182    }
183
184    /// Add a key argument (populates KEYS table in Lua).
185    pub fn key(mut self, key: impl Into<CommandArg>) -> Self {
186        self.keys.push(key.into());
187        self
188    }
189
190    /// Add a regular argument (populates ARGV table in Lua).
191    pub fn arg(mut self, arg: impl Into<CommandArg>) -> Self {
192        self.args.push(arg.into());
193        self
194    }
195}
196
197impl Command for EvalRo {
198    type Response = Frame;
199
200    fn to_frame(&self) -> Frame {
201        let mut parts = vec![
202            bulk("EVAL_RO"),
203            bulk(&self.script),
204            bulk(self.keys.len().to_string()),
205        ];
206        for k in &self.keys {
207            parts.push(bulk(k));
208        }
209        for a in &self.args {
210            parts.push(bulk(a));
211        }
212        array(parts)
213    }
214
215    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
216        Ok(frame)
217    }
218
219    fn name(&self) -> &str {
220        "EVAL_RO"
221    }
222}
223
224// ---------------------------------------------------------------------------
225// EVALSHA_RO
226// ---------------------------------------------------------------------------
227
228/// EVALSHA_RO sha1 numkeys [key ...] [arg ...]
229///
230/// Read-only variant of EVALSHA. Evaluates a cached Lua script by its SHA1
231/// digest, rejecting any write commands. Returns `Frame` directly.
232#[derive(Clone)]
233pub struct EvalShaRo {
234    sha1: String,
235    keys: Vec<CommandArg>,
236    args: Vec<CommandArg>,
237}
238
239impl EvalShaRo {
240    /// Create a new [`EvalShaRo`] command.
241    pub fn new(sha1: impl Into<String>) -> Self {
242        Self {
243            sha1: sha1.into(),
244            keys: Vec::new(),
245            args: Vec::new(),
246        }
247    }
248
249    /// Add a key argument (populates KEYS table in Lua).
250    pub fn key(mut self, key: impl Into<CommandArg>) -> Self {
251        self.keys.push(key.into());
252        self
253    }
254
255    /// Add a regular argument (populates ARGV table in Lua).
256    pub fn arg(mut self, arg: impl Into<CommandArg>) -> Self {
257        self.args.push(arg.into());
258        self
259    }
260}
261
262impl Command for EvalShaRo {
263    type Response = Frame;
264
265    fn to_frame(&self) -> Frame {
266        let mut parts = vec![
267            bulk("EVALSHA_RO"),
268            bulk(self.sha1.as_str()),
269            bulk(self.keys.len().to_string()),
270        ];
271        for k in &self.keys {
272            parts.push(bulk(k));
273        }
274        for a in &self.args {
275            parts.push(bulk(a));
276        }
277        array(parts)
278    }
279
280    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
281        Ok(frame)
282    }
283
284    fn name(&self) -> &str {
285        "EVALSHA_RO"
286    }
287}
288
289// ---------------------------------------------------------------------------
290// Script (SHA1-cached helper)
291// ---------------------------------------------------------------------------
292
293/// A Lua script with a pre-computed, cached SHA1 digest.
294///
295/// `Script` is the ergonomic way to run the same Lua script repeatedly. It
296/// hashes the source once at construction and then builds [`EvalSha`] commands
297/// (which send only the 40-character digest over the wire) instead of
298/// re-transmitting the full script body on every call.
299///
300/// The first time a script runs, the server has not cached it yet and EVALSHA
301/// fails with a `NOSCRIPT` error. Callers detect that with
302/// [`RedisError::is_noscript`](redis_tower_core::RedisError::is_noscript) and
303/// fall back to [`Script::eval`] (or the read-only [`Script::eval_ro`]), which
304/// sends the source; the server caches it so subsequent EVALSHA calls succeed.
305///
306/// This type lives in the command layer so every client (connection,
307/// multiplexed, pooled, cluster, ...) can reuse the same caching primitive. See
308/// `redis_tower::Script` for a wrapper that performs the EVALSHA-then-EVAL
309/// fallback automatically against any executor.
310///
311/// # Example
312///
313/// ```
314/// use redis_tower_commands::Script;
315/// use redis_tower_core::Command;
316///
317/// let script = Script::new("return redis.call('GET', KEYS[1])");
318///
319/// // Preferred path: send only the cached digest.
320/// let evalsha = script.evalsha(&["mykey"], &[]);
321/// assert_eq!(evalsha.name(), "EVALSHA");
322///
323/// // Fallback path on NOSCRIPT: send the full source (server caches it).
324/// let eval = script.eval(&["mykey"], &[]);
325/// assert_eq!(eval.name(), "EVAL");
326/// ```
327#[derive(Clone, Debug)]
328pub struct Script {
329    source: CommandArg,
330    sha: String,
331}
332
333impl Script {
334    /// Create a new `Script` from Lua source code.
335    ///
336    /// The SHA1 digest is computed immediately and cached for the lifetime of
337    /// the value. It matches the digest `SCRIPT LOAD` returns, so it can be used
338    /// directly with `EVALSHA`.
339    pub fn new(source: impl Into<CommandArg>) -> Self {
340        let source = source.into();
341        let sha = hex::encode(Sha1::digest(source.as_bytes()));
342        Self { source, sha }
343    }
344
345    /// Get the cached SHA1 hex digest of the script.
346    pub fn sha(&self) -> &str {
347        &self.sha
348    }
349
350    /// Get the exact Lua source bytes.
351    pub fn source(&self) -> &[u8] {
352        self.source.as_bytes()
353    }
354
355    /// Build an [`EvalSha`] command (preferred -- sends only the cached digest).
356    pub fn evalsha(&self, keys: &[&str], args: &[&str]) -> EvalSha {
357        self.evalsha_args(keys, args)
358    }
359
360    /// Build an [`EvalSha`] command from binary-safe keys and arguments.
361    pub fn evalsha_args(
362        &self,
363        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
364        args: impl IntoIterator<Item = impl Into<CommandArg>>,
365    ) -> EvalSha {
366        let mut cmd = EvalSha::new(&self.sha);
367        for key in keys {
368            cmd = cmd.key(key);
369        }
370        for arg in args {
371            cmd = cmd.arg(arg);
372        }
373        cmd
374    }
375
376    /// Build an [`EvalShaRo`] command, the read-only variant of
377    /// [`evalsha`](Script::evalsha).
378    pub fn evalsha_ro(&self, keys: &[&str], args: &[&str]) -> EvalShaRo {
379        self.evalsha_ro_args(keys, args)
380    }
381
382    /// Build an [`EvalShaRo`] command from binary-safe keys and arguments.
383    pub fn evalsha_ro_args(
384        &self,
385        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
386        args: impl IntoIterator<Item = impl Into<CommandArg>>,
387    ) -> EvalShaRo {
388        let mut cmd = EvalShaRo::new(&self.sha);
389        for key in keys {
390            cmd = cmd.key(key);
391        }
392        for arg in args {
393            cmd = cmd.arg(arg);
394        }
395        cmd
396    }
397
398    /// Build an [`Eval`] command (fallback when EVALSHA returns NOSCRIPT --
399    /// sends the full source, which the server then caches).
400    pub fn eval(&self, keys: &[&str], args: &[&str]) -> Eval {
401        self.eval_args(keys, args)
402    }
403
404    /// Build an [`Eval`] command from binary-safe keys and arguments.
405    pub fn eval_args(
406        &self,
407        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
408        args: impl IntoIterator<Item = impl Into<CommandArg>>,
409    ) -> Eval {
410        let mut cmd = Eval::new(&self.source);
411        for key in keys {
412            cmd = cmd.key(key);
413        }
414        for arg in args {
415            cmd = cmd.arg(arg);
416        }
417        cmd
418    }
419
420    /// Build an [`EvalRo`] command, the read-only variant of
421    /// [`eval`](Script::eval).
422    pub fn eval_ro(&self, keys: &[&str], args: &[&str]) -> EvalRo {
423        self.eval_ro_args(keys, args)
424    }
425
426    /// Build an [`EvalRo`] command from binary-safe keys and arguments.
427    pub fn eval_ro_args(
428        &self,
429        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
430        args: impl IntoIterator<Item = impl Into<CommandArg>>,
431    ) -> EvalRo {
432        let mut cmd = EvalRo::new(&self.source);
433        for key in keys {
434            cmd = cmd.key(key);
435        }
436        for arg in args {
437            cmd = cmd.arg(arg);
438        }
439        cmd
440    }
441}
442
443// ---------------------------------------------------------------------------
444// SCRIPT LOAD
445// ---------------------------------------------------------------------------
446
447/// SCRIPT LOAD script
448///
449/// Loads a Lua script into the script cache without executing it. Returns the
450/// SHA1 digest of the script.
451#[derive(Clone)]
452pub struct ScriptLoad {
453    script: CommandArg,
454}
455
456impl ScriptLoad {
457    /// Create a new [`ScriptLoad`] command.
458    pub fn new(script: impl Into<CommandArg>) -> Self {
459        Self {
460            script: script.into(),
461        }
462    }
463}
464
465impl Command for ScriptLoad {
466    type Response = String;
467
468    fn to_frame(&self) -> Frame {
469        array(vec![bulk("SCRIPT"), bulk("LOAD"), bulk(&self.script)])
470    }
471
472    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
473        match frame {
474            Frame::BulkString(Some(data)) => Ok(String::from_utf8_lossy(&data).into_owned()),
475            other => Err(RedisError::UnexpectedResponse {
476                expected: "bulk string",
477                actual: format!("{other:?}"),
478            }),
479        }
480    }
481
482    fn name(&self) -> &str {
483        "SCRIPT LOAD"
484    }
485}
486
487// ---------------------------------------------------------------------------
488// SCRIPT EXISTS
489// ---------------------------------------------------------------------------
490
491/// SCRIPT EXISTS sha1 [sha1 ...]
492///
493/// Returns a list of booleans indicating whether each script SHA1 exists in
494/// the cache.
495#[derive(Clone)]
496pub struct ScriptExists {
497    sha1s: Vec<String>,
498}
499
500impl ScriptExists {
501    /// Create a new [`ScriptExists`] command.
502    pub fn new(sha1: impl Into<String>) -> Self {
503        Self {
504            sha1s: vec![sha1.into()],
505        }
506    }
507
508    /// Add another SHA1 digest to check.
509    pub fn sha1(mut self, sha1: impl Into<String>) -> Self {
510        self.sha1s.push(sha1.into());
511        self
512    }
513}
514
515impl Command for ScriptExists {
516    type Response = Vec<bool>;
517
518    fn to_frame(&self) -> Frame {
519        let mut parts = vec![bulk("SCRIPT"), bulk("EXISTS")];
520        for s in &self.sha1s {
521            parts.push(bulk(s.as_str()));
522        }
523        array(parts)
524    }
525
526    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
527        match frame {
528            Frame::Array(Some(frames)) => frames
529                .into_iter()
530                .map(|f| match f {
531                    Frame::Integer(n) => Ok(n == 1),
532                    Frame::Boolean(b) => Ok(b),
533                    other => Err(RedisError::UnexpectedResponse {
534                        expected: "integer or boolean",
535                        actual: format!("{other:?}"),
536                    }),
537                })
538                .collect(),
539            other => Err(RedisError::UnexpectedResponse {
540                expected: "array",
541                actual: format!("{other:?}"),
542            }),
543        }
544    }
545
546    fn name(&self) -> &str {
547        "SCRIPT EXISTS"
548    }
549}
550
551// ---------------------------------------------------------------------------
552// SCRIPT FLUSH
553// ---------------------------------------------------------------------------
554
555/// SCRIPT FLUSH [ASYNC | SYNC]
556///
557/// Flushes the Lua script cache.
558#[derive(Clone)]
559pub struct ScriptFlush {
560    mode: Option<FlushMode>,
561}
562
563impl ScriptFlush {
564    /// Create a new [`ScriptFlush`] command.
565    pub fn new() -> Self {
566        Self { mode: None }
567    }
568
569    /// Set the flush mode (ASYNC or SYNC).
570    pub fn mode(mut self, mode: FlushMode) -> Self {
571        self.mode = Some(mode);
572        self
573    }
574}
575
576impl Default for ScriptFlush {
577    fn default() -> Self {
578        Self::new()
579    }
580}
581
582impl Command for ScriptFlush {
583    type Response = ();
584
585    fn to_frame(&self) -> Frame {
586        let mut parts = vec![bulk("SCRIPT"), bulk("FLUSH")];
587        match &self.mode {
588            Some(FlushMode::Async) => parts.push(bulk("ASYNC")),
589            Some(FlushMode::Sync) => parts.push(bulk("SYNC")),
590            None => {}
591        }
592        array(parts)
593    }
594
595    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
596        match frame {
597            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
598            other => Err(RedisError::UnexpectedResponse {
599                expected: "OK",
600                actual: format!("{other:?}"),
601            }),
602        }
603    }
604
605    fn name(&self) -> &str {
606        "SCRIPT FLUSH"
607    }
608}
609
610// ---------------------------------------------------------------------------
611// SCRIPT KILL
612// ---------------------------------------------------------------------------
613
614/// SCRIPT KILL
615///
616/// Kills the currently executing Lua script.
617#[derive(Clone)]
618pub struct ScriptKill;
619
620impl ScriptKill {
621    /// Create a new [`ScriptKill`] command.
622    pub fn new() -> Self {
623        Self
624    }
625}
626
627impl Default for ScriptKill {
628    fn default() -> Self {
629        Self::new()
630    }
631}
632
633impl Command for ScriptKill {
634    type Response = ();
635
636    fn to_frame(&self) -> Frame {
637        array(vec![bulk("SCRIPT"), bulk("KILL")])
638    }
639
640    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
641        match frame {
642            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
643            other => Err(RedisError::UnexpectedResponse {
644                expected: "OK",
645                actual: format!("{other:?}"),
646            }),
647        }
648    }
649
650    fn name(&self) -> &str {
651        "SCRIPT KILL"
652    }
653}
654
655// ---------------------------------------------------------------------------
656// FCALL
657// ---------------------------------------------------------------------------
658
659/// FCALL function numkeys [key ...] [arg ...]
660///
661/// Calls a Redis function. Returns `Frame` directly because functions can
662/// produce any response type.
663#[derive(Clone)]
664pub struct FCall {
665    function: String,
666    keys: Vec<CommandArg>,
667    args: Vec<CommandArg>,
668}
669
670impl FCall {
671    /// Create a new [`FCall`] command.
672    pub fn new(function: impl Into<String>) -> Self {
673        Self {
674            function: function.into(),
675            keys: Vec::new(),
676            args: Vec::new(),
677        }
678    }
679
680    /// Add a key argument (populates KEYS table).
681    pub fn key(mut self, key: impl Into<CommandArg>) -> Self {
682        self.keys.push(key.into());
683        self
684    }
685
686    /// Add a regular argument (populates ARGV table).
687    pub fn arg(mut self, arg: impl Into<CommandArg>) -> Self {
688        self.args.push(arg.into());
689        self
690    }
691}
692
693impl Command for FCall {
694    type Response = Frame;
695
696    fn to_frame(&self) -> Frame {
697        let mut parts = vec![
698            bulk("FCALL"),
699            bulk(self.function.as_str()),
700            bulk(self.keys.len().to_string()),
701        ];
702        for k in &self.keys {
703            parts.push(bulk(k));
704        }
705        for a in &self.args {
706            parts.push(bulk(a));
707        }
708        array(parts)
709    }
710
711    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
712        Ok(frame)
713    }
714
715    fn name(&self) -> &str {
716        "FCALL"
717    }
718}
719
720// ---------------------------------------------------------------------------
721// FCALL_RO
722// ---------------------------------------------------------------------------
723
724/// FCALL_RO function numkeys [key ...] [arg ...]
725///
726/// Read-only variant of FCALL. Calls a Redis function without write
727/// permissions. Returns `Frame` directly.
728#[derive(Clone)]
729pub struct FCallRo {
730    function: String,
731    keys: Vec<CommandArg>,
732    args: Vec<CommandArg>,
733}
734
735impl FCallRo {
736    /// Create a new [`FCallRo`] command.
737    pub fn new(function: impl Into<String>) -> Self {
738        Self {
739            function: function.into(),
740            keys: Vec::new(),
741            args: Vec::new(),
742        }
743    }
744
745    /// Add a key argument (populates KEYS table).
746    pub fn key(mut self, key: impl Into<CommandArg>) -> Self {
747        self.keys.push(key.into());
748        self
749    }
750
751    /// Add a regular argument (populates ARGV table).
752    pub fn arg(mut self, arg: impl Into<CommandArg>) -> Self {
753        self.args.push(arg.into());
754        self
755    }
756}
757
758impl Command for FCallRo {
759    type Response = Frame;
760
761    fn to_frame(&self) -> Frame {
762        let mut parts = vec![
763            bulk("FCALL_RO"),
764            bulk(self.function.as_str()),
765            bulk(self.keys.len().to_string()),
766        ];
767        for k in &self.keys {
768            parts.push(bulk(k));
769        }
770        for a in &self.args {
771            parts.push(bulk(a));
772        }
773        array(parts)
774    }
775
776    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
777        Ok(frame)
778    }
779
780    fn name(&self) -> &str {
781        "FCALL_RO"
782    }
783}
784
785// ---------------------------------------------------------------------------
786// FUNCTION LOAD
787// ---------------------------------------------------------------------------
788
789/// FUNCTION LOAD \[REPLACE\] function-code
790///
791/// Loads a library to Redis. Returns the library name.
792#[derive(Clone)]
793pub struct FunctionLoad {
794    code: CommandArg,
795    replace: bool,
796}
797
798impl FunctionLoad {
799    /// Create a new [`FunctionLoad`] command.
800    pub fn new(code: impl Into<CommandArg>) -> Self {
801        Self {
802            code: code.into(),
803            replace: false,
804        }
805    }
806
807    /// Replace the existing library if it already exists.
808    pub fn replace(mut self) -> Self {
809        self.replace = true;
810        self
811    }
812}
813
814impl Command for FunctionLoad {
815    type Response = String;
816
817    fn to_frame(&self) -> Frame {
818        let mut parts = vec![bulk("FUNCTION"), bulk("LOAD")];
819        if self.replace {
820            parts.push(bulk("REPLACE"));
821        }
822        parts.push(bulk(&self.code));
823        array(parts)
824    }
825
826    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
827        match frame {
828            Frame::BulkString(Some(data)) => Ok(String::from_utf8_lossy(&data).into_owned()),
829            other => Err(RedisError::UnexpectedResponse {
830                expected: "bulk string",
831                actual: format!("{other:?}"),
832            }),
833        }
834    }
835
836    fn name(&self) -> &str {
837        "FUNCTION LOAD"
838    }
839}
840
841// ---------------------------------------------------------------------------
842// FUNCTION DELETE
843// ---------------------------------------------------------------------------
844
845/// FUNCTION DELETE library-name
846///
847/// Deletes a library and all its functions.
848#[derive(Clone)]
849pub struct FunctionDelete {
850    library: String,
851}
852
853impl FunctionDelete {
854    /// Create a new [`FunctionDelete`] command.
855    pub fn new(library: impl Into<String>) -> Self {
856        Self {
857            library: library.into(),
858        }
859    }
860}
861
862impl Command for FunctionDelete {
863    type Response = ();
864
865    fn to_frame(&self) -> Frame {
866        array(vec![
867            bulk("FUNCTION"),
868            bulk("DELETE"),
869            bulk(self.library.as_str()),
870        ])
871    }
872
873    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
874        match frame {
875            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
876            other => Err(RedisError::UnexpectedResponse {
877                expected: "OK",
878                actual: format!("{other:?}"),
879            }),
880        }
881    }
882
883    fn name(&self) -> &str {
884        "FUNCTION DELETE"
885    }
886}
887
888// ---------------------------------------------------------------------------
889// FUNCTION LIST
890// ---------------------------------------------------------------------------
891
892/// FUNCTION LIST \[LIBRARYNAME library-name-pattern\] \[WITHCODE\]
893///
894/// Returns information about the libraries. Returns the raw `Frame` array
895/// because the response is a complex nested structure.
896#[derive(Clone)]
897pub struct FunctionList {
898    library_pattern: Option<String>,
899    withcode: bool,
900}
901
902impl FunctionList {
903    /// Create a new [`FunctionList`] command.
904    pub fn new() -> Self {
905        Self {
906            library_pattern: None,
907            withcode: false,
908        }
909    }
910
911    /// Filter by library name pattern.
912    pub fn library(mut self, pattern: impl Into<String>) -> Self {
913        self.library_pattern = Some(pattern.into());
914        self
915    }
916
917    /// Include the library source code in the response.
918    pub fn withcode(mut self) -> Self {
919        self.withcode = true;
920        self
921    }
922}
923
924impl Default for FunctionList {
925    fn default() -> Self {
926        Self::new()
927    }
928}
929
930impl Command for FunctionList {
931    type Response = Vec<Frame>;
932
933    fn to_frame(&self) -> Frame {
934        let mut parts = vec![bulk("FUNCTION"), bulk("LIST")];
935        if let Some(ref pattern) = self.library_pattern {
936            parts.push(bulk("LIBRARYNAME"));
937            parts.push(bulk(pattern.as_str()));
938        }
939        if self.withcode {
940            parts.push(bulk("WITHCODE"));
941        }
942        array(parts)
943    }
944
945    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
946        match frame {
947            Frame::Array(Some(frames)) => Ok(frames),
948            other => Err(RedisError::UnexpectedResponse {
949                expected: "array",
950                actual: format!("{other:?}"),
951            }),
952        }
953    }
954
955    fn name(&self) -> &str {
956        "FUNCTION LIST"
957    }
958}
959
960// ---------------------------------------------------------------------------
961// FUNCTION DUMP
962// ---------------------------------------------------------------------------
963
964/// FUNCTION DUMP
965///
966/// Returns a serialized payload of all libraries. The payload can be restored
967/// with FUNCTION RESTORE.
968#[derive(Clone)]
969pub struct FunctionDump;
970
971impl FunctionDump {
972    /// Create a new [`FunctionDump`] command.
973    pub fn new() -> Self {
974        Self
975    }
976}
977
978impl Default for FunctionDump {
979    fn default() -> Self {
980        Self::new()
981    }
982}
983
984impl Command for FunctionDump {
985    type Response = Bytes;
986
987    fn to_frame(&self) -> Frame {
988        array(vec![bulk("FUNCTION"), bulk("DUMP")])
989    }
990
991    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
992        match frame {
993            Frame::BulkString(Some(data)) => Ok(data),
994            other => Err(RedisError::UnexpectedResponse {
995                expected: "bulk string",
996                actual: format!("{other:?}"),
997            }),
998        }
999    }
1000
1001    fn name(&self) -> &str {
1002        "FUNCTION DUMP"
1003    }
1004}
1005
1006// ---------------------------------------------------------------------------
1007// FUNCTION RESTORE
1008// ---------------------------------------------------------------------------
1009
1010/// FUNCTION RESTORE serialized-value [FLUSH | APPEND | REPLACE]
1011///
1012/// Restores libraries from a serialized payload produced by FUNCTION DUMP.
1013#[derive(Clone)]
1014pub struct FunctionRestore {
1015    payload: Bytes,
1016    policy: Option<RestorePolicy>,
1017}
1018
1019/// Restore policy for FUNCTION RESTORE.
1020#[derive(Clone)]
1021pub enum RestorePolicy {
1022    /// Delete all existing libraries before restoring.
1023    Flush,
1024    /// Append new libraries; fail if a library already exists.
1025    Append,
1026    /// Replace existing libraries with the restored ones.
1027    Replace,
1028}
1029
1030impl FunctionRestore {
1031    /// Create a new [`FunctionRestore`] command.
1032    pub fn new(payload: Bytes) -> Self {
1033        Self {
1034            payload,
1035            policy: None,
1036        }
1037    }
1038
1039    /// Set the restore policy.
1040    pub fn policy(mut self, policy: RestorePolicy) -> Self {
1041        self.policy = Some(policy);
1042        self
1043    }
1044}
1045
1046impl Command for FunctionRestore {
1047    type Response = ();
1048
1049    fn to_frame(&self) -> Frame {
1050        let mut parts = vec![
1051            bulk("FUNCTION"),
1052            bulk("RESTORE"),
1053            Frame::BulkString(Some(self.payload.clone())),
1054        ];
1055        match &self.policy {
1056            Some(RestorePolicy::Flush) => parts.push(bulk("FLUSH")),
1057            Some(RestorePolicy::Append) => parts.push(bulk("APPEND")),
1058            Some(RestorePolicy::Replace) => parts.push(bulk("REPLACE")),
1059            None => {}
1060        }
1061        array(parts)
1062    }
1063
1064    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1065        match frame {
1066            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1067            other => Err(RedisError::UnexpectedResponse {
1068                expected: "OK",
1069                actual: format!("{other:?}"),
1070            }),
1071        }
1072    }
1073
1074    fn name(&self) -> &str {
1075        "FUNCTION RESTORE"
1076    }
1077}
1078
1079// ---------------------------------------------------------------------------
1080// FUNCTION FLUSH
1081// ---------------------------------------------------------------------------
1082
1083/// FUNCTION FLUSH [ASYNC | SYNC]
1084///
1085/// Deletes all libraries and functions.
1086#[derive(Clone)]
1087pub struct FunctionFlush {
1088    mode: Option<FlushMode>,
1089}
1090
1091impl FunctionFlush {
1092    /// Create a new [`FunctionFlush`] command.
1093    pub fn new() -> Self {
1094        Self { mode: None }
1095    }
1096
1097    /// Set the flush mode (ASYNC or SYNC).
1098    pub fn mode(mut self, mode: FlushMode) -> Self {
1099        self.mode = Some(mode);
1100        self
1101    }
1102}
1103
1104impl Default for FunctionFlush {
1105    fn default() -> Self {
1106        Self::new()
1107    }
1108}
1109
1110impl Command for FunctionFlush {
1111    type Response = ();
1112
1113    fn to_frame(&self) -> Frame {
1114        let mut parts = vec![bulk("FUNCTION"), bulk("FLUSH")];
1115        match &self.mode {
1116            Some(FlushMode::Async) => parts.push(bulk("ASYNC")),
1117            Some(FlushMode::Sync) => parts.push(bulk("SYNC")),
1118            None => {}
1119        }
1120        array(parts)
1121    }
1122
1123    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1124        match frame {
1125            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1126            other => Err(RedisError::UnexpectedResponse {
1127                expected: "OK",
1128                actual: format!("{other:?}"),
1129            }),
1130        }
1131    }
1132
1133    fn name(&self) -> &str {
1134        "FUNCTION FLUSH"
1135    }
1136}
1137
1138// ---------------------------------------------------------------------------
1139// FUNCTION KILL
1140// ---------------------------------------------------------------------------
1141
1142/// FUNCTION KILL
1143///
1144/// Terminates a currently executing function. Redis only permits killing a
1145/// function that has not yet performed a write.
1146#[derive(Debug, Clone)]
1147pub struct FunctionKill;
1148
1149impl FunctionKill {
1150    /// Create a `FUNCTION KILL` request.
1151    pub fn new() -> Self {
1152        Self
1153    }
1154}
1155
1156impl Default for FunctionKill {
1157    fn default() -> Self {
1158        Self::new()
1159    }
1160}
1161
1162impl Command for FunctionKill {
1163    type Response = ();
1164
1165    fn to_frame(&self) -> Frame {
1166        array(vec![bulk("FUNCTION"), bulk("KILL")])
1167    }
1168
1169    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1170        match frame {
1171            Frame::SimpleString(value) if value.eq_ignore_ascii_case(b"OK") => Ok(()),
1172            other => Err(RedisError::UnexpectedResponse {
1173                expected: "OK",
1174                actual: format!("{other:?}"),
1175            }),
1176        }
1177    }
1178
1179    fn name(&self) -> &str {
1180        "FUNCTION KILL"
1181    }
1182}
1183
1184// ---------------------------------------------------------------------------
1185// FUNCTION STATS
1186// ---------------------------------------------------------------------------
1187
1188/// FUNCTION STATS
1189///
1190/// Returns information about the function currently running and the available
1191/// execution engines. Returns the raw `Frame` array because the response is a
1192/// complex nested structure.
1193#[derive(Clone)]
1194pub struct FunctionStats;
1195
1196impl FunctionStats {
1197    /// Create a new [`FunctionStats`] command.
1198    pub fn new() -> Self {
1199        Self
1200    }
1201}
1202
1203impl Default for FunctionStats {
1204    fn default() -> Self {
1205        Self::new()
1206    }
1207}
1208
1209impl Command for FunctionStats {
1210    type Response = Vec<Frame>;
1211
1212    fn to_frame(&self) -> Frame {
1213        array(vec![bulk("FUNCTION"), bulk("STATS")])
1214    }
1215
1216    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1217        match frame {
1218            Frame::Array(Some(frames)) => Ok(frames),
1219            // RESP3 returns the stats as a map; flatten it to the RESP2
1220            // key/value array shape so callers see one stable layout.
1221            Frame::Map(pairs) => {
1222                let mut out = Vec::with_capacity(pairs.len() * 2);
1223                for (k, v) in pairs {
1224                    out.push(k);
1225                    out.push(v);
1226                }
1227                Ok(out)
1228            }
1229            other => Err(RedisError::UnexpectedResponse {
1230                expected: "array or map",
1231                actual: format!("{other:?}"),
1232            }),
1233        }
1234    }
1235
1236    fn name(&self) -> &str {
1237        "FUNCTION STATS"
1238    }
1239}
1240
1241/// FUNCTION HELP
1242///
1243/// Returns helpful text describing the FUNCTION subcommands.
1244#[derive(Clone)]
1245pub struct FunctionHelp;
1246
1247impl FunctionHelp {
1248    /// Create a new [`FunctionHelp`] command.
1249    pub fn new() -> Self {
1250        Self
1251    }
1252}
1253
1254impl Default for FunctionHelp {
1255    fn default() -> Self {
1256        Self::new()
1257    }
1258}
1259
1260impl Command for FunctionHelp {
1261    type Response = Vec<Bytes>;
1262
1263    fn to_frame(&self) -> Frame {
1264        array(vec![bulk("FUNCTION"), bulk("HELP")])
1265    }
1266
1267    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1268        crate::help::parse_help_lines(frame)
1269    }
1270
1271    fn name(&self) -> &str {
1272        "FUNCTION HELP"
1273    }
1274
1275    fn idempotent(&self) -> bool {
1276        true
1277    }
1278}
1279
1280/// SCRIPT HELP
1281///
1282/// Returns helpful text describing the SCRIPT subcommands.
1283#[derive(Clone)]
1284pub struct ScriptHelp;
1285
1286impl ScriptHelp {
1287    /// Create a new [`ScriptHelp`] command.
1288    pub fn new() -> Self {
1289        Self
1290    }
1291}
1292
1293impl Default for ScriptHelp {
1294    fn default() -> Self {
1295        Self::new()
1296    }
1297}
1298
1299impl Command for ScriptHelp {
1300    type Response = Vec<Bytes>;
1301
1302    fn to_frame(&self) -> Frame {
1303        array(vec![bulk("SCRIPT"), bulk("HELP")])
1304    }
1305
1306    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1307        crate::help::parse_help_lines(frame)
1308    }
1309
1310    fn name(&self) -> &str {
1311        "SCRIPT HELP"
1312    }
1313
1314    fn idempotent(&self) -> bool {
1315        true
1316    }
1317}
1318
1319/// Debug mode for [`ScriptDebug`].
1320#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1321pub enum ScriptDebugMode {
1322    /// Enable non-blocking asynchronous debugging of Lua scripts (YES).
1323    Yes,
1324    /// Enable blocking synchronous debugging of Lua scripts (SYNC).
1325    Sync,
1326    /// Disable script debugging (NO).
1327    No,
1328}
1329
1330impl ScriptDebugMode {
1331    fn as_arg(self) -> &'static str {
1332        match self {
1333            ScriptDebugMode::Yes => "YES",
1334            ScriptDebugMode::Sync => "SYNC",
1335            ScriptDebugMode::No => "NO",
1336        }
1337    }
1338}
1339
1340/// SCRIPT DEBUG YES|SYNC|NO
1341///
1342/// Sets the debug mode for subsequent EVAL executions on this connection.
1343#[derive(Clone)]
1344pub struct ScriptDebug {
1345    mode: ScriptDebugMode,
1346}
1347
1348impl ScriptDebug {
1349    /// Create a new [`ScriptDebug`] command.
1350    pub fn new(mode: ScriptDebugMode) -> Self {
1351        Self { mode }
1352    }
1353
1354    /// Enable non-blocking asynchronous debugging (`SCRIPT DEBUG YES`).
1355    pub fn yes() -> Self {
1356        Self::new(ScriptDebugMode::Yes)
1357    }
1358
1359    /// Enable blocking synchronous debugging (`SCRIPT DEBUG SYNC`).
1360    pub fn sync() -> Self {
1361        Self::new(ScriptDebugMode::Sync)
1362    }
1363
1364    /// Disable script debugging (`SCRIPT DEBUG NO`).
1365    pub fn no() -> Self {
1366        Self::new(ScriptDebugMode::No)
1367    }
1368}
1369
1370impl Command for ScriptDebug {
1371    type Response = ();
1372
1373    fn to_frame(&self) -> Frame {
1374        array(vec![
1375            bulk("SCRIPT"),
1376            bulk("DEBUG"),
1377            bulk(self.mode.as_arg()),
1378        ])
1379    }
1380
1381    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1382        match frame {
1383            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1384            other => Err(RedisError::UnexpectedResponse {
1385                expected: "OK",
1386                actual: format!("{other:?}"),
1387            }),
1388        }
1389    }
1390
1391    fn name(&self) -> &str {
1392        "SCRIPT DEBUG"
1393    }
1394}
1395
1396#[cfg(test)]
1397mod tests {
1398    use super::*;
1399    use redis_tower_core::Command;
1400    use redis_tower_protocol::Frame;
1401    use redis_tower_protocol::helpers::{array, bulk};
1402
1403    // -- Eval --
1404
1405    #[test]
1406    fn eval_simple_to_frame() {
1407        let cmd = Eval::new("return 1");
1408        assert_eq!(
1409            cmd.to_frame(),
1410            array(vec![bulk("EVAL"), bulk("return 1"), bulk("0")])
1411        );
1412    }
1413
1414    #[test]
1415    fn eval_with_keys_and_args_to_frame() {
1416        let cmd = Eval::new("return redis.call('GET', KEYS[1])")
1417            .key("mykey")
1418            .arg("extra");
1419        assert_eq!(
1420            cmd.to_frame(),
1421            array(vec![
1422                bulk("EVAL"),
1423                bulk("return redis.call('GET', KEYS[1])"),
1424                bulk("1"),
1425                bulk("mykey"),
1426                bulk("extra"),
1427            ])
1428        );
1429    }
1430
1431    #[test]
1432    fn eval_parse_response_passthrough() {
1433        let cmd = Eval::new("return 42");
1434        let frame = Frame::Integer(42);
1435        assert_eq!(cmd.parse_response(frame).unwrap(), Frame::Integer(42));
1436    }
1437
1438    // -- EvalSha --
1439
1440    #[test]
1441    fn evalsha_to_frame() {
1442        let cmd = EvalSha::new("abc123").key("k1").key("k2").arg("a1");
1443        assert_eq!(
1444            cmd.to_frame(),
1445            array(vec![
1446                bulk("EVALSHA"),
1447                bulk("abc123"),
1448                bulk("2"),
1449                bulk("k1"),
1450                bulk("k2"),
1451                bulk("a1"),
1452            ])
1453        );
1454    }
1455
1456    #[test]
1457    fn evalsha_parse_response() {
1458        let cmd = EvalSha::new("abc123");
1459        let frame = Frame::SimpleString(Bytes::from("OK"));
1460        assert_eq!(
1461            cmd.parse_response(frame).unwrap(),
1462            Frame::SimpleString(Bytes::from("OK"))
1463        );
1464    }
1465
1466    // -- FCall --
1467
1468    #[test]
1469    fn fcall_to_frame() {
1470        let cmd = FCall::new("myfunc").key("k1").arg("a1").arg("a2");
1471        assert_eq!(
1472            cmd.to_frame(),
1473            array(vec![
1474                bulk("FCALL"),
1475                bulk("myfunc"),
1476                bulk("1"),
1477                bulk("k1"),
1478                bulk("a1"),
1479                bulk("a2"),
1480            ])
1481        );
1482    }
1483
1484    #[test]
1485    fn fcall_no_keys_to_frame() {
1486        let cmd = FCall::new("noop");
1487        assert_eq!(
1488            cmd.to_frame(),
1489            array(vec![bulk("FCALL"), bulk("noop"), bulk("0")])
1490        );
1491    }
1492
1493    #[test]
1494    fn fcall_parse_response() {
1495        let cmd = FCall::new("myfunc");
1496        let frame = Frame::BulkString(Some(Bytes::from("result")));
1497        assert_eq!(
1498            cmd.parse_response(frame).unwrap(),
1499            Frame::BulkString(Some(Bytes::from("result")))
1500        );
1501    }
1502
1503    // -- FCallRo --
1504
1505    #[test]
1506    fn fcall_ro_to_frame() {
1507        let cmd = FCallRo::new("readonly_fn").key("k1");
1508        assert_eq!(
1509            cmd.to_frame(),
1510            array(vec![
1511                bulk("FCALL_RO"),
1512                bulk("readonly_fn"),
1513                bulk("1"),
1514                bulk("k1")
1515            ])
1516        );
1517    }
1518
1519    // -- EvalRo --
1520
1521    #[test]
1522    fn eval_ro_to_frame() {
1523        let cmd = EvalRo::new("return redis.call('GET', KEYS[1])").key("mykey");
1524        assert_eq!(
1525            cmd.to_frame(),
1526            array(vec![
1527                bulk("EVAL_RO"),
1528                bulk("return redis.call('GET', KEYS[1])"),
1529                bulk("1"),
1530                bulk("mykey"),
1531            ])
1532        );
1533    }
1534
1535    #[test]
1536    fn eval_ro_parse_response() {
1537        let cmd = EvalRo::new("return 1");
1538        assert_eq!(
1539            cmd.parse_response(Frame::Integer(1)).unwrap(),
1540            Frame::Integer(1)
1541        );
1542    }
1543
1544    // -- EvalShaRo --
1545
1546    #[test]
1547    fn evalsha_ro_to_frame() {
1548        let cmd = EvalShaRo::new("abc123").key("k1").arg("a1");
1549        assert_eq!(
1550            cmd.to_frame(),
1551            array(vec![
1552                bulk("EVALSHA_RO"),
1553                bulk("abc123"),
1554                bulk("1"),
1555                bulk("k1"),
1556                bulk("a1"),
1557            ])
1558        );
1559    }
1560
1561    // -- Script (SHA1-cached helper) --
1562
1563    #[test]
1564    fn script_sha_matches_known_digest() {
1565        // "return 1" has a well-known SHA1 digest:
1566        //   printf 'return 1' | sha1sum
1567        let script = Script::new("return 1");
1568        assert_eq!(script.sha(), "e0e1f9fabfc9d4800c877a703b823ac0578ff8db");
1569    }
1570
1571    #[test]
1572    fn script_source_is_preserved() {
1573        let script = Script::new("return redis.call('GET', KEYS[1])");
1574        assert_eq!(script.source(), b"return redis.call('GET', KEYS[1])");
1575    }
1576
1577    #[test]
1578    fn script_evalsha_sends_digest_not_source() {
1579        let script = Script::new("return 1");
1580        let cmd = script.evalsha(&["key1", "key2"], &["arg1"]);
1581        assert_eq!(cmd.name(), "EVALSHA");
1582        // The frame must carry the digest, never the source text.
1583        assert_eq!(
1584            cmd.to_frame(),
1585            array(vec![
1586                bulk("EVALSHA"),
1587                bulk(script.sha()),
1588                bulk("2"),
1589                bulk("key1"),
1590                bulk("key2"),
1591                bulk("arg1"),
1592            ])
1593        );
1594    }
1595
1596    #[test]
1597    fn script_eval_sends_full_source() {
1598        let script = Script::new("return 1");
1599        let cmd = script.eval(&["key1"], &["arg1", "arg2"]);
1600        assert_eq!(cmd.name(), "EVAL");
1601        assert_eq!(
1602            cmd.to_frame(),
1603            array(vec![
1604                bulk("EVAL"),
1605                bulk("return 1"),
1606                bulk("1"),
1607                bulk("key1"),
1608                bulk("arg1"),
1609                bulk("arg2"),
1610            ])
1611        );
1612    }
1613
1614    #[test]
1615    fn script_argument_helpers_preserve_binary_keys_and_args() {
1616        let script = Script::new(b"return {KEYS[1], ARGV[1]}".as_slice());
1617        let keys = [CommandArg::from_static(b"key\0\xff")];
1618        let args = [CommandArg::from_static(b"\r\n$5\r\nvalue")];
1619
1620        assert_eq!(
1621            script.eval_args(&keys, &args).to_frame(),
1622            array(vec![
1623                bulk("EVAL"),
1624                bulk(b"return {KEYS[1], ARGV[1]}".as_slice()),
1625                bulk("1"),
1626                bulk(b"key\0\xff".as_slice()),
1627                bulk(b"\r\n$5\r\nvalue".as_slice()),
1628            ])
1629        );
1630    }
1631
1632    #[test]
1633    fn script_ro_variants_use_ro_commands() {
1634        let script = Script::new("return redis.call('GET', KEYS[1])");
1635
1636        let evalsha_ro = script.evalsha_ro(&["k"], &[]);
1637        assert_eq!(evalsha_ro.name(), "EVALSHA_RO");
1638        assert_eq!(
1639            evalsha_ro.to_frame(),
1640            array(vec![
1641                bulk("EVALSHA_RO"),
1642                bulk(script.sha()),
1643                bulk("1"),
1644                bulk("k"),
1645            ])
1646        );
1647
1648        let eval_ro = script.eval_ro(&["k"], &[]);
1649        assert_eq!(eval_ro.name(), "EVAL_RO");
1650        assert_eq!(
1651            eval_ro.to_frame(),
1652            array(vec![
1653                bulk("EVAL_RO"),
1654                bulk("return redis.call('GET', KEYS[1])"),
1655                bulk("1"),
1656                bulk("k"),
1657            ])
1658        );
1659    }
1660
1661    #[test]
1662    fn script_empty_keys_and_args() {
1663        let script = Script::new("return 42");
1664        assert_eq!(
1665            script.evalsha(&[], &[]).to_frame(),
1666            array(vec![bulk("EVALSHA"), bulk(script.sha()), bulk("0")])
1667        );
1668        assert_eq!(
1669            script.eval(&[], &[]).to_frame(),
1670            array(vec![bulk("EVAL"), bulk("return 42"), bulk("0")])
1671        );
1672    }
1673
1674    // -- ScriptLoad --
1675
1676    #[test]
1677    fn script_load_to_frame() {
1678        let cmd = ScriptLoad::new("return 1");
1679        assert_eq!(
1680            cmd.to_frame(),
1681            array(vec![bulk("SCRIPT"), bulk("LOAD"), bulk("return 1")])
1682        );
1683    }
1684
1685    #[test]
1686    fn script_load_parse_response() {
1687        let cmd = ScriptLoad::new("return 1");
1688        let frame = Frame::BulkString(Some(Bytes::from(
1689            "e0e1f9fabfc9d4800c877a703b823ac0578ff831",
1690        )));
1691        assert_eq!(
1692            cmd.parse_response(frame).unwrap(),
1693            "e0e1f9fabfc9d4800c877a703b823ac0578ff831"
1694        );
1695    }
1696
1697    // -- ScriptExists --
1698
1699    #[test]
1700    fn script_exists_to_frame() {
1701        let cmd = ScriptExists::new("sha1").sha1("sha2");
1702        assert_eq!(
1703            cmd.to_frame(),
1704            array(vec![
1705                bulk("SCRIPT"),
1706                bulk("EXISTS"),
1707                bulk("sha1"),
1708                bulk("sha2")
1709            ])
1710        );
1711    }
1712
1713    #[test]
1714    fn script_exists_parse_response() {
1715        let cmd = ScriptExists::new("sha1").sha1("sha2");
1716        let frame = Frame::Array(Some(vec![Frame::Integer(1), Frame::Integer(0)]));
1717        let result = cmd.parse_response(frame).unwrap();
1718        assert_eq!(result, vec![true, false]);
1719    }
1720
1721    // -- ScriptFlush --
1722
1723    #[test]
1724    fn script_flush_to_frame() {
1725        let cmd = ScriptFlush::new().mode(FlushMode::Async);
1726        assert_eq!(
1727            cmd.to_frame(),
1728            array(vec![bulk("SCRIPT"), bulk("FLUSH"), bulk("ASYNC")])
1729        );
1730    }
1731
1732    // -- FunctionLoad --
1733
1734    #[test]
1735    fn function_load_to_frame() {
1736        let cmd = FunctionLoad::new(
1737            "#!lua name=mylib\nredis.register_function('myfunc', function() return 1 end)",
1738        )
1739        .replace();
1740        let frame = cmd.to_frame();
1741        if let Frame::Array(Some(parts)) = &frame {
1742            assert_eq!(parts[0], Frame::BulkString(Some(Bytes::from("FUNCTION"))));
1743            assert_eq!(parts[1], Frame::BulkString(Some(Bytes::from("LOAD"))));
1744            assert_eq!(parts[2], Frame::BulkString(Some(Bytes::from("REPLACE"))));
1745            assert_eq!(parts.len(), 4);
1746        } else {
1747            panic!("expected array frame");
1748        }
1749    }
1750
1751    // -- FunctionDelete --
1752
1753    #[test]
1754    fn function_delete_to_frame() {
1755        let cmd = FunctionDelete::new("mylib");
1756        assert_eq!(
1757            cmd.to_frame(),
1758            array(vec![bulk("FUNCTION"), bulk("DELETE"), bulk("mylib")])
1759        );
1760    }
1761
1762    #[test]
1763    fn function_delete_parse_ok() {
1764        let cmd = FunctionDelete::new("mylib");
1765        let frame = Frame::SimpleString(Bytes::from("OK"));
1766        cmd.parse_response(frame).unwrap();
1767    }
1768
1769    // -- FunctionKill --
1770
1771    #[test]
1772    fn function_kill_to_frame_and_metadata() {
1773        let cmd = FunctionKill::new();
1774        assert_eq!(cmd.to_frame(), array(vec![bulk("FUNCTION"), bulk("KILL")]));
1775        assert_eq!(cmd.name(), "FUNCTION KILL");
1776        assert!(!cmd.idempotent());
1777    }
1778
1779    #[test]
1780    fn function_kill_parses_only_ok() {
1781        let cmd = FunctionKill::new();
1782        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
1783            .unwrap();
1784        assert!(
1785            cmd.parse_response(Frame::SimpleString(Bytes::from("NOTBUSY")))
1786                .is_err()
1787        );
1788        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
1789    }
1790
1791    // -- FunctionStats --
1792
1793    #[test]
1794    fn function_stats_parses_resp3_map() {
1795        // Under RESP3 the server returns FUNCTION STATS as a map; we flatten it
1796        // to the RESP2 key/value array shape so callers see one stable layout.
1797        let cmd = FunctionStats::new();
1798        let frame = Frame::Map(vec![
1799            (bulk("running_script"), Frame::Null),
1800            (bulk("engines"), Frame::Array(Some(vec![]))),
1801        ]);
1802        let out = cmd.parse_response(frame).unwrap();
1803        assert_eq!(out.len(), 4, "two map pairs flatten to four frames");
1804        assert_eq!(out[0], bulk("running_script"));
1805        assert_eq!(out[1], Frame::Null);
1806        assert_eq!(out[2], bulk("engines"));
1807        assert_eq!(out[3], Frame::Array(Some(vec![])));
1808    }
1809
1810    #[test]
1811    fn help_subcommands_to_frame() {
1812        assert_eq!(
1813            FunctionHelp::new().to_frame(),
1814            array(vec![bulk("FUNCTION"), bulk("HELP")])
1815        );
1816        assert_eq!(
1817            ScriptHelp::new().to_frame(),
1818            array(vec![bulk("SCRIPT"), bulk("HELP")])
1819        );
1820        assert!(FunctionHelp::new().idempotent());
1821        assert!(ScriptHelp::new().idempotent());
1822    }
1823
1824    #[test]
1825    fn script_help_parse_lines() {
1826        let cmd = ScriptHelp::new();
1827        let reply = array(vec![bulk("SCRIPT <subcommand>"), bulk("LOAD <script>")]);
1828        let lines = cmd.parse_response(reply).unwrap();
1829        assert_eq!(lines.len(), 2);
1830        assert_eq!(&lines[0][..], b"SCRIPT <subcommand>");
1831    }
1832
1833    #[test]
1834    fn script_debug_to_frame() {
1835        assert_eq!(
1836            ScriptDebug::yes().to_frame(),
1837            array(vec![bulk("SCRIPT"), bulk("DEBUG"), bulk("YES")])
1838        );
1839        assert_eq!(
1840            ScriptDebug::sync().to_frame(),
1841            array(vec![bulk("SCRIPT"), bulk("DEBUG"), bulk("SYNC")])
1842        );
1843        assert_eq!(
1844            ScriptDebug::no().to_frame(),
1845            array(vec![bulk("SCRIPT"), bulk("DEBUG"), bulk("NO")])
1846        );
1847    }
1848
1849    #[test]
1850    fn script_debug_parse_ok() {
1851        ScriptDebug::no()
1852            .parse_response(Frame::SimpleString(Bytes::from("OK")))
1853            .unwrap();
1854        assert!(ScriptDebug::no().parse_response(Frame::Integer(1)).is_err());
1855    }
1856}