LocalSaveService.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. namespace DevilLink2.Persistence
  5. {
  6. public sealed class LocalSaveService
  7. {
  8. public const string MainFile = "save.json", BackupFile = "save.json.bak", TemporaryFile = "save.json.tmp";
  9. private const string BackupTemporaryFile = "save.json.bak.tmp";
  10. private readonly ISaveStorage storage;
  11. private readonly ISaveCodec codec;
  12. public LocalSaveService(ISaveStorage storage, ISaveCodec codec = null)
  13. { this.storage = storage ?? throw new ArgumentNullException(nameof(storage)); this.codec = codec ?? new JsonSaveCodec(); }
  14. public SaveLoadResult Load()
  15. {
  16. lock (storage.SyncRoot)
  17. {
  18. EnsureSupportedFiles();
  19. bool interrupted = storage.Exists(TemporaryFile);
  20. var main = ReadCandidate(MainFile);
  21. var backup = ReadCandidate(BackupFile);
  22. PreserveTemporaryFiles();
  23. if (main != null)
  24. {
  25. if (main.NeedsRewrite) WriteCore(main.Data, false);
  26. return new SaveLoadResult(main.Data, SaveLoadSource.Primary, main.NeedsRewrite);
  27. }
  28. bool mainExisted = storage.Exists(MainFile);
  29. if (mainExisted) Preserve(MainFile, "corrupt");
  30. if (storage.Exists(BackupFile) && backup == null) Preserve(BackupFile, "corrupt");
  31. // A pending temp identifies the portable rename's interrupted replacement window.
  32. // An ordinarily missing primary (even with an orphan backup) starts with defaults.
  33. bool recover = backup != null && (mainExisted || interrupted);
  34. var data = recover ? backup.Data : new SaveData();
  35. WriteCore(data, false);
  36. return new SaveLoadResult(data, recover ? SaveLoadSource.Backup : SaveLoadSource.Defaults, true);
  37. }
  38. }
  39. public void Save(SaveData snapshot)
  40. {
  41. lock (storage.SyncRoot)
  42. { EnsureSupportedFiles(); PreserveTemporaryFiles(); WriteCore(SaveDataValidator.Normalize(snapshot), false); }
  43. }
  44. public SaveData ResetSaveData()
  45. {
  46. lock (storage.SyncRoot)
  47. {
  48. // Reset is explicit, but still cannot destroy an unknown future schema.
  49. EnsureSupportedFiles(); PreserveTemporaryFiles();
  50. var defaults = new SaveData();
  51. WriteCore(defaults, true); // The backup is also defaults; old progress cannot return via recovery.
  52. return defaults;
  53. }
  54. }
  55. private DecodedSave ReadCandidate(string name)
  56. {
  57. if (!storage.Exists(name)) return null;
  58. try { return codec.Decode(storage.Read(name)); }
  59. catch (SaveFormatException) { return null; }
  60. catch (DecoderFallbackException) { return null; }
  61. // I/O/permission problems and unsupported versions are not "corrupt data".
  62. }
  63. private void EnsureSupportedFiles()
  64. {
  65. foreach (string name in new[] { MainFile, BackupFile, TemporaryFile, BackupTemporaryFile }) ReadCandidate(name);
  66. }
  67. private void Preserve(string name, string reason)
  68. { storage.Move(name, name + "." + reason + "." + Guid.NewGuid().ToString("N")); }
  69. private void PreserveTemporaryFiles()
  70. {
  71. foreach (string name in new[] { TemporaryFile, BackupTemporaryFile })
  72. if (storage.Exists(name)) Preserve(name, "interrupted");
  73. }
  74. private void WriteVerified(string name, string json)
  75. {
  76. storage.WriteDurable(name, json);
  77. if (storage.Read(name) != json) throw new InvalidDataException("Save write verification failed: " + name);
  78. codec.Decode(json);
  79. }
  80. private void Promote(string source, string destination)
  81. {
  82. if (storage.Exists(destination))
  83. {
  84. if (storage.TryAtomicReplace(source, destination)) return;
  85. storage.Delete(destination);
  86. }
  87. storage.Move(source, destination);
  88. }
  89. private void WriteCore(SaveData data, bool resetBackup)
  90. {
  91. string json = codec.Encode(data);
  92. var previous = ReadCandidate(MainFile);
  93. string previousJson = previous == null ? null : codec.Encode(previous.Data);
  94. var backup = ReadCandidate(BackupFile);
  95. WriteVerified(TemporaryFile, json);
  96. if (storage.Exists(MainFile) && previous == null) Preserve(MainFile, "corrupt");
  97. if (storage.Exists(BackupFile) && backup == null) Preserve(BackupFile, "corrupt");
  98. if (previousJson != null || resetBackup)
  99. {
  100. WriteVerified(BackupTemporaryFile, resetBackup ? json : previousJson);
  101. // Until this finishes, the old primary is intact. The backup must commit first.
  102. Promote(BackupTemporaryFile, BackupFile);
  103. }
  104. try { Promote(TemporaryFile, MainFile); }
  105. catch
  106. {
  107. // Best effort rollback. If the device is still unavailable, the durable backup
  108. // and pending temp allow Load to recover after the interruption.
  109. if (previousJson != null && !storage.Exists(MainFile))
  110. { try { storage.WriteDurable(MainFile, previousJson); } catch (IOException) { } catch (UnauthorizedAccessException) { } }
  111. throw;
  112. }
  113. }
  114. }
  115. }