use std::path::{Path, PathBuf};
use toml_edit::{DocumentMut, Item};
use crate::apply::backup::timestamp;
use crate::apply::journal::{APPLIES_DIR, JOURNAL_DIR};
use crate::apply::ledger::LEDGER_FILE;
use crate::apply::unmanaged::SEEN_FILE;
use crate::apply::write_atomic;
use crate::brand;
use crate::eject::EJECT_FILE;
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::layering::trust::TRUST_FILE;
use crate::local_settings::LOCAL_SETTINGS_FILE;
use crate::model::{SCHEMA_VERSION, StoreFile};
use crate::paths::SurjectionHome;
use crate::remote::config::REMOTES_FILE;
use crate::remote::sync::STATUS_FILE;
use crate::scan::RULES_OVERRIDE_FILE;
use crate::store::merge::{Files, MERGE_STATE};
use crate::store::{
CommitId, IDENTITY_FILE, LOCK_TIMEOUT, MACHINE_FILE, Operation, Store, StoreLock,
};
#[cfg(test)]
mod tests;
const FIRST: i64 = 1;
pub const BACKUP_DIR: &str = "schema";
const BOM: char = '\u{feff}';
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Area {
Store,
State,
}
impl Area {
pub fn dir(self) -> &'static str {
match self {
Area::Store => "store",
Area::State => "state",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
Toml,
Json,
}
#[derive(Debug, Clone)]
pub enum Doc {
Toml(DocumentMut),
Json(serde_json::Value),
}
pub type Rewrite = fn(&str, &mut Doc) -> Result<(), CoreError>;
#[derive(Debug, Clone, Copy)]
pub struct Step {
pub rewrite: Rewrite,
}
#[derive(Debug, Clone)]
pub struct Kind {
pub name: &'static str,
pub area: Area,
pub format: Format,
steps: Vec<Step>,
matches: fn(&str) -> bool,
}
impl Kind {
fn new(name: &'static str, area: Area, format: Format, matches: fn(&str) -> bool) -> Self {
Self {
name,
area,
format,
steps: Vec::new(),
matches,
}
}
pub fn current(&self) -> i64 {
FIRST + i64::try_from(self.steps.len()).unwrap_or(i64::MAX - FIRST)
}
}
pub type AfterCommit = fn() -> Result<(), CoreError>;
#[derive(Debug, Clone)]
pub struct Registry {
kinds: Vec<Kind>,
after_commit: Option<AfterCommit>,
}
impl Registry {
pub fn builtin() -> Self {
use Area::{State, Store};
use Format::{Json, Toml};
Self {
kinds: vec![
Kind::new("store", Store, Toml, is_store_schema_file),
Kind::new("machine", State, Toml, |p| p == MACHINE_FILE),
Kind::new("local-settings", State, Toml, |p| p == LOCAL_SETTINGS_FILE),
Kind::new("remotes", State, Toml, |p| p == REMOTES_FILE),
Kind::new("remote-status", State, Toml, |p| p == STATUS_FILE),
Kind::new("scan-rules", State, Toml, |p| p == RULES_OVERRIDE_FILE),
Kind::new("ledger", State, Json, |p| p == LEDGER_FILE),
Kind::new("trust", State, Json, |p| p == TRUST_FILE),
Kind::new("unmanaged-seen", State, Json, |p| p == SEEN_FILE),
Kind::new("merge-state", State, Json, is_merge_state),
Kind::new("journal", State, Json, is_journal),
Kind::new("eject", State, Json, |p| p == EJECT_FILE),
],
after_commit: None,
}
.with_step("ledger", Step { rewrite: renamed })
}
#[must_use]
pub fn with_step(mut self, name: &str, step: Step) -> Self {
let kind = self
.kinds
.iter_mut()
.find(|kind| kind.name == name)
.unwrap_or_else(|| panic!("unknown file kind {name:?}"));
kind.steps.push(step);
self
}
#[must_use]
pub fn with_after_commit(mut self, hook: AfterCommit) -> Self {
self.after_commit = Some(hook);
self
}
pub fn kinds(&self) -> &[Kind] {
&self.kinds
}
pub fn kind(&self, name: &str) -> Option<&Kind> {
self.kinds.iter().find(|kind| kind.name == name)
}
fn kind_of(&self, area: Area, relative: &str) -> Option<&Kind> {
self.kinds
.iter()
.find(|kind| kind.area == area && (kind.matches)(relative))
}
}
pub(crate) fn is_store_schema_file(relative: &str) -> bool {
relative == IDENTITY_FILE || StoreFile::classify(Path::new(relative)).is_some()
}
fn renamed(_: &str, _: &mut Doc) -> Result<(), CoreError> {
Ok(())
}
fn is_merge_state(relative: &str) -> bool {
relative
.strip_prefix("merge/")
.is_some_and(|name| name == MERGE_STATE)
}
fn is_journal(relative: &str) -> bool {
[JOURNAL_DIR, APPLIES_DIR].into_iter().any(|dir| {
relative
.strip_prefix(dir)
.and_then(|rest| rest.strip_prefix('/'))
.is_some_and(|name| !name.contains('/') && name.ends_with(".json"))
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Found {
pub kind: &'static str,
pub area: Area,
pub relative: String,
pub version: i64,
}
impl Found {
pub fn file(&self) -> String {
format!("{}/{}", self.area.dir(), self.relative)
}
}
pub fn survey(
fs: &dyn Fs,
home: &SurjectionHome,
registry: &Registry,
) -> Result<Vec<Found>, CoreError> {
let mut found = Vec::new();
let store = home.store_dir();
if fs.exists(&store.join(".git")) {
let mut dirs: Vec<String> = ["", "servers", "skill-meta", "machines"]
.into_iter()
.map(str::to_owned)
.collect();
for project in list_dirs(fs, &store.join("projects"))? {
dirs.push(format!("projects/{project}"));
}
collect(fs, &store, Area::Store, &dirs, registry, false, &mut found)?;
}
let state = home.state_dir();
let dirs = [String::new(), "merge".to_owned()];
collect(fs, &state, Area::State, &dirs, registry, false, &mut found)?;
let newest_only = registry
.kind("journal")
.is_some_and(|kind| kind.steps.is_empty());
let dirs = [JOURNAL_DIR.to_owned(), APPLIES_DIR.to_owned()];
collect(
fs,
&state,
Area::State,
&dirs,
registry,
newest_only,
&mut found,
)?;
Ok(found)
}
fn collect(
fs: &dyn Fs,
root: &Path,
area: Area,
dirs: &[String],
registry: &Registry,
newest_only: bool,
found: &mut Vec<Found>,
) -> Result<(), CoreError> {
for dir in dirs {
let mut files: Vec<(String, &Kind)> = list_files(fs, &join(root, dir))?
.into_iter()
.filter_map(|name| {
let relative = if dir.is_empty() {
name
} else {
format!("{dir}/{name}")
};
let kind = registry.kind_of(area, &relative)?;
Some((relative, kind))
})
.collect();
if newest_only {
files = files.pop().into_iter().collect();
}
for (relative, kind) in files {
let Ok(text) = fs.read_to_string(&join(root, &relative)) else {
continue;
};
if let Some(version) = read_version(kind.format, &text) {
found.push(Found {
kind: kind.name,
area,
relative,
version,
});
}
}
}
Ok(())
}
fn list_files(fs: &dyn Fs, dir: &Path) -> Result<Vec<String>, CoreError> {
list(fs, dir, false)
}
fn list_dirs(fs: &dyn Fs, dir: &Path) -> Result<Vec<String>, CoreError> {
list(fs, dir, true)
}
fn list(fs: &dyn Fs, dir: &Path, dirs: bool) -> Result<Vec<String>, CoreError> {
if !fs.is_dir(dir) {
return Ok(Vec::new());
}
let entries = fs.read_dir(dir).map_err(|err| {
CoreError::new(ErrorCode::IoError, format!("cannot list directory: {err}")).with_path(dir)
})?;
let mut names: Vec<String> = entries
.iter()
.filter(|entry| fs.is_dir(entry) == dirs)
.filter_map(|entry| entry.file_name()?.to_str().map(str::to_owned))
.collect();
names.sort();
Ok(names)
}
fn join(root: &Path, relative: &str) -> PathBuf {
relative
.split('/')
.filter(|part| !part.is_empty())
.fold(root.to_path_buf(), |path, part| path.join(part))
}
#[derive(serde::Deserialize)]
struct SchemaField {
#[serde(default)]
schema: Option<i64>,
}
pub fn read_version(format: Format, text: &str) -> Option<i64> {
let text = text.strip_prefix(BOM).unwrap_or(text);
let field: SchemaField = match format {
Format::Toml => toml::from_str(text).ok()?,
Format::Json => serde_json::from_str(text).ok()?,
};
field.schema
}
pub fn written_by_newer(fs: &dyn Fs, path: &Path, format: Format, supported: i64) -> bool {
fs.read_to_string(path)
.ok()
.and_then(|text| read_version(format, &text))
.is_some_and(|found| found > supported)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewerData {
pub kind: &'static str,
pub file: String,
pub found: i64,
pub supported: i64,
}
impl NewerData {
pub fn message(&self) -> String {
newer_message("This data folder was", self.found, self.supported)
}
pub fn to_error(&self, home: &SurjectionHome) -> CoreError {
CoreError::new(ErrorCode::UnsupportedSchema, self.message())
.with_path(join(&home.path, &self.file))
}
}
fn newer_message(subject: &str, found: i64, supported: i64) -> String {
let product = brand::PRODUCT_NAME;
format!(
"{subject} written by a newer {product} (schema {found}; this version reads up to \
{supported}). Update {product}."
)
}
fn first_newer(found: &[Found], registry: &Registry) -> Option<NewerData> {
found.iter().find_map(|file| {
let supported = registry.kind(file.kind)?.current();
(file.version > supported).then(|| NewerData {
kind: file.kind,
file: file.file(),
found: file.version,
supported,
})
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Migrated {
pub kind: &'static str,
pub file: String,
pub from: i64,
pub to: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Migration {
pub files: Vec<Migrated>,
pub commit: Option<CommitId>,
pub backup: Option<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Prepared {
Ready(Option<Migration>),
Newer(NewerData),
}
impl Prepared {
pub fn into_result(self, home: &SurjectionHome) -> Result<Option<Migration>, CoreError> {
match self {
Prepared::Ready(migration) => Ok(migration),
Prepared::Newer(newer) => Err(newer.to_error(home)),
}
}
}
pub fn prepare(
env: &Env,
fs: &dyn Fs,
home: &SurjectionHome,
client: &str,
) -> Result<Prepared, CoreError> {
prepare_with(env, fs, home, client, &Registry::builtin())
}
pub fn prepare_with(
env: &Env,
fs: &dyn Fs,
home: &SurjectionHome,
client: &str,
registry: &Registry,
) -> Result<Prepared, CoreError> {
let found = survey(fs, home, registry)?;
if let Some(newer) = first_newer(&found, registry) {
return Ok(Prepared::Newer(newer));
}
rename_legacy_names(fs, home);
if pending(&found, registry).next().is_none() {
return Ok(Prepared::Ready(None));
}
let _lock = StoreLock::acquire(fs, &home.state_dir(), LOCK_TIMEOUT)?;
let found = survey(fs, home, registry)?;
if let Some(newer) = first_newer(&found, registry) {
return Ok(Prepared::Newer(newer));
}
let pending: Vec<&Found> = pending(&found, registry).collect();
if pending.is_empty() {
return Ok(Prepared::Ready(None));
}
migrate(env, fs, home, client, registry, &pending).map(|m| Prepared::Ready(Some(m)))
}
fn pending<'f>(found: &'f [Found], registry: &'f Registry) -> impl Iterator<Item = &'f Found> + 'f {
found.iter().filter(|file| {
registry
.kind(file.kind)
.is_some_and(|kind| (FIRST..kind.current()).contains(&file.version))
})
}
fn migrate(
env: &Env,
fs: &dyn Fs,
home: &SurjectionHome,
client: &str,
registry: &Registry,
pending: &[&Found],
) -> Result<Migration, CoreError> {
let mut migration = Migration {
files: Vec::new(),
commit: None,
backup: None,
};
let state = home.state_dir();
let backup = home
.backups_dir()
.join(BACKUP_DIR)
.join(timestamp(env.now()));
for file in pending.iter().filter(|file| file.area == Area::State) {
let kind = registry.kind(file.kind).expect("surveyed kinds exist");
let path = join(&state, &file.relative);
let bytes = fs
.read(&path)
.map_err(|err| io_error("cannot read file", &path, &err))?;
let text = upgrade(kind, &file.relative, &bytes, file.version)
.map_err(|err| err.with_path(&path))?;
let copy = join(&backup.join(Area::State.dir()), &file.relative);
let parent = copy.parent().unwrap_or(&backup);
fs.create_private_dir_all(&backup)
.and_then(|()| fs.create_dir_all(parent))
.map_err(|err| io_error("cannot create directory", parent, &err))?;
fs.write(©, &bytes)
.map_err(|err| io_error("cannot write file", ©, &err))?;
write_atomic(fs, &path, text.as_bytes())?;
migration.backup = Some(backup.clone());
migration
.files
.push(migrated(&file.file(), file.version, kind));
}
let store_pending: Vec<&Found> = pending
.iter()
.copied()
.filter(|file| file.area == Area::Store)
.collect();
if !store_pending.is_empty() {
migrate_store(
env,
fs,
home,
client,
registry,
&store_pending,
&mut migration,
)?;
}
Ok(migration)
}
fn migrate_store(
env: &Env,
fs: &dyn Fs,
home: &SurjectionHome,
client: &str,
registry: &Registry,
pending: &[&Found],
migration: &mut Migration,
) -> Result<(), CoreError> {
let kind = registry.kind("store").expect("the store kind exists");
let to = kind.current();
let store = Store::open_raw(env, fs, home, client)?.ok_or_else(|| {
CoreError::new(ErrorCode::NotFound, "the store is not a repository")
.with_path(home.store_dir())
})?;
let revision = store.revision(&store.head()?)?;
let mut committed = Files::new();
let mut old_head = Files::new();
let mut from = to;
for relative in revision.files()? {
if !is_store_schema_file(&relative) {
continue;
}
let Some(bytes) = revision.read_bytes(&relative)? else {
continue;
};
let Some(version) = std::str::from_utf8(&bytes)
.ok()
.and_then(|text| read_version(Format::Toml, text))
else {
continue;
};
if !(FIRST..to).contains(&version) {
continue;
}
let text = upgrade(kind, &relative, &bytes, version)
.map_err(|err| err.with_path(store.path(&relative).unwrap_or_default()))?;
from = from.min(version);
committed.insert(relative.clone(), text.into_bytes());
old_head.insert(relative, bytes);
}
let mut worktree = Vec::new();
for file in pending {
let path = store.path(&file.relative)?;
let bytes = fs
.read(&path)
.map_err(|err| io_error("cannot read file", &path, &err))?;
let new = match (old_head.get(&file.relative), committed.get(&file.relative)) {
(Some(old), Some(new)) if *old == bytes => new.clone(),
_ => upgrade(kind, &file.relative, &bytes, file.version)
.map_err(|err| {
CoreError::new(
err.code(),
format!(
"store/{} has changes that are not committed and cannot be \
upgraded to schema {to}: {}. Fix or remove them by hand, then run \
{} again.",
file.relative,
err.message(),
brand::PRODUCT_NAME
),
)
.with_path(&path)
})?
.into_bytes(),
};
worktree.push((path, new));
}
for relative in committed.keys() {
if !pending.iter().any(|file| &file.relative == relative) {
let old = &old_head[relative];
let version = std::str::from_utf8(old)
.ok()
.and_then(|text| read_version(Format::Toml, text))
.unwrap_or(FIRST);
migration
.files
.push(migrated(&format!("store/{relative}"), version, kind));
}
}
for file in pending {
migration
.files
.push(migrated(&file.file(), file.version, kind));
}
if !committed.is_empty() {
let count = committed.len();
let noun = if count == 1 { "file" } else { "files" };
let operation = Operation::new(
"store.migrate",
format!("migrate: store schema {from} -> {to} ({count} {noun})"),
);
migration.commit = store.commit_migration(&operation, committed, to == SCHEMA_VERSION)?;
}
if let Some(hook) = registry.after_commit {
hook()?;
}
for (path, bytes) in worktree {
write_atomic(fs, &path, &bytes)?;
}
Ok(())
}
fn migrated(file: &str, from: i64, kind: &Kind) -> Migrated {
Migrated {
kind: kind.name,
file: file.to_owned(),
from,
to: kind.current(),
}
}
fn upgrade(kind: &Kind, relative: &str, bytes: &[u8], from: i64) -> Result<String, CoreError> {
let text = std::str::from_utf8(bytes)
.map_err(|_| CoreError::new(ErrorCode::ParseError, "the file is not UTF-8"))?;
let bom = text.starts_with(BOM);
let text = text.strip_prefix(BOM).unwrap_or(text);
let crlf = text.find('\n').is_some_and(|i| text[..i].ends_with('\r'));
let text = if crlf {
text.replace("\r\n", "\n")
} else {
text.to_owned()
};
let final_newline = text.ends_with('\n');
let mut doc = match kind.format {
Format::Toml => Doc::Toml(
text.parse::<DocumentMut>()
.map_err(|err| CoreError::new(ErrorCode::ParseError, err.message().to_owned()))?,
),
Format::Json => Doc::Json(
serde_json::from_str(&text)
.map_err(|err| CoreError::new(ErrorCode::ParseError, err.to_string()))?,
),
};
for version in from..kind.current() {
let index = usize::try_from(version - FIRST).map_err(|_| {
CoreError::new(
ErrorCode::UnsupportedSchema,
format!("schema {version} is older than any version this build migrates"),
)
})?;
let step = kind.steps.get(index).ok_or_else(|| {
CoreError::new(
ErrorCode::UnsupportedSchema,
format!("no migration from schema {version} for {}", kind.name),
)
})?;
(step.rewrite)(relative, &mut doc)?;
set_version(&mut doc, version + 1);
}
let mut out = match &doc {
Doc::Toml(doc) => doc.to_string(),
Doc::Json(value) => {
let mut out = serde_json::to_string_pretty(value).map_err(|err| {
CoreError::new(ErrorCode::InvalidValue, format!("cannot serialize: {err}"))
})?;
if final_newline {
out.push('\n');
}
out
}
};
if crlf {
out = out.replace('\n', "\r\n");
}
if bom {
out.insert(0, BOM);
}
Ok(out)
}
fn set_version(doc: &mut Doc, version: i64) {
match doc {
Doc::Toml(doc) => match doc.get_mut("schema").and_then(Item::as_value_mut) {
Some(value) => {
let decor = value.decor().clone();
*value = toml_edit::Value::from(version);
*value.decor_mut() = decor;
}
None => {
doc.insert("schema", toml_edit::value(version));
}
},
Doc::Json(value) => {
if let Some(object) = value.as_object_mut() {
object.insert("schema".to_owned(), serde_json::Value::from(version));
}
}
}
}
pub fn check_store_files<'f>(
files: impl IntoIterator<Item = (&'f str, &'f [u8])>,
origin: &str,
) -> Result<(), CoreError> {
check_store_files_with(files, origin, &Registry::builtin())
}
pub fn check_store_files_with<'f>(
files: impl IntoIterator<Item = (&'f str, &'f [u8])>,
origin: &str,
registry: &Registry,
) -> Result<(), CoreError> {
let current = registry.kind("store").map_or(SCHEMA_VERSION, Kind::current);
let product = brand::PRODUCT_NAME;
for (relative, bytes) in files {
if !is_store_schema_file(relative) {
continue;
}
let Some(found) = std::str::from_utf8(bytes)
.ok()
.and_then(|text| read_version(Format::Toml, text))
else {
continue;
};
let message = if found > current {
newer_message(&format!("{origin} holds data"), found, current)
} else if (FIRST..current).contains(&found) {
format!(
"{origin} holds data written by an older {product} (schema {found}; this version \
reads {current}). Update {product} on that machine and push again."
)
} else {
continue;
};
return Err(CoreError::new(ErrorCode::UnsupportedSchema, message).with_path(relative));
}
Ok(())
}
impl Store<'_> {
pub fn check_incoming(&self, id: &CommitId, origin: &str) -> Result<(), CoreError> {
self.check_incoming_with(id, origin, &Registry::builtin())
}
pub fn check_incoming_with(
&self,
id: &CommitId,
origin: &str,
registry: &Registry,
) -> Result<(), CoreError> {
let revision = self.revision(id)?;
let mut files = Files::new();
for relative in revision.files()? {
if is_store_schema_file(&relative)
&& let Some(bytes) = revision.read_bytes(&relative)?
{
files.insert(relative, bytes);
}
}
check_store_files_with(
files
.iter()
.map(|(path, bytes)| (path.as_str(), bytes.as_slice())),
origin,
registry,
)
}
}
fn io_error(what: &str, path: &Path, err: &std::io::Error) -> CoreError {
CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path)
}
const LEGACY_NAMES: [(&str, &str, &str); 1] =
[("logs", "loadout.log", crate::diagnostics::log::LOG_FILE)];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LegacyName {
pub from: String,
pub to: String,
}
pub fn legacy_names(fs: &dyn Fs, home: &SurjectionHome) -> Vec<LegacyName> {
let mut found = Vec::new();
for (folder, old, new) in LEGACY_NAMES {
let dir = home.path.join(folder);
let Ok(entries) = fs.read_dir(&dir) else {
continue;
};
for path in entries {
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
continue;
};
let Some(rest) = name.strip_prefix(old) else {
continue;
};
if !(rest.is_empty() || rest.starts_with('.')) || !fs.is_regular_file(&path) {
continue;
}
found.push(LegacyName {
from: format!("{folder}/{name}"),
to: format!("{folder}/{new}{rest}"),
});
}
}
found.sort_by(|a, b| a.from.cmp(&b.from));
found
}
pub fn rename_legacy_names(fs: &dyn Fs, home: &SurjectionHome) -> Vec<LegacyName> {
let mut done = Vec::new();
for name in legacy_names(fs, home) {
let from = join(&home.path, &name.from);
let to = join(&home.path, &name.to);
if fs.exists(&to) {
continue;
}
if fs.replace(&from, &to).is_ok() {
done.push(name);
}
}
done
}