use std::collections::BTreeMap;
use std::sync::Arc;
use serde::Serialize;
use tokio::sync::{RwLock, watch};
use crate::named::Named;
use crate::relogio::{Clock, Instant};
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SubscriberSnapshot {
pub name: &'static str,
pub subscriber_count: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ChildCountSnapshot {
pub name: &'static str,
pub child_count: usize,
}
#[macro_export]
macro_rules! impl_observable_subscriber {
($type:ty, $name:literal) => {
impl $crate::mirante::Observable for $type {
type Snapshot = $crate::mirante::SubscriberSnapshot;
fn snapshot(&self) -> Self::Snapshot {
$crate::mirante::SubscriberSnapshot {
name: $name,
subscriber_count: self.subscriber_count(),
}
}
}
};
}
#[macro_export]
macro_rules! impl_observable {
($type:ty, $snapshot:ty) => {
impl $crate::mirante::Observable for $type {
type Snapshot = $snapshot;
fn snapshot(&self) -> Self::Snapshot {
Self::snapshot(self)
}
}
};
}
pub trait Observable: Named + Send + Sync {
type Snapshot: Clone + Serialize + Send + Sync + 'static;
fn snapshot(&self) -> Self::Snapshot;
}
pub struct ObservationChannel<S: Clone + Send + Sync + 'static> {
tx: watch::Sender<S>,
rx: watch::Receiver<S>,
last_changed: Arc<RwLock<Instant>>,
clock: Arc<dyn Clock>,
}
impl<S: Clone + Send + Sync + 'static> ObservationChannel<S> {
#[must_use]
pub fn new(initial: S, clock: Arc<dyn Clock>) -> Self {
let (tx, rx) = watch::channel(initial);
let last_changed = Arc::new(RwLock::new(clock.now()));
Self {
tx,
rx,
last_changed,
clock,
}
}
pub fn publish(&self, next: S) {
let _ = self.tx.send(next);
let now = self.clock.now();
if let Ok(mut guard) = self.last_changed.try_write() {
*guard = now;
}
}
#[must_use]
pub fn current(&self) -> S {
self.rx.borrow().clone()
}
#[must_use]
pub fn subscribe(&self) -> watch::Receiver<S> {
self.rx.clone()
}
pub async fn last_changed(&self) -> Instant {
*self.last_changed.read().await
}
#[must_use]
pub fn subscriber_count(&self) -> usize {
self.tx.receiver_count()
}
}
impl<S: Clone + Send + Sync + 'static> Named for ObservationChannel<S> {
fn name(&self) -> &'static str {
"observation-channel"
}
}
impl<S: Clone + Send + Sync + 'static> Observable for ObservationChannel<S> {
type Snapshot = SubscriberSnapshot;
fn snapshot(&self) -> Self::Snapshot {
SubscriberSnapshot {
name: "observation-channel",
subscriber_count: self.subscriber_count(),
}
}
}
pub trait AnyChannel: Send + Sync {
fn name(&self) -> &'static str;
fn current_json(&self) -> serde_json::Value;
fn last_changed_packed(&self) -> u64;
}
impl<S: Clone + Serialize + Send + Sync + 'static> AnyChannel
for (&'static str, Arc<ObservationChannel<S>>)
{
fn name(&self) -> &'static str {
self.0
}
fn current_json(&self) -> serde_json::Value {
serde_json::to_value(self.1.current()).unwrap_or(serde_json::Value::Null)
}
fn last_changed_packed(&self) -> u64 {
match self.1.last_changed.try_read() {
Ok(guard) => guard.to_packed(),
Err(_) => 0,
}
}
}
#[derive(Default)]
pub struct Mirante {
channels: BTreeMap<&'static str, Arc<dyn AnyChannel>>,
}
impl Mirante {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn register<S: Clone + Serialize + Send + Sync + 'static>(
&mut self,
name: &'static str,
channel: Arc<ObservationChannel<S>>,
) {
let any: Arc<dyn AnyChannel> = Arc::new((name, channel));
self.channels.insert(name, any);
}
#[must_use]
pub fn list(&self) -> Vec<&'static str> {
self.channels.keys().copied().collect()
}
#[must_use]
pub fn len(&self) -> usize {
self.channels.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.channels.is_empty()
}
#[must_use]
pub fn snapshot_all(&self) -> BTreeMap<String, serde_json::Value> {
self.channels
.iter()
.map(|(name, ch)| ((*name).to_string(), ch.current_json()))
.collect()
}
#[must_use]
pub fn last_changed_all(&self) -> BTreeMap<String, u64> {
self.channels
.iter()
.map(|(name, ch)| ((*name).to_string(), ch.last_changed_packed()))
.collect()
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct MiranteSnapshot {
pub name: &'static str,
pub channel_count: usize,
pub channel_names: Vec<String>,
}
crate::define_named!(Mirante, "mirante");
impl Observable for Mirante {
type Snapshot = MiranteSnapshot;
fn snapshot(&self) -> Self::Snapshot {
MiranteSnapshot {
name: "mirante",
channel_count: self.len(),
channel_names: self.channels.keys().map(|s| (*s).to_string()).collect(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::relogio::FrozenClock;
use serde::Deserialize;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CacheStats {
hits: u64,
misses: u64,
}
fn frozen_clock(t: u64) -> Arc<dyn Clock> {
Arc::new(FrozenClock::at(t))
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FooSnapshot {
pub name: &'static str,
pub answer: u32,
}
pub struct Foo {
pub answer: u32,
}
crate::define_named!(Foo, "foo");
impl Foo {
pub fn snapshot(&self) -> FooSnapshot {
FooSnapshot {
name: "foo",
answer: self.answer,
}
}
}
crate::impl_observable!(Foo, FooSnapshot);
pub struct BarBroadcast {
sender: tokio::sync::broadcast::Sender<u32>,
}
impl BarBroadcast {
pub fn new() -> Self {
let (sender, _) = tokio::sync::broadcast::channel(8);
Self { sender }
}
pub fn subscriber_count(&self) -> usize {
self.sender.receiver_count()
}
}
crate::define_named!(BarBroadcast, "bar-broadcast");
crate::impl_observable_subscriber!(BarBroadcast, "bar-broadcast");
#[test]
fn impl_observable_macro_delegates_to_inherent() {
let f = Foo { answer: 42 };
let inh = Foo::snapshot(&f);
let via_trait = Observable::snapshot(&f);
assert_eq!(inh, via_trait);
assert_eq!(via_trait.name, "foo");
assert_eq!(via_trait.answer, 42);
}
#[test]
fn impl_observable_subscriber_macro_returns_subscriber_snapshot() {
let b = BarBroadcast::new();
let snap0 = Observable::snapshot(&b);
assert_eq!(snap0.name, "bar-broadcast");
assert_eq!(snap0.subscriber_count, 0);
let _rx1 = b.sender.subscribe();
let _rx2 = b.sender.subscribe();
let snap2 = Observable::snapshot(&b);
assert_eq!(snap2.subscriber_count, 2);
}
#[tokio::test]
async fn channel_publish_and_current_round_trip() {
let ch = ObservationChannel::new(CacheStats { hits: 0, misses: 0 }, frozen_clock(100));
assert_eq!(ch.current(), CacheStats { hits: 0, misses: 0 });
ch.publish(CacheStats {
hits: 10,
misses: 1,
});
assert_eq!(
ch.current(),
CacheStats {
hits: 10,
misses: 1
}
);
}
#[tokio::test]
async fn channel_subscribe_receives_latest() {
let ch = ObservationChannel::new(0u32, frozen_clock(0));
let mut rx = ch.subscribe();
ch.publish(42);
rx.changed().await.unwrap();
assert_eq!(*rx.borrow(), 42);
}
#[tokio::test]
async fn channel_subscriber_count_tracks_lifetimes() {
let ch = ObservationChannel::new(0u32, frozen_clock(0));
assert_eq!(ch.subscriber_count(), 1); let rx2 = ch.subscribe();
assert_eq!(ch.subscriber_count(), 2);
drop(rx2);
assert_eq!(ch.subscriber_count(), 1);
}
#[tokio::test]
async fn channel_last_changed_advances_on_publish() {
let clock = Arc::new(FrozenClock::at(100));
let ch = ObservationChannel::new(0u32, clock.clone());
let t0 = ch.last_changed().await;
clock.advance(50);
ch.publish(1);
tokio::task::yield_now().await;
let t1 = ch.last_changed().await;
assert!(t1 > t0);
}
#[tokio::test]
async fn channel_publishes_are_last_value_only() {
let ch = ObservationChannel::new(0u32, frozen_clock(0));
ch.publish(1);
ch.publish(2);
ch.publish(3);
assert_eq!(ch.current(), 3);
}
#[tokio::test]
async fn mirante_register_and_list() {
let mut m = Mirante::new();
let cache_ch = Arc::new(ObservationChannel::new(
CacheStats { hits: 0, misses: 0 },
frozen_clock(0),
));
let count_ch = Arc::new(ObservationChannel::new(0u32, frozen_clock(0)));
m.register("cache", cache_ch);
m.register("count", count_ch);
let names = m.list();
assert_eq!(names.len(), 2);
assert!(names.contains(&"cache"));
assert!(names.contains(&"count"));
assert_eq!(m.len(), 2);
assert!(!m.is_empty());
}
#[tokio::test]
async fn mirante_register_replaces_by_name() {
let mut m = Mirante::new();
m.register(
"x",
Arc::new(ObservationChannel::new(0u32, frozen_clock(0))),
);
m.register(
"x",
Arc::new(ObservationChannel::new(99u32, frozen_clock(0))),
);
let snap = m.snapshot_all();
assert_eq!(snap["x"], serde_json::json!(99));
}
#[tokio::test]
async fn mirante_snapshot_all_returns_json() {
let mut m = Mirante::new();
let cache_ch = Arc::new(ObservationChannel::new(
CacheStats {
hits: 10,
misses: 2,
},
frozen_clock(0),
));
m.register("cache", cache_ch);
let snap = m.snapshot_all();
assert_eq!(snap["cache"]["hits"], 10);
assert_eq!(snap["cache"]["misses"], 2);
}
#[tokio::test]
async fn mirante_reflects_publish_after_register() {
let mut m = Mirante::new();
let ch = Arc::new(ObservationChannel::new(0u32, frozen_clock(0)));
m.register("x", ch.clone());
ch.publish(42);
let snap = m.snapshot_all();
assert_eq!(snap["x"], serde_json::json!(42));
}
#[tokio::test]
async fn mirante_empty_default() {
let m = Mirante::new();
assert!(m.is_empty());
assert_eq!(m.len(), 0);
assert!(m.list().is_empty());
assert!(m.snapshot_all().is_empty());
}
#[tokio::test]
async fn mirante_last_changed_all_returns_packed() {
let clock = Arc::new(FrozenClock::at(100));
let ch = Arc::new(ObservationChannel::new(0u32, clock.clone()));
let mut m = Mirante::new();
m.register("x", ch.clone());
clock.advance(50);
ch.publish(1);
tokio::task::yield_now().await;
let lc = m.last_changed_all();
assert!(lc["x"] > 0);
}
#[derive(Default)]
pub struct FakeCache {
stats: std::sync::Mutex<CacheStats>,
}
crate::define_named!(FakeCache, "fake-cache");
impl Observable for FakeCache {
type Snapshot = CacheStats;
fn snapshot(&self) -> CacheStats {
self.stats.lock().unwrap().clone()
}
}
#[tokio::test]
async fn observable_implementer_returns_snapshot() {
let cache = FakeCache::default();
cache.stats.lock().unwrap().hits = 5;
let snap = cache.snapshot();
assert_eq!(snap.hits, 5);
assert_eq!(cache.name(), "fake-cache");
}
}