Skip to content
6 changes: 3 additions & 3 deletions src/DurableTask.ServiceBus/ServiceBusOrchestrationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -431,9 +431,9 @@ internal async Task<Dictionary<string, int>> 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;
}
Expand Down
21 changes: 12 additions & 9 deletions src/DurableTask.ServiceBus/Tracking/BlobStorageClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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);
}

/// <summary>
Expand Down Expand Up @@ -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);
}

/// <summary>
Expand Down Expand Up @@ -130,19 +130,22 @@ private async Task<BlobClient> GetCloudBlobClientAsync(string containerNameSuffi
}

/// <summary>
/// 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}-{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.
/// </summary>
/// <returns>A list of Azure blob containers</returns>
public async Task<IEnumerable<BlobContainerItem>> ListContainersAsync()
{
List<BlobContainerItem> results = new List<BlobContainerItem>();
// 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);
}
Expand All @@ -152,7 +155,7 @@ public async Task<IEnumerable<BlobContainerItem>> ListContainersAsync()


/// <summary>
/// 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.
/// </summary>
/// <param name="thresholdDateTimeUtc">The specified date threshold</param>
/// <returns></returns>
Expand All @@ -164,7 +167,7 @@ public async Task DeleteExpiredContainersAsync(DateTime thresholdDateTimeUtc)
}

/// <summary>
/// Delete blob containers with the containerNamePrefix as prefix.
/// Delete all containers of this hub.
/// </summary>
/// <returns></returns>
public async Task DeleteBlobStoreContainersAsync()
Expand Down
93 changes: 76 additions & 17 deletions src/DurableTask.ServiceBus/Tracking/BlobStorageClientHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -27,6 +28,20 @@ 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);

// 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.
// 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) 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;

/// <summary>
/// the blob storage access key is in the format of {DateTime}|{blobName}
Expand Down Expand Up @@ -60,7 +75,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)}";
}

/// <summary>
Expand All @@ -72,7 +87,7 @@ static string BuildContainerNameSuffix(string containerType, DateTime blobCreati
/// <returns>The container name prefix</returns>
public static string BuildContainerNamePrefix(string hubName)
{
return $"{hubName.ToLower()}{ContainerNameDelimiter}dtfx";
return $"{hubName.ToLowerInvariant()}{ContainerNameDelimiter}{ContainerNameMarker}";
}

/// <summary>
Expand All @@ -91,8 +106,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);
}

/// <summary>
Expand Down Expand Up @@ -129,8 +144,7 @@ public static void ParseKey(string key, out string containerNameSuffix, out stri
/// <returns>True if the container name suffix is valid.</returns>
static bool IsValidContainerNameSuffix(string containerNameSuffix)
{
var regex = new Regex(@"^[a-z0-9\\-]+$");
return regex.Match(containerNameSuffix).Success;
return ContainerNameSuffixRegex.IsMatch(containerNameSuffix);
}

/// <summary>
Expand All @@ -141,38 +155,83 @@ static bool IsValidContainerNameSuffix(string containerNameSuffix)
/// <returns></returns>
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))
Comment thread
davidemontanari marked this conversation as resolved.
Resolved
Comment thread
davidemontanari marked this conversation as resolved.
Resolved
{
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;
}

string dateString = segments[segments.Length - 1];
bool parseSucceeded = DateTime.TryParseExact(
dateString,
DateFormat,
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime containerDateTime);

if (!parseSucceeded)
if (!TryParseContainerDate(dateString, out DateTime containerDateTime))
{
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;
}

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;
}

/// <summary>
/// Check if the container belongs to the hub with the given container name prefix.
/// 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 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, Japanese 081106, Taiwan 1151106), and those containers still belong to the hub.
/// </summary>
/// <param name="containerName">The container name</param>
/// <param name="containerNamePrefix">The hub's container name prefix, i.e. {hubName}-dtfx</param>
/// <returns>True if the container belongs to the hub.</returns>
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 || typeDelimiterIndex == dateDelimiterIndex - 1)
{
return false;
}

return string.Equals(containerName.Substring(0, typeDelimiterIndex), containerNamePrefix, StringComparison.OrdinalIgnoreCase) &&
IsContainerDateSegment(containerName.Substring(dateDelimiterIndex + 1));
}

static bool IsContainerDateSegment(string dateString)
{
return dateString.Length >= MinimumLegacyDateLength && dateString.Length <= DateFormat.Length && dateString.All(c => c >= '0' && c <= '9');
}

static bool TryParseContainerDate(string dateString, out DateTime date)
{
return DateTime.TryParseExact(dateString, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
}

/// <summary>
/// Build a container name using prefix and suffix.
/// </summary>
Expand Down
Loading
Loading