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
450
451
452
453
454
455
456
457
458
459
460
461
462
use super::*;
#[cfg(feature = "sha-1")]
use crate::util::sha1_hash;
use crate::{
  error::*,
  modules::inner::ClientInner,
  protocol::{
    command::{Command, CommandKind},
    hashers::ClusterHash,
    responders::ResponseKind,
    utils as protocol_utils,
  },
  runtime::{oneshot_channel, RefCount},
  types::{
    scripts::{FnPolicy, ScriptDebugFlag},
    *,
  },
  utils,
};
use bytes::Bytes;
use bytes_utils::Str;
use redis_protocol::resp3::types::BytesFrame as Resp3Frame;
use std::{convert::TryInto, str};

/// Check that all the keys in an EVAL* command belong to the same server, returning a key slot that maps to that
/// server.
pub fn check_key_slot(inner: &RefCount<ClientInner>, keys: &[Key]) -> Result<Option<u16>, Error> {
  if inner.config.server.is_clustered() {
    inner.with_cluster_state(|state| {
      let (mut cmd_server, mut cmd_slot) = (None, None);
      for key in keys.iter() {
        let key_slot = redis_protocol::redis_keyslot(key.as_bytes());

        if let Some(server) = state.get_server(key_slot) {
          if let Some(ref cmd_server) = cmd_server {
            if cmd_server != server {
              return Err(Error::new(
                ErrorKind::Cluster,
                "All keys must belong to the same cluster node.",
              ));
            }
          } else {
            cmd_server = Some(server.clone());
            cmd_slot = Some(key_slot);
          }
        } else {
          return Err(Error::new(
            ErrorKind::Cluster,
            format!("Missing server for hash slot {}", key_slot),
          ));
        }
      }

      Ok(cmd_slot)
    })
  } else {
    Ok(None)
  }
}

pub async fn script_load<C: ClientLike>(client: &C, script: Str) -> Result<Value, Error> {
  one_arg_value_cmd(client, CommandKind::ScriptLoad, script.into()).await
}

#[cfg(feature = "sha-1")]
pub async fn script_load_cluster<C: ClientLike>(client: &C, script: Str) -> Result<Value, Error> {
  if !client.inner().config.server.is_clustered() {
    return script_load(client, script).await;
  }
  let hash = sha1_hash(&script);

  let (tx, rx) = oneshot_channel();
  let response = ResponseKind::Respond(Some(tx));
  let mut command: Command = (CommandKind::_ScriptLoadCluster, vec![script.into()], response).into();

  let timeout_dur = utils::prepare_command(client, &mut command);
  client.send_command(command)?;
  let _ = utils::timeout(rx, timeout_dur).await??;
  Ok(hash.into())
}

ok_cmd!(script_kill, ScriptKill);

pub async fn script_kill_cluster<C: ClientLike>(client: &C) -> Result<(), Error> {
  if !client.inner().config.server.is_clustered() {
    return script_kill(client).await;
  }

  let (tx, rx) = oneshot_channel();
  let response = ResponseKind::Respond(Some(tx));
  let mut command: Command = (CommandKind::_ScriptKillCluster, vec![], response).into();

  let timeout_dur = utils::prepare_command(client, &mut command);
  client.send_command(command)?;
  let _ = utils::timeout(rx, timeout_dur).await??;
  Ok(())
}

pub async fn script_flush<C: ClientLike>(client: &C, r#async: bool) -> Result<(), Error> {
  let frame = utils::request_response(client, move || {
    let arg = static_val!(if r#async { ASYNC } else { SYNC });
    Ok((CommandKind::ScriptFlush, vec![arg]))
  })
  .await?;

  let response = protocol_utils::frame_to_results(frame)?;
  protocol_utils::expect_ok(&response)
}

pub async fn script_flush_cluster<C: ClientLike>(client: &C, r#async: bool) -> Result<(), Error> {
  if !client.inner().config.server.is_clustered() {
    return script_flush(client, r#async).await;
  }

  let (tx, rx) = oneshot_channel();
  let arg = static_val!(if r#async { ASYNC } else { SYNC });
  let response = ResponseKind::Respond(Some(tx));
  let mut command: Command = (CommandKind::_ScriptFlushCluster, vec![arg], response).into();

  let timeout_dur = utils::prepare_command(client, &mut command);
  client.send_command(command)?;

  let _ = utils::timeout(rx, timeout_dur).await??;
  Ok(())
}

pub async fn script_exists<C: ClientLike>(client: &C, hashes: MultipleStrings) -> Result<Value, Error> {
  let frame = utils::request_response(client, move || {
    let args = hashes.inner().into_iter().map(|s| s.into()).collect();
    Ok((CommandKind::ScriptExists, args))
  })
  .await?;

  protocol_utils::frame_to_results(frame)
}

pub async fn script_debug<C: ClientLike>(client: &C, flag: ScriptDebugFlag) -> Result<(), Error> {
  let frame = utils::request_response(client, move || {
    Ok((CommandKind::ScriptDebug, vec![flag.to_str().into()]))
  })
  .await?;

  let response = protocol_utils::frame_to_results(frame)?;
  protocol_utils::expect_ok(&response)
}

pub async fn evalsha<C: ClientLike>(
  client: &C,
  hash: Str,
  keys: MultipleKeys,
  cmd_args: MultipleValues,
) -> Result<Value, Error> {
  let keys = keys.inner();
  let custom_key_slot = check_key_slot(client.inner(), &keys)?;

  let frame = utils::request_response(client, move || {
    let cmd_args = cmd_args.into_multiple_values();
    let mut args = Vec::with_capacity(2 + keys.len() + cmd_args.len());
    args.push(hash.into());
    args.push(keys.len().try_into()?);

    for key in keys.into_iter() {
      args.push(key.into());
    }
    for arg in cmd_args.into_iter() {
      args.push(arg);
    }

    let mut command: Command = (CommandKind::EvalSha, args).into();
    command.hasher = custom_key_slot.map(ClusterHash::Custom).unwrap_or(ClusterHash::Random);
    command.can_pipeline = false;
    Ok(command)
  })
  .await?;

  protocol_utils::frame_to_results(frame)
}

pub async fn eval<C: ClientLike>(
  client: &C,
  script: Str,
  keys: MultipleKeys,
  cmd_args: MultipleValues,
) -> Result<Value, Error> {
  let keys = keys.inner();
  let custom_key_slot = check_key_slot(client.inner(), &keys)?;

  let frame = utils::request_response(client, move || {
    let cmd_args = cmd_args.into_multiple_values();
    let mut args = Vec::with_capacity(2 + keys.len() + cmd_args.len());
    args.push(script.into());
    args.push(keys.len().try_into()?);

    for key in keys.into_iter() {
      args.push(key.into());
    }
    for arg in cmd_args.into_iter() {
      args.push(arg);
    }

    let mut command: Command = (CommandKind::Eval, args).into();
    command.hasher = custom_key_slot.map(ClusterHash::Custom).unwrap_or(ClusterHash::Random);
    command.can_pipeline = false;
    Ok(command)
  })
  .await?;

  protocol_utils::frame_to_results(frame)
}

pub async fn fcall<C: ClientLike>(
  client: &C,
  func: Str,
  keys: MultipleKeys,
  args: MultipleValues,
) -> Result<Value, Error> {
  let frame = utils::request_response(client, move || {
    let args = args.into_multiple_values();
    let mut arguments = Vec::with_capacity(keys.len() + args.len() + 2);
    let mut custom_key_slot = None;

    arguments.push(func.into());
    arguments.push(keys.len().try_into()?);

    for key in keys.inner().into_iter() {
      custom_key_slot = Some(key.cluster_hash());
      arguments.push(key.into());
    }
    for arg in args.into_iter() {
      arguments.push(arg);
    }

    let mut command: Command = (CommandKind::Fcall, arguments).into();
    command.hasher = custom_key_slot.map(ClusterHash::Custom).unwrap_or(ClusterHash::Random);
    command.can_pipeline = false;
    Ok(command)
  })
  .await?;

  protocol_utils::frame_to_results(frame)
}

pub async fn fcall_ro<C: ClientLike>(
  client: &C,
  func: Str,
  keys: MultipleKeys,
  args: MultipleValues,
) -> Result<Value, Error> {
  let frame = utils::request_response(client, move || {
    let args = args.into_multiple_values();
    let mut arguments = Vec::with_capacity(keys.len() + args.len() + 2);
    let mut custom_key_slot = None;

    arguments.push(func.into());
    arguments.push(keys.len().try_into()?);

    for key in keys.inner().into_iter() {
      custom_key_slot = Some(key.cluster_hash());
      arguments.push(key.into());
    }
    for arg in args.into_iter() {
      arguments.push(arg);
    }

    let mut command: Command = (CommandKind::FcallRO, arguments).into();
    command.hasher = custom_key_slot.map(ClusterHash::Custom).unwrap_or(ClusterHash::Random);
    command.can_pipeline = false;
    Ok(command)
  })
  .await?;

  protocol_utils::frame_to_results(frame)
}

pub async fn function_delete<C: ClientLike>(client: &C, library_name: Str) -> Result<Value, Error> {
  let frame = utils::request_response(client, move || {
    Ok((CommandKind::FunctionDelete, vec![library_name.into()]))
  })
  .await?;

  protocol_utils::frame_to_results(frame)
}

pub async fn function_delete_cluster<C: ClientLike>(client: &C, library_name: Str) -> Result<(), Error> {
  if !client.inner().config.server.is_clustered() {
    return function_delete(client, library_name).await.map(|_| ());
  }

  let (tx, rx) = oneshot_channel();
  let args: Vec<Value> = vec![library_name.into()];

  let response = ResponseKind::Respond(Some(tx));
  let mut command: Command = (CommandKind::_FunctionDeleteCluster, args, response).into();
  let timeout_dur = utils::prepare_command(client, &mut command);
  client.send_command(command)?;

  let _ = utils::timeout(rx, timeout_dur).await??;
  Ok(())
}

pub async fn function_flush<C: ClientLike>(client: &C, r#async: bool) -> Result<Value, Error> {
  let frame = utils::request_response(client, move || {
    let args = if r#async {
      vec![static_val!(ASYNC)]
    } else {
      vec![static_val!(SYNC)]
    };

    Ok((CommandKind::FunctionFlush, args))
  })
  .await?;

  protocol_utils::frame_to_results(frame)
}

pub async fn function_flush_cluster<C: ClientLike>(client: &C, r#async: bool) -> Result<(), Error> {
  if !client.inner().config.server.is_clustered() {
    return function_flush(client, r#async).await.map(|_| ());
  }

  let (tx, rx) = oneshot_channel();
  let args = if r#async {
    vec![static_val!(ASYNC)]
  } else {
    vec![static_val!(SYNC)]
  };

  let response = ResponseKind::Respond(Some(tx));
  let command: Command = (CommandKind::_FunctionFlushCluster, args, response).into();
  client.send_command(command)?;

  let _ = rx.await??;
  Ok(())
}

pub async fn function_kill<C: ClientLike>(client: &C) -> Result<Value, Error> {
  let inner = client.inner();
  let command = Command::new(CommandKind::FunctionKill, vec![]);

  let frame = utils::backchannel_request_response(inner, command, true).await?;
  protocol_utils::frame_to_results(frame)
}

pub async fn function_list<C: ClientLike>(
  client: &C,
  library_name: Option<Str>,
  withcode: bool,
) -> Result<Value, Error> {
  let frame = utils::request_response(client, move || {
    let mut args = Vec::with_capacity(3);

    if let Some(library_name) = library_name {
      args.push(static_val!(LIBRARYNAME));
      args.push(library_name.into());
    }
    if withcode {
      args.push(static_val!(WITHCODE));
    }

    Ok((CommandKind::FunctionList, args))
  })
  .await?;

  protocol_utils::frame_to_results(frame)
}

pub async fn function_load<C: ClientLike>(client: &C, replace: bool, code: Str) -> Result<Value, Error> {
  let frame = utils::request_response(client, move || {
    let mut args = Vec::with_capacity(2);
    if replace {
      args.push(static_val!(REPLACE));
    }
    args.push(code.into());

    Ok((CommandKind::FunctionLoad, args))
  })
  .await?;

  protocol_utils::frame_to_results(frame)
}

pub async fn function_load_cluster<C: ClientLike>(client: &C, replace: bool, code: Str) -> Result<Value, Error> {
  if !client.inner().config.server.is_clustered() {
    return function_load(client, replace, code).await;
  }

  let (tx, rx) = oneshot_channel();
  let mut args: Vec<Value> = Vec::with_capacity(2);
  if replace {
    args.push(static_val!(REPLACE));
  }
  args.push(code.into());

  let response = ResponseKind::Respond(Some(tx));
  let mut command: Command = (CommandKind::_FunctionLoadCluster, args, response).into();
  let timeout_dur = utils::prepare_command(client, &mut command);
  client.send_command(command)?;

  // each value in the response array is the response from a different primary node
  match utils::timeout(rx, timeout_dur).await?? {
    Resp3Frame::Array { mut data, .. } => {
      if let Some(frame) = data.pop() {
        protocol_utils::frame_to_results(frame)
      } else {
        Err(Error::new(ErrorKind::Protocol, "Missing library name response frame."))
      }
    },
    Resp3Frame::SimpleError { data, .. } => Err(protocol_utils::pretty_error(&data)),
    Resp3Frame::BlobError { data, .. } => {
      let parsed = str::from_utf8(&data)?;
      Err(protocol_utils::pretty_error(parsed))
    },
    _ => Err(Error::new(ErrorKind::Protocol, "Invalid response type.")),
  }
}

pub async fn function_restore<C: ClientLike>(
  client: &C,
  serialized: Bytes,
  policy: FnPolicy,
) -> Result<Value, Error> {
  let frame = utils::request_response(client, move || {
    let mut args = Vec::with_capacity(2);
    args.push(serialized.into());
    args.push(policy.to_str().into());

    Ok((CommandKind::FunctionRestore, args))
  })
  .await?;

  protocol_utils::frame_to_results(frame)
}

pub async fn function_restore_cluster<C: ClientLike>(
  client: &C,
  serialized: Bytes,
  policy: FnPolicy,
) -> Result<(), Error> {
  if !client.inner().config.server.is_clustered() {
    return function_restore(client, serialized, policy).await.map(|_| ());
  }

  let (tx, rx) = oneshot_channel();
  let args: Vec<Value> = vec![serialized.into(), policy.to_str().into()];

  let response = ResponseKind::Respond(Some(tx));
  let mut command: Command = (CommandKind::_FunctionRestoreCluster, args, response).into();
  let timeout_dur = utils::prepare_command(client, &mut command);
  client.send_command(command)?;
  let _ = utils::timeout(rx, timeout_dur).await??;
  Ok(())
}

pub async fn function_stats<C: ClientLike>(client: &C) -> Result<Value, Error> {
  let inner = client.inner();
  let command = Command::new(CommandKind::FunctionStats, vec![]);

  let frame = utils::backchannel_request_response(inner, command, true).await?;
  protocol_utils::frame_to_results(frame)
}

value_cmd!(function_dump, FunctionDump);