-
Notifications
You must be signed in to change notification settings - Fork 403
Expand file tree
/
Copy pathCacheSessionManager.cs
More file actions
250 lines (220 loc) · 11.7 KB
/
CacheSessionManager.cs
File metadata and controls
250 lines (220 loc) · 11.7 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Cache.Items;
using Microsoft.Identity.Client.Core;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Client.Internal.Requests;
using Microsoft.Identity.Client.OAuth2;
using Microsoft.Identity.Client.TelemetryCore.TelemetryClient;
using Microsoft.Identity.Client.Utils;
namespace Microsoft.Identity.Client.Cache
{
/// <summary>
/// MSAL should only interact with the cache though this object. It is responsible for firing cache notifications.
/// Flows should only perform (at most) 2 cache accesses: one to read data and one to write tokens. Reading data multiple times
/// (e.g. read all ATs, read all RTs) should not refresh the cache from disk because of performance impact.
/// Write operations are still the responsibility of TokenCache.
/// </summary>
internal class CacheSessionManager : ICacheSessionManager
{
private readonly AuthenticationRequestParameters _requestParams;
private bool _cacheRefreshedForRead = false;
public CacheSessionManager(
ITokenCacheInternal tokenCacheInternal,
AuthenticationRequestParameters requestParams)
{
TokenCacheInternal = tokenCacheInternal ?? throw new ArgumentNullException(nameof(tokenCacheInternal));
_requestParams = requestParams ?? throw new ArgumentNullException(nameof(requestParams));
RequestContext = _requestParams.RequestContext;
}
public RequestContext RequestContext { get; }
#region ICacheSessionManager implementation
public ITokenCacheInternal TokenCacheInternal { get; }
private bool IsInternalCacheDisabled =>
CacheOptions.IsDisabledFor(_requestParams.RequestContext.ServiceBundle.Config.AccessorOptions);
private bool ShouldSkipInternalCacheRead(string operationName)
{
if (!IsInternalCacheDisabled)
{
return false;
}
_requestParams.RequestContext.Logger.Verbose(
() => $"[Cache Session Manager] Internal cache disabled. Skipping {operationName}.");
return true;
}
private async Task RefreshCacheForReadOperationsIfEnabledAsync(string operationName)
{
if (ShouldSkipInternalCacheRead(operationName))
{
return;
}
await RefreshCacheForReadOperationsAsync().ConfigureAwait(false);
}
public async Task<MsalAccessTokenCacheItem> FindAccessTokenAsync()
{
await RefreshCacheForReadOperationsIfEnabledAsync("access token lookup").ConfigureAwait(false);
if (IsInternalCacheDisabled)
{
return null;
}
return await TokenCacheInternal.FindAccessTokenAsync(_requestParams).ConfigureAwait(false);
}
public async Task<Tuple<MsalAccessTokenCacheItem, MsalIdTokenCacheItem, Account>> SaveTokenResponseAsync(MsalTokenResponse tokenResponse)
{
var result = await TokenCacheInternal.SaveTokenResponseAsync(_requestParams, tokenResponse).ConfigureAwait(false);
RequestContext.ApiEvent.CachedAccessTokenCount = GetInternalCacheEntryCountForTelemetry();
return result;
}
public async Task<Account> GetAccountAssociatedWithAccessTokenAsync(MsalAccessTokenCacheItem msalAccessTokenCacheItem)
{
await RefreshCacheForReadOperationsIfEnabledAsync("account lookup for access token").ConfigureAwait(false);
if (IsInternalCacheDisabled)
{
return null;
}
return await TokenCacheInternal.GetAccountAssociatedWithAccessTokenAsync(_requestParams, msalAccessTokenCacheItem).ConfigureAwait(false);
}
public async Task<MsalIdTokenCacheItem> GetIdTokenCacheItemAsync(MsalAccessTokenCacheItem accessTokenCacheItem)
{
await RefreshCacheForReadOperationsIfEnabledAsync("ID token lookup").ConfigureAwait(false);
if (IsInternalCacheDisabled)
{
return null;
}
return TokenCacheInternal.GetIdTokenCacheItem(accessTokenCacheItem);
}
public async Task<MsalRefreshTokenCacheItem> FindFamilyRefreshTokenAsync(string familyId)
{
await RefreshCacheForReadOperationsIfEnabledAsync("family refresh token lookup").ConfigureAwait(false);
if (IsInternalCacheDisabled)
{
return null;
}
if (string.IsNullOrEmpty(familyId))
{
throw new ArgumentNullException(nameof(familyId));
}
return await TokenCacheInternal.FindRefreshTokenAsync(_requestParams, familyId).ConfigureAwait(false);
}
public async Task<MsalRefreshTokenCacheItem> FindRefreshTokenAsync()
{
await RefreshCacheForReadOperationsIfEnabledAsync("refresh token lookup").ConfigureAwait(false);
if (IsInternalCacheDisabled)
{
return null;
}
return await TokenCacheInternal.FindRefreshTokenAsync(_requestParams).ConfigureAwait(false);
}
public async Task<bool?> IsAppFociMemberAsync(string familyId)
{
await RefreshCacheForReadOperationsIfEnabledAsync("FOCI membership lookup").ConfigureAwait(false);
if (IsInternalCacheDisabled)
{
return null;
}
return await TokenCacheInternal.IsFociMemberAsync(_requestParams, familyId).ConfigureAwait(false);
}
public async Task<IEnumerable<IAccount>> GetAccountsAsync()
{
await RefreshCacheForReadOperationsIfEnabledAsync("accounts lookup").ConfigureAwait(false);
if (IsInternalCacheDisabled)
{
return System.Array.Empty<IAccount>();
}
return await TokenCacheInternal.GetAccountsAsync(_requestParams).ConfigureAwait(false);
}
#endregion
/// <remarks>
/// Possibly refreshes the internal cache by calling OnBeforeAccessAsync and OnAfterAccessAsync delegates.
/// </remarks>
private async Task RefreshCacheForReadOperationsAsync()
{
if (TokenCacheInternal.IsAppSubscribedToSerializationEvents())
{
if (!_cacheRefreshedForRead)
{
_requestParams.RequestContext.Logger.Verbose(()=>$"[Cache Session Manager] Entering the cache semaphore. { TokenCacheInternal.Semaphore.GetCurrentCountLogMessage()}");
await TokenCacheInternal.Semaphore.WaitAsync(_requestParams.RequestContext.UserCancellationToken).ConfigureAwait(false);
_requestParams.RequestContext.Logger.Verbose(()=>"[Cache Session Manager] Entered cache semaphore");
TelemetryData telemetryData = new TelemetryData();
try
{
if (!_cacheRefreshedForRead) // double check locking
{
string key = CacheKeyFactory.GetKeyFromRequest(_requestParams);
try
{
var args = new TokenCacheNotificationArgs(
TokenCacheInternal,
_requestParams.AppConfig.ClientId,
_requestParams.Account,
hasStateChanged: false,
isApplicationCache: TokenCacheInternal.IsApplicationCache,
suggestedCacheKey: key,
hasTokens: TokenCacheInternal.HasTokensNoLocks(),
cancellationToken: _requestParams.RequestContext.UserCancellationToken,
suggestedCacheExpiry: null,
correlationId: _requestParams.RequestContext.CorrelationId,
requestScopes: _requestParams.Scope,
requestTenantId: _requestParams.AuthorityManager.OriginalAuthority.TenantId,
identityLogger: _requestParams.RequestContext.Logger.IdentityLogger,
piiLoggingEnabled: _requestParams.RequestContext.Logger.PiiLoggingEnabled,
telemetryData: telemetryData);
var measureDurationResult = await TokenCacheInternal.OnBeforeAccessAsync(args).MeasureAsync().ConfigureAwait(false);
RequestContext.ApiEvent.DurationInCacheInMs += measureDurationResult.Milliseconds;
}
finally
{
var measureDurationResult = await StopwatchService.MeasureCodeBlockAsync(async () =>
{
var args = new TokenCacheNotificationArgs(
TokenCacheInternal,
_requestParams.AppConfig.ClientId,
_requestParams.Account,
hasStateChanged: false,
isApplicationCache: TokenCacheInternal.IsApplicationCache,
suggestedCacheKey: key,
hasTokens: TokenCacheInternal.HasTokensNoLocks(),
cancellationToken: _requestParams.RequestContext.UserCancellationToken,
suggestedCacheExpiry: null,
correlationId: _requestParams.RequestContext.CorrelationId,
requestScopes: _requestParams.Scope,
requestTenantId: _requestParams.AuthorityManager.OriginalAuthority.TenantId,
identityLogger: _requestParams.RequestContext.Logger.IdentityLogger,
piiLoggingEnabled: _requestParams.RequestContext.Logger.PiiLoggingEnabled,
telemetryData: telemetryData);
await TokenCacheInternal.OnAfterAccessAsync(args).ConfigureAwait(false);
}).ConfigureAwait(false);
RequestContext.ApiEvent.DurationInCacheInMs += measureDurationResult.Milliseconds;
}
_cacheRefreshedForRead = true;
}
}
finally
{
TokenCacheInternal.Semaphore.Release();
_requestParams.RequestContext.Logger.Verbose(()=>"[Cache Session Manager] Released cache semaphore");
RequestContext.ApiEvent.CacheLevel = telemetryData.CacheLevel;
}
}
} else
{
RequestContext.ApiEvent.CacheLevel = CacheLevel.L1Cache;
}
RequestContext.ApiEvent.CachedAccessTokenCount = GetInternalCacheEntryCountForTelemetry();
}
private int GetInternalCacheEntryCountForTelemetry()
{
if (IsInternalCacheDisabled)
{
return 0;
}
return TokenCacheInternal.Accessor.EntryCount;
}
}
}