use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;
const BACKLOG: usize = 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Event {
pub time: String,
pub kind: String,
pub client: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Connected {
pub client: String,
pub namespace: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Hello {
pub kind: String,
pub version: String,
pub port: u16,
pub clients: Vec<Connected>,
}
#[derive(Debug)]
pub struct Events {
sender: broadcast::Sender<Event>,
sessions: Mutex<BTreeMap<u64, Connected>>,
next: AtomicU64,
}
impl Default for Events {
fn default() -> Self {
Events {
sender: broadcast::channel(BACKLOG).0,
sessions: Mutex::new(BTreeMap::new()),
next: AtomicU64::new(1),
}
}
}
impl Events {
pub fn publish(&self, event: Event) {
let _ = self.sender.send(event);
}
pub fn subscribe(&self) -> broadcast::Receiver<Event> {
self.sender.subscribe()
}
pub fn connected(&self) -> Vec<Connected> {
self.sessions
.lock()
.unwrap_or_else(|e| e.into_inner())
.values()
.cloned()
.collect()
}
pub fn joined(&self, client_id: &str, namespace: &str) -> u64 {
let id = self.next.fetch_add(1, Ordering::Relaxed);
let entry = Connected {
client: crate::clients::display_for_writer(client_id),
namespace: namespace.to_owned(),
};
self.sessions
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(id, entry.clone());
self.publish(Event {
kind: "connected".to_owned(),
..Event::about(client_id, Some(namespace))
});
id
}
pub fn left(&self, handle: u64) {
let gone = self
.sessions
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&handle);
if let Some(gone) = gone {
self.publish(Event {
kind: "disconnected".to_owned(),
client: gone.client,
namespace: Some(gone.namespace),
..Event::about("", None)
});
}
}
}
impl Event {
pub fn about(client_id: &str, namespace: Option<&str>) -> Event {
let client = crate::clients::display_for_writer(client_id);
Event {
time: now(),
kind: "operation".to_owned(),
client_id: (!client_id.is_empty() && client != client_id).then(|| client_id.to_owned()),
client,
namespace: namespace.map(str::to_owned),
operation: None,
key: None,
branch: None,
ok: true,
error: None,
}
}
}
pub fn now() -> String {
jiff::Timestamp::now()
.round(jiff::Unit::Millisecond)
.map_or_else(|_| jiff::Timestamp::now().to_string(), |t| t.to_string())
}
pub fn local_clock(rfc3339: &str) -> String {
rfc3339
.parse::<jiff::Timestamp>()
.map(|t| {
t.to_zoned(jiff::tz::TimeZone::system())
.strftime("%H:%M:%S")
.to_string()
})
.unwrap_or_else(|_| rfc3339.to_owned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sessions_come_and_go_and_say_so() {
let hub = Events::default();
let mut rx = hub.subscribe();
let a = hub.joined("claude-code", "shop");
let _b = hub.joined("some-client", "blog");
assert_eq!(
hub.connected(),
vec![
Connected {
client: "Claude Code".to_owned(),
namespace: "shop".to_owned()
},
Connected {
client: "some-client".to_owned(),
namespace: "blog".to_owned()
},
]
);
hub.left(a);
assert_eq!(hub.connected().len(), 1);
let first = rx.try_recv().unwrap();
assert_eq!(first.kind, "connected");
assert_eq!(first.client, "Claude Code");
assert_eq!(first.client_id.as_deref(), Some("claude-code"));
let _ = rx.try_recv().unwrap();
let gone = rx.try_recv().unwrap();
assert_eq!(gone.kind, "disconnected");
assert_eq!(gone.client, "Claude Code");
}
#[test]
fn times_are_utc_and_read_back_as_a_clock() {
let t = now();
assert!(t.ends_with('Z'), "{t}");
let clock = local_clock(&t);
assert_eq!(clock.len(), 8, "{clock}");
assert_eq!(clock.matches(':').count(), 2);
}
#[test]
fn an_event_serialises_without_empty_fields() {
let e = Event {
operation: Some("put".to_owned()),
key: Some("shop:decision:x".to_owned()),
..Event::about("cli", Some("shop"))
};
let json = serde_json::to_value(&e).unwrap();
assert!(json.get("error").is_none());
assert_eq!(json["operation"], "put");
assert_eq!(json["kind"], "operation");
}
}