redis-module 2.0.8

A toolkit for building Redis modules in Rust
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
use crate::raw;
use crate::Context;
use crate::RedisError;
use crate::Status;
use bitflags::bitflags;
use libc::c_char;
use linkme::distributed_slice;
use redis_module_macros_internals::api;
use std::ffi::CString;
use std::iter;
use std::mem::MaybeUninit;
use std::os::raw::c_int;
use std::ptr;

const COMMNAD_INFO_VERSION: raw::RedisModuleCommandInfoVersion =
    raw::RedisModuleCommandInfoVersion {
        version: 1,
        sizeof_historyentry: std::mem::size_of::<raw::RedisModuleCommandHistoryEntry>(),
        sizeof_keyspec: std::mem::size_of::<raw::RedisModuleCommandKeySpec>(),
        sizeof_arg: std::mem::size_of::<raw::RedisModuleCommandArg>(),
    };

bitflags! {
    /// Key spec flags
    ///
    /// The first four refer to what the command actually does with the value or
    /// metadata of the key, and not necessarily the user data or how it affects
    /// it. Each key-spec must have exactly one of these. Any operation
    /// that's not distinctly deletion, overwrite or read-only would be marked as
    /// RW.
    ///
    /// The next four refer to user data inside the value of the key, not the
    /// metadata like LRU, type, cardinality. It refers to the logical operation
    /// on the user's data (actual input strings or TTL), being
    /// used/returned/copied/changed. It doesn't refer to modification or
    /// returning of metadata (like type, count, presence of data). ACCESS can be
    /// combined with one of the write operations INSERT, DELETE or UPDATE. Any
    /// write that's not an INSERT or a DELETE would be UPDATE.
    pub struct KeySpecFlags : u32 {
        /// Read-Only. Reads the value of the key, but doesn't necessarily return it.
        const READ_ONLY = raw::REDISMODULE_CMD_KEY_RO;

        /// Read-Write. Modifies the data stored in the value of the key or its metadata.
        const READ_WRITE = raw::REDISMODULE_CMD_KEY_RW;

        /// Overwrite. Overwrites the data stored in the value of the key.
        const OVERWRITE = raw::REDISMODULE_CMD_KEY_OW;

        /// Deletes the key.
        const REMOVE = raw::REDISMODULE_CMD_KEY_RM;

        /// Returns, copies or uses the user data from the value of the key.
        const ACCESS = raw::REDISMODULE_CMD_KEY_ACCESS;

        /// Updates data to the value, new value may depend on the old value.
        const UPDATE = raw::REDISMODULE_CMD_KEY_UPDATE;

        /// Adds data to the value with no chance of modification or deletion of existing data.
        const INSERT = raw::REDISMODULE_CMD_KEY_INSERT;

        /// Explicitly deletes some content from the value of the key.
        const DELETE = raw::REDISMODULE_CMD_KEY_DELETE;

        /// The key is not actually a key, but should be routed in cluster mode as if it was a key.
        const NOT_KEY = raw::REDISMODULE_CMD_KEY_NOT_KEY;

        /// The keyspec might not point out all the keys it should cover.
        const INCOMPLETE = raw::REDISMODULE_CMD_KEY_INCOMPLETE;

        /// Some keys might have different flags depending on arguments.
        const VARIABLE_FLAGS = raw::REDISMODULE_CMD_KEY_VARIABLE_FLAGS;
    }
}

impl TryFrom<&str> for KeySpecFlags {
    type Error = RedisError;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value.to_lowercase().as_str() {
            "read_only" => Ok(KeySpecFlags::READ_ONLY),
            "read_write" => Ok(KeySpecFlags::READ_WRITE),
            "overwrite" => Ok(KeySpecFlags::OVERWRITE),
            "remove" => Ok(KeySpecFlags::REMOVE),
            "access" => Ok(KeySpecFlags::ACCESS),
            "update" => Ok(KeySpecFlags::UPDATE),
            "insert" => Ok(KeySpecFlags::INSERT),
            "delete" => Ok(KeySpecFlags::DELETE),
            "not_key" => Ok(KeySpecFlags::NOT_KEY),
            "incomplete" => Ok(KeySpecFlags::INCOMPLETE),
            "variable_flags" => Ok(KeySpecFlags::VARIABLE_FLAGS),
            _ => Err(RedisError::String(format!(
                "Value {value} is not a valid key spec flag."
            ))),
        }
    }
}

impl From<Vec<KeySpecFlags>> for KeySpecFlags {
    fn from(value: Vec<KeySpecFlags>) -> Self {
        value
            .into_iter()
            .fold(KeySpecFlags::empty(), |a, item| a | item)
    }
}

/// A version of begin search spec that finds the index
/// indicating where to start search for keys based on
/// an index.
pub struct BeginSearchIndex {
    index: i32,
}

/// A version of begin search spec that finds the index
/// indicating where to start search for keys based on
/// a keyword.
pub struct BeginSearchKeyword {
    keyword: String,
    startfrom: i32,
}

/// This struct represents how Redis should start looking for keys.
/// There are 2 possible options:
/// 1. Index - start looking for keys from a given position.
/// 2. Keyword - Search for a specific keyward and start looking for keys from this keyword
pub enum BeginSearch {
    Index(BeginSearchIndex),
    Keyword(BeginSearchKeyword),
}

impl BeginSearch {
    pub fn new_index(index: i32) -> BeginSearch {
        BeginSearch::Index(BeginSearchIndex { index })
    }

    pub fn new_keyword(keyword: String, startfrom: i32) -> BeginSearch {
        BeginSearch::Keyword(BeginSearchKeyword { keyword, startfrom })
    }
}

impl From<&BeginSearch>
    for (
        raw::RedisModuleKeySpecBeginSearchType,
        raw::RedisModuleCommandKeySpec__bindgen_ty_1,
    )
{
    fn from(value: &BeginSearch) -> Self {
        match value {
            BeginSearch::Index(index_spec) => (
                raw::RedisModuleKeySpecBeginSearchType_REDISMODULE_KSPEC_BS_INDEX,
                raw::RedisModuleCommandKeySpec__bindgen_ty_1 {
                    index: raw::RedisModuleCommandKeySpec__bindgen_ty_1__bindgen_ty_1 {
                        pos: index_spec.index,
                    },
                },
            ),
            BeginSearch::Keyword(keyword_spec) => {
                let keyword = CString::new(keyword_spec.keyword.as_str())
                    .unwrap()
                    .into_raw();
                (
                    raw::RedisModuleKeySpecBeginSearchType_REDISMODULE_KSPEC_BS_KEYWORD,
                    raw::RedisModuleCommandKeySpec__bindgen_ty_1 {
                        keyword: raw::RedisModuleCommandKeySpec__bindgen_ty_1__bindgen_ty_2 {
                            keyword,
                            startfrom: keyword_spec.startfrom,
                        },
                    },
                )
            }
        }
    }
}

/// A version of find keys base on range.
/// * `last_key` - Index of the last key relative to the result of the
///   begin search step. Can be negative, in which case it's not
///   relative. -1 indicates the last argument, -2 one before the
///   last and so on.
/// * `steps` - How many arguments should we skip after finding a
///   key, in order to find the next one.
/// * `limit` - If `lastkey` is -1, we use `limit` to stop the search
///   by a factor. 0 and 1 mean no limit. 2 means 1/2 of the
///   remaining args, 3 means 1/3, and so on.
pub struct FindKeysRange {
    last_key: i32,
    steps: i32,
    limit: i32,
}

/// A version of find keys base on some argument representing the number of keys
/// * keynumidx - Index of the argument containing the number of
///   keys to come, relative to the result of the begin search step.
/// * firstkey - Index of the fist key relative to the result of the
///   begin search step. (Usually it's just after `keynumidx`, in
///   which case it should be set to `keynumidx + 1`.)
/// * keystep - How many arguments should we skip after finding a
///   key, in order to find the next one?
pub struct FindKeysNum {
    key_num_idx: i32,
    first_key: i32,
    key_step: i32,
}

/// After Redis finds the location from where it needs to start looking for keys,
/// Redis will start finding keys base on the information in this enum.
/// There are 2 possible options:
/// 1. Range - Required to specify additional 3 more values, `last_key`, `steps`, and `limit`.
/// 2. Keynum - Required to specify additional 3 more values, `keynumidx`, `firstkey`, and `keystep`.
///    Redis will consider the argument at `keynumidx` as an indicator
///    to the number of keys that will follow. Then it will start
///    from `firstkey` and jump each `keystep` to find the keys.
pub enum FindKeys {
    Range(FindKeysRange),
    Keynum(FindKeysNum),
}

impl FindKeys {
    pub fn new_range(last_key: i32, steps: i32, limit: i32) -> FindKeys {
        FindKeys::Range(FindKeysRange {
            last_key,
            steps,
            limit,
        })
    }

    pub fn new_keys_num(key_num_idx: i32, first_key: i32, key_step: i32) -> FindKeys {
        FindKeys::Keynum(FindKeysNum {
            key_num_idx,
            first_key,
            key_step,
        })
    }
}

impl From<&FindKeys>
    for (
        raw::RedisModuleKeySpecFindKeysType,
        raw::RedisModuleCommandKeySpec__bindgen_ty_2,
    )
{
    fn from(value: &FindKeys) -> Self {
        match value {
            FindKeys::Range(range_spec) => (
                raw::RedisModuleKeySpecFindKeysType_REDISMODULE_KSPEC_FK_RANGE,
                raw::RedisModuleCommandKeySpec__bindgen_ty_2 {
                    range: raw::RedisModuleCommandKeySpec__bindgen_ty_2__bindgen_ty_1 {
                        lastkey: range_spec.last_key,
                        keystep: range_spec.steps,
                        limit: range_spec.limit,
                    },
                },
            ),
            FindKeys::Keynum(keynum_spec) => (
                raw::RedisModuleKeySpecFindKeysType_REDISMODULE_KSPEC_FK_KEYNUM,
                raw::RedisModuleCommandKeySpec__bindgen_ty_2 {
                    keynum: raw::RedisModuleCommandKeySpec__bindgen_ty_2__bindgen_ty_2 {
                        keynumidx: keynum_spec.key_num_idx,
                        firstkey: keynum_spec.first_key,
                        keystep: keynum_spec.key_step,
                    },
                },
            ),
        }
    }
}

/// A struct that specify how to find keys from a command.
/// It is devided into 2 parts:
/// 1. begin_search - indicate how to find the first command argument from where to start searching for keys.
/// 2. find_keys - the methose to use in order to find the keys.
pub struct KeySpec {
    notes: Option<String>,
    flags: KeySpecFlags,
    begin_search: BeginSearch,
    find_keys: FindKeys,
}

impl KeySpec {
    pub fn new(
        notes: Option<String>,
        flags: KeySpecFlags,
        begin_search: BeginSearch,
        find_keys: FindKeys,
    ) -> KeySpec {
        KeySpec {
            notes,
            flags,
            begin_search,
            find_keys,
        }
    }
}

impl From<&KeySpec> for raw::RedisModuleCommandKeySpec {
    fn from(value: &KeySpec) -> Self {
        let (begin_search_type, bs) = (&value.begin_search).into();
        let (find_keys_type, fk) = (&value.find_keys).into();
        raw::RedisModuleCommandKeySpec {
            notes: value
                .notes
                .as_ref()
                .map(|v| CString::new(v.as_str()).unwrap().into_raw())
                .unwrap_or(ptr::null_mut()),
            flags: value.flags.bits() as u64,
            begin_search_type,
            bs,
            find_keys_type,
            fk,
        }
    }
}

type CommandCallback =
    extern "C" fn(*mut raw::RedisModuleCtx, *mut *mut raw::RedisModuleString, i32) -> i32;

bitflags! {
    pub struct CommandArgFlags : u32 {
        const NONE = raw::REDISMODULE_CMD_ARG_NONE;
        const OPTIONAL = raw::REDISMODULE_CMD_ARG_OPTIONAL;
        const MULTIPLE = raw::REDISMODULE_CMD_ARG_MULTIPLE;
        const MULTIPLE_TOKEN = raw::REDISMODULE_CMD_ARG_MULTIPLE_TOKEN;
    }
}

impl TryFrom<&str> for CommandArgFlags {
    type Error = RedisError;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value.to_lowercase().as_str() {
            "none" => Ok(CommandArgFlags::NONE),
            "optional" => Ok(CommandArgFlags::OPTIONAL),
            "multiple" => Ok(CommandArgFlags::MULTIPLE),
            "multiple_token" => Ok(CommandArgFlags::MULTIPLE_TOKEN),
            _ => Err(RedisError::String(format!(
                "Value {value} is not a valid command arg flag."
            ))),
        }
    }
}

impl From<Vec<CommandArgFlags>> for CommandArgFlags {
    fn from(value: Vec<CommandArgFlags>) -> Self {
        value
            .into_iter()
            .fold(CommandArgFlags::empty(), |a, item| a | item)
    }
}

pub struct RedisModuleCommandArg {
    name: String,
    type_: u32,
    key_spec_index: Option<u32>,
    token: Option<String>,
    summary: Option<String>,
    since: Option<String>,
    flags: CommandArgFlags,
    deprecated_since: Option<String>,
    subargs: Option<Vec<RedisModuleCommandArg>>,
    display_text: Option<String>,
}

impl RedisModuleCommandArg {
    #[expect(clippy::too_many_arguments)]
    pub fn new(
        name: String,
        type_: u32,
        key_spec_index: Option<u32>,
        token: Option<String>,
        summary: Option<String>,
        since: Option<String>,
        flags: CommandArgFlags,
        deprecated_since: Option<String>,
        subargs: Option<Vec<RedisModuleCommandArg>>,
        display_text: Option<String>,
    ) -> RedisModuleCommandArg {
        RedisModuleCommandArg {
            name,
            type_,
            key_spec_index,
            token,
            summary,
            since,
            flags,
            deprecated_since,
            subargs,
            display_text,
        }
    }
}

/// A struct represent a CommandInfo
pub struct CommandInfo {
    name: String,
    flags: Option<String>,
    enterprise_flags: Option<String>,
    summary: Option<String>,
    complexity: Option<String>,
    since: Option<String>,
    tips: Option<String>,
    arity: i64,
    key_spec: Vec<KeySpec>,
    callback: CommandCallback,
    args: Vec<RedisModuleCommandArg>,
    acl_categories: Option<Vec<String>>,
}

impl CommandInfo {
    #[expect(clippy::too_many_arguments)]
    pub fn new(
        name: String,
        flags: Option<String>,
        enterprise_flags: Option<String>,
        summary: Option<String>,
        complexity: Option<String>,
        since: Option<String>,
        tips: Option<String>,
        arity: i64,
        key_spec: Vec<KeySpec>,
        callback: CommandCallback,
        args: Vec<RedisModuleCommandArg>,
        acl_categories: Option<Vec<String>>,
    ) -> CommandInfo {
        CommandInfo {
            name,
            flags,
            enterprise_flags,
            summary,
            complexity,
            since,
            tips,
            arity,
            key_spec,
            callback,
            args,
            acl_categories,
        }
    }
}

#[distributed_slice()]
pub static COMMANDS_LIST: [fn() -> Result<CommandInfo, RedisError>] = [..];

pub fn get_redis_key_spec(key_spec: Vec<KeySpec>) -> Vec<raw::RedisModuleCommandKeySpec> {
    let mut redis_key_spec: Vec<raw::RedisModuleCommandKeySpec> =
        key_spec.into_iter().map(|v| (&v).into()).collect();
    let zerod: raw::RedisModuleCommandKeySpec = unsafe { MaybeUninit::zeroed().assume_init() };
    redis_key_spec.push(zerod);
    redis_key_spec
}

fn convert_command_arg_to_raw(arg: &RedisModuleCommandArg) -> raw::RedisModuleCommandArg {
    let name = CString::new(arg.name.as_str()).unwrap().into_raw();
    let token = arg
        .token
        .as_ref()
        .map(|v| CString::new(v.as_str()).unwrap().into_raw())
        .unwrap_or(ptr::null_mut());
    let summary = arg
        .summary
        .as_ref()
        .map(|v| CString::new(v.as_str()).unwrap().into_raw())
        .unwrap_or(ptr::null_mut());
    let since = arg
        .since
        .as_ref()
        .map(|v| CString::new(v.as_str()).unwrap().into_raw())
        .unwrap_or(ptr::null_mut());
    let deprecated_since = arg
        .deprecated_since
        .as_ref()
        .map(|v| CString::new(v.as_str()).unwrap().into_raw())
        .unwrap_or(ptr::null_mut());
    let display_text = arg
        .display_text
        .as_ref()
        .map(|v| CString::new(v.as_str()).unwrap().into_raw())
        .unwrap_or(ptr::null_mut());

    let subargs = arg.subargs.as_ref().map_or(ptr::null_mut(), |v| {
        Box::into_raw(
            v.iter()
                .map(convert_command_arg_to_raw)
                .chain(iter::once(unsafe { MaybeUninit::zeroed().assume_init() }))
                .collect::<Vec<_>>()
                .into_boxed_slice(),
        )
        .cast()
    });

    raw::RedisModuleCommandArg {
        name,
        type_: arg.type_,
        key_spec_index: arg.key_spec_index.unwrap_or(u32::MAX) as c_int,
        token,
        summary,
        since,
        flags: arg.flags.bits() as c_int,
        deprecated_since,
        subargs,
        display_text,
    }
}

pub fn get_redis_command_args(
    args: Vec<RedisModuleCommandArg>,
) -> Option<Vec<raw::RedisModuleCommandArg>> {
    if args.is_empty() {
        return None;
    }

    let raw_args: Vec<raw::RedisModuleCommandArg> = args
        .iter()
        .map(convert_command_arg_to_raw)
        .chain(iter::once(unsafe { MaybeUninit::zeroed().assume_init() }))
        .collect();

    Some(raw_args)
}

fn free_command_arg(arg: &raw::RedisModuleCommandArg) {
    if !arg.name.is_null() {
        drop(unsafe { CString::from_raw(arg.name as *mut c_char) });
    }
    if !arg.token.is_null() {
        drop(unsafe { CString::from_raw(arg.token as *mut c_char) });
    }
    if !arg.summary.is_null() {
        drop(unsafe { CString::from_raw(arg.summary as *mut c_char) });
    }
    if !arg.since.is_null() {
        drop(unsafe { CString::from_raw(arg.since as *mut c_char) });
    }
    if !arg.deprecated_since.is_null() {
        drop(unsafe { CString::from_raw(arg.deprecated_since as *mut c_char) });
    }
    if !arg.display_text.is_null() {
        drop(unsafe { CString::from_raw(arg.display_text as *mut c_char) });
    }

    if !arg.subargs.is_null() {
        let mut i = 0;
        loop {
            let subarg_ptr = unsafe { arg.subargs.offset(i) };
            if unsafe { (*subarg_ptr).name.is_null() } {
                break;
            }
            free_command_arg(unsafe { &*subarg_ptr });
            i += 1;
        }
        let len = i as usize + 1;
        drop(unsafe { Vec::from_raw_parts(arg.subargs, len, len) });
    }
}

api! {[
        RedisModule_CreateCommand,
        RedisModule_GetCommand,
        RedisModule_SetCommandInfo,
        RedisModule_SetCommandACLCategories,
    ],
    /// Register all the commands located on `COMMNADS_LIST`.
    fn register_commands_internal(ctx: &Context) -> Result<(), RedisError> {
        let is_enterprise = ctx.is_enterprise();
        COMMANDS_LIST.iter().try_for_each(|command| {
            let command_info = command()?;
            let name: CString = CString::new(command_info.name.as_str()).unwrap();
            let mut flags = command_info.flags.as_deref().unwrap_or("").to_owned();
            if is_enterprise {
                flags = format!("{flags} {}", command_info.enterprise_flags.as_deref().unwrap_or("")).trim().to_owned();
            }
            let flags = CString::new(flags).map_err(|e| RedisError::String(e.to_string()))?;

            if unsafe {
                RedisModule_CreateCommand(
                    ctx.ctx,
                    name.as_ptr(),
                    Some(command_info.callback),
                    flags.as_ptr(),
                    0,
                    0,
                    0,
                )
            } == raw::Status::Err as i32
            {
                return Err(RedisError::String(format!(
                    "Failed register command {}.",
                    command_info.name
                )));
            }

            // Register the extra data of the command
            let command = unsafe { RedisModule_GetCommand(ctx.ctx, name.as_ptr()) };

            if command.is_null() {
                return Err(RedisError::String(format!(
                    "Failed finding command {} after registration.",
                    command_info.name
                )));
            }

            if let Some(acl_categories) = command_info.acl_categories {
                let acl_categories = CString::new(acl_categories.join(" ")).map_err(|e| RedisError::String(e.to_string()))?;
                if unsafe { RedisModule_SetCommandACLCategories(command, acl_categories.as_ptr()) } == raw::Status::Err as i32 {
                    return Err(RedisError::String(format!(
                        "Failed setting ACL categories for command {}.",
                        command_info.name
                    )));
                }
            }

            let summary = command_info
                .summary
                .as_ref()
                .map(|v| Some(CString::new(v.as_str()).unwrap()))
                .unwrap_or(None);
            let complexity = command_info
                .complexity
                .as_ref()
                .map(|v| Some(CString::new(v.as_str()).unwrap()))
                .unwrap_or(None);
            let since = command_info
                .since
                .as_ref()
                .map(|v| Some(CString::new(v.as_str()).unwrap()))
                .unwrap_or(None);
            let tips = command_info
                .tips
                .as_ref()
                .map(|v| Some(CString::new(v.as_str()).unwrap()))
                .unwrap_or(None);

            let key_specs = get_redis_key_spec(command_info.key_spec);

            let args = get_redis_command_args(command_info.args);

            let mut redis_command_info = raw::RedisModuleCommandInfo {
                version: &COMMNAD_INFO_VERSION,
                summary: summary.as_ref().map(|v| v.as_ptr()).unwrap_or(ptr::null_mut()),
                complexity: complexity.as_ref().map(|v| v.as_ptr()).unwrap_or(ptr::null_mut()),
                since: since.as_ref().map(|v| v.as_ptr()).unwrap_or(ptr::null_mut()),
                history: ptr::null_mut(), // currently we will not support history
                tips: tips.as_ref().map(|v| v.as_ptr()).unwrap_or(ptr::null_mut()),
                arity: command_info.arity as c_int,
                key_specs: key_specs.as_ptr() as *mut raw::RedisModuleCommandKeySpec,
                args: args.as_ref().map(Vec::as_ptr).unwrap_or(ptr::null_mut()) as *mut raw::RedisModuleCommandArg,
            };

            if unsafe { RedisModule_SetCommandInfo(command, &mut redis_command_info as *mut raw::RedisModuleCommandInfo) } == raw::Status::Err as i32 {
                return Err(RedisError::String(format!(
                    "Failed setting info for command {}.",
                    command_info.name
                )));
            }

            // the only CString pointers which are not freed are those of the key_specs, lets free them here.
            key_specs.into_iter().for_each(|v|{
                if !v.notes.is_null() {
                    drop(unsafe{CString::from_raw(v.notes as *mut c_char)});
                }
                if v.begin_search_type == raw::RedisModuleKeySpecBeginSearchType_REDISMODULE_KSPEC_BS_KEYWORD {
                    let keyword = unsafe{v.bs.keyword.keyword};
                    if !keyword.is_null() {
                        drop(unsafe{CString::from_raw(v.bs.keyword.keyword as *mut c_char)});
                    }
                }
            });

            args.unwrap_or_default().iter().for_each(free_command_arg);

            Ok(())
        })
    }
}

#[cfg(all(
    any(
        feature = "min-redis-compatibility-version-8-0",
        feature = "min-redis-compatibility-version-7-4",
        feature = "min-redis-compatibility-version-7-2",
        feature = "min-redis-compatibility-version-7-0"
    ),
    not(any(
        feature = "min-redis-compatibility-version-6-2",
        feature = "min-redis-compatibility-version-6-0"
    ))
))]
pub fn register_commands(ctx: &Context) -> Status {
    register_commands_internal(ctx).map_or_else(
        |e| {
            ctx.log_warning(&e.to_string());
            Status::Err
        },
        |_| Status::Ok,
    )
}

#[cfg(all(
    any(
        feature = "min-redis-compatibility-version-6-2",
        feature = "min-redis-compatibility-version-6-0"
    ),
    not(any(
        feature = "min-redis-compatibility-version-8-0",
        feature = "min-redis-compatibility-version-7-4",
        feature = "min-redis-compatibility-version-7-2",
        feature = "min-redis-compatibility-version-7-0"
    ))
))]
pub fn register_commands(ctx: &Context) -> Status {
    register_commands_internal(ctx).map_or_else(
        |e| {
            /* Make sure new command registration API is not been used. */
            if COMMANDS_LIST.is_empty() {
                return Status::Ok;
            }
            ctx.log_warning(&e.to_string());
            Status::Err
        },
        |v| {
            v.map_or_else(
                |e| {
                    ctx.log_warning(&e.to_string());
                    Status::Err
                },
                |_| Status::Ok,
            )
        },
    )
}