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

Reduce NamedPipe Chatter (take 2) #10813

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
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
Expand Up @@ -2,29 +2,17 @@
// Licensed under the MIT license. See License.txt in the project root for license information.

using System;
using System.Buffers;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MessagePack;
using MessagePack.Resolvers;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.Serialization;
using Microsoft.AspNetCore.Razor.Serialization.MessagePack.Resolvers;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Internal;

namespace Microsoft.AspNetCore.Razor.ProjectSystem;

internal sealed record class RazorProjectInfo
{
private static readonly MessagePackSerializerOptions s_options = MessagePackSerializerOptions.Standard
.WithResolver(CompositeResolver.Create(
RazorProjectInfoResolver.Instance,
StandardResolver.Instance));

public ProjectKey ProjectKey { get; init; }
public string FilePath { get; init; }
public RazorConfiguration Configuration { get; init; }
Expand Down Expand Up @@ -75,22 +63,4 @@ public override int GetHashCode()

return hash.CombinedHash;
}

public byte[] Serialize()
=> MessagePackSerializer.Serialize(this, s_options);

public void SerializeTo(IBufferWriter<byte> bufferWriter)
=> MessagePackSerializer.Serialize(bufferWriter, this, s_options);

public void SerializeTo(Stream stream)
=> MessagePackSerializer.Serialize(stream, this, s_options);

public static RazorProjectInfo? DeserializeFrom(ReadOnlyMemory<byte> buffer)
=> MessagePackSerializer.Deserialize<RazorProjectInfo>(buffer, s_options);

public static RazorProjectInfo? DeserializeFrom(Stream stream)
=> MessagePackSerializer.Deserialize<RazorProjectInfo>(stream, s_options);

public static ValueTask<RazorProjectInfo> DeserializeFromAsync(Stream stream, CancellationToken cancellationToken)
=> MessagePackSerializer.DeserializeAsync<RazorProjectInfo>(stream, s_options, cancellationToken);
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.PooledObjects;
using Microsoft.AspNetCore.Razor.ProjectEngineHost;
Expand All @@ -15,60 +19,69 @@
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Razor;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Razor.ExternalAccess.RoslynWorkspace;
namespace Microsoft.AspNetCore.Razor;

internal static class RazorProjectInfoFactory
internal static class RazorProjectInfoHelpers
{
private static readonly StringComparison s_stringComparison;

static RazorProjectInfoFactory()
static RazorProjectInfoHelpers()
{
s_stringComparison = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
? StringComparison.Ordinal
: StringComparison.OrdinalIgnoreCase;
}

public static async Task<RazorProjectInfo?> ConvertAsync(Project project, ILogger? logger, CancellationToken cancellationToken)
ryzngard marked this conversation as resolved.
Show resolved Hide resolved
public static async Task<RazorProjectInfo?> ConvertAsync(
Project project,
string projectPath,
string intermediateOutputPath,
RazorConfiguration? razorConfiguration,
string? defaultNamespace,
ProjectWorkspaceState? projectWorkspaceState,
ImmutableArray<DocumentSnapshotHandle> documents,
CancellationToken cancellationToken)
{
var projectPath = Path.GetDirectoryName(project.FilePath);
if (projectPath is null)
if (documents.IsDefault)
{
logger?.LogInformation("projectPath is null, skip conversion for {projectId}", project.Id);
return null;
documents = GetDocuments(project, projectPath);
}

var intermediateOutputPath = Path.GetDirectoryName(project.CompilationOutputInfo.AssemblyPath);
if (intermediateOutputPath is null)
// Not a razor project
if (documents.Length == 0)
{
logger?.LogInformation("intermediatePath is null, skip conversion for {projectId}", project.Id);
return null;
}

// First, lets get the documents, because if there aren't any, we can skip out early
var documents = GetDocuments(project, projectPath);
if (razorConfiguration is null)
{
var options = project.AnalyzerOptions.AnalyzerConfigOptionsProvider;
razorConfiguration = ComputeRazorConfigurationOptions(options, out defaultNamespace);
}

// Not a razor project
if (documents.Length == 0)
if (projectWorkspaceState is null)
{
if (project.DocumentIds.Count == 0)
projectWorkspaceState = await GetWorkspaceStateAsync(project, razorConfiguration, defaultNamespace, projectPath, cancellationToken).ConfigureAwait(false);
if (projectWorkspaceState is null)
{
logger?.LogInformation("No razor documents for {projectId}", project.Id);
return null;
}
else
{
logger?.LogTrace("No documents in {projectId}", project.Id);
}

return null;
}

var csharpLanguageVersion = (project.ParseOptions as CSharpParseOptions)?.LanguageVersion ?? LanguageVersion.Default;

var options = project.AnalyzerOptions.AnalyzerConfigOptionsProvider;
var configuration = ComputeRazorConfigurationOptions(options, logger, out var defaultNamespace);
return new RazorProjectInfo(
projectKey: new ProjectKey(intermediateOutputPath),
ryzngard marked this conversation as resolved.
Show resolved Hide resolved
filePath: project.FilePath!,
ryzngard marked this conversation as resolved.
Show resolved Hide resolved
configuration: razorConfiguration,
rootNamespace: defaultNamespace,
displayName: project.Name,
projectWorkspaceState: projectWorkspaceState,
documents: documents);
}

public static async Task<ProjectWorkspaceState?> GetWorkspaceStateAsync(Project project, RazorConfiguration configuration, string? defaultNamespace, string projectPath, CancellationToken cancellationToken)
{
var csharpLanguageVersion = (project.ParseOptions as CSharpParseOptions)?.LanguageVersion ?? LanguageVersion.Default;
var fileSystem = RazorProjectFileSystem.Create(projectPath);

var defaultConfigure = (RazorProjectEngineBuilder builder) =>
Expand All @@ -92,19 +105,35 @@ static RazorProjectInfoFactory()
var resolver = new CompilationTagHelperResolver(NoOpTelemetryReporter.Instance);
var tagHelpers = await resolver.GetTagHelpersAsync(project, engine, cancellationToken).ConfigureAwait(false);

var projectWorkspaceState = ProjectWorkspaceState.Create(tagHelpers, csharpLanguageVersion);
return ProjectWorkspaceState.Create(tagHelpers, csharpLanguageVersion);
}

return new RazorProjectInfo(
projectKey: new ProjectKey(intermediateOutputPath),
filePath: project.FilePath!,
configuration: configuration,
rootNamespace: defaultNamespace,
displayName: project.Name,
projectWorkspaceState: projectWorkspaceState,
documents: documents);
public static RazorProjectEngine? GetProjectEngine(Project project, string projectPath)
{
var options = project.AnalyzerOptions.AnalyzerConfigOptionsProvider;
var configuration = ComputeRazorConfigurationOptions(options, out var defaultNamespace);
var csharpLanguageVersion = (project.ParseOptions as CSharpParseOptions)?.LanguageVersion ?? LanguageVersion.Default;
var fileSystem = RazorProjectFileSystem.Create(projectPath);
var defaultConfigure = (RazorProjectEngineBuilder builder) =>
{
if (defaultNamespace is not null)
{
builder.SetRootNamespace(defaultNamespace);
}

builder.SetCSharpLanguageVersion(csharpLanguageVersion);
builder.SetSupportLocalizedComponentNames(); // ProjectState in MS.CA.Razor.Workspaces does this, so I'm doing it too!
};

var engineFactory = ProjectEngineFactories.DefaultProvider.GetFactory(configuration);

return engineFactory.Create(
configuration,
fileSystem,
configure: defaultConfigure);
}

private static RazorConfiguration ComputeRazorConfigurationOptions(AnalyzerConfigOptionsProvider options, ILogger? logger, out string defaultNamespace)
public static RazorConfiguration ComputeRazorConfigurationOptions(AnalyzerConfigOptionsProvider options, out string defaultNamespace)
{
// See RazorSourceGenerator.RazorProviders.cs

Expand All @@ -119,7 +148,6 @@ private static RazorConfiguration ComputeRazorConfigurationOptions(AnalyzerConfi
if (!globalOptions.TryGetValue("build_property.RazorLangVersion", out var razorLanguageVersionString) ||
!RazorLanguageVersion.TryParse(razorLanguageVersionString, out var razorLanguageVersion))
{
logger?.LogTrace("Using default of latest language version");
razorLanguageVersion = RazorLanguageVersion.Latest;
}

Expand All @@ -130,7 +158,7 @@ private static RazorConfiguration ComputeRazorConfigurationOptions(AnalyzerConfi
return razorConfiguration;
}

internal static ImmutableArray<DocumentSnapshotHandle> GetDocuments(Project project, string projectPath)
public static ImmutableArray<DocumentSnapshotHandle> GetDocuments(Project project, string projectPath)
{
using var documents = new PooledArrayBuilder<DocumentSnapshotHandle>();

Expand Down Expand Up @@ -182,7 +210,7 @@ private static string GetTargetPath(string documentFilePath, string normalizedPr

private static bool TryGetFileKind(string filePath, [NotNullWhen(true)] out string? fileKind)
{
var extension = Path.GetExtension(filePath.AsSpan());
var extension = Path.GetExtension(filePath);

if (extension.Equals(".cshtml", s_stringComparison))
{
Expand Down Expand Up @@ -213,11 +241,9 @@ private static bool TryGetRazorFileName(string? filePath, [NotNullWhen(true)] ou
const string generatedRazorExtension = $".razor{suffix}";
const string generatedCshtmlExtension = $".cshtml{suffix}";

var path = filePath.AsSpan();

// Generated files have a path like: virtualcsharp-razor:///e:/Scratch/RazorInConsole/Goo.cshtml__virtual.cs
if (path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) &&
(path.EndsWith(generatedRazorExtension, s_stringComparison) || path.EndsWith(generatedCshtmlExtension, s_stringComparison)))
if (filePath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) &&
(filePath.EndsWith(generatedRazorExtension, s_stringComparison) || filePath.EndsWith(generatedCshtmlExtension, s_stringComparison)))
{
// Go through the file path normalizer because it also does Uri decoding, and we're converting from a Uri to a path
// but "new Uri(filePath).LocalPath" seems wasteful
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;
using MessagePack.Resolvers;
using MessagePack;
using Microsoft.AspNetCore.Razor.Serialization.MessagePack.Resolvers;
using System.Buffers;
using System.IO;
using System.Threading;

namespace Microsoft.AspNetCore.Razor.Serialization;
internal static class RazorMessagePackSerializer
{
private static readonly MessagePackSerializerOptions s_options = MessagePackSerializerOptions.Standard
.WithResolver(CompositeResolver.Create(
RazorProjectInfoResolver.Instance,
StandardResolver.Instance));

public static byte[] Serialize<T>(T instance)
=> MessagePackSerializer.Serialize(instance, s_options);

public static void SerializeTo<T>(T instance, IBufferWriter<byte> bufferWriter)
=> MessagePackSerializer.Serialize(bufferWriter, instance, s_options);

public static void SerializeTo<T>(T instance, Stream stream)
=> MessagePackSerializer.Serialize(stream, instance, s_options);

public static T? DeserializeFrom<T>(ReadOnlyMemory<byte> buffer)
=> MessagePackSerializer.Deserialize<T>(buffer, s_options);

public static T? DeserializeFrom<T>(Stream stream)
=> MessagePackSerializer.Deserialize<T>(stream, s_options);

public static ValueTask<T> DeserializeFromAsync<T>(Stream stream, CancellationToken cancellationToken)
=> MessagePackSerializer.DeserializeAsync<T>(stream, s_options, cancellationToken);
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public void GeneratedDocument()
.WithFilePath("virtualcsharp-razor:///e:/Scratch/RazorInConsole/Goo.cshtml__virtual.cs")
.Project;

var documents = RazorProjectInfoFactory.GetDocuments(project, "temp");
var documents = RazorProjectInfoHelpers.GetDocuments(project, "temp");

Assert.Single(documents);
}
Expand All @@ -35,7 +35,7 @@ public void AdditionalDocument()

project = workspace.CurrentSolution.GetProject(project.Id)!;

var documents = RazorProjectInfoFactory.GetDocuments(project, "temp");
var documents = RazorProjectInfoHelpers.GetDocuments(project, "temp");

Assert.Single(documents);
}
Expand All @@ -53,7 +53,7 @@ public void AdditionalAndGeneratedDocument()
.WithFilePath("virtualcsharp-razor:///e:/Scratch/RazorInConsole/Another.cshtml__virtual.cs")
.Project;

var documents = RazorProjectInfoFactory.GetDocuments(project, "temp");
var documents = RazorProjectInfoHelpers.GetDocuments(project, "temp");

Assert.Single(documents);
}
Expand All @@ -71,7 +71,7 @@ public void AdditionalNonRazorAndGeneratedDocument()
.WithFilePath("virtualcsharp-razor:///e:/Scratch/RazorInConsole/Another.cshtml__virtual.cs")
.Project;

var documents = RazorProjectInfoFactory.GetDocuments(project, "temp");
var documents = RazorProjectInfoHelpers.GetDocuments(project, "temp");

Assert.Single(documents);
}
Expand All @@ -85,7 +85,7 @@ public void NormalDocument()
.WithFilePath("e:/Scratch/RazorInConsole/Goo.cs")
.Project;

var documents = RazorProjectInfoFactory.GetDocuments(project, "temp");
var documents = RazorProjectInfoHelpers.GetDocuments(project, "temp");

Assert.Empty(documents);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public async Task SerializeProjectInfo()
projectWorkspaceState,
[new DocumentSnapshotHandle(@"C:\test\document.razor", @"document.razor", FileKinds.Component)]);

var bytesToSerialize = projectInfo.Serialize();
var bytesToSerialize = RazorMessagePackSerializer.Serialize(projectInfo);

await stream.WriteProjectInfoAsync(projectInfo, default);

Expand Down