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
//!
//! The container module contains all the basic data types that make up a container.
//!
//! Containers can then be run through [`clients`](crate::client::Client).
//!
//! See [Container] for further information on containers.
//!

use std::{fmt::Display, str::FromStr, time::Duration};

use lazy_static::lazy_static;
use rand::{distributions::Alphanumeric, Rng};
use regex::Regex;

use crate::error::{ContainerResult, ContainersError};

lazy_static! {
    static ref IMAGE_REGEX: Regex = Regex::new("([0-9a-zA-Z./]+)(:([0-9a-zA-Z.]+))?").unwrap();
}

pub trait TryIntoContainer {
    fn try_into_container(self) -> ContainerResult<Container>;
}

pub trait IntoContainer {
    fn into_container(self) -> Container;
}

impl<T: TryIntoContainer> IntoContainer for T {
    fn into_container(self) -> Container {
        self.try_into_container().unwrap()
    }
}

impl IntoContainer for Container {
    fn into_container(self) -> Container {
        self
    }
}

#[derive(Clone)]
pub struct HealthCheck {
    pub command: String,
    pub retries: Option<u32>,
    pub interval: Option<Duration>,
    pub start_period: Option<Duration>,
    pub timeout: Option<Duration>,
}

impl HealthCheck {
    pub fn new(command: &str) -> Self {
        Self {
            command: command.into(),
            retries: None,
            interval: None,
            start_period: None,
            timeout: None,
        }
    }

    pub fn retries(mut self, retries: u32) -> Self {
        self.retries = Some(retries);
        self
    }

    pub fn interval(mut self, interval: Duration) -> Self {
        self.interval = Some(interval);
        self
    }

    pub fn start_period(mut self, start_period: Duration) -> Self {
        self.start_period = Some(start_period);
        self
    }

    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
}

///
/// A wait strategy can be used to wait for a cotnainer to be ready.
///
#[derive(Clone, Debug)]
pub enum WaitStrategy {
    ///
    /// Waits for a log message to appear.
    ///
    LogMessage { pattern: Regex },
    ///
    /// Waits for the container to be healty.
    ///
    HealthCheck,
    ///
    /// Wait for some amount of time.
    ///
    WaitTime { duration: Duration },
}

#[derive(Clone)]
pub struct Network {
    // TODO
}

#[derive(Clone, PartialEq, Eq)]
pub struct Port {
    pub number: String,
}

impl<T> From<T> for Port
where
    T: ToString,
{
    fn from(value: T) -> Self {
        Self {
            number: value.to_string(),
        }
    }
}

#[derive(Clone)]
pub struct PortMapping {
    pub source: Port,
    pub target: Port,
}

#[derive(Clone)]
pub struct EnvVar {
    pub key: String,
    pub value: String,
}

impl EnvVar {
    pub fn new(key: String, value: String) -> Self {
        Self { key, value }
    }
}

impl<K, V> From<(K, V)> for EnvVar
where
    K: Into<String>,
    V: Into<String>,
{
    fn from(value: (K, V)) -> Self {
        EnvVar::new(value.0.into(), value.1.into())
    }
}

#[derive(Clone)]
pub struct Image {
    pub name: String,
    pub tag: String,
}

impl Display for Image {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.name, self.tag)
    }
}

impl Image {
    pub fn from_name_and_tag(name: &str, tag: &str) -> Self {
        Image {
            name: name.to_string(),
            tag: tag.to_string(),
        }
    }
}

impl FromStr for Image {
    type Err = ContainersError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let caps = IMAGE_REGEX.captures(s);

        if let Some(cap) = caps {
            Ok(Self::from_name_and_tag(
                cap.get(1).unwrap().as_str(),
                cap.get(3).map(|m| m.as_str()).unwrap_or("latest"),
            ))
        } else {
            Err(ContainersError::InvalidImageName {
                name: s.to_string(),
            })
        }
    }
}

impl From<Image> for String {
    fn from(i: Image) -> Self {
        format!("{}:{}", i.name, i.tag)
    }
}

impl From<&Image> for String {
    fn from(i: &Image) -> Self {
        format!("{}:{}", i.name, i.tag)
    }
}

#[derive(Clone)]
pub enum Volume {
    Mount {
        host_path: String,
        mount_point: String,
    },
    Named {
        name: String,
        mount_point: String,
    },
}

///
/// A container makes up the schedulable unit of this crate.
///
/// You can define an [Image] for it to be used and define port mappings and environment variables on it for example.
///
#[derive(Clone)]
pub struct Container {
    pub name: String,
    pub image: Image,
    pub command: Vec<String>,
    pub network: Option<Network>,
    pub volumes: Vec<Volume>,
    pub port_mappings: Vec<PortMapping>,
    pub env_vars: Vec<EnvVar>,
    pub health_check: Option<HealthCheck>,
    pub wait_strategy: Option<WaitStrategy>,
    pub additional_wait_period: Duration,
}

impl Container {
    fn gen_hash() -> String {
        rand::thread_rng()
            .sample_iter(&Alphanumeric)
            .take(8)
            .map(char::from)
            .collect()
    }

    ///
    /// Creates a new container from and [Image]
    ///
    pub fn from_image(image: Image) -> Self {
        Container {
            name: format!("contain-rs-{}", Self::gen_hash()),
            image,
            command: Vec::new(),
            network: None,
            port_mappings: Vec::new(),
            env_vars: Vec::new(),
            volumes: Vec::new(),
            health_check: None,
            wait_strategy: None,
            additional_wait_period: Duration::from_secs(0),
        }
    }

    ///
    /// Define a specific name for the container.
    ///
    /// In case no explicit name is defined contain-rs will generate one as the name is being used by the [crate::client::Client] for interaction.
    ///
    pub fn name(&mut self, name: &str) -> &mut Self {
        self.name = name.into();
        self
    }

    ///
    /// Define an explicit command to run in the container.
    ///
    pub fn command(&mut self, command: Vec<String>) -> &mut Self {
        self.command = command;
        self
    }

    pub fn arg<T: Into<String>>(&mut self, arg: T) -> &mut Self {
        self.command.push(arg.into());
        self
    }

    pub fn map_ports<T, T2>(&mut self, ports: &[(T, T2)]) -> &mut Self
    where
        T: Into<Port> + Clone,
        T2: Into<Port> + Clone,
    {
        self.port_mappings = ports
            .iter()
            .cloned()
            .map(|mapping| PortMapping {
                source: mapping.0.into(),
                target: mapping.1.into(),
            })
            .collect();

        self
    }

    pub fn volume(&mut self, name: &str, mount_point: &str) -> &mut Self {
        self.volumes.push(Volume::Named {
            name: name.to_string(),
            mount_point: mount_point.to_string(),
        });

        self
    }

    pub fn mount(&mut self, host_path: &str, mount_point: &str) -> &mut Self {
        self.volumes.push(Volume::Mount {
            host_path: host_path.to_string(),
            mount_point: mount_point.to_string(),
        });

        self
    }

    ///
    /// Map a port from `source` on the host to `target` in the container.
    ///
    pub fn map_port(&mut self, source: impl Into<Port>, target: impl Into<Port>) -> &mut Self {
        self.port_mappings.push(PortMapping {
            source: source.into(),
            target: target.into(),
        });
        self
    }

    ///
    /// Define an environment variable for the container.
    ///
    pub fn env_var<T: Into<String>>(&mut self, name: T, value: T) -> &mut Self {
        self.env_vars.push((name, value).into());
        self
    }

    ///
    /// Add a [WaitStrategy] to be used when running the container.
    ///
    pub fn wait_for(&mut self, strategy: WaitStrategy) -> &mut Self {
        self.wait_strategy = Some(strategy);
        self
    }

    ///
    /// Add some additional wait time for concidering the container healthy.
    ///
    /// Contain-rs waits this additional time after the [WaitStrategy] has been concidered successful.
    ///
    pub fn additional_wait_period(&mut self, period: Duration) -> &mut Self {
        self.additional_wait_period = period;
        self
    }

    ///
    /// Add an arbitrary healthcheck to the container.
    ///
    /// Some images may define healthchecks already, yet you can use this one to define one yourself explicitly.
    ///
    pub fn health_check(&mut self, health_check: HealthCheck) -> &mut Self {
        self.health_check = Some(health_check);
        self
    }
}

impl From<Image> for Container {
    fn from(image: Image) -> Self {
        Container::from_image(image)
    }
}