1use std::collections::BTreeMap;
22
23use bynk_project::json_string;
24
25pub const CONTRACTS_MANIFEST: &str = "bynk-contracts.json";
27
28pub(crate) const MANIFEST_VERSION: u32 = 1;
32
33#[derive(Default)]
37pub struct Shapes {
38 pub provides: BTreeMap<String, String>,
39 pub expects: BTreeMap<String, BTreeMap<String, String>>,
40 pub accepts: BTreeMap<String, Vec<String>>,
44}
45
46pub fn emit_contracts_manifest(
77 provides: &BTreeMap<String, String>,
78 expects: &BTreeMap<String, BTreeMap<String, String>>,
79 foreign: &BTreeMap<String, BTreeMap<String, String>>,
80 shapes: &Shapes,
81) -> Option<String> {
82 if provides.is_empty() && expects.is_empty() {
83 return None;
84 }
85 let foreign_part = if foreign.is_empty() {
88 String::new()
89 } else {
90 [",\n \"foreign\": ", &nested_map(foreign)].concat()
91 };
92 let shapes_part = {
96 let mut part = String::new();
97 if !shapes.provides.is_empty() {
98 part.push_str(",\n \"provides_shapes\": ");
99 part.push_str(&json_map(&shapes.provides, 2));
100 }
101 if !shapes.expects.is_empty() {
102 part.push_str(",\n \"expects_shapes\": ");
103 part.push_str(&nested_map(&shapes.expects));
104 }
105 if !shapes.accepts.is_empty() {
106 part.push_str(",\n \"accepts\": ");
107 part.push_str(&accepts_map(&shapes.accepts));
108 }
109 part
110 };
111 Some(format!(
112 "{{\n \"version\": {MANIFEST_VERSION},\n \"provides\": {},\n \"expects\": {}{foreign_part}{shapes_part}\n}}\n",
113 json_map(provides, 2),
114 nested_map(expects),
115 ))
116}
117
118#[derive(Debug, Clone, Default)]
122pub struct ContractParts {
123 pub provides: BTreeMap<String, String>,
124 pub expects: BTreeMap<String, BTreeMap<String, String>>,
125 pub foreign: BTreeMap<String, BTreeMap<String, String>>,
126 pub provides_shapes: BTreeMap<String, String>,
127 pub expects_shapes: BTreeMap<String, BTreeMap<String, String>>,
128 pub accepts: BTreeMap<String, Vec<String>>,
129}
130
131impl ContractParts {
132 pub fn render(&self) -> Option<String> {
133 emit_contracts_manifest(
134 &self.provides,
135 &self.expects,
136 &self.foreign,
137 &Shapes {
138 provides: self.provides_shapes.clone(),
139 expects: self.expects_shapes.clone(),
140 accepts: self.accepts.clone(),
141 },
142 )
143 }
144
145 pub fn merged(parts: impl IntoIterator<Item = Self>, members: &[String]) -> Self {
151 let mut all = Self::default();
152 for part in parts {
153 all.provides.extend(part.provides);
154 all.provides_shapes.extend(part.provides_shapes);
155 all.accepts.extend(part.accepts);
156 for (dep, services) in part.expects {
157 if !members.contains(&dep) {
158 all.expects.entry(dep).or_default().extend(services);
159 }
160 }
161 for (dep, services) in part.expects_shapes {
162 if !members.contains(&dep) {
163 all.expects_shapes.entry(dep).or_default().extend(services);
164 }
165 }
166 for (actor, services) in part.foreign {
167 all.foreign.entry(actor).or_default().extend(services);
168 }
169 }
170 all
171 }
172}
173
174fn nested_map(m: &BTreeMap<String, BTreeMap<String, String>>) -> String {
176 if m.is_empty() {
177 return "{}".to_string();
178 }
179 let body: Vec<String> = m
180 .iter()
181 .map(|(outer, inner)| [" ", &json_string(outer), ": ", &json_map(inner, 4)].concat())
182 .collect();
183 ["{\n", &body.join(",\n"), "\n }"].concat()
184}
185
186fn accepts_map(m: &BTreeMap<String, Vec<String>>) -> String {
188 let body: Vec<String> = m
189 .iter()
190 .map(|(service, hashes)| {
191 let list: Vec<String> = hashes.iter().map(|h| json_string(h)).collect();
192 [" ", &json_string(service), ": [", &list.join(", "), "]"].concat()
193 })
194 .collect();
195 ["{\n", &body.join(",\n"), "\n }"].concat()
196}
197
198fn json_map(m: &BTreeMap<String, String>, indent: usize) -> String {
199 if m.is_empty() {
200 return "{}".to_string();
201 }
202 let pad = " ".repeat(indent + 2);
203 let close = " ".repeat(indent);
204 let entries: Vec<String> = m
205 .iter()
206 .map(|(k, v)| format!("{pad}{}: {}", json_string(k), json_string(v)))
207 .collect();
208 format!("{{\n{}\n{close}}}", entries.join(",\n"))
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[test]
216 fn absent_when_a_context_neither_provides_nor_consumes() {
217 assert_eq!(
218 emit_contracts_manifest(
219 &BTreeMap::new(),
220 &BTreeMap::new(),
221 &BTreeMap::new(),
222 &Shapes::default()
223 ),
224 None
225 );
226 }
227
228 #[test]
229 fn renders_sorted_service_hashes() {
230 let mut h = BTreeMap::new();
231 h.insert("whoami".to_string(), "317bdd3de84d2176".to_string());
232 h.insert("ask".to_string(), "0011223344556677".to_string());
233 let out =
234 emit_contracts_manifest(&h, &BTreeMap::new(), &BTreeMap::new(), &Shapes::default())
235 .unwrap();
236 assert!(out.contains("\"version\": 1"));
237 let ask = out.find("\"ask\"").unwrap();
240 let whoami = out.find("\"whoami\"").unwrap();
241 assert!(ask < whoami, "services render in sorted order:\n{out}");
242 }
243
244 #[test]
245 fn foreign_callers_are_recorded_only_when_declared() {
246 let mut provides = BTreeMap::new();
247 provides.insert("status".to_string(), "226b9939f85e69ea".to_string());
248 let none = emit_contracts_manifest(
249 &provides,
250 &BTreeMap::new(),
251 &BTreeMap::new(),
252 &Shapes::default(),
253 )
254 .unwrap();
255 assert!(!none.contains("foreign"), "{none}");
256 let mut legacy = BTreeMap::new();
257 legacy.insert("status".to_string(), "226b9939f85e69ea".to_string());
258 let mut foreign = BTreeMap::new();
259 foreign.insert("Legacy".to_string(), legacy);
260 let out =
261 emit_contracts_manifest(&provides, &BTreeMap::new(), &foreign, &Shapes::default())
262 .unwrap();
263 assert!(
264 out.contains("\"foreign\": {\n \"Legacy\": {\n \"status\": \"226b9939f85e69ea\"\n }\n }"),
265 "{out}"
266 );
267 }
268
269 #[test]
270 fn a_consumer_records_what_it_expects_of_each_dependency() {
271 let mut inner = BTreeMap::new();
272 inner.insert("whoami".to_string(), "317bdd3de84d2176".to_string());
273 let mut expects = BTreeMap::new();
274 expects.insert("app.b".to_string(), inner);
275 let out = emit_contracts_manifest(
276 &BTreeMap::new(),
277 &expects,
278 &BTreeMap::new(),
279 &Shapes::default(),
280 )
281 .unwrap();
282 assert!(out.contains("\"app.b\""), "{out}");
283 assert!(out.contains("\"whoami\": \"317bdd3de84d2176\""), "{out}");
284 assert!(out.contains("\"provides\": {}"), "{out}");
285 }
286
287 #[test]
290 fn a_groups_expects_union_outside_dependencies_and_drop_its_own_members() {
291 let part = |expects: &[(&str, &str, &str)]| {
292 let mut p = ContractParts::default();
293 for (dep, service, hash) in expects {
294 p.expects
295 .entry(dep.to_string())
296 .or_default()
297 .insert(service.to_string(), hash.to_string());
298 }
299 p
300 };
301 let merged = ContractParts::merged(
302 [
303 part(&[("shop.pay", "charge", "h1"), ("shop.b", "inner", "h2")]),
304 part(&[("shop.pay", "refund", "h3")]),
305 ],
306 &["shop.a".to_string(), "shop.b".to_string()],
307 );
308 assert_eq!(
309 merged.expects.keys().collect::<Vec<_>>(),
310 ["shop.pay"],
311 "a member is not an outside dependency"
312 );
313 assert_eq!(
314 merged.expects["shop.pay"].keys().collect::<Vec<_>>(),
315 ["charge", "refund"],
316 "services of one dependency are unioned"
317 );
318 }
319}