-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Cache the MEF composition in the Roslyn LSP. #76276
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
Changes from 6 commits
2e9a0e7
c3d1800
9953341
ce0a590
81c77bb
2acfc74
b768288
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using Xunit.Abstractions; | ||
|
||
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests | ||
{ | ||
public sealed class ExportProviderBuilderTests(ITestOutputHelper testOutputHelper) | ||
: AbstractLanguageServerHostTests(testOutputHelper) | ||
{ | ||
[Fact] | ||
public async Task MefCompositionIsCached() | ||
{ | ||
await using var testServer = await CreateLanguageServerAsync(includeDevKitComponents: false); | ||
|
||
var mefCompositions = Directory.EnumerateFiles(MefCacheDirectory.Path, "*.mef-composition", SearchOption.AllDirectories); | ||
|
||
Assert.Single(mefCompositions); | ||
} | ||
|
||
[Fact] | ||
public async Task MefCompositionIsReused() | ||
{ | ||
await using var testServer = await CreateLanguageServerAsync(includeDevKitComponents: false); | ||
|
||
// Second test server with the same set of assemblies. | ||
await using var testServer2 = await CreateLanguageServerAsync(includeDevKitComponents: false); | ||
|
||
var mefCompositions = Directory.EnumerateFiles(MefCacheDirectory.Path, "*.mef-composition", SearchOption.AllDirectories); | ||
|
||
Assert.Single(mefCompositions); | ||
} | ||
|
||
[Fact] | ||
public async Task MultipleMefCompositionsAreCached() | ||
{ | ||
await using var testServer = await CreateLanguageServerAsync(includeDevKitComponents: false); | ||
|
||
// Second test server with a different set of assemblies. | ||
await using var testServer2 = await CreateLanguageServerAsync(includeDevKitComponents: true); | ||
|
||
var mefCompositions = Directory.EnumerateFiles(MefCacheDirectory.Path, "*.mef-composition", SearchOption.AllDirectories); | ||
|
||
Assert.Equal(2, mefCompositions.Count()); | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,8 @@ | |
// See the LICENSE file in the project root for more information. | ||
|
||
using System.Collections.Immutable; | ||
using System.IO.Hashing; | ||
using System.Text; | ||
using Microsoft.CodeAnalysis.LanguageServer.Logging; | ||
using Microsoft.CodeAnalysis.LanguageServer.Services; | ||
using Microsoft.CodeAnalysis.Shared.Collections; | ||
|
@@ -18,6 +20,7 @@ public static async Task<ExportProvider> CreateExportProviderAsync( | |
ExtensionAssemblyManager extensionManager, | ||
IAssemblyLoader assemblyLoader, | ||
string? devKitDependencyPath, | ||
string cacheDirectory, | ||
ILoggerFactory loggerFactory) | ||
{ | ||
var logger = loggerFactory.CreateLogger<ExportProviderBuilder>(); | ||
|
@@ -38,17 +41,60 @@ public static async Task<ExportProvider> CreateExportProviderAsync( | |
// Add the extension assemblies to the MEF catalog. | ||
assemblyPaths = assemblyPaths.Concat(extensionManager.ExtensionAssemblyPaths); | ||
|
||
logger.LogTrace($"Composing MEF catalog using:{Environment.NewLine}{string.Join($" {Environment.NewLine}", assemblyPaths)}."); | ||
// Get the cached MEF composition or create a new one. | ||
var exportProviderFactory = await GetCompositionConfigurationAsync(assemblyPaths.ToImmutableArray(), assemblyLoader, cacheDirectory, logger); | ||
|
||
// Create an export provider, which represents a unique container of values. | ||
// You can create as many of these as you want, but typically an app needs just one. | ||
var exportProvider = exportProviderFactory.CreateExportProvider(); | ||
|
||
// Immediately set the logger factory, so that way it'll be available for the rest of the composition | ||
exportProvider.GetExportedValue<ServerLoggerFactory>().SetFactory(loggerFactory); | ||
|
||
// Also add the ExtensionAssemblyManager so it will be available for the rest of the composition. | ||
exportProvider.GetExportedValue<ExtensionAssemblyManagerMefProvider>().SetMefExtensionAssemblyManager(extensionManager); | ||
|
||
return exportProvider; | ||
} | ||
|
||
private static async Task<IExportProviderFactory> GetCompositionConfigurationAsync( | ||
ImmutableArray<string> assemblyPaths, | ||
IAssemblyLoader assemblyLoader, | ||
string cacheDirectory, | ||
ILogger logger) | ||
{ | ||
// Create a MEF resolver that can resolve assemblies in the extension contexts. | ||
var resolver = new Resolver(assemblyLoader); | ||
|
||
var compositionCacheFile = GetCompositionCacheFilePath(cacheDirectory, assemblyPaths); | ||
|
||
// Try to load a cached composition. | ||
try | ||
{ | ||
if (File.Exists(compositionCacheFile)) | ||
{ | ||
logger.LogTrace($"Loading cached MEF catalog: {compositionCacheFile}"); | ||
|
||
CachedComposition cachedComposition = new(); | ||
using FileStream cacheStream = new(compositionCacheFile, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); | ||
var exportProviderFactory = await cachedComposition.LoadExportProviderFactoryAsync(cacheStream, resolver); | ||
|
||
return exportProviderFactory; | ||
} | ||
} | ||
catch (Exception ex) | ||
{ | ||
// Log the error, and move on to recover by recreating the MEF composition. | ||
logger.LogError($"Loading cached MEF composition failed: {ex}"); | ||
JoeRobich marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
logger.LogTrace($"Composing MEF catalog using:{Environment.NewLine}{string.Join($" {Environment.NewLine}", assemblyPaths)}."); | ||
|
||
var discovery = PartDiscovery.Combine( | ||
resolver, | ||
new AttributedPartDiscovery(resolver, isNonPublicSupported: true), // "NuGet MEF" attributes (Microsoft.Composition) | ||
new AttributedPartDiscoveryV1(resolver)); | ||
|
||
// TODO - we should likely cache the catalog so we don't have to rebuild it every time. | ||
var catalog = ComposableCatalog.Create(resolver) | ||
.AddParts(await discovery.CreatePartsAsync(assemblyPaths)) | ||
.WithCompositionService(); // Makes an ICompositionService export available to MEF parts to import | ||
|
@@ -59,20 +105,69 @@ public static async Task<ExportProvider> CreateExportProviderAsync( | |
// Verify we only have expected errors. | ||
ThrowOnUnexpectedErrors(config, catalog, logger); | ||
|
||
// Try to cache the composition. | ||
_ = WriteCompositionCacheAsync(compositionCacheFile, config, logger).ReportNonFatalErrorAsync(); | ||
|
||
// Prepare an ExportProvider factory based on this graph. | ||
var exportProviderFactory = config.CreateExportProviderFactory(); | ||
return config.CreateExportProviderFactory(); | ||
} | ||
|
||
// Create an export provider, which represents a unique container of values. | ||
// You can create as many of these as you want, but typically an app needs just one. | ||
var exportProvider = exportProviderFactory.CreateExportProvider(); | ||
private static string GetCompositionCacheFilePath(string cacheDirectory, ImmutableArray<string> assemblyPaths) | ||
{ | ||
// This should vary based on .NET runtime major version so that as some of our processes switch between our target | ||
// .NET version and the user's selected SDK runtime version (which may be newer), the MEF cache is kept isolated. | ||
// This can be important when the MEF catalog records full assembly names such as "System.Runtime, 8.0.0.0" yet | ||
// we might be running on .NET 7 or .NET 8, depending on the particular session and user settings. | ||
var cacheSubdirectory = $".NET {Environment.Version.Major}"; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does that Version.Major mean a minor update won't create a new cache? Is that a problem? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am not 100% sure. I took this bit from DevKit and have updated the comment to match theirs. I know we have changed target runtime from 8.0.9 to 8.0.10 and now 8.0.11 seemingly without incident. |
||
|
||
// Immediately set the logger factory, so that way it'll be available for the rest of the composition | ||
exportProvider.GetExportedValue<ServerLoggerFactory>().SetFactory(loggerFactory); | ||
return Path.Combine(cacheDirectory, cacheSubdirectory, $"c#-languageserver.{ComputeAssemblyHash(assemblyPaths)}.mef-composition"); | ||
|
||
// Also add the ExtensionAssemblyManager so it will be available for the rest of the composition. | ||
exportProvider.GetExportedValue<ExtensionAssemblyManagerMefProvider>().SetMefExtensionAssemblyManager(extensionManager); | ||
static string ComputeAssemblyHash(ImmutableArray<string> assemblyPaths) | ||
{ | ||
// Ensure AssemblyPaths are always in the same order. | ||
assemblyPaths = assemblyPaths.Sort(); | ||
|
||
return exportProvider; | ||
var assemblies = new StringBuilder(); | ||
foreach (var assemblyPath in assemblyPaths) | ||
JoeRobich marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
// Include assembly path in the hash so that changes to the set of included | ||
// assemblies cause the composition to be rebuilt. | ||
assemblies.Append(assemblyPath); | ||
// Include the last write time in the hash so that newer assemblies written | ||
// to the same location cause the composition to be rebuilt. | ||
assemblies.Append(File.GetLastWriteTimeUtc(assemblyPath).ToString("F")); | ||
} | ||
|
||
var hash = XxHash128.Hash(Encoding.UTF8.GetBytes(assemblies.ToString())); | ||
// Convert to filename safe base64 string. | ||
return Convert.ToBase64String(hash).Replace('+', '-').Replace('/', '_').TrimEnd('='); | ||
ToddGrun marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
private static async Task WriteCompositionCacheAsync(string compositionCacheFile, CompositionConfiguration config, ILogger logger) | ||
{ | ||
try | ||
{ | ||
await Task.Yield(); | ||
|
||
if (Path.GetDirectoryName(compositionCacheFile) is string directory) | ||
{ | ||
Directory.CreateDirectory(directory); | ||
JoeRobich marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
CachedComposition cachedComposition = new(); | ||
var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); | ||
using (FileStream cacheStream = new(tempFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) | ||
{ | ||
await cachedComposition.SaveAsync(config, cacheStream); | ||
} | ||
|
||
File.Move(tempFilePath, compositionCacheFile, overwrite: true); | ||
} | ||
catch (Exception ex) | ||
{ | ||
logger.LogError($"Failed to save MEF cache: {ex}"); | ||
} | ||
} | ||
|
||
private static void ThrowOnUnexpectedErrors(CompositionConfiguration configuration, ComposableCatalog catalog, ILogger logger) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry, I'm probably being dense here. Since the saving is asynchronous, how do you know that it's completed before we check for it here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ah, thanks. Will fix up.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ToddGrun Updated.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Out of curiosity, I thought the IAsynchronousOperationListener was the way that we usually exposed async operations to tests. Was that not an option?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I will admit I have not tested a lot of these async operations. Looking through the source it seems the IAsynchronousOperationListenerProvider is typically MEF imported but this code is building the MEF composition, so we couldn't follow that pattern. Nothing is stopping us from creating our own listener instance and making it available through the TestAccessor, but I am not sure that has any benefits over using a Task. If you know of any reasons, I am happy to rework this bit in a follow up.