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;
pub const SCHEMA: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Event {
pub schema: u32,
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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: 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 schema: u32,
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 {
schema: SCHEMA,
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,
detail: 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");
}
}
#[cfg(test)]
mod schema_tests {
use super::*;
const FIELDS_V1: &[&str] = &[
"schema",
"time",
"kind",
"client",
"client_id",
"namespace",
"operation",
"key",
"branch",
"detail",
"ok",
"error",
];
fn full_event() -> Event {
Event {
client_id: Some("claude-code".to_owned()),
operation: Some("claim".to_owned()),
key: Some("shop:task:3".to_owned()),
branch: Some("main".to_owned()),
detail: Some("held by Codex CLI".to_owned()),
ok: false,
error: Some("held".to_owned()),
..Event::about("claude-code", Some("shop"))
}
}
#[test]
fn schema_one_has_exactly_these_fields() {
assert_eq!(
SCHEMA, 1,
"a new schema needs a new field list and a docs section"
);
let json = serde_json::to_value(full_event()).unwrap_or_default();
let fields: Vec<&str> = json
.as_object()
.map(|o| o.keys().map(String::as_str).collect())
.unwrap_or_default();
assert_eq!(fields, FIELDS_V1);
assert_eq!(json["schema"], 1);
let hello = Hello {
schema: SCHEMA,
kind: "hello".to_owned(),
version: "0.0.0".to_owned(),
port: 1,
clients: vec![Connected {
client: "c".to_owned(),
namespace: "n".to_owned(),
}],
};
let json = serde_json::to_value(hello).unwrap_or_default();
let fields: Vec<&str> = json
.as_object()
.map(|o| o.keys().map(String::as_str).collect())
.unwrap_or_default();
assert_eq!(fields, ["schema", "kind", "version", "port", "clients"]);
}
#[test]
fn every_field_is_described_in_the_docs() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("..")
.join("docs")
.join("EVENTS.md");
let docs = std::fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));
for field in FIELDS_V1
.iter()
.chain(["version", "port", "clients"].iter())
{
assert!(
docs.contains(&format!("| `{field}` |")),
"docs/EVENTS.md does not describe `{field}`"
);
}
for kind in ["connected", "disconnected", "operation", "hello"] {
assert!(docs.contains(&format!("`{kind}`")), "{kind}");
}
for op in ["lesson", "fact", "flag", "ready", "maintain"] {
assert!(docs.contains(&format!("| `{op}` |")), "{op}");
}
}
#[test]
fn a_line_stays_readable_by_an_older_reader() {
let mut json = serde_json::to_value(full_event()).unwrap_or_default();
json["added_later"] = serde_json::json!("x");
let back: Result<Event, _> = serde_json::from_value(json);
assert!(back.is_ok());
}
}