mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
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
//! The six commands that read and write the stored settings.
//!
//! Every setting the product has is written and read here. Nothing in this file
//! reads the process environment, because a value that changes with the
//! surrounding shell is not a stored setting.

use crate::cli::config::ConfigCommand;
use crate::config::{doctor, keys, paths, secret, store, Config, Fallback, KeySpec, Resolved};
use crate::error::{Failure, Result};
use crate::output::Envelope;
use serde_json::{json, Value};
use std::path::Path;

/// Serves one configuration command.
///
/// # Errors
///
/// Returns a configuration failure when the location cannot be determined, the
/// settings file cannot be read or written, or the named setting does not
/// exist; and an absence failure when a setting is read but was never given a
/// value by any layer.
pub fn execute(
    command: &ConfigCommand,
    config_dir: Option<&Path>,
    dry_run: bool,
) -> Result<Envelope> {
    match command {
        ConfigCommand::Set(args) => set(
            config_dir,
            required(args.key.as_deref(), "key", "config set output.format json")?,
            required(
                args.value.as_deref(),
                "value",
                "config set output.format json",
            )?,
            dry_run,
        ),
        ConfigCommand::Get(args) => get(
            config_dir,
            required(args.key.as_deref(), "key", "config get output.format")?,
        ),
        ConfigCommand::List(args) => list(config_dir, args.stored_only),
        ConfigCommand::Path => path(config_dir),
        ConfigCommand::Unset(args) => unset(
            config_dir,
            required(args.key.as_deref(), "key", "config unset output.format")?,
            dry_run,
        ),
        ConfigCommand::Doctor => diagnose(config_dir),
    }
}

/// Demands an argument the contract layer is allowed to leave out.
///
/// # Errors
///
/// Returns a usage failure naming the missing argument and showing the form
/// that carries it.
fn required<'a>(given: Option<&'a str>, what: &str, example: &str) -> Result<&'a str> {
    given.ok_or_else(|| {
        Failure::usage(
            "config.argument_missing",
            format!("this command needs a {what} to work on"),
        )
        .with_detail("detail", what)
        .with_hint(format!("as in `{example}`"))
    })
}

/// Writes one setting, after checking it against its domain.
///
/// The check happens before the write, so a rejected value never reaches the
/// file and a caller never has to undo a bad store.
fn set(config_dir: Option<&Path>, name: &str, raw: &str, dry_run: bool) -> Result<Envelope> {
    let entry = keys::spec(name).ok_or_else(|| keys::unknown_key(name))?;
    let value = keys::validate(entry.name, raw)?;

    let file = paths::config_file(config_dir)?;
    // The check above has already run, so a simulation reports the value that
    // WOULD be stored rather than the text that was typed: a caller asking what
    // this would do learns both that it is admissible and what it becomes.
    if !dry_run {
        store::store(&file, entry.name, raw)?;
    }

    Ok(Envelope::new(
        "config set",
        json!({
            "key": entry.name,
            "value": rendered(entry, Some(&value)),
            "path": file.display().to_string(),
            "simulated": dry_run,
        }),
    ))
}

/// Reads the value in force for one setting, with the layer that decided it.
fn get(config_dir: Option<&Path>, name: &str) -> Result<Envelope> {
    let entry = keys::spec(name).ok_or_else(|| keys::unknown_key(name))?;
    let config = Config::load(config_dir)?;
    let resolved = config.resolve(entry.name)?;

    if resolved.value.is_none() {
        return Err(no_value(entry));
    }

    Ok(Envelope::new("config get", row(entry, &resolved)))
}

/// Lists every setting with the value in force and its origin.
///
/// `stored_only` narrows the list to what was actually written into the file,
/// which is what a caller reviewing their own choices wants to see.
fn list(config_dir: Option<&Path>, stored_only: bool) -> Result<Envelope> {
    let config = Config::load(config_dir)?;
    let mut rows = Vec::new();

    for (entry, resolved) in config.resolve_all() {
        if stored_only && !config.is_stored(entry.name) {
            continue;
        }
        // A value the file can no longer read is shown as a row carrying its
        // problem, so listing never hides a broken file behind a failure.
        match resolved {
            Ok(resolved) => rows.push(row(entry, &resolved)),
            Err(failure) => rows.push(json!({
                "key": entry.name,
                "about": entry.about,
                "problem": failure.message(),
            })),
        }
    }

    Ok(Envelope::new("config list", json!({ "rows": rows })))
}

/// Says where the settings live and whether anything is there yet.
fn path(config_dir: Option<&Path>) -> Result<Envelope> {
    let file = paths::config_file(config_dir)?;
    let directory = paths::config_dir(config_dir)?;
    Ok(Envelope::new(
        "config path",
        json!({
            "path": file.display().to_string(),
            "directory": directory.display().to_string(),
            "exists": file.exists(),
        }),
    ))
}

/// Removes one setting, so it falls back to the layer beneath.
fn unset(config_dir: Option<&Path>, name: &str, dry_run: bool) -> Result<Envelope> {
    let entry = keys::spec(name).ok_or_else(|| keys::unknown_key(name))?;
    let file = paths::config_file(config_dir)?;
    // `removed` answers whether the key was there to remove, which a simulation
    // has to report without removing it. Reading the store rather than writing
    // it is what makes the two answers agree.
    let removed = if dry_run {
        Config::load(config_dir)?.is_stored(entry.name)
    } else {
        store::remove(&file, entry.name)?
    };

    let fallback = entry.default_value()?;
    Ok(Envelope::new(
        "config unset",
        json!({
            "key": entry.name,
            "removed": removed,
            "value": rendered(entry, fallback.as_ref()),
            "origin": crate::config::Origin::Default.as_str(),
            "simulated": dry_run,
        }),
    ))
}

/// Reports everything that is wrong with the stored settings.
fn diagnose(config_dir: Option<&Path>) -> Result<Envelope> {
    let report = doctor::run(config_dir)?;
    let findings = serde_json::to_value(&report.findings).map_err(|error| {
        Failure::config(
            "config.report_not_serialisable",
            "the diagnosis could not be written out",
        )
        .with_cause(error.to_string())
    })?;

    Ok(Envelope::new(
        "config doctor",
        json!({
            "path": report.file,
            "exists": report.file_exists,
            "clean": report.is_clean(),
            "rows": findings,
        }),
    ))
}

/// One setting as it appears on the wire.
fn row(entry: &KeySpec, resolved: &Resolved) -> Value {
    json!({
        "key": entry.name,
        "value": rendered(entry, resolved.value.as_ref()),
        "origin": resolved.origin.as_str(),
        "domain": entry.domain.described(),
        "about": entry.about,
    })
}

/// The value as it appears on the wire.
///
/// A credential is never shown, whichever layer decided it.
fn rendered(entry: &KeySpec, value: Option<&keys::Value>) -> Value {
    let Some(value) = value else {
        return Value::Null;
    };
    if is_credential(entry.name) {
        return Value::from(secret::redact(&value.to_string()));
    }
    Value::from(value)
}

/// Whether a setting holds a credential rather than an ordinary value.
fn is_credential(name: &str) -> bool {
    name.starts_with("secret.") && name != "secret.storage_mode"
}

/// The failure for a setting no layer gave a value to.
fn no_value(entry: &KeySpec) -> Failure {
    let (decided, decided_by) = match entry.fallback {
        Fallback::Server => (
            "server",
            "the server decides this one, so it has no stored value",
        ),
        Fallback::Host => (
            "host",
            "the host decides this one, so it has no stored value",
        ),
        Fallback::Builtin(_) | Fallback::Absent => ("unstored", "no value was ever stored for it"),
    };
    Failure::absence("config.no_value", format!("`{}`", entry.name))
        .with_detail("detail", entry.name)
        .with_detail("decided", decided)
        .with_detail("setting", entry.name)
        .with_hint(format!(
            "{decided_by}; use `config set {}` to give it one",
            entry.name
        ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::config::{KeyArgs, ListArgs, SetArgs};

    fn scratch() -> tempfile::TempDir {
        tempfile::tempdir().expect("scratch directory")
    }

    fn run(dir: &tempfile::TempDir, command: &ConfigCommand) -> Result<Envelope> {
        execute(command, Some(dir.path()), false)
    }

    /// A simulated write reports what it would store and stores nothing.
    ///
    /// `--dry-run` is a global flag, so the argument layer accepted it on this
    /// command from the first day and nothing underneath ever read it. The flag
    /// was not inert in an obvious way: it was accepted, ignored, and the write
    /// happened anyway, which is the one outcome a caller asking for a
    /// simulation cannot recover from.
    #[test]
    fn a_simulated_write_changes_nothing_on_disk() {
        let dir = scratch();
        let asked = setting("output.format", "tsv");

        let answered = execute(&asked, Some(dir.path()), true).expect("the value is admissible");
        assert_eq!(answered.data["simulated"], true);
        assert_eq!(answered.data["value"], "tsv");

        let stored = Config::load(Some(dir.path())).expect("the location loads");
        assert!(
            !stored.is_stored("output.format"),
            "the simulation wrote the value it was only asked to describe"
        );
    }

    /// A simulated write still refuses a value outside the key's domain.
    ///
    /// Describing an impossible change as though it were possible would make
    /// the simulation useless for the one thing it is for.
    #[test]
    fn a_simulated_write_still_checks_the_value() {
        let dir = scratch();
        let asked = setting("output.format", "yaml");

        execute(&asked, Some(dir.path()), true).expect_err("no such shape is published");
    }

    /// A simulated removal reports whether the key was there and leaves it.
    #[test]
    fn a_simulated_removal_leaves_the_value_where_it_was() {
        let dir = scratch();
        run(&dir, &setting("output.format", "tsv")).expect("stores");

        let asked = ConfigCommand::Unset(KeyArgs {
            key: Some("output.format".to_owned()),
        });
        let answered = execute(&asked, Some(dir.path()), true).expect("the key exists");
        assert_eq!(answered.data["simulated"], true);
        assert_eq!(
            answered.data["removed"], true,
            "the simulation must still say the key was there to remove"
        );

        let stored = Config::load(Some(dir.path())).expect("the location loads");
        assert!(
            stored.is_stored("output.format"),
            "the simulation removed the value it was only asked to describe"
        );
    }

    fn setting(key: &str, value: &str) -> ConfigCommand {
        ConfigCommand::Set(SetArgs {
            key: Some(key.to_owned()),
            value: Some(value.to_owned()),
        })
    }

    fn reading(key: &str) -> ConfigCommand {
        ConfigCommand::Get(KeyArgs {
            key: Some(key.to_owned()),
        })
    }

    #[test]
    fn a_written_setting_is_read_back_with_its_origin() {
        let dir = scratch();
        run(&dir, &setting("output.format", "ndjson")).expect("writes");
        let envelope = run(&dir, &reading("output.format")).expect("reads");
        assert_eq!(envelope.data["value"], "ndjson");
        assert_eq!(envelope.data["origin"], "stored");
    }

    #[test]
    fn nothing_written_means_the_builtin_value_is_reported() {
        let dir = scratch();
        let envelope = run(&dir, &reading("limits.retries")).expect("reads");
        assert_eq!(envelope.data["value"], 2);
        assert_eq!(envelope.data["origin"], "default");
    }

    #[test]
    fn a_value_outside_the_domain_never_reaches_the_file() {
        let dir = scratch();
        let failure = run(&dir, &setting("output.format", "yaml")).expect_err("must refuse");
        assert_eq!(failure.code(), "config.value_outside_domain");
        let file = paths::config_file(Some(dir.path())).expect("location");
        assert!(!file.exists(), "a refused value created the file anyway");
    }

    #[test]
    fn an_unknown_setting_is_an_absence_of_that_name() {
        let dir = scratch();
        let failure = run(&dir, &reading("output.nonsense")).expect_err("must refuse");
        assert_eq!(failure.code(), "config.unknown_key");
    }

    #[test]
    fn the_list_uses_the_payload_key_the_output_pipeline_looks_for() {
        let dir = scratch();
        let envelope =
            run(&dir, &ConfigCommand::List(ListArgs { stored_only: false })).expect("lists");
        assert_eq!(envelope.payload_array_key(), Some("rows"));
        assert_eq!(
            envelope.data["rows"].as_array().map(Vec::len),
            Some(keys::all().len())
        );
    }

    #[test]
    fn listing_only_what_was_written_leaves_the_rest_out() {
        let dir = scratch();
        run(&dir, &setting("log.to_file", "true")).expect("writes");
        let envelope =
            run(&dir, &ConfigCommand::List(ListArgs { stored_only: true })).expect("lists");
        let rows = envelope.data["rows"].as_array().expect("array");
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["key"], "log.to_file");
        assert_eq!(rows[0]["origin"], "stored");
    }

    #[test]
    fn removing_a_setting_returns_it_to_the_builtin_value() {
        let dir = scratch();
        run(&dir, &setting("limits.retries", "9")).expect("writes");
        let envelope = run(
            &dir,
            &ConfigCommand::Unset(KeyArgs {
                key: Some("limits.retries".to_owned()),
            }),
        )
        .expect("removes");
        assert_eq!(envelope.data["removed"], true);
        assert_eq!(envelope.data["value"], 2);

        let after = run(&dir, &reading("limits.retries")).expect("reads");
        assert_eq!(after.data["origin"], "default");
    }

    #[test]
    fn removing_something_never_written_says_so_without_failing() {
        let dir = scratch();
        let envelope = run(
            &dir,
            &ConfigCommand::Unset(KeyArgs {
                key: Some("limits.retries".to_owned()),
            }),
        )
        .expect("removes nothing");
        assert_eq!(envelope.data["removed"], false);
    }

    #[test]
    fn a_setting_decided_by_the_server_reports_the_absence_of_a_value() {
        let dir = scratch();
        let failure = run(&dir, &reading("conn.timezone")).expect_err("must report");
        assert_eq!(failure.code(), "config.no_value");
        assert_eq!(failure.category(), crate::error::Category::Absence);
    }

    #[test]
    fn the_location_is_reported_with_whether_anything_is_there() {
        let dir = scratch();
        let before = run(&dir, &ConfigCommand::Path).expect("reports");
        assert_eq!(before.data["exists"], false);

        run(&dir, &setting("output.format", "json")).expect("writes");
        let after = run(&dir, &ConfigCommand::Path).expect("reports");
        assert_eq!(after.data["exists"], true);
    }

    #[test]
    fn the_diagnosis_lists_its_findings_under_the_published_payload_key() {
        let dir = scratch();
        let file = paths::config_file(Some(dir.path())).expect("location");
        std::fs::create_dir_all(dir.path()).expect("directory");
        std::fs::write(&file, "\"output.nonsense\" = \"1\"\n").expect("writes");

        let envelope = run(&dir, &ConfigCommand::Doctor).expect("examines");
        assert_eq!(envelope.data["clean"], false);
        assert_eq!(envelope.payload_array_key(), Some("rows"));
        assert_eq!(envelope.data["rows"][0]["kind"], "unknown_key");
    }

    #[test]
    fn a_clean_location_is_reported_as_clean() {
        let dir = scratch();
        run(&dir, &setting("output.format", "json")).expect("writes");
        let envelope = run(&dir, &ConfigCommand::Doctor).expect("examines");
        assert_eq!(envelope.data["clean"], true);
    }
}