From bfd51fd647e7b54cda244676c9b867b826d571ac Mon Sep 17 00:00:00 2001 From: Amer Jusupovic <32405726+amerjusupovic@users.noreply.github.com> Date: Thu, 22 Feb 2024 10:17:09 -0800 Subject: [PATCH] Merge replica discovery changes from preview to main (#521) * Automatic http failover base on Srv Dns (#442) * Automatic http failover base on Srv Dns * update failover condition * Logging messages for auto failover * Not use generic method * Remove useless constructor * Failover to TCP when response is truncated * Error handling of TCP failover * Resolve comments and add thrid party notice * Fix the tests * Fix the tess * Fix the test * Update to use DnsClient.NET * Remove unecessary code * Resolve conflict * Stop once it has been auto failovered * Update GetAvaliableClient method * Resolve comments * Resolve comments * Internalize getting dynamic client in ConfigurationClientManager * Fix format * Fix format * Resolve comments * Resolve comments * Resolve comments * Resolve comments * Resolve comments * Resolve comments * Resolve comments * Not await RefreshFallbackClients when startup * Revert non-await RefreshFallbackClients * Validate domain of Srv endpoints (#489) * Validate domain of Srv endpoints * Resolve comments * Resolve comments * Create object in using * Add the origin host to the srv lookup result * Validate endpoint by domain name (#499) * Validate endpoint by domain name * Resolve comments * Remove *-test * Fix formatResolve conflict * Use await using for IAsyncDisposible * Replace IAsyncEumerable with ValueTask * Resolve comments * Remove cancallation token * Resolve comments * Refactor and move backoff logic to AzureAppConfigurationProvider (#508) * move backoff logic to provider, can't access backoffendtime from manager for dynamic clients * add condition before calling getclients in refreshasync, add refreshclients method * fix logic to check if backoff ended for client * fix indents * check client backoff before refresh, fix tests in progress * remove tolist * comment changes, fix refresh tests * reduce minimum backoff when testing * fix tests, fix typo with failover logic * update comments in tests * resolve PR comments * resolve small comments * fix tests backoff duration * fix tests backoff duration * fix error from merging main branch in * add back fix for attempts backoff calculation --------- Co-authored-by: Richard chen <99175581+RichardChen820@users.noreply.github.com> --- NOTICE | 226 +++++++++++++++ .../AzureAppConfigurationOptions.cs | 10 + .../AzureAppConfigurationProvider.cs | 83 +++++- .../AzureAppConfigurationSource.cs | 4 +- .../ConfigurationClientManager.cs | 268 ++++++++++++++++-- .../ConfigurationClientWrapper.cs | 4 - ...ringParser.cs => ConnectionStringUtils.cs} | 26 +- .../Constants/FailOverConstants.cs | 2 + .../Constants/LoggingConstants.cs | 1 + .../Extensions/ListExtensions.cs | 57 +++- .../Extensions/TimeSpanExtensions.cs | 2 +- .../IConfigurationClientManager.cs | 8 +- .../LogHelper.cs | 5 + ...Configuration.AzureAppConfiguration.csproj | 1 + .../SrvLookupClient.cs | 72 +++++ .../FailoverTests.cs | 212 +++++++++----- .../LoggingTests.cs | 2 + .../MockedConfigurationClientManager.cs | 37 ++- .../RefreshTests.cs | 5 + .../Tests.AzureAppConfiguration.csproj | 1 + 20 files changed, 887 insertions(+), 139 deletions(-) create mode 100644 NOTICE rename src/Microsoft.Extensions.Configuration.AzureAppConfiguration/{ConnectionStringParser.cs => ConnectionStringUtils.cs} (60%) create mode 100644 src/Microsoft.Extensions.Configuration.AzureAppConfiguration/SrvLookupClient.cs diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..2cec0531 --- /dev/null +++ b/NOTICE @@ -0,0 +1,226 @@ +NOTICES AND INFORMATION +Do Not Translate or Localize + +This software incorporates material from third parties. Microsoft makes certain +open source code available at https://3rdpartysource.microsoft.com, or you may +send a check or money order for US $5.00, including the product name, the open +source component name, and version number, to: + +Source Code Compliance Team +Microsoft Corporation +One Microsoft Way +Redmond, WA 98052 +USA + +Notwithstanding any other terms, you may reverse engineer this software to the +extent required to debug changes to any libraries licensed under the GNU Lesser +General Public License. + +--- + +## [DnsClient.NET](https://github.com/MichaCo/DnsClient.NET) + +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. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationOptions.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationOptions.cs index 046233f6..d79838da 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationOptions.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationOptions.cs @@ -34,6 +34,11 @@ public class AzureAppConfigurationOptions // Since multiple prefixes could start with the same characters, we need to trim the longest prefix first. private SortedSet _keyPrefixes = new SortedSet(Comparer.Create((k1, k2) => -string.Compare(k1, k2, StringComparison.OrdinalIgnoreCase))); + /// + /// Flag to indicate whether enable replica discovery. + /// + public bool ReplicaDiscoveryEnabled { get; set; } = true; + /// /// The list of connection strings used to connect to an Azure App Configuration store and its replicas. /// @@ -91,6 +96,11 @@ internal IEnumerable Adapters /// This property is used only for unit testing. internal IConfigurationClientManager ClientManager { get; set; } + /// + /// An optional timespan value to set the minimum backoff duration to a value other than the default. + /// + internal TimeSpan MinBackoffDuration { get; set; } = FailOverConstants.MinBackoffDuration; + /// /// Options used to configure the client used to communicate with Azure App Configuration. /// diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationProvider.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationProvider.cs index 06e7c155..9cf9947b 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationProvider.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationProvider.cs @@ -22,7 +22,7 @@ namespace Microsoft.Extensions.Configuration.AzureAppConfiguration { - internal class AzureAppConfigurationProvider : ConfigurationProvider, IConfigurationRefresher + internal class AzureAppConfigurationProvider : ConfigurationProvider, IConfigurationRefresher, IDisposable { private bool _optional; private bool _isInitialLoadComplete = false; @@ -33,6 +33,7 @@ internal class AzureAppConfigurationProvider : ConfigurationProvider, IConfigura private Dictionary _mappedData; private Dictionary _watchedSettings = new Dictionary(); private RequestTracingOptions _requestTracingOptions; + private Dictionary _configClientBackoffs = new Dictionary(); private readonly TimeSpan MinCacheExpirationInterval; @@ -47,6 +48,12 @@ internal class AzureAppConfigurationProvider : ConfigurationProvider, IConfigura private Logger _logger = new Logger(); private ILoggerFactory _loggerFactory; + private class ConfigurationClientBackoffStatus + { + public int FailedAttempts { get; set; } + public DateTimeOffset BackoffEndTime { get; set; } + } + public Uri AppConfigurationEndpoint { get @@ -63,7 +70,7 @@ public Uri AppConfigurationEndpoint try { - return new Uri(ConnectionStringParser.Parse(_options.ConnectionStrings.First(), ConnectionStringParser.EndpointSection)); + return new Uri(ConnectionStringUtils.Parse(_options.ConnectionStrings.First(), ConnectionStringUtils.EndpointSection)); } catch (FormatException) { } } @@ -85,6 +92,11 @@ public ILoggerFactory LoggerFactory if (_loggerFactory != null) { _logger = new Logger(_loggerFactory.CreateLogger(LoggingConstants.AppConfigRefreshLogCategory)); + + if (_configClientManager is ConfigurationClientManager clientManager) + { + clientManager.SetLogger(_logger); + } } } } @@ -192,11 +204,31 @@ public async Task RefreshAsync(CancellationToken cancellationToken) return; } - IEnumerable availableClients = _configClientManager.GetAvailableClients(utcNow); + IEnumerable clients = _configClientManager.GetClients(); - if (!availableClients.Any()) + // + // Filter clients based on their backoff status + clients = clients.Where(client => { + Uri endpoint = _configClientManager.GetEndpointForClient(client); + + if (!_configClientBackoffs.TryGetValue(endpoint, out ConfigurationClientBackoffStatus clientBackoffStatus)) + { + clientBackoffStatus = new ConfigurationClientBackoffStatus(); + + _configClientBackoffs[endpoint] = clientBackoffStatus; + } + + return clientBackoffStatus.BackoffEndTime <= utcNow; + } + ); + + if (!clients.Any()) + { + _configClientManager.RefreshClients(); + _logger.LogDebug(LogHelper.BuildRefreshSkippedNoClientAvailableMessage()); + return; } @@ -207,7 +239,7 @@ public async Task RefreshAsync(CancellationToken cancellationToken) { InitializationCacheExpires = utcNow.Add(MinCacheExpirationInterval); - await InitializeAsync(availableClients, cancellationToken).ConfigureAwait(false); + await InitializeAsync(clients, cancellationToken).ConfigureAwait(false); } return; @@ -223,7 +255,7 @@ public async Task RefreshAsync(CancellationToken cancellationToken) StringBuilder logInfoBuilder = new StringBuilder(); StringBuilder logDebugBuilder = new StringBuilder(); - await ExecuteWithFailOverPolicyAsync(availableClients, async (client) => + await ExecuteWithFailOverPolicyAsync(clients, async (client) => { data = null; watchedSettings = null; @@ -358,7 +390,6 @@ await CallWithRequestTracing( adapter.InvalidateCache(change.Current); } } - } else { @@ -562,7 +593,7 @@ private async Task LoadAsync(bool ignoreFailures, CancellationToken cancellation { while (true) { - IEnumerable clients = _configClientManager.GetAllClients(); + IEnumerable clients = _configClientManager.GetClients(); if (await TryInitializeAsync(clients, startupExceptions, cancellationToken).ConfigureAwait(false)) { @@ -1017,15 +1048,17 @@ private async Task ExecuteWithFailOverPolicyAsync( do { - _configClientManager.UpdateClientStatus(currentClient, success); + UpdateClientBackoffStatus(previousEndpoint, success); + clientEnumerator.MoveNext(); + currentClient = clientEnumerator.Current; } while (currentClient != null); } else { - _configClientManager.UpdateClientStatus(currentClient, success); + UpdateClientBackoffStatus(previousEndpoint, success); } } @@ -1160,5 +1193,35 @@ private void EnsureFeatureManagementVersionInspected() } } } + + private void UpdateClientBackoffStatus(Uri endpoint, bool successful) + { + if (!_configClientBackoffs.TryGetValue(endpoint, out ConfigurationClientBackoffStatus clientBackoffStatus)) + { + clientBackoffStatus = new ConfigurationClientBackoffStatus(); + } + + if (successful) + { + clientBackoffStatus.BackoffEndTime = DateTimeOffset.UtcNow; + + clientBackoffStatus.FailedAttempts = 0; + } + else + { + clientBackoffStatus.FailedAttempts++; + + TimeSpan backoffDuration = _options.MinBackoffDuration.CalculateBackoffDuration(FailOverConstants.MaxBackoffDuration, clientBackoffStatus.FailedAttempts); + + clientBackoffStatus.BackoffEndTime = DateTimeOffset.UtcNow.Add(backoffDuration); + } + + _configClientBackoffs[endpoint] = clientBackoffStatus; + } + + public void Dispose() + { + (_configClientManager as ConfigurationClientManager)?.Dispose(); + } } } diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationSource.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationSource.cs index 24b53fb3..71a5f480 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationSource.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/AzureAppConfigurationSource.cs @@ -36,11 +36,11 @@ public IConfigurationProvider Build(IConfigurationBuilder builder) } else if (options.ConnectionStrings != null) { - clientManager = new ConfigurationClientManager(options.ConnectionStrings, options.ClientOptions); + clientManager = new ConfigurationClientManager(options.ConnectionStrings, options.ClientOptions, options.ReplicaDiscoveryEnabled); } else if (options.Endpoints != null && options.Credential != null) { - clientManager = new ConfigurationClientManager(options.Endpoints, options.Credential, options.ClientOptions); + clientManager = new ConfigurationClientManager(options.Endpoints, options.Credential, options.ClientOptions, options.ReplicaDiscoveryEnabled); } else { diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConfigurationClientManager.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConfigurationClientManager.cs index b56b7acf..9ae71d2a 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConfigurationClientManager.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConfigurationClientManager.cs @@ -4,10 +4,16 @@ using Azure.Core; using Azure.Data.AppConfiguration; +using DnsClient; +using DnsClient.Protocol; using Microsoft.Extensions.Configuration.AzureAppConfiguration.Extensions; using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; namespace Microsoft.Extensions.Configuration.AzureAppConfiguration { @@ -18,32 +24,89 @@ namespace Microsoft.Extensions.Configuration.AzureAppConfiguration /// This class is not thread-safe. Since config provider does not allow multiple network requests at the same time, /// there won't be multiple threads calling this client at the same time. /// - internal class ConfigurationClientManager : IConfigurationClientManager + internal class ConfigurationClientManager : IConfigurationClientManager, IDisposable { private readonly IList _clients; + private readonly Uri _endpoint; + private readonly string _secret; + private readonly string _id; + private readonly TokenCredential _credential; + private readonly ConfigurationClientOptions _clientOptions; + private readonly bool _replicaDiscoveryEnabled; + private readonly SrvLookupClient _srvLookupClient; + private readonly string _validDomain; - public ConfigurationClientManager(IEnumerable connectionStrings, ConfigurationClientOptions clientOptions) + private IList _dynamicClients; + private DateTimeOffset _lastFallbackClientRefresh = default; + private DateTimeOffset _lastFallbackClientRefreshAttempt = default; + private Logger _logger = new Logger(); + private bool _isDisposed = false; + + private static readonly TimeSpan FallbackClientRefreshExpireInterval = TimeSpan.FromHours(1); + private static readonly TimeSpan MinimalClientRefreshInterval = TimeSpan.FromSeconds(30); + private static readonly string[] TrustedDomainLabels = new[] { "azconfig", "appconfig" }; + + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + // Only used for unit testing + internal int RefreshClientsCalled { get; set; } = 0; + + public ConfigurationClientManager( + IEnumerable connectionStrings, + ConfigurationClientOptions clientOptions, + bool replicaDiscoveryEnabled) { if (connectionStrings == null || !connectionStrings.Any()) { throw new ArgumentNullException(nameof(connectionStrings)); } - _clients = connectionStrings.Select(connectionString => - { - var endpoint = new Uri(ConnectionStringParser.Parse(connectionString, ConnectionStringParser.EndpointSection)); - return new ConfigurationClientWrapper(endpoint, new ConfigurationClient(connectionString, clientOptions)); - }).ToList(); + string connectionString = connectionStrings.First(); + _endpoint = new Uri(ConnectionStringUtils.Parse(connectionString, ConnectionStringUtils.EndpointSection)); + _secret = ConnectionStringUtils.Parse(connectionString, ConnectionStringUtils.SecretSection); + _id = ConnectionStringUtils.Parse(connectionString, ConnectionStringUtils.IdSection); + _clientOptions = clientOptions; + _replicaDiscoveryEnabled = replicaDiscoveryEnabled; + + _validDomain = GetValidDomain(_endpoint); + _srvLookupClient = new SrvLookupClient(); + + _clients = connectionStrings + .Select(cs => + { + var endpoint = new Uri(ConnectionStringUtils.Parse(cs, ConnectionStringUtils.EndpointSection)); + return new ConfigurationClientWrapper(endpoint, new ConfigurationClient(cs, _clientOptions)); + }) + .ToList(); } - public ConfigurationClientManager(IEnumerable endpoints, TokenCredential credential, ConfigurationClientOptions clientOptions) + public ConfigurationClientManager( + IEnumerable endpoints, + TokenCredential credential, + ConfigurationClientOptions clientOptions, + bool replicaDiscoveryEnabled) { if (endpoints == null || !endpoints.Any()) { throw new ArgumentNullException(nameof(endpoints)); } - _clients = endpoints.Select(endpoint => new ConfigurationClientWrapper(endpoint, new ConfigurationClient(endpoint, credential, clientOptions))).ToList(); + if (credential == null) + { + throw new ArgumentNullException(nameof(credential)); + } + + _endpoint = endpoints.First(); + _credential = credential; + _clientOptions = clientOptions; + _replicaDiscoveryEnabled = replicaDiscoveryEnabled; + + _validDomain = GetValidDomain(_endpoint); + _srvLookupClient = new SrvLookupClient(); + + _clients = endpoints + .Select(endpoint => new ConfigurationClientWrapper(endpoint, new ConfigurationClient(endpoint, _credential, _clientOptions))) + .ToList(); } /// @@ -55,36 +118,43 @@ internal ConfigurationClientManager(IList clients) _clients = clients; } - public IEnumerable GetAvailableClients(DateTimeOffset time) + public IEnumerable GetClients() { - return _clients.Where(client => client.BackoffEndTime <= time).Select(c => c.Client).ToList(); - } - - public IEnumerable GetAllClients() - { - return _clients.Select(c => c.Client).ToList(); - } + DateTimeOffset now = DateTimeOffset.UtcNow; - public void UpdateClientStatus(ConfigurationClient client, bool successful) - { - if (client == null) + if (_replicaDiscoveryEnabled && + now >= _lastFallbackClientRefreshAttempt + MinimalClientRefreshInterval && + (_dynamicClients == null || + now >= _lastFallbackClientRefresh + FallbackClientRefreshExpireInterval)) { - throw new ArgumentNullException(nameof(client)); + _lastFallbackClientRefreshAttempt = now; + + _ = DiscoverFallbackClients(); } - ConfigurationClientWrapper clientWrapper = _clients.First(c => c.Client.Equals(client)); + IEnumerable clients = _clients.Select(c => c.Client); - if (successful) + if (_dynamicClients != null && _dynamicClients.Any()) { - clientWrapper.BackoffEndTime = DateTimeOffset.UtcNow; - clientWrapper.FailedAttempts = 0; + clients = clients.Concat(_dynamicClients.Select(c => c.Client)); } - else + + return clients; + } + + public void RefreshClients() + { + DateTimeOffset now = DateTimeOffset.UtcNow; + + if (_replicaDiscoveryEnabled && + now >= _lastFallbackClientRefreshAttempt + MinimalClientRefreshInterval) { - clientWrapper.FailedAttempts++; - TimeSpan backoffDuration = FailOverConstants.MinBackoffDuration.CalculateBackoffDuration(FailOverConstants.MaxBackoffDuration, clientWrapper.FailedAttempts); - clientWrapper.BackoffEndTime = DateTimeOffset.UtcNow.Add(backoffDuration); + _lastFallbackClientRefreshAttempt = now; + + _ = DiscoverFallbackClients(); } + + RefreshClientsCalled++; } public bool UpdateSyncToken(Uri endpoint, string syncToken) @@ -101,6 +171,11 @@ public bool UpdateSyncToken(Uri endpoint, string syncToken) ConfigurationClientWrapper clientWrapper = _clients.SingleOrDefault(c => new EndpointComparer().Equals(c.Endpoint, endpoint)); + if (_dynamicClients != null && clientWrapper == null) + { + clientWrapper = _dynamicClients.SingleOrDefault(c => new EndpointComparer().Equals(c.Endpoint, endpoint)); + } + if (clientWrapper != null) { clientWrapper.Client.UpdateSyncToken(syncToken); @@ -118,8 +193,141 @@ public Uri GetEndpointForClient(ConfigurationClient client) } ConfigurationClientWrapper currentClient = _clients.FirstOrDefault(c => c.Client == client); - + + if (_dynamicClients != null && currentClient == null) + { + currentClient = _dynamicClients.FirstOrDefault(c => c.Client == client); + } + return currentClient?.Endpoint; } + + public void SetLogger(Logger logger) + { + if (logger == null) + { + throw new ArgumentNullException(nameof(logger)); + } + + _logger = logger; + } + + private async Task DiscoverFallbackClients() + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token); + + cts.CancelAfter(MinimalClientRefreshInterval); + + try + { + await RefreshFallbackClients(cts.Token).ConfigureAwait(false); + } + catch (OperationCanceledException e) when (!_cancellationTokenSource.IsCancellationRequested) + { + _logger.LogWarning(LogHelper.BuildFallbackClientLookupFailMessage(e.Message)); + } + } + + private async Task RefreshFallbackClients(CancellationToken cancellationToken) + { + IEnumerable srvTargetHosts = Enumerable.Empty(); + + try + { + srvTargetHosts = await _srvLookupClient.QueryAsync(_endpoint.DnsSafeHost, cancellationToken).ConfigureAwait(false); + } + // Catch and log all exceptions thrown by srv lookup client to avoid new possible exceptions on app startup. + catch (SocketException ex) + { + _logger.LogWarning(LogHelper.BuildFallbackClientLookupFailMessage(ex.Message)); + return; + } + catch (DnsResponseException ex) + { + _logger.LogWarning(LogHelper.BuildFallbackClientLookupFailMessage(ex.Message)); + return; + } + catch (InvalidOperationException ex) + { + _logger.LogWarning(LogHelper.BuildFallbackClientLookupFailMessage(ex.Message)); + return; + } + catch (DnsXidMismatchException ex) + { + _logger.LogWarning(LogHelper.BuildFallbackClientLookupFailMessage(ex.Message)); + return; + } + + var newDynamicClients = new List(); + + // Honor with the DNS based service discovery protocol, but shuffle the results first to ensure hosts can be picked randomly, + // Srv lookup does retrieve trailing dot in the host name, just trim it. + IEnumerable OrderedHosts = srvTargetHosts.Any() ? + srvTargetHosts.ToList().Shuffle().SortSrvRecords().Select(r => $"{r.Target.Value.TrimEnd('.')}") : + Enumerable.Empty(); + + foreach (string host in OrderedHosts) + { + if (!string.IsNullOrEmpty(host) && + !_clients.Any(c => c.Endpoint.Host.Equals(host, StringComparison.OrdinalIgnoreCase)) && + IsValidEndpoint(host)) + { + var targetEndpoint = new Uri($"https://{host}"); + + var configClient = _credential == null ? + new ConfigurationClient(ConnectionStringUtils.Build(targetEndpoint, _id, _secret), _clientOptions) : + new ConfigurationClient(targetEndpoint, _credential, _clientOptions); + + newDynamicClients.Add(new ConfigurationClientWrapper(targetEndpoint, configClient)); + } + } + + _dynamicClients = newDynamicClients; + + _lastFallbackClientRefresh = DateTime.UtcNow; + } + + private string GetValidDomain(Uri endpoint) + { + Debug.Assert(endpoint != null); + + string hostName = endpoint.Host; + + foreach (string label in TrustedDomainLabels) + { + int index = hostName.LastIndexOf($".{label}.", StringComparison.OrdinalIgnoreCase); + + if (index > 0) + { + return hostName.Substring(index); + } + } + + return string.Empty; + } + + internal bool IsValidEndpoint(string hostName) + { + Debug.Assert(!string.IsNullOrEmpty(hostName)); + + if (string.IsNullOrEmpty(_validDomain)) + { + return false; + } + + return hostName.EndsWith(_validDomain, StringComparison.OrdinalIgnoreCase); + } + + public void Dispose() + { + if (!_isDisposed) + { + _cancellationTokenSource.Cancel(); + + _cancellationTokenSource.Dispose(); + + _isDisposed = true; + } + } } } diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConfigurationClientWrapper.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConfigurationClientWrapper.cs index ad6c18a9..f12cc43a 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConfigurationClientWrapper.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConfigurationClientWrapper.cs @@ -12,12 +12,8 @@ public ConfigurationClientWrapper(Uri endpoint, ConfigurationClient configuratio { Endpoint = endpoint; Client = configurationClient; - BackoffEndTime = DateTimeOffset.UtcNow; - FailedAttempts = 0; } - public int FailedAttempts { get; set; } - public DateTimeOffset BackoffEndTime { get; set; } public ConfigurationClient Client { get; private set; } public Uri Endpoint { get; private set; } } diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConnectionStringParser.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConnectionStringUtils.cs similarity index 60% rename from src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConnectionStringParser.cs rename to src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConnectionStringUtils.cs index 23676956..ad768733 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConnectionStringParser.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/ConnectionStringUtils.cs @@ -5,10 +5,14 @@ namespace Microsoft.Extensions.Configuration.AzureAppConfiguration { - internal static class ConnectionStringParser + internal static class ConnectionStringUtils { public const string EndpointSection = "Endpoint"; + public const string SecretSection = "Secret"; + + public const string IdSection = "Id"; + public static string Parse(string connectionString, string token) { if (connectionString == null) @@ -36,5 +40,25 @@ public static string Parse(string connectionString, string token) return connectionString.Substring(startIndex + parseToken.Length, endIndex - startIndex - parseToken.Length); } + + public static string Build(Uri endpoint, string id, string secret) + { + if (endpoint == null) + { + throw new ArgumentNullException(nameof(endpoint)); + } + + if (string.IsNullOrEmpty(id)) + { + throw new ArgumentNullException(nameof(id)); + } + + if (string.IsNullOrEmpty(secret)) + { + throw new ArgumentNullException(nameof(secret)); + } + + return $"{EndpointSection}={endpoint.AbsoluteUri.TrimEnd('/')};{IdSection}={id};{SecretSection}={secret}"; + } } } diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Constants/FailOverConstants.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Constants/FailOverConstants.cs index f4836ced..c3566d41 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Constants/FailOverConstants.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Constants/FailOverConstants.cs @@ -14,5 +14,7 @@ internal class FailOverConstants public static readonly TimeSpan MaxBackoffDuration = TimeSpan.FromMinutes(10); // Minimum backoff duration for retries that occur after the fixed backoff window during startup. public static readonly TimeSpan MinStartupBackoffDuration = TimeSpan.FromSeconds(30); + + public static readonly TimeSpan UdpSrvQueryTimeout = TimeSpan.FromSeconds(5); } } diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Constants/LoggingConstants.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Constants/LoggingConstants.cs index ec78facf..41c56ca3 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Constants/LoggingConstants.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Constants/LoggingConstants.cs @@ -14,6 +14,7 @@ internal class LoggingConstants public const string RefreshCanceledError = "A refresh operation was canceled."; public const string RefreshFailedDueToKeyVaultError = "A refresh operation failed while resolving a Key Vault reference."; public const string PushNotificationUnregisteredEndpoint = "Ignoring the push notification received for the unregistered endpoint"; + public const string FallbackClientLookupError = "Failed to perform fallback client lookup."; // Successful update, debug log level public const string RefreshKeyValueRead = "Key-value read from App Configuration."; diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Extensions/ListExtensions.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Extensions/ListExtensions.cs index 06bb5a29..9be9b55a 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Extensions/ListExtensions.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Extensions/ListExtensions.cs @@ -1,14 +1,51 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -// +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +using DnsClient.Protocol; using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; - -namespace Microsoft.Extensions.Configuration.AzureAppConfiguration.Extensions -{ - internal static class ListExtensions - { + +namespace Microsoft.Extensions.Configuration.AzureAppConfiguration.Extensions +{ + internal static class ListExtensions + { + public static List Shuffle(this List values) + { + var rdm = new Random(); + int count = values.Count; + + for (int i = count - 1; i > 0; i--) + { + int swapIndex = rdm.Next(i + 1); + + if (swapIndex != i) + { + T value = values[swapIndex]; + values[swapIndex] = values[i]; + values[i] = value; + } + } + + return values; + } + + public static List SortSrvRecords(this List srvRecords) + { + srvRecords.Sort((a, b) => + { + if (a.Priority != b.Priority) + return a.Priority.CompareTo(b.Priority); + + if (a.Weight != b.Weight) + return b.Weight.CompareTo(a.Weight); + + return 0; + }); + + return srvRecords; + } + public static void AppendUnique(this List items, T item) { if (item == null) @@ -28,4 +65,4 @@ public static void AppendUnique(this List items, T item) items.Add(item); } } -} +} \ No newline at end of file diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Extensions/TimeSpanExtensions.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Extensions/TimeSpanExtensions.cs index a00efc48..233c23c8 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Extensions/TimeSpanExtensions.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Extensions/TimeSpanExtensions.cs @@ -95,7 +95,7 @@ public static TimeSpan CalculateBackoffDuration(this TimeSpan minDuration, TimeS // // IMPORTANT: This can overflow - double calculatedMilliseconds = Math.Max(1, minDuration.TotalMilliseconds) * (1L << Math.Min(attempts, SafeShiftLimit)); + double calculatedMilliseconds = Math.Max(1, minDuration.TotalMilliseconds) * (1L << Math.Min(attempts - 1, SafeShiftLimit)); if (calculatedMilliseconds > maxDuration.TotalMilliseconds || calculatedMilliseconds <= 0 /*overflow*/) diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/IConfigurationClientManager.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/IConfigurationClientManager.cs index be56f5ff..798e35e6 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/IConfigurationClientManager.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/IConfigurationClientManager.cs @@ -10,13 +10,11 @@ namespace Microsoft.Extensions.Configuration.AzureAppConfiguration { internal interface IConfigurationClientManager { - IEnumerable GetAvailableClients(DateTimeOffset time); + IEnumerable GetClients(); - IEnumerable GetAllClients(); + void RefreshClients(); - void UpdateClientStatus(ConfigurationClient client, bool successful); - - bool UpdateSyncToken(Uri endpoint, String syncToken); + bool UpdateSyncToken(Uri endpoint, string syncToken); Uri GetEndpointForClient(ConfigurationClient client); } diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/LogHelper.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/LogHelper.cs index ce38204c..113a1499 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/LogHelper.cs +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/LogHelper.cs @@ -84,5 +84,10 @@ public static string BuildLastEndpointFailedMessage(string endpoint) { return $"{LoggingConstants.RefreshFailedToGetSettingsFromEndpoint} '{endpoint?.TrimEnd('/')}'."; } + + public static string BuildFallbackClientLookupFailMessage(string exceptionMessage) + { + return $"{LoggingConstants.FallbackClientLookupError}\n{exceptionMessage}"; + } } } diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Microsoft.Extensions.Configuration.AzureAppConfiguration.csproj b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Microsoft.Extensions.Configuration.AzureAppConfiguration.csproj index b02de112..91b812fc 100644 --- a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Microsoft.Extensions.Configuration.AzureAppConfiguration.csproj +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/Microsoft.Extensions.Configuration.AzureAppConfiguration.csproj @@ -17,6 +17,7 @@ + diff --git a/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/SrvLookupClient.cs b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/SrvLookupClient.cs new file mode 100644 index 00000000..bcbdff75 --- /dev/null +++ b/src/Microsoft.Extensions.Configuration.AzureAppConfiguration/SrvLookupClient.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using DnsClient; +using DnsClient.Protocol; + +namespace Microsoft.Extensions.Configuration.AzureAppConfiguration +{ + internal class SrvLookupClient + { + private readonly LookupClient _lookupClient; + + private const string TcpOrigin = "_origin._tcp"; + private const string TCP = "_tcp"; + private const string Alt = "_alt"; + + public SrvLookupClient() + { + _lookupClient = new LookupClient(); + } + + public async Task> QueryAsync(string host, CancellationToken cancellationToken) + { + string originSrvDns = $"{TcpOrigin}.{host}"; + + IEnumerable originRecords = await InternalQueryAsync(originSrvDns, cancellationToken).ConfigureAwait(false); + + if (originRecords == null || originRecords.Count() == 0) + { + return Enumerable.Empty(); + } + + SrvRecord originHostSrv = originRecords.First(); + + string originHost = originHostSrv.Target.Value.TrimEnd('.'); + + IEnumerable results = new SrvRecord[] { originHostSrv }; + + int index = 0; + + while (true) + { + string altSrvDns = $"{Alt}{index}.{TCP}.{originHost}"; + + IEnumerable records = await InternalQueryAsync(altSrvDns, cancellationToken).ConfigureAwait(false); + + // If we get no record from _alt{i} SRV, we have reached the end of _alt* list + if (records == null || !records.Any()) + { + break; + } + + results = results.Concat(records); + + index++; + } + + return results; + } + + private async Task> InternalQueryAsync(string srvDns, CancellationToken cancellationToken) + { + IDnsQueryResponse dnsResponse = await _lookupClient.QueryAsync(srvDns, QueryType.SRV, QueryClass.IN, cancellationToken).ConfigureAwait(false); + + return dnsResponse.Answers.SrvRecords(); + } + } +} diff --git a/tests/Tests.AzureAppConfiguration/FailoverTests.cs b/tests/Tests.AzureAppConfiguration/FailoverTests.cs index 32b4cd50..d302e407 100644 --- a/tests/Tests.AzureAppConfiguration/FailoverTests.cs +++ b/tests/Tests.AzureAppConfiguration/FailoverTests.cs @@ -3,6 +3,7 @@ // using Azure; using Azure.Data.AppConfiguration; +using Azure.Identity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.AzureAppConfiguration; using Moq; @@ -21,59 +22,6 @@ public class FailOverTests eTag: new ETag("0a76e3d7-7ec1-4e37-883c-9ea6d0d89e63"), contentType: "text"); - [Fact] - public void FailOverTests_DoesNotReturnBackedOffClient() - { - // Arrange - IConfigurationRefresher refresher = null; - var mockResponse = new Mock(); - - var mockClient1 = new Mock(); - mockClient1.Setup(c => c.GetConfigurationSettingsAsync(It.IsAny(), It.IsAny())) - .Throws(new RequestFailedException(503, "Request failed.")); - mockClient1.Setup(c => c.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny())) - .Throws(new RequestFailedException(503, "Request failed.")); - mockClient1.Setup(c => c.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny())) - .Throws(new RequestFailedException(503, "Request failed.")); - mockClient1.Setup(c => c.Equals(mockClient1)).Returns(true); - - var mockClient2 = new Mock(); - mockClient2.Setup(c => c.GetConfigurationSettingsAsync(It.IsAny(), It.IsAny())) - .Returns(new MockAsyncPageable(Enumerable.Empty().ToList())); - mockClient2.Setup(c => c.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(Task.FromResult(Response.FromValue(kv, mockResponse.Object))); - mockClient2.Setup(c => c.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(Task.FromResult(Response.FromValue(kv, mockResponse.Object))); - mockClient2.Setup(c => c.Equals(mockClient2)).Returns(true); - - ConfigurationClientWrapper cw1 = new ConfigurationClientWrapper(TestHelpers.PrimaryConfigStoreEndpoint, mockClient1.Object); - ConfigurationClientWrapper cw2 = new ConfigurationClientWrapper(TestHelpers.SecondaryConfigStoreEndpoint, mockClient2.Object); - - var clientList = new List() { cw1, cw2 }; - var configClientManager = new ConfigurationClientManager(clientList); - - // The client enumerator should return 2 clients for the first time. - Assert.Equal(2, configClientManager.GetAvailableClients(DateTimeOffset.UtcNow).Count()); - - var config = new ConfigurationBuilder() - .AddAzureAppConfiguration(options => - { - options.ClientManager = configClientManager; - options.Select("TestKey*"); - options.ConfigureRefresh(refreshOptions => - { - refreshOptions.Register("TestKey1", "label") - .SetCacheExpiration(TimeSpan.FromSeconds(1)); - }); - - refresher = options.GetRefresher(); - }) - .Build(); - - // The client enumerator should return just 1 client since one client is in the backoff state. - Assert.Single(configClientManager.GetAvailableClients(DateTimeOffset.UtcNow)); - } - [Fact] public void FailOverTests_ReturnsAllClientsIfAllBackedOff() { @@ -105,8 +53,8 @@ public void FailOverTests_ReturnsAllClientsIfAllBackedOff() var clientList = new List() { cw1, cw2 }; var configClientManager = new ConfigurationClientManager(clientList); - // The client enumerator should return 2 clients for the first time. - Assert.Equal(2, configClientManager.GetAvailableClients(DateTimeOffset.UtcNow).Count()); + // The client enumerator should return 2 clients + Assert.Equal(2, configClientManager.GetClients().Count()); var configBuilder = new ConfigurationBuilder() .AddAzureAppConfiguration(options => @@ -123,6 +71,8 @@ public void FailOverTests_ReturnsAllClientsIfAllBackedOff() .SetCacheExpiration(TimeSpan.FromSeconds(1)); }); + options.ReplicaDiscoveryEnabled = false; + refresher = options.GetRefresher(); }); @@ -135,8 +85,10 @@ public void FailOverTests_ReturnsAllClientsIfAllBackedOff() // Assert the inner request failed exceptions Assert.True((exception.InnerException as AggregateException)?.InnerExceptions?.All(e => e is RequestFailedException) ?? false); - // The client manager should return no clients since all clients are in the back-off state. - Assert.False(configClientManager.GetAvailableClients(DateTimeOffset.UtcNow).Any()); + refresher.RefreshAsync().Wait(); + + // The client manager should have called RefreshClients when all clients were backed off + Assert.Equal(1, configClientManager.RefreshClientsCalled); } [Fact] @@ -170,8 +122,8 @@ public void FailOverTests_PropagatesNonFailOverableExceptions() var clientList = new List() { cw1, cw2 }; var configClientManager = new ConfigurationClientManager(clientList); - // The client enumerator should return 2 clients for the first time. - Assert.Equal(2, configClientManager.GetAvailableClients(DateTimeOffset.UtcNow).Count()); + // The client enumerator should return 2 clients + Assert.Equal(2, configClientManager.GetClients().Count()); var configBuilder = new ConfigurationBuilder() .AddAzureAppConfiguration(options => @@ -229,12 +181,13 @@ public void FailOverTests_BackoffStateIsUpdatedOnSuccessfulRequest() var clientList = new List() { cw1, cw2 }; var configClientManager = new ConfigurationClientManager(clientList); - // The client enumerator should return 2 clients for the first time. - Assert.Equal(2, configClientManager.GetAvailableClients(DateTimeOffset.UtcNow).Count()); + // The client enumerator should return 2 clients + Assert.Equal(2, configClientManager.GetClients().Count()); var config = new ConfigurationBuilder() .AddAzureAppConfiguration(options => { + options.MinBackoffDuration = TimeSpan.FromSeconds(2); options.ClientManager = configClientManager; options.Select("TestKey*"); options.ConfigureRefresh(refreshOptions => @@ -246,16 +199,138 @@ public void FailOverTests_BackoffStateIsUpdatedOnSuccessfulRequest() refresher = options.GetRefresher(); }).Build(); - // The client enumerator should return just 1 client for the second time. - Assert.Single(configClientManager.GetAvailableClients(DateTimeOffset.UtcNow)); + refresher.RefreshAsync().Wait(); + + // The first client should not have been called during refresh + mockClient1.Verify(mc => mc.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(0)); + + mockClient1.Verify(mc => mc.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(0)); - // Sleep for backoff-time to pass. - Thread.Sleep(TimeSpan.FromSeconds(31)); + mockClient2.Verify(mc => mc.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(1)); + // Wait for client 1 backoff to end + Thread.Sleep(2500); + refresher.RefreshAsync().Wait(); - // The client enumerator should return 2 clients for the third time. - Assert.Equal(2, configClientManager.GetAvailableClients(DateTimeOffset.UtcNow).Count()); + // The first client should have been called now with refresh after the backoff time ends + mockClient1.Verify(mc => mc.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(1)); + } + + [Fact] + public void FailOverTests_AutoFailover() + { + // Arrange + IConfigurationRefresher refresher = null; + var mockResponse = new Mock(); + + var mockClient1 = new Mock(); + mockClient1.Setup(c => c.GetConfigurationSettingsAsync(It.IsAny(), It.IsAny())) + .Throws(new RequestFailedException(503, "Request failed.")); + mockClient1.Setup(c => c.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Throws(new RequestFailedException(503, "Request failed.")); + mockClient1.Setup(c => c.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Throws(new RequestFailedException(503, "Request failed.")); + mockClient1.Setup(c => c.Equals(mockClient1)).Returns(true); + + var mockClient2 = new Mock(); + mockClient2.Setup(c => c.GetConfigurationSettingsAsync(It.IsAny(), It.IsAny())) + .Returns(new MockAsyncPageable(Enumerable.Empty().ToList())); + mockClient2.Setup(c => c.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(Task.FromResult(Response.FromValue(kv, mockResponse.Object))); + mockClient2.Setup(c => c.GetConfigurationSettingAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(Task.FromResult(Response.FromValue(kv, mockResponse.Object))); + mockClient2.Setup(c => c.Equals(mockClient2)).Returns(true); + + ConfigurationClientWrapper cw1 = new ConfigurationClientWrapper(TestHelpers.PrimaryConfigStoreEndpoint, mockClient1.Object); + ConfigurationClientWrapper cw2 = new ConfigurationClientWrapper(TestHelpers.SecondaryConfigStoreEndpoint, mockClient2.Object); + + var clientList = new List() { cw1 }; + var autoFailoverList = new List() { cw2 }; + var mockedConfigClientManager = new MockedConfigurationClientManager(clientList, autoFailoverList); + + // Should not throw exception. + var config = new ConfigurationBuilder() + .AddAzureAppConfiguration(options => + { + options.ClientManager = mockedConfigClientManager; + options.Select("TestKey*"); + options.ConfigureRefresh(refreshOptions => + { + refreshOptions.Register("TestKey1", "label") + .SetCacheExpiration(TimeSpan.FromSeconds(1)); + }); + refresher = options.GetRefresher(); + }) + .Build(); + } + + [Fact] + public void FailOverTests_ValidateEndpoints() + { + var configClientManager = new ConfigurationClientManager( + new[] { new Uri("https://foobar.azconfig.io") }, + new DefaultAzureCredential(), + new ConfigurationClientOptions(), + true); + + Assert.True(configClientManager.IsValidEndpoint("azure.azconfig.io")); + Assert.True(configClientManager.IsValidEndpoint("appconfig.azconfig.io")); + Assert.True(configClientManager.IsValidEndpoint("azure.privatelink.azconfig.io")); + Assert.True(configClientManager.IsValidEndpoint("azure-replica.azconfig.io")); + Assert.False(configClientManager.IsValidEndpoint("azure.badazconfig.io")); + Assert.False(configClientManager.IsValidEndpoint("azure.azconfigbad.io")); + Assert.False(configClientManager.IsValidEndpoint("azure.appconfig.azure.com")); + Assert.False(configClientManager.IsValidEndpoint("azure.azconfig.bad.io")); + + var configClientManager2 = new ConfigurationClientManager( + new[] { new Uri("https://foobar.appconfig.azure.com") }, + new DefaultAzureCredential(), + new ConfigurationClientOptions(), + true); + + Assert.True(configClientManager2.IsValidEndpoint("azure.appconfig.azure.com")); + Assert.True(configClientManager2.IsValidEndpoint("azure.z1.appconfig.azure.com")); + Assert.True(configClientManager2.IsValidEndpoint("azure-replia.z1.appconfig.azure.com")); + Assert.True(configClientManager2.IsValidEndpoint("azure.privatelink.appconfig.azure.com")); + Assert.True(configClientManager2.IsValidEndpoint("azconfig.appconfig.azure.com")); + Assert.False(configClientManager2.IsValidEndpoint("azure.azconfig.io")); + Assert.False(configClientManager2.IsValidEndpoint("azure.badappconfig.azure.com")); + Assert.False(configClientManager2.IsValidEndpoint("azure.appconfigbad.azure.com")); + + var configClientManager3 = new ConfigurationClientManager( + new[] { new Uri("https://foobar.azconfig-test.io") }, + new DefaultAzureCredential(), + new ConfigurationClientOptions(), + true); + + Assert.False(configClientManager3.IsValidEndpoint("azure.azconfig-test.io")); + Assert.False(configClientManager3.IsValidEndpoint("azure.azconfig.io")); + + var configClientManager4 = new ConfigurationClientManager( + new[] { new Uri("https://foobar.z1.appconfig-test.azure.com") }, + new DefaultAzureCredential(), + new ConfigurationClientOptions(), + true); + + Assert.False(configClientManager4.IsValidEndpoint("foobar.z2.appconfig-test.azure.com")); + Assert.False(configClientManager4.IsValidEndpoint("foobar.appconfig-test.azure.com")); + Assert.False(configClientManager4.IsValidEndpoint("foobar.appconfig.azure.com")); + } + + [Fact] + public void FailOverTests_GetNoDynamicClient() + { + var configClientManager = new ConfigurationClientManager( + new[] { new Uri("https://azure.azconfig.io") }, + new DefaultAzureCredential(), + new ConfigurationClientOptions(), + true); + + var clients = configClientManager.GetClients(); + + // Only contains the client that passed while constructing the ConfigurationClientManager + Assert.Single(clients); } [Fact] @@ -304,9 +379,6 @@ public void FailOverTests_FailOverOnKeyVaultReferenceException() }) .Build(); - // The client enumerator should return just 1 client. - Assert.Single(configClientManager.GetAvailableClients(DateTimeOffset.UtcNow)); - // The build should be successful since one client was backed off and it failed over to the second client. Assert.Equal("TestValue1", config["TestKey1"]); } diff --git a/tests/Tests.AzureAppConfiguration/LoggingTests.cs b/tests/Tests.AzureAppConfiguration/LoggingTests.cs index 42132df5..96aa5933 100644 --- a/tests/Tests.AzureAppConfiguration/LoggingTests.cs +++ b/tests/Tests.AzureAppConfiguration/LoggingTests.cs @@ -372,6 +372,8 @@ public void ValidateFailoverToDifferentEndpointMessageLoggedAfterFailover() }); refresher = options.GetRefresher(); + + options.ReplicaDiscoveryEnabled = false; }) .Build(); diff --git a/tests/Tests.AzureAppConfiguration/MockedConfigurationClientManager.cs b/tests/Tests.AzureAppConfiguration/MockedConfigurationClientManager.cs index c0859d86..7e6c03e1 100644 --- a/tests/Tests.AzureAppConfiguration/MockedConfigurationClientManager.cs +++ b/tests/Tests.AzureAppConfiguration/MockedConfigurationClientManager.cs @@ -13,21 +13,20 @@ namespace Tests.AzureAppConfiguration internal class MockedConfigurationClientManager : IConfigurationClientManager { IList _clients; + IList _autoFailoverClients; internal int UpdateSyncTokenCalled { get; set; } = 0; - public bool HasAvailableClients => _clients.Any(client => client.BackoffEndTime <= DateTime.UtcNow); - public MockedConfigurationClientManager(IEnumerable clients) { _clients = clients.ToList(); + _autoFailoverClients = new List(); } - public IEnumerable GetAvailableClients(DateTimeOffset time) => GetAllClients(); - - public IEnumerable GetAllClients() + public MockedConfigurationClientManager(IEnumerable clients, IEnumerable autoFailoverClients) { - return _clients.Select(cw => cw.Client); + _autoFailoverClients = autoFailoverClients.ToList(); + _clients = clients.ToList(); } public void UpdateClientStatus(ConfigurationClient client, bool successful) @@ -52,7 +51,33 @@ public Uri GetEndpointForClient(ConfigurationClient client) ConfigurationClientWrapper currentClient = _clients.FirstOrDefault(c => c.Client == client); + if (currentClient == null) + { + currentClient = _autoFailoverClients.FirstOrDefault(c => c.Client == client); + } + return currentClient?.Endpoint; } + + public IEnumerable GetClients() + { + var result = new List(); + + foreach (var client in _clients) { + result.Add(client.Client); + } + + foreach (var client in _autoFailoverClients) + { + result.Add(client.Client); + } + + return result; + } + + public void RefreshClients() + { + return; + } } } diff --git a/tests/Tests.AzureAppConfiguration/RefreshTests.cs b/tests/Tests.AzureAppConfiguration/RefreshTests.cs index 7d797dba..48becbd9 100644 --- a/tests/Tests.AzureAppConfiguration/RefreshTests.cs +++ b/tests/Tests.AzureAppConfiguration/RefreshTests.cs @@ -730,6 +730,7 @@ public async Task RefreshTests_UpdatesAllSettingsIfInitialLoadFails() .AddAzureAppConfiguration(options => { options.Select("TestKey*"); + options.MinBackoffDuration = TimeSpan.FromTicks(1); options.ClientManager = TestHelpers.CreateMockedConfigurationClientManager(mockClient.Object); options.ConfigureRefresh(refreshOptions => { @@ -746,6 +747,9 @@ public async Task RefreshTests_UpdatesAllSettingsIfInitialLoadFails() Assert.Null(configuration["TestKey2"]); Assert.Null(configuration["TestKey3"]); + // Make sure MinBackoffDuration has ended + Thread.Sleep(100); + // Act await Assert.ThrowsAsync(async () => { @@ -801,6 +805,7 @@ Response GetIfChanged(ConfigurationSetting setting, bool o var config = new ConfigurationBuilder() .AddAzureAppConfiguration(options => { + options.MinBackoffDuration = TimeSpan.FromTicks(1); options.ClientManager = TestHelpers.CreateMockedConfigurationClientManager(mockClient.Object); options.Select("TestKey*", "label"); options.ConfigureRefresh(refreshOptions => diff --git a/tests/Tests.AzureAppConfiguration/Tests.AzureAppConfiguration.csproj b/tests/Tests.AzureAppConfiguration/Tests.AzureAppConfiguration.csproj index 4ed6e40f..0dfcabbd 100644 --- a/tests/Tests.AzureAppConfiguration/Tests.AzureAppConfiguration.csproj +++ b/tests/Tests.AzureAppConfiguration/Tests.AzureAppConfiguration.csproj @@ -14,6 +14,7 @@ +