U6: IndexHtmlInjector (markers OFFERINGS-JSON-LD / OFFERINGS-HTML), 60s cache, invalidatie bij wijziging, ETag
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -148,6 +148,32 @@ public static class StaticContentExtensions
|
||||
}
|
||||
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
|
||||
// Modules fill marker comments in index.html (e.g. the current offerings); cached, with an ETag.
|
||||
var injector = context.RequestServices.GetService<IndexHtmlInjector>();
|
||||
var page = injector is null
|
||||
? null
|
||||
: await injector.GetAsync(websiteIndex, context.Request, context.RequestAborted);
|
||||
if (page is not null)
|
||||
{
|
||||
context.Response.Headers["Cache-Control"] = "no-cache";
|
||||
context.Response.Headers["ETag"] = page.ETag;
|
||||
if (context.Response.StatusCode == StatusCodes.Status200OK
|
||||
&& context.Request.Headers.IfNoneMatch.Contains(page.ETag))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status304NotModified;
|
||||
return;
|
||||
}
|
||||
|
||||
context.Response.ContentLength = page.Body.Length;
|
||||
if (!HttpMethods.IsHead(context.Request.Method))
|
||||
{
|
||||
await context.Response.Body.WriteAsync(page.Body, context.RequestAborted);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await context.Response.SendFileAsync(websiteIndex);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Website;
|
||||
|
||||
/// <summary>
|
||||
/// A module's contribution to the website's <c>index.html</c>: replacement text for marker comments such as
|
||||
/// <c><!--SLP:OFFERINGS-HTML--></c>. The key is the marker name without the comment delimiters
|
||||
/// (<c>SLP:OFFERINGS-HTML</c>); the value is the HTML that replaces the whole comment (empty = remove it).
|
||||
/// </summary>
|
||||
public interface IIndexHtmlMarkerProvider
|
||||
{
|
||||
Task<IReadOnlyDictionary<string, string>> RenderAsync(string publicBaseUrl, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Lets a module say that the markers' content changed (the page is rebuilt on the next request).</summary>
|
||||
public interface IIndexHtmlCache
|
||||
{
|
||||
void Invalidate();
|
||||
}
|
||||
|
||||
public sealed record InjectedPage(byte[] Body, string ETag);
|
||||
|
||||
/// <summary>
|
||||
/// Fills the marker comments of the SpaFallback website's <c>index.html</c> from the registered
|
||||
/// <see cref="IIndexHtmlMarkerProvider"/>s. The rendered page is cached for <see cref="CacheTtl"/> per public base URL
|
||||
/// and dropped at once on <see cref="Invalidate"/> (a module calls it after a change) or when the file changes.
|
||||
/// </summary>
|
||||
public sealed class IndexHtmlInjector(
|
||||
IServiceScopeFactory scopes,
|
||||
IOptions<WebsiteOptions> options,
|
||||
ILogger<IndexHtmlInjector> logger,
|
||||
TimeProvider? time = null) : IIndexHtmlCache
|
||||
{
|
||||
public static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(60);
|
||||
private static readonly TimeSpan FailureTtl = TimeSpan.FromSeconds(5);
|
||||
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
private readonly ConcurrentDictionary<string, Entry> _cache = new();
|
||||
private long _version;
|
||||
|
||||
private sealed record Entry(long Version, DateTime FileTime, DateTimeOffset Expires, InjectedPage? Page);
|
||||
|
||||
public void Invalidate() => Interlocked.Increment(ref _version);
|
||||
|
||||
/// <summary>The page with its markers filled, or null when no provider is registered (serve the file as it is).</summary>
|
||||
public async Task<InjectedPage?> GetAsync(string indexPath, HttpRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var baseUrl = SpaSeoExtensions.BaseUrl(options.Value) ?? $"{request.Scheme}://{request.Host}";
|
||||
var fileTime = File.GetLastWriteTimeUtc(indexPath);
|
||||
var version = Interlocked.Read(ref _version);
|
||||
var now = _time.GetUtcNow();
|
||||
|
||||
if (_cache.TryGetValue(baseUrl, out var cached)
|
||||
&& cached.Version == version && cached.FileTime == fileTime && cached.Expires > now)
|
||||
{
|
||||
return cached.Page;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var providers = scope.ServiceProvider.GetServices<IIndexHtmlMarkerProvider>().ToList();
|
||||
if (providers.Count == 0)
|
||||
{
|
||||
_cache[baseUrl] = new Entry(version, fileTime, now + CacheTtl, null);
|
||||
return null;
|
||||
}
|
||||
|
||||
var markers = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var provider in providers)
|
||||
{
|
||||
foreach (var (name, replacement) in await provider.RenderAsync(baseUrl, cancellationToken))
|
||||
{
|
||||
markers[name] = replacement;
|
||||
}
|
||||
}
|
||||
|
||||
var html = await File.ReadAllTextAsync(indexPath, cancellationToken);
|
||||
foreach (var (name, replacement) in markers)
|
||||
{
|
||||
html = html.Replace($"<!--{name}-->", replacement, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
var body = Encoding.UTF8.GetBytes(html);
|
||||
var etag = "\"" + Convert.ToHexString(SHA256.HashData(body))[..32].ToLowerInvariant() + "\"";
|
||||
var page = new InjectedPage(body, etag);
|
||||
_cache[baseUrl] = new Entry(version, fileTime, now + CacheTtl, page);
|
||||
return page;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// Never take the website down for its dynamic parts: keep the last good page if there is one, else
|
||||
// serve the file with its markers untouched (they are HTML comments, so they render as nothing).
|
||||
logger.LogError(ex, "Filling the website markers failed; serving the previous or the plain page");
|
||||
var page = cached?.Page;
|
||||
_cache[baseUrl] = new Entry(version, fileTime, now + FailureTtl, page);
|
||||
return page;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ public static class SpaSeoExtensions
|
||||
public static IServiceCollection AddCmsSpaSeo(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddOptions<WebsiteOptions>().Bind(configuration.GetSection(WebsiteOptions.SectionName));
|
||||
services.AddSingleton<IndexHtmlInjector>();
|
||||
services.AddSingleton<IIndexHtmlCache>(provider => provider.GetRequiredService<IndexHtmlInjector>());
|
||||
return services;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user