using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace XFEWarframe.Core.Data;
/// Single-writer durable snapshot store. A mutation commits all account changes together.
public sealed class StateStore : IAsyncDisposable
{
private readonly SemaphoreSlim gate = new(1, 1);
private readonly FileStream lease;
private readonly string path;
private JObject state;
private bool compacted;
private readonly MissionReceiptArchive receipts;
public StateStore(string directory)
{
Directory.CreateDirectory(directory);
path = Path.Combine(directory, "state.json");
receipts = new(directory);
lease = new FileStream(Path.Combine(directory, "server.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
try
{
state = File.Exists(path) ? Wire.ReadObject(File.ReadAllText(path)) : CreateEmpty();
if (state.Value("schema") != 1 || state["accounts"] is not JObject || state["guilds"] is not JObject)
throw new InvalidDataException("Unsupported or damaged state.json. Restore a backup; the file has not been modified.");
compacted = MissionReceipts.CompactLegacy(state);
}
catch { lease.Dispose(); throw; }
}
private static JObject CreateEmpty() => new()
{
["schema"] = 1, ["revision"] = 0, ["accounts"] = new JObject(), ["guilds"] = new JObject(),
["sessions"] = new JObject(), ["friendships"] = new JArray(), ["config"] = new JObject(), ["worldState"] = new JObject()
};
public async Task Read(Func read)
{
await gate.WaitAsync();
try { return read((JObject)state.DeepClone()); }
finally { gate.Release(); }
}
// For internal immutable projections only. Never mutate or return references into state.
// Chat presence checks must not clone every player's inventory on every IRC command.
internal async Task Project(Func projection)
{
await gate.WaitAsync();
try { return projection(state); }
finally { gate.Release(); }
}
public async Task Update(Func update)
{
await gate.WaitAsync();
try
{
var candidate = (JObject)state.DeepClone();
var result = update(candidate); // Throws before commit: no partial currencies, items or trades.
if (!compacted && JToken.DeepEquals(candidate, state)) return result;
candidate["revision"] = state.Value("revision") + 1;
await Commit(candidate);
state = candidate;
compacted = false;
return result;
}
finally { gate.Release(); }
}
private async Task Commit(JObject value)
{
// Persist immutable payloads before committing their references. A crash
// here can leave an orphan, never a state file pointing at unwritten data.
var archived = receipts.Persist(value);
var temp = path + ".tmp";
// Flush once at the transaction boundary. WriteThrough on every serializer
// buffer caused many synchronous device flushes; the old file remains
// authoritative until the complete temp file has passed Flush(true).
await using (var stream = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None, 65536, FileOptions.SequentialScan))
{
await using var writer = new StreamWriter(stream, bufferSize: 65536, leaveOpen: true);
using var json = new JsonTextWriter(writer) { CloseOutput = false, Formatting = Formatting.None };
value.WriteTo(json);
await json.FlushAsync();
await writer.FlushAsync();
stream.Flush(true);
}
if (File.Exists(path)) File.Replace(temp, path, path + ".bak");
else File.Move(temp, path);
if (archived)
{
try { receipts.Prune(value, state); }
catch (IOException) { /* Cleanup can wait; the transaction is already durable. */ }
catch (UnauthorizedAccessException) { /* A locked old blob must not fail a committed reward. */ }
}
}
public ApiResponse ReplayMissionReceipt(JObject receipt) => MissionReceipts.Replay(receipt, receipts.Read);
// Kept independently of state.json.bak, which the next normal save replaces.
public string BackupInventory(string accountId, JObject inventory)
{
if (accountId.Length != 24 || !accountId.All(Uri.IsHexDigit)) throw new InvalidDataException("Invalid account backup identifier.");
var directory = Path.Combine(Path.GetDirectoryName(path)!, "inventory-backups");
Directory.CreateDirectory(directory);
var name = $"{accountId}-{DateTime.UtcNow:yyyyMMdd-HHmmss}-{Guid.NewGuid():N}.json";
var destination = Path.Combine(directory, name);
using (var stream = new FileStream(destination + ".tmp", FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536, FileOptions.WriteThrough))
{
using var writer = new StreamWriter(stream, leaveOpen: true);
writer.Write(inventory.ToString(Formatting.Indented)); writer.Flush(); stream.Flush(true);
}
File.Move(destination + ".tmp", destination);
return name;
}
public async ValueTask DisposeAsync()
{
await gate.WaitAsync();
try { await lease.DisposeAsync(); }
finally { gate.Release(); }
}
}