using System.Buffers.Binary;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.Win32.SafeHandles;
namespace XFEEDToolBox.Core.Data;
internal sealed record MarketFileStamp(string PhysicalPath,ulong Volume,ulong IdLow,ulong IdHigh,long Creation,long Modified,long Changed,long Bytes,string Header);
internal sealed record MarketGenerationStamp(MarketFileStamp Database,MarketFileStamp? Wal);
internal sealed record MarketGenerationReceipt(int Schema,DateTimeOffset VerifiedAt,string Sha256,MarketCacheHealth Health,long? Latest,MarketGenerationStamp Stamp,bool TrustedWriteContinuation=false);
/// A previous complete validation is reusable only while the same physical SQLite files remain unchanged.
internal static class MarketVerifiedGeneration
{
private const string Suffix=".verified-generation.json";
private static readonly JsonSerializerOptions Json=new(){WriteIndented=true};
internal static bool TryCapture(string path,out MarketGenerationStamp stamp)
{
stamp=null!;
try
{
if(!OperatingSystem.IsWindows()||!TryFile(path,true,out var database))return false;
MarketFileStamp? wal=null;
if(File.Exists(path+"-wal"))
{
if(!TryFile(path+"-wal",false,out var candidate))return false;
if(candidate.Bytes>0)wal=candidate;
}
stamp=new(database,wal);return true;
}
catch{return false;}
}
internal static bool TryRead(string path,out MarketGenerationReceipt receipt)
{
receipt=null!;
try
{
var proof=path+Suffix;if(!File.Exists(proof)||new FileInfo(proof).Length>65536)return false;
var value=JsonSerializer.Deserialize(File.ReadAllText(proof),Json);
if(value is null||value.Schema!=1||value.Health.Stations<=0||value.Health.Quotes<=0||value.Health.Snapshots<0||value.Latest is null
||value.Sha256.Length!=64||value.Sha256.Any(c=>!Uri.IsHexDigit(c))||!TryCapture(path,out var actual)||actual!=value.Stamp)return false;
receipt=value;return true;
}
catch{return false;}
}
internal static bool Matches(string path,MarketGenerationStamp expected)=>TryCapture(path,out var actual)&&actual==expected;
// The caller must have completed integrity/provenance validation, reopened
// row-count/time verification and byte-identical SHA validation. This seals
// that evidence to the final physical file after its atomic move.
internal static MarketGenerationReceipt Record(string path,MarketCacheHealth health,long? latest,string sha256,bool continuation=false,MarketGenerationStamp? expected=null)
=>RecordCore(path,health,latest,sha256,continuation,expected);
// A new anchor is a fresh SHA under exclusive write-denying file handles,
// tied to the exact stamp that survived a complete integrity/count check.
internal static MarketGenerationReceipt RecordFresh(string path,MarketCacheHealth health,long? latest,MarketGenerationStamp expected)
=>RecordCore(path,health,latest,null,false,expected);
private static MarketGenerationReceipt RecordCore(string path,MarketCacheHealth health,long? latest,string? sha256,bool continuation,MarketGenerationStamp? expected)
{
if(health.Stations<=0||health.Quotes<=0||health.Snapshots<0||latest is null||sha256 is not null&&(sha256.Length!=64||sha256.Any(c=>!Uri.IsHexDigit(c))))
throw new InvalidDataException("完整商品缓存验证结果无效,不能创建启动凭据。");
if((continuation||sha256 is null)&&expected is null)throw new InvalidDataException("商品缓存验证缺少已核对的文件身份。");
// Close the gap between checking a checkpoint and publishing its receipt.
// Existing writable SQLite/raw handles make these locks fail; callers
// defer sealing instead of trusting a state changed by another writer.
using var databaseLock=File.OpenHandle(path,FileMode.Open,FileAccess.Read,FileShare.Read,FileOptions.SequentialScan);
using var walLock=File.OpenHandle(path+"-wal",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.Read);
if(RandomAccess.GetLength(walLock)!=0)throw new IOException("商品缓存仍有WAL内容,不能创建启动凭据。");
if(!TryCapture(path,out var stamp)||stamp.Wal is not null)throw new IOException("商品缓存仍有WAL内容或文件身份不可验证,不能创建启动凭据。");
if(expected is not null&&stamp!=expected)throw new IOException("商品缓存已偏离完成checkpoint时的文件身份,不能续接验证凭据。");
if(sha256 is null)
{
using var bytes=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read,1024*1024,FileOptions.SequentialScan);
sha256=Convert.ToHexStringLower(SHA256.HashData(bytes));
if(!Matches(path,stamp))throw new IOException("商品缓存在计算完整验证SHA时发生变化。");
}
var receipt=new MarketGenerationReceipt(1,DateTimeOffset.UtcNow,sha256.ToLowerInvariant(),health,latest,stamp,continuation);
var temporary=path+Suffix+"."+Guid.NewGuid().ToString("N")+".tmp";
try
{
using(var stream=new FileStream(temporary,FileMode.CreateNew,FileAccess.Write,FileShare.Read,4096,FileOptions.WriteThrough))
{JsonSerializer.Serialize(stream,receipt,Json);stream.Flush(true);}
if(!Matches(path,stamp))throw new IOException("商品缓存在保存验证凭据时发生变化。");
File.Move(temporary,path+Suffix,true);
}
finally{if(File.Exists(temporary))File.Delete(temporary);}
return receipt;
}
private static bool TryFile(string path,bool database,out MarketFileStamp stamp)
{
stamp=null!;
using var handle=File.OpenHandle(path,FileMode.Open,FileAccess.Read,FileShare.ReadWrite|FileShare.Delete);
if(!GetFileInformationByHandleEx(handle,0,out BasicInfo before,40)||!GetFileInformationByHandleEx(handle,18,out IdInfo id,24)
||!GetFileSizeEx(handle,out var bytes)||bytes<0)return false;
var count=database?100:(int)Math.Min(32,bytes);var header=new byte[count];
if(RandomAccess.Read(handle,header,0)!=count)return false;
if(database)
{
if(bytes<512||!header.AsSpan(0,16).SequenceEqual("SQLite format 3\0"u8))return false;
var pageSize=BinaryPrimitives.ReadUInt16BigEndian(header.AsSpan(16,2));var size=pageSize==1?65536:pageSize;
if(size<512||size>65536||(size&(size-1))!=0||bytes%size!=0||BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(28,4))!=bytes/size)return false;
}
var physical=new StringBuilder(4096);var length=GetFinalPathNameByHandle(handle,physical,4096,0);
if(length==0||length>=4096||!GetFileInformationByHandleEx(handle,0,out BasicInfo after,40)
||before.Creation!=after.Creation||before.Write!=after.Write||before.Change!=after.Change||before.Attributes!=after.Attributes
||!GetFileSizeEx(handle,out var endBytes)||endBytes!=bytes)return false;
stamp=new(physical.ToString(),id.Volume,id.Low,id.High,before.Creation,before.Write,before.Change,bytes,Convert.ToHexStringLower(SHA256.HashData(header)));return true;
}
[StructLayout(LayoutKind.Sequential)]private readonly record struct BasicInfo(long Creation,long Access,long Write,long Change,uint Attributes);
[StructLayout(LayoutKind.Sequential)]private struct IdInfo{public ulong Volume,Low,High;}
[DllImport("kernel32.dll",SetLastError=true)]private static extern bool GetFileInformationByHandleEx(SafeFileHandle handle,int infoClass,out BasicInfo info,uint size);
[DllImport("kernel32.dll",SetLastError=true)]private static extern bool GetFileInformationByHandleEx(SafeFileHandle handle,int infoClass,out IdInfo info,uint size);
[DllImport("kernel32.dll",SetLastError=true)]private static extern bool GetFileSizeEx(SafeFileHandle handle,out long size);
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]private static extern uint GetFinalPathNameByHandle(SafeFileHandle handle,StringBuilder path,uint capacity,uint flags);
}