docker_wrapper/template/database/
mongodb.rs

1//! MongoDB template for quick MongoDB container setup
2
3#![allow(clippy::doc_markdown)]
4#![allow(clippy::must_use_candidate)]
5#![allow(clippy::return_self_not_must_use)]
6#![allow(clippy::map_unwrap_or)]
7#![allow(clippy::format_push_string)]
8#![allow(clippy::uninlined_format_args)]
9
10use crate::template::{HealthCheck, Template, TemplateConfig, VolumeMount};
11use async_trait::async_trait;
12use std::collections::HashMap;
13
14/// MongoDB container template with sensible defaults
15pub struct MongodbTemplate {
16    config: TemplateConfig,
17}
18
19impl MongodbTemplate {
20    /// Create a new MongoDB template with default settings
21    pub fn new(name: impl Into<String>) -> Self {
22        let name = name.into();
23        let env = HashMap::new();
24
25        let config = TemplateConfig {
26            name: name.clone(),
27            image: "mongo".to_string(),
28            tag: "7.0".to_string(),
29            ports: vec![(27017, 27017)],
30            env,
31            volumes: Vec::new(),
32            network: None,
33            health_check: Some(HealthCheck {
34                test: vec![
35                    "mongosh".to_string(),
36                    "--eval".to_string(),
37                    "db.adminCommand('ping')".to_string(),
38                ],
39                interval: "10s".to_string(),
40                timeout: "5s".to_string(),
41                retries: 5,
42                start_period: "20s".to_string(),
43            }),
44            auto_remove: false,
45            memory_limit: None,
46            cpu_limit: None,
47            platform: None,
48        };
49
50        Self { config }
51    }
52
53    /// Set a custom MongoDB port
54    pub fn port(mut self, port: u16) -> Self {
55        self.config.ports = vec![(port, 27017)];
56        self
57    }
58
59    /// Set root username
60    pub fn root_username(mut self, username: impl Into<String>) -> Self {
61        self.config
62            .env
63            .insert("MONGO_INITDB_ROOT_USERNAME".to_string(), username.into());
64        self
65    }
66
67    /// Set root password
68    pub fn root_password(mut self, password: impl Into<String>) -> Self {
69        self.config
70            .env
71            .insert("MONGO_INITDB_ROOT_PASSWORD".to_string(), password.into());
72        self
73    }
74
75    /// Set initial database name
76    pub fn database(mut self, db: impl Into<String>) -> Self {
77        self.config
78            .env
79            .insert("MONGO_INITDB_DATABASE".to_string(), db.into());
80        self
81    }
82
83    /// Enable persistence with a volume
84    pub fn with_persistence(mut self, volume_name: impl Into<String>) -> Self {
85        self.config.volumes.push(VolumeMount {
86            source: volume_name.into(),
87            target: "/data/db".to_string(),
88            read_only: false,
89        });
90        self
91    }
92
93    /// Mount initialization scripts directory
94    pub fn init_scripts(mut self, scripts_path: impl Into<String>) -> Self {
95        self.config.volumes.push(VolumeMount {
96            source: scripts_path.into(),
97            target: "/docker-entrypoint-initdb.d".to_string(),
98            read_only: true,
99        });
100        self
101    }
102
103    /// Mount custom MongoDB configuration
104    pub fn config_file(mut self, config_path: impl Into<String>) -> Self {
105        self.config.volumes.push(VolumeMount {
106            source: config_path.into(),
107            target: "/etc/mongo/mongod.conf".to_string(),
108            read_only: true,
109        });
110        self
111    }
112
113    /// Set memory limit for MongoDB
114    pub fn memory_limit(mut self, limit: impl Into<String>) -> Self {
115        self.config.memory_limit = Some(limit.into());
116        self
117    }
118
119    /// Set WiredTiger cache size
120    pub fn cache_size(mut self, size: impl Into<String>) -> Self {
121        self.config
122            .env
123            .insert("MONGO_WIREDTIGER_CACHE_SIZE_GB".to_string(), size.into());
124        self
125    }
126
127    /// Enable replica set mode
128    pub fn replica_set(mut self, name: impl Into<String>) -> Self {
129        self.config
130            .env
131            .insert("MONGO_REPLICA_SET".to_string(), name.into());
132        self
133    }
134
135    /// Enable authentication
136    pub fn with_auth(mut self) -> Self {
137        self.config
138            .env
139            .insert("MONGO_AUTH".to_string(), "yes".to_string());
140        self
141    }
142
143    /// Use a specific MongoDB version
144    pub fn version(mut self, version: impl Into<String>) -> Self {
145        self.config.tag = version.into();
146        self
147    }
148
149    /// Connect to a specific network
150    pub fn network(mut self, network: impl Into<String>) -> Self {
151        self.config.network = Some(network.into());
152        self
153    }
154
155    /// Enable auto-remove when stopped
156    pub fn auto_remove(mut self) -> Self {
157        self.config.auto_remove = true;
158        self
159    }
160
161    /// Set journal commit interval
162    pub fn journal_commit_interval(mut self, ms: u32) -> Self {
163        self.config
164            .env
165            .insert("MONGO_JOURNAL_COMMIT_INTERVAL".to_string(), ms.to_string());
166        self
167    }
168
169    /// Enable quiet logging
170    pub fn quiet(mut self) -> Self {
171        self.config
172            .env
173            .insert("MONGO_QUIET".to_string(), "yes".to_string());
174        self
175    }
176
177    /// Use a custom image and tag
178    pub fn custom_image(mut self, image: impl Into<String>, tag: impl Into<String>) -> Self {
179        self.config.image = image.into();
180        self.config.tag = tag.into();
181        self
182    }
183
184    /// Set the platform for the container (e.g., "linux/arm64", "linux/amd64")
185    pub fn platform(mut self, platform: impl Into<String>) -> Self {
186        self.config.platform = Some(platform.into());
187        self
188    }
189}
190
191#[async_trait]
192impl Template for MongodbTemplate {
193    fn name(&self) -> &str {
194        &self.config.name
195    }
196
197    fn config(&self) -> &TemplateConfig {
198        &self.config
199    }
200
201    fn config_mut(&mut self) -> &mut TemplateConfig {
202        &mut self.config
203    }
204}
205
206/// Builder for MongoDB connection strings
207pub struct MongodbConnectionString {
208    host: String,
209    port: u16,
210    database: Option<String>,
211    username: Option<String>,
212    password: Option<String>,
213    replica_set: Option<String>,
214}
215
216impl MongodbConnectionString {
217    /// Create from a MongodbTemplate
218    pub fn from_template(template: &MongodbTemplate) -> Self {
219        let config = template.config();
220        let port = config.ports.first().map(|(h, _)| *h).unwrap_or(27017);
221
222        Self {
223            host: "localhost".to_string(),
224            port,
225            database: config.env.get("MONGO_INITDB_DATABASE").cloned(),
226            username: config.env.get("MONGO_INITDB_ROOT_USERNAME").cloned(),
227            password: config.env.get("MONGO_INITDB_ROOT_PASSWORD").cloned(),
228            replica_set: config.env.get("MONGO_REPLICA_SET").cloned(),
229        }
230    }
231
232    /// Get the connection string in MongoDB URL format
233    pub fn url(&self) -> String {
234        let mut url = String::from("mongodb://");
235
236        // Add credentials if present
237        if let (Some(user), Some(pass)) = (&self.username, &self.password) {
238            url.push_str(&format!("{}:{}@", user, pass));
239        }
240
241        // Add host and port
242        url.push_str(&format!("{}:{}", self.host, self.port));
243
244        // Add database if present
245        if let Some(db) = &self.database {
246            url.push_str(&format!("/{}", db));
247        }
248
249        // Add replica set if present
250        if let Some(rs) = &self.replica_set {
251            if self.database.is_none() {
252                url.push('/');
253            }
254            url.push_str(&format!("?replicaSet={}", rs));
255        }
256
257        url
258    }
259
260    /// Get the connection string for MongoDB SRV (Atlas-style)
261    pub fn srv_url(&self) -> String {
262        let mut url = String::from("mongodb+srv://");
263
264        // Add credentials if present
265        if let (Some(user), Some(pass)) = (&self.username, &self.password) {
266            url.push_str(&format!("{}:{}@", user, pass));
267        }
268
269        // For SRV, we only use the host
270        url.push_str(&self.host);
271
272        // Add database if present
273        if let Some(db) = &self.database {
274            url.push_str(&format!("/{}", db));
275        }
276
277        url
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    #[test]
286    fn test_mongodb_template_basic() {
287        let template = MongodbTemplate::new("test-mongo");
288        assert_eq!(template.name(), "test-mongo");
289        assert_eq!(template.config().image, "mongo");
290        assert_eq!(template.config().tag, "7.0");
291        assert_eq!(template.config().ports, vec![(27017, 27017)]);
292    }
293
294    #[test]
295    fn test_mongodb_template_with_auth() {
296        let template = MongodbTemplate::new("test-mongo")
297            .root_username("admin")
298            .root_password("secret123")
299            .database("mydb")
300            .with_auth();
301
302        assert_eq!(
303            template.config().env.get("MONGO_INITDB_ROOT_USERNAME"),
304            Some(&"admin".to_string())
305        );
306        assert_eq!(
307            template.config().env.get("MONGO_INITDB_ROOT_PASSWORD"),
308            Some(&"secret123".to_string())
309        );
310        assert_eq!(
311            template.config().env.get("MONGO_INITDB_DATABASE"),
312            Some(&"mydb".to_string())
313        );
314        assert_eq!(
315            template.config().env.get("MONGO_AUTH"),
316            Some(&"yes".to_string())
317        );
318    }
319
320    #[test]
321    fn test_mongodb_template_with_persistence() {
322        let template = MongodbTemplate::new("test-mongo").with_persistence("mongo-data");
323
324        assert_eq!(template.config().volumes.len(), 1);
325        assert_eq!(template.config().volumes[0].source, "mongo-data");
326        assert_eq!(template.config().volumes[0].target, "/data/db");
327    }
328
329    #[test]
330    fn test_mongodb_connection_string() {
331        let template = MongodbTemplate::new("test-mongo")
332            .root_username("admin")
333            .root_password("pass")
334            .database("testdb")
335            .port(27018);
336
337        let conn = MongodbConnectionString::from_template(&template);
338
339        assert_eq!(conn.url(), "mongodb://admin:pass@localhost:27018/testdb");
340    }
341
342    #[test]
343    fn test_mongodb_connection_string_no_auth() {
344        let template = MongodbTemplate::new("test-mongo");
345        let conn = MongodbConnectionString::from_template(&template);
346
347        assert_eq!(conn.url(), "mongodb://localhost:27017");
348    }
349
350    #[test]
351    fn test_mongodb_connection_string_replica_set() {
352        let template = MongodbTemplate::new("test-mongo").replica_set("rs0");
353
354        let conn = MongodbConnectionString::from_template(&template);
355
356        assert_eq!(conn.url(), "mongodb://localhost:27017/?replicaSet=rs0");
357    }
358}