using System.Globalization; using System.Text.RegularExpressions; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Storage; namespace Febe.Core.Library; /// A daily copy of the database. public sealed record BackupFile(DateOnly Day, string Path, long Bytes); /// Result of a daily backup run. /// The copy made now, or null when today's copy already existed. /// Copies removed by the retention. public sealed record BackupResult(BackupFile? Created, IReadOnlyList Removed); /// /// Daily copy of the database (spec §8.5): VACUUM INTO a new file Dati/copie/febe-YYYY-MM-DD.sqlite /// (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 febe-YYYY-MM-DD.sqlite are ever removed. /// 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(); /// The backups folder. public string Folder { get; } = Path.GetFullPath(backupsFolder); /// File name of the copy of a day. public static string FileNameFor(DateOnly day) => Prefix + day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + Extension; /// Makes today's copy if missing, then applies the retention. Safe to call often. public async Task 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)); } /// /// «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. /// public async Task 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)); } /// The copies present, newest first. public IReadOnlyList List() { if (!Directory.Exists(Folder)) { return []; } var list = new List(); 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(); } /// /// Removes copies older than days (today included) and stale temporary copies. /// Returns the removed paths. /// public IReadOnlyList ApplyRetention(DateOnly today) { var removed = new List(); 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; } /// The day of a backup file name, or null for any other file. 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; } }