-
Notifications
You must be signed in to change notification settings - Fork 472
Expand file tree
/
Copy pathConfigurationManager_Blocking.cs
More file actions
187 lines (158 loc) · 8.8 KB
/
Copy pathConfigurationManager_Blocking.cs
File metadata and controls
187 lines (158 loc) · 8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Protocols.Configuration;
using Microsoft.IdentityModel.Telemetry;
using Microsoft.IdentityModel.Tokens;
namespace Microsoft.IdentityModel.Protocols
{
public partial class ConfigurationManager<T> where T : class
{
private readonly SemaphoreSlim _refreshLock = new(1, 1);
private TimeSpan _bootstrapRefreshInterval = TimeSpan.FromSeconds(1);
/// <summary>
/// Used to track the type of request for signaling the event handler and for telemetry.
/// </summary>
private bool _refreshRequested;
private async Task<T> GetConfigurationWithBlockingAsync(CancellationToken cancel)
{
Exception _fetchMetadataFailure = null;
await _refreshLock.WaitAsync(cancel).ConfigureAwait(false);
long startTimestamp = TimeProvider.GetTimestamp();
try
{
if (_syncAfter <= TimeProvider.GetUtcNow())
{
try
{
// Check if event handler can provide configuration
// If provided configuration is valid, skip regular retriaval process and update current configuration.
if (ConfigurationEventHandler != null)
{
ConfigurationEventHandlerResult<T> configurationRetrieved = await HandleBeforeRetrieveAsync(bypassCache: _refreshRequested, cancel).ConfigureAwait(false);
// replicate the behavior of successful retrieval from endpoint
if (configurationRetrieved != null && configurationRetrieved.Configuration != null)
{
TelemetryForUpdateBlocking(TelemetryConstants.Protocols.ConfigurationSourceHandler);
if (_refreshRequested)
_refreshRequested = false;
UpdateConfiguration(configurationRetrieved.Configuration, configurationRetrieved.RetrievalTime);
return _currentConfiguration;
}
}
// Don't use the individual CT here, this is a shared operation that shouldn't be affected by an individual's cancellation.
// The transport should have it's own timeouts, etc..
var configuration = await _configRetriever.GetConfigurationAsync(MetadataAddress, _docRetriever, CancellationToken.None).ConfigureAwait(false);
var elapsedTime = TimeProvider.GetElapsedTime(startTimestamp);
TelemetryClient.LogConfigurationRetrievalDuration(
MetadataAddress,
TelemetryConstants.Protocols.ConfigurationSourceRetriever,
elapsedTime);
if (_configValidator != null)
{
ConfigurationValidationResult result = _configValidator.Validate(configuration);
if (!result.Succeeded)
throw LogHelper.LogExceptionMessage(new InvalidConfigurationException(LogHelper.FormatInvariant(LogMessages.IDX20810, result.ErrorMessage)));
}
_lastRequestRefresh = TimeProvider.GetUtcNow().UtcDateTime;
TelemetryForUpdateBlocking(TelemetryConstants.Protocols.ConfigurationSourceRetriever);
if (_refreshRequested)
_refreshRequested = false;
UpdateConfiguration(configuration, TimeProvider.GetUtcNow());
}
catch (Exception ex)
{
_fetchMetadataFailure = ex;
if (_currentConfiguration == null)
{
if (_bootstrapRefreshInterval < RefreshInterval)
{
// Adopt exponential backoff for bootstrap refresh interval with a decorrelated jitter if it is not longer than the refresh interval.
TimeSpan _bootstrapRefreshIntervalWithJitter = TimeSpan.FromSeconds(new Random().Next((int)_bootstrapRefreshInterval.TotalSeconds));
_bootstrapRefreshInterval += _bootstrapRefreshInterval;
_syncAfter = DateTimeUtil.Add(DateTime.UtcNow, _bootstrapRefreshIntervalWithJitter);
}
else
{
_syncAfter = DateTimeUtil.Add(
TimeProvider.GetUtcNow().UtcDateTime,
AutomaticRefreshInterval < RefreshInterval ? AutomaticRefreshInterval : RefreshInterval);
}
TelemetryClient.IncrementConfigurationRefreshRequestCounter(
MetadataAddress,
TelemetryConstants.Protocols.FirstRefresh,
TelemetryConstants.Protocols.ConfigurationSourceRetriever,
ex);
throw LogHelper.LogExceptionMessage(
new InvalidOperationException(
LogHelper.FormatInvariant(LogMessages.IDX20803, LogHelper.MarkAsNonPII(MetadataAddress ?? "null"), LogHelper.MarkAsNonPII(_syncAfter), LogHelper.MarkAsNonPII(ex)), ex));
}
else
{
_syncAfter = DateTimeUtil.Add(
TimeProvider.GetUtcNow().UtcDateTime,
AutomaticRefreshInterval < RefreshInterval ? AutomaticRefreshInterval : RefreshInterval);
var elapsedTime = TimeProvider.GetElapsedTime(startTimestamp);
TelemetryClient.LogConfigurationRetrievalDuration(
MetadataAddress,
TelemetryConstants.Protocols.ConfigurationSourceRetriever,
elapsedTime,
ex);
LogHelper.LogExceptionMessage(
new InvalidOperationException(
LogHelper.FormatInvariant(LogMessages.IDX20806, LogHelper.MarkAsNonPII(MetadataAddress ?? "null"), LogHelper.MarkAsNonPII(ex)), ex));
}
}
}
// Stale metadata is better than no metadata
if (_currentConfiguration != null)
return _currentConfiguration;
else
throw LogHelper.LogExceptionMessage(
new InvalidOperationException(
LogHelper.FormatInvariant(
LogMessages.IDX20803,
LogHelper.MarkAsNonPII(MetadataAddress ?? "null"),
LogHelper.MarkAsNonPII(_syncAfter),
LogHelper.MarkAsNonPII(_fetchMetadataFailure)),
_fetchMetadataFailure));
}
finally
{
_refreshLock.Release();
}
}
private void RequestRefreshBlocking()
{
DateTime now = TimeProvider.GetUtcNow().UtcDateTime;
if (now >= DateTimeUtil.Add(_lastRequestRefresh.UtcDateTime, RefreshInterval) || _isFirstRefreshRequest)
{
_refreshRequested = true;
_syncAfter = now;
_isFirstRefreshRequest = false;
}
}
private void TelemetryForUpdateBlocking(string configurationSource)
{
string updateMode;
if (_currentConfiguration is null)
updateMode = TelemetryConstants.Protocols.FirstRefresh;
else
updateMode = _refreshRequested ? TelemetryConstants.Protocols.Manual : TelemetryConstants.Protocols.Automatic;
try
{
TelemetryClient.IncrementConfigurationRefreshRequestCounter(
MetadataAddress,
updateMode,
configurationSource);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch
{ }
#pragma warning restore CA1031 // Do not catch general exception types
}
}
}