use super::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ManualKind {
Stop,
Restart,
Delete,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum CommandOrigin {
Operator,
Automatic,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct PendingManual {
pub(crate) kind: ManualKind,
pub(crate) origin: CommandOrigin,
}
#[derive(Debug)]
pub(super) struct PendingAction {
pub(super) stamp: u64,
pub(super) action: String,
pub(super) waiter: Option<oneshot::Sender<String>>,
pub(super) reply: oneshot::Sender<ActionOutcome>,
}
#[derive(Debug)]
pub(super) struct AbandonedReply {
pub(super) stamp: u64,
pub(super) action: String,
}
#[derive(Debug, Default)]
pub(super) struct ActionWaits {
pub(super) live: Vec<PendingAction>,
pub(super) abandoned: VecDeque<AbandonedReply>,
}
impl ActionWaits {
pub(super) fn arm(&mut self, pending: PendingAction) {
self.live.push(pending);
}
pub(super) fn answer(
&mut self,
action: &str,
stamp: Option<u64>,
) -> Option<oneshot::Sender<String>> {
if let Some(stamp) = stamp {
if let Some(pending) = self
.live
.iter_mut()
.find(|pending| pending.stamp == stamp && pending.waiter.is_some())
{
return pending.waiter.take();
}
if let Some(owed) = self.abandoned.iter().position(|debt| debt.stamp == stamp) {
self.abandoned.remove(owed);
}
return None;
}
if let Some(owed) = self.abandoned.iter().position(|debt| debt.action == action) {
self.abandoned.remove(owed);
return None;
}
self.live
.iter_mut()
.find(|pending| pending.action == action && pending.waiter.is_some())
.and_then(|pending| pending.waiter.take())
}
pub(super) fn resolve(&mut self, stamp: u64) -> Option<oneshot::Sender<ActionOutcome>> {
let at = self
.live
.iter()
.position(|pending| pending.stamp == stamp)?;
let pending = self.live.remove(at);
if pending.waiter.is_some() {
self.abandoned.push_back(AbandonedReply {
stamp: pending.stamp,
action: pending.action,
});
if self.abandoned.len() > MAX_ABANDONED_ACTION_REPLIES {
self.abandoned.pop_front();
}
}
Some(pending.reply)
}
pub(super) fn abandon_all(&mut self) {
for pending in self.live.drain(..) {
let _ = pending.reply.send(ActionOutcome::NoChannel);
}
self.abandoned.clear();
}
}