bynk_check/
worker_groups.rs1use std::collections::{BTreeMap, BTreeSet, HashMap};
12use std::path::{Path, PathBuf};
13
14use bynk_project::UnitKind;
15use bynk_project::worker_groups::{
16 ProjectUnits, WorkerGroups, try_read_worker_groups_with, validate_against,
17};
18use bynk_syntax::CompileError;
19use bynk_syntax::span::Span;
20
21pub fn manifest_diagnostics(
26 project_root: Option<&Path>,
27 overlay: &HashMap<PathBuf, String>,
28 kinds: &BTreeMap<String, UnitKind>,
29) -> Vec<CompileError> {
30 let groups = project_root
31 .and_then(|root| try_read_worker_groups_with(root, overlay).ok())
32 .unwrap_or_default();
33 check_groups(&groups, kinds)
34}
35
36pub fn check_groups(
39 groups: &WorkerGroups,
40 kinds: &BTreeMap<String, UnitKind>,
41) -> Vec<CompileError> {
42 if groups.is_empty() {
43 return Vec::new();
44 }
45 let of_kind = |wanted: fn(&UnitKind) -> bool| -> BTreeSet<String> {
46 kinds
47 .iter()
48 .filter(|(name, kind)| wanted(kind) && crate::firstparty::unit(name).is_none())
49 .map(|(name, _)| name.clone())
50 .collect()
51 };
52 let contexts = of_kind(|k| matches!(k, UnitKind::Context));
53 let other_units = of_kind(|k| !matches!(k, UnitKind::Context));
54 validate_against(
55 groups,
56 &ProjectUnits {
57 contexts: &contexts,
58 other_units: &other_units,
59 },
60 )
61 .into_iter()
62 .map(|issue| CompileError::new(issue.code, Span::default(), issue.message))
63 .collect()
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 fn kinds() -> BTreeMap<String, UnitKind> {
71 BTreeMap::from([
72 ("money".to_string(), UnitKind::Commons),
73 ("shop.orders".to_string(), UnitKind::Context),
74 ("shop.pricing".to_string(), UnitKind::Context),
75 ("shop.payment".to_string(), UnitKind::Context),
76 ("bynk.cloudflare".to_string(), UnitKind::Context),
79 ])
80 }
81
82 fn codes(manifest: &str) -> Vec<&'static str> {
83 let root = Path::new("/project");
84 let overlay = HashMap::from([(root.join("bynk.toml"), manifest.to_string())]);
85 manifest_diagnostics(Some(root), &overlay, &kinds())
86 .iter()
87 .map(|e| e.category)
88 .collect()
89 }
90
91 #[test]
92 fn contexts_are_groupable() {
93 assert!(
94 codes("[deploy.workers.core]\ncontexts = [\"shop.orders\", \"shop.pricing\"]\n")
95 .is_empty()
96 );
97 }
98
99 #[test]
100 fn a_commons_is_not_a_context() {
101 assert_eq!(
102 codes("[deploy.workers.core]\ncontexts = [\"money\"]\n"),
103 ["bynk.deploy.not_a_context"]
104 );
105 }
106
107 #[test]
108 fn an_undeclared_or_first_party_unit_is_unknown() {
109 assert_eq!(
110 codes("[deploy.workers.core]\ncontexts = [\"shop.ordres\", \"bynk.cloudflare\"]\n"),
111 ["bynk.deploy.unknown_context", "bynk.deploy.unknown_context"]
112 );
113 }
114
115 #[test]
116 fn a_key_may_not_be_an_ungrouped_contexts_worker() {
117 assert_eq!(
118 codes("[deploy.workers.shop-payment]\ncontexts = [\"shop.orders\"]\n"),
119 ["bynk.deploy.group_name_conflict"]
120 );
121 }
122}