Skip to main content

tale_ndjson/readers/
backseeking.rs

1//! Backward-seeking file processor for negative and byte-based offsets on
2//! single files. Handles tail-like functionality (last N lines/bytes).
3
4use std::fs::File;
5use std::io::{self, BufRead, BufReader, Read, Seek, Write};
6use std::path::PathBuf;
7use std::time::{Duration, Instant};
8
9use bytes::BytesMut;
10use miette::IntoDiagnostic;
11
12use super::FileProcessor;
13use crate::config::OffsetUnit;
14use crate::defaults::io::*;
15use crate::errors::TaleError;
16use crate::{config, process_line, strip_line_ending};
17
18pub struct BackSeekingProcessor {
19    fpath: PathBuf,
20    initial_file_size: u64,
21    file: Option<File>,
22    // `io::stdout().lock()` yields a `'static` guard — stdout is a process
23    // global — so this processor never needs a lifetime parameter.
24    outlock: io::BufWriter<io::StdoutLock<'static>>,
25    buffer: BytesMut,
26    count: u16,
27}
28
29impl FileProcessor for BackSeekingProcessor {
30    fn process_lines<F>(&mut self, mut line_processor: F) -> Result<(), TaleError>
31    where
32        F: FnMut(&str) -> Result<(), TaleError>,
33    {
34        let file = self.move_to_position(0, OffsetUnit::Lines, false)?;
35        let mut reader = BufReader::new(file);
36
37        let mut line = String::with_capacity(LINE_CAPACITY);
38        while reader.read_line(&mut line)? != 0 {
39            strip_line_ending(&mut line);
40            line_processor(line.as_str())?;
41            line.clear();
42        }
43
44        Ok(())
45    }
46
47    fn skip_lines(&mut self, count: u64) -> Result<(), TaleError> {
48        let file = self.move_to_position(count as i64, OffsetUnit::Lines, false)?;
49        self.file = Some(file);
50        Ok(())
51    }
52
53    fn file_size(&self) -> u64 {
54        self.initial_file_size
55    }
56
57    fn seek(&mut self, pos: io::SeekFrom) -> Result<u64, TaleError> {
58        if let Some(mut f) = self.file.as_ref() {
59            Ok(f.seek(pos).map_err(TaleError::from)?)
60        } else {
61            let mut file = File::open(&self.fpath).map_err(TaleError::from)?;
62            let actual = file.seek(pos).map_err(TaleError::from)?;
63            self.file = Some(file);
64            Ok(actual)
65        }
66    }
67
68    fn position(&self) -> u64 {
69        if let Some(mut f) = self.file.as_ref() {
70            f.stream_position().unwrap_or_default()
71        } else {
72            0
73        }
74    }
75}
76
77impl BackSeekingProcessor {
78    pub fn new(fpath: PathBuf) -> Self {
79        // briefly open the file and figure out its size
80        let file_size = if let Ok(mut file) = File::open(&fpath) {
81            file.seek(io::SeekFrom::End(0)).unwrap_or_default()
82        } else {
83            0
84        };
85
86        Self {
87            fpath,
88            initial_file_size: file_size,
89            file: None,
90            outlock: crate::buffered_stdout(),
91            buffer: BytesMut::with_capacity(OUTPUT_BUFFER_CAPACITY),
92            count: 0,
93        }
94    }
95
96    /// Find the right file offset to start reading & printing this file from,
97    /// given the arg input. This seeks forward or backwards by lines, and
98    /// returns the current file position. As a side effect, the file is
99    /// left at the correct position to begin reading. IMPORTANT: The caller
100    /// has to do any last by-lines forward seeking by themselves. This is a
101    /// weakness in the internal API.
102    pub fn move_to_position(
103        &mut self,
104        offset: i64,
105        units: config::OffsetUnit,
106        tailing: bool,
107    ) -> Result<File, TaleError> {
108        let mut file = File::open(&self.fpath)?;
109        // Short circuit if there is no work to do.
110        let file_size = file.seek(io::SeekFrom::End(0))?;
111        if file_size == 0 {
112            return Ok(file);
113        }
114
115        // Reset to start after size read.
116        file.seek(io::SeekFrom::Start(0))?;
117
118        // Set our position in the file based on offset unit.
119        match units {
120            config::OffsetUnit::Lines => {
121                if offset < 0 {
122                    // Negative offset: start N lines from the end
123                    let start = self.move_n_lines_back(&mut file, (-offset) as u64)?;
124                    file.seek(io::SeekFrom::Start(start))?;
125                } else if offset == 0 && tailing {
126                    // Zero offset while tailing: start from the end (show only
127                    // new data)
128                    file.seek(io::SeekFrom::End(0))?;
129                }
130                // Positive offset: caller handles forward-skipping lines
131            }
132            config::OffsetUnit::Bytes => {
133                if offset > 0 {
134                    // Positive offset: skip N bytes from the beginning
135                    file.seek(io::SeekFrom::Start(offset as u64))?;
136                } else if offset < 0 {
137                    // Negative offset: start N bytes from the end
138                    file.seek(io::SeekFrom::End(offset))?;
139                } else if tailing {
140                    // Zero offset while tailing: start from the end
141                    file.seek(io::SeekFrom::End(0))?;
142                }
143            }
144        }
145
146        Ok(file)
147    }
148
149    /// Find the byte offset from the beginning of the file for the start of the
150    /// line to begin our pretty-printing. This is the seek backwards version.
151    /// It is made entirely of edge cases. Used only by
152    /// FileProcessor::move_to_position().
153    fn move_n_lines_back(&mut self, file: &mut File, line_count: u64) -> Result<u64, TaleError> {
154        let file_size = file.seek(io::SeekFrom::End(0))?;
155        if file_size == 0 {
156            return Ok(0);
157        }
158
159        const BUFFER_SIZE: usize = 8192;
160        let mut buffer = vec![0u8; BUFFER_SIZE];
161        let mut lines_found = 0u64;
162
163        // First check if the file ends with a newline
164        file.seek(io::SeekFrom::End(-1))?;
165        let mut last_byte = [0u8; 1];
166        file.read_exact(&mut last_byte)?;
167        let ends_with_newline = last_byte[0] == b'\n';
168
169        // To get the last N lines, we need to find the right number of newlines
170        // For a file that doesn't end with newline: last line is after the last
171        // newline For a file that ends with newline: last line is
172        // between the last two newlines
173        let target_newlines = if ends_with_newline { line_count } else { line_count - 1 };
174
175        let mut pos = file_size;
176
177        loop {
178            // how much should we read?
179            let chunk_size = std::cmp::min(BUFFER_SIZE as u64, pos) as usize;
180            if chunk_size == 0 {
181                // We've reached the beginning of the file
182                return Ok(0);
183            }
184
185            // Read a chonk. Chunk. Whatever.
186            pos -= chunk_size as u64;
187            file.seek(io::SeekFrom::Start(pos))?;
188            file.read_exact(&mut buffer[..chunk_size])?;
189
190            // Count newlines in reverse order
191            for (i, &byte) in buffer[..chunk_size].iter().enumerate().rev() {
192                if byte == b'\n' {
193                    lines_found += 1;
194                    if lines_found > target_newlines {
195                        // Found enough lines, return position after this
196                        // newline
197                        return Ok(pos + i as u64 + 1);
198                    }
199                }
200            }
201
202            // We hit the beginning: not enough lines. We start at the very
203            // beginning, a very good place to start.
204            if pos == 0 {
205                return Ok(0);
206            }
207        }
208    }
209
210    /// Process a single line through the formatting pipeline
211    pub fn process_line(&mut self, line: &str) -> Result<(), TaleError> {
212        process_line(line, &mut self.buffer, &mut self.outlock)
213            .map_err(|e| TaleError::from(std::io::Error::other(e.to_string())))?;
214        self.count += 1;
215        self.flush_if_needed()
216    }
217
218    /// Flush output if we've processed enough lines
219    pub fn flush_if_needed(&mut self) -> Result<(), TaleError> {
220        if self.count >= FLUSH_LINE_COUNT {
221            self.outlock.flush()?;
222            self.count = 0;
223        }
224        Ok(())
225    }
226
227    /// Force flush output
228    pub fn flush(&mut self) -> Result<(), TaleError> {
229        self.outlock.flush()?;
230        self.count = 0;
231        Ok(())
232    }
233
234    pub fn tail(&mut self) -> miette::Result<()> {
235        let tailing = config::tailing();
236        let offset_unit = config::offset_unit();
237        let offset = config::offset();
238
239        let file = self
240            .move_to_position(offset, offset_unit, tailing)
241            .map_err(miette::Report::from)?;
242        let mut reader = BufReader::new(file);
243
244        // If we've got a positive line offset, we still need to skip our N
245        // lines
246        if offset > 0 && matches!(offset_unit, config::OffsetUnit::Lines) {
247            let consume_me = (&mut reader).lines().take(offset as usize);
248            // We then must consume them. this feels v inefficient but I do not
249            // know.
250            let _count = consume_me.count();
251        };
252
253        // Now at last we get to start printing. What a fuss.
254        let mut line = String::with_capacity(LINE_CAPACITY);
255        while reader.read_line(&mut line).into_diagnostic()? != 0 {
256            strip_line_ending(&mut line);
257            self.process_line(line.as_str()).map_err(miette::Report::from)?;
258            line.clear();
259        }
260        self.flush().map_err(miette::Report::from)?;
261
262        if !tailing {
263            return Ok(());
264        }
265
266        // Keep the same BufReader alive across the polling loop so its internal
267        // buffer stays consistent with the file position. Re-creating BufReader
268        // each iteration caused it to read-ahead up to 8KB, advance the OS file
269        // position, and then stream_position() would record that inflated
270        // offset, silently skipping all the lines that were buffered
271        // but not yet consumed.
272        let mut last_flush = Instant::now();
273
274        loop {
275            match reader.read_line(&mut line).into_diagnostic()? {
276                0 => {
277                    // EOF - no new data yet; flush pending output and poll
278                    // again
279                    if last_flush.elapsed() >= TAIL_FLUSH_INTERVAL {
280                        crate::flush_out(&mut self.outlock)?;
281                        last_flush = Instant::now();
282                    }
283                    std::thread::sleep(Duration::from_millis(100));
284                }
285                _ => {
286                    strip_line_ending(&mut line);
287                    process_line(&line, &mut self.buffer, &mut self.outlock)?;
288                    line.clear();
289                    self.buffer.clear();
290                    if last_flush.elapsed() >= TAIL_FLUSH_INTERVAL {
291                        crate::flush_out(&mut self.outlock)?;
292                        last_flush = Instant::now();
293                    }
294                }
295            }
296        }
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    #[test]
305    fn move_to_position_tailing_zero_offset_starts_at_end() {
306        use std::io::{Read, Write};
307
308        use tempfile::NamedTempFile;
309
310        let mut temp_file = NamedTempFile::new().expect("Failed to create temp file");
311        temp_file
312            .write_all(b"line1\nline2\nline3\n")
313            .expect("Failed to write to temp file");
314
315        let mut processor = BackSeekingProcessor::new(PathBuf::from(temp_file.path()));
316        let mut file = processor
317            .move_to_position(0, config::OffsetUnit::Lines, true)
318            .expect("move_to_position should succeed");
319
320        // tailing with no offset starts at EOF: nothing to read until new data
321        // arrives
322        let mut result = String::new();
323        file.read_to_string(&mut result).expect("Failed to read file");
324        assert_eq!(result, "");
325    }
326
327    #[test]
328    fn move_to_position_negative_offset_seeks_from_end() {
329        use std::io::{Read, Write};
330
331        use tempfile::NamedTempFile;
332
333        let mut temp_file = NamedTempFile::new().expect("Failed to create temp file");
334        temp_file
335            .write_all(b"line1\nline2\nline3\nline4\nline5\n")
336            .expect("Failed to write to temp file");
337
338        let mut processor = BackSeekingProcessor::new(PathBuf::from(temp_file.path()));
339        let mut file = processor
340            .move_to_position(-2, config::OffsetUnit::Lines, false)
341            .expect("move_to_position should succeed");
342
343        let mut result = String::new();
344        file.read_to_string(&mut result).expect("Failed to read file");
345        assert_eq!(result, "line4\nline5\n");
346    }
347
348    #[test]
349    fn seeking_backwards() {
350        use std::io::{Read, Seek, Write};
351
352        use tempfile::NamedTempFile;
353
354        // Create a temporary file with known content
355        let mut temp_file = NamedTempFile::new().expect("Failed to create temp file");
356        let content = "line1\nline2\nline3\nline4\nline5\n";
357        temp_file
358            .write_all(content.as_bytes())
359            .expect("Failed to write to temp file");
360
361        let pathbuf = PathBuf::from(temp_file.path());
362        let mut processor = BackSeekingProcessor::new(pathbuf);
363        let mut file = File::open(temp_file.path()).expect("Failed to open temp file");
364
365        // Test getting last 2 lines (should start after "line3\n")
366        let pos = processor
367            .move_n_lines_back(&mut file, 2)
368            .expect("Failed to find position");
369        file.seek(io::SeekFrom::Start(pos)).expect("Failed to seek");
370
371        let mut remaining = String::new();
372        file.read_to_string(&mut remaining).expect("Failed to read remaining");
373        assert_eq!(remaining, "line4\nline5\n");
374
375        // Test getting last line (should start after "line4\n")
376        let pos = processor
377            .move_n_lines_back(&mut file, 1)
378            .expect("Failed to find position");
379        file.seek(io::SeekFrom::Start(pos)).expect("Failed to seek");
380
381        let mut remaining = String::new();
382        file.read_to_string(&mut remaining).expect("Failed to read remaining");
383        assert_eq!(remaining, "line5\n");
384
385        // Test getting more lines than exist (should start from beginning)
386        let pos = processor
387            .move_n_lines_back(&mut file, 10)
388            .expect("Failed to find position");
389        assert_eq!(pos, 0);
390    }
391
392    #[test]
393    fn seeking_in_empty() {
394        use tempfile::NamedTempFile;
395        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
396        let pathbuf = PathBuf::from(temp_file.path());
397        let mut processor = BackSeekingProcessor::new(pathbuf);
398        let mut file = File::open(temp_file.path()).expect("Failed to open temp file");
399
400        let pos = processor
401            .move_n_lines_back(&mut file, 5)
402            .expect("Failed to find position");
403        assert_eq!(pos, 0);
404    }
405
406    #[test]
407    fn good_circular_buffer_byte_logic() {
408        // Test the circular buffer logic without stdin dependency
409        let input_data = b"0123456789abcdefghij";
410        let buffer_size = 10;
411        let mut circular_buffer = vec![0u8; buffer_size];
412        let mut pos = 0usize;
413
414        // Simulate writing to circular buffer
415        for &byte in input_data {
416            circular_buffer[pos % buffer_size] = byte;
417            pos += 1;
418        }
419
420        // Should have wrapped around, last 10 bytes should be "abcdefghij"
421        let _total_read = input_data.len() as u64;
422        let _bytes_to_show = buffer_size as u64;
423        let start_pos = pos % buffer_size;
424
425        // Extract the last bytes_to_show bytes
426        let mut result = Vec::with_capacity(buffer_size);
427        for i in 0..buffer_size {
428            result.push(circular_buffer[(start_pos + i) % buffer_size]);
429        }
430
431        assert_eq!(result, b"abcdefghij");
432    }
433
434    #[test]
435    fn circular_buffer_partial_fill_works() {
436        // Test circular buffer when input is smaller than buffer
437        let input_data = b"hello";
438        let buffer_size = 10;
439        let mut circular_buffer = vec![0u8; buffer_size];
440
441        // Fill buffer
442        for (i, &byte) in input_data.iter().enumerate() {
443            circular_buffer[i] = byte;
444        }
445
446        let bytes_to_output = input_data.len();
447        let result = &circular_buffer[..bytes_to_output];
448
449        assert_eq!(result, b"hello");
450    }
451
452    #[test]
453    fn circular_line_logic() {
454        use std::collections::VecDeque;
455
456        // Test VecDeque circular behavior for line buffering
457        let lines_to_keep = 3;
458        let mut line_buffer: VecDeque<String> = VecDeque::with_capacity(lines_to_keep);
459
460        let input_lines = vec!["line1", "line2", "line3", "line4", "line5"];
461
462        for line in input_lines {
463            if line_buffer.len() >= lines_to_keep {
464                line_buffer.pop_front();
465            }
466            line_buffer.push_back(line.to_string());
467        }
468
469        // Should contain last 3 lines
470        let result: Vec<String> = line_buffer.into_iter().collect();
471        assert_eq!(result, vec!["line3", "line4", "line5"]);
472    }
473
474    #[test]
475    fn handles_overshoots_correctly() {
476        let overshoot = b"partial line\ncomplete line\nanother";
477        let overshoot_str = String::from_utf8_lossy(overshoot);
478        let mut remaining = overshoot_str.as_ref();
479        let mut complete_lines = Vec::new();
480
481        while let Some(pos) = remaining.find('\n') {
482            complete_lines.push(&remaining[..pos]);
483            remaining = &remaining[pos + 1..];
484        }
485
486        assert_eq!(complete_lines, vec!["partial line", "complete line"]);
487        assert_eq!(remaining, "another");
488    }
489}