fader_master/core/src/routing.rs

91 lines
3.1 KiB
Rust

//! Validated logical targets and deterministic stream resolution.
use crate::{ApplicationId, FaderId, GroupId, StreamHandle};
use std::collections::{BTreeMap, BTreeSet};
use thiserror::Error;
/// A logical target; group nesting is deliberately not representable.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Target {
/// Every stream belonging to one configured application.
Application(ApplicationId),
/// The union of the streams belonging to member applications.
Group(GroupId),
}
/// A dangling configuration reference or unknown command target.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum RoutingError {
/// Application is absent from the configured application set.
#[error("unknown application {0}")]
Application(ApplicationId),
/// Group is absent from the configured group map.
#[error("unknown group {0}")]
Group(GroupId),
/// Fader is absent from the configured fader map.
#[error("unknown fader {0}")]
Fader(FaderId),
}
/// Immutable, validated configuration graph. Live membership is supplied separately.
#[derive(Clone, Debug)]
pub struct Routing {
groups: BTreeMap<GroupId, Vec<ApplicationId>>,
faders: BTreeMap<FaderId, Target>,
}
impl Routing {
/// Validates all references before accepting the configuration graph.
pub fn new(
applications: BTreeSet<ApplicationId>,
groups: BTreeMap<GroupId, Vec<ApplicationId>>,
faders: BTreeMap<FaderId, Target>,
) -> Result<Self, RoutingError> {
for member in groups.values().flatten() {
if !applications.contains(member) {
return Err(RoutingError::Application(member.clone()));
}
}
for target in faders.values() {
match target {
Target::Application(id) if !applications.contains(id) => {
return Err(RoutingError::Application(id.clone()));
}
Target::Group(id) if !groups.contains_key(id) => {
return Err(RoutingError::Group(id.clone()));
}
_ => {}
}
}
Ok(Self { groups, faders })
}
/// Resolves one command to a deduplicated, deterministic stream set.
/// Missing live membership means offline, while unknown faders are errors.
pub fn resolve(
&self,
fader: &FaderId,
live: &BTreeMap<ApplicationId, BTreeSet<StreamHandle>>,
) -> Result<BTreeSet<StreamHandle>, RoutingError> {
let target = self
.faders
.get(fader)
.ok_or_else(|| RoutingError::Fader(fader.clone()))?;
match target {
Target::Application(id) => Ok(live.get(id).cloned().unwrap_or_default()),
Target::Group(id) => {
let members = self
.groups
.get(id)
.ok_or_else(|| RoutingError::Group(id.clone()))?;
Ok(members
.iter()
.filter_map(|member| live.get(member))
.flatten()
.copied()
.collect())
}
}
}
}