fader_master/midi/src/lifecycle.rs

264 lines
8.5 KiB
Rust

use std::collections::BTreeMap;
use fader_core::SurfaceId;
use thiserror::Error;
use crate::{DeviceMatch, MatchBasis, PortIdentity, PortResolution, resolve_port};
/// Durable matching policy for one configured surface.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SurfaceAssignment {
pub surface: SurfaceId,
pub expected: DeviceMatch,
pub manual_backend_id: Option<String>,
}
/// User-visible connection state retained even while a surface is absent.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SurfaceStatus {
Missing,
Ambiguous {
backend_ids: Vec<String>,
},
Connecting {
backend_id: String,
basis: MatchBasis,
},
Connected {
backend_id: String,
basis: MatchBasis,
},
Error {
backend_id: String,
message: String,
},
}
/// Native connection work requested by one reconciliation pass.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SurfaceAction {
Connect {
surface: SurfaceId,
port_index: usize,
backend_id: String,
},
Disconnect {
surface: SurfaceId,
backend_id: String,
},
}
#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum SurfaceLifecycleError {
#[error("duplicate configured surface {0}")]
Duplicate(SurfaceId),
#[error("surface {0} is not configured")]
Unknown(SurfaceId),
#[error("surface {surface} is not connecting to backend {backend_id:?}")]
UnexpectedConnection {
surface: SurfaceId,
backend_id: String,
},
}
#[derive(Clone, Debug)]
struct Entry {
assignment: SurfaceAssignment,
status: SurfaceStatus,
current_backend: Option<String>,
}
/// Deterministic hotplug reconciliation independent of native MIDI handles.
#[derive(Clone, Debug)]
pub struct SurfaceLifecycle {
entries: BTreeMap<SurfaceId, Entry>,
}
impl SurfaceLifecycle {
pub fn new(
assignments: impl IntoIterator<Item = SurfaceAssignment>,
) -> Result<Self, SurfaceLifecycleError> {
let mut entries = BTreeMap::new();
for assignment in assignments {
let id = assignment.surface.clone();
if entries
.insert(
id.clone(),
Entry {
assignment,
status: SurfaceStatus::Missing,
current_backend: None,
},
)
.is_some()
{
return Err(SurfaceLifecycleError::Duplicate(id));
}
}
Ok(Self { entries })
}
/// Reconciles all surfaces independently and returns native work in stable
/// surface-ID order. A port claimed by multiple surfaces is left ambiguous.
pub fn reconcile(&mut self, ports: &[PortIdentity]) -> Vec<SurfaceAction> {
let mut resolutions: BTreeMap<SurfaceId, PortResolution> = self
.entries
.iter()
.map(|(id, entry)| {
(
id.clone(),
resolve_port(
&entry.assignment.expected,
ports,
entry.assignment.manual_backend_id.as_deref(),
),
)
})
.collect();
let mut claims = BTreeMap::<usize, usize>::new();
for resolution in resolutions.values() {
if let PortResolution::Matched { index, .. } = resolution {
*claims.entry(*index).or_default() += 1;
}
}
for resolution in resolutions.values_mut() {
if let PortResolution::Matched { index, .. } = resolution
&& claims.get(index).copied().unwrap_or_default() > 1
{
*resolution = PortResolution::Ambiguous {
candidate_indices: vec![*index],
};
}
}
let mut actions = Vec::new();
for (id, entry) in &mut self.entries {
let resolution = resolutions.remove(id).unwrap_or(PortResolution::Missing);
match resolution {
PortResolution::Missing => {
disconnect_current(id, entry, &mut actions);
entry.status = SurfaceStatus::Missing;
}
PortResolution::Ambiguous { candidate_indices } => {
disconnect_current(id, entry, &mut actions);
entry.status = SurfaceStatus::Ambiguous {
backend_ids: candidate_indices
.into_iter()
.filter_map(|index| ports.get(index))
.map(|port| port.backend_id.clone())
.collect(),
};
}
PortResolution::Matched { index, basis } => {
let Some(port) = ports.get(index) else {
disconnect_current(id, entry, &mut actions);
entry.status = SurfaceStatus::Missing;
continue;
};
if entry.current_backend.as_deref() == Some(&port.backend_id) {
continue;
}
if matches!(
&entry.status,
SurfaceStatus::Connecting { backend_id, .. }
if backend_id == &port.backend_id
) {
continue;
}
disconnect_current(id, entry, &mut actions);
entry.status = SurfaceStatus::Connecting {
backend_id: port.backend_id.clone(),
basis,
};
actions.push(SurfaceAction::Connect {
surface: id.clone(),
port_index: index,
backend_id: port.backend_id.clone(),
});
}
}
}
actions
}
pub fn connection_succeeded(
&mut self,
surface: &SurfaceId,
backend_id: &str,
) -> Result<(), SurfaceLifecycleError> {
let entry = self
.entries
.get_mut(surface)
.ok_or_else(|| SurfaceLifecycleError::Unknown(surface.clone()))?;
let SurfaceStatus::Connecting {
backend_id: expected,
basis,
} = &entry.status
else {
return Err(SurfaceLifecycleError::UnexpectedConnection {
surface: surface.clone(),
backend_id: backend_id.to_owned(),
});
};
if expected != backend_id {
return Err(SurfaceLifecycleError::UnexpectedConnection {
surface: surface.clone(),
backend_id: backend_id.to_owned(),
});
}
let basis = *basis;
entry.current_backend = Some(backend_id.to_owned());
entry.status = SurfaceStatus::Connected {
backend_id: backend_id.to_owned(),
basis,
};
Ok(())
}
pub fn connection_failed(
&mut self,
surface: &SurfaceId,
backend_id: &str,
message: impl Into<String>,
) -> Result<(), SurfaceLifecycleError> {
let entry = self
.entries
.get_mut(surface)
.ok_or_else(|| SurfaceLifecycleError::Unknown(surface.clone()))?;
if !matches!(
&entry.status,
SurfaceStatus::Connecting { backend_id: expected, .. } if expected == backend_id
) {
return Err(SurfaceLifecycleError::UnexpectedConnection {
surface: surface.clone(),
backend_id: backend_id.to_owned(),
});
}
entry.current_backend = None;
entry.status = SurfaceStatus::Error {
backend_id: backend_id.to_owned(),
message: message.into(),
};
Ok(())
}
#[must_use]
pub fn status(&self, surface: &SurfaceId) -> Option<&SurfaceStatus> {
self.entries.get(surface).map(|entry| &entry.status)
}
/// All configured surface states in stable ID order.
pub fn statuses(&self) -> impl Iterator<Item = (&SurfaceId, &SurfaceStatus)> {
self.entries.iter().map(|(id, entry)| (id, &entry.status))
}
}
fn disconnect_current(id: &SurfaceId, entry: &mut Entry, actions: &mut Vec<SurfaceAction>) {
if let Some(backend_id) = entry.current_backend.take() {
actions.push(SurfaceAction::Disconnect {
surface: id.clone(),
backend_id,
});
}
}