use std::collections::{HashMap, hash_map::Entry};
use serde_json::{Map, Value};
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct PendingApproval {
pub approval_id: String,
pub requested: Value,
pub latest_update: Option<Value>,
}
#[derive(Debug, Default)]
pub(super) struct Approvals {
observed: u64,
pending: HashMap<String, (u64, PendingApproval)>,
resolved: HashMap<String, (u64, Value)>,
}
impl Approvals {
pub(super) fn request(&mut self, id: &str, params: &Map<String, Value>) -> bool {
if self.resolved.contains_key(id) {
return false;
}
let entry = PendingApproval {
approval_id: id.to_owned(),
requested: Value::Object(params.clone()),
latest_update: None,
};
match self.pending.entry(id.to_owned()) {
Entry::Occupied(mut slot) => slot.get_mut().1 = entry,
Entry::Vacant(slot) => {
slot.insert((self.observed, entry));
self.observed += 1;
}
}
true
}
pub(super) fn update(&mut self, id: &str, params: &Map<String, Value>) -> bool {
match self.pending.get_mut(id) {
Some((_, entry)) => {
entry.latest_update = Some(Value::Object(params.clone()));
true
}
None => false,
}
}
pub(super) fn resolve(&mut self, id: &str, params: &Map<String, Value>) -> bool {
self.pending.remove(id);
match self.resolved.entry(id.to_owned()) {
Entry::Vacant(slot) => {
slot.insert((self.observed, Value::Object(params.clone())));
self.observed += 1;
true
}
Entry::Occupied(_) => false,
}
}
pub(super) fn latest(&self, id: &str) -> Option<&Value> {
self.pending
.get(id)
.map(|(_, entry)| entry.latest_update.as_ref().unwrap_or(&entry.requested))
}
pub(super) fn resolved(&self, id: &str) -> Option<&Value> {
super::params_of(self.resolved.get(id))
}
pub(super) fn pending_in_order(&self) -> Vec<&PendingApproval> {
let mut ordered: Vec<_> = self.pending.values().collect();
ordered.sort_unstable_by_key(|(observed, _)| *observed);
ordered.into_iter().map(|(_, entry)| entry).collect()
}
pub(super) fn resolved_in_order(&self) -> Vec<&Value> {
super::in_observed_order(&self.resolved)
}
}