Repository navigation
Serve the site with a per-request file middleware instead of MapStaticAssets #2178
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
Merged
David Pine (IEvangelist)
merged 7 commits into
main
from
sebros/optimistic-babbage-j11aeu
Nov 20, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
470c179
Serve the site with a per-request file middleware instead of MapStati…
sebastienros d4efc16
Compress the site with a file-based app and tighten file preconditions
sebastienros 12329a6
Hash ETags with XxHash128 and explain the brotli lookup and key casing
sebastienros 5e666f1
Key cached ETags by physical path so the cache stays bounded
sebastienros 59afd58
Answer 405 for methods other than GET and HEAD on a file
sebastienros 8a78812
Merge origin/main into sebros/optimistic-babbage-j11aeu
IEvangelist e3a365c
Address review: HEAD ranges, encoding negotiation, ETag and brotli reuse
IEvangelist File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| <Project> | ||
| <!-- | ||
| Publishes the site (src/frontend/dist) to wwwroot with a brotli copy of each text file. | ||
|
|
||
| StaticHost serves the web root with SiteFileMiddleware, not MapStaticAssets, so the project | ||
| turns static web assets off (StaticWebAssetsEnabled). That pipeline hashed every file, wrote a | ||
| manifest of every URL, and made each instance load it at startup, which costs a lot with | ||
| about 70,000 files. What it did that the site needs is here: run the frontend build, copy its | ||
| output, and compress it once at publish. Caching and ETags are decided per request. | ||
|
|
||
| Asking frontend.esproj for JavaScriptOutputGroup runs its BuildCommand and returns dist's | ||
| files, as the static web assets pipeline did. The brotli copies are written by a file-based | ||
| app (../compress-site.cs), which reuses the copies of files that did not change. | ||
| --> | ||
| <PropertyGroup> | ||
| <!-- The text types the SDK compressed (Microsoft.NET.Sdk.StaticWebAssets.Compression.targets). --> | ||
| <SiteCompressedExtensions>.html;.htm;.md;.markdown;.txt;.xml;.json;.webmanifest;.js;.mjs;.jsx;.css;.map;.svg;.ico;.bmp;.otf;.wasm;.csv;.tsv;.ics;.xsl;.xslt</SiteCompressedExtensions> | ||
| <SiteCompressApp>$(MSBuildThisFileDirectory)../compress-site.cs</SiteCompressApp> | ||
| <!-- The dotnet that runs this build, so the app uses the same SDK; plain dotnet under msbuild.exe. --> | ||
| <SiteDotnet>$(DOTNET_HOST_PATH)</SiteDotnet> | ||
| <SiteDotnet Condition="'$(SiteDotnet)' == ''">dotnet</SiteDotnet> | ||
| </PropertyGroup> | ||
|
|
||
| <Target Name="AddSiteToPublish" AfterTargets="ComputeResolvedFilesToPublishList"> | ||
| <PropertyGroup> | ||
| <!-- Set here: IntermediateOutputPath is not defined yet when this file's properties are. --> | ||
| <_SiteIntermediateDirectory>$(MSBuildProjectDirectory)/$(IntermediateOutputPath)</_SiteIntermediateDirectory> | ||
| <_SiteCompressedDirectory>$(_SiteIntermediateDirectory)site-br/</_SiteCompressedDirectory> | ||
| <_SiteFileList>$(_SiteIntermediateDirectory)site-files.txt</_SiteFileList> | ||
| <_SiteBrotliList>$(_SiteIntermediateDirectory)site-br.txt</_SiteBrotliList> | ||
| </PropertyGroup> | ||
|
|
||
| <MSBuild Projects="@(ProjectReference->WithMetadataValue('Filename', 'frontend'))" Targets="JavaScriptOutputGroup"> | ||
| <Output TaskParameter="TargetOutputs" ItemName="_SiteFile" /> | ||
| </MSBuild> | ||
|
|
||
| <!-- The app reads each file's full path and its path in the site, separated by a tab. --> | ||
| <WriteLinesToFile File="$(_SiteFileList)" Lines="@(_SiteFile->'%(FullPath)%09%(TemplateSubPath)%(Filename)%(Extension)')" Overwrite="true" WriteOnlyWhenDifferent="true" /> | ||
| <Exec Command=""$(SiteDotnet)" run --file "$(SiteCompressApp)" -- "$(_SiteFileList)" "$(_SiteCompressedDirectory)" "$(SiteCompressedExtensions)" "$(_SiteBrotliList)"" | ||
| StandardOutputImportance="high" /> | ||
| <ReadLinesFromFile File="$(_SiteBrotliList)"> | ||
| <Output TaskParameter="Lines" ItemName="_SiteBrotliFile" /> | ||
| </ReadLinesFromFile> | ||
|
|
||
| <ItemGroup> | ||
| <ResolvedFileToPublish Include="@(_SiteFile)" | ||
| RelativePath="wwwroot/%(_SiteFile.TemplateSubPath)%(_SiteFile.Filename)%(_SiteFile.Extension)" | ||
| CopyToPublishDirectory="PreserveNewest" | ||
| ExcludeFromSingleFile="true" /> | ||
| <ResolvedFileToPublish Include="@(_SiteBrotliFile->'$(_SiteCompressedDirectory)%(Identity)')" | ||
| RelativePath="wwwroot/%(_SiteBrotliFile.Identity)" | ||
| CopyToPublishDirectory="PreserveNewest" | ||
| ExcludeFromSingleFile="true" /> | ||
| </ItemGroup> | ||
| </Target> | ||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| using System.Buffers; | ||
| using System.Collections.Concurrent; | ||
| using System.IO.Hashing; | ||
| using Microsoft.Extensions.FileProviders; | ||
|
|
||
| namespace StaticHost.SiteFiles; | ||
|
|
||
| /// <summary> | ||
| /// Computes a file's ETag from a hash of its content the first time it is served, then keeps it | ||
| /// in memory. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// The hash is XxHash128: an ETag only has to tell versions of a file apart, which needs no | ||
| /// cryptographic hash. A content hash, unlike the length and last-modified time | ||
| /// <c>UseStaticFiles</c> uses, stays the same across deployments for files that did not change, | ||
| /// though CI writes every file again. An entry is recomputed when the file's length or | ||
| /// last-modified time changes, which covers a web root that is replaced while StaticHost runs | ||
| /// (CI unpacks the site after StaticHost starts). | ||
| /// </para> | ||
| /// <para> | ||
| /// Length and time do not identify the bytes, though: a restore can replace a file with one of | ||
| /// the same length and time. A cached ETag is therefore only used where a stale one is harmless, | ||
| /// on a response that sends the file. A request with a precondition, which a stale ETag could | ||
| /// answer with a 304 for bytes the client does not have, hashes the file again | ||
| /// (<c>revalidate</c>). Watching the web root for changes would cost an inotify watch per | ||
| /// directory on Linux, and .NET does not expose the inode or change time that would tell a | ||
| /// replaced file apart. | ||
| /// </para> | ||
| /// </remarks> | ||
| internal sealed class SiteFileETags | ||
| { | ||
| private const int BufferSize = 64 * 1024; | ||
|
|
||
| // Keyed by the file's physical path, which the provider normalizes: the request paths | ||
| // /a/b.json, /a//b.json and /a///b.json are one file, so they share one entry, and the | ||
| // dictionary holds at most one entry per file of the web root. Request paths would let any | ||
| // client add entries without bound, each one costing a hash of the file. | ||
| // Ordinal, as the file system is in production (Linux): two paths that differ only by case are | ||
| // two files there, and must not share an entry. On a case-insensitive disk they are one file | ||
| // under two keys, which costs one more hash. Canonical redirects send most requests to one casing. | ||
| private readonly ConcurrentDictionary<string, Entry> _entries = new(StringComparer.Ordinal); | ||
|
|
||
| internal int Count => _entries.Count; | ||
|
|
||
| /// <param name="path"> | ||
| /// The file's path in the web root, the key when the provider gives no physical path. | ||
| /// </param> | ||
| /// <param name="file">The file to hash.</param> | ||
| /// <param name="revalidate">Hash the file even when an entry matches its length and time.</param> | ||
| /// <param name="cancellationToken">Cancels the hashing.</param> | ||
| public async ValueTask<string> GetAsync(string path, IFileInfo file, bool revalidate, CancellationToken cancellationToken) | ||
| { | ||
| var key = file.PhysicalPath ?? path; | ||
| var length = file.Length; | ||
| var lastModified = file.LastModified; | ||
|
|
||
| if (!revalidate | ||
| && _entries.TryGetValue(key, out var entry) | ||
| && entry.Length == length | ||
| && entry.LastModified == lastModified) | ||
| { | ||
| return entry.ETag; | ||
| } | ||
|
|
||
| // Two first requests for the same file may both hash it; the result is the same. That is | ||
| // not worth coordinating: it happens once per file per instance, and sending the file | ||
| // reads it anyway. | ||
| var hash = new XxHash128(); | ||
| var buffer = ArrayPool<byte>.Shared.Rent(BufferSize); | ||
| try | ||
| { | ||
| await using var stream = file.CreateReadStream(); | ||
| int read; | ||
| while ((read = await stream.ReadAsync(buffer, cancellationToken)) > 0) | ||
| { | ||
| hash.Append(buffer.AsSpan(0, read)); | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| ArrayPool<byte>.Shared.Return(buffer); | ||
| } | ||
|
|
||
| var etag = $"\"{Convert.ToBase64String(hash.GetCurrentHash())}\""; | ||
| _entries[key] = new Entry(length, lastModified, etag); | ||
| return etag; | ||
| } | ||
|
|
||
| private sealed record Entry(long Length, DateTimeOffset LastModified, string ETag); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| namespace StaticHost.SiteFiles; | ||
|
|
||
| internal static class SiteFileExtensions | ||
| { | ||
| public static IServiceCollection AddSiteFiles(this IServiceCollection services) => | ||
| services.AddSingleton<SiteFileETags>(); | ||
|
|
||
| /// <summary> | ||
| /// Serves the web root's files, preferring the precompressed brotli copy. Call it after | ||
| /// <c>UseRouting</c>: it leaves requests that matched an endpoint to that endpoint. | ||
| /// </summary> | ||
| public static IApplicationBuilder UseSiteFiles(this IApplicationBuilder app) => | ||
| app.UseMiddleware<SiteFileMiddleware>(); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.