Harden directory MessagePack record replacement

This commit is contained in:
Meta Vens 2026-07-02 21:00:36 +01:00
commit 14a4bc021f

View file

@ -5,6 +5,7 @@ using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using MessagePack;
namespace GameCult.Caching.MessagePack;
@ -274,7 +275,7 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
if (File.Exists(path))
{
File.Replace(tempPath, path, null);
ReplaceExistingFile(tempPath, path);
}
else
{
@ -289,4 +290,26 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
}
}
}
private static void ReplaceExistingFile(string sourcePath, string destinationPath)
{
for (var attempt = 0; attempt < 3; attempt++)
{
try
{
File.Replace(sourcePath, destinationPath, null);
return;
}
catch (IOException) when (attempt < 2)
{
Thread.Sleep(10 * (attempt + 1));
}
catch (UnauthorizedAccessException) when (attempt < 2)
{
Thread.Sleep(10 * (attempt + 1));
}
}
File.Copy(sourcePath, destinationPath, overwrite: true);
}
}