Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions Navigation.Test/JsonFilePersistenceProviderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,42 @@
Assert.AreEqual("c", string.Join(",", restored.GetForwardStack().Select(item => item.Id)));
}

[TestMethod]
public async Task ConcurrentFirstSaves_ToNewFile_BothSucceed()
{
// Two saves that both find no state file used to race on File.Move, and the loser threw
// "already exists". Loop, because the window is narrow
string directory = Path.Combine(Path.GetTempPath(), $"navigation-{Guid.NewGuid():N}");
try
{
for (int i = 0; i < 200; i++)
{
string filePath = Path.Combine(directory, $"state-{i}.json");
JsonFilePersistenceProvider<NavigationItem> provider = new(filePath);
Navigation<NavigationItem> first = new(null, provider);
first.NavigateTo(new NavigationItem("a", "A"));
Navigation<NavigationItem> second = new(null, provider);
second.NavigateTo(new NavigationItem("b", "B"));

await Task.WhenAll(
Task.Run(() => first.SaveStateAsync()),

Check warning on line 77 in Navigation.Test/JsonFilePersistenceProviderTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Navigation&issues=AaGpivsZCo9rc6GwBYxG&open=AaGpivsZCo9rc6GwBYxG&pullRequest=108

Check warning on line 77 in Navigation.Test/JsonFilePersistenceProviderTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Navigation&issues=AaGpivsZCo9rc6GwBYxH&open=AaGpivsZCo9rc6GwBYxH&pullRequest=108
Task.Run(() => second.SaveStateAsync())).ConfigureAwait(false);

Check warning on line 78 in Navigation.Test/JsonFilePersistenceProviderTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Navigation&issues=AaGpivsZCo9rc6GwBYxJ&open=AaGpivsZCo9rc6GwBYxJ&pullRequest=108

Check warning on line 78 in Navigation.Test/JsonFilePersistenceProviderTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Navigation&issues=AaGpivsZCo9rc6GwBYxI&open=AaGpivsZCo9rc6GwBYxI&pullRequest=108

Navigation<NavigationItem> restored = new(null, provider);
Assert.IsTrue(await restored.LoadStateAsync().ConfigureAwait(false), $"iteration {i}");

Check warning on line 81 in Navigation.Test/JsonFilePersistenceProviderTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Navigation&issues=AaGpivsZCo9rc6GwBYxK&open=AaGpivsZCo9rc6GwBYxK&pullRequest=108
Assert.IsTrue(restored.Current?.Id is "a" or "b", $"iteration {i}");
Assert.IsEmpty(Directory.GetFiles(directory, $"state-{i}.json.*.tmp"), $"iteration {i}");
}
}
finally
{
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}

private string[] GetTemporaryFiles() =>
Directory.GetFiles(Path.GetDirectoryName(_filePath!)!, $"{Path.GetFileName(_filePath!)}.*.tmp");

Expand Down
37 changes: 29 additions & 8 deletions Navigation/Services/JsonFilePersistenceProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,7 @@ public async Task SaveStateAsync(INavigationState<T> state, CancellationToken ca

cancellationToken.ThrowIfCancellationRequested();

if (File.Exists(_filePath))
{
File.Replace(tempPath, _filePath, destinationBackupFileName: null);
}
else
{
File.Move(tempPath, _filePath);
}
SwapIntoPlace(tempPath, _filePath);
}
catch
{
Expand All @@ -92,6 +85,34 @@ public async Task SaveStateAsync(INavigationState<T> state, CancellationToken ca

private static readonly UTF8Encoding Utf8NoBom = new(encoderShouldEmitUTF8Identifier: false);

/// <summary>
/// Moves a complete temporary file over the state file, whether or not the state file exists yet.
/// Two saves can both find no state file. Whichever moves second must replace the first one's file
/// rather than fail with "already exists", so the last writer wins as it does once the file exists.
/// </summary>
private static void SwapIntoPlace(string tempPath, string filePath)
{
if (File.Exists(filePath))
{
File.Replace(tempPath, filePath, destinationBackupFileName: null);
return;
}

#if NETCOREAPP3_0_OR_GREATER
File.Move(tempPath, filePath, overwrite: true);
#else
try
{
File.Move(tempPath, filePath);
}
catch (IOException) when (File.Exists(filePath))
{
// Another save created the file after the check above
File.Replace(tempPath, filePath, destinationBackupFileName: null);
}
#endif
}

private static void TryDelete(string path)
{
try
Expand Down
Loading