From 1eaeaf81e26f902b1e0126bad9a97399af35407c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 5 Oct 2026 08:04:32 +0200 Subject: [PATCH] feat(M1.2): match applications to live streams Add explicit normalized metadata selectors with case-sensitive exact and bounded Rust regex modes, OR application matching, raw metadata preservation, and epoch/incarnation-safe live membership. Tests: cargo test -p fader-core --all-targets --locked (17 passed) Tests: cargo clippy -p fader-core --all-targets --locked -- -D warnings; cargo test -p fader-core --doc --locked; cargo fmt --all -- --check; git diff --check (passed) --- Cargo.lock | 45 +++- Cargo.toml | 1 + core/Cargo.toml | 1 + core/src/lib.rs | 5 + core/src/matching.rs | 473 +++++++++++++++++++++++++++++++++++++++++++ task.md | 2 +- 6 files changed, 523 insertions(+), 4 deletions(-) create mode 100644 core/src/matching.rs diff --git a/Cargo.lock b/Cargo.lock index b706a24..711e0d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -173,6 +182,7 @@ name = "fader-core" version = "0.1.0" dependencies = [ "proptest", + "regex", "thiserror", ] @@ -330,6 +340,12 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + [[package]] name = "midi" version = "0.1.0" @@ -548,6 +564,29 @@ dependencies = [ "bitflags", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + [[package]] name = "regex-syntax" version = "0.8.11" @@ -564,7 +603,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -897,9 +936,9 @@ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-sys" -version = "0.59.0" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] diff --git a/Cargo.toml b/Cargo.toml index e08901e..b75d21a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ fader-config = { path = "config" } fader-core = { path = "core" } midi = { path = "midi" } ratatui = { version = "0.29.0", features = ["all-widgets", "serde"] } +regex = "1.13.1" thiserror = "2.0.21" tui = { path = "tui" } volume_lib = { path = "sound" } diff --git a/core/Cargo.toml b/core/Cargo.toml index 1de71d2..47f9894 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -8,6 +8,7 @@ repository.workspace = true publish.workspace = true [dependencies] +regex.workspace = true thiserror.workspace = true [dev-dependencies] diff --git a/core/src/lib.rs b/core/src/lib.rs index 493c3b2..422dfd2 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -6,11 +6,16 @@ #![forbid(unsafe_code)] mod id; +mod matching; mod revision; mod state; mod volume; pub use id::{ApplicationId, FaderId, GroupId, IdError, ProfileId, SurfaceId}; +pub use matching::{ + ApplicationMatcher, ApplicationRuntime, ApplicationSelector, MetadataField, SelectorError, + SelectorKind, StreamHandle, StreamMetadata, +}; pub use revision::{BackendEpoch, Revision}; pub use state::{Availability, Mute, ValueState}; pub use volume::{ChannelGainError, ChannelGains, Gain, GainError}; diff --git a/core/src/matching.rs b/core/src/matching.rs new file mode 100644 index 0000000..fe3be62 --- /dev/null +++ b/core/src/matching.rs @@ -0,0 +1,473 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use regex::{Regex, RegexBuilder}; +use thiserror::Error; + +use crate::{ApplicationId, BackendEpoch}; + +const MAX_PATTERN_LENGTH: usize = 256; +const REGEX_SIZE_LIMIT: usize = 1 << 20; + +/// Explicit normalized stream metadata fields supported by application selectors. +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub enum MetadataField { + /// Backend `application.name`. + ApplicationName, + /// Backend `application.id`. + ApplicationId, + /// Backend `application.process.binary`. + ProcessBinary, + /// Backend `media.name`. + MediaName, +} + +/// Normalized fields plus untouched backend metadata for diagnostics. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct StreamMetadata { + application_name: Option, + application_id: Option, + process_binary: Option, + media_name: Option, + raw: BTreeMap, +} + +impl StreamMetadata { + /// Creates an empty metadata snapshot. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Sets normalized `application.name`. + #[must_use] + pub fn with_application_name(mut self, value: impl Into) -> Self { + self.application_name = Some(value.into()); + self + } + + /// Sets normalized `application.id`. + #[must_use] + pub fn with_application_id(mut self, value: impl Into) -> Self { + self.application_id = Some(value.into()); + self + } + + /// Sets normalized `application.process.binary`. + #[must_use] + pub fn with_process_binary(mut self, value: impl Into) -> Self { + self.process_binary = Some(value.into()); + self + } + + /// Sets normalized `media.name`. + #[must_use] + pub fn with_media_name(mut self, value: impl Into) -> Self { + self.media_name = Some(value.into()); + self + } + + /// Adds an untouched backend property for inspection. + #[must_use] + pub fn with_raw_property(mut self, key: impl Into, value: impl Into) -> Self { + self.raw.insert(key.into(), value.into()); + self + } + + /// Returns a normalized field, preserving absence rather than substituting another field. + #[must_use] + pub fn value(&self, field: MetadataField) -> Option<&str> { + match field { + MetadataField::ApplicationName => self.application_name.as_deref(), + MetadataField::ApplicationId => self.application_id.as_deref(), + MetadataField::ProcessBinary => self.process_binary.as_deref(), + MetadataField::MediaName => self.media_name.as_deref(), + } + } + + /// Returns untouched backend metadata. + #[must_use] + pub fn raw(&self) -> &BTreeMap { + &self.raw + } +} + +/// Selector comparison mode. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum SelectorKind { + /// Case-sensitive whole-string equality. + Exact, + /// Rust regex substring search unless the pattern is anchored. + Regex, +} + +#[derive(Clone, Debug)] +enum Expression { + Exact(String), + Regex { pattern: String, compiled: Regex }, +} + +/// Why an application selector was rejected. +#[derive(Debug, Error)] +pub enum SelectorError { + /// Applications must declare at least one selector. + #[error("application {application} must have at least one selector")] + NoSelectors { + /// Application missing selectors. + application: ApplicationId, + }, + /// Empty patterns are too easy to match accidentally. + #[error("selector pattern must not be empty")] + EmptyPattern, + /// Patterns are bounded before regex compilation. + #[error("selector pattern length {actual} exceeds maximum {maximum}")] + PatternTooLong { + /// Actual byte length. + actual: usize, + /// Maximum allowed byte length. + maximum: usize, + }, + /// Rust regex compilation failed. + #[error("invalid selector regex {pattern:?}: {source}")] + InvalidRegex { + /// Rejected source pattern. + pattern: String, + /// Regex parser/compiler error. + #[source] + source: regex::Error, + }, +} + +/// One explicit field matcher for a virtual application. +#[derive(Clone, Debug)] +pub struct ApplicationSelector { + field: MetadataField, + expression: Expression, +} + +impl ApplicationSelector { + /// Creates a case-sensitive exact selector. + /// + /// # Errors + /// + /// Returns [`SelectorError`] when the pattern is empty or too long. + pub fn exact(field: MetadataField, pattern: impl Into) -> Result { + let pattern = pattern.into(); + validate_pattern(&pattern)?; + Ok(Self { + field, + expression: Expression::Exact(pattern), + }) + } + + /// Creates a bounded Rust regex selector. + /// + /// # Errors + /// + /// Returns [`SelectorError`] when the pattern is empty, too long, or not a + /// valid Rust regular expression. + pub fn regex(field: MetadataField, pattern: impl Into) -> Result { + let pattern = pattern.into(); + validate_pattern(&pattern)?; + let compiled = RegexBuilder::new(&pattern) + .size_limit(REGEX_SIZE_LIMIT) + .build() + .map_err(|source| SelectorError::InvalidRegex { + pattern: pattern.clone(), + source, + })?; + Ok(Self { + field, + expression: Expression::Regex { pattern, compiled }, + }) + } + + /// Returns the selected normalized field. + #[must_use] + pub const fn field(&self) -> MetadataField { + self.field + } + + /// Returns the selector mode. + #[must_use] + pub const fn kind(&self) -> SelectorKind { + match self.expression { + Expression::Exact(_) => SelectorKind::Exact, + Expression::Regex { .. } => SelectorKind::Regex, + } + } + + /// Returns the configured source pattern. + #[must_use] + pub fn pattern(&self) -> &str { + match &self.expression { + Expression::Exact(pattern) | Expression::Regex { pattern, .. } => pattern, + } + } + + /// Tests only the configured normalized field. + #[must_use] + pub fn matches(&self, metadata: &StreamMetadata) -> bool { + let Some(candidate) = metadata.value(self.field) else { + return false; + }; + match &self.expression { + Expression::Exact(pattern) => candidate == pattern, + Expression::Regex { compiled, .. } => compiled.is_match(candidate), + } + } +} + +fn validate_pattern(pattern: &str) -> Result<(), SelectorError> { + if pattern.is_empty() { + return Err(SelectorError::EmptyPattern); + } + if pattern.len() > MAX_PATTERN_LENGTH { + return Err(SelectorError::PatternTooLong { + actual: pattern.len(), + maximum: MAX_PATTERN_LENGTH, + }); + } + Ok(()) +} + +/// Immutable OR-combination of selectors for one virtual application. +#[derive(Clone, Debug)] +pub struct ApplicationMatcher { + id: ApplicationId, + selectors: Vec, +} + +impl ApplicationMatcher { + /// Constructs a matcher with at least one selector. + /// + /// # Errors + /// + /// Returns [`SelectorError::NoSelectors`] for an empty selector list. + pub fn new( + id: ApplicationId, + selectors: Vec, + ) -> Result { + if selectors.is_empty() { + return Err(SelectorError::NoSelectors { application: id }); + } + Ok(Self { id, selectors }) + } + + /// Returns the stable application identifier. + #[must_use] + pub fn id(&self) -> &ApplicationId { + &self.id + } + + /// Returns whether any configured selector matches. + #[must_use] + pub fn matches(&self, metadata: &StreamMetadata) -> bool { + self.selectors + .iter() + .any(|selector| selector.matches(metadata)) + } +} + +/// Ephemeral stream identity protected against backend ID reuse. +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct StreamHandle { + epoch: BackendEpoch, + backend_id: u64, + incarnation: u64, +} + +impl StreamHandle { + /// Creates a handle scoped to a connection epoch and incarnation. + #[must_use] + pub const fn new(epoch: BackendEpoch, backend_id: u64, incarnation: u64) -> Self { + Self { + epoch, + backend_id, + incarnation, + } + } + + /// Returns the owning backend epoch. + #[must_use] + pub const fn epoch(self) -> BackendEpoch { + self.epoch + } + + /// Returns the adapter-local object ID. + #[must_use] + pub const fn backend_id(self) -> u64 { + self.backend_id + } + + /// Returns the object incarnation within the epoch. + #[must_use] + pub const fn incarnation(self) -> u64 { + self.incarnation + } +} + +/// Live matching membership for one virtual application. +#[derive(Clone, Debug)] +pub struct ApplicationRuntime { + matcher: ApplicationMatcher, + matching_streams: BTreeSet, +} + +impl ApplicationRuntime { + /// Starts an application offline with no stream membership. + #[must_use] + pub fn new(matcher: ApplicationMatcher) -> Self { + Self { + matcher, + matching_streams: BTreeSet::new(), + } + } + + /// Re-evaluates one stream and returns its current membership. + pub fn upsert(&mut self, handle: StreamHandle, metadata: &StreamMetadata) -> bool { + if self.matcher.matches(metadata) { + self.matching_streams.insert(handle); + true + } else { + self.matching_streams.remove(&handle); + false + } + } + + /// Removes exactly one stream incarnation. + pub fn remove(&mut self, handle: StreamHandle) -> bool { + self.matching_streams.remove(&handle) + } + + /// Returns matching live stream identities in deterministic order. + #[must_use] + pub fn matching_streams(&self) -> &BTreeSet { + &self.matching_streams + } + + /// Returns whether the configured application currently has no stream. + #[must_use] + pub fn is_offline(&self) -> bool { + self.matching_streams.is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn application_id() -> ApplicationId { + ApplicationId::new("browser").expect("valid application ID") + } + + #[test] + fn exact_matching_is_whole_string_and_case_sensitive() { + let selector = ApplicationSelector::exact(MetadataField::ApplicationName, "Firefox") + .expect("valid selector"); + + assert!(selector.matches(&StreamMetadata::new().with_application_name("Firefox"))); + assert!(!selector.matches(&StreamMetadata::new().with_application_name("firefox"))); + assert!(!selector.matches(&StreamMetadata::new().with_application_name("Firefox Beta"))); + } + + #[test] + fn regex_searches_substrings_unless_anchored() { + let substring = ApplicationSelector::regex(MetadataField::ProcessBinary, "firefox") + .expect("valid regex"); + let anchored = ApplicationSelector::regex(MetadataField::ProcessBinary, "^firefox$") + .expect("valid regex"); + let metadata = StreamMetadata::new().with_process_binary("firefox-beta"); + + assert!(substring.matches(&metadata)); + assert!(!anchored.matches(&metadata)); + } + + #[test] + fn missing_field_does_not_fall_back_to_raw_or_another_field() { + let selector = ApplicationSelector::exact(MetadataField::ApplicationName, "Player") + .expect("valid selector"); + let metadata = StreamMetadata::new() + .with_media_name("Player") + .with_raw_property("application.name", "Player"); + + assert!(!selector.matches(&metadata)); + assert_eq!( + metadata.raw().get("application.name").map(String::as_str), + Some("Player") + ); + } + + #[test] + fn application_selectors_are_ored() { + let matcher = ApplicationMatcher::new( + application_id(), + vec![ + ApplicationSelector::exact(MetadataField::ApplicationName, "Firefox") + .expect("valid selector"), + ApplicationSelector::regex(MetadataField::ProcessBinary, "^(firefox|librewolf)$") + .expect("valid selector"), + ], + ) + .expect("application has selectors"); + + assert!(matcher.matches(&StreamMetadata::new().with_process_binary("librewolf"))); + } + + #[test] + fn malformed_and_unbounded_patterns_are_rejected() { + assert!(matches!( + ApplicationSelector::regex(MetadataField::ApplicationName, "("), + Err(SelectorError::InvalidRegex { .. }) + )); + assert!(matches!( + ApplicationSelector::exact(MetadataField::ApplicationName, "x".repeat(257)), + Err(SelectorError::PatternTooLong { .. }) + )); + } + + #[test] + fn runtime_tracks_multiple_streams_and_remains_configured_offline() { + let matcher = ApplicationMatcher::new( + application_id(), + vec![ + ApplicationSelector::exact(MetadataField::ApplicationId, "org.mozilla.firefox") + .expect("valid selector"), + ], + ) + .expect("application has selectors"); + let mut runtime = ApplicationRuntime::new(matcher); + let metadata = StreamMetadata::new().with_application_id("org.mozilla.firefox"); + let first = StreamHandle::new(BackendEpoch::new(1), 7, 1); + let second = StreamHandle::new(BackendEpoch::new(1), 8, 1); + + assert!(runtime.is_offline()); + assert!(runtime.upsert(first, &metadata)); + assert!(runtime.upsert(second, &metadata)); + assert_eq!(runtime.matching_streams().len(), 2); + assert!(runtime.remove(first)); + assert!(runtime.remove(second)); + assert!(runtime.is_offline()); + } + + #[test] + fn backend_id_reuse_cannot_remove_a_new_incarnation() { + let matcher = ApplicationMatcher::new( + application_id(), + vec![ + ApplicationSelector::exact(MetadataField::ApplicationName, "Browser") + .expect("valid selector"), + ], + ) + .expect("application has selectors"); + let mut runtime = ApplicationRuntime::new(matcher); + let metadata = StreamMetadata::new().with_application_name("Browser"); + let old = StreamHandle::new(BackendEpoch::new(3), 42, 1); + let replacement = StreamHandle::new(BackendEpoch::new(3), 42, 2); + + assert!(runtime.upsert(old, &metadata)); + assert!(runtime.remove(old)); + assert!(runtime.upsert(replacement, &metadata)); + assert!(!runtime.remove(old)); + assert_eq!(runtime.matching_streams(), &BTreeSet::from([replacement])); + } +} diff --git a/task.md b/task.md index 3d9dcfd..7da00c2 100644 --- a/task.md +++ b/task.md @@ -28,7 +28,7 @@ Dependencies: planning. Dependencies: M0. - [x] **M1.1 Typed values:** stable IDs, finite gain, channel vectors, mute/availability/mixed states, revisions and backend epochs. Tests: invalid ranges/NaN/infinity rejected; gain/silence/channel-balance properties hold; IDs cannot be interchanged accidentally. -- [ ] **M1.2 Application selectors:** normalized metadata, exact/regex matching, OR selectors, multiple live streams and offline objects. Tests: anchored/unanchored/case-sensitive cases, missing fields, malformed regex, stream creation/removal and backend ID reuse. +- [x] **M1.2 Application selectors:** normalized metadata, exact/regex matching, OR selectors, multiple live streams and offline objects. Tests: anchored/unanchored/case-sensitive cases, missing fields, malformed regex, stream creation/removal and backend ID reuse. - [ ] **M1.3 Fader resolution:** surface binding -> fader -> application/group -> deduplicated live streams. Tests: identical CCs on different surfaces stay separate, multiple faders can share an object, and overlap never writes the same stream twice per operation. - [ ] **M1.4 Group gain:** absolute and relative modes with channel balance, aggregate max/mixed state, zero fallback and clipping. Tests: heterogeneous members, externally changed members, all-zero recovery, empty group, late joiner adopting live state, and partial failure. - [ ] **M1.5 Mute:** explicit set/toggle independent of volume. Tests: mixed-group toggle mutes all, fully muted toggle unmutes all, two rapid toggles cancel logically, zero gain does not imply mute, and unmute does not alter gain.