1use crate::discovery::read_source;
30use crate::paths::{ProjectPathsError, did_you_mean};
31use std::collections::{BTreeMap, BTreeSet, HashMap};
32use std::path::{Path, PathBuf};
33
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub struct WorkerGroup {
37 pub contexts: Vec<String>,
40 pub name: Option<String>,
42 pub routes: Vec<String>,
44 pub custom_domains: Vec<String>,
46}
47
48impl WorkerGroup {
49 pub fn script_name<'a>(&'a self, key: &'a str) -> &'a str {
51 self.name.as_deref().unwrap_or(key)
52 }
53}
54
55pub type WorkerGroups = BTreeMap<String, WorkerGroup>;
57
58pub const GROUP_KEYS: &[&str] = &["contexts", "name", "routes", "custom_domains"];
60
61fn bad(key: &str, reason: String) -> ProjectPathsError {
62 ProjectPathsError::BadWorkerGroup {
63 key: key.to_string(),
64 reason,
65 }
66}
67
68pub fn is_worker_name(name: &str) -> bool {
73 (1..=63).contains(&name.len())
74 && name
75 .bytes()
76 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
77 && !name.starts_with('-')
78 && !name.ends_with('-')
79}
80
81pub fn is_qualified_name(name: &str) -> bool {
84 !name.is_empty()
85 && name.split('.').all(|seg| {
86 let mut bytes = seg.bytes();
87 bytes
88 .next()
89 .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
90 && bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
91 })
92}
93
94fn is_hostname(host: &str) -> bool {
97 host.len() <= 253
98 && host.split('.').count() >= 2
99 && host.split('.').all(|label| {
100 (1..=63).contains(&label.len())
101 && label
102 .bytes()
103 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
104 && !label.starts_with('-')
105 && !label.ends_with('-')
106 })
107}
108
109fn is_route_pattern(route: &str) -> bool {
112 let Some((host, _)) = route.split_once('/') else {
113 return false;
114 };
115 let host = host.strip_prefix("*.").unwrap_or(host);
116 is_hostname(host) && !route.bytes().any(|b| b.is_ascii_whitespace())
117}
118
119fn string_list(
120 key: &str,
121 field: &str,
122 value: &toml::Value,
123) -> Result<Vec<String>, ProjectPathsError> {
124 let shape = || {
125 bad(
126 key,
127 format!("`{field}` must be a list of strings, like `{field} = [\"…\"]`"),
128 )
129 };
130 let list = value.as_array().ok_or_else(shape)?;
131 list.iter()
132 .map(|v| v.as_str().map(str::to_string).ok_or_else(shape))
133 .collect()
134}
135
136fn first_duplicate(items: &[String]) -> Option<&str> {
138 let mut seen = BTreeSet::new();
139 items
140 .iter()
141 .find(|item| !seen.insert(item.as_str()))
142 .map(String::as_str)
143}
144
145fn group_from(key: &str, value: &toml::Value) -> Result<WorkerGroup, ProjectPathsError> {
147 let entry = value
148 .as_table()
149 .ok_or_else(|| bad(key, "must be a table".to_string()))?;
150 if !is_worker_name(key) {
151 return Err(bad(
152 key,
153 "is not a valid Worker name: 1 to 63 lowercase letters, digits or `-`, not starting or ending with `-`"
154 .to_string(),
155 ));
156 }
157 for k in entry.keys() {
158 if !GROUP_KEYS.contains(&k.as_str()) {
159 let hint = did_you_mean(k, GROUP_KEYS.iter().copied())
160 .map(|h| format!(" — did you mean `{h}`?"))
161 .unwrap_or_default();
162 return Err(bad(
163 key,
164 format!(
165 "has no key named `{k}`{hint} (its keys are `contexts`, `name`, `routes` and `custom_domains`)"
166 ),
167 ));
168 }
169 }
170 let Some(contexts) = entry.get("contexts") else {
171 return Err(bad(
172 key,
173 "needs `contexts`, like `contexts = [\"shop.orders\", \"shop.pricing\"]`".to_string(),
174 ));
175 };
176 let contexts = string_list(key, "contexts", contexts)?;
177 if contexts.is_empty() {
178 return Err(bad(
179 key,
180 "bynk.deploy.empty_group: `contexts` names no context".to_string(),
181 ));
182 }
183 if let Some(bad_name) = contexts.iter().find(|c| !is_qualified_name(c)) {
184 return Err(bad(
185 key,
186 format!(
187 "`contexts` holds `{bad_name}`, which is not a qualified context name like `shop.orders` (globs are not supported)"
188 ),
189 ));
190 }
191 if let Some(dup) = first_duplicate(&contexts) {
192 return Err(bad(key, format!("lists context `{dup}` twice")));
193 }
194 let name = match entry.get("name") {
195 None => None,
196 Some(v) => {
197 let n = v.as_str().filter(|n| is_worker_name(n)).ok_or_else(|| {
198 bad(
199 key,
200 "`name` must be a Worker name: 1 to 63 lowercase letters, digits or `-`, not starting or ending with `-`"
201 .to_string(),
202 )
203 })?;
204 Some(n.to_string())
205 }
206 };
207 let routes = match entry.get("routes") {
208 None => Vec::new(),
209 Some(v) => string_list(key, "routes", v)?,
210 };
211 if let Some(r) = routes.iter().find(|r| !is_route_pattern(r)) {
212 return Err(bad(
213 key,
214 format!(
215 "`routes` holds `{r}`, which is not a route pattern like `pay.example.com/*` (a host, then `/` and a path, with no scheme)"
216 ),
217 ));
218 }
219 let custom_domains = match entry.get("custom_domains") {
220 None => Vec::new(),
221 Some(v) => string_list(key, "custom_domains", v)?,
222 };
223 if let Some(d) = custom_domains.iter().find(|d| !is_hostname(d)) {
224 return Err(bad(
225 key,
226 format!(
227 "`custom_domains` holds `{d}`, which is not a hostname like `pay.example.com` (no scheme, path or wildcard)"
228 ),
229 ));
230 }
231 Ok(WorkerGroup {
232 contexts,
233 name,
234 routes,
235 custom_domains,
236 })
237}
238
239fn normalised_host(pattern: &str) -> String {
242 match pattern.split_once('/') {
243 Some((host, path)) => format!("{}/{path}", host.to_ascii_lowercase()),
244 None => pattern.to_ascii_lowercase(),
245 }
246}
247
248fn check_across(groups: &WorkerGroups) -> Result<(), ProjectPathsError> {
251 let mut context_owner: BTreeMap<&str, &str> = BTreeMap::new();
252 let mut script_owner: BTreeMap<&str, &str> = BTreeMap::new();
253 let mut route_owner: BTreeMap<String, &str> = BTreeMap::new();
254 let mut domain_owner: BTreeMap<String, &str> = BTreeMap::new();
255 for (key, group) in groups {
256 for context in &group.contexts {
257 if let Some(first) = context_owner.insert(context, key) {
258 return Err(bad(
259 key,
260 format!(
261 "bynk.deploy.context_in_two_groups: context `{context}` is already in `[deploy.workers.{first}]`; a context is in one Worker only"
262 ),
263 ));
264 }
265 }
266 let script = group.script_name(key);
267 if let Some(first) = script_owner.insert(script, key) {
268 return Err(bad(
269 key,
270 format!(
271 "bynk.deploy.group_name_conflict: its Worker would be named `{script}`, as `[deploy.workers.{first}]`'s is"
272 ),
273 ));
274 }
275 for route in &group.routes {
276 if let Some(first) = route_owner.insert(normalised_host(route), key) {
277 return Err(bad(
278 key,
279 format!(
280 "bynk.deploy.duplicate_hostname: route `{route}` is also in `[deploy.workers.{first}]`"
281 ),
282 ));
283 }
284 }
285 for domain in &group.custom_domains {
286 if let Some(first) = domain_owner.insert(normalised_host(domain), key) {
287 return Err(bad(
288 key,
289 format!(
290 "bynk.deploy.duplicate_hostname: custom domain `{domain}` is also in `[deploy.workers.{first}]`"
291 ),
292 ));
293 }
294 }
295 }
296 Ok(())
297}
298
299pub fn deploy_workers_from(deploy: &toml::Table) -> Result<WorkerGroups, ProjectPathsError> {
301 let mut out = WorkerGroups::new();
302 let Some(value) = deploy.get("workers") else {
303 return Ok(out);
304 };
305 let all = value.as_table().ok_or_else(|| {
306 bad(
307 "",
308 "must be a table of Workers, like `[deploy.workers.core]`".to_string(),
309 )
310 })?;
311 for (key, value) in all {
312 out.insert(key.clone(), group_from(key, value)?);
313 }
314 check_across(&out)?;
315 Ok(out)
316}
317
318pub fn try_read_worker_groups_with(
322 project_root: &Path,
323 overlay: &HashMap<PathBuf, String>,
324) -> Result<WorkerGroups, ProjectPathsError> {
325 let manifest = project_root.join("bynk.toml");
326 let content = match read_source(&manifest, overlay) {
327 Ok(text) => text,
328 Err(_) => match std::fs::read_to_string(&manifest) {
329 Ok(text) => text,
330 Err(_) => return Ok(WorkerGroups::new()),
331 },
332 };
333 let doc = content
334 .parse::<toml::Table>()
335 .map_err(|_| ProjectPathsError::Malformed)?;
336 match doc.get("deploy").and_then(|v| v.as_table()) {
337 Some(t) => deploy_workers_from(t),
338 None => Ok(WorkerGroups::new()),
339 }
340}
341
342pub fn try_read_worker_groups(project_root: &Path) -> Result<WorkerGroups, ProjectPathsError> {
344 try_read_worker_groups_with(project_root, &HashMap::new())
345}
346
347#[derive(Debug, Clone, PartialEq, Eq)]
349pub struct GroupIssue {
350 pub code: &'static str,
352 pub group: String,
354 pub message: String,
356}
357
358pub struct ProjectUnits<'a> {
360 pub contexts: &'a BTreeSet<String>,
362 pub other_units: &'a BTreeSet<String>,
364}
365
366pub fn validate_against(groups: &WorkerGroups, units: &ProjectUnits<'_>) -> Vec<GroupIssue> {
370 let mut issues = Vec::new();
371 let grouped: BTreeSet<&str> = groups
372 .values()
373 .flat_map(|g| g.contexts.iter().map(String::as_str))
374 .collect();
375 let implicit: BTreeMap<String, &str> = units
376 .contexts
377 .iter()
378 .filter(|c| !grouped.contains(c.as_str()))
379 .map(|c| {
380 (
381 crate::paths::worker_dir_name(c).to_ascii_lowercase(),
382 c.as_str(),
383 )
384 })
385 .collect();
386 for (key, group) in groups {
387 for context in &group.contexts {
388 if units.other_units.contains(context) {
389 issues.push(GroupIssue {
390 code: "bynk.deploy.not_a_context",
391 group: key.clone(),
392 message: format!(
393 "`{context}` is not a `context`: only contexts are deployed as Workers, so it cannot be in `[deploy.workers.{key}]`"
394 ),
395 });
396 } else if !units.contexts.contains(context) {
397 let hint = did_you_mean(context, units.contexts.iter().map(String::as_str))
398 .map(|c| format!(" — did you mean `{c}`?"))
399 .unwrap_or_default();
400 issues.push(GroupIssue {
401 code: "bynk.deploy.unknown_context",
402 group: key.clone(),
403 message: format!(
404 "`[deploy.workers.{key}]` names context `{context}`, which this project does not declare{hint}"
405 ),
406 });
407 }
408 }
409 let named = group.name.as_deref().map(|n| ("name", n));
410 for (what, name) in std::iter::once(("key", key.as_str())).chain(named) {
411 if let Some(context) = implicit.get(name) {
412 issues.push(GroupIssue {
413 code: "bynk.deploy.group_name_conflict",
414 group: key.clone(),
415 message: format!(
416 "`[deploy.workers.{key}]`'s {what} `{name}` is the Worker of context `{context}`, which is in no group; name it in a group, or choose another {what}"
417 ),
418 });
419 }
420 }
421 }
422 issues
423}
424
425#[cfg(test)]
426mod tests;