Skip to main content

gondola_core/io/caraspace/
writer.rs

1// This file is part of gaps-online-software and published 
2// under the GPLv3 license
3
4use crate::prelude::*;
5
6/// Write CRFrames ("caraspace frames") to disk. 
7/// 
8/// A frame can hold any TOF/TelemetryPacket.
9/// Data are written to disk in sequential matter,
10/// where frames can be added one at a time and 
11/// buffered for efficient writing
12///
13/// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
14///
15/// How to create a new CRWriter (python)
16///
17/// # Arguments
18///
19/// * file_path        (str) : Path to store the file under
20/// * run_id           (u32) : Run ID for this file (will be written in filename)
21/// * subrun_id        (u32) : Sub-Run ID for this file (will be written in filename. 
22///                            If None, a generic "0" will be used
23/// * timestamp        (str) : The writer will add an automatic timestamp to the current file
24///                            based on the current time. This option allows to overwrite 
25///                            that behaviour
26/// * file_len_gcu_sec (u32) : If not None, this will use the gcu time from added packets 
27///                            as the timestamp in the filename, and will write a new file 
28///                            every given number of seconds
29#[cfg_attr(feature="pybindings", pyclass)]
30pub struct CRWriter {
31
32  /// The file we are currently writing to. None after a 
33  /// file has been closed, the next file is only opened 
34  /// when the next frame arrives (so there are no empty files)
35  pub file            : Option<File>,
36  /// location to store the file
37  pub file_path       : String,
38  /// The maximum number of packets 
39  /// for a single file. Ater this 
40  /// number is reached, a new 
41  /// file is started.
42  pub pkts_per_file   : usize,
43  /// The maximum number of (Mega)bytes
44  /// per file. After this a new file 
45  /// is started
46  pub mbytes_per_file     : usize,
47  /// the name of the current file we are writing to
48  pub file_name           : String,
49  pub run_id              : u32,
50  file_id                 : usize,
51  /// internal packet counter, number of 
52  /// packets which went through the writer
53  n_packets               : usize,
54  /// internal counter for bytes written in 
55  /// this file
56  file_nbytes_wr          : usize,
57  /// it can also take a timestamp, in case we 
58  /// don't want to use the current time when the 
59  /// file is written
60  pub file_timestamp      : Option<String>,
61  /// if writing a new file every gcu seconds, keep 
62  /// the first gcutimestamp 
63  pub first_gcu_timestamp : Option<u64>,
64  /// Write a new file every gcu seconds (from telemetry packet header) 
65  pub file_len_gcu_sec    : Option<u32>,
66  /// only complain once about frames without timestamp 
67  /// when writing files every gcu seconds
68  warned_no_timestamp     : bool,
69  /// The summary of the current file, which will be 
70  /// written as the footer when the file is closed
71  summary                 : CRFileSummary,
72  /// number of frames in the current file with a CRFrameHeader
73  n_frames_with_header    : u32,
74  /// frames in the current file with data, but no data 
75  /// sources in their header
76  n_data_without_source   : u32,
77  /// frames in the current file with only a header, but 
78  /// data sources in it
79  n_empty_with_source     : u32,
80}
81
82impl CRWriter {
83
84  /// Instantiate a new PacketWriter 
85  ///
86  /// # Arguments
87  ///
88  /// * file_path        : Path to store the file under
89  /// * run_id           : Run ID for this file (will be written in filename)
90  /// * subrun_id        : Sub-Run ID for this file (will be written in filename. 
91  ///                      If None, a generic "0" will be used
92  /// * timestamp        : The writer will add an automatic timestamp to the current file
93  ///                      based on the current time. This option allows to overwrite 
94  ///                      that behaviour
95  /// * file_len_gcu_sec : If not None, this will use the gcu time from added packets 
96  ///                      as the timestamp in the filename, and will write a new file 
97  ///                      every given number of seconds
98  pub fn new(mut file_path : String, run_id : u32,
99             subrun_id : Option<u64>, timestamp : Option<String>, file_len_gcu_sec : Option<u32>, delete_if_exist : bool) -> Self {
100    if file_len_gcu_sec.is_some() {
101      if timestamp.is_none() {
102        panic!("If the writer should operate in the mode where it writes a new file every x seconds depending on the delta of gcu times in the packets, it needs the first timestamp given. This needs to be the first timestamp of the packets to be written");
103      }
104    }
105    if !file_path.ends_with("/") {
106      file_path += "/";
107    }
108    // check if this path exists 
109    let tmppath = Path::new(&file_path);
110    if !tmppath.exists() {
111      fs::create_dir_all(tmppath)
112      .expect(&format!("Failed to create directory at: {}", file_path));
113    }
114
115    let first_timestamp = timestamp.clone();
116    let subrun          = subrun_id.unwrap_or(0);
117    let filename        = format!("{}{}", file_path, get_runfilename(run_id, subrun, None, timestamp, false));
118    let path     = Path::new(&filename); 
119    //println!("Writing to file {filename}");
120    //FIXME - do we really want to have this append here?
121    if path.exists() && delete_if_exist {
122      fs::remove_file(path).expect(&format!("Tried to delete {}, but that failed!", filename));
123    }
124    let file = Self::open_file(path);
125    //file_name = filename;
126    let mut first_gcu_timestamp = None;
127    if first_timestamp.is_some() {
128      first_gcu_timestamp = get_unix_timestamp(&first_timestamp.unwrap(), None);
129    }
130    let mut summary = CRFileSummary::new();
131    summary.run_id  = run_id;
132    summary.subrun  = subrun;
133    Self {
134      file                : Some(file),
135      file_path           : file_path,
136      pkts_per_file       : 0,
137      mbytes_per_file     : 420,
138      run_id              : run_id,
139      file_nbytes_wr      : 0,    
140      // the subrun id for the next file 
141      file_id             : subrun as usize + 1,
142      n_packets           : 0,
143      file_name           : filename,
144      file_timestamp      : None,
145      first_gcu_timestamp : first_gcu_timestamp,
146      file_len_gcu_sec    : file_len_gcu_sec,
147      warned_no_timestamp : false,
148      summary             : summary,
149      n_frames_with_header : 0,
150      n_data_without_source : 0,
151      n_empty_with_source   : 0,
152    }
153  }
154
155  /// Open a file for appending. 
156  fn open_file(path : &Path) -> File {
157    if let Ok(meta) = fs::metadata(path) {
158      if meta.len() > 0 {
159        warn!("File {} exists already and is not empty! Will append to it, its footer will then be in the middle of the file!", path.display());
160      }
161    }
162    OpenOptions::new().create(true).append(true).open(path).expect(&format!("Unable to open file {}", path.display()))
163  }
164
165  /// Update the summary of the current file with a frame
166  fn add_to_summary(&mut self, frame : &CRFrame) {
167    self.summary.n_frames += 1;
168    if let Some(ts) = frame.timestamp {
169      if self.summary.first_gcutime == 0.0 {
170        self.summary.first_gcutime = ts;
171      }
172      self.summary.last_gcutime = ts;
173    }
174    if let Some(ts) = frame.gpstime {
175      if self.summary.first_gpstime == 0.0 {
176        self.summary.first_gpstime = ts;
177      }
178      self.summary.last_gpstime = ts;
179    }
180    let header = match frame.get_header() {
181      None    => return,
182      Some(h) => h
183    };
184    let evid = header.event_id;
185    if self.n_frames_with_header == 0 {
186      self.summary.min_evid = evid;
187      self.summary.max_evid = evid;
188    } else {
189      self.summary.min_evid = self.summary.min_evid.min(evid);
190      self.summary.max_evid = self.summary.max_evid.max(evid);
191    }
192    self.n_frames_with_header += 1;
193    for source in &header.data_sources {
194      if !self.summary.data_sources.contains(source) {
195        self.summary.data_sources.push(*source);
196      }
197    }
198    // the header has to agree with the content of the frame. 
199    // This is only reported, the frame is written as it is
200    if !frame.is_empty_event() && header.data_sources.is_empty() {
201      if self.n_data_without_source == 0 {
202        error!("Frame for event {} contains data, but its header has no data sources! Use CRFrame::add_datasource when adding packets", evid);
203      }
204      self.n_data_without_source += 1;
205    }
206    if frame.is_empty_event() && !header.data_sources.is_empty() {
207      if self.n_empty_with_source == 0 {
208        error!("Frame for event {} contains only its header, but the header has data sources {:?}!", evid, header.data_sources);
209      }
210      self.n_empty_with_source += 1;
211    }
212    if frame.is_empty_event() {
213      // consecutive empty frames form one gap
214      match self.summary.missing_evid.last_mut() {
215        Some(gap) if gap.0 as u64 + gap.1 as u64 == evid as u64 => {
216          gap.1 += 1;
217        }
218        _ => {
219          self.summary.missing_evid.push((evid, 1));
220        }
221      }
222    }
223  }
224
225  /// Finish the current file: write the footer with the 
226  /// summary of the file and sync it to disk. 
227  ///
228  /// If more frames are added after that, they go to a new 
229  /// file. Closing an already closed writer does nothing. 
230  /// Files without frames do not get a footer.
231  pub fn close(&mut self) {
232    let mut file = match self.file.take() {
233      None    => return,
234      Some(f) => f
235    };
236    if self.summary.n_frames > 0 {
237      if self.n_frames_with_header == 0 {
238        info!("None of the frames in {} has a CRFrameHeader, the footer will not have any event ids!", self.file_name);
239      }
240      if self.n_data_without_source > 0 {
241        error!("{} frames in {} contain data, but no data sources in their header. The data sources in the footer are incomplete!", self.n_data_without_source, self.file_name);
242      }
243      if self.n_empty_with_source > 0 {
244        error!("{} frames in {} contain only a header, but with data sources!", self.n_empty_with_source, self.file_name);
245      }
246      let footer = self.summary.to_footer();
247      match file.write_all(footer.as_slice()) {
248        Err(err) => error!("Writing the footer to {} failed! {}", self.file_name, err),
249        Ok(_)    => ()
250      }
251    }
252    match file.sync_all() {
253      Err(err) => error!("Unable to sync file {} to disc! {err}", self.file_name),
254      Ok(_)    => ()
255    }
256    self.n_packets            = 0;
257    self.file_nbytes_wr       = 0;
258    self.n_frames_with_header = 0;
259    self.n_data_without_source = 0;
260    self.n_empty_with_source   = 0;
261    self.summary              = CRFileSummary::new();
262    self.summary.run_id       = self.run_id;
263  }
264
265  /// The full path of the next file
266  fn get_filename(&self, timestamp : Option<String>) -> String {
267    format!("{}{}", self.file_path, get_runfilename(self.run_id, self.file_id as u64, None, timestamp, false))
268  }
269
270  pub fn get_file(&self, timestamp : Option<String>) -> File { 
271    let filename = self.get_filename(timestamp);
272    //let filename = self.file_path.clone() + &get_runfilename(runid,self.file_id as u64, None);
273    let path     = Path::new(&filename); 
274    info!("Writing to file {filename}");
275    Self::open_file(path)
276  }
277
278  /// Induce serialization to disk for a CRFrame
279  ///
280  ///
281  pub fn add_frame(&mut self, frame : &CRFrame) {
282    if self.file.is_none() {
283      // the previous file has been closed, start the next one
284      self.file_name      = self.get_filename(self.file_timestamp.clone());
285      self.file           = Some(self.get_file(self.file_timestamp.clone()));
286      self.summary.subrun = self.file_id as u64;
287      self.file_id       += 1;
288    }
289    let buffer = frame.to_bytestream();
290    self.file_nbytes_wr += buffer.len();
291    if let Some(file) = self.file.as_mut() {
292      match file.write_all(buffer.as_slice()) {
293        Err(err) => error!("Writing to file to path {} failed! {}", self.file_path, err),
294        Ok(_)    => ()
295      }
296    }
297    self.add_to_summary(frame);
298    self.n_packets += 1;
299    let mut newfile = false;
300    if self.pkts_per_file != 0 {
301      if self.n_packets == self.pkts_per_file {
302        newfile = true;
303      }
304    } else if let Some(file_len) = self.file_len_gcu_sec {
305      // a file length in gcu time was explicitly requested, 
306      // so it takes precedence over the file size
307      match (frame.timestamp, self.first_gcu_timestamp) {
308        (Some(ts), Some(first_ts)) => {
309          if ts - first_ts as f64 > file_len as f64 {
310            newfile = true; 
311            self.file_timestamp      = get_utc_timestamp_from_unix(ts); 
312            self.first_gcu_timestamp = Some(ts as u64);
313          }
314        }
315        _ => {
316          if !self.warned_no_timestamp {
317            error!("Can not start a new file every {} gcu seconds, since the frame (or the writer) does not have a timestamp! Use record_timestamp when adding packets to the frame. Writing everything to {}", file_len, self.file_name);
318            self.warned_no_timestamp = true;
319          }
320        }
321      }
322    } else if self.mbytes_per_file != 0 {
323      // multiply by mebibyte
324      if self.file_nbytes_wr >= self.mbytes_per_file * 1_048_576 {
325        newfile = true;
326      }
327    }
328    if newfile {
329      // the next file will be opened with the next frame
330      self.close();
331    }
332  debug!("CRFrame written!");
333  }
334}
335
336impl Drop for CRWriter {
337  /// Make sure the footer gets written when the 
338  /// writer goes out of scope (also from python)
339  fn drop(&mut self) {
340    self.close();
341  }
342}
343
344// deliberately no Default: there is no sensible default 
345// location to write files to (an empty path would write 
346// into the root directory "/")
347
348impl fmt::Display for CRWriter {
349  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
350    let mut repr = String::from("<CRWriter:");
351    repr += &(format!("\n  path: {}", self.file_path)); 
352    repr += ">";
353    write!(f, "{}", repr)
354  }
355}
356
357#[cfg(feature="pybindings")]
358#[pymethods]
359impl CRWriter {
360  
361  #[new]
362  #[pyo3(signature = (filename, run_id, subrun_id = None, timestamp = None, file_len_gcu_sec = None, delete_if_exist = false))]
363  fn new_py(filename : String, run_id : u32, subrun_id : Option<u64>, timestamp : Option<String>, file_len_gcu_sec : Option<u32>, delete_if_exist : bool) -> Self {
364    Self::new(filename, run_id, subrun_id, timestamp, file_len_gcu_sec, delete_if_exist)
365  }
366
367  #[getter] 
368  #[pyo3(name="current_filename")] 
369  fn get_current_filename_py(&self) -> String { 
370    self.file_name.clone()
371  }
372
373  fn set_mbytes_per_file(&mut self, fsize : usize) {
374    self.mbytes_per_file = fsize;
375  }
376
377  fn set_file_timestamp(&mut self, timestamp : String) {
378    self.file_timestamp = Some(timestamp);
379  }
380  
381  #[pyo3(name="add_frame")]
382  fn add_frame_py(&mut self, frame : CRFrame) {
383    self.add_frame(&frame);  
384  }
385
386  /// Finish the current file and write its footer. 
387  /// Frames added afterwards go to a new file.
388  #[pyo3(name="close")]
389  fn close_py(&mut self) {
390    self.close();
391  }
392
393  fn __enter__(slf : PyRef<'_, Self>) -> PyRef<'_, Self> {
394    slf
395  }
396
397  #[pyo3(signature = (_exc_type=None, _exc_value=None, _traceback=None))]
398  fn __exit__(&mut self, _exc_type : Option<Py<PyAny>>, _exc_value : Option<Py<PyAny>>, _traceback : Option<Py<PyAny>>) -> bool {
399    self.close();
400    false
401  }
402}
403
404#[cfg(feature="pybindings")]
405pythonize_display!(CRWriter);
406
407
408//---------------------------------------------------
409
410#[cfg(test)]
411mod tests {
412  use super::*;
413
414  /// The names of all files in a directory, sorted
415  fn files_in(dir : &Path) -> Vec<String> {
416    let mut names : Vec<String> = fs::read_dir(dir).unwrap()
417      .map(|f| f.unwrap().file_name().into_string().unwrap())
418      .collect();
419    names.sort();
420    names
421  }
422
423  fn frame_at(ts : Option<f64>) -> CRFrame {
424    let mut frame   = CRFrame::new();
425    frame.timestamp = ts;
426    frame
427  }
428
429  #[test]
430  fn crwriter_new_file_every_gcu_seconds() {
431    // the default file size must not prevent writing 
432    // a new file every file_len_gcu_sec seconds
433    let dir    = tempfile::tempdir().unwrap();
434    let t0     = 1_700_000_000.0;
435    let ts     = get_utc_timestamp_from_unix(t0);
436    let mut wr = CRWriter::new(dir.path().to_str().unwrap().to_string(), 42, None, ts.clone(), Some(60), false);
437    assert_ne!(wr.mbytes_per_file, 0);
438    for dt in [0.0, 30.0, 59.0, 61.0, 90.0, 122.0] {
439      wr.add_frame(&frame_at(Some(t0 + dt)));
440    }
441    // 0-61 s and 90-122 s. The frame at 122 s closes the second 
442    // file, but no (empty) third file is opened
443    let files = files_in(dir.path());
444    assert_eq!(files.len(), 2, "{:?}", files);
445    assert!(files.contains(&format!("Run42_0.{}.gaps", ts.unwrap())));
446    // the writer knows about the file it has last written to 
447    assert_eq!(wr.file_name, format!("{}/Run42_1.{}.gaps", dir.path().display(), get_utc_timestamp_from_unix(t0 + 61.0).unwrap()));
448  }
449
450  #[test]
451  fn crwriter_gcu_seconds_without_timestamp() {
452    // frames without timestamp must not crash the writer, 
453    // everything goes into the first file
454    let dir    = tempfile::tempdir().unwrap();
455    let ts     = get_utc_timestamp_from_unix(1_700_000_000.0);
456    let mut wr = CRWriter::new(dir.path().to_str().unwrap().to_string(), 42, None, ts, Some(60), false);
457    for _ in 0..5 {
458      wr.add_frame(&frame_at(None));
459    }
460    assert_eq!(files_in(dir.path()).len(), 1);
461  }
462
463  #[test]
464  fn crwriter_subrun_numbering() {
465    // the files continue counting from the given subrun id
466    let dir    = tempfile::tempdir().unwrap();
467    let mut wr = CRWriter::new(dir.path().to_str().unwrap().to_string(), 42, Some(5), Some(String::from("231114_221320")), None, false);
468    wr.pkts_per_file = 2;
469    let mut fnames = vec![wr.file_name.clone()];
470    for _ in 0..6 {
471      wr.add_frame(&frame_at(None));
472      if *fnames.last().unwrap() != wr.file_name {
473        fnames.push(wr.file_name.clone());
474      }
475    }
476    let subruns : Vec<String> = fnames.iter()
477      .map(|f| Path::new(f).file_name().unwrap().to_str().unwrap().split('.').next().unwrap().to_string())
478      .collect();
479    // no empty file Run42_8 after the last frame
480    assert_eq!(subruns, vec!["Run42_5", "Run42_6", "Run42_7"]);
481    assert_eq!(files_in(dir.path()).len(), 3);
482    // the current file name always points to a file which exists
483    for f in &fnames {
484      assert!(Path::new(f).exists(), "{}", f);
485    }
486  }
487
488  /// Read the summary from the footer of a file
489  fn read_summary(fname : &str) -> Option<CRFileSummary> {
490    let bytes = fs::read(fname).unwrap();
491    let len   = CRFileSummary::footer_len_from_trailer(&bytes)? as usize;
492    let frame = CRFrame::from_bytestream(&bytes, &mut (bytes.len() - len)).unwrap();
493    Some(frame.get::<CRFileSummary>(CRFILESUMMARY_NAME).unwrap())
494  }
495
496  /// A frame with a header and some data, or an empty 
497  /// frame for a missing event
498  fn event_frame(evid : u32, sources : &[GapsDataSource], gcutime : f64) -> CRFrame {
499    let mut frame  = CRFrame::new();
500    let mut header = CRFrameHeader::new();
501    header.event_id = evid;
502    for k in sources {
503      header.add_datasource(*k);
504    }
505    frame.put(header, CRFRAMEHEADER_NAME);
506    if !sources.is_empty() {
507      frame.put(TofPacket::new(), "TofPacket");
508      frame.timestamp = Some(gcutime);
509      frame.gpstime   = Some(gcutime + 18.0);
510    }
511    frame
512  }
513
514  #[test]
515  fn crwriter_footer() {
516    let dir    = tempfile::tempdir().unwrap();
517    let mut wr = CRWriter::new(dir.path().to_str().unwrap().to_string(), 42, Some(3), Some(String::from("231114_221320")), None);
518    let fname  = wr.file_name.clone();
519    for evid in 10..20u32 {
520      let frame = match evid {
521        // a cluster of missing events
522        12 | 13 | 14 => event_frame(evid, &[], 0.0),
523        // and a single one
524        17           => event_frame(evid, &[], 0.0),
525        _            => event_frame(evid, &[GapsDataSource::TOFCPU, GapsDataSource::GCU], 1000.0 + evid as f64),
526      };
527      wr.add_frame(&frame);
528    }
529    // nothing is written before the file is closed
530    assert_eq!(read_summary(&fname), None);
531    wr.close();
532    let s = read_summary(&fname).unwrap();
533    assert_eq!((s.run_id, s.subrun, s.n_frames), (42, 3, 10));
534    assert_eq!((s.min_evid, s.max_evid), (10, 19));
535    assert_eq!(s.missing_evid, vec![(12, 3), (17, 1)]);
536    assert_eq!(s.data_sources, vec![GapsDataSource::TOFCPU, GapsDataSource::GCU]);
537    assert_eq!((s.first_gcutime, s.last_gcutime), (1010.0, 1019.0));
538    assert_eq!((s.first_gpstime, s.last_gpstime), (1028.0, 1037.0));
539    // closing again does not write a second footer
540    let size = fs::metadata(&fname).unwrap().len();
541    wr.close();
542    assert_eq!(fs::metadata(&fname).unwrap().len(), size);
543    // a new frame goes into the next file with its own footer
544    wr.add_frame(&event_frame(20, &[GapsDataSource::AUXGCU], 2000.0));
545    assert!(wr.file_name.contains("Run42_4."));
546    let next = wr.file_name.clone();
547    drop(wr);
548    let s = read_summary(&next).unwrap();
549    assert_eq!((s.subrun, s.n_frames, s.min_evid, s.max_evid), (4, 1, 20, 20));
550    assert!(s.missing_evid.is_empty());
551  }
552
553  #[test]
554  fn crwriter_footer_on_drop_and_rotation() {
555    let dir    = tempfile::tempdir().unwrap();
556    {
557      let mut wr = CRWriter::new(dir.path().to_str().unwrap().to_string(), 42, None, Some(String::from("231114_221320")), None, false);
558      wr.pkts_per_file = 3;
559      for evid in 0..7u32 {
560        wr.add_frame(&event_frame(evid, &[GapsDataSource::TOFCPU], 1.0));
561      }
562      // the writer goes out of scope here
563    }
564    let files = files_in(dir.path());
565    assert_eq!(files.len(), 3, "{:?}", files);
566    let mut ranges = Vec::<(u64, u32, u32, u32)>::new();
567    for f in &files {
568      let s = read_summary(&format!("{}/{}", dir.path().display(), f)).unwrap();
569      ranges.push((s.subrun, s.n_frames, s.min_evid, s.max_evid));
570    }
571    ranges.sort();
572    assert_eq!(ranges, vec![(0, 3, 0, 2), (1, 3, 3, 5), (2, 1, 6, 6)]);
573  }
574
575  #[test]
576  fn crwriter_no_footer_without_frames() {
577    // the first file is created right away, it 
578    // stays empty if no frames are written
579    let dir    = tempfile::tempdir().unwrap();
580    let wr     = CRWriter::new(dir.path().to_str().unwrap().to_string(), 42, None, Some(String::from("231114_221320")), None, false);
581    let fname  = wr.file_name.clone();
582    drop(wr);
583    assert_eq!(fs::metadata(&fname).unwrap().len(), 0);
584  }
585
586  #[test]
587  fn crwriter_frames_without_header() {
588    // frames without CRFrameHeader are counted, but 
589    // do not give event ids
590    let dir    = tempfile::tempdir().unwrap();
591    let mut wr = CRWriter::new(dir.path().to_str().unwrap().to_string(), 42, None, Some(String::from("231114_221320")), None, false);
592    let fname  = wr.file_name.clone();
593    for _ in 0..4 {
594      wr.add_frame(&frame_at(Some(5.0)));
595    }
596    drop(wr);
597    let s = read_summary(&fname).unwrap();
598    assert_eq!((s.n_frames, s.min_evid, s.max_evid), (4, 0, 0));
599    assert_eq!((s.first_gcutime, s.last_gcutime), (5.0, 5.0));
600    assert!(s.data_sources.is_empty() && s.missing_evid.is_empty());
601  }
602
603  #[test]
604  fn crwriter_filled_empty_frame() {
605    // a frame which was empty (missing event) and got its 
606    // data later on is not missing anymore
607    let dir    = tempfile::tempdir().unwrap();
608    let mut wr = CRWriter::new(dir.path().to_str().unwrap().to_string(), 42, None, Some(String::from("231114_221320")), None, false);
609    let fname  = wr.file_name.clone();
610    let mut filled = event_frame(11, &[], 0.0);
611    filled.put(TofPacket::new(), "TofPacket");
612    filled.add_datasource(GapsDataSource::AUXGCU).unwrap();
613    wr.add_frame(&event_frame(10, &[GapsDataSource::TOFCPU], 1.0));
614    wr.add_frame(&filled);
615    wr.add_frame(&event_frame(12, &[], 0.0));
616    assert_eq!((wr.n_data_without_source, wr.n_empty_with_source), (0, 0));
617    drop(wr);
618    let s = read_summary(&fname).unwrap();
619    assert_eq!(s.missing_evid, vec![(12, 1)]);
620    assert_eq!(s.data_sources, vec![GapsDataSource::TOFCPU, GapsDataSource::AUXGCU]);
621  }
622
623  #[test]
624  fn crwriter_reports_inconsistent_headers() {
625    let dir    = tempfile::tempdir().unwrap();
626    let mut wr = CRWriter::new(dir.path().to_str().unwrap().to_string(), 42, None, Some(String::from("231114_221320")), None, false);
627    let fname  = wr.file_name.clone();
628    // data, but the data source was not added to the header
629    let mut forgotten = event_frame(20, &[], 0.0);
630    forgotten.put(TofPacket::new(), "TofPacket");
631    wr.add_frame(&forgotten);
632    wr.add_frame(&forgotten);
633    // only a header, but with data sources
634    let mut header  = CRFrameHeader::new();
635    header.event_id = 21;
636    header.add_datasource(GapsDataSource::GCU);
637    let mut empty   = CRFrame::new();
638    empty.put_header(header);
639    wr.add_frame(&empty);
640    assert_eq!((wr.n_data_without_source, wr.n_empty_with_source), (2, 1));
641    // the frames are written as they are
642    wr.close();
643    assert_eq!((wr.n_data_without_source, wr.n_empty_with_source), (0, 0));
644    let s = read_summary(&fname).unwrap();
645    assert_eq!(s.n_frames, 3);
646    assert_eq!(s.missing_evid, vec![(21, 1)]);
647    assert_eq!(s.data_sources, vec![GapsDataSource::GCU]);
648  }
649}