blitz_control_protocol/
journal.rs1use std::collections::VecDeque;
2use std::sync::{Arc, Mutex};
3
4use nagoya::sync::Notify;
5
6use crate::{DebugEvent, DiagnosticRecord, TargetContext};
7
8#[derive(Clone, Debug, PartialEq)]
9pub enum JournalItem {
10 Event(Arc<DiagnosticRecord>),
11 Overflow { first: u64, last: u64 },
12}
13
14impl JournalItem {
15 pub fn sequence(&self) -> u64 {
16 match self {
17 Self::Event(event) => event.sequence,
18 Self::Overflow { last, .. } => *last,
19 }
20 }
21}
22
23#[derive(Default)]
24struct State {
25 sequence: u64,
26 records: VecDeque<Arc<DiagnosticRecord>>,
27}
28
29pub struct DiagnosticJournal {
30 capacity: usize,
31 state: Mutex<State>,
32 changed: Notify,
33}
34
35impl DiagnosticJournal {
36 pub fn new(capacity: usize) -> Arc<Self> {
37 assert!(capacity > 0);
38 Arc::new(Self {
39 capacity,
40 state: Mutex::new(State::default()),
41 changed: Notify::new(),
42 })
43 }
44
45 pub fn publish(&self, context: TargetContext, event: DebugEvent) {
46 let mut state = self.state.lock().unwrap();
47 state.sequence = state
48 .sequence
49 .checked_add(1)
50 .expect("diagnostic sequence exhausted");
51 let sequence = state.sequence;
52 if state.records.len() == self.capacity {
53 state.records.pop_front();
54 }
55 state.records.push_back(Arc::new(DiagnosticRecord {
56 context,
57 sequence,
58 event,
59 }));
60 drop(state);
61 self.changed.notify_waiters();
62 }
63
64 pub fn sequence(&self) -> u64 {
65 self.state.lock().unwrap().sequence
66 }
67
68 pub fn read_after(&self, seen: u64) -> Option<JournalItem> {
69 let state = self.state.lock().unwrap();
70 let first = state.records.front()?.sequence;
71 if seen < first - 1 {
72 return Some(JournalItem::Overflow {
73 first: seen + 1,
74 last: first - 1,
75 });
76 }
77 state
78 .records
79 .iter()
80 .find(|record| record.sequence > seen)
81 .cloned()
82 .map(JournalItem::Event)
83 }
84
85 pub async fn next_after(&self, seen: u64) -> JournalItem {
86 loop {
87 let notified = self.changed.notified();
88 futures::pin_mut!(notified);
89 let ready = notified.as_mut().enable();
90 if let Some(item) = self.read_after(seen) {
91 return item;
92 }
93 if !ready {
94 notified.await;
95 }
96 }
97 }
98}