diff --git a/src/ColumnizerLib.UnitTests/LogLineTests.cs b/src/ColumnizerLib.UnitTests/LogLineTests.cs new file mode 100644 index 00000000..8fad5d9c --- /dev/null +++ b/src/ColumnizerLib.UnitTests/LogLineTests.cs @@ -0,0 +1,33 @@ +using System.Runtime.CompilerServices; + +using ColumnizerLib; + +using NUnit.Framework; + +namespace LogExpert.ColumnizerLib.Tests; + +[TestFixture] +public class LogLineTests +{ + [Test] + public void LogLine_StoresTheLineOnce () + { + // One ReadOnlyMemory plus the line number; every resident line pays for this. + Assert.That(Unsafe.SizeOf(), Is.LessThan(2 * Unsafe.SizeOf>())); + } + + [Test] + public void LogLine_TextIsTheFullLine () + { + var memory = "2026-11-20 INFO started".AsMemory(11); + var line = new LogLine(memory, 7); + + Assert.Multiple(() => + { + Assert.That(line.Text.Equals(line.FullLine), Is.True); + Assert.That(line.Text.ToString(), Is.EqualTo("INFO started")); + Assert.That(line.LineNumber, Is.EqualTo(7)); + Assert.That(line, Is.EqualTo(new LogLine(memory, 7))); + }); + } +} \ No newline at end of file diff --git a/src/ColumnizerLib/LogLine.cs b/src/ColumnizerLib/LogLine.cs index c68b28e6..f9ff773f 100644 --- a/src/ColumnizerLib/LogLine.cs +++ b/src/ColumnizerLib/LogLine.cs @@ -22,19 +22,18 @@ namespace ColumnizerLib; public ReadOnlyMemory FullLine { get; } - public ReadOnlyMemory Text { get; } + // Not stored: a second copy of the memory would cost 16 bytes on every resident line. + public ReadOnlyMemory Text => FullLine; public LogLine (string fullLine, int lineNumber) { LineNumber = lineNumber; FullLine = fullLine.AsMemory(); - Text = fullLine.AsMemory(); } public LogLine (ReadOnlyMemory fullLine, int lineNumber) { LineNumber = lineNumber; FullLine = fullLine; - Text = fullLine; } -} +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Log/Buffers/LogBuffer.cs b/src/LogExpert.Core/Classes/Log/Buffers/LogBuffer.cs index 020752fb..834a39a5 100644 --- a/src/LogExpert.Core/Classes/Log/Buffers/LogBuffer.cs +++ b/src/LogExpert.Core/Classes/Log/Buffers/LogBuffer.cs @@ -85,6 +85,8 @@ public long Size public int PrevBuffersDroppedLinesSum { get; set; } + internal int CharBlockCapacity => _charBlocks?.Sum(block => block.Length) ?? 0; + #endregion #region Public methods diff --git a/src/LogExpert.Core/Classes/Log/LogfileReader.cs b/src/LogExpert.Core/Classes/Log/LogfileReader.cs index d0a23ef7..f003bd8b 100644 --- a/src/LogExpert.Core/Classes/Log/LogfileReader.cs +++ b/src/LogExpert.Core/Classes/Log/LogfileReader.cs @@ -1171,7 +1171,7 @@ private bool ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int start try { using var fileStream = logFileInfo.OpenStream(); - using var reader = GetLogStreamReader(fileStream, EncodingOptions) as ILogStreamReaderMemory; + using var reader = GetLogStreamReader(fileStream, EncodingOptions); reader.Position = filePos; _fileLength = logFileInfo.Length; @@ -1270,7 +1270,7 @@ private bool ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int start // Detach char blocks from the reader and attach to the completed buffer. // Must happen before Monitor.Exit so the buffer is still exclusively owned. - logBuffer.AttachCharBlocks(reader.DetachCharBlocks()); + AttachReaderBlocks(logBuffer, reader); Monitor.Exit(logBuffer); try @@ -1302,7 +1302,7 @@ private bool ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int start logBuffer.Size = filePos - logBuffer.StartPos; // Attach remaining blocks to the final buffer - logBuffer.AttachCharBlocks(reader.DetachCharBlocks()); + AttachReaderBlocks(logBuffer, reader); } finally { @@ -1395,10 +1395,7 @@ private void ReReadBuffer (LogBuffer logBuffer) using Stream fileStream = openendFileStream; { - //TODO LogStream Reader has to be changed to ILogStreamReaderMemory - var reader = GetLogStreamReader(fileStream, EncodingOptions) as ILogStreamReaderMemory; - - using var readerDisposabel = reader as IDisposable; + using var reader = GetLogStreamReader(fileStream, EncodingOptions); { var filePos = logBuffer.StartPos; reader.Position = logBuffer.StartPos; @@ -1433,7 +1430,7 @@ private void ReReadBuffer (LogBuffer logBuffer) } // Attach char blocks from the reader to the re-read buffer - logBuffer.AttachCharBlocks(reader.DetachCharBlocks()); + AttachReaderBlocks(logBuffer, reader); if (maxLinesCount != logBuffer.LineCount) { @@ -1777,20 +1774,22 @@ private bool ReadLine (ILogStreamReader reader, int lineNum, int realLineNum, ou /// the line as a string. If the reader supports memory-based access, the memory buffer is populated; otherwise, it /// is null. /// - private (bool Success, ReadOnlyMemory LineMemory, bool wasDropped) ReadLineMemory (ILogStreamReaderMemory reader, int lineNum, int realLineNum) + private (bool Success, ReadOnlyMemory LineMemory, bool wasDropped) ReadLineMemory (ILogStreamReader reader, int lineNum, int realLineNum) { - if (reader is null) + if (reader is not ILogStreamReaderMemory memoryReader) { - // Fallback to string-based reading if memory reader not available - if (ReadLine(reader, lineNum, realLineNum, out var outLine)) + // String readers (XML mode); a null line after preprocessing means the line was dropped. + if (!ReadLine(reader, lineNum, realLineNum, out var outLine)) { - return (true, outLine.AsMemory(), false); + return (false, ReadOnlyMemory.Empty, false); } - return (false, ReadOnlyMemory.Empty, false); + return outLine is null + ? (true, ReadOnlyMemory.Empty, true) + : (true, outLine.AsMemory(), false); } - if (!reader.TryReadLine(out var lineMemory)) + if (!memoryReader.TryReadLine(out var lineMemory)) { return (false, ReadOnlyMemory.Empty, false); } @@ -1811,6 +1810,15 @@ private bool ReadLine (ILogStreamReader reader, int lineNum, int realLineNum, ou return (true, lineMemory, false); } + // Only memory readers hand out pooled char blocks; string readers own no blocks to transfer. + private static void AttachReaderBlocks (LogBuffer logBuffer, ILogStreamReader reader) + { + if (reader is ILogStreamReaderMemory memoryReader) + { + logBuffer.AttachCharBlocks(memoryReader.DetachCharBlocks()); + } + } + #if DEBUG /// /// Outputs detailed information about the specified log buffer to the trace logger for debugging purposes. @@ -1992,4 +2000,4 @@ PinHandle IBufferPinning.PinRange (int startLine, int endLine) } #endregion -} +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Log/Streamreaders/PositionAwareStreamReaderBase.cs b/src/LogExpert.Core/Classes/Log/Streamreaders/PositionAwareStreamReaderBase.cs index 7c60d3f1..4111cd51 100644 --- a/src/LogExpert.Core/Classes/Log/Streamreaders/PositionAwareStreamReaderBase.cs +++ b/src/LogExpert.Core/Classes/Log/Streamreaders/PositionAwareStreamReaderBase.cs @@ -1,4 +1,4 @@ -using System.Text; +using System.Text; using LogExpert.Core.Entities; @@ -90,11 +90,7 @@ public sealed override long Position public sealed override bool IsBufferComplete => true; - protected static int MaximumLineLength - { - get => field; - private set => field = value; - } + protected int MaximumLineLength { get; } #endregion diff --git a/src/LogExpert.Core/Classes/Log/Streamreaders/PositionAwareStreamReaderDirect.cs b/src/LogExpert.Core/Classes/Log/Streamreaders/PositionAwareStreamReaderDirect.cs index bee4c10b..cb898f4e 100644 --- a/src/LogExpert.Core/Classes/Log/Streamreaders/PositionAwareStreamReaderDirect.cs +++ b/src/LogExpert.Core/Classes/Log/Streamreaders/PositionAwareStreamReaderDirect.cs @@ -38,7 +38,11 @@ public class PositionAwareStreamReaderDirect : PositionAwareStreamReaderBase, IL private int _byteEnd; private int _scannedBytes; // bytes after _byteStart already searched without a terminator private bool _eof; + private bool _lastReadShort; // the last Read returned less than asked for: the rest of the file is buffered private bool _initialized; + private bool _truncating; // the line in progress is over the cap: its bytes are dropped up to the terminator + private ReadOnlyMemory _truncatedLine; + private int _truncateAfterBytes; private int _unitSize; // bytes per code unit: 1, 2 or 4 private uint _crUnit; @@ -57,7 +61,7 @@ public class PositionAwareStreamReaderDirect : PositionAwareStreamReaderBase, IL public PositionAwareStreamReaderDirect (Stream stream, EncodingOptions encodingOptions, int maximumLineLength) : base(stream, encodingOptions, maximumLineLength) { - _readBlock = ArrayPool.Shared.Rent(BLOCK_SIZE); + _readBlock = []; } #endregion @@ -105,12 +109,19 @@ public bool TryReadLine (out ReadOnlyMemory lineMemory) else { // \r is the last unit read so far: refill, then re-scan from the \r to classify it. + if (_truncating) + { + ConsumeBytes(hitIndex); + hitIndex = 0; + } + _scannedBytes = hitIndex; Refill(); continue; } - lineMemory = DecodeLine(hitIndex); + lineMemory = _truncating ? _truncatedLine : DecodeLine(hitIndex); + _truncating = false; ConsumeBytes(hitIndex + terminatorBytes); return true; } @@ -118,9 +129,10 @@ public bool TryReadLine (out ReadOnlyMemory lineMemory) if (_eof) { // Emit remaining content as final line (no trailing newline) - if (available > 0) + if (available > 0 || _truncating) { - lineMemory = DecodeLine(available); + lineMemory = _truncating ? _truncatedLine : DecodeLine(available); + _truncating = false; ConsumeBytes(available); return true; } @@ -130,7 +142,24 @@ public bool TryReadLine (out ReadOnlyMemory lineMemory) } // Only whole units are searched; a partial one is completed by the refill. - _scannedBytes = available - (available % _unitSize); + var searchedBytes = available - (available % _unitSize); + + if (!_truncating && searchedBytes >= _truncateAfterBytes) + { + _truncatedLine = DecodeLine(_truncateAfterBytes); + _truncating = true; + } + + if (_truncating) + { + // Position still counts the dropped bytes, so it stays exact. + ConsumeBytes(searchedBytes); + } + else + { + _scannedBytes = searchedBytes; + } + Refill(); } } @@ -149,7 +178,7 @@ public List DetachCharBlocks () if (_usedChars > 0) { _completedBlocks.Add(_readBlock); - _readBlock = ArrayPool.Shared.Rent(BLOCK_SIZE); + _readBlock = []; _usedChars = 0; } @@ -200,6 +229,10 @@ private void ResolveTerminatorUnits () _lfUnit = ReadUnit(lf, _unitSize); _asciiCompatible = _unitSize == 1 && DecodesAsciiUnchanged(Encoding); _isUtf16LittleEndian = Encoding.CodePage == CODE_PAGE_UTF16_LE; + + // No supported encoding needs more than 4 bytes per char, so this prefix holds the first MaximumLineLength + // chars complete; the extra 4 bytes keep a character cut at the end beyond the cap. A multiple of every unit size. + _truncateAfterBytes = (int)Math.Min((4L * Math.Max(MaximumLineLength, 0)) + 4, 1 << 29); } // False for encodings like UTF-7 or EBCDIC, whose 0x00–0x7F bytes are not plain ASCII. @@ -268,44 +301,67 @@ private int FindTerminator (ReadOnlySpan bytes) } // A line is decoded on its own: a sequence cut short by the terminator becomes U+FFFD in this line. + // Only the text up to the maximum line length reaches the char block. private ReadOnlyMemory DecodeLine (int byteCount) { var bytes = _byteBuffer.AsSpan(_byteStart, byteCount); - int charCount; if (_asciiCompatible) { - // Pure-ASCII lines skip the per-call cost of the encoding's decoder. - EnsureCharCapacity(byteCount); - if (Ascii.ToUtf16(bytes, _readBlock.AsSpan(_usedChars), out charCount) != OperationStatus.Done) + // Pure-ASCII text skips the per-call cost of the encoding's decoder. An ASCII byte is one char + // whatever follows, so only the bytes up to the cap are converted. + var prefix = bytes[..Math.Min(byteCount, MaximumLineLength)]; + EnsureCharCapacity(prefix.Length); + if (Ascii.ToUtf16(prefix, _readBlock.AsSpan(_usedChars), out var asciiCount) == OperationStatus.Done) { - charCount = DecodeWithEncoding(bytes); + return Commit(asciiCount); } } - else if (_isUtf16LittleEndian && (byteCount & 1) == 0 && !MemoryMarshal.Cast(bytes).ContainsAny(_surrogates)) + else if (_isUtf16LittleEndian) { - // UTF-16 LE without surrogates decodes to its own code units. - var source = MemoryMarshal.Cast(bytes); - EnsureCharCapacity(source.Length); - source.CopyTo(_readBlock.AsSpan(_usedChars)); - charCount = source.Length; + // UTF-16 LE without surrogates decodes to its own code units. An odd trailing byte beyond the cap does not matter. + var units = MemoryMarshal.Cast(bytes); + var prefix = units[..Math.Min(units.Length, MaximumLineLength)]; + if (((byteCount & 1) == 0 || units.Length >= MaximumLineLength) && !prefix.ContainsAny(_surrogates)) + { + EnsureCharCapacity(prefix.Length); + prefix.CopyTo(_readBlock.AsSpan(_usedChars)); + return Commit(prefix.Length); + } } - else + + return DecodeWithEncoding(bytes); + } + + private ReadOnlyMemory DecodeWithEncoding (ReadOnlySpan bytes) + { + var maxChars = Encoding.GetMaxCharCount(bytes.Length); + if (maxChars <= MaximumLineLength) { - charCount = DecodeWithEncoding(bytes); + EnsureCharCapacity(maxChars); + return Commit(Encoding.GetChars(bytes, _readBlock.AsSpan(_usedChars))); } - var cappedLength = Math.Min(charCount, MaximumLineLength); - - var lineMemory = _readBlock.AsMemory(_usedChars, cappedLength); - _usedChars += cappedLength; - return lineMemory; + // Text that may exceed the cap is decoded into scratch, so the char block holds only the capped text. + var scratch = ArrayPool.Shared.Rent(maxChars); + try + { + var cappedLength = Math.Min(Encoding.GetChars(bytes, scratch), MaximumLineLength); + EnsureCharCapacity(cappedLength); + scratch.AsSpan(0, cappedLength).CopyTo(_readBlock.AsSpan(_usedChars)); + return Commit(cappedLength); + } + finally + { + ArrayPool.Shared.Return(scratch); + } } - private int DecodeWithEncoding (ReadOnlySpan bytes) + private ReadOnlyMemory Commit (int charCount) { - EnsureCharCapacity(Encoding.GetMaxCharCount(bytes.Length)); - return Encoding.GetChars(bytes, _readBlock.AsSpan(_usedChars)); + var lineMemory = _readBlock.AsMemory(_usedChars, charCount); + _usedChars += charCount; + return lineMemory; } private void ConsumeBytes (int byteCount) @@ -316,6 +372,7 @@ private void ConsumeBytes (int byteCount) } // A block that already holds lines is kept for DetachCharBlocks; lines longer than BLOCK_SIZE get a block of their own. + // A block is never larger than the bytes left to read, so a tail poll that reads one line does not pin a full block. private void EnsureCharCapacity (int charCount) { if (_readBlock.Length - _usedChars >= charCount) @@ -327,15 +384,26 @@ private void EnsureCharCapacity (int charCount) { _completedBlocks.Add(_readBlock); } - else + else if (_readBlock.Length > 0) { ArrayPool.Shared.Return(_readBlock); } - var blockSize = BLOCK_SIZE; - while (blockSize < charCount) + int blockSize; + if (charCount > BLOCK_SIZE) + { + blockSize = BLOCK_SIZE; + while (blockSize < charCount) + { + blockSize *= 2; + } + } + else { - blockSize *= 2; + // After a short read the rest of the file is buffered, and no encoding decodes n bytes to more than n + 1 chars. + blockSize = _lastReadShort + ? Math.Clamp(_byteEnd - _byteStart + 1, charCount, BLOCK_SIZE) + : BLOCK_SIZE; } _readBlock = ArrayPool.Shared.Rent(blockSize); @@ -365,8 +433,10 @@ private void Refill () _byteEnd = lineLength; } - var bytesRead = GetByteStream().Read(_byteBuffer, _byteEnd, _byteBuffer.Length - _byteEnd); + var requested = _byteBuffer.Length - _byteEnd; + var bytesRead = GetByteStream().Read(_byteBuffer, _byteEnd, requested); _byteEnd += bytesRead; + _lastReadShort = bytesRead < requested; if (bytesRead == 0) { @@ -382,6 +452,8 @@ protected override void ResetReader () _byteEnd = 0; _scannedBytes = 0; _eof = false; + _lastReadShort = false; + _truncating = false; _initialized = false; base.ResetReader(); @@ -392,12 +464,13 @@ protected override void Dispose (bool disposing) if (disposing) { // Return the current (partially filled) block - if (_readBlock != null) + if (_readBlock is { Length: > 0 }) { ArrayPool.Shared.Return(_readBlock); - _readBlock = null!; } + _readBlock = null!; + if (_byteBuffer != null) { ArrayPool.Shared.Return(_byteBuffer); diff --git a/src/LogExpert.Tests/StreamReaderTests/DirectReaderLongLineMemoryTests.cs b/src/LogExpert.Tests/StreamReaderTests/DirectReaderLongLineMemoryTests.cs new file mode 100644 index 00000000..f6dfe346 --- /dev/null +++ b/src/LogExpert.Tests/StreamReaderTests/DirectReaderLongLineMemoryTests.cs @@ -0,0 +1,271 @@ +using System.Buffers; +using System.Numerics; +using System.Text; + +using LogExpert.Core.Classes.Log.Streamreaders; +using LogExpert.Core.Entities; +using LogExpert.Core.Helpers; + +using NUnit.Framework; + +namespace LogExpert.Tests.StreamReaderTests; + +// Issue #758: memory used to read one line must be bounded by the maximum line length, not by the +// line's raw length. A 50 MB run without terminators used to grow the byte buffer to the whole run +// and hand a 64 M char block to the LogBuffer. +[TestFixture] +public class DirectReaderLongLineMemoryTests +{ + private const int MAX_LINE_LENGTH = 20_000; + private const int RUN_LENGTH = 50 * 1024 * 1024; + private const int BLOCK_SIZE = 32_768; + private const int BYTE_BUFFER_SIZE = 65_536; + private const int GB18030_CODE_PAGE = 54_936; + + // A small multiple of the maximum line length (decoded chars plus the bytes behind them) and the read buffer. + private const long ALLOCATION_BOUND = (16L * MAX_LINE_LENGTH * sizeof(char)) + (4L * BYTE_BUFFER_SIZE); + + private static readonly string[] _runEncodings = ["utf-8", "utf-16"]; + + #region Long run without terminators + + [TestCaseSource(nameof(_runEncodings))] + public void LongRun_AllocationsStayBounded (string encodingName) + { + var encoding = Encoding.GetEncoding(encodingName); + var data = TextAroundRun(encoding, RandomRun(encoding, RUN_LENGTH, seed: 758)); + + using var stream = new MemoryStream(data, writable: false); + using var reader = new PositionAwareStreamReaderDirect(stream, new EncodingOptions { Encoding = encoding }, MAX_LINE_LENGTH); + + var before = GC.GetAllocatedBytesForCurrentThread(); + var lineCount = 0; + while (reader.TryReadLine(out _)) + { + lineCount++; + } + + var blocks = reader.DetachCharBlocks(); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + ReturnBlocks(blocks); + + Assert.Multiple(() => + { + Assert.That(lineCount, Is.EqualTo(5)); + Assert.That(allocated, Is.LessThan(ALLOCATION_BOUND), "Bytes allocated while reading"); + }); + } + + [TestCaseSource(nameof(_runEncodings))] + public void LongRun_DetachedBlocksAreNotOversized (string encodingName) + { + var encoding = Encoding.GetEncoding(encodingName); + var data = TextAroundRun(encoding, RandomRun(encoding, RUN_LENGTH, seed: 758)); + + using var stream = new MemoryStream(data, writable: false); + using var reader = new PositionAwareStreamReaderDirect(stream, new EncodingOptions { Encoding = encoding }, MAX_LINE_LENGTH); + + var blocks = new List(); + while (reader.TryReadLine(out _)) + { + blocks.AddRange(reader.DetachCharBlocks()); + } + + var largest = blocks.Max(block => block.Length); + ReturnBlocks(blocks); + + Assert.That(largest, Is.LessThanOrEqualTo(LargestAllowedBlock(MAX_LINE_LENGTH))); + } + + [TestCaseSource(nameof(_runEncodings))] + public void LongRun_TextAndPositionsMatchRawBytes (string encodingName) + { + var encoding = Encoding.GetEncoding(encodingName); + var run = RandomRun(encoding, RUN_LENGTH, seed: 758); + var data = TextAroundRun(encoding, run); + + using var stream = new MemoryStream(data, writable: false); + using var reader = new PositionAwareStreamReaderDirect(stream, new EncodingOptions { Encoding = encoding }, MAX_LINE_LENGTH); + + var lines = new List<(string Content, long End)>(); + while (reader.TryReadLine(out var line)) + { + lines.Add((line.ToString(), reader.Position)); + } + + var runStart = encoding.GetByteCount("first\nsecond\r\n"); + var runEnd = runStart + run.Length + encoding.GetByteCount("\r\n"); + + Assert.That(lines.Select(line => line.Content).ToArray(), Is.EqualTo(new[] + { + "first", + "second", + encoding.GetString(run)[..MAX_LINE_LENGTH], + "after", + "last" + })); + Assert.That(lines.Select(line => line.End).ToArray(), Is.EqualTo(new long[] + { + encoding.GetByteCount("first\n"), + runStart, + runEnd, + runEnd + encoding.GetByteCount("after\n"), + data.Length + })); + } + + #endregion + + #region Cut points and terminators at refill boundaries + + // Lines of 1 MB, so the cut happens while the reader still has to refill. + [Test] + public void LongLine_CutInsideMultiByteSequence_MatchesFullDecodeTruncated ( + [Values(0, 1, 2, 3)] int asciiPrefix, + [Values(0x65E5, 0x1F642, 0xC4)] int codePoint, + [Values(7, 100, 20_000)] int maxLineLength) + { + var character = char.ConvertFromUtf32(codePoint); + var line = new string('A', asciiPrefix) + string.Concat(Enumerable.Repeat(character, 1_000_000 / character.Length / 3)); + var data = Encoding.UTF8.GetBytes($"head\n{line}\nnext\n{line}"); + + RawByteLineOracle.AssertMatches(data, Encoding.UTF8, maxLineLength); + } + + [Test] + public void LongLine_InvalidSequenceAtCut_MatchesFullDecodeTruncated ([Values(0, 1, 2)] int asciiPrefix, [Values(7, 100)] int maxLineLength) + { + byte[] pattern = [0xE6, 0x97, 0x41, 0xF0, 0x9F, 0x99, 0xFF]; + var data = new List(Enumerable.Repeat((byte)'A', asciiPrefix)); + while (data.Count < 300_000) + { + data.AddRange(pattern); + } + + data.AddRange("\nend"u8.ToArray()); + + RawByteLineOracle.AssertMatches([.. data], Encoding.UTF8, maxLineLength); + } + + [Test] + public void LongLine_Utf16SurrogatePairsAtCut_MatchesFullDecodeTruncated ([Values(0, 1)] int asciiPrefix, [Values(7, 100, 20_000)] int maxLineLength) + { + var line = new string('A', asciiPrefix) + string.Concat(Enumerable.Repeat("🙂", 300_000)); + + RawByteLineOracle.AssertMatches(Encoding.Unicode.GetBytes($"{line}\r\n{line}"), Encoding.Unicode, maxLineLength); + } + + // GB18030 has 4-byte sequences; a cut one may decode to a char per byte. + [Test] + public void LongLine_Gb18030FourByteSequenceAtCut_MatchesFullDecodeTruncated ( + [Values(0, 1, 2, 3)] int asciiPrefix, + [Values(true, false)] bool broken, + [Values(1, 7, 100)] int maxLineLength) + { + byte[] pattern = broken ? [0x81, 0x30, 0x81, 0x41] : [0x81, 0x30, 0x81, 0x30]; + var data = new List(Enumerable.Repeat((byte)'A', asciiPrefix)); + while (data.Count < 300_000) + { + data.AddRange(pattern); + } + + data.AddRange("\nend"u8.ToArray()); + + RawByteLineOracle.AssertMatches([.. data], EncodingRegistry.GetEncoding(GB18030_CODE_PAGE), maxLineLength); + } + + // The \r is the last byte of a buffer fill, so its partner arrives with the next refill. + [Test] + public void LongLine_CrAtRefillBoundary_IsClassifiedCorrectly ( + [Values(BYTE_BUFFER_SIZE - 1, (2 * BYTE_BUFFER_SIZE) - 1, (3 * BYTE_BUFFER_SIZE) - 1)] int crOffset, + [Values("\n", "Y\n", "\r\n")] string afterCr, + [Values(100, 20_000)] int maxLineLength) + { + byte[] data = [.. Enumerable.Repeat((byte)'X', crOffset), (byte)'\r', .. Encoding.UTF8.GetBytes(afterCr), .. "tail"u8]; + + RawByteLineOracle.AssertMatches(data, Encoding.UTF8, maxLineLength); + } + + [Test] + public void LongLine_Utf16CrAtRefillBoundary_IsClassifiedCorrectly ([Values("\n", "Y")] string afterCr) + { + var data = Encoding.Unicode.GetBytes(new string('X', (BYTE_BUFFER_SIZE / 2) - 1) + "\r" + afterCr + "tail"); + + RawByteLineOracle.AssertMatches(data, Encoding.Unicode, 100); + } + + #endregion + + #region Generated input + + [Test] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5394:Do not use insecure randomness", Justification = "Unit Tests")] + public void LongLines_RandomBytes_MatchFullDecodeTruncated ( + [Range(0, 9)] int seed, + [Values("utf-8", "utf-16", "utf-16BE", "utf-32", "gb2312", "gb18030")] string encodingName, + [Values(1, 7, 1_000)] int maxLineLength) + { + var encoding = encodingName switch + { + "gb2312" => EncodingRegistry.GetEncoding(EncodingRegistry.CODE_PAGE_GB2312), + "gb18030" => EncodingRegistry.GetEncoding(GB18030_CODE_PAGE), + _ => Encoding.GetEncoding(encodingName) + }; + var random = new Random(seed); + var data = RandomRun(encoding, random.Next(100_000, 400_000), seed); + + // Rare terminators, so most lines span several refills. + var terminator = encoding.GetBytes(random.Next(3) switch { 0 => "\n", 1 => "\r", _ => "\r\n" }); + for (var i = 0; i < 4; i++) + { + var offset = random.Next(data.Length - terminator.Length); + terminator.CopyTo(data, offset - (offset % terminator.Length)); + } + + RawByteLineOracle.AssertMatches(data, encoding, maxLineLength); + } + + #endregion + + #region Helpers + + private static int LargestAllowedBlock (int maxLineLength) => Math.Max(BLOCK_SIZE, (int)BitOperations.RoundUpToPowerOf2((uint)maxLineLength)); + + private static byte[] TextAroundRun (Encoding encoding, byte[] run) + { + return [.. encoding.GetBytes("first\nsecond\r\n"), .. run, .. encoding.GetBytes("\r\nafter\nlast")]; + } + + // Random code units, none of them \r or \n. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5394:Do not use insecure randomness", Justification = "Unit Tests")] + private static byte[] RandomRun (Encoding encoding, int length, int seed) + { + var random = new Random(seed); + var run = new byte[length]; + random.NextBytes(run); + + var unitSize = encoding.GetByteCount("\n"); + var lf = encoding.GetBytes("\n"); + var cr = encoding.GetBytes("\r"); + for (var i = 0; i + unitSize <= run.Length; i += unitSize) + { + var unit = run.AsSpan(i, unitSize); + if (unit.SequenceEqual(lf) || unit.SequenceEqual(cr)) + { + unit[0] ^= 0x40; + } + } + + return run; + } + + private static void ReturnBlocks (List blocks) + { + foreach (var block in blocks) + { + ArrayPool.Shared.Return(block); + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Tests/StreamReaderTests/LogfileReaderSingleFileMonitoringTests.cs b/src/LogExpert.Tests/StreamReaderTests/LogfileReaderSingleFileMonitoringTests.cs index ca0a58de..60e6e53f 100644 --- a/src/LogExpert.Tests/StreamReaderTests/LogfileReaderSingleFileMonitoringTests.cs +++ b/src/LogExpert.Tests/StreamReaderTests/LogfileReaderSingleFileMonitoringTests.cs @@ -132,4 +132,49 @@ public void SingleFileReader_GrowingFileWithBinaryBlock_TakesGrowthPathNotNewFil Assert.That(reader.FileSize, Is.EqualTo(new FileInfo(_logFile).Length), "Size read after the growth"); }); } -} + + // Every poll reads the appended line with a new reader; each used to pin a 32,768-char block in the buffer. + [Test] + public void SingleFileReader_OneLinePerPoll_KeepsCharBlocksSizedToTheText () + { + const int appends = 10; + + using var loadingFinished = new ManualResetEventSlim(false); + var progressReporterMock = new Mock(); + _ = progressReporterMock + .Setup(reporter => reporter.ReportLoadingFinished()) + .Callback(() => loadingFinished.Set()); + + using var reader = new LogfileReader( + _logFile, + new EncodingOptions { Encoding = Encoding.UTF8 }, + multiFile: false, + bufferCount: 40, + linesPerBuffer: 500, + new MultiFileOptions(), + PluginRegistry.PluginRegistry.Instance, + maximumLineLength: 500, + progressReporter: progressReporterMock.Object); + + reader.StartMonitoring(); + Assert.That(loadingFinished.Wait(TimeSpan.FromSeconds(5)), Is.True, "Initial load did not finish"); + + for (var i = 1; i <= appends; i++) + { + File.AppendAllText(_logFile, $"Appended {i}\n", Encoding.UTF8); + var expected = 100 + i; + Assert.That(SpinWait.SpinUntil(() => reader.LineCount == expected, TimeSpan.FromSeconds(5)), Is.True, $"Append {i} was not read"); + } + + Assert.That(reader.LineCount, Is.EqualTo(100 + appends)); + + int capacity; + using (reader.BufferIndex.AcquireReadLock()) + { + capacity = reader.BufferIndex.EnumerateBuffers().Sum(buffer => buffer.CharBlockCapacity); + } + + // The text is about 1,000 chars; one full block per poll would be more than 300,000. + Assert.That(capacity, Is.LessThanOrEqualTo(16_384)); + } +} \ No newline at end of file diff --git a/src/LogExpert.Tests/StreamReaderTests/LogfileReaderXmlModeTests.cs b/src/LogExpert.Tests/StreamReaderTests/LogfileReaderXmlModeTests.cs new file mode 100644 index 00000000..ba151c9a --- /dev/null +++ b/src/LogExpert.Tests/StreamReaderTests/LogfileReaderXmlModeTests.cs @@ -0,0 +1,72 @@ +using System.Text; + +using ColumnizerLib; + +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Entities; + +using NUnit.Framework; + +namespace LogExpert.Tests.StreamReaderTests; + +[TestFixture] +public class LogfileReaderXmlModeTests +{ + private string _tempFile; + + [SetUp] + public void Setup () + { + _tempFile = Path.GetTempFileName(); + _ = PluginRegistry.PluginRegistry.Create(Path.GetDirectoryName(_tempFile)!, 500); + } + + [TearDown] + public void Cleanup () + { + if (File.Exists(_tempFile)) + { + File.Delete(_tempFile); + } + } + + [Test] + public void ReadFiles_XmlMode_ReadsOneLinePerEvent () + { + File.WriteAllText(_tempFile, + "first\nsecond\n", + Encoding.UTF8); + + using var reader = new LogfileReader( + _tempFile, + new EncodingOptions { Encoding = Encoding.UTF8 }, + multiFile: false, + bufferCount: 100, + linesPerBuffer: 500, + new MultiFileOptions(), + PluginRegistry.PluginRegistry.Instance, + maximumLineLength: 500, + progressReporter: Core.Classes.Log.ProgressReporters.NullProgressReporter.Instance) + { + IsXmlMode = true, + XmlLogConfig = new PlainXmlConfig() + }; + + reader.ReadFiles(); + + Assert.That(reader.LineCount, Is.EqualTo(2)); + Assert.That(reader.GetLogLineMemory(0)?.FullLine.ToString(), Does.Contain("first")); + Assert.That(reader.GetLogLineMemory(1)?.FullLine.ToString(), Does.Contain("second")); + } + + private sealed class PlainXmlConfig : IXmlLogConfiguration + { + public string XmlStartTag => " ""; + + public string Stylesheet => null; + + public string[] GetNamespaceDeclaration () => null; + } +} \ No newline at end of file diff --git a/src/LogExpert.Tests/StreamReaderTests/PositionAwareStreamReaderDirectTests.cs b/src/LogExpert.Tests/StreamReaderTests/PositionAwareStreamReaderDirectTests.cs index c0e6d6b7..5ca5292d 100644 --- a/src/LogExpert.Tests/StreamReaderTests/PositionAwareStreamReaderDirectTests.cs +++ b/src/LogExpert.Tests/StreamReaderTests/PositionAwareStreamReaderDirectTests.cs @@ -116,6 +116,38 @@ public void TryReadLine_LongLine_Truncated () Assert.That(line2.Span.ToString(), Is.EqualTo("short")); } + // Issue #762: the cap was static, so the last reader constructed set it for every reader. + [Test] + public void TryReadLine_AnotherReaderWithLargerCap_KeepsOwnCap () + { + using var stream = CreateStream(new string('x', 100) + "\n"); + using var reader = new PositionAwareStreamReaderDirect(stream, new EncodingOptions(), 10); + using var otherStream = CreateStream("other\n"); + using var other = new PositionAwareStreamReaderDirect(otherStream, new EncodingOptions(), 1_000); + + Assert.That(reader.TryReadLine(out var line), Is.True); + Assert.That(line.Length, Is.EqualTo(10)); + } + + // The line is far over the cap and spans several refills, so it is cut from the truncation prefix. + [Test] + public void TryReadLine_AnotherReaderCreatedMidRead_KeepsOwnCapForOverLongLine () + { + using var stream = CreateStream("first\n" + new string('x', 200_000) + "\nlast\n"); + using var reader = new PositionAwareStreamReaderDirect(stream, new EncodingOptions(), 10); + + Assert.That(reader.TryReadLine(out var first), Is.True); + Assert.That(first.ToString(), Is.EqualTo("first")); + + using var otherStream = CreateStream("other\n"); + using var other = new PositionAwareStreamReaderDirect(otherStream, new EncodingOptions(), 1_000); + + Assert.That(reader.TryReadLine(out var line), Is.True); + Assert.That(line.ToString(), Is.EqualTo(new string('x', 10))); + Assert.That(reader.TryReadLine(out var last), Is.True); + Assert.That(last.ToString(), Is.EqualTo("last")); + } + #endregion #region Cross-block boundary @@ -326,6 +358,63 @@ public void DetachCharBlocks_ReturnsCompletedBlocks () Assert.That(blocks2.Count, Is.EqualTo(0)); } + [Test] + [TestCase(0)] + [TestCase(200_000)] + public void DetachCharBlocks_ShortTailRead_BlockSizedToRemainingBytes (int precedingBytes) + { + // A tail poll opens a reader near the end of the file and reads one appended line. + const string appended = "one appended line\n"; + using var stream = CreateStream(new string('x', precedingBytes) + appended); + using var reader = new PositionAwareStreamReaderDirect(stream, new EncodingOptions { Encoding = Encoding.UTF8 }, 500); + reader.Position = precedingBytes; + + Assert.That(reader.TryReadLine(out var line), Is.True); + Assert.That(line.ToString(), Is.EqualTo("one appended line")); + + var blocks = reader.DetachCharBlocks(); + Assert.That(blocks.Sum(block => block.Length), Is.LessThanOrEqualTo(64)); + } + + #endregion + + #region Lines longer than the maximum line length + + [Test] + [TestCase("utf-8", 'x', 1_000_000, "\n", "\nnext\n")] + [TestCase("utf-8", 'ä', 1_000_000, "\n", "\nnext\n")] + [TestCase("utf-8", 'x', 1_000_000, "", "")] + [TestCase("utf-8", 'x', 1_000_000, "\r\n", "\r\nnext")] + [TestCase("utf-16", 'ä', 1_000_000, "\r\n", "\r\nnext\r\n")] + [TestCase("utf-32", 'x', 1_000_000, "\r", "\rnext\r")] + // The \r is the last byte of the second 64 KB read, so it is classified after a refill. + [TestCase("utf-8", 'x', 131_071, "\r\n", "\r\nnext")] + [TestCase("utf-8", 'x', 131_071, "\r", "\rnext")] + public void TryReadLine_LineFarOverMaximum_TruncatesWithoutHoldingTheWholeLine (string encodingName, char fill, int length, string terminator, string tail) + { + const int maximumLineLength = 500; + var encoding = Encoding.GetEncoding(encodingName); + var longLine = new string(fill, length); + var data = encoding.GetBytes(longLine + tail); + + using var stream = new MemoryStream(data, writable: false); + using var reader = new PositionAwareStreamReaderDirect(stream, new EncodingOptions { Encoding = encoding }, maximumLineLength); + + Assert.That(reader.TryReadLine(out var first), Is.True); + Assert.That(first.ToString(), Is.EqualTo(longLine[..maximumLineLength])); + Assert.That(reader.Position, Is.EqualTo(encoding.GetByteCount(longLine + terminator))); + + if (tail.Length > 0) + { + Assert.That(reader.TryReadLine(out var next), Is.True); + Assert.That(next.ToString(), Is.EqualTo("next")); + } + + Assert.That(reader.TryReadLine(out _), Is.False); + Assert.That(reader.Position, Is.EqualTo(data.Length)); + Assert.That(reader.DetachCharBlocks().Sum(block => block.Length), Is.LessThanOrEqualTo(65_536)); + } + #endregion #region Lines longer than BLOCK_SIZE (32768 chars) diff --git a/src/LogExpert.Tests/StreamReaderTests/RawByteLineOracle.cs b/src/LogExpert.Tests/StreamReaderTests/RawByteLineOracle.cs index df063fcf..e03e1599 100644 --- a/src/LogExpert.Tests/StreamReaderTests/RawByteLineOracle.cs +++ b/src/LogExpert.Tests/StreamReaderTests/RawByteLineOracle.cs @@ -14,10 +14,10 @@ internal static class RawByteLineOracle { public const int MAX_LINE_LENGTH = 500_000; - public static void AssertMatches (byte[] data, Encoding encoding) + public static void AssertMatches (byte[] data, Encoding encoding, int maxLineLength = MAX_LINE_LENGTH) { - var expected = ExpectedLines(data, encoding); - var actual = ReadAll(data, encoding); + var expected = ExpectedLines(data, encoding, maxLineLength); + var actual = ReadAll(data, encoding, maxLineLength); Assert.That(actual.Count, Is.EqualTo(expected.Count), "Line count"); for (var i = 0; i < expected.Count; i++) @@ -29,10 +29,10 @@ public static void AssertMatches (byte[] data, Encoding encoding) } } - public static List<(string Content, long End)> ReadAll (byte[] data, Encoding encoding) + public static List<(string Content, long End)> ReadAll (byte[] data, Encoding encoding, int maxLineLength = MAX_LINE_LENGTH) { using var stream = new MemoryStream(data); - using var reader = new PositionAwareStreamReaderDirect(stream, new EncodingOptions { Encoding = encoding }, MAX_LINE_LENGTH); + using var reader = new PositionAwareStreamReaderDirect(stream, new EncodingOptions { Encoding = encoding }, maxLineLength); var lines = new List<(string, long)>(); while (reader.TryReadLine(out var line)) @@ -44,7 +44,8 @@ public static void AssertMatches (byte[] data, Encoding encoding) } // A trailing line without terminator is a line; an empty remainder after the last terminator is not. - private static List<(string Content, long End)> ExpectedLines (byte[] data, Encoding encoding) + // Text longer than the maximum is the full line decoded, then truncated. + private static List<(string Content, long End)> ExpectedLines (byte[] data, Encoding encoding, int maxLineLength) { var cr = encoding.GetBytes("\r"); var lf = encoding.GetBytes("\n"); @@ -65,7 +66,7 @@ public static void AssertMatches (byte[] data, Encoding encoding) terminatorLength = 2 * unit; } - lines.Add((encoding.GetString(data, lineStart, position - lineStart), position + terminatorLength)); + lines.Add((Truncate(encoding.GetString(data, lineStart, position - lineStart), maxLineLength), position + terminatorLength)); position += terminatorLength; lineStart = position; } @@ -77,11 +78,13 @@ public static void AssertMatches (byte[] data, Encoding encoding) if (lineStart < data.Length) { - lines.Add((encoding.GetString(data, lineStart, data.Length - lineStart), data.Length)); + lines.Add((Truncate(encoding.GetString(data, lineStart, data.Length - lineStart), maxLineLength), data.Length)); } return lines; } + private static string Truncate (string text, int maxLength) => text.Length <= maxLength ? text : text[..maxLength]; + private static string Shorten (string text) => text.Length <= 60 ? text : $"{text[..60]}… ({text.Length} chars)"; } \ No newline at end of file