Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jmprieur/perf with scalable Public Client Application cache #614

Merged
merged 4 commits into from
Sep 25, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Identity.Client;

namespace Microsoft.Identity.Web.Perf.Client
{
static class ScalableTokenCacheHelper
{
/// <summary>
/// Path to the token cache
/// </summary>
public static readonly string s_cacheFileFolder =
Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),
"TokenCaches");
public static readonly string s_cacheKeysFolder = s_cacheFileFolder + "Keys";

static ScalableTokenCacheHelper()
{
if (!Directory.Exists(s_cacheFileFolder))
{
Directory.CreateDirectory(s_cacheFileFolder);
}
if (!Directory.Exists(s_cacheKeysFolder))
{
Directory.CreateDirectory(s_cacheKeysFolder);
}
}

public static Dictionary<int, string> GetAccountIdsByUserNumber()
{
int start = "MIWTestUser".Length;
Dictionary<int, string> accountIdByUserNumber = new Dictionary<int, string>();

foreach(string filePath in Directory.EnumerateFiles(s_cacheKeysFolder))
{
string fileName = Path.GetFileName(filePath);
string[] segments = fileName.Split('-');
string userUpn = segments[0];
string number = userUpn.Substring(start, userUpn.IndexOf('@')-start);

accountIdByUserNumber.Add(int.Parse(number), string.Join("-", segments.Skip(1)));
}
return accountIdByUserNumber;
}


public static void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
string cacheFilePath = GetCacheFilePath(args);
args.TokenCache.DeserializeMsalV3(File.Exists(cacheFilePath)
? File.ReadAllBytes(cacheFilePath)
: null);
}

private static string GetCacheFilePath(TokenCacheNotificationArgs args)
{
string suggestedKey = args.SuggestedCacheKey ?? args.Account.HomeAccountId.Identifier;
if (suggestedKey == null)
{
return null;
}
return Path.Combine(s_cacheFileFolder, suggestedKey);
}

public static void AfterAccessNotification(TokenCacheNotificationArgs args)
{
// if the access operation resulted in a cache update
if (args.HasStateChanged)
{
string cacheFilePath = GetCacheFilePath(args);

// reflect changesgs in the persistent store
File.WriteAllBytes(cacheFilePath,
args.TokenCache.SerializeMsalV3());

WriteKey(args);
}
}

private static void WriteKey(TokenCacheNotificationArgs args)
{
if (args.Account != null)
{
string keyPath = Path.Combine(s_cacheKeysFolder,
args.Account.Username + "-" + args.Account.HomeAccountId.Identifier);
if (!File.Exists(keyPath))
{
File.WriteAllText(keyPath, " ");
}
}
}

internal static void EnableSerialization(ITokenCache tokenCache)
{
tokenCache.SetBeforeAccess(BeforeAccessNotification);
tokenCache.SetAfterAccess(AfterAccessNotification);
}
}
}
23 changes: 12 additions & 11 deletions tests/Perf/Microsoft.Identity.Web.Perf.Client/TestRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -32,24 +33,17 @@ public TestRunner(IConfiguration configuration)
_configuration = configuration;
_usersToSimulate = int.Parse(configuration["UsersToSimulate"]);
_userAccountIdentifiers = new string[_usersToSimulate + 1];
_msalPublicClient = PublicClientApplicationBuilder
.Create(_configuration["ClientId"])
.WithAuthority(TestConstants.AadInstance, TestConstants.Organizations)
.WithLogging(Log, LogLevel.Info, false)
.Build();
TokenCacheHelper.EnableSerialization(_msalPublicClient.UserTokenCache);

}

public async Task Run()
{
Console.WriteLine($"Initializing tokens for {_usersToSimulate} users");

var accounts = await _msalPublicClient.GetAccountsAsync().ConfigureAwait(false);

int index = 1;
foreach (var account in accounts)
IDictionary<int, string> accounts = ScalableTokenCacheHelper.GetAccountIdsByUserNumber();
foreach(var account in accounts)
{
_userAccountIdentifiers[index++] = account.HomeAccountId.Identifier;
_userAccountIdentifiers[account.Key] = account.Value;
}

// Configuring the http client to trust the self-signed certificate
Expand Down Expand Up @@ -129,6 +123,13 @@ private async Task<AuthenticationResult> AcquireTokenAsync(int userIndex)
var scopes = new string[] { _configuration["ApiScopes"] };
var upn = $"{NamePrefix}{userIndex}@{_configuration["TenantDomain"]}";

var _msalPublicClient = PublicClientApplicationBuilder
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recreating a PublicClientApplication each time to avoid the MSAL.NET performance bug which makes the cache grow with the number of users even if we store it in a different file (singleton)

.Create(_configuration["ClientId"])
.WithAuthority(TestConstants.AadInstance, TestConstants.Organizations)
.WithLogging(Log, LogLevel.Info, false)
.Build();
ScalableTokenCacheHelper.EnableSerialization(_msalPublicClient.UserTokenCache);

AuthenticationResult authResult = null;
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,21 @@ static class TokenCacheHelper
/// </summary>
public static readonly string s_cacheFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location + ".msalcache.bin3";

private static readonly object s_fileLock = new object();

public static void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lock is not necessary and takes time

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, i already removed that

lock (s_fileLock)
{
args.TokenCache.DeserializeMsalV3(File.Exists(s_cacheFilePath)
? File.ReadAllBytes(s_cacheFilePath)
: null);
}
}

public static void AfterAccessNotification(TokenCacheNotificationArgs args)
{
// if the access operation resulted in a cache update
if (args.HasStateChanged)
{
lock (s_fileLock)
{
// reflect changesgs in the persistent store
File.WriteAllBytes(s_cacheFilePath,
args.TokenCache.SerializeMsalV3());
}
}
}

Expand Down