Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Two storages opened through paths that differ only in form (`a/save.dat` and `./a/save.dat`) no longer publish the same file without serializing against each other.
- A storage larger than 1 MB no longer re-grows its serialization buffer from 1 MB on every save.
- A save stopped between the two steps of `File.Replace` on Windows no longer loses the data: the next load reads the new file, or the backup if the new file cannot be read.
- A failed write no longer loses the change: the next change, `Save()` or `Dispose()` writes the data again.

## [1.0.5]
- Baseline of the changelog. See the GitHub Releases page for earlier history.
14 changes: 11 additions & 3 deletions src/Runtime/BinaryStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -663,11 +663,11 @@ public virtual void Dispose()
return;
}

if (AutoSave && _hasUnsavedChanges)
if (AutoSave && (_hasUnsavedChanges || !_persistence.Flush()))
{
SaveDataOnDisk(true);
}
else
else if (!AutoSave)
{
_persistence.Flush();
}
Expand Down Expand Up @@ -717,7 +717,15 @@ private void LoadDataFromDisk(KeyLoadFailedBehaviour keyLoadFailedBehaviour)
private void SaveDataOnDisk(bool waitForDisk)
{
ThrowIfDisposed();
_persistence.Save(_data, waitForDisk);
try
{
_persistence.Save(_data, waitForDisk);
}
catch
{
_hasUnsavedChanges = true;
throw;
}
_hasUnsavedChanges = false;
}

Expand Down
20 changes: 14 additions & 6 deletions src/Runtime/Persistence/BackgroundStorageWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ internal sealed class BackgroundStorageWriter : IStorageWriter
private StorageSnapshot? _pending;
private bool _isScheduled;
private bool _isPublishing;
private bool _lastWriteFailed;

public BackgroundStorageWriter(StorageFile file)
{
Expand All @@ -32,17 +33,19 @@ public void Write(StorageSnapshot snapshot, bool waitForDisk)
Schedule(snapshot);
return;
}
TakePending()?.Release();
TakePending(out _)?.Release();
_file.Publish(snapshot);
}

public void Flush()
public bool Flush()
{
var pending = TakePending();
if (pending != null)
var pending = TakePending(out var lastWriteFailed);
if (pending == null)
{
_file.Publish(pending.Value);
return !lastWriteFailed;
}
_file.Publish(pending.Value);
return true;
}

private void Schedule(StorageSnapshot snapshot)
Expand All @@ -62,14 +65,16 @@ private void Schedule(StorageSnapshot snapshot)
replaced?.Release();
}

private StorageSnapshot? TakePending()
private StorageSnapshot? TakePending(out bool lastWriteFailed)
{
lock (_lock)
{
while (_isPublishing)
{
Monitor.Wait(_lock);
}
lastWriteFailed = _lastWriteFailed;
_lastWriteFailed = false;
var pending = _pending;
_pending = null;
return pending;
Expand All @@ -91,18 +96,21 @@ private void PublishScheduled()
_isPublishing = true;
}

var failed = false;
try
{
_file.Publish(snapshot);
}
catch (Exception exception)
{
failed = true;
Debug.LogError($"Failed to save storage '{_file.Main}'. Reason: {exception.Message}");
}
finally
{
lock (_lock)
{
_lastWriteFailed = failed;
_isPublishing = false;
Monitor.PulseAll(_lock);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Runtime/Persistence/IStorageWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ internal interface IStorageWriter
{
void Write(StorageSnapshot snapshot, bool waitForDisk);

void Flush();
bool Flush();
}
}
3 changes: 2 additions & 1 deletion src/Runtime/Persistence/ImmediateStorageWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ public void Write(StorageSnapshot snapshot, bool waitForDisk)
_file.Publish(snapshot);
}

public void Flush()
public bool Flush()
{
return true;
}
}
}
4 changes: 2 additions & 2 deletions src/Runtime/Persistence/StoragePersistence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ public void Save(Dictionary<string, Record> data, bool waitForDisk)
}
}

public void Flush()
public bool Flush()
{
_writer.Flush();
return _writer.Flush();
}

private void SaveJsonCopy(IReadOnlyDictionary<string, Record> data)
Expand Down
68 changes: 68 additions & 0 deletions src/Tests/Persistence/FailedWriteTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using FluentAssertions;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;

namespace Appegy.Storage
{
public class FailedWriteTests : BaseStorageTests
{
[TearDown]
public void UnblockWrites()
{
if (Directory.Exists(TempPath))
{
Directory.Delete(TempPath);
}
}

[Test]
public void WhenBackgroundWriteFails_ThenDisposeWritesTheChange()
{
var storage = Open(autoSave: true);
Directory.CreateDirectory(TempPath);
using (var writeFailed = new ManualResetEventSlim())
{
void OnLog(string message, string stackTrace, LogType type)
{
if (type == LogType.Error && message.StartsWith("Failed to save storage"))
{
writeFailed.Set();
}
}

LogAssert.Expect(LogType.Error, new Regex("Failed to save storage"));
Application.logMessageReceivedThreaded += OnLog;
storage.Set("value", 7);
var failed = writeFailed.Wait(TimeSpan.FromSeconds(10));
Application.logMessageReceivedThreaded -= OnLog;
failed.Should().BeTrue();
}

Directory.Delete(TempPath);
storage.Dispose();

using var reopened = Open();
reopened.Get<int>("value").Should().Be(7);
}

[Test]
public void WhenAutoSaveWriteFails_ThenDisposeWritesTheChange()
{
var storage = Open(autoSave: true, saveOnBackgroundThread: false);
Directory.CreateDirectory(TempPath);

storage.Invoking(s => s.Set("value", 7)).Should().Throw<Exception>();

Directory.Delete(TempPath);
storage.Dispose();

using var reopened = Open();
reopened.Get<int>("value").Should().Be(7);
}
}
}
2 changes: 2 additions & 0 deletions src/Tests/Persistence/FailedWriteTests.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading