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
1 change: 1 addition & 0 deletions AspNetCore.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -1299,6 +1299,7 @@
<Build Solution="*|Any CPU" Project="false" />
<Build Solution="*|arm64" Project="false" />
</Project>
<Project Path="src/StaticAssets/perf/Microbenchmarks/Microsoft.AspNetCore.StaticAssets.Microbenchmarks.csproj" />
<Project Path="src/StaticAssets/src/Microsoft.AspNetCore.StaticAssets.csproj" />
<Project Path="src/StaticAssets/test/Microsoft.AspNetCore.StaticAssets.Tests.csproj" />
<Project Path="src/Testing/src/Microsoft.AspNetCore.InternalTesting.csproj" />
Expand Down
4 changes: 4 additions & 0 deletions src/StaticAssets/perf/Microbenchmarks/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

[assembly: BenchmarkDotNet.Attributes.AspNetCoreBenchmark]
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
<OutputType>Exe</OutputType>
<ServerGarbageCollection>true</ServerGarbageCollection>
<RootNamespace>Microsoft.AspNetCore.StaticAssets</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="BenchmarkDotNet" />

<PackageReference Include="Microsoft.Extensions.Configuration" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" />
<PackageReference Include="Microsoft.Extensions.Logging" />

<ProjectReference Include="$(RepoRoot)src\Hosting\Abstractions\src\Microsoft.AspNetCore.Hosting.Abstractions.csproj" />
<ProjectReference Include="$(RepoRoot)src\Hosting\Hosting\src\Microsoft.AspNetCore.Hosting.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Headers\src\Microsoft.Net.Http.Headers.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Http.Abstractions\src\Microsoft.AspNetCore.Http.Abstractions.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Http.Extensions\src\Microsoft.AspNetCore.Http.Extensions.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Http.Features\src\Microsoft.AspNetCore.Http.Features.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Http\src\Microsoft.AspNetCore.Http.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Routing.Abstractions\src\Microsoft.AspNetCore.Routing.Abstractions.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Routing\src\Microsoft.AspNetCore.Routing.csproj" />
<ProjectReference Include="$(RepoRoot)src\Middleware\StaticFiles\src\Microsoft.AspNetCore.StaticFiles.csproj" />
<ProjectReference Include="$(RepoRoot)src\StaticAssets\src\Microsoft.AspNetCore.StaticAssets.csproj" />
</ItemGroup>

<ItemGroup>
<Compile Include="$(SharedSourceRoot)BenchmarkRunner\*.cs" />
</ItemGroup>
</Project>
135 changes: 135 additions & 0 deletions src/StaticAssets/perf/Microbenchmarks/StaticAssetsInvokerBenchmark.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using System.Text.Json;
using BenchmarkDotNet.Attributes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace Microsoft.AspNetCore.StaticAssets;

// Invokes the real endpoint produced by MapStaticAssets for a publish (non-build) manifest,
// so no development-time runtime handler is involved.
public class StaticAssetsInvokerBenchmark
{
private const string ETag = "\"Fa0yOlTdLpA5u5+vzI2jL3sZcGbSqTqxWDWdRxRxNTI=\"";

private string _root;
private ServiceProvider _services;
private RequestDelegate _requestDelegate;

[GlobalSetup]
public void Setup()
{
_root = Path.Combine(Path.GetTempPath(), "StaticAssetsInvokerBenchmark", Guid.NewGuid().ToString("N"));
var webRoot = Path.Combine(_root, "wwwroot");
Directory.CreateDirectory(webRoot);
File.WriteAllText(Path.Combine(webRoot, "site.css"), new string('a', 1024));

var manifestPath = Path.Combine(_root, "app.staticwebassets.endpoints.json");
File.WriteAllText(manifestPath, JsonSerializer.Serialize(new
{
Version = 1,
ManifestType = "Publish",
Endpoints = new[]
{
new StaticAssetDescriptor
{
Route = "site.css",
AssetPath = "site.css",
Selectors = [],
Properties = [],
ResponseHeaders =
[
new("Accept-Ranges", "bytes"),
new("Cache-Control", "max-age=31536000, immutable"),
new("Content-Length", "1024"),
new("Content-Type", "text/css"),
new("ETag", ETag),
new("Last-Modified", new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture)),
],
},
},
}));

var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance);
services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>));
services.AddSingleton<IWebHostEnvironment>(new BenchmarkWebHostEnvironment(_root, webRoot));
services.AddRouting();
_services = services.BuildServiceProvider();

var endpoints = new BenchmarkEndpointRouteBuilder(_services);
endpoints.MapStaticAssets(manifestPath);

var endpoint = endpoints.DataSources.SelectMany(d => d.Endpoints).OfType<RouteEndpoint>().Single();
_requestDelegate = endpoint.RequestDelegate;

if (Head200().GetAwaiter().GetResult() != StatusCodes.Status200OK ||
GetIfNoneMatch304().GetAwaiter().GetResult() != StatusCodes.Status304NotModified)
{
throw new InvalidOperationException("The benchmark requests did not produce the expected status codes.");
}
}

[GlobalCleanup]
public void Cleanup()
{
_services.Dispose();
Directory.Delete(_root, recursive: true);
}

[Benchmark]
public async Task<int> Head200()
{
var context = CreateContext(HttpMethods.Head);
await _requestDelegate(context);
return context.Response.StatusCode;
}

[Benchmark]
public async Task<int> GetIfNoneMatch304()
{
var context = CreateContext(HttpMethods.Get);
context.Request.Headers.IfNoneMatch = ETag;
await _requestDelegate(context);
return context.Response.StatusCode;
}

private DefaultHttpContext CreateContext(string method)
{
var context = new DefaultHttpContext { RequestServices = _services };
context.Request.Method = method;
context.Request.Path = "/site.css";
context.Response.Body = Stream.Null;
return context;
}

private sealed class BenchmarkEndpointRouteBuilder(IServiceProvider serviceProvider) : IEndpointRouteBuilder
{
public IServiceProvider ServiceProvider { get; } = serviceProvider;

public ICollection<EndpointDataSource> DataSources { get; } = new List<EndpointDataSource>();

public IApplicationBuilder CreateApplicationBuilder() => new ApplicationBuilder(ServiceProvider);
}

private sealed class BenchmarkWebHostEnvironment(string contentRoot, string webRoot) : IWebHostEnvironment
{
public string ApplicationName { get; set; } = "app";
public string EnvironmentName { get; set; } = "Production";
public string ContentRootPath { get; set; } = contentRoot;
public IFileProvider ContentRootFileProvider { get; set; } = new PhysicalFileProvider(contentRoot);
public string WebRootPath { get; set; } = webRoot;
public IFileProvider WebRootFileProvider { get; set; } = new PhysicalFileProvider(webRoot);
}
}
33 changes: 26 additions & 7 deletions src/StaticAssets/src/StaticAssetsInvoker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ internal class StaticAssetsInvoker
private readonly DateTimeOffset _lastModified;
private readonly List<StaticAssetResponseHeader> _remainingHeaders;

// The ETag and Last-Modified values are fixed for a given asset, so format them once.
private readonly string _etagHeaderValue;
private readonly string _lastModifiedHeaderValue;

private IFileInfo? _fileInfo;

public StaticAssetsInvoker(StaticAssetDescriptor resource, IFileProvider fileProvider, ILogger<StaticAssetsInvoker> logger)
Expand Down Expand Up @@ -75,6 +79,9 @@ public StaticAssetsInvoker(StaticAssetDescriptor resource, IFileProvider filePro
{
throw new InvalidOperationException("The ETag header is required.");
}

_etagHeaderValue = _etag.ToString();
_lastModifiedHeaderValue = HeaderUtilities.FormatDate(_lastModified);
}

public string Route => _resource.Route;
Expand All @@ -97,12 +104,12 @@ private Task ApplyResponseHeadersAsync(StaticAssetInvocationContext context, int
context.Response.ContentType = _contentType;
}

var responseHeaders = context.ResponseHeaders;
responseHeaders.LastModified = _lastModified;
responseHeaders.ETag = _etag;
responseHeaders.Headers.AcceptRanges = "bytes";
var responseHeaders = context.Response.Headers;
responseHeaders.LastModified = _lastModifiedHeaderValue;
responseHeaders.ETag = _etagHeaderValue;
responseHeaders.AcceptRanges = "bytes";

foreach (var header in _remainingHeaders ?? [])
foreach (var header in _remainingHeaders)
{
responseHeaders.Append(header.Name, header.Value);
}
Expand All @@ -129,6 +136,7 @@ public async Task Invoke(HttpContext context)
var requestContext = new StaticAssetInvocationContext(
context,
_etag,
_etagHeaderValue,
_lastModified,
_length,
_logger);
Expand Down Expand Up @@ -254,6 +262,7 @@ private readonly struct StaticAssetInvocationContext
private readonly HttpContext _context = null!;
private readonly HttpRequest _request = null!;
private readonly EntityTagHeaderValue _etag;
private readonly string _etagHeaderValue;
private readonly DateTimeOffset _lastModified;
private readonly long _length;
private readonly ILogger _logger;
Expand All @@ -262,24 +271,26 @@ private readonly struct StaticAssetInvocationContext
public StaticAssetInvocationContext(
HttpContext context,
EntityTagHeaderValue entityTag,
string etagHeaderValue,
DateTimeOffset lastModified,
long length,
ILogger logger)
{
_context = context;
_request = context.Request;
ResponseHeaders = context.Response.GetTypedHeaders();
_requestHeaders = _request.GetTypedHeaders();
Response = context.Response;
_etag = entityTag;
_etagHeaderValue = etagHeaderValue;
_lastModified = lastModified;
_length = length;
_logger = logger;
}

public CancellationToken CancellationToken => _context.RequestAborted;

public ResponseHeaders ResponseHeaders { get; }
// Only needed when sending Content-Range, so avoid allocating it for every request.
public ResponseHeaders ResponseHeaders => Response.GetTypedHeaders();

public HttpResponse Response { get; }

Expand Down Expand Up @@ -317,6 +328,14 @@ public StaticAssetInvocationContext(

// 14.26 If-None-Match
var ifNoneMatchResult = PreconditionState.Unspecified;

// Fast path for the common revalidation request that echoes back the exact ETag we sent.
var rawIfNoneMatch = _request.Headers.IfNoneMatch;
if (rawIfNoneMatch.Count == 1 && string.Equals(rawIfNoneMatch[0], _etagHeaderValue, StringComparison.Ordinal))
{
return (ifMatchResult, PreconditionState.NotModified);
}

var ifNoneMatch = requestHeaders.IfNoneMatch;
if (ifNoneMatch?.Count > 0)
{
Expand Down
75 changes: 75 additions & 0 deletions src/StaticAssets/test/StaticAssetsIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,81 @@ public async Task RangeGivesMatchingRange()
Assert.Equal(5, res2.Content.Headers.ContentLength);
}

[Fact]
public async Task ResponseHeadersAreConsistentAcrossStatusCodes()
{
var client = await CreateClient();
var expectedETag = $"\"{GetEtag("Hello, World!")}\"";
const string expectedLastModified = "Fri, 03 Mar 2023 00:00:00 GMT";

var get = await client.GetAsync("http://localhost/sample.txt");
AssertHeaders(get, HttpStatusCode.OK);

var head = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, "http://localhost/sample.txt"));
AssertHeaders(head, HttpStatusCode.OK);

var notModifiedRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/sample.txt");
notModifiedRequest.Headers.TryAddWithoutValidation("If-None-Match", expectedETag);
var notModified = await client.SendAsync(notModifiedRequest);
AssertHeaders(notModified, HttpStatusCode.NotModified);

var rangeRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/sample.txt");
rangeRequest.Headers.Range = new RangeHeaderValue(0, 4);
var range = await client.SendAsync(rangeRequest);
AssertHeaders(range, HttpStatusCode.PartialContent);
Assert.Equal("bytes 0-4/13", Assert.Single(range.Content.Headers.GetValues("Content-Range")));

var unsatisfiableRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/sample.txt");
unsatisfiableRequest.Headers.Range = new RangeHeaderValue(100, 200);
var unsatisfiable = await client.SendAsync(unsatisfiableRequest);
Assert.Equal(HttpStatusCode.RequestedRangeNotSatisfiable, unsatisfiable.StatusCode);
Assert.Equal("bytes */13", Assert.Single(unsatisfiable.Content.Headers.GetValues("Content-Range")));
Assert.False(unsatisfiable.Headers.Contains("ETag"));
Assert.False(unsatisfiable.Content.Headers.Contains("Last-Modified"));

void AssertHeaders(HttpResponseMessage response, HttpStatusCode statusCode)
{
Assert.Equal(statusCode, response.StatusCode);
Assert.Equal(expectedETag, Assert.Single(response.Headers.GetValues("ETag")));
Assert.Equal(expectedLastModified, Assert.Single(response.Content.Headers.GetValues("Last-Modified")));
Assert.Contains("bytes", response.Headers.AcceptRanges);
}
}

[Theory]
[InlineData("{0}", HttpStatusCode.NotModified)]
[InlineData("W/{0}", HttpStatusCode.NotModified)]
[InlineData(" {0} ", HttpStatusCode.NotModified)]
[InlineData("\"other\", {0}", HttpStatusCode.NotModified)]
[InlineData("\"other\"", HttpStatusCode.OK)]
[InlineData("W/\"other\"", HttpStatusCode.OK)]
public async Task IfNoneMatchVariantsAreEvaluated(string ifNoneMatchFormat, HttpStatusCode expectedStatusCode)
{
var client = await CreateClient();
var etag = $"\"{GetEtag("Hello, World!")}\"";

var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/sample.txt");
request.Headers.TryAddWithoutValidation("If-None-Match", string.Format(CultureInfo.InvariantCulture, ifNoneMatchFormat, etag));
var response = await client.SendAsync(request);

Assert.Equal(expectedStatusCode, response.StatusCode);
Assert.Equal(etag, Assert.Single(response.Headers.GetValues("ETag")));
}

[Fact]
public async Task IfMatchFailureTakesPrecedenceOverMatchingIfNoneMatch()
{
var client = await CreateClient();
var etag = $"\"{GetEtag("Hello, World!")}\"";

var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/sample.txt");
request.Headers.TryAddWithoutValidation("If-None-Match", etag);
request.Headers.TryAddWithoutValidation("If-Match", "\"other\"");
var response = await client.SendAsync(request);

Assert.Equal(HttpStatusCode.PreconditionFailed, response.StatusCode);
}

public static IEnumerable<object[]> SupportedMethods => new[]
{
new [] { HttpMethod.Get },
Expand Down
Loading