Files
Chronos/src/Chronos.Core/IO/AtomicFile.cs
T
Alby96andClaude Opus 5.5 728ffa35cb
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
Owner review 1 R3, R8, R9. A grouped Export step and Render menu; encoding, playback (reverse, boomerang, loops, fades, hold) and still frames; one videos library on the desktop and the server with a verified trash and copies to a videos folder.

Closes #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-05 09:18:40 +01:00

193 lines
7.9 KiB
C#

using System.Text;
namespace Chronos.Core.IO;
/// <summary>
/// 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 (<see cref="Replace"/>), and <see cref="ReadAllBytes"/> and its siblings read such files whole
/// and at once, sharing deletion where the file system allows a rename over an open file.
/// </summary>
public static class AtomicFile
{
/// <summary>Renames tried, some 1 s in all, before a replace held by a reader or another program (an indexer, an antivirus) fails.</summary>
private const int ReplaceAttempts = 15;
private const int SharingViolation = unchecked((int)0x80070020);
private const int LockViolation = unchecked((int)0x80070021);
/// <summary>The whole file as it was when opened, read so that a writer may replace it meanwhile.</summary>
/// <exception cref="IOException">The file is larger than an array holds (2 GB), as <see cref="File.ReadAllBytes"/> says.</exception>
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;
}
/// <inheritdoc cref="ReadAllBytes"/>
public static async Task<byte[]> 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;
}
/// <summary>The file's text (UTF-8 unless it starts with another byte order mark), read as <see cref="ReadAllBytes"/>.</summary>
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<byte> 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));
/// <summary>Streams content produced by <paramref name="write"/> and commits it atomically.</summary>
public static async Task WriteAsync(string path, Func<Stream, CancellationToken, Task> 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;
}
}
/// <summary>Commits an already-written temporary file over <paramref name="path"/> after flushing it.</summary>
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);
}
/// <summary>
/// Commits an already-written temporary file as <paramref name="path"/>, which must not exist: an output whose free name
/// something else took meanwhile (a restore, another program) is never overwritten.
/// </summary>
/// <exception cref="IOException"><paramref name="path"/> exists (the temporary file stays for the caller to discard).</exception>
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");
}
/// <summary>Opened for reading whole: other readers and a rename over it may come, a writer in place may not.</summary>
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.");
/// <summary>
/// Renames <paramref name="temp"/> over <paramref name="path"/>, trying again for a moment while another handle holds
/// the target (<see cref="Holds"/>); anything else fails at once.
/// </summary>
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);
}
}
}
/// <inheritdoc cref="Replace"/>
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);
}
}
}
/// <summary>
/// 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).
/// </summary>
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)
{
}
}
}