ITextFileStore.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Text;
  2. namespace RackPeek.Domain.Persistence.Yaml;
  3. public interface ITextFileStore {
  4. Task<bool> ExistsAsync(string path);
  5. Task<string> ReadAllTextAsync(string path);
  6. Task WriteAllTextAsync(string path, string contents);
  7. }
  8. public sealed class PhysicalTextFileStore : ITextFileStore {
  9. public Task<bool> ExistsAsync(string path) => Task.FromResult(File.Exists(path));
  10. public Task<string> ReadAllTextAsync(string path) => File.ReadAllTextAsync(path);
  11. /// <summary>
  12. /// Atomic and durable replacement for File.WriteAllTextAsync, which truncates
  13. /// the destination before writing and never flushes to disk — so a crash or
  14. /// power loss mid-save could leave a truncated config, and a save that had
  15. /// "succeeded" could still be lost (#337). The content is written to a
  16. /// temporary file in the same directory, flushed to disk, then moved over the
  17. /// destination — a rename, so readers only ever see the old or the new file,
  18. /// never a partial one.
  19. /// </summary>
  20. public async Task WriteAllTextAsync(string path, string contents) {
  21. var fullPath = Path.GetFullPath(path);
  22. var directory = Path.GetDirectoryName(fullPath)
  23. ?? throw new IOException($"'{path}' has no parent directory.");
  24. var tempPath = Path.Combine(
  25. directory,
  26. $"{Path.GetFileName(fullPath)}.tmp-{Guid.NewGuid():N}");
  27. try {
  28. await using (var stream = new FileStream(
  29. tempPath,
  30. FileMode.CreateNew,
  31. FileAccess.Write,
  32. FileShare.None)) {
  33. var bytes = Encoding.UTF8.GetBytes(contents);
  34. await stream.WriteAsync(bytes);
  35. // Flush through the OS cache to the disk itself, so the rename
  36. // below never publishes a file whose bytes could still vanish.
  37. stream.Flush(true);
  38. }
  39. File.Move(tempPath, fullPath, true);
  40. }
  41. catch {
  42. // Never leave temp files behind on a failed write; the destination
  43. // is untouched by construction.
  44. try {
  45. File.Delete(tempPath);
  46. }
  47. catch (IOException) {
  48. // Best effort — the stray temp file is harmless.
  49. }
  50. throw;
  51. }
  52. }
  53. }