|
| 1 | +namespace AiDotNet.Data; |
| 2 | + |
| 3 | +/// <summary> |
| 4 | +/// Filesystem helpers that tolerate transient locks — particularly the |
| 5 | +/// "sharing violation" window that Windows Defender or the search indexer |
| 6 | +/// can hold on a freshly written file for a few hundred milliseconds after |
| 7 | +/// the writer's handle is released. |
| 8 | +/// </summary> |
| 9 | +/// <remarks> |
| 10 | +/// <para> |
| 11 | +/// Every download path in this library writes to a temp file and then |
| 12 | +/// renames to the final location. On Windows, an antivirus scanner or the |
| 13 | +/// search indexer can hold a secondary handle on the temp file briefly |
| 14 | +/// after the writer closes it — long enough that the immediate |
| 15 | +/// <c>File.Move</c> fails with <see cref="IOException"/>. Without retry |
| 16 | +/// logic, a single transient lock aborts the entire download; the caller |
| 17 | +/// then typically wipes the temp file in a <c>finally</c> block and must |
| 18 | +/// re-download from scratch, which will race again the next time. |
| 19 | +/// </para> |
| 20 | +/// <para> |
| 21 | +/// <see cref="MoveWithRetryAsync"/> retries on <see cref="IOException"/> |
| 22 | +/// and <see cref="UnauthorizedAccessException"/> with linear backoff. The |
| 23 | +/// final attempt still propagates the real exception so callers see a |
| 24 | +/// clear failure rather than a silent no-op. |
| 25 | +/// </para> |
| 26 | +/// </remarks> |
| 27 | +internal static class RobustFileOps |
| 28 | +{ |
| 29 | + /// <summary> |
| 30 | + /// Moves <paramref name="sourcePath"/> to <paramref name="destinationPath"/>, |
| 31 | + /// tolerating transient Windows-style sharing violations. |
| 32 | + /// </summary> |
| 33 | + /// <param name="sourcePath">The source file path (typically a temp file).</param> |
| 34 | + /// <param name="destinationPath">The destination path (final location).</param> |
| 35 | + /// <param name="cancellationToken">Cancellation token.</param> |
| 36 | + /// <param name="maxAttempts">Maximum total attempts (default 5).</param> |
| 37 | + /// <param name="initialDelayMs">Initial delay between retries; each subsequent |
| 38 | + /// retry waits <c>attempt * initialDelayMs</c> milliseconds (default 200 ms, |
| 39 | + /// so default schedule is 200 / 400 / 600 / 800 ms).</param> |
| 40 | + /// <exception cref="IOException">Final attempt failed with an IO error.</exception> |
| 41 | + /// <exception cref="UnauthorizedAccessException">Final attempt failed with an access error.</exception> |
| 42 | + /// <remarks> |
| 43 | + /// <para> |
| 44 | + /// The retry tolerates <see cref="IOException"/> (e.g. sharing violation on |
| 45 | + /// Windows) and <see cref="UnauthorizedAccessException"/> (e.g. ACL |
| 46 | + /// contention mid-move). Other exceptions are surfaced immediately. |
| 47 | + /// </para> |
| 48 | + /// </remarks> |
| 49 | + internal static async Task MoveWithRetryAsync( |
| 50 | + string sourcePath, |
| 51 | + string destinationPath, |
| 52 | + CancellationToken cancellationToken, |
| 53 | + int maxAttempts = 5, |
| 54 | + int initialDelayMs = 200) |
| 55 | + { |
| 56 | + ValidateRetryArguments(maxAttempts, initialDelayMs); |
| 57 | + |
| 58 | + for (int attempt = 1; attempt <= maxAttempts; attempt++) |
| 59 | + { |
| 60 | + try |
| 61 | + { |
| 62 | + File.Move(sourcePath, destinationPath); |
| 63 | + return; |
| 64 | + } |
| 65 | + // On the final attempt the `when` clause is false, so the |
| 66 | + // catch is skipped and the original exception propagates to |
| 67 | + // the caller — exactly the intended "clear failure" behavior. |
| 68 | + catch (IOException) when (attempt < maxAttempts) |
| 69 | + { |
| 70 | + await Task.Delay(TimeSpan.FromMilliseconds(initialDelayMs * attempt), cancellationToken); |
| 71 | + } |
| 72 | + catch (UnauthorizedAccessException) when (attempt < maxAttempts) |
| 73 | + { |
| 74 | + await Task.Delay(TimeSpan.FromMilliseconds(initialDelayMs * attempt), cancellationToken); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + /// <summary> |
| 80 | + /// Synchronous sibling of <see cref="MoveWithRetryAsync"/>. For call sites |
| 81 | + /// that can't go async (e.g. atomic index flushes from a sync save path). |
| 82 | + /// Uses <see cref="Thread.Sleep"/> between attempts; prefer the async |
| 83 | + /// variant when an awaitable context is available. |
| 84 | + /// </summary> |
| 85 | + internal static void MoveWithRetry( |
| 86 | + string sourcePath, |
| 87 | + string destinationPath, |
| 88 | + int maxAttempts = 5, |
| 89 | + int initialDelayMs = 200) |
| 90 | + { |
| 91 | + ValidateRetryArguments(maxAttempts, initialDelayMs); |
| 92 | + |
| 93 | + for (int attempt = 1; attempt <= maxAttempts; attempt++) |
| 94 | + { |
| 95 | + try |
| 96 | + { |
| 97 | + File.Move(sourcePath, destinationPath); |
| 98 | + return; |
| 99 | + } |
| 100 | + // Final attempt falls through `when (attempt < maxAttempts)`, |
| 101 | + // so the underlying exception naturally propagates. |
| 102 | + catch (IOException) when (attempt < maxAttempts) |
| 103 | + { |
| 104 | + Thread.Sleep(initialDelayMs * attempt); |
| 105 | + } |
| 106 | + catch (UnauthorizedAccessException) when (attempt < maxAttempts) |
| 107 | + { |
| 108 | + Thread.Sleep(initialDelayMs * attempt); |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + /// <summary> |
| 114 | + /// Atomically replaces <paramref name="destinationPath"/> with |
| 115 | + /// <paramref name="sourcePath"/>, optionally keeping a backup at |
| 116 | + /// <paramref name="destinationBackupPath"/>. Retries on transient |
| 117 | + /// <see cref="IOException"/> / <see cref="UnauthorizedAccessException"/> |
| 118 | + /// with linear backoff, mirroring <see cref="MoveWithRetry"/>. |
| 119 | + /// Synchronous; used by atomic index / checkpoint flush paths that are |
| 120 | + /// not async. |
| 121 | + /// </summary> |
| 122 | + /// <remarks> |
| 123 | + /// On Windows <see cref="File.Replace(string, string, string)"/> is the |
| 124 | + /// in-place atomic rename, but it can still fail with a sharing |
| 125 | + /// violation if Windows Defender or the search indexer is mid-scan of |
| 126 | + /// either file. |
| 127 | + /// </remarks> |
| 128 | + internal static void ReplaceWithRetry( |
| 129 | + string sourcePath, |
| 130 | + string destinationPath, |
| 131 | + string? destinationBackupPath, |
| 132 | + int maxAttempts = 5, |
| 133 | + int initialDelayMs = 200) |
| 134 | + { |
| 135 | + ValidateRetryArguments(maxAttempts, initialDelayMs); |
| 136 | + |
| 137 | + for (int attempt = 1; attempt <= maxAttempts; attempt++) |
| 138 | + { |
| 139 | + try |
| 140 | + { |
| 141 | + File.Replace(sourcePath, destinationPath, destinationBackupPath); |
| 142 | + return; |
| 143 | + } |
| 144 | + // Final attempt: the `when` gate is false so the exception |
| 145 | + // propagates directly to the caller. |
| 146 | + catch (IOException) when (attempt < maxAttempts) |
| 147 | + { |
| 148 | + Thread.Sleep(initialDelayMs * attempt); |
| 149 | + } |
| 150 | + catch (UnauthorizedAccessException) when (attempt < maxAttempts) |
| 151 | + { |
| 152 | + Thread.Sleep(initialDelayMs * attempt); |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + /// <summary> |
| 158 | + /// Validates retry parameters. Rejects silent-success configurations — |
| 159 | + /// <c>maxAttempts < 1</c> would exit the retry loop without ever |
| 160 | + /// touching the filesystem and without throwing, which is a confusing |
| 161 | + /// failure mode for any caller that forwards user-supplied config. |
| 162 | + /// </summary> |
| 163 | + /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxAttempts"/> |
| 164 | + /// is less than 1, or <paramref name="initialDelayMs"/> is negative.</exception> |
| 165 | + private static void ValidateRetryArguments(int maxAttempts, int initialDelayMs) |
| 166 | + { |
| 167 | + if (maxAttempts < 1) |
| 168 | + { |
| 169 | + throw new ArgumentOutOfRangeException( |
| 170 | + nameof(maxAttempts), |
| 171 | + maxAttempts, |
| 172 | + "maxAttempts must be at least 1."); |
| 173 | + } |
| 174 | + |
| 175 | + if (initialDelayMs < 0) |
| 176 | + { |
| 177 | + throw new ArgumentOutOfRangeException( |
| 178 | + nameof(initialDelayMs), |
| 179 | + initialDelayMs, |
| 180 | + "initialDelayMs must be non-negative."); |
| 181 | + } |
| 182 | + } |
| 183 | +} |
0 commit comments