feat(M9.1): own revisioned drafts in the server

Test: cargo test -p fader_master --all-targets --all-features

Test: cargo test -p tui --all-targets --all-features

Test: cargo clippy -p fader_master -p tui --all-targets --all-features -- -D warnings
This commit is contained in:
Dandaedre 2026-10-15 04:11:38 +02:00
parent b5d7ac9c5f
commit 102f233980
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
11 changed files with 352 additions and 15 deletions

View File

@ -304,6 +304,11 @@ 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 live mixer revision and configuration-draft revision are independent.
Draft edits are serialized by the server, require the caller's expected draft
revision, and never mutate live routing or audio as a side effect. Successful
draft edits are explicitly marked unsaved until a later apply/save command.
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

@ -19,6 +19,7 @@ pub struct SelectorDraft {
}
/// A comment-preserving profile edit that is revalidated before use.
#[derive(Debug)]
pub struct ProfileDocument {
document: DocumentMut,
}

199
fader_master/src/editor.rs Normal file
View File

@ -0,0 +1,199 @@
use fader_config::{
ConfigError, Profile, ProfileDocument, SelectorDraft, SelectorField, SelectorPattern,
TargetKind,
};
use thiserror::Error;
use crate::ipc::{ConfigurationEdit, MixerObjectKind};
#[derive(Debug, Error)]
pub(crate) enum EditorError {
#[error("stale configuration revision {actual}; current revision is {current}")]
StaleRevision { actual: u64, current: u64 },
#[error(transparent)]
Config(#[from] ConfigError),
}
#[derive(Debug)]
pub(crate) struct ConfigurationEditor {
document: ProfileDocument,
revision: u64,
dirty: bool,
}
impl ConfigurationEditor {
pub(crate) const fn new(document: ProfileDocument) -> Self {
Self {
document,
revision: 0,
dirty: false,
}
}
pub(crate) const fn revision(&self) -> u64 {
self.revision
}
pub(crate) const fn dirty(&self) -> bool {
self.dirty
}
pub(crate) fn profile(&self) -> Result<Profile, EditorError> {
Ok(self.document.preview()?)
}
pub(crate) fn apply(
&mut self,
expected_revision: u64,
edit: ConfigurationEdit,
) -> Result<Profile, EditorError> {
if expected_revision != self.revision {
return Err(EditorError::StaleRevision {
actual: expected_revision,
current: self.revision,
});
}
match edit {
ConfigurationEdit::AddApplication {
id,
label,
field,
pattern,
regex,
} => {
self.document
.add_application(&id, &label, &[selector(&field, pattern, regex)?])?
}
ConfigurationEdit::SetApplication {
id,
label,
field,
pattern,
regex,
} => {
self.document
.set_application(&id, &label, &[selector(&field, pattern, regex)?])?
}
ConfigurationEdit::RemoveApplication { id } => self.document.remove_application(&id)?,
ConfigurationEdit::AddGroup { id, label, members } => {
let members = members.iter().map(String::as_str).collect::<Vec<_>>();
self.document.add_group(&id, &label, &members)?;
}
ConfigurationEdit::SetGroup { id, label, members } => {
let members = members.iter().map(String::as_str).collect::<Vec<_>>();
self.document.set_group(&id, &label, &members)?;
}
ConfigurationEdit::RemoveGroup { id } => self.document.remove_group(&id)?,
ConfigurationEdit::AddFader {
id,
target,
pickup,
pickup_tolerance,
} => self.document.add_fader(
&id,
target_kind(target.kind),
&target.id,
pickup,
pickup_tolerance,
)?,
ConfigurationEdit::SetFader {
id,
target,
pickup,
pickup_tolerance,
} => self.document.set_fader(
&id,
target_kind(target.kind),
&target.id,
pickup,
pickup_tolerance,
)?,
ConfigurationEdit::RemoveFader { id } => self.document.remove_fader(&id)?,
}
self.revision = self.revision.saturating_add(1);
self.dirty = true;
self.profile()
}
}
fn selector(field: &str, pattern: String, regex: bool) -> Result<SelectorDraft, ConfigError> {
let field = match field {
"application.name" => SelectorField::ApplicationName,
"application.id" => SelectorField::ApplicationId,
"application.process.binary" => SelectorField::ProcessBinary,
"media.name" => SelectorField::MediaName,
_ => {
return Err(ConfigError::Validation {
path: "application.selector.field".to_owned(),
message: format!("unsupported selector field {field:?}"),
});
}
};
Ok(SelectorDraft {
field,
pattern: if regex {
SelectorPattern::Regex(pattern)
} else {
SelectorPattern::Exact(pattern)
},
})
}
const fn target_kind(kind: MixerObjectKind) -> TargetKind {
match kind {
MixerObjectKind::Application => TargetKind::Application,
MixerObjectKind::Group => TargetKind::Group,
MixerObjectKind::Output => TargetKind::Output,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ipc::MixerObjectKey;
const PROFILE: &str = include_str!("../../examples/profiles/desktop.toml");
#[test]
fn accepted_edits_advance_revision_and_stale_or_invalid_edits_do_not() {
let document = ProfileDocument::parse(PROFILE).unwrap();
let mut editor = ConfigurationEditor::new(document);
let profile = editor
.apply(
0,
ConfigurationEdit::AddFader {
id: "browser-fader".into(),
target: MixerObjectKey {
kind: MixerObjectKind::Application,
id: "browser".into(),
},
pickup: true,
pickup_tolerance: 0.02,
},
)
.unwrap();
assert_eq!(profile.faders().len(), 2);
assert_eq!(editor.revision(), 1);
assert!(editor.dirty());
let stale = editor
.apply(0, ConfigurationEdit::RemoveGroup { id: "media".into() })
.unwrap_err();
assert!(matches!(stale, EditorError::StaleRevision { .. }));
let invalid = editor
.apply(
1,
ConfigurationEdit::SetApplication {
id: "browser".into(),
label: "Browser".into(),
field: "application.process.binary".into(),
pattern: "(".into(),
regex: true,
},
)
.unwrap_err();
assert!(invalid.to_string().contains("regex"));
assert_eq!(editor.revision(), 1);
assert_eq!(editor.profile().unwrap().faders().len(), 2);
}
}

View File

@ -3,7 +3,7 @@ use std::io::{self, Read, Write};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use thiserror::Error;
pub const PROTOCOL_VERSION: u16 = 5;
pub const PROTOCOL_VERSION: u16 = 6;
pub const MAX_FRAME_BYTES: usize = 64 * 1024;
/// Kind of mixer object addressed by a client.
@ -43,6 +43,10 @@ pub struct ClientRequest {
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RequestCommand {
Snapshot,
EditConfiguration {
expected_revision: u64,
edit: ConfigurationEdit,
},
SetVolume {
object: MixerObjectKey,
gain: f64,
@ -54,6 +58,56 @@ pub enum RequestCommand {
},
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "operation", rename_all = "snake_case")]
pub enum ConfigurationEdit {
AddApplication {
id: String,
label: String,
field: String,
pattern: String,
regex: bool,
},
SetApplication {
id: String,
label: String,
field: String,
pattern: String,
regex: bool,
},
RemoveApplication {
id: String,
},
AddGroup {
id: String,
label: String,
members: Vec<String>,
},
SetGroup {
id: String,
label: String,
members: Vec<String>,
},
RemoveGroup {
id: String,
},
AddFader {
id: String,
target: MixerObjectKey,
pickup: bool,
pickup_tolerance: f64,
},
SetFader {
id: String,
target: MixerObjectKey,
pickup: bool,
pickup_tolerance: f64,
},
RemoveFader {
id: String,
},
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ServerResponse {
pub version: u16,
@ -64,7 +118,7 @@ pub struct ServerResponse {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ResponseResult {
Snapshot { snapshot: MixerSnapshot },
Snapshot { snapshot: Box<MixerSnapshot> },
Error { message: String, resync: bool },
}
@ -80,6 +134,8 @@ pub struct MixerSnapshot {
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct ConfigurationSnapshot {
pub revision: u64,
pub dirty: bool,
pub profile_id: String,
pub applications: Vec<ConfiguredApplication>,
pub groups: Vec<ConfiguredGroup>,

View File

@ -3,6 +3,7 @@
#![forbid(unsafe_code)]
pub mod cli;
mod editor;
pub mod ipc;
pub mod live;
pub mod local;

View File

@ -97,8 +97,14 @@ pub enum LiveMixerError {
Profile(String),
}
fn configuration_snapshot(profile: &Profile) -> ConfigurationSnapshot {
pub(crate) fn configuration_snapshot(
profile: &Profile,
revision: u64,
dirty: bool,
) -> ConfigurationSnapshot {
ConfigurationSnapshot {
revision,
dirty,
profile_id: profile.id().to_string(),
applications: profile
.applications()
@ -251,7 +257,7 @@ impl LiveMixerState {
write_ceiling,
backend: backend.into(),
status: "connecting".to_owned(),
configuration: configuration_snapshot(profile),
configuration: configuration_snapshot(profile, 0, false),
})
}
@ -402,6 +408,10 @@ impl LiveMixerState {
self.devices = devices;
}
pub(crate) fn set_configuration(&mut self, configuration: ConfigurationSnapshot) {
self.configuration = configuration;
}
pub fn midi_intent(
&mut self,
intent: MidiIntent,
@ -555,6 +565,11 @@ impl LiveMixerState {
let request_id = request.request_id;
let commands = match request.command {
RequestCommand::Snapshot => Vec::new(),
RequestCommand::EditConfiguration { .. } => {
return Err(LiveMixerError::Profile(
"configuration edits must be handled by the server owner".to_owned(),
));
}
RequestCommand::SetVolume {
object,
gain,
@ -570,7 +585,7 @@ impl LiveMixerState {
version: PROTOCOL_VERSION,
request_id,
result: ResponseResult::Snapshot {
snapshot: self.snapshot(),
snapshot: Box::new(self.snapshot()),
},
},
commands,

View File

@ -9,16 +9,17 @@ use std::{
time::Duration,
};
use fader_config::{Profile, XdgEnvironment, XdgPaths};
use fader_config::{ProfileDocument, XdgEnvironment, XdgPaths};
use fader_core::{BackendEpoch, Gain};
use thiserror::Error;
use volume_lib::{AdapterQueue, Enqueue, PulseWorker, WorkerEvent};
use crate::{
editor::ConfigurationEditor,
ipc::{
ClientRequest, PROTOCOL_VERSION, ResponseResult, ServerResponse, read_frame, write_frame,
},
live::LiveMixerState,
live::{LiveMixerState, configuration_snapshot},
};
const CLIENT_TIMEOUT: Duration = Duration::from_millis(500);
@ -176,16 +177,18 @@ pub struct LocalServer {
midi_sequence: u64,
dispatch: AdapterQueue,
poll_interval: Duration,
configuration: ConfigurationEditor,
}
impl LocalServer {
pub fn pulse(
socket: impl Into<PathBuf>,
write_ceiling: Gain,
profile: &Profile,
document: ProfileDocument,
) -> Result<Self, LocalError> {
let profile = document.preview()?;
let midi =
crate::midi_runtime::MidiRuntime::new(profile).map_err(LocalError::MidiRuntime)?;
crate::midi_runtime::MidiRuntime::new(&profile).map_err(LocalError::MidiRuntime)?;
Ok(Self {
listener: OwnedListener::bind(socket)?,
// One waiting native command keeps round-trip backpressure at the
@ -196,11 +199,12 @@ impl LocalServer {
256,
profile.poll_interval(),
),
mixer: LiveMixerState::new(write_ceiling, "pulse", profile)?,
mixer: LiveMixerState::new(write_ceiling, "pulse", &profile)?,
midi,
midi_sequence: 1,
dispatch: AdapterQueue::new(256),
poll_interval: profile.poll_interval(),
configuration: ConfigurationEditor::new(document),
})
}
@ -259,7 +263,34 @@ impl LocalServer {
fn serve_client(&mut self, stream: &mut UnixStream) -> Result<(), LocalError> {
let request: ClientRequest = read_frame(stream)?;
let request_id = request.request_id;
let response = match self.mixer.request(request) {
let result = match request.command {
crate::ipc::RequestCommand::EditConfiguration {
expected_revision,
edit,
} if request.version == PROTOCOL_VERSION => {
match self.configuration.apply(expected_revision, edit) {
Ok(profile) => {
self.mixer.set_configuration(configuration_snapshot(
&profile,
self.configuration.revision(),
self.configuration.dirty(),
));
self.mixer.request(ClientRequest {
version: request.version,
request_id,
command: crate::ipc::RequestCommand::Snapshot,
})
}
Err(error) => Err(crate::live::LiveMixerError::Profile(error.to_string())),
}
}
command => self.mixer.request(ClientRequest {
version: request.version,
request_id,
command,
}),
};
let response = match result {
Ok((response, commands)) => {
self.enqueue(commands)?;
response

View File

@ -2,7 +2,7 @@ use std::{fs, os::unix::fs::PermissionsExt, path::Path};
use anyhow::{Context, Result, bail};
use clap::Parser;
use fader_config::{Profile, XdgEnvironment, XdgPaths};
use fader_config::{Profile, ProfileDocument, XdgEnvironment, XdgPaths};
use fader_core::Gain;
use fader_master::{
audio_selection_policy,
@ -47,12 +47,19 @@ fn load_profile(path: &Path) -> Result<Profile> {
Profile::parse(&input).with_context(|| format!("profile {} is invalid", path.display()))
}
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()))
}
fn serve(
config: &Path,
override_choice: Option<volume_lib::AdapterChoice>,
socket_override: Option<&Path>,
) -> Result<()> {
let profile = load_profile(config)?;
let document = load_profile_document(config)?;
let profile = document.preview()?;
let policy = audio_selection_policy(&profile, override_choice)?;
let selected = select_adapter(
&policy,
@ -82,7 +89,7 @@ fn serve(
profile.poll_interval().as_millis(),
socket.display()
);
LocalServer::pulse(socket, Gain::new(profile.max_gain())?, &profile)?.run()?;
LocalServer::pulse(socket, Gain::new(profile.max_gain())?, document)?.run()?;
Ok(())
}

View File

@ -90,6 +90,8 @@ impl IpcMixerClient {
})
.collect(),
configuration: tui::ConfigurationSnapshot {
revision: snapshot.configuration.revision,
dirty: snapshot.configuration.dirty,
profile_id: snapshot.configuration.profile_id,
applications: snapshot
.configuration

View File

@ -338,6 +338,9 @@ Dependencies: M8, M2, M1.
deletes. A separate Config tab now shows the server-owned applications, group
membership, logical fader targets, pickup policy, and MIDI assignments. The
selection controls, matcher preview, and full edit/delete surface remain.
The server now owns the validated draft and its independent revision; stale
or invalid edit requests are rejected without advancing or altering it, and
accepted edits are exposed as an unsaved draft in the Config tab.
- [ ] **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.

View File

@ -76,6 +76,8 @@ pub struct MidiDevice {
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ConfigurationSnapshot {
pub revision: u64,
pub dirty: bool,
pub profile_id: String,
pub applications: Vec<ConfiguredApplication>,
pub groups: Vec<ConfiguredGroup>,
@ -753,7 +755,19 @@ impl<C> LiveTui<C> {
fn render_configuration(&self, area: Rect, buf: &mut Buffer) {
let theme = self.theme.palette();
let config = &self.snapshot.configuration;
let mut lines = vec![Line::from(format!("Profile: {}", config.profile_id)).bold()];
let mut lines = vec![
Line::from(format!(
"Profile: {} · config rev {}{}",
config.profile_id,
config.revision,
if config.dirty {
" · unsaved draft"
} else {
""
}
))
.bold(),
];
lines.push(Line::from(""));
lines.push(Line::from("Applications").fg(theme.accent).bold());
lines.extend(config.applications.iter().map(|application| {
@ -1100,6 +1114,8 @@ mod tests {
let mut client = DemoClient::default();
let mut snapshot = client.view();
snapshot.configuration = ConfigurationSnapshot {
revision: 3,
dirty: true,
profile_id: "desktop".into(),
applications: vec![ConfiguredApplication {
id: "browser".into(),
@ -1140,6 +1156,7 @@ mod tests {
.collect::<String>();
assert!(rendered.contains("Profile: desktop"));
assert!(rendered.contains("unsaved draft"));
assert!(rendered.contains("media — Media [browser]"));
assert!(rendered.contains("media-fader -> group:media (pickup)"));
assert!(rendered.contains("desk-left · volume · cc ch1 #49"));