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
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
//! The connection layer: how a named destination becomes an open session.
//!
//! The layer is built from six parts, each with one job:
//!
//! - [`profile`] describes one named destination and never holds a secret in
//!   clear text.
//! - [`store`] keeps those destinations between invocations.
//! - [`dsn`] turns a single text into one throw-away destination.
//! - [`abort`] asks the server to stop work this process gave up on.
//! - [`options`] maps a destination onto the driver's option set.
//! - [`tls`] builds the encrypted channel, or refuses when this build has none.
//! - [`handshake`] asks the server, once, everything the invocation needs.
//! - [`session`] opens, hands over and closes within a single invocation.
//!
//! No connection outlives the invocation and no pool is ever created, because
//! the process is born, works and dies for one call.

pub mod abort;
pub mod dsn;
pub mod handshake;
pub mod options;
pub mod profile;
pub mod provider;
pub mod session;
pub mod store;
pub mod tls;

pub use abort::SecondConnection;
pub use dsn::Dsn;
pub use handshake::ServerFacts;
pub use options::ConnectionSettings;
pub use profile::{Profile, SecretRef, SecretVault};
pub use session::Session;
pub use store::ProfileStore;

use crate::error::Failure;
use mysql_async::{DriverError as ProtocolFault, Error as DriverError, ServerError};

/// The stable identifier a method this build cannot complete is refused under.
pub const AUTH_METHOD_UNSUPPORTED: &str = "authentication.method_unsupported";

/// The stable identifier a session that stopped mid-statement is reported under.
///
/// Named here rather than written where it is built, because a proof has to be
/// able to say the word without copying it, and a copied identifier is one that
/// can be changed in one of the two places.
pub const SESSION_ENDED: &str = "interrupted.session_ended";

/// The refusal an authentication method this build cannot complete earns.
///
/// Stated once, and reachable from both places such a method can be met: the
/// destination declares it, or the server asks for it in the middle of the
/// handshake. Those two used to answer differently — one of them not at all —
/// and a caller cannot be expected to know which of the two happened. What the
/// caller must never be told is that the secret was wrong when it was the
/// method, so the name of the method travels in the message itself.
#[must_use]
pub fn unsupported_auth_method(method: &str) -> Failure {
    Failure::authentication(
        AUTH_METHOD_UNSUPPORTED,
        format!("`{method}` is not an authentication method this build can complete"),
    )
    .with_detail("detail", method)
    .with_hint(
        "give this user a method this build implements: mysql_native_password, \
         caching_sha2_password, client_ed25519, parsec or mysql_clear_password",
    )
}

/// Where in the life of the channel a driver failure was met.
///
/// The driver reports the same input-output error whether the channel never
/// opened or a working session stopped mid-statement, because at that level
/// both are the same event: the bytes stopped. They are not the same event to
/// the caller. One says the destination is wrong or the server is down, and
/// repeating may work. The other says the work was cut after the server was
/// reached, authenticated and already running, and repeating may redo something
/// somebody chose to stop.
///
/// The distinction cannot be recovered from the error, so it travels here, from
/// the one place that knows it: the call site that either was opening the
/// channel or already held it open.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channel {
    /// The channel was still being opened and nothing had been agreed yet.
    Opening,
    /// The channel was open and the session was working.
    Established,
}

/// Turns a driver failure into the product's own closed shape.
///
/// The driver reports one flat error type, while the caller branches on the
/// thirteen published categories. This is the single place that conversion
/// happens, so two call sites can never disagree about what a condition means.
///
/// Reads as an established session, because that is what all but two call sites
/// are: a connection is opened exactly twice in this product, and both of those
/// sites name [`Channel::Opening`] for themselves. A proof holds every
/// `Conn::new` in the source to that, so a third one cannot be added and
/// silently inherit the wrong reading.
#[must_use]
pub fn map_driver_error(error: &DriverError) -> Failure {
    map_driver_error_in(Channel::Established, error)
}

/// The transport's own account of a refusal, when the refusal was the transport's.
///
/// Read by type rather than by reading the message, because a message is prose
/// and prose is rewritten between releases: matching on the words would turn a
/// wording change upstream into a silent reclassification here. The driver
/// names one of these outright; the other arrives wrapped, because the
/// handshake reports through the same input-output channel it runs over, so
/// the wrapper is followed to its source rather than trusted at its surface.
///
/// Answers `None` for every failure that is not the transport's, which is what
/// keeps an ordinary unreachable server reading as unreachable.
#[cfg(feature = "tls")]
fn tls_refusal(inner: &mysql_async::IoError) -> Option<String> {
    if let mysql_async::IoError::Tls(refusal) = inner {
        return Some(refusal.to_string());
    }

    let mysql_async::IoError::Io(wrapped) = inner else {
        return None;
    };
    let mut link: Option<&(dyn std::error::Error + 'static)> =
        wrapped.get_ref().map(|error| error as _);
    while let Some(error) = link {
        if let Some(refusal) = error.downcast_ref::<rustls::Error>() {
            return Some(refusal.to_string());
        }
        link = error.source();
    }
    None
}

/// Answers `None` for every failure, because a build without the transport
/// cannot meet one of its refusals.
#[cfg(not(feature = "tls"))]
fn tls_refusal(_inner: &mysql_async::IoError) -> Option<String> {
    None
}

/// Turns a driver failure into the product's own shape, given the channel.
///
/// Only the input-output case reads the channel, because it is the only case
/// whose meaning depends on it: a server condition, a malformed destination and
/// a protocol fault each say the same thing whenever they are met.
#[must_use]
pub fn map_driver_error_in(channel: Channel, error: &DriverError) -> Failure {
    match error {
        DriverError::Io(inner) => match channel {
            // A refused certificate arrives here as an input-output failure,
            // because that is how the transport hands it over, and answering
            // `network.unreachable` to it made four false statements at once:
            // the host was wrong, the port was wrong, the server was refusing
            // connections, and repeating the call might work. All four were
            // false. The server was reached, it offered a certificate, and the
            // certificate was the whole of the problem, so the caller was sent
            // to check the one thing that was already correct. Trust is a
            // setting, so this reads as configuration and refuses a repeat.
            Channel::Opening => tls_refusal(inner).map_or_else(
                || {
                    Failure::network(
                        "network.unreachable",
                        "the server could not be reached over the channel",
                    )
                    .with_hint(
                        "check the host, the port and whether the server accepts connections",
                    )
                    .with_cause(inner.to_string())
                },
                |refusal| {
                    Failure::config(
                        "config.tls_refused_certificate",
                        "the server was reached and its certificate was refused",
                    )
                    .with_hint(
                        "name the authority with `--ca`, or set `tls.verify` to what \
                         this destination can prove",
                    )
                    .with_cause(refusal)
                },
            ),

            // Not a network failure, and saying so cost the caller four false
            // statements at once: the server *was* reached, it *did* accept the
            // credential, it *was* running the statement, and repeating was
            // called worthwhile when an operator may have chosen to stop it.
            // What is actually known is only this: the session ended before the
            // statement finished. Whether it was ended on the server or the
            // link broke is not knowable from here, and both leave the work
            // unfinished, so both earn the same answer and the same refusal to
            // recommend a repeat.
            Channel::Established => Failure::interrupted(
                SESSION_ENDED,
                "the session ended before the statement finished",
            )
            .with_hint(
                "check `server processes` for whether the connection was ended; \
                 the work may have stopped part-way",
            )
            .with_cause(inner.to_string()),
        },

        DriverError::Server(condition) => map_server_condition(condition),

        DriverError::Url(inner) => Failure::config(
            "config.malformed_destination",
            "the destination text is not a form the driver accepts",
        )
        .with_hint("write the destination as scheme://user@host:port/database")
        .with_cause(inner.to_string()),

        DriverError::Driver(inner) => map_protocol_fault(inner),

        DriverError::Other(inner) => {
            Failure::server("server.unclassified", "the server call failed")
                .with_cause(inner.to_string())
        }
    }
}

/// Carries a driver outcome across into the product's own shape.
///
/// The conversion itself has always lived in one place, but the call to it did
/// not: thirty-nine sites each wrote the same closure by hand, and a closure
/// written by hand is a closure that can be written differently. One of them
/// reaching for a different conversion would read as ordinary code rather than
/// as the divergence it is, and nothing would catch it.
///
/// Stated as a trait rather than a free function so the call reads in the
/// direction the value travels, and so the conversion cannot be applied to an
/// outcome that did not come from the driver.
pub trait OrFailure<T> {
    /// Answers the product's shape, converting a driver failure on the way.
    ///
    /// # Errors
    ///
    /// Answers the category [`map_driver_error`] chose for the condition.
    fn or_failure(self) -> crate::error::Result<T>;
}

impl<T> OrFailure<T> for std::result::Result<T, DriverError> {
    fn or_failure(self) -> crate::error::Result<T> {
        // The one hand-written call that remains, and the reason the others no
        // longer are.
        self.map_err(|failed| map_driver_error(&failed))
    }
}

/// Maps one fault in the exchange itself onto the product's own shape.
///
/// Three of these faults are about the authentication method rather than about
/// the protocol, and folding them into the generic protocol failure is what
/// made the declared method a field nobody acted on: a user whose server asks
/// for a method this build has no code for ended the call reading about the
/// server, with no way to learn that the method was the whole story.
fn map_protocol_fault(fault: &ProtocolFault) -> Failure {
    match fault {
        ProtocolFault::UnknownAuthPlugin { name } => {
            unsupported_auth_method(name).with_cause(fault.to_string())
        }

        // The driver refuses this one outright, and so does the product: it is
        // the method whose exchange can be replayed, and no destination has a
        // way of asking for it back.
        ProtocolFault::MysqlOldPasswordDisabled => unsupported_auth_method("mysql_old_password")
            .with_cause(fault.to_string())
            .with_hint("move this user onto mysql_native_password or a stronger method"),

        // This one the build does implement, and deliberately does not use
        // unless the destination names it: it puts the secret on the channel as
        // it is. The refusal names it and says how to ask for it, because the
        // caller who meets it has a working credential and no idea why.
        ProtocolFault::CleartextPluginDisabled => Failure::authentication(
            "authentication.method_not_declared",
            "the server asked for `mysql_clear_password`, which sends the secret \
             as it is and is only used when the destination declares it",
        )
        .with_hint(
            "declare it with `conn add ... --auth mysql_clear_password`, \
             and only over an encrypted channel",
        )
        .with_cause(fault.to_string()),

        _ => Failure::server(
            "server.driver_protocol",
            "the exchange with the server did not follow the protocol",
        )
        .with_cause(fault.to_string()),
    }
}

/// Maps one server condition onto its category and retry mark.
///
/// The condition code decides both, because the category alone cannot tell a
/// deadlock, which is worth repeating, from a syntax error, which is not.
fn map_server_condition(condition: &ServerError) -> Failure {
    classify(condition.code, &condition.message)
        .with_cause(format!(
            "server condition {} ({})",
            condition.code, condition.state
        ))
        .with_cause(condition.message.clone())
}

/// Chooses the category and the retry mark for one condition code.
///
/// The conditions about who the caller is are asked first, because they are the
/// only ones whose answer is a change of credential rather than a change of
/// statement, and mistaking one for a server fault sends the caller in circles.
fn classify(code: u16, message: &str) -> Failure {
    classify_credential(code).unwrap_or_else(|| classify_outcome(code, message))
}

/// The conditions about who the caller is and what that credential may reach.
///
/// Answers `None` when the code is about something else, so the caller falls
/// through to the conditions about what the statement did.
fn classify_credential(code: u16) -> Option<Failure> {
    match code {
        // The credential itself was refused.
        1045 | 1251 | 1698 | 1524 => Some(
            Failure::authentication(
                "authentication.refused",
                "the server refused the credential",
            )
            .with_hint("check the user and the secret stored for this destination"),
        ),

        // The credential exists but may not do what was asked.
        1044 | 1142 | 1143 | 1227 | 1370 | 1419 => Some(
            Failure::permission(
                "permission.denied",
                "the credential may not perform this operation",
            )
            .with_hint("grant the missing right on the server, or use another credential"),
        ),

        // The named object does not exist.
        1049 | 1051 | 1054 | 1146 | 1305 | 1360 | 1364 => Some(
            Failure::absence("absence.unknown_object", "the named object does not exist")
                .with_hint("list the structure first to confirm the name"),
        ),

        _ => None,
    }
}

/// The conditions about what happened to the statement itself.
fn classify_outcome(code: u16, message: &str) -> Failure {
    match code {
        // A lock, a deadlock or a constraint stopped the change.
        1213 => Failure::conflict("conflict.deadlock", "the change hit a deadlock")
            .with_hint("repeat the call; the server rolled the change back"),
        1205 => Failure::conflict(
            "conflict.lock_wait",
            "the change waited too long for a lock",
        ),
        1062 | 1451 | 1452 | 1216 | 1217 => Failure::conflict(
            "conflict.constraint",
            "the change was refused by a constraint",
        )
        .with_retryable(false),

        // The server ran out of room for another caller.
        1040 | 1203 => Failure::server(
            "server.too_many_connections",
            "the server accepts no further connections right now",
        )
        .with_retryable(true),

        // Time ran out on the server side.
        3024 | 1969 => Failure::timeout(
            "timeout.server_execution",
            "the server stopped the statement at its own time limit",
        ),

        // A server option, and in practice read-only, forbids the statement.
        // The same condition caught before the send is `safety.server_read_only`
        // in `exec`, so it carries the same category, the same identifier and
        // the same next step here: a caller must not have to tell the two apart
        // by whether the refusal happened a moment earlier or a moment later.
        1290 => Failure::validation(
            "safety.server_read_only",
            "the destination is a read-only server and accepts no change",
        )
        .with_hint("point at a destination that accepts writes"),

        // Somebody stopped the statement from outside.
        1317 => Failure::interrupted(
            "interrupted.by_server",
            "the statement was stopped before it finished",
        ),

        // Every other condition keeps the server's own text as its message. The
        // stable identifier is shared, because a per-code identifier would have
        // to be a static text and the server's code space is open-ended; the
        // numeric code travels in the cause chain instead, where it is exact.
        _ => Failure::server("server.condition", message.to_owned()).with_retryable(false),
    }
}

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

    fn server(code: u16) -> DriverError {
        DriverError::Server(ServerError {
            code,
            message: "condition text".to_owned(),
            state: "HY000".to_owned(),
        })
    }

    /// A refused credential is an authentication failure, never a server one,
    /// because the caller's next step is to fix the secret and not to retry.
    #[test]
    fn a_refused_credential_is_an_authentication_failure() {
        let failure = map_driver_error(&server(1045));
        assert_eq!(failure.category(), crate::error::Category::Authentication);
        assert!(!failure.is_retryable());
    }

    /// A missing right is a permission failure and is never worth repeating.
    #[test]
    fn a_missing_right_is_a_permission_failure() {
        let failure = map_driver_error(&server(1142));
        assert_eq!(failure.category(), crate::error::Category::Permission);
        assert!(!failure.is_retryable());
    }

    /// An unknown object is an absence, so the caller lists the structure
    /// rather than repeating the same call.
    #[test]
    fn an_unknown_object_is_an_absence() {
        let failure = map_driver_error(&server(1146));
        assert_eq!(failure.category(), crate::error::Category::Absence);
        assert_eq!(failure.exit_number().code(), 8);
    }

    /// A deadlock is a conflict the caller may repeat; a constraint is not.
    #[test]
    fn a_deadlock_is_repeatable_and_a_constraint_is_not() {
        let deadlock = map_driver_error(&server(1213));
        assert_eq!(deadlock.category(), crate::error::Category::Conflict);
        assert!(deadlock.is_retryable());

        let constraint = map_driver_error(&server(1062));
        assert_eq!(constraint.category(), crate::error::Category::Conflict);
        assert!(!constraint.is_retryable());
    }

    /// A destination that turned read-only refuses the change with the same
    /// answer the pre-flight check gives, so a replica promoted to read-only
    /// mid-invocation never reaches the caller as raw server text.
    #[test]
    fn a_read_only_destination_is_refused_the_same_way_before_and_after_the_send() {
        let failure = map_driver_error(&server(1290));
        assert_eq!(failure.category(), crate::error::Category::Validation);
        assert_eq!(failure.code(), "safety.server_read_only");
        assert!(!failure.is_retryable());
        assert_eq!(failure.exit_number().code(), 3);
        assert!(failure.hint().is_some(), "the caller is told where to go");
    }

    /// An unnamed server condition keeps its numeric code in the cause chain,
    /// so nothing the server said is lost.
    #[test]
    fn an_unnamed_condition_keeps_its_code_in_the_cause_chain() {
        let failure = map_driver_error(&server(4242));
        assert_eq!(failure.category(), crate::error::Category::Server);
        assert!(
            failure.causes().iter().any(|cause| cause.contains("4242")),
            "the numeric code must survive: {:?}",
            failure.causes()
        );
    }

    /// A refused certificate is a settings failure and never a network one.
    ///
    /// Measured against a live server whose certificate this host cannot build
    /// a chain to: the answer was `network.unreachable`, retryable, telling the
    /// caller to check a host and a port that were both already right. The
    /// server had been reached. Only the trust was missing, and trust is a
    /// setting, so the caller is sent to the setting and not to the wire.
    #[cfg(feature = "tls")]
    #[test]
    fn a_refused_certificate_reads_as_settings_and_not_as_an_unreachable_server() {
        let refusal = rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer);
        let carried = std::io::Error::new(std::io::ErrorKind::InvalidData, refusal);
        let failure = map_driver_error_in(
            Channel::Opening,
            &DriverError::Io(mysql_async::IoError::Io(carried)),
        );

        assert_eq!(failure.category(), crate::error::Category::Config);
        assert_eq!(failure.code(), "config.tls_refused_certificate");
        assert!(
            !failure.is_retryable(),
            "repeating cannot make this host trust that issuer"
        );
        assert!(
            failure
                .causes()
                .iter()
                .any(|cause| cause.contains("UnknownIssuer")),
            "the transport's own account must survive: {:?}",
            failure.causes()
        );
    }

    /// An ordinary unreachable server still reads as unreachable.
    ///
    /// The guard above narrows one case, and a narrowing that swallows its
    /// neighbours is worse than the fault it fixes. This holds the neighbour.
    #[test]
    fn a_server_that_refuses_the_connection_still_reads_as_unreachable() {
        let refused =
            std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "connection refused");
        let failure = map_driver_error_in(
            Channel::Opening,
            &DriverError::Io(mysql_async::IoError::Io(refused)),
        );

        assert_eq!(failure.category(), crate::error::Category::Network);
        assert_eq!(failure.code(), "network.unreachable");
        assert!(failure.is_retryable(), "a refused connection may yet open");
    }
}