Skip to main content

surjection_core/versions/
mod.rs

1//! Schema versions of the data folder (SPEC 5.0): which files carry a
2//! `schema` number, refusing a data folder a newer Surjection wrote, and
3//! migrating files an older Surjection wrote.
4//!
5//! The store has one version for all of its files ([`SCHEMA_VERSION`]): a
6//! pull merges whole trees between machines, so "this store is schema N"
7//! must mean one thing on every machine, and bumping it migrates every
8//! store file in one commit. State files are machine-local and owned by one
9//! module each, so each kind keeps its own version and migrates on its own.
10//!
11//! [`prepare`] runs before a command touches the data folder (the CLI
12//! before any command, the app at startup). A file newer than this build
13//! fails it with `unsupported_schema` and nothing is written. Files older
14//! than this build are migrated under the store lock, after a second look
15//! (another process may have migrated them meanwhile): state files first,
16//! each original copied to `backups/schema/<timestamp>/state/`, then the
17//! store files as one commit (git history keeps the old versions). A file
18//! at the current version is never rewritten, so running it again does
19//! nothing.
20//!
21//! One migration exists: the ledger's 1 -> 2 of the rename to Surjection
22//! (no change in the file; it makes Loadout 1.0.x refuse the folder).
23//! [`Registry::with_step`] adds a step; it is how a real migration is added
24//! and how tests exercise the runner.
25
26use std::path::{Path, PathBuf};
27
28use toml_edit::{DocumentMut, Item};
29
30use crate::apply::backup::timestamp;
31use crate::apply::journal::{APPLIES_DIR, JOURNAL_DIR};
32use crate::apply::ledger::LEDGER_FILE;
33use crate::apply::unmanaged::SEEN_FILE;
34use crate::apply::write_atomic;
35use crate::brand;
36use crate::eject::EJECT_FILE;
37use crate::env::Env;
38use crate::error::{CoreError, ErrorCode};
39use crate::fs::Fs;
40use crate::layering::trust::TRUST_FILE;
41use crate::local_settings::LOCAL_SETTINGS_FILE;
42use crate::model::{SCHEMA_VERSION, StoreFile};
43use crate::paths::SurjectionHome;
44use crate::remote::config::REMOTES_FILE;
45use crate::remote::sync::STATUS_FILE;
46use crate::scan::RULES_OVERRIDE_FILE;
47use crate::store::merge::{Files, MERGE_STATE};
48use crate::store::{
49    CommitId, IDENTITY_FILE, LOCK_TIMEOUT, MACHINE_FILE, Operation, Store, StoreLock,
50};
51
52#[cfg(test)]
53mod tests;
54
55/// Every kind starts at this version.
56const FIRST: i64 = 1;
57/// Below `backups/`: one folder per migration with the state files it
58/// rewrote, as they were.
59pub const BACKUP_DIR: &str = "schema";
60const BOM: char = '\u{feff}';
61
62/// Where a file lives in the data folder.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
64pub enum Area {
65    /// `<SURJECTION_HOME>/store`, versioned and synced.
66    Store,
67    /// `<SURJECTION_HOME>/state`, machine-local.
68    State,
69}
70
71impl Area {
72    /// The folder below the data folder.
73    pub fn dir(self) -> &'static str {
74        match self {
75            Area::Store => "store",
76            Area::State => "state",
77        }
78    }
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum Format {
83    Toml,
84    Json,
85}
86
87/// A file being migrated, parsed. TOML keeps its formatting and comments.
88#[derive(Debug, Clone)]
89pub enum Doc {
90    Toml(DocumentMut),
91    Json(serde_json::Value),
92}
93
94/// Upgrades one file by one version. Gets the area-relative path and the
95/// parsed file; the runner sets `schema` afterwards.
96pub type Rewrite = fn(&str, &mut Doc) -> Result<(), CoreError>;
97
98/// One migration step `N -> N + 1` of a kind.
99#[derive(Debug, Clone, Copy)]
100pub struct Step {
101    pub rewrite: Rewrite,
102}
103
104/// A kind of versioned file.
105#[derive(Debug, Clone)]
106pub struct Kind {
107    pub name: &'static str,
108    pub area: Area,
109    pub format: Format,
110    /// `steps[i]` upgrades version `1 + i` to `2 + i`.
111    steps: Vec<Step>,
112    /// Whether an area-relative path (`/`-separated) is of this kind.
113    matches: fn(&str) -> bool,
114}
115
116impl Kind {
117    fn new(name: &'static str, area: Area, format: Format, matches: fn(&str) -> bool) -> Self {
118        Self {
119            name,
120            area,
121            format,
122            steps: Vec::new(),
123            matches,
124        }
125    }
126
127    /// The highest version this build reads and writes.
128    pub fn current(&self) -> i64 {
129        FIRST + i64::try_from(self.steps.len()).unwrap_or(i64::MAX - FIRST)
130    }
131}
132
133/// Runs between a migration's store commit and its working-tree writes
134/// (test hook, see [`Registry::with_after_commit`]).
135pub type AfterCommit = fn() -> Result<(), CoreError>;
136
137/// Every versioned kind with its migration steps.
138#[derive(Debug, Clone)]
139pub struct Registry {
140    kinds: Vec<Kind>,
141    after_commit: Option<AfterCommit>,
142}
143
144impl Registry {
145    /// The kinds of this build (M56 inventory). Each kind's current version
146    /// equals the constant its module reads and writes (checked by a test).
147    pub fn builtin() -> Self {
148        use Area::{State, Store};
149        use Format::{Json, Toml};
150        Self {
151            kinds: vec![
152                Kind::new("store", Store, Toml, is_store_schema_file),
153                Kind::new("machine", State, Toml, |p| p == MACHINE_FILE),
154                Kind::new("local-settings", State, Toml, |p| p == LOCAL_SETTINGS_FILE),
155                Kind::new("remotes", State, Toml, |p| p == REMOTES_FILE),
156                Kind::new("remote-status", State, Toml, |p| p == STATUS_FILE),
157                Kind::new("scan-rules", State, Toml, |p| p == RULES_OVERRIDE_FILE),
158                Kind::new("ledger", State, Json, |p| p == LEDGER_FILE),
159                Kind::new("trust", State, Json, |p| p == TRUST_FILE),
160                Kind::new("unmanaged-seen", State, Json, |p| p == SEEN_FILE),
161                Kind::new("merge-state", State, Json, is_merge_state),
162                Kind::new("journal", State, Json, is_journal),
163                Kind::new("eject", State, Json, |p| p == EJECT_FILE),
164            ],
165            after_commit: None,
166        }
167        // Ledger 1 -> 2 (Surjection 1.1.0): no change in the file. Its only
168        // purpose is the version: a Loadout 1.0.x binary that still reaches
169        // this data folder (through the link `surject migrate loadout`
170        // leaves) refuses it with `unsupported_schema` instead of changing
171        // it, while its `exec` and `secret` hooks, which never survey the
172        // folder, keep working.
173        .with_step("ledger", Step { rewrite: renamed })
174    }
175
176    /// Appends a migration step to kind `name`, raising its current version
177    /// by one. Panics on an unknown kind (a programming error).
178    #[must_use]
179    pub fn with_step(mut self, name: &str, step: Step) -> Self {
180        let kind = self
181            .kinds
182            .iter_mut()
183            .find(|kind| kind.name == name)
184            .unwrap_or_else(|| panic!("unknown file kind {name:?}"));
185        kind.steps.push(step);
186        self
187    }
188
189    /// Test hook: `hook` runs after a migration's store commit and before
190    /// its working-tree writes, so a test can stop the migration in its
191    /// worst place and check that the next run converges.
192    #[must_use]
193    pub fn with_after_commit(mut self, hook: AfterCommit) -> Self {
194        self.after_commit = Some(hook);
195        self
196    }
197
198    pub fn kinds(&self) -> &[Kind] {
199        &self.kinds
200    }
201
202    pub fn kind(&self, name: &str) -> Option<&Kind> {
203        self.kinds.iter().find(|kind| kind.name == name)
204    }
205
206    fn kind_of(&self, area: Area, relative: &str) -> Option<&Kind> {
207        self.kinds
208            .iter()
209            .find(|kind| kind.area == area && (kind.matches)(relative))
210    }
211}
212
213/// `loadout.toml` and every store file with a schema (SPEC 4.5).
214pub(crate) fn is_store_schema_file(relative: &str) -> bool {
215    relative == IDENTITY_FILE || StoreFile::classify(Path::new(relative)).is_some()
216}
217
218/// The ledger step of the rename to Surjection: nothing to rewrite.
219fn renamed(_: &str, _: &mut Doc) -> Result<(), CoreError> {
220    Ok(())
221}
222
223fn is_merge_state(relative: &str) -> bool {
224    relative
225        .strip_prefix("merge/")
226        .is_some_and(|name| name == MERGE_STATE)
227}
228
229fn is_journal(relative: &str) -> bool {
230    [JOURNAL_DIR, APPLIES_DIR].into_iter().any(|dir| {
231        relative
232            .strip_prefix(dir)
233            .and_then(|rest| rest.strip_prefix('/'))
234            .is_some_and(|name| !name.contains('/') && name.ends_with(".json"))
235    })
236}
237
238/// A versioned file found in the data folder.
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct Found {
241    pub kind: &'static str,
242    pub area: Area,
243    /// Below the area's folder, `/`-separated.
244    pub relative: String,
245    pub version: i64,
246}
247
248impl Found {
249    /// Relative to the data folder (`store/servers/github.toml`).
250    pub fn file(&self) -> String {
251        format!("{}/{}", self.area.dir(), self.relative)
252    }
253}
254
255/// Every versioned file of the data folder with the version it says. The
256/// store is read only when it is a repository (as [`Store::open`] does);
257/// skill content and `.git` are not walked. Files that do not parse or have
258/// no integer `schema` are left out: their readers report them.
259///
260/// `journal/` and `applies/` hold up to 200 files of one kind, named by
261/// ULID, so in time order. While that kind has no migration step only the
262/// newest file of each folder is read: a newer Surjection that wrote any of
263/// them wrote the newest one last, which is all the refusal needs; a step
264/// to run makes every file count again.
265pub fn survey(
266    fs: &dyn Fs,
267    home: &SurjectionHome,
268    registry: &Registry,
269) -> Result<Vec<Found>, CoreError> {
270    let mut found = Vec::new();
271    let store = home.store_dir();
272    if fs.exists(&store.join(".git")) {
273        let mut dirs: Vec<String> = ["", "servers", "skill-meta", "machines"]
274            .into_iter()
275            .map(str::to_owned)
276            .collect();
277        for project in list_dirs(fs, &store.join("projects"))? {
278            dirs.push(format!("projects/{project}"));
279        }
280        collect(fs, &store, Area::Store, &dirs, registry, false, &mut found)?;
281    }
282    let state = home.state_dir();
283    let dirs = [String::new(), "merge".to_owned()];
284    collect(fs, &state, Area::State, &dirs, registry, false, &mut found)?;
285    let newest_only = registry
286        .kind("journal")
287        .is_some_and(|kind| kind.steps.is_empty());
288    let dirs = [JOURNAL_DIR.to_owned(), APPLIES_DIR.to_owned()];
289    collect(
290        fs,
291        &state,
292        Area::State,
293        &dirs,
294        registry,
295        newest_only,
296        &mut found,
297    )?;
298    Ok(found)
299}
300
301fn collect(
302    fs: &dyn Fs,
303    root: &Path,
304    area: Area,
305    dirs: &[String],
306    registry: &Registry,
307    newest_only: bool,
308    found: &mut Vec<Found>,
309) -> Result<(), CoreError> {
310    for dir in dirs {
311        let mut files: Vec<(String, &Kind)> = list_files(fs, &join(root, dir))?
312            .into_iter()
313            .filter_map(|name| {
314                let relative = if dir.is_empty() {
315                    name
316                } else {
317                    format!("{dir}/{name}")
318                };
319                let kind = registry.kind_of(area, &relative)?;
320                Some((relative, kind))
321            })
322            .collect();
323        if newest_only {
324            files = files.pop().into_iter().collect();
325        }
326        for (relative, kind) in files {
327            // A file removed or locked meanwhile is someone else's problem.
328            let Ok(text) = fs.read_to_string(&join(root, &relative)) else {
329                continue;
330            };
331            if let Some(version) = read_version(kind.format, &text) {
332                found.push(Found {
333                    kind: kind.name,
334                    area,
335                    relative,
336                    version,
337                });
338            }
339        }
340    }
341    Ok(())
342}
343
344/// Names of the files directly in `dir`, sorted; empty when it is absent.
345fn list_files(fs: &dyn Fs, dir: &Path) -> Result<Vec<String>, CoreError> {
346    list(fs, dir, false)
347}
348
349fn list_dirs(fs: &dyn Fs, dir: &Path) -> Result<Vec<String>, CoreError> {
350    list(fs, dir, true)
351}
352
353fn list(fs: &dyn Fs, dir: &Path, dirs: bool) -> Result<Vec<String>, CoreError> {
354    if !fs.is_dir(dir) {
355        return Ok(Vec::new());
356    }
357    let entries = fs.read_dir(dir).map_err(|err| {
358        CoreError::new(ErrorCode::IoError, format!("cannot list directory: {err}")).with_path(dir)
359    })?;
360    let mut names: Vec<String> = entries
361        .iter()
362        .filter(|entry| fs.is_dir(entry) == dirs)
363        .filter_map(|entry| entry.file_name()?.to_str().map(str::to_owned))
364        .collect();
365    names.sort();
366    Ok(names)
367}
368
369/// `root` joined with a `/`-separated relative path.
370fn join(root: &Path, relative: &str) -> PathBuf {
371    relative
372        .split('/')
373        .filter(|part| !part.is_empty())
374        .fold(root.to_path_buf(), |path, part| path.join(part))
375}
376
377/// Only the `schema` key; every other key is skipped, not kept.
378#[derive(serde::Deserialize)]
379struct SchemaField {
380    #[serde(default)]
381    schema: Option<i64>,
382}
383
384/// The top-level integer `schema` of a file's text.
385pub fn read_version(format: Format, text: &str) -> Option<i64> {
386    let text = text.strip_prefix(BOM).unwrap_or(text);
387    let field: SchemaField = match format {
388        Format::Toml => toml::from_str(text).ok()?,
389        Format::Json => serde_json::from_str(text).ok()?,
390    };
391    field.schema
392}
393
394/// Whether the file at `path` says a `schema` above `supported`: a newer
395/// Surjection wrote it (possibly while this process runs), so it must not be
396/// overwritten. Absent or unreadable files are not.
397pub fn written_by_newer(fs: &dyn Fs, path: &Path, format: Format, supported: i64) -> bool {
398    fs.read_to_string(path)
399        .ok()
400        .and_then(|text| read_version(format, &text))
401        .is_some_and(|found| found > supported)
402}
403
404/// A file a newer Surjection wrote.
405#[derive(Debug, Clone, PartialEq, Eq)]
406pub struct NewerData {
407    pub kind: &'static str,
408    /// Relative to the data folder (`store/servers/github.toml`).
409    pub file: String,
410    pub found: i64,
411    pub supported: i64,
412}
413
414impl NewerData {
415    pub fn message(&self) -> String {
416        newer_message("This data folder was", self.found, self.supported)
417    }
418
419    /// `unsupported_schema` with [`Self::message`] and the file's path.
420    pub fn to_error(&self, home: &SurjectionHome) -> CoreError {
421        CoreError::new(ErrorCode::UnsupportedSchema, self.message())
422            .with_path(join(&home.path, &self.file))
423    }
424}
425
426fn newer_message(subject: &str, found: i64, supported: i64) -> String {
427    let product = brand::PRODUCT_NAME;
428    format!(
429        "{subject} written by a newer {product} (schema {found}; this version reads up to \
430         {supported}). Update {product}."
431    )
432}
433
434/// The first file of `found` newer than its kind's current version.
435fn first_newer(found: &[Found], registry: &Registry) -> Option<NewerData> {
436    found.iter().find_map(|file| {
437        let supported = registry.kind(file.kind)?.current();
438        (file.version > supported).then(|| NewerData {
439            kind: file.kind,
440            file: file.file(),
441            found: file.version,
442            supported,
443        })
444    })
445}
446
447/// One file a migration rewrote.
448#[derive(Debug, Clone, PartialEq, Eq)]
449pub struct Migrated {
450    pub kind: &'static str,
451    /// Relative to the data folder.
452    pub file: String,
453    pub from: i64,
454    pub to: i64,
455}
456
457/// What a migration did.
458#[derive(Debug, Clone, PartialEq, Eq)]
459pub struct Migration {
460    pub files: Vec<Migrated>,
461    /// The store commit holding the migrated store files.
462    pub commit: Option<CommitId>,
463    /// Copies of the state files as they were.
464    pub backup: Option<PathBuf>,
465}
466
467/// What [`prepare`] found.
468#[derive(Debug, Clone, PartialEq, Eq)]
469pub enum Prepared {
470    /// The folder can be used; `Some` when files were migrated first.
471    Ready(Option<Migration>),
472    /// A newer Surjection wrote this file; nothing was written.
473    Newer(NewerData),
474}
475
476impl Prepared {
477    /// [`Prepared::Newer`] as its `unsupported_schema` error.
478    pub fn into_result(self, home: &SurjectionHome) -> Result<Option<Migration>, CoreError> {
479        match self {
480            Prepared::Ready(migration) => Ok(migration),
481            Prepared::Newer(newer) => Err(newer.to_error(home)),
482        }
483    }
484}
485
486/// [`prepare_with`] over [`Registry::builtin`].
487pub fn prepare(
488    env: &Env,
489    fs: &dyn Fs,
490    home: &SurjectionHome,
491    client: &str,
492) -> Result<Prepared, CoreError> {
493    prepare_with(env, fs, home, client, &Registry::builtin())
494}
495
496/// Surveys the data folder once: a file a newer Surjection wrote is returned
497/// as [`Prepared::Newer`] and nothing is written; files an older one wrote
498/// are migrated. `client` names the program for the store commit's
499/// `Surjection-Client` trailer. An error is a failed survey or migration.
500pub fn prepare_with(
501    env: &Env,
502    fs: &dyn Fs,
503    home: &SurjectionHome,
504    client: &str,
505    registry: &Registry,
506) -> Result<Prepared, CoreError> {
507    let found = survey(fs, home, registry)?;
508    if let Some(newer) = first_newer(&found, registry) {
509        return Ok(Prepared::Newer(newer));
510    }
511    rename_legacy_names(fs, home);
512    if pending(&found, registry).next().is_none() {
513        return Ok(Prepared::Ready(None));
514    }
515    let _lock = StoreLock::acquire(fs, &home.state_dir(), LOCK_TIMEOUT)?;
516    // Another process may have migrated, or a newer one written, meanwhile.
517    let found = survey(fs, home, registry)?;
518    if let Some(newer) = first_newer(&found, registry) {
519        return Ok(Prepared::Newer(newer));
520    }
521    let pending: Vec<&Found> = pending(&found, registry).collect();
522    if pending.is_empty() {
523        return Ok(Prepared::Ready(None));
524    }
525    migrate(env, fs, home, client, registry, &pending).map(|m| Prepared::Ready(Some(m)))
526}
527
528/// Files below their kind's current version. A version below the first one
529/// (0 or negative) is no version Surjection wrote: left to the file's reader.
530fn pending<'f>(found: &'f [Found], registry: &'f Registry) -> impl Iterator<Item = &'f Found> + 'f {
531    found.iter().filter(|file| {
532        registry
533            .kind(file.kind)
534            .is_some_and(|kind| (FIRST..kind.current()).contains(&file.version))
535    })
536}
537
538/// Migrates `pending` (the caller holds the lock): state files first, so
539/// `state/machine.toml` is current before the store commit reads it, then
540/// the store.
541fn migrate(
542    env: &Env,
543    fs: &dyn Fs,
544    home: &SurjectionHome,
545    client: &str,
546    registry: &Registry,
547    pending: &[&Found],
548) -> Result<Migration, CoreError> {
549    let mut migration = Migration {
550        files: Vec::new(),
551        commit: None,
552        backup: None,
553    };
554    let state = home.state_dir();
555    let backup = home
556        .backups_dir()
557        .join(BACKUP_DIR)
558        .join(timestamp(env.now()));
559    for file in pending.iter().filter(|file| file.area == Area::State) {
560        let kind = registry.kind(file.kind).expect("surveyed kinds exist");
561        let path = join(&state, &file.relative);
562        let bytes = fs
563            .read(&path)
564            .map_err(|err| io_error("cannot read file", &path, &err))?;
565        let text = upgrade(kind, &file.relative, &bytes, file.version)
566            .map_err(|err| err.with_path(&path))?;
567        let copy = join(&backup.join(Area::State.dir()), &file.relative);
568        let parent = copy.parent().unwrap_or(&backup);
569        fs.create_private_dir_all(&backup)
570            .and_then(|()| fs.create_dir_all(parent))
571            .map_err(|err| io_error("cannot create directory", parent, &err))?;
572        fs.write(&copy, &bytes)
573            .map_err(|err| io_error("cannot write file", &copy, &err))?;
574        write_atomic(fs, &path, text.as_bytes())?;
575        migration.backup = Some(backup.clone());
576        migration
577            .files
578            .push(migrated(&file.file(), file.version, kind));
579    }
580    let store_pending: Vec<&Found> = pending
581        .iter()
582        .copied()
583        .filter(|file| file.area == Area::Store)
584        .collect();
585    if !store_pending.is_empty() {
586        migrate_store(
587            env,
588            fs,
589            home,
590            client,
591            registry,
592            &store_pending,
593            &mut migration,
594        )?;
595    }
596    Ok(migration)
597}
598
599/// The store part of a migration. HEAD's blobs are upgraded and committed
600/// first, without touching the working tree; then the working tree is
601/// written. A working-tree file with the same bytes as HEAD gets the
602/// committed bytes; one that differs (hand edits, or a file a crash left
603/// at the old version after the commit) is upgraded on its own and stays
604/// as it is relative to HEAD (uncommitted). Every upgrade is computed
605/// before anything is written, so a working-tree file that cannot be
606/// upgraded fails the migration with nothing committed.
607fn migrate_store(
608    env: &Env,
609    fs: &dyn Fs,
610    home: &SurjectionHome,
611    client: &str,
612    registry: &Registry,
613    pending: &[&Found],
614    migration: &mut Migration,
615) -> Result<(), CoreError> {
616    let kind = registry.kind("store").expect("the store kind exists");
617    let to = kind.current();
618    let store = Store::open_raw(env, fs, home, client)?.ok_or_else(|| {
619        CoreError::new(ErrorCode::NotFound, "the store is not a repository")
620            .with_path(home.store_dir())
621    })?;
622    let revision = store.revision(&store.head()?)?;
623    let mut committed = Files::new();
624    let mut old_head = Files::new();
625    let mut from = to;
626    for relative in revision.files()? {
627        if !is_store_schema_file(&relative) {
628            continue;
629        }
630        let Some(bytes) = revision.read_bytes(&relative)? else {
631            continue;
632        };
633        let Some(version) = std::str::from_utf8(&bytes)
634            .ok()
635            .and_then(|text| read_version(Format::Toml, text))
636        else {
637            continue;
638        };
639        if !(FIRST..to).contains(&version) {
640            continue;
641        }
642        let text = upgrade(kind, &relative, &bytes, version)
643            .map_err(|err| err.with_path(store.path(&relative).unwrap_or_default()))?;
644        from = from.min(version);
645        committed.insert(relative.clone(), text.into_bytes());
646        old_head.insert(relative, bytes);
647    }
648
649    let mut worktree = Vec::new();
650    for file in pending {
651        let path = store.path(&file.relative)?;
652        let bytes = fs
653            .read(&path)
654            .map_err(|err| io_error("cannot read file", &path, &err))?;
655        let new = match (old_head.get(&file.relative), committed.get(&file.relative)) {
656            (Some(old), Some(new)) if *old == bytes => new.clone(),
657            _ => upgrade(kind, &file.relative, &bytes, file.version)
658                .map_err(|err| {
659                    CoreError::new(
660                        err.code(),
661                        format!(
662                            "store/{} has changes that are not committed and cannot be \
663                             upgraded to schema {to}: {}. Fix or remove them by hand, then run \
664                             {} again.",
665                            file.relative,
666                            err.message(),
667                            brand::PRODUCT_NAME
668                        ),
669                    )
670                    .with_path(&path)
671                })?
672                .into_bytes(),
673        };
674        worktree.push((path, new));
675    }
676    for relative in committed.keys() {
677        if !pending.iter().any(|file| &file.relative == relative) {
678            let old = &old_head[relative];
679            let version = std::str::from_utf8(old)
680                .ok()
681                .and_then(|text| read_version(Format::Toml, text))
682                .unwrap_or(FIRST);
683            migration
684                .files
685                .push(migrated(&format!("store/{relative}"), version, kind));
686        }
687    }
688    for file in pending {
689        migration
690            .files
691            .push(migrated(&file.file(), file.version, kind));
692    }
693
694    if !committed.is_empty() {
695        let count = committed.len();
696        let noun = if count == 1 { "file" } else { "files" };
697        let operation = Operation::new(
698            "store.migrate",
699            format!("migrate: store schema {from} -> {to} ({count} {noun})"),
700        );
701        migration.commit = store.commit_migration(&operation, committed, to == SCHEMA_VERSION)?;
702    }
703    if let Some(hook) = registry.after_commit {
704        hook()?;
705    }
706    for (path, bytes) in worktree {
707        write_atomic(fs, &path, &bytes)?;
708    }
709    Ok(())
710}
711
712fn migrated(file: &str, from: i64, kind: &Kind) -> Migrated {
713    Migrated {
714        kind: kind.name,
715        file: file.to_owned(),
716        from,
717        to: kind.current(),
718    }
719}
720
721/// `bytes` (a file of `kind` at version `from`) upgraded to the kind's
722/// current version. Keeps a UTF-8 BOM, CRLF line endings and, for TOML,
723/// comments and formatting.
724fn upgrade(kind: &Kind, relative: &str, bytes: &[u8], from: i64) -> Result<String, CoreError> {
725    let text = std::str::from_utf8(bytes)
726        .map_err(|_| CoreError::new(ErrorCode::ParseError, "the file is not UTF-8"))?;
727    let bom = text.starts_with(BOM);
728    let text = text.strip_prefix(BOM).unwrap_or(text);
729    let crlf = text.find('\n').is_some_and(|i| text[..i].ends_with('\r'));
730    let text = if crlf {
731        text.replace("\r\n", "\n")
732    } else {
733        text.to_owned()
734    };
735    let final_newline = text.ends_with('\n');
736    let mut doc = match kind.format {
737        Format::Toml => Doc::Toml(
738            text.parse::<DocumentMut>()
739                .map_err(|err| CoreError::new(ErrorCode::ParseError, err.message().to_owned()))?,
740        ),
741        Format::Json => Doc::Json(
742            serde_json::from_str(&text)
743                .map_err(|err| CoreError::new(ErrorCode::ParseError, err.to_string()))?,
744        ),
745    };
746    for version in from..kind.current() {
747        let index = usize::try_from(version - FIRST).map_err(|_| {
748            CoreError::new(
749                ErrorCode::UnsupportedSchema,
750                format!("schema {version} is older than any version this build migrates"),
751            )
752        })?;
753        let step = kind.steps.get(index).ok_or_else(|| {
754            CoreError::new(
755                ErrorCode::UnsupportedSchema,
756                format!("no migration from schema {version} for {}", kind.name),
757            )
758        })?;
759        (step.rewrite)(relative, &mut doc)?;
760        set_version(&mut doc, version + 1);
761    }
762    let mut out = match &doc {
763        Doc::Toml(doc) => doc.to_string(),
764        Doc::Json(value) => {
765            let mut out = serde_json::to_string_pretty(value).map_err(|err| {
766                CoreError::new(ErrorCode::InvalidValue, format!("cannot serialize: {err}"))
767            })?;
768            if final_newline {
769                out.push('\n');
770            }
771            out
772        }
773    };
774    if crlf {
775        out = out.replace('\n', "\r\n");
776    }
777    if bom {
778        out.insert(0, BOM);
779    }
780    Ok(out)
781}
782
783/// Sets the top-level `schema`, keeping the TOML key's comments.
784fn set_version(doc: &mut Doc, version: i64) {
785    match doc {
786        Doc::Toml(doc) => match doc.get_mut("schema").and_then(Item::as_value_mut) {
787            Some(value) => {
788                let decor = value.decor().clone();
789                *value = toml_edit::Value::from(version);
790                *value.decor_mut() = decor;
791            }
792            None => {
793                doc.insert("schema", toml_edit::value(version));
794            }
795        },
796        Doc::Json(value) => {
797            if let Some(object) = value.as_object_mut() {
798                object.insert("schema".to_owned(), serde_json::Value::from(version));
799            }
800        }
801    }
802}
803
804/// [`check_store_files_with`] over [`Registry::builtin`].
805pub fn check_store_files<'f>(
806    files: impl IntoIterator<Item = (&'f str, &'f [u8])>,
807    origin: &str,
808) -> Result<(), CoreError> {
809    check_store_files_with(files, origin, &Registry::builtin())
810}
811
812/// Refuses an incoming store (an incoming commit, an export or a restore
813/// source; store-relative paths and bytes) whose files are at another
814/// store version than this build's, with `unsupported_schema`. Newer:
815/// update Surjection here. Older (after a version bump, from a machine that
816/// still runs an older Surjection): its files cannot be merged field by field
817/// into migrated ones, so the other machine has to be updated and push
818/// again. Versions below the first one are left to the readers. `origin`
819/// starts the message (`The remote "backup"`).
820pub fn check_store_files_with<'f>(
821    files: impl IntoIterator<Item = (&'f str, &'f [u8])>,
822    origin: &str,
823    registry: &Registry,
824) -> Result<(), CoreError> {
825    let current = registry.kind("store").map_or(SCHEMA_VERSION, Kind::current);
826    let product = brand::PRODUCT_NAME;
827    for (relative, bytes) in files {
828        if !is_store_schema_file(relative) {
829            continue;
830        }
831        let Some(found) = std::str::from_utf8(bytes)
832            .ok()
833            .and_then(|text| read_version(Format::Toml, text))
834        else {
835            continue;
836        };
837        let message = if found > current {
838            newer_message(&format!("{origin} holds data"), found, current)
839        } else if (FIRST..current).contains(&found) {
840            format!(
841                "{origin} holds data written by an older {product} (schema {found}; this version \
842                 reads {current}). Update {product} on that machine and push again."
843            )
844        } else {
845            continue;
846        };
847        return Err(CoreError::new(ErrorCode::UnsupportedSchema, message).with_path(relative));
848    }
849    Ok(())
850}
851
852impl Store<'_> {
853    /// [`Store::check_incoming_with`] over [`Registry::builtin`].
854    pub fn check_incoming(&self, id: &CommitId, origin: &str) -> Result<(), CoreError> {
855        self.check_incoming_with(id, origin, &Registry::builtin())
856    }
857
858    /// [`check_store_files_with`] over commit `id`'s tree (its objects are
859    /// in the store already): run before a pull or restore tags or merges
860    /// it, so a refused source leaves HEAD, the working tree and the tags
861    /// as they were.
862    pub fn check_incoming_with(
863        &self,
864        id: &CommitId,
865        origin: &str,
866        registry: &Registry,
867    ) -> Result<(), CoreError> {
868        let revision = self.revision(id)?;
869        let mut files = Files::new();
870        for relative in revision.files()? {
871            if is_store_schema_file(&relative)
872                && let Some(bytes) = revision.read_bytes(&relative)?
873            {
874                files.insert(relative, bytes);
875            }
876        }
877        check_store_files_with(
878            files
879                .iter()
880                .map(|(path, bytes)| (path.as_str(), bytes.as_slice())),
881            origin,
882            registry,
883        )
884    }
885}
886
887fn io_error(what: &str, path: &Path, err: &std::io::Error) -> CoreError {
888    CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path)
889}
890
891/// The machine-local file names Loadout 1.0.x gave its own files, by
892/// folder below the data folder: `(folder, old prefix, new prefix)`. A
893/// file is renamed when its name is the old prefix or starts with it
894/// followed by `.` (`loadout.log.1`, `loadout.log.lock`).
895/// `state/loadout.lock` keeps its name: the store lock holds it too
896/// ([`crate::store::StoreLock`]).
897const LEGACY_NAMES: [(&str, &str, &str); 1] =
898    [("logs", "loadout.log", crate::diagnostics::log::LOG_FILE)];
899
900/// A machine-local file that still carries the former product name and
901/// what it becomes (relative to the data folder, `/`-separated).
902#[derive(Debug, Clone, PartialEq, Eq)]
903pub struct LegacyName {
904    pub from: String,
905    pub to: String,
906}
907
908/// The machine-local files of `home` that Loadout 1.0.x named after itself
909/// and that [`rename_legacy_names`] would rename. Reads only. The synced
910/// store keeps its names (`store/loadout.toml`, `store/.loadout-allow`):
911/// renaming them would need a store schema bump, which would refuse pulls
912/// from 1.0.x machines and restores of 1.0.x backups.
913pub fn legacy_names(fs: &dyn Fs, home: &SurjectionHome) -> Vec<LegacyName> {
914    let mut found = Vec::new();
915    for (folder, old, new) in LEGACY_NAMES {
916        let dir = home.path.join(folder);
917        let Ok(entries) = fs.read_dir(&dir) else {
918            continue;
919        };
920        for path in entries {
921            let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
922                continue;
923            };
924            let Some(rest) = name.strip_prefix(old) else {
925                continue;
926            };
927            if !(rest.is_empty() || rest.starts_with('.')) || !fs.is_regular_file(&path) {
928                continue;
929            }
930            found.push(LegacyName {
931                from: format!("{folder}/{name}"),
932                to: format!("{folder}/{new}{rest}"),
933            });
934        }
935    }
936    found.sort_by(|a, b| a.from.cmp(&b.from));
937    found
938}
939
940/// Renames the files [`legacy_names`] lists (M56 data-folder names, run
941/// before anything opens them). A file whose new name exists already is
942/// left alone. Idempotent. Returns what was renamed.
943pub fn rename_legacy_names(fs: &dyn Fs, home: &SurjectionHome) -> Vec<LegacyName> {
944    let mut done = Vec::new();
945    for name in legacy_names(fs, home) {
946        let from = join(&home.path, &name.from);
947        let to = join(&home.path, &name.to);
948        if fs.exists(&to) {
949            continue;
950        }
951        if fs.replace(&from, &to).is_ok() {
952            done.push(name);
953        }
954    }
955    done
956}