Skip to main content

mysql_replication/
config.rs

1//! Reusable replication settings; file positions are supplied by the caller.
2
3use crate::{Error, Result, error::invalid, stream};
4use serde::Deserialize;
5use std::{fmt, path::PathBuf, str::FromStr, time::Duration};
6
7/// Required upstream row-image mode. Both modes support borrowed row decoding.
8#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
9#[serde(rename_all = "lowercase")]
10pub enum RowImageMode {
11    #[default]
12    Minimal,
13    Full,
14}
15
16impl RowImageMode {
17    pub fn server_value(self) -> &'static str {
18        match self {
19            Self::Minimal => "MINIMAL",
20            Self::Full => "FULL",
21        }
22    }
23}
24
25impl fmt::Display for RowImageMode {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.write_str(match self {
28            Self::Minimal => "minimal",
29            Self::Full => "full",
30        })
31    }
32}
33
34impl FromStr for RowImageMode {
35    type Err = Error;
36
37    fn from_str(value: &str) -> Result<Self> {
38        match value {
39            "minimal" => Ok(Self::Minimal),
40            "full" => Ok(Self::Full),
41            _ => Err(invalid("row_image must be minimal or full")),
42        }
43    }
44}
45
46impl From<RowImageMode> for stream::RowImage {
47    fn from(mode: RowImageMode) -> Self {
48        match mode {
49            RowImageMode::Minimal => Self::Minimal,
50            RowImageMode::Full => Self::Full,
51        }
52    }
53}
54
55/// Connection and subscription settings shared by direct and CDC consumers.
56/// Credentials remain in the named environment variable. No CDC table/schema,
57/// transaction, checkpoint or output policy is part of this configuration.
58#[derive(Debug, Clone, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct Config {
61    pub url_env: String,
62    pub server_id: u32,
63    pub tls_ca: Option<PathBuf>,
64    #[serde(default)]
65    pub row_image: RowImageMode,
66    #[serde(default = "connect_timeout_secs")]
67    pub connect_timeout_secs: u64,
68    #[serde(default = "read_timeout_secs")]
69    pub read_timeout_secs: u64,
70}
71
72fn connect_timeout_secs() -> u64 {
73    10
74}
75
76fn read_timeout_secs() -> u64 {
77    90
78}
79
80impl Config {
81    pub fn new(url_env: impl Into<String>, server_id: u32) -> Self {
82        Self {
83            url_env: url_env.into(),
84            server_id,
85            tls_ca: None,
86            row_image: RowImageMode::Minimal,
87            connect_timeout_secs: connect_timeout_secs(),
88            read_timeout_secs: read_timeout_secs(),
89        }
90    }
91
92    pub fn validate(&self) -> Result<()> {
93        if self.url_env.is_empty() || self.server_id == 0 {
94            return Err(invalid(
95                "replication requires nonempty url_env and nonzero server_id",
96            ));
97        }
98        if self.connect_timeout_secs == 0 || self.read_timeout_secs == 0 {
99            return Err(invalid("replication timeouts must be nonzero"));
100        }
101        Ok(())
102    }
103
104    pub fn connection_config(&self) -> Result<stream::ConnectionConfig> {
105        self.validate()?;
106        Ok(stream::ConnectionConfig {
107            url_env: self.url_env.clone(),
108            tls_ca: self.tls_ca.clone(),
109            connect_timeout: Duration::from_secs(self.connect_timeout_secs),
110            read_timeout: Duration::from_secs(self.read_timeout_secs),
111        })
112    }
113
114    /// Binds reusable settings to a caller-supplied binlog position.
115    /// This validates upstream mode at stream startup without changing MySQL.
116    pub fn replication_config(
117        &self,
118        file: impl Into<String>,
119        position: u64,
120    ) -> Result<stream::ReplicationConfig> {
121        self.validate()?;
122        let mut config = stream::ReplicationConfig::new(self.server_id, file, position);
123        config.required_row_image = Some(self.row_image.into());
124        Ok(config)
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn reusable_config_binds_both_modes_and_connection_settings() {
134        let mut config = Config::new("MYSQL_URL", 101);
135        config.tls_ca = Some("certs/ca.pem".into());
136        config.connect_timeout_secs = 4;
137        config.read_timeout_secs = 30;
138        assert_eq!(config.row_image, RowImageMode::Minimal);
139        for (mode, expected) in [
140            (RowImageMode::Minimal, stream::RowImage::Minimal),
141            (RowImageMode::Full, stream::RowImage::Full),
142        ] {
143            config.row_image = mode;
144            let connection = config.connection_config().unwrap();
145            assert_eq!(connection.url_env, "MYSQL_URL");
146            assert_eq!(connection.tls_ca, Some("certs/ca.pem".into()));
147            assert_eq!(connection.connect_timeout, Duration::from_secs(4));
148            assert_eq!(connection.read_timeout, Duration::from_secs(30));
149            let subscription = config.replication_config("binlog.000007", 1234).unwrap();
150            assert_eq!(subscription.server_id, 101);
151            assert_eq!(subscription.file, "binlog.000007");
152            assert_eq!(subscription.position, 1234);
153            assert_eq!(subscription.required_row_image, Some(expected));
154            assert!(!subscription.non_blocking);
155        }
156    }
157
158    #[test]
159    fn invalid_settings_fail_before_connection_or_subscription() {
160        let mut missing_id = Config::new("MYSQL_URL", 0);
161        let mut missing_url = Config::new("", 101);
162        for config in [&mut missing_id, &mut missing_url] {
163            assert!(
164                matches!(config.connection_config(), Err(Error::Invalid(message))
165                if message == "replication requires nonempty url_env and nonzero server_id")
166            );
167            assert!(
168                matches!(config.replication_config("binlog.000001", 4), Err(Error::Invalid(message))
169                if message == "replication requires nonempty url_env and nonzero server_id")
170            );
171        }
172        for (connect, read) in [(0, 90), (10, 0)] {
173            let mut config = Config::new("MYSQL_URL", 101);
174            config.connect_timeout_secs = connect;
175            config.read_timeout_secs = read;
176            assert!(
177                matches!(config.connection_config(), Err(Error::Invalid(message))
178                if message == "replication timeouts must be nonzero")
179            );
180        }
181    }
182}