fred 10.1.0

An async client for Redis and Valkey.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#[cfg(feature = "sha-1")]
use crate::util::sha1_hash;
use crate::{
  clients::Client,
  interfaces::{FunctionInterface, LuaInterface},
  prelude::{Error, ErrorKind, FredResult, FromValue},
  types::{MultipleKeys, MultipleValues, Value},
  utils,
};
use bytes_utils::Str;
use std::{
  cmp::Ordering,
  collections::HashMap,
  convert::TryInto,
  fmt,
  fmt::Formatter,
  hash::{Hash, Hasher},
  ops::Deref,
};

/// Flags for the SCRIPT DEBUG command.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ScriptDebugFlag {
  Yes,
  No,
  Sync,
}

impl ScriptDebugFlag {
  #[cfg(feature = "i-scripts")]
  pub(crate) fn to_str(&self) -> Str {
    utils::static_str(match *self {
      ScriptDebugFlag::Yes => "YES",
      ScriptDebugFlag::No => "NO",
      ScriptDebugFlag::Sync => "SYNC",
    })
  }
}

/// The policy type for the [FUNCTION RESTORE](https://redis.io/commands/function-restore/) command.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FnPolicy {
  Flush,
  Append,
  Replace,
}

impl Default for FnPolicy {
  fn default() -> Self {
    FnPolicy::Append
  }
}

impl FnPolicy {
  #[cfg(feature = "i-scripts")]
  pub(crate) fn to_str(&self) -> Str {
    utils::static_str(match *self {
      FnPolicy::Flush => "FLUSH",
      FnPolicy::Append => "APPEND",
      FnPolicy::Replace => "REPLACE",
    })
  }

  pub(crate) fn from_str(s: &str) -> Result<Self, Error> {
    Ok(match s {
      "flush" | "FLUSH" => FnPolicy::Flush,
      "append" | "APPEND" => FnPolicy::Append,
      "replace" | "REPLACE" => FnPolicy::Replace,
      _ => {
        return Err(Error::new(
          ErrorKind::InvalidArgument,
          "Invalid function restore policy.",
        ))
      },
    })
  }
}

// have to implement these for specific types to avoid conflicting with the core Into implementation
impl TryFrom<&str> for FnPolicy {
  type Error = Error;

  fn try_from(value: &str) -> Result<Self, Self::Error> {
    FnPolicy::from_str(value)
  }
}

impl TryFrom<&String> for FnPolicy {
  type Error = Error;

  fn try_from(value: &String) -> Result<Self, Self::Error> {
    FnPolicy::from_str(value.as_str())
  }
}

impl TryFrom<String> for FnPolicy {
  type Error = Error;

  fn try_from(value: String) -> Result<Self, Self::Error> {
    FnPolicy::from_str(value.as_str())
  }
}

impl TryFrom<Str> for FnPolicy {
  type Error = Error;

  fn try_from(value: Str) -> Result<Self, Self::Error> {
    FnPolicy::from_str(&value)
  }
}

impl TryFrom<&Str> for FnPolicy {
  type Error = Error;

  fn try_from(value: &Str) -> Result<Self, Self::Error> {
    FnPolicy::from_str(value)
  }
}

/// An interface for caching and running lua scripts.
///
/// ```rust no_run
/// # use fred::types::scripts::Script;
/// # use fred::prelude::*;
/// async fn example(client: &Client) -> Result<(), Error> {
///   let script = Script::from_lua("return ARGV[1]");
///   assert_eq!(script.sha1(), "098e0f0d1448c0a81dafe820f66d460eb09263da");
///
///   let _ = script.load(client).await?;
///   let result: String = script.evalsha(client, "key", "arg").await?;
///   assert_eq!(result, "arg");
///   Ok(())
/// }
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Script {
  lua:  Option<Str>,
  hash: Str,
}

impl fmt::Display for Script {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    write!(f, "{}", self.hash)
  }
}

impl Hash for Script {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.hash.hash(state);
  }
}

impl Ord for Script {
  fn cmp(&self, other: &Self) -> Ordering {
    self.hash.cmp(&other.hash)
  }
}

impl PartialOrd for Script {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl Script {
  /// Create a new `Script` from a lua script.
  #[cfg(feature = "sha-1")]
  #[cfg_attr(docsrs, doc(cfg(feature = "sha-1")))]
  pub fn from_lua<S: Into<Str>>(lua: S) -> Self {
    let lua: Str = lua.into();
    let hash = Str::from(sha1_hash(&lua));

    Script { lua: Some(lua), hash }
  }

  /// Create a new `Script` from a lua hash.
  pub fn from_hash<S: Into<Str>>(hash: S) -> Self {
    Script {
      lua:  None,
      hash: hash.into(),
    }
  }

  /// Read the lua script contents.
  pub fn lua(&self) -> Option<&Str> {
    self.lua.as_ref()
  }

  /// Read the SHA-1 hash for the script.
  pub fn sha1(&self) -> &Str {
    &self.hash
  }

  /// Call `SCRIPT LOAD` on all the associated servers. This must be
  /// called once before calling [evalsha](Self::evalsha).
  #[cfg(feature = "sha-1")]
  #[cfg_attr(docsrs, doc(cfg(feature = "sha-1")))]
  pub async fn load(&self, client: &Client) -> FredResult<()> {
    if let Some(ref lua) = self.lua {
      client.script_load_cluster::<(), _>(lua.clone()).await
    } else {
      Err(Error::new(ErrorKind::Unknown, "Missing lua script contents."))
    }
  }

  /// Send `EVALSHA` to the server with the provided arguments.
  pub async fn evalsha<R, C, K, V>(&self, client: &C, keys: K, args: V) -> FredResult<R>
  where
    R: FromValue,
    C: LuaInterface + Send + Sync,
    K: Into<MultipleKeys> + Send,
    V: TryInto<MultipleValues> + Send,
    V::Error: Into<Error> + Send,
  {
    client.evalsha(self.hash.clone(), keys, args).await
  }

  /// Send `EVALSHA` to the server with the provided arguments. Automatically `SCRIPT LOAD` in case
  /// of `NOSCRIPT` error and try `EVALSHA` again.
  #[cfg(feature = "sha-1")]
  #[cfg_attr(docsrs, doc(cfg(feature = "sha-1")))]
  pub async fn evalsha_with_reload<R, K, V>(&self, client: &Client, keys: K, args: V) -> FredResult<R>
  where
    R: FromValue,
    K: Into<MultipleKeys> + Send,
    V: TryInto<MultipleValues> + Send,
    V::Error: Into<Error> + Send,
  {
    into!(keys);
    try_into!(args);

    match client.evalsha(self.hash.clone(), keys.clone(), args.clone()).await {
      Err(error) if error.details().starts_with("NOSCRIPT") => {
        self.load(client).await?;
        client.evalsha(self.hash.clone(), keys, args).await
      },
      result => result,
    }
  }
}

/// Possible [flags](https://redis.io/docs/manual/programmability/lua-api/) associated with a [Function](crate::types::scripts::Function).
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum FunctionFlag {
  NoWrites,
  AllowOOM,
  NoCluster,
  AllowCrossSlotKeys,
  AllowStale,
}

impl FunctionFlag {
  /// Parse the string representation of the flag.
  #[allow(clippy::should_implement_trait)]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "allow-oom" => FunctionFlag::AllowOOM,
      "allow-stale" => FunctionFlag::AllowStale,
      "allow-cross-slot-keys" => FunctionFlag::AllowCrossSlotKeys,
      "no-writes" => FunctionFlag::NoWrites,
      "no-cluster" => FunctionFlag::NoCluster,
      _ => return None,
    })
  }

  /// Convert to the string representation of the flag.
  pub fn to_str(&self) -> &'static str {
    match self {
      FunctionFlag::AllowCrossSlotKeys => "allow-cross-slot-keys",
      FunctionFlag::AllowOOM => "allow-oom",
      FunctionFlag::NoCluster => "no-cluster",
      FunctionFlag::NoWrites => "no-writes",
      FunctionFlag::AllowStale => "allow-stale",
    }
  }
}

/// An individual function within a [Library](crate::types::scripts::Library).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Function {
  pub(crate) name:  Str,
  pub(crate) flags: Vec<FunctionFlag>,
}

impl fmt::Display for Function {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    write!(f, "{}", self.name)
  }
}

impl Hash for Function {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.name.hash(state);
  }
}

impl Ord for Function {
  fn cmp(&self, other: &Self) -> Ordering {
    self.name.cmp(&other.name)
  }
}

impl PartialOrd for Function {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl Function {
  /// Create a new `Function`.
  pub fn new<S: Into<Str>>(name: S, flags: Vec<FunctionFlag>) -> Self {
    Function {
      name: name.into(),
      flags,
    }
  }

  /// Read the name of the function.
  pub fn name(&self) -> &Str {
    &self.name
  }

  /// Read the flags associated with the function.
  pub fn flags(&self) -> &[FunctionFlag] {
    &self.flags
  }

  /// Send the [fcall](crate::interfaces::FunctionInterface::fcall) command via the provided client.
  pub async fn fcall<R, C, K, V>(&self, client: &C, keys: K, args: V) -> FredResult<R>
  where
    R: FromValue,
    C: FunctionInterface + Send + Sync,
    K: Into<MultipleKeys> + Send,
    V: TryInto<MultipleValues> + Send,
    V::Error: Into<Error> + Send,
  {
    client.fcall(self.name.clone(), keys, args).await
  }

  /// Send the [fcall_ro](crate::interfaces::FunctionInterface::fcall_ro) command via the provided client.
  pub async fn fcall_ro<R, C, K, V>(&self, client: &C, keys: K, args: V) -> FredResult<R>
  where
    R: FromValue,
    C: FunctionInterface + Send + Sync,
    K: Into<MultipleKeys> + Send,
    V: TryInto<MultipleValues> + Send,
    V::Error: Into<Error> + Send,
  {
    client.fcall_ro(self.name.clone(), keys, args).await
  }
}

/// A helper struct for interacting with [libraries and functions](https://redis.io/docs/manual/programmability/functions-intro/).
///
/// ```rust no_run
/// # use fred::types::scripts::{FunctionFlag, Library};
/// let code = "#!lua name=mylib \n redis.register_function('myfunc', function(keys, args) return \
///             args[1] end)";
/// let library = Library::from_code(client, code).await?;
/// assert_eq!(library.name(), "mylib");
///
/// if let Some(func) = library.functions().get("myfunc") {
///   if func.flags().contains(&FunctionFlag::NoWrites) {
///     let _: () = func.fcall_ro(client, "key", "arg").await?;
///   } else {
///     let _: () = func.fcall(client, "key", "arg").await?;
///   }
/// }
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Library {
  name:      Str,
  functions: HashMap<Str, Function>,
}

impl fmt::Display for Library {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    write!(f, "{}", self.name)
  }
}

impl Hash for Library {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.name.hash(state);
  }
}

impl Ord for Library {
  fn cmp(&self, other: &Self) -> Ordering {
    self.name.cmp(&other.name)
  }
}

impl PartialOrd for Library {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl Library {
  /// Create a new `Library` with the provided code, loading it on all the servers and inspecting the contents via the [FUNCTION LIST](https://redis.io/commands/function-list/) command.
  ///
  /// This interface will load the library on the server.
  pub async fn from_code<S>(client: &Client, code: S) -> Result<Self, Error>
  where
    S: Into<Str>,
  {
    let code = code.into();
    let name: Str = client.function_load_cluster(true, code).await?;
    let functions = client
      .function_list::<Value, _>(Some(name.deref()), false)
      .await?
      .as_functions(&name)?;

    Ok(Library {
      name,
      functions: functions.into_iter().map(|f| (f.name.clone(), f)).collect(),
    })
  }

  /// Create a new `Library` with the associated name, inspecting the library contents via the [FUNCTION LIST](https://redis.io/commands/function-list/) command.
  ///
  /// This interface assumes the library is already loaded on the server.
  pub async fn from_name<S>(client: &Client, name: S) -> Result<Self, Error>
  where
    S: Into<Str>,
  {
    let name = name.into();
    let functions = client
      .function_list::<Value, _>(Some(name.deref()), false)
      .await?
      .as_functions(&name)?;

    Ok(Library {
      name,
      functions: functions.into_iter().map(|f| (f.name.clone(), f)).collect(),
    })
  }

  /// Read the name of the library.
  pub fn name(&self) -> &Str {
    &self.name
  }

  /// Read the functions contained within this library.
  pub fn functions(&self) -> &HashMap<Str, Function> {
    &self.functions
  }
}