1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3pub enum DeployTarget {
4 Docker,
5 Standalone,
6 Serverless,
7}
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum DeployError {
10 InvalidName,
11 InvalidVersion,
12 MissingEnvironment,
13 Capacity,
14}
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct DeploySpec {
17 pub name: String,
18 pub version: String,
19 pub target: DeployTarget,
20 pub required_env: Vec<String>,
21}
22#[derive(Debug, Clone, Default)]
23pub struct DeployPlan {
24 specs: Vec<DeploySpec>,
25 capacity: usize,
26}
27impl DeployPlan {
28 pub fn new(capacity: usize) -> Self {
29 Self {
30 specs: Vec::new(),
31 capacity,
32 }
33 }
34 pub fn add(
35 mut self,
36 name: impl Into<String>,
37 version: impl Into<String>,
38 target: DeployTarget,
39 required_env: impl Into<Vec<String>>,
40 ) -> Result<Self, DeployError> {
41 let name = name.into();
42 let version = version.into();
43 if name.is_empty()
44 || name.len() > 128
45 || name.chars().any(|c| c.is_control() || c.is_whitespace())
46 {
47 return Err(DeployError::InvalidName);
48 }
49 if version.is_empty()
50 || version.len() > 64
51 || version.chars().any(|c| c.is_control() || c.is_whitespace())
52 {
53 return Err(DeployError::InvalidVersion);
54 }
55 if self.specs.len() >= self.capacity {
56 return Err(DeployError::Capacity);
57 }
58 let mut env = required_env.into();
59 env.sort();
60 env.dedup();
61 self.specs.push(DeploySpec {
62 name,
63 version,
64 target,
65 required_env: env,
66 });
67 self.specs.sort_by(|a, b| a.name.cmp(&b.name));
68 Ok(self)
69 }
70 pub fn validate_environment(
71 &self,
72 present: impl IntoIterator<Item = String>,
73 ) -> Result<(), DeployError> {
74 let present: std::collections::BTreeSet<_> = present.into_iter().collect();
75 if self
76 .specs
77 .iter()
78 .any(|s| s.required_env.iter().any(|e| !present.contains(e)))
79 {
80 Err(DeployError::MissingEnvironment)
81 } else {
82 Ok(())
83 }
84 }
85 pub fn snapshot(&self) -> &[DeploySpec] {
86 &self.specs
87 }
88}
89#[cfg(test)]
90mod tests {
91 use super::*;
92 #[test]
93 fn sorts_specs_and_validates_environment() {
94 let p = DeployPlan::new(2)
95 .add("web", "1.0", DeployTarget::Docker, vec!["PORT".into()])
96 .unwrap()
97 .add("api", "1.0", DeployTarget::Standalone, Vec::new())
98 .unwrap();
99 assert_eq!(p.snapshot()[0].name, "api");
100 assert!(p.validate_environment(vec!["PORT".into()]).is_ok())
101 }
102 #[test]
103 fn rejects_bad_metadata_missing_environment_and_capacity() {
104 assert!(DeployPlan::new(1)
105 .add("bad name", "1", DeployTarget::Docker, Vec::new())
106 .is_err());
107 let p = DeployPlan::new(1)
108 .add("app", "1", DeployTarget::Docker, vec!["SECRET".into()])
109 .unwrap();
110 assert!(p.validate_environment(Vec::<String>::new()).is_err());
111 assert!(p
112 .add("other", "1", DeployTarget::Docker, Vec::new())
113 .is_err())
114 }
115}