-
Notifications
You must be signed in to change notification settings - Fork 42
fix: write RFL_DB.dat and rksys.dat atomically #310
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| using Testably.Abstractions.Testing; | ||
| using WheelWizard.Helpers; | ||
|
|
||
| namespace WheelWizard.Test.Helpers; | ||
|
|
||
| public class AtomicFileHelperTests | ||
| { | ||
| private const string FilePath = "/save/rksys.dat"; | ||
|
|
||
| [Fact] | ||
| public void WriteAllBytesAtomic_CreatesFileAndDirectory_WhenFileDoesNotExist() | ||
| { | ||
| var fileSystem = new MockFileSystem(); | ||
| var contents = new byte[] { 1, 2, 3, 4 }; | ||
|
|
||
| var result = fileSystem.WriteAllBytesAtomic(FilePath, contents); | ||
|
|
||
| Assert.True(result.IsSuccess); | ||
| Assert.Equal(contents, fileSystem.File.ReadAllBytes(FilePath)); | ||
| Assert.False(fileSystem.File.Exists(FilePath + AtomicFileHelper.TempExtension)); | ||
| Assert.False(fileSystem.File.Exists(FilePath + AtomicFileHelper.BackupExtension)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WriteAllBytesAtomic_ReplacesFileAndKeepsBackup_WhenFileAlreadyExists() | ||
| { | ||
| var fileSystem = new MockFileSystem(); | ||
| var oldContents = new byte[] { 9, 9, 9 }; | ||
| var newContents = new byte[] { 1, 2, 3, 4 }; | ||
| fileSystem.Directory.CreateDirectory("/save"); | ||
| fileSystem.File.WriteAllBytes(FilePath, oldContents); | ||
|
|
||
| var result = fileSystem.WriteAllBytesAtomic(FilePath, newContents); | ||
|
|
||
| Assert.True(result.IsSuccess); | ||
| Assert.Equal(newContents, fileSystem.File.ReadAllBytes(FilePath)); | ||
| Assert.Equal(oldContents, fileSystem.File.ReadAllBytes(FilePath + AtomicFileHelper.BackupExtension)); | ||
| Assert.False(fileSystem.File.Exists(FilePath + AtomicFileHelper.TempExtension)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WriteAllBytesAtomic_LeavesOriginalIntact_WhenWriteFails() | ||
| { | ||
| var fileSystem = new MockFileSystem(); | ||
| var oldContents = new byte[] { 9, 9, 9 }; | ||
| fileSystem.Directory.CreateDirectory("/save"); | ||
| fileSystem.File.WriteAllBytes(FilePath, oldContents); | ||
|
|
||
| // A directory on the temp path makes writing the temp file fail before anything is swapped in. | ||
| fileSystem.Directory.CreateDirectory(FilePath + AtomicFileHelper.TempExtension); | ||
|
|
||
| var result = fileSystem.WriteAllBytesAtomic(FilePath, [1, 2, 3, 4], "Failed to save rksys.dat."); | ||
|
|
||
| Assert.True(result.IsFailure); | ||
| Assert.Equal("Failed to save rksys.dat.", result.Error.Message); | ||
| Assert.Equal(oldContents, fileSystem.File.ReadAllBytes(FilePath)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| using System.IO.Abstractions; | ||
|
|
||
| namespace WheelWizard.Helpers; | ||
|
|
||
| /// <summary> | ||
| /// Helpers for writing files that must never end up half written (Wii save files for example). | ||
| /// The new contents are written to a temporary file first, flushed to disk, and only then swapped | ||
| /// in place, keeping a backup of the previous file. | ||
| /// </summary> | ||
| public static class AtomicFileHelper | ||
| { | ||
| /// <summary> | ||
| /// The extension appended to the file that is being written before it is swapped in. | ||
| /// </summary> | ||
| public const string TempExtension = ".tmp"; | ||
|
|
||
| /// <summary> | ||
| /// The extension appended to the backup of the previous version of the file. | ||
| /// </summary> | ||
| public const string BackupExtension = ".bak"; | ||
|
|
||
| /// <summary> | ||
| /// Writes the given bytes to the given path without ever leaving the destination truncated. | ||
| /// The data is written to a temporary file, flushed to disk, and then atomically swapped in. | ||
| /// When the destination already exists, the previous version is kept as a <c>.bak</c> file. | ||
| /// </summary> | ||
| /// <param name="fileSystem">The file system to write with.</param> | ||
| /// <param name="filePath">The final path of the file.</param> | ||
| /// <param name="contents">The complete contents of the file.</param> | ||
| /// <param name="errorMessage">The error message to return when writing fails.</param> | ||
| public static OperationResult WriteAllBytesAtomic( | ||
| this IFileSystem fileSystem, | ||
| string filePath, | ||
| byte[] contents, | ||
| string? errorMessage = null | ||
| ) | ||
| { | ||
| return TryCatch( | ||
| () => | ||
| { | ||
| var directory = fileSystem.Path.GetDirectoryName(filePath); | ||
| if (!string.IsNullOrEmpty(directory) && !fileSystem.Directory.Exists(directory)) | ||
| fileSystem.Directory.CreateDirectory(directory); | ||
|
|
||
| var tempPath = filePath + TempExtension; | ||
| var backupPath = filePath + BackupExtension; | ||
|
|
||
| using (var stream = fileSystem.File.Create(tempPath)) | ||
| { | ||
| stream.Write(contents, 0, contents.Length); | ||
| stream.Flush(flushToDisk: true); | ||
| } | ||
|
|
||
| // File.Replace requires the destination to already exist, so for a brand new file | ||
| // there is nothing to replace (or to back up) and a plain move is already atomic. | ||
| if (!fileSystem.File.Exists(filePath)) | ||
| { | ||
| fileSystem.File.Move(tempPath, filePath); | ||
| return; | ||
| } | ||
|
|
||
| fileSystem.File.Replace(tempPath, filePath, backupPath, ignoreMetadataErrors: true); | ||
| }, | ||
| errorMessage ?? $"Failed to write file: {filePath}" | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Use a unique temporary path for each write.
Line 45 gives every write to the same destination one shared
.tmppath. If two saves overlap, the secondFile.Create(tempPath)can truncate and replace the first operation's staged bytes. The first operation can then return success afterFile.Replaceinstalls the second operation's bytes, while the second operation fails because its temporary file was consumed.Generate a unique temporary name per operation. Clean up that operation's temporary file on failure. Add a concurrent-write test that verifies each successful call writes its own payload.
Proposed change
📝 Committable suggestion
🤖 Prompt for AI Agents