fader_master/core/src/matching.rs

474 lines
15 KiB
Rust

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<String>,
application_id: Option<String>,
process_binary: Option<String>,
media_name: Option<String>,
raw: BTreeMap<String, String>,
}
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<String>) -> Self {
self.application_name = Some(value.into());
self
}
/// Sets normalized `application.id`.
#[must_use]
pub fn with_application_id(mut self, value: impl Into<String>) -> 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<String>) -> Self {
self.process_binary = Some(value.into());
self
}
/// Sets normalized `media.name`.
#[must_use]
pub fn with_media_name(mut self, value: impl Into<String>) -> 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<String>, value: impl Into<String>) -> 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<String, String> {
&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<String>) -> Result<Self, SelectorError> {
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<String>) -> Result<Self, SelectorError> {
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<ApplicationSelector>,
}
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<ApplicationSelector>,
) -> Result<Self, SelectorError> {
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<StreamHandle>,
}
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<StreamHandle> {
&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]));
}
}