Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions src/aspnetcore/AspNetCore.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@
<Folder Name="/src/Components/CustomElements/">
<Project Path="src/Components/CustomElements/src/Microsoft.AspNetCore.Components.CustomElements.csproj" />
</Folder>
<Folder Name="/src/Components/Gateway/">
<Project Path="src/Components/Gateway/src/Microsoft.AspNetCore.Components.Gateway.csproj" />
<Project Path="src/Components/Gateway/cli/Microsoft.AspNetCore.Components.Gateway.Cli.csproj" />
<Project Path="src/Components/Gateway/test/Microsoft.AspNetCore.Components.Gateway.Tests.csproj" />
</Folder>
<Folder Name="/src/Components/Media/">
<Project Path="src/Components/Media/src/Microsoft.AspNetCore.Components.Media.csproj" />
<Project Path="src/Components/Media/test/Microsoft.AspNetCore.Components.Media.Tests.csproj" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<DotNetCliTool Version="1">
<Commands>
<Command Name="blazor-gateway" EntryPoint="blazor-gateway.dll" Runner="dotnet" />
</Commands>
</DotNetCliTool>
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
<PackageId>Microsoft.AspNetCore.Components.Gateway.Cli</PackageId>
<IsShippingPackage>true</IsShippingPackage>
<IsPackable>true</IsPackable>
<Description>Command line tool (blazor-gateway) for hosting Blazor applications.</Description>
<PackageTags>blazor;gateway;dotnettool</PackageTags>
<!-- This project only repackages the gateway binaries as a dotnet tool; it has no code of its own. -->
<IncludeBuildOutput>false</IncludeBuildOutput>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<IsProjectReferenceProvider>false</IsProjectReferenceProvider>
<AddPublicApiAnalyzers>false</AddPublicApiAnalyzers>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Nullable>enable</Nullable>
<NuspecFile>Microsoft.AspNetCore.Components.Gateway.Cli.nuspec</NuspecFile>
</PropertyGroup>

<PropertyGroup>
<_GatewayProject>$(MSBuildThisFileDirectory)..\src\Microsoft.AspNetCore.Components.Gateway.csproj</_GatewayProject>
<!-- Arcade lays projects out under artifacts/bin/<ProjectName>/<Configuration>/<TargetFramework>/.
The gateway publishes into the "publish" subfolder of that output directory. -->
<_GatewayOutputDir>$(ArtifactsBinDir)Microsoft.AspNetCore.Components.Gateway\$(Configuration)\$(DefaultNetCoreTargetFramework)\</_GatewayOutputDir>
<_GatewayPublishDir>$(_GatewayOutputDir)publish\</_GatewayPublishDir>
<_DotnetToolSettings>$(MSBuildThisFileDirectory)DotnetToolSettings.xml</_DotnetToolSettings>
</PropertyGroup>

<!-- Reference the gateway project purely to establish restore and build ordering. Its output
assembly is not referenced; the binaries are consumed from the published output below. -->
<ItemGroup>
<ProjectReference Include="$(_GatewayProject)"
ReferenceOutputAssembly="false"
SkipGetTargetFrameworkProperties="true"
Private="false"
PrivateAssets="All" />
</ItemGroup>

<!-- Build and publish the gateway before packing so its binaries are available to the nuspec. -->
<Target Name="_PublishGatewayForTool" BeforeTargets="GenerateNuspec">
<MSBuild Projects="$(_GatewayProject)"
Targets="Publish"
Properties="Configuration=$(Configuration);TargetFramework=$(DefaultNetCoreTargetFramework)" />

<Error Condition="!Exists('$(_GatewayPublishDir)blazor-gateway.dll')"
Text="Expected the gateway to publish 'blazor-gateway.dll' to '$(_GatewayPublishDir)' but it was not found." />
<Error Condition="!Exists('$(_GatewayOutputDir)blazor-gateway.runtimeconfig.json')"
Text="Expected the gateway build to produce 'blazor-gateway.runtimeconfig.json' in '$(_GatewayOutputDir)' but it was not found." />
</Target>

<ItemGroup>
<NuspecProperty Include="publishDir=$(_GatewayPublishDir)" />
<NuspecProperty Include="binDir=$(_GatewayOutputDir)" />
<NuspecProperty Include="toolTfm=$(DefaultNetCoreTargetFramework)" />
<NuspecProperty Include="dotnetToolSettings=$(_DotnetToolSettings)" />
<NuspecProperty Include="PackageThirdPartyNoticesFile=$(PackageThirdPartyNoticesFile)" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
<metadata>
$CommonMetadataElements$
<packageTypes>
<packageType name="DotnetTool" />
</packageTypes>
</metadata>
<files>
$CommonFileElements$
<!-- Reuse the exact binaries produced by the Microsoft.AspNetCore.Components.Gateway
package by packing the gateway's publish output into the dotnet tool layout. -->
<file src="$publishDir$**\*" target="tools\$toolTfm$\any" />
<!-- The gateway disables GenerateRuntimeConfigurationFiles and emits its runtimeconfig
(with the correct shared framework version) into the build output directory, so it is
copied in explicitly rather than picked up from the publish directory. -->
<file src="$binDir$blazor-gateway.runtimeconfig.json" target="tools\$toolTfm$\any\blazor-gateway.runtimeconfig.json" />
<!-- The tool manifest that maps the "blazor-gateway" command to blazor-gateway.dll. -->
<file src="$dotnetToolSettings$" target="tools\$toolTfm$\any\DotnetToolSettings.xml" />
<file src="$PackageThirdPartyNoticesFile$" target=".\THIRD-PARTY-NOTICES.txt" />
</files>
</package>
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<!-- Microsoft.NET.Sdk.Web defaults IsPackable to false. Override it so the
<NuspecFile> below is honored and the shipping package is produced. -->
<IsPackable>true</IsPackable>
<Description>Gateway server for hosting standalone Blazor WebAssembly applications.</Description>
<Description>Gateway server for hosting Blazor applications.</Description>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<!-- Assemblies should not reference this assembly directly -->
<IsProjectReferenceProvider>false</IsProjectReferenceProvider>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Xml.Linq;
using Microsoft.AspNetCore.InternalTesting;

namespace Microsoft.AspNetCore.Components.Gateway;

/// <summary>
/// Installs the built <c>Microsoft.AspNetCore.Components.Gateway.Cli</c> package as a dotnet tool and
/// asserts it is a well-formed tool that repackages the gateway binaries under the
/// <c>blazor-gateway</c> command. These tests install into a throwaway tool-path rather than reading
/// the .nupkg directly, so they exercise the same acquisition path as a real consumer.
/// </summary>
[RequiresBuiltGatewayCliPackage]
public class BlazorGatewayCliPackageTests
{
private static string ToolDir => $"tools/{GatewayCliTestData.DefaultTargetFramework}/any";

[ConditionalFact]
public void Package_IsMarkedAsDotnetTool()
{
using var tool = GatewayToolInstallation.Install();

var nuspec = XDocument.Parse(tool.ReadNuspec());
var ns = nuspec.Root!.Name.Namespace;

var packageTypes = nuspec.Root
.Element(ns + "metadata")?
.Element(ns + "packageTypes")?
.Elements(ns + "packageType")
.Select(e => e.Attribute("name")?.Value)
.ToArray() ?? [];

Assert.Contains("DotnetTool", packageTypes);
}

[ConditionalFact]
public void Package_ContainsDotnetToolSettings_ForBlazorGatewayCommand()
{
using var tool = GatewayToolInstallation.Install();

Assert.True(
tool.HasFile($"{ToolDir}/DotnetToolSettings.xml"),
$"Expected DotnetToolSettings.xml under {ToolDir}.");

var settings = XDocument.Parse(tool.ReadFile($"{ToolDir}/DotnetToolSettings.xml"));
var command = settings.Descendants("Command").Single();

Assert.Equal(GatewayCliTestData.ToolCommandName, command.Attribute("Name")?.Value);
Assert.Equal("blazor-gateway.dll", command.Attribute("EntryPoint")?.Value);
Assert.Equal("dotnet", command.Attribute("Runner")?.Value);
}

[ConditionalFact]
public void Package_ContainsGatewayBinariesAndRuntimeConfig()
{
using var tool = GatewayToolInstallation.Install();

// The entry point plus the framework-dependent app files that make it runnable.
Assert.True(tool.HasFile($"{ToolDir}/blazor-gateway.dll"), "Missing blazor-gateway.dll.");
Assert.True(tool.HasFile($"{ToolDir}/blazor-gateway.deps.json"), "Missing blazor-gateway.deps.json.");
Assert.True(
tool.HasFile($"{ToolDir}/blazor-gateway.runtimeconfig.json"),
"Missing blazor-gateway.runtimeconfig.json (the gateway emits it into the build output; the tool package must copy it in).");
}

[ConditionalFact]
public void Package_RuntimeConfig_TargetsAspNetCoreSharedFramework()
{
using var tool = GatewayToolInstallation.Install();

var runtimeConfig = tool.ReadFile($"{ToolDir}/blazor-gateway.runtimeconfig.json");

// The gateway is a framework-dependent app; the tool must roll forward onto the installed
// Microsoft.AspNetCore.App shared framework rather than carrying its own runtime.
Assert.Contains("Microsoft.AspNetCore.App", runtimeConfig, StringComparison.Ordinal);
}

[ConditionalFact]
public void Package_IncludesBundledDependencies()
{
using var tool = GatewayToolInstallation.Install();

// The gateway depends on YARP for reverse proxying; it must travel inside the tool package
// because a dotnet tool cannot pull additional package references at run time.
Assert.True(tool.HasFile($"{ToolDir}/Yarp.ReverseProxy.dll"), "Missing bundled Yarp.ReverseProxy.dll.");
}

[ConditionalFact]
public void Package_IncludesThirdPartyNotices()
{
using var tool = GatewayToolInstallation.Install();

Assert.True(tool.HasFile("THIRD-PARTY-NOTICES.txt"), "Missing THIRD-PARTY-NOTICES.txt.");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Net;
using System.Net.Http;
using Microsoft.AspNetCore.InternalTesting;

namespace Microsoft.AspNetCore.Components.Gateway;

/// <summary>
/// End-to-end validation that the <c>Microsoft.AspNetCore.Components.Gateway.Cli</c> package can be
/// installed as a dotnet tool and that the resulting <c>blazor-gateway</c> command runs and serves
/// requests. These tests install the locally-built package into a throwaway tool-path and launch the
/// real gateway process, so they only run where the package has been packed (and not on Helix).
/// </summary>
[RequiresBuiltGatewayCliPackage]
public class BlazorGatewayCliToolTests
{
[ConditionalFact]
public void Tool_Installs_AndExposesBlazorGatewayCommand()
{
using var tool = GatewayToolInstallation.Install();

Assert.True(
File.Exists(tool.CommandPath),
$"Expected the installed tool to expose the '{GatewayCliTestData.ToolCommandName}' command at '{tool.CommandPath}'.");
}

[ConditionalFact]
public async Task Tool_Runs_AndAnswersLivenessProbe()
{
using var tool = GatewayToolInstallation.Install();

await using var running = await tool.StartAsync("--environment", "Development");

// The liveness endpoint is mapped in every environment, so a 200 here proves the installed
// tool launched the real gateway and is serving requests.
var alive = await running.Client.GetAsync("/alive");
Assert.Equal(HttpStatusCode.OK, alive.StatusCode);

// The aggregate health endpoint is only mapped in Development.
var health = await running.Client.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, health.StatusCode);
}

[ConditionalFact]
public async Task Tool_HostsConfiguredClientApp_AndServesItsConfiguration()
{
const string configJson = """{"webAssembly":{"environment":{"OTEL_SERVICE_NAME":"my-app"}}}""";

using var tool = GatewayToolInstallation.Install();

// Drive the gateway exactly the way Aspire's Blazor integration does: pass a client app's
// configuration on the command line and confirm the running tool serves it back.
await using var running = await tool.StartAsync(
"--environment", "Development",
"--ClientApps:app:ConfigEndpointPath", "/myapp/_blazor/_configuration",
"--ClientApps:app:ConfigResponse", $"\"{configJson.Replace("\"", "\\\"")}\"");

var request = new HttpRequestMessage(HttpMethod.Get, "/myapp/_blazor/_configuration");
request.Headers.AcceptEncoding.ParseAdd("identity");

var response = await running.Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();

Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
Assert.Equal(configJson, body, ignoreLineEndingDifferences: true);
}
}
89 changes: 89 additions & 0 deletions src/aspnetcore/src/Components/Gateway/test/GatewayCliTestData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Reflection;

namespace Microsoft.AspNetCore.Components.Gateway;

/// <summary>
/// Resolves test-time configuration (package locations, version, repo paths) injected as assembly
/// metadata by the test project's csproj. Used by the tests that validate the
/// <c>Microsoft.AspNetCore.Components.Gateway.Cli</c> dotnet tool package.
/// </summary>
internal static class GatewayCliTestData
{
/// <summary>
/// The id of the dotnet tool package that repackages the gateway binaries.
/// </summary>
public const string PackageId = "Microsoft.AspNetCore.Components.Gateway.Cli";

/// <summary>
/// The command the tool exposes once installed (matches the assembly name of the gateway).
/// </summary>
public const string ToolCommandName = "blazor-gateway";

private static readonly Dictionary<string, string> Metadata = typeof(GatewayCliTestData).Assembly
.GetCustomAttributes<AssemblyMetadataAttribute>()
.Where(a => a.Value is not null)
.GroupBy(a => a.Key, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.Last().Value!, StringComparer.Ordinal);

public static string PackageVersion => GetValue("GatewayCliPackageVersion");

public static string ShippingPackagesDir => GetValue("ArtifactsShippingPackagesDir");

public static string NonShippingPackagesDir => GetValue("ArtifactsNonShippingPackagesDir");

public static string RepoRoot => GetValue("RepoRoot");

public static string ArtifactsTmpDir => GetValue("ArtifactsTmpDir");

public static string DefaultTargetFramework => GetValue("DefaultNetCoreTargetFramework");

/// <summary>
/// Path to the locally-built SDK host (.dotnet/dotnet[.exe]) used to install and run the tool.
/// </summary>
public static string DotNetHost
{
get
{
var fileName = OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet";
return Path.Combine(RepoRoot, ".dotnet", fileName);
}
}

/// <summary>
/// The directory containing the shared framework (.dotnet), used as DOTNET_ROOT when running the
/// installed tool so the framework-dependent gateway can resolve Microsoft.AspNetCore.App.
/// </summary>
public static string DotNetRoot => Path.Combine(RepoRoot, ".dotnet");

/// <summary>
/// Locates the .nupkg for the given package id (looking in the shipping and non-shipping package
/// output folders). Returns <see langword="null"/> when the package was not built.
/// </summary>
public static string? TryGetPackagePath(string packageId)
{
var fileName = $"{packageId}.{PackageVersion}.nupkg";
foreach (var dir in new[] { ShippingPackagesDir, NonShippingPackagesDir })
{
if (string.IsNullOrEmpty(dir))
{
continue;
}

var candidate = Path.Combine(dir, fileName);
if (File.Exists(candidate))
{
return candidate;
}
}

return null;
}

private static string GetValue(string key)
=> Metadata.TryGetValue(key, out var value)
? value
: throw new InvalidOperationException($"Missing assembly metadata '{key}'. Ensure the test project injects it.");
}
Loading
Loading