orbit-events 0.5.6

Fleet-shared topic event streams over Orbit rings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! `FleetEventBus` — append-only event stream over one Orbit ring.
//!
//! Events are not cache entries and not metrics snapshots. Cache reads
//! ask "what is the newest value for this key?" Metrics reads ask "what
//! is the newest sample for each node?" Event reads ask "which frames
//! have appeared since my cursor?"
//!
//! One event SHM segment carries all topics, with one writer lane per fleet
//! node. The topic is carried inside the frame payload, so adding a new event
//! type does not allocate another SHM segment. Subscribers keep one cursor per
//! node lane and do not assume a total order across nodes.

use std::marker::PhantomData;
use std::sync::Arc;

use bytes::{BufMut, Bytes, BytesMut};
#[cfg(any(
    target_os = "linux",
    target_os = "freebsd",
    target_os = "macos"
))]
use orbit_core::RingEventFd;
use orbit_core::fleet::FleetLaneCursor;
use orbit_core::{Fleet, NetId64, NodeId, OrbitEpoch};

mod layout;

use layout::EventRecord;
pub use layout::{
    DefaultEventLayout, EVENT_PAYLOAD_MAX, EVENT_RING_CAPACITY,
    EVENT_RING_KIND, EVENT_RING_PAYLOAD_CAPACITY, EVENT_RING_SPEC, EventLayout,
};

pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Failures produced by the Orbit event semantic layer.
#[derive(Debug)]
pub enum Error {
    /// A topic and payload envelope cannot fit in one configured event frame.
    FrameTooLarge { topic_len: usize, payload_len: usize, max_payload: usize },
    /// The underlying Orbit ring operation failed.
    Io(std::io::Error),
    /// A custom [`EventLayout`] names a ring this bus cannot use.
    InvalidLayout(&'static str),
}

impl std::fmt::Display for Error {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        match self {
            Self::FrameTooLarge { topic_len, payload_len, max_payload } => {
                write!(
                    f,
                    "orbit event frame too large: topic_len={topic_len} payload_len={payload_len} max_payload={max_payload}"
                )
            }
            Self::Io(error) => write!(f, "orbit event io error: {error}"),
            Self::InvalidLayout(reason) => {
                write!(f, "orbit event layout invalid: {reason}")
            }
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            Self::FrameTooLarge { .. } | Self::InvalidLayout(_) => None,
        }
    }
}

const HEADER_LEN: usize = 2 + 2 + 8;
const FRAME_KIND_EVENT: u8 = 1;

/// Cursor for one event subscriber.
///
/// The cursor stores one next counter per node lane. It is intentionally
/// caller-owned so different consumers can advance independently.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FleetEventCursor {
    inner: FleetLaneCursor,
}

impl FleetEventCursor {
    /// Start from the beginning of the ring history that is still
    /// available.
    pub const fn from_start() -> Self {
        Self { inner: FleetLaneCursor::from_counter(0) }
    }

    /// Start every node lane at the same lane-local next counter.
    ///
    /// This does not restore independently advanced lane positions. Retain or
    /// clone the cursor to preserve them; a numerical minimum is not a checkpoint.
    pub const fn from_counter(next_counter: u64) -> Self {
        Self { inner: FleetLaneCursor::from_counter(next_counter) }
    }

    /// Numerical minimum of the lane-local next counters, including idle lanes.
    ///
    /// Each physical node lane advances independently. This is not a global
    /// event cursor, event order, completion watermark, or multi-lane checkpoint.
    /// An idle lane at zero keeps this value at zero even when all available
    /// events have been consumed. Retain or clone this cursor to preserve each
    /// lane's position; passing the minimum to [`Self::from_counter`] can replay
    /// already consumed events. This reads only caller-owned cursor memory.
    pub fn minimum_lane_next_counter(&self) -> u64 {
        self.inner.minimum_lane_next_counter()
    }

    /// Numerical minimum of independent lane-local counters, not a global cursor.
    #[deprecated(
        note = "use minimum_lane_next_counter; this is not a global cursor or checkpoint"
    )]
    pub fn next_counter(&self) -> u64 {
        self.minimum_lane_next_counter()
    }
}

/// One decoded event from the shared event ring.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FleetEvent {
    pub id: NetId64,
    pub topic: String,
    pub payload: Vec<u8>,
    pub timestamp_ms: u64,
}

/// Result of polling an event cursor.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FleetEventPoll {
    pub events: Vec<FleetEvent>,
    /// Number of counters that could not be delivered because the
    /// subscriber lagged past the ring capacity, a slot was empty, or a
    /// slot had already wrapped to another counter.
    pub lagged: u64,
}

impl FleetEventPoll {
    pub fn is_empty(&self) -> bool {
        self.events.is_empty() && self.lagged == 0
    }
}

/// Fleet-shared raw event bus over the ring named by `L`. Cheap to clone.
pub struct FleetEventBus<L: EventLayout = DefaultEventLayout> {
    fleet: Arc<Fleet>,
    _layout: PhantomData<L>,
}

impl<L: EventLayout> Clone for FleetEventBus<L> {
    fn clone(&self) -> Self {
        Self { fleet: Arc::clone(&self.fleet), _layout: PhantomData }
    }
}

impl FleetEventBus<DefaultEventLayout> {
    /// A bus over the fleet's default event ring.
    pub fn new(fleet: Arc<Fleet>) -> Self {
        Self { fleet, _layout: PhantomData }
    }
}

impl<L: EventLayout> FleetEventBus<L> {
    /// Largest frame this bus can carry: the topic, the payload and the
    /// frame header together.
    pub const PAYLOAD_MAX: usize = L::RING_SPEC.payload_capacity;

    /// A bus over the ring named by `L`.
    pub fn with_layout(fleet: Arc<Fleet>) -> Result<Self> {
        layout::validate::<L>()?;
        Ok(Self { fleet, _layout: PhantomData })
    }

    pub fn node_id(&self) -> NodeId {
        self.fleet.node_id()
    }

    /// Cursor that starts after all events currently in the ring.
    /// Useful for subscribers that only want future events.
    pub fn cursor_at_head(&self) -> FleetEventCursor {
        FleetEventCursor {
            inner: self.fleet.lane_cursor_at_head::<EventRecord<L>>(),
        }
    }

    /// Cursor that starts at counter 0 and replays whatever history has
    /// not wrapped out of the ring.
    pub const fn cursor_from_start(&self) -> FleetEventCursor {
        let _ = self;
        FleetEventCursor::from_start()
    }

    /// Clear the shared event ring.
    ///
    /// Intended for owner-controlled boot-time cleanup before peer
    /// processes publish events into the ring. This prevents stale
    /// events from a previous process lifetime from being replayed or
    /// counted as current runtime state.
    pub fn reset_ring(&self) -> Result<()> {
        self.fleet.reset_ring::<EventRecord<L>>().map_err(Error::Io)
    }

    /// Create this process' native fd readiness bridge for the event ring.
    ///
    /// The returned fd is local to this process. Publishers notify a shared
    /// generation after committing an event; the bridge converts that
    /// broadcast into local fd readiness suitable for epoll/kqueue/AsyncFd.
    /// Drain the fd, then poll the ring with this subscriber's cursor.
    #[cfg(any(
        target_os = "linux",
        target_os = "freebsd",
        target_os = "macos"
    ))]
    pub fn event_fd(&self) -> Result<RingEventFd> {
        self.fleet.ring_event_fd::<EventRecord<L>>().map_err(Error::Io)
    }

    /// Publish one event under `topic`.
    pub fn publish(
        &self,
        topic: &str,
        payload: &[u8],
    ) -> Result<NetId64> {
        let timestamp = OrbitEpoch::now();
        let frame = encode_frame(
            topic.as_bytes(),
            payload,
            timestamp,
            Self::PAYLOAD_MAX,
        )?;
        #[cfg(any(
            target_os = "linux",
            target_os = "freebsd",
            target_os = "macos"
        ))]
        let id = self
            .fleet
            .publish_notified::<EventRecord<L>>(
                FRAME_KIND_EVENT,
                timestamp.as_unix_ms(),
                frame,
            )
            .map_err(Error::Io)?;
        #[cfg(not(any(
            target_os = "linux",
            target_os = "freebsd",
            target_os = "macos"
        )))]
        let id = self.fleet.publish::<EventRecord<L>>(
            FRAME_KIND_EVENT,
            timestamp.as_unix_ms(),
            frame,
        );
        Ok(id)
    }

    /// Poll all events since `cursor`, advancing the cursor to the
    /// current ring head. If the cursor has fallen behind the ring
    /// capacity, older overwritten counters are reported as `lagged`.
    pub fn poll(
        &self,
        cursor: &mut FleetEventCursor,
    ) -> FleetEventPoll {
        self.poll_where(cursor, |_| true)
    }

    /// Poll, building an event only for frames whose topic `keep` takes; a
    /// skipped frame costs a comparison, not a copy of its topic and payload.
    fn poll_where(
        &self,
        cursor: &mut FleetEventCursor,
        keep: impl Fn(&[u8]) -> bool,
    ) -> FleetEventPoll {
        let ring_poll =
            self.fleet.poll_lanes::<EventRecord<L>>(&mut cursor.inner);
        let mut lagged = ring_poll.loss.total();
        let mut events = Vec::new();
        for frame in ring_poll.frames {
            let Some(decoded) = decode_frame(&frame.payload) else {
                lagged = lagged.saturating_add(1);
                continue;
            };
            if !keep(decoded.topic) {
                continue;
            }
            events.push(FleetEvent {
                id: frame.id,
                topic: String::from_utf8_lossy(decoded.topic).into_owned(),
                payload: decoded.payload.to_vec(),
                timestamp_ms: decoded.timestamp.as_unix_ms(),
            });
        }

        FleetEventPoll { events, lagged }
    }

    /// Poll and keep only events whose topic matches `topic`.
    ///
    /// The cursor still advances past all events, including filtered
    /// topics. Use separate cursors for independent consumers.
    pub fn poll_topic(
        &self,
        cursor: &mut FleetEventCursor,
        topic: &str,
    ) -> FleetEventPoll {
        self.poll_where(cursor, |candidate| candidate == topic.as_bytes())
    }
}

struct DecodedFrame<'a> {
    topic: &'a [u8],
    payload: &'a [u8],
    timestamp: OrbitEpoch,
}

fn encode_frame(
    topic: &[u8],
    payload: &[u8],
    timestamp: OrbitEpoch,
    max_payload: usize,
) -> Result<Bytes> {
    let total = HEADER_LEN + topic.len() + payload.len();
    if topic.len() > u16::MAX as usize
        || payload.len() > u16::MAX as usize
        || total > max_payload
    {
        return Err(Error::FrameTooLarge {
            topic_len: topic.len(),
            payload_len: payload.len(),
            max_payload,
        });
    }

    let mut buf = BytesMut::with_capacity(total);
    buf.put_u16_le(topic.len() as u16);
    buf.put_u16_le(payload.len() as u16);
    buf.put_u64_le(timestamp.as_unix_ms());
    buf.put_slice(topic);
    buf.put_slice(payload);
    Ok(buf.freeze())
}

fn decode_frame(payload: &Bytes) -> Option<DecodedFrame<'_>> {
    if payload.len() < HEADER_LEN {
        return None;
    }

    let topic_len = u16::from_le_bytes(payload[0..2].try_into().ok()?) as usize;
    let payload_len =
        u16::from_le_bytes(payload[2..4].try_into().ok()?) as usize;
    let timestamp = OrbitEpoch::from_unix_ms(u64::from_le_bytes(
        payload[4..12].try_into().ok()?,
    ));
    let topic_start = HEADER_LEN;
    let topic_end = topic_start.checked_add(topic_len)?;
    let payload_end = topic_end.checked_add(payload_len)?;
    if payload.len() < payload_end {
        return None;
    }

    Some(DecodedFrame {
        topic: &payload[topic_start..topic_end],
        payload: &payload[topic_end..payload_end],
        timestamp,
    })
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use orbit_core::{Fleet, OrbitEpoch, RingSpec};

    use super::{EventLayout, FleetEventBus};

    struct WideLayout;

    impl EventLayout for WideLayout {
        const RING_KIND: u8 = 221;
        const RING_SPEC: RingSpec = RingSpec::per_node(16, 8_192);
    }

    #[test]
    fn polls_events_since_cursor() {
        let fleet = Arc::new(Fleet::join("event_poll", 1).expect("fleet"));
        let bus = FleetEventBus::new(fleet);
        let mut cursor = bus.cursor_from_start();

        bus.publish("worker.booted", b"w1").expect("publish first");
        bus.publish("cache.reset", b"all").expect("publish second");

        let poll = bus.poll(&mut cursor);
        assert_eq!(poll.lagged, 0);
        assert_eq!(poll.events.len(), 2);
        assert_eq!(poll.events[0].topic, "worker.booted");
        assert_eq!(poll.events[0].payload, b"w1");
        assert_eq!(poll.events[1].topic, "cache.reset");
        assert_eq!(poll.events[1].payload, b"all");

        assert!(bus.poll(&mut cursor).is_empty());
    }

    #[test]
    fn minimum_lane_next_counter_can_stay_zero_after_all_events_are_read() {
        let fleet = Arc::new(Fleet::join("event_lane_min", 2).expect("fleet"));
        let bus = FleetEventBus::new(fleet);
        let mut cursor = bus.cursor_from_start();

        for _ in 0..3 {
            bus.publish("test.event", b"payload").expect("publish");
        }

        let poll = bus.poll(&mut cursor);
        assert_eq!(poll.events.len(), 3);
        assert_eq!(poll.lagged, 0);
        assert_eq!(cursor.minimum_lane_next_counter(), 0);
        assert!(bus.poll(&mut cursor).is_empty());

        bus.publish("test.event", b"next").expect("publish");
        let poll = bus.poll(&mut cursor);
        assert_eq!(poll.events.len(), 1);
        assert_eq!(poll.events[0].payload, b"next");
        assert_eq!(poll.lagged, 0);
        assert_eq!(cursor.minimum_lane_next_counter(), 0);
    }

    #[test]
    fn cursor_at_head_only_reads_future_events() {
        let fleet = Arc::new(Fleet::join("event_head", 1).expect("fleet"));
        let bus = FleetEventBus::new(fleet);

        bus.publish("old", b"ignored").expect("publish old");
        let mut cursor = bus.cursor_at_head();
        bus.publish("new", b"seen").expect("publish new");

        let poll = bus.poll(&mut cursor);
        assert_eq!(poll.events.len(), 1);
        assert_eq!(poll.events[0].topic, "new");
    }

    #[test]
    fn topic_filter_advances_cursor() {
        let fleet = Arc::new(Fleet::join("event_topic", 1).expect("fleet"));
        let bus = FleetEventBus::new(fleet);
        let mut cursor = bus.cursor_from_start();

        bus.publish("a", b"1").expect("publish a");
        bus.publish("b", b"2").expect("publish b");

        let poll = bus.poll_topic(&mut cursor, "b");
        assert_eq!(poll.events.len(), 1);
        assert_eq!(poll.events[0].payload, b"2");
        assert!(bus.poll(&mut cursor).is_empty());
    }

    #[test]
    fn event_frame_contract_uses_the_compile_time_geometry() {
        let expected = orbit_core::compile::usize_from_env(
            option_env!("ORBIT_EVENT_RING_PAYLOAD_CAPACITY"),
            512,
        );
        assert_eq!(super::EVENT_PAYLOAD_MAX, expected);

        let largest_payload =
            vec![0_u8; super::EVENT_PAYLOAD_MAX - super::HEADER_LEN - 1];
        let frame = super::encode_frame(
            b"x",
            &largest_payload,
            OrbitEpoch::ZERO,
            expected,
        )
        .expect("frame must fit");
        assert_eq!(frame.len(), super::EVENT_PAYLOAD_MAX);

        let oversized_payload = vec![0_u8; largest_payload.len() + 1];
        assert!(matches!(
            super::encode_frame(b"x", &oversized_payload, OrbitEpoch::ZERO, expected),
            Err(super::Error::FrameTooLarge {
                max_payload,
                ..
            }) if max_payload == expected
        ));
    }

    #[test]
    fn reports_lag_when_cursor_falls_behind_capacity() {
        let fleet = Arc::new(Fleet::join("event_lag", 1).expect("fleet"));
        let bus = FleetEventBus::new(fleet);
        let mut cursor = bus.cursor_from_start();

        for value in 0..=super::EVENT_RING_SPEC.capacity {
            bus.publish("n", value.to_string().as_bytes())
                .expect("publish event");
        }

        let poll = bus.poll(&mut cursor);
        assert_eq!(poll.lagged, 1);
        assert_eq!(poll.events.len(), super::EVENT_RING_SPEC.capacity);
        assert_eq!(poll.events[0].payload, b"1");
    }

    #[test]
    fn a_second_layout_is_a_separate_ring_with_its_own_frame_size() {
        let fleet = Arc::new(Fleet::join("event_layout", 1).expect("fleet"));
        let fleet_bus = FleetEventBus::new(Arc::clone(&fleet));
        let wide_bus =
            FleetEventBus::<WideLayout>::with_layout(fleet).expect("layout");
        let mut fleet_cursor = fleet_bus.cursor_from_start();
        let mut wide_cursor = wide_bus.cursor_from_start();

        let wide_payload = vec![7_u8; super::EVENT_PAYLOAD_MAX];
        assert!(fleet_bus.publish("wide", &wide_payload).is_err());
        wide_bus.publish("wide", &wide_payload).expect("wide frame fits");
        fleet_bus.publish("small", b"1").expect("small frame fits");

        let wide = wide_bus.poll(&mut wide_cursor);
        assert_eq!(wide.events.len(), 1);
        assert_eq!(wide.events[0].payload, wide_payload);

        let small = fleet_bus.poll(&mut fleet_cursor);
        assert_eq!(small.events.len(), 1);
        assert_eq!(small.events[0].topic, "small");
    }
}