1mod backseeking;
15mod buffered;
16mod chunked; mod stdin;
18pub mod strategies; use std::io::SeekFrom;
21use std::path::{Path, PathBuf};
22
23pub use backseeking::*;
24pub use buffered::*;
25use bytes::BytesMut;
26pub use chunked::*;
27use miette::Result;
28use owo_colors::OwoColorize;
29pub use stdin::*;
30pub use strategies::*;
31
32use crate::defaults::io::*;
33use crate::defaults::processing::*;
34use crate::errors::{FileError, TaleError, find_similar_files};
35use crate::multiplexed::watcher::{MultiFileWatcher, WatchEvent};
36use crate::{config, process_line};
37
38fn tale_error_from_report(report: miette::Report) -> TaleError {
44 for cause in report.chain() {
45 if let Some(io_err) = cause.downcast_ref::<std::io::Error>() {
46 return TaleError::from(std::io::Error::new(io_err.kind(), io_err.to_string()));
47 }
48 }
49 TaleError::from(std::io::Error::other(report.to_string()))
50}
51
52async fn wait_for_file_creation(target_path: &Path) -> Result<()> {
54 use std::time::Duration;
55
56 eprintln!("Watching for '{}'…", target_path.display().yellow().bold());
57
58 let parent_dir = target_path.parent().ok_or_else(|| {
60 TaleError::from(Box::new(FileError::NotFound {
61 path: target_path.to_path_buf(),
62 similar_files: vec!["Parent directory not found".to_string()],
63 }))
64 })?;
65
66 if !parent_dir.exists() {
68 return Err(TaleError::from(Box::new(FileError::NotFound {
69 path: parent_dir.to_path_buf(),
70 similar_files: vec!["Parent directory must exist for file watching".to_string()],
71 }))
72 .into());
73 }
74
75 let target_filename = target_path.file_name().and_then(|n| n.to_str()).ok_or_else(|| {
76 miette::Report::from(TaleError::from(Box::new(FileError::NotFound {
77 path: target_path.to_path_buf(),
78 similar_files: vec!["Invalid filename".to_string()],
79 })))
80 })?;
81
82 let mut watcher = MultiFileWatcher::new();
84
85 watcher.add_files(vec![parent_dir]).await?;
87
88 let mut event_receiver = watcher.watch().await?;
90
91 let mut elapsed_seconds = 0;
92 let mut last_message_time = std::time::Instant::now();
93
94 loop {
95 match tokio::time::timeout(Duration::from_secs(5), event_receiver.recv()).await {
97 Ok(Some(event)) => {
98 match event {
99 WatchEvent::FileCreated(created_path) => {
100 if let Some(created_filename) = created_path.file_name().and_then(|n| n.to_str())
101 && created_filename == target_filename
102 {
103 eprintln!("+++> '{}' created; tailing", target_filename.yellow().bold());
104 return Ok(());
105 }
106 }
107 WatchEvent::Error(_err) => {
108 }
110 _ => {
111 }
113 }
114 }
115 Ok(None) => {
116 return Err(TaleError::from(Box::new(FileError::NotFound {
118 path: target_path.to_path_buf(),
119 similar_files: vec!["File watcher stopped unexpectedly".to_string()],
120 }))
121 .into());
122 }
123 Err(_) => {
124 elapsed_seconds += 5;
126 if last_message_time.elapsed() >= Duration::from_secs(30) {
127 eprintln!(
128 "Still watching for '{}' ({}s elapsed)...",
129 target_path.display().yellow().bold(),
130 elapsed_seconds.bright_magenta()
131 );
132 last_message_time = std::time::Instant::now();
133 }
134
135 if target_path.exists() {
138 eprintln!("+++> '{}' created; tailing", target_filename.yellow().bold());
139 return Ok(());
140 }
141 }
142 }
143 }
144}
145
146pub async fn handle_file(fpath: &Path) -> Result<()> {
148 let sticky = config::sticky();
149
150 if !fpath.exists() {
152 if sticky {
153 wait_for_file_creation(fpath).await?;
155
156 if !fpath.is_file() {
159 return Err(TaleError::from(Box::new(FileError::not_a_file_with_type(fpath.to_path_buf()))).into());
160 }
161 } else {
162 let similar_files = find_similar_files(fpath);
164 return Err(TaleError::from(Box::new(FileError::not_found_with_suggestions(
165 fpath.to_path_buf(),
166 similar_files,
167 )))
168 .into());
169 }
170 }
171
172 if !fpath.is_file() {
174 return Err(TaleError::from(Box::new(FileError::not_a_file_with_type(fpath.to_path_buf()))).into());
175 }
176
177 let mut processor = create_file_processor(fpath, None).map_err(|e| enhance_error_context(e, fpath))?;
179
180 if let FileProcessorType::BackSeeking(mut backseeker) = processor {
183 return backseeker.tail();
184 }
185
186 let offset = config::offset();
188 let offset_unit = config::offset_unit();
189
190 match (offset.is_positive(), offset_unit) {
192 (true, config::OffsetUnit::Lines) if offset > 0 => {
194 processor.skip_lines(offset as u64)?;
195
196 let mut buffer = BytesMut::with_capacity(OUTPUT_BUFFER_CAPACITY);
198 let mut outlock = crate::buffered_stdout();
199
200 processor
201 .process_lines(|line| process_line(line, &mut buffer, &mut outlock).map_err(tale_error_from_report))?;
202
203 crate::flush_out(&mut outlock)?;
204 }
205
206 _ => {
208 let mut buffer = BytesMut::with_capacity(OUTPUT_BUFFER_CAPACITY);
209 let mut outlock = crate::buffered_stdout();
210
211 processor
212 .process_lines(|line| process_line(line, &mut buffer, &mut outlock).map_err(tale_error_from_report))?;
213
214 crate::flush_out(&mut outlock)?;
215 }
216 }
217 Ok(())
218}
219
220fn enhance_error_context(error: TaleError, path: &Path) -> TaleError {
221 match error {
222 TaleError::Io(io_error) => {
223 let crate::errors::IoError::OperationFailed { source, .. } = io_error.as_ref();
224 if source.kind() == std::io::ErrorKind::PermissionDenied {
225 let suggestion = if cfg!(unix) {
226 Some(format!("Try: chmod +r {}", path.display()))
227 } else {
228 Some("Check file permissions in Properties".to_string())
229 };
230 Box::new(FileError::permission_denied_with_suggestion(
231 path.to_path_buf(),
232 suggestion,
233 ))
234 .into()
235 } else {
236 TaleError::Io(io_error)
237 }
238 }
239 other => other,
240 }
241}
242
243pub fn create_file_processor<P: AsRef<Path>>(
245 path: P,
246 file_size_hint: Option<u64>,
247) -> Result<FileProcessorType, TaleError> {
248 let path = path.as_ref();
249
250 let file_size = file_size_hint.unwrap_or_else(|| std::fs::metadata(path).map(|m| m.len()).unwrap_or(0));
252
253 let offset = config::offset();
254 let offset_unit = config::offset_unit();
255 let large_offset = offset.abs() > LARGE_OFFSET_THRESHOLD as i64;
256
257 let use_chunked = !config::disable_chunked()
259 && (config::force_chunked()
260 || (file_size > CHUNKED_WITH_OFFSET_FILE_SIZE && large_offset)
261 || file_size > ALWAYS_CHUNKED_FILE_SIZE);
262
263 if offset < 0 || matches!(offset_unit, config::OffsetUnit::Bytes) || config::tailing() {
266 let processor = BackSeekingProcessor::new(PathBuf::from(path));
267 return Ok(FileProcessorType::BackSeeking(processor));
268 }
269
270 if use_chunked {
271 let reader = ChunkedFileReader::with_optimal_config(path)?;
272 return Ok(FileProcessorType::Chunked(Box::new(reader)));
273 }
274
275 let reader = BufferedFileProcessor::new(path)?;
277 Ok(FileProcessorType::Buffered(reader))
278}
279
280pub trait FileProcessor {
282 fn process_lines<F>(&mut self, line_processor: F) -> Result<(), TaleError>
284 where
285 F: FnMut(&str) -> Result<(), TaleError>;
286
287 fn skip_lines(&mut self, count: u64) -> Result<(), TaleError>;
289
290 fn file_size(&self) -> u64;
292
293 fn seek(&mut self, pos: SeekFrom) -> Result<u64, TaleError>;
295
296 fn position(&self) -> u64;
298}
299
300pub enum FileProcessorType {
302 Buffered(BufferedFileProcessor),
303 Chunked(Box<ChunkedFileReader>),
304 BackSeeking(BackSeekingProcessor),
305}
306
307impl FileProcessor for FileProcessorType {
308 fn process_lines<F>(&mut self, line_processor: F) -> Result<(), TaleError>
309 where
310 F: FnMut(&str) -> Result<(), TaleError>,
311 {
312 match self {
313 FileProcessorType::Buffered(processor) => processor.process_lines(line_processor),
314 FileProcessorType::Chunked(processor) => processor.process_lines(line_processor),
315 FileProcessorType::BackSeeking(processor) => processor.process_lines(line_processor),
316 }
317 }
318
319 fn skip_lines(&mut self, count: u64) -> Result<(), TaleError> {
320 match self {
321 FileProcessorType::Buffered(processor) => processor.skip_lines(count),
322 FileProcessorType::Chunked(processor) => processor.skip_lines(count),
323 FileProcessorType::BackSeeking(processor) => processor.skip_lines(count),
324 }
325 }
326
327 fn file_size(&self) -> u64 {
328 match self {
329 FileProcessorType::Buffered(processor) => processor.file_size(),
330 FileProcessorType::Chunked(processor) => processor.file_size(),
331 FileProcessorType::BackSeeking(processor) => processor.file_size(),
332 }
333 }
334
335 fn seek(&mut self, pos: SeekFrom) -> Result<u64, TaleError> {
336 match self {
337 FileProcessorType::Buffered(processor) => processor.seek(pos),
338 FileProcessorType::Chunked(processor) => processor.seek(pos),
339 FileProcessorType::BackSeeking(processor) => processor.seek(pos),
340 }
341 }
342
343 fn position(&self) -> u64 {
344 match self {
345 FileProcessorType::Buffered(processor) => processor.position(),
346 FileProcessorType::Chunked(processor) => processor.position(),
347 FileProcessorType::BackSeeking(processor) => processor.position(),
348 }
349 }
350}
351
352#[cfg(test)]
353mod tests {
354 use std::io::Write;
355
356 use tempfile::NamedTempFile;
357
358 use super::*;
359 use crate::config::ConfigOpts;
360 use crate::tests::TestLogPattern;
361
362 fn create_test_file(content: &str) -> NamedTempFile {
363 let mut file = NamedTempFile::new().expect("Failed to create temp file");
364 file.write_all(content.as_bytes()).expect("Failed to write test data");
365 file.flush().expect("Failed to flush test file");
366 file
367 }
368
369 #[test]
370 fn chonk_size_optimizer() {
371 assert_eq!(optimal_chunk_size(500_000), 8_192);
373
374 assert_eq!(optimal_chunk_size(50_000_000), 131_072); assert_eq!(optimal_chunk_size(500_000_000), 524_288); }
384
385 #[test]
386 fn processor_selection() {
387 let testfp = crate::tests::create_test_file(120_000, TestLogPattern::Canonical);
388
389 crate::config::with_config(
391 ConfigOpts {
392 offset: -20,
393 offset_unit: config::OffsetUnit::Lines,
394 force_chunked: false,
395 disable_chunked: false,
396 ..ConfigOpts::default()
397 },
398 || {
399 let result = create_file_processor(&testfp, Some(1_000_000_000))
400 .expect("should create processor for negative offset");
401 assert!(
402 matches!(result, FileProcessorType::BackSeeking(_)),
403 "Negative offset should use Simple processor"
404 );
405 },
406 );
407
408 crate::config::with_config(
410 ConfigOpts {
411 offset: 100,
412 offset_unit: config::OffsetUnit::Bytes,
413 force_chunked: false,
414 disable_chunked: false,
415 ..ConfigOpts::default()
416 },
417 || {
418 let result = create_file_processor(&testfp, Some(1_000_000_000))
419 .expect("should create processor for byte offset");
420 assert!(
421 matches!(result, FileProcessorType::BackSeeking(_)),
422 "Byte offset should use Simple processor"
423 );
424 },
425 );
426
427 crate::config::with_config(
429 ConfigOpts {
430 offset: 100,
431 offset_unit: config::OffsetUnit::Lines,
432 force_chunked: true,
433 disable_chunked: false,
434 ..ConfigOpts::default()
435 },
436 || {
437 let result = create_file_processor(&testfp, Some(100_000_000))
438 .expect("should create processor for force_chunked");
439 assert!(
440 matches!(result, FileProcessorType::Chunked(_)),
441 "force_chunked should use Chunked processor"
442 );
443 },
444 );
445
446 crate::config::with_config(
448 ConfigOpts {
449 offset: 20_000, offset_unit: config::OffsetUnit::Lines,
451 force_chunked: false,
452 disable_chunked: true,
453 ..ConfigOpts::default()
454 },
455 || {
456 let result = create_file_processor(&testfp, Some(200_000_000))
457 .expect("should create processor for disable_chunked");
458 assert!(
459 matches!(result, FileProcessorType::Buffered(_)),
460 "disable_chunked should prevent Chunked processor"
461 );
462 },
463 );
464
465 crate::config::with_config(
467 ConfigOpts {
468 offset: 100,
469 offset_unit: config::OffsetUnit::Lines,
470 force_chunked: false,
471 disable_chunked: false,
472 ..ConfigOpts::default()
473 },
474 || {
475 let result = create_file_processor(&testfp, Some(1_500_000_000)) .expect("should create processor for large file");
477 assert!(
478 matches!(result, FileProcessorType::Chunked(_)),
479 "Large file (>1GB) should use Chunked processor"
480 );
481 },
482 );
483
484 crate::config::with_config(
486 ConfigOpts {
487 offset: 20_000, offset_unit: config::OffsetUnit::Lines,
489 force_chunked: false,
490 disable_chunked: false,
491 ..ConfigOpts::default()
492 },
493 || {
494 let result = create_file_processor(&testfp, Some(150_000_000)) .expect("should create processor for large file + large offset");
496 assert!(
497 matches!(result, FileProcessorType::Chunked(_)),
498 "Large file (>100MB) + large offset (>10k) should use Chunked processor"
499 );
500 },
501 );
502
503 crate::config::with_config(
505 ConfigOpts {
506 offset: 100, offset_unit: config::OffsetUnit::Lines,
508 force_chunked: false,
509 disable_chunked: false,
510 ..ConfigOpts::default()
511 },
512 || {
513 let result = create_file_processor(&testfp, Some(10_000_000)) .expect("should create processor for small file + small offset");
515 assert!(
516 matches!(result, FileProcessorType::Buffered(_)),
517 "Small file + small offset should use Buffered processor"
518 );
519 },
520 );
521 }
522
523 #[test]
524 fn can_create_chonker() {
525 let data = b"line1\nline2\nline3\n".to_vec();
526 let chunk = FileChunk::new(data.clone(), 0, data.len() as u64);
527
528 assert_eq!(chunk.size(), data.len());
529 assert!(!chunk.is_empty());
530 assert!(chunk.starts_at_line_boundary);
531 assert!(chunk.ends_at_line_boundary);
532 }
533
534 #[test]
535 fn can_chunkread_small_files() -> Result<(), TaleError> {
536 let test_data = "line1\nline2\nline3\n";
537 let temp_file = create_test_file(test_data);
538
539 let config = ChunkConfig {
540 overlap_size: 2,
541 low_memory_mode: true,
542 };
543 let strategy = StaticStrategy {
544 chunk_size: 8, config: config.clone(),
546 };
547
548 let mut reader = ChunkedFileReader::with_strategy(temp_file.path(), strategy)?;
549
550 assert_eq!(reader.file_size(), test_data.len() as u64);
551 assert_eq!(reader.position(), 0);
552 assert!(!reader.is_at_end());
553
554 let mut all_content = String::new();
556 while let Some(chunk) = reader.read_chunk()? {
557 let chunk_str = std::str::from_utf8(&chunk.data).expect("we expected a valid utf8 string in this test");
558 all_content.push_str(chunk_str);
559 }
560
561 assert_eq!(all_content, test_data);
562 assert!(reader.is_at_end());
563
564 Ok(())
565 }
566
567 #[test]
568 fn line_boundary_handling() {
569 let data = b"line1\nline2\npartial".to_vec();
570 let data_len = data.len();
571 let mut chunk = FileChunk::new(data, 0, data_len as u64);
572
573 assert!(!chunk.ends_at_line_boundary);
574
575 let remainder = chunk.split_at_last_line();
576 assert!(remainder.is_some());
577 assert_eq!(
578 remainder.expect("we expected some remainder after the end of the line"),
579 b"partial"
580 );
581 assert_eq!(chunk.data, b"line1\nline2\n");
582 assert!(chunk.ends_at_line_boundary);
583 }
584
585 #[test]
586 fn chunk_iterator_works() {
587 let data = b"line1\nline2\nline3".to_vec();
588 let data_len = data.len();
589 let chunk = FileChunk::new(data, 0, data_len as u64);
590
591 let lines: Vec<&str> = chunk.lines().collect();
592 assert_eq!(lines, vec!["line1", "line2", "line3"]);
593 }
594
595 #[test]
596 fn buffer_thing_works() -> Result<(), TaleError> {
597 let test_data = "line1\nline2\nline3\n";
598 let temp_file = create_test_file(test_data);
599
600 let mut processor = BufferedFileProcessor::new(temp_file.path())?;
601
602 assert_eq!(processor.file_size(), test_data.len() as u64);
603 assert_eq!(processor.position(), 0);
604
605 let mut lines = Vec::new();
606 processor.process_lines(|line| {
607 lines.push(line.to_string());
608 Ok(())
609 })?;
610
611 assert_eq!(lines, vec!["line1", "line2", "line3"]);
612 Ok(())
613 }
614
615 #[test]
616 fn abstract_processor_impl_factory_noun() -> Result<(), TaleError> {
617 let test_data = "line1\nline2\nline3\n";
618 let temp_file = create_test_file(test_data);
619
620 config::with_config(ConfigOpts::default(), || {
622 let mut processor = create_file_processor(temp_file.path(), None).expect("should create processor");
624 assert_eq!(processor.file_size(), test_data.len() as u64);
625
626 let mut lines = Vec::new();
627 processor
628 .process_lines(|line| {
629 lines.push(line.to_string());
630 Ok(())
631 })
632 .expect("should process lines");
633
634 assert_eq!(lines, vec!["line1", "line2", "line3"]);
635 });
636
637 Ok(())
638 }
639
640 #[test]
641 fn can_skip_chunked_lines() -> Result<(), TaleError> {
642 let test_data = "line1\nline2\nline3\nline4\nline5\nline6\nline7\nline8\nline9\nline10\n";
644 let temp_file = create_test_file(test_data);
645
646 let config = ChunkConfig {
648 overlap_size: 2,
649 low_memory_mode: true,
650 };
651 let strategy = StaticStrategy {
652 chunk_size: 15, config: config.clone(),
654 };
655
656 let mut reader = ChunkedFileReader::with_strategy(temp_file.path(), strategy)?;
657
658 reader.skip_lines(3)?;
660
661 let mut remaining_lines = Vec::new();
663 reader.process_lines(|line| {
664 remaining_lines.push(line.to_string());
665 Ok(())
666 })?;
667
668 assert_eq!(
670 remaining_lines,
671 vec!["line4", "line5", "line6", "line7", "line8", "line9", "line10"]
672 );
673
674 Ok(())
675 }
676
677 #[test]
678 fn chunked_skip_lines_partial_chunk() -> Result<(), TaleError> {
679 let test_data = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n";
681 let temp_file = create_test_file(test_data);
682
683 let config = ChunkConfig {
684 overlap_size: 1,
685 low_memory_mode: true,
686 };
687 let strategy = StaticStrategy {
688 chunk_size: 8, config: config.clone(),
690 };
691
692 let mut reader = ChunkedFileReader::with_strategy(temp_file.path(), strategy)?;
693
694 reader.skip_lines(5)?;
696
697 let mut next_lines = Vec::new();
699 reader.process_lines(|line| {
700 next_lines.push(line.to_string());
701 if next_lines.len() >= 2 {
702 return Ok(()); }
704 Ok(())
705 })?;
706
707 assert!(next_lines.len() >= 2);
709 assert_eq!(next_lines[0], "f");
710 assert_eq!(next_lines[1], "g");
711
712 Ok(())
713 }
714}