diff --git a/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs b/src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs index 76b8a267..4178bb9e 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 390a9260..4eb85650 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 a61ac9f5..f404955f 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 a3191330..c39c99d3 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 ebe98065..7967db4f 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 4b1113f4..c9f2cbd4 100644 --- a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs +++ b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs @@ -3052,7 +3052,10 @@ private static async Task ValidateLargeMessageBlobUrlAsync(string taskHubName, s Assert.IsTrue(value.EndsWith(".json.gz")); string blobName = value.Split('/').Last(); - Assert.IsTrue(await new Blob(serviceClient, new Uri(value)).ExistsAsync(), $"Blob named {blobName} is expected to exist."); + BlobUriBuilder blobUri = new(new Uri(value)); + Assert.IsTrue( + await serviceClient.GetBlobContainerClient(blobUri.BlobContainerName).GetBlobClient(blobUri.BlobName).ExistsAsync(), + $"Blob named {blobName} is expected to exist."); string containerName = $"{taskHubName.ToLowerInvariant()}-largemessages"; BlobContainerClient container = serviceClient.GetBlobContainerClient(containerName); diff --git a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs index 6fb93d91..8f8a6bd2 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,