Skip to content

Commit bb891ea

Browse files
committed
Rebuild evicted log indexes
1 parent 45d3c87 commit bb891ea

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

src/Readers/IndexedLogReader.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,15 @@ public function numberOfNewBytes(): int
274274

275275
public function requiresScan(): bool
276276
{
277+
// File metadata can outlive index cache entries; rebuild when the index was lost.
278+
if ($this->file->size() > 0) {
279+
$index = $this->index();
280+
281+
if ($index->getLastScannedFilePosition() === 0 && $index->count() === 0) {
282+
return true;
283+
}
284+
}
285+
277286
if (isset($this->mtimeBeforeScan) && ($this->file->mtime() > $this->mtimeBeforeScan || $this->file->mtime() === time())) {
278287
// The file has been modified since the last scan in this request.
279288
// Let's only request another scan if it's not the last chunk (smaller than lazyScanChunkSize).

tests/Unit/LogReaderTest.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22

33
use Illuminate\Support\Facades\File;
44
use Opcodes\LogViewer\Exceptions\CannotOpenFileException;
5+
use Opcodes\LogViewer\Facades\Cache as LogViewerCache;
6+
use Opcodes\LogViewer\LogFile;
57
use Opcodes\LogViewer\Readers\IndexedLogReader;
8+
use Opcodes\LogViewer\Utils\GenerateCacheKey;
69
use Spatie\TestTime\TestTime;
710

811
beforeEach(function () {
@@ -43,6 +46,43 @@
4346
->and($index->getFlatIndex())->toHaveCount(2);
4447
});
4548

49+
it('rebuilds a search index when its cache is evicted but file metadata survives', function () {
50+
$path = $this->file->path;
51+
52+
$read = function () use ($path) {
53+
IndexedLogReader::clearInstances();
54+
55+
$logReader = (new LogFile($path))->logs()->search('Testing');
56+
$logReader->scan();
57+
58+
return [
59+
'requires_scan' => $logReader->requiresScan(),
60+
'new_bytes' => $logReader->numberOfNewBytes(),
61+
'total' => $logReader->total(),
62+
'count' => count($logReader->reset()->get()),
63+
];
64+
};
65+
66+
expect($read())->toMatchArray([
67+
'requires_scan' => false,
68+
'new_bytes' => 0,
69+
'total' => 1,
70+
'count' => 1,
71+
]);
72+
73+
$index = (new LogFile($path))->index('~Testing~iu');
74+
75+
LogViewerCache::forget(GenerateCacheKey::for($index, 'metadata'));
76+
LogViewerCache::forget(GenerateCacheKey::for($index, 'chunk:0'));
77+
78+
expect($read())->toMatchArray([
79+
'requires_scan' => false,
80+
'new_bytes' => 0,
81+
'total' => 1,
82+
'count' => 1,
83+
]);
84+
});
85+
4686
it('throws an exception when file cannot be opened for reading', function () {
4787
if (PHP_OS_FAMILY === 'Windows') {
4888
$this->markTestSkipped('File permissions work differently on Windows. The feature tested might still work.');

0 commit comments

Comments
 (0)