diff --git a/src/DurableTask.AzureStorage/DefaultStorageServiceClientProvider.cs b/src/DurableTask.AzureStorage/DefaultStorageServiceClientProvider.cs index 10ac513b..2e47d737 100644 --- a/src/DurableTask.AzureStorage/DefaultStorageServiceClientProvider.cs +++ b/src/DurableTask.AzureStorage/DefaultStorageServiceClientProvider.cs @@ -19,13 +19,19 @@ namespace DurableTask.AzureStorage sealed class DefaultStorageServiceClientProvider : IStorageServiceClientProvider, IStorageTokenCredentialProvider where TClientOptions : ClientOptions { readonly Func factory; - readonly TClientOptions options; + readonly Func optionsFactory; + readonly TClientOptions? sharedOptions; - public DefaultStorageServiceClientProvider(Func factory, TClientOptions options, TokenCredential? tokenCredential = null) + public DefaultStorageServiceClientProvider( + Func factory, + Func optionsFactory, + TokenCredential? tokenCredential = null, + TClientOptions? sharedOptions = null) { this.TokenCredential = tokenCredential; + this.sharedOptions = sharedOptions; this.factory = factory ?? throw new ArgumentNullException(nameof(factory)); - this.options = options ?? throw new ArgumentNullException(nameof(options)); + this.optionsFactory = optionsFactory ?? throw new ArgumentNullException(nameof(optionsFactory)); } public TokenCredential? TokenCredential { get; } @@ -37,7 +43,17 @@ public TClient CreateClient(TClientOptions options) public TClientOptions CreateOptions() { - return this.options; + return this.sharedOptions ?? this.optionsFactory(); + } + + public TClientOptions CreateFreshOptions() + { + TClientOptions options = this.optionsFactory(); + if (ReferenceEquals(options, this.sharedOptions)) + { + throw new InvalidOperationException("Fresh client options are required. Use an options factory that returns a new options object on every call."); + } + return options; } } } diff --git a/src/DurableTask.AzureStorage/IStorageServiceClientProvider.cs b/src/DurableTask.AzureStorage/IStorageServiceClientProvider.cs index 821ad0a7..47f40aa5 100644 --- a/src/DurableTask.AzureStorage/IStorageServiceClientProvider.cs +++ b/src/DurableTask.AzureStorage/IStorageServiceClientProvider.cs @@ -27,6 +27,7 @@ public interface IStorageServiceClientProvider where TC /// /// /// The result may be modified by callers before invoking . + /// Custom providers used during migration must return fresh options so that migration policies do not affect other clients. /// /// The corresponding client options. TClientOptions CreateOptions(); diff --git a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs index 76b8a267..4bc8fd8f 100644 --- a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs +++ b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs @@ -19,14 +19,30 @@ namespace DurableTask.AzureStorage.Storage using Azure.Data.Tables; using Azure.Storage.Blobs; using Azure.Storage.Queues; + using Azure.Storage.Queues.Models; using DurableTask.AzureStorage.Http; using DurableTask.AzureStorage.Monitoring; class AzureStorageClient { - readonly BlobServiceClient blobClient; - readonly QueueServiceClient queueClient; - readonly TableServiceClient tableClient; + protected readonly BlobServiceClient blobClient; + protected readonly QueueServiceClient queueClient; + protected readonly TableServiceClient tableClient; + protected readonly QueueClientOptions queueOptions; + protected readonly TableClientOptions tableOptions; + protected readonly BlobClientOptions blobOptions; + readonly ThrottlingHttpPipelinePolicy throttlingPolicy; + readonly LeaseTimeoutHttpPipelinePolicy timeoutPolicy; + readonly MonitoringHttpPipelinePolicy monitoringPolicy; + + public static AzureStorageClient Create( + AzureStorageOrchestrationServiceSettings settings, + Guid? migrationId = null) + { + return migrationId.HasValue + ? new MigratingAzureStorageClient(settings, migrationId.Value) + : new AzureStorageClient(settings); + } public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings) { @@ -42,95 +58,22 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings) this.Settings = settings; this.Stats = new AzureStorageOrchestrationServiceStats(); - - var throttlingPolicy = new ThrottlingHttpPipelinePolicy(this.Settings.MaxStorageOperationConcurrency); - var timeoutPolicy = new LeaseTimeoutHttpPipelinePolicy(this.Settings.LeaseRenewInterval); - var monitoringPolicy = new MonitoringHttpPipelinePolicy(this.Stats); - - this.queueClient = CreateClient(settings.StorageAccountClientProvider.Queue, ConfigureQueueClientPolicies); - if (settings.HasTrackingStoreStorageAccount) - { - this.blobClient = CreateClient(settings.TrackingServiceClientProvider!.Blob, ConfigureClientPolicies); - this.tableClient = CreateClient(settings.TrackingServiceClientProvider!.Table, ConfigureClientPolicies); - } - else - { - this.blobClient = CreateClient(settings.StorageAccountClientProvider.Blob, ConfigureClientPolicies); - this.tableClient = CreateClient(settings.StorageAccountClientProvider.Table, ConfigureClientPolicies); - } - - void ConfigureClientPolicies(TClientOptions options) where TClientOptions : ClientOptions - { - options.AddPolicy(throttlingPolicy!, HttpPipelinePosition.PerCall); - options.AddPolicy(timeoutPolicy!, HttpPipelinePosition.PerCall); - options.AddPolicy(monitoringPolicy!, HttpPipelinePosition.PerRetry); - } - - void ConfigureQueueClientPolicies(QueueClientOptions options) - { - // Configure message encoding based on settings - options.MessageEncoding = this.Settings.QueueClientMessageEncoding switch - { - QueueClientMessageEncoding.UTF8 => QueueMessageEncoding.None, - QueueClientMessageEncoding.Base64 => QueueMessageEncoding.Base64, - _ => throw new ArgumentException($"Unsupported encoding strategy: {this.Settings.QueueClientMessageEncoding}") - }; - - // Base64-encoded clients will fail to decode messages sent in UTF-8 format. - // This handler catches decoding failures and update the message with its the original content, - // so that the client can successfully process it on the next attempt. - if (this.Settings.QueueClientMessageEncoding == QueueClientMessageEncoding.Base64) - { - options.MessageDecodingFailed += async (QueueMessageDecodingFailedEventArgs args) => - { - this.Settings.Logger.GeneralWarning( - this.QueueAccountName, - this.Settings.TaskHubName, - $"Base64-encoded queue client failed to decode message with ID: {args.ReceivedMessage.MessageId}. " + - "The message appears to have been originally sent using UTF-8 encoding. " + - "Will attempt to re-encode the message content as Base64 and update the queue message in-place " + - "so it can be successfully processed on the next attempt." - ); - - if (args.ReceivedMessage != null) - { - var queueMessage = args.ReceivedMessage; - - try - { - // Get the raw message content and update the message. - string originalJson = Encoding.UTF8.GetString(queueMessage.Body.ToArray()); - - // Update the message in the queue with the Base64-encoded body - if (args.IsRunningSynchronously) - { - args.Queue.UpdateMessage( - queueMessage.MessageId, - queueMessage.PopReceipt, - originalJson, - TimeSpan.FromSeconds(0)); - } - else - { - await args.Queue.UpdateMessageAsync( - queueMessage.MessageId, - queueMessage.PopReceipt, - originalJson, - TimeSpan.FromSeconds(0)); - } - } - catch (Exception ex) - { - // If re-encoding or update fails, rethrow the error to be handled upstream - throw new InvalidOperationException( - $"Failed to re-encode and update UTF-8 message as Base64. MessageId: {queueMessage.MessageId}", ex); - } - } - }; - } - - ConfigureClientPolicies(options); - } + this.throttlingPolicy = new ThrottlingHttpPipelinePolicy(settings.MaxStorageOperationConcurrency); + this.timeoutPolicy = new LeaseTimeoutHttpPipelinePolicy(settings.LeaseRenewInterval); + this.monitoringPolicy = new MonitoringHttpPipelinePolicy(this.Stats); + this.queueClient = CreateClient( + settings.StorageAccountClientProvider.Queue, + this.ConfigureQueueClientPolicies, + out this.queueOptions); + TrackingServiceClientProvider trackingProvider = settings.TrackingServiceClientProvider ?? settings.StorageAccountClientProvider; + this.blobClient = CreateClient( + trackingProvider.Blob, + this.ConfigureClientPolicies, + out this.blobOptions); + this.tableClient = CreateClient( + trackingProvider.Table, + this.ConfigureClientPolicies, + out this.tableOptions); } public AzureStorageOrchestrationServiceSettings Settings { get; } @@ -143,37 +86,112 @@ await args.Queue.UpdateMessageAsync( public string TableAccountName => this.tableClient.AccountName; - public Blob GetBlobReference(string container, string blobName) + public virtual Blob GetBlobReference(string container, string blobName) { return new Blob(this.blobClient, container, blobName); } - internal Blob GetBlobReference(Uri blobUri) + internal virtual Blob GetBlobReference(Uri blobUri) { return new Blob(this.blobClient, blobUri); } - public BlobContainer GetBlobContainerReference(string container) + public virtual BlobContainer GetBlobContainerReference(string container) { return new BlobContainer(this, this.blobClient, container); } - public Queue GetQueueReference(string queueName) + public virtual Queue GetQueueReference(string queueName) { return new Queue(this, this.queueClient, queueName); } - public Table GetTableReference(string tableName) + public virtual Table GetTableReference(string tableName) { return new Table(this, this.tableClient, tableName); } + protected void ConfigureClientPolicies(TClientOptions options) where TClientOptions : ClientOptions + { + options.AddPolicy(this.throttlingPolicy, HttpPipelinePosition.PerCall); + options.AddPolicy(this.timeoutPolicy, HttpPipelinePosition.PerCall); + options.AddPolicy(this.monitoringPolicy, HttpPipelinePosition.PerRetry); + } + + protected void ConfigureQueueClientPolicies(QueueClientOptions options) + { + // Configure message encoding based on settings + options.MessageEncoding = this.Settings.QueueClientMessageEncoding switch + { + QueueClientMessageEncoding.UTF8 => QueueMessageEncoding.None, + QueueClientMessageEncoding.Base64 => QueueMessageEncoding.Base64, + _ => throw new ArgumentException($"Unsupported encoding strategy: {this.Settings.QueueClientMessageEncoding}") + }; + + // Base64-encoded clients will fail to decode messages sent in UTF-8 format. + // This handler catches decoding failures and update the message with its the original content, + // so that the client can successfully process it on the next attempt. + if (this.Settings.QueueClientMessageEncoding == QueueClientMessageEncoding.Base64) + { + options.MessageDecodingFailed += async (QueueMessageDecodingFailedEventArgs args) => + { + this.Settings.Logger.GeneralWarning( + this.QueueAccountName, + this.Settings.TaskHubName, + $"Base64-encoded queue client failed to decode message with ID: {args.ReceivedMessage.MessageId}. " + + "The message appears to have been originally sent using UTF-8 encoding. " + + "Will attempt to re-encode the message content as Base64 and update the queue message in-place " + + "so it can be successfully processed on the next attempt." + ); + + if (args.ReceivedMessage != null) + { + QueueMessage queueMessage = args.ReceivedMessage; + + try + { + // Get the raw message content and update the message. + string originalJson = Encoding.UTF8.GetString(queueMessage.Body.ToArray()); + + // Update the message in the queue with the Base64-encoded body + if (args.IsRunningSynchronously) + { + args.Queue.UpdateMessage( + queueMessage.MessageId, + queueMessage.PopReceipt, + originalJson, + TimeSpan.FromSeconds(0)); + } + else + { + await args.Queue.UpdateMessageAsync( + queueMessage.MessageId, + queueMessage.PopReceipt, + originalJson, + TimeSpan.FromSeconds(0)); + } + } + catch (Exception ex) + { + // If re-encoding or update fails, rethrow the error to be handled upstream + throw new InvalidOperationException( + $"Failed to re-encode and update UTF-8 message as Base64. MessageId: {queueMessage.MessageId}", + ex); + } + } + }; + } + + this.ConfigureClientPolicies(options); + } + static TClient CreateClient( IStorageServiceClientProvider storageProvider, - Action configurePolicies) + Action configurePolicies, + out TClientOptions options) where TClientOptions : ClientOptions { - TClientOptions options = storageProvider.CreateOptions(); + options = storageProvider.CreateOptions(); // Disable distributed tracing by default to reduce the noise in the traces. options.Diagnostics.IsDistributedTracingEnabled = false; diff --git a/src/DurableTask.AzureStorage/Storage/Blob.cs b/src/DurableTask.AzureStorage/Storage/Blob.cs index 390a9260..9c129909 100644 --- a/src/DurableTask.AzureStorage/Storage/Blob.cs +++ b/src/DurableTask.AzureStorage/Storage/Blob.cs @@ -26,6 +26,7 @@ namespace DurableTask.AzureStorage.Storage class Blob { readonly BlockBlobClient blockBlobClient; + protected virtual BlockBlobClient Client => this.blockBlobClient; public Blob(BlobServiceClient blobServiceClient, string containerName, string blobName) { @@ -51,23 +52,27 @@ public Blob(BlobServiceClient blobServiceClient, Uri blobUri) public Uri Uri => this.blockBlobClient.Uri; - public async Task ExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task ExistsAsync(CancellationToken cancellationToken = default) { - return await this.blockBlobClient.ExistsAsync(cancellationToken).DecorateFailure(); + return await this.Client.ExistsAsync(cancellationToken).DecorateFailure(); } - public async Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) { - return await this.blockBlobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, cancellationToken: cancellationToken).DecorateFailure(); + return await this.Client.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, cancellationToken: cancellationToken).DecorateFailure(); } - public async Task IsLeasedAsync(CancellationToken cancellationToken = default) + public async virtual Task IsLeasedAsync(CancellationToken cancellationToken = default) { - BlobProperties properties = await this.blockBlobClient.GetPropertiesAsync(cancellationToken: cancellationToken).DecorateFailure(); + BlobProperties properties = await this.Client.GetPropertiesAsync(cancellationToken: cancellationToken).DecorateFailure(); return properties.LeaseState == LeaseState.Leased; } - public async Task UploadTextAsync(string content, string? leaseId = null, bool ifDoesntExist = false, CancellationToken cancellationToken = default) + public async virtual Task UploadTextAsync( + string content, + string? leaseId = null, + bool ifDoesntExist = false, + CancellationToken cancellationToken = default) { BlobRequestConditions? conditions = null; if (ifDoesntExist) @@ -80,20 +85,24 @@ public async Task UploadTextAsync(string content, string? leaseId = null, bool i } using var buffer = new MemoryStream(Encoding.UTF8.GetBytes(content), writable: false); - await this.blockBlobClient.UploadAsync(buffer, conditions: conditions, cancellationToken: cancellationToken).DecorateFailure(); + await this.Client.UploadAsync(buffer, conditions: conditions, cancellationToken: cancellationToken).DecorateFailure(); } - public async Task UploadFromByteArrayAsync(byte[] buffer, int index, int byteCount, CancellationToken cancellationToken = default) + public async virtual Task UploadFromByteArrayAsync( + byte[] buffer, + int index, + int byteCount, + CancellationToken cancellationToken = default) { using var stream = new MemoryStream(buffer, index, byteCount, writable: false); - await this.blockBlobClient.UploadAsync(stream, cancellationToken: cancellationToken).DecorateFailure(); + await this.Client.UploadAsync(stream, cancellationToken: cancellationToken).DecorateFailure(); } - public async Task OpenWriteAsync(CancellationToken cancellationToken = default) + public async virtual Task OpenWriteAsync(CancellationToken cancellationToken = default) { try { - return await this.blockBlobClient.OpenWriteAsync(overwrite: true, cancellationToken: cancellationToken); + return await this.Client.OpenWriteAsync(overwrite: true, cancellationToken: cancellationToken); } catch (RequestFailedException rfe) { @@ -101,27 +110,32 @@ public async Task OpenWriteAsync(CancellationToken cancellationToken = d } } - public async Task DownloadTextAsync(CancellationToken cancellationToken = default) + public async virtual Task DownloadTextAsync(CancellationToken cancellationToken = default) { - using BlobDownloadStreamingResult result = await this.blockBlobClient.DownloadStreamingAsync(cancellationToken: cancellationToken).DecorateFailure(); + using BlobDownloadStreamingResult result = await this.Client.DownloadStreamingAsync(cancellationToken: cancellationToken).DecorateFailure(); using var reader = new StreamReader(result.Content, Encoding.UTF8); return await reader.ReadToEndAsync(); } - public Task DownloadToStreamAsync(MemoryStream target, CancellationToken cancellationToken = default) + public async virtual Task DownloadToStreamAsync( + MemoryStream target, + CancellationToken cancellationToken = default) { - return this.blockBlobClient.DownloadToAsync(target, cancellationToken: cancellationToken).DecorateFailure(); + await this.Client.DownloadToAsync(target, cancellationToken: cancellationToken).DecorateFailure(); } - public async Task DownloadStreamingAsync(CancellationToken cancellationToken = default) + public async virtual Task DownloadStreamingAsync(CancellationToken cancellationToken = default) { - return await this.blockBlobClient.DownloadStreamingAsync(cancellationToken: cancellationToken).DecorateFailure(); + return await this.Client.DownloadStreamingAsync(cancellationToken: cancellationToken).DecorateFailure(); } - public async Task AcquireLeaseAsync(TimeSpan leaseInterval, string leaseId, CancellationToken cancellationToken = default) + public async virtual Task AcquireLeaseAsync( + TimeSpan leaseInterval, + string leaseId, + CancellationToken cancellationToken = default) { - BlobLease lease = await this.blockBlobClient + BlobLease lease = await this.Client .GetBlobLeaseClient(leaseId) .AcquireAsync(leaseInterval, cancellationToken: cancellationToken) .DecorateFailure(); @@ -129,9 +143,12 @@ public async Task AcquireLeaseAsync(TimeSpan leaseInterval, string lease return lease.LeaseId; } - public async Task ChangeLeaseAsync(string proposedLeaseId, string currentLeaseId, CancellationToken cancellationToken = default) + public async virtual Task ChangeLeaseAsync( + string proposedLeaseId, + string currentLeaseId, + CancellationToken cancellationToken = default) { - BlobLease lease = await this.blockBlobClient + BlobLease lease = await this.Client .GetBlobLeaseClient(currentLeaseId) .ChangeAsync(proposedLeaseId, cancellationToken: cancellationToken) .DecorateFailure(); @@ -139,17 +156,21 @@ public async Task ChangeLeaseAsync(string proposedLeaseId, string curren return lease.LeaseId; } - public Task RenewLeaseAsync(string leaseId, CancellationToken cancellationToken = default) + public async virtual Task RenewLeaseAsync( + string leaseId, + CancellationToken cancellationToken = default) { - return this.blockBlobClient + await this.Client .GetBlobLeaseClient(leaseId) .RenewAsync(cancellationToken: cancellationToken) .DecorateFailure(); } - public Task ReleaseLeaseAsync(string leaseId, CancellationToken cancellationToken = default) + public async virtual Task ReleaseLeaseAsync( + string leaseId, + CancellationToken cancellationToken = default) { - return this.blockBlobClient + await this.Client .GetBlobLeaseClient(leaseId) .ReleaseAsync(cancellationToken: cancellationToken) .DecorateFailure(); diff --git a/src/DurableTask.AzureStorage/Storage/BlobContainer.cs b/src/DurableTask.AzureStorage/Storage/BlobContainer.cs index a61ac9f5..9282854f 100644 --- a/src/DurableTask.AzureStorage/Storage/BlobContainer.cs +++ b/src/DurableTask.AzureStorage/Storage/BlobContainer.cs @@ -44,7 +44,7 @@ public Blob GetBlobReference(string blobName, string? blobPrefix = null) return this.azureStorageClient.GetBlobReference(this.containerName, fullBlobName); } - public async Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { // TODO: Any encryption scope? // If we received null, then the response must have been a 409 (Conflict) and the container must already exist @@ -57,7 +57,9 @@ public async Task ExistsAsync(CancellationToken cancellationToken = defaul return await this.blobContainerClient.ExistsAsync(cancellationToken).DecorateFailure(); } - public async Task DeleteIfExistsAsync(string? appLeaseId = null, CancellationToken cancellationToken = default) + public async virtual Task DeleteIfExistsAsync( + string? appLeaseId = null, + CancellationToken cancellationToken = default) { BlobRequestConditions? conditions = null; if (appLeaseId != null) @@ -71,7 +73,8 @@ public async Task DeleteIfExistsAsync(string? appLeaseId = null, Cancellat public AsyncPageable ListBlobsAsync(string? prefix = null, CancellationToken cancellationToken = default) { // GetBlobsAsync will return directories if hierarchical namespace (HNS) is enabled, - // so we must filter them out by checking for a special piece of metadata called "hdi_isfolder" + // so we must filter them out by checking for a special piece of metadata called "hdi_isfolder". + return this.blobContainerClient .GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, prefix, cancellationToken) .DecorateFailure() @@ -80,7 +83,10 @@ public AsyncPageable ListBlobsAsync(string? prefix = null, CancellationTok .Select(b => this.GetBlobReference(b.Name))); } - public async Task AcquireLeaseAsync(TimeSpan leaseInterval, string leaseId, CancellationToken cancellationToken = default) + public async virtual Task AcquireLeaseAsync( + TimeSpan leaseInterval, + string leaseId, + CancellationToken cancellationToken = default) { BlobLease lease = await this.blobContainerClient .GetBlobLeaseClient(leaseId) @@ -90,7 +96,10 @@ public async Task AcquireLeaseAsync(TimeSpan leaseInterval, string lease return lease.LeaseId; } - public async Task ChangeLeaseAsync(string proposedLeaseId, string currentLeaseId, CancellationToken cancellationToken = default) + public async virtual Task ChangeLeaseAsync( + string proposedLeaseId, + string currentLeaseId, + CancellationToken cancellationToken = default) { BlobLease lease = await this.blobContainerClient .GetBlobLeaseClient(currentLeaseId) @@ -100,9 +109,11 @@ public async Task ChangeLeaseAsync(string proposedLeaseId, string curren return lease.LeaseId; } - public Task RenewLeaseAsync(string leaseId, CancellationToken cancellationToken = default) + public async virtual Task RenewLeaseAsync( + string leaseId, + CancellationToken cancellationToken = default) { - return this.blobContainerClient + await this.blobContainerClient .GetBlobLeaseClient(leaseId) .RenewAsync(cancellationToken: cancellationToken) .DecorateFailure(); diff --git a/src/DurableTask.AzureStorage/Storage/MigratingAzureStorageClient.cs b/src/DurableTask.AzureStorage/Storage/MigratingAzureStorageClient.cs new file mode 100644 index 00000000..0e67bb64 --- /dev/null +++ b/src/DurableTask.AzureStorage/Storage/MigratingAzureStorageClient.cs @@ -0,0 +1,202 @@ +// ---------------------------------------------------------------------------------- +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +#nullable enable +namespace DurableTask.AzureStorage.Storage +{ + using System; + using System.Collections.Concurrent; + using System.Threading; + using System.Threading.Tasks; + using Azure.Core; + using Azure.Data.Tables; + using Azure.Storage.Blobs; + using Azure.Storage.Blobs.Specialized; + using Azure.Storage.Queues; + using DurableTask.AzureStorage.Http; + + sealed class MigratingAzureStorageClient : AzureStorageClient + { + readonly MigrationSasManager migration; + readonly SemaphoreSlim initializationLock = new(1, 1); + readonly QueueClientOptions sasQueueOptions; + readonly TableClientOptions sasTableOptions; + readonly BlobClientOptions sasBlobOptions; + readonly ConcurrentDictionary sasQueues = new(); + readonly ConcurrentDictionary sasTables = new(); + readonly ConcurrentDictionary sasContainers = new(); + volatile bool migrationInitialized; + + public MigratingAzureStorageClient( + AzureStorageOrchestrationServiceSettings settings, + Guid migrationId) + : base(settings) + { + StorageAccountClientProvider provider = settings.StorageAccountClientProvider!; + TrackingServiceClientProvider trackingProvider = settings.TrackingServiceClientProvider ?? provider; + this.migration = new MigrationSasManager( + settings, + migrationId, + this.blobClient, + this.queueClient, + this.tableClient, + trackingProvider.Table, + () => this.MigrationEnding?.Invoke()); + + // Retry authentication failures once with a refreshed SAS. + MigrationSasRetryPolicy sasRetry = new(this.migration); + + // Get fresh provider options before adding migration policies. + this.sasQueueOptions = CreateMigrationOptions(provider.Queue, this.queueOptions); + this.sasQueueOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); + this.ConfigureQueueClientPolicies(this.sasQueueOptions); + this.sasQueueOptions.AddPolicy(new MigrationRequestPolicy(this.migration, useDelegationVersion: true), HttpPipelinePosition.PerRetry); + this.sasTableOptions = CreateMigrationOptions(trackingProvider.Table, this.tableOptions); + this.sasTableOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); + this.ConfigureClientPolicies(this.sasTableOptions); + this.sasTableOptions.AddPolicy(new MigrationRequestPolicy(this.migration, useDelegationVersion: true), HttpPipelinePosition.PerRetry); + this.sasBlobOptions = CreateMigrationOptions(trackingProvider.Blob, this.blobOptions); + this.sasBlobOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); + this.ConfigureClientPolicies(this.sasBlobOptions); + this.sasBlobOptions.AddPolicy(new MigrationRequestPolicy(this.migration), HttpPipelinePosition.PerRetry); + } + + public event Action? MigrationEnding; + + public bool IsMigrationEnding => this.migration.IsMigrationEnding; + + public async Task InitializeMigrationAsync( + bool refresh = false, + CancellationToken cancellationToken = default) + { + if (!refresh && this.migrationInitialized) + { + return; + } + + await this.initializationLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // Another caller may have initialized while we waited. + if (refresh || !this.migrationInitialized) + { + this.migrationInitialized = false; + await this.migration.RefreshAsync(cancellationToken).ConfigureAwait(false); + _ = this.migration.StartRefreshLoop(); + this.migrationInitialized = true; + } + } + finally + { + this.initializationLock.Release(); + } + } + + public async Task StopMigrationTokenRefreshAsync() + { + // Finish initialization before stopping the loop it starts. + await this.initializationLock.WaitAsync().ConfigureAwait(false); + try + { + await this.migration.StopRefreshing().ConfigureAwait(false); + } + finally + { + this.initializationLock.Release(); + } + } + + internal async Task EnsureAccessAsync(CancellationToken cancellationToken) + { + await this.InitializeMigrationAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + this.migration.EnsureAccess(); + } + + internal static OrchestrationServiceUnavailableException ResourceDeletionNotSupported() + { + return new("Task hub resource deletion is not supported during migration."); + } + + public QueueClient GetQueueClient(QueueClient original) + { + return this.sasQueues.GetOrAdd( + original.Name, + name => new QueueClient(original.Uri, this.migration.GetCredential('q', name), this.sasQueueOptions)); + } + + public TableClient GetTableClient(TableClient original) + { + return this.sasTables.GetOrAdd( + original.Name, + name => new TableClient(original.Uri, this.migration.GetCredential('t', name), this.sasTableOptions)); + } + + public BlobContainerClient GetBlobContainerClient(BlobContainerClient original) + { + return this.sasContainers.GetOrAdd( + original.Name, + name => new BlobContainerClient(original.Uri, this.migration.GetCredential('b', name), this.sasBlobOptions)); + } + + public BlockBlobClient GetBlockBlobClient(BlockBlobClient original) + { + return this.GetBlobContainerClient( + this.blobClient.GetBlobContainerClient(original.BlobContainerName)).GetBlockBlobClient(original.Name); + } + + public override Blob GetBlobReference(string container, string blobName) + { + return new MigratingBlob(this, this.blobClient, container, blobName); + } + + internal override Blob GetBlobReference(Uri blobUri) + { + return new MigratingBlob(this, this.blobClient, blobUri); + } + + public override BlobContainer GetBlobContainerReference(string container) + { + return new MigratingBlobContainer(this, this.blobClient, container); + } + + public override Queue GetQueueReference(string queueName) + { + return new MigratingQueue(this, this.queueClient, queueName); + } + + public override Table GetTableReference(string tableName) + { + return new MigratingTable(this, this.tableClient, tableName); + } + + static TOptions CreateMigrationOptions( + IStorageServiceClientProvider provider, + TOptions managementOptions) + where TOptions : ClientOptions + { + TOptions options = provider.CreateFreshOptions(); + if (ReferenceEquals(options, managementOptions)) + { + throw new InvalidOperationException("Migration requires fresh client options. Use an options factory that returns a new options object on every call."); + } + + // Disable distributed tracing by default to reduce the noise in the traces. + options.Diagnostics.IsDistributedTracingEnabled = false; + + // Disable SDK retries so that migration can rely on a strict deadline per request. + // Authentication failures still get one refresh and retry. + options.RetryPolicy = null; + options.Retry.MaxRetries = 0; + return options; + } + } +} diff --git a/src/DurableTask.AzureStorage/Storage/MigratingBlob.cs b/src/DurableTask.AzureStorage/Storage/MigratingBlob.cs new file mode 100644 index 00000000..f52e06c1 --- /dev/null +++ b/src/DurableTask.AzureStorage/Storage/MigratingBlob.cs @@ -0,0 +1,149 @@ +// ---------------------------------------------------------------------------------- +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +#nullable enable +namespace DurableTask.AzureStorage.Storage +{ + using System; + using System.IO; + using System.Threading; + using System.Threading.Tasks; + using Azure.Storage.Blobs; + using Azure.Storage.Blobs.Models; + using Azure.Storage.Blobs.Specialized; + + sealed class MigratingBlob : Blob + { + readonly MigratingAzureStorageClient azureStorageClient; + BlockBlobClient? cachedClient; + + protected override BlockBlobClient Client => Volatile.Read(ref this.cachedClient) + ?? LazyInitializer.EnsureInitialized(ref this.cachedClient, () => this.azureStorageClient.GetBlockBlobClient(base.Client))!; + + public MigratingBlob( + MigratingAzureStorageClient azureStorageClient, + BlobServiceClient blobServiceClient, + string containerName, + string blobName) + : base(blobServiceClient, containerName, blobName) + { + this.azureStorageClient = azureStorageClient; + } + + public MigratingBlob( + MigratingAzureStorageClient azureStorageClient, + BlobServiceClient blobServiceClient, + Uri blobUri) + : base(blobServiceClient, blobUri) + { + this.azureStorageClient = azureStorageClient; + } + + public async override Task ExistsAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.ExistsAsync(cancellationToken).ConfigureAwait(false); + } + + public async override Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.DeleteIfExistsAsync(cancellationToken).ConfigureAwait(false); + } + + public async override Task IsLeasedAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.IsLeasedAsync(cancellationToken).ConfigureAwait(false); + } + + public async override Task UploadTextAsync( + string content, + string? leaseId = null, + bool ifDoesntExist = false, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.UploadTextAsync(content, leaseId, ifDoesntExist, cancellationToken).ConfigureAwait(false); + } + + public async override Task UploadFromByteArrayAsync( + byte[] buffer, + int index, + int byteCount, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.UploadFromByteArrayAsync(buffer, index, byteCount, cancellationToken).ConfigureAwait(false); + } + + public async override Task OpenWriteAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.OpenWriteAsync(cancellationToken).ConfigureAwait(false); + } + + public async override Task DownloadTextAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.DownloadTextAsync(cancellationToken).ConfigureAwait(false); + } + + public async override Task DownloadToStreamAsync( + MemoryStream target, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.DownloadToStreamAsync(target, cancellationToken).ConfigureAwait(false); + } + + public async override Task DownloadStreamingAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.DownloadStreamingAsync(cancellationToken).ConfigureAwait(false); + } + + public async override Task AcquireLeaseAsync( + TimeSpan leaseInterval, + string leaseId, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.AcquireLeaseAsync(leaseInterval, leaseId, cancellationToken).ConfigureAwait(false); + } + + public async override Task ChangeLeaseAsync( + string proposedLeaseId, + string currentLeaseId, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.ChangeLeaseAsync(proposedLeaseId, currentLeaseId, cancellationToken).ConfigureAwait(false); + } + + public async override Task RenewLeaseAsync( + string leaseId, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.RenewLeaseAsync(leaseId, cancellationToken).ConfigureAwait(false); + } + + public async override Task ReleaseLeaseAsync( + string leaseId, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.ReleaseLeaseAsync(leaseId, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/DurableTask.AzureStorage/Storage/MigratingBlobContainer.cs b/src/DurableTask.AzureStorage/Storage/MigratingBlobContainer.cs new file mode 100644 index 00000000..2df597b0 --- /dev/null +++ b/src/DurableTask.AzureStorage/Storage/MigratingBlobContainer.cs @@ -0,0 +1,77 @@ +// ---------------------------------------------------------------------------------- +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +#nullable enable +namespace DurableTask.AzureStorage.Storage +{ + using System; + using System.Threading; + using System.Threading.Tasks; + using Azure.Storage.Blobs; + + // Existence checks use the original client because our SAS cannot read container properties. + // Paging also keeps the original client to avoid migration checks while listing blobs. + // This is fine because paging does not require any write operations, which are what must be + // strictly gated during migration by SAS access. + sealed class MigratingBlobContainer : BlobContainer + { + readonly MigratingAzureStorageClient azureStorageClient; + + public MigratingBlobContainer( + MigratingAzureStorageClient azureStorageClient, + BlobServiceClient blobServiceClient, + string name) + : base(azureStorageClient, blobServiceClient, name) + { + this.azureStorageClient = azureStorageClient; + } + + public async override Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.CreateIfNotExistsAsync(cancellationToken).ConfigureAwait(false); + } + + public override Task DeleteIfExistsAsync( + string? appLeaseId = null, + CancellationToken cancellationToken = default) + { + return Task.FromException(MigratingAzureStorageClient.ResourceDeletionNotSupported()); + } + + public async override Task AcquireLeaseAsync( + TimeSpan leaseInterval, + string leaseId, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.AcquireLeaseAsync(leaseInterval, leaseId, cancellationToken).ConfigureAwait(false); + } + + public async override Task ChangeLeaseAsync( + string proposedLeaseId, + string currentLeaseId, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.ChangeLeaseAsync(proposedLeaseId, currentLeaseId, cancellationToken).ConfigureAwait(false); + } + + public async override Task RenewLeaseAsync( + string leaseId, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.RenewLeaseAsync(leaseId, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/DurableTask.AzureStorage/Storage/MigratingQueue.cs b/src/DurableTask.AzureStorage/Storage/MigratingQueue.cs new file mode 100644 index 00000000..4fa7d476 --- /dev/null +++ b/src/DurableTask.AzureStorage/Storage/MigratingQueue.cs @@ -0,0 +1,123 @@ +// ---------------------------------------------------------------------------------- +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +#nullable enable +namespace DurableTask.AzureStorage.Storage +{ + using System; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Azure.Storage.Queues; + using Azure.Storage.Queues.Models; + + sealed class MigratingQueue : Queue + { + readonly MigratingAzureStorageClient azureStorageClient; + QueueClient? cachedClient; + + protected override QueueClient Client => Volatile.Read(ref this.cachedClient) + ?? LazyInitializer.EnsureInitialized(ref this.cachedClient, () => this.azureStorageClient.GetQueueClient(base.Client))!; + + public MigratingQueue( + MigratingAzureStorageClient azureStorageClient, + QueueServiceClient queueServiceClient, + string queueName) + : base(azureStorageClient, queueServiceClient, queueName) + { + this.azureStorageClient = azureStorageClient; + } + + public async override Task ExistsAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.ExistsAsync(cancellationToken).ConfigureAwait(false); + } + + public async override Task GetApproximateMessagesCountAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.GetApproximateMessagesCountAsync(cancellationToken).ConfigureAwait(false); + } + + public async override Task AddMessageAsync( + string message, + TimeSpan? visibilityDelay, + Guid? clientRequestId = null, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.AddMessageAsync(message, visibilityDelay, clientRequestId, cancellationToken).ConfigureAwait(false); + } + + public async override Task UpdateMessageAsync( + QueueMessage queueMessage, + TimeSpan visibilityTimeout, + Guid? clientRequestId = null, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.UpdateMessageAsync(queueMessage, visibilityTimeout, clientRequestId, cancellationToken).ConfigureAwait(false); + } + + public async override Task DeleteMessageAsync( + QueueMessage queueMessage, + Guid? clientRequestId = null, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.DeleteMessageAsync(queueMessage, clientRequestId, cancellationToken).ConfigureAwait(false); + } + + public async override Task GetMessageAsync( + TimeSpan visibilityTimeout, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.GetMessageAsync(visibilityTimeout, cancellationToken).ConfigureAwait(false); + } + + public async override Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.CreateIfNotExistsAsync(cancellationToken).ConfigureAwait(false); + } + + public override Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) + { + return Task.FromException(MigratingAzureStorageClient.ResourceDeletionNotSupported()); + } + + public async override Task> GetMessagesAsync( + int batchSize, + TimeSpan visibilityTimeout, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.GetMessagesAsync(batchSize, visibilityTimeout, cancellationToken).ConfigureAwait(false); + } + + public async override Task> PeekMessagesAsync( + int batchSize, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.PeekMessagesAsync(batchSize, cancellationToken).ConfigureAwait(false); + } + + public async override Task PeekMessageAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.PeekMessageAsync(cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/DurableTask.AzureStorage/Storage/MigratingTable.cs b/src/DurableTask.AzureStorage/Storage/MigratingTable.cs new file mode 100644 index 00000000..de4c63c5 --- /dev/null +++ b/src/DurableTask.AzureStorage/Storage/MigratingTable.cs @@ -0,0 +1,126 @@ +// ---------------------------------------------------------------------------------- +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +#nullable enable +namespace DurableTask.AzureStorage.Storage +{ + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Azure; + using Azure.Data.Tables; + + // Existence checks use the original client because our SAS cannot list tables. + // Paging also keeps the original client to avoid migration checks while reading rows. + // This is fine because paging does not require any write operations, which are what must be + // strictly gated during migration by SAS access. + sealed class MigratingTable : Table + { + readonly MigratingAzureStorageClient azureStorageClient; + TableClient? cachedClient; + + protected override TableClient Client => Volatile.Read(ref this.cachedClient) + ?? LazyInitializer.EnsureInitialized(ref this.cachedClient, () => this.azureStorageClient.GetTableClient(base.Client))!; + + public MigratingTable( + MigratingAzureStorageClient azureStorageClient, + TableServiceClient tableServiceClient, + string tableName) + : base(azureStorageClient, tableServiceClient, tableName) + { + this.azureStorageClient = azureStorageClient; + } + + public async override Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.CreateIfNotExistsAsync(cancellationToken).ConfigureAwait(false); + } + + public override Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) + { + return Task.FromException(MigratingAzureStorageClient.ResourceDeletionNotSupported()); + } + + public override Task DeleteAsync(CancellationToken cancellationToken = default) + { + return Task.FromException(MigratingAzureStorageClient.ResourceDeletionNotSupported()); + } + + public async override Task ReplaceEntityAsync( + T tableEntity, + ETag ifMatch, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.ReplaceEntityAsync(tableEntity, ifMatch, cancellationToken).ConfigureAwait(false); + } + + public async override Task DeleteEntityAsync( + T tableEntity, + ETag ifMatch = default, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.DeleteEntityAsync(tableEntity, ifMatch, cancellationToken).ConfigureAwait(false); + } + + public async override Task InsertEntityAsync( + T tableEntity, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.InsertEntityAsync(tableEntity, cancellationToken).ConfigureAwait(false); + } + + public async override Task MergeEntityAsync( + T tableEntity, + ETag ifMatch, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.MergeEntityAsync(tableEntity, ifMatch, cancellationToken).ConfigureAwait(false); + } + + public async override Task InsertOrMergeEntityAsync( + T tableEntity, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.InsertOrMergeEntityAsync(tableEntity, cancellationToken).ConfigureAwait(false); + } + + public async override Task InsertOrReplaceEntityAsync( + T tableEntity, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await base.InsertOrReplaceEntityAsync(tableEntity, cancellationToken).ConfigureAwait(false); + } + + protected async override Task DeleteEntitiesIndividuallyAsync( + List batch, + CancellationToken cancellationToken) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.DeleteEntitiesIndividuallyAsync(batch, cancellationToken).ConfigureAwait(false); + } + + public async override Task ExecuteBatchAsync( + IEnumerable batchOperation, + CancellationToken cancellationToken = default) + { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + return await base.ExecuteBatchAsync(batchOperation, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/DurableTask.AzureStorage/Storage/MigrationSasManager.cs b/src/DurableTask.AzureStorage/Storage/MigrationSasManager.cs index 379c32a9..656d533f 100644 --- a/src/DurableTask.AzureStorage/Storage/MigrationSasManager.cs +++ b/src/DurableTask.AzureStorage/Storage/MigrationSasManager.cs @@ -206,8 +206,12 @@ async Task RefreshKeysAsync(DateTimeOffset serverTime, CancellationToken c TokenCredential? credential = (this.tableProvider as IStorageTokenCredentialProvider)?.TokenCredential; if (credential != null && (this.tableKey == null || this.tableKey.ExpiresOn <= serverTime.AddMinutes(5))) { - TableUserDelegationKey key = await TableUserDelegationKey.GetAsync(this.tableService.Uri, credential, - this.tableProvider.CreateOptions(), serverTime, cancellationToken).ConfigureAwait(false); + TableUserDelegationKey key = await TableUserDelegationKey.GetAsync( + this.tableService.Uri, + credential, + this.tableProvider.CreateFreshOptions(), + serverTime, + cancellationToken).ConfigureAwait(false); lock (this.sync) { this.tableKey = key; diff --git a/src/DurableTask.AzureStorage/Storage/Queue.cs b/src/DurableTask.AzureStorage/Storage/Queue.cs index a3191330..e71d806a 100644 --- a/src/DurableTask.AzureStorage/Storage/Queue.cs +++ b/src/DurableTask.AzureStorage/Storage/Queue.cs @@ -24,14 +24,13 @@ namespace DurableTask.AzureStorage.Storage class Queue { - readonly AzureStorageClient azureStorageClient; readonly AzureStorageOrchestrationServiceStats stats; readonly QueueClient queueClient; + protected virtual QueueClient Client => this.queueClient; public Queue(AzureStorageClient azureStorageClient, QueueServiceClient queueServiceClient, string queueName) { - this.azureStorageClient = azureStorageClient; - this.stats = this.azureStorageClient.Stats; + this.stats = azureStorageClient.Stats; this.queueClient = queueServiceClient.GetQueueClient(queueName); } @@ -39,16 +38,20 @@ public Queue(AzureStorageClient azureStorageClient, QueueServiceClient queueServ public Uri Uri => this.queueClient.Uri; - public async Task GetApproximateMessagesCountAsync(CancellationToken cancellationToken = default) + public async virtual Task GetApproximateMessagesCountAsync(CancellationToken cancellationToken = default) { - QueueProperties properties = await this.queueClient.GetPropertiesAsync(cancellationToken).DecorateFailure(); + QueueProperties properties = await this.Client.GetPropertiesAsync(cancellationToken).DecorateFailure(); return properties.ApproximateMessagesCount; } - public async Task AddMessageAsync(string message, TimeSpan? visibilityDelay, Guid? clientRequestId = null, CancellationToken cancellationToken = default) + public async virtual Task AddMessageAsync( + string message, + TimeSpan? visibilityDelay, + Guid? clientRequestId = null, + CancellationToken cancellationToken = default) { using IDisposable scope = OperationContext.CreateClientRequestScope(clientRequestId); - await this.queueClient + await this.Client .SendMessageAsync( message, visibilityDelay, @@ -59,10 +62,14 @@ await this.queueClient this.stats.MessagesSent.Increment(); } - public async Task UpdateMessageAsync(QueueMessage queueMessage, TimeSpan visibilityTimeout, Guid? clientRequestId = null, CancellationToken cancellationToken = default) + public async virtual Task UpdateMessageAsync( + QueueMessage queueMessage, + TimeSpan visibilityTimeout, + Guid? clientRequestId = null, + CancellationToken cancellationToken = default) { using IDisposable scope = OperationContext.CreateClientRequestScope(clientRequestId); - UpdateReceipt receipt = await this.queueClient + UpdateReceipt receipt = await this.Client .UpdateMessageAsync( queueMessage.MessageId, queueMessage.PopReceipt, @@ -74,10 +81,13 @@ public async Task UpdateMessageAsync(QueueMessage queueMessage, T return receipt; } - public async Task DeleteMessageAsync(QueueMessage queueMessage, Guid? clientRequestId = null, CancellationToken cancellationToken = default) + public async virtual Task DeleteMessageAsync( + QueueMessage queueMessage, + Guid? clientRequestId = null, + CancellationToken cancellationToken = default) { using IDisposable scope = OperationContext.CreateClientRequestScope(clientRequestId); - await this.queueClient + await this.Client .DeleteMessageAsync( queueMessage.MessageId, queueMessage.PopReceipt, @@ -87,9 +97,11 @@ await this.queueClient this.stats.MessagesUpdated.Increment(); } - public async Task GetMessageAsync(TimeSpan visibilityTimeout, CancellationToken cancellationToken = default) + public async virtual Task GetMessageAsync( + TimeSpan visibilityTimeout, + CancellationToken cancellationToken = default) { - QueueMessage message = await this.queueClient.ReceiveMessageAsync(visibilityTimeout, cancellationToken).DecorateFailure(); + QueueMessage message = await this.Client.ReceiveMessageAsync(visibilityTimeout, cancellationToken).DecorateFailure(); if (message == null) { @@ -100,40 +112,45 @@ await this.queueClient return message; } - public async Task ExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task ExistsAsync(CancellationToken cancellationToken = default) { - return await this.queueClient.ExistsAsync(cancellationToken).DecorateFailure(); + return await this.Client.ExistsAsync(cancellationToken).DecorateFailure(); } - public async Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { // If we received null, then the response must have been a 409 (Conflict) and the queue must already exist Response response = await this.queueClient.CreateIfNotExistsAsync(cancellationToken: cancellationToken).DecorateFailure(); return response != null; } - public async Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) { - return await this.queueClient.DeleteIfExistsAsync(cancellationToken).DecorateFailure(); + return await this.Client.DeleteIfExistsAsync(cancellationToken).DecorateFailure(); } - public async Task> GetMessagesAsync(int batchSize, TimeSpan visibilityTimeout, CancellationToken cancellationToken = default) + public async virtual Task> GetMessagesAsync( + int batchSize, + TimeSpan visibilityTimeout, + CancellationToken cancellationToken = default) { - QueueMessage[] messages = await this.queueClient.ReceiveMessagesAsync(batchSize, visibilityTimeout, cancellationToken).DecorateFailure(); + QueueMessage[] messages = await this.Client.ReceiveMessagesAsync(batchSize, visibilityTimeout, cancellationToken).DecorateFailure(); this.stats.MessagesRead.Increment(messages.Length); return messages; } - public async Task> PeekMessagesAsync(int batchSize, CancellationToken cancellationToken = default) + public async virtual Task> PeekMessagesAsync( + int batchSize, + CancellationToken cancellationToken = default) { - PeekedMessage[] messages = await this.queueClient.PeekMessagesAsync(batchSize, cancellationToken).DecorateFailure(); + PeekedMessage[] messages = await this.Client.PeekMessagesAsync(batchSize, cancellationToken).DecorateFailure(); this.stats.MessagesRead.Increment(messages.Length); return messages; } - public async Task PeekMessageAsync(CancellationToken cancellationToken = default) + public async virtual Task PeekMessageAsync(CancellationToken cancellationToken = default) { - return await this.queueClient.PeekMessageAsync(cancellationToken).DecorateFailure(); + return await this.Client.PeekMessageAsync(cancellationToken).DecorateFailure(); } } } diff --git a/src/DurableTask.AzureStorage/Storage/Table.cs b/src/DurableTask.AzureStorage/Storage/Table.cs index ebe98065..8fac2012 100644 --- a/src/DurableTask.AzureStorage/Storage/Table.cs +++ b/src/DurableTask.AzureStorage/Storage/Table.cs @@ -28,15 +28,14 @@ class Table { const int MaxParallelBatchDeletes = 10; - readonly AzureStorageClient azureStorageClient; readonly AzureStorageOrchestrationServiceStats stats; readonly TableServiceClient tableServiceClient; readonly TableClient tableClient; + protected virtual TableClient Client => this.tableClient; public Table(AzureStorageClient azureStorageClient, TableServiceClient tableServiceClient, string tableName) { - this.azureStorageClient = azureStorageClient; - this.stats = this.azureStorageClient.Stats; + this.stats = azureStorageClient.Stats; this.tableServiceClient = tableServiceClient; this.tableClient = tableServiceClient.GetTableClient(tableName); @@ -46,17 +45,17 @@ public Table(AzureStorageClient azureStorageClient, TableServiceClient tableServ internal Uri Uri => this.tableClient.Uri; - public async Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { // If we received null, then the response must have been a 409 (Conflict) and the table must already exist Response response = await this.tableClient.CreateIfNotExistsAsync(cancellationToken).DecorateFailure(); return response != null; } - public async Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) { // If we received null, then the response must have been a 404 (NotFound) and the table must not exist - Response response = await this.tableClient.DeleteAsync(cancellationToken).DecorateFailure(); + Response response = await this.Client.DeleteAsync(cancellationToken).DecorateFailure(); return response != null; } @@ -64,53 +63,68 @@ public async Task ExistsAsync(CancellationToken cancellationToken = defaul { // TODO: Re-evaluate the use of an "Exists" method as it was intentional omitted from the client API List tables = await this.tableServiceClient - .QueryAsync(filter: $"TableName eq '{this.tableClient.Name}'", cancellationToken: cancellationToken) + .QueryAsync(filter: $"TableName eq '{this.Name}'", cancellationToken: cancellationToken) .DecorateFailure() .ToListAsync(cancellationToken); return tables.Count > 0; } - public async Task DeleteAsync(CancellationToken cancellationToken = default) + public async virtual Task DeleteAsync(CancellationToken cancellationToken = default) { - await this.tableClient.DeleteAsync(cancellationToken).DecorateFailure(); + await this.Client.DeleteAsync(cancellationToken).DecorateFailure(); } - public async Task ReplaceEntityAsync(T tableEntity, ETag ifMatch, CancellationToken cancellationToken = default) where T : ITableEntity + public async virtual Task ReplaceEntityAsync( + T tableEntity, + ETag ifMatch, + CancellationToken cancellationToken = default) where T : ITableEntity { - await this.tableClient.UpdateEntityAsync(tableEntity, ifMatch, TableUpdateMode.Replace, cancellationToken).DecorateFailure(); + await this.Client.UpdateEntityAsync(tableEntity, ifMatch, TableUpdateMode.Replace, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); } - public async Task DeleteEntityAsync(T tableEntity, ETag ifMatch = default, CancellationToken cancellationToken = default) where T : ITableEntity + public async virtual Task DeleteEntityAsync( + T tableEntity, + ETag ifMatch = default, + CancellationToken cancellationToken = default) where T : ITableEntity { - await this.tableClient.DeleteEntityAsync(tableEntity.PartitionKey, tableEntity.RowKey, ifMatch, cancellationToken).DecorateFailure(); + await this.Client.DeleteEntityAsync(tableEntity.PartitionKey, tableEntity.RowKey, ifMatch, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); } - public async Task InsertEntityAsync(T tableEntity, CancellationToken cancellationToken = default) where T : ITableEntity + public async virtual Task InsertEntityAsync( + T tableEntity, + CancellationToken cancellationToken = default) where T : ITableEntity { - Response result = await this.tableClient.AddEntityAsync(tableEntity, cancellationToken).DecorateFailure(); + Response result = await this.Client.AddEntityAsync(tableEntity, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); return result; } - public async Task MergeEntityAsync(T tableEntity, ETag ifMatch, CancellationToken cancellationToken = default) where T : ITableEntity + public async virtual Task MergeEntityAsync( + T tableEntity, + ETag ifMatch, + CancellationToken cancellationToken = default) where T : ITableEntity { - Response result = await this.tableClient.UpdateEntityAsync(tableEntity, ifMatch, TableUpdateMode.Merge, cancellationToken).DecorateFailure(); + Response result = await this.Client.UpdateEntityAsync(tableEntity, ifMatch, TableUpdateMode.Merge, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); return result; } - public async Task InsertOrMergeEntityAsync(T tableEntity, CancellationToken cancellationToken = default) where T : ITableEntity + public async virtual Task InsertOrMergeEntityAsync( + T tableEntity, + CancellationToken cancellationToken = default) where T : ITableEntity { - await this.tableClient.UpsertEntityAsync(tableEntity, TableUpdateMode.Merge, cancellationToken).DecorateFailure(); + await this.Client.UpsertEntityAsync(tableEntity, TableUpdateMode.Merge, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); } - public async Task InsertOrReplaceEntityAsync(T tableEntity, CancellationToken cancellationToken = default) where T : ITableEntity + public async virtual Task InsertOrReplaceEntityAsync( + T tableEntity, + CancellationToken cancellationToken = default) where T : ITableEntity { - await this.tableClient.UpsertEntityAsync(tableEntity, TableUpdateMode.Replace, cancellationToken).DecorateFailure(); + await this.Client.UpsertEntityAsync(tableEntity, TableUpdateMode.Replace, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); } @@ -217,7 +231,7 @@ async Task ExecuteBatchWithFallbackAsync( } } - async Task DeleteEntitiesIndividuallyAsync( + protected async virtual Task DeleteEntitiesIndividuallyAsync( List batch, CancellationToken cancellationToken) { @@ -230,7 +244,7 @@ async Task DeleteEntitiesIndividuallyAsync( requestCount++; try { - Response response = await this.tableClient.DeleteEntityAsync( + Response response = await this.Client.DeleteEntityAsync( action.Entity.PartitionKey, action.Entity.RowKey, action.Entity.ETag, @@ -296,11 +310,13 @@ async Task ExecuteBatchAsync( return resultsBuilder.ToResults(); } - public async Task ExecuteBatchAsync(IEnumerable batchOperation, CancellationToken cancellationToken = default) + public async virtual Task ExecuteBatchAsync( + IEnumerable batchOperation, + CancellationToken cancellationToken = default) { var stopwatch = new Stopwatch(); - Response> response = await this.tableClient.SubmitTransactionAsync(batchOperation, cancellationToken).DecorateFailure(); + Response> response = await this.Client.SubmitTransactionAsync(batchOperation, cancellationToken).DecorateFailure(); IReadOnlyList batchResults = response.Value; stopwatch.Stop(); diff --git a/src/DurableTask.AzureStorage/Storage/TableUserDelegationKey.cs b/src/DurableTask.AzureStorage/Storage/TableUserDelegationKey.cs index d7443943..4f9d200b 100644 --- a/src/DurableTask.AzureStorage/Storage/TableUserDelegationKey.cs +++ b/src/DurableTask.AzureStorage/Storage/TableUserDelegationKey.cs @@ -77,15 +77,10 @@ public static async Task GetAsync(Uri endpoint, TokenCre : audience.ToString().TrimEnd('/'); string scope = resource.EndsWith("/.default", StringComparison.OrdinalIgnoreCase) ? resource : resource + "/.default"; - // Workload options may contain the SAS fence policy. Key acquisition has its own authenticated - // pipeline and cannot depend on an existing, unexpired workload SAS. - var keyOptions = new TableClientOptions { Transport = options.Transport }; - keyOptions.Retry.Mode = options.Retry.Mode; - keyOptions.Retry.Delay = options.Retry.Delay; - keyOptions.Retry.MaxDelay = options.Retry.MaxDelay; - keyOptions.Retry.MaxRetries = options.Retry.MaxRetries; - keyOptions.Retry.NetworkTimeout = options.Retry.NetworkTimeout; - HttpPipeline pipeline = HttpPipelineBuilder.Build(keyOptions, new BearerTokenAuthenticationPolicy(credential, scope)); + + // These fresh options keep the provider's settings without the migration SAS checks. + // Fetching a delegation key must work before a SAS is available. + HttpPipeline pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, scope)); using HttpMessage message = pipeline.CreateMessage(); message.Request.Method = RequestMethod.Post; message.Request.Uri.Reset(new Uri(endpoint, "?restype=service&comp=userdelegationkey")); diff --git a/src/DurableTask.AzureStorage/StorageServiceClientProvider.cs b/src/DurableTask.AzureStorage/StorageServiceClientProvider.cs index 9c20fe70..57304fa1 100644 --- a/src/DurableTask.AzureStorage/StorageServiceClientProvider.cs +++ b/src/DurableTask.AzureStorage/StorageServiceClientProvider.cs @@ -32,7 +32,7 @@ public static class StorageServiceClientProvider /// Creates an for the Azure Blob Storage service. /// /// An Azure Storage connection string for the blob service. - /// An optional set of client options. + /// An optional set of shared client options. /// An Azure Blob Storage service client whose connection is based on the given . /// /// is or consists entirely of white space characters. @@ -46,7 +46,28 @@ public static IStorageServiceClientProvider( o => new BlobServiceClient(connectionString, o), - options ?? new BlobClientOptions()); + () => options ?? new BlobClientOptions(), + sharedOptions: options ?? new BlobClientOptions()); + } + + /// + /// Creates a blob client provider with fresh options for each client. + /// + /// An Azure Storage connection string. + /// Creates a new, configured options object on every call. + /// The client provider. + public static IStorageServiceClientProvider ForBlobWithOptionsFactory( + string connectionString, + Func optionsFactory) + { + if (string.IsNullOrEmpty(connectionString)) + { + throw new ArgumentNullException(nameof(connectionString)); + } + + return new DefaultStorageServiceClientProvider( + o => new BlobServiceClient(connectionString, o), + optionsFactory); } /// @@ -54,7 +75,7 @@ public static IStorageServiceClientProvider /// An Azure Storage account name. /// A token credential for accessing the service. - /// An optional set of client options. + /// An optional set of shared client options. /// An Azure Blob Storage service client whose connection is based on the given . /// /// @@ -71,12 +92,27 @@ public static IStorageServiceClientProvider + /// Creates a blob client provider with fresh options for each client. + /// + /// An Azure Storage account name. + /// The credential for accessing the service. + /// Creates a new, configured options object on every call. + /// The client provider. + public static IStorageServiceClientProvider ForBlobWithOptionsFactory( + string accountName, + TokenCredential tokenCredential, + Func optionsFactory) + { + return ForBlobWithOptionsFactory(CreateDefaultServiceUri(accountName, "blob"), tokenCredential, optionsFactory); + } + /// /// Creates an for the Azure Blob Storage service. /// /// An Azure Blob Storage service URI. /// A token credential for accessing the service. - /// An optional set of client options. + /// An optional set of shared client options. /// An Azure Blob Storage service client whose connection is based on the given . /// /// or is . @@ -93,7 +129,32 @@ public static IStorageServiceClientProvider( o => new BlobServiceClient(serviceUri, tokenCredential, o), - options ?? new BlobClientOptions(), tokenCredential); + () => options ?? new BlobClientOptions(), + tokenCredential, + sharedOptions: options ?? new BlobClientOptions()); + } + + /// + /// Creates a blob client provider with fresh options for each client. + /// + /// The service URI. + /// The credential for accessing the service. + /// Creates a new, configured options object on every call. + /// The client provider. + public static IStorageServiceClientProvider ForBlobWithOptionsFactory( + Uri serviceUri, + TokenCredential tokenCredential, + Func optionsFactory) + { + if (tokenCredential == null) + { + throw new ArgumentNullException(nameof(tokenCredential)); + } + + return new DefaultStorageServiceClientProvider( + o => new BlobServiceClient(serviceUri, tokenCredential, o), + optionsFactory, + tokenCredential); } #endregion @@ -104,7 +165,7 @@ public static IStorageServiceClientProvider for the Azure Queue Storage service. /// /// An Azure Storage connection string for the queue service. - /// An optional set of client options. + /// An optional set of shared client options. /// An Azure Queue Storage service client whose connection is based on the given . /// /// is or consists entirely of white space characters. @@ -118,7 +179,28 @@ public static IStorageServiceClientProvider( o => new QueueServiceClient(connectionString, o), - options ?? new QueueClientOptions()); + () => options ?? new QueueClientOptions(), + sharedOptions: options ?? new QueueClientOptions()); + } + + /// + /// Creates a queue client provider with fresh options for each client. + /// + /// An Azure Storage connection string. + /// Creates a new, configured options object on every call. + /// The client provider. + public static IStorageServiceClientProvider ForQueueWithOptionsFactory( + string connectionString, + Func optionsFactory) + { + if (string.IsNullOrEmpty(connectionString)) + { + throw new ArgumentNullException(nameof(connectionString)); + } + + return new DefaultStorageServiceClientProvider( + o => new QueueServiceClient(connectionString, o), + optionsFactory); } /// @@ -126,7 +208,7 @@ public static IStorageServiceClientProvider /// An Azure Storage account name. /// A token credential for accessing the service. - /// An optional set of client options. + /// An optional set of shared client options. /// An Azure Queue Storage service client whose connection is based on the given . /// /// @@ -143,12 +225,27 @@ public static IStorageServiceClientProvider + /// Creates a queue client provider with fresh options for each client. + /// + /// An Azure Storage account name. + /// The credential for accessing the service. + /// Creates a new, configured options object on every call. + /// The client provider. + public static IStorageServiceClientProvider ForQueueWithOptionsFactory( + string accountName, + TokenCredential tokenCredential, + Func optionsFactory) + { + return ForQueueWithOptionsFactory(CreateDefaultServiceUri(accountName, "queue"), tokenCredential, optionsFactory); + } + /// /// Creates an for the Azure Queue Storage service. /// /// An Azure Queue Storage service URI. /// A token credential for accessing the service. - /// An optional set of client options. + /// An optional set of shared client options. For custom migration settings, use ForQueueWithOptionsFactory instead. /// An Azure Queue Storage service client whose connection is based on the given . /// /// or is . @@ -165,7 +262,32 @@ public static IStorageServiceClientProvider( o => new QueueServiceClient(serviceUri, tokenCredential, o), - options ?? new QueueClientOptions(), tokenCredential); + () => options ?? new QueueClientOptions(), + tokenCredential, + sharedOptions: options ?? new QueueClientOptions()); + } + + /// + /// Creates a queue client provider with fresh options for each client. + /// + /// The service URI. + /// The credential for accessing the service. + /// Creates a new, configured options object on every call. + /// The client provider. + public static IStorageServiceClientProvider ForQueueWithOptionsFactory( + Uri serviceUri, + TokenCredential tokenCredential, + Func optionsFactory) + { + if (tokenCredential == null) + { + throw new ArgumentNullException(nameof(tokenCredential)); + } + + return new DefaultStorageServiceClientProvider( + o => new QueueServiceClient(serviceUri, tokenCredential, o), + optionsFactory, + tokenCredential); } #endregion @@ -176,7 +298,7 @@ public static IStorageServiceClientProvider for the Azure Table Storage service. /// /// An Azure Storage connection string for the table service. - /// An optional set of client options. + /// An optional set of shared client options. /// An Azure Table Storage service client whose connection is based on the given . /// /// is or consists entirely of white space characters. @@ -190,7 +312,28 @@ public static IStorageServiceClientProvider( o => new TableServiceClient(connectionString, o), - options ?? new TableClientOptions()); + () => options ?? new TableClientOptions(), + sharedOptions: options ?? new TableClientOptions()); + } + + /// + /// Creates a table client provider with fresh options for each client. + /// + /// An Azure Storage connection string. + /// Creates a new, configured options object on every call. + /// The client provider. + public static IStorageServiceClientProvider ForTableWithOptionsFactory( + string connectionString, + Func optionsFactory) + { + if (string.IsNullOrEmpty(connectionString)) + { + throw new ArgumentNullException(nameof(connectionString)); + } + + return new DefaultStorageServiceClientProvider( + o => new TableServiceClient(connectionString, o), + optionsFactory); } /// @@ -198,7 +341,7 @@ public static IStorageServiceClientProvider /// An Azure Storage account name. /// A token credential for accessing the service. - /// An optional set of client options. + /// An optional set of shared client options. /// An Azure Table Storage service client whose connection is based on the given . /// /// @@ -215,12 +358,27 @@ public static IStorageServiceClientProvider + /// Creates a table client provider with fresh options for each client. + /// + /// An Azure Storage account name. + /// The credential for accessing the service. + /// Creates a new, configured options object on every call. + /// The client provider. + public static IStorageServiceClientProvider ForTableWithOptionsFactory( + string accountName, + TokenCredential tokenCredential, + Func optionsFactory) + { + return ForTableWithOptionsFactory(CreateDefaultServiceUri(accountName, "table"), tokenCredential, optionsFactory); + } + /// /// Creates an for the Azure Table Storage service. /// /// An Azure Table Storage service URI. /// A token credential for accessing the service. - /// An optional set of client options. + /// An optional set of shared client options. /// An Azure Table Storage service client whose connection is based on the given . /// /// or is . @@ -237,11 +395,44 @@ public static IStorageServiceClientProvider( o => new TableServiceClient(serviceUri, tokenCredential, o), - options ?? new TableClientOptions(), tokenCredential); + () => options ?? new TableClientOptions(), + tokenCredential, + sharedOptions: options ?? new TableClientOptions()); + } + + /// + /// Creates a table client provider with fresh options for each client. + /// + /// The service URI. + /// The credential for accessing the service. + /// Creates a new, configured options object on every call. + /// The client provider. + public static IStorageServiceClientProvider ForTableWithOptionsFactory( + Uri serviceUri, + TokenCredential tokenCredential, + Func optionsFactory) + { + if (tokenCredential == null) + { + throw new ArgumentNullException(nameof(tokenCredential)); + } + + return new DefaultStorageServiceClientProvider( + o => new TableServiceClient(serviceUri, tokenCredential, o), + optionsFactory, + tokenCredential); } #endregion + internal static TOptions CreateFreshOptions(this IStorageServiceClientProvider provider) + where TOptions : ClientOptions + { + return provider is DefaultStorageServiceClientProvider defaults + ? defaults.CreateFreshOptions() + : provider.CreateOptions(); + } + static Uri CreateDefaultServiceUri(string accountName, string service) { if (string.IsNullOrWhiteSpace(accountName)) diff --git a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs index 4b1113f4..c9f2cbd4 100644 --- a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs +++ b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs @@ -3052,7 +3052,10 @@ private static async Task ValidateLargeMessageBlobUrlAsync(string taskHubName, s Assert.IsTrue(value.EndsWith(".json.gz")); string blobName = value.Split('/').Last(); - Assert.IsTrue(await new Blob(serviceClient, new Uri(value)).ExistsAsync(), $"Blob named {blobName} is expected to exist."); + BlobUriBuilder blobUri = new(new Uri(value)); + Assert.IsTrue( + await serviceClient.GetBlobContainerClient(blobUri.BlobContainerName).GetBlobClient(blobUri.BlobName).ExistsAsync(), + $"Blob named {blobName} is expected to exist."); string containerName = $"{taskHubName.ToLowerInvariant()}-largemessages"; BlobContainerClient container = serviceClient.GetBlobContainerClient(containerName); diff --git a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs index 6fb93d91..3ade3cf6 100644 --- a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs +++ b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs @@ -1,4 +1,4 @@ -// ---------------------------------------------------------------------------------- +// ---------------------------------------------------------------------------------- // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ namespace DurableTask.AzureStorage.Tests using System.Linq; using System.Net; using System.Net.Http; + using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -28,7 +29,9 @@ namespace DurableTask.AzureStorage.Tests using Azure.Core; using Azure.Core.Pipeline; using Azure.Data.Tables; + using Azure.Storage; using Azure.Storage.Blobs; + using Azure.Storage.Blobs.Models; using Azure.Storage.Queues; using DurableTask.AzureStorage.Http; using DurableTask.AzureStorage.Storage; @@ -551,6 +554,634 @@ public async Task Requests_CancellationPreventsAuthenticationRetry(bool synchron Assert.AreEqual(1, storage.Workload.Count); } + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task StorageClients_CachedWrappersRenewAndStopAfterDrain(bool sharedKey) + { + using StorageResponses storage = new(sharedKey); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); + Func[] writes = CachedWrites(client); + int ending = 0; + client.MigrationEnding += () => ending++; + try + { + // 1. The first data request initializes migration without service startup. + foreach (Func write in writes) + { + await write(); + } + await client.StopMigrationTokenRefreshAsync(); + DateTimeOffset firstExpiry = storage.Expiry; + Assert.AreEqual(sharedKey ? 0 : 3, storage.KeyRequests); + Assert.IsTrue(storage.Workload.All(uri => DateTimeOffset.Parse(Query(uri.Query)["se"]) == firstExpiry)); + + // 2. The same wrappers use renewed credentials without fetching more keys. + storage.ServerTime = firstExpiry.AddSeconds(1); + await client.InitializeMigrationAsync(refresh: true); + await client.StopMigrationTokenRefreshAsync(); + storage.Workload.Clear(); + foreach (Func write in writes) + { + await write(); + } + Assert.AreEqual(sharedKey ? 0 : 3, storage.KeyRequests); + Assert.IsTrue(storage.Expiry > firstExpiry); + Assert.IsTrue(storage.Workload.All(uri => DateTimeOffset.Parse(Query(uri.Query)["se"]) == storage.Expiry)); + + // 3. Cached wrappers stop before sending after the client observes migration ending. + await storage.EndAsync(); + await client.InitializeMigrationAsync(refresh: true); + int sent = storage.Workload.Count; + foreach (Func write in writes) + { + await Assert.ThrowsExceptionAsync(write); + } + Assert.AreEqual(sent, storage.Workload.Count); + Assert.IsTrue(client.IsMigrationEnding); + Assert.AreEqual(1, ending); + } + finally + { + await client.StopMigrationTokenRefreshAsync(); + } + } + + [DataTestMethod] + [DataRow(false, false)] + [DataRow(true, false)] + [DataRow(false, true)] + [DataRow(true, true)] + [Timeout(15000)] + public async Task StorageClients_StopWaitsForInitializationOrRestart(bool restart, bool failRefresh) + { + using StorageResponses storage = new(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); + if (restart) + { + await client.InitializeMigrationAsync(); + await client.StopMigrationTokenRefreshAsync(); + storage.ServerTime = storage.Expiry.AddSeconds(1); + } + + // 1. Hold initialization or restart inside a storage read. + TaskCompletionSource started = new(TaskCreationOptions.RunContinuationsAsynchronously); + TaskCompletionSource release = new(TaskCreationOptions.RunContinuationsAsynchronously); + storage.AfterRead = async _ => + { + started.SetResult(true); + await release.Task; + if (failRefresh) + { + throw new InvalidOperationException("Initialization failed."); + } + }; + Task initialization = client.InitializeMigrationAsync(refresh: restart); + try + { + await started.Task; + + // 2. Stop waits even when the renewal loop has not started yet. + Task stopping = client.StopMigrationTokenRefreshAsync(); + Task repeatedStop = client.StopMigrationTokenRefreshAsync(); + Assert.IsFalse(stopping.IsCompleted); + Assert.IsFalse(repeatedStop.IsCompleted); + release.SetResult(true); + if (failRefresh) + { + await Assert.ThrowsExceptionAsync(() => initialization); + } + else + { + await initialization; + } + await Task.WhenAll(stopping, repeatedStop); + + // 3. After stop, a later explicit restart still works. + int reads = storage.GateReads; + await client.InitializeMigrationAsync(refresh: true); + Assert.IsTrue(storage.GateReads > reads); + } + finally + { + release.TrySetResult(true); + try + { + await initialization; + } + catch (InvalidOperationException) when (failRefresh) { } + await client.StopMigrationTokenRefreshAsync(); + } + } + + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task StorageClients_OptionsFactoryPreservesPoliciesWithoutSharingMigrationSettings(bool sharedKey) + { + // 1. Configure a policy that must run exactly once on each request. + using StorageResponses storage = new( + sharedKey: sharedKey, + retries: 1, + configureOptions: options => options.AddPolicy(new OptionsHeaderPolicy(), HttpPipelinePosition.PerCall)); + int requests = 0; + storage.BeforeWorkload = request => + { + Assert.AreEqual("x", request.Headers.GetValues("x-options-policy").Single()); + requests++; + }; + MigratingAzureStorageClient migrating = storage.CreateMigratingClient(); + try + { + // 2. All three SAS clients retain the provider's custom policy. + foreach (Func write in CachedWrites(migrating).Take(3)) + { + await write(); + } + Assert.AreEqual(3, requests); + await migrating.StopMigrationTokenRefreshAsync(); + await storage.EndAsync(); + await migrating.InitializeMigrationAsync(refresh: true); + + // 3. The same provider still creates ordinary clients that retry and ignore the closed gate. + storage.RequireSasAuthentication = false; + storage.WorkloadFailures = 1; + storage.WorkloadFailureStatus = HttpStatusCode.ServiceUnavailable; + storage.WorkloadFailureCode = "ServerBusy"; + int gateReads = storage.GateReads; + int keyRequests = storage.KeyRequests; + storage.FailReads = true; + storage.FailKeys = true; + AzureStorageClient ordinary = storage.CreateClient(migrating: false); + foreach (Func write in CachedWrites(ordinary).Take(3)) + { + await write(); + } + Assert.AreEqual(7, requests); + Assert.AreEqual(gateReads, storage.GateReads); + Assert.AreEqual(keyRequests, storage.KeyRequests); + Assert.IsTrue(storage.Workload.Skip(3).All(uri => !Query(uri.Query).ContainsKey("timeout"))); + Assert.IsTrue(storage.Workload.Skip(3).All(uri => !Query(uri.Query).ContainsKey("sig"))); + } + finally + { + await migrating.StopMigrationTokenRefreshAsync(); + } + } + + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task StorageClients_BatchDeleteFallbackUsesMigrationAccess(bool ending) + { + // 1. Force a batch delete to fall back to individual deletes. + using StorageResponses storage = new() + { + WorkloadFailures = 1, + WorkloadFailureStatus = HttpStatusCode.NotFound, + WorkloadFailureCode = "ResourceNotFound", + }; + MigratingAzureStorageClient client = storage.CreateMigratingClient(); + Table table = client.GetTableReference("Workload"); + TableEntity[] entities = + { + new("partition", "first"), + new("partition", "second"), + }; + try + { + if (ending) + { + storage.BeforeWorkloadFailure = async () => + { + await storage.EndAsync(); + await client.InitializeMigrationAsync(refresh: true); + }; + } + + // 2. Fallback deletes use SAS and stop if migration has ended. + if (ending) + { + await Assert.ThrowsExceptionAsync( + () => table.DeleteBatchParallelAsync(entities)); + Assert.AreEqual(1, storage.Workload.Count); + } + else + { + TableTransactionResults result = await table.DeleteBatchParallelAsync(entities); + Assert.AreEqual(2, result.Responses.Count); + Assert.AreEqual(3, storage.Workload.Count); + } + + Assert.IsTrue(storage.Workload.All(uri => Query(uri.Query).ContainsKey("sig"))); + } + finally + { + await client.StopMigrationTokenRefreshAsync(); + } + } + + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task StorageClients_FailedInitializationCanBeRetried(bool missingGate) + { + using StorageResponses storage = new(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); + JObject gate = storage.Row!; + storage.Row = missingGate ? null : gate; + storage.FailKeys = !missingGate; + try + { + // 1. Initialization failure blocks data requests. + if (missingGate) + { + await Assert.ThrowsExceptionAsync(() => client.InitializeMigrationAsync()); + } + else + { + await Assert.ThrowsExceptionAsync(() => client.InitializeMigrationAsync()); + } + Assert.AreEqual(0, storage.Workload.Count); + + // 2. The same client can retry after the problem is resolved. + storage.Row = gate; + storage.FailKeys = false; + await CachedWrites(client)[0](); + Assert.AreEqual(1, storage.Workload.Count); + Assert.IsTrue(Query(storage.Workload[0].Query).ContainsKey("sig")); + } + finally + { + await client.StopMigrationTokenRefreshAsync(); + } + } + + [TestMethod] + public async Task StorageClients_ManagementUsesOriginalCredentialsAndBlocksResourceDeletion() + { + using StorageResponses storage = new() { RequireSasAuthentication = false }; + MigratingAzureStorageClient client = storage.CreateMigratingClient(); + Queue queue = client.GetQueueReference("workload"); + Table table = client.GetTableReference("Workload"); + BlobContainer container = client.GetBlobContainerReference("workload"); + Func[] creates = + { + () => queue.CreateIfNotExistsAsync(), + () => table.CreateIfNotExistsAsync(), + () => container.CreateIfNotExistsAsync(), + }; + Func[] deletes = + { + () => queue.DeleteIfExistsAsync(), + () => table.DeleteAsync(), + () => table.DeleteIfExistsAsync(), + () => container.DeleteIfExistsAsync(), + }; + try + { + // 1. Resource creation uses the original credentials. + foreach (Func create in creates) + { + await create(); + } + await client.StopMigrationTokenRefreshAsync(); + Assert.AreEqual(3, storage.Workload.Count); + Assert.IsTrue(storage.Workload.All(uri => !Query(uri.Query).ContainsKey("sig"))); + Assert.IsTrue(storage.WorkloadAuthorizations.All(value => value is not null)); + + // 2. Migration blocks deletion of whole queues, tables, and containers. + foreach (Func delete in deletes) + { + await Assert.ThrowsExceptionAsync(delete); + } + Assert.AreEqual(3, storage.Workload.Count); + + // 3. Management calls also stop after the client observes migration ending. + await storage.EndAsync(); + await client.InitializeMigrationAsync(refresh: true); + foreach (Func create in creates) + { + await Assert.ThrowsExceptionAsync(create); + } + Assert.AreEqual(3, storage.Workload.Count); + + // 4. Sharing the provider does not restrict an ordinary client. + AzureStorageClient ordinary = storage.CreateClient(migrating: false); + await ordinary.GetQueueReference("workload").AddMessageAsync("payload", null); + Assert.AreEqual(typeof(AzureStorageClient), ordinary.GetType()); + Assert.IsFalse(Query(storage.Workload.Last().Query).ContainsKey("timeout")); + Assert.IsNotNull(storage.WorkloadAuthorizations.Last()); + } + finally + { + await client.StopMigrationTokenRefreshAsync(); + } + } + + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task StorageClients_GenericRetriesChangeOnlyDuringMigration(bool migrating) + { + using StorageResponses storage = new(retries: 1) { RequireSasAuthentication = migrating }; + AzureStorageClient client = storage.CreateClient(migrating); + storage.WorkloadFailures = 1; + storage.WorkloadFailureStatus = HttpStatusCode.ServiceUnavailable; + storage.WorkloadFailureCode = "ServerBusy"; + try + { + // 1. Send the same transient failure through each client's SDK pipeline. + Func write = CachedWrites(client)[0]; + if (migrating) + { + await Assert.ThrowsExceptionAsync(write); + } + else + { + await write(); + } + + // 2. Only migration disables generic retries and adds the server timeout. + Assert.AreEqual(migrating ? 1 : 2, storage.Workload.Count); + foreach (Uri uri in storage.Workload) + { + Assert.AreEqual(migrating, Query(uri.Query).ContainsKey("timeout")); + Assert.AreEqual(migrating, Query(uri.Query).ContainsKey("sig")); + } + } + finally + { + if (client is MigratingAzureStorageClient migratingClient) + { + await migratingClient.StopMigrationTokenRefreshAsync(); + } + } + } + + [DataTestMethod] + [DataRow(0)] + [DataRow(1)] + [DataRow(2)] + public async Task StorageClients_AuthenticationRetryUsesRenewedCredentials(int service) + { + using StorageResponses storage = new(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); + try + { + // 1. Expire the SAS after the wrapper sends its first request. + await client.InitializeMigrationAsync(); + await client.StopMigrationTokenRefreshAsync(); + DateTimeOffset expiry = storage.Expiry; + storage.WorkloadFailures = 1; + storage.BeforeWorkloadFailure = () => + { + storage.ServerTime = expiry.AddSeconds(1); + return Task.CompletedTask; + }; + + // 2. Retry once with a new signature and the same body. + await CachedWrites(client)[service](); + Assert.AreEqual(2, storage.Workload.Count); + Assert.AreNotEqual(Query(storage.Workload[0].Query)["sig"], Query(storage.Workload[1].Query)["sig"]); + Assert.AreEqual(storage.WorkloadBodies[0], storage.WorkloadBodies[1]); + Assert.AreEqual("30", Query(storage.Workload[1].Query)["timeout"]); + } + finally + { + await client.StopMigrationTokenRefreshAsync(); + } + } + + [DataTestMethod] + [DataRow("queue", false)] + [DataRow("queue", true)] + [DataRow("table", false)] + [DataRow("blob", false)] + [DataRow("management", false)] + [Timeout(10000)] + public async Task StorageClients_CanceledInitializationCanBeRetried( + string operation, + bool blockKeys) + { + // 1. Hold the first operation in a gate or key read. + using StorageResponses storage = new(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); + TaskCompletionSource started = new(TaskCreationOptions.RunContinuationsAsynchronously); + async Task block(CancellationToken token) + { + started.SetResult(true); + await Task.Delay(Timeout.Infinite, token); + } + if (blockKeys) + { + storage.BeforeKey = block; + } + else + { + storage.AfterRead = block; + } + + using CancellationTokenSource cancellation = new(); + Task pending = RunAsync(cancellation.Token); + try + { + await started.Task; + + // 2. Cancellation stops initialization before any workload request is sent. + cancellation.Cancel(); + await AssertCanceledAsync(pending); + Assert.AreEqual(0, storage.Workload.Count); + Assert.AreEqual(0, storage.GateWrites); + + // 3. Another operation can initialize; later calls reuse that result. + await CachedWrites(client)[0](); + int reads = storage.GateReads; + int keys = storage.KeyRequests; + await CachedWrites(client)[1](); + Assert.AreEqual(reads, storage.GateReads); + Assert.AreEqual(keys, storage.KeyRequests); + Assert.AreEqual(2, storage.Workload.Count); + Assert.AreEqual(1, storage.GateWrites); + } + finally + { + cancellation.Cancel(); + await client.StopMigrationTokenRefreshAsync(); + } + + async Task RunAsync(CancellationToken token) + { + switch (operation) + { + case "queue": + await client.GetQueueReference("workload").GetMessagesAsync(1, TimeSpan.FromSeconds(30), token); + break; + case "table": + await client.GetTableReference("Workload").InsertEntityAsync(new TableEntity("instance", ""), token); + break; + case "blob": + await client.GetBlobReference(new Uri("https://account.blob.core.windows.net/workload/payload")) + .UploadTextAsync("payload", cancellationToken: token); + break; + case "management": + await client.GetBlobContainerReference("workload").CreateIfNotExistsAsync(token); + break; + default: + Assert.Fail("Unknown operation."); + break; + } + } + } + + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task StorageClients_PagingAndResourceChecksUseOriginalCredentials(bool sharedKey) + { + // 1. Make migration initialization fail if any read attempts it. + using StorageResponses storage = new(sharedKey: sharedKey) + { + FailReads = true, + FailKeys = true, + RequireSasAuthentication = false, + }; + MigratingAzureStorageClient client = storage.CreateMigratingClient(); + try + { + // 2. Paging and table/container existence checks still work. + TableQueryResults rows = await client.GetTableReference("Workload") + .ExecuteQueryAsync().GetResultsAsync(); + Assert.AreEqual(0, rows.Entities.Count); + await using (IAsyncEnumerator blobs = client.GetBlobContainerReference("workload") + .ListBlobsAsync().GetAsyncEnumerator()) + { + Assert.IsFalse(await blobs.MoveNextAsync()); + } + + Assert.IsFalse(await client.GetTableReference("Workload").ExistsAsync()); + Assert.IsFalse(await client.GetBlobContainerReference("workload").ExistsAsync()); + + // 3. These reads do not need the migration gate or keys. + Assert.AreEqual(4, storage.Workload.Count); + Assert.AreEqual(0, storage.GateReads); + Assert.AreEqual(0, storage.GateWrites); + Assert.AreEqual(0, storage.KeyRequests); + foreach (Uri request in storage.Workload) + { + Assert.IsFalse(Query(request.Query).ContainsKey("sig")); + } + foreach (string? authorization in storage.WorkloadAuthorizations) + { + Assert.IsNotNull(authorization); + } + } + finally + { + await client.StopMigrationTokenRefreshAsync(); + } + } + + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task StorageClients_BlobAndQueueExistenceUseMigrationCredentials(bool sharedKey) + { + using StorageResponses storage = new(sharedKey); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); + Queue queue = client.GetQueueReference("workload"); + Blob blob = client.GetBlobContainerReference("workload").GetBlobReference("payload"); + Func>[] checks = + { + () => queue.ExistsAsync(), + () => blob.ExistsAsync(), + }; + try + { + // 1. Existence checks initialize migration and use its SAS. + foreach (Func> check in checks) + { + Assert.IsFalse(await check()); + } + await client.StopMigrationTokenRefreshAsync(); + Assert.AreEqual(2, storage.Workload.Count); + Assert.AreEqual(sharedKey ? 0 : 3, storage.KeyRequests); + foreach (Uri request in storage.Workload) + { + Assert.IsTrue(Query(request.Query).ContainsKey("sig")); + Assert.AreEqual("30", Query(request.Query)["timeout"]); + } + + // 2. The same wrappers stop sending when migration ends. + await storage.EndAsync(); + await client.InitializeMigrationAsync(refresh: true); + foreach (Func> check in checks) + { + await Assert.ThrowsExceptionAsync(() => check()); + } + Assert.AreEqual(2, storage.Workload.Count); + } + finally + { + await client.StopMigrationTokenRefreshAsync(); + } + } + + [TestMethod] + [Timeout(10000)] + public async Task StorageClients_CanceledWaiterDoesNotCancelInitialization() + { + // 1. Hold the first caller in initialization. + using StorageResponses storage = new(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); + TaskCompletionSource started = new(TaskCreationOptions.RunContinuationsAsynchronously); + TaskCompletionSource release = new(TaskCreationOptions.RunContinuationsAsynchronously); + storage.AfterRead = async _ => { started.SetResult(true); await release.Task; }; + Task first = client.EnsureAccessAsync(default); + await started.Task; + try + { + // 2. Cancel one waiter while another still waits for the same initialization. + using CancellationTokenSource cancellation = new(); + Task canceled = client.EnsureAccessAsync(cancellation.Token); + Task waiting = client.EnsureAccessAsync(default); + cancellation.Cancel(); + await AssertCanceledAsync(canceled); + Assert.IsFalse(first.IsCompleted); + Assert.IsFalse(waiting.IsCompleted); + Assert.AreEqual(1, storage.GateReads); + + // 3. The remaining callers finish after just one initialization. + release.SetResult(true); + await Task.WhenAll(first, waiting); + // Key acquisition rereads the gate before granting access. + Assert.AreEqual(2, storage.GateReads); + Assert.AreEqual(1, storage.GateWrites); + Assert.AreEqual(3, storage.KeyRequests); + } + finally + { + release.TrySetResult(true); + await first; + await client.StopMigrationTokenRefreshAsync(); + } + } + + static Func[] CachedWrites(AzureStorageClient client) + { + Queue queue = client.GetQueueReference("workload"); + Table table = client.GetTableReference("Workload"); + Blob blob = client.GetBlobContainerReference("workload").GetBlobReference("payload"); + Blob uriBlob = client.GetBlobReference(new Uri("https://account.blob.core.windows.net/workload/uri-payload")); + return new Func[] + { + () => queue.AddMessageAsync("payload", null), + () => table.InsertEntityAsync(new TableEntity("instance", string.Empty)), + () => blob.UploadTextAsync("payload"), + () => uriBlob.UploadTextAsync("payload"), + }; + } + static async Task AssertCanceledAsync(Task task) { try @@ -562,28 +1193,46 @@ static async Task AssertCanceledAsync(Task task) } static Dictionary Query(string signature) => signature.TrimStart('?').Split('&') + .Where(part => part.Length > 0) .Select(part => part.Split(new[] { '=' }, 2)) .ToDictionary(parts => parts[0], parts => Uri.UnescapeDataString(parts[1])); + sealed class OptionsHeaderPolicy : HttpPipelineSynchronousPolicy + { + public override void OnSendingRequest(HttpMessage message) + { + message.Request.Headers.TryGetValue("x-options-policy", out string? value); + message.Request.Headers.SetValue("x-options-policy", value + "x"); + } + } + // Real SDK clients use this local handler; no requests reach Azure. sealed class StorageResponses : HttpPipelineTransport, IDisposable { readonly StorageAccountClientProvider provider; + readonly int managementRetries; + readonly Action? configureOptions; int revision; - public StorageResponses(bool sharedKey = false) + public StorageResponses( + bool sharedKey = false, + int retries = 0, + Func? blobOptionsFactory = null, + Action? configureOptions = null) { + this.managementRetries = retries; + this.configureOptions = configureOptions; TestCredential credential = new TestCredential(); string connection = "DefaultEndpointsProtocol=https;AccountName=account;AccountKey=" + Convert.ToBase64String(new byte[32]) + ";EndpointSuffix=core.windows.net"; this.provider = sharedKey ? new StorageAccountClientProvider( - StorageServiceClientProvider.ForBlob(connection, this.Options(new BlobClientOptions())), - StorageServiceClientProvider.ForQueue(connection, this.Options(new QueueClientOptions())), - StorageServiceClientProvider.ForTable(connection, this.Options(new TableClientOptions()))) + StorageServiceClientProvider.ForBlobWithOptionsFactory(connection, () => this.Options(blobOptionsFactory?.Invoke() ?? new BlobClientOptions())), + StorageServiceClientProvider.ForQueueWithOptionsFactory(connection, () => this.Options(new QueueClientOptions())), + StorageServiceClientProvider.ForTableWithOptionsFactory(connection, () => this.Options(new TableClientOptions()))) : new StorageAccountClientProvider( - StorageServiceClientProvider.ForBlob("account", credential, this.Options(new BlobClientOptions())), - StorageServiceClientProvider.ForQueue("account", credential, this.Options(new QueueClientOptions())), - StorageServiceClientProvider.ForTable("account", credential, this.Options(new TableClientOptions()))); + StorageServiceClientProvider.ForBlobWithOptionsFactory("account", credential, () => this.Options(blobOptionsFactory?.Invoke() ?? new BlobClientOptions())), + StorageServiceClientProvider.ForQueueWithOptionsFactory("account", credential, () => this.Options(new QueueClientOptions())), + StorageServiceClientProvider.ForTableWithOptionsFactory("account", credential, () => this.Options(new TableClientOptions()))); this.Control = new AzureStorageMigration(this.provider.Table.CreateClient(this.provider.Table.CreateOptions()), "TestHub"); this.Row = new JObject { @@ -609,6 +1258,9 @@ public StorageResponses(bool sharedKey = false) public HttpStatusCode WorkloadFailureStatus { get; set; } = HttpStatusCode.Forbidden; public string? WorkloadFailureCode { get; set; } = "AuthenticationFailed"; public Func? BeforeWorkloadFailure { get; set; } + public Action? BeforeWorkload { get; set; } + public bool RequireSasAuthentication { get; set; } = true; + public List WorkloadAuthorizations { get; } = new(); public List Workload { get; } = new(); public List WorkloadBodies { get; } = new(); public List WorkloadVersions { get; } = new(); @@ -622,6 +1274,12 @@ public StorageResponses(bool sharedKey = false) public Func? BeforeKey { get; set; } public AzureStorageMigration Control { get; } + public MigratingAzureStorageClient CreateMigratingClient() => (MigratingAzureStorageClient)this.CreateClient(migrating: true); + + public AzureStorageClient CreateClient(bool migrating = false) => AzureStorageClient.Create( + new AzureStorageOrchestrationServiceSettings { TaskHubName = "TestHub", StorageAccountClientProvider = this.provider }, + migrating ? this.MigrationId : null); + public MigrationSasManager CreateManager() => new MigrationSasManager( new AzureStorageOrchestrationServiceSettings { TaskHubName = "TestHub", StorageAccountClientProvider = this.provider }, this.MigrationId, @@ -678,7 +1336,9 @@ T WorkloadOptions(T options, MigrationSasManager manager, bool delegationVers T Options(T options) where T : ClientOptions { options.Transport = this; - options.Retry.MaxRetries = 0; + options.Retry.Delay = TimeSpan.Zero; + options.Retry.MaxRetries = this.managementRetries; + this.configureOptions?.Invoke(options); return options; } @@ -706,10 +1366,15 @@ async Task SendAsync(HttpRequestMessage request, Cancellati if (!uri.AbsolutePath.StartsWith("/TestHubMigrationCtrl", StringComparison.Ordinal)) { + this.BeforeWorkload?.Invoke(request); this.Workload.Add(uri); this.WorkloadBodies.Add(request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync()); this.WorkloadVersions.Add(request.Headers.GetValues("x-ms-version").Single()); - Assert.IsNull(request.Headers.Authorization, "SAS requests must not use identity authentication."); + this.WorkloadAuthorizations.Add(request.Headers.Authorization?.ToString()); + if (this.RequireSasAuthentication) + { + Assert.IsNull(request.Headers.Authorization, "SAS requests must not use identity authentication."); + } if (this.WorkloadFailures > 0) { this.WorkloadFailures--; @@ -722,6 +1387,38 @@ async Task SendAsync(HttpRequestMessage request, Cancellati if (this.WorkloadFailureCode is not null) failure.Headers.Add("x-ms-error-code", this.WorkloadFailureCode); return failure; } + if (request.Method == HttpMethod.Head + || (request.Method == HttpMethod.Get && uri.Host.Contains(".queue.") && !uri.AbsolutePath.EndsWith("/messages")) + || (request.Method == HttpMethod.Get && uri.Host.Contains(".blob.") && uri.Query.Contains("restype=container") && !uri.Query.Contains("comp="))) + { + string code = uri.Host.Contains(".queue.") ? "QueueNotFound" + : uri.Query.Contains("restype=container") ? "ContainerNotFound" : "BlobNotFound"; + HttpResponseMessage missing = this.Response( + HttpStatusCode.NotFound, + $"{code}The resource does not exist.", + "application/xml"); + missing.Headers.Add("x-ms-error-code", code); + return missing; + } + if (request.Method == HttpMethod.Get && uri.AbsolutePath == "/Tables") + { + return this.Response(HttpStatusCode.OK, "{\"value\":[]}"); + } + if (request.Method == HttpMethod.Get && uri.Host.Contains(".table.") && uri.AbsolutePath != "/Tables") + { + return this.Response(HttpStatusCode.OK, "{\"value\":[]}"); + } + if (request.Method == HttpMethod.Get && uri.Host.Contains(".blob.") && uri.Query.Contains("comp=list")) + { + return this.Response( + HttpStatusCode.OK, + "", + "application/xml"); + } + if (uri.AbsolutePath == "/Tables") + { + return this.Response(HttpStatusCode.Created, "{\"TableName\":\"Workload\"}"); + } if (uri.Host.Contains(".queue.")) { return this.Response(HttpStatusCode.Created, @@ -806,6 +1503,11 @@ public override async ValueTask ProcessAsync(HttpMessage message) } using HttpResponseMessage response = await this.SendAsync(request, message.CancellationToken); message.Response = new StorageResponse(response, await response.Content.ReadAsByteArrayAsync()); + if (request.Method == HttpMethod.Head) + { + // HEAD responses have no body. + message.Response.ContentStream = null; + } } public void Dispose() { } diff --git a/test/DurableTask.AzureStorage.Tests/StorageServiceClientProviderTests.cs b/test/DurableTask.AzureStorage.Tests/StorageServiceClientProviderTests.cs index 6d138478..19b2a5d5 100644 --- a/test/DurableTask.AzureStorage.Tests/StorageServiceClientProviderTests.cs +++ b/test/DurableTask.AzureStorage.Tests/StorageServiceClientProviderTests.cs @@ -20,6 +20,7 @@ namespace DurableTask.AzureStorage.Tests using Azure.Data.Tables; using Azure.Storage.Blobs; using Azure.Storage.Queues; + using DurableTask.AzureStorage.Storage; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] @@ -92,6 +93,103 @@ public void ConnectionStringProvider_HasNoTokenCredential(string service) } } + [DataTestMethod] + [DataRow(0, false)] + [DataRow(0, true)] + [DataRow(1, false)] + [DataRow(1, true)] + [DataRow(2, false)] + [DataRow(2, true)] + public void OptionsFactory_PreservesOrdinarySharingAndCreatesFreshMigrationOptions(int endpointKind, bool customOptions) + { + // 1. Use defaults or a factory with a custom service version and retry limit. + const string connection = "UseDevelopmentStorage=true"; + TestCredential credential = new(); + Uri endpoint = new("https://account.core.windows.net"); + static BlobClientOptions blobs() => new(BlobClientOptions.ServiceVersion.V2023_11_03) { Retry = { MaxRetries = 7 } }; + static QueueClientOptions queues() => new() { Retry = { MaxRetries = 7 } }; + static TableClientOptions tables() => new() { Retry = { MaxRetries = 7 } }; + + IStorageServiceClientProvider blobProvider = endpointKind switch + { + 0 => customOptions ? StorageServiceClientProvider.ForBlobWithOptionsFactory(connection, blobs) : StorageServiceClientProvider.ForBlob(connection), + 1 => customOptions ? StorageServiceClientProvider.ForBlobWithOptionsFactory("account", credential, blobs) : StorageServiceClientProvider.ForBlob("account", credential, null), + _ => customOptions ? StorageServiceClientProvider.ForBlobWithOptionsFactory(endpoint, credential, blobs) : StorageServiceClientProvider.ForBlob(endpoint, credential, null), + }; + IStorageServiceClientProvider queueProvider = endpointKind switch + { + 0 => customOptions ? StorageServiceClientProvider.ForQueueWithOptionsFactory(connection, queues) : StorageServiceClientProvider.ForQueue(connection), + 1 => customOptions ? StorageServiceClientProvider.ForQueueWithOptionsFactory("account", credential, queues) : StorageServiceClientProvider.ForQueue("account", credential, null), + _ => customOptions ? StorageServiceClientProvider.ForQueueWithOptionsFactory(endpoint, credential, queues) : StorageServiceClientProvider.ForQueue(endpoint, credential, null), + }; + IStorageServiceClientProvider tableProvider = endpointKind switch + { + 0 => customOptions ? StorageServiceClientProvider.ForTableWithOptionsFactory(connection, tables) : StorageServiceClientProvider.ForTable(connection), + 1 => customOptions ? StorageServiceClientProvider.ForTableWithOptionsFactory("account", credential, tables) : StorageServiceClientProvider.ForTable("account", credential, null), + _ => customOptions ? StorageServiceClientProvider.ForTableWithOptionsFactory(endpoint, credential, tables) : StorageServiceClientProvider.ForTable(endpoint, credential, null), + }; + + // 2. Ordinary calls keep their sharing behavior; migration gets separate options. + AssertFreshOptions(blobProvider, customOptions, endpointKind == 0 ? null : credential); + AssertFreshOptions(queueProvider, customOptions, endpointKind == 0 ? null : credential); + AssertFreshOptions(tableProvider, customOptions, endpointKind == 0 ? null : credential); + + if (customOptions) + { + Assert.AreEqual(BlobClientOptions.ServiceVersion.V2023_11_03, blobProvider.CreateOptions().Version); + } + } + + [TestMethod] + public void Migration_RejectsSharedOptionsWithoutChangingTheirRetrySettings() + { + // 1. The existing overload still supports ordinary clients with shared options. + const string connection = "UseDevelopmentStorage=true"; + BlobClientOptions options = new() { Retry = { MaxRetries = 7 } }; + AzureStorageOrchestrationServiceSettings settings = new() + { + StorageAccountClientProvider = new StorageAccountClientProvider( + StorageServiceClientProvider.ForBlob(connection, options), + StorageServiceClientProvider.ForQueue(connection), + StorageServiceClientProvider.ForTable(connection)), + }; + _ = new AzureStorageClient(settings); + + // 2. Migration requires fresh options instead of adding policies to the shared object. + InvalidOperationException error = Assert.ThrowsException(() => AzureStorageClient.Create(settings, Guid.NewGuid())); + StringAssert.Contains(error.Message, "options factory"); + Assert.AreEqual(7, options.Retry.MaxRetries); + } + + static void AssertFreshOptions( + IStorageServiceClientProvider provider, + bool customOptions, + TokenCredential? credential) + where TOptions : ClientOptions + { + TOptions first = provider.CreateOptions(); + int retries = first.Retry.MaxRetries; + first.Retry.MaxRetries = 0; + TOptions second = provider.CreateOptions(); + if (customOptions) + { + Assert.AreNotSame(first, second); + Assert.AreEqual(7, second.Retry.MaxRetries); + } + else + { + Assert.AreSame(first, second); + Assert.AreEqual(0, second.Retry.MaxRetries); + } + + TOptions fresh = provider.CreateFreshOptions(); + Assert.AreNotSame(first, fresh); + Assert.AreNotSame(fresh, provider.CreateFreshOptions()); + Assert.AreEqual(customOptions ? 7 : retries, fresh.Retry.MaxRetries); + Assert.AreSame(credential, ((IStorageTokenCredentialProvider)provider).TokenCredential); + Assert.IsNotNull(provider.CreateClient(fresh)); + } + [TestMethod] public void CustomProvider_DoesNotRequireTheOptionalInterface() { @@ -101,10 +199,13 @@ public void CustomProvider_DoesNotRequireTheOptionalInterface() // 2. Client creation still works without exposing a credential. Assert.IsFalse(provider is IStorageTokenCredentialProvider); Assert.IsNotNull(provider.CreateClient(provider.CreateOptions())); + Assert.AreNotSame(provider.CreateOptions(), provider.CreateFreshOptions()); } static void AssertProvider( - IStorageServiceClientProvider provider, TOptions options, TokenCredential? credential) + IStorageServiceClientProvider provider, + TOptions options, + TokenCredential? credential) where TOptions : ClientOptions { // 2. Keep the same credential and options, and continue creating clients. diff --git a/test/DurableTask.AzureStorage.Tests/TableUserDelegationKeyTests.cs b/test/DurableTask.AzureStorage.Tests/TableUserDelegationKeyTests.cs index bb03ee42..744276a3 100644 --- a/test/DurableTask.AzureStorage.Tests/TableUserDelegationKeyTests.cs +++ b/test/DurableTask.AzureStorage.Tests/TableUserDelegationKeyTests.cs @@ -61,12 +61,19 @@ public async Task Get_UsesStorageTimeAndAnIndependentAuthenticatedPipeline() Assert.AreEqual(KeyExpiry, (string?)body.Element("Expiry")); return KeyResponse(); })); - TableClientOptions options = Options(http); - options.AddPolicy(new RejectWorkloadRequestsPolicy(), HttpPipelinePosition.PerCall); TestCredential credential = new TestCredential(); + IStorageServiceClientProvider provider = + StorageServiceClientProvider.ForTableWithOptionsFactory(Endpoint, credential, () => Options(http)); + TableClientOptions workloadOptions = provider.CreateOptions(); + workloadOptions.AddPolicy(new RejectWorkloadRequestsPolicy(), HttpPipelinePosition.PerCall); - // 2. Key acquisition must not run policies that require a workload SAS. - TableUserDelegationKey key = await TableUserDelegationKey.GetAsync(Endpoint, credential, options, ServerTime, default); + // 2. Fresh key options do not contain the workload's SAS policy. + TableUserDelegationKey key = await TableUserDelegationKey.GetAsync( + Endpoint, + credential, + provider.CreateFreshOptions(), + ServerTime, + default); Assert.AreEqual(new DateTimeOffset(2030, 1, 2, 0, 15, 0, TimeSpan.Zero), key.ExpiresOn); Assert.AreEqual(1, requests); CollectionAssert.AreEqual(new[] { "https://storage.azure.com/.default" }, credential.Scopes);