Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
153 lines
5.6 KiB
C#
153 lines
5.6 KiB
C#
using System.Globalization;
|
|
using System.Text.RegularExpressions;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Storage;
|
|
|
|
namespace Febe.Core.Library;
|
|
|
|
/// <summary>A daily copy of the database.</summary>
|
|
public sealed record BackupFile(DateOnly Day, string Path, long Bytes);
|
|
|
|
/// <summary>Result of a daily backup run.</summary>
|
|
/// <param name="Created">The copy made now, or null when today's copy already existed.</param>
|
|
/// <param name="Removed">Copies removed by the retention.</param>
|
|
public sealed record BackupResult(BackupFile? Created, IReadOnlyList<string> Removed);
|
|
|
|
/// <summary>
|
|
/// Daily copy of the database (spec §8.5): <c>VACUUM INTO</c> a new file <c>Dati/copie/febe-YYYY-MM-DD.sqlite</c>
|
|
/// (local date), keeping seven days. A copy is written under a temporary name and renamed, so a cut copy never has a
|
|
/// final name. Only files named <c>febe-YYYY-MM-DD.sqlite</c> are ever removed.
|
|
/// </summary>
|
|
public sealed partial class DailyBackup(IDatabaseMaintenance database, IClock clock, string backupsFolder, int keepDays = DailyBackup.DefaultKeepDays)
|
|
{
|
|
public const int DefaultKeepDays = 7;
|
|
|
|
private const string Prefix = "febe-";
|
|
private const string Extension = ".sqlite";
|
|
private const string PartSuffix = ".part";
|
|
|
|
[GeneratedRegex(@"^febe-(\d{4}-\d{2}-\d{2})\.sqlite$", RegexOptions.CultureInvariant)]
|
|
private static partial Regex BackupName();
|
|
|
|
/// <summary>The backups folder.</summary>
|
|
public string Folder { get; } = Path.GetFullPath(backupsFolder);
|
|
|
|
/// <summary>File name of the copy of a day.</summary>
|
|
public static string FileNameFor(DateOnly day) => Prefix + day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + Extension;
|
|
|
|
/// <summary>Makes today's copy if missing, then applies the retention. Safe to call often.</summary>
|
|
public async Task<BackupResult> RunAsync(CancellationToken ct = default)
|
|
{
|
|
Directory.CreateDirectory(Folder);
|
|
var today = LocalCalendar.Today(clock.Now, clock.LocalZone);
|
|
var target = Path.Combine(Folder, FileNameFor(today));
|
|
BackupFile? created = null;
|
|
if (!File.Exists(target))
|
|
{
|
|
var part = target + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix;
|
|
try
|
|
{
|
|
await database.BackupToAsync(part, ct).ConfigureAwait(false);
|
|
File.Move(part, target, overwrite: false);
|
|
created = new BackupFile(today, target, new FileInfo(target).Length);
|
|
}
|
|
finally
|
|
{
|
|
if (File.Exists(part))
|
|
{
|
|
File.Delete(part);
|
|
}
|
|
}
|
|
}
|
|
|
|
return new BackupResult(created, ApplyRetention(today));
|
|
}
|
|
|
|
/// <summary>
|
|
/// «Fai una copia adesso» (Impostazioni, Dati): a fresh copy of the database now. It becomes today's copy, replacing
|
|
/// the one made earlier today only after the new one is complete (one copy per day, as the retention expects).
|
|
/// Then the retention is applied.
|
|
/// </summary>
|
|
public async Task<BackupResult> RunNowAsync(CancellationToken ct = default)
|
|
{
|
|
Directory.CreateDirectory(Folder);
|
|
var today = LocalCalendar.Today(clock.Now, clock.LocalZone);
|
|
var target = Path.Combine(Folder, FileNameFor(today));
|
|
var part = target + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix;
|
|
BackupFile created;
|
|
try
|
|
{
|
|
await database.BackupToAsync(part, ct).ConfigureAwait(false);
|
|
File.Move(part, target, overwrite: true);
|
|
created = new BackupFile(today, target, new FileInfo(target).Length);
|
|
}
|
|
finally
|
|
{
|
|
if (File.Exists(part))
|
|
{
|
|
File.Delete(part);
|
|
}
|
|
}
|
|
|
|
return new BackupResult(created, ApplyRetention(today));
|
|
}
|
|
|
|
/// <summary>The copies present, newest first.</summary>
|
|
public IReadOnlyList<BackupFile> List()
|
|
{
|
|
if (!Directory.Exists(Folder))
|
|
{
|
|
return [];
|
|
}
|
|
|
|
var list = new List<BackupFile>();
|
|
foreach (var file in Directory.EnumerateFiles(Folder, Prefix + "*" + Extension))
|
|
{
|
|
if (TryParseDay(Path.GetFileName(file)) is { } day)
|
|
{
|
|
list.Add(new BackupFile(day, file, new FileInfo(file).Length));
|
|
}
|
|
}
|
|
|
|
return list.OrderByDescending(b => b.Day).ToList();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Removes copies older than <see cref="DefaultKeepDays"/> days (today included) and stale temporary copies.
|
|
/// Returns the removed paths.
|
|
/// </summary>
|
|
public IReadOnlyList<string> ApplyRetention(DateOnly today)
|
|
{
|
|
var removed = new List<string>();
|
|
if (!Directory.Exists(Folder))
|
|
{
|
|
return removed;
|
|
}
|
|
|
|
var oldestKept = today.AddDays(-(Math.Max(1, keepDays) - 1));
|
|
foreach (var backup in List().Where(b => b.Day < oldestKept))
|
|
{
|
|
File.Delete(backup.Path);
|
|
removed.Add(backup.Path);
|
|
}
|
|
|
|
foreach (var part in Directory.EnumerateFiles(Folder, Prefix + "*" + PartSuffix))
|
|
{
|
|
File.Delete(part);
|
|
removed.Add(part);
|
|
}
|
|
|
|
return removed;
|
|
}
|
|
|
|
/// <summary>The day of a backup file name, or null for any other file.</summary>
|
|
public static DateOnly? TryParseDay(string fileName)
|
|
{
|
|
var match = BackupName().Match(fileName);
|
|
return match.Success && DateOnly.TryParseExact(match.Groups[1].Value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day)
|
|
? day
|
|
: null;
|
|
}
|
|
}
|