docker_wrapper/template/redis/
basic.rs1#![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
17pub struct RedisTemplate {
19 config: TemplateConfig,
20 use_redis_stack: bool,
21}
22
23impl RedisTemplate {
24 pub fn new(name: impl Into<String>) -> Self {
26 let name = name.into();
27 let env = HashMap::new();
28
29 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 pub fn port(mut self, port: u16) -> Self {
53 self.config.ports = vec![(port, 6379)];
54 self
55 }
56
57 pub fn password(mut self, password: impl Into<String>) -> Self {
59 self.config
61 .env
62 .insert("REDIS_PASSWORD".to_string(), password.into());
63 self
64 }
65
66 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 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 pub fn memory_limit(mut self, limit: impl Into<String>) -> Self {
80 self.config.memory_limit = Some(limit.into());
81 self
82 }
83
84 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 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 pub fn version(mut self, version: impl Into<String>) -> Self {
102 self.config.tag = format!("{}-alpine", version.into());
103 self
104 }
105
106 pub fn network(mut self, network: impl Into<String>) -> Self {
108 self.config.network = Some(network.into());
109 self
110 }
111
112 pub fn auto_remove(mut self) -> Self {
114 self.config.auto_remove = true;
115 self
116 }
117
118 pub fn with_redis_stack(mut self) -> Self {
120 self.use_redis_stack = true;
121 self
122 }
123
124 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 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 async fn wait_for_ready(&self) -> crate::template::Result<()> {
153 use std::time::Duration;
154 use tokio::time::{sleep, timeout};
155
156 let wait_timeout = Duration::from_secs(30);
158 let check_interval = Duration::from_millis(500);
159
160 timeout(wait_timeout, async {
161 loop {
162 if !self.is_running().await? {
164 return Err(crate::template::TemplateError::NotRunning(
165 self.config().name.clone(),
166 ));
167 }
168
169 let password = self.config.env.get("REDIS_PASSWORD");
171 let mut ping_cmd = vec!["redis-cli", "-h", "localhost"];
172
173 let auth_args;
175 if let Some(pass) = password {
176 auth_args = vec!["-a", pass.as_str()];
177 ping_cmd.extend(&auth_args);
178 }
179
180 ping_cmd.push("ping");
181
182 if let Ok(result) = self.exec(ping_cmd).await {
184 if result.stdout.trim() == "PONG" {
185 return Ok(());
186 }
187 }
188
189 sleep(check_interval).await;
190 }
191 })
192 .await
193 .map_err(|_| {
194 crate::template::TemplateError::InvalidConfig(format!(
195 "Redis container {} failed to become ready within timeout",
196 self.config().name
197 ))
198 })?
199 }
200
201 fn build_command(&self) -> crate::RunCommand {
202 let config = self.config();
203
204 let image_tag = if self.use_redis_stack {
206 format!("{REDIS_STACK_IMAGE}:{REDIS_STACK_TAG}")
207 } else {
208 format!("{}:{}", config.image, config.tag)
209 };
210
211 let mut cmd = crate::RunCommand::new(image_tag)
212 .name(&config.name)
213 .detach();
214
215 for (host, container) in &config.ports {
217 cmd = cmd.port(*host, *container);
218 }
219
220 for mount in &config.volumes {
222 if mount.read_only {
223 cmd = cmd.volume_ro(&mount.source, &mount.target);
224 } else {
225 cmd = cmd.volume(&mount.source, &mount.target);
226 }
227 }
228
229 if let Some(network) = &config.network {
231 cmd = cmd.network(network);
232 }
233
234 if let Some(health) = &config.health_check {
236 cmd = cmd
237 .health_cmd(&health.test.join(" "))
238 .health_interval(&health.interval)
239 .health_timeout(&health.timeout)
240 .health_retries(health.retries)
241 .health_start_period(&health.start_period);
242 }
243
244 if let Some(memory) = &config.memory_limit {
246 cmd = cmd.memory(memory);
247 }
248
249 if let Some(cpu) = &config.cpu_limit {
250 cmd = cmd.cpus(cpu);
251 }
252
253 if config.auto_remove {
255 cmd = cmd.remove();
256 }
257
258 if let Some(password) = config.env.get("REDIS_PASSWORD") {
260 if self.use_redis_stack {
261 cmd = cmd.env("REDIS_ARGS", format!("--requirepass {password}"));
263 } else {
264 cmd = cmd.entrypoint("redis-server").cmd(vec![
266 "--requirepass".to_string(),
267 password.clone(),
268 "--protected-mode".to_string(),
269 "yes".to_string(),
270 ]);
271 }
272 }
273
274 let has_config = config
276 .volumes
277 .iter()
278 .any(|v| v.target == "/usr/local/etc/redis/redis.conf");
279 if has_config && config.env.get("REDIS_PASSWORD").is_none() {
280 cmd = cmd.cmd(vec![
281 "redis-server".to_string(),
282 "/usr/local/etc/redis/redis.conf".to_string(),
283 ]);
284 }
285
286 cmd
287 }
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293 use crate::DockerCommand;
294
295 #[test]
296 fn test_redis_template_basic() {
297 let template = RedisTemplate::new("test-redis");
298 assert_eq!(template.name(), "test-redis");
299 assert_eq!(template.config().image, "redis");
300 assert_eq!(template.config().tag, "7-alpine");
301 assert_eq!(template.config().ports, vec![(6379, 6379)]);
302 }
303
304 #[test]
305 fn test_redis_template_with_password() {
306 let template = RedisTemplate::new("test-redis").password("secret123");
307
308 assert_eq!(
309 template.config().env.get("REDIS_PASSWORD"),
310 Some(&"secret123".to_string())
311 );
312 }
313
314 #[test]
315 fn test_redis_template_with_persistence() {
316 let template = RedisTemplate::new("test-redis").with_persistence("redis-data");
317
318 assert_eq!(template.config().volumes.len(), 1);
319 assert_eq!(template.config().volumes[0].source, "redis-data");
320 assert_eq!(template.config().volumes[0].target, "/data");
321 }
322
323 #[test]
324 fn test_redis_template_custom_port() {
325 let template = RedisTemplate::new("test-redis").port(16379);
326
327 assert_eq!(template.config().ports, vec![(16379, 6379)]);
328 }
329
330 #[test]
331 fn test_redis_build_command() {
332 let template = RedisTemplate::new("test-redis")
333 .password("mypass")
334 .port(16379);
335
336 let cmd = template.build_command();
337 let args = cmd.build_command_args();
338
339 assert!(args.contains(&"run".to_string()));
341 assert!(args.contains(&"--name".to_string()));
342 assert!(args.contains(&"test-redis".to_string()));
343 assert!(args.contains(&"--publish".to_string()));
344 assert!(args.contains(&"16379:6379".to_string()));
345 }
346}