|
| 1 | +/******************************************************************************* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use |
| 4 | + * this file except in compliance with the License. A copy of the License is located at |
| 5 | + * |
| 6 | + * http://aws.amazon.com/apache2.0 |
| 7 | + * |
| 8 | + * or in the "license" file accompanying this file. |
| 9 | + * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 10 | + * CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 11 | + * specific language governing permissions and limitations under the License. |
| 12 | + * ***************************************************************************** |
| 13 | + * __ _ _ ___ |
| 14 | + * ( )( \/\/ )/ __) |
| 15 | + * /__\ \ / \__ \ |
| 16 | + * (_)(_) \/\/ (___/ |
| 17 | + * |
| 18 | + * AWS SDK for .NET |
| 19 | + * API Version: 2006-03-01 |
| 20 | + * |
| 21 | + */ |
| 22 | +using System; |
| 23 | +using System.IO; |
| 24 | +using System.Security.Cryptography; |
| 25 | + |
| 26 | +namespace Amazon.S3.Transfer.Internal |
| 27 | +{ |
| 28 | + /// <summary> |
| 29 | + /// Handles atomic file operations for multipart downloads using SEP-compliant temporary file pattern. |
| 30 | + /// Creates .s3tmp.{uniqueId} files and ensures atomic commits to prevent partial file corruption. |
| 31 | + /// </summary> |
| 32 | + internal class AtomicFileHandler : IDisposable |
| 33 | + { |
| 34 | + private string _tempFilePath; |
| 35 | + private bool _disposed = false; |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// Creates a temporary file with unique identifier for atomic operations. |
| 39 | + /// Pattern: {destinationPath}.s3tmp.{8-char-unique-id} |
| 40 | + /// Uses FileMode.CreateNew for atomic file creation (no race condition). |
| 41 | + /// </summary> |
| 42 | + public string CreateTemporaryFile(string destinationPath) |
| 43 | + { |
| 44 | + if (string.IsNullOrEmpty(destinationPath)) |
| 45 | + throw new ArgumentException("Destination path cannot be null or empty", nameof(destinationPath)); |
| 46 | + |
| 47 | + // Create directory if it doesn't exist (Directory.CreateDirectory is idempotent) |
| 48 | + var directory = Path.GetDirectoryName(destinationPath); |
| 49 | + if (!string.IsNullOrEmpty(directory)) |
| 50 | + { |
| 51 | + Directory.CreateDirectory(directory); |
| 52 | + } |
| 53 | + |
| 54 | + // Try up to 100 times to create unique file atomically |
| 55 | + for (int attempt = 0; attempt < 100; attempt++) |
| 56 | + { |
| 57 | + var uniqueId = GenerateUniqueId(8); |
| 58 | + var tempPath = $"{destinationPath}.s3tmp.{uniqueId}"; |
| 59 | + |
| 60 | + try |
| 61 | + { |
| 62 | + // FileMode.CreateNew fails atomically if file exists - no race condition |
| 63 | + using (var stream = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write)) |
| 64 | + { |
| 65 | + // File created successfully - immediately close it |
| 66 | + } |
| 67 | + |
| 68 | + _tempFilePath = tempPath; |
| 69 | + return tempPath; |
| 70 | + } |
| 71 | + catch (IOException) when (attempt < 99) |
| 72 | + { |
| 73 | + // File exists, try again with new ID |
| 74 | + continue; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + throw new InvalidOperationException("Unable to generate unique temporary file name after 100 attempts"); |
| 79 | + } |
| 80 | + |
| 81 | + /// <summary> |
| 82 | + /// Atomically commits the temporary file to the final destination. |
| 83 | + /// Uses File.Replace for atomic replacement when destination exists, or File.Move for new files. |
| 84 | + /// This prevents data loss if the process crashes during commit. |
| 85 | + /// </summary> |
| 86 | + public void CommitFile(string tempPath, string destinationPath) |
| 87 | + { |
| 88 | + if (string.IsNullOrEmpty(tempPath)) |
| 89 | + throw new ArgumentException("Temp path cannot be null or empty", nameof(tempPath)); |
| 90 | + if (string.IsNullOrEmpty(destinationPath)) |
| 91 | + throw new ArgumentException("Destination path cannot be null or empty", nameof(destinationPath)); |
| 92 | + |
| 93 | + if (!File.Exists(tempPath)) |
| 94 | + throw new FileNotFoundException($"Temporary file not found: {tempPath}"); |
| 95 | + |
| 96 | + try |
| 97 | + { |
| 98 | + // Use File.Replace for atomic replacement when overwriting existing file |
| 99 | + // This prevents data loss if process crashes between delete and move operations |
| 100 | + // File.Replace is atomic on Windows (ReplaceFile API) and Unix (rename syscall) |
| 101 | + if (File.Exists(destinationPath)) |
| 102 | + { |
| 103 | + File.Replace(tempPath, destinationPath, null); |
| 104 | + } |
| 105 | + else |
| 106 | + { |
| 107 | + // For new files, File.Move is sufficient and atomic on same volume |
| 108 | + File.Move(tempPath, destinationPath); |
| 109 | + } |
| 110 | + |
| 111 | + if (_tempFilePath == tempPath) |
| 112 | + _tempFilePath = null; // Successfully committed |
| 113 | + } |
| 114 | + catch (Exception ex) |
| 115 | + { |
| 116 | + throw new InvalidOperationException($"Failed to commit temporary file {tempPath} to {destinationPath}", ex); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + /// <summary> |
| 121 | + /// Cleans up temporary file in case of failure or cancellation. |
| 122 | + /// Safe to call multiple times - File.Delete() is idempotent (no-op if file doesn't exist). |
| 123 | + /// </summary> |
| 124 | + public void CleanupOnFailure(string tempPath = null) |
| 125 | + { |
| 126 | + var pathToClean = string.IsNullOrEmpty(tempPath) ? _tempFilePath : tempPath; |
| 127 | + |
| 128 | + if (string.IsNullOrEmpty(pathToClean)) |
| 129 | + return; |
| 130 | + |
| 131 | + try |
| 132 | + { |
| 133 | + // File.Delete() is idempotent - doesn't throw if file doesn't exist |
| 134 | + File.Delete(pathToClean); |
| 135 | + |
| 136 | + if (_tempFilePath == pathToClean) |
| 137 | + _tempFilePath = null; |
| 138 | + } |
| 139 | + catch (IOException) |
| 140 | + { |
| 141 | + // Log warning but don't throw - cleanup is best effort |
| 142 | + // In production, this would use proper logging infrastructure |
| 143 | + } |
| 144 | + catch (UnauthorizedAccessException) |
| 145 | + { |
| 146 | + // Log warning but don't throw - cleanup is best effort |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + /// <summary> |
| 151 | + /// Generates a cryptographically secure unique identifier of specified length. |
| 152 | + /// Uses base32 encoding to avoid filesystem-problematic characters. |
| 153 | + /// </summary> |
| 154 | + private string GenerateUniqueId(int length) |
| 155 | + { |
| 156 | + const string base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; // RFC 4648 base32 |
| 157 | + |
| 158 | + using (var rng = RandomNumberGenerator.Create()) |
| 159 | + { |
| 160 | + var bytes = new byte[length]; |
| 161 | + rng.GetBytes(bytes); |
| 162 | + |
| 163 | + var result = new char[length]; |
| 164 | + for (int i = 0; i < length; i++) |
| 165 | + { |
| 166 | + result[i] = base32Chars[bytes[i] % base32Chars.Length]; |
| 167 | + } |
| 168 | + |
| 169 | + return new string(result); |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + public void Dispose() |
| 174 | + { |
| 175 | + if (!_disposed) |
| 176 | + { |
| 177 | + // Cleanup any remaining temp file |
| 178 | + CleanupOnFailure(); |
| 179 | + _disposed = true; |
| 180 | + } |
| 181 | + } |
| 182 | + } |
| 183 | +} |
0 commit comments