| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- using System;
- using System.IO;
- using System.Text;
- namespace DevilLink2.Persistence
- {
- public sealed class LocalSaveService
- {
- public const string MainFile = "save.json", BackupFile = "save.json.bak", TemporaryFile = "save.json.tmp";
- private const string BackupTemporaryFile = "save.json.bak.tmp";
- private readonly ISaveStorage storage;
- private readonly ISaveCodec codec;
- public LocalSaveService(ISaveStorage storage, ISaveCodec codec = null)
- { this.storage = storage ?? throw new ArgumentNullException(nameof(storage)); this.codec = codec ?? new JsonSaveCodec(); }
- public SaveLoadResult Load()
- {
- lock (storage.SyncRoot)
- {
- EnsureSupportedFiles();
- bool interrupted = storage.Exists(TemporaryFile);
- var main = ReadCandidate(MainFile);
- var backup = ReadCandidate(BackupFile);
- PreserveTemporaryFiles();
- if (main != null)
- {
- if (main.NeedsRewrite) WriteCore(main.Data, false);
- return new SaveLoadResult(main.Data, SaveLoadSource.Primary, main.NeedsRewrite);
- }
- bool mainExisted = storage.Exists(MainFile);
- if (mainExisted) Preserve(MainFile, "corrupt");
- if (storage.Exists(BackupFile) && backup == null) Preserve(BackupFile, "corrupt");
- // A pending temp identifies the portable rename's interrupted replacement window.
- // An ordinarily missing primary (even with an orphan backup) starts with defaults.
- bool recover = backup != null && (mainExisted || interrupted);
- var data = recover ? backup.Data : new SaveData();
- WriteCore(data, false);
- return new SaveLoadResult(data, recover ? SaveLoadSource.Backup : SaveLoadSource.Defaults, true);
- }
- }
- public void Save(SaveData snapshot)
- {
- lock (storage.SyncRoot)
- { EnsureSupportedFiles(); PreserveTemporaryFiles(); WriteCore(SaveDataValidator.Normalize(snapshot), false); }
- }
- public SaveData ResetSaveData()
- {
- lock (storage.SyncRoot)
- {
- // Reset is explicit, but still cannot destroy an unknown future schema.
- EnsureSupportedFiles(); PreserveTemporaryFiles();
- var defaults = new SaveData();
- WriteCore(defaults, true); // The backup is also defaults; old progress cannot return via recovery.
- return defaults;
- }
- }
- private DecodedSave ReadCandidate(string name)
- {
- if (!storage.Exists(name)) return null;
- try { return codec.Decode(storage.Read(name)); }
- catch (SaveFormatException) { return null; }
- catch (DecoderFallbackException) { return null; }
- // I/O/permission problems and unsupported versions are not "corrupt data".
- }
- private void EnsureSupportedFiles()
- {
- foreach (string name in new[] { MainFile, BackupFile, TemporaryFile, BackupTemporaryFile }) ReadCandidate(name);
- }
- private void Preserve(string name, string reason)
- { storage.Move(name, name + "." + reason + "." + Guid.NewGuid().ToString("N")); }
- private void PreserveTemporaryFiles()
- {
- foreach (string name in new[] { TemporaryFile, BackupTemporaryFile })
- if (storage.Exists(name)) Preserve(name, "interrupted");
- }
- private void WriteVerified(string name, string json)
- {
- storage.WriteDurable(name, json);
- if (storage.Read(name) != json) throw new InvalidDataException("Save write verification failed: " + name);
- codec.Decode(json);
- }
- private void Promote(string source, string destination)
- {
- if (storage.Exists(destination))
- {
- if (storage.TryAtomicReplace(source, destination)) return;
- storage.Delete(destination);
- }
- storage.Move(source, destination);
- }
- private void WriteCore(SaveData data, bool resetBackup)
- {
- string json = codec.Encode(data);
- var previous = ReadCandidate(MainFile);
- string previousJson = previous == null ? null : codec.Encode(previous.Data);
- var backup = ReadCandidate(BackupFile);
- WriteVerified(TemporaryFile, json);
- if (storage.Exists(MainFile) && previous == null) Preserve(MainFile, "corrupt");
- if (storage.Exists(BackupFile) && backup == null) Preserve(BackupFile, "corrupt");
- if (previousJson != null || resetBackup)
- {
- WriteVerified(BackupTemporaryFile, resetBackup ? json : previousJson);
- // Until this finishes, the old primary is intact. The backup must commit first.
- Promote(BackupTemporaryFile, BackupFile);
- }
- try { Promote(TemporaryFile, MainFile); }
- catch
- {
- // Best effort rollback. If the device is still unavailable, the durable backup
- // and pending temp allow Load to recover after the interruption.
- if (previousJson != null && !storage.Exists(MainFile))
- { try { storage.WriteDurable(MainFile, previousJson); } catch (IOException) { } catch (UnauthorizedAccessException) { } }
- throw;
- }
- }
- }
- }
|