Skip to main content

bynk/deploy/plan/
run.rs

1use super::model::GroupNames;
2use super::model::account_name_problem;
3use super::model::confirm;
4use super::model::confirm_destructive;
5use super::model::derive_plan;
6use super::model::recreate_refusal;
7use crate::cloudflare::Wrangler;
8use crate::deploy::LOCK_FILE;
9use crate::deploy::agent_move::checked_agent_moves;
10use crate::deploy::apply::LedgerWriter;
11use crate::deploy::apply::PlanApply;
12use crate::deploy::apply::apply_plan;
13use crate::deploy::apply::prune_plan;
14use crate::deploy::config::Resources;
15use crate::deploy::config::deployed_worker_name;
16use crate::deploy::config::project_resources;
17use crate::deploy::config::read_contracts_manifest;
18use crate::deploy::containers::apply_adoptions;
19use crate::deploy::destinations::print_plan_then_forward_warnings;
20use crate::deploy::gates::AccountChecked;
21use crate::deploy::gates::AccountCx;
22use crate::deploy::gates::ContextGate;
23use crate::deploy::gates::KeysCx;
24use crate::deploy::gates::account_checks;
25use crate::deploy::gates::check_foreign_pins;
26use crate::deploy::gates::context_gate;
27use crate::deploy::gates::decide_keys;
28use crate::deploy::gates::ordered;
29use crate::deploy::gates::preflight;
30use crate::deploy::graph::service_graph;
31use crate::deploy::hyperdrive;
32use crate::deploy::kind::Kv;
33use crate::deploy::kind::LedgerView;
34use crate::deploy::kind::Lives;
35use crate::deploy::kind::ProjectCx;
36use crate::deploy::kind::Tools;
37use crate::deploy::ledger::DeployLock;
38use crate::deploy::ledger::read_lock;
39use crate::deploy::provisioning::secrets_file_supported;
40use crate::deploy::provisioning::sweep_stale_upload_dirs;
41use crate::deploy::secrets::SecretSource;
42use crate::deploy::secrets::wrangler_runner_in;
43use crate::probe::Toolbox;
44use crate::workers;
45use bynk_driver::colour;
46use bynk_driver::emsg;
47use std::collections::BTreeSet;
48use std::path::Path;
49use std::process::ExitCode;
50
51/// Where a deploy builds, ready to write into. A real deploy keeps its build
52/// under `.bynk/deploy`; a dry run builds in a scratch directory, removed when
53/// the returned guard is dropped, so it writes nothing to the project (#3796).
54/// `None` once the failure has been reported.
55fn build_dir_for(
56    project_root: &Path,
57    dry_run: bool,
58) -> Option<(std::path::PathBuf, Option<workers::ScratchBuildDir>)> {
59    let prepared = if dry_run {
60        workers::ScratchBuildDir::new().map(|s| (s.path().to_path_buf(), Some(s)))
61    } else {
62        let build_dir = project_root.join(".bynk").join("deploy");
63        workers::prepare_build_dir(project_root, &build_dir).map(|()| (build_dir, None))
64    };
65    prepared
66        .map_err(|e| emsg!("bynk: error: could not prepare build directory: {e}"))
67        .ok()
68}
69
70/// The rebuild after recording older contracts: the same build as the first,
71/// so `--no-install` and `--dry-run` apply to it as well (#3350).
72pub(crate) fn rebuild(project_root: &Path, build_dir: &Path, opts: &DeployOptions) -> bool {
73    let build = workers::Build::new(true, opts.dry_run).no_install(opts.no_install);
74    workers::compile_once_reporting(project_root, build_dir, build, None)
75}
76
77#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
78pub enum DeployFormat {
79    #[default]
80    Short,
81    Json,
82}
83
84#[derive(Debug, Clone, Default)]
85pub struct DeployOptions {
86    pub dry_run: bool,
87    /// `--no-install` (or `BYNK_NO_INSTALL`): stop on a missing npm package
88    /// instead of installing it (#3350).
89    pub no_install: bool,
90    pub format: DeployFormat,
91    pub yes: bool,
92    /// `--context NAME` — deploy this context alone, assuming the contexts it
93    /// consumes are already live (slice 2, D4). Absent deploys the whole
94    /// project in dependency order.
95    pub context: Option<String>,
96    /// #3562: `context` was given as `--worker NAME`, a Worker directory (a group's
97    /// key) and not a context's name.
98    pub by_worker: bool,
99    /// `--env NAME` — slice 4. Selects the `bynk.deploy.lock` section; for any
100    /// value other than `"default"` also drives synthesis of an environment-
101    /// scoped Wrangler config section, since Cloudflare does not inherit
102    /// bindings into a named environment (confirmed against Cloudflare's own
103    /// docs — see #835). `DeployOptions::default()`'s empty string is a
104    /// test-only artefact of `#[derive(Default)]`; every real invocation goes
105    /// through the CLI, whose `default_value = "default"` guarantees this is
106    /// never empty.
107    pub environment: String,
108    /// `--secrets-file` — a dotenv-style source of `NAME=value` pairs. Supplies
109    /// **names and values** (slice 3, ADR 0195 D3).
110    pub secrets_file: Option<std::path::PathBuf>,
111    /// `--secret NAME` — a name whose *value* comes from the environment or a
112    /// prompt. The environment is never scanned for names, so this is how a
113    /// `bynk.Secrets` name reaches `deploy` without a file.
114    pub secrets: Vec<String>,
115    /// `--force` — overwrite a secret already set, rather than skipping it.
116    pub force: bool,
117    /// `--prune` (slice 5) — delete every reported KV/queue orphan, behind
118    /// its own confirmation. Never deletes a Worker (DECISION C). Defaults
119    /// to report-only, matching the track's "report or prevent, never
120    /// silently share/destroy" posture (§6).
121    pub prune: bool,
122    /// State-migrations S3 (#2248): `--confirm-delete <context>.<Class>` —
123    /// each Durable Object class whose data a `removed agent` deletes, named
124    /// back. `--yes` never stands in for it (Decision E).
125    pub confirm_delete: Vec<String>,
126    /// #2554: `--accept-compatible-skew` — with `--context`, deploy a callee
127    /// ahead of live callers still on an older contract when each such change
128    /// is compatible for them. Records the older contracts in
129    /// `bynk.contracts.lock` and rebuilds, so the callee answers them.
130    pub accept_compatible_skew: bool,
131    /// #3562 (G5): `--accept-fresh-agent <context>` (repeatable): a context with agents that
132    /// moves to another Worker script starts fresh, its old state staying in the old script.
133    pub accept_fresh_agent: Vec<String>,
134    pub wrangler_args: Vec<String>,
135}
136
137/// What the ledger learns from a successful push of `worker` (whose build
138/// directory is `dir`), from the build's contract manifest:
139///
140/// - v0.177 (#643): what it now *provides*, so a later `--context` push of one of
141///   its callers can be refused before it ships a caller that would 409. `Some`
142///   even when empty: this build *knows* what the Worker provides, and "knows it
143///   provides nothing" must not read as "no record" at the next gate.
144/// - #2077: what it was compiled against, so a later push of one of its callees
145///   can be refused before it ships a callee this Worker would 409 against, and
146///   #2485 the structure behind both, so the next gate can say whether a skew is
147///   compatible.
148/// - I4 (#1970): what its declared foreign callers may call it at, so the ledger
149///   knows the consumers no manifest of their own records.
150/// - #3562: the contexts of a group's Worker.
151pub(crate) fn record_pushed_contracts(
152    lock: &mut DeployLock,
153    environment: &str,
154    (worker, dir): (&str, &Path),
155    (members, script): (&[String], &str),
156) {
157    let manifest = read_contracts_manifest(dir);
158    let provided = manifest.as_ref().ok().map(|m| m.provides.clone());
159    lock.record_deployed(environment, worker, provided);
160    lock.record_members(environment, worker, members);
161    lock.record_script(environment, worker, script);
162    if let Ok(m) = &manifest {
163        lock.record_expects(environment, worker, m.expects.clone());
164        lock.record_shapes(m.provides_shapes.clone(), m.expects_shapes.clone());
165    }
166    lock.record_foreign(
167        environment,
168        worker,
169        manifest.map(|m| m.foreign).unwrap_or_default(),
170    );
171}
172
173/// The `exports` tombstones a successful push of `worker` carried, recorded
174/// so later plans show them as applied: its deletions (State-migrations S3,
175/// #2248, #2253 review) and its renames (#2276 Decision D). Each replaces what
176/// was recorded for the Worker.
177pub(crate) fn record_pushed_tombstones(
178    lock: &mut DeployLock,
179    environment: &str,
180    worker: &str,
181    pushed: &Resources,
182) {
183    lock.record_deleted_classes(
184        environment,
185        worker,
186        pushed.deleted_durable_objects.iter().cloned().collect(),
187    );
188    lock.record_renamed_classes(
189        environment,
190        worker,
191        pushed.renamed_durable_objects.iter().cloned().collect(),
192    );
193    // #3328: and the Email Routing addresses it carried.
194    lock.record_email_addresses(
195        environment,
196        worker,
197        pushed.email_addresses.iter().cloned().collect(),
198    );
199}
200
201/// The `--` passthrough argument that conflicts with the driver's own
202/// `--env`, if any (slice 4, DECISION E) — bare or `=`-joined, mirroring
203/// `dev/run.rs`'s `passthrough_has` matching rule for the same class of clash
204/// (`--port`/`--inspector-port` there). Returns the matched literal, not just
205/// a bool, so the error can name what it conflicts with. Pure, so the rule is
206/// tested without touching `DeployOptions`.
207///
208/// `pub(crate)`: `dev.rs` reuses this for the identical clash between its own
209/// `--env` (which environment's ledger section `--remote` reads) and a
210/// `-- --env`/`-- --environment` passthrough to `wrangler dev` (which
211/// environment Wrangler actually connects to) — the same "two explicit,
212/// conflicting environment selections, one of them silent" shape, just
213/// without a value `dev` forwards to wrangler itself.
214pub(crate) fn conflicting_env_passthrough(wrangler_args: &[String]) -> Option<&str> {
215    wrangler_args
216        .iter()
217        .find(|arg| {
218            ["--env", "--environment"]
219                .iter()
220                .any(|flag| arg.as_str() == *flag || arg.starts_with(&format!("{flag}=")))
221        })
222        .map(String::as_str)
223}
224
225/// #2055: the refusal for a `--secrets-file` passed through after `--` when
226/// the run includes a first deploy. That deploy uploads the Worker's secrets
227/// with its own `wrangler deploy --secrets-file`, so the passthrough would be
228/// a second, contradictory one. Matched bare or `=`-joined, as
229/// [`conflicting_env_passthrough`] matches. `None` when there is no such
230/// argument or every Worker in `order` has been deployed in `environment`
231/// (a redeploy passes nothing of its own). Pure, so the wording is tested.
232pub(crate) fn secrets_file_passthrough_refusal(
233    wrangler_args: &[String],
234    order: &[String],
235    lock: &DeployLock,
236    environment: &str,
237) -> Option<String> {
238    let arg = wrangler_args
239        .iter()
240        .find(|arg| arg.as_str() == "--secrets-file" || arg.starts_with("--secrets-file="))?;
241    let first: Vec<String> = order
242        .iter()
243        .filter(|worker| !lock.is_deployed(environment, worker))
244        .map(|worker| format!("`{}`", deployed_worker_name(environment, worker)))
245        .collect();
246    if first.is_empty() {
247        return None;
248    }
249    Some(format!(
250        "bynk: error: `{arg}` after `--` conflicts with the secrets file `bynk deploy` uploads with a new Worker's first version ({}).\n  \
251         Pass it to bynk instead, before `--`: `bynk deploy --secrets-file <file>`.\n",
252        first.join(", ")
253    ))
254}
255
256/// Run the slice-0 single-context deployment pipeline.
257pub fn run(
258    tb: &dyn Toolbox,
259    project_root: &Path,
260    node_floor: (u32, u32),
261    opts: &DeployOptions,
262) -> ExitCode {
263    match deploy(tb, project_root, node_floor, opts) {
264        Ok(()) => ExitCode::SUCCESS,
265        Err(code) => code,
266    }
267}
268
269/// [`run`]'s orchestration (1D.2c, #4001 Decision E): the gates, the plan, the confirmation, the
270/// apply and `--prune`, each a step that returns the code the run exits with when it stops.
271fn deploy(
272    tb: &dyn Toolbox,
273    project_root: &Path,
274    node_floor: (u32, u32),
275    opts: &DeployOptions,
276) -> Result<(), ExitCode> {
277    preflight(tb, project_root, node_floor, opts)?;
278
279    // `_scratch` removes a dry run's build when the run ends (#3796).
280    let Some((build_dir, _scratch)) = build_dir_for(project_root, opts.dry_run) else {
281        return Err(ExitCode::FAILURE);
282    };
283    let Some(model) = workers::compile_built(
284        project_root,
285        &build_dir,
286        workers::Build::new(true, opts.dry_run).no_install(opts.no_install),
287        bynk_driver::progress::terminal_sink(),
288    ) else {
289        return Err(ExitCode::FAILURE);
290    };
291    // Slice 2: every context, ordered — not the one context slice 0 demanded.
292    let workers_dir = build_dir.join("workers");
293    let available = workers::discover_workers(&workers_dir);
294    let selected = match select_workers(opts, project_root, &available) {
295        Ok(selected) => selected,
296        Err(e) => {
297            emsg!("bynk: error: {e}");
298            return Err(ExitCode::FAILURE);
299        }
300    };
301    // Read spans the *whole* project even under `--context`: D4 needs the
302    // selected context's binding targets to check they are live, and they are
303    // by definition outside the selection.
304    let mut resources = match project_resources(&workers_dir, &available, &model) {
305        Ok(resources) => resources,
306        Err(e) => {
307            emsg!("bynk: error: {e}");
308            return Err(ExitCode::FAILURE);
309        }
310    };
311    let (graph, groups) = (service_graph(&resources), GroupNames::of(project_root));
312    // Read before the plan: a malformed `--secrets-file` is the user's typo, and
313    // it should surface as one now rather than as a missing-secret failure
314    // partway through a run that has already pushed a Worker.
315    let secret_source = match SecretSource::read(opts) {
316        Ok(source) => source,
317        Err(e) => {
318            emsg!("bynk: error: {e}");
319            return Err(ExitCode::FAILURE);
320        }
321    };
322    let lock_path = project_root.join(LOCK_FILE);
323    let runner = wrangler_runner_in(project_root);
324    let mut lock = match read_lock(&lock_path) {
325        Ok(lock) => lock,
326        Err(e) => {
327            emsg!("bynk: error: could not read {}: {e}", lock_path.display());
328            return Err(ExitCode::FAILURE);
329        }
330    };
331
332    // (D4) `--context` does not deploy a dependency closure, and a context deployed alone must
333    // not skew the contracts of what it calls or what calls it.
334    context_gate(
335        &ContextGate {
336            opts,
337            project_root,
338            build_dir: &build_dir,
339            workers_dir: &workers_dir,
340            graph: &graph,
341            groups: &groups,
342            lock: &lock,
343            runner,
344        },
345        &selected,
346    )?;
347
348    let order = ordered(&selected, &graph, &resources)?;
349
350    // #3562 (G5): a context with agent state that would change scripts is refused before
351    // anything is pushed, `--dry-run` included.
352    let Some(moves) = checked_agent_moves(&lock, opts, &resources, &order, &groups) else {
353        return Err(ExitCode::FAILURE);
354    };
355
356    check_foreign_pins(project_root, &workers_dir, &order, opts)?;
357
358    // Review of #1974: names the account scopes (a namespace's title, a
359    // bucket's, a database's, a dataset's) can coincide, so they are refused
360    // before the plan, `--dry-run` included, not met as wrangler's own error.
361    // #3479: an index `bynk.toml` names for this environment is adopted, not
362    // created, so its name is known before the plan.
363    if apply_adoptions(project_root, &mut resources, &opts.environment).is_err() {
364        return Err(ExitCode::FAILURE);
365    }
366    if let Some(message) = account_name_problem(&resources, &lock, &opts.environment) {
367        emsg!("bynk: error: {message}");
368        return Err(ExitCode::FAILURE);
369    }
370    // #2055: a first deploy hands `wrangler deploy` Bynk's own
371    // `--secrets-file`, so a passthrough one would be a second, with
372    // wrangler deciding which wins. Refused before the plan, as `--env`'s
373    // clash is.
374    if let Some(refusal) =
375        secrets_file_passthrough_refusal(&opts.wrangler_args, &order, &lock, &opts.environment)
376    {
377        colour::eprint(&refusal);
378        return Err(ExitCode::FAILURE);
379    }
380
381    // #3319: each `Postgres` binding's connection string is read now, from the
382    // environment variable `bynk.toml` names, so a missing variable fails the
383    // deploy before the plan (`--dry-run` included) and the plan can show a
384    // changed string as an update. The string itself goes no further than the
385    // `Wants` below.
386    let Some(hyperdrive_wants) =
387        hyperdrive::wants_for_run(project_root, &order, &resources, &opts.environment)
388    else {
389        return Err(ExitCode::FAILURE);
390    };
391    let plan = derive_plan(
392        &order,
393        &resources,
394        &lock,
395        &secret_source,
396        opts.force,
397        &opts.environment,
398    )
399    .with_lives(
400        &order,
401        &resources,
402        &lock,
403        Lives::for_plan(&hyperdrive_wants),
404    )
405    .checked_against_account();
406    print_plan_then_forward_warnings(&plan, opts, &order, &resources, project_root);
407    if opts.dry_run {
408        return Ok(());
409    }
410    // P5 (#2323): a changed `@jurisdiction` is a new bucket beside the old,
411    // whose objects do not move, so it is only made on an explicit `--yes`.
412    if let Some(refusal) = recreate_refusal(&plan, opts.yes) {
413        emsg!("bynk: error: {refusal}");
414        return Err(ExitCode::FAILURE);
415    }
416
417    let AccountChecked {
418        probe,
419        linked_stores,
420        hyperdrive_api,
421    } = account_checks(
422        tb,
423        &AccountCx {
424            project_root,
425            opts,
426            plan: &plan,
427            order: &order,
428            resources: &resources,
429            lock: &lock,
430            hyperdrive_wants: &hyperdrive_wants,
431        },
432    )?;
433    let hyperdrive_run = hyperdrive::HyperdriveRun::new(&hyperdrive_wants, hyperdrive_api.as_ref());
434    // State-migrations S3 (#2248): a deletion is confirmed by name, apart
435    // from — and before — the ordinary confirmation.
436    if !confirm_destructive(&plan, opts, &lock) {
437        return Err(ExitCode::FAILURE);
438    }
439    if !confirm(opts.yes) {
440        return Err(ExitCode::FAILURE);
441    }
442
443    let api = Wrangler::new(&probe.provenance, project_root);
444    let tools = Tools {
445        api: &api,
446        project_root,
447    };
448    // Slice 5, DECISION B: the account's live KV ids, read once per run.
449    let live_kv = Kv::read_live(
450        tools,
451        &ProjectCx {
452            ledger: LedgerView::of(&lock, &opts.environment),
453            resources: &resources,
454            order: &order,
455        },
456    );
457    // 1D.1 (#3929): what the run read once, for each kind.
458    // Shared across the loop: a queue two contexts consume is one queue, so it
459    // wants one create attempt per run, not one per consumer (ADR 0194 D2).
460    let attempted_queues = std::cell::RefCell::new(BTreeSet::new());
461    let lives = Lives {
462        kv: live_kv.as_ref(),
463        hyperdrive: hyperdrive_run,
464        queues: Some(&attempted_queues),
465        linked: Some(&linked_stores),
466    };
467
468    // Provision → wire → push, per context, in dependency order. Each context's
469    // state is written to the ledger as it lands (ADR 0180's incremental
470    // posture), so an interrupted multi-context run is resumable rather than
471    // restartable — and never rolled back (D2): a half-deployed project is a
472    // real state the next plan will show, not an error to unwind.
473    let keys = decide_keys(
474        &KeysCx {
475            order: &order,
476            resources: &resources,
477            api: &api,
478            workers_dir: &workers_dir,
479            lock: &lock,
480            opts,
481        },
482        &secret_source,
483    )?;
484    sweep_and_report_stale_uploads();
485    let mut writer = LedgerWriter::new(&mut lock, &lock_path);
486    let apply = PlanApply {
487        plan: &plan,
488        order: &order,
489        opts,
490        tools,
491        workers_dir: &workers_dir,
492        resources: &resources,
493        groups: &groups,
494        moves: &moves,
495        keys: &keys,
496        secret_source: &secret_source,
497        with_upload: secrets_file_supported(&probe),
498        runner,
499        lives,
500    };
501    apply_plan(&apply, &mut writer)?;
502    prune_plan(&apply, &mut writer)?;
503    Ok(())
504}
505
506/// #2055: a first deploy's secrets file that a SIGKILLed run left behind goes
507/// before this run might write one of its own.
508fn sweep_and_report_stale_uploads() {
509    let stale_removed = sweep_stale_upload_dirs(&std::env::temp_dir());
510    if stale_removed > 0 {
511        emsg!(
512            "bynk: removed {stale_removed} secrets file(s) an interrupted deploy left in the temp directory"
513        );
514    }
515}
516
517/// The Workers a run deploys: every one, or the one `--context` or `--worker`
518/// names (#3562). A group is one Worker, so a member cannot deploy alone: naming
519/// one says which Worker holds it.
520fn select_workers(
521    opts: &DeployOptions,
522    project_root: &Path,
523    available: &[String],
524) -> Result<Vec<String>, String> {
525    let Some(name) = opts.context.as_deref().filter(|_| opts.by_worker) else {
526        let found = workers::select_contexts(available, opts.context.as_slice());
527        return found.map_err(|e| match (e, &opts.context) {
528            (workers::SelectError::NotFound { .. }, Some(context)) => {
529                match GroupNames::of(project_root).holding(context) {
530                    Some(worker) => format!(
531                        "context `{context}` is in Worker `{worker}`, which deploys as a unit: use `--worker {worker}`"
532                    ),
533                    None => workers::SelectError::NotFound {
534                        requested: context.clone(),
535                        available: available.to_vec(),
536                    }
537                    .to_string(),
538                }
539            }
540            (e, _) => e.to_string(),
541        });
542    };
543    if available.iter().any(|worker| worker == name) {
544        return Ok(vec![name.to_string()]);
545    }
546    Err(format!(
547        "no Worker `{name}` was built (available: {})",
548        available.join(", ")
549    ))
550}