From 7fece44fac726985477223afa68cd07d0d8354bb Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Tue, 1 Dec 2026 17:18:22 -0800 Subject: [PATCH 1/6] Use migration SAS credentials in Storage clients --- .../Storage/AzureStorageClient.cs | 236 +++++++++++++++- src/DurableTask.AzureStorage/Storage/Blob.cs | 20 +- .../Storage/BlobContainer.cs | 32 ++- src/DurableTask.AzureStorage/Storage/Queue.cs | 18 +- src/DurableTask.AzureStorage/Storage/Table.cs | 21 +- .../AzureStorageScenarioTests.cs | 5 +- .../MigrationSasManagerTests.cs | 261 +++++++++++++++++- 7 files changed, 555 insertions(+), 38 deletions(-) diff --git a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs index 76b8a2678..4178bb9e8 100644 --- a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs +++ b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs @@ -14,10 +14,14 @@ namespace DurableTask.AzureStorage.Storage { using System; + using System.Collections.Concurrent; using System.Text; + 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; using DurableTask.AzureStorage.Monitoring; @@ -27,8 +31,120 @@ class AzureStorageClient readonly BlobServiceClient blobClient; readonly QueueServiceClient queueClient; readonly TableServiceClient tableClient; + readonly MigrationSasManager? migration; + readonly bool isMigrationActive; + readonly object? initializationLock; + Task? migrationInitialization; + readonly QueueClientOptions? sasQueueOptions; + readonly TableClientOptions? sasTableOptions; + readonly BlobClientOptions? sasBlobOptions; + readonly ConcurrentDictionary? sasQueues; + readonly ConcurrentDictionary? sasTables; + readonly ConcurrentDictionary? sasContainers; - public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings) + public event Action? MigrationEnding; + public bool IsMigrationActive => this.isMigrationActive; + public bool IsMigrationEnding => this.isMigrationActive && this.migration!.IsMigrationEnding; + + public async Task InitializeMigrationAsync(bool refresh = false) + { + if (!this.IsMigrationActive) + { + return; + } + Task initialization; + bool refreshCachedInitialization; + lock (this.initializationLock!) + { + // New or in-progress initialization already refreshes credentials and starts the loop. + refreshCachedInitialization = refresh && this.migrationInitialization?.Status == TaskStatus.RanToCompletion; + // Run on the thread pool because synchronous SDK wrapper properties also call this method. + initialization = this.migrationInitialization ??= Task.Run(this.InitializeMigrationCoreAsync); + } + try + { + await initialization.ConfigureAwait(false); + } + catch + { + lock (this.initializationLock!) + { + // Do not clear a newer initialization started by another caller. + if (ReferenceEquals(this.migrationInitialization, initialization)) + { + this.migrationInitialization = null; + } + } + throw; + } + if (refreshCachedInitialization) + { + // A completed initialization may belong to a stopped service; refresh and restart its loop. + await this.InitializeMigrationCoreAsync(); + } + } + + public Task StopMigrationTokenRefreshAsync() + { + return this.migration?.StopRefreshing() ?? Task.CompletedTask; + } + + async Task InitializeMigrationCoreAsync() + { + await this.migration!.RefreshAsync(CancellationToken.None).ConfigureAwait(false); + _ = this.migration!.StartRefreshLoop(); + } + + public void EnsureAccess() + { + if (this.isMigrationActive) + { + this.InitializeMigrationAsync().GetAwaiter().GetResult(); + this.migration!.EnsureAccess(); + } + } + + public void ThrowIfMigrationResourceDeletion() + { + this.EnsureAccess(); + if (this.isMigrationActive) + { + throw new OrchestrationServiceUnavailableException("Task hub resource deletion is not supported during migration."); + } + } + + public QueueClient GetQueueClient(QueueClient original) + { + this.EnsureAccess(); + return !this.isMigrationActive ? original : this.sasQueues!.GetOrAdd( + original.Name, + name => new QueueClient(original.Uri, this.migration!.GetCredential('q', name), this.sasQueueOptions)); + } + + public TableClient GetTableClient(TableClient original) + { + this.EnsureAccess(); + return !this.isMigrationActive ? original : this.sasTables!.GetOrAdd( + original.Name, + name => new TableClient(original.Uri, this.migration!.GetCredential('t', name), this.sasTableOptions)); + } + + public BlobContainerClient GetBlobContainerClient(BlobContainerClient original) + { + this.EnsureAccess(); + return !this.isMigrationActive ? original : this.sasContainers!.GetOrAdd( + original.Name, + name => new BlobContainerClient(original.Uri, this.migration!.GetCredential('b', name), this.sasBlobOptions)); + } + + public BlockBlobClient GetBlockBlobClient(BlockBlobClient original) + { + this.EnsureAccess(); + return !this.isMigrationActive ? original : this.GetBlobContainerClient( + this.blobClient.GetBlobContainerClient(original.BlobContainerName)).GetBlockBlobClient(original.Name); + } + + public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings, Guid? migrationId = null) { if (settings == null) { @@ -40,6 +156,7 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings) throw new ArgumentException("Storage account client provider is not specified.", nameof(settings)); } + this.isMigrationActive = migrationId.HasValue; this.Settings = settings; this.Stats = new AzureStorageOrchestrationServiceStats(); @@ -47,16 +164,99 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings) var timeoutPolicy = new LeaseTimeoutHttpPipelinePolicy(this.Settings.LeaseRenewInterval); var monitoringPolicy = new MonitoringHttpPipelinePolicy(this.Stats); - this.queueClient = CreateClient(settings.StorageAccountClientProvider.Queue, ConfigureQueueClientPolicies); + QueueClientOptions? queueManagementOptions = null; + BlobClientOptions? blobManagementOptions = null; + TableClientOptions? tableManagementOptions = null; + this.queueClient = CreateClient( + settings.StorageAccountClientProvider.Queue, + options => + { + queueManagementOptions = options; + ConfigureQueueClientPolicies(options); + }); if (settings.HasTrackingStoreStorageAccount) { - this.blobClient = CreateClient(settings.TrackingServiceClientProvider!.Blob, ConfigureClientPolicies); - this.tableClient = CreateClient(settings.TrackingServiceClientProvider!.Table, ConfigureClientPolicies); + this.blobClient = CreateClient( + settings.TrackingServiceClientProvider!.Blob, + options => + { + blobManagementOptions = options; + ConfigureClientPolicies(options); + }); + this.tableClient = CreateClient( + settings.TrackingServiceClientProvider!.Table, + options => + { + tableManagementOptions = options; + options.Diagnostics.IsLoggingContentEnabled = false; + ConfigureClientPolicies(options); + }); } else { - this.blobClient = CreateClient(settings.StorageAccountClientProvider.Blob, ConfigureClientPolicies); - this.tableClient = CreateClient(settings.StorageAccountClientProvider.Table, ConfigureClientPolicies); + this.blobClient = CreateClient( + settings.StorageAccountClientProvider.Blob, + options => + { + blobManagementOptions = options; + ConfigureClientPolicies(options); + }); + this.tableClient = CreateClient( + settings.StorageAccountClientProvider.Table, + options => + { + tableManagementOptions = options; + options.Diagnostics.IsLoggingContentEnabled = false; + ConfigureClientPolicies(options); + }); + } + + if (migrationId.HasValue) + { + this.initializationLock = new object(); + this.sasQueues = new ConcurrentDictionary(); + this.sasTables = new ConcurrentDictionary(); + this.sasContainers = new ConcurrentDictionary(); + + this.migration = new MigrationSasManager( + settings, + migrationId.Value, + this.blobClient, + this.queueClient, + this.tableClient, + (settings.TrackingServiceClientProvider ?? settings.StorageAccountClientProvider).Table, + () => this.MigrationEnding?.Invoke()); + + // Retry authentication failures once with a refreshed SAS. + MigrationSasRetryPolicy sasRetry = new MigrationSasRetryPolicy(this.migration); + + // Keep migration policies off options shared with other clients. + this.sasQueueOptions = CopyTransportOptions( + queueManagementOptions!, + new QueueClientOptions + { + Audience = queueManagementOptions!.Audience, + GeoRedundantSecondaryUri = queueManagementOptions.GeoRedundantSecondaryUri, + }); + this.sasQueueOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); + ConfigureQueueClientPolicies(this.sasQueueOptions); + this.sasQueueOptions.AddPolicy(new MigrationRequestPolicy(this.migration, useDelegationVersion: true), HttpPipelinePosition.PerRetry); + this.sasTableOptions = CopyTransportOptions( + tableManagementOptions!, + new TableClientOptions { Audience = tableManagementOptions!.Audience }); + this.sasTableOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); + ConfigureClientPolicies(this.sasTableOptions); + this.sasTableOptions.AddPolicy(new MigrationRequestPolicy(this.migration, useDelegationVersion: true), HttpPipelinePosition.PerRetry); + this.sasBlobOptions = CopyTransportOptions( + blobManagementOptions!, + new BlobClientOptions + { + Audience = blobManagementOptions!.Audience, + GeoRedundantSecondaryUri = blobManagementOptions.GeoRedundantSecondaryUri, + }); + this.sasBlobOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); + ConfigureClientPolicies(this.sasBlobOptions); + this.sasBlobOptions.AddPolicy(new MigrationRequestPolicy(this.migration), HttpPipelinePosition.PerRetry); } void ConfigureClientPolicies(TClientOptions options) where TClientOptions : ClientOptions @@ -129,7 +329,7 @@ await args.Queue.UpdateMessageAsync( }; } - ConfigureClientPolicies(options); + ConfigureClientPolicies(options); } } @@ -145,12 +345,12 @@ await args.Queue.UpdateMessageAsync( public Blob GetBlobReference(string container, string blobName) { - return new Blob(this.blobClient, container, blobName); + return new Blob(this, this.blobClient, container, blobName); } internal Blob GetBlobReference(Uri blobUri) { - return new Blob(this.blobClient, blobUri); + return new Blob(this, this.blobClient, blobUri); } public BlobContainer GetBlobContainerReference(string container) @@ -182,5 +382,23 @@ static TClient CreateClient( return storageProvider.CreateClient(options); } + + static TOptions CopyTransportOptions(ClientOptions source, TOptions destination) where TOptions : ClientOptions + { + destination.Transport = source.Transport; + destination.Retry.Mode = source.Retry.Mode; + destination.Retry.Delay = source.Retry.Delay; + destination.Retry.MaxDelay = source.Retry.MaxDelay; + + // Limit request duration during migration by disabling SDK retries. + // Authentication failures still get one refresh and retry. + destination.Retry.MaxRetries = 0; + destination.Retry.NetworkTimeout = source.Retry.NetworkTimeout; + destination.Diagnostics.ApplicationId = source.Diagnostics.ApplicationId; + destination.Diagnostics.IsLoggingEnabled = source.Diagnostics.IsLoggingEnabled; + destination.Diagnostics.IsLoggingContentEnabled = source.Diagnostics.IsLoggingContentEnabled; + destination.Diagnostics.IsDistributedTracingEnabled = false; + return destination; + } } } diff --git a/src/DurableTask.AzureStorage/Storage/Blob.cs b/src/DurableTask.AzureStorage/Storage/Blob.cs index 390a92607..4eb856500 100644 --- a/src/DurableTask.AzureStorage/Storage/Blob.cs +++ b/src/DurableTask.AzureStorage/Storage/Blob.cs @@ -25,16 +25,21 @@ namespace DurableTask.AzureStorage.Storage class Blob { - readonly BlockBlobClient blockBlobClient; + readonly AzureStorageClient azureStorageClient; + readonly BlockBlobClient originalBlockBlobClient; + BlockBlobClient? cachedBlockBlobClient; + BlockBlobClient blockBlobClient => Volatile.Read(ref this.cachedBlockBlobClient) + ?? LazyInitializer.EnsureInitialized(ref this.cachedBlockBlobClient, () => this.azureStorageClient.GetBlockBlobClient(this.originalBlockBlobClient))!; - public Blob(BlobServiceClient blobServiceClient, string containerName, string blobName) + public Blob(AzureStorageClient azureStorageClient, BlobServiceClient blobServiceClient, string containerName, string blobName) { - this.blockBlobClient = blobServiceClient + this.azureStorageClient = azureStorageClient; + this.originalBlockBlobClient = blobServiceClient .GetBlobContainerClient(containerName) .GetBlockBlobClient(blobName); } - public Blob(BlobServiceClient blobServiceClient, Uri blobUri) + public Blob(AzureStorageClient azureStorageClient, BlobServiceClient blobServiceClient, Uri blobUri) { if (!blobUri.AbsoluteUri.StartsWith(blobServiceClient.Uri.AbsoluteUri, StringComparison.Ordinal)) { @@ -42,14 +47,15 @@ public Blob(BlobServiceClient blobServiceClient, Uri blobUri) } var builder = new BlobUriBuilder(blobUri); - this.blockBlobClient = blobServiceClient + this.azureStorageClient = azureStorageClient; + this.originalBlockBlobClient = blobServiceClient .GetBlobContainerClient(builder.BlobContainerName) .GetBlockBlobClient(builder.BlobName); } - public string Name => this.blockBlobClient.Name; + public string Name => this.originalBlockBlobClient.Name; - public Uri Uri => this.blockBlobClient.Uri; + public Uri Uri => this.originalBlockBlobClient.Uri; public async Task ExistsAsync(CancellationToken cancellationToken = default) { diff --git a/src/DurableTask.AzureStorage/Storage/BlobContainer.cs b/src/DurableTask.AzureStorage/Storage/BlobContainer.cs index a61ac9f5b..f404955ff 100644 --- a/src/DurableTask.AzureStorage/Storage/BlobContainer.cs +++ b/src/DurableTask.AzureStorage/Storage/BlobContainer.cs @@ -28,14 +28,19 @@ class BlobContainer { readonly AzureStorageClient azureStorageClient; readonly string containerName; - readonly BlobContainerClient blobContainerClient; + readonly BlobContainerClient originalBlobContainerClient; + BlobContainerClient? cachedBlobContainerClient; + + // During migration we use a blob container client that relies on short-lived SAS tokens + BlobContainerClient blobContainerClient => Volatile.Read(ref this.cachedBlobContainerClient) + ?? LazyInitializer.EnsureInitialized(ref this.cachedBlobContainerClient, () => this.azureStorageClient.GetBlobContainerClient(this.originalBlobContainerClient))!; public BlobContainer(AzureStorageClient azureStorageClient, BlobServiceClient blobServiceClient, string name) { this.azureStorageClient = azureStorageClient; this.containerName = name; - this.blobContainerClient = blobServiceClient.GetBlobContainerClient(this.containerName); + this.originalBlobContainerClient = blobServiceClient.GetBlobContainerClient(this.containerName); } public Blob GetBlobReference(string blobName, string? blobPrefix = null) @@ -46,19 +51,24 @@ public Blob GetBlobReference(string blobName, string? blobPrefix = null) public async Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { + // This management call needs the original credentials and an explicit access check. + this.azureStorageClient.EnsureAccess(); // TODO: Any encryption scope? // If we received null, then the response must have been a 409 (Conflict) and the container must already exist - Response response = await this.blobContainerClient.CreateIfNotExistsAsync(PublicAccessType.None, cancellationToken: cancellationToken).DecorateFailure(); + Response response = await this.originalBlobContainerClient.CreateIfNotExistsAsync(PublicAccessType.None, cancellationToken: cancellationToken).DecorateFailure(); return response != null; } public async Task ExistsAsync(CancellationToken cancellationToken = default) { - return await this.blobContainerClient.ExistsAsync(cancellationToken).DecorateFailure(); + // This management call needs the original credentials and an explicit access check. + this.azureStorageClient.EnsureAccess(); + return await this.originalBlobContainerClient.ExistsAsync(cancellationToken).DecorateFailure(); } public async Task DeleteIfExistsAsync(string? appLeaseId = null, CancellationToken cancellationToken = default) { + this.azureStorageClient.ThrowIfMigrationResourceDeletion(); BlobRequestConditions? conditions = null; if (appLeaseId != null) { @@ -82,7 +92,9 @@ public AsyncPageable ListBlobsAsync(string? prefix = null, CancellationTok public async Task AcquireLeaseAsync(TimeSpan leaseInterval, string leaseId, CancellationToken cancellationToken = default) { - BlobLease lease = await this.blobContainerClient + // This management call needs the original credentials and an explicit access check. + this.azureStorageClient.EnsureAccess(); + BlobLease lease = await this.originalBlobContainerClient .GetBlobLeaseClient(leaseId) .AcquireAsync(leaseInterval, cancellationToken: cancellationToken) .DecorateFailure(); @@ -92,7 +104,9 @@ public async Task AcquireLeaseAsync(TimeSpan leaseInterval, string lease public async Task ChangeLeaseAsync(string proposedLeaseId, string currentLeaseId, CancellationToken cancellationToken = default) { - BlobLease lease = await this.blobContainerClient + // This management call needs the original credentials and an explicit access check. + this.azureStorageClient.EnsureAccess(); + BlobLease lease = await this.originalBlobContainerClient .GetBlobLeaseClient(currentLeaseId) .ChangeAsync(proposedLeaseId, cancellationToken: cancellationToken) .DecorateFailure(); @@ -102,7 +116,9 @@ public async Task ChangeLeaseAsync(string proposedLeaseId, string curren public Task RenewLeaseAsync(string leaseId, CancellationToken cancellationToken = default) { - return this.blobContainerClient + // This management call needs the original credentials and an explicit access check. + this.azureStorageClient.EnsureAccess(); + return this.originalBlobContainerClient .GetBlobLeaseClient(leaseId) .RenewAsync(cancellationToken: cancellationToken) .DecorateFailure(); @@ -110,7 +126,7 @@ public Task RenewLeaseAsync(string leaseId, CancellationToken cancellationToken public Uri GetBlobContainerUri() { - return this.blobContainerClient.Uri; + return this.originalBlobContainerClient.Uri; } static bool IsHnsFolder(BlobItem item) diff --git a/src/DurableTask.AzureStorage/Storage/Queue.cs b/src/DurableTask.AzureStorage/Storage/Queue.cs index a31913306..c39c99d31 100644 --- a/src/DurableTask.AzureStorage/Storage/Queue.cs +++ b/src/DurableTask.AzureStorage/Storage/Queue.cs @@ -26,18 +26,23 @@ class Queue { readonly AzureStorageClient azureStorageClient; readonly AzureStorageOrchestrationServiceStats stats; - readonly QueueClient queueClient; + readonly QueueClient originalQueueClient; + QueueClient? cachedQueueClient; + + // During migration we use a queue client that relies on short-lived SAS tokens + QueueClient queueClient => Volatile.Read(ref this.cachedQueueClient) + ?? LazyInitializer.EnsureInitialized(ref this.cachedQueueClient, () => this.azureStorageClient.GetQueueClient(this.originalQueueClient))!; public Queue(AzureStorageClient azureStorageClient, QueueServiceClient queueServiceClient, string queueName) { this.azureStorageClient = azureStorageClient; this.stats = this.azureStorageClient.Stats; - this.queueClient = queueServiceClient.GetQueueClient(queueName); + this.originalQueueClient = queueServiceClient.GetQueueClient(queueName); } - public string Name => this.queueClient.Name; + public string Name => this.originalQueueClient.Name; - public Uri Uri => this.queueClient.Uri; + public Uri Uri => this.originalQueueClient.Uri; public async Task GetApproximateMessagesCountAsync(CancellationToken cancellationToken = default) { @@ -107,13 +112,16 @@ public async Task ExistsAsync(CancellationToken cancellationToken = defaul public async Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { + // This management call needs the original credentials and an explicit access check. + this.azureStorageClient.EnsureAccess(); // 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(); + Response response = await this.originalQueueClient.CreateIfNotExistsAsync(cancellationToken: cancellationToken).DecorateFailure(); return response != null; } public async Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) { + this.azureStorageClient.ThrowIfMigrationResourceDeletion(); return await this.queueClient.DeleteIfExistsAsync(cancellationToken).DecorateFailure(); } diff --git a/src/DurableTask.AzureStorage/Storage/Table.cs b/src/DurableTask.AzureStorage/Storage/Table.cs index ebe98065b..7967db4f6 100644 --- a/src/DurableTask.AzureStorage/Storage/Table.cs +++ b/src/DurableTask.AzureStorage/Storage/Table.cs @@ -31,7 +31,12 @@ class Table readonly AzureStorageClient azureStorageClient; readonly AzureStorageOrchestrationServiceStats stats; readonly TableServiceClient tableServiceClient; - readonly TableClient tableClient; + readonly TableClient originalTableClient; + TableClient? cachedTableClient; + + // During migration we use a table client that relies on short-lived SAS tokens + TableClient tableClient => Volatile.Read(ref this.cachedTableClient) + ?? LazyInitializer.EnsureInitialized(ref this.cachedTableClient, () => this.azureStorageClient.GetTableClient(this.originalTableClient))!; public Table(AzureStorageClient azureStorageClient, TableServiceClient tableServiceClient, string tableName) { @@ -39,22 +44,25 @@ public Table(AzureStorageClient azureStorageClient, TableServiceClient tableServ this.stats = this.azureStorageClient.Stats; this.tableServiceClient = tableServiceClient; - this.tableClient = tableServiceClient.GetTableClient(tableName); + this.originalTableClient = tableServiceClient.GetTableClient(tableName); } - public string Name => this.tableClient.Name; + public string Name => this.originalTableClient.Name; - internal Uri Uri => this.tableClient.Uri; + internal Uri Uri => this.originalTableClient.Uri; public async Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { + // This management call needs the original credentials and an explicit access check. + this.azureStorageClient.EnsureAccess(); // 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(); + Response response = await this.originalTableClient.CreateIfNotExistsAsync(cancellationToken).DecorateFailure(); return response != null; } public async Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) { + this.azureStorageClient.ThrowIfMigrationResourceDeletion(); // 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(); return response != null; @@ -62,6 +70,8 @@ public async Task DeleteIfExistsAsync(CancellationToken cancellationToken public async Task ExistsAsync(CancellationToken cancellationToken = default) { + // This management call needs the original credentials and an explicit access check. + this.azureStorageClient.EnsureAccess(); // 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) @@ -73,6 +83,7 @@ public async Task ExistsAsync(CancellationToken cancellationToken = defaul public async Task DeleteAsync(CancellationToken cancellationToken = default) { + this.azureStorageClient.ThrowIfMigrationResourceDeletion(); await this.tableClient.DeleteAsync(cancellationToken).DecorateFailure(); } diff --git a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs index 4b1113f42..c9f2cbd49 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 6fb93d917..8f8a6bd22 100644 --- a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs +++ b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs @@ -551,6 +551,243 @@ 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); + AzureStorageClient client = storage.CreateClient(); + 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 drain. + 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)] + [DataRow(true)] + public async Task StorageClients_FailedInitializationCanBeRetried(bool missingGate) + { + using StorageResponses storage = new(); + AzureStorageClient client = storage.CreateClient(); + 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 }; + AzureStorageClient client = storage.CreateClient(); + 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 drain. + 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 provider options does not restrict an ordinary client. + AzureStorageClient ordinary = storage.CreateClient(migrating: false); + await ordinary.GetQueueReference("workload").AddMessageAsync("payload", null); + Assert.IsFalse(ordinary.IsMigrationActive); + 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 + { + await client.StopMigrationTokenRefreshAsync(); + } + } + + [DataTestMethod] + [DataRow(0)] + [DataRow(1)] + [DataRow(2)] + public async Task StorageClients_AuthenticationRetryUsesRenewedCredentials(int service) + { + using StorageResponses storage = new(); + AzureStorageClient client = storage.CreateClient(); + 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(); + } + } + + 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,6 +799,7 @@ 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])); @@ -569,10 +807,12 @@ static Dictionary Query(string signature) => signature.TrimStart sealed class StorageResponses : HttpPipelineTransport, IDisposable { readonly StorageAccountClientProvider provider; + readonly int managementRetries; int revision; - public StorageResponses(bool sharedKey = false) + public StorageResponses(bool sharedKey = false, int retries = 0) { + this.managementRetries = retries; TestCredential credential = new TestCredential(); string connection = "DefaultEndpointsProtocol=https;AccountName=account;AccountKey=" + Convert.ToBase64String(new byte[32]) + ";EndpointSuffix=core.windows.net"; this.provider = sharedKey @@ -609,6 +849,8 @@ public StorageResponses(bool sharedKey = false) public HttpStatusCode WorkloadFailureStatus { get; set; } = HttpStatusCode.Forbidden; public string? WorkloadFailureCode { get; set; } = "AuthenticationFailed"; public Func? BeforeWorkloadFailure { 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 +864,10 @@ public StorageResponses(bool sharedKey = false) public Func? BeforeKey { get; set; } public AzureStorageMigration Control { get; } + public AzureStorageClient CreateClient(bool migrating = true) => new( + 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 +924,8 @@ 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; return options; } @@ -709,7 +956,11 @@ async Task SendAsync(HttpRequestMessage request, Cancellati 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 +973,10 @@ async Task SendAsync(HttpRequestMessage request, Cancellati if (this.WorkloadFailureCode is not null) failure.Headers.Add("x-ms-error-code", this.WorkloadFailureCode); return failure; } + if (uri.AbsolutePath == "/Tables") + { + return this.Response(HttpStatusCode.Created, "{\"TableName\":\"Workload\"}"); + } if (uri.Host.Contains(".queue.")) { return this.Response(HttpStatusCode.Created, From 9551a8013b28bba8c406d452880b812a2b5bde45 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Tue, 1 Dec 2026 21:02:24 -0800 Subject: [PATCH 2/6] addressing PR comments --- .../Storage/AzureStorageClient.cs | 62 ++++++--- src/DurableTask.AzureStorage/Storage/Blob.cs | 2 + .../MigrationSasManagerTests.cs | 124 +++++++++++++++++- 3 files changed, 168 insertions(+), 20 deletions(-) diff --git a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs index 4178bb9e8..a4d08a8b7 100644 --- a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs +++ b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs @@ -35,6 +35,7 @@ class AzureStorageClient readonly bool isMigrationActive; readonly object? initializationLock; Task? migrationInitialization; + Task migrationRefreshStop = Task.CompletedTask; readonly QueueClientOptions? sasQueueOptions; readonly TableClientOptions? sasTableOptions; readonly BlobClientOptions? sasBlobOptions; @@ -52,15 +53,25 @@ public async Task InitializeMigrationAsync(bool refresh = false) { return; } + Task initialization; - bool refreshCachedInitialization; lock (this.initializationLock!) { - // New or in-progress initialization already refreshes credentials and starts the loop. - refreshCachedInitialization = refresh && this.migrationInitialization?.Status == TaskStatus.RanToCompletion; - // Run on the thread pool because synchronous SDK wrapper properties also call this method. - initialization = this.migrationInitialization ??= Task.Run(this.InitializeMigrationCoreAsync); + if (this.migrationInitialization is null || + (refresh && this.migrationInitialization.Status == TaskStatus.RanToCompletion)) + { + Task stopping = this.migrationRefreshStop; + // Run on the thread pool because synchronous SDK wrapper properties also call this method. + this.migrationInitialization = Task.Run(async () => + { + // Finish an earlier stop before starting a new renewal loop. + await stopping.ConfigureAwait(false); + await this.InitializeMigrationCoreAsync().ConfigureAwait(false); + }); + } + initialization = this.migrationInitialization; } + try { await initialization.ConfigureAwait(false); @@ -77,16 +88,36 @@ public async Task InitializeMigrationAsync(bool refresh = false) } throw; } - if (refreshCachedInitialization) - { - // A completed initialization may belong to a stopped service; refresh and restart its loop. - await this.InitializeMigrationCoreAsync(); - } } public Task StopMigrationTokenRefreshAsync() { - return this.migration?.StopRefreshing() ?? Task.CompletedTask; + if (!this.IsMigrationActive) + { + return Task.CompletedTask; + } + + lock (this.initializationLock!) + { + Task initialization = this.migrationInitialization ?? Task.CompletedTask; + Task stopping = this.migrationRefreshStop; + return this.migrationRefreshStop = Task.Run(async () => + { + // Keep repeated stops in order before allowing a restart. + await stopping.ConfigureAwait(false); + + // Wait for initialization or restart before stopping the loop it creates. + try + { + await initialization.ConfigureAwait(false); + } + catch + { + // The initialization caller handles the failure; stopping must still finish. + } + await this.migration!.StopRefreshing().ConfigureAwait(false); + }); + } } async Task InitializeMigrationCoreAsync() @@ -188,7 +219,6 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings, Gui options => { tableManagementOptions = options; - options.Diagnostics.IsLoggingContentEnabled = false; ConfigureClientPolicies(options); }); } @@ -206,7 +236,6 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings, Gui options => { tableManagementOptions = options; - options.Diagnostics.IsLoggingContentEnabled = false; ConfigureClientPolicies(options); }); } @@ -228,7 +257,7 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings, Gui () => this.MigrationEnding?.Invoke()); // Retry authentication failures once with a refreshed SAS. - MigrationSasRetryPolicy sasRetry = new MigrationSasRetryPolicy(this.migration); + MigrationSasRetryPolicy sasRetry = new(this.migration); // Keep migration policies off options shared with other clients. this.sasQueueOptions = CopyTransportOptions( @@ -253,6 +282,8 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings, Gui { Audience = blobManagementOptions!.Audience, GeoRedundantSecondaryUri = blobManagementOptions.GeoRedundantSecondaryUri, + CustomerProvidedKey = blobManagementOptions.CustomerProvidedKey, + EncryptionScope = blobManagementOptions.EncryptionScope, }); this.sasBlobOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); ConfigureClientPolicies(this.sasBlobOptions); @@ -391,13 +422,14 @@ static TOptions CopyTransportOptions(ClientOptions source, TOptions de destination.Retry.MaxDelay = source.Retry.MaxDelay; // Limit request duration during migration by disabling SDK retries. + // This is necessary so that we can maintain strict bounds on how long a request can take. // Authentication failures still get one refresh and retry. destination.Retry.MaxRetries = 0; destination.Retry.NetworkTimeout = source.Retry.NetworkTimeout; destination.Diagnostics.ApplicationId = source.Diagnostics.ApplicationId; destination.Diagnostics.IsLoggingEnabled = source.Diagnostics.IsLoggingEnabled; destination.Diagnostics.IsLoggingContentEnabled = source.Diagnostics.IsLoggingContentEnabled; - destination.Diagnostics.IsDistributedTracingEnabled = false; + destination.Diagnostics.IsDistributedTracingEnabled = source.Diagnostics.IsDistributedTracingEnabled; return destination; } } diff --git a/src/DurableTask.AzureStorage/Storage/Blob.cs b/src/DurableTask.AzureStorage/Storage/Blob.cs index 4eb856500..f32b12644 100644 --- a/src/DurableTask.AzureStorage/Storage/Blob.cs +++ b/src/DurableTask.AzureStorage/Storage/Blob.cs @@ -28,6 +28,8 @@ class Blob readonly AzureStorageClient azureStorageClient; readonly BlockBlobClient originalBlockBlobClient; BlockBlobClient? cachedBlockBlobClient; + + // During migration we use a blob client that relies on short-lived SAS tokens BlockBlobClient blockBlobClient => Volatile.Read(ref this.cachedBlockBlobClient) ?? LazyInitializer.EnsureInitialized(ref this.cachedBlockBlobClient, () => this.azureStorageClient.GetBlockBlobClient(this.originalBlockBlobClient))!; diff --git a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs index 8f8a6bd22..0d337f5ac 100644 --- a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs +++ b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs @@ -29,6 +29,7 @@ namespace DurableTask.AzureStorage.Tests using Azure.Core.Pipeline; using Azure.Data.Tables; using Azure.Storage.Blobs; + using Azure.Storage.Blobs.Models; using Azure.Storage.Queues; using DurableTask.AzureStorage.Http; using DurableTask.AzureStorage.Storage; @@ -586,7 +587,7 @@ public async Task StorageClients_CachedWrappersRenewAndStopAfterDrain(bool share 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 drain. + // 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; @@ -604,6 +605,114 @@ public async Task StorageClients_CachedWrappersRenewAndStopAfterDrain(bool share } } + [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(); + AzureStorageClient client = storage.CreateClient(); + 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. No renewal runs after stop, but a later explicit restart still works. + int reads = storage.GateReads; + int writes = storage.GateWrites; + await Task.Delay(TimeSpan.FromSeconds(2.2)); + Assert.AreEqual(reads, storage.GateReads); + Assert.AreEqual(writes, storage.GateWrites); + 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_PreserveBlobEncryptionOptions(bool customerProvidedKey) + { + // 1. Configure either a customer key or an encryption scope on the provider. + string key = Convert.ToBase64String(new byte[32]); + BlobClientOptions options = new() + { + CustomerProvidedKey = customerProvidedKey ? new CustomerProvidedKey(key) : null, + EncryptionScope = customerProvidedKey ? null : "migration-scope", + }; + using StorageResponses storage = new(blobOptions: options); + AzureStorageClient client = storage.CreateClient(); + string headerName = customerProvidedKey ? "x-ms-encryption-key" : "x-ms-encryption-scope"; + string expected = customerProvidedKey ? key : "migration-scope"; + int requests = 0; + storage.BeforeWorkload = request => + { + Assert.IsTrue(request.Headers.TryGetValues(headerName, out IEnumerable? values)); + Assert.AreEqual(expected, values!.Single()); + requests++; + }; + try + { + // 2. Both container and URI wrappers keep the setting in their SAS requests. + await client.GetBlobContainerReference("workload").GetBlobReference("payload").UploadTextAsync("payload"); + await client.GetBlobReference(new Uri("https://account.blob.core.windows.net/workload/uri-payload")) + .UploadTextAsync("payload"); + Assert.AreEqual(2, requests); + } + finally + { + await client.StopMigrationTokenRefreshAsync(); + } + } + [DataTestMethod] [DataRow(false)] [DataRow(true)] @@ -680,7 +789,7 @@ public async Task StorageClients_ManagementUsesOriginalCredentialsAndBlocksResou } Assert.AreEqual(3, storage.Workload.Count); - // 3. Management calls also stop after the client observes drain. + // 3. Management calls also stop after the client observes migration ending. await storage.EndAsync(); await client.InitializeMigrationAsync(refresh: true); foreach (Func create in creates) @@ -810,18 +919,21 @@ sealed class StorageResponses : HttpPipelineTransport, IDisposable readonly int managementRetries; int revision; - public StorageResponses(bool sharedKey = false, int retries = 0) + public StorageResponses( + bool sharedKey = false, + int retries = 0, + BlobClientOptions? blobOptions = null) { this.managementRetries = retries; 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.ForBlob(connection, this.Options(blobOptions ?? new BlobClientOptions())), StorageServiceClientProvider.ForQueue(connection, this.Options(new QueueClientOptions())), StorageServiceClientProvider.ForTable(connection, this.Options(new TableClientOptions()))) : new StorageAccountClientProvider( - StorageServiceClientProvider.ForBlob("account", credential, this.Options(new BlobClientOptions())), + StorageServiceClientProvider.ForBlob("account", credential, this.Options(blobOptions ?? new BlobClientOptions())), StorageServiceClientProvider.ForQueue("account", credential, this.Options(new QueueClientOptions())), StorageServiceClientProvider.ForTable("account", credential, this.Options(new TableClientOptions()))); this.Control = new AzureStorageMigration(this.provider.Table.CreateClient(this.provider.Table.CreateOptions()), "TestHub"); @@ -849,6 +961,7 @@ public StorageResponses(bool sharedKey = false, int retries = 0) 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(); @@ -953,6 +1066,7 @@ 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()); From f6a61444965db52d684f7489a3aa71a21c45504d Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Wed, 2 Dec 2026 11:00:19 -0800 Subject: [PATCH 3/6] added an options factory to avoid the fragile individual copying of settings --- .../DefaultStorageServiceClientProvider.cs | 24 +- .../IStorageServiceClientProvider.cs | 1 + .../Storage/AzureStorageClient.cs | 55 ++--- .../Storage/MigrationSasManager.cs | 8 +- src/DurableTask.AzureStorage/Storage/Table.cs | 2 +- .../Storage/TableUserDelegationKey.cs | 13 +- .../StorageServiceClientProvider.cs | 221 ++++++++++++++++-- .../MigrationSasManagerTests.cs | 91 +++++--- .../StorageServiceClientProviderTests.cs | 103 +++++++- .../TableUserDelegationKeyTests.cs | 15 +- 10 files changed, 429 insertions(+), 104 deletions(-) diff --git a/src/DurableTask.AzureStorage/DefaultStorageServiceClientProvider.cs b/src/DurableTask.AzureStorage/DefaultStorageServiceClientProvider.cs index 10ac513b7..e29de33d3 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("Migration requires fresh client options. 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 821ad0a7b..47f40aa52 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 a4d08a8b7..01af5e87a 100644 --- a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs +++ b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs @@ -259,32 +259,17 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings, Gui // Retry authentication failures once with a refreshed SAS. MigrationSasRetryPolicy sasRetry = new(this.migration); - // Keep migration policies off options shared with other clients. - this.sasQueueOptions = CopyTransportOptions( - queueManagementOptions!, - new QueueClientOptions - { - Audience = queueManagementOptions!.Audience, - GeoRedundantSecondaryUri = queueManagementOptions.GeoRedundantSecondaryUri, - }); + // Get fresh provider options before adding migration policies. + this.sasQueueOptions = CreateMigrationOptions(settings.StorageAccountClientProvider.Queue, queueManagementOptions!); this.sasQueueOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); ConfigureQueueClientPolicies(this.sasQueueOptions); this.sasQueueOptions.AddPolicy(new MigrationRequestPolicy(this.migration, useDelegationVersion: true), HttpPipelinePosition.PerRetry); - this.sasTableOptions = CopyTransportOptions( - tableManagementOptions!, - new TableClientOptions { Audience = tableManagementOptions!.Audience }); + TrackingServiceClientProvider trackingProvider = settings.TrackingServiceClientProvider ?? settings.StorageAccountClientProvider; + this.sasTableOptions = CreateMigrationOptions(trackingProvider.Table, tableManagementOptions!); this.sasTableOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); ConfigureClientPolicies(this.sasTableOptions); this.sasTableOptions.AddPolicy(new MigrationRequestPolicy(this.migration, useDelegationVersion: true), HttpPipelinePosition.PerRetry); - this.sasBlobOptions = CopyTransportOptions( - blobManagementOptions!, - new BlobClientOptions - { - Audience = blobManagementOptions!.Audience, - GeoRedundantSecondaryUri = blobManagementOptions.GeoRedundantSecondaryUri, - CustomerProvidedKey = blobManagementOptions.CustomerProvidedKey, - EncryptionScope = blobManagementOptions.EncryptionScope, - }); + this.sasBlobOptions = CreateMigrationOptions(trackingProvider.Blob, blobManagementOptions!); this.sasBlobOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); ConfigureClientPolicies(this.sasBlobOptions); this.sasBlobOptions.AddPolicy(new MigrationRequestPolicy(this.migration), HttpPipelinePosition.PerRetry); @@ -414,23 +399,25 @@ static TClient CreateClient( return storageProvider.CreateClient(options); } - static TOptions CopyTransportOptions(ClientOptions source, TOptions destination) where TOptions : ClientOptions + static TOptions CreateMigrationOptions( + IStorageServiceClientProvider provider, + TOptions managementOptions) + where TOptions : ClientOptions { - destination.Transport = source.Transport; - destination.Retry.Mode = source.Retry.Mode; - destination.Retry.Delay = source.Retry.Delay; - destination.Retry.MaxDelay = source.Retry.MaxDelay; + 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; - // Limit request duration during migration by disabling SDK retries. - // This is necessary so that we can maintain strict bounds on how long a request can take. + // Disable SDK retries so that migration can rely on a strict deadline per request. // Authentication failures still get one refresh and retry. - destination.Retry.MaxRetries = 0; - destination.Retry.NetworkTimeout = source.Retry.NetworkTimeout; - destination.Diagnostics.ApplicationId = source.Diagnostics.ApplicationId; - destination.Diagnostics.IsLoggingEnabled = source.Diagnostics.IsLoggingEnabled; - destination.Diagnostics.IsLoggingContentEnabled = source.Diagnostics.IsLoggingContentEnabled; - destination.Diagnostics.IsDistributedTracingEnabled = source.Diagnostics.IsDistributedTracingEnabled; - return destination; + options.RetryPolicy = null; + options.Retry.MaxRetries = 0; + return options; } } } diff --git a/src/DurableTask.AzureStorage/Storage/MigrationSasManager.cs b/src/DurableTask.AzureStorage/Storage/MigrationSasManager.cs index 379c32a99..656d533f9 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/Table.cs b/src/DurableTask.AzureStorage/Storage/Table.cs index 7967db4f6..176eaf6ce 100644 --- a/src/DurableTask.AzureStorage/Storage/Table.cs +++ b/src/DurableTask.AzureStorage/Storage/Table.cs @@ -74,7 +74,7 @@ public async Task ExistsAsync(CancellationToken cancellationToken = defaul this.azureStorageClient.EnsureAccess(); // 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); diff --git a/src/DurableTask.AzureStorage/Storage/TableUserDelegationKey.cs b/src/DurableTask.AzureStorage/Storage/TableUserDelegationKey.cs index d74439437..4f9d200be 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 9c20fe703..57304fa12 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/MigrationSasManagerTests.cs b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs index 0d337f5ac..9c21db988 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,6 +29,7 @@ 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; @@ -655,12 +657,8 @@ public async Task StorageClients_StopWaitsForInitializationOrRestart(bool restar } await Task.WhenAll(stopping, repeatedStop); - // 3. No renewal runs after stop, but a later explicit restart still works. + // 3. After stop, a later explicit restart still works. int reads = storage.GateReads; - int writes = storage.GateWrites; - await Task.Delay(TimeSpan.FromSeconds(2.2)); - Assert.AreEqual(reads, storage.GateReads); - Assert.AreEqual(writes, storage.GateWrites); await client.InitializeMigrationAsync(refresh: true); Assert.IsTrue(storage.GateReads > reads); } @@ -679,37 +677,49 @@ public async Task StorageClients_StopWaitsForInitializationOrRestart(bool restar [DataTestMethod] [DataRow(false)] [DataRow(true)] - public async Task StorageClients_PreserveBlobEncryptionOptions(bool customerProvidedKey) + public async Task StorageClients_OptionsFactoryPreservesPoliciesWithoutSharingMigrationSettings(bool sharedKey) { - // 1. Configure either a customer key or an encryption scope on the provider. - string key = Convert.ToBase64String(new byte[32]); - BlobClientOptions options = new() - { - CustomerProvidedKey = customerProvidedKey ? new CustomerProvidedKey(key) : null, - EncryptionScope = customerProvidedKey ? null : "migration-scope", - }; - using StorageResponses storage = new(blobOptions: options); - AzureStorageClient client = storage.CreateClient(); - string headerName = customerProvidedKey ? "x-ms-encryption-key" : "x-ms-encryption-scope"; - string expected = customerProvidedKey ? key : "migration-scope"; + // 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.IsTrue(request.Headers.TryGetValues(headerName, out IEnumerable? values)); - Assert.AreEqual(expected, values!.Single()); + Assert.AreEqual("x", request.Headers.GetValues("x-options-policy").Single()); requests++; }; + AzureStorageClient migrating = storage.CreateClient(); try { - // 2. Both container and URI wrappers keep the setting in their SAS requests. - await client.GetBlobContainerReference("workload").GetBlobReference("payload").UploadTextAsync("payload"); - await client.GetBlobReference(new Uri("https://account.blob.core.windows.net/workload/uri-payload")) - .UploadTextAsync("payload"); - Assert.AreEqual(2, requests); + // 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"; + AzureStorageClient ordinary = storage.CreateClient(migrating: false); + foreach (Func write in CachedWrites(ordinary).Take(3)) + { + await write(); + } + Assert.AreEqual(7, requests); + 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 client.StopMigrationTokenRefreshAsync(); + await migrating.StopMigrationTokenRefreshAsync(); } } @@ -798,7 +808,7 @@ public async Task StorageClients_ManagementUsesOriginalCredentialsAndBlocksResou } Assert.AreEqual(3, storage.Workload.Count); - // 4. Sharing provider options does not restrict an ordinary client. + // 4. Sharing the provider does not restrict an ordinary client. AzureStorageClient ordinary = storage.CreateClient(migrating: false); await ordinary.GetQueueReference("workload").AddMessageAsync("payload", null); Assert.IsFalse(ordinary.IsMigrationActive); @@ -912,30 +922,42 @@ static Dictionary Query(string signature) => signature.TrimStart .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, int retries = 0, - BlobClientOptions? blobOptions = null) + 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(blobOptions ?? 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(blobOptions ?? 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 { @@ -1039,6 +1061,7 @@ T Options(T options) where T : ClientOptions options.Transport = this; options.Retry.Delay = TimeSpan.Zero; options.Retry.MaxRetries = this.managementRetries; + this.configureOptions?.Invoke(options); return options; } diff --git a/test/DurableTask.AzureStorage.Tests/StorageServiceClientProviderTests.cs b/test/DurableTask.AzureStorage.Tests/StorageServiceClientProviderTests.cs index 6d138478c..a03283763 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(() => new AzureStorageClient(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 bb03ee421..744276a3c 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); From 183885ac58a08ebac242340a36939d7c5283d452 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Wed, 2 Dec 2026 11:03:36 -0800 Subject: [PATCH 4/6] updating an exception message to remove migration references --- .../DefaultStorageServiceClientProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/DurableTask.AzureStorage/DefaultStorageServiceClientProvider.cs b/src/DurableTask.AzureStorage/DefaultStorageServiceClientProvider.cs index e29de33d3..2e47d737f 100644 --- a/src/DurableTask.AzureStorage/DefaultStorageServiceClientProvider.cs +++ b/src/DurableTask.AzureStorage/DefaultStorageServiceClientProvider.cs @@ -51,7 +51,7 @@ public TClientOptions CreateFreshOptions() TClientOptions options = this.optionsFactory(); if (ReferenceEquals(options, this.sharedOptions)) { - throw new InvalidOperationException("Migration requires fresh client options. Use an options factory that returns a new options object on every call."); + throw new InvalidOperationException("Fresh client options are required. Use an options factory that returns a new options object on every call."); } return options; } From 9e9f8b0745ea1892d4b5a6234ba5787a0bc76cdb Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Wed, 2 Dec 2026 12:14:17 -0800 Subject: [PATCH 5/6] moved to a sequential initialization model --- .../Storage/AzureStorageClient.cs | 98 +++------ src/DurableTask.AzureStorage/Storage/Blob.cs | 27 ++- .../Storage/BlobContainer.cs | 30 ++- src/DurableTask.AzureStorage/Storage/Queue.cs | 13 +- src/DurableTask.AzureStorage/Storage/Table.cs | 18 +- .../MigrationSasManagerTests.cs | 204 ++++++++++++++++++ 6 files changed, 293 insertions(+), 97 deletions(-) diff --git a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs index 01af5e87a..0736eb684 100644 --- a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs +++ b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs @@ -33,9 +33,8 @@ class AzureStorageClient readonly TableServiceClient tableClient; readonly MigrationSasManager? migration; readonly bool isMigrationActive; - readonly object? initializationLock; - Task? migrationInitialization; - Task migrationRefreshStop = Task.CompletedTask; + readonly SemaphoreSlim? initializationLock; + volatile bool migrationInitialized; readonly QueueClientOptions? sasQueueOptions; readonly TableClientOptions? sasTableOptions; readonly BlobClientOptions? sasBlobOptions; @@ -47,97 +46,64 @@ class AzureStorageClient public bool IsMigrationActive => this.isMigrationActive; public bool IsMigrationEnding => this.isMigrationActive && this.migration!.IsMigrationEnding; - public async Task InitializeMigrationAsync(bool refresh = false) + public async Task InitializeMigrationAsync( + bool refresh = false, + CancellationToken cancellationToken = default) { - if (!this.IsMigrationActive) + // If no migration is active, or if migration has already been initialized and no refresh is requested, return early. + if (!this.IsMigrationActive || (!refresh && this.migrationInitialized)) { return; } - Task initialization; - lock (this.initializationLock!) + await this.initializationLock!.WaitAsync(cancellationToken).ConfigureAwait(false); + try { - if (this.migrationInitialization is null || - (refresh && this.migrationInitialization.Status == TaskStatus.RanToCompletion)) + // Another caller may have initialized while we waited. + if (refresh || !this.migrationInitialized) { - Task stopping = this.migrationRefreshStop; - // Run on the thread pool because synchronous SDK wrapper properties also call this method. - this.migrationInitialization = Task.Run(async () => - { - // Finish an earlier stop before starting a new renewal loop. - await stopping.ConfigureAwait(false); - await this.InitializeMigrationCoreAsync().ConfigureAwait(false); - }); + this.migrationInitialized = false; + await this.migration!.RefreshAsync(cancellationToken).ConfigureAwait(false); + _ = this.migration.StartRefreshLoop(); + this.migrationInitialized = true; } - initialization = this.migrationInitialization; - } - - try - { - await initialization.ConfigureAwait(false); } - catch + finally { - lock (this.initializationLock!) - { - // Do not clear a newer initialization started by another caller. - if (ReferenceEquals(this.migrationInitialization, initialization)) - { - this.migrationInitialization = null; - } - } - throw; + this.initializationLock.Release(); } } - public Task StopMigrationTokenRefreshAsync() + public async Task StopMigrationTokenRefreshAsync() { if (!this.IsMigrationActive) { - return Task.CompletedTask; + return; } - lock (this.initializationLock!) + // Finish initialization before stopping the loop it starts. + await this.initializationLock!.WaitAsync().ConfigureAwait(false); + try { - Task initialization = this.migrationInitialization ?? Task.CompletedTask; - Task stopping = this.migrationRefreshStop; - return this.migrationRefreshStop = Task.Run(async () => - { - // Keep repeated stops in order before allowing a restart. - await stopping.ConfigureAwait(false); - - // Wait for initialization or restart before stopping the loop it creates. - try - { - await initialization.ConfigureAwait(false); - } - catch - { - // The initialization caller handles the failure; stopping must still finish. - } - await this.migration!.StopRefreshing().ConfigureAwait(false); - }); + await this.migration!.StopRefreshing().ConfigureAwait(false); + } + finally + { + this.initializationLock.Release(); } } - async Task InitializeMigrationCoreAsync() - { - await this.migration!.RefreshAsync(CancellationToken.None).ConfigureAwait(false); - _ = this.migration!.StartRefreshLoop(); - } - - public void EnsureAccess() + public async Task EnsureAccessAsync(CancellationToken cancellationToken) { if (this.isMigrationActive) { - this.InitializeMigrationAsync().GetAwaiter().GetResult(); + await this.InitializeMigrationAsync(cancellationToken: cancellationToken).ConfigureAwait(false); this.migration!.EnsureAccess(); } } public void ThrowIfMigrationResourceDeletion() { - this.EnsureAccess(); if (this.isMigrationActive) { throw new OrchestrationServiceUnavailableException("Task hub resource deletion is not supported during migration."); @@ -146,7 +112,6 @@ public void ThrowIfMigrationResourceDeletion() public QueueClient GetQueueClient(QueueClient original) { - this.EnsureAccess(); return !this.isMigrationActive ? original : this.sasQueues!.GetOrAdd( original.Name, name => new QueueClient(original.Uri, this.migration!.GetCredential('q', name), this.sasQueueOptions)); @@ -154,7 +119,6 @@ public QueueClient GetQueueClient(QueueClient original) public TableClient GetTableClient(TableClient original) { - this.EnsureAccess(); return !this.isMigrationActive ? original : this.sasTables!.GetOrAdd( original.Name, name => new TableClient(original.Uri, this.migration!.GetCredential('t', name), this.sasTableOptions)); @@ -162,7 +126,6 @@ public TableClient GetTableClient(TableClient original) public BlobContainerClient GetBlobContainerClient(BlobContainerClient original) { - this.EnsureAccess(); return !this.isMigrationActive ? original : this.sasContainers!.GetOrAdd( original.Name, name => new BlobContainerClient(original.Uri, this.migration!.GetCredential('b', name), this.sasBlobOptions)); @@ -170,7 +133,6 @@ public BlobContainerClient GetBlobContainerClient(BlobContainerClient original) public BlockBlobClient GetBlockBlobClient(BlockBlobClient original) { - this.EnsureAccess(); return !this.isMigrationActive ? original : this.GetBlobContainerClient( this.blobClient.GetBlobContainerClient(original.BlobContainerName)).GetBlockBlobClient(original.Name); } @@ -242,7 +204,7 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings, Gui if (migrationId.HasValue) { - this.initializationLock = new object(); + this.initializationLock = new SemaphoreSlim(1, 1); this.sasQueues = new ConcurrentDictionary(); this.sasTables = new ConcurrentDictionary(); this.sasContainers = new ConcurrentDictionary(); diff --git a/src/DurableTask.AzureStorage/Storage/Blob.cs b/src/DurableTask.AzureStorage/Storage/Blob.cs index f32b12644..7c1250831 100644 --- a/src/DurableTask.AzureStorage/Storage/Blob.cs +++ b/src/DurableTask.AzureStorage/Storage/Blob.cs @@ -61,22 +61,26 @@ public Blob(AzureStorageClient azureStorageClient, BlobServiceClient blobService public async Task ExistsAsync(CancellationToken cancellationToken = default) { - return await this.blockBlobClient.ExistsAsync(cancellationToken).DecorateFailure(); + // Checking existence only reads data, so migration credentials are not needed. + return await this.originalBlockBlobClient.ExistsAsync(cancellationToken).DecorateFailure(); } public async Task DeleteIfExistsAsync(CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); return await this.blockBlobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, cancellationToken: cancellationToken).DecorateFailure(); } public async Task IsLeasedAsync(CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); BlobProperties properties = await this.blockBlobClient.GetPropertiesAsync(cancellationToken: cancellationToken).DecorateFailure(); return properties.LeaseState == LeaseState.Leased; } public async Task UploadTextAsync(string content, string? leaseId = null, bool ifDoesntExist = false, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); BlobRequestConditions? conditions = null; if (ifDoesntExist) { @@ -93,12 +97,14 @@ public async Task UploadTextAsync(string content, string? leaseId = null, bool i public async Task UploadFromByteArrayAsync(byte[] buffer, int index, int byteCount, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); using var stream = new MemoryStream(buffer, index, byteCount, writable: false); await this.blockBlobClient.UploadAsync(stream, cancellationToken: cancellationToken).DecorateFailure(); } public async Task OpenWriteAsync(CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); try { return await this.blockBlobClient.OpenWriteAsync(overwrite: true, cancellationToken: cancellationToken); @@ -111,24 +117,28 @@ public async Task OpenWriteAsync(CancellationToken cancellationToken = d public async Task DownloadTextAsync(CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); using BlobDownloadStreamingResult result = await this.blockBlobClient.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 Task DownloadToStreamAsync(MemoryStream target, CancellationToken cancellationToken = default) { - return this.blockBlobClient.DownloadToAsync(target, cancellationToken: cancellationToken).DecorateFailure(); + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await this.blockBlobClient.DownloadToAsync(target, cancellationToken: cancellationToken).DecorateFailure(); } public async Task DownloadStreamingAsync(CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); return await this.blockBlobClient.DownloadStreamingAsync(cancellationToken: cancellationToken).DecorateFailure(); } public async Task AcquireLeaseAsync(TimeSpan leaseInterval, string leaseId, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); BlobLease lease = await this.blockBlobClient .GetBlobLeaseClient(leaseId) .AcquireAsync(leaseInterval, cancellationToken: cancellationToken) @@ -139,6 +149,7 @@ public async Task AcquireLeaseAsync(TimeSpan leaseInterval, string lease public async Task ChangeLeaseAsync(string proposedLeaseId, string currentLeaseId, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); BlobLease lease = await this.blockBlobClient .GetBlobLeaseClient(currentLeaseId) .ChangeAsync(proposedLeaseId, cancellationToken: cancellationToken) @@ -147,17 +158,19 @@ public async Task ChangeLeaseAsync(string proposedLeaseId, string curren return lease.LeaseId; } - public Task RenewLeaseAsync(string leaseId, CancellationToken cancellationToken = default) + public async Task RenewLeaseAsync(string leaseId, CancellationToken cancellationToken = default) { - return this.blockBlobClient + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await this.blockBlobClient .GetBlobLeaseClient(leaseId) .RenewAsync(cancellationToken: cancellationToken) .DecorateFailure(); } - public Task ReleaseLeaseAsync(string leaseId, CancellationToken cancellationToken = default) + public async Task ReleaseLeaseAsync(string leaseId, CancellationToken cancellationToken = default) { - return this.blockBlobClient + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await this.blockBlobClient .GetBlobLeaseClient(leaseId) .ReleaseAsync(cancellationToken: cancellationToken) .DecorateFailure(); diff --git a/src/DurableTask.AzureStorage/Storage/BlobContainer.cs b/src/DurableTask.AzureStorage/Storage/BlobContainer.cs index f404955ff..05351be3d 100644 --- a/src/DurableTask.AzureStorage/Storage/BlobContainer.cs +++ b/src/DurableTask.AzureStorage/Storage/BlobContainer.cs @@ -29,11 +29,6 @@ class BlobContainer readonly AzureStorageClient azureStorageClient; readonly string containerName; readonly BlobContainerClient originalBlobContainerClient; - BlobContainerClient? cachedBlobContainerClient; - - // During migration we use a blob container client that relies on short-lived SAS tokens - BlobContainerClient blobContainerClient => Volatile.Read(ref this.cachedBlobContainerClient) - ?? LazyInitializer.EnsureInitialized(ref this.cachedBlobContainerClient, () => this.azureStorageClient.GetBlobContainerClient(this.originalBlobContainerClient))!; public BlobContainer(AzureStorageClient azureStorageClient, BlobServiceClient blobServiceClient, string name) { @@ -52,7 +47,7 @@ public Blob GetBlobReference(string blobName, string? blobPrefix = null) public async Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { // This management call needs the original credentials and an explicit access check. - this.azureStorageClient.EnsureAccess(); + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); // TODO: Any encryption scope? // If we received null, then the response must have been a 409 (Conflict) and the container must already exist Response response = await this.originalBlobContainerClient.CreateIfNotExistsAsync(PublicAccessType.None, cancellationToken: cancellationToken).DecorateFailure(); @@ -61,8 +56,7 @@ public async Task CreateIfNotExistsAsync(CancellationToken cancellationTok public async Task ExistsAsync(CancellationToken cancellationToken = default) { - // This management call needs the original credentials and an explicit access check. - this.azureStorageClient.EnsureAccess(); + // Checking existence only reads data, so migration credentials are not needed. return await this.originalBlobContainerClient.ExistsAsync(cancellationToken).DecorateFailure(); } @@ -75,14 +69,18 @@ public async Task DeleteIfExistsAsync(string? appLeaseId = null, Cancellat conditions = new BlobRequestConditions { LeaseId = appLeaseId }; } - return await this.blobContainerClient.DeleteIfExistsAsync(conditions, cancellationToken).DecorateFailure(); + return await this.originalBlobContainerClient.DeleteIfExistsAsync(conditions, cancellationToken).DecorateFailure(); } 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" - return this.blobContainerClient + // so we must filter them out by checking for a special piece of metadata called "hdi_isfolder". + + // During migration, we can still use the original credentials to perform reads (but not writes). + // Using them here avoids wrapping lazy pages to initialize SAS. + // Other async reads, such as blob downloads, can await that initialization directly. + return this.originalBlobContainerClient .GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, prefix, cancellationToken) .DecorateFailure() .TransformPages(p => p.Values @@ -93,7 +91,7 @@ public AsyncPageable ListBlobsAsync(string? prefix = null, CancellationTok public async Task AcquireLeaseAsync(TimeSpan leaseInterval, string leaseId, CancellationToken cancellationToken = default) { // This management call needs the original credentials and an explicit access check. - this.azureStorageClient.EnsureAccess(); + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); BlobLease lease = await this.originalBlobContainerClient .GetBlobLeaseClient(leaseId) .AcquireAsync(leaseInterval, cancellationToken: cancellationToken) @@ -105,7 +103,7 @@ public async Task AcquireLeaseAsync(TimeSpan leaseInterval, string lease public async Task ChangeLeaseAsync(string proposedLeaseId, string currentLeaseId, CancellationToken cancellationToken = default) { // This management call needs the original credentials and an explicit access check. - this.azureStorageClient.EnsureAccess(); + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); BlobLease lease = await this.originalBlobContainerClient .GetBlobLeaseClient(currentLeaseId) .ChangeAsync(proposedLeaseId, cancellationToken: cancellationToken) @@ -114,11 +112,11 @@ public async Task ChangeLeaseAsync(string proposedLeaseId, string curren return lease.LeaseId; } - public Task RenewLeaseAsync(string leaseId, CancellationToken cancellationToken = default) + public async Task RenewLeaseAsync(string leaseId, CancellationToken cancellationToken = default) { // This management call needs the original credentials and an explicit access check. - this.azureStorageClient.EnsureAccess(); - return this.originalBlobContainerClient + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); + await this.originalBlobContainerClient .GetBlobLeaseClient(leaseId) .RenewAsync(cancellationToken: cancellationToken) .DecorateFailure(); diff --git a/src/DurableTask.AzureStorage/Storage/Queue.cs b/src/DurableTask.AzureStorage/Storage/Queue.cs index c39c99d31..e663399c0 100644 --- a/src/DurableTask.AzureStorage/Storage/Queue.cs +++ b/src/DurableTask.AzureStorage/Storage/Queue.cs @@ -46,12 +46,14 @@ public Queue(AzureStorageClient azureStorageClient, QueueServiceClient queueServ public async Task GetApproximateMessagesCountAsync(CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); QueueProperties properties = await this.queueClient.GetPropertiesAsync(cancellationToken).DecorateFailure(); return properties.ApproximateMessagesCount; } public async Task AddMessageAsync(string message, TimeSpan? visibilityDelay, Guid? clientRequestId = null, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); using IDisposable scope = OperationContext.CreateClientRequestScope(clientRequestId); await this.queueClient .SendMessageAsync( @@ -66,6 +68,7 @@ await this.queueClient public async Task UpdateMessageAsync(QueueMessage queueMessage, TimeSpan visibilityTimeout, Guid? clientRequestId = null, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); using IDisposable scope = OperationContext.CreateClientRequestScope(clientRequestId); UpdateReceipt receipt = await this.queueClient .UpdateMessageAsync( @@ -81,6 +84,7 @@ public async Task UpdateMessageAsync(QueueMessage queueMessage, T public async Task DeleteMessageAsync(QueueMessage queueMessage, Guid? clientRequestId = null, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); using IDisposable scope = OperationContext.CreateClientRequestScope(clientRequestId); await this.queueClient .DeleteMessageAsync( @@ -94,6 +98,7 @@ await this.queueClient public async Task GetMessageAsync(TimeSpan visibilityTimeout, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); QueueMessage message = await this.queueClient.ReceiveMessageAsync(visibilityTimeout, cancellationToken).DecorateFailure(); if (message == null) @@ -107,13 +112,14 @@ await this.queueClient public async Task ExistsAsync(CancellationToken cancellationToken = default) { - return await this.queueClient.ExistsAsync(cancellationToken).DecorateFailure(); + // Checking existence only reads data, so migration credentials are not needed. + return await this.originalQueueClient.ExistsAsync(cancellationToken).DecorateFailure(); } public async Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { // This management call needs the original credentials and an explicit access check. - this.azureStorageClient.EnsureAccess(); + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); // If we received null, then the response must have been a 409 (Conflict) and the queue must already exist Response response = await this.originalQueueClient.CreateIfNotExistsAsync(cancellationToken: cancellationToken).DecorateFailure(); return response != null; @@ -127,6 +133,7 @@ public async Task DeleteIfExistsAsync(CancellationToken cancellationToken public async Task> GetMessagesAsync(int batchSize, TimeSpan visibilityTimeout, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); QueueMessage[] messages = await this.queueClient.ReceiveMessagesAsync(batchSize, visibilityTimeout, cancellationToken).DecorateFailure(); this.stats.MessagesRead.Increment(messages.Length); return messages; @@ -134,6 +141,7 @@ public async Task> GetMessagesAsync(int batchS public async Task> PeekMessagesAsync(int batchSize, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); PeekedMessage[] messages = await this.queueClient.PeekMessagesAsync(batchSize, cancellationToken).DecorateFailure(); this.stats.MessagesRead.Increment(messages.Length); return messages; @@ -141,6 +149,7 @@ public async Task> PeekMessagesAsync(int batc public async Task PeekMessageAsync(CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); return await this.queueClient.PeekMessageAsync(cancellationToken).DecorateFailure(); } } diff --git a/src/DurableTask.AzureStorage/Storage/Table.cs b/src/DurableTask.AzureStorage/Storage/Table.cs index 176eaf6ce..ad0497148 100644 --- a/src/DurableTask.AzureStorage/Storage/Table.cs +++ b/src/DurableTask.AzureStorage/Storage/Table.cs @@ -54,7 +54,7 @@ public Table(AzureStorageClient azureStorageClient, TableServiceClient tableServ public async Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { // This management call needs the original credentials and an explicit access check. - this.azureStorageClient.EnsureAccess(); + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); // If we received null, then the response must have been a 409 (Conflict) and the table must already exist Response response = await this.originalTableClient.CreateIfNotExistsAsync(cancellationToken).DecorateFailure(); return response != null; @@ -70,8 +70,7 @@ public async Task DeleteIfExistsAsync(CancellationToken cancellationToken public async Task ExistsAsync(CancellationToken cancellationToken = default) { - // This management call needs the original credentials and an explicit access check. - this.azureStorageClient.EnsureAccess(); + // Checking existence only reads data, so migration credentials are not needed. // 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.Name}'", cancellationToken: cancellationToken) @@ -89,18 +88,21 @@ public async Task DeleteAsync(CancellationToken cancellationToken = default) public async Task ReplaceEntityAsync(T tableEntity, ETag ifMatch, CancellationToken cancellationToken = default) where T : ITableEntity { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); await this.tableClient.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 { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); await this.tableClient.DeleteEntityAsync(tableEntity.PartitionKey, tableEntity.RowKey, ifMatch, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); } public async Task InsertEntityAsync(T tableEntity, CancellationToken cancellationToken = default) where T : ITableEntity { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); Response result = await this.tableClient.AddEntityAsync(tableEntity, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); return result; @@ -108,6 +110,7 @@ public async Task InsertEntityAsync(T tableEntity, CancellationToke public async Task MergeEntityAsync(T tableEntity, ETag ifMatch, CancellationToken cancellationToken = default) where T : ITableEntity { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); Response result = await this.tableClient.UpdateEntityAsync(tableEntity, ifMatch, TableUpdateMode.Merge, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); return result; @@ -115,12 +118,14 @@ public async Task MergeEntityAsync(T tableEntity, ETag ifMatch, Can public async Task InsertOrMergeEntityAsync(T tableEntity, CancellationToken cancellationToken = default) where T : ITableEntity { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); await this.tableClient.UpsertEntityAsync(tableEntity, TableUpdateMode.Merge, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); } public async Task InsertOrReplaceEntityAsync(T tableEntity, CancellationToken cancellationToken = default) where T : ITableEntity { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); await this.tableClient.UpsertEntityAsync(tableEntity, TableUpdateMode.Replace, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); } @@ -232,6 +237,7 @@ async Task DeleteEntitiesIndividuallyAsync( List batch, CancellationToken cancellationToken) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); var responses = new List(); var stopwatch = Stopwatch.StartNew(); int requestCount = 0; @@ -309,6 +315,7 @@ async Task ExecuteBatchAsync( public async Task ExecuteBatchAsync(IEnumerable batchOperation, CancellationToken cancellationToken = default) { + await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); var stopwatch = new Stopwatch(); Response> response = await this.tableClient.SubmitTransactionAsync(batchOperation, cancellationToken).DecorateFailure(); @@ -327,8 +334,11 @@ public TableQueryResponse ExecuteQueryAsync( IEnumerable? select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { + // During migration, we can still use the original credentials to perform reads (but not writes). + // Using them here avoids wrapping lazy pages to initialize SAS. + // Other async reads, such as blob downloads, can await that initialization directly. return new TableQueryResponse( - this.tableClient.QueryAsync(filter, maxPerPage, select, cancellationToken).DecorateFailure(), + this.originalTableClient.QueryAsync(filter, maxPerPage, select, cancellationToken).DecorateFailure(), this.stats); } } diff --git a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs index 9c21db988..ef3f5c50e 100644 --- a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs +++ b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs @@ -892,6 +892,177 @@ public async Task StorageClients_AuthenticationRetryUsesRenewedCredentials(int s } } + [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(); + AzureStorageClient client = storage.CreateClient(); + 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_ReadsUseOriginalCredentialsWithoutInitialization(bool sharedKey) + { + // 1. Make migration initialization fail if any read attempts it. + using StorageResponses storage = new(sharedKey: sharedKey) + { + FailReads = true, + FailKeys = true, + RequireSasAuthentication = false, + }; + AzureStorageClient client = storage.CreateClient(); + try + { + // 2. Queries, listings, and 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.GetQueueReference("workload").ExistsAsync()); + Assert.IsFalse(await client.GetTableReference("Workload").ExistsAsync()); + Assert.IsFalse(await client.GetBlobContainerReference("workload").ExistsAsync()); + Assert.IsFalse(await client.GetBlobContainerReference("workload").GetBlobReference("payload").ExistsAsync()); + + // 3. All reads use the original credentials without reading the migration gate or keys. + Assert.AreEqual(6, 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(); + } + } + + [TestMethod] + [Timeout(10000)] + public async Task StorageClients_CanceledWaiterDoesNotCancelInitialization() + { + // 1. Hold the first caller in initialization. + using StorageResponses storage = new(); + AzureStorageClient client = storage.CreateClient(); + 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"); @@ -1110,6 +1281,34 @@ 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\"}"); @@ -1198,6 +1397,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() { } From c9a3b0475ade2a8439d320407b85ddf83e76e94e Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Thu, 3 Dec 2026 17:43:37 -0800 Subject: [PATCH 6/6] extracted the migration logic into new classes --- .../Storage/AzureStorageClient.cs | 411 +++++------------- src/DurableTask.AzureStorage/Storage/Blob.cs | 108 ++--- .../Storage/BlobContainer.cs | 53 ++- .../Storage/MigratingAzureStorageClient.cs | 202 +++++++++ .../Storage/MigratingBlob.cs | 149 +++++++ .../Storage/MigratingBlobContainer.cs | 77 ++++ .../Storage/MigratingQueue.cs | 123 ++++++ .../Storage/MigratingTable.cs | 126 ++++++ src/DurableTask.AzureStorage/Storage/Queue.cs | 92 ++-- src/DurableTask.AzureStorage/Storage/Table.cs | 97 ++--- .../MigrationSasManagerTests.cs | 142 +++++- .../StorageServiceClientProviderTests.cs | 2 +- 12 files changed, 1088 insertions(+), 494 deletions(-) create mode 100644 src/DurableTask.AzureStorage/Storage/MigratingAzureStorageClient.cs create mode 100644 src/DurableTask.AzureStorage/Storage/MigratingBlob.cs create mode 100644 src/DurableTask.AzureStorage/Storage/MigratingBlobContainer.cs create mode 100644 src/DurableTask.AzureStorage/Storage/MigratingQueue.cs create mode 100644 src/DurableTask.AzureStorage/Storage/MigratingTable.cs diff --git a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs index 0736eb684..4bc8fd8fe 100644 --- a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs +++ b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs @@ -14,130 +14,37 @@ namespace DurableTask.AzureStorage.Storage { using System; - using System.Collections.Concurrent; using System.Text; - 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 Azure.Storage.Queues.Models; using DurableTask.AzureStorage.Http; using DurableTask.AzureStorage.Monitoring; class AzureStorageClient { - readonly BlobServiceClient blobClient; - readonly QueueServiceClient queueClient; - readonly TableServiceClient tableClient; - readonly MigrationSasManager? migration; - readonly bool isMigrationActive; - readonly SemaphoreSlim? initializationLock; - volatile bool migrationInitialized; - readonly QueueClientOptions? sasQueueOptions; - readonly TableClientOptions? sasTableOptions; - readonly BlobClientOptions? sasBlobOptions; - readonly ConcurrentDictionary? sasQueues; - readonly ConcurrentDictionary? sasTables; - readonly ConcurrentDictionary? sasContainers; + 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 event Action? MigrationEnding; - public bool IsMigrationActive => this.isMigrationActive; - public bool IsMigrationEnding => this.isMigrationActive && this.migration!.IsMigrationEnding; - - public async Task InitializeMigrationAsync( - bool refresh = false, - CancellationToken cancellationToken = default) - { - // If no migration is active, or if migration has already been initialized and no refresh is requested, return early. - if (!this.IsMigrationActive || (!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() - { - if (!this.IsMigrationActive) - { - return; - } - - // 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(); - } - } - - public async Task EnsureAccessAsync(CancellationToken cancellationToken) - { - if (this.isMigrationActive) - { - await this.InitializeMigrationAsync(cancellationToken: cancellationToken).ConfigureAwait(false); - this.migration!.EnsureAccess(); - } - } - - public void ThrowIfMigrationResourceDeletion() - { - if (this.isMigrationActive) - { - throw new OrchestrationServiceUnavailableException("Task hub resource deletion is not supported during migration."); - } - } - - public QueueClient GetQueueClient(QueueClient original) - { - return !this.isMigrationActive ? original : this.sasQueues!.GetOrAdd( - original.Name, - name => new QueueClient(original.Uri, this.migration!.GetCredential('q', name), this.sasQueueOptions)); - } - - public TableClient GetTableClient(TableClient original) + public static AzureStorageClient Create( + AzureStorageOrchestrationServiceSettings settings, + Guid? migrationId = null) { - return !this.isMigrationActive ? original : this.sasTables!.GetOrAdd( - original.Name, - name => new TableClient(original.Uri, this.migration!.GetCredential('t', name), this.sasTableOptions)); + return migrationId.HasValue + ? new MigratingAzureStorageClient(settings, migrationId.Value) + : new AzureStorageClient(settings); } - public BlobContainerClient GetBlobContainerClient(BlobContainerClient original) - { - return !this.isMigrationActive ? original : this.sasContainers!.GetOrAdd( - original.Name, - name => new BlobContainerClient(original.Uri, this.migration!.GetCredential('b', name), this.sasBlobOptions)); - } - - public BlockBlobClient GetBlockBlobClient(BlockBlobClient original) - { - return !this.isMigrationActive ? original : this.GetBlobContainerClient( - this.blobClient.GetBlobContainerClient(original.BlobContainerName)).GetBlockBlobClient(original.Name); - } - - public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings, Guid? migrationId = null) + public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings) { if (settings == null) { @@ -149,166 +56,24 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings, Gui throw new ArgumentException("Storage account client provider is not specified.", nameof(settings)); } - this.isMigrationActive = migrationId.HasValue; 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); - - QueueClientOptions? queueManagementOptions = null; - BlobClientOptions? blobManagementOptions = null; - TableClientOptions? tableManagementOptions = null; + this.throttlingPolicy = new ThrottlingHttpPipelinePolicy(settings.MaxStorageOperationConcurrency); + this.timeoutPolicy = new LeaseTimeoutHttpPipelinePolicy(settings.LeaseRenewInterval); + this.monitoringPolicy = new MonitoringHttpPipelinePolicy(this.Stats); this.queueClient = CreateClient( settings.StorageAccountClientProvider.Queue, - options => - { - queueManagementOptions = options; - ConfigureQueueClientPolicies(options); - }); - if (settings.HasTrackingStoreStorageAccount) - { - this.blobClient = CreateClient( - settings.TrackingServiceClientProvider!.Blob, - options => - { - blobManagementOptions = options; - ConfigureClientPolicies(options); - }); - this.tableClient = CreateClient( - settings.TrackingServiceClientProvider!.Table, - options => - { - tableManagementOptions = options; - ConfigureClientPolicies(options); - }); - } - else - { - this.blobClient = CreateClient( - settings.StorageAccountClientProvider.Blob, - options => - { - blobManagementOptions = options; - ConfigureClientPolicies(options); - }); - this.tableClient = CreateClient( - settings.StorageAccountClientProvider.Table, - options => - { - tableManagementOptions = options; - ConfigureClientPolicies(options); - }); - } - - if (migrationId.HasValue) - { - this.initializationLock = new SemaphoreSlim(1, 1); - this.sasQueues = new ConcurrentDictionary(); - this.sasTables = new ConcurrentDictionary(); - this.sasContainers = new ConcurrentDictionary(); - - this.migration = new MigrationSasManager( - settings, - migrationId.Value, - this.blobClient, - this.queueClient, - this.tableClient, - (settings.TrackingServiceClientProvider ?? settings.StorageAccountClientProvider).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(settings.StorageAccountClientProvider.Queue, queueManagementOptions!); - this.sasQueueOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); - ConfigureQueueClientPolicies(this.sasQueueOptions); - this.sasQueueOptions.AddPolicy(new MigrationRequestPolicy(this.migration, useDelegationVersion: true), HttpPipelinePosition.PerRetry); - TrackingServiceClientProvider trackingProvider = settings.TrackingServiceClientProvider ?? settings.StorageAccountClientProvider; - this.sasTableOptions = CreateMigrationOptions(trackingProvider.Table, tableManagementOptions!); - this.sasTableOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); - ConfigureClientPolicies(this.sasTableOptions); - this.sasTableOptions.AddPolicy(new MigrationRequestPolicy(this.migration, useDelegationVersion: true), HttpPipelinePosition.PerRetry); - this.sasBlobOptions = CreateMigrationOptions(trackingProvider.Blob, blobManagementOptions!); - this.sasBlobOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall); - ConfigureClientPolicies(this.sasBlobOptions); - this.sasBlobOptions.AddPolicy(new MigrationRequestPolicy(this.migration), HttpPipelinePosition.PerRetry); - } - - 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.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; } @@ -321,65 +86,119 @@ 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, this.blobClient, container, blobName); + return new Blob(this.blobClient, container, blobName); } - internal Blob GetBlobReference(Uri blobUri) + internal virtual Blob GetBlobReference(Uri blobUri) { - return new Blob(this, this.blobClient, 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); } - static TClient CreateClient( - IStorageServiceClientProvider storageProvider, - Action configurePolicies) - where TClientOptions : ClientOptions + protected void ConfigureClientPolicies(TClientOptions options) where TClientOptions : ClientOptions { - TClientOptions options = storageProvider.CreateOptions(); + options.AddPolicy(this.throttlingPolicy, HttpPipelinePosition.PerCall); + options.AddPolicy(this.timeoutPolicy, HttpPipelinePosition.PerCall); + options.AddPolicy(this.monitoringPolicy, HttpPipelinePosition.PerRetry); + } - // Disable distributed tracing by default to reduce the noise in the traces. - options.Diagnostics.IsDistributedTracingEnabled = false; + 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}") + }; - configurePolicies?.Invoke(options); + // 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; - return storageProvider.CreateClient(options); + 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 TOptions CreateMigrationOptions( - IStorageServiceClientProvider provider, - TOptions managementOptions) - where TOptions : ClientOptions + static TClient CreateClient( + IStorageServiceClientProvider storageProvider, + Action configurePolicies, + out TClientOptions options) + where TClientOptions : 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."); - } + options = storageProvider.CreateOptions(); // 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; + configurePolicies?.Invoke(options); + + return storageProvider.CreateClient(options); } } } diff --git a/src/DurableTask.AzureStorage/Storage/Blob.cs b/src/DurableTask.AzureStorage/Storage/Blob.cs index 7c1250831..9c1299099 100644 --- a/src/DurableTask.AzureStorage/Storage/Blob.cs +++ b/src/DurableTask.AzureStorage/Storage/Blob.cs @@ -25,23 +25,17 @@ namespace DurableTask.AzureStorage.Storage class Blob { - readonly AzureStorageClient azureStorageClient; - readonly BlockBlobClient originalBlockBlobClient; - BlockBlobClient? cachedBlockBlobClient; + readonly BlockBlobClient blockBlobClient; + protected virtual BlockBlobClient Client => this.blockBlobClient; - // During migration we use a blob client that relies on short-lived SAS tokens - BlockBlobClient blockBlobClient => Volatile.Read(ref this.cachedBlockBlobClient) - ?? LazyInitializer.EnsureInitialized(ref this.cachedBlockBlobClient, () => this.azureStorageClient.GetBlockBlobClient(this.originalBlockBlobClient))!; - - public Blob(AzureStorageClient azureStorageClient, BlobServiceClient blobServiceClient, string containerName, string blobName) + public Blob(BlobServiceClient blobServiceClient, string containerName, string blobName) { - this.azureStorageClient = azureStorageClient; - this.originalBlockBlobClient = blobServiceClient + this.blockBlobClient = blobServiceClient .GetBlobContainerClient(containerName) .GetBlockBlobClient(blobName); } - public Blob(AzureStorageClient azureStorageClient, BlobServiceClient blobServiceClient, Uri blobUri) + public Blob(BlobServiceClient blobServiceClient, Uri blobUri) { if (!blobUri.AbsoluteUri.StartsWith(blobServiceClient.Uri.AbsoluteUri, StringComparison.Ordinal)) { @@ -49,38 +43,37 @@ public Blob(AzureStorageClient azureStorageClient, BlobServiceClient blobService } var builder = new BlobUriBuilder(blobUri); - this.azureStorageClient = azureStorageClient; - this.originalBlockBlobClient = blobServiceClient + this.blockBlobClient = blobServiceClient .GetBlobContainerClient(builder.BlobContainerName) .GetBlockBlobClient(builder.BlobName); } - public string Name => this.originalBlockBlobClient.Name; + public string Name => this.blockBlobClient.Name; - public Uri Uri => this.originalBlockBlobClient.Uri; + public Uri Uri => this.blockBlobClient.Uri; - public async Task ExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task ExistsAsync(CancellationToken cancellationToken = default) { - // Checking existence only reads data, so migration credentials are not needed. - return await this.originalBlockBlobClient.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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); BlobRequestConditions? conditions = null; if (ifDoesntExist) { @@ -92,22 +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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); 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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); try { - return await this.blockBlobClient.OpenWriteAsync(overwrite: true, cancellationToken: cancellationToken); + return await this.Client.OpenWriteAsync(overwrite: true, cancellationToken: cancellationToken); } catch (RequestFailedException rfe) { @@ -115,31 +110,32 @@ public async Task OpenWriteAsync(CancellationToken cancellationToken = d } } - public async Task DownloadTextAsync(CancellationToken cancellationToken = default) + public async virtual Task DownloadTextAsync(CancellationToken cancellationToken = default) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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 async Task DownloadToStreamAsync(MemoryStream target, CancellationToken cancellationToken = default) + public async virtual Task DownloadToStreamAsync( + MemoryStream target, + CancellationToken cancellationToken = default) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - await 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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - BlobLease lease = await this.blockBlobClient + BlobLease lease = await this.Client .GetBlobLeaseClient(leaseId) .AcquireAsync(leaseInterval, cancellationToken: cancellationToken) .DecorateFailure(); @@ -147,10 +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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - BlobLease lease = await this.blockBlobClient + BlobLease lease = await this.Client .GetBlobLeaseClient(currentLeaseId) .ChangeAsync(proposedLeaseId, cancellationToken: cancellationToken) .DecorateFailure(); @@ -158,19 +156,21 @@ public async Task ChangeLeaseAsync(string proposedLeaseId, string curren return lease.LeaseId; } - public async Task RenewLeaseAsync(string leaseId, CancellationToken cancellationToken = default) + public async virtual Task RenewLeaseAsync( + string leaseId, + CancellationToken cancellationToken = default) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - await this.blockBlobClient + await this.Client .GetBlobLeaseClient(leaseId) .RenewAsync(cancellationToken: cancellationToken) .DecorateFailure(); } - public async Task ReleaseLeaseAsync(string leaseId, CancellationToken cancellationToken = default) + public async virtual Task ReleaseLeaseAsync( + string leaseId, + CancellationToken cancellationToken = default) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - await 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 05351be3d..9282854fb 100644 --- a/src/DurableTask.AzureStorage/Storage/BlobContainer.cs +++ b/src/DurableTask.AzureStorage/Storage/BlobContainer.cs @@ -28,14 +28,14 @@ class BlobContainer { readonly AzureStorageClient azureStorageClient; readonly string containerName; - readonly BlobContainerClient originalBlobContainerClient; + readonly BlobContainerClient blobContainerClient; public BlobContainer(AzureStorageClient azureStorageClient, BlobServiceClient blobServiceClient, string name) { this.azureStorageClient = azureStorageClient; this.containerName = name; - this.originalBlobContainerClient = blobServiceClient.GetBlobContainerClient(this.containerName); + this.blobContainerClient = blobServiceClient.GetBlobContainerClient(this.containerName); } public Blob GetBlobReference(string blobName, string? blobPrefix = null) @@ -44,32 +44,30 @@ 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) { - // This management call needs the original credentials and an explicit access check. - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); // TODO: Any encryption scope? // If we received null, then the response must have been a 409 (Conflict) and the container must already exist - Response response = await this.originalBlobContainerClient.CreateIfNotExistsAsync(PublicAccessType.None, cancellationToken: cancellationToken).DecorateFailure(); + Response response = await this.blobContainerClient.CreateIfNotExistsAsync(PublicAccessType.None, cancellationToken: cancellationToken).DecorateFailure(); return response != null; } public async Task ExistsAsync(CancellationToken cancellationToken = default) { - // Checking existence only reads data, so migration credentials are not needed. - return await this.originalBlobContainerClient.ExistsAsync(cancellationToken).DecorateFailure(); + 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) { - this.azureStorageClient.ThrowIfMigrationResourceDeletion(); BlobRequestConditions? conditions = null; if (appLeaseId != null) { conditions = new BlobRequestConditions { LeaseId = appLeaseId }; } - return await this.originalBlobContainerClient.DeleteIfExistsAsync(conditions, cancellationToken).DecorateFailure(); + return await this.blobContainerClient.DeleteIfExistsAsync(conditions, cancellationToken).DecorateFailure(); } public AsyncPageable ListBlobsAsync(string? prefix = null, CancellationToken cancellationToken = default) @@ -77,10 +75,7 @@ public AsyncPageable ListBlobsAsync(string? prefix = null, CancellationTok // 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". - // During migration, we can still use the original credentials to perform reads (but not writes). - // Using them here avoids wrapping lazy pages to initialize SAS. - // Other async reads, such as blob downloads, can await that initialization directly. - return this.originalBlobContainerClient + return this.blobContainerClient .GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, prefix, cancellationToken) .DecorateFailure() .TransformPages(p => p.Values @@ -88,11 +83,12 @@ 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) { - // This management call needs the original credentials and an explicit access check. - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - BlobLease lease = await this.originalBlobContainerClient + BlobLease lease = await this.blobContainerClient .GetBlobLeaseClient(leaseId) .AcquireAsync(leaseInterval, cancellationToken: cancellationToken) .DecorateFailure(); @@ -100,11 +96,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) { - // This management call needs the original credentials and an explicit access check. - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - BlobLease lease = await this.originalBlobContainerClient + BlobLease lease = await this.blobContainerClient .GetBlobLeaseClient(currentLeaseId) .ChangeAsync(proposedLeaseId, cancellationToken: cancellationToken) .DecorateFailure(); @@ -112,11 +109,11 @@ public async Task ChangeLeaseAsync(string proposedLeaseId, string curren return lease.LeaseId; } - public async Task RenewLeaseAsync(string leaseId, CancellationToken cancellationToken = default) + public async virtual Task RenewLeaseAsync( + string leaseId, + CancellationToken cancellationToken = default) { - // This management call needs the original credentials and an explicit access check. - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - await this.originalBlobContainerClient + await this.blobContainerClient .GetBlobLeaseClient(leaseId) .RenewAsync(cancellationToken: cancellationToken) .DecorateFailure(); @@ -124,7 +121,7 @@ await this.originalBlobContainerClient public Uri GetBlobContainerUri() { - return this.originalBlobContainerClient.Uri; + return this.blobContainerClient.Uri; } static bool IsHnsFolder(BlobItem item) diff --git a/src/DurableTask.AzureStorage/Storage/MigratingAzureStorageClient.cs b/src/DurableTask.AzureStorage/Storage/MigratingAzureStorageClient.cs new file mode 100644 index 000000000..0e67bb643 --- /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 000000000..f52e06c11 --- /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 000000000..2df597b05 --- /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 000000000..4fa7d4766 --- /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 000000000..de4c63c5e --- /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/Queue.cs b/src/DurableTask.AzureStorage/Storage/Queue.cs index e663399c0..e71d806a7 100644 --- a/src/DurableTask.AzureStorage/Storage/Queue.cs +++ b/src/DurableTask.AzureStorage/Storage/Queue.cs @@ -24,38 +24,34 @@ namespace DurableTask.AzureStorage.Storage class Queue { - readonly AzureStorageClient azureStorageClient; readonly AzureStorageOrchestrationServiceStats stats; - readonly QueueClient originalQueueClient; - QueueClient? cachedQueueClient; - - // During migration we use a queue client that relies on short-lived SAS tokens - QueueClient queueClient => Volatile.Read(ref this.cachedQueueClient) - ?? LazyInitializer.EnsureInitialized(ref this.cachedQueueClient, () => this.azureStorageClient.GetQueueClient(this.originalQueueClient))!; + 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.originalQueueClient = queueServiceClient.GetQueueClient(queueName); + this.stats = azureStorageClient.Stats; + this.queueClient = queueServiceClient.GetQueueClient(queueName); } - public string Name => this.originalQueueClient.Name; + public string Name => this.queueClient.Name; - public Uri Uri => this.originalQueueClient.Uri; + public Uri Uri => this.queueClient.Uri; - public async Task GetApproximateMessagesCountAsync(CancellationToken cancellationToken = default) + public async virtual Task GetApproximateMessagesCountAsync(CancellationToken cancellationToken = default) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); using IDisposable scope = OperationContext.CreateClientRequestScope(clientRequestId); - await this.queueClient + await this.Client .SendMessageAsync( message, visibilityDelay, @@ -66,11 +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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); using IDisposable scope = OperationContext.CreateClientRequestScope(clientRequestId); - UpdateReceipt receipt = await this.queueClient + UpdateReceipt receipt = await this.Client .UpdateMessageAsync( queueMessage.MessageId, queueMessage.PopReceipt, @@ -82,11 +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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); using IDisposable scope = OperationContext.CreateClientRequestScope(clientRequestId); - await this.queueClient + await this.Client .DeleteMessageAsync( queueMessage.MessageId, queueMessage.PopReceipt, @@ -96,10 +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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - QueueMessage message = await this.queueClient.ReceiveMessageAsync(visibilityTimeout, cancellationToken).DecorateFailure(); + QueueMessage message = await this.Client.ReceiveMessageAsync(visibilityTimeout, cancellationToken).DecorateFailure(); if (message == null) { @@ -110,47 +112,45 @@ await this.queueClient return message; } - public async Task ExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task ExistsAsync(CancellationToken cancellationToken = default) { - // Checking existence only reads data, so migration credentials are not needed. - return await this.originalQueueClient.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) { - // This management call needs the original credentials and an explicit access check. - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); // If we received null, then the response must have been a 409 (Conflict) and the queue must already exist - Response response = await this.originalQueueClient.CreateIfNotExistsAsync(cancellationToken: cancellationToken).DecorateFailure(); + 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) { - this.azureStorageClient.ThrowIfMigrationResourceDeletion(); - 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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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 ad0497148..8fac20121 100644 --- a/src/DurableTask.AzureStorage/Storage/Table.cs +++ b/src/DurableTask.AzureStorage/Storage/Table.cs @@ -28,49 +28,39 @@ class Table { const int MaxParallelBatchDeletes = 10; - readonly AzureStorageClient azureStorageClient; readonly AzureStorageOrchestrationServiceStats stats; readonly TableServiceClient tableServiceClient; - readonly TableClient originalTableClient; - TableClient? cachedTableClient; - - // During migration we use a table client that relies on short-lived SAS tokens - TableClient tableClient => Volatile.Read(ref this.cachedTableClient) - ?? LazyInitializer.EnsureInitialized(ref this.cachedTableClient, () => this.azureStorageClient.GetTableClient(this.originalTableClient))!; + 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.originalTableClient = tableServiceClient.GetTableClient(tableName); + this.tableClient = tableServiceClient.GetTableClient(tableName); } - public string Name => this.originalTableClient.Name; + public string Name => this.tableClient.Name; - internal Uri Uri => this.originalTableClient.Uri; + internal Uri Uri => this.tableClient.Uri; - public async Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) + public async virtual Task CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { - // This management call needs the original credentials and an explicit access check. - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); // If we received null, then the response must have been a 409 (Conflict) and the table must already exist - Response response = await this.originalTableClient.CreateIfNotExistsAsync(cancellationToken).DecorateFailure(); + 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) { - this.azureStorageClient.ThrowIfMigrationResourceDeletion(); // 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; } public async Task ExistsAsync(CancellationToken cancellationToken = default) { - // Checking existence only reads data, so migration credentials are not needed. // 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.Name}'", cancellationToken: cancellationToken) @@ -80,53 +70,61 @@ public async Task ExistsAsync(CancellationToken cancellationToken = defaul return tables.Count > 0; } - public async Task DeleteAsync(CancellationToken cancellationToken = default) + public async virtual Task DeleteAsync(CancellationToken cancellationToken = default) { - this.azureStorageClient.ThrowIfMigrationResourceDeletion(); - 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.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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 { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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 { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - 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.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); - await this.tableClient.UpsertEntityAsync(tableEntity, TableUpdateMode.Replace, cancellationToken).DecorateFailure(); + await this.Client.UpsertEntityAsync(tableEntity, TableUpdateMode.Replace, cancellationToken).DecorateFailure(); this.stats.TableEntitiesWritten.Increment(); } @@ -233,11 +231,10 @@ async Task ExecuteBatchWithFallbackAsync( } } - async Task DeleteEntitiesIndividuallyAsync( + protected async virtual Task DeleteEntitiesIndividuallyAsync( List batch, CancellationToken cancellationToken) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); var responses = new List(); var stopwatch = Stopwatch.StartNew(); int requestCount = 0; @@ -247,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, @@ -313,12 +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) { - await this.azureStorageClient.EnsureAccessAsync(cancellationToken).ConfigureAwait(false); 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(); @@ -334,11 +332,8 @@ public TableQueryResponse ExecuteQueryAsync( IEnumerable? select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { - // During migration, we can still use the original credentials to perform reads (but not writes). - // Using them here avoids wrapping lazy pages to initialize SAS. - // Other async reads, such as blob downloads, can await that initialization directly. return new TableQueryResponse( - this.originalTableClient.QueryAsync(filter, maxPerPage, select, cancellationToken).DecorateFailure(), + this.tableClient.QueryAsync(filter, maxPerPage, select, cancellationToken).DecorateFailure(), this.stats); } } diff --git a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs index ef3f5c50e..3ade3cf60 100644 --- a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs +++ b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs @@ -560,7 +560,7 @@ public async Task Requests_CancellationPreventsAuthenticationRetry(bool synchron public async Task StorageClients_CachedWrappersRenewAndStopAfterDrain(bool sharedKey) { using StorageResponses storage = new(sharedKey); - AzureStorageClient client = storage.CreateClient(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); Func[] writes = CachedWrites(client); int ending = 0; client.MigrationEnding += () => ending++; @@ -616,7 +616,7 @@ public async Task StorageClients_CachedWrappersRenewAndStopAfterDrain(bool share public async Task StorageClients_StopWaitsForInitializationOrRestart(bool restart, bool failRefresh) { using StorageResponses storage = new(); - AzureStorageClient client = storage.CreateClient(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); if (restart) { await client.InitializeMigrationAsync(); @@ -690,7 +690,7 @@ public async Task StorageClients_OptionsFactoryPreservesPoliciesWithoutSharingMi Assert.AreEqual("x", request.Headers.GetValues("x-options-policy").Single()); requests++; }; - AzureStorageClient migrating = storage.CreateClient(); + MigratingAzureStorageClient migrating = storage.CreateMigratingClient(); try { // 2. All three SAS clients retain the provider's custom policy. @@ -708,12 +708,18 @@ public async Task StorageClients_OptionsFactoryPreservesPoliciesWithoutSharingMi 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"))); } @@ -723,13 +729,65 @@ public async Task StorageClients_OptionsFactoryPreservesPoliciesWithoutSharingMi } } + [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(); - AzureStorageClient client = storage.CreateClient(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); JObject gate = storage.Row!; storage.Row = missingGate ? null : gate; storage.FailKeys = !missingGate; @@ -763,7 +821,7 @@ public async Task StorageClients_FailedInitializationCanBeRetried(bool missingGa public async Task StorageClients_ManagementUsesOriginalCredentialsAndBlocksResourceDeletion() { using StorageResponses storage = new() { RequireSasAuthentication = false }; - AzureStorageClient client = storage.CreateClient(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); Queue queue = client.GetQueueReference("workload"); Table table = client.GetTableReference("Workload"); BlobContainer container = client.GetBlobContainerReference("workload"); @@ -811,7 +869,7 @@ public async Task StorageClients_ManagementUsesOriginalCredentialsAndBlocksResou // 4. Sharing the provider does not restrict an ordinary client. AzureStorageClient ordinary = storage.CreateClient(migrating: false); await ordinary.GetQueueReference("workload").AddMessageAsync("payload", null); - Assert.IsFalse(ordinary.IsMigrationActive); + Assert.AreEqual(typeof(AzureStorageClient), ordinary.GetType()); Assert.IsFalse(Query(storage.Workload.Last().Query).ContainsKey("timeout")); Assert.IsNotNull(storage.WorkloadAuthorizations.Last()); } @@ -854,7 +912,10 @@ public async Task StorageClients_GenericRetriesChangeOnlyDuringMigration(bool mi } finally { - await client.StopMigrationTokenRefreshAsync(); + if (client is MigratingAzureStorageClient migratingClient) + { + await migratingClient.StopMigrationTokenRefreshAsync(); + } } } @@ -865,7 +926,7 @@ public async Task StorageClients_GenericRetriesChangeOnlyDuringMigration(bool mi public async Task StorageClients_AuthenticationRetryUsesRenewedCredentials(int service) { using StorageResponses storage = new(); - AzureStorageClient client = storage.CreateClient(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); try { // 1. Expire the SAS after the wrapper sends its first request. @@ -905,7 +966,7 @@ public async Task StorageClients_CanceledInitializationCanBeRetried( { // 1. Hold the first operation in a gate or key read. using StorageResponses storage = new(); - AzureStorageClient client = storage.CreateClient(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); TaskCompletionSource started = new(TaskCreationOptions.RunContinuationsAsynchronously); async Task block(CancellationToken token) { @@ -976,7 +1037,7 @@ await client.GetBlobReference(new Uri("https://account.blob.core.windows.net/wor [DataTestMethod] [DataRow(false)] [DataRow(true)] - public async Task StorageClients_ReadsUseOriginalCredentialsWithoutInitialization(bool sharedKey) + public async Task StorageClients_PagingAndResourceChecksUseOriginalCredentials(bool sharedKey) { // 1. Make migration initialization fail if any read attempts it. using StorageResponses storage = new(sharedKey: sharedKey) @@ -985,10 +1046,10 @@ public async Task StorageClients_ReadsUseOriginalCredentialsWithoutInitializatio FailKeys = true, RequireSasAuthentication = false, }; - AzureStorageClient client = storage.CreateClient(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); try { - // 2. Queries, listings, and existence checks still work. + // 2. Paging and table/container existence checks still work. TableQueryResults rows = await client.GetTableReference("Workload") .ExecuteQueryAsync().GetResultsAsync(); Assert.AreEqual(0, rows.Entities.Count); @@ -998,13 +1059,11 @@ public async Task StorageClients_ReadsUseOriginalCredentialsWithoutInitializatio Assert.IsFalse(await blobs.MoveNextAsync()); } - Assert.IsFalse(await client.GetQueueReference("workload").ExistsAsync()); Assert.IsFalse(await client.GetTableReference("Workload").ExistsAsync()); Assert.IsFalse(await client.GetBlobContainerReference("workload").ExistsAsync()); - Assert.IsFalse(await client.GetBlobContainerReference("workload").GetBlobReference("payload").ExistsAsync()); - // 3. All reads use the original credentials without reading the migration gate or keys. - Assert.AreEqual(6, storage.Workload.Count); + // 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); @@ -1023,13 +1082,58 @@ public async Task StorageClients_ReadsUseOriginalCredentialsWithoutInitializatio } } + [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(); - AzureStorageClient client = storage.CreateClient(); + MigratingAzureStorageClient client = storage.CreateMigratingClient(); TaskCompletionSource started = new(TaskCreationOptions.RunContinuationsAsynchronously); TaskCompletionSource release = new(TaskCreationOptions.RunContinuationsAsynchronously); storage.AfterRead = async _ => { started.SetResult(true); await release.Task; }; @@ -1170,7 +1274,9 @@ public StorageResponses( public Func? BeforeKey { get; set; } public AzureStorageMigration Control { get; } - public AzureStorageClient CreateClient(bool migrating = true) => new( + 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); diff --git a/test/DurableTask.AzureStorage.Tests/StorageServiceClientProviderTests.cs b/test/DurableTask.AzureStorage.Tests/StorageServiceClientProviderTests.cs index a03283763..19b2a5d59 100644 --- a/test/DurableTask.AzureStorage.Tests/StorageServiceClientProviderTests.cs +++ b/test/DurableTask.AzureStorage.Tests/StorageServiceClientProviderTests.cs @@ -156,7 +156,7 @@ public void Migration_RejectsSharedOptionsWithoutChangingTheirRetrySettings() _ = new AzureStorageClient(settings); // 2. Migration requires fresh options instead of adding policies to the shared object. - InvalidOperationException error = Assert.ThrowsException(() => new AzureStorageClient(settings, Guid.NewGuid())); + InvalidOperationException error = Assert.ThrowsException(() => AzureStorageClient.Create(settings, Guid.NewGuid())); StringAssert.Contains(error.Message, "options factory"); Assert.AreEqual(7, options.Retry.MaxRetries); }