From 1a5485a1e534726e2ab4316fd0b8b9700b7efda5 Mon Sep 17 00:00:00 2001 From: Davide Montanari Date: Thu, 22 Oct 2026 10:19:25 -0700 Subject: [PATCH 1/7] Fix blob container purge for hub names with dashes and culture-dependent container names --- .../ServiceBusOrchestrationService.cs | 6 +-- .../Tracking/BlobStorageClient.cs | 4 +- .../Tracking/BlobStorageClientHelper.cs | 21 +++++---- .../BlobStorageClientHelperTest.cs | 46 +++++++++++++++++++ .../NoOpTokenCredential.cs | 35 ++++++++++++++ .../WaitForOrchestrationTests.cs | 5 +- 6 files changed, 100 insertions(+), 17 deletions(-) create mode 100644 test/DurableTask.ServiceBus.Tests/NoOpTokenCredential.cs diff --git a/src/DurableTask.ServiceBus/ServiceBusOrchestrationService.cs b/src/DurableTask.ServiceBus/ServiceBusOrchestrationService.cs index b8cd27913..30e7b6ff4 100644 --- a/src/DurableTask.ServiceBus/ServiceBusOrchestrationService.cs +++ b/src/DurableTask.ServiceBus/ServiceBusOrchestrationService.cs @@ -431,9 +431,9 @@ internal async Task> GetHubQueueMaxDeliveryCountsAsync() var queues = (await managementClient.GetQueuesAsync()).Where(x => x.Path.StartsWith(this.hubName)).ToList(); - result.Add("TaskOrchestration", queues.Single(q => string.Equals(q.Path, this.orchestratorEntityName))?.MaxDeliveryCount ?? -1); - result.Add("TaskActivity", queues.Single(q => string.Equals(q.Path, this.workerEntityName))?.MaxDeliveryCount ?? -1); - result.Add("Tracking", queues.Single(q => string.Equals(q.Path, this.trackingEntityName))?.MaxDeliveryCount ?? -1); + result.Add("TaskOrchestration", queues.SingleOrDefault(q => string.Equals(q.Path, this.orchestratorEntityName))?.MaxDeliveryCount ?? -1); + result.Add("TaskActivity", queues.SingleOrDefault(q => string.Equals(q.Path, this.workerEntityName))?.MaxDeliveryCount ?? -1); + result.Add("Tracking", queues.SingleOrDefault(q => string.Equals(q.Path, this.trackingEntityName))?.MaxDeliveryCount ?? -1); return result; } diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs index a1d32d363..c0e120c3a 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs @@ -59,7 +59,7 @@ public BlobStorageClient(string hubName, string connectionString) // make the hub name lower case since it will be used as part of the prefix of the container name, // which only allows lower case letters - this.containerNamePrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName.ToLower()); + this.containerNamePrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName); } /// @@ -89,7 +89,7 @@ public BlobStorageClient(string hubName, Uri endpoint, TokenCredential credentia // make the hub name lower case since it will be used as part of the prefix of the container name, // which only allows lower case letters - this.containerNamePrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName.ToLower()); + this.containerNamePrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName); } /// diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs index fd6dc511d..7322ea680 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs @@ -27,6 +27,8 @@ public class BlobStorageClientHelper { static readonly string DateFormat = "yyyyMMdd"; static readonly char ContainerNameDelimiter = '-'; + static readonly string ContainerNameMarker = "dtfx"; + static readonly Regex ContainerNameSuffixRegex = new Regex(@"^[a-z0-9-]+\z", RegexOptions.Compiled | RegexOptions.CultureInvariant); /// /// the blob storage access key is in the format of {DateTime}|{blobName} @@ -60,7 +62,7 @@ public static string BuildMessageBlobKey(string instanceId, string executionId, static string BuildContainerNameSuffix(string containerType, DateTime blobCreationTime) { - return $"{containerType.ToLower()}{ContainerNameDelimiter}{GetDateStringForContainerName(blobCreationTime)}"; + return $"{containerType.ToLowerInvariant()}{ContainerNameDelimiter}{GetDateStringForContainerName(blobCreationTime)}"; } /// @@ -72,7 +74,7 @@ static string BuildContainerNameSuffix(string containerType, DateTime blobCreati /// The container name prefix public static string BuildContainerNamePrefix(string hubName) { - return $"{hubName.ToLower()}{ContainerNameDelimiter}dtfx"; + return $"{hubName.ToLowerInvariant()}{ContainerNameDelimiter}{ContainerNameMarker}"; } /// @@ -91,8 +93,8 @@ public static string BuildSessionBlobKey(string sessionId) static string GetDateStringForContainerName(DateTime messageFireTime) { return messageFireTime.IsSet() ? - messageFireTime.ToString(DateFormat) : - DateTime.UtcNow.ToString(DateFormat); + messageFireTime.ToString(DateFormat, CultureInfo.InvariantCulture) : + DateTime.UtcNow.ToString(DateFormat, CultureInfo.InvariantCulture); } /// @@ -129,8 +131,7 @@ public static void ParseKey(string key, out string containerNameSuffix, out stri /// True if the container name suffix is valid. static bool IsValidContainerNameSuffix(string containerNameSuffix) { - var regex = new Regex(@"^[a-z0-9\\-]+$"); - return regex.Match(containerNameSuffix).Success; + return ContainerNameSuffixRegex.IsMatch(containerNameSuffix); } /// @@ -141,13 +142,15 @@ static bool IsValidContainerNameSuffix(string containerNameSuffix) /// public static bool IsContainerExpired(string containerName, DateTime thresholdDateTimeUtc) { + // Container names are {hubName}-dtfx-{type}-{yyyyMMdd}; the hub name may itself contain dashes, + // so the fixed segments are read from the end. string[] segments = containerName.Split(ContainerNameDelimiter); - if (segments.Length != 4) + if (segments.Length < 4 || !string.Equals(segments[segments.Length - 3], ContainerNameMarker, StringComparison.Ordinal)) { TraceHelper.Trace( TraceEventType.Warning, "BlobStorageClientHelper-IsContainerExpired-ContainerIgnored", - $"Container name {containerName} does not contain required 4 segments. Container {containerName} is ignored."); + $"Container name {containerName} is not in the format {{hubName}}-{ContainerNameMarker}-{{type}}-{{date}}. Container {containerName} is ignored."); return false; } @@ -156,7 +159,7 @@ public static bool IsContainerExpired(string containerName, DateTime thresholdDa bool parseSucceeded = DateTime.TryParseExact( dateString, DateFormat, - System.Globalization.CultureInfo.InvariantCulture, + CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime containerDateTime); diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs index 30bf01a98..1cc54332b 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs @@ -15,6 +15,7 @@ namespace DurableTask.ServiceBus.Tests { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Text.RegularExpressions; using Microsoft.VisualStudio.TestTools.UnitTesting; using DurableTask.ServiceBus.Tracking; @@ -42,6 +43,51 @@ public void IsContainerExpiredTest() Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired("hubname-dtfx-message-20146789", DateTime.UtcNow)); } + [TestMethod] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void IsContainerExpiredHubNameWithDashesTest() + { + var dateTime = new DateTime(2015, 05, 17); + Assert.IsTrue(BlobStorageClientHelper.IsContainerExpired("my-hub-dtfx-message-20150516", dateTime)); + Assert.IsTrue(BlobStorageClientHelper.IsContainerExpired("my-test-hub-dtfx-session-20140518", dateTime)); + Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired("my-hub-dtfx-message-20150518", dateTime)); + + // containers not created by the framework are ignored + Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired("my-hub-other-message-20100101", DateTime.UtcNow)); + Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired("dtfx-message-20100101", DateTime.UtcNow)); + } + + [TestMethod] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void ContainerNamesAreCultureInvariantTest() + { + CultureInfo originalCulture = CultureInfo.CurrentCulture; + try + { + // th-TH uses the Buddhist calendar (year 2558 for 2015) + CultureInfo.CurrentCulture = new CultureInfo("th-TH"); + string key = BlobStorageClientHelper.BuildMessageBlobKey("aa", "bb", new DateTime(2015, 05, 17)); + StringAssert.StartsWith(key, "message-20150517|"); + + // tr-TR lower-cases 'I' to a dotless 'ı', which is invalid in a container name + CultureInfo.CurrentCulture = new CultureInfo("tr-TR"); + Assert.AreEqual("myhubid-dtfx", BlobStorageClientHelper.BuildContainerNamePrefix("MYHUBID")); + } + finally + { + CultureInfo.CurrentCulture = originalCulture; + } + } + + [TestMethod] + public void ParseKeyRejectsInvalidSuffixCharactersTest() + { + Assert.ThrowsException( + () => BlobStorageClientHelper.ParseKey(@"message\-20100319|aa/bb/cc", out _, out _)); + Assert.ThrowsException( + () => BlobStorageClientHelper.ParseKey("message-20100319\n|aa/bb/cc", out _, out _)); + } + [TestMethod] public void BuildMessageBlobKeyTest() { diff --git a/test/DurableTask.ServiceBus.Tests/NoOpTokenCredential.cs b/test/DurableTask.ServiceBus.Tests/NoOpTokenCredential.cs new file mode 100644 index 000000000..3ef5dbdf2 --- /dev/null +++ b/test/DurableTask.ServiceBus.Tests/NoOpTokenCredential.cs @@ -0,0 +1,35 @@ +// ---------------------------------------------------------------------------------- +// 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. +// ---------------------------------------------------------------------------------- + +namespace DurableTask.ServiceBus.Tests +{ + using System; + using System.Threading; + using System.Threading.Tasks; + using Azure.Core; + + /// + /// Credential stub for offline tests that construct a + /// but never contact Service Bus, so no token is ever requested. + /// + sealed class NoOpTokenCredential : TokenCredential + { + public const string NamespaceHostName = "test.servicebus.windows.net"; + + public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public override ValueTask GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) + => throw new NotSupportedException(); + } +} diff --git a/test/DurableTask.ServiceBus.Tests/WaitForOrchestrationTests.cs b/test/DurableTask.ServiceBus.Tests/WaitForOrchestrationTests.cs index faee45921..ec85ad394 100644 --- a/test/DurableTask.ServiceBus.Tests/WaitForOrchestrationTests.cs +++ b/test/DurableTask.ServiceBus.Tests/WaitForOrchestrationTests.cs @@ -31,15 +31,14 @@ namespace DurableTask.ServiceBus.Tests public class WaitForOrchestrationTests { const string InstanceId = "instance-1"; - const string FakeConnectionString = - "Endpoint=sb://test.servicebus.windows.net/;SharedAccessKeyName=key;SharedAccessKey=dGVzdGtleQ=="; static readonly DateTime BaseTime = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); static ServiceBusOrchestrationService CreateService(FakeInstanceStore instanceStore) { return new ServiceBusOrchestrationService( - FakeConnectionString, + NoOpTokenCredential.NamespaceHostName, + new NoOpTokenCredential(), "testhub", instanceStore, null, From ddee351ad00d6a1f81fabba583d9bf9b2745ef30 Mon Sep 17 00:00:00 2001 From: Davide Montanari Date: Thu, 22 Oct 2026 11:23:32 -0700 Subject: [PATCH 2/7] Fixed blob container listing --- .../Tracking/BlobStorageClient.cs | 14 +-- .../Tracking/BlobStorageClientHelper.cs | 26 +++++ .../BlobStorageClientHelperTest.cs | 20 ++++ .../BlobStorageClientTest.cs | 96 +++++++++++++++++++ 4 files changed, 150 insertions(+), 6 deletions(-) diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs index c0e120c3a..dfc268deb 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs @@ -130,19 +130,21 @@ private async Task GetCloudBlobClientAsync(string containerNameSuffi } /// - /// List all containers of the blob storage, whose prefix is containerNamePrefix, i.e., {hubName}-dtfx. + /// List all containers of this hub, i.e. containers named {hubName}-dtfx-{type}-{yyyyMMdd}. + /// Containers of other hubs whose names share this hub's prefix (e.g. hub "alpha-dtfx-backup" for hub "alpha") + /// are not returned. /// /// A list of Azure blob containers public async Task> ListContainersAsync() { List results = new List(); // Use the service client's prefix parameter to only enumerate containers that start with the - // configured containerNamePrefix. Also apply a defensive in-memory filter in case of any - // unexpected differences in casing or service behavior. + // configured containerNamePrefix, then keep only the containers that belong to this hub, since + // hub names may contain dashes and another hub's containers can share the same prefix. var response = this.blobServiceClient.GetBlobContainersAsync(prefix: this.containerNamePrefix); await foreach (var container in response) { - if (container.Name != null && container.Name.StartsWith(this.containerNamePrefix, StringComparison.OrdinalIgnoreCase)) + if (container.Name != null && BlobStorageClientHelper.IsContainerOwnedByHub(container.Name, this.containerNamePrefix)) { results.Add(container); } @@ -152,7 +154,7 @@ public async Task> ListContainersAsync() /// - /// Delete all containers that are older than the input threshold date. + /// Delete all containers of this hub that are older than the input threshold date. /// /// The specified date threshold /// @@ -164,7 +166,7 @@ public async Task DeleteExpiredContainersAsync(DateTime thresholdDateTimeUtc) } /// - /// Delete blob containers with the containerNamePrefix as prefix. + /// Delete all containers of this hub. /// /// public async Task DeleteBlobStoreContainersAsync() diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs index 7322ea680..8e9d4a584 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs @@ -176,6 +176,32 @@ public static bool IsContainerExpired(string containerName, DateTime thresholdDa return containerDateTime < thresholdDateTimeUtc; } + /// + /// Check if the container belongs to the hub with the given container name prefix. + /// Container names are {hubName}-dtfx-{type}-{yyyyMMdd}; because hub names may contain dashes, a different hub + /// (e.g. "alpha-dtfx-backup") can share the prefix "alpha-dtfx". The container belongs to the hub only if the + /// whole name without its trailing "-{type}-{yyyyMMdd}" segments equals the hub's container name prefix. + /// + /// The container name + /// The hub's container name prefix, i.e. {hubName}-dtfx + /// True if the container belongs to the hub. + internal static bool IsContainerOwnedByHub(string containerName, string containerNamePrefix) + { + int dateDelimiterIndex = containerName.LastIndexOf(ContainerNameDelimiter); + if (dateDelimiterIndex <= 0) + { + return false; + } + + int typeDelimiterIndex = containerName.LastIndexOf(ContainerNameDelimiter, dateDelimiterIndex - 1); + if (typeDelimiterIndex <= 0) + { + return false; + } + + return string.Equals(containerName.Substring(0, typeDelimiterIndex), containerNamePrefix, StringComparison.OrdinalIgnoreCase); + } + /// /// Build a container name using prefix and suffix. /// diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs index 1cc54332b..69a4be3c3 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs @@ -88,6 +88,26 @@ public void ParseKeyRejectsInvalidSuffixCharactersTest() () => BlobStorageClientHelper.ParseKey("message-20100319\n|aa/bb/cc", out _, out _)); } + [TestMethod] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void IsContainerOwnedByHubTest() + { + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-20150516", "alpha-dtfx")); + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-backup-dtfx-session-20150516", "alpha-dtfx-backup-dtfx")); + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("my-hub-dtfx-message-20150516", "my-hub-dtfx")); + + // another hub whose container names share this hub's prefix + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-backup-dtfx-session-20150516", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-20150516", "alpha-dtfx-backup-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-extra-session-20150516", "alpha-dtfx")); + + // malformed names + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-20150516", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("-session-20150516", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("invalidContainerName", "alpha-dtfx")); + } + [TestMethod] public void BuildMessageBlobKeyTest() { diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs index ebc3c2350..68ef72cbf 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs @@ -103,6 +103,102 @@ public async Task TestDeleteContainers() Assert.AreEqual(0, containers.Count); } + [TestMethod] + public async Task TestDeleteExpiredContainersPreservesOverlappingHub() + { + // "{hub}-dtfx-backup" shares the container name prefix "{hub}-dtfx" with "{hub}", + // so listing "{hub}" containers also returns the other hub's containers. + string storageConnectionString = TestHelpers.GetTestSetting("StorageConnectionString"); + var serviceClient = new BlobServiceClient(storageConnectionString); + string hubName = "alpha" + Guid.NewGuid().ToString("N").Substring(0, 8); + string overlappingHubName = hubName + "-dtfx-backup"; + var hubClient = new BlobStorageClient(hubName, storageConnectionString); + var overlappingHubClient = new BlobStorageClient(overlappingHubName, storageConnectionString); + + string hubPrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName); + string overlappingPrefix = BlobStorageClientHelper.BuildContainerNamePrefix(overlappingHubName); + string hubExpired = BlobStorageClientHelper.BuildContainerName(hubPrefix, "message-20150516"); + string hubCurrent = BlobStorageClientHelper.BuildContainerName(hubPrefix, "message-20150518"); + string overlappingExpiredMessage = BlobStorageClientHelper.BuildContainerName(overlappingPrefix, "message-20150516"); + string overlappingExpiredSession = BlobStorageClientHelper.BuildContainerName(overlappingPrefix, "session-20150516"); + + try + { + await UploadAsync(hubClient, "message-20150516|a"); + await UploadAsync(hubClient, "message-20150518|b"); + await UploadAsync(overlappingHubClient, "message-20150516|c"); + await UploadAsync(overlappingHubClient, "session-20150516|d"); + + await hubClient.DeleteExpiredContainersAsync(new DateTime(2015, 05, 17)); + + Assert.IsFalse(await serviceClient.GetBlobContainerClient(hubExpired).ExistsAsync(), "The hub's expired container must be deleted."); + Assert.IsTrue(await serviceClient.GetBlobContainerClient(hubCurrent).ExistsAsync(), "The hub's current container must be kept."); + Assert.IsTrue(await serviceClient.GetBlobContainerClient(overlappingExpiredMessage).ExistsAsync(), "The other hub's message container must be kept."); + Assert.IsTrue(await serviceClient.GetBlobContainerClient(overlappingExpiredSession).ExistsAsync(), "The other hub's session container must be kept."); + + Stream session = await overlappingHubClient.DownloadStreamAsync("session-20150516|d"); + Assert.AreEqual("test stream content", new StreamReader(session).ReadToEnd()); + } + finally + { + foreach (string name in new[] { hubExpired, hubCurrent, overlappingExpiredMessage, overlappingExpiredSession }) + { + await serviceClient.GetBlobContainerClient(name).DeleteIfExistsAsync(); + } + } + } + + [TestMethod] + public async Task TestDeleteBlobStoreContainersPreservesOverlappingHub() + { + string storageConnectionString = TestHelpers.GetTestSetting("StorageConnectionString"); + var serviceClient = new BlobServiceClient(storageConnectionString); + string hubName = "alpha" + Guid.NewGuid().ToString("N").Substring(0, 8); + string overlappingHubName = hubName + "-dtfx-backup"; + var hubClient = new BlobStorageClient(hubName, storageConnectionString); + var overlappingHubClient = new BlobStorageClient(overlappingHubName, storageConnectionString); + + string hubPrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName); + string overlappingPrefix = BlobStorageClientHelper.BuildContainerNamePrefix(overlappingHubName); + string hubMessage = BlobStorageClientHelper.BuildContainerName(hubPrefix, "message-20150516"); + string hubSession = BlobStorageClientHelper.BuildContainerName(hubPrefix, "session-20150516"); + string overlappingMessage = BlobStorageClientHelper.BuildContainerName(overlappingPrefix, "message-20150516"); + string overlappingSession = BlobStorageClientHelper.BuildContainerName(overlappingPrefix, "session-20150516"); + + try + { + await UploadAsync(hubClient, "message-20150516|a"); + await UploadAsync(hubClient, "session-20150516|b"); + await UploadAsync(overlappingHubClient, "message-20150516|c"); + await UploadAsync(overlappingHubClient, "session-20150516|d"); + + List listed = (await hubClient.ListContainersAsync()).Select(c => c.Name).OrderBy(n => n).ToList(); + CollectionAssert.AreEqual(new[] { hubMessage, hubSession }, listed, "Only the hub's own containers must be listed."); + + await hubClient.DeleteBlobStoreContainersAsync(); + + Assert.IsFalse(await serviceClient.GetBlobContainerClient(hubMessage).ExistsAsync(), "The hub's message container must be deleted."); + Assert.IsFalse(await serviceClient.GetBlobContainerClient(hubSession).ExistsAsync(), "The hub's session container must be deleted."); + Assert.IsTrue(await serviceClient.GetBlobContainerClient(overlappingMessage).ExistsAsync(), "The other hub's message container must be kept."); + Assert.IsTrue(await serviceClient.GetBlobContainerClient(overlappingSession).ExistsAsync(), "The other hub's session container must be kept."); + } + finally + { + foreach (string name in new[] { hubMessage, hubSession, overlappingMessage, overlappingSession }) + { + await serviceClient.GetBlobContainerClient(name).DeleteIfExistsAsync(); + } + } + } + + static async Task UploadAsync(BlobStorageClient client, string key) + { + using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes("test stream content"))) + { + await client.UploadStreamBlobAsync(key, stream); + } + } + [TestMethod] public async Task TestListContainersOnlyWithPrefix() { From 9d3ea9905d0ea9087b77eb67bbdef7217c75298c Mon Sep 17 00:00:00 2001 From: Davide Montanari Date: Thu, 22 Oct 2026 11:59:07 -0700 Subject: [PATCH 3/7] Added date validation --- .../Tracking/BlobStorageClientHelper.cs | 22 +++++----- .../BlobStorageClientHelperTest.cs | 13 ++++++ .../BlobStorageClientTest.cs | 44 +++++++++++++++++++ 3 files changed, 68 insertions(+), 11 deletions(-) diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs index 8e9d4a584..e415fd8a3 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs @@ -156,14 +156,7 @@ public static bool IsContainerExpired(string containerName, DateTime thresholdDa } string dateString = segments[segments.Length - 1]; - bool parseSucceeded = DateTime.TryParseExact( - dateString, - DateFormat, - CultureInfo.InvariantCulture, - DateTimeStyles.None, - out DateTime containerDateTime); - - if (!parseSucceeded) + if (!TryParseContainerDate(dateString, out DateTime containerDateTime)) { TraceHelper.Trace( TraceEventType.Warning, @@ -180,7 +173,8 @@ public static bool IsContainerExpired(string containerName, DateTime thresholdDa /// Check if the container belongs to the hub with the given container name prefix. /// Container names are {hubName}-dtfx-{type}-{yyyyMMdd}; because hub names may contain dashes, a different hub /// (e.g. "alpha-dtfx-backup") can share the prefix "alpha-dtfx". The container belongs to the hub only if the - /// whole name without its trailing "-{type}-{yyyyMMdd}" segments equals the hub's container name prefix. + /// whole name without its trailing "-{type}-{yyyyMMdd}" segments equals the hub's container name prefix, + /// the type is not empty, and the last segment is a valid yyyyMMdd date. /// /// The container name /// The hub's container name prefix, i.e. {hubName}-dtfx @@ -194,12 +188,18 @@ internal static bool IsContainerOwnedByHub(string containerName, string containe } int typeDelimiterIndex = containerName.LastIndexOf(ContainerNameDelimiter, dateDelimiterIndex - 1); - if (typeDelimiterIndex <= 0) + if (typeDelimiterIndex <= 0 || typeDelimiterIndex == dateDelimiterIndex - 1) { return false; } - return string.Equals(containerName.Substring(0, typeDelimiterIndex), containerNamePrefix, StringComparison.OrdinalIgnoreCase); + return string.Equals(containerName.Substring(0, typeDelimiterIndex), containerNamePrefix, StringComparison.OrdinalIgnoreCase) && + TryParseContainerDate(containerName.Substring(dateDelimiterIndex + 1), out _); + } + + static bool TryParseContainerDate(string dateString, out DateTime date) + { + return DateTime.TryParseExact(dateString, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date); } /// diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs index 69a4be3c3..7da528224 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs @@ -106,6 +106,19 @@ public void IsContainerOwnedByHubTest() Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-20150516", "alpha-dtfx")); Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("-session-20150516", "alpha-dtfx")); Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("invalidContainerName", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx--20150516", "alpha-dtfx")); + + // non-date suffixes + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-backup", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-2015051", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-201505160", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-", "alpha-dtfx")); + + // invalid calendar dates + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-20150230", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-20151301", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-message-20150001", "alpha-dtfx")); + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-message-20160229", "alpha-dtfx")); } [TestMethod] diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs index 68ef72cbf..5baa2ba2f 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs @@ -191,6 +191,50 @@ public async Task TestDeleteBlobStoreContainersPreservesOverlappingHub() } } + [TestMethod] + public async Task TestDeleteBlobStoreContainersIgnoresMalformedContainers() + { + string storageConnectionString = TestHelpers.GetTestSetting("StorageConnectionString"); + var serviceClient = new BlobServiceClient(storageConnectionString); + string hubName = "alpha" + Guid.NewGuid().ToString("N").Substring(0, 8); + var hubClient = new BlobStorageClient(hubName, storageConnectionString); + + string hubPrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName); + string hubContainer = BlobStorageClientHelper.BuildContainerName(hubPrefix, "session-20150516"); + string[] malformedContainers = + { + BlobStorageClientHelper.BuildContainerName(hubPrefix, "session-backup"), + BlobStorageClientHelper.BuildContainerName(hubPrefix, "session-20150230"), + }; + + try + { + await UploadAsync(hubClient, "session-20150516|a"); + foreach (string name in malformedContainers) + { + await serviceClient.GetBlobContainerClient(name).CreateIfNotExistsAsync(); + } + + List listed = (await hubClient.ListContainersAsync()).Select(c => c.Name).ToList(); + CollectionAssert.AreEqual(new[] { hubContainer }, listed, "Containers outside the {type}-{yyyyMMdd} format must not be listed."); + + await hubClient.DeleteBlobStoreContainersAsync(); + + Assert.IsFalse(await serviceClient.GetBlobContainerClient(hubContainer).ExistsAsync(), "The hub's container must be deleted."); + foreach (string name in malformedContainers) + { + Assert.IsTrue(await serviceClient.GetBlobContainerClient(name).ExistsAsync(), $"Malformed container {name} must be kept."); + } + } + finally + { + foreach (string name in malformedContainers.Append(hubContainer)) + { + await serviceClient.GetBlobContainerClient(name).DeleteIfExistsAsync(); + } + } + } + static async Task UploadAsync(BlobStorageClient client, string key) { using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes("test stream content"))) From dcbe9fe84208c7466a6c70b6b5d7a9ceca6fb37f Mon Sep 17 00:00:00 2001 From: Davide Montanari Date: Wed, 4 Nov 2026 17:49:00 -0800 Subject: [PATCH 4/7] Protect legacy-calendar blobs before enabling dashed-hub expiry --- .../Tracking/BlobStorageClientHelper.cs | 17 ++++++++ .../BlobStorageClientHelperTest.cs | 42 +++++++++++++++++++ .../BlobStorageClientTest.cs | 40 ++++++++++++++++++ 3 files changed, 99 insertions(+) diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs index e415fd8a3..0f8616081 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs @@ -30,6 +30,13 @@ public class BlobStorageClientHelper static readonly string ContainerNameMarker = "dtfx"; static readonly Regex ContainerNameSuffixRegex = new Regex(@"^[a-z0-9-]+\z", RegexOptions.Compiled | RegexOptions.CultureInvariant); + // Earlier versions formatted container dates with the current culture's calendar, so an existing container + // can hold a non-Gregorian date, e.g. Um Al Qura 1448xxxx, Persian 1405xxxx, Japanese 0008xxxx, Taiwan 0115xxxx. + // Read as Gregorian, these look centuries old although their payloads may still be referenced, so containers + // dated before any Gregorian date this framework could have written are never treated as expired. + // Calendars whose years read as far-future Gregorian years (Thai Buddhist, Korean, Hebrew) never expire either. + static readonly DateTime MinimumGregorianContainerDate = new DateTime(2000, 1, 1); + /// /// the blob storage access key is in the format of {DateTime}|{blobName} /// @@ -166,6 +173,16 @@ public static bool IsContainerExpired(string containerName, DateTime thresholdDa return false; } + if (containerDateTime < MinimumGregorianContainerDate) + { + TraceHelper.Trace( + TraceEventType.Warning, + "BlobStorageClientHelper-IsContainerExpired-LegacyCalendarDate", + $"The date string {dateString} is earlier than {MinimumGregorianContainerDate.ToString(DateFormat, CultureInfo.InvariantCulture)} and may have been written using a non-Gregorian calendar by an earlier version. Container {containerName} is ignored."); + + return false; + } + return containerDateTime < thresholdDateTimeUtc; } diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs index 7da528224..7d1f65754 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs @@ -57,6 +57,48 @@ public void IsContainerExpiredHubNameWithDashesTest() Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired("dtfx-message-20100101", DateTime.UtcNow)); } + [TestMethod] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void IsContainerExpiredIgnoresLegacyNonGregorianContainersTest() + { + // Before container dates were formatted with the invariant culture, the current culture's calendar was used. + // A container written for a recent payload must not be read as centuries old and purged. + var messageFireTime = new DateTime(2026, 11, 04); + var threshold = new DateTime(2026, 01, 01); + + foreach (string cultureName in new[] { "ar-SA", "fa-IR", "th-TH" }) + { + string legacyDate = BuildLegacyContainerDate(messageFireTime, cultureName); + Assert.AreNotEqual("20261104", legacyDate, $"{cultureName} must not use the Gregorian calendar for this test to be meaningful."); + + foreach (string hubPrefix in new[] { "my-hub-dtfx", "myhub-dtfx" }) + { + string containerName = $"{hubPrefix}-message-{legacyDate}"; + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub(containerName, hubPrefix), $"{containerName} must still belong to the hub."); + Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired(containerName, threshold), $"Legacy {cultureName} container {containerName} must not be treated as expired."); + } + } + + // Gregorian dates on or after the guard are still purged. + Assert.IsTrue(BlobStorageClientHelper.IsContainerExpired("my-hub-dtfx-message-20000101", threshold)); + Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired("my-hub-dtfx-message-19991231", threshold)); + } + + // Reproduces the container date formatting of earlier versions: DateTime.ToString("yyyyMMdd") under the current culture. + static string BuildLegacyContainerDate(DateTime messageFireTime, string cultureName) + { + CultureInfo originalCulture = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = new CultureInfo(cultureName); + return messageFireTime.ToString("yyyyMMdd"); + } + finally + { + CultureInfo.CurrentCulture = originalCulture; + } + } + [TestMethod] [SuppressMessage("ReSharper", "StringLiteralTypo")] public void ContainerNamesAreCultureInvariantTest() diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs index 5baa2ba2f..3f303b3e5 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs @@ -235,6 +235,46 @@ public async Task TestDeleteBlobStoreContainersIgnoresMalformedContainers() } } + [TestMethod] + public async Task TestDeleteExpiredContainersPreservesLegacyNonGregorianContainers() + { + // Earlier versions formatted the container date with the current culture's calendar: under ar-SA, a message + // fired on 2026-11-04 was stored in "{hub}-dtfx-message-14480524". It must survive a purge with a 2026-01-01 cutoff. + string storageConnectionString = TestHelpers.GetTestSetting("StorageConnectionString"); + var serviceClient = new BlobServiceClient(storageConnectionString); + string hubName = "my-hub-" + Guid.NewGuid().ToString("N").Substring(0, 8); + var hubClient = new BlobStorageClient(hubName, storageConnectionString); + + string legacyDate = new DateTime(2026, 11, 04).ToString("yyyyMMdd", new System.Globalization.CultureInfo("ar-SA")); + Assert.AreNotEqual("20261104", legacyDate); + string legacyKey = $"message-{legacyDate}|instance/execution/payload"; + + string hubPrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName); + string legacyContainer = BlobStorageClientHelper.BuildContainerName(hubPrefix, $"message-{legacyDate}"); + string expiredContainer = BlobStorageClientHelper.BuildContainerName(hubPrefix, "message-20251231"); + + try + { + await UploadAsync(hubClient, legacyKey); + await UploadAsync(hubClient, "message-20251231|a"); + + await hubClient.DeleteExpiredContainersAsync(new DateTime(2026, 01, 01)); + + Assert.IsFalse(await serviceClient.GetBlobContainerClient(expiredContainer).ExistsAsync(), "The hub's expired container must be deleted."); + Assert.IsTrue(await serviceClient.GetBlobContainerClient(legacyContainer).ExistsAsync(), "The legacy non-Gregorian container must be kept."); + + Stream payload = await hubClient.DownloadStreamAsync(legacyKey); + Assert.AreEqual("test stream content", new StreamReader(payload).ReadToEnd()); + } + finally + { + foreach (string name in new[] { legacyContainer, expiredContainer }) + { + await serviceClient.GetBlobContainerClient(name).DeleteIfExistsAsync(); + } + } + } + static async Task UploadAsync(BlobStorageClient client, string key) { using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes("test stream content"))) From 8179593534f512480218898240b2152473b48649 Mon Sep 17 00:00:00 2001 From: Davide Montanari Date: Wed, 4 Nov 2026 18:06:16 -0800 Subject: [PATCH 5/7] Keep legitimate legacy containers visible to full-store deletion --- .../Tracking/BlobStorageClient.cs | 2 +- .../Tracking/BlobStorageClientHelper.cs | 16 ++++-- .../BlobStorageClientHelperTest.cs | 16 ++++-- .../BlobStorageClientTest.cs | 52 ++++++++++++++++++- 4 files changed, 75 insertions(+), 11 deletions(-) diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs index dfc268deb..23ce121f1 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs @@ -130,7 +130,7 @@ private async Task GetCloudBlobClientAsync(string containerNameSuffi } /// - /// List all containers of this hub, i.e. containers named {hubName}-dtfx-{type}-{yyyyMMdd}. + /// List all containers of this hub, i.e. containers named {hubName}-dtfx-{type}-{date}, where date is 8 digits. /// Containers of other hubs whose names share this hub's prefix (e.g. hub "alpha-dtfx-backup" for hub "alpha") /// are not returned. /// diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs index 0f8616081..50be5dc5a 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs @@ -16,6 +16,7 @@ namespace DurableTask.ServiceBus.Tracking using System; using System.Diagnostics; using System.Globalization; + using System.Linq; using System.Text.RegularExpressions; using DurableTask.Core.Tracing; using DurableTask.Core.Common; @@ -188,10 +189,12 @@ public static bool IsContainerExpired(string containerName, DateTime thresholdDa /// /// Check if the container belongs to the hub with the given container name prefix. - /// Container names are {hubName}-dtfx-{type}-{yyyyMMdd}; because hub names may contain dashes, a different hub + /// Container names are {hubName}-dtfx-{type}-{date}; because hub names may contain dashes, a different hub /// (e.g. "alpha-dtfx-backup") can share the prefix "alpha-dtfx". The container belongs to the hub only if the - /// whole name without its trailing "-{type}-{yyyyMMdd}" segments equals the hub's container name prefix, - /// the type is not empty, and the last segment is a valid yyyyMMdd date. + /// whole name without its trailing "-{type}-{date}" segments equals the hub's container name prefix, + /// the type is not empty, and the date is 8 digits. + /// The date is not required to be a valid Gregorian date: earlier versions formatted it with the current culture's + /// calendar (e.g. Thai Buddhist 25670229, Hebrew month 13), and those containers still belong to the hub. /// /// The container name /// The hub's container name prefix, i.e. {hubName}-dtfx @@ -211,7 +214,12 @@ internal static bool IsContainerOwnedByHub(string containerName, string containe } return string.Equals(containerName.Substring(0, typeDelimiterIndex), containerNamePrefix, StringComparison.OrdinalIgnoreCase) && - TryParseContainerDate(containerName.Substring(dateDelimiterIndex + 1), out _); + IsContainerDateSegment(containerName.Substring(dateDelimiterIndex + 1)); + } + + static bool IsContainerDateSegment(string dateString) + { + return dateString.Length == DateFormat.Length && dateString.All(c => c >= '0' && c <= '9'); } static bool TryParseContainerDate(string dateString, out DateTime date) diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs index 7d1f65754..fadf7381b 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs @@ -82,6 +82,12 @@ public void IsContainerExpiredIgnoresLegacyNonGregorianContainersTest() // Gregorian dates on or after the guard are still purged. Assert.IsTrue(BlobStorageClientHelper.IsContainerExpired("my-hub-dtfx-message-20000101", threshold)); Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired("my-hub-dtfx-message-19991231", threshold)); + + // th-TH 2024-02-29 is 25670229, which is not a valid Gregorian date: still owned by the hub, never expired. + string thaiLeapDay = BuildLegacyContainerDate(new DateTime(2024, 02, 29), "th-TH"); + Assert.AreEqual("25670229", thaiLeapDay); + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub($"my-hub-dtfx-message-{thaiLeapDay}", "my-hub-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired($"my-hub-dtfx-message-{thaiLeapDay}", threshold)); } // Reproduces the container date formatting of earlier versions: DateTime.ToString("yyyyMMdd") under the current culture. @@ -156,11 +162,13 @@ public void IsContainerOwnedByHubTest() Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-201505160", "alpha-dtfx")); Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-", "alpha-dtfx")); - // invalid calendar dates - Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-20150230", "alpha-dtfx")); - Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-20151301", "alpha-dtfx")); - Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-message-20150001", "alpha-dtfx")); + // dates that are not valid Gregorian dates were written by earlier versions using the current culture's + // calendar (e.g. Thai Buddhist 25670229 for 2024-02-29, Hebrew month 13) and still belong to the hub + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-20150230", "alpha-dtfx")); + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-57841301", "alpha-dtfx")); + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("my-hub-dtfx-message-25670229", "my-hub-dtfx")); Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-message-20160229", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-2015o516", "alpha-dtfx")); } [TestMethod] diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs index 3f303b3e5..27b6ee779 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs @@ -204,7 +204,7 @@ public async Task TestDeleteBlobStoreContainersIgnoresMalformedContainers() string[] malformedContainers = { BlobStorageClientHelper.BuildContainerName(hubPrefix, "session-backup"), - BlobStorageClientHelper.BuildContainerName(hubPrefix, "session-20150230"), + BlobStorageClientHelper.BuildContainerName(hubPrefix, "session-201505160"), }; try @@ -216,7 +216,7 @@ public async Task TestDeleteBlobStoreContainersIgnoresMalformedContainers() } List listed = (await hubClient.ListContainersAsync()).Select(c => c.Name).ToList(); - CollectionAssert.AreEqual(new[] { hubContainer }, listed, "Containers outside the {type}-{yyyyMMdd} format must not be listed."); + CollectionAssert.AreEqual(new[] { hubContainer }, listed, "Containers outside the {type}-{date} format, where date is 8 digits, must not be listed."); await hubClient.DeleteBlobStoreContainersAsync(); @@ -275,6 +275,54 @@ public async Task TestDeleteExpiredContainersPreservesLegacyNonGregorianContaine } } + [TestMethod] + public async Task TestDeleteBlobStoreContainersDeletesLegacyNonGregorianContainers() + { + // Earlier versions formatted the container date with the current culture's calendar: under th-TH, a message + // fired on 2024-02-29 was stored in "{hub}-dtfx-message-25670229", which is not a valid Gregorian date. + // Full-store deletion must still remove such containers. + string storageConnectionString = TestHelpers.GetTestSetting("StorageConnectionString"); + var serviceClient = new BlobServiceClient(storageConnectionString); + string hubName = "my-hub-" + Guid.NewGuid().ToString("N").Substring(0, 8); + var hubClient = new BlobStorageClient(hubName, storageConnectionString); + + string thaiDate = new DateTime(2024, 02, 29).ToString("yyyyMMdd", new System.Globalization.CultureInfo("th-TH")); + string hijriDate = new DateTime(2026, 11, 04).ToString("yyyyMMdd", new System.Globalization.CultureInfo("ar-SA")); + Assert.AreEqual("25670229", thaiDate); + + string hubPrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName); + string[] containers = + { + BlobStorageClientHelper.BuildContainerName(hubPrefix, $"message-{thaiDate}"), + BlobStorageClientHelper.BuildContainerName(hubPrefix, $"session-{hijriDate}"), + BlobStorageClientHelper.BuildContainerName(hubPrefix, "message-20240229"), + }; + + try + { + await UploadAsync(hubClient, $"message-{thaiDate}|instance/execution/a"); + await UploadAsync(hubClient, $"session-{hijriDate}|instance/execution/b"); + await UploadAsync(hubClient, "message-20240229|instance/execution/c"); + + List listed = (await hubClient.ListContainersAsync()).Select(c => c.Name).OrderBy(n => n).ToList(); + CollectionAssert.AreEquivalent(containers, listed, "Legacy non-Gregorian containers must be listed."); + + await hubClient.DeleteBlobStoreContainersAsync(); + + foreach (string name in containers) + { + Assert.IsFalse(await serviceClient.GetBlobContainerClient(name).ExistsAsync(), $"Container {name} must be deleted."); + } + } + finally + { + foreach (string name in containers) + { + await serviceClient.GetBlobContainerClient(name).DeleteIfExistsAsync(); + } + } + } + static async Task UploadAsync(BlobStorageClient client, string key) { using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes("test stream content"))) From d9b64f5777fa5458b313852ff9b802c9d54fdccc Mon Sep 17 00:00:00 2001 From: Davide Montanari Date: Wed, 4 Nov 2026 18:16:28 -0800 Subject: [PATCH 6/7] Fixed comments --- src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs | 2 +- src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs index 23ce121f1..ccb7817ab 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs @@ -30,7 +30,7 @@ public class BlobStorageClient // container prefix is in the format of {hubName}-dtfx. It is not part of the blob key. // the container full name is in the format of {hubName}-dtfx-{streamType}-{DateTime}; // the streamType is the type of the stream, either 'message' or 'session'; - // the date time is in the format of yyyyMMdd. + // the date time is in the format of yyyyMMdd (invariant culture; containers written by earlier versions may use the host's calendar). readonly string containerNamePrefix; readonly BlobServiceClient blobServiceClient; diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs index 50be5dc5a..78f5612c1 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs @@ -169,7 +169,7 @@ public static bool IsContainerExpired(string containerName, DateTime thresholdDa TraceHelper.Trace( TraceEventType.Warning, "BlobStorageClientHelper-IsContainerExpired-InvalidDate", - $"Cannot parse the the date string {dateString} in the format of yyyyMMdd. Container {containerName} is ignored."); + $"Cannot parse the date string {dateString} in the format of yyyyMMdd. Container {containerName} is ignored."); return false; } From 5d04f825367fc2300a4e3b4773aaf0dea1f9d5c1 Mon Sep 17 00:00:00 2001 From: Davide Montanari Date: Fri, 6 Nov 2026 11:45:28 -0800 Subject: [PATCH 7/7] Recognize shorter legacy Japanese/Taiwan calendar dates --- .../Tracking/BlobStorageClient.cs | 3 +- .../Tracking/BlobStorageClientHelper.cs | 15 ++++-- .../BlobStorageClientHelperTest.cs | 35 ++++++++++-- .../BlobStorageClientTest.cs | 53 +++++++++++++++---- 4 files changed, 84 insertions(+), 22 deletions(-) diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs index ccb7817ab..fd83612d6 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs @@ -130,7 +130,8 @@ private async Task GetCloudBlobClientAsync(string containerNameSuffi } /// - /// List all containers of this hub, i.e. containers named {hubName}-dtfx-{type}-{date}, where date is 8 digits. + /// List all containers of this hub, i.e. containers named {hubName}-dtfx-{type}-{date}, where date is 6 to 8 digits + /// (8 for Gregorian dates; earlier versions may have written fewer digits using Japanese or Taiwan calendars). /// Containers of other hubs whose names share this hub's prefix (e.g. hub "alpha-dtfx-backup" for hub "alpha") /// are not returned. /// diff --git a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs index 78f5612c1..d32e3b6d1 100644 --- a/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs +++ b/src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs @@ -32,12 +32,17 @@ public class BlobStorageClientHelper static readonly Regex ContainerNameSuffixRegex = new Regex(@"^[a-z0-9-]+\z", RegexOptions.Compiled | RegexOptions.CultureInvariant); // Earlier versions formatted container dates with the current culture's calendar, so an existing container - // can hold a non-Gregorian date, e.g. Um Al Qura 1448xxxx, Persian 1405xxxx, Japanese 0008xxxx, Taiwan 0115xxxx. + // can hold a non-Gregorian date, e.g. Um Al Qura 1448xxxx, Persian 1405xxxx. // Read as Gregorian, these look centuries old although their payloads may still be referenced, so containers // dated before any Gregorian date this framework could have written are never treated as expired. - // Calendars whose years read as far-future Gregorian years (Thai Buddhist, Korean, Hebrew) never expire either. + // Calendars whose years read as far-future Gregorian years (Thai Buddhist, Korean) never expire either. + // Japanese and Taiwan calendars format the era year with as few as 2 digits (e.g. 081106, 1151106); + // these dates are shorter than yyyyMMdd, do not parse, and never expire. static readonly DateTime MinimumGregorianContainerDate = new DateTime(2000, 1, 1); + // yyyyMMdd with a 2-digit year, as written by earlier versions for Japanese and Taiwan calendar era years. + static readonly int MinimumLegacyDateLength = 6; + /// /// the blob storage access key is in the format of {DateTime}|{blobName} /// @@ -192,9 +197,9 @@ public static bool IsContainerExpired(string containerName, DateTime thresholdDa /// Container names are {hubName}-dtfx-{type}-{date}; because hub names may contain dashes, a different hub /// (e.g. "alpha-dtfx-backup") can share the prefix "alpha-dtfx". The container belongs to the hub only if the /// whole name without its trailing "-{type}-{date}" segments equals the hub's container name prefix, - /// the type is not empty, and the date is 8 digits. + /// the type is not empty, and the date is 6 to 8 digits. /// The date is not required to be a valid Gregorian date: earlier versions formatted it with the current culture's - /// calendar (e.g. Thai Buddhist 25670229, Hebrew month 13), and those containers still belong to the hub. + /// calendar (e.g. Thai Buddhist 25670229, Japanese 081106, Taiwan 1151106), and those containers still belong to the hub. /// /// The container name /// The hub's container name prefix, i.e. {hubName}-dtfx @@ -219,7 +224,7 @@ internal static bool IsContainerOwnedByHub(string containerName, string containe static bool IsContainerDateSegment(string dateString) { - return dateString.Length == DateFormat.Length && dateString.All(c => c >= '0' && c <= '9'); + return dateString.Length >= MinimumLegacyDateLength && dateString.Length <= DateFormat.Length && dateString.All(c => c >= '0' && c <= '9'); } static bool TryParseContainerDate(string dateString, out DateTime date) diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs index fadf7381b..ea91cef4c 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientHelperTest.cs @@ -88,15 +88,37 @@ public void IsContainerExpiredIgnoresLegacyNonGregorianContainersTest() Assert.AreEqual("25670229", thaiLeapDay); Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub($"my-hub-dtfx-message-{thaiLeapDay}", "my-hub-dtfx")); Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired($"my-hub-dtfx-message-{thaiLeapDay}", threshold)); + + // Japanese and Taiwan calendars format the era year with as few as 2 digits: still owned by the hub, never expired. + foreach ((string cultureName, Calendar calendar, DateTime fireTime, string expectedDate) in new (string, Calendar, DateTime, string)[] + { + ("ja-JP", new JapaneseCalendar(), messageFireTime, "081104"), + ("zh-TW", new TaiwanCalendar(), messageFireTime, "1151104"), + ("zh-TW", new TaiwanCalendar(), new DateTime(2010, 12, 31), "991231"), + }) + { + string legacyDate = BuildLegacyContainerDate(fireTime, cultureName, calendar); + Assert.AreEqual(expectedDate, legacyDate); + + string containerName = $"my-hub-dtfx-message-{legacyDate}"; + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub(containerName, "my-hub-dtfx"), $"{containerName} must still belong to the hub."); + Assert.IsFalse(BlobStorageClientHelper.IsContainerExpired(containerName, threshold), $"Legacy {cultureName} container {containerName} must not be treated as expired."); + } } // Reproduces the container date formatting of earlier versions: DateTime.ToString("yyyyMMdd") under the current culture. - static string BuildLegacyContainerDate(DateTime messageFireTime, string cultureName) + static string BuildLegacyContainerDate(DateTime messageFireTime, string cultureName, Calendar calendar = null) { CultureInfo originalCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentCulture = new CultureInfo(cultureName); + var culture = new CultureInfo(cultureName); + if (calendar != null) + { + culture.DateTimeFormat.Calendar = calendar; + } + + CultureInfo.CurrentCulture = culture; return messageFireTime.ToString("yyyyMMdd"); } finally @@ -158,15 +180,18 @@ public void IsContainerOwnedByHubTest() // non-date suffixes Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-backup", "alpha-dtfx")); - Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-2015051", "alpha-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-20150", "alpha-dtfx")); Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-201505160", "alpha-dtfx")); Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-", "alpha-dtfx")); // dates that are not valid Gregorian dates were written by earlier versions using the current culture's - // calendar (e.g. Thai Buddhist 25670229 for 2024-02-29, Hebrew month 13) and still belong to the hub + // calendar (e.g. Thai Buddhist 25670229 for 2024-02-29, Japanese 081106 and Taiwan 1151106 for 2026-11-06) + // and still belong to the hub Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-20150230", "alpha-dtfx")); - Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-57841301", "alpha-dtfx")); Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("my-hub-dtfx-message-25670229", "my-hub-dtfx")); + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("my-hub-dtfx-message-081106", "my-hub-dtfx")); + Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("my-hub-dtfx-message-1151106", "my-hub-dtfx")); + Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-backup-dtfx-message-081106", "alpha-dtfx")); Assert.IsTrue(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-message-20160229", "alpha-dtfx")); Assert.IsFalse(BlobStorageClientHelper.IsContainerOwnedByHub("alpha-dtfx-session-2015o516", "alpha-dtfx")); } diff --git a/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs b/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs index 27b6ee779..1b334caf9 100644 --- a/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs +++ b/test/DurableTask.ServiceBus.Tests/BlobStorageClientTest.cs @@ -216,7 +216,7 @@ public async Task TestDeleteBlobStoreContainersIgnoresMalformedContainers() } List listed = (await hubClient.ListContainersAsync()).Select(c => c.Name).ToList(); - CollectionAssert.AreEqual(new[] { hubContainer }, listed, "Containers outside the {type}-{date} format, where date is 8 digits, must not be listed."); + CollectionAssert.AreEqual(new[] { hubContainer }, listed, "Containers outside the {type}-{date} format, where date is 6 to 8 digits, must not be listed."); await hubClient.DeleteBlobStoreContainersAsync(); @@ -248,27 +248,38 @@ public async Task TestDeleteExpiredContainersPreservesLegacyNonGregorianContaine string legacyDate = new DateTime(2026, 11, 04).ToString("yyyyMMdd", new System.Globalization.CultureInfo("ar-SA")); Assert.AreNotEqual("20261104", legacyDate); string legacyKey = $"message-{legacyDate}|instance/execution/payload"; + string japaneseDate = new DateTime(2026, 11, 04).ToString("yyyyMMdd", LegacyCulture("ja-JP", new System.Globalization.JapaneseCalendar())); + string taiwanDate = new DateTime(2026, 11, 04).ToString("yyyyMMdd", LegacyCulture("zh-TW", new System.Globalization.TaiwanCalendar())); + Assert.AreEqual("081104", japaneseDate); + Assert.AreEqual("1151104", taiwanDate); string hubPrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName); string legacyContainer = BlobStorageClientHelper.BuildContainerName(hubPrefix, $"message-{legacyDate}"); + string japaneseContainer = BlobStorageClientHelper.BuildContainerName(hubPrefix, $"message-{japaneseDate}"); + string taiwanContainer = BlobStorageClientHelper.BuildContainerName(hubPrefix, $"message-{taiwanDate}"); string expiredContainer = BlobStorageClientHelper.BuildContainerName(hubPrefix, "message-20251231"); try { await UploadAsync(hubClient, legacyKey); + await UploadAsync(hubClient, $"message-{japaneseDate}|instance/execution/a"); + await UploadAsync(hubClient, $"message-{taiwanDate}|instance/execution/b"); await UploadAsync(hubClient, "message-20251231|a"); await hubClient.DeleteExpiredContainersAsync(new DateTime(2026, 01, 01)); Assert.IsFalse(await serviceClient.GetBlobContainerClient(expiredContainer).ExistsAsync(), "The hub's expired container must be deleted."); - Assert.IsTrue(await serviceClient.GetBlobContainerClient(legacyContainer).ExistsAsync(), "The legacy non-Gregorian container must be kept."); + foreach (string name in new[] { legacyContainer, japaneseContainer, taiwanContainer }) + { + Assert.IsTrue(await serviceClient.GetBlobContainerClient(name).ExistsAsync(), $"The legacy non-Gregorian container {name} must be kept."); + } Stream payload = await hubClient.DownloadStreamAsync(legacyKey); Assert.AreEqual("test stream content", new StreamReader(payload).ReadToEnd()); } finally { - foreach (string name in new[] { legacyContainer, expiredContainer }) + foreach (string name in new[] { legacyContainer, japaneseContainer, taiwanContainer, expiredContainer }) { await serviceClient.GetBlobContainerClient(name).DeleteIfExistsAsync(); } @@ -279,7 +290,8 @@ public async Task TestDeleteExpiredContainersPreservesLegacyNonGregorianContaine public async Task TestDeleteBlobStoreContainersDeletesLegacyNonGregorianContainers() { // Earlier versions formatted the container date with the current culture's calendar: under th-TH, a message - // fired on 2024-02-29 was stored in "{hub}-dtfx-message-25670229", which is not a valid Gregorian date. + // fired on 2024-02-29 was stored in "{hub}-dtfx-message-25670229", which is not a valid Gregorian date, and + // Japanese and Taiwan calendars wrote shorter era-year dates such as "081106" and "1151106". // Full-store deletion must still remove such containers. string storageConnectionString = TestHelpers.GetTestSetting("StorageConnectionString"); var serviceClient = new BlobServiceClient(storageConnectionString); @@ -288,21 +300,33 @@ public async Task TestDeleteBlobStoreContainersDeletesLegacyNonGregorianContaine string thaiDate = new DateTime(2024, 02, 29).ToString("yyyyMMdd", new System.Globalization.CultureInfo("th-TH")); string hijriDate = new DateTime(2026, 11, 04).ToString("yyyyMMdd", new System.Globalization.CultureInfo("ar-SA")); + string japaneseDate = new DateTime(2026, 11, 06).ToString("yyyyMMdd", LegacyCulture("ja-JP", new System.Globalization.JapaneseCalendar())); + string taiwanDate = new DateTime(2026, 11, 06).ToString("yyyyMMdd", LegacyCulture("zh-TW", new System.Globalization.TaiwanCalendar())); Assert.AreEqual("25670229", thaiDate); + Assert.AreEqual("081106", japaneseDate); + Assert.AreEqual("1151106", taiwanDate); string hubPrefix = BlobStorageClientHelper.BuildContainerNamePrefix(hubName); - string[] containers = + string[] keys = { - BlobStorageClientHelper.BuildContainerName(hubPrefix, $"message-{thaiDate}"), - BlobStorageClientHelper.BuildContainerName(hubPrefix, $"session-{hijriDate}"), - BlobStorageClientHelper.BuildContainerName(hubPrefix, "message-20240229"), + $"message-{thaiDate}|instance/execution/a", + $"session-{hijriDate}|instance/execution/b", + "message-20240229|instance/execution/c", + $"message-{japaneseDate}|instance/execution/d", + $"message-{taiwanDate}|instance/execution/e", }; + string[] containers = keys + .Select(k => BlobStorageClientHelper.BuildContainerName(hubPrefix, k.Substring(0, k.IndexOf(BlobStorageClientHelper.KeyDelimiter)))) + .ToArray(); try { - await UploadAsync(hubClient, $"message-{thaiDate}|instance/execution/a"); - await UploadAsync(hubClient, $"session-{hijriDate}|instance/execution/b"); - await UploadAsync(hubClient, "message-20240229|instance/execution/c"); + foreach (string key in keys) + { + await UploadAsync(hubClient, key); + Stream payload = await hubClient.DownloadStreamAsync(key); + Assert.AreEqual("test stream content", new StreamReader(payload).ReadToEnd(), $"Payload {key} must be readable."); + } List listed = (await hubClient.ListContainersAsync()).Select(c => c.Name).OrderBy(n => n).ToList(); CollectionAssert.AreEquivalent(containers, listed, "Legacy non-Gregorian containers must be listed."); @@ -323,6 +347,13 @@ public async Task TestDeleteBlobStoreContainersDeletesLegacyNonGregorianContaine } } + static System.Globalization.CultureInfo LegacyCulture(string cultureName, System.Globalization.Calendar calendar) + { + var culture = new System.Globalization.CultureInfo(cultureName); + culture.DateTimeFormat.Calendar = calendar; + return culture; + } + static async Task UploadAsync(BlobStorageClient client, string key) { using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes("test stream content")))