Skip to main content

rightsize_modules/
mysql.rs

1//! A single-node MySQL container. Defaults to a `test`/`test`/`test`
2//! user/password/database trio (plus `MYSQL_ROOT_PASSWORD=test`) so
3//! [`MySqlGuard::connection_string`] is usable with zero configuration; call
4//! [`MySqlContainer::with_username`]/[`MySqlContainer::with_password`]/
5//! [`MySqlContainer::with_database`] before `start()` to override any of them.
6//!
7//! ### Readiness — empirically pinned, not guessed
8//!
9//! The official entrypoint boots `mysqld` **twice**: once as a throwaway "temp
10//! server" to run init scripts, then for real. Both prints, plus the X Plugin's own
11//! "ready for connections" line, contain the substring `ready for connections`, and
12//! naively counting occurrences is a trap: the temp server's X Plugin binds `port:
13//! 33060` — whose digits *start with* `3306`, so an unanchored `port: 3306` search
14//! false-matches it too. Captured verbatim from a real `docker run mysql:8.4` boot
15//! with this module's env (`MYSQL_USER=test`, `MYSQL_DATABASE=test`,
16//! `MYSQL_ROOT_PASSWORD=test`):
17//!
18//! ```text
19//! [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
20//! [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.10'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server - GPL.
21//! ...(init scripts run, temp server shuts down)...
22//! [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
23//! [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.10'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
24//! ```
25//!
26//! Four lines contain `ready for connections`; only the last is the real server bound
27//! to 3306. The temp server prints `port: 0` (no port yet) and the X Plugin lines
28//! print `33060`, whose `3306` prefix would satisfy an unanchored match — so simple
29//! occurrence-counting is fragile here. The fix is a regex anchored on the real
30//! server's `port: 3306` with a trailing non-digit-or-end boundary
31//! (`.*mysqld: ready for connections.*port: 3306($|[^0-9]).*`). This module implements
32//! that same anchoring *logic* as a small custom [`WaitStrategy`] with hand-written
33//! character-boundary checks rather than a regex — predates `Wait::for_log_message`'s
34//! move to a real regex engine (`regex-lite`), and the hand-written version is
35//! unaffected by that swap since it was never routed through the shared matcher.
36
37use std::time::Duration;
38
39use rightsize::wait::{WaitStrategy, WaitTarget};
40use rightsize::{Container, ContainerGuard, Result};
41
42/// A single-node MySQL container.
43pub struct MySqlContainer {
44    container: Container,
45    username: String,
46    password: String,
47    database: String,
48}
49
50impl MySqlContainer {
51    const PORT: u16 = 3306;
52
53    /// Builds a container from the pinned default image (`mysql:8.4`).
54    pub fn new() -> Self {
55        Self::with_image("mysql:8.4")
56    }
57
58    /// Builds a container from a caller-chosen image.
59    pub fn with_image(image: &str) -> Self {
60        let username = "test".to_string();
61        let password = "test".to_string();
62        let database = "test".to_string();
63        let container = Container::new(image)
64            .with_exposed_ports(&[Self::PORT])
65            .with_env("MYSQL_USER", &username)
66            .with_env("MYSQL_PASSWORD", &password)
67            .with_env("MYSQL_DATABASE", &database)
68            .with_env("MYSQL_ROOT_PASSWORD", "test")
69            // Anchored on the real server's line (see the module doc for the
70            // captured log excerpt and why an unanchored "port: 3306" search
71            // misfires on the temp-server boot).
72            .waiting_for(MySqlReadyForConnections::default());
73        // No with_memory_limit override: unlike SpringCloudConfig's Paketo JVM
74        // image, MySQL 8.4's InnoDB default footprint fits msb's default ~450M
75        // microVM RAM, so no module-level memory floor is warranted here.
76        Self {
77            container,
78            username,
79            password,
80            database,
81        }
82    }
83
84    /// Overrides `MYSQL_USER` (default `test`).
85    pub fn with_username(mut self, username: &str) -> Self {
86        self.username = username.to_string();
87        self.container = self.container.with_env("MYSQL_USER", username);
88        self
89    }
90
91    /// Overrides `MYSQL_PASSWORD` (default `test`).
92    pub fn with_password(mut self, password: &str) -> Self {
93        self.password = password.to_string();
94        self.container = self.container.with_env("MYSQL_PASSWORD", password);
95        self
96    }
97
98    /// Overrides `MYSQL_DATABASE` (default `test`).
99    pub fn with_database(mut self, database: &str) -> Self {
100        self.database = database.to_string();
101        self.container = self.container.with_env("MYSQL_DATABASE", database);
102        self
103    }
104
105    /// Boots the container.
106    pub async fn start(self) -> Result<MySqlGuard> {
107        let guard = self.container.start().await?;
108        Ok(MySqlGuard {
109            guard,
110            username: self.username,
111            password: self.password,
112            database: self.database,
113        })
114    }
115}
116
117impl Default for MySqlContainer {
118    fn default() -> Self {
119        Self::new()
120    }
121}
122
123/// The exact substring the real (non-temp, non-X-Plugin) server line contains, up to
124/// but not including the port number.
125const READY_PREFIX: &str = "mysqld: ready for connections";
126/// The port marker immediately preceded by `READY_PREFIX` somewhere earlier on the
127/// same line, per the captured log shape in the module doc.
128const PORT_MARKER: &str = "port: 3306";
129
130/// Ready when a log line contains `mysqld: ready for connections` and, later on that
131/// same line, `port: 3306` immediately followed by end-of-line or a non-digit — never
132/// matching the X Plugin's `port: 33060` (whose digits merely start with `3306`).
133struct MySqlReadyForConnections {
134    timeout: Duration,
135}
136
137impl Default for MySqlReadyForConnections {
138    fn default() -> Self {
139        // First boot initializes the datafiles and boots mysqld twice (a throwaway
140        // temp server for init scripts, then the real one). On a fast host that
141        // finishes well under 60s, but a loaded Windows CI runner's first boot
142        // overruns it — 120s absorbs the slow case without masking a real hang.
143        Self {
144            timeout: Duration::from_secs(120),
145        }
146    }
147}
148
149impl MySqlReadyForConnections {
150    fn line_signals_ready(line: &str) -> bool {
151        if !line.contains(READY_PREFIX) {
152            return false;
153        }
154        let Some(idx) = line.find(PORT_MARKER) else {
155            return false;
156        };
157        match line[idx + PORT_MARKER.len()..].chars().next() {
158            None => true,                   // end of line right after "port: 3306"
159            Some(c) => !c.is_ascii_digit(), // anything but another digit (rules out 33060)
160        }
161    }
162
163    async fn is_ready(target: &dyn WaitTarget) -> bool {
164        let logs = target.current_logs().await;
165        logs.lines().any(Self::line_signals_ready)
166    }
167}
168
169#[async_trait::async_trait]
170impl WaitStrategy for MySqlReadyForConnections {
171    async fn wait_until_ready(&self, target: &dyn WaitTarget) -> Result<()> {
172        rightsize::wait::poll_until_ready(
173            target,
174            self.timeout,
175            "mysqld ready for connections on port 3306",
176            || Self::is_ready(target),
177        )
178        .await
179    }
180
181    fn with_startup_timeout(mut self: Box<Self>, timeout: Duration) -> Box<dyn WaitStrategy> {
182        self.timeout = timeout;
183        self
184    }
185}
186
187/// The running guard for a [`MySqlContainer`].
188pub struct MySqlGuard {
189    guard: ContainerGuard,
190    username: String,
191    password: String,
192    database: String,
193}
194
195impl MySqlGuard {
196    /// The configured database user (default `test`).
197    pub fn username(&self) -> &str {
198        &self.username
199    }
200
201    /// The configured database password (default `test`).
202    pub fn password(&self) -> &str {
203        &self.password
204    }
205
206    /// The configured database name (default `test`).
207    pub fn database_name(&self) -> &str {
208        &self.database
209    }
210
211    /// A `mysql://` connection string for the running container's
212    /// [`Self::database_name`].
213    pub fn connection_string(&self) -> String {
214        format!(
215            "mysql://{}:{}@{}:{}/{}",
216            self.username,
217            self.password,
218            self.guard.host(),
219            self.guard.get_mapped_port(MySqlContainer::PORT).unwrap(),
220            self.database,
221        )
222    }
223
224    /// Stops and removes the container, releasing its host port.
225    pub async fn stop(self) -> Result<()> {
226        self.guard.stop().await
227    }
228}
229
230impl std::ops::Deref for MySqlGuard {
231    type Target = ContainerGuard;
232    fn deref(&self) -> &ContainerGuard {
233        &self.guard
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn defaults_are_the_test_trio() {
243        let c = MySqlContainer::new();
244        assert_eq!(c.username, "test");
245        assert_eq!(c.password, "test");
246        assert_eq!(c.database, "test");
247    }
248
249    #[test]
250    fn builders_override_the_defaults() {
251        let c = MySqlContainer::new()
252            .with_username("alice")
253            .with_password("s3cret")
254            .with_database("app");
255        assert_eq!(c.username, "alice");
256        assert_eq!(c.password, "s3cret");
257        assert_eq!(c.database, "app");
258    }
259
260    // The exact captured log excerpt from the module doc: four "ready for
261    // connections" lines, only the last of which must be recognized as ready.
262    const CAPTURED_LOG: &str = "\
263[System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
264[System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.10'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server - GPL.
265[System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
266[System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.10'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.";
267
268    #[test]
269    fn temp_server_and_x_plugin_lines_do_not_signal_ready() {
270        for line in CAPTURED_LOG.lines().take(3) {
271            assert!(
272                !MySqlReadyForConnections::line_signals_ready(line),
273                "must not misfire on: {line}"
274            );
275        }
276    }
277
278    #[test]
279    fn only_the_real_servers_port_3306_line_signals_ready() {
280        let real_line = CAPTURED_LOG.lines().nth(3).unwrap();
281        assert!(MySqlReadyForConnections::line_signals_ready(real_line));
282    }
283
284    #[test]
285    fn port_3306_at_end_of_line_with_no_trailing_text_also_matches() {
286        assert!(MySqlReadyForConnections::line_signals_ready(
287            "mysqld: ready for connections. port: 3306"
288        ));
289    }
290
291    #[tokio::test]
292    async fn is_ready_true_only_once_the_real_line_is_in_the_logs() {
293        struct FakeTarget(std::sync::Mutex<String>);
294        #[async_trait::async_trait]
295        impl WaitTarget for FakeTarget {
296            fn host(&self) -> &str {
297                "127.0.0.1"
298            }
299            fn mapped_port(&self, guest_port: u16) -> u16 {
300                guest_port
301            }
302            fn exposed_guest_ports(&self) -> Vec<u16> {
303                vec![3306]
304            }
305            async fn current_logs(&self) -> String {
306                self.0.lock().unwrap().clone()
307            }
308            fn describe(&self) -> String {
309                "fake-mysql".to_string()
310            }
311        }
312
313        let partial: String = CAPTURED_LOG.lines().take(3).collect::<Vec<_>>().join("\n");
314        let target = FakeTarget(std::sync::Mutex::new(partial));
315        assert!(!MySqlReadyForConnections::is_ready(&target).await);
316
317        *target.0.lock().unwrap() = CAPTURED_LOG.to_string();
318        assert!(MySqlReadyForConnections::is_ready(&target).await);
319    }
320}