docker_wrapper/template/redis/
basic.rs

1//! Basic Redis template for quick Redis 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::needless_borrows_for_generic_args)]
7#![allow(clippy::unnecessary_get_then_check)]
8
9use super::common::{
10    default_redis_health_check, redis_config_volume, redis_data_volume, DEFAULT_REDIS_IMAGE,
11    DEFAULT_REDIS_TAG, REDIS_STACK_IMAGE, REDIS_STACK_TAG,
12};
13use crate::template::{Template, TemplateConfig};
14use async_trait::async_trait;
15use std::collections::HashMap;
16
17/// Redis container template with sensible defaults
18pub struct RedisTemplate {
19    config: TemplateConfig,
20    use_redis_stack: bool,
21}
22
23impl RedisTemplate {
24    /// Create a new Redis template with default settings
25    pub fn new(name: impl Into<String>) -> Self {
26        let name = name.into();
27        let env = HashMap::new();
28
29        // Default Redis configuration
30        let config = TemplateConfig {
31            name: name.clone(),
32            image: DEFAULT_REDIS_IMAGE.to_string(),
33            tag: DEFAULT_REDIS_TAG.to_string(),
34            ports: vec![(6379, 6379)],
35            env,
36            volumes: Vec::new(),
37            network: None,
38            health_check: Some(default_redis_health_check()),
39            auto_remove: false,
40            memory_limit: None,
41            cpu_limit: None,
42            platform: None,
43        };
44
45        Self {
46            config,
47            use_redis_stack: false,
48        }
49    }
50
51    /// Set a custom Redis port
52    pub fn port(mut self, port: u16) -> Self {
53        self.config.ports = vec![(port, 6379)];
54        self
55    }
56
57    /// Set Redis password
58    pub fn password(mut self, password: impl Into<String>) -> Self {
59        // Redis uses command args for password, we'll handle this in build_command
60        self.config
61            .env
62            .insert("REDIS_PASSWORD".to_string(), password.into());
63        self
64    }
65
66    /// Enable persistence with a volume
67    pub fn with_persistence(mut self, volume_name: impl Into<String>) -> Self {
68        self.config.volumes.push(redis_data_volume(volume_name));
69        self
70    }
71
72    /// Set custom Redis configuration file
73    pub fn config_file(mut self, config_path: impl Into<String>) -> Self {
74        self.config.volumes.push(redis_config_volume(config_path));
75        self
76    }
77
78    /// Set memory limit for Redis
79    pub fn memory_limit(mut self, limit: impl Into<String>) -> Self {
80        self.config.memory_limit = Some(limit.into());
81        self
82    }
83
84    /// Enable Redis cluster mode
85    pub fn cluster_mode(mut self) -> Self {
86        self.config
87            .env
88            .insert("REDIS_CLUSTER".to_string(), "yes".to_string());
89        self
90    }
91
92    /// Set max memory policy
93    pub fn maxmemory_policy(mut self, policy: impl Into<String>) -> Self {
94        self.config
95            .env
96            .insert("REDIS_MAXMEMORY_POLICY".to_string(), policy.into());
97        self
98    }
99
100    /// Use a specific Redis version
101    pub fn version(mut self, version: impl Into<String>) -> Self {
102        self.config.tag = format!("{}-alpine", version.into());
103        self
104    }
105
106    /// Connect to a specific network
107    pub fn network(mut self, network: impl Into<String>) -> Self {
108        self.config.network = Some(network.into());
109        self
110    }
111
112    /// Enable auto-remove when stopped
113    pub fn auto_remove(mut self) -> Self {
114        self.config.auto_remove = true;
115        self
116    }
117
118    /// Use Redis Stack image instead of basic Redis
119    pub fn with_redis_stack(mut self) -> Self {
120        self.use_redis_stack = true;
121        self
122    }
123
124    /// Use a custom image and tag
125    pub fn custom_image(mut self, image: impl Into<String>, tag: impl Into<String>) -> Self {
126        self.config.image = image.into();
127        self.config.tag = tag.into();
128        self
129    }
130
131    /// Set the platform for the container (e.g., "linux/arm64", "linux/amd64")
132    pub fn platform(mut self, platform: impl Into<String>) -> Self {
133        self.config.platform = Some(platform.into());
134        self
135    }
136}
137
138#[async_trait]
139impl Template for RedisTemplate {
140    fn name(&self) -> &str {
141        &self.config.name
142    }
143
144    fn config(&self) -> &TemplateConfig {
145        &self.config
146    }
147
148    fn config_mut(&mut self) -> &mut TemplateConfig {
149        &mut self.config
150    }
151
152    fn build_command(&self) -> crate::RunCommand {
153        let config = self.config();
154
155        // Choose image based on Redis Stack preference
156        let image_tag = if self.use_redis_stack {
157            format!("{REDIS_STACK_IMAGE}:{REDIS_STACK_TAG}")
158        } else {
159            format!("{}:{}", config.image, config.tag)
160        };
161
162        let mut cmd = crate::RunCommand::new(image_tag)
163            .name(&config.name)
164            .detach();
165
166        // Add port mappings
167        for (host, container) in &config.ports {
168            cmd = cmd.port(*host, *container);
169        }
170
171        // Add volume mounts
172        for mount in &config.volumes {
173            if mount.read_only {
174                cmd = cmd.volume_ro(&mount.source, &mount.target);
175            } else {
176                cmd = cmd.volume(&mount.source, &mount.target);
177            }
178        }
179
180        // Add network
181        if let Some(network) = &config.network {
182            cmd = cmd.network(network);
183        }
184
185        // Add health check
186        if let Some(health) = &config.health_check {
187            cmd = cmd
188                .health_cmd(&health.test.join(" "))
189                .health_interval(&health.interval)
190                .health_timeout(&health.timeout)
191                .health_retries(health.retries)
192                .health_start_period(&health.start_period);
193        }
194
195        // Add resource limits
196        if let Some(memory) = &config.memory_limit {
197            cmd = cmd.memory(memory);
198        }
199
200        if let Some(cpu) = &config.cpu_limit {
201            cmd = cmd.cpus(cpu);
202        }
203
204        // Auto-remove
205        if config.auto_remove {
206            cmd = cmd.remove();
207        }
208
209        // Handle Redis-specific command args
210        if let Some(password) = config.env.get("REDIS_PASSWORD") {
211            if self.use_redis_stack {
212                // For Redis Stack, use environment variable instead of command override
213                cmd = cmd.env("REDIS_ARGS", format!("--requirepass {password}"));
214            } else {
215                // For basic Redis, override entrypoint to bypass docker-entrypoint.sh and directly run redis-server
216                cmd = cmd.entrypoint("redis-server").cmd(vec![
217                    "--requirepass".to_string(),
218                    password.clone(),
219                    "--protected-mode".to_string(),
220                    "yes".to_string(),
221                ]);
222            }
223        }
224
225        // If custom config file is mounted
226        let has_config = config
227            .volumes
228            .iter()
229            .any(|v| v.target == "/usr/local/etc/redis/redis.conf");
230        if has_config && config.env.get("REDIS_PASSWORD").is_none() {
231            cmd = cmd.cmd(vec![
232                "redis-server".to_string(),
233                "/usr/local/etc/redis/redis.conf".to_string(),
234            ]);
235        }
236
237        cmd
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244    use crate::DockerCommand;
245
246    #[test]
247    fn test_redis_template_basic() {
248        let template = RedisTemplate::new("test-redis");
249        assert_eq!(template.name(), "test-redis");
250        assert_eq!(template.config().image, "redis");
251        assert_eq!(template.config().tag, "7-alpine");
252        assert_eq!(template.config().ports, vec![(6379, 6379)]);
253    }
254
255    #[test]
256    fn test_redis_template_with_password() {
257        let template = RedisTemplate::new("test-redis").password("secret123");
258
259        assert_eq!(
260            template.config().env.get("REDIS_PASSWORD"),
261            Some(&"secret123".to_string())
262        );
263    }
264
265    #[test]
266    fn test_redis_template_with_persistence() {
267        let template = RedisTemplate::new("test-redis").with_persistence("redis-data");
268
269        assert_eq!(template.config().volumes.len(), 1);
270        assert_eq!(template.config().volumes[0].source, "redis-data");
271        assert_eq!(template.config().volumes[0].target, "/data");
272    }
273
274    #[test]
275    fn test_redis_template_custom_port() {
276        let template = RedisTemplate::new("test-redis").port(16379);
277
278        assert_eq!(template.config().ports, vec![(16379, 6379)]);
279    }
280
281    #[test]
282    fn test_redis_build_command() {
283        let template = RedisTemplate::new("test-redis")
284            .password("mypass")
285            .port(16379);
286
287        let cmd = template.build_command();
288        let args = cmd.build_command_args();
289
290        // Check that basic args are present
291        assert!(args.contains(&"run".to_string()));
292        assert!(args.contains(&"--name".to_string()));
293        assert!(args.contains(&"test-redis".to_string()));
294        assert!(args.contains(&"--publish".to_string()));
295        assert!(args.contains(&"16379:6379".to_string()));
296    }
297}