|
| 1 | +// Licensed to Elasticsearch B.V under one or more agreements. |
| 2 | +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. |
| 3 | +// See the LICENSE file in the project root for more information |
| 4 | + |
| 5 | +using System.Collections.Concurrent; |
| 6 | +using System.Diagnostics.CodeAnalysis; |
| 7 | +using System.Security.Cryptography; |
| 8 | +using Amazon.S3; |
| 9 | +using Amazon.S3.Model; |
| 10 | +using Microsoft.Extensions.Logging; |
| 11 | + |
| 12 | +namespace Documentation.Assembler.Deploying; |
| 13 | + |
| 14 | +public class AwsS3SyncPlanStrategy(IAmazonS3 s3Client, string bucketName, AssembleContext context, ILoggerFactory loggerFactory) : IDocsSyncPlanStrategy |
| 15 | +{ |
| 16 | + internal const long PartSize = 5 * 1024 * 1024; // 5MB |
| 17 | + private readonly ILogger<AwsS3SyncPlanStrategy> _logger = loggerFactory.CreateLogger<AwsS3SyncPlanStrategy>(); |
| 18 | + private static readonly ConcurrentDictionary<string, string> EtagCache = new(); |
| 19 | + |
| 20 | + private bool IsSymlink(string path) |
| 21 | + { |
| 22 | + var fileInfo = context.ReadFileSystem.FileInfo.New(path); |
| 23 | + return fileInfo.LinkTarget != null; |
| 24 | + } |
| 25 | + |
| 26 | + public async Task<SyncPlan> Plan(Cancel ctx = default) |
| 27 | + { |
| 28 | + var remoteObjects = await ListObjects(ctx); |
| 29 | + var localObjects = context.OutputDirectory.GetFiles("*", SearchOption.AllDirectories) |
| 30 | + .Where(f => !IsSymlink(f.FullName)) |
| 31 | + .ToArray(); |
| 32 | + var deleteRequests = new ConcurrentBag<DeleteRequest>(); |
| 33 | + var addRequests = new ConcurrentBag<AddRequest>(); |
| 34 | + var updateRequests = new ConcurrentBag<UpdateRequest>(); |
| 35 | + var skipRequests = new ConcurrentBag<SkipRequest>(); |
| 36 | + |
| 37 | + await Parallel.ForEachAsync(localObjects, ctx, async (localFile, token) => |
| 38 | + { |
| 39 | + var relativePath = Path.GetRelativePath(context.OutputDirectory.FullName, localFile.FullName); |
| 40 | + var destinationPath = relativePath.Replace('\\', '/'); |
| 41 | + |
| 42 | + if (remoteObjects.TryGetValue(destinationPath, out var remoteObject)) |
| 43 | + { |
| 44 | + // Check if the ETag differs for updates |
| 45 | + var localETag = await CalculateS3ETag(localFile.FullName, token); |
| 46 | + var remoteETag = remoteObject.ETag.Trim('"'); // Remove quotes from remote ETag |
| 47 | + if (localETag == remoteETag) |
| 48 | + { |
| 49 | + var skipRequest = new SkipRequest |
| 50 | + { |
| 51 | + LocalPath = localFile.FullName, |
| 52 | + DestinationPath = remoteObject.Key |
| 53 | + }; |
| 54 | + skipRequests.Add(skipRequest); |
| 55 | + } |
| 56 | + else |
| 57 | + { |
| 58 | + var updateRequest = new UpdateRequest() |
| 59 | + { |
| 60 | + LocalPath = localFile.FullName, |
| 61 | + DestinationPath = remoteObject.Key |
| 62 | + }; |
| 63 | + updateRequests.Add(updateRequest); |
| 64 | + } |
| 65 | + } |
| 66 | + else |
| 67 | + { |
| 68 | + var addRequest = new AddRequest |
| 69 | + { |
| 70 | + LocalPath = localFile.FullName, |
| 71 | + DestinationPath = destinationPath |
| 72 | + }; |
| 73 | + addRequests.Add(addRequest); |
| 74 | + } |
| 75 | + }); |
| 76 | + |
| 77 | + // Find deletions (files in S3 but not locally) |
| 78 | + foreach (var remoteObject in remoteObjects) |
| 79 | + { |
| 80 | + var localPath = Path.Combine(context.OutputDirectory.FullName, remoteObject.Key.Replace('/', Path.DirectorySeparatorChar)); |
| 81 | + if (context.ReadFileSystem.File.Exists(localPath)) |
| 82 | + continue; |
| 83 | + var deleteRequest = new DeleteRequest |
| 84 | + { |
| 85 | + DestinationPath = remoteObject.Key |
| 86 | + }; |
| 87 | + deleteRequests.Add(deleteRequest); |
| 88 | + } |
| 89 | + |
| 90 | + return new SyncPlan |
| 91 | + { |
| 92 | + DeleteRequests = deleteRequests.ToList(), |
| 93 | + AddRequests = addRequests.ToList(), |
| 94 | + UpdateRequests = updateRequests.ToList(), |
| 95 | + SkipRequests = skipRequests.ToList(), |
| 96 | + Count = deleteRequests.Count + addRequests.Count + updateRequests.Count + skipRequests.Count |
| 97 | + }; |
| 98 | + } |
| 99 | + |
| 100 | + private async Task<Dictionary<string, S3Object>> ListObjects(Cancel ctx = default) |
| 101 | + { |
| 102 | + var listBucketRequest = new ListObjectsV2Request |
| 103 | + { |
| 104 | + BucketName = bucketName, |
| 105 | + MaxKeys = 1000, |
| 106 | + }; |
| 107 | + var objects = new List<S3Object>(); |
| 108 | + ListObjectsV2Response response; |
| 109 | + do |
| 110 | + { |
| 111 | + response = await s3Client.ListObjectsV2Async(listBucketRequest, ctx); |
| 112 | + objects.AddRange(response.S3Objects); |
| 113 | + listBucketRequest.ContinuationToken = response?.NextContinuationToken; |
| 114 | + } while (response?.IsTruncated == true); |
| 115 | + |
| 116 | + return objects.ToDictionary(o => o.Key); |
| 117 | + } |
| 118 | + |
| 119 | + [SuppressMessage("Security", "CA5351:Do Not Use Broken Cryptographic Algorithms")] |
| 120 | + private async Task<string> CalculateS3ETag(string filePath, Cancel ctx = default) |
| 121 | + { |
| 122 | + if (EtagCache.TryGetValue(filePath, out var cachedEtag)) |
| 123 | + { |
| 124 | + _logger.LogDebug("Using cached ETag for {Path}", filePath); |
| 125 | + return cachedEtag; |
| 126 | + } |
| 127 | + |
| 128 | + var fileInfo = context.ReadFileSystem.FileInfo.New(filePath); |
| 129 | + var fileSize = fileInfo.Length; |
| 130 | + |
| 131 | + // For files under 5MB, use simple MD5 (matching TransferUtility behavior) |
| 132 | + if (fileSize <= PartSize) |
| 133 | + { |
| 134 | + await using var stream = context.ReadFileSystem.FileStream.New(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); |
| 135 | + var smallBuffer = new byte[fileSize]; |
| 136 | + var bytesRead = await stream.ReadAsync(smallBuffer.AsMemory(0, (int)fileSize), ctx); |
| 137 | + var hash = MD5.HashData(smallBuffer.AsSpan(0, bytesRead)); |
| 138 | + var etag = Convert.ToHexStringLower(hash); |
| 139 | + EtagCache[filePath] = etag; |
| 140 | + return etag; |
| 141 | + } |
| 142 | + |
| 143 | + // For files over 5MB, use multipart format with 5MB parts (matching TransferUtility) |
| 144 | + var parts = (int)Math.Ceiling((double)fileSize / PartSize); |
| 145 | + |
| 146 | + await using var fileStream = context.ReadFileSystem.FileStream.New(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); |
| 147 | + var partBuffer = new byte[PartSize]; |
| 148 | + var partHashes = new List<byte[]>(); |
| 149 | + |
| 150 | + for (var i = 0; i < parts; i++) |
| 151 | + { |
| 152 | + var bytesRead = await fileStream.ReadAsync(partBuffer.AsMemory(0, partBuffer.Length), ctx); |
| 153 | + var partHash = MD5.HashData(partBuffer.AsSpan(0, bytesRead)); |
| 154 | + partHashes.Add(partHash); |
| 155 | + } |
| 156 | + |
| 157 | + // Concatenate all part hashes |
| 158 | + var concatenatedHashes = partHashes.SelectMany(h => h).ToArray(); |
| 159 | + var finalHash = MD5.HashData(concatenatedHashes); |
| 160 | + |
| 161 | + var multipartEtag = $"{Convert.ToHexStringLower(finalHash)}-{parts}"; |
| 162 | + EtagCache[filePath] = multipartEtag; |
| 163 | + return multipartEtag; |
| 164 | + } |
| 165 | +} |
0 commit comments