|
| 1 | +use csv::{Writer, WriterBuilder}; |
| 2 | +use serde::Serialize; |
| 3 | +use std::fs::File; |
| 4 | +use std::path::PathBuf; |
| 5 | + |
| 6 | +use crate::SimulationError; |
| 7 | + |
| 8 | +/// Implements a writer that will write records in batches to the file provided. |
| 9 | +pub struct BatchedWriter { |
| 10 | + batch_size: u32, |
| 11 | + counter: u32, |
| 12 | + writer: Writer<File>, |
| 13 | +} |
| 14 | + |
| 15 | +impl BatchedWriter { |
| 16 | + /// Creates a new writer and the results file that output will be written to. |
| 17 | + pub fn new( |
| 18 | + directory: PathBuf, |
| 19 | + file_name: String, |
| 20 | + batch_size: u32, |
| 21 | + ) -> Result<BatchedWriter, SimulationError> { |
| 22 | + if batch_size == 0 { |
| 23 | + return Err(SimulationError::FileError); |
| 24 | + } |
| 25 | + |
| 26 | + let file = directory.join(file_name); |
| 27 | + |
| 28 | + let writer = WriterBuilder::new() |
| 29 | + .from_path(file) |
| 30 | + .map_err(SimulationError::CsvError)?; |
| 31 | + |
| 32 | + Ok(BatchedWriter { |
| 33 | + batch_size, |
| 34 | + counter: 0, |
| 35 | + writer, |
| 36 | + }) |
| 37 | + } |
| 38 | + |
| 39 | + /// Adds an item to the batch to be written, flushing to disk if the batch size has been reached. |
| 40 | + pub fn queue<S: Serialize>(&mut self, record: S) -> Result<(), SimulationError> { |
| 41 | + // If there's an error serializing an input, flush and exit with an error. |
| 42 | + self.writer.serialize(record).map_err(|e| { |
| 43 | + // If we encounter another errors (when we've already failed to serialize), we just log because we've |
| 44 | + // already experienced a critical error. |
| 45 | + if let Err(e) = self.write(true) { |
| 46 | + log::error!("Error flushing to disk: {e}"); |
| 47 | + } |
| 48 | + |
| 49 | + SimulationError::CsvError(e) |
| 50 | + })?; |
| 51 | + |
| 52 | + // Otherwise increment counter and flush if we've reached batch size. |
| 53 | + self.counter = self.counter % self.batch_size + 1; |
| 54 | + self.write(false) |
| 55 | + } |
| 56 | + |
| 57 | + /// Writes the contents of the batched writer to disk. Will result in a write if force is true _or_ the batch is |
| 58 | + /// full. |
| 59 | + pub fn write(&mut self, force: bool) -> Result<(), SimulationError> { |
| 60 | + if force || self.batch_size == self.counter { |
| 61 | + self.counter = 0; |
| 62 | + return self |
| 63 | + .writer |
| 64 | + .flush() |
| 65 | + .map_err(|e| SimulationError::CsvError(e.into())); |
| 66 | + } |
| 67 | + |
| 68 | + Ok(()) |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +#[cfg(test)] |
| 73 | +mod tests { |
| 74 | + use super::*; |
| 75 | + use serde::{Deserialize, Serialize}; |
| 76 | + use tempfile::tempdir; |
| 77 | + |
| 78 | + #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Copy)] |
| 79 | + struct TestRecord { |
| 80 | + id: u32, |
| 81 | + } |
| 82 | + |
| 83 | + fn read_csv_contents(file_path: &PathBuf) -> Vec<TestRecord> { |
| 84 | + let mut reader = csv::Reader::from_path(file_path).unwrap(); |
| 85 | + reader.deserialize().map(|r| r.unwrap()).collect() |
| 86 | + } |
| 87 | + |
| 88 | + #[test] |
| 89 | + fn test_basic_write_and_flush_on_batch_size() { |
| 90 | + let dir = tempdir().unwrap(); |
| 91 | + let file_name = "test_basic_write_and_flush_on_batch_size.csv".to_string(); |
| 92 | + let file_path = dir.path().join(&file_name); |
| 93 | + let mut writer = BatchedWriter::new(dir.path().to_path_buf(), file_name, 2).unwrap(); |
| 94 | + |
| 95 | + let rec1 = TestRecord { id: 1 }; |
| 96 | + let rec2 = TestRecord { id: 2 }; |
| 97 | + |
| 98 | + writer.queue(rec1).unwrap(); |
| 99 | + writer.queue(rec2).unwrap(); |
| 100 | + |
| 101 | + assert!(file_path.exists(), "File should exist after flush"); |
| 102 | + let records = read_csv_contents(&file_path); |
| 103 | + assert_eq!(records, vec![rec1, rec2]); |
| 104 | + |
| 105 | + // Queuing a record that doesn't hit our batch limit shouldn't flush. |
| 106 | + let rec3 = TestRecord { id: 3 }; |
| 107 | + |
| 108 | + writer.queue(rec3).unwrap(); |
| 109 | + let records = read_csv_contents(&file_path); |
| 110 | + assert_eq!(records, vec![rec1, rec2]); |
| 111 | + |
| 112 | + // Force flushing should write even if batch isn't hit. |
| 113 | + writer.write(true).unwrap(); |
| 114 | + let records = read_csv_contents(&file_path); |
| 115 | + assert_eq!(records, vec![rec1, rec2, rec3]); |
| 116 | + } |
| 117 | + |
| 118 | + #[test] |
| 119 | + fn test_forced_flush() { |
| 120 | + let dir = tempdir().unwrap(); |
| 121 | + let file_name = "test_forced_flush.csv".to_string(); |
| 122 | + let file_path = dir.path().join(&file_name); |
| 123 | + let mut writer = BatchedWriter::new(dir.path().to_path_buf(), file_name, 10).unwrap(); |
| 124 | + |
| 125 | + let rec = TestRecord { id: 1 }; |
| 126 | + writer.queue(rec).unwrap(); |
| 127 | + |
| 128 | + writer.write(true).unwrap(); |
| 129 | + assert!(file_path.exists(), "File should exist after forced flush"); |
| 130 | + let records = read_csv_contents(&file_path); |
| 131 | + assert_eq!(records, vec![rec]); |
| 132 | + } |
| 133 | + |
| 134 | + #[test] |
| 135 | + fn test_zero_batch_size() { |
| 136 | + let dir = tempdir().unwrap(); |
| 137 | + let file_name = "test_zero_batch_size_no_auto_flush.csv".to_string(); |
| 138 | + assert!(BatchedWriter::new(dir.path().to_path_buf(), file_name, 0).is_err()); |
| 139 | + } |
| 140 | + |
| 141 | + /// Create a record that can't be serialized. |
| 142 | + struct BadRecord {} |
| 143 | + |
| 144 | + impl Serialize for BadRecord { |
| 145 | + fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error> |
| 146 | + where |
| 147 | + S: serde::Serializer, |
| 148 | + { |
| 149 | + Err(serde::ser::Error::custom("intentional failure")) |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + #[test] |
| 154 | + fn test_serialization_error() { |
| 155 | + let dir = tempdir().unwrap(); |
| 156 | + let file_name = "test_serialization_error.csv".to_string(); |
| 157 | + let file_path = dir.path().join(&file_name); |
| 158 | + let mut writer = BatchedWriter::new(dir.path().to_path_buf(), file_name, 2).unwrap(); |
| 159 | + |
| 160 | + let rec = TestRecord { id: 1 }; |
| 161 | + writer.queue(rec).unwrap(); |
| 162 | + |
| 163 | + let bad = BadRecord {}; |
| 164 | + let result = writer.queue(bad); |
| 165 | + assert!(result.is_err()); |
| 166 | + |
| 167 | + writer.write(true).unwrap(); |
| 168 | + assert!(file_path.exists(), "File should exist after forced flush"); |
| 169 | + let records = read_csv_contents(&file_path); |
| 170 | + assert_eq!(records, vec![rec]); |
| 171 | + } |
| 172 | +} |
0 commit comments