using System.Text;
namespace Chronos.Core.IO;
///
/// Crash-safe writes: content goes to a temporary sibling, is flushed to disk, then renamed over the
/// target (BRIEF §7 "temp → fsync → rename"). The readers of sidecars and projects take no lease (a thumbnail pass reads
/// a sidecar while an upload commits to it), and Windows refuses to rename over a file someone has open: a write tries the
/// rename again for a moment (), and and its siblings read such files whole
/// and at once, sharing deletion where the file system allows a rename over an open file.
///
public static class AtomicFile
{
/// Renames tried, some 1 s in all, before a replace held by a reader or another program (an indexer, an antivirus) fails.
private const int ReplaceAttempts = 15;
private const int SharingViolation = unchecked((int)0x80070020);
private const int LockViolation = unchecked((int)0x80070021);
/// The whole file as it was when opened, read so that a writer may replace it meanwhile.
/// The file is larger than an array holds (2 GB), as says.
public static byte[] ReadAllBytes(string path)
{
using var stream = OpenShared(path, FileOptions.SequentialScan);
var bytes = new byte[CheckedLength(stream, path)];
stream.ReadExactly(bytes);
return bytes;
}
///
public static async Task ReadAllBytesAsync(string path, CancellationToken cancellationToken = default)
{
await using var stream = OpenShared(path, FileOptions.SequentialScan | FileOptions.Asynchronous);
var bytes = new byte[CheckedLength(stream, path)];
await stream.ReadExactlyAsync(bytes, cancellationToken).ConfigureAwait(false);
return bytes;
}
/// The file's text (UTF-8 unless it starts with another byte order mark), read as .
public static string ReadAllText(string path)
{
using var reader = new StreamReader(OpenShared(path, FileOptions.SequentialScan), Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
return reader.ReadToEnd();
}
public static void WriteAllBytes(string path, ReadOnlySpan content)
{
var temp = TempPathFor(path);
try
{
using (var fs = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.WriteThrough))
{
fs.Write(content);
fs.Flush(flushToDisk: true);
}
Replace(temp, path);
}
catch
{
TryDelete(temp);
throw;
}
}
public static void WriteAllText(string path, string content) => WriteAllBytes(path, new UTF8Encoding(false).GetBytes(content));
/// Streams content produced by and commits it atomically.
public static async Task WriteAsync(string path, Func write, CancellationToken cancellationToken = default)
{
var temp = TempPathFor(path);
try
{
await using (var fs = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous))
{
await write(fs, cancellationToken).ConfigureAwait(false);
await fs.FlushAsync(cancellationToken).ConfigureAwait(false);
fs.Flush(flushToDisk: true);
}
await ReplaceAsync(temp, path, cancellationToken).ConfigureAwait(false);
}
catch
{
TryDelete(temp);
throw;
}
}
/// Commits an already-written temporary file over after flushing it.
public static void Commit(string tempPath, string path)
{
using (var fs = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
fs.Flush(flushToDisk: true);
Replace(tempPath, path);
}
///
/// Commits an already-written temporary file as , which must not exist: an output whose free name
/// something else took meanwhile (a restore, another program) is never overwritten.
///
/// exists (the temporary file stays for the caller to discard).
public static void CommitNew(string tempPath, string path)
{
using (var fs = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
fs.Flush(flushToDisk: true);
File.Move(tempPath, path, overwrite: false);
}
public static string TempPathFor(string path)
{
var dir = Path.GetDirectoryName(Path.GetFullPath(path)) ?? ".";
Directory.CreateDirectory(dir);
return Path.Combine(dir, "." + Path.GetFileName(path) + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp");
}
/// Opened for reading whole: other readers and a rename over it may come, a writer in place may not.
private static FileStream OpenShared(string path, FileOptions options) =>
new(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 1 << 16, options);
private static int CheckedLength(FileStream stream, string path) =>
stream.Length <= Array.MaxLength ? (int)stream.Length : throw new IOException($"{path} is larger than 2 GB.");
///
/// Renames over , trying again for a moment while another handle holds
/// the target (); anything else fails at once.
///
private static void Replace(string temp, string path)
{
for (var attempt = 1; ; attempt++)
{
try
{
File.Move(temp, path, overwrite: true);
return;
}
catch (Exception ex) when (attempt < ReplaceAttempts && Holds(ex, temp, path))
{
Thread.Sleep(10 * attempt);
}
}
}
///
private static async Task ReplaceAsync(string temp, string path, CancellationToken cancellationToken)
{
for (var attempt = 1; ; attempt++)
{
try
{
File.Move(temp, path, overwrite: true);
return;
}
catch (Exception ex) when (attempt < ReplaceAttempts && Holds(ex, temp, path))
{
await Task.Delay(10 * attempt, cancellationToken).ConfigureAwait(false);
}
}
}
///
/// Whether the rename failed because another handle holds the target, which clears once it closes: a sharing or lock
/// violation, or the "access denied" Windows answers for an open file that is neither read-only nor a folder (those
/// never clear, so they fail at once, as a missing file or folder does).
///
private static bool Holds(Exception ex, string temp, string path)
{
if (!File.Exists(temp)) return false;
if (ex is IOException { HResult: SharingViolation or LockViolation }) return true;
if (ex is not UnauthorizedAccessException) return false;
try
{
return (File.GetAttributes(path) & (FileAttributes.ReadOnly | FileAttributes.Directory)) == 0;
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{
return false;
}
}
private static void TryDelete(string path)
{
try
{
if (File.Exists(path)) File.Delete(path);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
}