reddb-io-server 1.1.2

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
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
/// Shell completion generation for the RedDB CLI.
///
/// Generates static completion scripts for bash, zsh, and fish shells,
/// plus a dynamic `complete_partial` function for runtime tab-completion.
///
/// Supported shell targets for completion script generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shell {
    Bash,
    Zsh,
    Fish,
}

/// Generate a full completion script for the given shell.
///
/// * `shell`        - Target shell.
/// * `domains`      - `(name, aliases)` for each domain.
/// * `global_flags` - `(long_name, optional_short)` for global flags.
pub fn generate_completion_script(
    shell: Shell,
    domains: &[(String, Vec<String>)],
    global_flags: &[(&str, Option<char>)],
) -> String {
    match shell {
        Shell::Bash => generate_bash(domains, global_flags),
        Shell::Zsh => generate_zsh(domains, global_flags),
        Shell::Fish => generate_fish(domains, global_flags),
    }
}

/// Complete partial input tokens at runtime.
///
/// * `tokens`  - Words typed so far.
/// * `domains` - `domain_name -> [(resource_name, [verb_names])]`.
///
/// Returns candidate completions for the next position.
pub fn complete_partial(
    tokens: &[&str],
    domains: &[(String, Vec<(String, Vec<String>)>)],
) -> Vec<String> {
    let domain_names: Vec<&str> = domains.iter().map(|(n, _)| n.as_str()).collect();

    match tokens.len() {
        // No input yet: return all domain names.
        0 => domain_names.iter().map(|s| s.to_string()).collect(),

        // Single partial token: filter matching domains.
        1 => {
            let prefix = tokens[0];
            domain_names
                .iter()
                .filter(|d| d.starts_with(prefix))
                .map(|d| d.to_string())
                .collect()
        }

        // Two tokens: domain given, complete the resource.
        2 => {
            let domain = tokens[0];
            let prefix = tokens[1];
            domains
                .iter()
                .find(|(name, _)| name == domain)
                .map(|(_, resources)| {
                    resources
                        .iter()
                        .map(|(r, _)| r.as_str())
                        .filter(|r| r.starts_with(prefix))
                        .map(|r| r.to_string())
                        .collect()
                })
                .unwrap_or_default()
        }

        // Three tokens: domain + resource given, complete the verb.
        3 => {
            let domain = tokens[0];
            let prefix = tokens[2];
            domains
                .iter()
                .find(|(name, _)| name == domain)
                .and_then(|(_, resources)| {
                    resources
                        .iter()
                        .find(|(r, _)| r == tokens[1])
                        .map(|(_, verbs)| {
                            verbs
                                .iter()
                                .filter(|v| v.starts_with(prefix))
                                .cloned()
                                .collect()
                        })
                })
                .unwrap_or_default()
        }

        // Four or more tokens: suggest flag names starting with --
        _ => {
            let last = *tokens.last().unwrap_or(&"");
            if let Some(prefix) = last.strip_prefix("--") {
                let flag_names = ["help", "json", "output", "verbose", "no-color", "version"];
                flag_names
                    .iter()
                    .filter(|f| f.starts_with(prefix))
                    .map(|f| format!("--{}", f))
                    .collect()
            } else if last.starts_with('-') && last.len() == 1 {
                vec![
                    "-h".to_string(),
                    "-j".to_string(),
                    "-o".to_string(),
                    "-v".to_string(),
                ]
            } else {
                Vec::new()
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Bash completion
// ---------------------------------------------------------------------------

fn generate_bash(
    domains: &[(String, Vec<String>)],
    global_flags: &[(&str, Option<char>)],
) -> String {
    let all_domains: Vec<&str> = domains.iter().map(|(n, _)| n.as_str()).collect();
    let domain_word_list = all_domains.join(" ");

    let flag_word_list: String = global_flags
        .iter()
        .map(|(long, short)| {
            let mut parts = vec![format!("--{}", long)];
            if let Some(ch) = short {
                parts.push(format!("-{}", ch));
            }
            parts.join(" ")
        })
        .collect::<Vec<_>>()
        .join(" ");

    format!(
        r#"_red_completions() {{
    local cur prev words cword
    _init_completion || return

    # Global flags at any position
    if [[ "$cur" == -* ]]; then
        COMPREPLY=($(compgen -W "{flags}" -- "$cur"))
        return
    fi

    case $cword in
        1)
            COMPREPLY=($(compgen -W "{domains} help version" -- "$cur"))
            ;;
        *)
            # Delegate deeper completions to the binary when available
            if command -v red &>/dev/null; then
                local completions
                completions=$(red --complete "${{words[@]:1}}" 2>/dev/null)
                if [[ -n "$completions" ]]; then
                    COMPREPLY=($(compgen -W "$completions" -- "$cur"))
                fi
            fi
            ;;
    esac
}}
complete -F _red_completions red
"#,
        flags = flag_word_list,
        domains = domain_word_list,
    )
}

// ---------------------------------------------------------------------------
// Zsh completion
// ---------------------------------------------------------------------------

fn generate_zsh(
    domains: &[(String, Vec<String>)],
    global_flags: &[(&str, Option<char>)],
) -> String {
    let mut out = String::with_capacity(1024);

    out.push_str("#compdef red\n\n");
    out.push_str("_red() {\n");
    out.push_str("    local -a global_flags\n");
    out.push_str("    global_flags=(\n");
    for (long, short) in global_flags {
        match short {
            Some(ch) => {
                out.push_str(&format!(
                    "        '(-{ch} --{long})'{{-{ch},--{long}}}'[{long}]'\n",
                    ch = ch,
                    long = long,
                ));
            }
            None => {
                out.push_str(&format!("        '--{long}[{long}]'\n", long = long));
            }
        }
    }
    out.push_str("    )\n\n");

    out.push_str("    _arguments -C \\\n");
    out.push_str("        $global_flags \\\n");
    out.push_str("        '1:command:->command' \\\n");
    out.push_str("        '*::arg:->args'\n\n");

    out.push_str("    case $state in\n");
    out.push_str("        command)\n");
    out.push_str("            local -a commands\n");
    out.push_str("            commands=(\n");
    for (name, _) in domains {
        out.push_str(&format!("                '{}'\n", name));
    }
    out.push_str("                'help'\n");
    out.push_str("                'version'\n");
    out.push_str("            )\n");
    out.push_str("            _describe 'command' commands\n");
    out.push_str("            ;;\n");

    out.push_str("        args)\n");
    out.push_str("            # Delegate to binary for deeper completions\n");
    out.push_str("            if (( $+commands[red] )); then\n");
    out.push_str("                local completions\n");
    out.push_str(
        "                completions=(${(f)\"$(red --complete ${words[2,-1]} 2>/dev/null)\"})\n",
    );
    out.push_str("                _describe 'subcommand' completions\n");
    out.push_str("            fi\n");
    out.push_str("            ;;\n");
    out.push_str("    esac\n");
    out.push_str("}\n\n");
    out.push_str("_red\n");
    out
}

// ---------------------------------------------------------------------------
// Fish completion
// ---------------------------------------------------------------------------

fn generate_fish(
    domains: &[(String, Vec<String>)],
    global_flags: &[(&str, Option<char>)],
) -> String {
    let mut out = String::with_capacity(1024);

    out.push_str("# Fish completions for red (reddb)\n\n");

    // Global flags
    for (long, short) in global_flags {
        match short {
            Some(ch) => {
                out.push_str(&format!(
                    "complete -c red -s {} -l {} -d '{}'\n",
                    ch, long, long
                ));
            }
            None => {
                out.push_str(&format!("complete -c red -l {} -d '{}'\n", long, long));
            }
        }
    }
    out.push('\n');

    // Domain completions: only when no subcommand has been given yet
    out.push_str("# Command completions\n");
    for (name, _) in domains {
        out.push_str(&format!(
            "complete -c red -n '__fish_use_subcommand' -a {} -d '{}'\n",
            name, name
        ));
    }
    out.push_str("complete -c red -n '__fish_use_subcommand' -a help -d 'Show help'\n");
    out.push_str("complete -c red -n '__fish_use_subcommand' -a version -d 'Show version'\n");
    out.push('\n');

    // Deeper completions via binary
    out.push_str("# Delegate deeper completions to the binary\n");
    out.push_str("complete -c red -n 'not __fish_use_subcommand' -a '(red --complete (commandline -cop) 2>/dev/null)'\n");

    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_domains() -> Vec<(String, Vec<String>)> {
        vec![
            ("server".to_string(), vec![]),
            ("query".to_string(), vec!["q".to_string()]),
            ("health".to_string(), vec![]),
        ]
    }

    fn sample_global_flags() -> Vec<(&'static str, Option<char>)> {
        vec![
            ("help", Some('h')),
            ("json", Some('j')),
            ("output", Some('o')),
            ("verbose", Some('v')),
            ("no-color", None),
        ]
    }

    fn sample_domain_tree() -> Vec<(String, Vec<(String, Vec<String>)>)> {
        vec![
            (
                "server".to_string(),
                vec![(
                    "grpc".to_string(),
                    vec!["start".to_string(), "stop".to_string()],
                )],
            ),
            (
                "query".to_string(),
                vec![
                    (
                        "sql".to_string(),
                        vec!["execute".to_string(), "explain".to_string()],
                    ),
                    ("graph".to_string(), vec!["traverse".to_string()]),
                ],
            ),
            (
                "health".to_string(),
                vec![(
                    "check".to_string(),
                    vec!["status".to_string(), "ping".to_string()],
                )],
            ),
        ]
    }

    // ----------------------------------------------------------------
    // complete_partial tests
    // ----------------------------------------------------------------

    #[test]
    fn test_complete_partial_domains() {
        let tree = sample_domain_tree();
        let result = complete_partial(&[], &tree);
        assert!(result.contains(&"server".to_string()));
        assert!(result.contains(&"query".to_string()));
        assert!(result.contains(&"health".to_string()));
        assert_eq!(result.len(), 3);
    }

    #[test]
    fn test_complete_partial_domains_filter() {
        let tree = sample_domain_tree();
        let result = complete_partial(&["s"], &tree);
        assert_eq!(result, vec!["server".to_string()]);
    }

    #[test]
    fn test_complete_partial_resources() {
        let tree = sample_domain_tree();
        let result = complete_partial(&["query", ""], &tree);
        assert!(result.contains(&"sql".to_string()));
        assert!(result.contains(&"graph".to_string()));
    }

    #[test]
    fn test_complete_partial_resources_filter() {
        let tree = sample_domain_tree();
        let result = complete_partial(&["query", "s"], &tree);
        assert_eq!(result, vec!["sql".to_string()]);
    }

    #[test]
    fn test_complete_partial_verbs() {
        let tree = sample_domain_tree();
        let result = complete_partial(&["server", "grpc", ""], &tree);
        assert!(result.contains(&"start".to_string()));
        assert!(result.contains(&"stop".to_string()));
    }

    #[test]
    fn test_complete_partial_verbs_filter() {
        let tree = sample_domain_tree();
        let result = complete_partial(&["server", "grpc", "sta"], &tree);
        assert_eq!(result, vec!["start".to_string()]);
    }

    #[test]
    fn test_complete_partial_flags() {
        let tree = sample_domain_tree();
        let result = complete_partial(&["server", "grpc", "start", "--"], &tree);
        // All global flags start with empty prefix after --
        assert!(result.contains(&"--help".to_string()));
        assert!(result.contains(&"--json".to_string()));
        assert!(result.contains(&"--verbose".to_string()));
    }

    #[test]
    fn test_complete_partial_unknown_domain() {
        let tree = sample_domain_tree();
        let result = complete_partial(&["unknown", ""], &tree);
        assert!(result.is_empty());
    }

    // ----------------------------------------------------------------
    // Bash completion script tests
    // ----------------------------------------------------------------

    #[test]
    fn test_bash_completion_script() {
        let script =
            generate_completion_script(Shell::Bash, &sample_domains(), &sample_global_flags());
        assert!(script.contains("_red_completions()"));
        assert!(script.contains("complete -F _red_completions red"));
        assert!(script.contains("server"));
        assert!(script.contains("query"));
        assert!(script.contains("health"));
        assert!(script.contains("--help"));
        assert!(script.contains("-h"));
        assert!(script.contains("help version"));
    }

    // ----------------------------------------------------------------
    // Zsh completion script tests
    // ----------------------------------------------------------------

    #[test]
    fn test_zsh_completion_script() {
        let script =
            generate_completion_script(Shell::Zsh, &sample_domains(), &sample_global_flags());
        assert!(script.contains("#compdef red"));
        assert!(script.contains("_red()"));
        assert!(script.contains("_arguments"));
        assert!(script.contains("server"));
        assert!(script.contains("query"));
        assert!(script.contains("health"));
        assert!(script.contains("--help"));
    }

    // ----------------------------------------------------------------
    // Fish completion script tests
    // ----------------------------------------------------------------

    #[test]
    fn test_fish_completion_script() {
        let script =
            generate_completion_script(Shell::Fish, &sample_domains(), &sample_global_flags());
        assert!(script.contains("complete -c red"));
        assert!(script.contains("-s h -l help"));
        assert!(script.contains("__fish_use_subcommand"));
        assert!(script.contains("server"));
        assert!(script.contains("query"));
    }
}