diff --git a/Cargo.lock b/Cargo.lock index 711e0d2..cf592e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -175,6 +175,9 @@ name = "fader-config" version = "0.1.0" dependencies = [ "fader-core", + "serde", + "thiserror", + "toml", ] [[package]] @@ -249,6 +252,12 @@ dependencies = [ "foldhash", ] +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" @@ -261,6 +270,16 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + [[package]] name = "indoc" version = "2.0.7" @@ -337,7 +356,7 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" dependencies = [ - "hashbrown", + "hashbrown 0.15.5", ] [[package]] @@ -679,6 +698,15 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + [[package]] name = "signal-hook" version = "0.3.18" @@ -826,6 +854,47 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "tui" version = "0.1.0" @@ -1016,6 +1085,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/Cargo.toml b/Cargo.toml index e6e88d9..034e32f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,9 @@ midi = { path = "midi" } proptest = "1.11.0" ratatui = { version = "0.29.0", features = ["all-widgets", "serde"] } regex = "1.13.1" +serde = { version = "1.0.228", features = ["derive"] } thiserror = "2.0.21" +toml = "0.8.23" tui = { path = "tui" } volume_lib = { path = "sound" } diff --git a/architecture.md b/architecture.md index 95a2d8b..7425b65 100644 --- a/architecture.md +++ b/architecture.md @@ -1,6 +1,9 @@ # fader_master architecture -Status: design researched 2026-10-05; foundation and M1 domain contracts are implemented. The executable remains a Hello World scaffold and the TUI remains a basic Ratatui example. Configuration, runtime workers, and native adapters below are planned, not shipped. +Status: design researched 2026-10-05; foundation, M1 domain contracts, and M2.1 +validated TOML schemas are implemented. The executable remains a Hello World +scaffold and the TUI remains a basic Ratatui example. Configuration persistence, +runtime workers, and native adapters below are planned, not shipped. ## Implemented boundary at M2 entry @@ -8,9 +11,13 @@ Rust 1.88.0 is the pinned toolchain and tested MSRV. The workspace inherits package metadata, including the existing custom `LICENSE` through `license-file`. `core` contains typed IDs, finite gain/channel vectors, normalized selectors, stream identities, logical routing, device-scoped bindings, group gain planning, -and serial mute intent planning. `config` is an empty inward-dependent crate; -M2 configuration work has not started. MIDI/audio crates are adapter boundaries -without native handles or transport behavior yet. +and serial mute intent planning. `config` contains strict version-1 profile, +device-capability, and persisted-state schemas. Parsing validates stable IDs, +selectors, references, duplicate IDs and physical bindings, audio/MIDI bounds, +and feedback/output capabilities before returning a document. It serializes a +canonical semantic round trip; comment-preserving edits and filesystem behavior +remain M2.2 work. MIDI/audio crates are adapter boundaries without native handles +or transport behavior yet. Stable IDs contain 1–64 ASCII bytes, start with an alphanumeric character, and otherwise allow alphanumerics, `_`, and `-`. Selector patterns contain 1–256 @@ -37,6 +44,12 @@ toolchain. Regex provides bounded compiled matching, thiserror implements typed library errors, and proptest exercises numerical invariants. Cargo.lock records the resolved versions; dependency versions are workspace-managed. +M2.1 adds `serde 1.0.229` (Rust 1.56) and `toml 0.8.23` / `toml_edit +0.22.27` (Rust 1.66), each MIT OR Apache-2.0 with no native prerequisite. +Serde defines strict data shapes and TOML supplies parsing and canonical +serialization; the resolved `toml_edit` dependency will also underpin M2.2 +comment-preserving edits. These versions compile on the pinned Rust 1.88.0. + ## Purpose and scope Run a per-user Linux server that receives controls from multiple USB MIDI surfaces, records requested state, resolves virtual application/group targets, and dispatches volume/mute commands through one selected audio adapter. Observe external audio changes and send confirmed state to every relevant TUI and MIDI output. @@ -157,7 +170,10 @@ All durable application data is TOML: profiles, device profiles/bindings, active - `~/.config/fader_master/devices/.toml`: reusable MIDI output/input protocol profiles when needed. - `~/.local/state/fader_master/state.toml`: schema version, per-profile confirmed object/channel state and separately validated desired object volume/mute, remembered assignments, last selected UI view. No ephemeral backend handles or pending operation IDs; cached observations are marked stale until refreshed. Desired values may include commands issued offline, but are applied after restart only under explicit restore policy. -The following proposed profile is syntactically valid TOML, not a claim that a parser is implemented. Sample application and MIDI names must be selected from actual discovery. CLI overrides apply for the session; persist them only on explicit Save. +The following profile is parsed and semantically validated by an automated test +and mirrored at `examples/profiles/desktop.toml`. Sample application and MIDI +names must still be selected from actual discovery. CLI overrides apply for the +session; persist them only on explicit Save. ```toml schema_version = 1 diff --git a/config/Cargo.toml b/config/Cargo.toml index 198581c..b0bee58 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -9,3 +9,6 @@ publish.workspace = true [dependencies] fader-core.workspace = true +serde.workspace = true +thiserror.workspace = true +toml.workspace = true diff --git a/config/src/device.rs b/config/src/device.rs new file mode 100644 index 0000000..a2c8bfd --- /dev/null +++ b/config/src/device.rs @@ -0,0 +1,63 @@ +use fader_core::SurfaceId; +use serde::{Deserialize, Serialize}; + +use crate::{ConfigError, SCHEMA_VERSION, profile::parse_id}; + +/// Output and motion features explicitly supported by a device profile. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct DeviceCapabilities { + /// A mute indicator can be driven. + pub mute_led: bool, + /// A numeric or bar-style value display can be driven. + pub value_display: bool, + /// A motorized fader can accept position feedback. + pub motorized_fader: bool, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +struct RawDeviceProfile { + schema_version: u16, + id: String, + label: String, + capabilities: DeviceCapabilities, +} + +/// A reusable, validated MIDI device capability document. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct DeviceProfile { + raw: RawDeviceProfile, + id: SurfaceId, +} + +impl DeviceProfile { + /// Parses and validates a device profile. + pub fn parse(input: &str) -> Result { + let raw: RawDeviceProfile = toml::from_str(input)?; + if raw.schema_version != SCHEMA_VERSION { + return Err(ConfigError::validation( + "schema_version", + format!( + "unsupported version {}; expected {SCHEMA_VERSION}", + raw.schema_version + ), + )); + } + let id = parse_id(&raw.id, "device.id")?; + if raw.label.trim().is_empty() { + return Err(ConfigError::validation("device.label", "must not be empty")); + } + Ok(Self { raw, id }) + } + + /// Serializes a canonical representation. + pub fn to_toml(&self) -> Result { + Ok(toml::to_string_pretty(&self.raw)?) + } + + /// Stable device-profile identifier. + pub fn id(&self) -> &SurfaceId { + &self.id + } +} diff --git a/config/src/error.rs b/config/src/error.rs new file mode 100644 index 0000000..b4baa5c --- /dev/null +++ b/config/src/error.rs @@ -0,0 +1,29 @@ +use thiserror::Error; + +/// A TOML syntax/schema error or a semantic validation failure. +#[derive(Debug, Error)] +pub enum ConfigError { + /// The TOML document did not conform to its strict structural schema. + #[error("TOML schema error: {0}")] + Toml(#[from] toml::de::Error), + /// A field was structurally valid TOML but violated a domain invariant. + #[error("validation error at {path}: {message}")] + Validation { + /// Stable, editor-friendly field path. + path: String, + /// Human-readable reason. + message: String, + }, + /// A validated document unexpectedly failed serialization. + #[error("could not serialize validated TOML: {0}")] + Serialize(#[from] toml::ser::Error), +} + +impl ConfigError { + pub(crate) fn validation(path: impl Into, message: impl Into) -> Self { + Self::Validation { + path: path.into(), + message: message.into(), + } + } +} diff --git a/config/src/lib.rs b/config/src/lib.rs index abc0828..c51ce1e 100644 --- a/config/src/lib.rs +++ b/config/src/lib.rs @@ -1,5 +1,23 @@ -//! TOML schemas, validation, migration, and persistence for fader_master. +//! Strict TOML schemas and semantic validation for fader_master. //! -//! Configuration depends on domain contracts but never on runtime adapters. +//! Parsing produces validated documents: callers cannot accidentally activate +//! a profile whose identifiers, references, MIDI ranges, or capabilities are +//! invalid. Persistence and migration live in separate modules in later M2 +//! increments. #![forbid(unsafe_code)] + +mod device; +mod error; +mod profile; +mod state; + +pub use device::{DeviceCapabilities, DeviceProfile}; +pub use error::ConfigError; +pub use profile::{ + Adapter, Application, Audio, Binding, Fader, Group, NewStreamPolicy, Profile, StartupPolicy, + Surface, +}; +pub use state::{PersistedState, ProfileState}; + +pub(crate) const SCHEMA_VERSION: u16 = 1; diff --git a/config/src/profile.rs b/config/src/profile.rs new file mode 100644 index 0000000..5a10e0e --- /dev/null +++ b/config/src/profile.rs @@ -0,0 +1,519 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use fader_core::{ + ApplicationId, ApplicationSelector, FaderId, GroupId, MetadataField, MidiChannel, MidiData, + ProfileId, SurfaceId, +}; +use serde::{Deserialize, Serialize}; + +use crate::{ConfigError, SCHEMA_VERSION}; + +/// Behavior when a profile becomes active. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum StartupPolicy { + /// Observe live audio without issuing writes. + Adopt, + /// Deliberately apply saved desired object state after discovery. + Restore, +} + +/// Behavior when a new stream joins a configured application. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum NewStreamPolicy { + /// Preserve the stream's live state. + Adopt, + /// Apply a saved desired value when one exists. + Restore, +} + +/// Audio adapter selection value. +#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum Adapter { + Auto, + Pulse, + Pipewire, +} + +/// Validated audio selection and write ceiling. +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Audio { + adapter: Adapter, + #[serde(default)] + preference: Vec, + max_gain: f64, +} + +/// A validated virtual application. +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Application { + id: String, + label: String, + selectors: Vec, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +struct Selector { + field: SelectorField, + #[serde(skip_serializing_if = "Option::is_none")] + exact: Option, + #[serde(skip_serializing_if = "Option::is_none")] + regex: Option, +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +enum SelectorField { + #[serde(rename = "application.name")] + ApplicationName, + #[serde(rename = "application.id")] + ApplicationId, + #[serde(rename = "application.process.binary")] + ProcessBinary, + #[serde(rename = "media.name")] + MediaName, +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +enum VolumeMode { + Absolute, + Relative, +} + +/// A validated non-nesting application group. +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Group { + id: String, + label: String, + members: Vec, + volume_mode: VolumeMode, +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +enum IdentityPolicy { + RequireUnique, + Manual, +} + +/// A configured physical control surface. +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Surface { + id: String, + label: String, + input_port: String, + #[serde(skip_serializing_if = "Option::is_none")] + output_port: Option, + identity_policy: IdentityPolicy, + motorized: bool, +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +enum TargetKind { + Application, + Group, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +struct Target { + kind: TargetKind, + id: String, +} + +/// A logical fader targeting one application or group. +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Fader { + id: String, + target: Target, + pickup: bool, + pickup_tolerance: f64, +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +enum Action { + Volume, + ToggleMute, +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "snake_case")] +enum MessageKind { + Cc, + Note, +} + +#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(deny_unknown_fields)] +struct Message { + kind: MessageKind, + channel: u16, + number: u16, +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +enum Edge { + Press, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +struct Feedback { + kind: MessageKind, + channel: u16, + number: u16, + on: u16, + off: u16, +} + +/// A validated physical-message-to-logical-fader binding. +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Binding { + surface: String, + fader: String, + action: Action, + #[serde(skip_serializing_if = "Option::is_none")] + edge: Option, + message: Message, + #[serde(skip_serializing_if = "Option::is_none")] + feedback: Option, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +struct RawProfile { + schema_version: u16, + id: String, + startup: StartupPolicy, + new_stream: NewStreamPolicy, + audio: Audio, + #[serde(default)] + applications: Vec, + #[serde(default)] + groups: Vec, + #[serde(default)] + surfaces: Vec, + #[serde(default)] + faders: Vec, + #[serde(default)] + bindings: Vec, +} + +/// A complete, semantically validated runtime profile document. +#[derive(Clone, Debug, PartialEq)] +pub struct Profile { + raw: RawProfile, + id: ProfileId, +} + +impl Profile { + /// Parses strict TOML and validates all cross-document invariants. + pub fn parse(input: &str) -> Result { + let raw: RawProfile = toml::from_str(input)?; + validate_version(raw.schema_version)?; + let id = parse_id::(&raw.id, "profile.id")?; + validate_audio(&raw.audio)?; + validate_profile_members(&raw)?; + Ok(Self { raw, id }) + } + + /// Serializes a canonical representation of this validated profile. + pub fn to_toml(&self) -> Result { + Ok(toml::to_string_pretty(&self.raw)?) + } + + /// Stable profile identifier. + pub fn id(&self) -> &ProfileId { + &self.id + } + + /// Startup state policy. + pub const fn startup(&self) -> StartupPolicy { + self.raw.startup + } + + /// Applications in declared order. + pub fn applications(&self) -> &[Application] { + &self.raw.applications + } + + /// Groups in declared restore-conflict order. + pub fn groups(&self) -> &[Group] { + &self.raw.groups + } + + /// Validated bindings. + pub fn bindings(&self) -> &[Binding] { + &self.raw.bindings + } +} + +fn validate_version(version: u16) -> Result<(), ConfigError> { + if version == SCHEMA_VERSION { + Ok(()) + } else { + Err(ConfigError::validation( + "schema_version", + format!("unsupported version {version}; expected {SCHEMA_VERSION}"), + )) + } +} + +fn validate_audio(audio: &Audio) -> Result<(), ConfigError> { + if !audio.max_gain.is_finite() || audio.max_gain < 0.0 { + return Err(ConfigError::validation( + "audio.max_gain", + "must be finite and non-negative", + )); + } + let mut seen = BTreeSet::new(); + for (index, adapter) in audio.preference.iter().enumerate() { + if *adapter == Adapter::Auto { + return Err(ConfigError::validation( + format!("audio.preference[{index}]"), + "auto is a selection policy, not a concrete adapter", + )); + } + if !seen.insert(adapter) { + return Err(ConfigError::validation( + format!("audio.preference[{index}]"), + "duplicate adapter", + )); + } + } + Ok(()) +} + +fn validate_profile_members(raw: &RawProfile) -> Result<(), ConfigError> { + let applications = unique_ids::( + raw.applications.iter().map(|item| item.id.as_str()), + "applications", + )?; + for (index, application) in raw.applications.iter().enumerate() { + if application.selectors.is_empty() { + return Err(ConfigError::validation( + format!("applications[{index}].selectors"), + "at least one selector is required", + )); + } + for (selector_index, selector) in application.selectors.iter().enumerate() { + validate_selector(selector, index, selector_index)?; + } + } + + let groups = + unique_ids::(raw.groups.iter().map(|item| item.id.as_str()), "groups")?; + for (index, group) in raw.groups.iter().enumerate() { + let mut members = BTreeSet::new(); + for (member_index, member) in group.members.iter().enumerate() { + let member_id = parse_id::( + member, + &format!("groups[{index}].members[{member_index}]"), + )?; + if !applications.contains_key(member_id.as_str()) { + return Err(ConfigError::validation( + format!("groups[{index}].members[{member_index}]"), + format!("unknown application {member:?}"), + )); + } + if !members.insert(member) { + return Err(ConfigError::validation( + format!("groups[{index}].members[{member_index}]"), + "duplicate member", + )); + } + } + } + + let surfaces = + unique_ids::(raw.surfaces.iter().map(|item| item.id.as_str()), "surfaces")?; + for (index, surface) in raw.surfaces.iter().enumerate() { + if surface.input_port.is_empty() { + return Err(ConfigError::validation( + format!("surfaces[{index}].input_port"), + "must not be empty", + )); + } + if surface.motorized && surface.output_port.is_none() { + return Err(ConfigError::validation( + format!("surfaces[{index}].output_port"), + "a motorized surface requires an output port", + )); + } + } + let faders = + unique_ids::(raw.faders.iter().map(|item| item.id.as_str()), "faders")?; + for (index, fader) in raw.faders.iter().enumerate() { + if !fader.pickup_tolerance.is_finite() || !(0.0..=1.0).contains(&fader.pickup_tolerance) { + return Err(ConfigError::validation( + format!("faders[{index}].pickup_tolerance"), + "must be finite and within 0..=1", + )); + } + let found = match fader.target.kind { + TargetKind::Application => applications.contains_key(&fader.target.id), + TargetKind::Group => groups.contains_key(&fader.target.id), + }; + if !found { + return Err(ConfigError::validation( + format!("faders[{index}].target.id"), + format!("unknown {:?} {:?}", fader.target.kind, fader.target.id), + )); + } + } + validate_bindings(raw, &surfaces, &faders) +} + +fn validate_selector( + selector: &Selector, + application: usize, + index: usize, +) -> Result<(), ConfigError> { + let path = format!("applications[{application}].selectors[{index}]"); + let field = match selector.field { + SelectorField::ApplicationName => MetadataField::ApplicationName, + SelectorField::ApplicationId => MetadataField::ApplicationId, + SelectorField::ProcessBinary => MetadataField::ProcessBinary, + SelectorField::MediaName => MetadataField::MediaName, + }; + match (&selector.exact, &selector.regex) { + (Some(pattern), None) => ApplicationSelector::exact(field, pattern) + .map(|_| ()) + .map_err(|error| ConfigError::validation(format!("{path}.exact"), error.to_string())), + (None, Some(pattern)) => ApplicationSelector::regex(field, pattern) + .map(|_| ()) + .map_err(|error| ConfigError::validation(format!("{path}.regex"), error.to_string())), + _ => Err(ConfigError::validation( + path, + "exactly one of exact or regex is required", + )), + } +} + +fn validate_bindings( + raw: &RawProfile, + surfaces: &BTreeMap, + faders: &BTreeMap, +) -> Result<(), ConfigError> { + let mut physical = BTreeSet::new(); + for (index, binding) in raw.bindings.iter().enumerate() { + if !surfaces.contains_key(&binding.surface) { + return Err(ConfigError::validation( + format!("bindings[{index}].surface"), + format!("unknown surface {:?}", binding.surface), + )); + } + if !faders.contains_key(&binding.fader) { + return Err(ConfigError::validation( + format!("bindings[{index}].fader"), + format!("unknown fader {:?}", binding.fader), + )); + } + validate_message(&binding.message, &format!("bindings[{index}].message"))?; + let key = (&binding.surface, binding.message.clone()); + if !physical.insert(key) { + return Err(ConfigError::validation( + format!("bindings[{index}].message"), + "duplicate physical binding for this surface", + )); + } + match (binding.action, binding.message.kind, binding.edge) { + (Action::Volume, MessageKind::Cc, None) => {} + (Action::Volume, _, _) => { + return Err(ConfigError::validation( + format!("bindings[{index}].action"), + "volume requires a cc message and no edge", + )); + } + (Action::ToggleMute, _, Some(Edge::Press)) => {} + (Action::ToggleMute, _, None) => { + return Err(ConfigError::validation( + format!("bindings[{index}].edge"), + "toggle_mute requires edge = press", + )); + } + } + if let Some(feedback) = &binding.feedback { + let surface = raw + .surfaces + .iter() + .find(|surface| surface.id == binding.surface) + .expect("validated surface lookup is consistent"); + if surface.output_port.is_none() { + return Err(ConfigError::validation( + format!("bindings[{index}].feedback"), + "surface output_port is required for feedback", + )); + } + validate_feedback(feedback, &format!("bindings[{index}].feedback"))?; + } + } + Ok(()) +} + +fn validate_message(message: &Message, path: &str) -> Result<(), ConfigError> { + MidiChannel::new(message.channel) + .map_err(|error| ConfigError::validation(format!("{path}.channel"), error.to_string()))?; + MidiData::new(message.number) + .map_err(|error| ConfigError::validation(format!("{path}.number"), error.to_string()))?; + Ok(()) +} + +fn validate_feedback(feedback: &Feedback, path: &str) -> Result<(), ConfigError> { + validate_message( + &Message { + kind: feedback.kind, + channel: feedback.channel, + number: feedback.number, + }, + path, + )?; + MidiData::new(feedback.on) + .map_err(|error| ConfigError::validation(format!("{path}.on"), error.to_string()))?; + MidiData::new(feedback.off) + .map_err(|error| ConfigError::validation(format!("{path}.off"), error.to_string()))?; + Ok(()) +} + +fn unique_ids(values: I, collection: &str) -> Result, ConfigError> +where + T: std::str::FromStr, + T::Err: std::fmt::Display, + I: IntoIterator, + I::Item: AsRef, +{ + let mut result = BTreeMap::new(); + for (index, value) in values.into_iter().enumerate() { + let value = value.as_ref(); + let id = parse_id::(value, &format!("{collection}[{index}].id"))?; + if result.insert(value.to_owned(), id).is_some() { + return Err(ConfigError::validation( + format!("{collection}[{index}].id"), + format!("duplicate ID {value:?}"), + )); + } + } + Ok(result) +} + +pub(crate) fn parse_id(value: &str, path: &str) -> Result +where + T: std::str::FromStr, + T::Err: std::fmt::Display, +{ + value + .parse() + .map_err(|error: T::Err| ConfigError::validation(path, error.to_string())) +} diff --git a/config/src/state.rs b/config/src/state.rs new file mode 100644 index 0000000..1b47dfb --- /dev/null +++ b/config/src/state.rs @@ -0,0 +1,186 @@ +use std::collections::BTreeSet; + +use fader_core::{ApplicationId, ChannelGains, Gain, ProfileId, SurfaceId}; +use serde::{Deserialize, Serialize}; + +use crate::{ConfigError, SCHEMA_VERSION, profile::parse_id}; + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +struct ObservedObject { + object: String, + gain: Vec, + muted: bool, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +struct DesiredObject { + object: String, + #[serde(skip_serializing_if = "Option::is_none")] + gain: Option, + #[serde(skip_serializing_if = "Option::is_none")] + muted: Option, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +struct Assignment { + surface: String, + input_port: String, + #[serde(skip_serializing_if = "Option::is_none")] + output_port: Option, +} + +/// Durable state for one stable profile; observed values are cache-only. +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ProfileState { + id: String, + last_view: String, + #[serde(default)] + observed: Vec, + #[serde(default)] + desired: Vec, + #[serde(default)] + assignments: Vec, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +struct RawState { + schema_version: u16, + #[serde(default)] + profiles: Vec, +} + +/// Strict durable state without runtime handles, generations, or operations. +#[derive(Clone, Debug, PartialEq)] +pub struct PersistedState { + raw: RawState, +} + +impl PersistedState { + /// Parses and validates cached observations, desired state, and assignments. + pub fn parse(input: &str) -> Result { + let raw: RawState = toml::from_str(input)?; + if raw.schema_version != SCHEMA_VERSION { + return Err(ConfigError::validation( + "schema_version", + format!( + "unsupported version {}; expected {SCHEMA_VERSION}", + raw.schema_version + ), + )); + } + validate_profiles(&raw.profiles)?; + Ok(Self { raw }) + } + + /// Serializes a canonical representation. + pub fn to_toml(&self) -> Result { + Ok(toml::to_string_pretty(&self.raw)?) + } + + /// Per-profile state in stable order. + pub fn profiles(&self) -> &[ProfileState] { + &self.raw.profiles + } +} + +fn validate_profiles(profiles: &[ProfileState]) -> Result<(), ConfigError> { + let mut profile_ids = BTreeSet::new(); + for (profile_index, profile) in profiles.iter().enumerate() { + parse_id::(&profile.id, &format!("profiles[{profile_index}].id"))?; + if !profile_ids.insert(&profile.id) { + return Err(ConfigError::validation( + format!("profiles[{profile_index}].id"), + "duplicate profile state", + )); + } + if !matches!( + profile.last_view.as_str(), + "mixer" | "devices" | "status" | "editor" + ) { + return Err(ConfigError::validation( + format!("profiles[{profile_index}].last_view"), + "must be mixer, devices, status, or editor", + )); + } + validate_observed(profile_index, &profile.observed)?; + validate_desired(profile_index, &profile.desired)?; + validate_assignments(profile_index, &profile.assignments)?; + } + Ok(()) +} + +fn validate_observed(profile: usize, objects: &[ObservedObject]) -> Result<(), ConfigError> { + let mut ids = BTreeSet::new(); + for (index, object) in objects.iter().enumerate() { + let base = format!("profiles[{profile}].observed[{index}]"); + parse_id::(&object.object, &format!("{base}.object"))?; + if !ids.insert(&object.object) { + return Err(ConfigError::validation( + format!("{base}.object"), + "duplicate observed object", + )); + } + let gains = object + .gain + .iter() + .copied() + .map(Gain::new) + .collect::, _>>() + .map_err(|error| ConfigError::validation(format!("{base}.gain"), error.to_string()))?; + ChannelGains::new(gains) + .map_err(|error| ConfigError::validation(format!("{base}.gain"), error.to_string()))?; + } + Ok(()) +} + +fn validate_desired(profile: usize, objects: &[DesiredObject]) -> Result<(), ConfigError> { + let mut ids = BTreeSet::new(); + for (index, object) in objects.iter().enumerate() { + let base = format!("profiles[{profile}].desired[{index}]"); + parse_id::(&object.object, &format!("{base}.object"))?; + if !ids.insert(&object.object) { + return Err(ConfigError::validation( + format!("{base}.object"), + "duplicate desired object", + )); + } + if object.gain.is_none() && object.muted.is_none() { + return Err(ConfigError::validation( + base, + "at least one desired gain or mute value is required", + )); + } + if let Some(gain) = object.gain { + Gain::new(gain).map_err(|error| { + ConfigError::validation(format!("{base}.gain"), error.to_string()) + })?; + } + } + Ok(()) +} + +fn validate_assignments(profile: usize, assignments: &[Assignment]) -> Result<(), ConfigError> { + let mut ids = BTreeSet::new(); + for (index, assignment) in assignments.iter().enumerate() { + let base = format!("profiles[{profile}].assignments[{index}]"); + parse_id::(&assignment.surface, &format!("{base}.surface"))?; + if !ids.insert(&assignment.surface) { + return Err(ConfigError::validation( + format!("{base}.surface"), + "duplicate surface assignment", + )); + } + if assignment.input_port.is_empty() { + return Err(ConfigError::validation( + format!("{base}.input_port"), + "must not be empty", + )); + } + } + Ok(()) +} diff --git a/config/tests/schema.rs b/config/tests/schema.rs new file mode 100644 index 0000000..012f8cd --- /dev/null +++ b/config/tests/schema.rs @@ -0,0 +1,173 @@ +use fader_config::{DeviceProfile, PersistedState, Profile, StartupPolicy}; + +const EXAMPLE: &str = include_str!("../../examples/profiles/desktop.toml"); +const ARCHITECTURE: &str = include_str!("../../architecture.md"); + +#[test] +fn architecture_profile_parses_and_round_trips_semantically() { + let marker = "The following profile"; + let documented = ARCHITECTURE + .split_once(marker) + .and_then(|(_, remainder)| remainder.split_once("```toml")) + .and_then(|(_, remainder)| remainder.split_once("```")) + .map(|(toml, _)| toml.trim()) + .expect("architecture must contain its profile example"); + assert_eq!(documented, EXAMPLE.trim(), "checked-in example drifted"); + + let profile = Profile::parse(documented).expect("architecture profile must validate"); + assert_eq!(profile.id().as_str(), "desktop"); + assert_eq!(profile.startup(), StartupPolicy::Adopt); + assert_eq!(profile.applications().len(), 2); + assert_eq!(profile.groups().len(), 1); + assert_eq!(profile.bindings().len(), 2); + + let encoded = profile.to_toml().expect("validated profile must serialize"); + let reparsed = Profile::parse(&encoded).expect("serialized profile must validate"); + assert_eq!(profile, reparsed); +} + +#[test] +fn rejects_unknown_fields_versions_and_bad_ids_with_context() { + let unknown = EXAMPLE.replace("schema_version = 1", "schema_version = 1\nsurprise = true"); + assert_error_contains(Profile::parse(&unknown), "surprise"); + + let version = EXAMPLE.replace("schema_version = 1", "schema_version = 7"); + assert_error_contains(Profile::parse(&version), "schema_version"); + + let bad_id = EXAMPLE.replace("id = \"desktop\"", "id = \"bad/profile\""); + assert_error_contains(Profile::parse(&bad_id), "profile.id"); +} + +#[test] +fn rejects_dangling_references_and_duplicate_physical_bindings() { + let missing_member = EXAMPLE.replace( + "members = [\"music\", \"browser\"]", + "members = [\"music\", \"missing\"]", + ); + assert_error_contains(Profile::parse(&missing_member), "groups[0].members[1]"); + + let missing_target = EXAMPLE.replace("id = \"media\" }", "id = \"missing\" }"); + assert_error_contains(Profile::parse(&missing_target), "faders[0].target.id"); + + let duplicate = EXAMPLE.replace( + "kind = \"note\", channel = 1, number = 32", + "kind = \"cc\", channel = 1, number = 0", + ); + assert_error_contains(Profile::parse(&duplicate), "bindings[1].message"); +} + +#[test] +fn validates_all_midi_data_ranges_and_action_capabilities() { + for (needle, replacement, path) in [ + ( + "channel = 1, number = 0", + "channel = 0, number = 0", + "channel", + ), + ( + "channel = 1, number = 0", + "channel = 17, number = 0", + "channel", + ), + ( + "channel = 1, number = 32", + "channel = 1, number = 128", + "number", + ), + ("on = 127, off = 0", "on = 128, off = 0", "feedback.on"), + ("on = 127, off = 0", "on = 127, off = 128", "feedback.off"), + ] { + assert_error_contains( + Profile::parse(&EXAMPLE.replacen(needle, replacement, 1)), + path, + ); + } + + let volume_on_note = EXAMPLE.replace( + "action = \"volume\"\nmessage = { kind = \"cc\"", + "action = \"volume\"\nmessage = { kind = \"note\"", + ); + assert_error_contains(Profile::parse(&volume_on_note), "requires a cc message"); + + let feedback_on_input_only = + EXAMPLE.replace("output_port = \"Example Controller MIDI 1\"\n", ""); + assert_error_contains(Profile::parse(&feedback_on_input_only), "output_port"); +} + +#[test] +fn device_and_state_documents_are_strict_and_validated() { + let device = DeviceProfile::parse( + r#" +schema_version = 1 +id = "nano" +label = "Nano controller" +[capabilities] +mute_led = true +value_display = false +motorized_fader = false +"#, + ) + .expect("device profile must validate"); + assert_eq!(device.id().as_str(), "nano"); + assert_eq!( + device + .to_toml() + .and_then(|text| DeviceProfile::parse(&text)) + .unwrap(), + device + ); + + let state = PersistedState::parse( + r#" +schema_version = 1 + +[[profiles]] +id = "desktop" +last_view = "mixer" + +[[profiles.observed]] +object = "music" +gain = [0.5, 0.25] +muted = false + +[[profiles.desired]] +object = "music" +gain = 0.7 +muted = true + +[[profiles.assignments]] +surface = "desk-left" +input_port = "hw:1" +output_port = "hw:1" +"#, + ) + .expect("state must validate"); + assert_eq!(state.profiles().len(), 1); + assert_eq!( + state + .to_toml() + .and_then(|text| PersistedState::parse(&text)) + .unwrap(), + state + ); + + assert_error_contains( + PersistedState::parse("schema_version = 1\npending_operation = 4"), + "pending_operation", + ); + assert_error_contains( + PersistedState::parse("schema_version = 2\nprofiles = []"), + "schema_version", + ); +} + +fn assert_error_contains(result: Result, needle: &str) { + let error = result + .err() + .expect("document should be rejected") + .to_string(); + assert!( + error.contains(needle), + "expected {error:?} to contain {needle:?}" + ); +} diff --git a/examples/profiles/desktop.toml b/examples/profiles/desktop.toml new file mode 100644 index 0000000..2dee55f --- /dev/null +++ b/examples/profiles/desktop.toml @@ -0,0 +1,53 @@ +schema_version = 1 +id = "desktop" +startup = "adopt" +new_stream = "adopt" + +[audio] +adapter = "auto" +preference = ["pulse", "pipewire"] +max_gain = 1.0 + +[[applications]] +id = "music" +label = "Music" +selectors = [{ field = "application.name", exact = "Music Player" }] + +[[applications]] +id = "browser" +label = "Browser" +selectors = [{ field = "application.process.binary", regex = '^(firefox|chromium)$' }] + +[[groups]] +id = "media" +label = "Media" +members = ["music", "browser"] +volume_mode = "absolute" + +[[surfaces]] +id = "desk-left" +label = "Left controller" +input_port = "Example Controller MIDI 1" +output_port = "Example Controller MIDI 1" +identity_policy = "require_unique" +motorized = false + +[[faders]] +id = "media-fader" +target = { kind = "group", id = "media" } +pickup = true +pickup_tolerance = 0.02 + +[[bindings]] +surface = "desk-left" +fader = "media-fader" +action = "volume" +message = { kind = "cc", channel = 1, number = 0 } + +[[bindings]] +surface = "desk-left" +fader = "media-fader" +action = "toggle_mute" +edge = "press" +message = { kind = "note", channel = 1, number = 32 } +feedback = { kind = "note", channel = 1, number = 32, on = 127, off = 0 } diff --git a/task.md b/task.md index d3efc41..ad0379c 100644 --- a/task.md +++ b/task.md @@ -46,7 +46,12 @@ requires a real Jenkins run. Per user direction, stop here before starting M2. Dependencies: M1 types; runtime activation follows in M10. -- [ ] **M2.1 Schema and validation:** profile, application/group/fader/binding/device, and state schemas; check all references and capabilities. Tests: architecture example parses semantically, round trip preserves meaning, invalid IDs/duplicate bindings/unknown fields/schema versions fail with useful paths, all supported MIDI ranges are checked. +- [x] **M2.1 Schema and validation:** profile, application/group/fader/binding/device, and state schemas; check all references and capabilities. Tests: architecture example parses semantically, round trip preserves meaning, invalid IDs/duplicate bindings/unknown fields/schema versions fail with useful paths, all supported MIDI ranges are checked. + The strict version-1 profile, reusable device-capability, and persisted-state + documents now validate before construction. The architecture TOML block and + checked-in example are test-locked to one another; five integration tests + cover semantic round trips, reference/capability failures, unknown fields, + versions, duplicates, and MIDI channel/data endpoints. - [ ] **M2.2 Atomic files:** XDG paths, same-directory temp/rename/fsync, restrictive ownership, comment-preserving edits and migration backups. Tests: disk/permission/write failures keep the old document readable; malformed/missing state is recoverable; unsafe profile paths and incompatible migrations are rejected. - [ ] **M2.3 Checkpoints:** per-profile observed state and separate validated desired object volume/mute, surface assignments, UI preferences, debounce and shutdown flush. Tests with a fake clock: sustained movement causes bounded writes and final state persists; crash/restart treats cached observations as stale, never restores runtime IDs or pending requests; an offline command survives restart as saved intent but only explicit restore applies it when the application launches (adopt emits no write).