Skip to main content

qualia_core_db/services/
pulse_transport.rs

1//! Pulse transport — process-wide broadcast channel for `pulse.publish` events.
2//!
3//! The 0.1 `pulse.publish(topic, payload)` binding routes through this module
4//! when the Poet snapshot is `attached` to the live daemon graph. Subscribers
5//! (e.g. an SSE endpoint, WebSocket relay, or collaborative sync layer) receive
6//! a [`PulseEvent`] for every published pulse.
7//!
8//! Design mirrors [`crate::daemon_graph`]: a `OnceLock<broadcast::Sender>` so
9//! the channel is lazily initialised on first use and shared across all
10//! callers in the process. The channel capacity is bounded (64) to avoid
11//! unbounded memory growth if no subscriber is draining.
12
13use std::sync::OnceLock;
14use std::time::{SystemTime, UNIX_EPOCH};
15
16use tokio::sync::broadcast;
17
18/// Maximum in-flight pulse events before backpressure drops to the slowest
19/// subscriber. Matches the graph-revision channel capacity.
20const PULSE_CHANNEL_CAPACITY: usize = 64;
21
22/// A single pulse event emitted by `pulse.publish`.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct PulseEvent {
25    /// The topic string (must match the 0.1 allowlist prefixes).
26    pub topic: String,
27    /// A compact textual summary of the payload value (for SSE / log display).
28    pub payload_summary: String,
29    /// Monotonic sequence number for this pulse (starts at 1).
30    pub seq: u64,
31    /// UNIX timestamp (seconds) at which the pulse was emitted.
32    pub timestamp: u64,
33}
34
35static PULSE_TX: OnceLock<broadcast::Sender<PulseEvent>> = OnceLock::new();
36static PULSE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
37
38fn pulse_tx() -> &'static broadcast::Sender<PulseEvent> {
39    PULSE_TX.get_or_init(|| {
40        let (tx, _rx) = broadcast::channel(PULSE_CHANNEL_CAPACITY);
41        tx
42    })
43}
44
45/// Publish a pulse event to all subscribers. Returns the sequence number
46/// assigned to this event, or `0` if there are no subscribers (the event is
47/// still recorded in the sequence counter for monotonicity).
48///
49/// This is the native transport path called by `PoetSnapshot::pulse_publish`
50/// when `attached`. On WASM, the Poet host falls back to the in-memory
51/// `published` vector.
52pub fn publish(topic: &str, payload_summary: &str) -> u64 {
53    let seq = PULSE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Release) + 1;
54    let timestamp = SystemTime::now()
55        .duration_since(UNIX_EPOCH)
56        .map(|d| d.as_secs())
57        .unwrap_or(0);
58    let event = PulseEvent {
59        topic: topic.to_string(),
60        payload_summary: payload_summary.to_string(),
61        seq,
62        timestamp,
63    };
64    let _ = pulse_tx().send(event);
65    seq
66}
67
68/// Subscribe to the pulse event stream. Each subscriber gets its own
69/// `broadcast::Receiver`; slow subscribers may miss events if they lag
70/// behind by more than `PULSE_CHANNEL_CAPACITY`.
71pub fn subscribe() -> broadcast::Receiver<PulseEvent> {
72    pulse_tx().subscribe()
73}
74
75/// Current monotonic pulse sequence counter (for diagnostics / UI display).
76pub fn pulse_seq() -> u64 {
77    PULSE_SEQ.load(std::sync::atomic::Ordering::Acquire)
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    #[test]
85    fn publish_increments_seq() {
86        let before = pulse_seq();
87        let seq = publish("pulse/test-seq", "hello");
88        assert!(seq > before, "seq {seq} should be > before {before}");
89        // pulse_seq may have advanced further if another test ran in parallel;
90        // we only assert monotonicity (seq >= pulse_seq is always true since
91        // seq was just allocated from the same counter).
92        assert!(pulse_seq() >= seq);
93    }
94
95    #[test]
96    fn subscribe_receives_event() {
97        let mut rx = subscribe();
98        let seq = publish("pulse/test-recv", "payload-text");
99        let event = rx.try_recv().expect("subscriber should receive event");
100        assert_eq!(event.seq, seq);
101        assert_eq!(event.topic, "pulse/test-recv");
102        assert_eq!(event.payload_summary, "payload-text");
103    }
104
105    #[test]
106    fn publish_without_subscriber_is_ok() {
107        // Publishing with no subscriber must not panic (broadcast::send returns
108        // Err, which we discard).
109        let _ = publish("pulse/test-no-sub", "orphan");
110    }
111}