feat: safely upgrade legacy profiles
Recognize pre-versioned and schema-0 profiles during server startup, preserve comments, validate the complete migrated candidate, save exact original bytes as a versioned backup, and atomically install the upgrade. Never rewrite malformed or future-schema profiles. Tests: cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features; cargo test --workspace --all-targets --all-features; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features; cargo check --workspace; cargo check --workspace --no-default-features; cargo check -p midi --no-default-features --features midir; cargo check -p volume_lib --no-default-features --features pulse
This commit is contained in:
parent
564fca9001
commit
c30b361fd0
|
|
@ -59,6 +59,13 @@ active selection names a missing managed profile, that empty profile is created
|
|||
with the selected ID. Explicit missing `--config` paths still fail, preventing a
|
||||
mistyped path from silently creating a file.
|
||||
|
||||
Server startup recognizes the pre-versioned/schema-0 profile format. It updates
|
||||
only the schema marker after validating the complete migrated profile, keeps
|
||||
comments via `toml_edit`, writes the exact original bytes beside the profile as
|
||||
`NAME.toml.v0.bak`, and atomically installs the result. Unknown newer schemas or
|
||||
malformed profiles are never rewritten; the startup error explains that a safe
|
||||
upgrade was unavailable. The `validate` command remains read-only.
|
||||
|
||||
The mixer arrow keys follow its orientation. In Vertical mode, use Up/Down to
|
||||
select a configured fader or separator and Left/Right to change its volume. In
|
||||
Horizontal mode, use Left/Right to select and Up/Down to change volume. J/K
|
||||
|
|
|
|||
|
|
@ -340,6 +340,10 @@ directories are mode `0700`. Missing state and malformed readable state are
|
|||
distinct recoverable load outcomes; malformed bytes are retained for diagnosis.
|
||||
Profile migration accepts only versions below the current schema, validates the
|
||||
replacement first, and durably backs up the original bytes before replacement.
|
||||
Server startup invokes the registered migration for pre-versioned/schema-0
|
||||
profiles, preserving TOML comments and reporting the `.v0.bak` path. A malformed
|
||||
document, invalid migrated candidate, unknown future schema, or existing backup
|
||||
aborts without replacing the profile. Validation-only commands never migrate.
|
||||
Checkpoint changes are written after 500 ms without another change and at least
|
||||
every two seconds during sustained input, then flushed once more on orderly
|
||||
shutdown. A process or machine crash can therefore lose up to the latest
|
||||
|
|
|
|||
|
|
@ -3,10 +3,12 @@ use std::{
|
|||
io::{self, Cursor, Read, Write},
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
use tempfile::NamedTempFile;
|
||||
use thiserror::Error;
|
||||
use toml_edit::{DocumentMut, value};
|
||||
|
||||
use crate::{ConfigError, PersistedState, Profile, SCHEMA_VERSION};
|
||||
|
||||
|
|
@ -192,6 +194,75 @@ pub enum MigrationError {
|
|||
Persistence(#[from] PersistenceError),
|
||||
}
|
||||
|
||||
/// Result of checking and, when supported, upgrading a profile document.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum ProfileUpgrade {
|
||||
/// The profile already uses the current schema and was only validated.
|
||||
Current {
|
||||
/// Current schema version.
|
||||
version: u16,
|
||||
},
|
||||
/// An older profile was validated, backed up, and atomically replaced.
|
||||
Upgraded {
|
||||
/// Durable backup containing the exact original bytes.
|
||||
backup: PathBuf,
|
||||
/// Original schema version.
|
||||
from: u16,
|
||||
/// Installed schema version.
|
||||
to: u16,
|
||||
},
|
||||
}
|
||||
|
||||
/// Upgrades a known older profile schema without discarding comments.
|
||||
///
|
||||
/// A missing schema marker is treated as the pre-versioned schema `0`. The
|
||||
/// migrated candidate must pass complete current validation before either the
|
||||
/// backup or destination is written.
|
||||
pub fn upgrade_profile(path: &Path) -> Result<ProfileUpgrade, MigrationError> {
|
||||
let source = fs::read_to_string(path)
|
||||
.map_err(|error| PersistenceError::io("read profile for upgrade", path, error))?;
|
||||
let mut document = DocumentMut::from_str(&source).map_err(ConfigError::from)?;
|
||||
let from = profile_schema_version(&document)?;
|
||||
if from == SCHEMA_VERSION {
|
||||
Profile::parse(&source)?;
|
||||
return Ok(ProfileUpgrade::Current { version: from });
|
||||
}
|
||||
if from != 0 {
|
||||
return Err(MigrationError::Incompatible {
|
||||
from,
|
||||
to: SCHEMA_VERSION,
|
||||
});
|
||||
}
|
||||
|
||||
document["schema_version"] = value(i64::from(SCHEMA_VERSION));
|
||||
let migrated = document.to_string();
|
||||
Profile::parse(&migrated)?;
|
||||
let backup = migrate_profile(path, from, &migrated)?;
|
||||
Ok(ProfileUpgrade::Upgraded {
|
||||
backup,
|
||||
from,
|
||||
to: SCHEMA_VERSION,
|
||||
})
|
||||
}
|
||||
|
||||
fn profile_schema_version(document: &DocumentMut) -> Result<u16, ConfigError> {
|
||||
let Some(item) = document.get("schema_version") else {
|
||||
return Ok(0);
|
||||
};
|
||||
let Some(version) = item.as_integer() else {
|
||||
return Err(ConfigError::validation(
|
||||
"schema_version",
|
||||
"must be a non-negative integer",
|
||||
));
|
||||
};
|
||||
u16::try_from(version).map_err(|_| {
|
||||
ConfigError::validation(
|
||||
"schema_version",
|
||||
"must be within the supported integer range",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Validates and atomically installs a forward migration after backing up bytes.
|
||||
pub fn migrate_profile(
|
||||
path: &Path,
|
||||
|
|
|
|||
|
|
@ -21,7 +21,10 @@ pub use checkpoint::{CheckpointCoordinator, CheckpointSink, Clock, StateFileSink
|
|||
pub use device::{DeviceCapabilities, DeviceProfile};
|
||||
pub use document::{ProfileDocument, SelectorDraft, SelectorPattern};
|
||||
pub use error::ConfigError;
|
||||
pub use files::{AtomicFile, MigrationError, PersistenceError, StateLoad, migrate_profile};
|
||||
pub use files::{
|
||||
AtomicFile, MigrationError, PersistenceError, ProfileUpgrade, StateLoad, migrate_profile,
|
||||
upgrade_profile,
|
||||
};
|
||||
pub use paths::{XdgEnvironment, XdgPaths};
|
||||
pub use profile::{
|
||||
Action, Adapter, Application, Audio, Binding, Fader, FaderDensity, Group, MessageKind,
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ use std::{
|
|||
|
||||
use fader_config::{
|
||||
ActiveConfig, AtomicFile, ConfigError, MigrationError, PersistenceError, ProfileDocument,
|
||||
StateLoad, XdgEnvironment, XdgPaths, migrate_profile,
|
||||
ProfileUpgrade, StateLoad, XdgEnvironment, XdgPaths, migrate_profile, upgrade_profile,
|
||||
};
|
||||
|
||||
#[test]
|
||||
|
|
@ -187,6 +187,59 @@ fn migration_keeps_a_backup_and_rejects_downgrades() {
|
|||
assert!(matches!(result, Err(MigrationError::Incompatible { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_upgrade_preserves_comments_and_backs_up_old_schema() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().unwrap();
|
||||
let target = paths.profile_file("desktop").unwrap();
|
||||
let legacy = PROFILE
|
||||
.replace("schema_version = 1", "schema_version = 0")
|
||||
.replace("id = \"desktop\"", "# keep this comment\nid = \"desktop\"");
|
||||
AtomicFile::write(&target, legacy.as_bytes()).unwrap();
|
||||
|
||||
let outcome = upgrade_profile(&target).expect("known old schema upgrades");
|
||||
|
||||
let ProfileUpgrade::Upgraded { backup, from, to } = outcome else {
|
||||
panic!("old profile was not upgraded");
|
||||
};
|
||||
assert_eq!((from, to), (0, 1));
|
||||
assert_eq!(fs::read_to_string(backup).unwrap(), legacy);
|
||||
let upgraded = fs::read_to_string(target).unwrap();
|
||||
assert!(upgraded.contains("# keep this comment"));
|
||||
assert!(fader_config::Profile::parse(&upgraded).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_upgrade_never_rewrites_an_invalid_candidate() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().unwrap();
|
||||
let target = paths.profile_file("broken").unwrap();
|
||||
let invalid = "schema_version = 0\nid = 'broken'\nunknown = true\n";
|
||||
AtomicFile::write(&target, invalid.as_bytes()).unwrap();
|
||||
|
||||
assert!(upgrade_profile(&target).is_err());
|
||||
assert_eq!(fs::read_to_string(&target).unwrap(), invalid);
|
||||
assert!(!target.with_file_name("broken.toml.v0.bak").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_upgrade_accepts_a_pre_versioned_document() {
|
||||
let root = tempdir().expect("temporary root");
|
||||
let paths = test_paths(root.path());
|
||||
paths.create_layout().unwrap();
|
||||
let target = paths.profile_file("desktop").unwrap();
|
||||
let legacy = PROFILE.replacen("schema_version = 1\n", "", 1);
|
||||
AtomicFile::write(&target, legacy.as_bytes()).unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
upgrade_profile(&target).unwrap(),
|
||||
ProfileUpgrade::Upgraded { from: 0, to: 1, .. }
|
||||
));
|
||||
assert!(fader_config::Profile::parse(&fs::read_to_string(target).unwrap()).is_ok());
|
||||
}
|
||||
|
||||
fn test_paths(root: &Path) -> XdgPaths {
|
||||
XdgPaths::resolve(&XdgEnvironment {
|
||||
home: root.join("home"),
|
||||
|
|
|
|||
|
|
@ -10,7 +10,10 @@ use std::{
|
|||
};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use fader_config::{ActiveConfig, AtomicFile, Profile, ProfileDocument, XdgEnvironment, XdgPaths};
|
||||
use fader_config::{
|
||||
ActiveConfig, AtomicFile, Profile, ProfileDocument, ProfileUpgrade, XdgEnvironment, XdgPaths,
|
||||
upgrade_profile,
|
||||
};
|
||||
use fader_core::Gain;
|
||||
use midi::{LinuxIdentityCatalog, MidiInputCatalog};
|
||||
use volume_lib::{AudioBackend, CompiledAdapterProbe, TargetRequirements, select_adapter};
|
||||
|
|
@ -165,7 +168,33 @@ fn load_profile(path: &Path) -> Result<Profile> {
|
|||
fn load_profile_document(path: &Path) -> Result<ProfileDocument> {
|
||||
let input = fs::read_to_string(path)
|
||||
.with_context(|| format!("could not read profile {}", path.display()))?;
|
||||
ProfileDocument::parse(&input).with_context(|| format!("profile {} is invalid", path.display()))
|
||||
match ProfileDocument::parse(&input) {
|
||||
Ok(document) => Ok(document),
|
||||
Err(original_error) => match upgrade_profile(path) {
|
||||
Ok(ProfileUpgrade::Upgraded { backup, from, to }) => {
|
||||
eprintln!(
|
||||
"upgraded profile {} from schema {} to {}; backup: {}",
|
||||
path.display(),
|
||||
from,
|
||||
to,
|
||||
backup.display()
|
||||
);
|
||||
let upgraded = fs::read_to_string(path).with_context(|| {
|
||||
format!("could not read upgraded profile {}", path.display())
|
||||
})?;
|
||||
ProfileDocument::parse(&upgraded)
|
||||
.with_context(|| format!("upgraded profile {} is invalid", path.display()))
|
||||
}
|
||||
Ok(ProfileUpgrade::Current { .. }) => Err(original_error)
|
||||
.with_context(|| format!("profile {} is invalid", path.display())),
|
||||
Err(upgrade_error) => Err(original_error).with_context(|| {
|
||||
format!(
|
||||
"profile {} is invalid and could not be safely upgraded: {upgrade_error}",
|
||||
path.display()
|
||||
)
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_managed_profile(paths: &XdgPaths) -> Result<PathBuf> {
|
||||
|
|
@ -366,7 +395,7 @@ mod tests {
|
|||
use fader_config::{ActiveConfig, ProfileDocument, XdgEnvironment, XdgPaths};
|
||||
use tempfile::tempdir;
|
||||
|
||||
use super::{resolve_managed_profile, start_if_missing};
|
||||
use super::{load_profile_document, resolve_managed_profile, start_if_missing};
|
||||
|
||||
#[test]
|
||||
fn combined_mode_only_starts_a_server_when_probe_did_not_find_one() {
|
||||
|
|
@ -431,4 +460,38 @@ mod tests {
|
|||
let document = ProfileDocument::parse(&fs::read_to_string(&profile_path).unwrap()).unwrap();
|
||||
assert_eq!(document.preview().unwrap().id().as_str(), "arch-pipewire");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_load_upgrades_an_old_profile_with_a_backup() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("legacy.toml");
|
||||
let legacy = ProfileDocument::empty("legacy")
|
||||
.unwrap()
|
||||
.finish()
|
||||
.unwrap()
|
||||
.replace("schema_version = 1", "schema_version = 0");
|
||||
fs::write(&path, &legacy).unwrap();
|
||||
|
||||
let document = load_profile_document(&path).unwrap();
|
||||
|
||||
assert_eq!(document.preview().unwrap().id().as_str(), "legacy");
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.path().join("legacy.toml.v0.bak")).unwrap(),
|
||||
legacy
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_load_does_not_rewrite_a_malformed_profile() {
|
||||
let root = tempdir().unwrap();
|
||||
let path = root.path().join("broken.toml");
|
||||
let malformed = "schema_version = 0\nid = [not valid";
|
||||
fs::write(&path, malformed).unwrap();
|
||||
|
||||
let error = load_profile_document(&path).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("could not be safely upgraded"));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), malformed);
|
||||
assert!(!root.path().join("broken.toml.v0.bak").exists());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
4
task.md
4
task.md
|
|
@ -464,7 +464,9 @@ Dependencies: all required feature milestones; hardware-only ALSA remains an exp
|
|||
Managed startup now initializes a valid empty `default` profile and active
|
||||
pointer on first run, and recreates only a missing profile referenced by a
|
||||
valid existing pointer. Explicit paths and malformed existing files remain
|
||||
errors rather than being overwritten.
|
||||
errors rather than being overwritten. Pre-versioned/schema-0 profiles upgrade
|
||||
automatically only after full candidate validation, with comment preservation,
|
||||
an exact `.v0.bak` backup, and atomic replacement.
|
||||
- [ ] **M12.4 Release gates:** all workspace/default/feature/MSRV checks, reproducible lockfile, license review and dependency advisory review using maintained tooling selected at implementation time. Measure/control latency under multi-surface load and publish the tested envelope.
|
||||
|
||||
## User requirement coverage
|
||||
|
|
|
|||
Loading…
Reference in New Issue