docker-wrapper 0.11.1

A Docker CLI wrapper for Rust
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
//! PostgreSQL template for quick PostgreSQL container setup

#![allow(clippy::doc_markdown)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::return_self_not_must_use)]
#![allow(clippy::map_unwrap_or)]
#![allow(clippy::format_push_string)]
#![allow(clippy::uninlined_format_args)]

use crate::template::{HealthCheck, Template, TemplateConfig, VolumeMount};
use async_trait::async_trait;
use std::collections::HashMap;

/// PostgreSQL container template with sensible defaults
pub struct PostgresTemplate {
    config: TemplateConfig,
}

impl PostgresTemplate {
    /// Create a new PostgreSQL template with default settings
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();
        let mut env = HashMap::new();

        // Default PostgreSQL configuration
        env.insert("POSTGRES_PASSWORD".to_string(), "postgres".to_string());
        env.insert("POSTGRES_USER".to_string(), "postgres".to_string());
        env.insert("POSTGRES_DB".to_string(), "postgres".to_string());

        let config = TemplateConfig {
            name: name.clone(),
            image: "postgres".to_string(),
            tag: "15-alpine".to_string(),
            ports: vec![(5432, 5432)],
            env,
            volumes: Vec::new(),
            network: None,
            health_check: Some(HealthCheck {
                test: vec![
                    "pg_isready".to_string(),
                    "-U".to_string(),
                    "postgres".to_string(),
                ],
                interval: "10s".to_string(),
                timeout: "5s".to_string(),
                retries: 5,
                start_period: "10s".to_string(),
            }),
            auto_remove: false,
            memory_limit: None,
            cpu_limit: None,
            platform: None,
        };

        Self { config }
    }

    /// Set a custom PostgreSQL port
    pub fn port(mut self, port: u16) -> Self {
        self.config.ports = vec![(port, 5432)];
        self
    }

    /// Set database name
    pub fn database(mut self, db: impl Into<String>) -> Self {
        self.config.env.insert("POSTGRES_DB".to_string(), db.into());
        self
    }

    /// Set database user
    pub fn user(mut self, user: impl Into<String>) -> Self {
        let user = user.into();
        self.config
            .env
            .insert("POSTGRES_USER".to_string(), user.clone());

        // Update health check to use the correct user
        if let Some(health) = &mut self.config.health_check {
            health.test = vec!["pg_isready".to_string(), "-U".to_string(), user];
        }
        self
    }

    /// Set database password
    pub fn password(mut self, password: impl Into<String>) -> Self {
        self.config
            .env
            .insert("POSTGRES_PASSWORD".to_string(), password.into());
        self
    }

    /// Enable persistence with a volume
    pub fn with_persistence(mut self, volume_name: impl Into<String>) -> Self {
        self.config.volumes.push(VolumeMount {
            source: volume_name.into(),
            target: "/var/lib/postgresql/data".to_string(),
            read_only: false,
        });
        self
    }

    /// Mount initialization scripts directory
    pub fn init_scripts(mut self, scripts_path: impl Into<String>) -> Self {
        self.config.volumes.push(VolumeMount {
            source: scripts_path.into(),
            target: "/docker-entrypoint-initdb.d".to_string(),
            read_only: true,
        });
        self
    }

    /// Set memory limit for PostgreSQL
    pub fn memory_limit(mut self, limit: impl Into<String>) -> Self {
        self.config.memory_limit = Some(limit.into());
        self
    }

    /// Set shared memory size
    pub fn shared_memory(mut self, size: impl Into<String>) -> Self {
        self.config
            .env
            .insert("POSTGRES_SHARED_MEMORY".to_string(), size.into());
        self
    }

    /// Enable PostgreSQL extensions
    pub fn with_extension(mut self, extension: impl Into<String>) -> Self {
        let ext = extension.into();
        let current = self
            .config
            .env
            .get("POSTGRES_EXTENSIONS")
            .map(|s| format!("{},{}", s, ext))
            .unwrap_or(ext);
        self.config
            .env
            .insert("POSTGRES_EXTENSIONS".to_string(), current);
        self
    }

    /// Use a specific PostgreSQL version
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.config.tag = format!("{}-alpine", version.into());
        self
    }

    /// Connect to a specific network
    pub fn network(mut self, network: impl Into<String>) -> Self {
        self.config.network = Some(network.into());
        self
    }

    /// Enable auto-remove when stopped
    pub fn auto_remove(mut self) -> Self {
        self.config.auto_remove = true;
        self
    }

    /// Set additional PostgreSQL configuration
    pub fn postgres_args(mut self, args: impl Into<String>) -> Self {
        self.config
            .env
            .insert("POSTGRES_INITDB_ARGS".to_string(), args.into());
        self
    }

    /// Enable SSL/TLS
    pub fn with_ssl(mut self) -> Self {
        self.config
            .env
            .insert("POSTGRES_SSL_MODE".to_string(), "require".to_string());
        self
    }

    /// Set locale
    pub fn locale(mut self, locale: impl Into<String>) -> Self {
        let locale = locale.into();
        self.config.env.insert(
            "POSTGRES_INITDB_ARGS".to_string(),
            format!("--locale={}", locale),
        );
        self
    }

    /// Use a custom image and tag
    pub fn custom_image(mut self, image: impl Into<String>, tag: impl Into<String>) -> Self {
        self.config.image = image.into();
        self.config.tag = tag.into();
        self
    }

    /// Set the platform for the container (e.g., "linux/arm64", "linux/amd64")
    pub fn platform(mut self, platform: impl Into<String>) -> Self {
        self.config.platform = Some(platform.into());
        self
    }
}

#[async_trait]
impl Template for PostgresTemplate {
    fn name(&self) -> &str {
        &self.config.name
    }

    fn config(&self) -> &TemplateConfig {
        &self.config
    }

    fn config_mut(&mut self) -> &mut TemplateConfig {
        &mut self.config
    }

    async fn wait_for_ready(&self) -> crate::template::Result<()> {
        use std::time::Duration;
        use tokio::time::{sleep, timeout};

        // Custom PostgreSQL readiness check
        // Use 60 second timeout for slower systems (especially Windows)
        let wait_timeout = Duration::from_secs(60);
        let check_interval = Duration::from_millis(500);

        timeout(wait_timeout, async {
            loop {
                // Check if container is running - keep retrying if not yet started
                // Don't fail immediately as the container may still be starting up
                if !self.is_running().await.unwrap_or(false) {
                    sleep(check_interval).await;
                    continue;
                }

                // Try to connect to PostgreSQL using pg_isready
                let user = self
                    .config
                    .env
                    .get("POSTGRES_USER")
                    .map(|s| s.as_str())
                    .unwrap_or("postgres");
                let db = self
                    .config
                    .env
                    .get("POSTGRES_DB")
                    .map(|s| s.as_str())
                    .unwrap_or("postgres");

                let check_cmd = vec!["pg_isready", "-h", "localhost", "-U", user, "-d", db];

                // Execute readiness check
                if let Ok(result) = self.exec(check_cmd).await {
                    // pg_isready returns 0 on success
                    if result.stdout.contains("accepting connections") {
                        return Ok(());
                    }
                }

                sleep(check_interval).await;
            }
        })
        .await
        .map_err(|_| {
            crate::template::TemplateError::InvalidConfig(format!(
                "PostgreSQL container {} failed to become ready within timeout",
                self.config().name
            ))
        })?
    }
}

/// Builder for PostgreSQL connection strings
pub struct PostgresConnectionString {
    host: String,
    port: u16,
    database: String,
    user: String,
    password: String,
}

impl PostgresConnectionString {
    /// Create from a PostgresTemplate
    pub fn from_template(template: &PostgresTemplate) -> Self {
        let config = template.config();
        let port = config.ports.first().map(|(h, _)| *h).unwrap_or(5432);

        Self {
            host: "localhost".to_string(),
            port,
            database: config
                .env
                .get("POSTGRES_DB")
                .cloned()
                .unwrap_or_else(|| "postgres".to_string()),
            user: config
                .env
                .get("POSTGRES_USER")
                .cloned()
                .unwrap_or_else(|| "postgres".to_string()),
            password: config
                .env
                .get("POSTGRES_PASSWORD")
                .cloned()
                .unwrap_or_else(|| "postgres".to_string()),
        }
    }

    /// Get the connection string in PostgreSQL URL format
    pub fn url(&self) -> String {
        format!(
            "postgresql://{}:{}@{}:{}/{}",
            self.user, self.password, self.host, self.port, self.database
        )
    }

    /// Get the connection string in key-value format
    pub fn key_value(&self) -> String {
        format!(
            "host={} port={} dbname={} user={} password={}",
            self.host, self.port, self.database, self.user, self.password
        )
    }
}

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

    #[test]
    fn test_postgres_template_basic() {
        let template = PostgresTemplate::new("test-postgres");
        assert_eq!(template.name(), "test-postgres");
        assert_eq!(template.config().image, "postgres");
        assert_eq!(template.config().tag, "15-alpine");
        assert_eq!(template.config().ports, vec![(5432, 5432)]);
    }

    #[test]
    fn test_postgres_template_custom_config() {
        let template = PostgresTemplate::new("test-postgres")
            .database("mydb")
            .user("myuser")
            .password("secret123")
            .port(15432);

        assert_eq!(
            template.config().env.get("POSTGRES_DB"),
            Some(&"mydb".to_string())
        );
        assert_eq!(
            template.config().env.get("POSTGRES_USER"),
            Some(&"myuser".to_string())
        );
        assert_eq!(
            template.config().env.get("POSTGRES_PASSWORD"),
            Some(&"secret123".to_string())
        );
        assert_eq!(template.config().ports, vec![(15432, 5432)]);
    }

    #[test]
    fn test_postgres_template_with_persistence() {
        let template = PostgresTemplate::new("test-postgres").with_persistence("postgres-data");

        assert_eq!(template.config().volumes.len(), 1);
        assert_eq!(template.config().volumes[0].source, "postgres-data");
        assert_eq!(
            template.config().volumes[0].target,
            "/var/lib/postgresql/data"
        );
    }

    #[test]
    fn test_postgres_template_with_init_scripts() {
        let template = PostgresTemplate::new("test-postgres").init_scripts("./init-scripts");

        assert_eq!(template.config().volumes.len(), 1);
        assert_eq!(template.config().volumes[0].source, "./init-scripts");
        assert_eq!(
            template.config().volumes[0].target,
            "/docker-entrypoint-initdb.d"
        );
        assert!(template.config().volumes[0].read_only);
    }

    #[test]
    fn test_postgres_connection_string() {
        let template = PostgresTemplate::new("test-postgres")
            .database("testdb")
            .user("testuser")
            .password("testpass")
            .port(15432);

        let conn = PostgresConnectionString::from_template(&template);

        assert_eq!(
            conn.url(),
            "postgresql://testuser:testpass@localhost:15432/testdb"
        );

        assert_eq!(
            conn.key_value(),
            "host=localhost port=15432 dbname=testdb user=testuser password=testpass"
        );
    }

    #[test]
    fn test_postgres_build_command() {
        let template = PostgresTemplate::new("test-postgres")
            .database("mydb")
            .port(15432);

        let cmd = template.build_command();
        let args = cmd.build_command_args();

        // Check that basic args are present
        assert!(args.contains(&"run".to_string()));
        assert!(args.contains(&"--name".to_string()));
        assert!(args.contains(&"test-postgres".to_string()));
        assert!(args.contains(&"--publish".to_string()));
        assert!(args.contains(&"15432:5432".to_string()));
        assert!(args.contains(&"--env".to_string()));
    }
}