fader_master/core/src/server.rs

418 lines
13 KiB
Rust

//! Pure server reducer and adapter effects.
use crate::{ChannelGainError, ChannelGains, Gain, Mute, Revision, StreamHandle};
use std::collections::BTreeMap;
use thiserror::Error;
/// Monotonic identifier for one accepted adapter operation.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct OperationId(u64);
impl OperationId {
/// Creates an identifier at an adapter or wire boundary.
#[must_use]
pub const fn new(value: u64) -> Self {
Self(value)
}
#[must_use]
pub const fn get(self) -> u64 {
self.0
}
}
/// Source of a command accepted by the state owner.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CommandOrigin {
Midi { surface: String, sequence: u64 },
Client { request: u64 },
Restore,
}
/// A validated command addressed to one resolved stream.
#[derive(Clone, Debug, PartialEq)]
pub enum ServerCommand {
SetVolume {
origin: CommandOrigin,
expected_revision: Revision,
stream: StreamHandle,
target: Gain,
},
SetMute {
origin: CommandOrigin,
expected_revision: Revision,
stream: StreamHandle,
muted: Mute,
},
}
/// Commands emitted to an audio adapter.
#[derive(Clone, Debug, PartialEq)]
pub enum AdapterCommand {
SetVolume {
operation: OperationId,
stream: StreamHandle,
channels: ChannelGains,
},
SetMute {
operation: OperationId,
stream: StreamHandle,
muted: Mute,
},
Readback {
operation: OperationId,
stream: StreamHandle,
},
}
/// Events copied from an audio adapter into the state owner.
#[derive(Clone, Debug, PartialEq)]
pub enum AdapterEvent {
Observed {
stream: StreamHandle,
channels: ChannelGains,
muted: Mute,
operation: Option<OperationId>,
},
WriteAccepted {
operation: OperationId,
},
WriteFailed {
operation: OperationId,
message: String,
},
WriteSuperseded {
operation: OperationId,
},
StreamRemoved {
stream: StreamHandle,
},
}
/// Immutable state published to clients and feedback workers.
#[derive(Clone, Debug, PartialEq)]
pub struct StreamView {
pub stream: StreamHandle,
pub revision: Revision,
pub channels: ChannelGains,
pub muted: Mute,
pub desired_gain: Option<Gain>,
pub desired_mute: Option<Mute>,
pub pending: bool,
pub error: Option<String>,
}
/// Effects produced by one deterministic reducer step.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Transition {
pub adapter: Vec<AdapterCommand>,
pub confirmed: Vec<StreamView>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Property {
Volume,
Mute,
}
#[derive(Clone, Debug)]
struct Pending {
stream: StreamHandle,
property: Property,
}
#[derive(Clone, Debug)]
struct StreamState {
channels: ChannelGains,
muted: Mute,
desired_gain: Option<Gain>,
desired_mute: Option<Mute>,
volume_operation: Option<OperationId>,
mute_operation: Option<OperationId>,
error: Option<String>,
}
/// Errors that reject a command before dispatch.
#[derive(Debug, Error, PartialEq)]
pub enum ReducerError {
#[error("stale revision {actual:?}; current revision is {current:?}")]
StaleRevision { actual: Revision, current: Revision },
#[error("stream {0:?} is not currently observed")]
Offline(StreamHandle),
#[error(transparent)]
Channels(#[from] ChannelGainError),
#[error("revision counter exhausted")]
RevisionExhausted,
#[error("operation counter exhausted")]
OperationExhausted,
}
/// Single owner of desired, pending, and observed stream state.
#[derive(Debug)]
pub struct ServerReducer {
revision: Revision,
next_operation: u64,
write_ceiling: Gain,
streams: BTreeMap<StreamHandle, StreamState>,
operations: BTreeMap<OperationId, Pending>,
active_epoch: Option<crate::BackendEpoch>,
}
impl ServerReducer {
#[must_use]
pub fn new(write_ceiling: Gain) -> Self {
Self {
revision: Revision::INITIAL,
next_operation: 1,
write_ceiling,
streams: BTreeMap::new(),
operations: BTreeMap::new(),
active_epoch: None,
}
}
#[must_use]
pub const fn revision(&self) -> Revision {
self.revision
}
#[must_use]
pub fn view(&self, stream: StreamHandle) -> Option<StreamView> {
self.streams
.get(&stream)
.map(|state| self.stream_view(stream, state))
}
pub fn command(&mut self, command: ServerCommand) -> Result<Transition, ReducerError> {
let expected = match &command {
ServerCommand::SetVolume {
expected_revision, ..
}
| ServerCommand::SetMute {
expected_revision, ..
} => *expected_revision,
};
if expected != self.revision {
return Err(ReducerError::StaleRevision {
actual: expected,
current: self.revision,
});
}
match command {
ServerCommand::SetVolume { stream, target, .. } => {
let channels = self
.streams
.get(&stream)
.ok_or(ReducerError::Offline(stream))?
.channels
.scaled_to(target, self.write_ceiling)?;
let operation = self.operation(stream, Property::Volume)?;
let state = self
.streams
.get_mut(&stream)
.ok_or(ReducerError::Offline(stream))?;
state.desired_gain = Some(target);
state.volume_operation = Some(operation);
state.error = None;
self.advance_revision()?;
Ok(Transition {
adapter: vec![AdapterCommand::SetVolume {
operation,
stream,
channels,
}],
confirmed: Vec::new(),
})
}
ServerCommand::SetMute { stream, muted, .. } => {
let operation = self.operation(stream, Property::Mute)?;
let state = self
.streams
.get_mut(&stream)
.ok_or(ReducerError::Offline(stream))?;
state.desired_mute = Some(muted);
state.mute_operation = Some(operation);
state.error = None;
self.advance_revision()?;
Ok(Transition {
adapter: vec![AdapterCommand::SetMute {
operation,
stream,
muted,
}],
confirmed: Vec::new(),
})
}
}
}
pub fn event(&mut self, event: AdapterEvent) -> Result<Transition, ReducerError> {
match event {
AdapterEvent::Observed {
stream,
channels,
muted,
operation,
} => {
if self.event_is_stale(stream) {
return Ok(Transition::default());
}
self.adopt_epoch_and_incarnation(stream);
if let Some(operation) = operation {
self.settle_if_current(operation);
}
let state = self.streams.entry(stream).or_insert_with(|| StreamState {
channels: channels.clone(),
muted,
desired_gain: None,
desired_mute: None,
volume_operation: None,
mute_operation: None,
error: None,
});
state.channels = channels;
state.muted = muted;
state.error = None;
self.advance_revision()?;
let view = self.view(stream).ok_or(ReducerError::Offline(stream))?;
Ok(Transition {
adapter: Vec::new(),
confirmed: vec![view],
})
}
AdapterEvent::WriteAccepted { operation } => {
let Some(pending) = self.operations.get(&operation) else {
return Ok(Transition::default());
};
Ok(Transition {
adapter: vec![AdapterCommand::Readback {
operation,
stream: pending.stream,
}],
confirmed: Vec::new(),
})
}
AdapterEvent::WriteFailed { operation, message } => {
let stream = self
.operations
.get(&operation)
.map(|pending| pending.stream);
if let Some(stream) = stream
&& self.settle_if_current(operation)
&& let Some(state) = self.streams.get_mut(&stream)
{
state.error = Some(message);
self.advance_revision()?;
let view = self.view(stream).ok_or(ReducerError::Offline(stream))?;
return Ok(Transition {
adapter: Vec::new(),
confirmed: vec![view],
});
}
Ok(Transition::default())
}
AdapterEvent::WriteSuperseded { operation } => {
self.operations.remove(&operation);
Ok(Transition::default())
}
AdapterEvent::StreamRemoved { stream } => {
self.streams.remove(&stream);
self.operations
.retain(|_, pending| pending.stream != stream);
self.advance_revision()?;
Ok(Transition::default())
}
}
}
fn operation(
&mut self,
stream: StreamHandle,
property: Property,
) -> Result<OperationId, ReducerError> {
if !self.streams.contains_key(&stream) {
return Err(ReducerError::Offline(stream));
}
let operation = OperationId(self.next_operation);
self.next_operation = self
.next_operation
.checked_add(1)
.ok_or(ReducerError::OperationExhausted)?;
self.operations
.insert(operation, Pending { stream, property });
Ok(operation)
}
fn event_is_stale(&self, stream: StreamHandle) -> bool {
if self
.active_epoch
.is_some_and(|epoch| stream.epoch() < epoch)
{
return true;
}
self.streams.keys().any(|known| {
known.epoch() == stream.epoch()
&& known.backend_id() == stream.backend_id()
&& known.incarnation() > stream.incarnation()
})
}
fn adopt_epoch_and_incarnation(&mut self, stream: StreamHandle) {
if self.active_epoch.is_none_or(|epoch| stream.epoch() > epoch) {
self.active_epoch = Some(stream.epoch());
self.streams.clear();
self.operations.clear();
}
self.streams.retain(|known, _| {
known.epoch() != stream.epoch()
|| known.backend_id() != stream.backend_id()
|| known.incarnation() >= stream.incarnation()
});
self.operations.retain(|_, pending| {
pending.stream.epoch() != stream.epoch()
|| pending.stream.backend_id() != stream.backend_id()
|| pending.stream.incarnation() >= stream.incarnation()
});
}
fn settle_if_current(&mut self, operation: OperationId) -> bool {
let Some(pending) = self.operations.remove(&operation) else {
return false;
};
let Some(state) = self.streams.get_mut(&pending.stream) else {
return false;
};
let slot = match pending.property {
Property::Volume => &mut state.volume_operation,
Property::Mute => &mut state.mute_operation,
};
if *slot == Some(operation) {
*slot = None;
true
} else {
false
}
}
fn advance_revision(&mut self) -> Result<(), ReducerError> {
self.revision = self
.revision
.checked_next()
.ok_or(ReducerError::RevisionExhausted)?;
Ok(())
}
fn stream_view(&self, stream: StreamHandle, state: &StreamState) -> StreamView {
StreamView {
stream,
revision: self.revision,
channels: state.channels.clone(),
muted: state.muted,
desired_gain: state.desired_gain,
desired_mute: state.desired_mute,
pending: state.volume_operation.is_some() || state.mute_operation.is_some(),
error: state.error.clone(),
}
}
}