log-reader 0.1.0

A simple rust library to read log files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! File reading utilities for log processing.

use crate::error::Result;
use std::path::Path;
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio::sync::mpsc;

/// Read content from file and send lines through the channel
pub(crate) async fn read_file_content(
    file_path: &Path,
    last_position: &mut u64,
    separator: &str,
    tx: &mpsc::UnboundedSender<Result<String>>,
) -> Result<()> {
    if !file_path.exists() {
        return Ok(());
    }

    let mut file = File::open(file_path).await?;
    let metadata = file.metadata().await?;
    let current_size = metadata.len();

    // Handle file truncation
    if detect_file_truncation(current_size, *last_position) {
        *last_position = 0;
    }

    // Check if there's new content to read
    let bytes_to_read = match calculate_bytes_to_read(current_size, *last_position) {
        Some(bytes) => bytes,
        None => return Ok(()), // Nothing new to read
    };

    // Seek to last known position
    file.seek(std::io::SeekFrom::Start(*last_position)).await?;

    // Read new content
    let mut new_content = String::new();
    file.take(bytes_to_read)
        .read_to_string(&mut new_content)
        .await?;

    // Update position
    *last_position = current_size;

    // Split by separator and send all parts
    let parts = split_and_filter_content(&new_content, separator);

    for part in parts {
        if tx.send(Ok(part)).is_err() {
            // Receiver dropped, stop sending
            return Ok(());
        }
    }

    Ok(())
}

/// Split content by separator and filter out empty/whitespace-only parts
fn split_and_filter_content(content: &str, separator: &str) -> Vec<String> {
    content
        .split(separator)
        .filter_map(|part| {
            let trimmed = part.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(part.to_string())
            }
        })
        .collect()
}

/// Detect if the file was truncated by comparing current size with last position
fn detect_file_truncation(current_size: u64, last_position: u64) -> bool {
    current_size < last_position
}

/// Calculate bytes to read based on current size and last position
fn calculate_bytes_to_read(current_size: u64, last_position: u64) -> Option<u64> {
    if current_size <= last_position {
        None // Nothing new to read
    } else {
        Some(current_size - last_position)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use tokio::fs;
    use tokio::sync::mpsc;

    /// Helper function to collect all messages from the receiver
    async fn collect_messages(mut rx: mpsc::UnboundedReceiver<Result<String>>) -> Vec<String> {
        let mut messages = Vec::new();

        // Use try_recv to avoid blocking - all messages should be available immediately
        while let Ok(result) = rx.try_recv() {
            match result {
                Ok(content) => messages.push(content),
                Err(e) => panic!("Unexpected error: {}", e),
            }
        }

        messages
    }

    // Tests for the new pure functions
    #[test]
    fn test_split_and_filter_content_newline() {
        let content = "line1\nline2\nline3\n";
        let result = split_and_filter_content(content, "\n");
        assert_eq!(result, vec!["line1", "line2", "line3"]);
    }

    #[test]
    fn test_split_and_filter_content_with_empty_lines() {
        let content = "line1\n\n\nline2\n  \n\nline3\n";
        let result = split_and_filter_content(content, "\n");
        assert_eq!(result, vec!["line1", "line2", "line3"]);
    }

    #[test]
    fn test_split_and_filter_content_custom_separator() {
        let content = "data1|data2|data3|";
        let result = split_and_filter_content(content, "|");
        assert_eq!(result, vec!["data1", "data2", "data3"]);
    }

    #[test]
    fn test_split_and_filter_content_multi_char_separator() {
        let content = "part1<<>>part2<<>>part3<<>>";
        let result = split_and_filter_content(content, "<<>>");
        assert_eq!(result, vec!["part1", "part2", "part3"]);
    }

    #[test]
    fn test_split_and_filter_content_no_separator() {
        let content = "single_line_content";
        let result = split_and_filter_content(content, "\n");
        assert_eq!(result, vec!["single_line_content"]);
    }

    #[test]
    fn test_split_and_filter_content_empty_string() {
        let content = "";
        let result = split_and_filter_content(content, "\n");
        assert_eq!(result, Vec::<String>::new());
    }

    #[test]
    fn test_split_and_filter_content_only_separators() {
        let content = "\n\n\n";
        let result = split_and_filter_content(content, "\n");
        assert_eq!(result, Vec::<String>::new());
    }

    #[test]
    fn test_split_and_filter_content_whitespace_preservation() {
        let content = "  line1  \n  line2  \n";
        let result = split_and_filter_content(content, "\n");
        // Should preserve internal whitespace but filter empty lines
        assert_eq!(result, vec!["  line1  ", "  line2  "]);
    }

    #[test]
    fn test_detect_file_truncation() {
        assert!(detect_file_truncation(100, 200)); // File was truncated
        assert!(!detect_file_truncation(200, 100)); // File grew
        assert!(!detect_file_truncation(100, 100)); // No change
    }

    #[test]
    fn test_calculate_bytes_to_read() {
        assert_eq!(calculate_bytes_to_read(200, 100), Some(100)); // 100 new bytes
        assert_eq!(calculate_bytes_to_read(100, 100), None); // No new bytes
        assert_eq!(calculate_bytes_to_read(50, 100), None); // File truncated
        assert_eq!(calculate_bytes_to_read(0, 0), None); // Empty file, no change
    }

    // Integration tests for read_file_content function
    #[tokio::test]
    async fn test_read_simple_file_with_newline_separator() {
        let file_path = PathBuf::from("fixtures/simple_append.log");
        let (tx, rx) = mpsc::unbounded_channel();
        let mut position = 0u64;

        read_file_content(&file_path, &mut position, "\n", &tx)
            .await
            .expect("Should read file successfully");

        let messages = collect_messages(rx).await;

        // Expected all 10 lines from the fixture
        let expected = vec![
            "2023-01-01 10:00:00 INFO Starting application",
            "2023-01-01 10:00:01 INFO Loading configuration",
            "2023-01-01 10:00:02 INFO Database connection established",
            "2023-01-01 10:00:03 DEBUG User session created for user_id=123",
            "2023-01-01 10:00:04 INFO Application ready to serve requests",
            "2023-01-01 10:00:05 WARN High memory usage detected: 85%",
            "2023-01-01 10:00:06 ERROR Failed to process request: timeout",
            "2023-01-01 10:00:07 INFO Request processed successfully",
            "2023-01-01 10:00:08 DEBUG Cache hit for key=user_data_123",
            "2023-01-01 10:00:09 INFO User authenticated successfully ",
        ];

        assert_eq!(messages, expected);

        // Position should be at the end of file
        let metadata = fs::metadata(&file_path).await.unwrap();
        assert_eq!(position, metadata.len());
    }

    #[tokio::test]
    async fn test_read_file_with_different_separator() {
        let file_path = PathBuf::from("fixtures/different_separators.log");
        let (tx, rx) = mpsc::unbounded_channel();
        let mut position = 0u64;

        read_file_content(&file_path, &mut position, "|", &tx)
            .await
            .expect("Should read file successfully");

        let messages = collect_messages(rx).await;

        // Should split by pipe character
        assert!(messages.len() > 1);
        assert!(messages[0].contains("Starting application"));
        assert!(messages[1].contains("Loading configuration"));

        let metadata = fs::metadata(&file_path).await.unwrap();
        assert_eq!(position, metadata.len());
    }

    #[tokio::test]
    async fn test_incremental_reading() {
        let file_path = PathBuf::from("fixtures/simple_append.log");
        let (tx, rx) = mpsc::unbounded_channel();

        // First read - only read first 50 bytes to simulate partial reading
        let file = File::open(&file_path).await.unwrap();
        let first_chunk_size = 50;
        let mut content = String::new();
        file.take(first_chunk_size)
            .read_to_string(&mut content)
            .await
            .unwrap();
        let mut position = first_chunk_size;

        // Now read from position 50 to end
        read_file_content(&file_path, &mut position, "\n", &tx)
            .await
            .expect("Should read remaining content");

        let messages = collect_messages(rx).await;

        // Expected messages when reading from position 50 onwards
        let expected = vec![
            "-01-01 10:00:01 INFO Loading configuration",
            "2023-01-01 10:00:02 INFO Database connection established",
            "2023-01-01 10:00:03 DEBUG User session created for user_id=123",
            "2023-01-01 10:00:04 INFO Application ready to serve requests",
            "2023-01-01 10:00:05 WARN High memory usage detected: 85%",
            "2023-01-01 10:00:06 ERROR Failed to process request: timeout",
            "2023-01-01 10:00:07 INFO Request processed successfully",
            "2023-01-01 10:00:08 DEBUG Cache hit for key=user_data_123",
            "2023-01-01 10:00:09 INFO User authenticated successfully ",
        ];

        assert_eq!(messages, expected);

        // Position should be at end of file
        let metadata = fs::metadata(&file_path).await.unwrap();
        assert_eq!(position, metadata.len());
    }

    #[tokio::test]
    async fn test_file_truncation_handling() {
        let file_path = PathBuf::from("fixtures/simple_append.log");
        let (tx, rx) = mpsc::unbounded_channel();
        let mut position = 1000u64; // Set position beyond file size

        read_file_content(&file_path, &mut position, "\n", &tx)
            .await
            .expect("Should handle truncation");

        let messages = collect_messages(rx).await;

        // Should read all content from beginning due to truncation detection
        assert!(messages.len() > 0);

        // Position should be reset and then set to end of file
        let metadata = fs::metadata(&file_path).await.unwrap();
        assert_eq!(position, metadata.len());
    }

    #[tokio::test]
    async fn test_nonexistent_file() {
        let file_path = PathBuf::from("fixtures/nonexistent.log");
        let (tx, _rx) = mpsc::unbounded_channel();
        let mut position = 0u64;

        let result = read_file_content(&file_path, &mut position, "\n", &tx).await;

        // Should not error for non-existent file
        assert!(result.is_ok());
        assert_eq!(position, 0);
    }

    #[tokio::test]
    async fn test_empty_file() {
        let file_path = PathBuf::from("fixtures/empty.log");
        let (tx, rx) = mpsc::unbounded_channel();
        let mut position = 0u64;

        read_file_content(&file_path, &mut position, "\n", &tx)
            .await
            .expect("Should handle empty file");

        let messages = collect_messages(rx).await;

        // Empty file should produce no messages
        assert_eq!(messages.len(), 0);

        // Position should match file size (which is minimal for empty file)
        let metadata = fs::metadata(&file_path).await.unwrap();
        assert_eq!(position, metadata.len());
    }

    #[tokio::test]
    async fn test_no_new_content_when_position_at_end() {
        let file_path = PathBuf::from("fixtures/simple_append.log");
        let (tx, rx) = mpsc::unbounded_channel();

        // Set position to file size (at end)
        let metadata = fs::metadata(&file_path).await.unwrap();
        let mut position = metadata.len();

        read_file_content(&file_path, &mut position, "\n", &tx)
            .await
            .expect("Should handle no new content");

        let messages = collect_messages(rx).await;

        // Should produce no messages when already at end
        assert_eq!(messages.len(), 0);
        assert_eq!(position, metadata.len());
    }

    #[tokio::test]
    async fn test_receiver_dropped() {
        let file_path = PathBuf::from("fixtures/simple_append.log");
        let (tx, rx) = mpsc::unbounded_channel();
        let mut position = 0u64;

        // Drop the receiver to simulate channel closure
        drop(rx);

        // Should not panic and should complete successfully
        let result = read_file_content(&file_path, &mut position, "\n", &tx).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_filters_empty_lines() {
        // Create a temporary file with empty lines
        let temp_file = "test_empty_lines.tmp";
        fs::write(temp_file, "line1\n\n\nline2\n  \n\nline3\n")
            .await
            .unwrap();

        let file_path = PathBuf::from(temp_file);
        let (tx, rx) = mpsc::unbounded_channel();
        let mut position = 0u64;

        read_file_content(&file_path, &mut position, "\n", &tx)
            .await
            .expect("Should read file successfully");

        let messages = collect_messages(rx).await;

        // Should only get non-empty lines
        assert_eq!(messages.len(), 3);
        assert_eq!(messages[0], "line1");
        assert_eq!(messages[1], "line2");
        assert_eq!(messages[2], "line3");

        // Clean up
        fs::remove_file(temp_file).await.unwrap();
    }

    #[tokio::test]
    async fn test_utf8_handling_valid_content() {
        let temp_file = "test_utf8_valid.tmp";
        let utf8_content = "Hello 世界\nUnicode: 🦀\n日本語テスト\n";
        fs::write(temp_file, utf8_content).await.unwrap();

        let file_path = PathBuf::from(temp_file);
        let (tx, rx) = mpsc::unbounded_channel();
        let mut position = 0u64;

        read_file_content(&file_path, &mut position, "\n", &tx)
            .await
            .expect("Should read UTF-8 content successfully");

        let messages = collect_messages(rx).await;

        assert_eq!(messages.len(), 3);
        assert_eq!(messages[0], "Hello 世界");
        assert_eq!(messages[1], "Unicode: 🦀");
        assert_eq!(messages[2], "日本語テスト");

        // Clean up
        fs::remove_file(temp_file).await.unwrap();
    }

    #[tokio::test]
    async fn test_large_file_reading() {
        let temp_file = "test_large_file.tmp";

        // Create a large file with many lines
        let mut large_content = String::new();
        for i in 0..1000 {
            large_content.push_str(&format!("Line number {}\n", i));
        }
        fs::write(temp_file, &large_content).await.unwrap();

        let file_path = PathBuf::from(temp_file);
        let (tx, rx) = mpsc::unbounded_channel();
        let mut position = 0u64;

        read_file_content(&file_path, &mut position, "\n", &tx)
            .await
            .expect("Should read large file successfully");

        let messages = collect_messages(rx).await;

        // Should get all 1000 lines
        assert_eq!(messages.len(), 1000);
        assert_eq!(messages[0], "Line number 0");
        assert_eq!(messages[999], "Line number 999");

        // Clean up
        fs::remove_file(temp_file).await.unwrap();
    }

    #[tokio::test]
    async fn test_file_with_very_long_lines() {
        let temp_file = "test_long_lines.tmp";

        // Create a file with very long lines
        let long_line = "A".repeat(10000);
        let content = format!("{}\n{}\n", long_line, "short line");
        fs::write(temp_file, &content).await.unwrap();

        let file_path = PathBuf::from(temp_file);
        let (tx, rx) = mpsc::unbounded_channel();
        let mut position = 0u64;

        read_file_content(&file_path, &mut position, "\n", &tx)
            .await
            .expect("Should read file with long lines successfully");

        let messages = collect_messages(rx).await;

        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].len(), 10000);
        assert!(messages[0].chars().all(|c| c == 'A'));
        assert_eq!(messages[1], "short line");

        // Clean up
        fs::remove_file(temp_file).await.unwrap();
    }

    #[tokio::test]
    async fn test_binary_like_content_handling() {
        let temp_file = "test_binary_content.tmp";

        // Create content with null bytes and other binary-like data
        let content = "line1\nline with \0 null byte\nline3\n";
        fs::write(temp_file, content).await.unwrap();

        let file_path = PathBuf::from(temp_file);
        let (tx, rx) = mpsc::unbounded_channel();
        let mut position = 0u64;

        read_file_content(&file_path, &mut position, "\n", &tx)
            .await
            .expect("Should read binary-like content successfully");

        let messages = collect_messages(rx).await;

        assert_eq!(messages.len(), 3);
        assert_eq!(messages[0], "line1");
        assert!(messages[1].contains("null byte"));
        assert_eq!(messages[2], "line3");

        // Clean up
        fs::remove_file(temp_file).await.unwrap();
    }

    #[tokio::test]
    async fn test_concurrent_reading_attempts() {
        let file_path = PathBuf::from("fixtures/simple_append.log");

        // Spawn multiple concurrent reading tasks
        let mut handles = Vec::new();

        for i in 0..5 {
            let path = file_path.clone();
            let handle = tokio::spawn(async move {
                let (tx, rx) = mpsc::unbounded_channel();
                let mut position = 0u64;

                read_file_content(&path, &mut position, "\n", &tx)
                    .await
                    .expect("Should read file successfully");

                let messages = collect_messages(rx).await;
                (i, messages.len())
            });
            handles.push(handle);
        }

        // Wait for all tasks to complete
        let results: Vec<_> = futures::future::join_all(handles).await;

        // All tasks should complete successfully
        for result in results {
            let (task_id, message_count) = result.unwrap();
            assert!(
                message_count > 0,
                "Task {} should have read some messages",
                task_id
            );
        }
    }

    #[test]
    fn test_split_and_filter_content_edge_cases() {
        // Test with separator at the beginning
        let content = "\nline1\nline2";
        let result = split_and_filter_content(content, "\n");
        assert_eq!(result, vec!["line1", "line2"]);

        // Test with separator at the end
        let content = "line1\nline2\n";
        let result = split_and_filter_content(content, "\n");
        assert_eq!(result, vec!["line1", "line2"]);

        // Test with repeated separators
        let content = "line1\n\n\n\nline2";
        let result = split_and_filter_content(content, "\n");
        assert_eq!(result, vec!["line1", "line2"]);

        // Test with whitespace-only content between separators
        let content = "line1\n   \n\t\n  \nline2";
        let result = split_and_filter_content(content, "\n");
        assert_eq!(result, vec!["line1", "line2"]);
    }

    #[test]
    fn test_position_calculation_edge_cases() {
        // Test with zero values
        assert_eq!(calculate_bytes_to_read(0, 0), None);

        // Test with large values
        assert_eq!(calculate_bytes_to_read(u64::MAX, u64::MAX - 1), Some(1));
        assert_eq!(calculate_bytes_to_read(u64::MAX - 1, u64::MAX), None);

        // Test boundary conditions
        assert_eq!(calculate_bytes_to_read(1, 0), Some(1));
        assert_eq!(calculate_bytes_to_read(0, 1), None);
    }

    #[test]
    fn test_file_truncation_edge_cases() {
        // Test with equal sizes
        assert!(!detect_file_truncation(100, 100));

        // Test with zero values
        assert!(!detect_file_truncation(0, 0));
        assert!(detect_file_truncation(0, 1));

        // Test with large values
        assert!(detect_file_truncation(u64::MAX - 1, u64::MAX));
        assert!(!detect_file_truncation(u64::MAX, u64::MAX - 1));
    }
}