Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
<RepositoryUrl>https://github.com/managedcode/Storage</RepositoryUrl>
<PackageProjectUrl>https://github.com/managedcode/Storage</PackageProjectUrl>
<Product>Managed Code - Storage</Product>
<Version>10.1.14</Version>
<PackageVersion>10.1.14</PackageVersion>
<Version>10.1.15</Version>
<PackageVersion>10.1.15</PackageVersion>

</PropertyGroup>

Expand Down
14 changes: 10 additions & 4 deletions Storages/ManagedCode.Storage.Azure/AzureMetadataTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>? Encode(IEnumerable<KeyValuePair<string, string>>? metadata)
internal static Dictionary<string, string>? Encode(IEnumerable<KeyValuePair<string, string>>? metadata) =>
Encode(metadata, out _);

internal static Dictionary<string, string>? Encode(IEnumerable<KeyValuePair<string, string>>? metadata,
out Dictionary<string, string>? 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;

Expand Down Expand Up @@ -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 <= '~');
}
32 changes: 27 additions & 5 deletions Storages/ManagedCode.Storage.Azure/AzureObjectOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<StorageContainerInfo> GetContainerInfoAsync(CancellationToken cancellationToken = default) => ExecuteAsync(async () =>
Expand Down Expand Up @@ -73,16 +75,36 @@ public Task<Stream> OpenObjectReadAsync(string path, StorageReadOptions? options
public Task<StorageObjectInfo> 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<string, string>(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<string, string> metadata, string? ifMatch = null, CancellationToken cancellationToken = default) => ExecuteAsync(async () =>
{
await container.GetBlobClient(path).SetMetadataAsync(AzureMetadataTransport.Encode(metadata), new BlobRequestConditions { IfMatch = ETagOrNull(ifMatch) }, cancellationToken);
Expand Down
45 changes: 45 additions & 0 deletions Tests/ManagedCode.Storage.Tests/Storages/Azure/AzureUploadTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> { ["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")]
Expand Down
6 changes: 3 additions & 3 deletions docs/Architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/Development/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions docs/Features/provider-azure-blob.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"sdk": {
"version": "10.0.100",
"rollForward": "latestFeature",
"allowPrerelease": false
}
}
Loading