feat(M9.1): add transactional profile drafts

Test: cargo test -p fader-config --all-targets --all-features

Test: cargo clippy -p fader-config --all-targets --all-features -- -D warnings
This commit is contained in:
Dandaedre 2026-10-15 04:05:39 +02:00
parent 44582036c5
commit 9493183365
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
6 changed files with 280 additions and 29 deletions

View File

@ -298,6 +298,12 @@ Reject unknown schema versions/fields, duplicate IDs/physical bindings, dangling
Write same-directory temporary files, flush/fsync, rename atomically, then sync the directory. Debounce state writes (initial target: 500 ms after changes, maximum 2 s between dirty checkpoints), flush on orderly shutdown, and document the corresponding crash-loss window. Permission/disk-full errors leave the old file usable and show an unsaved state. Preserve user comments in profile edits with `toml_edit`. The server is the sole writer; TUI edits carry a base revision and conflict if stale. Detect out-of-process file edits before saving rather than overwriting them.
Editor mutations are first applied to a cloned, comment-preserving document and
the complete candidate profile is semantically validated before the draft is
replaced. Invalid matchers, duplicate IDs, and referenced deletes therefore
leave the prior draft unchanged. The v1 editor creates absolute groups; relative
group controls remain a reserved future mode.
The implemented atomic writer checks that its parent and any existing target
are owned by the effective user and are not symlinks. It creates mode-`0600`
temporary files in the destination directory, streams and syncs their content,

View File

@ -1,8 +1,22 @@
use std::str::FromStr;
use toml_edit::{DocumentMut, Item, Value};
use toml_edit::{Array, DocumentMut, InlineTable, Item, Table, Value, value};
use crate::{ConfigError, Profile};
use crate::{ConfigError, Profile, SelectorField, TargetKind};
/// Match expression used when creating an application selector.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SelectorPattern {
Exact(String),
Regex(String),
}
/// Editable selector input for a virtual application.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SelectorDraft {
pub field: SelectorField,
pub pattern: SelectorPattern,
}
/// A comment-preserving profile edit that is revalidated before use.
pub struct ProfileDocument {
@ -23,30 +37,172 @@ impl ProfileDocument {
application_id: &str,
label: &str,
) -> Result<(), ConfigError> {
let applications = self
.document
.get_mut("applications")
.and_then(Item::as_array_of_tables_mut)
.ok_or_else(|| ConfigError::validation("applications", "missing application array"))?;
let Some(application) = applications.iter_mut().find(|table| {
table
.get("id")
.and_then(Item::as_str)
.is_some_and(|id| id == application_id)
}) else {
return Err(ConfigError::validation(
"applications",
format!("unknown application {application_id:?}"),
));
};
let existing = application
.get_mut("label")
.and_then(Item::as_value_mut)
.ok_or_else(|| ConfigError::validation("applications.label", "missing string label"))?;
let decor = existing.decor().clone();
let mut replacement = Value::from(label);
*replacement.decor_mut() = decor;
*existing = replacement;
self.transaction(|document| {
let applications = document
.get_mut("applications")
.and_then(Item::as_array_of_tables_mut)
.ok_or_else(|| {
ConfigError::validation("applications", "missing application array")
})?;
let Some(application) = applications.iter_mut().find(|table| {
table
.get("id")
.and_then(Item::as_str)
.is_some_and(|id| id == application_id)
}) else {
return Err(ConfigError::validation(
"applications",
format!("unknown application {application_id:?}"),
));
};
let existing = application
.get_mut("label")
.and_then(Item::as_value_mut)
.ok_or_else(|| {
ConfigError::validation("applications.label", "missing string label")
})?;
let decor = existing.decor().clone();
let mut replacement = Value::from(label);
*replacement.decor_mut() = decor;
*existing = replacement;
Ok(())
})
}
/// Adds a virtual application and validates the whole resulting profile.
pub fn add_application(
&mut self,
id: &str,
label: &str,
selectors: &[SelectorDraft],
) -> Result<(), ConfigError> {
self.transaction(|document| {
let applications = document
.get_mut("applications")
.and_then(Item::as_array_of_tables_mut)
.ok_or_else(|| {
ConfigError::validation("applications", "missing application array")
})?;
let mut table = Table::new();
table["id"] = value(id);
table["label"] = value(label);
let mut selector_values = Array::new();
for selector in selectors {
let mut inline = InlineTable::new();
inline.insert("field", Value::from(selector.field.as_str()));
match &selector.pattern {
SelectorPattern::Exact(pattern) => {
inline.insert("exact", Value::from(pattern.as_str()));
}
SelectorPattern::Regex(pattern) => {
inline.insert("regex", Value::from(pattern.as_str()));
}
}
selector_values.push(Value::InlineTable(inline));
}
table["selectors"] = value(selector_values);
applications.push(table);
Ok(())
})
}
/// Removes an application only when no remaining object references it.
pub fn remove_application(&mut self, id: &str) -> Result<(), ConfigError> {
self.transaction(|document| {
let applications = document
.get_mut("applications")
.and_then(Item::as_array_of_tables_mut)
.ok_or_else(|| {
ConfigError::validation("applications", "missing application array")
})?;
let index = applications
.iter()
.position(|table| table.get("id").and_then(Item::as_str) == Some(id))
.ok_or_else(|| {
ConfigError::validation("applications", format!("unknown application {id:?}"))
})?;
applications.remove(index);
Ok(())
})
}
/// Adds an absolute group and validates all member references.
pub fn add_group(
&mut self,
id: &str,
label: &str,
members: &[&str],
) -> Result<(), ConfigError> {
self.transaction(|document| {
let groups = document
.get_mut("groups")
.and_then(Item::as_array_of_tables_mut)
.ok_or_else(|| ConfigError::validation("groups", "missing group array"))?;
let mut table = Table::new();
table["id"] = value(id);
table["label"] = value(label);
let mut member_values = Array::new();
for member in members {
member_values.push(*member);
}
table["members"] = value(member_values);
table["volume_mode"] = value("absolute");
groups.push(table);
Ok(())
})
}
/// Adds a logical fader and validates its target.
pub fn add_fader(
&mut self,
id: &str,
target_kind: TargetKind,
target_id: &str,
pickup: bool,
pickup_tolerance: f64,
) -> Result<(), ConfigError> {
self.transaction(|document| {
let faders = document
.get_mut("faders")
.and_then(Item::as_array_of_tables_mut)
.ok_or_else(|| ConfigError::validation("faders", "missing fader array"))?;
let mut table = Table::new();
table["id"] = value(id);
let mut target = InlineTable::new();
let kind = match target_kind {
TargetKind::Application => "application",
TargetKind::Group => "group",
TargetKind::Output => "output",
};
target.insert("kind", Value::from(kind));
target.insert("id", Value::from(target_id));
table["target"] = value(target);
table["pickup"] = value(pickup);
table["pickup_tolerance"] = value(pickup_tolerance);
faders.push(table);
Ok(())
})
}
/// Returns the current source without consuming the draft.
#[must_use]
pub fn source(&self) -> String {
self.document.to_string()
}
/// Builds a validated runtime profile without consuming the draft.
pub fn preview(&self) -> Result<Profile, ConfigError> {
Profile::parse(&self.document.to_string())
}
fn transaction(
&mut self,
edit: impl FnOnce(&mut DocumentMut) -> Result<(), ConfigError>,
) -> Result<(), ConfigError> {
let mut candidate = self.document.clone();
edit(&mut candidate)?;
Profile::parse(&candidate.to_string())?;
self.document = candidate;
Ok(())
}

View File

@ -18,13 +18,13 @@ mod state;
pub use checkpoint::{CheckpointCoordinator, CheckpointSink, Clock, StateFileSink, SystemClock};
pub use device::{DeviceCapabilities, DeviceProfile};
pub use document::ProfileDocument;
pub use document::{ProfileDocument, SelectorDraft, SelectorPattern};
pub use error::ConfigError;
pub use files::{AtomicFile, MigrationError, PersistenceError, StateLoad, migrate_profile};
pub use paths::{XdgEnvironment, XdgPaths};
pub use profile::{
Action, Adapter, Application, Audio, Binding, Fader, Group, MessageKind, NewStreamPolicy,
Profile, StartupPolicy, Surface, TargetKind,
Profile, SelectorField, StartupPolicy, Surface, TargetKind,
};
pub use state::{
CachedObservation, DesiredWrite, PersistedState, ProfileState, StartupState, UiView,

View File

@ -93,7 +93,7 @@ struct Selector {
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
enum SelectorField {
pub enum SelectorField {
#[serde(rename = "application.name")]
ApplicationName,
#[serde(rename = "application.id")]
@ -104,6 +104,17 @@ enum SelectorField {
MediaName,
}
impl SelectorField {
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::ApplicationName => "application.name",
Self::ApplicationId => "application.id",
Self::ProcessBinary => "application.process.binary",
Self::MediaName => "media.name",
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
enum VolumeMode {

74
config/tests/editor.rs Normal file
View File

@ -0,0 +1,74 @@
use fader_config::{ProfileDocument, SelectorDraft, SelectorField, SelectorPattern, TargetKind};
const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml");
#[test]
fn draft_creates_an_application_group_and_fader_as_valid_toml() {
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
draft
.add_application(
"chat",
"Chat",
&[SelectorDraft {
field: SelectorField::ProcessBinary,
pattern: SelectorPattern::Exact("signal-desktop".to_owned()),
}],
)
.unwrap();
draft
.add_group("communications", "Communications", &["chat", "browser"])
.unwrap();
draft
.add_fader(
"communications-fader",
TargetKind::Group,
"communications",
true,
0.02,
)
.unwrap();
let profile = draft.preview().unwrap();
assert!(
profile
.applications()
.iter()
.any(|item| item.id() == "chat")
);
assert!(
profile
.groups()
.iter()
.any(|item| item.id() == "communications")
);
assert!(
profile
.faders()
.iter()
.any(|item| item.id() == "communications-fader")
);
ProfileDocument::parse(&draft.finish().unwrap()).unwrap();
}
#[test]
fn invalid_edits_and_referenced_deletes_roll_back_the_draft() {
let mut draft = ProfileDocument::parse(PROFILE).unwrap();
let original = draft.source();
let invalid = draft
.add_application(
"broken",
"Broken",
&[SelectorDraft {
field: SelectorField::ApplicationName,
pattern: SelectorPattern::Regex("(".to_owned()),
}],
)
.unwrap_err();
assert!(invalid.to_string().contains("regex"));
assert_eq!(draft.source(), original);
let referenced = draft.remove_application("browser").unwrap_err();
assert!(referenced.to_string().contains("unknown application"));
assert_eq!(draft.source(), original);
}

View File

@ -333,6 +333,10 @@ regression-tested profile fix then matched it into the two-stream media group.
Dependencies: M8, M2, M1.
- [ ] **M9.1 Editor drafts:** separate tab to create/edit/delete applications, groups and faders; target/member selection, matcher preview, validation errors and referenced-delete handling. Tests: invalid regex/dangling member rejected; Cancel has no side effects; creating a group/fader produces the expected semantic TOML.
Transactional, comment-preserving draft primitives now create applications,
absolute groups and faders, and roll back invalid regexes or referenced
deletes. The separate TUI tab, selection controls, matcher preview, and full
edit/delete surface remain.
- [ ] **M9.2 Surface bindings / MIDI learn:** select surface, listen for one supported control, preview conflicts and save binding. Tests: learning suppresses the normal action, other surfaces are not captured accidentally, cancellation restores routing, duplicate binding is rejected.
- [ ] **M9.3 Apply/save/conflict:** server-owned revisioned edits, separate live apply and persistence. Tests: stale edits conflict, external file edits are not overwritten, comments survive save, write failure is shown as unsaved and leaves previous disk config usable.