using System.Text.Json;
using Microsoft.Extensions.Logging;
namespace MMail.Client.Services;
public sealed class StorageUsageService : BackgroundService
{
public const string Category = "System";
public const string Key = "StorageUsage";
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(30);
private readonly AppSettingsService _settings;
private readonly MailStore _store;
private readonly ILogger<StorageUsageService> _logger;
private readonly SemaphoreSlim _gate = new(1, 1);
public StorageUsageService(
AppSettingsService settings, MailStore store, ILogger<StorageUsageService> logger)
{
_settings = settings;
_store = store;
_logger = logger;
}
public async Task<StorageUsage?> ReadAsync(CancellationToken ct)
{
var json = await _settings.GetAsync(Category, Key, ct);
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
return JsonSerializer.Deserialize<StorageUsage>(json);
}
catch (JsonException ex)
{
_logger.LogWarning(ex, "库里的磁盘占用记录无法解析,当作未统计。");
return null;
}
}
public async Task RefreshAsync(CancellationToken ct = default)
{
if (!await _gate.WaitAsync(0, ct)) return;
try
{
await MeasureAsync(ct);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "统计磁盘占用失败。");
}
finally
{
_gate.Release();
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("磁盘占用统计服务启动,间隔 {Minutes} 分钟", Interval.TotalMinutes);
try
{
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
catch (OperationCanceledException)
{
return;
}
using var timer = new PeriodicTimer(Interval);
while (!stoppingToken.IsCancellationRequested)
{
try
{
await _gate.WaitAsync(stoppingToken);
try
{
await MeasureAsync(stoppingToken);
}
finally
{
_gate.Release();
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(ex, "本轮磁盘占用统计失败");
}
try
{
await timer.WaitForNextTickAsync(stoppingToken);
}
catch (OperationCanceledException)
{
break;
}
}
_logger.LogInformation("磁盘占用统计服务已停止");
}
private async Task MeasureAsync(CancellationToken ct)
{
var mailBytes = Measure(_store.Root);
var otherBytes = Measure(PathHelper.DataDirectory, _store.Root);
var usage = new StorageUsage(mailBytes, otherBytes, mailBytes + otherBytes, DateTime.UtcNow);
await _settings.SetAsync(Category, Key, JsonSerializer.Serialize(usage), false, ct);
_logger.LogInformation(
"磁盘占用统计完成:合计 {Total} 字节(邮件与附件 {Mail},其余 {Other})",
usage.TotalBytes, usage.MailBytes, usage.OtherBytes);
}
private static long Measure(string root, string? skip = null)
{
if (!Directory.Exists(root)) return 0;
var skipPath = string.IsNullOrWhiteSpace(skip) ? null : Path.GetFullPath(skip);
var pending = new Stack<string>();
pending.Push(Path.GetFullPath(root));
long total = 0;
while (pending.Count > 0)
{
var dir = pending.Pop();
try
{
foreach (var file in new DirectoryInfo(dir).EnumerateFiles())
{
try { total += file.Length; }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
foreach (var sub in Directory.EnumerateDirectories(dir))
{
if (skipPath is null || !IsSameOrUnder(skipPath, sub)) pending.Push(sub);
}
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
return total;
}
private static bool IsSameOrUnder(string parent, string candidate)
{
var full = Path.GetFullPath(candidate);
return string.Equals(full, parent, StringComparison.Ordinal)
|| full.StartsWith(parent + Path.DirectorySeparatorChar, StringComparison.Ordinal);
}
}
public sealed record StorageUsage(
long MailBytes,
long OtherBytes,
long TotalBytes,
DateTime MeasuredAt);