Files
linuxdistro-roguelite/Assets/Scripts/Meta/SaveService.cs
T

739 lines
27 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using KernelPanic.Data;
using KernelPanic.Core;
using KernelPanic.Run;
using UnityEngine;
namespace KernelPanic.Meta
{
/// <summary>
/// Provides save and load contracts for persistent meta progression.
/// </summary>
public sealed class SaveService
{
private const string SaveFileName = "kernel-panic-save.json";
public const int CurrentSchemaVersion = 5;
private static readonly object FileLock = new();
public string SavePath { get; }
public string BackupPath => SavePath + ".bak";
public SaveService() : this(ResolveDefaultSavePath()) { }
/// <summary>Allows tools and tests to use isolated saves without touching player progression.</summary>
public SaveService(string savePath)
{
if (string.IsNullOrWhiteSpace(savePath) || !Path.IsPathFullyQualified(savePath))
{
throw new ArgumentException("Save path must be an absolute file path.", nameof(savePath));
}
SavePath = Path.GetFullPath(savePath);
}
public void Save(SaveData data)
{
lock (FileLock)
{
// Check even when the caller did not Load first. An older build must never
// overwrite a newer save, nor replace unrecoverable data with fresh progression.
ReadResult primary = ReadFile(SavePath, out _, out string primaryProblem);
ReadResult backup = ReadFile(BackupPath, out _, out string backupProblem);
RejectFutureVersion(primary, primaryProblem);
RejectFutureVersion(backup, backupProblem);
if ((primary == ReadResult.Invalid || backup == ReadResult.Invalid)
&& primary != ReadResult.Valid && backup != ReadResult.Valid)
{
throw UnrecoverableSave(primaryProblem, backupProblem);
}
data ??= SaveData.CreateDefault();
data.EnsureLists();
string payload = JsonUtility.ToJson(data, true);
string json = JsonUtility.ToJson(new SaveFile
{
schemaVersion = CurrentSchemaVersion,
payload = payload,
checksum = Checksum(payload)
}, true);
Directory.CreateDirectory(Path.GetDirectoryName(SavePath));
string temporaryPath = SavePath + ".tmp." + Guid.NewGuid().ToString("N");
try
{
// The temporary file lives beside the destination, so replacement stays
// on the same volume. Flush the complete snapshot before committing it.
byte[] bytes = new UTF8Encoding(false).GetBytes(json);
using (FileStream stream = new(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
stream.Write(bytes, 0, bytes.Length);
stream.Flush(true);
}
if (primary == ReadResult.Missing)
{
File.Move(temporaryPath, SavePath);
}
else
{
// A corrupt primary must not displace the known-good backup we just
// recovered. File.Replace atomically commits the completed snapshot.
File.Replace(temporaryPath, SavePath, primary == ReadResult.Valid ? BackupPath : null);
}
}
finally
{
try
{
if (File.Exists(temporaryPath))
{
File.Delete(temporaryPath);
}
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
{
// Preserve the original write/commit failure if cleanup also fails.
// Leftover temporary files are never considered committed saves.
Debug.LogWarning($"Temporary save file could not be removed: {ex.Message}");
}
}
}
}
public SaveData Load()
{
lock (FileLock)
{
ReadResult primary = ReadFile(SavePath, out SaveData data, out string primaryProblem);
RejectFutureVersion(primary, primaryProblem);
if (primary == ReadResult.Valid)
{
data.EnsureLists();
return data;
}
ReadResult backup = ReadFile(BackupPath, out data, out string backupProblem);
RejectFutureVersion(backup, backupProblem);
if (backup == ReadResult.Valid)
{
data.EnsureLists();
Debug.LogWarning("Recovered progression from the backup save. The primary save will be repaired on the next successful save.");
return data;
}
if (primary == ReadResult.Missing && backup == ReadResult.Missing)
{
return SaveData.CreateDefault();
}
throw UnrecoverableSave(primaryProblem, backupProblem);
}
}
private static ReadResult ReadFile(string path, out SaveData data, out string problem)
{
data = null;
problem = null;
if (!File.Exists(path))
{
return ReadResult.Missing;
}
// Permission and device errors propagate; they are not evidence of corrupt data.
string json = File.ReadAllText(path);
try
{
if (string.IsNullOrWhiteSpace(json) || !json.TrimStart().StartsWith("{") || !json.TrimEnd().EndsWith("}"))
{
throw new InvalidDataException("The save is empty or incomplete.");
}
SaveFile file = JsonUtility.FromJson<SaveFile>(json);
if (file == null || file.schemaVersion < 0)
{
throw new InvalidDataException("The save header is invalid.");
}
if (file.schemaVersion > CurrentSchemaVersion)
{
problem = $"Save '{path}' uses schema {file.schemaVersion}; this build supports up to {CurrentSchemaVersion}. Open it with a newer game build. No files were changed.";
return ReadResult.FutureVersion;
}
if (file.schemaVersion == 0)
{
// Version 0 is the original unversioned SaveData JSON. Actual legacy
// saves always wrote ownership lists; reject arbitrary or empty objects.
LegacySaveMarker marker = JsonUtility.FromJson<LegacySaveMarker>(json);
if (marker == null || (marker.ownedUnits == null && marker.ownedUnitIds == null
&& marker.ownedPackages == null && marker.ownedPackageIds == null))
{
throw new InvalidDataException("The file is not a recognized legacy save.");
}
data = JsonUtility.FromJson<SaveData>(json);
}
else
{
if (string.IsNullOrWhiteSpace(file.payload) || string.IsNullOrEmpty(file.checksum)
|| !string.Equals(Checksum(file.payload), file.checksum, StringComparison.Ordinal))
{
throw new InvalidDataException("The save integrity check failed.");
}
data = JsonUtility.FromJson<SaveData>(file.payload);
}
if (data == null)
{
throw new InvalidDataException("The save contains no progression.");
}
// Existing EnsureLists migrations (ownership, currencies, merge balances)
// run only on the snapshot selected by Load, preserving duplicate refunds.
return ReadResult.Valid;
}
catch (Exception ex) when (ex is ArgumentException || ex is InvalidDataException)
{
problem = $"{path}: {ex.Message}";
return ReadResult.Invalid;
}
}
private static void RejectFutureVersion(ReadResult result, string problem)
{
if (result == ReadResult.FutureVersion)
{
throw new InvalidDataException(problem);
}
}
private static InvalidDataException UnrecoverableSave(string primaryProblem, string backupProblem)
{
return new InvalidDataException($"Progression could not be loaded from the save or its backup. Files were left unchanged; restore a known-good save and retry. {primaryProblem} {backupProblem}");
}
private static string Checksum(string payload)
{
using SHA256 sha = SHA256.Create();
return Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(payload)));
}
private static string ResolveDefaultSavePath()
{
#if UNITY_EDITOR || DEVELOPMENT_BUILD
string[] arguments = Environment.GetCommandLineArgs();
for (int i = 0; i < arguments.Length; i++)
{
if (arguments[i] == "--kernel-panic-save-path")
{
if (i + 1 >= arguments.Length || !Path.IsPathFullyQualified(arguments[i + 1]))
{
throw new ArgumentException("--kernel-panic-save-path requires an absolute file path.");
}
return arguments[i + 1];
}
}
#endif
return Path.Combine(Application.persistentDataPath, SaveFileName);
}
private enum ReadResult { Missing, Valid, Invalid, FutureVersion }
[Serializable]
private sealed class SaveFile
{
public int schemaVersion;
public string payload;
public string checksum;
}
[Serializable]
private sealed class LegacySaveMarker
{
public OwnedUnitSaveEntry[] ownedUnits;
public string[] ownedUnitIds;
public OwnedPackageSaveEntry[] ownedPackages;
public string[] ownedPackageIds;
}
}
/// <summary>
/// Stores persistent progression data for serialization.
/// </summary>
[Serializable]
public sealed class SaveData
{
public bool starterChosen;
// Opt-in at the first starter transaction. Missing fields leave existing profiles alone.
public bool tutorialRequired;
public int tutorialLesson;
public string tutorialDistroId;
public bool tutorialRewardClaimed;
public RunCheckpoint tutorialCheckpoint;
public int entropyBalance;
public int rootCredits = GachaService.TestRootCreditsBalance;
public int commitsBalance;
public int bandwidthBalance;
// Legacy conflated balance. Older builds used this for both Commits and Bandwidth.
// Migration preserves it as Bandwidth and starts Commits at 0 because the source is ambiguous.
public int standardPullCurrency;
// Legacy pull-token field kept only so older saves deserialize cleanly.
public int limitedPullCurrency;
public int cacheBalance;
// Legacy per-pull package-dupe pool. Package dupes now auto-scrap directly to Cache.
public int packageMerges;
// Legacy global balance kept only so older saves deserialize cleanly.
// New duplicate-pull merges live on OwnedUnitSaveEntry.merges.
public int merges;
public List<OwnedUnitSaveEntry> ownedUnits = new();
public List<OwnedPackageSaveEntry> ownedPackages = new();
public List<string> ownedPackageIds = new();
public List<PackageLoadoutSaveEntry> packageLoadouts = new();
public List<string> ownedUnitIds = new();
public List<string> bannerPoolIds = new();
public GachaBannerState beginnerBannerState = new(GachaService.BeginnerBannerId);
public GachaBannerState standardBannerState = new(GachaService.StandardBannerId);
public LastRunLoadoutSaveEntry lastRunLoadout = new();
public List<RunBuildDraftSaveEntry> runBuildDrafts = new();
public string lastSetupDistroId;
public RunCheckpoint activeRun;
public List<RunHistoryEntry> recentRuns = new();
public string lastRunDistroId;
public List<DistroBestWaveSaveEntry> distroBestWaves = new();
// Populated by NormalizeOwnedPackages when a save contains more than one instance of the
// same package id (packages are unique-per-type). Not serialized: the owner (bootstrap code
// with access to PackageDatabase) consumes this once per load to grant Cache for the extras,
// then clears it. See MainMenuController.LoadMetaState.
[NonSerialized]
public List<CollapsedPackageDuplicate> CollapsedPackageDuplicates = new();
public static SaveData CreateDefault()
{
return new SaveData();
}
public void EnsureLists()
{
if (tutorialCheckpoint != null && string.IsNullOrEmpty(tutorialCheckpoint.runId)) tutorialCheckpoint = null;
// JsonUtility materializes null inline serializable objects as empty instances.
// Preserve malformed/nonempty checkpoints for an explicit recovery error, but
// recognize the empty representation emitted when a checkpoint is consumed.
if (activeRun != null && string.IsNullOrEmpty(activeRun.runId) && string.IsNullOrEmpty(activeRun.distroId)
&& string.IsNullOrEmpty(activeRun.savedUtc) && activeRun.wave == 0)
activeRun = null;
ownedUnits ??= new List<OwnedUnitSaveEntry>();
ownedPackages ??= new List<OwnedPackageSaveEntry>();
ownedPackageIds ??= new List<string>();
packageLoadouts ??= new List<PackageLoadoutSaveEntry>();
ownedUnitIds ??= new List<string>();
bannerPoolIds ??= new List<string>();
distroBestWaves ??= new List<DistroBestWaveSaveEntry>();
beginnerBannerState ??= new GachaBannerState(GachaService.BeginnerBannerId);
beginnerBannerState.bannerId = GachaService.BeginnerBannerId;
beginnerBannerState.EnsureLists();
standardBannerState ??= new GachaBannerState(GachaService.StandardBannerId);
standardBannerState.bannerId = GachaService.StandardBannerId;
standardBannerState.EnsureLists();
lastRunLoadout ??= new LastRunLoadoutSaveEntry();
lastRunLoadout.EnsureLists();
runBuildDrafts ??= new List<RunBuildDraftSaveEntry>();
foreach (RunBuildDraftSaveEntry draft in runBuildDrafts) draft?.EnsureLists();
recentRuns ??= new List<RunHistoryEntry>();
RunHistory.Normalize(recentRuns);
if (string.IsNullOrWhiteSpace(lastRunDistroId) && !string.IsNullOrWhiteSpace(lastRunLoadout.distroId))
{
lastRunDistroId = lastRunLoadout.distroId;
}
MigrateLegacyConflatedCurrency();
entropyBalance = Math.Max(0, entropyBalance);
rootCredits = Math.Max(0, rootCredits);
commitsBalance = Math.Max(0, commitsBalance);
bandwidthBalance = Math.Max(0, bandwidthBalance);
merges = Math.Max(0, merges);
packageMerges = Math.Max(0, packageMerges);
cacheBalance = Math.Max(0, cacheBalance);
MigrateLegacyOwnedUnitIds();
MigrateLegacyOwnedPackageIds();
NormalizeOwnedUnits();
NormalizeOwnedPackages();
NormalizePackageLoadouts();
NormalizeDistroBestWaves();
MigrateLegacyGlobalMerges();
}
private void MigrateLegacyConflatedCurrency()
{
if (standardPullCurrency <= 0)
{
return;
}
if (bandwidthBalance <= 0)
{
bandwidthBalance = Math.Max(0, standardPullCurrency);
Debug.Log("Migrated legacy standardPullCurrency to Bandwidth. Commits defaulted to 0 because the old field conflated pull tokens and upgrade currency.");
}
standardPullCurrency = 0;
limitedPullCurrency = 0;
}
public OwnedUnitSaveEntry FindOwnedUnit(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
return null;
}
EnsureLists();
for (int i = 0; i < ownedUnits.Count; i++)
{
OwnedUnitSaveEntry entry = ownedUnits[i];
if (entry != null && string.Equals(entry.id, id, StringComparison.OrdinalIgnoreCase))
{
return entry;
}
}
return null;
}
public bool IsUnitOwned(string id)
{
return FindOwnedUnit(id) != null;
}
public OwnedUnitSaveEntry AddOwnedUnit(string id, int version)
{
if (string.IsNullOrWhiteSpace(id))
{
return null;
}
EnsureLists();
OwnedUnitSaveEntry existing = FindOwnedUnit(id);
if (existing != null)
{
existing.version = Math.Max(1, Math.Min(GachaTuning.MaxVersion, existing.version));
return existing;
}
OwnedUnitSaveEntry entry = new()
{
id = id,
version = Math.Max(1, Math.Min(GachaTuning.MaxVersion, version))
};
ownedUnits.Add(entry);
return entry;
}
private void MigrateLegacyOwnedUnitIds()
{
for (int i = 0; i < ownedUnitIds.Count; i++)
{
string id = ownedUnitIds[i];
if (string.IsNullOrWhiteSpace(id) || HasOwnedUnitEntry(id))
{
continue;
}
ownedUnits.Add(new OwnedUnitSaveEntry
{
id = id,
version = 1
});
}
}
private void NormalizeOwnedUnits()
{
HashSet<string> seen = new(StringComparer.OrdinalIgnoreCase);
for (int i = ownedUnits.Count - 1; i >= 0; i--)
{
OwnedUnitSaveEntry entry = ownedUnits[i];
if (entry == null || string.IsNullOrWhiteSpace(entry.id) || !seen.Add(entry.id))
{
ownedUnits.RemoveAt(i);
continue;
}
entry.version = Math.Max(1, Math.Min(GachaTuning.MaxVersion, entry.version));
entry.merges = Math.Max(0, entry.merges);
}
}
private void NormalizeOwnedPackages()
{
CollapsedPackageDuplicates.Clear();
Dictionary<string, OwnedPackageSaveEntry> highestById = new(StringComparer.OrdinalIgnoreCase);
Dictionary<string, int> extraCountById = new(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < ownedPackages.Count; i++)
{
OwnedPackageSaveEntry entry = ownedPackages[i];
if (entry == null || string.IsNullOrWhiteSpace(entry.id))
{
continue;
}
entry.upgradeLevel = Math.Max(0, Math.Min(PackageTuning.MaxPackageLevel, entry.upgradeLevel));
if (highestById.TryGetValue(entry.id, out OwnedPackageSaveEntry existing))
{
extraCountById[entry.id] = extraCountById.TryGetValue(entry.id, out int count) ? count + 1 : 1;
if (entry.upgradeLevel > existing.upgradeLevel)
{
highestById[entry.id] = entry;
}
}
else
{
highestById[entry.id] = entry;
}
}
ownedPackages = new List<OwnedPackageSaveEntry>(highestById.Values);
foreach (KeyValuePair<string, int> extra in extraCountById)
{
CollapsedPackageDuplicates.Add(new CollapsedPackageDuplicate(extra.Key, extra.Value));
}
ownedPackageIds.Clear();
for (int i = 0; i < ownedPackages.Count; i++)
{
ownedPackageIds.Add(ownedPackages[i].id);
}
}
public int GetBestWave(string distroId)
{
if (string.IsNullOrWhiteSpace(distroId))
{
return 0;
}
EnsureLists();
for (int i = 0; i < distroBestWaves.Count; i++)
{
DistroBestWaveSaveEntry entry = distroBestWaves[i];
if (entry != null && string.Equals(entry.distroId, distroId, StringComparison.OrdinalIgnoreCase))
{
return Math.Max(0, entry.bestWave);
}
}
return 0;
}
public void RecordRunStats(string distroId, int waveReached)
{
if (string.IsNullOrWhiteSpace(distroId))
{
return;
}
EnsureLists();
lastRunDistroId = distroId;
lastRunLoadout ??= new LastRunLoadoutSaveEntry();
lastRunLoadout.distroId = distroId;
int safeWave = Math.Max(0, waveReached);
for (int i = 0; i < distroBestWaves.Count; i++)
{
DistroBestWaveSaveEntry entry = distroBestWaves[i];
if (entry != null && string.Equals(entry.distroId, distroId, StringComparison.OrdinalIgnoreCase))
{
entry.bestWave = Math.Max(entry.bestWave, safeWave);
return;
}
}
distroBestWaves.Add(new DistroBestWaveSaveEntry { distroId = distroId, bestWave = safeWave });
}
private void NormalizeDistroBestWaves()
{
HashSet<string> seen = new(StringComparer.OrdinalIgnoreCase);
for (int i = distroBestWaves.Count - 1; i >= 0; i--)
{
DistroBestWaveSaveEntry entry = distroBestWaves[i];
if (entry == null || string.IsNullOrWhiteSpace(entry.distroId) || !seen.Add(entry.distroId))
{
distroBestWaves.RemoveAt(i);
continue;
}
entry.bestWave = Math.Max(0, entry.bestWave);
}
}
private void MigrateLegacyOwnedPackageIds()
{
for (int i = 0; i < ownedPackageIds.Count; i++)
{
string id = ownedPackageIds[i];
if (string.IsNullOrWhiteSpace(id) || HasOwnedPackageEntry(id))
{
continue;
}
ownedPackages.Add(new OwnedPackageSaveEntry { id = id, upgradeLevel = 0 });
}
}
private bool HasOwnedPackageEntry(string id)
{
for (int i = 0; i < ownedPackages.Count; i++)
{
OwnedPackageSaveEntry entry = ownedPackages[i];
if (entry != null && string.Equals(entry.id, id, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private void NormalizePackageLoadouts()
{
HashSet<string> seenDistros = new(StringComparer.OrdinalIgnoreCase);
for (int i = packageLoadouts.Count - 1; i >= 0; i--)
{
PackageLoadoutSaveEntry entry = packageLoadouts[i];
if (entry == null || string.IsNullOrWhiteSpace(entry.distroId) || !seenDistros.Add(entry.distroId))
{
packageLoadouts.RemoveAt(i);
continue;
}
entry.EnsureLists();
}
}
private void MigrateLegacyGlobalMerges()
{
if (merges <= 0 || ownedUnits.Count == 0)
{
return;
}
bool hasSpecificMerges = false;
for (int i = 0; i < ownedUnits.Count; i++)
{
if (ownedUnits[i] != null && ownedUnits[i].merges > 0)
{
hasSpecificMerges = true;
break;
}
}
if (!hasSpecificMerges)
{
ownedUnits[0].merges = Math.Max(0, ownedUnits[0].merges) + merges;
merges = 0;
}
}
private bool HasOwnedUnitEntry(string id)
{
for (int i = 0; i < ownedUnits.Count; i++)
{
OwnedUnitSaveEntry entry = ownedUnits[i];
if (entry != null && string.Equals(entry.id, id, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
[Serializable]
public sealed class OwnedUnitSaveEntry
{
public string id;
public int version = 1;
public int merges;
}
[Serializable]
public sealed class OwnedPackageSaveEntry
{
public string id;
public int upgradeLevel;
}
public sealed class CollapsedPackageDuplicate
{
public CollapsedPackageDuplicate(string id, int extraCount)
{
Id = id;
ExtraCount = extraCount;
}
public string Id { get; }
public int ExtraCount { get; }
}
[Serializable]
public sealed class LastRunLoadoutSaveEntry
{
public string distroId;
public List<string> cardIds = new();
public List<Language> languages = new();
public List<RunBuildPackageSaveEntry> packages = new();
public int distroVersion = 1;
public bool hasRunSeed;
public int runSeed;
public void EnsureLists()
{
cardIds ??= new List<string>();
languages ??= new List<Language>();
packages ??= new List<RunBuildPackageSaveEntry>();
}
}
[Serializable]
public sealed class DistroBestWaveSaveEntry
{
public string distroId;
public int bestWave;
}
[Serializable]
public sealed class PackageLoadoutSaveEntry
{
public string distroId;
public List<PackageLoadoutSlotSaveEntry> slots = new();
public void EnsureLists()
{
slots ??= new List<PackageLoadoutSlotSaveEntry>();
HashSet<PackageSlot> seen = new();
for (int i = slots.Count - 1; i >= 0; i--)
{
PackageLoadoutSlotSaveEntry slot = slots[i];
if (slot == null || string.IsNullOrWhiteSpace(slot.packageId) || !seen.Add(slot.slot))
{
slots.RemoveAt(i);
}
}
}
}
[Serializable]
public sealed class PackageLoadoutSlotSaveEntry
{
public PackageSlot slot;
public string packageId;
}
}