Skip to main content

labstream_net/
history.rs

1//! The history of an outlet for the `resume` feature (`docs/extensions.md`,
2//! section `resume`) and disk-backed store-and-forward (`docs/roadmap.md`,
3//! step 3).
4//!
5//! The history holds the last samples of the outlet, with full timestamps,
6//! in the order of their `seq` numbers. A consumer that connects again after
7//! a dropout gets the samples that it did not receive from here.
8//!
9//! When `disk_bytes > 0` (`labstream.ResumeDisk`), samples evicted from RAM
10//! spill into bounded immutable segment files on disk. Reading a segment
11//! during a resend happens outside the `Fanout` lock so live pushes and
12//! other consumers do not wait on disk I/O. Every spool file is removed when
13//! the segment ages out or when the outlet closes.
14//!
15//! liblsl has no history. Its outlet makes an empty queue for each new
16//! connection (`src/tcp_server.cpp:746`, `src/consumer_queue.cpp:10-20`).
17
18use labstream_wire::{Format, PackedSample, PackedValues, Sample, Value, IRREGULAR_RATE};
19use std::collections::VecDeque;
20use std::fs::{self, File};
21use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
22use std::path::{Path, PathBuf};
23use std::sync::{Arc, Mutex};
24
25/// The bytes that the history counts for each sample: the timestamp and the
26/// number.
27const SAMPLE_BYTES: usize = 16;
28
29/// The bytes that the history counts for one value in the legacy [`Sample`]
30/// representation, retained for [`sample_bytes`].
31const VALUE_BYTES: usize = std::mem::size_of::<Value>();
32
33/// Sparse byte-offset index stride inside one disk segment, in samples.
34const INDEX_STRIDE: usize = 256;
35
36/// On-disk per-record header size: `seq (8) + ts (8) + fmt (1) + len (4)`.
37const RECORD_HEADER_BYTES: usize = 21;
38
39/// The limits of a history. The history removes its oldest samples when it
40/// reaches them.
41#[derive(Debug, Clone, PartialEq)]
42pub struct HistoryLimits {
43    /// The time of samples at the nominal rate. `labstream.ResumeSeconds`.
44    /// The value 0 turns the history off.
45    pub seconds: f64,
46    /// The memory limit in bytes. `labstream.ResumeMemory`, which is in MiB.
47    pub bytes: usize,
48    /// The disk spool limit in bytes. `labstream.ResumeDisk`, which is in MiB.
49    /// Zero keeps the history in memory only (the default).
50    pub disk_bytes: u64,
51    /// Optional directory for disk spool files (`labstream.ResumeDiskPath`).
52    /// `None` uses the system temporary directory.
53    pub disk_dir: Option<PathBuf>,
54}
55
56impl HistoryLimits {
57    /// The defaults of `docs/extensions.md`: 30 s, 64 MiB RAM, no disk spool.
58    ///
59    /// A cut of 10 s, plus the time to connect again, gave a gap of about
60    /// 11.8 s in the lossy-link benchmark (`docs/roadmap.md`, step 0). A
61    /// default of 10 s lost the oldest samples of that gap.
62    pub const DEFAULT: HistoryLimits = HistoryLimits {
63        seconds: 30.0,
64        bytes: 64 << 20,
65        disk_bytes: 0,
66        disk_dir: None,
67    };
68
69    /// A history with these limits holds no sample.
70    pub const OFF: HistoryLimits = HistoryLimits {
71        seconds: 0.0,
72        bytes: 0,
73        disk_bytes: 0,
74        disk_dir: None,
75    };
76
77    /// True when these limits let a history hold a sample.
78    pub fn allow_history(&self) -> bool {
79        self.seconds > 0.0 && (self.bytes > 0 || self.disk_bytes > 0)
80    }
81
82    /// The count of samples that the time limit allows at a nominal rate.
83    ///
84    /// A stream with an irregular rate, or an infinite time limit, has no
85    /// count limit and uses the memory and disk limits only.
86    fn max_samples(&self, srate: f64) -> usize {
87        if srate == IRREGULAR_RATE || !srate.is_finite() || srate < 0.0 || !self.seconds.is_finite()
88        {
89            return usize::MAX;
90        }
91        let n = (self.seconds * srate).ceil();
92        if n >= usize::MAX as f64 {
93            usize::MAX
94        } else {
95            (n as usize).max(1)
96        }
97    }
98}
99
100impl Default for HistoryLimits {
101    fn default() -> Self {
102        HistoryLimits::DEFAULT
103    }
104}
105
106/// The memory that the history counts for one sample.
107///
108/// The count is 16 bytes, plus the size of a `Value` for each channel, plus
109/// the bytes of each string value. `docs/extensions.md`, history rule 5.
110pub fn sample_bytes(s: &Sample) -> usize {
111    let strings: usize = s
112        .values
113        .iter()
114        .map(|v| match v {
115            Value::Str(b) => b.len(),
116            _ => 0,
117        })
118        .sum();
119    SAMPLE_BYTES + VALUE_BYTES * s.values.len() + strings
120}
121
122/// The memory that the history counts for one [`PackedSample`].
123///
124/// For numeric streams, this is `16 + channels * format_width` (272 bytes
125/// for 64 `f32` channels instead of 2064 bytes with `Vec<Value>`).
126pub fn packed_sample_bytes(s: &PackedSample) -> usize {
127    SAMPLE_BYTES + s.payload_bytes()
128}
129
130/// Owns a per-outlet temporary spool directory and deletes it on drop.
131///
132/// Each [`SegmentFile`] holds an `Arc<SpoolDir>` so the directory disappears
133/// only after the last segment file closes and unlinks cleanly on Linux,
134/// Windows, and macOS.
135#[derive(Debug)]
136struct SpoolDir {
137    path: PathBuf,
138}
139
140impl Drop for SpoolDir {
141    fn drop(&mut self) {
142        let _ = fs::remove_dir_all(&self.path);
143    }
144}
145
146/// Owns one on-disk segment file and removes it once no reader holds it.
147#[derive(Debug)]
148struct SegmentFile {
149    path: PathBuf,
150    _dir: Arc<SpoolDir>,
151}
152
153impl Drop for SegmentFile {
154    fn drop(&mut self) {
155        let _ = fs::remove_file(&self.path);
156    }
157}
158
159/// Metadata for one contiguous range of numbered samples in a segment file.
160#[derive(Debug)]
161struct Segment {
162    file: Arc<SegmentFile>,
163    first: u64,
164    len: usize,
165    bytes: u64,
166    /// Sparse `(sample_seq, file_byte_offset)` entries every `INDEX_STRIDE`.
167    index: Vec<(u64, u64)>,
168}
169
170impl Segment {
171    fn next_seq(&self) -> u64 {
172        self.first.wrapping_add(self.len as u64)
173    }
174
175    fn seek_offset_for(&self, seq: u64) -> u64 {
176        let target = seq.wrapping_sub(self.first);
177        let pos = self
178            .index
179            .partition_point(|&(s, _)| s.wrapping_sub(self.first) <= target);
180        if pos == 0 {
181            0
182        } else {
183            self.index[pos - 1].1
184        }
185    }
186}
187
188#[derive(Debug)]
189struct ActiveSegment {
190    seg: Segment,
191    writer: BufWriter<File>,
192}
193
194/// Bounded ring of segment files on disk.
195#[derive(Debug)]
196struct DiskSpool {
197    dir: Arc<SpoolDir>,
198    next_seg_id: u64,
199    sealed: VecDeque<Segment>,
200    active: Option<ActiveSegment>,
201    total_bytes: u64,
202    total_samples: usize,
203    max_bytes: u64,
204    segment_target_bytes: u64,
205}
206
207impl DiskSpool {
208    fn create(base_dir: Option<&Path>, max_bytes: u64) -> std::io::Result<Self> {
209        let root = match base_dir {
210            Some(p) => p.to_path_buf(),
211            None => std::env::temp_dir(),
212        };
213        let r = crate::random_bytes();
214        let tag = u64::from_le_bytes([r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7]]);
215        let path = root.join(format!("labstream-spool-{}-{tag:016x}", std::process::id()));
216        fs::create_dir_all(&path)?;
217        // Aim for ~8 segments so eviction drops small chunks without creating
218        // thousands of files. Clamp between 32 KiB and 16 MiB, never above max_bytes.
219        let target = (max_bytes / 8)
220            .clamp(32 * 1024, 16 * 1024 * 1024)
221            .min(max_bytes.max(1));
222        Ok(DiskSpool {
223            dir: Arc::new(SpoolDir { path }),
224            next_seg_id: 0,
225            sealed: VecDeque::new(),
226            active: None,
227            total_bytes: 0,
228            total_samples: 0,
229            max_bytes,
230            segment_target_bytes: target,
231        })
232    }
233
234    fn oldest(&self) -> Option<u64> {
235        if let Some(s) = self.sealed.front() {
236            Some(s.first)
237        } else {
238            self.active.as_ref().map(|a| a.seg.first)
239        }
240    }
241
242    fn seal_active(&mut self) {
243        if let Some(mut act) = self.active.take() {
244            let _ = act.writer.flush();
245            drop(act.writer);
246            if act.seg.len > 0 {
247                self.sealed.push_back(act.seg);
248            }
249        }
250    }
251
252    fn append(&mut self, seq: u64, s: &PackedSample) -> std::io::Result<()> {
253        let rec_bytes = encoded_record_len(s) as u64;
254        if rec_bytes > self.max_bytes {
255            self.clear();
256            return Ok(());
257        }
258        // Seal current segment if adding this record crosses the segment target.
259        if let Some(act) = &self.active {
260            if act.seg.len > 0 && act.seg.bytes + rec_bytes > self.segment_target_bytes {
261                self.seal_active();
262            }
263        }
264        if self.active.is_none() {
265            let id = self.next_seg_id;
266            self.next_seg_id += 1;
267            let path = self.dir.path.join(format!("seg-{id:08}.bin"));
268            let file = File::create(&path)?;
269            let seg = Segment {
270                file: Arc::new(SegmentFile {
271                    path,
272                    _dir: Arc::clone(&self.dir),
273                }),
274                first: seq,
275                len: 0,
276                bytes: 0,
277                index: Vec::new(),
278            };
279            self.active = Some(ActiveSegment {
280                seg,
281                writer: BufWriter::with_capacity(64 * 1024, file),
282            });
283        }
284        let act = self.active.as_mut().unwrap();
285        if act.seg.len % INDEX_STRIDE == 0 {
286            act.seg.index.push((seq, act.seg.bytes));
287        }
288        let written = write_record(&mut act.writer, seq, s)? as u64;
289        act.seg.len += 1;
290        act.seg.bytes += written;
291        self.total_bytes += written;
292        self.total_samples += 1;
293        self.trim_to_limits(usize::MAX);
294        Ok(())
295    }
296
297    fn trim_to_limits(&mut self, max_disk_samples: usize) {
298        while let Some(front) = self.sealed.front() {
299            let over_bytes = self.total_bytes > self.max_bytes;
300            let over_samples = self.total_samples > max_disk_samples;
301            if !over_bytes && !over_samples {
302                break;
303            }
304            let drop_bytes = front.bytes;
305            let drop_len = front.len;
306            self.sealed.pop_front();
307            self.total_bytes -= drop_bytes;
308            self.total_samples -= drop_len;
309        }
310        // If even with no sealed segments the active segment exceeds max_bytes,
311        // drop it so total disk bytes never exceed the limit.
312        if self.total_bytes > self.max_bytes {
313            self.clear();
314        }
315    }
316
317    fn clear(&mut self) {
318        self.active = None;
319        self.sealed.clear();
320        self.total_bytes = 0;
321        self.total_samples = 0;
322    }
323
324    /// Seal any active segment if needed and build a lock-free [`DiskReadPlan`]
325    /// starting at `from` (clamped up to `oldest`) and stopping below `until`.
326    fn plan_read(&mut self, from: u64, until: u64, max: usize) -> Option<DiskReadPlan> {
327        let oldest = self.oldest()?;
328        // Seal active segment if the requested start falls inside it so that
329        // the file is flushed and immutable for concurrent readers.
330        if let Some(act) = &self.active {
331            let d_from = from.wrapping_sub(act.seg.first);
332            if d_from < act.seg.len as u64 {
333                self.seal_active();
334            }
335        }
336        // Find the first sealed segment whose range overlaps `[from, until)`.
337        let d_until = until.wrapping_sub(oldest);
338        if d_until == 0 || d_until > u64::MAX / 2 || max == 0 {
339            return None;
340        }
341        let target_from = if from.wrapping_sub(oldest) > u64::MAX / 2 {
342            oldest
343        } else {
344            from
345        };
346        let seg = self.sealed.iter().find(|seg| {
347            let d = target_from.wrapping_sub(seg.first);
348            d < seg.len as u64
349        })?;
350        let start_seq = target_from;
351        let seg_rem = seg.next_seq().wrapping_sub(start_seq);
352        let req_rem = until.wrapping_sub(start_seq);
353        if req_rem == 0 || req_rem > u64::MAX / 2 {
354            return None;
355        }
356        let count = (seg_rem.min(req_rem) as usize).min(max);
357        if count == 0 {
358            return None;
359        }
360        Some(DiskReadPlan {
361            file: Arc::clone(&seg.file),
362            start_offset: seg.seek_offset_for(start_seq),
363            start_seq,
364            count,
365        })
366    }
367}
368
369/// A self-contained disk read that executes outside the `Fanout` lock so
370/// resending old samples from disk never delays live consumers.
371#[derive(Debug)]
372pub(crate) struct DiskReadPlan {
373    file: Arc<SegmentFile>,
374    start_offset: u64,
375    start_seq: u64,
376    count: usize,
377}
378
379impl DiskReadPlan {
380    /// Read the planned samples from disk into `out`.
381    pub(crate) fn execute(self, out: &mut Vec<PackedSample>) -> Option<(u64, usize)> {
382        let mut f = File::open(&self.file.path).ok()?;
383        f.seek(SeekFrom::Start(self.start_offset)).ok()?;
384        let mut reader = BufReader::with_capacity(64 * 1024, f);
385        let mut read = 0usize;
386        while read < self.count {
387            let (seq, sample) = read_record(&mut reader).ok()?;
388            let dist = seq.wrapping_sub(self.start_seq);
389            if dist > u64::MAX / 2 {
390                // Still before `start_seq` within the index stride.
391                continue;
392            }
393            if dist >= self.count as u64 {
394                break;
395            }
396            out.push(sample);
397            read += 1;
398        }
399        if read == 0 {
400            None
401        } else {
402            Some((self.start_seq, read))
403        }
404    }
405}
406
407/// Result of planning a history read under the `Fanout` lock.
408#[derive(Debug)]
409pub(crate) enum HistoryRead {
410    /// No sample available in `[from, until)`.
411    Empty,
412    /// Samples were copied from RAM directly into `out`.
413    Ready {
414        /// Sequence number of the first sample appended to `out`.
415        first: u64,
416        /// Count of samples appended to `out`.
417        count: usize,
418    },
419    /// Samples live on disk; execute this plan after releasing the lock.
420    Disk(DiskReadPlan),
421}
422
423fn encoded_record_len(s: &PackedSample) -> usize {
424    let payload = match &s.values {
425        PackedValues::Numeric { bytes, .. } => bytes.len(),
426        PackedValues::Strings(list) => 4 + list.iter().map(|b| 4 + b.len()).sum::<usize>(),
427    };
428    RECORD_HEADER_BYTES + payload
429}
430
431fn write_record<W: Write>(w: &mut W, seq: u64, s: &PackedSample) -> std::io::Result<usize> {
432    match &s.values {
433        PackedValues::Numeric { format, bytes } => {
434            let payload_len = bytes.len() as u32;
435            let mut hdr = [0u8; RECORD_HEADER_BYTES];
436            hdr[0..8].copy_from_slice(&seq.to_le_bytes());
437            hdr[8..16].copy_from_slice(&s.timestamp.to_le_bytes());
438            hdr[16] = *format as u8;
439            hdr[17..21].copy_from_slice(&payload_len.to_le_bytes());
440            w.write_all(&hdr)?;
441            w.write_all(bytes)?;
442            Ok(RECORD_HEADER_BYTES + bytes.len())
443        }
444        PackedValues::Strings(list) => {
445            let payload_len: usize = 4 + list.iter().map(|b| 4 + b.len()).sum::<usize>();
446            let mut hdr = [0u8; RECORD_HEADER_BYTES];
447            hdr[0..8].copy_from_slice(&seq.to_le_bytes());
448            hdr[8..16].copy_from_slice(&s.timestamp.to_le_bytes());
449            hdr[16] = Format::String as u8;
450            hdr[17..21].copy_from_slice(&(payload_len as u32).to_le_bytes());
451            w.write_all(&hdr)?;
452            w.write_all(&(list.len() as u32).to_le_bytes())?;
453            for b in list.iter() {
454                w.write_all(&(b.len() as u32).to_le_bytes())?;
455                w.write_all(b)?;
456            }
457            Ok(RECORD_HEADER_BYTES + payload_len)
458        }
459    }
460}
461
462fn read_record<R: Read>(r: &mut R) -> std::io::Result<(u64, PackedSample)> {
463    let mut hdr = [0u8; RECORD_HEADER_BYTES];
464    r.read_exact(&mut hdr)?;
465    let seq = u64::from_le_bytes(hdr[0..8].try_into().unwrap());
466    let timestamp = f64::from_le_bytes(hdr[8..16].try_into().unwrap());
467    let format = Format::from_u8(hdr[16])
468        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "bad format byte"))?;
469    let payload_len = u32::from_le_bytes(hdr[17..21].try_into().unwrap()) as usize;
470    if format == Format::String {
471        let mut buf = vec![0u8; payload_len];
472        r.read_exact(&mut buf)?;
473        if buf.len() < 4 {
474            return Err(std::io::Error::new(
475                std::io::ErrorKind::UnexpectedEof,
476                "truncated string sample",
477            ));
478        }
479        let count = u32::from_le_bytes(buf[0..4].try_into().unwrap()) as usize;
480        let mut pos = 4usize;
481        let mut strings = Vec::with_capacity(count);
482        for _ in 0..count {
483            if pos + 4 > buf.len() {
484                return Err(std::io::Error::new(
485                    std::io::ErrorKind::UnexpectedEof,
486                    "truncated string length",
487                ));
488            }
489            let len = u32::from_le_bytes(buf[pos..pos + 4].try_into().unwrap()) as usize;
490            pos += 4;
491            if pos + len > buf.len() {
492                return Err(std::io::Error::new(
493                    std::io::ErrorKind::UnexpectedEof,
494                    "truncated string bytes",
495                ));
496            }
497            strings.push(buf[pos..pos + len].to_vec());
498            pos += len;
499        }
500        Ok((seq, PackedSample::from_strings(timestamp, strings)))
501    } else {
502        let mut buf = vec![0u8; payload_len];
503        r.read_exact(&mut buf)?;
504        Ok((
505            seq,
506            PackedSample::from_raw_bytes(timestamp, format, Arc::from(buf)),
507        ))
508    }
509}
510
511/// The last samples of an outlet, with their numbers.
512///
513/// The samples have the numbers `back - len .. back`, with no gap. The
514/// owner gives the number of each sample at the push, and the history
515/// removes samples only from the front.
516#[derive(Debug)]
517pub struct History {
518    samples: VecDeque<PackedSample>,
519    back: u64,
520    bytes: usize,
521    max_samples: usize,
522    max_bytes: usize,
523    disk_max_bytes: u64,
524    disk_dir: Option<PathBuf>,
525    /// Disk spool created lazily when RAM fills and `disk_max_bytes > 0`.
526    /// Wrapped in `Mutex` so `read_packed(&self)` can seal an active segment
527    /// when a consumer asks for disk-spilled samples, while `push_packed(&mut self)`
528    /// uses `get_mut()` with zero lock overhead.
529    spool: Option<Mutex<DiskSpool>>,
530}
531
532impl History {
533    /// Build an empty history. The next sample gets the number `next`.
534    pub fn new(limits: HistoryLimits, srate: f64, next: u64) -> History {
535        History {
536            samples: VecDeque::new(),
537            back: next,
538            bytes: 0,
539            max_samples: limits.max_samples(srate),
540            max_bytes: limits.bytes,
541            disk_max_bytes: limits.disk_bytes,
542            disk_dir: limits.disk_dir,
543            spool: None,
544        }
545    }
546
547    /// How many samples the history holds across RAM and disk.
548    pub fn len(&self) -> usize {
549        self.samples.len() + self.disk_samples()
550    }
551
552    /// True when the history holds no sample in RAM or on disk.
553    pub fn is_empty(&self) -> bool {
554        self.len() == 0
555    }
556
557    /// The memory that the history holds in RAM now, in bytes.
558    pub fn bytes(&self) -> usize {
559        self.bytes
560    }
561
562    /// The bytes stored in disk spool segments now. Zero when disk spooling is off
563    /// or has not spilled yet.
564    pub fn disk_bytes(&self) -> u64 {
565        self.spool
566            .as_ref()
567            .map_or(0, |s| s.lock().unwrap().total_bytes)
568    }
569
570    /// Path of the active spool directory, if disk spilling has started.
571    pub fn spool_dir(&self) -> Option<PathBuf> {
572        self.spool
573            .as_ref()
574            .map(|s| s.lock().unwrap().dir.path.clone())
575    }
576
577    fn disk_samples(&self) -> usize {
578        self.spool
579            .as_ref()
580            .map_or(0, |s| s.lock().unwrap().total_samples)
581    }
582
583    fn ram_oldest(&self) -> u64 {
584        self.back.wrapping_sub(self.samples.len() as u64)
585    }
586
587    /// The number of the oldest sample across disk and RAM. With no sample,
588    /// the number that the next sample gets.
589    pub fn oldest(&self) -> u64 {
590        self.back.wrapping_sub(self.len() as u64)
591    }
592
593    /// The number that the next sample gets.
594    pub fn next(&self) -> u64 {
595        self.back
596    }
597
598    /// Add one sample. Its timestamp must be a full timestamp, not the
599    /// deduced tag.
600    ///
601    /// The history then removes its oldest samples (or spills them to disk
602    /// when `disk_bytes > 0`) until it is in its limits.
603    pub fn push(&mut self, s: Sample) {
604        self.push_packed(PackedSample::from(s));
605    }
606
607    /// Add one [`PackedSample`] without copying its `Arc` payload.
608    pub fn push_packed(&mut self, s: PackedSample) {
609        debug_assert!(s.timestamp != labstream_wire::DEDUCED_TIMESTAMP);
610        let seq = self.back;
611        self.back = self.back.wrapping_add(1);
612        let size = packed_sample_bytes(&s);
613        if self.max_samples == 0 {
614            self.clear_all();
615            return;
616        }
617        if self.disk_max_bytes == 0 {
618            if size > self.max_bytes {
619                self.samples.clear();
620                self.bytes = 0;
621                return;
622            }
623            self.bytes += size;
624            self.samples.push_back(s);
625            while self.samples.len() > self.max_samples || self.bytes > self.max_bytes {
626                match self.samples.pop_front() {
627                    Some(old) => self.bytes -= packed_sample_bytes(&old),
628                    None => break,
629                }
630            }
631            return;
632        }
633
634        // Disk-backed mode: keep newest samples in RAM up to `max_bytes`,
635        // spilling older samples into bounded segment files on disk.
636        if size > self.max_bytes {
637            // Spill all buffered RAM first so sequence order on disk stays contiguous,
638            // then spill this oversized sample directly to disk.
639            self.spill_from_ram(self.samples.len());
640            self.append_to_spool(seq, &s);
641            self.enforce_total_sample_limit();
642            return;
643        }
644        self.bytes += size;
645        self.samples.push_back(s);
646        if self.bytes > self.max_bytes {
647            // Spill enough oldest samples to bring RAM down to ~75% of max_bytes
648            // so disk appends happen in amortized batches while RAM stays <= max_bytes.
649            let target = self.max_bytes.saturating_mul(3) / 4;
650            let mut to_spill = 0usize;
651            let mut freed = 0usize;
652            for item in &self.samples {
653                if self.bytes.saturating_sub(freed) <= target && to_spill > 0 {
654                    break;
655                }
656                freed += packed_sample_bytes(item);
657                to_spill += 1;
658                if self.bytes.saturating_sub(freed) <= self.max_bytes
659                    && to_spill == self.samples.len()
660                {
661                    break;
662                }
663            }
664            self.spill_from_ram(to_spill.max(1));
665        }
666        self.enforce_total_sample_limit();
667    }
668
669    fn clear_all(&mut self) {
670        self.samples.clear();
671        self.bytes = 0;
672        if let Some(sp) = self.spool.as_mut() {
673            sp.get_mut().unwrap().clear();
674        }
675    }
676
677    fn ensure_spool(&mut self) -> Option<&mut DiskSpool> {
678        if self.spool.is_none() {
679            match DiskSpool::create(self.disk_dir.as_deref(), self.disk_max_bytes) {
680                Ok(sp) => self.spool = Some(Mutex::new(sp)),
681                Err(_) => return None,
682            }
683        }
684        Some(self.spool.as_mut().unwrap().get_mut().unwrap())
685    }
686
687    fn append_to_spool(&mut self, seq: u64, sample: &PackedSample) {
688        if let Some(sp) = self.ensure_spool() {
689            if sp.append(seq, sample).is_err() {
690                sp.clear();
691            }
692        }
693    }
694
695    fn spill_from_ram(&mut self, count: usize) {
696        let count = count.min(self.samples.len());
697        if count == 0 {
698            return;
699        }
700        let mut next_seq = self.ram_oldest();
701        let mut evicted = Vec::with_capacity(count);
702        for _ in 0..count {
703            if let Some(old) = self.samples.pop_front() {
704                self.bytes -= packed_sample_bytes(&old);
705                evicted.push((next_seq, old));
706                next_seq = next_seq.wrapping_add(1);
707            }
708        }
709        if let Some(sp) = self.ensure_spool() {
710            for (seq, sample) in &evicted {
711                if sp.append(*seq, sample).is_err() {
712                    sp.clear();
713                    break;
714                }
715            }
716        }
717    }
718
719    fn enforce_total_sample_limit(&mut self) {
720        if self.max_samples == usize::MAX {
721            return;
722        }
723        let ram_len = self.samples.len();
724        if let Some(sp) = self.spool.as_mut() {
725            let max_disk = self.max_samples.saturating_sub(ram_len);
726            sp.get_mut().unwrap().trim_to_limits(max_disk);
727        }
728        while self.samples.len() > self.max_samples {
729            if let Some(old) = self.samples.pop_front() {
730                self.bytes -= packed_sample_bytes(&old);
731            }
732            if let Some(sp) = self.spool.as_mut() {
733                sp.get_mut().unwrap().clear();
734            }
735        }
736    }
737
738    /// Copy at most `max` samples to the end of `out`, from the number
739    /// `from`, and below the number `until`, in order.
740    ///
741    /// `until` is the first number that a consumer queue holds. The history
742    /// also holds the samples from that number, so without the bound a
743    /// resend gives a sample twice. `docs/extensions.md`, resend rule 5.
744    ///
745    /// If `from` is below the oldest number, the copy starts at the oldest
746    /// number. The result is the number of the first copied sample, and the
747    /// count of copied samples. With no copied sample, the result is `None`.
748    pub fn read(
749        &self,
750        from: u64,
751        until: u64,
752        max: usize,
753        out: &mut Vec<Sample>,
754    ) -> Option<(u64, usize)> {
755        let mut packed = Vec::new();
756        let res = self.read_packed(from, until, max, &mut packed)?;
757        out.extend(packed.iter().map(PackedSample::to_sample));
758        Some(res)
759    }
760
761    /// Plan a read of at most `max` packed samples from `from` below `until`.
762    ///
763    /// Samples in RAM are cloned into `out` immediately. Samples on disk
764    /// return a [`DiskReadPlan`] that the caller runs after releasing the
765    /// `Fanout` lock.
766    pub(crate) fn plan_read_packed(
767        &self,
768        from: u64,
769        until: u64,
770        max: usize,
771        out: &mut Vec<PackedSample>,
772    ) -> HistoryRead {
773        if max == 0 {
774            return HistoryRead::Empty;
775        }
776        let oldest = self.oldest();
777        let total_len = self.len() as u64;
778        if total_len == 0 {
779            return HistoryRead::Empty;
780        }
781        let position = |n: u64| -> u64 {
782            let d = n.wrapping_sub(oldest);
783            if d > u64::MAX / 2 {
784                0
785            } else {
786                d.min(total_len)
787            }
788        };
789        let start_rel = position(from);
790        let end_rel = position(until);
791        if start_rel >= end_rel {
792            return HistoryRead::Empty;
793        }
794        let start_seq = oldest.wrapping_add(start_rel);
795        let ram_oldest = self.ram_oldest();
796        let disk_len = ram_oldest.wrapping_sub(oldest);
797
798        // If `start_rel` is in the disk portion, serve one contiguous block
799        // from the matching disk segment outside the Fanout lock.
800        if start_rel < disk_len {
801            if let Some(sp) = self.spool.as_ref() {
802                let disk_until = oldest.wrapping_add(end_rel.min(disk_len));
803                if let Some(plan) = sp.lock().unwrap().plan_read(start_seq, disk_until, max) {
804                    return HistoryRead::Disk(plan);
805                }
806            }
807            // Fall through to RAM if the disk segment could not be planned.
808        }
809
810        // Serve from RAM.
811        let ram_len = self.samples.len() as u64;
812        let ram_pos = |n: u64| -> u64 {
813            let d = n.wrapping_sub(ram_oldest);
814            if d > u64::MAX / 2 {
815                0
816            } else {
817                d.min(ram_len)
818            }
819        };
820        let r_start = ram_pos(start_seq);
821        let r_end = ram_pos(until);
822        if r_start >= r_end {
823            return HistoryRead::Empty;
824        }
825        let count = ((r_end - r_start) as usize).min(max);
826        out.extend(
827            self.samples
828                .range(r_start as usize..r_start as usize + count)
829                .cloned(),
830        );
831        HistoryRead::Ready {
832            first: ram_oldest.wrapping_add(r_start),
833            count,
834        }
835    }
836
837    /// Share at most `max` packed samples to the end of `out` (`Arc` clone
838    /// for RAM samples, or direct read from disk segment), from `from` and
839    /// below `until`.
840    pub fn read_packed(
841        &self,
842        from: u64,
843        until: u64,
844        max: usize,
845        out: &mut Vec<PackedSample>,
846    ) -> Option<(u64, usize)> {
847        match self.plan_read_packed(from, until, max, out) {
848            HistoryRead::Empty => None,
849            HistoryRead::Ready { first, count } => Some((first, count)),
850            HistoryRead::Disk(plan) => plan.execute(out),
851        }
852    }
853}
854
855#[cfg(test)]
856mod tests {
857    use super::*;
858
859    fn sample(i: u64) -> Sample {
860        Sample {
861            timestamp: i as f64,
862            values: vec![Value::F32(i as f32)],
863        }
864    }
865
866    fn numbers(out: &[Sample]) -> Vec<u64> {
867        out.iter().map(|s| s.timestamp as u64).collect()
868    }
869
870    #[test]
871    fn the_time_limit_keeps_the_newest_samples() {
872        let limits = HistoryLimits {
873            seconds: 1.0,
874            bytes: usize::MAX,
875            ..HistoryLimits::DEFAULT
876        };
877        let mut h = History::new(limits, 100.0, 0);
878        for i in 0..250 {
879            h.push(sample(i));
880        }
881        assert_eq!(h.len(), 100);
882        assert_eq!(h.oldest(), 150);
883        assert_eq!(h.next(), 250);
884    }
885
886    #[test]
887    fn the_memory_limit_keeps_the_newest_samples() {
888        let one = packed_sample_bytes(&PackedSample::from(sample(0)));
889        assert_eq!(one, 16 + 4);
890        let limits = HistoryLimits {
891            seconds: 1000.0,
892            bytes: 10 * one,
893            ..HistoryLimits::DEFAULT
894        };
895        let mut h = History::new(limits, 100.0, 0);
896        for i in 0..25 {
897            h.push(sample(i));
898        }
899        assert_eq!(h.len(), 10);
900        assert_eq!(h.bytes(), 10 * one);
901        assert_eq!(h.oldest(), 15);
902    }
903
904    #[test]
905    fn an_irregular_stream_uses_the_memory_limit_only() {
906        let one = packed_sample_bytes(&PackedSample::from(sample(0)));
907        let limits = HistoryLimits {
908            seconds: 0.001,
909            bytes: 50 * one,
910            ..HistoryLimits::DEFAULT
911        };
912        let mut h = History::new(limits, IRREGULAR_RATE, 0);
913        for i in 0..80 {
914            h.push(sample(i));
915        }
916        assert_eq!(h.len(), 50);
917    }
918
919    #[test]
920    fn a_string_counts_its_bytes() {
921        let marker = |text: &str| Sample {
922            timestamp: 1.0,
923            values: vec![Value::Str(text.as_bytes().to_vec())],
924        };
925        assert_eq!(sample_bytes(&marker("")), 16 + VALUE_BYTES);
926        assert_eq!(sample_bytes(&marker("stimulus")), 16 + VALUE_BYTES + 8);
927        let packed_long = |text: &str| packed_sample_bytes(&PackedSample::from(marker(text)));
928
929        // Long markers reach the memory limit first.
930        let long = "x".repeat(1000);
931        let limits = HistoryLimits {
932            seconds: 10.0,
933            bytes: 3 * packed_long(&long),
934            ..HistoryLimits::DEFAULT
935        };
936        let mut h = History::new(limits, IRREGULAR_RATE, 0);
937        for _ in 0..5 {
938            h.push(marker(&long));
939        }
940        assert_eq!(h.len(), 3);
941    }
942
943    #[test]
944    fn packed_history_uses_a_fraction_of_value_memory_for_64_channels() {
945        let wide = PackedSample::from_f32(1.0, &[0.0f32; 64]);
946        // 16 bytes metadata + 64 * 4 bytes payload = 272 bytes (vs 2064 with Vec<Value>).
947        assert_eq!(packed_sample_bytes(&wide), 272);
948    }
949
950    #[test]
951    fn a_sample_larger_than_the_memory_limit_empties_the_history() {
952        let limits = HistoryLimits {
953            seconds: 10.0,
954            bytes: 100,
955            ..HistoryLimits::DEFAULT
956        };
957        let mut h = History::new(limits, IRREGULAR_RATE, 0);
958        h.push(sample(0));
959        assert_eq!(h.len(), 1);
960        h.push(Sample {
961            timestamp: 1.0,
962            values: vec![Value::Str(vec![b'x'; 200])],
963        });
964        // The history cannot hold sample 1, and it must not hold sample 0
965        // alone, because then the numbers would have a gap.
966        assert!(h.is_empty());
967        assert_eq!(h.oldest(), 2);
968        h.push(sample(2));
969        assert_eq!(h.oldest(), 2);
970    }
971
972    #[test]
973    fn a_read_gives_the_samples_from_the_asked_number() {
974        let mut h = History::new(HistoryLimits::DEFAULT, 100.0, 1000);
975        for i in 1000..1100 {
976            h.push(sample(i));
977        }
978        let mut out = Vec::new();
979        assert_eq!(h.read(1040, 1100, 5, &mut out), Some((1040, 5)));
980        assert_eq!(numbers(&out), vec![1040, 1041, 1042, 1043, 1044]);
981
982        // The last block is shorter than the maximum.
983        out.clear();
984        assert_eq!(h.read(1098, 1100, 256, &mut out), Some((1098, 2)));
985        assert_eq!(numbers(&out), vec![1098, 1099]);
986    }
987
988    #[test]
989    fn a_read_below_the_history_starts_at_the_oldest_sample() {
990        let limits = HistoryLimits {
991            seconds: 1.0,
992            bytes: usize::MAX,
993            ..HistoryLimits::DEFAULT
994        };
995        let mut h = History::new(limits, 10.0, 0);
996        for i in 0..30 {
997            h.push(sample(i));
998        }
999        let mut out = Vec::new();
1000        assert_eq!(h.read(3, 30, 256, &mut out), Some((20, 10)));
1001        assert_eq!(numbers(&out), (20..30).collect::<Vec<_>>());
1002    }
1003
1004    #[test]
1005    fn a_read_at_or_above_the_next_number_gives_nothing() {
1006        let mut h = History::new(HistoryLimits::DEFAULT, 100.0, 0);
1007        let mut out = Vec::new();
1008        assert_eq!(h.read(0, 10, 256, &mut out), None);
1009        for i in 0..10 {
1010            h.push(sample(i));
1011        }
1012        assert_eq!(h.read(10, 20, 256, &mut out), None);
1013        assert_eq!(h.read(5000, 6000, 256, &mut out), None);
1014        assert_eq!(h.read(5, 10, 0, &mut out), None);
1015        assert!(out.is_empty());
1016    }
1017
1018    #[test]
1019    fn a_read_stops_below_the_bound() {
1020        let mut h = History::new(HistoryLimits::DEFAULT, 100.0, 0);
1021        for i in 0..50 {
1022            h.push(sample(i));
1023        }
1024        let mut out = Vec::new();
1025        assert_eq!(h.read(10, 20, 256, &mut out), Some((10, 10)));
1026        assert_eq!(numbers(&out), (10..20).collect::<Vec<_>>());
1027        // A bound at or below the start gives nothing.
1028        assert_eq!(h.read(20, 20, 256, &mut Vec::new()), None);
1029        assert_eq!(h.read(30, 20, 256, &mut Vec::new()), None);
1030        // A bound below the oldest number gives nothing.
1031        let limits = HistoryLimits {
1032            seconds: 0.1,
1033            bytes: usize::MAX,
1034            ..HistoryLimits::DEFAULT
1035        };
1036        let mut small = History::new(limits, 100.0, 0);
1037        for i in 0..50 {
1038            small.push(sample(i));
1039        }
1040        assert_eq!(small.oldest(), 40);
1041        assert_eq!(small.read(0, 30, 256, &mut Vec::new()), None);
1042    }
1043
1044    #[test]
1045    fn the_numbers_can_wrap() {
1046        let start = u64::MAX - 4;
1047        let mut h = History::new(HistoryLimits::DEFAULT, 100.0, start);
1048        for i in 0..10u64 {
1049            h.push(sample(i));
1050        }
1051        assert_eq!(h.oldest(), start);
1052        assert_eq!(h.next(), 5);
1053        let mut out = Vec::new();
1054        assert_eq!(h.read(1, 5, 256, &mut out), Some((1, 4)));
1055        assert_eq!(numbers(&out), vec![6, 7, 8, 9]);
1056        out.clear();
1057        assert_eq!(h.read(start - 3, 5, 2, &mut out), Some((start, 2)));
1058        assert_eq!(numbers(&out), vec![0, 1]);
1059    }
1060
1061    #[test]
1062    fn the_default_history_holds_30_s() {
1063        assert_eq!(HistoryLimits::DEFAULT.seconds, 30.0);
1064        assert_eq!(HistoryLimits::DEFAULT.bytes, 64 << 20);
1065        assert_eq!(HistoryLimits::DEFAULT.disk_bytes, 0);
1066        // At 512 Hz x 8 channels, the time limit acts first.
1067        let mut h = History::new(HistoryLimits::DEFAULT, 512.0, 0);
1068        let s = Sample {
1069            timestamp: 1.0,
1070            values: vec![Value::F32(0.0); 8],
1071        };
1072        for _ in 0..40 * 512 {
1073            h.push(s.clone());
1074        }
1075        assert_eq!(h.len(), 30 * 512);
1076    }
1077
1078    #[test]
1079    fn the_limits_can_turn_the_history_off() {
1080        assert!(HistoryLimits::DEFAULT.allow_history());
1081        assert!(!HistoryLimits::OFF.allow_history());
1082        let no_time = HistoryLimits {
1083            seconds: 0.0,
1084            bytes: 1 << 20,
1085            ..HistoryLimits::DEFAULT
1086        };
1087        assert!(!no_time.allow_history());
1088    }
1089
1090    #[test]
1091    fn disk_spool_spills_when_ram_fills_reads_exact_and_cleans_up_on_drop() {
1092        let limits = HistoryLimits {
1093            seconds: f64::INFINITY,
1094            bytes: 8 * 1024,             // 8 KiB RAM cap
1095            disk_bytes: 2 * 1024 * 1024, // 2 MiB disk cap
1096            disk_dir: None,
1097        };
1098        let spool_path;
1099        {
1100            let mut h = History::new(limits, 512.0, 100);
1101            let total = 2000u64;
1102            for i in 0..total {
1103                let ch: Vec<f32> = (0..16).map(|c| (i as f32) + (c as f32) * 0.1).collect();
1104                h.push_packed(PackedSample::from_f32(10.0 + i as f64 / 512.0, &ch));
1105                assert!(
1106                    h.bytes() <= 8 * 1024,
1107                    "RAM {} exceeded 8 KiB at sample {i}",
1108                    h.bytes()
1109                );
1110            }
1111            assert_eq!(h.len(), total as usize);
1112            assert_eq!(h.oldest(), 100);
1113            assert!(h.disk_bytes() > 0, "expected samples to spill to disk");
1114            spool_path = h.spool_dir().expect("spool directory created");
1115            assert!(spool_path.exists());
1116
1117            // Read every sample across disk + RAM boundary in 256-sample blocks.
1118            let mut got = Vec::new();
1119            let mut at = 100u64;
1120            let until = 100 + total;
1121            while let Some((first, taken)) = h.read_packed(at, until, 256, &mut got) {
1122                assert_eq!(first, at);
1123                at = first + taken as u64;
1124            }
1125            assert_eq!(got.len(), total as usize);
1126            for (idx, s) in got.iter().enumerate() {
1127                let want_t = 10.0 + idx as f64 / 512.0;
1128                assert_eq!(s.timestamp.to_bits(), want_t.to_bits());
1129                let mut vals = Vec::new();
1130                s.push_into_f32(&mut vals);
1131                assert_eq!(vals.len(), 16);
1132                assert_eq!(vals[0], idx as f32);
1133                assert_eq!(vals[15], (idx as f32) + 1.5);
1134            }
1135        }
1136        assert!(
1137            !spool_path.exists(),
1138            "spool directory must be removed when History drops"
1139        );
1140    }
1141
1142    #[test]
1143    fn disk_spool_enforces_max_disk_bytes_and_handles_strings() {
1144        let limits = HistoryLimits {
1145            seconds: f64::INFINITY,
1146            bytes: 2 * 1024,
1147            disk_bytes: 128 * 1024, // 128 KiB disk cap
1148            disk_dir: None,
1149        };
1150        let mut h = History::new(limits, IRREGULAR_RATE, 0);
1151        for i in 0..1000u64 {
1152            let payload = format!("marker-{i:04}-{}", "a".repeat(200)).into_bytes();
1153            h.push_packed(PackedSample::from_strings(i as f64, vec![payload]));
1154            assert!(h.bytes() <= 2 * 1024);
1155            assert!(
1156                h.disk_bytes() <= 128 * 1024,
1157                "disk {} exceeded 128 KiB",
1158                h.disk_bytes()
1159            );
1160        }
1161        assert!(h.oldest() > 0, "oldest segments must evict under disk cap");
1162        let oldest = h.oldest();
1163        let mut out = Vec::new();
1164        let mut at = 0u64;
1165        while let Some((first, taken)) = h.read_packed(at, 1000, 64, &mut out) {
1166            if at == 0 {
1167                assert_eq!(first, oldest);
1168            } else {
1169                assert_eq!(first, at);
1170            }
1171            at = first + taken as u64;
1172        }
1173        assert_eq!(out.len(), (1000 - oldest) as usize);
1174        let first_s = out[0].to_sample();
1175        let expected_prefix = format!("marker-{oldest:04}-");
1176        match &first_s.values[0] {
1177            Value::Str(b) => assert!(b.starts_with(expected_prefix.as_bytes())),
1178            _ => panic!("expected string sample"),
1179        }
1180    }
1181}