Skip to main content

bynk/
migrate.rs

1//! `bynk migrate`: where each agent class's stored state stands, and the sweep
2//! that migrates every stored instance and raises the class's floor
3//! (state-migrations S4, #2259; the retired track's summary in
4//! `design/archive/retired-tracks.md`, §3.3, §3.6).
5//!
6//! `status` is offline. It reads `bynk.schema.lock`, checks the source against
7//! it (read-only, as `bynk check` does), and reads `bynk.deploy.lock` only for
8//! the environments each Worker is pushed in.
9
10use bynk_driver::emsg;
11use std::collections::BTreeMap;
12use std::path::Path;
13use std::process::ExitCode;
14
15use bynk_driver::project::AgentVersions;
16use bynk_project::schema_registry::SchemaRegistry;
17use bynk_project::worker_layout::WorkerLayout;
18use serde::Serialize;
19
20pub(crate) mod live;
21pub(crate) mod sweep;
22
23/// Output choices for `bynk migrate status`.
24#[derive(Copy, Clone, Debug, PartialEq, Eq)]
25pub enum StatusFormat {
26    Short,
27    Json,
28}
29
30/// One agent class's migration state.
31#[derive(Debug, PartialEq, Eq, Serialize)]
32pub struct ClassStatus {
33    /// `<context>.<Agent>`, the lock's key.
34    pub class: String,
35    pub version: i64,
36    pub floor: i64,
37    /// The oldest stored version that reads forward to `version` without a
38    /// step (an all-additive path).
39    pub oldest_readable: i64,
40    pub steps: Vec<StepStatus>,
41    /// Versions from the floor up that no step covers and that have no
42    /// all-additive path: a stored record there faults `NoMigrationPath`.
43    pub without_path: Vec<i64>,
44    /// The environments `bynk.deploy.lock` records this class's Worker in. A
45    /// floor-raising sweep must cover every one.
46    pub deployed_to: Vec<String>,
47}
48
49/// One valid `migrate from N` step and the stored versions it covers.
50#[derive(Debug, PartialEq, Eq, Serialize)]
51pub struct StepStatus {
52    pub from: i64,
53    /// The oldest version the step covers (`lo..=from`).
54    pub covers_from: i64,
55}
56
57/// The unit (`<context>`) of agent class `class` (`<unit>.<Agent>`).
58fn unit_of(class: &str) -> &str {
59    class.rsplit_once('.').map_or(class, |(unit, _)| unit)
60}
61
62/// The Worker directory holding agent class `class` (`<unit>.<Agent>`), as
63/// `bynk deploy` lays the project out and keys the ledger (#3686): its
64/// `[deploy.workers]` group's, or the unit's qualified name dasherised.
65pub(crate) fn worker_of(layout: &WorkerLayout, class: &str) -> String {
66    layout.dir(unit_of(class))
67}
68
69/// The name agent class `class`'s Worker has on Cloudflare, before an
70/// environment qualifies it: its group's `name` or key, or the Worker's own.
71pub(crate) fn script_of(layout: &WorkerLayout, class: &str) -> String {
72    layout.script_name(unit_of(class))
73}
74
75/// Every recorded agent class's status, in key order. `versions` is the
76/// check's reconciled view (steps that hold, by class); `deployed` maps each
77/// Worker directory to its recorded environments.
78pub fn class_statuses(
79    lock: &SchemaRegistry,
80    versions: &std::collections::HashMap<String, AgentVersions>,
81    deployed: &BTreeMap<String, Vec<String>>,
82    layout: &WorkerLayout,
83) -> Vec<ClassStatus> {
84    lock.agents()
85        .map(|(class, entry)| {
86            // A class the source no longer declares has no reconciled view:
87            // its recorded entry alone says where it stands.
88            let (oldest_readable, steps) = match versions.get(class) {
89                Some(v) => (
90                    v.oldest_readable,
91                    v.steps
92                        .iter()
93                        .map(|s| StepStatus {
94                            from: s.from,
95                            covers_from: s.lo,
96                        })
97                        .collect(),
98                ),
99                None => (entry.oldest_readable(), Vec::new()),
100            };
101            let without_path = (entry.floor..entry.version)
102                .filter(|v| {
103                    *v < oldest_readable
104                        && !steps
105                            .iter()
106                            .any(|s: &StepStatus| s.covers_from <= *v && *v <= s.from)
107                })
108                .collect();
109            ClassStatus {
110                class: class.clone(),
111                version: entry.version,
112                floor: entry.floor,
113                oldest_readable,
114                steps,
115                without_path,
116                deployed_to: deployed
117                    .get(&worker_of(layout, class))
118                    .cloned()
119                    .unwrap_or_default(),
120            }
121        })
122        .collect()
123}
124
125/// `status`'s short form: one block per class.
126pub fn render_short(classes: &[ClassStatus]) -> String {
127    if classes.is_empty() {
128        return "no agent classes recorded in bynk.schema.lock\n".to_string();
129    }
130    let mut out = String::new();
131    for c in classes {
132        out.push_str(&format!(
133            "{}  version {}, floor {}\n",
134            c.class, c.version, c.floor
135        ));
136        for s in &c.steps {
137            let range = if s.covers_from == s.from {
138                s.from.to_string()
139            } else {
140                format!("{}..={}", s.covers_from, s.from)
141            };
142            out.push_str(&format!(
143                "  migrate from {}  covers {range}; deletable once the floor passes {}\n",
144                s.from, s.from
145            ));
146        }
147        if c.oldest_readable < c.version {
148            out.push_str(&format!(
149                "  versions {}..={} read forward without a step\n",
150                c.oldest_readable,
151                c.version - 1
152            ));
153        }
154        for v in &c.without_path {
155            out.push_str(&format!(
156                "  version {v} has no path: a stored record there faults `NoMigrationPath`\n"
157            ));
158        }
159        if c.deployed_to.is_empty() {
160            out.push_str("  deployed to: nothing recorded in bynk.deploy.lock\n");
161        } else {
162            out.push_str(&format!(
163                "  deployed to: {} (a sweep of {} can raise the floor)\n",
164                c.deployed_to.join(", "),
165                if c.deployed_to.len() == 1 {
166                    "it"
167                } else if c.deployed_to.len() == 2 {
168                    "both"
169                } else {
170                    "all of them"
171                }
172            ));
173        }
174    }
175    out
176}
177
178/// `status`'s JSON form: `{ "classes": [...] }`, one entry per [`ClassStatus`].
179/// The editor's State Migrations view reads this document
180/// (`tests/golden/migrate-status.json` pins it; the extension, in
181/// bynk-lang/vscode-bynk, keeps a copy as its parser's fixture).
182pub fn render_json(classes: &[ClassStatus]) -> String {
183    serde_json::to_string_pretty(&serde_json::json!({ "classes": classes }))
184        .expect("a status report always serializes")
185}
186
187/// Run `bynk migrate status` on the project at `root`.
188pub fn status(root: &Path, format: StatusFormat) -> ExitCode {
189    match status_report(root) {
190        Ok(classes) => {
191            match format {
192                StatusFormat::Short => print!("{}", render_short(&classes)),
193                StatusFormat::Json => println!("{}", render_json(&classes)),
194            }
195            ExitCode::SUCCESS
196        }
197        Err(e) => {
198            emsg!("bynk migrate status: error: {e}");
199            ExitCode::FAILURE
200        }
201    }
202}
203
204/// The lock, the source checked against it, and the ledger, as statuses. A
205/// source with errors is refused: a step that fails its check covers nothing,
206/// so the report would understate what the next build does.
207fn status_report(root: &Path) -> Result<Vec<ClassStatus>, String> {
208    let existing = bynk_driver::schema_lock::read(root).map_err(|e| {
209        format!(
210            "could not read {}: {e}",
211            bynk_driver::schema_lock::lock_path(root).display()
212        )
213    })?;
214    let lock = bynk_project::schema_registry::parse(existing.as_deref(), root)?;
215    let options = bynk_driver::try_project_options(root).map_err(|e| e.to_string())?;
216    let options = options.schema_registry(bynk_driver::project::SchemaLock::On { existing });
217    let check = bynk_driver::project::check_project(&options);
218    if check.has_errors() {
219        bynk_driver::print_project_check_short(&check);
220        return Err("the project has errors; fix them first (`bynk check`)".to_string());
221    }
222    let layout = WorkerLayout::for_project(root, &std::collections::HashMap::new());
223    let workers: Vec<String> = lock
224        .agents()
225        .map(|(class, _)| worker_of(&layout, class))
226        .collect();
227    let deployed = crate::deploy::deployed_environments(root, &workers)?;
228    Ok(class_statuses(
229        &lock,
230        &check.agent_versions,
231        &deployed,
232        &layout,
233    ))
234}
235
236/// `bynk migrate sweep`'s options.
237#[derive(Debug, Clone, Default)]
238pub struct SweepOptions {
239    /// Only this context's classes (its qualified name, dashed or not, or its
240    /// Worker directory, a group's key included).
241    pub context: Option<String>,
242    /// Only these environments; every recorded one when empty. A narrowed
243    /// run migrates but never raises a floor.
244    pub environments: Vec<String>,
245    /// Instances woken per Worker request.
246    pub batch: usize,
247    /// Skip the confirmation.
248    pub yes: bool,
249    /// `<deployed Worker name>=<https://its host>`, for a Worker that does
250    /// not serve on `workers.dev`.
251    pub urls: Vec<String>,
252}
253
254/// Run `bynk migrate sweep` on the project at `root`.
255pub fn sweep(root: &Path, opts: &SweepOptions) -> ExitCode {
256    match sweep_run(root, opts) {
257        Ok(true) => ExitCode::SUCCESS,
258        Ok(false) => ExitCode::FAILURE,
259        Err(e) => {
260            emsg!("bynk migrate sweep: error: {e}");
261            ExitCode::FAILURE
262        }
263    }
264}
265
266/// The token a sweep needs, in the words its missing-credentials message uses (a revert's
267/// message names the same token).
268pub(crate) const SWEEP_TOKEN_NEEDS: &str = "an API token with \"Workers Scripts: Edit\" (the listings need read access, and `wrangler` uses the same token to set and delete the sweep's key)";
269
270/// The sweep, end to end: `Ok(true)` when every selected instance woke.
271fn sweep_run(root: &Path, opts: &SweepOptions) -> Result<bool, String> {
272    let mut urls = BTreeMap::new();
273    for entry in &opts.urls {
274        let (script, url) = entry
275            .split_once('=')
276            .filter(|(s, u)| !s.is_empty() && u.starts_with("https://"))
277            .ok_or_else(|| format!("`--url {entry}`: expected `<worker>=https://<host>`"))?;
278        urls.insert(script.to_string(), url.to_string());
279    }
280    let existing = bynk_driver::schema_lock::read(root).map_err(|e| e.to_string())?;
281    let lock = bynk_project::schema_registry::parse(existing.as_deref(), root)?;
282    let layout = WorkerLayout::for_project(root, &std::collections::HashMap::new());
283    let workers: Vec<String> = lock
284        .agents()
285        .map(|(class, _)| worker_of(&layout, class))
286        .collect();
287    let deployed = crate::deploy::deployed_environments(root, &workers)?;
288    let selection = sweep::select(
289        &lock,
290        &deployed,
291        &layout,
292        opts.context.as_deref(),
293        &opts.environments,
294    )?;
295    for class in &selection.never_deployed {
296        eprintln!("{class}: its Worker is recorded in no environment; nothing to sweep");
297    }
298    if selection.targets.is_empty() {
299        return Err("nothing to sweep".to_string());
300    }
301    let rest = crate::cloudflare::rest::for_purpose("sweep", SWEEP_TOKEN_NEEDS)?;
302    let agent = rest.agent().clone();
303    // #2276: the listing's age is measured from when it is taken.
304    let listed_at = std::time::SystemTime::now();
305    let plans = sweep::prepare(&selection, &rest, &urls)?;
306    let instances: usize = plans
307        .values()
308        .flat_map(|p| p.classes.iter().map(|(_, ids)| ids.len()))
309        .sum();
310    for (script, plan) in &plans {
311        for (target, ids) in &plan.classes {
312            eprintln!(
313                "{script} ({}): {}  {} instances with stored data",
314                target.environment,
315                target.agent,
316                ids.len()
317            );
318        }
319    }
320    eprintln!(
321        "The sweep sets a temporary secret, {}, on {} Worker(s) and deletes it afterwards; \
322         each set and delete creates a Worker version. It wakes {instances} instance(s).",
323        bynk_emit::wire_format::MIGRATE_KEY,
324        plans.len()
325    );
326    if !confirm(opts.yes) {
327        return Ok(false);
328    }
329    let probe = crate::probe::detect(
330        &crate::probe::SystemToolbox,
331        "wrangler",
332        crate::probe::DetectOpts {
333            project_root: Some(root),
334            allow_npx: true,
335            manager: Some(bynk_driver::npm_install::system_tool_manager(root)),
336        },
337    );
338    let scratch = std::env::temp_dir().join(format!("bynk-migrate-{}", std::process::id()));
339    let api = crate::cloudflare::Wrangler::new(&probe.provenance, &scratch);
340    let secrets = live::WranglerSecrets {
341        api: &api,
342        scratch: scratch.clone(),
343    };
344    let results = {
345        // A Ctrl-C stops the waking, never the key's deletion.
346        let _deferred = crate::stop::defer();
347        sweep::execute(
348            &plans,
349            &secrets,
350            &live::Https(agent),
351            opts.batch,
352            &sweep::Timing::LIVE,
353            &crate::deploy::mint_key,
354            &|| crate::stop::received().is_some(),
355            &mut std::io::stdout(),
356        )
357    };
358    let _ = std::fs::remove_dir_all(&secrets.scratch);
359    let unsettled = sweep::unsettled(&plans, listed_at, sweep::SETTLING_MARGIN);
360    let raises = sweep::floor_raises(&lock, &selection, &results, &unsettled);
361    // The classes whose floor would have risen had every Worker settled: only
362    // their held floor is the margin's doing (#2279 review).
363    let would_rise: Vec<String> =
364        sweep::floor_raises(&lock, &selection, &results, &BTreeMap::new())
365            .into_iter()
366            .map(|(class, _, _)| class)
367            .collect();
368    if !raises.is_empty() {
369        let mut lock = lock;
370        for (class, from, to) in &raises {
371            lock.raise_floor(class, *to)?;
372            println!("floor: {class} {from} → {to} (every recorded environment swept in this run)");
373        }
374        bynk_driver::schema_lock::write(root, &bynk_project::schema_registry::serialize(&lock))
375            .map_err(|e| format!("could not write bynk.schema.lock: {e}"))?;
376        println!(
377            "bynk.schema.lock updated; commit it. The next build warns about every `migrate \
378             from N` step below the new floor (`bynk.agent.migrate_below_floor`): delete them."
379        );
380    }
381    let raised: Vec<&String> = raises.iter().map(|(c, _, _)| c).collect();
382    for class in selection.covers_all.keys() {
383        if raised.contains(&class) {
384            continue;
385        }
386        if let Some(why) = sweep::floor_held_reason(
387            class,
388            &selection,
389            &results,
390            &unsettled,
391            would_rise.contains(class),
392        ) {
393            println!("floor: {class} unchanged ({why})");
394        }
395    }
396    Ok(results.iter().all(sweep::ClassResult::complete))
397}
398
399/// Ask before changing anything on the account, unless `--yes`.
400fn confirm(yes: bool) -> bool {
401    use std::io::{IsTerminal, Write};
402    if yes {
403        return true;
404    }
405    if !std::io::stdin().is_terminal() {
406        emsg!(
407            "bynk: error: refusing to change Cloudflare in a non-interactive session without --yes"
408        );
409        return false;
410    }
411    eprint!("Sweep? [y/N] ");
412    let _ = std::io::stderr().flush();
413    let mut answer = String::new();
414    std::io::stdin().read_line(&mut answer).is_ok()
415        && matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421    use bynk_driver::project::MigrationStep;
422    use bynk_project::schema_registry::{AgentEntry, AgentShape};
423
424    fn entry(version: i64, floor: i64, additive: &[bool]) -> AgentEntry {
425        AgentEntry {
426            version,
427            floor,
428            shapes: (floor..=version)
429                .zip(additive.iter())
430                .map(|(v, a)| AgentShape {
431                    version: v,
432                    additive: *a,
433                    fields: Vec::new(),
434                })
435                .collect(),
436            renamed_from: Vec::new(),
437        }
438    }
439
440    fn step(lo: i64, from: i64) -> MigrationStep {
441        MigrationStep {
442            lo,
443            from,
444            carried: Vec::new(),
445            known: Vec::new(),
446            store_maps: Vec::new(),
447        }
448    }
449
450    #[test]
451    fn worker_of_dasherises_the_unit() {
452        let identity = WorkerLayout::identity();
453        assert_eq!(worker_of(&identity, "shop.Cart"), "shop");
454        assert_eq!(worker_of(&identity, "acme.shop.Cart"), "acme-shop");
455    }
456
457    #[test]
458    fn a_class_reports_its_steps_gaps_and_environments() {
459        let mut lock = SchemaRegistry::new();
460        // 1 -> 2 additive, 2 -> 3 not, 3 -> 4 not: a step from 3 only.
461        lock.insert_agent(
462            "shop.Cart".to_string(),
463            entry(4, 1, &[false, true, false, false]),
464        );
465        let versions = std::collections::HashMap::from([(
466            "shop.Cart".to_string(),
467            AgentVersions {
468                version: 4,
469                oldest_readable: 4,
470                steps: vec![step(3, 3)],
471            },
472        )]);
473        let deployed = BTreeMap::from([(
474            "shop".to_string(),
475            vec!["default".to_string(), "staging".to_string()],
476        )]);
477        let classes = class_statuses(&lock, &versions, &deployed, &WorkerLayout::identity());
478        assert_eq!(
479            classes,
480            vec![ClassStatus {
481                class: "shop.Cart".to_string(),
482                version: 4,
483                floor: 1,
484                oldest_readable: 4,
485                steps: vec![StepStatus {
486                    from: 3,
487                    covers_from: 3
488                }],
489                without_path: vec![1, 2],
490                deployed_to: vec!["default".to_string(), "staging".to_string()],
491            }]
492        );
493        let text = render_short(&classes);
494        assert!(text.contains("shop.Cart  version 4, floor 1"), "{text}");
495        assert!(text.contains("migrate from 3  covers 3;"), "{text}");
496        assert!(text.contains("version 1 has no path"), "{text}");
497        assert!(
498            text.contains("deployed to: default, staging (a sweep of both"),
499            "{text}"
500        );
501    }
502
503    /// #3686: a context in a `[deploy.workers]` group deploys as part of the
504    /// group's Worker, and the ledger records it under the group's directory.
505    #[test]
506    fn a_group_members_class_reports_the_groups_environments() {
507        let groups = bynk_project::worker_groups::WorkerGroups::from([(
508            "store".to_string(),
509            bynk_project::worker_groups::WorkerGroup {
510                contexts: vec!["shop.cart".to_string(), "shop.orders".to_string()],
511                name: Some("storefront".to_string()),
512                ..Default::default()
513            },
514        )]);
515        let layout = WorkerLayout::from_groups(&groups);
516        assert_eq!(worker_of(&layout, "shop.cart.Cart"), "store");
517        assert_eq!(worker_of(&layout, "billing.Ledger"), "billing");
518        let mut lock = SchemaRegistry::new();
519        lock.insert_agent("shop.cart.Cart".to_string(), entry(1, 1, &[false]));
520        let deployed = BTreeMap::from([(
521            "store".to_string(),
522            vec!["default".to_string(), "staging".to_string()],
523        )]);
524        let classes = class_statuses(&lock, &std::collections::HashMap::new(), &deployed, &layout);
525        assert_eq!(
526            classes[0].deployed_to,
527            vec!["default".to_string(), "staging".to_string()]
528        );
529    }
530
531    #[test]
532    fn a_class_gone_from_source_reads_from_its_entry() {
533        let mut lock = SchemaRegistry::new();
534        lock.insert_agent("shop.Old".to_string(), entry(2, 1, &[false, true]));
535        let classes = class_statuses(
536            &lock,
537            &std::collections::HashMap::new(),
538            &BTreeMap::new(),
539            &WorkerLayout::identity(),
540        );
541        assert_eq!(classes[0].oldest_readable, 1);
542        assert!(classes[0].without_path.is_empty());
543        assert!(render_short(&classes).contains("nothing recorded in bynk.deploy.lock"));
544    }
545
546    /// The document the editor reads: pinned against the extension's fixture, so
547    /// a change to the driver's JSON fails here before it breaks the view.
548    #[test]
549    fn the_json_form_matches_the_editors_fixture() {
550        let classes = vec![
551            ClassStatus {
552                class: "shop.Cart".to_string(),
553                version: 4,
554                floor: 1,
555                oldest_readable: 4,
556                steps: vec![StepStatus {
557                    from: 3,
558                    covers_from: 3,
559                }],
560                without_path: vec![1, 2],
561                deployed_to: vec!["default".to_string(), "staging".to_string()],
562            },
563            ClassStatus {
564                class: "shop.Order".to_string(),
565                version: 3,
566                floor: 2,
567                oldest_readable: 2,
568                steps: Vec::new(),
569                without_path: Vec::new(),
570                deployed_to: Vec::new(),
571            },
572        ];
573        let produced: serde_json::Value = serde_json::from_str(&render_json(&classes)).unwrap();
574        let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
575            .join("tests/golden/migrate-status.json");
576        let pinned: serde_json::Value =
577            serde_json::from_str(&std::fs::read_to_string(&fixture).unwrap()).unwrap();
578        assert_eq!(produced, pinned);
579        assert_eq!(render_json(&[]), "{\n  \"classes\": []\n}");
580    }
581}