Skip to main content

bynk/dev/
bindings.rs

1use super::serving::Serving;
2use super::stand_ins::StandIn;
3use super::stand_ins::stand_in_name;
4use super::watch::persist_to_args;
5use crate::cloudflare::CloudflareApi;
6use crate::probe::Provenance;
7use bynk_driver::colour;
8use bynk_driver::emsg;
9use std::path::Path;
10
11/// The config every context is served from: its generated `wrangler.toml`
12/// with the development bindings applied and each binding to a foreign Worker
13/// pointed at its stand-in, beside the original so `main` resolves the same.
14pub const DEV_CONFIG: &str = "wrangler.dev.toml";
15
16/// Write each served context's [`DEV_CONFIG`] from its generated
17/// `wrangler.toml`, the last step after every build. A copy, not an edit: a
18/// rebuild rewrites `wrangler.toml` with the deploy's names (its real Workers,
19/// its derived Vectorize indexes), and `wrangler dev` watching it would reload
20/// with those bound (review of #2008; #3505) before the development bindings
21/// replaced them. The copy is replaced by a rename once they are all applied,
22/// so wrangler only ever reads it whole, and only when it changes.
23pub(super) fn publish_dev_configs(
24    workers_dir: &Path,
25    serving: &[Serving],
26    plans: &[(String, Vec<StandIn>)],
27) -> Result<(), String> {
28    for context in serving.iter().map(|s| &s.worker) {
29        let targets: std::collections::BTreeMap<String, String> = plans
30            .iter()
31            .filter(|(c, _)| c == context)
32            .flat_map(|(_, stand_ins)| stand_ins)
33            .flat_map(|s| {
34                let name = stand_in_name(context, &s.worker);
35                s.bindings.iter().map(move |b| (b.clone(), name.clone()))
36            })
37            .collect();
38        let dir = workers_dir.join(context);
39        let text = std::fs::read_to_string(dir.join("wrangler.toml")).map_err(|e| e.to_string())?;
40        let out = bynk_emit::emitter::wrangler::retarget_services(&text, &targets)?;
41        let path = dir.join(DEV_CONFIG);
42        if std::fs::read_to_string(&path).ok().as_deref() != Some(out.as_str()) {
43            let staged = dir.join(format!("{DEV_CONFIG}.tmp"));
44            std::fs::write(&staged, out).map_err(|e| e.to_string())?;
45            std::fs::rename(&staged, &path).map_err(|e| e.to_string())?;
46        }
47    }
48    Ok(())
49}
50
51/// Fill each served Worker's generated config from the deploy ledger, for
52/// `-- --remote`. A never-deployed project gets an actionable error instead of
53/// sending a generated placeholder to Cloudflare; `false` after printing it.
54pub(super) fn materialise_remote_state(
55    project_root: &Path,
56    workers_dir: &Path,
57    serving: &[Serving],
58    environment: &str,
59) -> bool {
60    for s in serving {
61        let config = workers_dir.join(&s.worker).join("wrangler.toml");
62        if let Err(e) =
63            crate::deploy::materialise_deploy_state(project_root, &s.worker, &config, environment)
64        {
65            emsg!("bynk: error: {e}");
66            return false;
67        }
68    }
69    true
70}
71
72/// What binding the served Workers' `Vectorize` instances for development did.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74enum DevVectorize {
75    /// Bound as `[dev.vectorize-index]` says (or nothing to bind).
76    Bound,
77    /// Not bound, but every instance is left out, so the config names no
78    /// deploy index: safe to serve.
79    Unbound,
80    /// Neither bound nor unbound: the config may still name the deploy's
81    /// indexes, so it must not be served (#3505 review).
82    Unsafe,
83}
84
85impl DevVectorize {
86    /// Whether the configs may then be served: never with the deploy's indexes
87    /// possibly still bound, and on the first build only once bound as asked.
88    fn may_publish(self, announce: bool) -> bool {
89        match self {
90            DevVectorize::Bound => true,
91            DevVectorize::Unbound => !announce,
92            DevVectorize::Unsafe => false,
93        }
94    }
95}
96
97/// #3479: bind the served Workers' `Vectorize` instances for development
98/// (see [`crate::dev_vectorize`]), printing why not on a failure and, when
99/// `announce`, the one note of what is bound. `--remote` keeps the account's
100/// deployed names, so it binds nothing.
101fn bind_dev_vectorize(
102    project_root: &Path,
103    workers_dir: &Path,
104    available: &[String],
105    serving: &[Serving],
106    remote: bool,
107    announce: bool,
108    model: &bynk_emit::emit_model::WorkersBuild,
109) -> DevVectorize {
110    if remote {
111        return DevVectorize::Bound;
112    }
113    let names: Vec<String> = serving.iter().map(|s| s.worker.clone()).collect();
114    match crate::dev_vectorize::bind_for_dev(project_root, workers_dir, available, &names, model) {
115        Ok(bound) => {
116            if announce && let Some(note) = crate::dev_vectorize::report_note(&bound) {
117                colour::eprintln(&note);
118            }
119            DevVectorize::Bound
120        }
121        // The first build stops here, before anything is served.
122        Err(e) if announce => {
123            emsg!("bynk: error: {e}");
124            DevVectorize::Unsafe
125        }
126        Err(e) => {
127            // A rebuild keeps serving.
128            emsg!("bynk: warning: {e}");
129            // A rebuild's configs name the deploy's indexes again: never serve
130            // them. Unbound, a call to an instance faults until `bynk.toml` reads.
131            match crate::dev_vectorize::unbind_all(workers_dir, &names) {
132                Ok(()) => {
133                    emsg!(
134                        "bynk dev: warning: Vectorize instances are unbound until `bynk.toml` is fixed; calls to them fail"
135                    );
136                    DevVectorize::Unbound
137                }
138                Err(e) => {
139                    emsg!("bynk: warning: could not unbind the Vectorize instances: {e}");
140                    DevVectorize::Unsafe
141                }
142            }
143        }
144    }
145}
146
147/// #3319: the local connection strings of the served Workers' `Postgres`
148/// instances, or `None` after printing why not. `--remote` runs against the
149/// account's Hyperdrive config, so no local string applies.
150pub(super) fn hyperdrive_local_env(
151    project_root: &Path,
152    workers_dir: &Path,
153    serving: &[Serving],
154    remote: bool,
155) -> Option<crate::dev_hyperdrive::LocalConnections> {
156    if remote {
157        return Some(Default::default());
158    }
159    let workers: Vec<String> = serving.iter().map(|s| s.worker.clone()).collect();
160    let lookup = |name: &str| std::env::var(name).ok();
161    match crate::dev_hyperdrive::local_connections(project_root, workers_dir, &workers, &lookup) {
162        Ok((strings, warnings)) => {
163            for warning in warnings {
164                emsg!("bynk: warning: {warning}");
165            }
166            Some(strings)
167        }
168        Err(e) => {
169            emsg!("bynk: error: {e}");
170            None
171        }
172    }
173}
174
175/// #3301: whether the table `wrangler secrets-store secret list` printed has
176/// a row for secret `name`: the name is a whole cell of the first column, so
177/// a longer name that merely starts with it does not count. Only names are
178/// ever in that table, never a value.
179fn secret_listed(stdout: &str, name: &str) -> bool {
180    stdout
181        .lines()
182        .filter_map(|line| line.trim_start().strip_prefix('│'))
183        .filter_map(|row| row.split('│').next())
184        .any(|cell| cell.trim() == name)
185}
186
187/// #3301: what `bynk dev` says of a stored secret the local Secrets Store
188/// does not hold. Under `bynk dev` the binding reads the local store, never
189/// the account's (a production secret cannot be read locally), whose id is the
190/// store's name as written.
191fn missing_local_secret_hint(worker: &str, binding: &str, store: &str, secret: &str) -> String {
192    format!(
193        "bynk dev: warning: `{worker}` reads secret `{secret}` of Secrets Store `{store}` through `{binding}`, from the local store, which does not have it, so reading it will fault; create it with `wrangler secrets-store secret create {store} --name {secret} --scopes workers` (no `--remote`; it asks for the value)"
194    )
195}
196
197/// #3301: warn about each served Worker's stored secret that the local
198/// Secrets Store lacks (`wrangler secrets-store secret list <store>`, local,
199/// from the Worker's directory where `wrangler dev` keeps its state). A list
200/// that cannot be read warns too: the secret may be there, but it was not
201/// confirmed. The session keeps serving.
202pub(super) fn warn_missing_local_secrets(
203    provenance: &Provenance,
204    workers_dir: &Path,
205    serving: &[Serving],
206    wrangler_args: &[String],
207) {
208    for s in serving {
209        let worker_dir = workers_dir.join(&s.worker);
210        let Ok(config) = std::fs::read_to_string(worker_dir.join("wrangler.toml")) else {
211            continue;
212        };
213        let Ok(entries) = bynk_emit::emitter::wrangler::stored_secret_entries(&config) else {
214            continue;
215        };
216        for (binding, store, secret) in entries {
217            let listed = crate::cloudflare::Wrangler::new(provenance, &worker_dir)
218                .secrets_store_list_local(&worker_dir, &store, &persist_to_args(wrangler_args));
219            if listed.as_ref().is_err_and(|e| e.is_missing()) {
220                return;
221            }
222            let present = listed.is_ok_and(|stdout| secret_listed(&stdout, &secret));
223            if !present {
224                eprintln!(
225                    "{}",
226                    missing_local_secret_hint(&s.worker, &binding, &store, &secret)
227                );
228            }
229        }
230    }
231}
232
233/// What a build's development configs are made from.
234pub(super) struct DevConfigs<'a> {
235    pub(super) project_root: &'a Path,
236    pub(super) workers_dir: &'a Path,
237    /// Every Worker of the build.
238    pub(super) available: &'a [String],
239    pub(super) serving: &'a [Serving],
240    pub(super) stand_ins: &'a [(String, Vec<StandIn>)],
241    pub(super) remote: bool,
242    pub(super) environment: &'a str,
243}
244
245impl DevConfigs<'_> {
246    /// Make each served Worker's development config from the build's generated
247    /// one, after every build. `announce` on the first build, which fails on what a
248    /// rebuild only reports. `false` after printing why.
249    ///
250    /// #3505: every change is made to the generated config, which nothing serves,
251    /// and the served [`DEV_CONFIG`] is replaced whole only after the last of
252    /// them, so `wrangler dev` never reloads with the deploy's names bound.
253    pub(super) fn write(
254        &self,
255        model: &bynk_emit::emit_model::WorkersBuild,
256        announce: bool,
257    ) -> bool {
258        dev_config_patches(
259            self.project_root,
260            self.workers_dir,
261            self.serving,
262            self.environment,
263        );
264        // #3479: each `Vectorize` instance is bound to the index
265        // `[dev.vectorize-index]` names, or left unbound.
266        let bound = bind_dev_vectorize(
267            self.project_root,
268            self.workers_dir,
269            self.available,
270            self.serving,
271            self.remote,
272            announce,
273            model,
274        );
275        if !bound.may_publish(announce) {
276            if bound == DevVectorize::Unsafe && !announce {
277                emsg!("bynk dev: still serving the last good build's configs");
278            }
279            return false;
280        }
281        match publish_dev_configs(self.workers_dir, self.serving, self.stand_ins) {
282            Ok(()) => bound == DevVectorize::Bound,
283            Err(e) => {
284                // At start the session stops; on a rebuild it keeps serving.
285                let label = if announce { "error" } else { "warning" };
286                emsg!("bynk: {label}: could not write the development configs: {e}");
287                false
288            }
289        }
290    }
291}
292
293/// What `bynk dev` changes in each Worker's development copy of its config: the
294/// remote-only bindings (AI Search, #3480; mTLS certificates, #3513), and the
295/// agent-inspection registry (#3581).
296fn dev_config_patches(
297    project_root: &Path,
298    workers_dir: &Path,
299    serving: &[Serving],
300    environment: &str,
301) {
302    proxy_remote_bindings(project_root, workers_dir, serving, environment);
303    bind_inspect_registry(workers_dir, serving);
304}
305
306/// #3581: bind the agent-inspection registry in each Worker's development copy of its
307/// config, for a Worker whose entry exports its class (one that hosts an agent). The
308/// config `bynk deploy` reads is a different build and never carries it.
309fn bind_inspect_registry(workers_dir: &Path, serving: &[Serving]) {
310    for s in serving {
311        let dir = workers_dir.join(&s.worker);
312        let (Ok(text), Ok(entry)) = (
313            std::fs::read_to_string(dir.join("wrangler.toml")),
314            std::fs::read_to_string(dir.join("index.ts")),
315        ) else {
316            continue;
317        };
318        match bynk_emit::emitter::wrangler::enable_agent_inspection(&text, &entry) {
319            Ok(out) if out != text => {
320                if let Err(e) = std::fs::write(dir.join("wrangler.toml"), out) {
321                    emsg!(
322                        "bynk: warning: could not bind `{}`'s inspect registry: {e}",
323                        s.worker
324                    );
325                }
326            }
327            Ok(_) => {}
328            Err(e) => emsg!(
329                "bynk: warning: could not bind `{}`'s inspect registry: {e}",
330                s.worker
331            ),
332        }
333    }
334}
335
336/// #3480: each served Worker's development copy of its config proxies an
337/// `[[ai_search]]` binding to the deployed instance (`remote = true`), since
338/// AI Search has no local simulation. The generated config `bynk deploy`
339/// reads is written elsewhere and never carries it. A failure is reported and
340/// the Worker serves without, so a call faults naming the binding.
341fn proxy_ai_search(workers_dir: &Path, serving: &[Serving]) {
342    for s in serving {
343        let path = workers_dir.join(&s.worker).join("wrangler.toml");
344        let Ok(text) = std::fs::read_to_string(&path) else {
345            continue;
346        };
347        match bynk_emit::emitter::wrangler::enable_remote_ai_search(&text) {
348            Ok(out) if out != text => {
349                if let Err(e) = std::fs::write(&path, out) {
350                    emsg!(
351                        "bynk: warning: could not proxy `{}`'s AI Search bindings to the account: {e}",
352                        s.worker
353                    );
354                }
355            }
356            Ok(_) => {}
357            Err(e) => emsg!(
358                "bynk: warning: could not proxy `{}`'s AI Search bindings: {e}",
359                s.worker
360            ),
361        }
362    }
363}
364
365/// #3513 A: each served Worker's development copy of its config runs an `[[mtls_certificates]]`
366/// binding on Cloudflare (`remote = true`), bound by the certificate id the last deploy of
367/// `environment` recorded, since mTLS has no local simulation. A certificate no deploy has linked
368/// is reported, and the Worker serves with it unbound, so a call through it fails.
369fn proxy_mtls(project_root: &Path, workers_dir: &Path, serving: &[Serving], environment: &str) {
370    for s in serving {
371        let path = workers_dir.join(&s.worker).join("wrangler.toml");
372        let Ok(text) = std::fs::read_to_string(&path) else {
373            continue;
374        };
375        if !text.contains("mtls_certificates") {
376            continue;
377        }
378        if let Err(e) =
379            crate::deploy::materialise_mtls_for_dev(project_root, &s.worker, &path, environment)
380        {
381            emsg!("bynk: warning: {e}");
382        }
383        let Ok(text) = std::fs::read_to_string(&path) else {
384            continue;
385        };
386        match bynk_emit::emitter::wrangler::enable_remote_mtls(&text) {
387            Ok(out) if out != text => {
388                if let Err(e) = std::fs::write(&path, out) {
389                    emsg!(
390                        "bynk: warning: could not run `{}`'s mTLS bindings on the account: {e}",
391                        s.worker
392                    );
393                }
394            }
395            Ok(_) => {}
396            Err(e) => emsg!(
397                "bynk: warning: could not run `{}`'s mTLS bindings: {e}",
398                s.worker
399            ),
400        }
401    }
402}
403
404/// #3513 B: each served Worker's development copy runs its `[analytics]` (Analytics SQL)
405/// binding on Cloudflare (`remote = true`), since it has no local implementation.
406fn proxy_analytics_sql(workers_dir: &Path, serving: &[Serving]) {
407    for s in serving {
408        let path = workers_dir.join(&s.worker).join("wrangler.toml");
409        let Ok(text) = std::fs::read_to_string(&path) else {
410            continue;
411        };
412        if !text.contains("[analytics]") {
413            continue;
414        }
415        match bynk_emit::emitter::wrangler::enable_remote_analytics_sql(&text) {
416            Ok(out) if out != text => {
417                if let Err(e) = std::fs::write(&path, out) {
418                    emsg!(
419                        "bynk: warning: could not run `{}`'s Analytics SQL binding on the account: {e}",
420                        s.worker
421                    );
422                }
423            }
424            Ok(_) => {}
425            Err(e) => emsg!(
426                "bynk: warning: could not run `{}`'s Analytics SQL binding: {e}",
427                s.worker
428            ),
429        }
430    }
431}
432
433/// The remote-only bindings of the development copy: AI Search (#3480), mTLS certificates
434/// (#3513 A) and Analytics SQL (#3513 B).
435fn proxy_remote_bindings(
436    project_root: &Path,
437    workers_dir: &Path,
438    serving: &[Serving],
439    environment: &str,
440) {
441    proxy_ai_search(workers_dir, serving);
442    proxy_mtls(project_root, workers_dir, serving, environment);
443    proxy_analytics_sql(workers_dir, serving);
444}
445
446/// #3478: the `--var`s of [`dev_var_args`] for `project_root`'s `[dev]`
447/// acknowledgements, or `None` after printing why not.
448pub(super) fn dev_vars_for(project_root: &Path) -> Option<Vec<String>> {
449    match bynk_project::dev_ack::try_read_dev_acks(project_root) {
450        Ok(acks) => {
451            let mut args = dev_var_args(&acks);
452            // #3581: the local key `bynk dev inspect` signs under, as `bynk.dev`.
453            args.extend([
454                "--var".to_string(),
455                format!(
456                    "{}:{}",
457                    bynk_emit::INSPECT_CALLER_KEY_VAR,
458                    bynk_emit::LOCAL_CALL_KEY
459                ),
460            ]);
461            Some(args)
462        }
463        Err(e) => {
464            emsg!("bynk: error: {e}");
465            None
466        }
467    }
468}
469
470/// #3478: the `--var`s every served Worker gets: `BYNK_DEV` marks a
471/// development session, and each acknowledged remote-only kind (`[dev] ai =
472/// "allow"`) sets its variable to `allow`, which its provider reads to stay
473/// quiet. A deployed Worker has none of them.
474fn dev_var_args(acks: &std::collections::BTreeSet<&'static str>) -> Vec<String> {
475    use bynk_project::dev_ack::{ALLOW, DEV_VAR, REMOTE_KINDS};
476    let mut args = vec!["--var".to_string(), format!("{DEV_VAR}:1")];
477    for kind in REMOTE_KINDS.iter().filter(|k| acks.contains(k.key)) {
478        args.push("--var".to_string());
479        args.push(format!("{}:{ALLOW}", kind.var));
480    }
481    args
482}
483
484#[cfg(test)]
485mod tests {
486    use super::*;
487    use crate::dev::serving::Serving;
488    use crate::dev::stand_ins::StandIn;
489
490    use crate::dev::test_support::generated_shop_config;
491    use crate::dev::test_support::names;
492    use crate::dev::test_support::serving_shop;
493    use crate::dev::test_support::shop_model;
494    use crate::dev::test_support::vectorize_project;
495    use std::collections::BTreeMap;
496
497    /// #3478: every served Worker is marked as a development session, and an
498    /// acknowledged remote-only kind sets its own variable to `allow`.
499    #[test]
500    fn dev_vars_mark_the_session_and_carry_acknowledgements() {
501        use std::collections::BTreeSet;
502        assert_eq!(dev_var_args(&BTreeSet::new()), ["--var", "BYNK_DEV:1"]);
503        assert_eq!(
504            dev_var_args(&BTreeSet::from(["ai"])),
505            ["--var", "BYNK_DEV:1", "--var", "BYNK_DEV_ACK_AI:allow"]
506        );
507        // #3479: Vectorize shares the mechanism, under its own key and variable.
508        assert_eq!(
509            dev_var_args(&BTreeSet::from(["vectorize"])),
510            [
511                "--var",
512                "BYNK_DEV:1",
513                "--var",
514                "BYNK_DEV_ACK_VECTORIZE:allow"
515            ]
516        );
517        // #3480: AI Search has its own acknowledgement.
518        assert_eq!(
519            dev_var_args(&BTreeSet::from(["ai-search"])),
520            [
521                "--var",
522                "BYNK_DEV:1",
523                "--var",
524                "BYNK_DEV_ACK_AI_SEARCH:allow"
525            ]
526        );
527        // #3513 A: and so does an mTLS certificate binding.
528        assert_eq!(
529            dev_var_args(&BTreeSet::from(["mtls"])),
530            ["--var", "BYNK_DEV:1", "--var", "BYNK_DEV_ACK_MTLS:allow"]
531        );
532        // #3513 B: and Analytics SQL.
533        assert_eq!(
534            dev_var_args(&BTreeSet::from(["analytics-sql"])),
535            [
536                "--var",
537                "BYNK_DEV:1",
538                "--var",
539                "BYNK_DEV_ACK_ANALYTICS_SQL:allow"
540            ]
541        );
542    }
543
544    #[test]
545    fn a_secret_is_listed_only_by_a_whole_name() {
546        let table = "šŸ” Listing secrets...\nā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”\n│ Name        │ ID │\nā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¼ā”€ā”€ā”€ā”€ā”¤\n│ stripe-live │ 1  │\nā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”˜\n";
547        assert!(secret_listed(table, "stripe-live"));
548        assert!(!secret_listed(table, "stripe"));
549        assert!(!secret_listed(table, "stripe-live-2"));
550        assert!(!secret_listed("", "stripe-live"));
551    }
552
553    #[test]
554    fn a_missing_local_secret_is_told_how_to_create_it_locally() {
555        let hint =
556            missing_local_secret_hint("shop", "SECRET_STRIPE_KEY", "payments", "stripe-live");
557        assert!(
558            hint.contains(
559                "wrangler secrets-store secret create payments --name stripe-live --scopes workers"
560            ),
561            "{hint}"
562        );
563        assert!(hint.contains("no `--remote`"), "{hint}");
564    }
565
566    /// The served copy points the binding at the stand-in; the generated
567    /// config keeps the real name (review of #2008).
568    #[test]
569    fn the_stand_in_config_is_a_retargeted_copy() {
570        let dir = std::env::temp_dir().join(format!("bynk-stand-in-copy-{}", std::process::id()));
571        let ctx = dir.join("shop-billing");
572        std::fs::create_dir_all(&ctx).unwrap();
573        let generated = "name = \"shop-billing\"\n\n[[services]]\nbinding = \"SERVICE_BILLING\"\nservice = \"legacy-billing\"\n";
574        std::fs::write(ctx.join("wrangler.toml"), generated).unwrap();
575        let plans = vec![(
576            "shop-billing".to_string(),
577            vec![StandIn {
578                worker: "legacy-billing".into(),
579                bindings: names(&["SERVICE_BILLING"]),
580            }],
581        )];
582        let serving = vec![Serving {
583            worker: "shop-billing".to_string(),
584            port: None,
585            inspector_port: None,
586            inspect: false,
587        }];
588        publish_dev_configs(&dir, &serving, &plans).unwrap();
589        assert_eq!(
590            std::fs::read_to_string(ctx.join("wrangler.toml")).unwrap(),
591            generated
592        );
593        let served = std::fs::read_to_string(ctx.join(DEV_CONFIG)).unwrap();
594        assert!(
595            served.contains("service = \"bynk-stand-in-shop-billing-legacy-billing\""),
596            "{served}"
597        );
598        assert!(!ctx.join(format!("{DEV_CONFIG}.tmp")).exists());
599        let _ = std::fs::remove_dir_all(&dir);
600    }
601
602    /// #3505: a rebuild writes the generated config with the deploy's derived
603    /// index names. What `wrangler dev` serves from must never carry them, not
604    /// even between the compile and the development rebind.
605    #[test]
606    fn a_rebuild_never_exposes_the_deploys_index_to_wrangler() {
607        let (root, workers) = vectorize_project("rebuild", "");
608        let available = names(&["shop"]);
609        let serving = serving_shop();
610        let configs = DevConfigs {
611            project_root: &root,
612            workers_dir: &workers,
613            available: &available,
614            serving: &serving,
615            stand_ins: &[],
616            remote: false,
617            environment: "default",
618        };
619        assert!(configs.write(&shop_model(), true));
620        let served = workers.join("shop").join(DEV_CONFIG);
621        let first = std::fs::read_to_string(&served).unwrap();
622        assert!(first.contains("index_name = \"docs-dev\""), "{first}");
623        assert!(!first.contains("shop-docs"), "{first}");
624
625        // The rebuild's compile rewrites the generated config.
626        std::fs::write(
627            workers.join("shop").join("wrangler.toml"),
628            generated_shop_config(""),
629        )
630        .unwrap();
631        let between = std::fs::read_to_string(&served).unwrap();
632        assert!(
633            !between.contains("shop-docs"),
634            "served before the rebind: {between}"
635        );
636
637        assert!(configs.write(&shop_model(), false));
638        let after = std::fs::read_to_string(&served).unwrap();
639        assert!(after.contains("index_name = \"docs-dev\""), "{after}");
640        assert!(!after.contains("shop-docs"), "{after}");
641        let _ = std::fs::remove_dir_all(&root);
642    }
643
644    /// #3505 review: a rebuild that cannot bind serves its Workers unbound, never
645    /// with the deploy's index; one whose config may still name it serves nothing
646    /// new.
647    #[test]
648    fn a_rebuild_that_cannot_bind_never_publishes_the_deploys_index() {
649        let (root, workers) = vectorize_project("unbound", "");
650        let available = names(&["shop"]);
651        let serving = serving_shop();
652        let configs = DevConfigs {
653            project_root: &root,
654            workers_dir: &workers,
655            available: &available,
656            serving: &serving,
657            stand_ins: &[],
658            remote: false,
659            environment: "default",
660        };
661        assert!(configs.write(&shop_model(), true));
662        // `vars` that is not a table: the binding cannot edit the config.
663        std::fs::write(
664            workers.join("shop").join("wrangler.toml"),
665            generated_shop_config("").replace(
666                "name = \"shop\"\n",
667                "name = \"shop\"\nvars = \"not a table\"\n",
668            ),
669        )
670        .unwrap();
671        assert!(!configs.write(&shop_model(), false));
672        let served = std::fs::read_to_string(workers.join("shop").join(DEV_CONFIG)).unwrap();
673        assert!(!served.contains("shop-docs"), "{served}");
674        assert!(!served.contains("VECTORIZE_DOCS"), "{served}");
675        let _ = std::fs::remove_dir_all(&root);
676
677        // A config the unbinding could not edit (a failed write) is never
678        // published; the last good one keeps serving.
679        assert!(!DevVectorize::Unsafe.may_publish(false));
680        assert!(!DevVectorize::Unsafe.may_publish(true));
681        assert!(DevVectorize::Unbound.may_publish(false));
682        assert!(!DevVectorize::Unbound.may_publish(true));
683        assert!(DevVectorize::Bound.may_publish(true));
684    }
685
686    /// #3505: a Worker served with stand-ins is served from its copy, and the
687    /// copy carries the development bindings too.
688    #[test]
689    fn a_worker_with_stand_ins_serves_the_development_index() {
690        let (root, workers) = vectorize_project(
691            "stand-ins",
692            "\n[[services]]\nbinding = \"SERVICE_BILLING\"\nservice = \"legacy-billing\"\n",
693        );
694        let available = names(&["shop"]);
695        let serving = serving_shop();
696        let plans = vec![(
697            "shop".to_string(),
698            vec![StandIn {
699                worker: "legacy-billing".into(),
700                bindings: names(&["SERVICE_BILLING"]),
701            }],
702        )];
703        let configs = DevConfigs {
704            project_root: &root,
705            workers_dir: &workers,
706            available: &available,
707            serving: &serving,
708            stand_ins: &plans,
709            remote: false,
710            environment: "default",
711        };
712        assert!(configs.write(&shop_model(), true));
713        let served = std::fs::read_to_string(workers.join("shop").join(DEV_CONFIG)).unwrap();
714        assert!(
715            served.contains("service = \"bynk-stand-in-shop-legacy-billing\""),
716            "{served}"
717        );
718        assert!(served.contains("index_name = \"docs-dev\""), "{served}");
719        assert!(!served.contains("shop-docs"), "{served}");
720        let _ = std::fs::remove_dir_all(&root);
721    }
722
723    /// An mTLS certificate's name is replaced in the served copy by the ledger's
724    /// id (or the entry dropped), which the model, still naming the certificate,
725    /// must not be read against: `bynk dev` reads Worker bindings from the model,
726    /// never from the files it patches.
727    #[test]
728    fn the_model_is_checked_against_the_build_before_the_dev_patches_edit_it() {
729        use bynk_check::worker_bindings::{BindingSource, WorkerBinding};
730        let (root, workers) = vectorize_project(
731            "mtls",
732            "\n[[mtls_certificates]]\nbinding = \"MTLS_BACKEND\"\ncertificate_id = \"acme-client\"\n",
733        );
734        let binding = |name: &str, source| WorkerBinding {
735            name: name.to_string(),
736            source,
737        };
738        let model = bynk_emit::emit_model::WorkersBuild {
739            bindings: bynk_emit::emitter::WorkerBindings::of_workers(BTreeMap::from([(
740                "shop".to_string(),
741                vec![
742                    binding(
743                        "VECTORIZE_DOCS",
744                        BindingSource::VectorizeIndex {
745                            capability: "Docs".to_string(),
746                            dimensions: 768,
747                            metric: "cosine".to_string(),
748                            indexed: Vec::new(),
749                        },
750                    ),
751                    binding(
752                        "MTLS_BACKEND",
753                        BindingSource::MtlsCertificate {
754                            capability: "Backend".to_string(),
755                            certificate: "acme-client".to_string(),
756                        },
757                    ),
758                ],
759            )])),
760            layout: bynk_project::worker_layout::WorkerLayout::identity(),
761        };
762        let available = names(&["shop"]);
763        let serving = serving_shop();
764        let configs = DevConfigs {
765            project_root: &root,
766            workers_dir: &workers,
767            available: &available,
768            serving: &serving,
769            stand_ins: &[],
770            remote: false,
771            environment: "default",
772        };
773        assert!(configs.write(&model, true));
774        // The patch ran: the unlinked certificate is not in the served copy.
775        let served = std::fs::read_to_string(workers.join("shop").join(DEV_CONFIG)).unwrap();
776        assert!(!served.contains("acme-client"), "{served}");
777        let _ = std::fs::remove_dir_all(&root);
778    }
779}