From f52b87a9dd6c11f83d99ace8b96af7ce3ad47d3b Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Mon, 30 Nov 2026 15:25:45 -0800 Subject: [PATCH 1/4] Add migration SAS request and retry policies --- .../Http/MigrationRequestPolicy.cs | 49 ++++ .../Http/MigrationSasRetryPolicy.cs | 68 +++++ .../MigrationSasManagerTests.cs | 238 ++++++++++++++++++ 3 files changed, 355 insertions(+) create mode 100644 src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs create mode 100644 src/DurableTask.AzureStorage/Http/MigrationSasRetryPolicy.cs diff --git a/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs b/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs new file mode 100644 index 000000000..0d3c85b08 --- /dev/null +++ b/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs @@ -0,0 +1,49 @@ +// ---------------------------------------------------------------------------------- +// 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.Http +{ + using System; + using System.Linq; + using Azure.Core; + using Azure.Core.Pipeline; + using DurableTask.AzureStorage.Storage; + + // Check source access before each request, including SDK retries. + sealed class MigrationRequestPolicy : HttpPipelineSynchronousPolicy + { + readonly MigrationSasManager manager; + readonly bool useDelegationVersion; + + public MigrationRequestPolicy(MigrationSasManager manager, bool useDelegationVersion = false) + { + this.manager = manager; + this.useDelegationVersion = useDelegationVersion; + } + + public override void OnSendingRequest(HttpMessage message) + { + this.manager.EnsureAccess(); + // SDK retries reuse the URI. Replace the parameter rather than appending duplicates. + UriBuilder uri = new UriBuilder(message.Request.Uri.ToUri()); + string query = string.Join("&", uri.Query.TrimStart('?').Split('&') + .Where(part => part.Length > 0 && !part.StartsWith("timeout=", StringComparison.OrdinalIgnoreCase))); + uri.Query = query.Length == 0 ? "timeout=30" : query + "&timeout=30"; + message.Request.Uri.Reset(uri.Uri); + if (this.useDelegationVersion) + { + message.Request.Headers.SetValue("x-ms-version", TableUserDelegationKey.ServiceVersion); + } + } + } +} diff --git a/src/DurableTask.AzureStorage/Http/MigrationSasRetryPolicy.cs b/src/DurableTask.AzureStorage/Http/MigrationSasRetryPolicy.cs new file mode 100644 index 000000000..aee02cf63 --- /dev/null +++ b/src/DurableTask.AzureStorage/Http/MigrationSasRetryPolicy.cs @@ -0,0 +1,68 @@ +// ---------------------------------------------------------------------------------- +// 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.Http +{ + using System; + using System.Threading.Tasks; + using Azure; + using Azure.Core; + using Azure.Core.Pipeline; + using DurableTask.AzureStorage.Storage; + + sealed class MigrationSasRetryPolicy : HttpPipelinePolicy + { + readonly MigrationSasManager manager; + + public MigrationSasRetryPolicy(MigrationSasManager manager) + { + this.manager = manager; + } + + public override void Process(HttpMessage message, ReadOnlyMemory pipeline) + { + ProcessNext(message, pipeline); + if (IsAuthenticationFailedResponse(message)) + { + this.manager.RefreshAsync(message.CancellationToken).GetAwaiter().GetResult(); + this.manager.EnsureAccess(); + message.CancellationToken.ThrowIfCancellationRequested(); + message.Response.Dispose(); + // Retry this request once with the refreshed SAS. + ProcessNext(message, pipeline); + } + } + + public override async ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory pipeline) + { + await ProcessNextAsync(message, pipeline).ConfigureAwait(false); + if (IsAuthenticationFailedResponse(message)) + { + await this.manager.RefreshAsync(message.CancellationToken).ConfigureAwait(false); + this.manager.EnsureAccess(); + message.CancellationToken.ThrowIfCancellationRequested(); + message.Response.Dispose(); + await ProcessNextAsync(message, pipeline).ConfigureAwait(false); + } + } + + static bool IsAuthenticationFailedResponse(HttpMessage message) + { + Response response = message.Response; + + // Refresh on any authentication failure, but retry only once. + return response.Status == 403 && + response.Headers.TryGetValue("x-ms-error-code", out string? code) && code == "AuthenticationFailed"; + } + } +} diff --git a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs index f18bf614f..43a1add25 100644 --- a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs +++ b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs @@ -30,6 +30,7 @@ namespace DurableTask.AzureStorage.Tests using Azure.Data.Tables; using Azure.Storage.Blobs; using Azure.Storage.Queues; + using DurableTask.AzureStorage.Http; using DurableTask.AzureStorage.Storage; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; @@ -353,6 +354,169 @@ public async Task RefreshLoop_CanStopAndRestartAndStopsWhenMigrationEnds() } } + [DataTestMethod] + [DataRow('q', false)] + [DataRow('q', true)] + [DataRow('t', false)] + [DataRow('t', true)] + [DataRow('b', false)] + [DataRow('b', true)] + public async Task Requests_AuthenticationRetryUsesTheRefreshedSas(char service, bool synchronous) + { + // 1. Expire the SAS after the SDK has signed the first request. + using StorageResponses storage = new(); + MigrationSasManager manager = storage.CreateManager(); + await manager.RefreshAsync(default); + DateTimeOffset expiry = storage.Expiry; + storage.WorkloadFailures = 1; + storage.BeforeWorkloadFailure = () => + { + storage.ServerTime = expiry.AddSeconds(1); + return Task.CompletedTask; + }; + + // 2. Retry the same body with the new SAS and no identity token. + await storage.SendWorkloadAsync(service, manager, synchronous); + Assert.AreEqual(2, storage.Workload.Count); + Dictionary first = Query(storage.Workload[0].Query); + Dictionary retry = Query(storage.Workload[1].Query); + Assert.AreEqual(expiry, DateTimeOffset.Parse(first["se"], CultureInfo.InvariantCulture)); + Assert.AreEqual(storage.Expiry, DateTimeOffset.Parse(retry["se"], CultureInfo.InvariantCulture)); + Assert.IsTrue(storage.Expiry > expiry); + Assert.AreNotEqual(first["sig"], retry["sig"]); + Assert.AreEqual(storage.WorkloadBodies[0], storage.WorkloadBodies[1]); + Assert.AreEqual("30", retry["timeout"]); + Assert.AreEqual(3, storage.KeyRequests); + if (service != 'b') + { + Assert.IsTrue(storage.WorkloadVersions.All(version => version == TableUserDelegationKey.ServiceVersion)); + } + } + + [DataTestMethod] + [DataRow(false, false)] + [DataRow(false, true)] + [DataRow(true, false)] + [DataRow(true, true)] + public async Task Requests_AuthenticationRetryStopsAfterOneRetryOrDrain(bool synchronous, bool ending) + { + // 1. Reject both attempts, or close the gate after the first rejection. + using StorageResponses storage = new(); + MigrationSasManager manager = storage.CreateManager(); + await manager.RefreshAsync(default); + storage.WorkloadFailures = 2; + if (ending) + { + storage.BeforeWorkloadFailure = storage.EndAsync; + } + + // 2. Drain prevents another send; a second rejection reaches the caller. + if (ending) + { + await Assert.ThrowsExceptionAsync( + () => storage.SendWorkloadAsync('q', manager, synchronous)); + } + else + { + RequestFailedException error = await Assert.ThrowsExceptionAsync( + () => storage.SendWorkloadAsync('q', manager, synchronous)); + Assert.AreEqual("AuthenticationFailed", error.ErrorCode); + } + Assert.AreEqual(ending ? 1 : 2, storage.Workload.Count); + } + + [DataTestMethod] + [DataRow(403, "AuthenticationFailed", true)] + [DataRow(403, "AuthorizationPermissionMismatch", false)] + [DataRow(403, null, false)] + [DataRow(401, "AuthenticationFailed", false)] + [DataRow(503, "ServerBusy", false)] + public async Task Requests_OnlyAuthenticationFailedResponsesRefresh(int status, string? code, bool retry) + { + // 1. Return the chosen error without expiring the current SAS. + using StorageResponses storage = new(); + MigrationSasManager manager = storage.CreateManager(); + await manager.RefreshAsync(default); + int reads = storage.GateReads; + storage.WorkloadFailures = 1; + storage.WorkloadFailureStatus = (HttpStatusCode)status; + storage.WorkloadFailureCode = code; + + // 2. Only the authentication error refreshes and retries the request. + if (retry) + { + await storage.SendWorkloadAsync('q', manager, synchronous: false); + } + else + { + await Assert.ThrowsExceptionAsync( + () => storage.SendWorkloadAsync('q', manager, synchronous: false)); + } + Assert.AreEqual(retry ? 2 : 1, storage.Workload.Count); + Assert.AreEqual(reads + (retry ? 1 : 0), storage.GateReads); + } + + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task Requests_SdkRetryKeepsOneTimeoutAndRechecksDrain(bool ending) + { + // 1. Let the SDK retry a transient Storage failure. + using StorageResponses storage = new(); + MigrationSasManager manager = storage.CreateManager(); + await manager.RefreshAsync(default); + storage.WorkloadRetries = 1; + storage.WorkloadFailures = 1; + storage.WorkloadFailureStatus = HttpStatusCode.ServiceUnavailable; + storage.WorkloadFailureCode = "ServerBusy"; + if (ending) + { + storage.BeforeWorkloadFailure = async () => + { + await storage.EndAsync(); + await manager.RefreshAsync(default); + }; + } + + // 2. Each retry checks access and replaces the existing timeout. + if (ending) + { + await Assert.ThrowsExceptionAsync( + () => storage.SendWorkloadAsync('q', manager, synchronous: false)); + } + else + { + await storage.SendWorkloadAsync('q', manager, synchronous: false); + } + Assert.AreEqual(ending ? 1 : 2, storage.Workload.Count); + foreach (Uri uri in storage.Workload) + { + Assert.AreEqual("30", Query(uri.Query)["timeout"]); + } + } + + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task Requests_CancellationPreventsAuthenticationRetry(bool synchronous) + { + // 1. Cancel the caller after Storage rejects the first request. + using StorageResponses storage = new(); + MigrationSasManager manager = storage.CreateManager(); + await manager.RefreshAsync(default); + using CancellationTokenSource cancellation = new(); + storage.WorkloadFailures = 1; + storage.BeforeWorkloadFailure = () => + { + cancellation.Cancel(); + return Task.CompletedTask; + }; + + // 2. Renewal observes cancellation before another request is sent. + await AssertCanceledAsync(storage.SendWorkloadAsync('q', manager, synchronous, cancellation.Token)); + Assert.AreEqual(1, storage.Workload.Count); + } + static async Task AssertCanceledAsync(Task task) { try @@ -404,7 +568,16 @@ public StorageResponses(bool sharedKey = false) public DateTimeOffset ServerTime { get; set; } = new DateTimeOffset(2030, 1, 1, 0, 0, 0, TimeSpan.Zero); public JObject? Row { get; set; } public DateTimeOffset Expiry => this.Row!["AccessExpiresAt"]!.ToObject(); + public int GateReads { get; private set; } public int GateWrites { get; private set; } + public int WorkloadFailures { get; set; } + public int WorkloadRetries { get; set; } + public HttpStatusCode WorkloadFailureStatus { get; set; } = HttpStatusCode.Forbidden; + public string? WorkloadFailureCode { get; set; } = "AuthenticationFailed"; + public Func? BeforeWorkloadFailure { get; set; } + public List Workload { get; } = new(); + public List WorkloadBodies { get; } = new(); + public List WorkloadVersions { get; } = new(); public int KeyRequests { get; private set; } public int Conflicts { get; private set; } public int EndingCalls { get; private set; } @@ -431,6 +604,43 @@ public async Task EndAsync() Assert.IsTrue(await this.Control.TryUpdateAsync(gate, default)); } + public async Task SendWorkloadAsync(char service, MigrationSasManager manager, bool synchronous, CancellationToken cancellationToken = default) + { + switch (service) + { + case 'q': + QueueClient queue = new(new Uri("https://account.queue.core.windows.net/workload"), + manager.GetCredential('q', "workload"), this.WorkloadOptions(new QueueClientOptions(), manager, true)); + if (synchronous) queue.SendMessage("payload", cancellationToken); + else await queue.SendMessageAsync("payload", cancellationToken); + break; + case 't': + TableClient table = new(new Uri("https://account.table.core.windows.net/Workload"), + manager.GetCredential('t', "Workload"), this.WorkloadOptions(new TableClientOptions(), manager, true)); + if (synchronous) table.AddEntity(new TableEntity("instance", string.Empty), cancellationToken); + else await table.AddEntityAsync(new TableEntity("instance", string.Empty), cancellationToken); + break; + case 'b': + BlobClient blob = new(new Uri("https://account.blob.core.windows.net/workload/payload"), + manager.GetCredential('b', "workload"), this.WorkloadOptions(new BlobClientOptions(), manager, false)); + if (synchronous) blob.Upload(BinaryData.FromString("payload"), overwrite: true, cancellationToken); + else await blob.UploadAsync(BinaryData.FromString("payload"), overwrite: true, cancellationToken); + break; + default: + throw new ArgumentOutOfRangeException(nameof(service)); + } + } + + T WorkloadOptions(T options, MigrationSasManager manager, bool delegationVersion) where T : ClientOptions + { + options.Transport = this; + options.Retry.MaxRetries = this.WorkloadRetries; + options.Retry.Delay = TimeSpan.Zero; + options.AddPolicy(new MigrationSasRetryPolicy(manager), HttpPipelinePosition.PerCall); + options.AddPolicy(new MigrationRequestPolicy(manager, delegationVersion), HttpPipelinePosition.PerRetry); + return options; + } + T Options(T options) where T : ClientOptions { options.Transport = this; @@ -460,9 +670,37 @@ async Task SendAsync(HttpRequestMessage request, Cancellati return this.Response(HttpStatusCode.OK, body.ToString(), "application/xml"); } + if (!uri.AbsolutePath.StartsWith("/TestHubMigrationCtrl", StringComparison.Ordinal)) + { + 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."); + if (this.WorkloadFailures > 0) + { + this.WorkloadFailures--; + Func? hook = this.BeforeWorkloadFailure; + this.BeforeWorkloadFailure = null; + if (hook is not null) await hook(); + XElement error = new("Error", new XElement("Code", this.WorkloadFailureCode ?? "Unknown"), + new XElement("Message", "The request failed.")); + HttpResponseMessage failure = this.Response(this.WorkloadFailureStatus, error.ToString(), "application/xml"); + if (this.WorkloadFailureCode is not null) failure.Headers.Add("x-ms-error-code", this.WorkloadFailureCode); + return failure; + } + if (uri.Host.Contains(".queue.")) + { + return this.Response(HttpStatusCode.Created, + $"id{this.ServerTime:R}{this.ServerTime.AddDays(7):R}receipt{this.ServerTime:R}", + "application/xml"); + } + return this.Response(uri.Host.Contains(".blob.") ? HttpStatusCode.Created : HttpStatusCode.NoContent); + } + Assert.AreEqual($"/TestHubMigrationCtrl(PartitionKey='',RowKey='{this.MigrationId:D}')", Uri.UnescapeDataString(uri.AbsolutePath)); if (request.Method == HttpMethod.Get) { + this.GateReads++; if (this.FailReads) return this.Error(HttpStatusCode.ServiceUnavailable, "ServerBusy"); HttpResponseMessage response = this.Row is null ? this.Error(HttpStatusCode.NotFound, "ResourceNotFound") : this.Response(HttpStatusCode.OK, this.Row.ToString()); From 3772dd2e382424ecd5a711944622fbb4383f36ee Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Mon, 30 Nov 2026 15:57:58 -0800 Subject: [PATCH 2/4] refactoring and comment updates --- .../Http/MigrationRequestPolicy.cs | 8 +++-- .../Http/MigrationSasRetryPolicy.cs | 29 +++++++++---------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs b/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs index 0d3c85b08..19238b025 100644 --- a/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs +++ b/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs @@ -34,10 +34,14 @@ public MigrationRequestPolicy(MigrationSasManager manager, bool useDelegationVer public override void OnSendingRequest(HttpMessage message) { this.manager.EnsureAccess(); - // SDK retries reuse the URI. Replace the parameter rather than appending duplicates. - UriBuilder uri = new UriBuilder(message.Request.Uri.ToUri()); + + // SDK retries reuse the URI, so we must replace the timeout parameter rather than appending a new one each time + UriBuilder uri = new(message.Request.Uri.ToUri()); string query = string.Join("&", uri.Query.TrimStart('?').Split('&') .Where(part => part.Length > 0 && !part.StartsWith("timeout=", StringComparison.OrdinalIgnoreCase))); + + // Set a timeout of 30 seconds for all requests - the migration logic relies on this bound to ensure that no further writes + // can occur post-SAS-expiry after this timeout expires uri.Query = query.Length == 0 ? "timeout=30" : query + "&timeout=30"; message.Request.Uri.Reset(uri.Uri); if (this.useDelegationVersion) diff --git a/src/DurableTask.AzureStorage/Http/MigrationSasRetryPolicy.cs b/src/DurableTask.AzureStorage/Http/MigrationSasRetryPolicy.cs index aee02cf63..0f2982a6d 100644 --- a/src/DurableTask.AzureStorage/Http/MigrationSasRetryPolicy.cs +++ b/src/DurableTask.AzureStorage/Http/MigrationSasRetryPolicy.cs @@ -32,13 +32,8 @@ public MigrationSasRetryPolicy(MigrationSasManager manager) public override void Process(HttpMessage message, ReadOnlyMemory pipeline) { ProcessNext(message, pipeline); - if (IsAuthenticationFailedResponse(message)) + if (this.TryPrepareRetryAsync(message).GetAwaiter().GetResult()) { - this.manager.RefreshAsync(message.CancellationToken).GetAwaiter().GetResult(); - this.manager.EnsureAccess(); - message.CancellationToken.ThrowIfCancellationRequested(); - message.Response.Dispose(); - // Retry this request once with the refreshed SAS. ProcessNext(message, pipeline); } } @@ -46,23 +41,27 @@ public override void Process(HttpMessage message, ReadOnlyMemory pipeline) { await ProcessNextAsync(message, pipeline).ConfigureAwait(false); - if (IsAuthenticationFailedResponse(message)) + if (await this.TryPrepareRetryAsync(message).ConfigureAwait(false)) { - await this.manager.RefreshAsync(message.CancellationToken).ConfigureAwait(false); - this.manager.EnsureAccess(); - message.CancellationToken.ThrowIfCancellationRequested(); - message.Response.Dispose(); await ProcessNextAsync(message, pipeline).ConfigureAwait(false); } } - static bool IsAuthenticationFailedResponse(HttpMessage message) + async ValueTask TryPrepareRetryAsync(HttpMessage message) { Response response = message.Response; + if (response.Status != 403 || + !response.Headers.TryGetValue("x-ms-error-code", out string? code) || code != "AuthenticationFailed") + { + return false; + } - // Refresh on any authentication failure, but retry only once. - return response.Status == 403 && - response.Headers.TryGetValue("x-ms-error-code", out string? code) && code == "AuthenticationFailed"; + // Refresh the SAS before the caller retries this request once. + await this.manager.RefreshAsync(message.CancellationToken).ConfigureAwait(false); + this.manager.EnsureAccess(); + message.CancellationToken.ThrowIfCancellationRequested(); + response.Dispose(); + return true; } } } From c0d823770722d28f1dfdc872addb4bd5b2374e4e Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Mon, 30 Nov 2026 16:06:49 -0800 Subject: [PATCH 3/4] addressing a thread deadlock issue --- src/DurableTask.AzureStorage/AzureStorageMigration.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/DurableTask.AzureStorage/AzureStorageMigration.cs b/src/DurableTask.AzureStorage/AzureStorageMigration.cs index d1f0028ce..da1c71ba6 100644 --- a/src/DurableTask.AzureStorage/AzureStorageMigration.cs +++ b/src/DurableTask.AzureStorage/AzureStorageMigration.cs @@ -48,7 +48,7 @@ public AzureStorageMigration(TableServiceClient tableServiceClient, string taskH { try { - Response response = await this.table.GetEntityAsync(string.Empty, migrationId.ToString("D"), cancellationToken: cancellationToken); + Response response = await this.table.GetEntityAsync(string.Empty, migrationId.ToString("D"), cancellationToken: cancellationToken).ConfigureAwait(false); TableEntity row = response.Value; return new Gate { @@ -76,7 +76,7 @@ internal async Task TryUpdateAsync(Gate gate, CancellationToken cancellati [MigrationEndingPropertyName] = gate.IsMigrationEnding, [nameof(Gate.AccessExpiresAt)] = gate.AccessExpiresAt, }; - await this.table.UpdateEntityAsync(entity, gate.ETag, TableUpdateMode.Replace, cancellationToken); + await this.table.UpdateEntityAsync(entity, gate.ETag, TableUpdateMode.Replace, cancellationToken).ConfigureAwait(false); return true; } // Another host may have updated the gate. The caller can retry with a fresh read. From 851673407c017720e07ed0f977d1c190497c3442 Mon Sep 17 00:00:00 2001 From: Sophia Tevosyan Date: Tue, 1 Dec 2026 13:40:00 -0800 Subject: [PATCH 4/4] addressing PR comments --- .../Http/MigrationRequestPolicy.cs | 24 ++++++++----- .../MigrationSasManagerTests.cs | 36 ++++++++++++++++++- 2 files changed, 51 insertions(+), 9 deletions(-) diff --git a/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs b/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs index 19238b025..083182256 100644 --- a/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs +++ b/src/DurableTask.AzureStorage/Http/MigrationRequestPolicy.cs @@ -35,15 +35,23 @@ public override void OnSendingRequest(HttpMessage message) { this.manager.EnsureAccess(); - // SDK retries reuse the URI, so we must replace the timeout parameter rather than appending a new one each time - UriBuilder uri = new(message.Request.Uri.ToUri()); - string query = string.Join("&", uri.Query.TrimStart('?').Split('&') - .Where(part => part.Length > 0 && !part.StartsWith("timeout=", StringComparison.OrdinalIgnoreCase))); + // Migration relies on this 30-second request timeout after SAS expiry. + var uri = message.Request.Uri.ToUri(); + string[] parts = uri.Query.TrimStart('?').Split('&'); + string[] timeouts = parts.Where(part => part.StartsWith("timeout=", StringComparison.OrdinalIgnoreCase)).ToArray(); - // Set a timeout of 30 seconds for all requests - the migration logic relies on this bound to ensure that no further writes - // can occur post-SAS-expiry after this timeout expires - uri.Query = query.Length == 0 ? "timeout=30" : query + "&timeout=30"; - message.Request.Uri.Reset(uri.Uri); + // A single timeout=30 is already correct; retries can reuse this duration. + if (timeouts.Length != 1 || timeouts[0] != "timeout=30") + { + // Remove old timeout values, preserve other query parameters, and add exactly one timeout=30. + string query = string.Join("&", parts + .Where(part => part.Length > 0 && !part.StartsWith("timeout=", StringComparison.OrdinalIgnoreCase))); + UriBuilder updated = new(uri) + { + Query = query.Length == 0 ? "timeout=30" : query + "&timeout=30", + }; + message.Request.Uri.Reset(updated.Uri); + } if (this.useDelegationVersion) { message.Request.Headers.SetValue("x-ms-version", TableUserDelegationKey.ServiceVersion); diff --git a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs index 43a1add25..6fb93d917 100644 --- a/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs +++ b/test/DurableTask.AzureStorage.Tests/MigrationSasManagerTests.cs @@ -456,6 +456,40 @@ await Assert.ThrowsExceptionAsync( Assert.AreEqual(reads + (retry ? 1 : 0), storage.GateReads); } + [DataTestMethod] + [DataRow("", "?timeout=30")] + [DataRow("?comp=list&sig=a%2Bb%3D", "?comp=list&sig=a%2Bb%3D&timeout=30")] + [DataRow("?comp=list&timeout=30&sig=a%2Bb%3D", "?comp=list&timeout=30&sig=a%2Bb%3D")] + [DataRow("?comp=list&timeout=60&sig=a%2Bb%3D", "?comp=list&sig=a%2Bb%3D&timeout=30")] + [DataRow("?timeout=30&comp=list&TIMEOUT=60&sig=a%2Bb%3D", "?comp=list&sig=a%2Bb%3D&timeout=30")] + [DataRow("?timeout=30&comp=list&timeout=30", "?comp=list&timeout=30")] + [DataRow("?TIMEOUT=30&comp=list", "?comp=list&timeout=30")] + public async Task Requests_TimeoutPreservesOtherParametersAndAvoidsRewritingCorrectValues( + string query, + string expectedQuery) + { + // 1. Prepare a request with the supplied timeout and other query parameters. + using StorageResponses storage = new(); + MigrationSasManager manager = storage.CreateManager(); + await manager.RefreshAsync(default); + using HttpMessage message = new(storage.CreateRequest(), new ResponseClassifier()); + message.Request.Uri.Reset(new Uri("https://account.queue.core.windows.net/workload" + query)); + MigrationRequestPolicy policy = new(manager, useDelegationVersion: true); + + // 2. Keep a correct timeout in place, or replace it without changing the other parameters. + policy.OnSendingRequest(message); + Assert.AreEqual(expectedQuery, message.Request.Uri.ToUri().Query); + Assert.IsTrue(message.Request.Headers.TryGetValue("x-ms-version", out string? version)); + Assert.AreEqual(TableUserDelegationKey.ServiceVersion, version); + + // 3. A retry keeps the same query and still sets the required service version. + message.Request.Headers.SetValue("x-ms-version", "old-version"); + policy.OnSendingRequest(message); + Assert.AreEqual(expectedQuery, message.Request.Uri.ToUri().Query); + Assert.IsTrue(message.Request.Headers.TryGetValue("x-ms-version", out version)); + Assert.AreEqual(TableUserDelegationKey.ServiceVersion, version); + } + [DataTestMethod] [DataRow(false)] [DataRow(true)] @@ -478,7 +512,7 @@ public async Task Requests_SdkRetryKeepsOneTimeoutAndRechecksDrain(bool ending) }; } - // 2. Each retry checks access and replaces the existing timeout. + // 2. Each retry checks access and keeps a single timeout. if (ending) { await Assert.ThrowsExceptionAsync(