Skip to main content

bynk/dev/
run.rs

1use super::bindings::DEV_CONFIG;
2use super::bindings::DevConfigs;
3use super::bindings::dev_vars_for;
4use super::bindings::hyperdrive_local_env;
5use super::bindings::materialise_remote_state;
6use super::bindings::warn_missing_local_secrets;
7use super::events::DevEvent;
8use super::events::DevFormat;
9use super::events::emit;
10use super::events::serving_event;
11use super::events::serving_report;
12use super::events::session_of;
13use super::serving::LocalKeys;
14use super::serving::allocate;
15use super::serving::assign_free_inspector;
16use super::serving::free_local_port;
17use super::serving::inspector_port_in_use;
18use super::serving::port_clash;
19use super::serving::serve_args;
20use super::stand_ins::plan_stand_ins;
21use super::stand_ins::stand_in_report;
22use super::stand_ins::write_stand_ins;
23use super::supervise::DRAIN_GRACE;
24use super::supervise::Served;
25use super::supervise::join_pumps;
26use super::supervise::pipes_output;
27use super::supervise::pump_output;
28use super::supervise::supervise;
29use super::supervise::terminate;
30use super::watch::MigrationsSeen;
31use super::watch::apply_local_migrations;
32use super::watch::watch_fingerprint;
33use crate::doctor;
34use crate::doctor::Capability;
35use crate::doctor::Context;
36use crate::doctor::DoctorOptions;
37use crate::doctor::Report;
38use crate::probe;
39use crate::probe::Provenance;
40use crate::probe::Toolbox;
41use crate::report;
42use crate::report::Format;
43use crate::workers::discover_workers;
44use crate::workers::prepare_build_dir;
45use crate::workers::select_contexts;
46use bynk_driver::colour;
47use bynk_driver::emsg;
48use std::path::Path;
49use std::path::PathBuf;
50use std::process::ExitCode;
51
52/// Parsed `bynk dev` flags (the project `PATH` is resolved into `project_root`
53/// before we get here).
54#[derive(Debug, Clone, Default)]
55pub struct DevOptions {
56    /// `--no-install` (or `BYNK_NO_INSTALL`): stop on a missing npm package
57    /// instead of installing it (#3350).
58    pub no_install: bool,
59    /// `--context NAME`, repeatable — which contexts' workers to serve. Empty
60    /// serves **every** context in the project, wired (ADR 0096 D3 superseded).
61    pub contexts: Vec<String>,
62    /// `--base-port N` — the first port of the per-context allocation. `None`
63    /// leaves a lone worker on wrangler's own default, so `-- --port N` keeps
64    /// working exactly as it did when `dev` served one context.
65    pub base_port: Option<u16>,
66    /// `--inspect` (slice 3): start `wrangler dev` with the V8 inspector so a
67    /// JavaScript debugger can attach; breakpoints in `.bynk` resolve through the
68    /// emitted source maps composed into the worker bundle.
69    pub inspect: bool,
70    /// `--inspect-port N` — the base inspector port, allocated per context
71    /// exactly as `base_port` is. `None` means it was not given: the base is
72    /// 9229 under `--inspect` or with several contexts, and a lone worker
73    /// without `--inspect` is given a free port of its own
74    /// ([`assign_free_inspector`]). wrangler's inspector is always on, so left
75    /// on its default every session would race for 9229 (#1954, #3237).
76    pub inspect_port: Option<u16>,
77    /// `--env NAME` (default `"default"`) — which `bynk.deploy.lock` section
78    /// `--remote` reads the KV id from. `dev` never provisions and never
79    /// writes the ledger (unchanged); this only selects which of `deploy`'s
80    /// environments `--remote` connects the placeholder to. Purely a `bynk`
81    /// concept — never forwarded to `wrangler dev` itself, since `dev` curates
82    /// no Wrangler-side environment config (slice 4, #837 review: a project
83    /// deployed only under a non-default `--env` previously read as
84    /// "never provisioned" here, because this always looked at `"default"`).
85    pub environment: String,
86    /// `--local-worker NAME`, repeatable (interop I5, #1972): a foreign
87    /// Worker a `Service` instance names that `wrangler dev` should reach in
88    /// the user's own locally running `wrangler dev` of it, through the dev
89    /// registry, rather than in the stand-in `dev` binds by default.
90    pub local_workers: Vec<String>,
91    /// Everything after `--`, forwarded to `wrangler dev` verbatim (D5).
92    pub wrangler_args: Vec<String>,
93    /// `--format` (#2094): `human` (the default) prints only the readable
94    /// stderr stream; `json` also writes one [`DevEvent`] per line to stdout.
95    pub format: DevFormat,
96    /// `--ready-json FILE` (#2138): once every served context answers a
97    /// probe, write `{ "<worker>": "<url>" }` to FILE ([`crate::ready`]).
98    pub ready_json: Option<PathBuf>,
99    /// `--log-events` (#2474): under `--format json`, also write each line a
100    /// worker prints as a [`DevEvent::Log`], its stack frames rewritten to
101    /// `.bynk` locations. Off by default, so a script reading the stream sees
102    /// only the lifecycle events.
103    pub log_events: bool,
104    /// `--trace-events` (#3580): build the workers with per-request trace
105    /// recording, and write each request as a [`DevEvent::Request`]. Implies
106    /// `--format json`.
107    pub trace_events: bool,
108    /// `--rewrite-frames` (#2474): rewrite stack frames to `.bynk` even on a
109    /// terminal, where the driver otherwise leaves wrangler's output alone.
110    pub rewrite_frames: bool,
111}
112
113/// Whether the forwarded wrangler arguments ask for remote mode: `--remote`,
114/// its `-r` alias, or `--remote=true`.
115pub(crate) fn is_remote(args: &[String]) -> bool {
116    args.iter()
117        .any(|arg| matches!(arg.as_str(), "--remote" | "-r" | "--remote=true"))
118}
119
120/// #837 review: once `--remote` reads a ledger section by `--env`, a
121/// `-- --env`/`-- --environment` passthrough would silently diverge — `bynk`
122/// materialises one environment's KV id while Wrangler actually connects to a
123/// different one. Checked only when `--remote` is present, since `--env` is
124/// otherwise inert (nothing reads the ledger without it). Prints the conflict
125/// and returns `true` when there is one.
126fn remote_env_conflict(opts: &DevOptions) -> bool {
127    if !is_remote(&opts.wrangler_args) {
128        return false;
129    }
130    let Some(conflict) = crate::deploy::conflicting_env_passthrough(&opts.wrangler_args) else {
131        return false;
132    };
133    emsg!(
134        "bynk: error: `--env {}` conflicts with `{conflict}` after `--` — pass one or the other, not both",
135        opts.environment
136    );
137    true
138}
139
140/// #3562 (G6): a group is one Worker, so `--context` naming a member selects the
141/// Worker that holds it, and says so: the rest of the group cannot be left out of a
142/// Worker. A name that is no member passes through (it is a Worker's own, or unknown).
143fn groups_serving(project_root: &Path, requested: &[String]) -> Result<Vec<String>, String> {
144    let groups = bynk_project::worker_groups::try_read_worker_groups(project_root)
145        .map_err(|e| format!("invalid `[deploy.workers]` in `bynk.toml`: {e}"))?;
146    Ok(requested
147        .iter()
148        .map(|name| {
149            let dotted = name.replace('-', ".");
150            let Some((key, _)) = groups
151                .iter()
152                .find(|(_, g)| g.contexts.contains(&dotted))
153            else {
154                return name.clone();
155            };
156            emsg!(
157                "bynk: `{dotted}` is in the Worker group `{key}`, which runs as one Worker: serving the whole group"
158            );
159            key.clone()
160        })
161        .collect())
162}
163
164/// The Workers to serve: every one, or those `--context` names (a group member selecting
165/// its group, [`groups_serving`]).
166fn selected_workers(
167    project_root: &Path,
168    available: &[String],
169    requested: &[String],
170) -> Option<Vec<String>> {
171    let chosen = groups_serving(project_root, requested)
172        .and_then(|r| select_contexts(available, &r).map_err(|e| e.to_string()));
173    chosen.map_err(|e| emsg!("bynk: error: {e}")).ok()
174}
175
176/// Orchestrate a local dev session: pre-flight, compile, select the worker, and
177/// hand off to `wrangler dev`. Returns wrangler's own exit code on a clean
178/// hand-off, or a pre-flight/build failure code before serving.
179pub fn run(
180    tb: &dyn Toolbox,
181    project_root: &Path,
182    node_floor: (u32, u32),
183    opts: &DevOptions,
184) -> ExitCode {
185    if remote_env_conflict(opts) {
186        return ExitCode::FAILURE;
187    }
188
189    if opts.log_events && opts.format != DevFormat::Json {
190        emsg!("bynk: error: `--log-events` writes events, so it needs `--format json`");
191        return ExitCode::FAILURE;
192    }
193
194    // 1. Pre-flight — reuse doctor's Deploy gate (Node + wrangler) plus the
195    //    always-on compile floor. Failing here, with doctor's remedy text, beats
196    //    a confusing error out of a half-built tree (proposal §2.2).
197    let ctx = Context {
198        project_root: Some(project_root.to_path_buf()),
199        in_repo: false,
200        node_floor,
201    };
202    let preflight_opts = DoctorOptions {
203        only: Some(Capability::Deploy),
204        strict: false,
205    };
206    let report = doctor::diagnose(tb, &ctx, &preflight_opts);
207    if report.exit_nonzero(&preflight_opts) {
208        colour::eprint(&preflight_failure_message(&report));
209        return ExitCode::FAILURE;
210    }
211    // 2. Compile — in-process (slice 7: the driver links the pipeline instead of
212    //    shelling a separate compiler). Into the managed `.bynk/dev/` build dir (D1).
213    //    Compilation is additive (never prunes), so clear `workers/` first;
214    //    otherwise a renamed/deleted context would linger and spuriously trip the
215    //    §2.4 ambiguity check.
216    let build_dir = project_root.join(".bynk").join("dev");
217    if let Err(e) = prepare_build_dir(project_root, &build_dir) {
218        emsg!("bynk: error: could not prepare build directory: {e}");
219        return ExitCode::FAILURE;
220    }
221    // #524: compile the SAME project shape as `bynk compile <project_root>`
222    // — the shared rooting rule over the full `[paths]` layout. `dev`
223    // previously re-rooted on the first `include` entry only, silently
224    // dropping further includes and the whole `exclude` list.
225    // #3100: the first build reports each context; a watch rebuild stays quiet.
226    let Some(model) = crate::workers::compile_built(
227        project_root,
228        &build_dir,
229        dev_build(opts),
230        bynk_driver::progress::terminal_sink(),
231    ) else {
232        return ExitCode::FAILURE;
233    };
234
235    // 3. Select the workers — every context by default, or the `--context`
236    //    subset (#552, superseding ADR 0096 D3's select-or-default). Serving
237    //    them *together* is the whole point: a cross-context call only resolves
238    //    when its callee is up too, so an ambiguity error here was the feature
239    //    being withheld, not a project being wrong.
240    let workers_dir = build_dir.join("workers");
241    let available = discover_workers(&workers_dir);
242    let Some(workers) = selected_workers(project_root, &available, &opts.contexts) else {
243        return ExitCode::FAILURE;
244    };
245    let mut serving = allocate(&workers, opts.base_port, opts);
246    // #3237: a lone worker would otherwise take wrangler's default inspector,
247    // 9229, which two sessions starting together both claim. Not when the
248    // caller put `--inspector-port` in the `--` passthrough: that is theirs.
249    if !passthrough_has(&opts.wrangler_args, "--inspector-port") {
250        assign_free_inspector(&mut serving, free_local_port());
251    }
252    if let Some(port) = inspector_port_in_use(&serving) {
253        emsg!(
254            "bynk: error: inspector port {port} is already in use — another `bynk dev` or debugger \
255             holds it. Pass a different `--inspect-port`, or stop the process using it."
256        );
257        return ExitCode::FAILURE;
258    }
259    // I2 (#1971): over every built Worker, not only the served ones, so a
260    // context served here alone still admits a caller served by another
261    // `bynk dev --context` session.
262    let local = match LocalKeys::read(&workers_dir, &available, &model) {
263        Ok(keys) => keys,
264        Err(e) => {
265            emsg!("bynk: error: {e}");
266            return ExitCode::FAILURE;
267        }
268    };
269
270    // Where the driver injects a port it owns the allocation, so the same flag
271    // arriving through `--` is a conflict — and wrangler rejects a repeated
272    // `--port` with a usage dump rather than taking the last one. Catch it here
273    // and name the driver flag that owns it.
274    for (flag, owner, injected) in [
275        (
276            "--port",
277            "--base-port",
278            serving.iter().any(|s| s.port.is_some()),
279        ),
280        (
281            "--inspector-port",
282            "--inspect-port",
283            serving.iter().any(|s| s.inspector_port.is_some()),
284        ),
285    ] {
286        if injected && passthrough_has(&opts.wrangler_args, flag) {
287            emsg!(
288                "bynk: error: `{flag}` is allocated per context — pass `{owner}` to `bynk dev` instead of `-- {flag}`."
289            );
290            return ExitCode::FAILURE;
291        }
292    }
293
294    // Now that inspectors are allocated without `--inspect` too (#1954), an
295    // overlap with the HTTP range is reachable from plain flags (`--base-port
296    // 9229` over two contexts). Name it here rather than leave wrangler to die
297    // with `Address already in use`.
298    if let Some(port) = port_clash(&serving) {
299        emsg!(
300            "bynk: error: port {port} is allocated both to a context's server and to an inspector — \
301             move `--base-port` or `--inspect-port` so the two ranges do not overlap."
302        );
303        return ExitCode::FAILURE;
304    }
305
306    // #3477: a container Worker runs under Docker here, never `--remote`.
307    let Some(containers) =
308        crate::dev_containers::for_session(&model, &serving, &opts.wrangler_args)
309    else {
310        return ExitCode::FAILURE;
311    };
312
313    // Remote dev reads the real Cloudflare ids, unlike Miniflare's local mode,
314    // from the deploy ledger immediately before Wrangler runs.
315    if is_remote(&opts.wrangler_args)
316        && !materialise_remote_state(project_root, &workers_dir, &serving, &opts.environment)
317    {
318        return ExitCode::FAILURE;
319    }
320
321    // Interop I5 (#1972, track §11 Q8): each context's Service Bindings to
322    // foreign Workers get a stand-in in its own `wrangler dev`, unless
323    // `--local-worker` names the Worker (the dev registry then reaches the
324    // user's own `wrangler dev` of it). Under `--remote` the bindings are the
325    // account's, so there is nothing to stand in for.
326    let remote = is_remote(&opts.wrangler_args);
327    let stand_in_plans = plan_stand_ins(&workers_dir, &serving, &available, opts, remote);
328    let user_config = passthrough_has(&opts.wrangler_args, "-c")
329        || passthrough_has(&opts.wrangler_args, "--config");
330    if !stand_in_plans.is_empty() && user_config {
331        emsg!(
332            "bynk: error: `-c`/`--config` is the driver's when it runs stand-ins for foreign Workers — pass `--local-worker NAME` instead of a config after `--`."
333        );
334        return ExitCode::FAILURE;
335    }
336    let stand_in_configs = match write_stand_ins(&build_dir, &stand_in_plans) {
337        Ok(configs) => configs,
338        Err(e) => {
339            emsg!("bynk: error: could not write the stand-ins for foreign Workers: {e}");
340            return ExitCode::FAILURE;
341        }
342    };
343    let dev_configs = DevConfigs {
344        project_root,
345        workers_dir: &workers_dir,
346        available: &available,
347        serving: &serving,
348        stand_ins: &stand_in_plans,
349        remote,
350        environment: &opts.environment,
351    };
352    if !dev_configs.write(&model, true) {
353        return ExitCode::FAILURE;
354    }
355
356    // 4. Serve — one `wrangler dev` per context, each from inside its own worker
357    //    dir (the emitted `index.ts` imports `../../runtime.js`, so cwd must be
358    //    the worker dir, exactly the manual recipe's `cd`). The processes find
359    //    each other through wrangler's **dev registry** and wire the generated
360    //    `[[services]]` bindings between themselves — verified: a binding starts
361    //    `[not connected]` and converges to `[connected]` once its callee is up,
362    //    so start order does not matter and we need not stage the spawns.
363    //    Resolve wrangler once with doctor's provenance ordering; an npx
364    //    resolution downloads on first use, so it is a notice, never a silent
365    //    green path.
366    let (manager, probe) = probe::detect_in_project(tb, "wrangler", project_root);
367    if let Some(runner) = probe.provenance.runner_label() {
368        emsg!("bynk: wrangler resolved via {runner} — it will download on first run.");
369    }
370    if let Some(notice) = wrangler_age_notice(&probe, manager) {
371        colour::eprintln(&notice);
372    }
373    if matches!(probe.provenance, Provenance::Missing) {
374        // The pre-flight gate should have caught this; defensive only.
375        emsg!("bynk: error: wrangler not found (run `bynk doctor --only deploy`)");
376        return ExitCode::FAILURE;
377    }
378
379    // #3477: Docker: containers off when it is absent.
380    let containers_off = crate::dev_containers::session(tb, &containers);
381
382    if !warm_up_wrangler(&probe.provenance, serving.len()) {
383        return ExitCode::FAILURE;
384    }
385
386    // P4b (#2608): each served Worker's local D1 databases get their
387    // migrations before it serves. Never with `--remote`: that database is a
388    // real one, and only `bynk deploy` changes it. Nothing is spawned yet, so
389    // a signal during a slow apply needs no reaping.
390    let mut applied = MigrationsSeen::default();
391    if !remote {
392        apply_local_migrations(
393            &probe.provenance,
394            &workers_dir,
395            &serving,
396            &opts.wrangler_args,
397            &mut applied,
398        );
399        // #3301: and a stored secret the local store does not hold is said
400        // so now, not found as a fault on the first request.
401        warn_missing_local_secrets(
402            &probe.provenance,
403            &workers_dir,
404            &serving,
405            &opts.wrangler_args,
406        );
407    }
408
409    // Inherited stdio (the default) keeps every session interactive. The driver
410    // and the wranglers share the terminal's foreground process group, so a
411    // Ctrl-C SIGINT reaches them all — we must not bail before reaping; we reap
412    // in the watch loop and propagate the first exit code (ADR 0096 §Exit).
413    //
414    // #1955: a SIGINT or SIGTERM sent to `bynk dev` *alone* (a CI step, a test
415    // harness) used to kill it outright and strand every wrangler and its
416    // `workerd`s. Record it instead, and let the watch loop stop the contexts.
417    // Installed before the spawns, so there is no window in which a child is
418    // up and the driver still dies of the default action; the children
419    // themselves get the default back at `exec`.
420    crate::stop::install();
421    // #3319: each `Postgres` instance's local connection string, from the
422    // variable `[dev.hyperdrive]` names, into that Worker's environment only.
423    let Some(local_strings) = hyperdrive_local_env(project_root, &workers_dir, &serving, remote)
424    else {
425        return ExitCode::FAILURE;
426    };
427    // #3478: `BYNK_DEV` and the acknowledged remote-only kinds, as `--var`s.
428    let Some(dev_vars) = dev_vars_for(project_root) else {
429        return ExitCode::FAILURE;
430    };
431    let rewriter = std::sync::Arc::new(crate::logs::Rewriter::new(&build_dir));
432    let mut children: Vec<(String, Served)> = Vec::new();
433    let mut pumps: Vec<std::thread::JoinHandle<()>> = Vec::new();
434    for s in &serving {
435        let Some(mut cmd) = crate::cloudflare::spawn_command(&probe.provenance, "dev") else {
436            emsg!("bynk: error: wrangler not found (run `bynk doctor --only deploy`)");
437            terminate(&mut children, &workers_dir);
438            return ExitCode::FAILURE;
439        };
440        cmd.current_dir(workers_dir.join(&s.worker));
441        // Interop I5 (#1972): the context's own config first (wrangler's
442        // primary Worker, the one served on the port), then its stand-ins.
443        // #3505: a `-- -c`/`--config` of the developer's own (refused above when
444        // stand-ins run) is served as given.
445        if !user_config {
446            cmd.args(["-c", DEV_CONFIG]);
447        }
448        for config in stand_in_configs.get(&s.worker).into_iter().flatten() {
449            cmd.arg("-c").arg(config);
450        }
451        let keys = local
452            .edge
453            .get(&s.worker)
454            .map(Vec::as_slice)
455            .unwrap_or_default();
456        cmd.args(serve_args(s, keys));
457        cmd.args(&dev_vars);
458        cmd.args(crate::dev_containers::off_args_for(
459            containers_off,
460            &containers,
461            &s.worker,
462        ));
463        cmd.args(local.session_args(&s.worker, &opts.wrangler_args));
464        for arg in &opts.wrangler_args {
465            cmd.arg(arg);
466        }
467        for local in local_strings.get(&s.worker).into_iter().flatten() {
468            cmd.env(&local.name, &local.value);
469        }
470        // #2474: off a terminal (the editor's task, CI) or on request,
471        // wrangler's output passes through the driver, line by line, so a
472        // stack frame into generated code is rewritten to the `.bynk` line it
473        // came from. On a terminal it is left alone: piping would turn off
474        // wrangler's colour and interactive hotkeys. Piped output is not a
475        // terminal, so colour is asked back for when ours is one. `--color
476        // always`/`never` is passed on either way.
477        let piped = pipes_output(opts);
478        bynk_driver::colour::apply_to_child(&mut cmd, piped);
479        if piped {
480            cmd.stdout(std::process::Stdio::piped())
481                .stderr(std::process::Stdio::piped());
482        } else if opts.format == DevFormat::Json {
483            // #2094: stdout is the event stream, so wrangler's banner and
484            // request log go to stderr with the rest of the readable output.
485            cmd.stdout(std::io::stderr());
486        }
487        match cmd.spawn() {
488            Ok(mut child) => {
489                if piped {
490                    pumps.extend(pump_output(&mut child, &s.worker, &rewriter, opts));
491                }
492                children.push((s.worker.clone(), Served::new(child)));
493            }
494            Err(e) => {
495                let w = &s.worker;
496                emsg!("bynk: error: could not run wrangler for `{w}`: {e}");
497                terminate(&mut children, &workers_dir);
498                return ExitCode::FAILURE;
499            }
500        }
501    }
502    colour::eprint(&serving_report(&serving));
503    colour::eprint(&stand_in_report(&stand_in_plans));
504    let serving_now = serving_event(&serving, &opts.wrangler_args);
505    emit(opts.format, &serving_now);
506    let _session = crate::dev_inspect::SessionFile::write(
507        project_root,
508        &session_of(&serving_now, &workers_dir),
509    );
510    // #2138: `--ready-json` — written from the watch loop below once every
511    // served context answers a probe. The probe is plain HTTP on localhost,
512    // so a server it can't reach never reads as ready; say so up front.
513    if opts.ready_json.is_some()
514        && let Some(why) = crate::ready::unprobeable(&opts.wrangler_args)
515    {
516        emsg!(
517            "bynk dev: warning: {why}, which the `--ready-json` probe (plain HTTP on localhost) can't reach, so the file may never be written."
518        );
519    }
520    let mut readiness = opts.ready_json.as_ref().map(|file| {
521        let DevEvent::Serving { contexts } = &serving_now else {
522            unreachable!("serving_event builds a Serving event")
523        };
524        crate::ready::Readiness::new(
525            file.clone(),
526            contexts
527                .iter()
528                .map(|c| (c.name.clone(), c.port, c.url.clone())),
529        )
530    });
531
532    // 5. Watch — #524: `bynk dev` is the edit loop, so watch the project's
533    // `.bynk` sources (the full `[paths]` layout plus `bynk.toml`) and rebuild
534    // into the same build dir on change. Each `wrangler dev` watches its own
535    // built worker files, so one rebuild hot-reloads every context that changed
536    // without a restart; a failing rebuild renders diagnostics and keeps both
537    // the watch and the last good build serving. std-only mtime polling
538    // (500ms): no native watcher dependency, and an edit-loop latency well
539    // under a keystroke-to-glance.
540    emsg!("bynk dev: watching for source changes (edit `.bynk` files to rebuild)");
541    let mut fingerprint = watch_fingerprint(project_root);
542    // The model of the last good build, replaced only by a build that
543    // succeeds, as the build it describes is.
544    let mut model = model;
545    let code = supervise(&mut children, &workers_dir, || {
546        if let Some(r) = readiness.as_mut() {
547            if let Some(written) = r.poll(crate::ready::probe) {
548                match written {
549                    Ok(()) => emsg!("bynk dev: every context answers — ready"),
550                    // Not retried: the session keeps serving, unsignalled.
551                    Err(e) => emsg!("bynk: warning: could not write the `--ready-json` file: {e}"),
552                }
553            }
554            if let Some(note) = r.slow_note(std::time::Instant::now()) {
555                colour::eprintln(&note);
556            }
557        }
558        let now = watch_fingerprint(project_root);
559        if now != fingerprint {
560            fingerprint = now;
561            emsg!("bynk dev: change detected — rebuilding…");
562            emit(opts.format, &DevEvent::Rebuilding);
563            let rebuild = dev_build(opts);
564            if let Some(rebuilt) =
565                crate::workers::compile_built(project_root, &build_dir, rebuild, None)
566            {
567                model = rebuilt;
568                // Interop I5 (#1972): a binding added since start has no
569                // stand-in until `bynk dev` restarts.
570                dev_configs.write(&model, false);
571                emsg!("bynk dev: rebuilt");
572                emit(opts.format, &DevEvent::RebuildOk);
573            } else {
574                // The diagnostics are already rendered; keep serving the last
575                // good build and keep watching.
576                emit(opts.format, &DevEvent::RebuildFailed);
577            }
578        }
579    });
580    // The workers are stopped: let their last lines out before `stopped`.
581    join_pumps(pumps, DRAIN_GRACE);
582    if let Some(r) = &readiness {
583        r.stop();
584    }
585    emit(opts.format, &DevEvent::Stopped { code });
586    ExitCode::from(code)
587}
588
589/// How `bynk dev` builds, first and on every rebuild: it reconciles the schema
590/// lock, never dry-runs, and (#3580, `--trace-events`) records request traces.
591fn dev_build(opts: &DevOptions) -> crate::workers::Build {
592    crate::workers::Build::new(true, false)
593        .no_install(opts.no_install)
594        .trace_requests(opts.trace_events)
595        .inspect_agents(true)
596}
597
598/// #1957: N parallel first-run `npx wrangler dev`s race to install into the
599/// same `_npx` cache entry, and the loser dies at boot (ENOTEMPTY). Install it
600/// once, up front, so every spawn finds it already there. Stdout is dropped
601/// (the version line is noise); stderr stays, because npm's progress is the
602/// only sign a slow first download is not a hang. `false` when it could not be
603/// installed: spawning anyway would re-run the very race this avoids.
604fn warm_up_wrangler(provenance: &Provenance, serving: usize) -> bool {
605    if !needs_wrangler_warmup(provenance, serving) {
606        return true;
607    }
608    let runner = provenance.runner_label().unwrap_or("npx");
609    emsg!("bynk dev: installing wrangler via {runner} once before starting the contexts…");
610    let warmed = crate::cloudflare::spawn_command(provenance, "--version").map(|mut cmd| {
611        cmd.stdout(std::process::Stdio::null())
612            .status()
613            .is_ok_and(|s| s.success())
614    });
615    if warmed != Some(true) {
616        emsg!(
617            "bynk: error: `{}` failed — wrangler could not be installed via {runner}.",
618            wrangler_warm_up_command_line(provenance)
619        );
620        return false;
621    }
622    true
623}
624
625/// The warm-up command as a user would type it, to reproduce a failure.
626fn wrangler_warm_up_command_line(provenance: &Provenance) -> String {
627    let Provenance::Runner(manager) = provenance else {
628        return "wrangler --version".to_string();
629    };
630    let program = manager.runner_program().unwrap_or("npx");
631    let args = manager.runner_args(bynk_driver::tools::pins::WRANGLER_SPEC, "wrangler");
632    format!("{program} {} --version", args.join(" "))
633}
634
635/// #1732: the warning `bynk dev` prints before serving with a wrangler older
636/// than [`bynk_emit::WRANGLER_MIN`]. An older `workerd` can refuse the pinned
637/// compatibility date outright, and wrangler's own error says nothing about
638/// Bynk, so this names the cause and the fix first. A warning, not a refusal:
639/// the version is `doctor`'s judgement, and the wrangler itself has the last
640/// word. `None` when the wrangler is new enough, or can't be versioned (npx).
641pub fn wrangler_age_notice(
642    probe: &probe::Probe,
643    manager: bynk_driver::npm_install::PackageManager,
644) -> Option<String> {
645    let v = probe
646        .version
647        .filter(|_| doctor::wrangler_below_min(probe))?;
648    Some(format!(
649        "bynk: warning: wrangler {v} is older than {}, the oldest this Bynk release supports; \
650         an older runtime may refuse compatibility date {}, and `wrangler dev` then exits. \
651         Upgrade with `{}`.",
652        bynk_emit::WRANGLER_MIN,
653        bynk_emit::COMPATIBILITY_DATE,
654        doctor::wrangler_upgrade_remedy(probe, manager)
655    ))
656}
657
658/// The text `bynk dev` prints when the deploy pre-flight fails: a lead line plus
659/// doctor's own human report, so the remedy lines are identical to `bynk
660/// doctor`. Pure (no I/O) so this deterministic surface is pinned by a golden
661/// (§5), unlike the non-deterministic `wrangler dev` stream.
662pub fn preflight_failure_message(report: &Report) -> String {
663    format!(
664        "bynk: error: environment not ready for `dev` — see below.\n\n{}",
665        report::render(report, Format::Human)
666    )
667}
668
669/// #1957: whether to install wrangler once before spawning the contexts. Only
670/// an npx resolution installs on first use, and only several spawns at once
671/// race each other in npm's `_npx` cache; a lone context installs alone.
672pub fn needs_wrangler_warmup(provenance: &Provenance, contexts: usize) -> bool {
673    matches!(provenance, Provenance::Runner(_)) && contexts > 1
674}
675
676/// Whether the `--` passthrough carries `flag`, which the driver also injects.
677/// Wrangler rejects a repeated `--port`/`--inspector-port` outright ("expects a
678/// single value, but received multiple"), so we catch the clash ourselves and
679/// say which driver flag owns it instead of letting wrangler's usage dump land.
680pub(super) fn passthrough_has(args: &[String], flag: &str) -> bool {
681    args.iter()
682        .any(|a| a == flag || a.starts_with(&format!("{flag}=")))
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688    use crate::dev::test_support::group_project;
689    use crate::dev::test_support::names;
690    use crate::probe::Provenance;
691    use crate::workers::SelectError;
692    use crate::workers::select_contexts;
693    use bynk_driver::npm_install::PackageManager;
694
695    use std::path::PathBuf;
696
697    /// #3562 (G6): `--context` naming a member of a group serves the Worker that holds it
698    /// (dotted or dashed); a Worker's own name, or an unknown one, passes through.
699    #[test]
700    fn a_member_context_serves_the_group_that_holds_it() {
701        let root = group_project(
702            "serve",
703            "[project]\nname = \"p\"\nversion = \"0.1.0\"\n\n[deploy.workers.core]\ncontexts = [\"shop.a\", \"shop.b\"]\n",
704        );
705        let served = groups_serving(
706            &root,
707            &names(&["shop.a", "shop-b", "core", "shop.pay", "nope"]),
708        )
709        .unwrap();
710        assert_eq!(served, names(&["core", "core", "core", "shop.pay", "nope"]));
711        let _ = std::fs::remove_dir_all(&root);
712    }
713
714    #[test]
715    fn a_project_with_no_groups_passes_its_contexts_through() {
716        let root = group_project("none", "[project]\nname = \"p\"\nversion = \"0.1.0\"\n");
717        assert_eq!(
718            groups_serving(&root, &names(&["shop.a"])).unwrap(),
719            names(&["shop.a"])
720        );
721        let _ = std::fs::remove_dir_all(&root);
722    }
723
724    #[test]
725    fn a_sole_context_is_selected_without_a_flag() {
726        assert_eq!(
727            select_contexts(&names(&["links"]), &[]),
728            Ok(names(&["links"]))
729        );
730    }
731
732    #[test]
733    fn no_workers_is_its_own_error() {
734        assert_eq!(select_contexts(&[], &[]), Err(SelectError::NoneBuilt));
735    }
736
737    // ---- #552: multi-context selection ------------------------------------
738
739    #[test]
740    fn no_context_flag_serves_every_context() {
741        // The defining change: several contexts is the expected shape, so the
742        // whole project is served rather than refused as ambiguous.
743        assert_eq!(
744            select_contexts(&names(&["api", "worker"]), &[]),
745            Ok(names(&["api", "worker"]))
746        );
747    }
748
749    #[test]
750    fn context_flags_narrow_to_a_subset() {
751        let avail = names(&["api", "commerce-payment", "worker"]);
752        assert_eq!(
753            select_contexts(&avail, &names(&["worker", "api"])),
754            Ok(names(&["api", "worker"])),
755            "the subset is served in the deterministic order, not the typed one"
756        );
757        // Dotted and dasherised forms both resolve, and repeats collapse.
758        assert_eq!(
759            select_contexts(&avail, &names(&["commerce.payment", "commerce-payment"])),
760            Ok(names(&["commerce-payment"]))
761        );
762    }
763
764    #[test]
765    fn selecting_many_reports_an_unknown_context() {
766        assert_eq!(
767            select_contexts(&names(&["api"]), &names(&["api", "nope"])),
768            Err(SelectError::NotFound {
769                requested: "nope".to_string(),
770                available: names(&["api"]),
771            })
772        );
773    }
774
775    #[test]
776    fn selecting_many_from_an_empty_build_is_still_none_built() {
777        assert_eq!(select_contexts(&[], &[]), Err(SelectError::NoneBuilt));
778    }
779
780    #[test]
781    fn the_warm_up_failure_quotes_the_command_to_reproduce() {
782        let line = |m| wrangler_warm_up_command_line(&Provenance::Runner(m));
783        assert_eq!(
784            line(PackageManager::Npm),
785            "npx --yes -p wrangler@4 wrangler --version"
786        );
787        assert_eq!(
788            line(PackageManager::Pnpm),
789            "pnpm dlx --package wrangler@4 wrangler --version"
790        );
791        assert_eq!(
792            line(PackageManager::Bun),
793            "bunx --package wrangler@4 wrangler --version"
794        );
795    }
796
797    #[test]
798    fn npx_is_warmed_up_only_for_several_contexts() {
799        // #1957: parallel first-run `npx` installs race in npm's cache.
800        assert!(needs_wrangler_warmup(
801            &Provenance::Runner(PackageManager::Npm),
802            2
803        ));
804        assert!(!needs_wrangler_warmup(
805            &Provenance::Runner(PackageManager::Npm),
806            1
807        ));
808        let installed = Provenance::Path(PathBuf::from("/usr/bin/wrangler"));
809        assert!(!needs_wrangler_warmup(&installed, 2));
810    }
811}