Files
Anubis/src/Anubis/Db/Backups.cs
T
Alby96andClaude Opus 5.5 4897594b87 Rebuild the state from the brokers after a restore and refuse an older copy
A restore, an import or an adopted database restarts protected: the engine
stays stopped, reads from the broker what the archive does not know (orders,
stops, executions, also from the OKX history up to 89 days), cancels orders
left working, protects what it finds and waits for the user. Strategies with
real money stay exit only until confirmed again. The database of before the
restore, put back by mistake, is refused by its fingerprint.

A failed migration leaves the engine off with one backup and a way to try
again; an archive is checked whole before the database is touched; a changed
secret key no longer crashes anything, and "anubis access reset" gives the
access back to whoever holds the computer. The image runs the db and access
commands without the guard.

refs #69

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:52:08 +01:00

107 lines
4.4 KiB
C#

using System.Globalization;
using Anubis.Core;
using Anubis.Platform;
namespace Anubis.Db;
/// <summary>A backup folder in /data/backups.</summary>
public sealed record BackupInfo(string Folder, string Name, DateTimeOffset TakenAt, string Reason, bool HasSqliteCopy);
/// <summary>
/// Backups (SPEC 5.4): the engine-independent archive, plus a consistent copy of the SQLite file made with the
/// backup API. Nightly at 03:30 Italian time, before every migration, and on request. The last 14 nightly ones are
/// kept, and separately the last 14 of each other kind, so a series of one kind never pushes out the others.
/// </summary>
public sealed class Backups(DataDirectory data, IClock clock)
{
public const int Keep = 14;
public const string BeforeMigration = "prima-della-migrazione";
public const string ArchiveFolder = "archivio";
public const string SqliteCopy = "anubis.sqlite3";
public async Task<BackupInfo> TakeAsync(Database db, string reason, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(db);
Directory.CreateDirectory(data.Backups);
var now = clock.UtcNow;
var name = now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture) + "-" + reason;
var folder = Path.Combine(data.Backups, name);
for (var n = 2; Directory.Exists(folder); n++)
{
folder = Path.Combine(data.Backups, name + "-" + n.ToString(CultureInfo.InvariantCulture));
}
// Written under a temporary name and renamed at the end: a half-written backup never looks complete.
var temp = folder + ".partial";
try
{
await Archive.ExportAsync(db, Path.Combine(temp, ArchiveFolder), clock, cancellationToken).ConfigureAwait(false);
if (db.Engine == DbEngine.Sqlite)
{
await db.BackupSqliteFileAsync(Path.Combine(temp, SqliteCopy), cancellationToken).ConfigureAwait(false);
await Installation.SealCopyAsync(Path.Combine(temp, SqliteCopy), cancellationToken).ConfigureAwait(false);
}
Directory.Move(temp, folder);
}
catch
{
if (Directory.Exists(temp))
{
Directory.Delete(temp, recursive: true);
}
throw;
}
Prune();
return Describe(folder)!;
}
/// <summary>Backups from the newest, only complete ones.</summary>
public IReadOnlyList<BackupInfo> List() =>
!Directory.Exists(data.Backups)
? []
: Directory.EnumerateDirectories(data.Backups)
.Where(d => !d.EndsWith(".partial", StringComparison.Ordinal))
.Select(Describe)
.OfType<BackupInfo>()
.OrderByDescending(b => b.TakenAt)
.ThenByDescending(b => b.Name, StringComparer.Ordinal)
.ToList();
private void Prune()
{
foreach (var old in List().GroupBy(b => Kind(b.Reason)).SelectMany(g => g.Skip(Keep)))
{
Directory.Delete(old.Folder, recursive: true);
}
// What a backup cut off by a power failure left behind; one under way right now is younger than a day.
foreach (var partial in Directory.EnumerateDirectories(data.Backups, "*.partial").Where(d => clock.UtcNow - new DateTimeOffset(Directory.GetLastWriteTimeUtc(d)) > TimeSpan.FromDays(1)))
{
Directory.Delete(partial, recursive: true);
}
}
// "notturno-2" is the second of the same second: the number is not part of the kind.
private static string Kind(string reason)
{
var dash = reason.LastIndexOf('-');
return dash > 0 && int.TryParse(reason[(dash + 1)..], NumberStyles.None, CultureInfo.InvariantCulture, out _) ? reason[..dash] : reason;
}
private static BackupInfo? Describe(string folder)
{
var name = Path.GetFileName(folder);
if (name.Length < 16 || !File.Exists(Path.Combine(folder, ArchiveFolder, Archive.IndexFile))
|| !DateTime.TryParseExact(name[..15], "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var taken))
{
return null;
}
var reason = name.Length > 16 ? name[16..] : "";
return new BackupInfo(folder, name, new DateTimeOffset(taken, TimeSpan.Zero), reason, File.Exists(Path.Combine(folder, SqliteCopy)));
}
}