|
| 1 | +using Azure; |
| 2 | +using Azure.Storage.Blobs; |
| 3 | +using Azure.Storage.Blobs.Models; |
| 4 | +using Microsoft.Extensions.Options; |
| 5 | +using System.Text; |
| 6 | + |
| 7 | +namespace Automation.UI.Services.Persistence; |
| 8 | + |
| 9 | +public sealed class AzureBlobSnapshotPayloadStore : ISnapshotPayloadStore |
| 10 | +{ |
| 11 | + private readonly ImportedBundleBlobStorageSettings _settings; |
| 12 | + private readonly BlobContainerClient _container; |
| 13 | + private readonly HashSet<string> _externalizedDomains; |
| 14 | + private readonly Func<string, CancellationToken, AsyncPageable<BlobItem>> _listBlobs; |
| 15 | + private readonly Func<string, CancellationToken, Task> _deleteBlob; |
| 16 | + |
| 17 | + public AzureBlobSnapshotPayloadStore(IOptions<ImportedBundleBlobStorageSettings> settings) |
| 18 | + : this( |
| 19 | + settings.Value, |
| 20 | + CreateContainer(settings.Value), |
| 21 | + listBlobs: null, |
| 22 | + deleteBlob: null) |
| 23 | + { |
| 24 | + } |
| 25 | + |
| 26 | + internal AzureBlobSnapshotPayloadStore( |
| 27 | + ImportedBundleBlobStorageSettings settings, |
| 28 | + BlobContainerClient container, |
| 29 | + Func<string, CancellationToken, AsyncPageable<BlobItem>>? listBlobs, |
| 30 | + Func<string, CancellationToken, Task>? deleteBlob) |
| 31 | + { |
| 32 | + _settings = settings; |
| 33 | + _container = container; |
| 34 | + _externalizedDomains = (_settings.SnapshotPayloadExternalizedDomains ?? []) |
| 35 | + .Where(d => !string.IsNullOrWhiteSpace(d)) |
| 36 | + .Select(d => d.Trim()) |
| 37 | + .ToHashSet(StringComparer.OrdinalIgnoreCase); |
| 38 | + |
| 39 | + _listBlobs = listBlobs ?? ((prefix, ct) => _container.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix, ct)); |
| 40 | + _deleteBlob = deleteBlob ?? ((blobName, ct) => |
| 41 | + _container.DeleteBlobIfExistsAsync(blobName, DeleteSnapshotsOption.IncludeSnapshots, cancellationToken: ct)); |
| 42 | + } |
| 43 | + |
| 44 | + public bool ShouldExternalize(string domain, int payloadUtf8Bytes) |
| 45 | + { |
| 46 | + if (string.IsNullOrWhiteSpace(domain)) |
| 47 | + return false; |
| 48 | + |
| 49 | + if (payloadUtf8Bytes <= 0) |
| 50 | + return false; |
| 51 | + |
| 52 | + if (!_externalizedDomains.Contains(domain)) |
| 53 | + return false; |
| 54 | + |
| 55 | + var maxInlineBytes = _settings.SnapshotPayloadInlineMaxBytes; |
| 56 | + if (maxInlineBytes <= 0) |
| 57 | + return true; |
| 58 | + |
| 59 | + return payloadUtf8Bytes > maxInlineBytes; |
| 60 | + } |
| 61 | + |
| 62 | + public async Task<SnapshotPayloadPointer> StoreAsync(Guid runId, string domain, string payloadJson, CancellationToken ct = default) |
| 63 | + { |
| 64 | + if (string.IsNullOrWhiteSpace(payloadJson)) |
| 65 | + throw new InvalidOperationException("Snapshot payload JSON is required."); |
| 66 | + |
| 67 | + await _container.CreateIfNotExistsAsync(cancellationToken: ct); |
| 68 | + |
| 69 | + var blobName = BuildBlobName(runId, domain); |
| 70 | + var bytes = Encoding.UTF8.GetBytes(payloadJson); |
| 71 | + |
| 72 | + var blob = _container.GetBlobClient(blobName); |
| 73 | + using var stream = new MemoryStream(bytes, writable: false); |
| 74 | + var upload = await blob.UploadAsync(stream, overwrite: true, cancellationToken: ct); |
| 75 | + await blob.SetHttpHeadersAsync(new BlobHttpHeaders |
| 76 | + { |
| 77 | + ContentType = "application/json" |
| 78 | + }, cancellationToken: ct); |
| 79 | + |
| 80 | + return new SnapshotPayloadPointer |
| 81 | + { |
| 82 | + BlobName = blobName, |
| 83 | + Utf8Bytes = bytes.Length, |
| 84 | + ETag = upload.Value.ETag.ToString() |
| 85 | + }; |
| 86 | + } |
| 87 | + |
| 88 | + public async Task<string?> ReadAsync(SnapshotPayloadPointer pointer, CancellationToken ct = default) |
| 89 | + { |
| 90 | + if (string.IsNullOrWhiteSpace(pointer.BlobName)) |
| 91 | + return null; |
| 92 | + |
| 93 | + var blob = _container.GetBlobClient(pointer.BlobName); |
| 94 | + var exists = await blob.ExistsAsync(ct); |
| 95 | + if (!exists.Value) |
| 96 | + return null; |
| 97 | + |
| 98 | + var download = await blob.DownloadContentAsync(ct); |
| 99 | + return download.Value.Content.ToString(); |
| 100 | + } |
| 101 | + |
| 102 | + public async Task DeleteIfExistsAsync(SnapshotPayloadPointer pointer, CancellationToken ct = default) |
| 103 | + { |
| 104 | + if (string.IsNullOrWhiteSpace(pointer.BlobName)) |
| 105 | + return; |
| 106 | + |
| 107 | + await _container.DeleteBlobIfExistsAsync(pointer.BlobName, cancellationToken: ct); |
| 108 | + } |
| 109 | + |
| 110 | + public async Task DeleteRunPayloadsAsync(Guid runId, CancellationToken ct = default) |
| 111 | + { |
| 112 | + var prefix = BuildRunPrefix(runId); |
| 113 | + |
| 114 | + try |
| 115 | + { |
| 116 | + await foreach (var blob in _listBlobs(prefix, ct)) |
| 117 | + { |
| 118 | + await _deleteBlob(blob.Name, ct); |
| 119 | + } |
| 120 | + } |
| 121 | + catch (RequestFailedException ex) when (ex.Status == 404) |
| 122 | + { |
| 123 | + // Missing container is treated as an empty cleanup result. |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + private static BlobContainerClient CreateContainer(ImportedBundleBlobStorageSettings settings) |
| 128 | + { |
| 129 | + if (string.IsNullOrWhiteSpace(settings.ConnectionString)) |
| 130 | + throw new InvalidOperationException("InternalBlobStorage:ConnectionString is required for snapshot payload storage."); |
| 131 | + if (string.IsNullOrWhiteSpace(settings.BlobContainerName)) |
| 132 | + throw new InvalidOperationException("InternalBlobStorage:BlobContainerName is required for snapshot payload storage."); |
| 133 | + |
| 134 | + return new BlobContainerClient(settings.ConnectionString, settings.BlobContainerName); |
| 135 | + } |
| 136 | + |
| 137 | + private string BuildBlobName(Guid runId, string domain) |
| 138 | + { |
| 139 | + var sanitizedDomain = string.Join("-", domain |
| 140 | + .Trim() |
| 141 | + .Select(ch => char.IsLetterOrDigit(ch) || ch is '-' or '_' ? ch : '-')); |
| 142 | + |
| 143 | + return $"{BuildRunPrefix(runId)}{sanitizedDomain}/{DateTimeOffset.UtcNow:yyyyMMddHHmmssfff}-{Guid.NewGuid():N}.json"; |
| 144 | + } |
| 145 | + |
| 146 | + private string BuildRunPrefix(Guid runId) |
| 147 | + { |
| 148 | + var root = string.IsNullOrWhiteSpace(_settings.SnapshotPayloadBlobRoot) |
| 149 | + ? "automation/run-snapshots" |
| 150 | + : _settings.SnapshotPayloadBlobRoot.Trim('/'); |
| 151 | + |
| 152 | + return $"{root}/{runId:N}/"; |
| 153 | + } |
| 154 | +} |
0 commit comments