use std::collections::BTreeMap;
use std::future::Future;
use std::hash::Hash;
use std::pin::Pin;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use super::source::Block;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StateChange<'a, K, V> {
key: &'a K,
seen: Option<&'a V>,
now: &'a V,
}
impl<'a, K, V> StateChange<'a, K, V> {
#[must_use]
pub const fn key(&self) -> &'a K {
self.key
}
#[must_use]
pub const fn seen(&self) -> Option<&'a V> {
self.seen
}
#[must_use]
pub const fn now(&self) -> &'a V {
self.now
}
}
pub trait StateSource: Send + Sync + 'static {
const ID: &'static str;
type Key: Eq + Hash + Clone + Serialize + DeserializeOwned + Send + Sync + 'static;
type Value: PartialEq + Clone + Serialize + DeserializeOwned + Send + Sync + 'static;
fn poll(&mut self) -> impl Future<Output = Vec<(Self::Key, Self::Value)>> + Send;
fn is_normal(&self, key: &Self::Key, value: &Self::Value) -> bool;
fn announce(&self, change: &StateChange<'_, Self::Key, Self::Value>) -> Block;
}
struct Entry<K, V> {
key: K,
now: V,
}
struct Tracked<S: StateSource> {
source: S,
entries: Vec<Entry<S::Key, S::Value>>,
}
impl<S: StateSource> Tracked<S> {
fn record(&mut self, key: S::Key, value: S::Value) {
match self.entries.iter_mut().find(|entry| entry.key == key) {
Some(entry) => entry.now = value,
None => self.entries.push(Entry { key, now: value }),
}
}
fn alerts(&self, stored: Option<serde_json::Value>) -> (Vec<Block>, serde_json::Value) {
let mut seen: Vec<(S::Key, S::Value)> = stored.map_or_else(Vec::new, |stored| {
serde_json::from_value(stored).unwrap_or_else(|error| {
panic!(
"the context holds what the model saw of `{}` in another form: {error}",
S::ID
)
})
});
let mut alerts = Vec::new();
for entry in &self.entries {
let position = seen.iter().position(|(key, _)| *key == entry.key);
let known = position.map_or_else(
|| self.source.is_normal(&entry.key, &entry.now),
|position| seen[position].1 == entry.now,
);
if known {
continue;
}
alerts.push(self.source.announce(&StateChange {
key: &entry.key,
seen: position.map(|position| &seen[position].1),
now: &entry.now,
}));
match position {
Some(position) => seen[position].1 = entry.now.clone(),
None => seen.push((entry.key.clone(), entry.now.clone())),
}
}
let seen = serde_json::to_value(&seen).expect("the keys and values of a state serialize");
(alerts, seen)
}
}
type Answer = (Vec<Block>, serde_json::Value);
trait StateSourceImpl: Send + Sync {
fn id(&self) -> &'static str;
fn on_request(
&mut self,
stored: Option<serde_json::Value>,
) -> Pin<Box<dyn Future<Output = Answer> + Send + '_>>;
}
impl<S: StateSource> StateSourceImpl for Tracked<S> {
fn id(&self) -> &'static str {
S::ID
}
fn on_request(
&mut self,
stored: Option<serde_json::Value>,
) -> Pin<Box<dyn Future<Output = Answer> + Send + '_>> {
Box::pin(async move {
for (key, value) in self.source.poll().await {
self.record(key, value);
}
self.alerts(stored)
})
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeenStates(BTreeMap<String, serde_json::Value>);
impl SeenStates {
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub(crate) fn get(&self, id: &str) -> Option<&serde_json::Value> {
self.0.get(id)
}
pub(crate) fn set(&mut self, id: &str, seen: serde_json::Value) {
self.0.insert(id.to_owned(), seen);
}
pub(crate) fn clear(&mut self) {
self.0.clear();
}
}
pub struct AnyStateSource {
inner: Box<dyn StateSourceImpl>,
}
impl std::fmt::Debug for AnyStateSource {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("AnyStateSource")
.finish_non_exhaustive()
}
}
impl AnyStateSource {
#[must_use]
pub fn new<S: StateSource>(source: S) -> Self {
Self {
inner: Box::new(Tracked {
source,
entries: Vec::new(),
}),
}
}
pub(crate) fn id(&self) -> &'static str {
self.inner.id()
}
pub(crate) fn on_request(
&mut self,
stored: Option<serde_json::Value>,
) -> impl Future<Output = Answer> + Send + '_ {
self.inner.on_request(stored)
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Disk {
levels: async_channel::Receiver<u8>,
}
impl StateSource for Disk {
const ID: &'static str = "disk";
type Key = String;
type Value = u8;
fn poll(&mut self) -> impl Future<Output = Vec<(String, u8)>> + Send {
std::future::ready(
std::iter::from_fn(|| self.levels.try_recv().ok())
.map(|level| ("/work".to_owned(), level))
.collect(),
)
}
fn is_normal(&self, _: &String, level: &u8) -> bool {
*level == 0
}
fn announce(&self, change: &StateChange<'_, String, u8>) -> Block {
Block::new(
"disk",
format!("{} {:?} -> {}", change.key(), change.seen(), change.now()),
)
}
}
struct Harness {
levels: async_channel::Sender<u8>,
source: AnyStateSource,
seen: SeenStates,
}
impl Harness {
fn new() -> Self {
let (levels, receiver) = async_channel::unbounded();
Self {
levels,
source: AnyStateSource::new(Disk { levels: receiver }),
seen: SeenStates::default(),
}
}
async fn send(&self, level: u8) {
self.levels.send(level).await.expect("open");
}
async fn request(&mut self, reassembled: bool) -> Vec<String> {
if reassembled {
self.seen.clear();
}
let id = self.source.id();
let (alerts, seen) = self.source.on_request(self.seen.get(id).cloned()).await;
self.seen.set(id, seen);
alerts
.iter()
.map(|block| block.content().to_owned())
.collect()
}
}
const NONE: [&str; 0] = [];
#[tokio::test]
async fn only_a_value_the_model_does_not_know_is_announced() {
let mut disk = Harness::new();
disk.send(0).await;
assert_eq!(disk.request(false).await, NONE);
disk.send(1).await;
disk.send(2).await;
assert_eq!(disk.request(false).await, ["/work None -> 2"]);
assert_eq!(disk.request(false).await, NONE, "said once");
disk.send(0).await;
assert_eq!(disk.request(false).await, ["/work Some(2) -> 0"]);
}
#[tokio::test]
async fn a_return_to_the_value_the_model_saw_says_nothing() {
let mut disk = Harness::new();
disk.send(2).await;
assert_eq!(disk.request(false).await.len(), 1);
disk.send(0).await;
disk.send(2).await;
assert_eq!(disk.request(false).await, NONE);
}
#[tokio::test]
async fn a_reassembly_restates_only_a_value_that_is_not_normal() {
let mut disk = Harness::new();
disk.send(2).await;
assert_eq!(disk.request(false).await.len(), 1);
assert_eq!(disk.request(true).await, ["/work None -> 2"]);
disk.send(0).await;
assert_eq!(disk.request(false).await.len(), 1);
assert_eq!(disk.request(true).await, NONE);
}
}