Skip to main content

bynk_emit/emitter/
contracts.rs

1//! `bynk-contracts.json` generation per Worker (v0.177, #643).
2//!
3//! The contract hash a context's Worker entry compares an incoming
4//! `X-Bynk-Contract` against, per `on call` service — the same constants the
5//! entry stamps, written where the **driver** can read them.
6//!
7//! Why the driver needs them: the runtime check fails closed, but it does so in
8//! *production*, on live traffic, after the skewed pair is already deployed.
9//! `deploy` can know sooner. It records each context's hashes when it pushes,
10//! so a later `deploy --context A` can compare A's compiled view of its
11//! dependencies against what those dependencies actually have live, and refuse
12//! before the push rather than let requests 409 (ADR 0193's D4 gate already
13//! checks a dependency *exists*; this extends it to *matches*).
14//!
15//! Why a file rather than an API: the driver has two compile paths, and under a
16//! `bynkc` override the compiler is a child process handing back an exit status
17//! — there is no in-memory model to consult. A fact the compiler knows must
18//! reach the driver in the build output, or not at all (ADR 0195 D5, the same
19//! reasoning as `bynk-secrets.json`).
20
21use std::collections::BTreeMap;
22
23use bynk_project::json_string;
24
25/// The file the driver reads, beside each Worker's `wrangler.toml`.
26pub const CONTRACTS_MANIFEST: &str = "bynk-contracts.json";
27
28/// The manifest schema version. Bumped only by a breaking shape change; the
29/// driver refuses a version it does not know rather than guessing, as the
30/// deploy ledger and the secrets manifest do.
31pub(crate) const MANIFEST_VERSION: u32 = 1;
32
33/// #2485: the structured shape text ([`bynk_check::contract_compat`]) beside
34/// each hash the manifest records: `provides` by service, `expects` by
35/// dependency then service.
36#[derive(Default)]
37pub struct Shapes {
38    pub provides: BTreeMap<String, String>,
39    pub expects: BTreeMap<String, BTreeMap<String, String>>,
40    /// #2554: service to the older contract hashes it also accepts, from the
41    /// contracts lock. The driver holds a live caller's recorded hash against
42    /// these before it lets a compatible skew through.
43    pub accepts: BTreeMap<String, Vec<String>>,
44}
45
46/// Render a context's contract manifest: what it **provides**, and what it
47/// **expects** of each context it consumes.
48///
49/// Both halves are needed, and they are not the same fact:
50///
51/// - `provides` is this context's own constant per `on call` service — what its
52///   entry enforces. `deploy` records it when the Worker is pushed, so the
53///   ledger knows what is *live*.
54/// - `expects` is this context's compiled view of each dependency's contract —
55///   the constant it stamps at each call site. `deploy` compares it against the
56///   ledger's `provides` for that dependency, which is exactly the runtime check
57///   moved earlier.
58///
59/// A gate built on `provides` alone could not work: it would compare a context
60/// against itself.
61///
62/// Absent rather than empty when a context neither exposes nor calls an `on
63/// call` service: a project that never crosses a context boundary must not grow
64/// a file into every worker directory for a feature it does not use — and "no
65/// file" is the same answer as "empty" to a driver that must tolerate a build
66/// tree from a compiler predating this file anyway.
67///
68/// I4 (#1970): `foreign` is the third half, **what each declared foreign
69/// caller's generated client embeds** — actor → service → hash, the services
70/// that actor may call. A foreign caller has no `bynk-contracts.json` of its
71/// own to state its `expects`, so `deploy` holds this against the pin the
72/// callee's project records for it (`bynk.foreign.toml`) and refuses a build
73/// that would break it (`design/archive/retired-tracks.md`, interop track D3, Q6). Additive
74/// within version 1, and absent when empty, so every manifest of a context
75/// with no foreign caller is byte-identical to before.
76pub 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    // Hand-rendered rather than via serde: this crate does not depend on
86    // serde_json, and the shape is three fields.
87    let foreign_part = if foreign.is_empty() {
88        String::new()
89    } else {
90        [",\n  \"foreign\": ", &nested_map(foreign)].concat()
91    };
92    // #2485: the structured form of each hash above, so `deploy` can say
93    // whether a skew is compatible. Additive within version 1 and absent when
94    // empty; a reader that ignores it sees the manifest it always did.
95    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/// What one context's contract manifest says, before it is rendered, so a
119/// `[deploy.workers.<key>]` group's members (one Worker, one file) can be merged
120/// (#3562).
121#[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    /// One Worker's contracts: what its members provide (a service name is unique
146    /// within a group, so the union loses nothing) and what they expect of
147    /// contexts **outside** the Worker. A member's call to another member is the
148    /// same build and the same upload, so it has no contract to skew against and
149    /// is left out of `expects`.
150    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
174/// A two-level map at the manifest's top level, `{}` when empty.
175fn 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
186/// `{"charge": ["hash", …]}` for the manifest's top level.
187fn 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        // BTreeMap ordering: the file is byte-stable across builds, which the
238        // golden fixtures depend on.
239        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    /// #3562: two members expecting the same outside dependency are one `expects`
288    /// entry (services unioned), and a call between members is no expectation.
289    #[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}