1use crate::discovery::read_source;
20use crate::paths::{ProjectPathsError, did_you_mean};
21use std::collections::{BTreeMap, HashMap};
22use std::path::{Path, PathBuf};
23
24#[derive(Debug, Clone, Default, PartialEq, Eq)]
26pub struct ContainerDeploy {
27 pub image: BTreeMap<String, String>,
30}
31
32pub type ContainerDeployConfig = BTreeMap<String, ContainerDeploy>;
34
35pub const DEPLOY_ENTRY_KEYS: &[&str] = &["image"];
37
38pub const REGISTRY: &str = "registry.cloudflare.com";
40
41fn bad(table: &'static str, capability: &str, reason: String) -> ProjectPathsError {
42 ProjectPathsError::BadContainers {
43 table,
44 capability: capability.to_string(),
45 reason,
46 }
47}
48
49pub fn is_image_reference(image: &str) -> bool {
54 let Some(rest) = image
55 .strip_prefix(REGISTRY)
56 .and_then(|r| r.strip_prefix('/'))
57 else {
58 return false;
59 };
60 let Some((path, digest)) = rest.split_once("@sha256:") else {
61 return false;
62 };
63 digest.len() == 64
64 && digest
65 .bytes()
66 .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
67 && path.split('/').count() >= 2
68 && path.split('/').all(|segment| {
69 !segment.is_empty()
70 && segment.bytes().all(|b| {
71 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
72 })
73 })
74}
75
76pub fn deploy_containers_from(
78 deploy: &toml::Table,
79) -> Result<ContainerDeployConfig, ProjectPathsError> {
80 let mut out = ContainerDeployConfig::new();
81 let Some(value) = deploy.get("containers") else {
82 return Ok(out);
83 };
84 let table = "deploy.containers";
85 let all = value.as_table().ok_or_else(|| {
86 bad(
87 "deploy",
88 "…",
89 "`containers` must be a table of capabilities, like `[deploy.containers.Renderer]`"
90 .to_string(),
91 )
92 })?;
93 for (capability, value) in all {
94 let entry = value
95 .as_table()
96 .ok_or_else(|| bad(table, capability, "must be a table".to_string()))?;
97 for key in entry.keys() {
98 if !DEPLOY_ENTRY_KEYS.contains(&key.as_str()) {
99 let hint = did_you_mean(key, DEPLOY_ENTRY_KEYS.iter().copied())
100 .map(|k| format!(" — did you mean `{k}`?"))
101 .unwrap_or_default();
102 return Err(bad(
103 table,
104 capability,
105 format!("has no key named `{key}`{hint} (its key is `image`)"),
106 ));
107 }
108 }
109 let Some(image) = entry.get("image") else {
110 return Err(bad(
111 table,
112 capability,
113 "needs an `image`, like `image = { production = \"registry.cloudflare.com/<ACCOUNT_ID>/renderer@sha256:<DIGEST>\" }`".to_string(),
114 ));
115 };
116 let images = image.as_table().ok_or_else(|| {
117 bad(
118 table,
119 capability,
120 "`image` must be a table of environment to image reference, like `image = { production = \"registry.cloudflare.com/<ACCOUNT_ID>/renderer@sha256:<DIGEST>\" }`".to_string(),
121 )
122 })?;
123 let mut deploy = ContainerDeploy::default();
124 for (environment, reference) in images {
125 let reference = reference
126 .as_str()
127 .filter(|r| is_image_reference(r))
128 .ok_or_else(|| {
129 bad(
130 table,
131 capability,
132 format!(
133 "`image.{environment}` must be an image in Cloudflare's registry, named by digest: `{REGISTRY}/<ACCOUNT_ID>/<REPOSITORY>@sha256:<64 hex digits>` (another registry, or a tag, is not supported for this kind of container)"
134 ),
135 )
136 })?;
137 deploy
138 .image
139 .insert(environment.clone(), reference.to_string());
140 }
141 if deploy.image.is_empty() {
142 return Err(bad(
143 table,
144 capability,
145 "`image` names no environment".to_string(),
146 ));
147 }
148 out.insert(capability.clone(), deploy);
149 }
150 Ok(out)
151}
152
153pub fn try_read_containers_deploy_with(
156 project_root: &Path,
157 overlay: &HashMap<PathBuf, String>,
158) -> Result<ContainerDeployConfig, ProjectPathsError> {
159 let Ok(content) = read_source(&project_root.join("bynk.toml"), overlay) else {
160 return Ok(ContainerDeployConfig::new());
161 };
162 let doc = content
163 .parse::<toml::Table>()
164 .map_err(|_| ProjectPathsError::Malformed)?;
165 match doc.get("deploy").and_then(|v| v.as_table()) {
166 Some(t) => deploy_containers_from(t),
167 None => Ok(ContainerDeployConfig::new()),
168 }
169}
170
171pub fn try_read_containers_deploy(
173 project_root: &Path,
174) -> Result<ContainerDeployConfig, ProjectPathsError> {
175 let path = project_root.join("bynk.toml");
176 let overlay = match std::fs::read_to_string(&path) {
177 Ok(text) => HashMap::from([(path, text)]),
178 Err(_) => HashMap::new(),
179 };
180 try_read_containers_deploy_with(project_root, &overlay)
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 const DIGEST: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
188
189 fn read(text: &str) -> Result<ContainerDeployConfig, ProjectPathsError> {
190 let doc: toml::Table = text.parse().unwrap();
191 deploy_containers_from(doc["deploy"].as_table().unwrap())
192 }
193
194 #[test]
195 fn an_image_is_cloudflares_registry_by_digest() {
196 let good = format!("registry.cloudflare.com/0123abcd/renderer@sha256:{DIGEST}");
197 assert!(is_image_reference(&good));
198 assert!(is_image_reference(&format!(
199 "registry.cloudflare.com/acct/team/render-er.v2@sha256:{DIGEST}"
200 )));
201 for bad in [
202 format!("docker.io/library/nginx@sha256:{DIGEST}"),
203 "registry.cloudflare.com/acct/renderer:latest".to_string(),
204 "registry.cloudflare.com/acct/renderer@sha256:abc".to_string(),
205 format!("registry.cloudflare.com/renderer@sha256:{DIGEST}"),
206 format!("registry.cloudflare.com/acct/Renderer@sha256:{DIGEST}"),
207 format!("registry.cloudflare.com/acct/ren derer@sha256:{DIGEST}"),
208 format!("registry.cloudflare.com//renderer@sha256:{DIGEST}"),
209 format!(
210 "registry.cloudflare.com/acct/renderer@sha256:{}",
211 DIGEST.to_uppercase()
212 ),
213 ] {
214 assert!(!is_image_reference(&bad), "{bad}");
215 }
216 }
217
218 #[test]
219 fn an_entry_names_an_image_per_environment() {
220 let text = format!(
221 "[deploy.containers.Renderer]\nimage = {{ production = \"registry.cloudflare.com/a1/r@sha256:{DIGEST}\" }}\n"
222 );
223 let config = read(&text).unwrap();
224 assert_eq!(
225 config["Renderer"].image["production"],
226 format!("registry.cloudflare.com/a1/r@sha256:{DIGEST}")
227 );
228 assert!(read("[deploy]\n").unwrap().is_empty());
229 }
230
231 #[test]
232 fn a_malformed_entry_is_refused_with_its_table_and_capability() {
233 for (text, needle) in [
234 (
235 "[deploy.containers.R]\nimagee = {}\n",
236 "did you mean `image`",
237 ),
238 ("[deploy.containers.R]\n", "needs an `image`"),
239 ("[deploy.containers.R]\nimage = \"x\"\n", "must be a table"),
240 (
241 "[deploy.containers.R]\nimage = {}\n",
242 "names no environment",
243 ),
244 (
245 "[deploy.containers.R]\nimage = { production = \"docker.io/x/y:1\" }\n",
246 "Cloudflare's registry",
247 ),
248 ] {
249 let err = read(text).unwrap_err().to_string();
250 assert!(err.contains("[deploy.containers.R]"), "{err}");
251 assert!(err.contains(needle), "{needle}: {err}");
252 }
253 }
254}