using System.Text.Json;
using Microsoft.Data.Sqlite;
namespace XFEEDToolBox.Core.Data;
public sealed record MarketCacheHealth(long Stations, long Quotes, long Snapshots, string SqliteVersion);
public sealed record MarketCacheRecovery(string OriginalBackup, string VerifiedBackup, MarketCacheHealth Health)
{public string? ActiveDatabasePath{get;init;}public bool OriginalPreservedInPlace{get;init;}}
/// <summary>Checks and restores the cache through the same SQLite connection mode as its reader/writer.</summary>
internal static class MarketCacheMaintenance
{
internal static bool IsCorruption(SqliteException error) => error.SqliteErrorCode is 11 or 26;
private static SqliteConnection Open(string path, SqliteOpenMode mode)
{
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
{ DataSource = path, Mode = mode, Pooling = false, DefaultTimeout = 30 }.ToString());
try{connection.Open();return connection;}catch{connection.Dispose();throw;}
}
internal static MarketCacheHealth Check(string path, bool full = false)
{
// Run inside the client: external runtimes may resolve this same path to an MSIX cache copy.
using var connection = Open(path, SqliteOpenMode.ReadWrite);
return Check(connection, full);
}
private static MarketCacheHealth Check(SqliteConnection connection, bool full, SqliteTransaction? transaction = null)
{
using var command = connection.CreateCommand();
command.Transaction = transaction;
long? previousCache=null;var elapsed=System.Diagnostics.Stopwatch.StartNew();var passed=false;
if(full)
{
// Full integrity cross-checks every index entry. A tiny default
// pager cache repeatedly reloads those pages on large generations.
// This connection-local limit allocates on demand and changes no
// persistent setting or integrity-check coverage.
command.CommandText="PRAGMA cache_size";previousCache=(long)command.ExecuteScalar()!;
command.CommandText="PRAGMA cache_size=-131072";command.ExecuteNonQuery();
command.CommandText="PRAGMA cache_size";var applied=(long)command.ExecuteScalar()!;
if(applied!=-131072)throw new InvalidOperationException("完整商品缓存检查的局部页缓存配置未生效。");
Log(connection.DataSource,"full-integrity-start",new{previousCache,appliedCacheKiB=applied});
}
try
{
command.CommandText = full ? "PRAGMA integrity_check(1)" : "PRAGMA quick_check(1)";
var result = command.ExecuteScalar() as string;
if (result != "ok") throw new InvalidDataException("商品缓存完整性检查失败:" + result);
command.CommandText = "SELECT (SELECT count(*) FROM stations),(SELECT count(*) FROM quotes),(SELECT count(*) FROM snapshots),sqlite_version()";
using var reader = command.ExecuteReader();
reader.Read();
var health=new MarketCacheHealth(reader.GetInt64(0), reader.GetInt64(1), reader.GetInt64(2), reader.GetString(3));passed=true;return health;
}
finally
{
if(previousCache is {} before)
{
command.CommandText="PRAGMA cache_size="+before.ToString(System.Globalization.CultureInfo.InvariantCulture);command.ExecuteNonQuery();
Log(connection.DataSource,"full-integrity-finished",new{passed,elapsedMilliseconds=elapsed.Elapsed.TotalMilliseconds,restoredCache=before});
}
}
}
internal static void SaveVerifiedBackup(string path, string backupPath,Func<long>? availableBytes=null)
{
// A WAL destination can first hold the whole new backup in its WAL and
// then grow its main file during checkpoint. Refuse before opening it
// when a large full refresh would consume the remaining disk space.
var required=checked(2*(new FileInfo(path).Length+(File.Exists(path+"-wal")?new FileInfo(path+"-wal").Length:0)));
var available=availableBytes?.Invoke()??new DriveInfo(Path.GetPathRoot(Path.GetFullPath(backupPath))!).AvailableFreeSpace;
const long reserve=256L*1024*1024;
if(available<reserve||required>available-reserve)
throw new IOException($"商品缓存备份需要约 {required:N0} 字节,当前可用 {available:N0} 字节;已保留原验证备份。");
var temporary=backupPath+"."+Guid.NewGuid().ToString("N")+".tmp";
try
{
using(var source = Open(path, SqliteOpenMode.ReadWrite))
using(var transaction = source.BeginTransaction(deferred: true))
{
var health=Check(source, true, transaction);
if(health.Quotes==0||health.Stations==0)throw new InvalidDataException("空缓存不能覆盖已验证的行情备份。");
using var destination=Open(temporary,SqliteOpenMode.ReadWriteCreate);source.BackupDatabase(destination);
if(Check(destination,true)!=health)throw new InvalidDataException("新验证备份条数与来源不一致。");
using var checkpoint=destination.CreateCommand();checkpoint.CommandText="PRAGMA wal_checkpoint(TRUNCATE)";checkpoint.ExecuteNonQuery();
transaction.Commit();
}
if(File.Exists(backupPath))
{
string? archive=null;
try{Check(backupPath);}
catch(Exception error)when(error is InvalidDataException||error is SqliteException sql&&IsCorruption(sql))
{archive=backupPath+".invalid-"+DateTimeOffset.UtcNow.ToString("yyyyMMdd-HHmmss")+"-"+Guid.NewGuid().ToString("N")[..8]+".db";}
if(File.Exists(backupPath+"-wal")&&new FileInfo(backupPath+"-wal").Length>0)throw new IOException("现有验证备份仍被WAL读取,保留原件,稍后重试。");
File.Replace(temporary,backupPath,archive);
}
else File.Move(temporary,backupPath);
}
finally
{
foreach(var extra in new[]{temporary,temporary+"-wal",temporary+"-shm"})if(File.Exists(extra))File.Delete(extra);
}
}
internal static string ActivePath(string originalPath)
{
var marker=originalPath+".active";
if(!File.Exists(marker))return originalPath;
var name=File.ReadAllText(marker).Trim();
if(name!=Path.GetFileName(name)||!name.StartsWith(Path.GetFileName(originalPath)+".recovered-",StringComparison.Ordinal)
||!name.EndsWith(".db",StringComparison.Ordinal))throw new InvalidDataException("商品缓存恢复记录中的文件名无效。");
var active=Path.Combine(Path.GetDirectoryName(originalPath)!,name);
if(!File.Exists(active))throw new InvalidDataException("商品缓存恢复记录指向的数据库不存在,原始库已保留。");
return active;
}
internal static MarketCacheRecovery Restore(string path, string backupPath,string originalPath)
{
if (Path.GetFullPath(path).Equals(Path.GetFullPath(backupPath), StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("恢复来源不能是当前缓存。");
var identity=Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(Path.GetFullPath(originalPath).ToUpperInvariant())));
using var recoveryLock=new Mutex(false,"XFEEDToolBox.MarketRecovery."+identity);
var acquired=false;
try
{
try{acquired=recoveryLock.WaitOne(TimeSpan.FromSeconds(60));}catch(AbandonedMutexException){acquired=true;}
if(!acquired)throw new IOException("另一进程正在恢复商品缓存,请稍后重试。");
using(var pool=new SqliteConnection(new SqliteConnectionStringBuilder
{DataSource=path,Mode=SqliteOpenMode.ReadWriteCreate,DefaultTimeout=20}.ToString()))SqliteConnection.ClearPool(pool);
var selected=ActivePath(originalPath);
if(!Path.GetFullPath(selected).Equals(Path.GetFullPath(path),StringComparison.OrdinalIgnoreCase))
{
var existing=Check(selected,true);
return new(path,backupPath,existing){ActiveDatabasePath=selected,OriginalPreservedInPlace=true};
}
using var source = Open(backupPath, SqliteOpenMode.ReadWrite);
using var snapshot = source.BeginTransaction(deferred: true);
var expected = Check(source, true, snapshot);
if (expected.Stations == 0 || expected.Quotes == 0)
throw new InvalidDataException("恢复副本没有行情,保留当前缓存,停止恢复。");
// A truncated database may not even permit sqlite3_backup to archive
// it or open it as a backup destination. Preserve it and its WAL/SHM
// untouched, and publish a separately verified healthy generation.
var replacement=originalPath+".recovered-"+DateTimeOffset.UtcNow.ToString("yyyyMMdd-HHmmss")+"-"+Guid.NewGuid().ToString("N")[..8]+".db";
using(var destination=Open(replacement,SqliteOpenMode.ReadWriteCreate))
{
source.BackupDatabase(destination);
var actual=Check(destination,true);
if(actual!=expected)throw new InvalidDataException("商品缓存恢复后的条数与恢复来源不一致。");
using var checkpoint=destination.CreateCommand();checkpoint.CommandText="PRAGMA wal_checkpoint(TRUNCATE)";checkpoint.ExecuteNonQuery();
}
snapshot.Commit();
var reopened = Check(replacement, true);
if (reopened != expected) throw new InvalidDataException("商品缓存重新打开后的校验失败。");
var marker=originalPath+".active";var temporary=marker+"."+Guid.NewGuid().ToString("N")+".tmp";
try
{
using(var file=new FileStream(temporary,FileMode.CreateNew,FileAccess.Write,FileShare.Read,4096,FileOptions.WriteThrough))
{var bytes=System.Text.Encoding.UTF8.GetBytes(Path.GetFileName(replacement));file.Write(bytes);file.Flush(true);}
File.Move(temporary,marker,true);
}
finally{if(File.Exists(temporary))File.Delete(temporary);}
return new(path, backupPath, reopened){ActiveDatabasePath=replacement,OriginalPreservedInPlace=true};
}
finally{if(acquired)recoveryLock.ReleaseMutex();}
}
internal static void Log(string path, string operation, object detail)
{
try { File.AppendAllText(path + ".diagnostics.jsonl", JsonSerializer.Serialize(new
{ time = DateTimeOffset.UtcNow, pid = Environment.ProcessId, database = path, mode = "ReadWrite", operation, detail }) + Environment.NewLine); }
catch (IOException) { /* Diagnostics must not make a healthy database unavailable. */ }
catch (UnauthorizedAccessException) { }
}
}
using System.Text.Json;
using Microsoft.Data.Sqlite;
namespace XFEEDToolBox.Core.Data;
public sealed record MarketCacheHealth(long Stations, long Quotes, long Snapshots, string SqliteVersion);
public sealed record MarketCacheRecovery(string OriginalBackup, string VerifiedBackup, MarketCacheHealth Health)
{public string? ActiveDatabasePath{get;init;}public bool OriginalPreservedInPlace{get;init;}}
/// <summary>Checks and restores the cache through the same SQLite connection mode as its reader/writer.</summary>
internal static class MarketCacheMaintenance
{
internal static bool IsCorruption(SqliteException error) => error.SqliteErrorCode is 11 or 26;
private static SqliteConnection Open(string path, SqliteOpenMode mode)
{
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
{ DataSource = path, Mode = mode, Pooling = false, DefaultTimeout = 30 }.ToString());
try{connection.Open();return connection;}catch{connection.Dispose();throw;}
}
internal static MarketCacheHealth Check(string path, bool full = false)
{
// Run inside the client: external runtimes may resolve this same path to an MSIX cache copy.
using var connection = Open(path, SqliteOpenMode.ReadWrite);
return Check(connection, full);
}
private static MarketCacheHealth Check(SqliteConnection connection, bool full, SqliteTransaction? transaction = null)
{
using var command = connection.CreateCommand();
command.Transaction = transaction;
long? previousCache=null;var elapsed=System.Diagnostics.Stopwatch.StartNew();var passed=false;
if(full)
{
// Full integrity cross-checks every index entry. A tiny default
// pager cache repeatedly reloads those pages on large generations.
// This connection-local limit allocates on demand and changes no
// persistent setting or integrity-check coverage.
command.CommandText="PRAGMA cache_size";previousCache=(long)command.ExecuteScalar()!;
command.CommandText="PRAGMA cache_size=-131072";command.ExecuteNonQuery();
command.CommandText="PRAGMA cache_size";var applied=(long)command.ExecuteScalar()!;
if(applied!=-131072)throw new InvalidOperationException("完整商品缓存检查的局部页缓存配置未生效。");
Log(connection.DataSource,"full-integrity-start",new{previousCache,appliedCacheKiB=applied});
}
try
{
command.CommandText = full ? "PRAGMA integrity_check(1)" : "PRAGMA quick_check(1)";
var result = command.ExecuteScalar() as string;
if (result != "ok") throw new InvalidDataException("商品缓存完整性检查失败:" + result);
command.CommandText = "SELECT (SELECT count(*) FROM stations),(SELECT count(*) FROM quotes),(SELECT count(*) FROM snapshots),sqlite_version()";
using var reader = command.ExecuteReader();
reader.Read();
var health=new MarketCacheHealth(reader.GetInt64(0), reader.GetInt64(1), reader.GetInt64(2), reader.GetString(3));passed=true;return health;
}
finally
{
if(previousCache is {} before)
{
command.CommandText="PRAGMA cache_size="+before.ToString(System.Globalization.CultureInfo.InvariantCulture);command.ExecuteNonQuery();
Log(connection.DataSource,"full-integrity-finished",new{passed,elapsedMilliseconds=elapsed.Elapsed.TotalMilliseconds,restoredCache=before});
}
}
}
internal static void SaveVerifiedBackup(string path, string backupPath,Func<long>? availableBytes=null)
{
// A WAL destination can first hold the whole new backup in its WAL and
// then grow its main file during checkpoint. Refuse before opening it
// when a large full refresh would consume the remaining disk space.
var required=checked(2*(new FileInfo(path).Length+(File.Exists(path+"-wal")?new FileInfo(path+"-wal").Length:0)));
var available=availableBytes?.Invoke()??new DriveInfo(Path.GetPathRoot(Path.GetFullPath(backupPath))!).AvailableFreeSpace;
const long reserve=256L*1024*1024;
if(available<reserve||required>available-reserve)
throw new IOException($"商品缓存备份需要约 {required:N0} 字节,当前可用 {available:N0} 字节;已保留原验证备份。");
var temporary=backupPath+"."+Guid.NewGuid().ToString("N")+".tmp";
try
{
using(var source = Open(path, SqliteOpenMode.ReadWrite))
using(var transaction = source.BeginTransaction(deferred: true))
{
var health=Check(source, true, transaction);
if(health.Quotes==0||health.Stations==0)throw new InvalidDataException("空缓存不能覆盖已验证的行情备份。");
using var destination=Open(temporary,SqliteOpenMode.ReadWriteCreate);source.BackupDatabase(destination);
if(Check(destination,true)!=health)throw new InvalidDataException("新验证备份条数与来源不一致。");
using var checkpoint=destination.CreateCommand();checkpoint.CommandText="PRAGMA wal_checkpoint(TRUNCATE)";checkpoint.ExecuteNonQuery();
transaction.Commit();
}
if(File.Exists(backupPath))
{
string? archive=null;
try{Check(backupPath);}
catch(Exception error)when(error is InvalidDataException||error is SqliteException sql&&IsCorruption(sql))
{archive=backupPath+".invalid-"+DateTimeOffset.UtcNow.ToString("yyyyMMdd-HHmmss")+"-"+Guid.NewGuid().ToString("N")[..8]+".db";}
if(File.Exists(backupPath+"-wal")&&new FileInfo(backupPath+"-wal").Length>0)throw new IOException("现有验证备份仍被WAL读取,保留原件,稍后重试。");
File.Replace(temporary,backupPath,archive);
}
else File.Move(temporary,backupPath);
}
finally
{
foreach(var extra in new[]{temporary,temporary+"-wal",temporary+"-shm"})if(File.Exists(extra))File.Delete(extra);
}
}
internal static string ActivePath(string originalPath)
{
var marker=originalPath+".active";
if(!File.Exists(marker))return originalPath;
var name=File.ReadAllText(marker).Trim();
if(name!=Path.GetFileName(name)||!name.StartsWith(Path.GetFileName(originalPath)+".recovered-",StringComparison.Ordinal)
||!name.EndsWith(".db",StringComparison.Ordinal))throw new InvalidDataException("商品缓存恢复记录中的文件名无效。");
var active=Path.Combine(Path.GetDirectoryName(originalPath)!,name);
if(!File.Exists(active))throw new InvalidDataException("商品缓存恢复记录指向的数据库不存在,原始库已保留。");
return active;
}
internal static MarketCacheRecovery Restore(string path, string backupPath,string originalPath)
{
if (Path.GetFullPath(path).Equals(Path.GetFullPath(backupPath), StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("恢复来源不能是当前缓存。");
var identity=Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(Path.GetFullPath(originalPath).ToUpperInvariant())));
using var recoveryLock=new Mutex(false,"XFEEDToolBox.MarketRecovery."+identity);
var acquired=false;
try
{
try{acquired=recoveryLock.WaitOne(TimeSpan.FromSeconds(60));}catch(AbandonedMutexException){acquired=true;}
if(!acquired)throw new IOException("另一进程正在恢复商品缓存,请稍后重试。");
using(var pool=new SqliteConnection(new SqliteConnectionStringBuilder
{DataSource=path,Mode=SqliteOpenMode.ReadWriteCreate,DefaultTimeout=20}.ToString()))SqliteConnection.ClearPool(pool);
var selected=ActivePath(originalPath);
if(!Path.GetFullPath(selected).Equals(Path.GetFullPath(path),StringComparison.OrdinalIgnoreCase))
{
var existing=Check(selected,true);
return new(path,backupPath,existing){ActiveDatabasePath=selected,OriginalPreservedInPlace=true};
}
using var source = Open(backupPath, SqliteOpenMode.ReadWrite);
using var snapshot = source.BeginTransaction(deferred: true);
var expected = Check(source, true, snapshot);
if (expected.Stations == 0 || expected.Quotes == 0)
throw new InvalidDataException("恢复副本没有行情,保留当前缓存,停止恢复。");
// A truncated database may not even permit sqlite3_backup to archive
// it or open it as a backup destination. Preserve it and its WAL/SHM
// untouched, and publish a separately verified healthy generation.
var replacement=originalPath+".recovered-"+DateTimeOffset.UtcNow.ToString("yyyyMMdd-HHmmss")+"-"+Guid.NewGuid().ToString("N")[..8]+".db";
using(var destination=Open(replacement,SqliteOpenMode.ReadWriteCreate))
{
source.BackupDatabase(destination);
var actual=Check(destination,true);
if(actual!=expected)throw new InvalidDataException("商品缓存恢复后的条数与恢复来源不一致。");
using var checkpoint=destination.CreateCommand();checkpoint.CommandText="PRAGMA wal_checkpoint(TRUNCATE)";checkpoint.ExecuteNonQuery();
}
snapshot.Commit();
var reopened = Check(replacement, true);
if (reopened != expected) throw new InvalidDataException("商品缓存重新打开后的校验失败。");
var marker=originalPath+".active";var temporary=marker+"."+Guid.NewGuid().ToString("N")+".tmp";
try
{
using(var file=new FileStream(temporary,FileMode.CreateNew,FileAccess.Write,FileShare.Read,4096,FileOptions.WriteThrough))
{var bytes=System.Text.Encoding.UTF8.GetBytes(Path.GetFileName(replacement));file.Write(bytes);file.Flush(true);}
File.Move(temporary,marker,true);
}
finally{if(File.Exists(temporary))File.Delete(temporary);}
return new(path, backupPath, reopened){ActiveDatabasePath=replacement,OriginalPreservedInPlace=true};
}
finally{if(acquired)recoveryLock.ReleaseMutex();}
}
internal static void Log(string path, string operation, object detail)
{
try { File.AppendAllText(path + ".diagnostics.jsonl", JsonSerializer.Serialize(new
{ time = DateTimeOffset.UtcNow, pid = Environment.ProcessId, database = path, mode = "ReadWrite", operation, detail }) + Environment.NewLine); }
catch (IOException) { /* Diagnostics must not make a healthy database unavailable. */ }
catch (UnauthorizedAccessException) { }
}
}