using System.Text; namespace FinalToken.Core; public static class AtomicFile { // D5: same-directory rename; a reader sees either complete version. public static Task WriteAsync(string path, string contents, CancellationToken cancellationToken = default) => WriteAsync(path, contents, cancellationToken, TimeProvider.System); public static async Task WriteAsync(string path, string contents, CancellationToken cancellationToken, TimeProvider timeProvider) { Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!); var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { await using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous | FileOptions.WriteThrough)) { await stream.WriteAsync(Encoding.UTF8.GetBytes(contents), cancellationToken).ConfigureAwait(false); await stream.FlushAsync(cancellationToken).ConfigureAwait(false); stream.Flush(true); } cancellationToken.ThrowIfCancellationRequested(); for (var attempt = 0; ; attempt++) { cancellationToken.ThrowIfCancellationRequested(); try { if (File.Exists(path)) File.Replace(temporary, path, null); else File.Move(temporary, path); break; } catch (Exception e) when (OperatingSystem.IsWindows() && e is IOException or UnauthorizedAccessException && (e.HResult & 0xffff) is 5 or 32 or 33) { // Windows can report ACCESS_DENIED for an open destination as well as SHARING_VIOLATION. if (attempt == 10) throw new IOException("Atomic replacement remained blocked after 500 ms.", e); await Task.Delay(TimeSpan.FromMilliseconds(50), timeProvider, cancellationToken).ConfigureAwait(false); } } } finally { if (File.Exists(temporary)) File.Delete(temporary); } } } /// The host must hold this for the entire lifetime of a writing HistoryStore/RefreshEngine (D5). public sealed class StoreLock : IDisposable { private readonly FileStream stream; private StoreLock(FileStream stream) => this.stream = stream; public static StoreLock? TryAcquire(string directory) { Directory.CreateDirectory(directory); try { return new(new FileStream(Path.Combine(directory, "store.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)); } catch (IOException) { return null; } } public void Dispose() => stream.Dispose(); } public static class ActivationFile { public static Task RequestAsync(string directory, CancellationToken cancellationToken = default) => AtomicFile.WriteAsync(Path.Combine(directory, "activate.request"), Guid.NewGuid().ToString("N"), cancellationToken); public static string? ReadRequest(string directory) { try { return SharedFile.ReadAllText(Path.Combine(directory, "activate.request")); } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return null; } } } public static class SharedFile { public static FileStream OpenRead(string path) => new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 65536, FileOptions.SequentialScan); public static string ReadAllText(string path) { using var stream = OpenRead(path); using var reader = new StreamReader(stream, Encoding.UTF8); return reader.ReadToEnd(); } }