From 90e1dcae86ea359a338499f8a7dbeb6fb5ceaf3b Mon Sep 17 00:00:00 2001 From: ksemenenko Date: Wed, 25 Nov 2026 10:44:18 +0100 Subject: [PATCH] fix: remove redundant Azure object write metadata reads --- Directory.Build.props | 4 +- .../AzureMetadataTransport.cs | 14 ++++-- .../AzureObjectOperations.cs | 32 ++++++++++--- .../Storages/Azure/AzureUploadTests.cs | 45 +++++++++++++++++++ docs/Architecture.md | 6 +-- docs/Development/setup.md | 2 +- docs/Features/provider-azure-blob.md | 5 ++- global.json | 7 +++ 8 files changed, 98 insertions(+), 17 deletions(-) create mode 100644 global.json diff --git a/Directory.Build.props b/Directory.Build.props index 49cd91c1..53996d86 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -29,8 +29,8 @@ https://github.com/managedcode/Storage https://github.com/managedcode/Storage Managed Code - Storage - 10.1.14 - 10.1.14 + 10.1.15 + 10.1.15 diff --git a/Storages/ManagedCode.Storage.Azure/AzureMetadataTransport.cs b/Storages/ManagedCode.Storage.Azure/AzureMetadataTransport.cs index 9028ebd2..8c82f90b 100644 --- a/Storages/ManagedCode.Storage.Azure/AzureMetadataTransport.cs +++ b/Storages/ManagedCode.Storage.Azure/AzureMetadataTransport.cs @@ -13,12 +13,16 @@ internal static class AzureMetadataTransport private const string EnvelopePrefix = "utf8-json-base64:"; private static readonly UTF8Encoding StrictUtf8 = new(false, true); - internal static Dictionary? Encode(IEnumerable>? metadata) + internal static Dictionary? Encode(IEnumerable>? metadata) => + Encode(metadata, out _); + + internal static Dictionary? Encode(IEnumerable>? metadata, + out Dictionary? logicalMetadata) { - if (metadata is null) + logicalMetadata = metadata?.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase); + if (logicalMetadata is not { } values) return null; - var values = metadata.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase); if (values.All(pair => IsNativeKey(pair.Key) && IsNativeValue(pair.Value)) && !values.ContainsKey(EnvelopeKey)) return values; @@ -71,5 +75,7 @@ private static bool IsNativeKey(string key) => key.Length > 0 && IsInitialKeyCha private static bool IsInitialKeyCharacter(char character) => character is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or '_'; - private static bool IsNativeValue(string value) => value is not null && value.All(character => character is >= ' ' and <= '~'); + // HTTP can trim surrounding spaces before the service verifies the request signature. + private static bool IsNativeValue(string value) => value is { Length: > 0 } && + value[0] != ' ' && value[^1] != ' ' && value.All(character => character is >= ' ' and <= '~'); } diff --git a/Storages/ManagedCode.Storage.Azure/AzureObjectOperations.cs b/Storages/ManagedCode.Storage.Azure/AzureObjectOperations.cs index 0e968b86..7ee63cea 100644 --- a/Storages/ManagedCode.Storage.Azure/AzureObjectOperations.cs +++ b/Storages/ManagedCode.Storage.Azure/AzureObjectOperations.cs @@ -14,6 +14,8 @@ namespace ManagedCode.Storage.Azure; internal sealed class AzureObjectOperations(BlobContainerClient container) : IMultipartObjectStorage { + private const string DefaultBlobContentType = "application/octet-stream"; + public Uri ContainerUri => container.Uri; public Task GetContainerInfoAsync(CancellationToken cancellationToken = default) => ExecuteAsync(async () => @@ -73,16 +75,36 @@ public Task OpenObjectReadAsync(string path, StorageReadOptions? options public Task WriteObjectAsync(string path, Stream content, StorageWriteOptions? options = null, CancellationToken cancellationToken = default) => ExecuteAsync(async () => { options ??= new StorageWriteOptions(); - var response = await container.GetBlobClient(path).UploadAsync(content, new BlobUploadOptions + ArgumentNullException.ThrowIfNull(content); + var headers = Headers(options); + var metadata = AzureMetadataTransport.Encode(options.Metadata, out var logicalMetadata); + var length = content.CanSeek ? content.Length - content.Position : (long?)null; + var progress = length.HasValue ? null : new UploadLengthProgress(); + var written = (await container.GetBlobClient(path).UploadAsync(content, new BlobUploadOptions { Conditions = Conditions(options), - HttpHeaders = Headers(options), - Metadata = AzureMetadataTransport.Encode(options.Metadata), + HttpHeaders = headers, + Metadata = metadata, + ProgressHandler = progress, TransferOptions = new global::Azure.Storage.StorageTransferOptions { MaximumConcurrency = 1, InitialTransferSize = 4 * 1024 * 1024, MaximumTransferSize = 4 * 1024 * 1024 } - }, cancellationToken); - return await ReadWrittenInfoAsync(path, response.Value.ETag, cancellationToken); + }, cancellationToken)).Value; + + // The upload response identifies the committed version. Only read its properties + // when HTTP header normalization can change one of the values we sent. + if (!IsExactHeaderValue(headers.ContentType) || !IsExactHeaderValue(headers.ContentEncoding)) + { + return await ReadWrittenInfoAsync(path, written.ETag, cancellationToken); + } + + return new StorageObjectInfo(path, written.ETag.ToString("H"), + length ?? checked((long)progress!.BytesTransferred), headers.ContentType ?? DefaultBlobContentType, + headers.ContentEncoding, logicalMetadata ?? new Dictionary(StringComparer.OrdinalIgnoreCase), + written.LastModified); }); + private static bool IsExactHeaderValue(string? value) => + value is null || (value.Length > 0 && value.AsSpan().Trim().Length == value.Length); + public Task SetObjectMetadataAsync(string path, IReadOnlyDictionary metadata, string? ifMatch = null, CancellationToken cancellationToken = default) => ExecuteAsync(async () => { await container.GetBlobClient(path).SetMetadataAsync(AzureMetadataTransport.Encode(metadata), new BlobRequestConditions { IfMatch = ETagOrNull(ifMatch) }, cancellationToken); diff --git a/Tests/ManagedCode.Storage.Tests/Storages/Azure/AzureUploadTests.cs b/Tests/ManagedCode.Storage.Tests/Storages/Azure/AzureUploadTests.cs index 0fee26d2..edc36ab2 100644 --- a/Tests/ManagedCode.Storage.Tests/Storages/Azure/AzureUploadTests.cs +++ b/Tests/ManagedCode.Storage.Tests/Storages/Azure/AzureUploadTests.cs @@ -83,6 +83,51 @@ public async Task UploadAsync_ReturnsCompleteMetadata_WithoutReadingBlobProperti _requestPolicy.BlobWriteRequestCount.ShouldBeGreaterThan(0); } + [Theory] + [InlineData(true, 7, "text/plain", "identity", "публікація")] + [InlineData(true, 0, null, null, "native")] + [InlineData(true, 4 * 1024 * 1024 + 7, "application/octet-stream", null, "native")] + [InlineData(false, 4 * 1024 * 1024 + 7, null, null, "native")] + [InlineData(true, 7, "text/plain", null, " padded ")] + [InlineData(true, 7, "text/plain", null, "")] + public async Task WriteObjectAsync_ReturnsCommittedProperties_WithoutReadingBlobProperties( + bool seekable, int length, string? contentType, string? contentEncoding, string purpose) + { + var cancellationToken = TestContext.Current.CancellationToken; + var objects = Storage.RequireObjectStorage(); + await objects.CreatePrivateContainerAsync(cancellationToken: cancellationToken); + var bytes = new byte[length]; + var prefixLength = length == 0 ? 0 : 1; + var prefixed = new byte[prefixLength + length]; + if (prefixLength > 0) + prefixed[0] = 1; + await using var stream = new MemoryStream(prefixed) { Position = prefixLength }; + await using var source = seekable ? null : new NonSeekableReadStream(stream); + var options = new StorageWriteOptions + { + IfAbsent = true, + ContentType = contentType, + ContentEncoding = contentEncoding, + Metadata = new Dictionary { ["purpose"] = purpose } + }; + _requestPolicy.Reset(); + + var written = await objects.WriteObjectAsync(ObservedBlobName, (Stream?)source ?? stream, options, cancellationToken); + + _requestPolicy.BlobHeadRequestCount.ShouldBe(0); + _requestPolicy.BlobWriteRequestCount.ShouldBeGreaterThan(0); + var persisted = await objects.GetObjectInfoAsync(ObservedBlobName, cancellationToken); + written.Length.ShouldBe(length); + (written with { Metadata = persisted.Metadata }).ShouldBe(persisted); + written.Metadata.Count.ShouldBe(persisted.Metadata.Count); + written.Metadata["purpose"].ShouldBe(purpose); + persisted.Metadata["purpose"].ShouldBe(purpose); + await using var download = await objects.OpenObjectReadAsync(ObservedBlobName, cancellationToken: cancellationToken); + using var downloaded = new MemoryStream(); + await download.CopyToAsync(downloaded, cancellationToken); + downloaded.ToArray().ShouldBe(bytes); + } + [Theory] [InlineData(false, 1, "payload")] [InlineData(true, 0, "ayl")] diff --git a/docs/Architecture.md b/docs/Architecture.md index 5b79134e..abc8be9f 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -47,9 +47,9 @@ conditions because Azure does not offer that condition for this operation. Provider failures become `StorageOperationException` with a status code; task cancellation propagates normally. These optional streaming capabilities follow the VFS exception model; existing `IStorage` result contracts are unchanged. -Azure metadata transport belongs exclusively to the provider: printable ASCII -metadata stays native, while Unicode/control-character dictionaries use one -versioned ASCII envelope decoded across all metadata reads. See the +Azure metadata transport belongs exclusively to the provider. Native headers +carry nonempty printable ASCII values without surrounding spaces. Other +dictionaries use one versioned ASCII envelope decoded across all metadata reads. See the [Azure provider](Features/provider-azure-blob.md#metadata-transport) for its physical representation, collision handling and metadata-size constraints. VFS metadata reads return absence only for a provider 404. Cancellation and other provider failures propagate to the caller and never populate missing-file metadata caches. A later uncancelled read remains able to read the retained file. diff --git a/docs/Development/setup.md b/docs/Development/setup.md index 0958c768..988ad073 100644 --- a/docs/Development/setup.md +++ b/docs/Development/setup.md @@ -10,7 +10,7 @@ nav_order: 2 ## Prerequisites -- .NET SDK: **.NET 10** (`10.0.x`) +- Install **.NET 10 SDK** (`10.0.x`). The repository resolves the latest installed stable .NET 10 feature band for builds, tests, and CodeQL. - Docker: required for Testcontainers-backed integration tests (Azurite / LocalStack / FakeGcsServer / SFTP) ## Workflow (Local) diff --git a/docs/Features/provider-azure-blob.md b/docs/Features/provider-azure-blob.md index 4127b1be..e656860f 100644 --- a/docs/Features/provider-azure-blob.md +++ b/docs/Features/provider-azure-blob.md @@ -54,13 +54,14 @@ builder.Services.AddAzureStorageAsDefault(options => - Blob listing URIs use the SDK's escaping for object keys containing reserved characters. - Uses Azure SDK transfer options when configured (`UploadTransferOptions`). - Builds the upload result from the successful Azure upload response and the caller's options, without issuing a second blob-properties request that can race with deletion or lifecycle processing. +- Atomic object writes use the upload response for the committed ETag and time, and the upload length and options for the other properties. They read back properties when content headers can be normalized. Explicit multipart commits also read back properties because the selected parts may have been staged by another process. - Returns a failed metadata result for an absent blob without logging the expected Azure `404 BlobNotFound` response as an unhandled exception; other metadata failures retain error logging. - Preserves Unicode and control characters in logical metadata through uploads, downloads, metadata/listing reads, conditional object writes, multipart commits and container operations. The Azure provider owns the HTTP-header representation; callers pass their original strings. ## Metadata transport -Ordinary metadata with native Azure identifier keys and printable ASCII values -is stored directly. A dictionary requiring encoding is stored as one reserved +Metadata with native Azure identifier keys and nonempty printable ASCII values +without surrounding spaces is stored directly. A dictionary requiring encoding is stored as one reserved `managedcode_storage_metadata_v1` value: `utf8-json-base64:` followed by the base64 of the complete UTF-8 JSON string dictionary. Reads restore the logical dictionary once. A caller-supplied reserved key is itself wrapped, so its value diff --git a/global.json b/global.json new file mode 100644 index 00000000..d46d21e5 --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature", + "allowPrerelease": false + } +}