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};
pub const AUTH_METHOD_UNSUPPORTED: &str = "authentication.method_unsupported";
pub const SESSION_ENDED: &str = "interrupted.session_ended";
#[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",
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channel {
Opening,
Established,
}
#[must_use]
pub fn map_driver_error(error: &DriverError) -> Failure {
map_driver_error_in(Channel::Established, error)
}
#[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
}
#[cfg(not(feature = "tls"))]
fn tls_refusal(_inner: &mysql_async::IoError) -> Option<String> {
None
}
#[must_use]
pub fn map_driver_error_in(channel: Channel, error: &DriverError) -> Failure {
match error {
DriverError::Io(inner) => match channel {
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)
},
),
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())
}
}
}
pub trait OrFailure<T> {
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> {
self.map_err(|failed| map_driver_error(&failed))
}
}
fn map_protocol_fault(fault: &ProtocolFault) -> Failure {
match fault {
ProtocolFault::UnknownAuthPlugin { name } => {
unsupported_auth_method(name).with_cause(fault.to_string())
}
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"),
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()),
}
}
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())
}
fn classify(code: u16, message: &str) -> Failure {
classify_credential(code).unwrap_or_else(|| classify_outcome(code, message))
}
fn classify_credential(code: u16) -> Option<Failure> {
match code {
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"),
),
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"),
),
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,
}
}
fn classify_outcome(code: u16, message: &str) -> Failure {
match code {
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),
1040 | 1203 => Failure::server(
"server.too_many_connections",
"the server accepts no further connections right now",
)
.with_retryable(true),
3024 | 1969 => Failure::timeout(
"timeout.server_execution",
"the server stopped the statement at its own time limit",
),
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"),
1317 => Failure::interrupted(
"interrupted.by_server",
"the statement was stopped before it finished",
),
_ => 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(),
})
}
#[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());
}
#[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());
}
#[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);
}
#[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());
}
#[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");
}
#[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()
);
}
#[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()
);
}
#[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");
}
}