using System.Text;
namespace AttendanceHub.Sync.Host;
///
/// Size-based rotating for the service console redirect.
///
/// The old implementation held a single open forever, so the log
/// grew without bound (53 MB in ~6 days, ~50 MB/day with the v2-perf heartbeat cadence).
/// When the active file exceeds maxBytes it is rotated to path.1
/// (path.1 → path.2, oldest deleted) and a fresh file is started.
/// All writes are serialized so multi-threaded console/logger output cannot interleave
/// mid-line or rotate underneath an open write.
///
public sealed class RotatingFileWriter : TextWriter
{
/// 32 MB per file × (1 active + 2 rotated) ≈ 96 MB hard ceiling.
public const long DefaultMaxBytes = 32L * 1024 * 1024;
public const int DefaultKeep = 2;
private readonly string _path;
private readonly long _maxBytes;
private readonly int _keep;
private readonly Encoding _encoding = new UTF8Encoding(false);
private readonly object _gate = new();
private StreamWriter _writer;
private long _writtenBytes;
private bool _disposed;
public RotatingFileWriter(string path, long maxBytes = DefaultMaxBytes, int keep = DefaultKeep)
{
_path = path;
_maxBytes = Math.Max(64 * 1024, maxBytes);
_keep = Math.Max(1, keep);
_writer = CreateWriter();
_writtenBytes = File.Exists(path) ? new FileInfo(path).Length : 0;
}
public override Encoding Encoding => _encoding;
public override void Write(char value)
{
lock (_gate)
{
if (_disposed) return;
_writer.Write(value);
_writtenBytes += _encoding.GetByteCount(value.ToString());
MaybeRotate();
}
}
public override void Write(char[] buffer, int index, int count)
{
lock (_gate)
{
if (_disposed) return;
_writer.Write(buffer, index, count);
_writtenBytes += _encoding.GetByteCount(buffer, index, count);
MaybeRotate();
}
}
public override void Write(string? value)
{
if (value is null) return;
lock (_gate)
{
if (_disposed) return;
_writer.Write(value);
_writtenBytes += _encoding.GetByteCount(value);
MaybeRotate();
}
}
public override void Flush()
{
lock (_gate)
{
if (!_disposed)
_writer.Flush();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
lock (_gate)
{
if (_disposed) return;
_disposed = true;
_writer.Dispose();
}
}
base.Dispose(disposing);
}
private StreamWriter CreateWriter()
=> new(_path, append: true, _encoding) { AutoFlush = true };
private void MaybeRotate()
{
if (_writtenBytes < _maxBytes)
return;
// 1) Close the active stream so the file can be moved.
_writer.Dispose();
// 2) Shift history: path.(keep-1) → path.keep, ..., path.1 → path.2, path → path.1.
for (var i = _keep - 1; i >= 1; i--)
{
var src = $"{_path}.{i}";
if (!File.Exists(src)) continue;
var dst = $"{_path}.{i + 1}";
File.Delete(dst);
File.Move(src, dst);
}
var oldest = $"{_path}.1";
File.Delete(oldest);
File.Move(_path, oldest);
// 3) Fresh stream for the new period.
_writer = CreateWriter();
_writtenBytes = 0;
_writer.WriteLine(
$"{DateTimeOffset.UtcNow:o} LOG_ROTATED previous={oldest} maxBytes={_maxBytes} keep={_keep}");
}
}