Skip to main content

bynk/
workers.rs

1//! Shared Workers-build plumbing for `bynk dev` and `bynk deploy`.
2//!
3//! Both commands do the same four things before they diverge: prepare a managed
4//! build directory, compile the project into it, discover the worker directories
5//! that came out, and shell `wrangler`. That machinery grew up inside `dev.rs`
6//! and `deploy.rs` reached across for it, which left `dev` reading as `deploy`'s
7//! utility library. It lives here instead — a sibling of both, owned by neither.
8
9use bynk_driver::emsg;
10use std::path::Path;
11
12use bynk_driver::project::{BuildTarget, SchemaLock};
13
14/// One compile of the project into `build_dir`, in-process, on the same rooting
15/// rule as `bynk compile <project_root>` (#524, via
16/// [`bynk_driver::project_options`]). Returns `false` on failure with the
17/// diagnostics already rendered.
18///
19/// `schema_registry` (#980): `true` for the real `bynk dev`/`bynk deploy`
20/// call sites — otherwise a deploy could ship a `schemaVersion` computed
21/// purely from `@schema(N)` annotations, diverging from what `bynk compile`
22/// would have shipped for the same source (the write is a no-op when the
23/// tree is already up to date). `false` for
24/// `compile_once_warnings_behaviour.rs`, the only other caller: it compiles a
25/// **committed** repo fixture in place, the same hazard
26/// `bynk-tests/tests/e2e.rs`'s in-place fixtures have — an unconditional write
27/// would leave a real `bynk.schema.lock` in the tree on every test run.
28pub fn compile_once(project_root: &Path, build_dir: &Path, schema_registry: bool) -> bool {
29    // Never installs (#3350): the callers are `bynk tail` and fixtures compiled in
30    // place, neither of which should run a package manager. A missing npm
31    // package stops the build, naming the command, as it did before installing.
32    compile_once_reporting(
33        project_root,
34        build_dir,
35        Build::new(schema_registry, false).no_install(true),
36        None,
37    )
38}
39
40/// How a build is made: whether it reconciles `bynk.schema.lock`, whether it
41/// only reports what a deploy would do (`--dry-run`), which never installs, and
42/// whether a missing npm package stops it instead of being installed (#3350).
43#[derive(Clone, Copy)]
44pub struct Build {
45    schema_registry: bool,
46    dry_run: bool,
47    no_install: bool,
48    /// #3580: record per-request traces (`bynk dev --trace-events`).
49    trace_requests: bool,
50    /// #3581: record agent instances and answer the inspect route (`bynk dev`).
51    inspect_agents: bool,
52}
53
54impl Build {
55    pub fn new(schema_registry: bool, dry_run: bool) -> Self {
56        Build {
57            schema_registry,
58            dry_run,
59            no_install: false,
60            trace_requests: false,
61            inspect_agents: false,
62        }
63    }
64
65    /// `bynk dev` (#3581): build the Workers so a running session can list and read
66    /// its agent instances. Never set for a deploy build.
67    pub fn inspect_agents(self, inspect_agents: bool) -> Self {
68        Build {
69            inspect_agents,
70            ..self
71        }
72    }
73
74    /// `bynk dev --trace-events` (#3580): build the Workers with per-request
75    /// trace recording, and the compatibility flag its request scope needs.
76    pub fn trace_requests(self, trace_requests: bool) -> Self {
77        Build {
78            trace_requests,
79            ..self
80        }
81    }
82
83    /// `--no-install`, or `BYNK_NO_INSTALL` in the environment (#3350): a
84    /// missing npm package stops the build, naming the install command,
85    /// instead of being installed.
86    pub fn no_install(self, no_install: bool) -> Self {
87        Build {
88            no_install: no_install || bynk_driver::npm_install::no_install_from_env(),
89            ..self
90        }
91    }
92}
93
94/// #3580: a traced build records per-request steps, and finds the request's
95/// record through `AsyncLocalStorage`, which a Worker has under `nodejs_als` (or
96/// `nodejs_compat`, which includes it). The flag goes through the ordinary
97/// `compatibility_flags` path, so it merges with the project's own; it is added
98/// only when neither is already listed, so the duplicate warning never fires.
99fn with_trace(
100    options: bynk_driver::project::CompileOptions,
101    trace_requests: bool,
102) -> bynk_driver::project::CompileOptions {
103    if !trace_requests {
104        return options;
105    }
106    let mut flags = options.compatibility_flags.clone();
107    if !flags
108        .iter()
109        .any(|f| f == "nodejs_als" || f == "nodejs_compat")
110    {
111        flags.push("nodejs_als".to_string());
112    }
113    options.compatibility_flags(flags).trace_requests(true)
114}
115
116/// [`compile_once`], reporting each context to `progress` as it compiles (#3100).
117pub fn compile_once_reporting(
118    project_root: &Path,
119    build_dir: &Path,
120    build: Build,
121    progress: Option<bynk_driver::project::ProgressSink>,
122) -> bool {
123    compile_built(project_root, build_dir, build, progress).is_some()
124}
125
126/// [`compile_once_reporting`], handing back the binding model the build wrote
127/// its Workers from (1C.3a, #4040), or `None` when the build failed (already
128/// reported). The commands that act on a Worker's bindings read this rather
129/// than reading them back out of the files.
130pub fn compile_built(
131    project_root: &Path,
132    build_dir: &Path,
133    build: Build,
134    progress: Option<bynk_driver::project::ProgressSink>,
135) -> Option<bynk_emit::emit_model::WorkersBuild> {
136    // #1078: `bynk-emit` touches no disk for `bynk.schema.lock` — read its
137    // current content here (verified-absent `None` for a fresh project) and
138    // hand it in; write the reconciled content back after a clean compile.
139    let schema_lock = if build.schema_registry {
140        match bynk_driver::schema_lock::read(project_root) {
141            Ok(existing) => SchemaLock::On { existing },
142            Err(e) => {
143                emsg!(
144                    "bynk: error: could not read {}: {e}",
145                    bynk_driver::schema_lock::lock_path(project_root).display()
146                );
147                return None;
148            }
149        }
150    } else {
151        SchemaLock::Off
152    };
153    let options = match bynk_driver::try_project_options(project_root) {
154        // #1821 (ADR 0147 D3): the deployable carries no `suite`.
155        Ok(o) => o
156            .target(BuildTarget::Workers)
157            .schema_registry(schema_lock)
158            .progress(progress)
159            .tests(false),
160        Err(e) => {
161            emsg!("bynk: error: {e}");
162            return None;
163        }
164    };
165    let options = with_trace(options, build.trace_requests).inspect_agents(build.inspect_agents);
166    let output = match bynk_driver::project::compile_project(&options) {
167        Ok(out) => out,
168        Err(failure) => {
169            // Render with full source context, exactly as the shelled `bynk
170            // compile` did — the front-end's flatten-then-delegate (ADR 0100),
171            // shared with `bynk check` (see `crate::diagnostics`).
172            crate::diagnostics::render_project_failure(&failure);
173            return None;
174        }
175    };
176    // A write failure here is reported but does not fail the build — the
177    // same non-fatal handling `schema_registry::write`'s own eprintln used
178    // to give it when this lived inside `compile_project`.
179    // #3796: a dry run reconciles the lock in memory only; the project's
180    // committed lock changes when a real build does.
181    if let Some(content) = &output.schema_lock
182        && !build.dry_run
183        && let Err(e) = bynk_driver::schema_lock::write_reporting("bynk", project_root, content)
184    {
185        emsg!(
186            "bynk: warning: could not write {}: {e}",
187            bynk_driver::schema_lock::lock_path(project_root).display()
188        );
189    }
190    if let Err(e) = bynk_driver::write_output(&output, build_dir) {
191        emsg!(
192            "bynk: error: could not write build output under `{}`: {e}",
193            build_dir.display()
194        );
195        return None;
196    }
197    // ADR 0117: surface non-failing warnings.
198    crate::diagnostics::print_project_warnings(
199        &output.warnings,
200        &output.snapshots,
201        &output.display_root,
202    );
203    // #3350: install the emitted `package.json`'s packages with the project's
204    // own package manager before wrangler runs. A dry run reports instead, and
205    // `--no-install` stops, naming the detected command.
206    let mode = bynk_driver::npm_install::Mode::of(build.dry_run, build.no_install);
207    let setting = bynk_driver::npm_install::configured_manager(project_root);
208    // #3796: a dry run builds in a scratch directory; its report names where a
209    // real deploy installs.
210    let shown_dir = if build.dry_run {
211        project_root.join(".bynk").join("deploy")
212    } else {
213        build_dir.to_path_buf()
214    };
215    if let Err(e) = bynk_driver::npm_install::install_for_project_shown_as(
216        project_root,
217        build_dir,
218        &shown_dir,
219        setting.as_deref(),
220        mode,
221    ) {
222        emsg!("bynk: error: {e}");
223        return None;
224    }
225    output.workers
226}
227
228/// #3796: where a `bynk deploy --dry-run` builds: a fresh directory under the
229/// system's temporary directory, removed when this is dropped, so previewing a
230/// deploy leaves the project as it found it.
231pub struct ScratchBuildDir(std::path::PathBuf);
232
233impl ScratchBuildDir {
234    pub fn new() -> std::io::Result<Self> {
235        let nanos = std::time::SystemTime::now()
236            .duration_since(std::time::UNIX_EPOCH)
237            .map_or(0, |d| d.as_nanos());
238        let dir =
239            std::env::temp_dir().join(format!("bynk-deploy-plan-{}-{nanos}", std::process::id()));
240        std::fs::create_dir_all(&dir)?;
241        Ok(ScratchBuildDir(dir))
242    }
243
244    pub fn path(&self) -> &Path {
245        &self.0
246    }
247}
248
249impl Drop for ScratchBuildDir {
250    fn drop(&mut self) {
251        let _ = std::fs::remove_dir_all(&self.0);
252    }
253}
254
255/// Ensure `.bynk/` is gitignored on first build (cargo's `target/.gitignore`
256/// precedent — a `dev` run never dirties `git status`), then clear the
257/// `workers/` tree so selection only ever sees this build's contexts (D1).
258pub fn prepare_build_dir(project_root: &Path, build_dir: &Path) -> std::io::Result<()> {
259    let bynk_dir = project_root.join(".bynk");
260    std::fs::create_dir_all(&bynk_dir)?;
261    let gitignore = bynk_dir.join(".gitignore");
262    if !gitignore.exists() {
263        std::fs::write(&gitignore, "*\n")?;
264    }
265    let workers = build_dir.join("workers");
266    match std::fs::remove_dir_all(&workers) {
267        Ok(()) => Ok(()),
268        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
269        Err(e) => Err(e),
270    }
271}
272
273/// The worker directories under `<build>/workers/` that carry a `wrangler.toml`
274/// (the unit `wrangler dev` can serve), sorted for deterministic messages.
275pub fn discover_workers(workers_dir: &Path) -> Vec<String> {
276    let mut names = Vec::new();
277    let Ok(entries) = std::fs::read_dir(workers_dir) else {
278        return names;
279    };
280    for entry in entries.flatten() {
281        let path = entry.path();
282        if path.join("wrangler.toml").is_file()
283            && let Some(name) = path.file_name().and_then(|n| n.to_str())
284        {
285            names.push(name.to_string());
286        }
287    }
288    names.sort();
289    names
290}
291
292/// Why context selection failed — rendered to the user with the next step.
293#[derive(Debug, PartialEq, Eq)]
294pub enum SelectError {
295    /// No worker was produced by the compile (e.g. an empty project).
296    NoneBuilt,
297    /// `--context NAME` named a context that doesn't exist.
298    NotFound {
299        requested: String,
300        available: Vec<String>,
301    },
302}
303
304impl std::fmt::Display for SelectError {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        match self {
307            SelectError::NoneBuilt => {
308                write!(
309                    f,
310                    "no workers were built — does the project define any contexts?"
311                )
312            }
313            SelectError::NotFound {
314                requested,
315                available,
316            } => write!(
317                f,
318                "no context `{requested}` — available: {}",
319                available.join(", ")
320            ),
321        }
322    }
323}
324
325/// Match one requested context against the built worker dirs, accepting either
326/// the dotted name or its dasherised form (`commerce.payment` /
327/// `commerce-payment`).
328fn resolve_one(available: &[String], name: &str) -> Result<String, SelectError> {
329    let dashed = name.replace('.', "-");
330    available
331        .iter()
332        .find(|d| d.as_str() == name || d.as_str() == dashed)
333        .cloned()
334        .ok_or_else(|| SelectError::NotFound {
335            requested: name.to_string(),
336            available: available.to_vec(),
337        })
338}
339
340/// Pick the workers `dev` will serve **together** (#552). No `--context` serves
341/// every context in the project — the whole point of the increment, since a
342/// cross-context call only resolves when its callee is up too. `--context` is
343/// repeatable and narrows to a subset, in `available`'s deterministic order
344/// rather than the order they were typed, and duplicates collapse.
345///
346/// There is no `Ambiguous` case: several contexts is the expected shape, not a
347/// failure. Pure (the FS scan is the caller's) so the rule is unit-tested.
348pub fn select_contexts(
349    available: &[String],
350    requested: &[String],
351) -> Result<Vec<String>, SelectError> {
352    if available.is_empty() {
353        return Err(SelectError::NoneBuilt);
354    }
355    if requested.is_empty() {
356        return Ok(available.to_vec());
357    }
358    let mut chosen = Vec::new();
359    for name in requested {
360        let worker = resolve_one(available, name)?;
361        if !chosen.contains(&worker) {
362            chosen.push(worker);
363        }
364    }
365    chosen.sort();
366    Ok(chosen)
367}
368
369#[cfg(test)]
370mod trace_flag_tests {
371    use super::with_trace;
372
373    fn flags(listed: &[&str], trace: bool) -> Vec<String> {
374        let mut o = bynk_driver::project::CompileOptions::single(".");
375        o.compatibility_flags = listed.iter().map(|s| s.to_string()).collect();
376        with_trace(o, trace).compatibility_flags
377    }
378
379    #[test]
380    fn a_traced_build_adds_the_request_scope_flag_once() {
381        assert_eq!(flags(&[], true), ["nodejs_als"]);
382        assert_eq!(flags(&["x"], true), ["x", "nodejs_als"]);
383    }
384
385    #[test]
386    fn a_flag_that_already_provides_it_is_left_alone() {
387        assert_eq!(flags(&["nodejs_compat"], true), ["nodejs_compat"]);
388        assert_eq!(flags(&["nodejs_als"], true), ["nodejs_als"]);
389    }
390
391    #[test]
392    fn an_untraced_build_is_untouched() {
393        assert!(flags(&[], false).is_empty());
394    }
395}