Skip to main content

bynk_emit/emitter/wrangler/
environment.rs

1//! The `[env.<name>]` block of a named-environment deploy (back-half paydown 1C.2, Decision A of
2//! #4039).
3//!
4//! **Why a named environment needs a block at all.** Wrangler does not inherit a Worker's
5//! bindings into a named environment: a bare `--env staging` against the flat config
6//! [`super::emit_wrangler_toml`] writes would deploy with *no* bindings. The block restates what
7//! Wrangler does not inherit, and it cannot be written at build time, because no environment is
8//! known then and its values (the ids the deploy has just resolved, the environment's names) do
9//! not exist until the deploy.
10//!
11//! **What this renders it from.** The generated `wrangler.toml` as the deploy has materialised it
12//! for the environment, which is the file Wrangler is about to upload, so the top level and the
13//! block cannot disagree (ADR 0193 D3, ADR 0254 D2). What it does with each top-level key is the
14//! key's [`WranglerKey::environment_rule`], one exhaustive `match` over every table the emitter
15//! writes: a binding table cannot be left out of the block by omission (#3577, #3586). A key that
16//! is not one of the emitter's is dropped.
17//!
18//! **The bytes.** The block is a [`toml::Table`], keys sorted, written by
19//! `toml::to_string_pretty` and appended after a newline. The top level is never touched. This
20//! layout is what `bynk deploy` has always handed Wrangler, and it stays (no format change).
21
22use std::collections::{BTreeMap, BTreeSet};
23
24use bynk_project::environment::{analytics_dataset_name, deployed_worker_name, env_qualify};
25use bynk_project::wrangler_keys::{EnvironmentRule, Qualify, WranglerKey};
26
27/// What the deploy has resolved for the environment that the generated file does not say.
28pub struct Resolved<'a> {
29    /// The resolved id of each KV namespace, by binding. Empty for a Worker with no KV.
30    pub kv_ids: &'a BTreeMap<String, String>,
31    /// Interop I5 (#1972): the bindings of Service Bindings to foreign Workers, whose targets
32    /// are copied as declared.
33    pub foreign_bindings: &'a BTreeSet<String>,
34}
35
36/// `config_text` with the `[env.<environment>]` block appended, or unchanged when the block
37/// would be empty (a config that names nothing and binds nothing, which `bynk build` never
38/// emits).
39pub fn render(config_text: &str, environment: &str, resolved: &Resolved) -> Result<String, String> {
40    let doc: toml::Table = config_text
41        .parse()
42        .map_err(|e| format!("generated configuration is not valid TOML: {e}"))?;
43    let mut block = toml::Table::new();
44    for (key, value) in &doc {
45        let Some(rule) = rule_of(key) else {
46            continue;
47        };
48        if let Some(value) = apply(rule, value, environment, resolved) {
49            block.insert(key.clone(), value);
50        }
51    }
52    if block.is_empty() {
53        return Ok(config_text.to_string());
54    }
55    let mut env_table = toml::Table::new();
56    env_table.insert(environment.to_string(), toml::Value::Table(block));
57    let mut wrapper = toml::Table::new();
58    wrapper.insert("env".to_string(), toml::Value::Table(env_table));
59    let appended = toml::to_string_pretty(&wrapper)
60        .map_err(|e| format!("could not serialise the `[env.{environment}]` block: {e}"))?;
61    Ok(format!("{config_text}\n{appended}"))
62}
63
64/// The rule for the top-level key `key`: the emitter's own, or a one-per-Worker table the
65/// registry names (copied). `None` for a key the emitter does not write.
66fn rule_of(key: &str) -> Option<EnvironmentRule> {
67    WranglerKey::from_top_key(key)
68        .map(WranglerKey::environment_rule)
69        .or_else(|| {
70            singleton_tables()
71                .any(|table| table == key)
72                .then_some(EnvironmentRule::Copied)
73        })
74}
75
76/// The one-per-Worker tables of `bynk.cloudflare` (`version_metadata`, `ai`, `images`,
77/// `analytics`), as `bynk-std`'s registry spells them.
78fn singleton_tables() -> impl Iterator<Item = &'static str> {
79    bynk_check::firstparty::unit(bynk_check::firstparty::CLOUDFLARE_UNIT)
80        .into_iter()
81        .flat_map(|unit| unit.singletons.iter().map(|s| s.wrangler_table))
82}
83
84/// The block's value for a top-level `value` under `rule`, or `None` when the block has none.
85fn apply(
86    rule: EnvironmentRule,
87    value: &toml::Value,
88    environment: &str,
89    resolved: &Resolved,
90) -> Option<toml::Value> {
91    match rule {
92        EnvironmentRule::Inherited => None,
93        EnvironmentRule::Copied => Some(value.clone()),
94        // #2028: the deployed name, from the function the plan prints it with.
95        EnvironmentRule::DeployedName => value
96            .as_str()
97            .map(|name| toml::Value::String(deployed_worker_name(environment, name))),
98        // S4b (#1967): each namespace's resolved id, by binding. A Worker with no ids resolved
99        // restates none of its namespaces.
100        EnvironmentRule::ResolvedIds { field } => {
101            if resolved.kv_ids.is_empty() {
102                return None;
103            }
104            let mut entries = array_of(value)?;
105            for entry in &mut entries {
106                if let toml::Value::Table(t) = entry
107                    && let Some(id) = t
108                        .get("binding")
109                        .and_then(toml::Value::as_str)
110                        .and_then(|b| resolved.kv_ids.get(b))
111                {
112                    t.insert(field.to_string(), toml::Value::String(id.clone()));
113                }
114            }
115            Some(toml::Value::Array(entries))
116        }
117        // P5 (#2323), #3479, P3b (#2582): each entry under its environment-qualified name, or
118        // staging would write into the default environment's bucket, index or dataset.
119        EnvironmentRule::Qualified { field, form } => {
120            let mut entries = array_of(value)?;
121            for entry in &mut entries {
122                qualify_field(entry, field, |name| match form {
123                    Qualify::Suffix => env_qualify(environment, name),
124                    Qualify::Dataset => analytics_dataset_name(environment, name),
125                });
126            }
127            Some(toml::Value::Array(entries))
128        }
129        // #3513 B: the `[vars]` the dataset names travel in (`Analytics.dataset()` reads them),
130        // each under the qualified name its binding now has, or `dataset()` would name the
131        // default environment's table from a staging Worker. `vars` is not inherited either.
132        EnvironmentRule::QualifiedVars { prefix } => {
133            let toml::Value::Table(vars) = value else {
134                return None;
135            };
136            let carried = vars
137                .iter()
138                .map(|(key, value)| {
139                    let value = match value {
140                        toml::Value::String(name) if key.starts_with(prefix) => {
141                            toml::Value::String(analytics_dataset_name(environment, name))
142                        }
143                        toml::Value::String(_)
144                        | toml::Value::Integer(_)
145                        | toml::Value::Float(_)
146                        | toml::Value::Boolean(_)
147                        | toml::Value::Datetime(_)
148                        | toml::Value::Array(_)
149                        | toml::Value::Table(_) => value.clone(),
150                    };
151                    (key.clone(), value)
152                })
153                .collect();
154            Some(toml::Value::Table(carried))
155        }
156        // P2 (#2578): a producer's queue is qualified as a consumer's is, or staging would send
157        // into the default environment's queue.
158        EnvironmentRule::QualifiedQueues => {
159            let mut queues = value.clone();
160            if let toml::Value::Table(q) = &mut queues {
161                for side in ["consumers", "producers"] {
162                    let Some(toml::Value::Array(entries)) = q.get_mut(side) else {
163                        continue;
164                    };
165                    for entry in entries.iter_mut() {
166                        qualify_field(entry, "queue", |name| env_qualify(environment, name));
167                    }
168                }
169            }
170            Some(queues)
171        }
172        // A Service Binding to a project Worker names the Worker's deployed name; one to a
173        // foreign Worker, which Bynk did not name, is copied as declared (interop I5, #1972).
174        EnvironmentRule::QualifiedServices => {
175            let mut services = array_of(value)?;
176            for service in &mut services {
177                let foreign = matches!(service, toml::Value::Table(t)
178                    if t.get("binding").and_then(toml::Value::as_str).is_some_and(|b| resolved.foreign_bindings.contains(b)));
179                if !foreign {
180                    qualify_field(service, "service", |target| {
181                        deployed_worker_name(environment, target)
182                    });
183                }
184            }
185            Some(toml::Value::Array(services))
186        }
187    }
188}
189
190/// `value`'s entries, when it is an array.
191fn array_of(value: &toml::Value) -> Option<Vec<toml::Value>> {
192    value.as_array().cloned()
193}
194
195/// Replace `entry`'s string field `field` with `qualify` of it, if the entry is a table with one.
196fn qualify_field(entry: &mut toml::Value, field: &str, qualify: impl Fn(&str) -> String) {
197    if let toml::Value::Table(t) = entry
198        && let Some(name) = t
199            .get(field)
200            .and_then(toml::Value::as_str)
201            .map(str::to_owned)
202    {
203        t.insert(field.to_string(), toml::Value::String(qualify(&name)));
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    fn block(
212        config: &str,
213        environment: &str,
214        kv: &[(&str, &str)],
215        foreign: &[&str],
216    ) -> toml::Table {
217        let kv_ids: BTreeMap<String, String> = kv
218            .iter()
219            .map(|(b, i)| (b.to_string(), i.to_string()))
220            .collect();
221        let foreign_bindings: BTreeSet<String> = foreign.iter().map(|b| b.to_string()).collect();
222        let out = render(
223            config,
224            environment,
225            &Resolved {
226                kv_ids: &kv_ids,
227                foreign_bindings: &foreign_bindings,
228            },
229        )
230        .expect("renders");
231        let parsed: toml::Table = out.parse().expect("valid TOML out");
232        parsed["env"][environment]
233            .as_table()
234            .expect("a block")
235            .clone()
236    }
237
238    #[test]
239    fn the_name_is_the_deployed_name() {
240        let b = block("name = \"shop\"\n", "staging", &[], &[]);
241        assert_eq!(b["name"].as_str(), Some("shop-staging"));
242        let b = block("name = \"shop\"\n", "default", &[], &[]);
243        assert_eq!(b["name"].as_str(), Some("shop"));
244    }
245
246    #[test]
247    fn a_namespace_takes_its_resolved_id_and_none_resolved_leaves_the_table_out() {
248        let config = "name = \"s\"\n[[kv_namespaces]]\nbinding = \"KV\"\nid = \"<KV_ID>\"\n";
249        let b = block(config, "staging", &[("KV", "abc")], &[]);
250        assert_eq!(b["kv_namespaces"][0]["id"].as_str(), Some("abc"));
251        let b = block(config, "staging", &[], &[]);
252        assert!(!b.contains_key("kv_namespaces"), "{b:?}");
253    }
254
255    #[test]
256    fn a_bucket_an_index_and_a_dataset_are_qualified_each_in_its_form() {
257        let config = "name = \"s\"\n[[r2_buckets]]\nbinding = \"B\"\nbucket_name = \"media\"\n\
258                      [[vectorize]]\nbinding = \"V\"\nindex_name = \"docs\"\n\
259                      [[analytics_engine_datasets]]\nbinding = \"A\"\ndataset = \"signups\"\n";
260        let b = block(config, "eu-staging", &[], &[]);
261        assert_eq!(
262            b["r2_buckets"][0]["bucket_name"].as_str(),
263            Some("media-eu-staging")
264        );
265        assert_eq!(
266            b["vectorize"][0]["index_name"].as_str(),
267            Some("docs-eu-staging")
268        );
269        assert_eq!(
270            b["analytics_engine_datasets"][0]["dataset"].as_str(),
271            Some("signups_eu_staging")
272        );
273    }
274
275    #[test]
276    fn only_the_dataset_variables_are_qualified() {
277        let config = "name = \"s\"\n[vars]\nBYNK_DATASET_A = \"signups\"\nOTHER = \"keep\"\n";
278        let b = block(config, "staging", &[], &[]);
279        assert_eq!(
280            b["vars"]["BYNK_DATASET_A"].as_str(),
281            Some("signups_staging")
282        );
283        assert_eq!(b["vars"]["OTHER"].as_str(), Some("keep"));
284    }
285
286    #[test]
287    fn producers_and_consumers_are_both_qualified() {
288        let config = "name = \"s\"\n[[queues.producers]]\nbinding = \"Q\"\nqueue = \"jobs\"\n\
289                      [[queues.consumers]]\nqueue = \"jobs\"\nmax_batch_size = 10\n";
290        let b = block(config, "staging", &[], &[]);
291        assert_eq!(
292            b["queues"]["producers"][0]["queue"].as_str(),
293            Some("jobs-staging")
294        );
295        assert_eq!(
296            b["queues"]["consumers"][0]["queue"].as_str(),
297            Some("jobs-staging")
298        );
299    }
300
301    #[test]
302    fn a_service_to_a_project_worker_is_qualified_and_a_foreign_one_is_not() {
303        let config = "name = \"s\"\n[[services]]\nbinding = \"OTHER\"\nservice = \"other\"\n\
304                      [[services]]\nbinding = \"LEGACY\"\nservice = \"legacy\"\n";
305        let b = block(config, "staging", &[], &["LEGACY"]);
306        assert_eq!(b["services"][0]["service"].as_str(), Some("other-staging"));
307        assert_eq!(b["services"][1]["service"].as_str(), Some("legacy"));
308    }
309
310    #[test]
311    fn the_inherited_keys_and_an_unknown_one_are_not_restated_and_a_singleton_is_copied() {
312        let config = "name = \"s\"\nmain = \"index.ts\"\ncompatibility_date = \"2026-01-01\"\n\
313                      compatibility_flags = []\nworkers_dev = true\naddresses = [\"a@b\"]\n\
314                      unknown = 1\n[assets]\ndirectory = \"a\"\n[cache]\nenabled = true\n\
315                      [[rules]]\ntype = \"CompiledWasm\"\n[version_metadata]\nbinding = \"V\"\n\
316                      [ai]\nbinding = \"AI\"\n";
317        let b = block(config, "staging", &[], &[]);
318        let keys: Vec<&str> = b.keys().map(String::as_str).collect();
319        assert_eq!(keys, ["ai", "name", "version_metadata"]);
320    }
321
322    /// Every top-level key the rules copy is copied byte for byte from the top level, which the
323    /// deploy has already made this environment's.
324    #[test]
325    fn a_copied_table_is_the_top_levels() {
326        let config = "name = \"s\"\n[[d1_databases]]\nbinding = \"D\"\ndatabase_name = \"x\"\n\
327                      database_id = \"1\"\n[triggers]\ncrons = [\"0 * * * *\"]\n";
328        let b = block(config, "staging", &[], &[]);
329        assert_eq!(b["d1_databases"][0]["database_id"].as_str(), Some("1"));
330        assert_eq!(b["triggers"]["crons"][0].as_str(), Some("0 * * * *"));
331    }
332
333    #[test]
334    fn nothing_to_state_is_left_exactly_as_emitted_and_bad_text_is_an_error() {
335        let nameless = "main = \"index.ts\"\n";
336        let out = render(
337            nameless,
338            "staging",
339            &Resolved {
340                kv_ids: &BTreeMap::new(),
341                foreign_bindings: &BTreeSet::new(),
342            },
343        );
344        assert_eq!(out.as_deref(), Ok(nameless));
345        let bad = render(
346            "not = valid = toml",
347            "staging",
348            &Resolved {
349                kv_ids: &BTreeMap::new(),
350                foreign_bindings: &BTreeSet::new(),
351            },
352        );
353        assert!(bad.is_err());
354    }
355}