Skip to main content

gondola_core/io/caraspace/
file_summary.rs

1//! Caraspace I/O system - the file summary ("footer")
2//!
3// The following file is part of gaps-online-software and published
4// under the GPLv3 license
5
6use crate::prelude::*;
7
8//---------------------------------------------------
9
10/// The name under which the CRFileSummary is stored
11/// in the footer frame
12pub const CRFILESUMMARY_NAME : &str = "file_summary";
13
14/// Marks the end of a file which has a footer.
15/// (Does not contain 0xAA, so it can not be mistaken
16/// for the beginning of a frame)
17pub const CRFILESUMMARY_MAGIC : [u8;4] = *b"CRFS";
18
19//---------------------------------------------------
20
21/// Meta information about a whole caraspace file.
22///
23/// The summary is stored in the last frame of a file
24/// (the "footer"), so that it can be written when the
25/// file is closed, without going back to the beginning
26/// of the file.
27///
28/// Every file with a footer ends with the same 18 bytes:
29///
30/// `magic (4) | footer_len (8) | TAIL (2) | CRFrameObject TAIL (2) | CRFrame TAIL (2)`
31///
32/// so the footer can be found by reading the last 18 bytes
33/// of a file and jumping back footer_len bytes.
34#[derive(Debug, Clone, PartialEq)]
35#[cfg_attr(feature="pybindings", pyclass)]
36pub struct CRFileSummary {
37  /// The version of the summary, needs to be compatible
38  /// with CRReader/Writer
39  pub version       : u8,
40  /// Run id of the frames in this file
41  pub run_id        : u32,
42  /// Subrun id (number of the file within the run)
43  pub subrun        : u64,
44  /// Number of frames in this file, including empty
45  /// frames, but without the footer frame itself
46  pub n_frames      : u32,
47  /// Smallest event id in this file (only meaningful if
48  /// n_frames > 0)
49  pub min_evid      : u32,
50  /// Largest event id in this file (only meaningful if
51  /// n_frames > 0)
52  pub max_evid      : u32,
53  /// GCU time of the first frame with a timestamp
54  /// (0 if there is none)
55  pub first_gcutime : f64,
56  /// GCU time of the last frame with a timestamp
57  /// (0 if there is none)
58  pub last_gcutime  : f64,
59  /// GPS time of the first frame with a GPS timestamp
60  /// (0 if there is none)
61  pub first_gpstime : f64,
62  /// GPS time of the last frame with a GPS timestamp
63  /// (0 if there is none)
64  pub last_gpstime  : f64,
65  /// All data sources which appear in the frames of
66  /// this file
67  pub data_sources  : Vec<GapsDataSource>,
68  /// Clusters of missing event ids, filled by empty frames:
69  /// (first missing event id, number of missing ids)
70  pub missing_evid  : Vec<(u32, u32)>,
71  /// Size of the whole footer frame in bytes. Set when
72  /// the footer is created (see to_footer)
73  pub footer_len    : u64,
74}
75
76impl CRFileSummary {
77
78  /// The last bytes of a file with a footer:
79  /// magic, footer_len and three tails
80  pub const TRAILER_SIZE : usize = 4 + 8 + 2 + 2 + 2;
81
82  /// Serialized size without data sources and gaps,
83  /// including HEAD and TAIL
84  const FIXED_SIZE : usize = 2 + 1 + 4 + 8 + 4 + 4 + 4 + 8 + 8 + 8 + 8 + 1 + 4 + 4 + 8 + 2;
85
86  pub fn new() -> Self {
87    Self {
88      version       : 0,
89      run_id        : 0,
90      subrun        : 0,
91      n_frames      : 0,
92      min_evid      : 0,
93      max_evid      : 0,
94      first_gcutime : 0.0,
95      last_gcutime  : 0.0,
96      first_gpstime : 0.0,
97      last_gpstime  : 0.0,
98      data_sources  : Vec::<GapsDataSource>::new(),
99      missing_evid  : Vec::<(u32, u32)>::new(),
100      footer_len    : 0,
101    }
102  }
103
104  /// The total number of missing event ids
105  pub fn n_missing(&self) -> u64 {
106    self.missing_evid.iter().map(|gap| gap.1 as u64).sum()
107  }
108
109  /// The complete footer frame, ready to be appended
110  /// to a file. footer_len is set to its size.
111  pub fn to_footer(&self) -> Vec<u8> {
112    // footer_len has a fixed width, so its value does
113    // not change the size of the footer
114    let mut summary    = self.clone();
115    summary.footer_len = 0;
116    let mut frame      = CRFrame::new();
117    frame.put(summary.clone(), CRFILESUMMARY_NAME);
118    summary.footer_len = frame.to_bytestream().len() as u64;
119    let mut frame      = CRFrame::new();
120    frame.put(summary, CRFILESUMMARY_NAME);
121    frame.to_bytestream()
122  }
123
124  /// Check the last bytes of a file for a footer
125  ///
126  /// # Arguments:
127  ///   * trailer : The last TRAILER_SIZE (or more) bytes of a file
128  ///
129  /// # Returns:
130  ///   The size of the footer frame (the footer starts footer_len bytes
131  ///   before the end of the file), or None if the file does not have
132  ///   a footer
133  pub fn footer_len_from_trailer(trailer : &[u8]) -> Option<u64> {
134    if trailer.len() < Self::TRAILER_SIZE {
135      return None;
136    }
137    let tr = &trailer[trailer.len() - Self::TRAILER_SIZE..];
138    if tr[0..4] != CRFILESUMMARY_MAGIC {
139      return None;
140    }
141    if tr[12..18].iter().any(|b| *b != 0x55) {
142      return None;
143    }
144    let footer_len = parse_u64(&tr[4..12].to_vec(), &mut 0);
145    if footer_len < Self::FIXED_SIZE as u64 {
146      return None;
147    }
148    Some(footer_len)
149  }
150}
151
152impl Default for CRFileSummary {
153  fn default() -> Self {
154    Self::new()
155  }
156}
157
158impl fmt::Display for CRFileSummary {
159  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
160    let mut repr = format!("<CRFileSummary (version:{}):", self.version);
161    repr += &(format!("\n  Run/Subrun   : {}/{}", self.run_id, self.subrun));
162    repr += &(format!("\n  Frames       : {}", self.n_frames));
163    if self.n_frames > 0 {
164      repr += &(format!("\n  Event ids    : {} - {}", self.min_evid, self.max_evid));
165    }
166    repr += &(format!("\n  GCU time     : {} - {}", self.first_gcutime, self.last_gcutime));
167    repr += &(format!("\n  GPS time     : {} - {}", self.first_gpstime, self.last_gpstime));
168    repr += &(format!("\n  Missing      : {} event ids in {} gaps", self.n_missing(), self.missing_evid.len()));
169    if self.data_sources.len() > 0 {
170      repr += "\n  Data sources : [";
171      for k in &self.data_sources {
172        repr += &(format!(" {} ", k));
173      }
174      repr += "]";
175    }
176    repr += ">";
177    write!(f, "{}", repr)
178  }
179}
180
181//---------------------------------------------------
182
183impl Serialization for CRFileSummary {
184
185  /// Decode a CRFileSummary from a bytestream
186  ///
187  /// Layout (little endian):
188  ///   HEAD (2) | version (1) | run_id (4) | subrun (8) | n_frames (4) |
189  ///   min_evid (4) | max_evid (4) | first_gcutime (8) | last_gcutime (8) |
190  ///   first_gpstime (8) | last_gpstime (8) |
191  ///   n_sources (1) | sources (n_sources) |
192  ///   n_gaps (4) | gaps (n_gaps x (first u32, count u32)) |
193  ///   magic (4) | footer_len (8) | TAIL (2)
194  fn from_bytestream(stream : &Vec<u8>,
195                     pos    : &mut usize)
196    -> Result<Self, SerializationError> {
197    if stream.len() < *pos + Self::FIXED_SIZE {
198      return Err(SerializationError::StreamTooShort);
199    }
200    let head = parse_u16(stream, pos);
201    if head != Self::HEAD {
202      error!("Got wrong head bytes! Found {} instead of {}", head, Self::HEAD);
203      return Err(SerializationError::HeadInvalid);
204    }
205    let mut summary       = Self::new();
206    summary.version       = parse_u8 (stream, pos);
207    summary.run_id        = parse_u32(stream, pos);
208    summary.subrun        = parse_u64(stream, pos);
209    summary.n_frames      = parse_u32(stream, pos);
210    summary.min_evid      = parse_u32(stream, pos);
211    summary.max_evid      = parse_u32(stream, pos);
212    summary.first_gcutime = parse_f64(stream, pos);
213    summary.last_gcutime  = parse_f64(stream, pos);
214    summary.first_gpstime = parse_f64(stream, pos);
215    summary.last_gpstime  = parse_f64(stream, pos);
216    let n_sources         = parse_u8 (stream, pos) as usize;
217    // the n_gaps field and everything after it
218    if stream.len() < *pos + n_sources + 4 + 4 + 8 + 2 {
219      return Err(SerializationError::StreamTooShort);
220    }
221    for _ in 0..n_sources {
222      summary.data_sources.push(GapsDataSource::from(parse_u8(stream, pos)));
223    }
224    let n_gaps = parse_u32(stream, pos) as usize;
225    if stream.len() < *pos + 8*n_gaps + 4 + 8 + 2 {
226      return Err(SerializationError::StreamTooShort);
227    }
228    for _ in 0..n_gaps {
229      let first = parse_u32(stream, pos);
230      let count = parse_u32(stream, pos);
231      if count == 0 {
232        error!("Found a gap of 0 missing event ids at event id {}!", first);
233        return Err(SerializationError::InvalidByte);
234      }
235      summary.missing_evid.push((first, count));
236    }
237    if stream[*pos..*pos + 4] != CRFILESUMMARY_MAGIC {
238      error!("Got wrong magic bytes {:?}, expected {:?}!", &stream[*pos..*pos + 4], CRFILESUMMARY_MAGIC);
239      return Err(SerializationError::InvalidByte);
240    }
241    *pos += 4;
242    summary.footer_len = parse_u64(stream, pos);
243    let tail = parse_u16(stream, pos);
244    if tail != Self::TAIL {
245      error!("Got wrong tail bytes! Found {} instead of {}", tail, Self::TAIL);
246      return Err(SerializationError::TailInvalid);
247    }
248    Ok(summary)
249  }
250
251  /// Encode a CRFileSummary to a bytestream
252  fn to_bytestream(&self) -> Vec<u8> {
253    let n_sources  = self.data_sources.len().min(u8::MAX as usize);
254    let mut stream = Vec::<u8>::with_capacity(Self::FIXED_SIZE + n_sources + 8*self.missing_evid.len());
255    stream.extend_from_slice(&Self::HEAD.to_le_bytes());
256    stream.push(self.version);
257    stream.extend_from_slice(&self.run_id.to_le_bytes());
258    stream.extend_from_slice(&self.subrun.to_le_bytes());
259    stream.extend_from_slice(&self.n_frames.to_le_bytes());
260    stream.extend_from_slice(&self.min_evid.to_le_bytes());
261    stream.extend_from_slice(&self.max_evid.to_le_bytes());
262    stream.extend_from_slice(&self.first_gcutime.to_le_bytes());
263    stream.extend_from_slice(&self.last_gcutime.to_le_bytes());
264    stream.extend_from_slice(&self.first_gpstime.to_le_bytes());
265    stream.extend_from_slice(&self.last_gpstime.to_le_bytes());
266    if self.data_sources.len() > u8::MAX as usize {
267      error!("Too many data sources ({}), only the first {} will be serialized!", self.data_sources.len(), u8::MAX);
268    }
269    stream.push(n_sources as u8);
270    for k in &self.data_sources[0..n_sources] {
271      stream.push(*k as u8);
272    }
273    stream.extend_from_slice(&(self.missing_evid.len() as u32).to_le_bytes());
274    for (first, count) in &self.missing_evid {
275      stream.extend_from_slice(&first.to_le_bytes());
276      stream.extend_from_slice(&count.to_le_bytes());
277    }
278    stream.extend_from_slice(&CRFILESUMMARY_MAGIC);
279    stream.extend_from_slice(&self.footer_len.to_le_bytes());
280    stream.extend_from_slice(&Self::TAIL.to_le_bytes());
281    stream
282  }
283}
284
285impl Frameable for CRFileSummary {
286  const CRFRAMEOBJECT_TYPE : CRFrameObjectType = CRFrameObjectType::CRFileSummary;
287}
288
289//---------------------------------------------------
290
291#[cfg(feature="pybindings")]
292#[pymethods]
293impl CRFileSummary {
294
295  /// The version of the summary
296  #[getter]
297  fn get_version(&self) -> u8 {
298    self.version
299  }
300
301  /// Run id of the frames in this file
302  #[getter]
303  fn get_run_id(&self) -> u32 {
304    self.run_id
305  }
306
307  /// Subrun id (number of the file within the run)
308  #[getter]
309  fn get_subrun(&self) -> u64 {
310    self.subrun
311  }
312
313  /// Number of frames in this file, including empty frames
314  #[getter]
315  fn get_n_frames(&self) -> u32 {
316    self.n_frames
317  }
318
319  /// Smallest event id in this file
320  #[getter]
321  fn get_min_evid(&self) -> u32 {
322    self.min_evid
323  }
324
325  /// Largest event id in this file
326  #[getter]
327  fn get_max_evid(&self) -> u32 {
328    self.max_evid
329  }
330
331  /// GCU time of the first frame with a timestamp
332  #[getter]
333  fn get_first_gcutime(&self) -> f64 {
334    self.first_gcutime
335  }
336
337  /// GCU time of the last frame with a timestamp
338  #[getter]
339  fn get_last_gcutime(&self) -> f64 {
340    self.last_gcutime
341  }
342
343  /// GPS time of the first frame with a GPS timestamp
344  #[getter]
345  fn get_first_gpstime(&self) -> f64 {
346    self.first_gpstime
347  }
348
349  /// GPS time of the last frame with a GPS timestamp
350  #[getter]
351  fn get_last_gpstime(&self) -> f64 {
352    self.last_gpstime
353  }
354
355  /// All data sources which appear in the frames of this file
356  #[getter]
357  fn get_data_sources(&self) -> Vec<GapsDataSource> {
358    self.data_sources.clone()
359  }
360
361  /// Clusters of missing event ids as
362  /// (first missing event id, number of missing ids)
363  #[getter]
364  fn get_missing_evid(&self) -> Vec<(u32, u32)> {
365    self.missing_evid.clone()
366  }
367
368  /// The total number of missing event ids
369  #[getter]
370  #[pyo3(name="n_missing")]
371  fn get_n_missing_py(&self) -> u64 {
372    self.n_missing()
373  }
374
375  /// Size of the footer frame in bytes
376  #[getter]
377  fn get_footer_len(&self) -> u64 {
378    self.footer_len
379  }
380
381  #[cfg(feature="random")]
382  #[staticmethod]
383  #[pyo3(name="from_random")]
384  fn from_random_py() -> Self {
385    Self::from_random()
386  }
387}
388
389#[cfg(feature="pybindings")]
390pythonize!(CRFileSummary);
391
392//---------------------------------------------------
393
394#[cfg(feature="random")]
395impl FromRandom for CRFileSummary {
396
397  fn from_random() -> Self {
398    let mut s       = Self::new();
399    let mut rng     = rand::rng();
400    s.version       = rng.random::<u8>();
401    s.run_id        = rng.random::<u32>();
402    s.subrun        = rng.random::<u64>();
403    s.n_frames      = rng.random::<u32>();
404    s.min_evid      = rng.random::<u32>();
405    s.max_evid      = rng.random::<u32>();
406    s.first_gcutime = rng.random::<f64>();
407    s.last_gcutime  = rng.random::<f64>();
408    s.first_gpstime = rng.random::<f64>();
409    s.last_gpstime  = rng.random::<f64>();
410    for source in GapsDataSource::iter() {
411      if rng.random::<bool>() {
412        s.data_sources.push(source);
413      }
414    }
415    let n_gaps = rng.random_range(0..20);
416    for _ in 0..n_gaps {
417      s.missing_evid.push((rng.random::<u32>(), rng.random_range(1..1000)));
418    }
419    s.footer_len    = rng.random::<u64>();
420    s
421  }
422}
423
424//---------------------------------------------------
425
426#[cfg(test)]
427mod tests {
428  use super::*;
429
430  #[test]
431  #[cfg(feature="random")]
432  fn serialize_deserialize_crfilesummary() {
433    for _ in 0..100 {
434      let s       = CRFileSummary::from_random();
435      let stream  = s.to_bytestream();
436      assert_eq!(stream.len(), CRFileSummary::FIXED_SIZE + s.data_sources.len() + 8*s.missing_evid.len());
437      let mut pos = 0;
438      let test    = CRFileSummary::from_bytestream(&stream, &mut pos).unwrap();
439      assert_eq!(s, test);
440      assert_eq!(pos, stream.len());
441    }
442  }
443
444  #[test]
445  #[cfg(feature="random")]
446  fn pack_crfilesummary() {
447    for _ in 0..100 {
448      let s    = CRFileSummary::from_random();
449      let test : CRFileSummary = s.pack().extract().unwrap();
450      assert_eq!(s, test);
451    }
452  }
453
454  #[test]
455  #[cfg(feature="random")]
456  fn crfilesummary_stream_too_short() {
457    let s      = CRFileSummary::from_random();
458    let stream = s.to_bytestream();
459    for k in 0..stream.len() {
460      let short = stream[0..k].to_vec();
461      assert!(CRFileSummary::from_bytestream(&short, &mut 0).is_err());
462    }
463  }
464
465  #[test]
466  fn crfilesummary_rejects_wrong_magic_and_empty_gaps() {
467    let mut s = CRFileSummary::new();
468    s.missing_evid.push((100, 5));
469    let good = s.to_bytestream();
470    // the magic is right in front of footer_len and TAIL
471    let mut stream = good.clone();
472    let magic_pos  = stream.len() - 2 - 8 - 4;
473    stream[magic_pos] = b'X';
474    assert!(CRFileSummary::from_bytestream(&stream, &mut 0).is_err());
475    // a gap of 0 missing event ids can not be written by us
476    s.missing_evid[0].1 = 0;
477    assert!(CRFileSummary::from_bytestream(&s.to_bytestream(), &mut 0).is_err());
478  }
479
480  #[test]
481  fn crfilesummary_time_fields() {
482    // the times are at a fixed position in the stream
483    let mut s = CRFileSummary::new();
484    s.first_gcutime = 1.0;
485    s.last_gcutime  = 2.0;
486    s.first_gpstime = 3.0;
487    s.last_gpstime  = 4.0;
488    let stream = s.to_bytestream();
489    // HEAD, version, run_id, subrun, n_frames, min_evid, max_evid
490    let mut pos = 2 + 1 + 4 + 8 + 4 + 4 + 4;
491    for expected in [1.0, 2.0, 3.0, 4.0] {
492      assert_eq!(parse_f64(&stream, &mut pos), expected);
493    }
494    let test = CRFileSummary::from_bytestream(&stream, &mut 0).unwrap();
495    assert_eq!((test.first_gpstime, test.last_gpstime), (3.0, 4.0));
496  }
497
498  #[test]
499  fn crfilesummary_n_missing() {
500    let mut s = CRFileSummary::new();
501    s.missing_evid = vec![(1000, 500), (1503, 1)];
502    assert_eq!(s.n_missing(), 501);
503  }
504
505  #[test]
506  #[cfg(feature="random")]
507  fn crfilesummary_footer() {
508    for _ in 0..100 {
509      let s      = CRFileSummary::from_random();
510      let footer = s.to_footer();
511      // the footer can be found from the last bytes of the file
512      let len    = CRFileSummary::footer_len_from_trailer(&footer).unwrap();
513      assert_eq!(len as usize, footer.len());
514      // the footer is a regular frame
515      let frame  = CRFrame::from_bytestream(&footer, &mut 0).unwrap();
516      let test   = frame.get::<CRFileSummary>(CRFILESUMMARY_NAME).unwrap();
517      assert_eq!(test.footer_len, len);
518      let mut expected   = s.clone();
519      expected.footer_len = len;
520      assert_eq!(test, expected);
521    }
522  }
523
524  #[test]
525  fn crfilesummary_needs_magic_to_be_a_footer() {
526    // a regular frame, which ends with a TofPacket, ends with
527    // the same three tails 0x5555 as a footer. Without the
528    // magic it would be mistaken for one.
529    let mut frame = CRFrame::new();
530    frame.put(TofPacket::new(), "TofPacket");
531    let stream = frame.to_bytestream();
532    assert!(stream[stream.len() - 6..].iter().all(|b| *b == 0x55));
533    assert_eq!(CRFileSummary::footer_len_from_trailer(&stream), None);
534    // too short to be a footer
535    assert_eq!(CRFileSummary::footer_len_from_trailer(&stream[stream.len() - 6..]), None);
536  }
537}