Serve 503 when PocketBase is unavailable across all content pages

This commit is contained in:
tleininger committed 2026-09-24 13:00:14 +02:00
1 parent 0f7e968c16
commit e242eaf79a
25 files changed
+492 -253

No files matched your search

@@ -6,14 +6,19 @@ namespace Elternbeirat.Web.Components.Layout;
public partial class MainLayout
{
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load navigation pages from PocketBase.")]
private static partial void LogLoadFailed(ILogger logger, Exception exception);
[LoggerMessage(
Level = LogLevel.Warning,
Message = "Could not load navigation pages from PocketBase; the menu is empty.")]
private static partial void LogSourceUnavailable(ILogger logger, Exception exception);
[Inject]
private PocketBaseClient PocketBase { get; set; } = default!;
private PocketBaseClient PocketBase { get; set; } = null!;
[Inject]
private ILogger<MainLayout> Logger { get; set; } = default!;
private ILogger<MainLayout> Logger { get; set; } = null!;
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
private IReadOnlyList<NavLinkItem> _header = [];
private IReadOnlyList<NavLinkItem> _footer = [];
@@ -22,15 +27,15 @@ public partial class MainLayout
{
try
{
var pages = await PocketBase.GetPagesAsync();
var pages = await PocketBase.GetPagesAsync(HttpContext?.RequestAborted ?? default);
_header = NavBuilder.Header(pages);
_footer = NavBuilder.Footer(pages);
}
catch (HttpRequestException ex)
catch (PocketBaseUnavailableException ex)
{
// Source unreachable -> render the chrome with an empty menu instead of
// a 500. The brand link still leads home.
LogLoadFailed(Logger, ex);
// Only the menu fails: render the chrome with an empty menu instead of a
// 500, so every page stays reachable. The brand link still leads home.
LogSourceUnavailable(Logger, ex);
}
}
}
@@ -1,12 +1,7 @@
<section class="embed embed-events">
<h2>Kommende Termine</h2>
@if (_upcoming.Count == 0)
{
<p>Zurzeit sind keine Termine geplant.</p>
}
else
{
@if (_upcoming.Count > 0)
{
<section class="embed embed-events">
<h2>Kommende Termine</h2>
<ul class="event-list">
@foreach (var ev in _upcoming)
{
@@ -21,5 +16,5 @@
}
</ul>
<p class="embed-more"><a href="/events">Alle Termine <span aria-hidden="true">&rarr;</span></a></p>
}
</section>
</section>
}
@@ -6,14 +6,24 @@ namespace Elternbeirat.Web.Features.Embeds;
public partial class EventsEmbed
{
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load events for an embed from PocketBase.")]
private static partial void LogLoadFailed(ILogger logger, Exception exception);
// Number of upcoming events shown in the teaser; the full list is one link away.
private const int TeaserCount = 3;
[LoggerMessage(
Level = LogLevel.Warning,
Message = "Could not load events for an embed from PocketBase; the teaser is omitted.")]
private static partial void LogSourceUnavailable(
ILogger logger,
Exception exception);
[Inject]
private PocketBaseClient PocketBase { get; set; } = default!;
private PocketBaseClient PocketBase { get; set; } = null!;
[Inject]
private ILogger<EventsEmbed> Logger { get; set; } = default!;
private ILogger<EventsEmbed> Logger { get; set; } = null!;
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
private IReadOnlyList<Event> _upcoming = [];
@@ -22,22 +32,25 @@ public partial class EventsEmbed
IReadOnlyList<Event> events;
try
{
events = await PocketBase.GetEventsAsync();
events = await PocketBase.GetEventsAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
}
catch (HttpRequestException ex)
catch (PocketBaseUnavailableException exception)
{
// Source unreachable -> show no teaser instead of a 500.
LogLoadFailed(Logger, ex);
// Only part of the page fails: omit the teaser, keep the page (and its
// 200) intact. A missing teaser is degraded, not broken.
LogSourceUnavailable(Logger, exception);
return;
}
// Teaser: the three soonest upcoming events, earliest first. An event
// earlier today still counts as upcoming.
// Teaser: the soonest upcoming events, earliest first. An event earlier
// today still counts as upcoming.
var today = DateOnly.FromDateTime(DateTime.Today);
_upcoming = events
.Where(e => DateOnly.FromDateTime(e.Start) >= today)
.OrderBy(e => e.Start)
.Take(3)
.ToList();
_upcoming =
[
.. events
.Where(@event => DateOnly.FromDateTime(@event.Start) >= today)
.OrderBy(@event => @event.Start)
.Take(TeaserCount)
];
}
}
@@ -1,12 +1,7 @@
<section class="embed embed-faqs">
<h2>Häufige Fragen</h2>
@if (_faqs.Count == 0)
{
<p>Zurzeit gibt es keine Fragen.</p>
}
else
{
@if (_faqs.Count > 0)
{
<section class="embed embed-faqs">
<h2>Häufige Fragen</h2>
@foreach (var faq in _faqs)
{
<details class="faq-item">
@@ -17,5 +12,5 @@
</details>
}
<p class="embed-more"><a href="/faqs">Alle Fragen <span aria-hidden="true">&rarr;</span></a></p>
}
</section>
</section>
}
@@ -6,14 +6,24 @@ namespace Elternbeirat.Web.Features.Embeds;
public partial class FaqsEmbed
{
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load FAQs for an embed from PocketBase.")]
private static partial void LogLoadFailed(ILogger logger, Exception exception);
// Number of questions shown in the teaser; the full hub is one link away.
private const int TeaserCount = 3;
[LoggerMessage(
Level = LogLevel.Warning,
Message = "Could not load FAQs for an embed from PocketBase; the teaser is omitted.")]
private static partial void LogSourceUnavailable(
ILogger logger,
Exception exception);
[Inject]
private PocketBaseClient PocketBase { get; set; } = default!;
private PocketBaseClient PocketBase { get; set; } = null!;
[Inject]
private ILogger<FaqsEmbed> Logger { get; set; } = default!;
private ILogger<FaqsEmbed> Logger { get; set; } = null!;
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
private IReadOnlyList<Faq> _faqs = [];
@@ -21,14 +31,16 @@ public partial class FaqsEmbed
{
try
{
// Teaser: the first three questions, with a link to the full hub.
var faqs = await PocketBase.GetFaqsAsync();
_faqs = [.. faqs.Take(3)];
// GetFaqsAsync is ordered by topic, then question, so the first entries
// the teaser takes are stable across requests.
var faqs = await PocketBase.GetFaqsAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
_faqs = [.. faqs.Take(TeaserCount)];
}
catch (HttpRequestException ex)
catch (PocketBaseUnavailableException exception)
{
// Source unreachable -> show no teaser instead of a 500.
LogLoadFailed(Logger, ex);
// Only part of the page fails: omit the teaser, keep the page (and its
// 200) intact. A missing teaser is degraded, not broken.
LogSourceUnavailable(Logger, exception);
}
}
}
@@ -1,23 +1,18 @@
<section class="embed embed-posts">
<h2>Aktuelle Beiträge</h2>
@if (_latest.Count == 0)
{
<p>Zurzeit gibt es keine Beiträge.</p>
}
else
{
@if (_latest.Count > 0)
{
<section class="embed embed-posts">
<h2>Aktuelle Beiträge</h2>
<ul class="post-list">
@foreach (var post in _latest)
{
<li>
<a href="@($"/posts/{post.Slug}")">@post.Title</a>
<time datetime="@post.Date.ToString("yyyy-MM-dd")">
@post.Date.ToString("d. MMMM yyyy", German)
<time datetime="@post.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)">
@post.Date.ToString("d. MMMM yyyy", Cultures.German)
</time>
</li>
}
</ul>
<p class="embed-more"><a href="/posts">Alle Beiträge <span aria-hidden="true">&rarr;</span></a></p>
}
</section>
</section>
}
@@ -1,4 +1,3 @@
using System.Globalization;
using Elternbeirat.Contracts;
using Elternbeirat.PocketBase;
using Microsoft.AspNetCore.Components;
@@ -7,16 +6,24 @@ namespace Elternbeirat.Web.Features.Embeds;
public partial class PostsEmbed
{
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
// Number of posts shown in the teaser; the full list is one link away.
private const int TeaserCount = 3;
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load posts for an embed from PocketBase.")]
private static partial void LogLoadFailed(ILogger logger, Exception exception);
[LoggerMessage(
Level = LogLevel.Warning,
Message = "Could not load posts for an embed from PocketBase; the teaser is omitted.")]
private static partial void LogSourceUnavailable(
ILogger logger,
Exception exception);
[Inject]
private PocketBaseClient PocketBase { get; set; } = default!;
private PocketBaseClient PocketBase { get; set; } = null!;
[Inject]
private ILogger<PostsEmbed> Logger { get; set; } = default!;
private ILogger<PostsEmbed> Logger { get; set; } = null!;
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
private IReadOnlyList<Post> _latest = [];
@@ -24,14 +31,15 @@ public partial class PostsEmbed
{
try
{
// Teaser: the three most recent posts, with a link to the full list.
var posts = await PocketBase.GetPostsAsync();
_latest = [.. posts.Take(3)];
// GetPostsAsync returns newest first, so the first entries are the latest.
var posts = await PocketBase.GetPostsAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
_latest = [.. posts.Take(TeaserCount)];
}
catch (HttpRequestException ex)
catch (PocketBaseUnavailableException exception)
{
// Source unreachable -> show no teaser instead of a 500.
LogLoadFailed(Logger, ex);
// Only part of the page fails: omit the teaser, keep the page (and its
// 200) intact. A missing teaser is degraded, not broken.
LogSourceUnavailable(Logger, exception);
}
}
}
@@ -4,53 +4,60 @@
<h1>Termine</h1>
<p class="intro">
Alle Termine des Elternbeirats auf einen Blick. Sie können den Kalender auch
<a href="/events.ics">abonnieren</a> und in Ihrer Kalender-App automatisch
aktuell halten.
</p>
<h2>Kommende Termine</h2>
@if (_upcoming.Count == 0)
@if (_unavailable)
{
<p>Zurzeit sind keine Termine geplant.</p>
<p>Die Termine sind gerade nicht erreichbar. Bitte später erneut versuchen.</p>
}
else
{
<ul class="event-list">
@foreach (var ev in _upcoming)
{
<li>
<time datetime="@ev.Start.ToString("s")">@EventFormat.Range(ev)</time>
<span class="event-title">@ev.Title</span>
@if (!string.IsNullOrWhiteSpace(ev.Location))
{
<span class="event-location">@ev.Location</span>
}
@if (!string.IsNullOrWhiteSpace(ev.Note))
{
<p class="event-note">@ev.Note</p>
}
</li>
}
</ul>
}
<p class="intro">
Alle Termine des Elternbeirats auf einen Blick. Sie können den Kalender auch
<a href="/events.ics">abonnieren</a> und in Ihrer Kalender-App automatisch
aktuell halten.
</p>
@if (_past.Count > 0)
{
<h2>Vergangene Termine</h2>
<ul class="event-list event-list-past">
@foreach (var ev in _past)
{
<li>
<time datetime="@ev.Start.ToString("s")">@EventFormat.Range(ev)</time>
<span class="event-title">@ev.Title</span>
@if (!string.IsNullOrWhiteSpace(ev.Location))
{
<span class="event-location">@ev.Location</span>
}
</li>
}
</ul>
<h2>Kommende Termine</h2>
@if (_upcoming.Count == 0)
{
<p>Zurzeit sind keine Termine geplant.</p>
}
else
{
<ul class="event-list">
@foreach (var ev in _upcoming)
{
<li>
<time datetime="@ev.Start.ToString("s")">@EventFormat.Range(ev)</time>
<span class="event-title">@ev.Title</span>
@if (!string.IsNullOrWhiteSpace(ev.Location))
{
<span class="event-location">@ev.Location</span>
}
@if (!string.IsNullOrWhiteSpace(ev.Note))
{
<p class="event-note">@ev.Note</p>
}
</li>
}
</ul>
}
@if (_past.Count > 0)
{
<h2>Vergangene Termine</h2>
<ul class="event-list event-list-past">
@foreach (var ev in _past)
{
<li>
<time datetime="@ev.Start.ToString("s")">@EventFormat.Range(ev)</time>
<span class="event-title">@ev.Title</span>
@if (!string.IsNullOrWhiteSpace(ev.Location))
{
<span class="event-location">@ev.Location</span>
}
</li>
}
</ul>
}
}
@@ -1,48 +1,67 @@
using Elternbeirat.Contracts;
using Elternbeirat.PocketBase;
using Elternbeirat.Web.Shared;
using Microsoft.AspNetCore.Components;
namespace Elternbeirat.Web.Features.Events;
public partial class EventList
{
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load events from PocketBase.")]
private static partial void LogLoadFailed(ILogger logger, Exception exception);
[LoggerMessage(
Level = LogLevel.Error,
Message = "Could not load events from PocketBase; content source is unavailable.")]
private static partial void LogSourceUnavailable(
ILogger logger,
Exception exception);
[Inject]
private PocketBaseClient PocketBase { get; set; } = default!;
private PocketBaseClient PocketBase { get; set; } = null!;
[Inject]
private ILogger<EventList> Logger { get; set; } = default!;
private ILogger<EventList> Logger { get; set; } = null!;
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
private IReadOnlyList<Event> _upcoming = [];
private IReadOnlyList<Event> _past = [];
// Set when the content source could not be reached or read. The markup then
// shows a "temporarily unavailable" note instead of "no events", matching the
// 503 this sets on the response.
private bool _unavailable;
protected override async Task OnInitializedAsync()
{
IReadOnlyList<Event> events;
try
{
events = await PocketBase.GetEventsAsync();
events = await PocketBase.GetEventsAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
}
catch (HttpRequestException ex)
catch (PocketBaseUnavailableException exception)
{
// Source unreachable -> show empty sections instead of a 500. The page
// stays up; the "keine Termine" note is rendered.
LogLoadFailed(Logger, ex);
// Empty sections would claim there are no events. The site works, its
// data store is down: 503 and an honest note.
LogSourceUnavailable(Logger, exception);
_unavailable = true;
SourceUnavailable.SetStatus(HttpContext);
return;
}
// Split into upcoming and past by date, so an event earlier today still
// counts as upcoming. Upcoming earliest first, past most recent first.
var today = DateOnly.FromDateTime(DateTime.Today);
_upcoming = events
.Where(e => DateOnly.FromDateTime(e.Start) >= today)
.OrderBy(e => e.Start)
.ToList();
_past = events
.Where(e => DateOnly.FromDateTime(e.Start) < today)
.OrderByDescending(e => e.Start)
.ToList();
_upcoming =
[
.. events
.Where(@event => DateOnly.FromDateTime(@event.Start) >= today)
.OrderBy(@event => @event.Start)
];
_past =
[
.. events
.Where(@event => DateOnly.FromDateTime(@event.Start) < today)
.OrderByDescending(@event => @event.Start)
];
}
}
+5 -1
View File
@@ -4,7 +4,11 @@
<h1>Häufige Fragen</h1>
@if (_groups.Count == 0)
@if (_unavailable)
{
<p>Die Fragen sind gerade nicht erreichbar. Bitte später erneut versuchen.</p>
}
else if (_groups.Count == 0)
{
<p>Zurzeit gibt es keine Fragen.</p>
}
+26 -11
View File
@@ -1,13 +1,18 @@
using Elternbeirat.Contracts;
using Elternbeirat.PocketBase;
using Elternbeirat.Web.Shared;
using Microsoft.AspNetCore.Components;
namespace Elternbeirat.Web.Features.Faqs;
public partial class FaqList
{
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load FAQs from PocketBase.")]
private static partial void LogLoadFailed(ILogger logger, Exception exception);
[LoggerMessage(
Level = LogLevel.Error,
Message = "Could not load FAQs from PocketBase; content source is unavailable.")]
private static partial void LogSourceUnavailable(
ILogger logger,
Exception exception);
// German heading per topic. Unknown topics fall back to the raw key so a new
// topic in PocketBase still shows up rather than being silently dropped.
@@ -21,28 +26,38 @@ public partial class FaqList
};
[Inject]
private PocketBaseClient PocketBase { get; set; } = default!;
private PocketBaseClient PocketBase { get; set; } = null!;
[Inject]
private ILogger<FaqList> Logger { get; set; } = default!;
private ILogger<FaqList> Logger { get; set; } = null!;
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
private IReadOnlyList<IGrouping<string, Faq>> _groups = [];
// Set when the content source could not be reached or read. The markup then
// shows a "temporarily unavailable" note instead of "no questions", matching
// the 503 this sets on the response.
private bool _unavailable;
protected override async Task OnInitializedAsync()
{
try
{
var faqs = await PocketBase.GetFaqsAsync();
var faqs = await PocketBase.GetFaqsAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
_groups = [.. faqs.GroupBy(faq => faq.Topic)];
}
catch (HttpRequestException ex)
catch (PocketBaseUnavailableException exception)
{
// Source unreachable -> show an empty page instead of a 500. The page
// stays up; the "keine Fragen" note is rendered.
LogLoadFailed(Logger, ex);
// An empty page would claim there are no questions. The site works, its
// data store is down: 503 and an honest note.
LogSourceUnavailable(Logger, exception);
_unavailable = true;
SourceUnavailable.SetStatus(HttpContext);
}
}
private static string TopicLabel(string topic) =>
TopicLabels.TryGetValue(topic, out var label) ? label : topic;
private static string TopicLabel(string topic)
=> TopicLabels.GetValueOrDefault(topic, topic);
}
+10 -6
View File
@@ -8,8 +8,8 @@ public partial class Home
{
[LoggerMessage(
Level = LogLevel.Warning,
Message = "Could not load the home page from PocketBase.")]
private static partial void LogLoadFailed(
Message = "Could not load the home page from PocketBase; embeds are omitted.")]
private static partial void LogSourceUnavailable(
ILogger logger,
Exception exception);
@@ -19,6 +19,9 @@ public partial class Home
[Inject]
private ILogger<Home> Logger { get; set; } = null!;
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
// Which dynamic blocks the home page shows is editorial: it comes from the
// "home" page's embed field in PocketBase, not from hard-coded markup.
private IReadOnlyList<string> _embed = [];
@@ -27,14 +30,15 @@ public partial class Home
{
try
{
var pages = await PocketBase.GetPagesAsync();
var pages = await PocketBase.GetPagesAsync(HttpContext?.RequestAborted ?? default);
var home = pages.FirstOrDefault(page => Page.IsHomeSlug(page.Slug));
_embed = home?.Embed ?? [];
}
catch (HttpRequestException exception)
catch (PocketBaseUnavailableException exception)
{
// Source unreachable -> render the intro without embeds instead of a 500.
LogLoadFailed(Logger, exception);
// Only the embeds fail: render the static intro without them instead of a
// 500. The home page's own text is markup, so it stays intact.
LogSourceUnavailable(Logger, exception);
}
}
}
@@ -1,14 +1,18 @@
@page "/{Slug}"
@if (_page is null)
@if (_unavailable)
{
<PageTitle>Nicht gefunden</PageTitle>
<PageTitle>Vorübergehend nicht erreichbar</PageTitle>
<p>Die Seite ist gerade nicht erreichbar. Bitte später erneut versuchen.</p>
}
else
else if (_page is not null)
{
<PageTitle>@_page.Title</PageTitle>
<article>
<h1>@_page.Title</h1>
@Body
</article>
<PageEmbeds Embed="_page.Embed" />
}
@* No page and not unavailable: the slug was unknown; NavigationManager.NotFound()
already ran in OnParametersSetAsync and renders the not-found page. *@
@@ -8,9 +8,9 @@ namespace Elternbeirat.Web.Features.Pages;
public partial class ContentPage
{
[LoggerMessage(
Level = LogLevel.Warning,
Message = "Could not load page '{slug}' from PocketBase.")]
private static partial void LogLoadFailed(
Level = LogLevel.Error,
Message = "Could not load page '{Slug}' from PocketBase; content source is unavailable.")]
private static partial void LogSourceUnavailable(
ILogger logger,
string slug,
Exception exception);
@@ -24,11 +24,19 @@ public partial class ContentPage
[Inject]
private ILogger<ContentPage> Logger { get; set; } = null!;
[Inject]
private NavigationManager Navigation { get; set; } = null!;
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
private Page? _page;
// Set when the content source could not be reached or read. The markup then
// shows a "temporarily unavailable" note instead of a not-found page, matching
// the 503 this sets on the response.
private bool _unavailable;
// The page body rendered from Markdown to HTML, ready to emit as a
// MarkupString in the markup.
private MarkupString Body => (MarkupString)Markdown.ToHtml(_page?.Body);
@@ -37,24 +45,23 @@ public partial class ContentPage
{
try
{
var pages = await PocketBase.GetPagesAsync();
var pages = await PocketBase.GetPagesAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
_page = pages.FirstOrDefault(
p => string.Equals(p.Slug, Slug, StringComparison.OrdinalIgnoreCase));
page => string.Equals(page.Slug, Slug, StringComparison.OrdinalIgnoreCase));
}
catch (HttpRequestException ex)
catch (PocketBaseUnavailableException exception)
{
// Source unreachable -> treat as "not found" rather than a 500. The
// 404 branch below serves the friendly /not-found page.
LogLoadFailed(Logger, Slug, ex);
_page = null;
// The site works, its data store is down: 503, not 404.
LogSourceUnavailable(Logger, Slug, exception);
_unavailable = true;
SourceUnavailable.SetStatus(HttpContext);
return;
}
// Unknown slug (or unreachable source) -> 404, so
// UseStatusCodePagesWithReExecute serves the /not-found page instead of an
// empty 200 response.
if (_page is null && HttpContext is not null)
if (_page is null)
{
HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
// The source answered, but there is no page with this slug: a genuine 404.
Navigation.NotFound();
}
}
}
@@ -1,19 +1,25 @@
@page "/posts/{Slug}"
@if (_post is null)
@if (_unavailable)
{
<PageTitle>Nicht gefunden</PageTitle>
<PageTitle>Vorübergehend nicht erreichbar</PageTitle>
<p>Der Beitrag ist gerade nicht erreichbar. Bitte später erneut versuchen.</p>
}
else
else if (_post is not null)
{
<PageTitle>@_post.Title</PageTitle>
<nav>
<a href="/posts">&larr; Alle Beiträge</a>
</nav>
<article>
<p class="post-meta">
<a href="/posts">&larr; Alle Beiträge</a>
<time datetime="@_post.Date.ToString("yyyy-MM-dd")">
@_post.Date.ToString("d. MMMM yyyy", German)
<header>
<h1>@_post.Title</h1>
<time class="post-meta" datetime="@_post.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)">
@_post.Date.ToString("d. MMMM yyyy", Cultures.German)
</time>
</p>
</header>
@Body
</article>
}
@* No post and not unavailable: the slug was unknown; NavigationManager.NotFound()
already ran in OnParametersSetAsync and renders the not-found page. *@
@@ -1,33 +1,42 @@
using System.Globalization;
using Elternbeirat.Contracts;
using Elternbeirat.PocketBase;
using Elternbeirat.Web.Shared;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
namespace Elternbeirat.Web.Features.Posts;
public partial class PostDetail
{
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load post '{slug}' from PocketBase.")]
private static partial void LogLoadFailed(ILogger logger, string slug, Exception exception);
[LoggerMessage(
Level = LogLevel.Error,
Message = "Could not load post '{Slug}' from PocketBase; content source is unavailable.")]
private static partial void LogSourceUnavailable(
ILogger logger,
string slug,
Exception exception);
[Parameter]
public string Slug { get; set; } = string.Empty;
[Inject]
private PocketBaseClient PocketBase { get; set; } = default!;
private PocketBaseClient PocketBase { get; set; } = null!;
[Inject]
private ILogger<PostDetail> Logger { get; set; } = default!;
private ILogger<PostDetail> Logger { get; set; } = null!;
[Inject]
private NavigationManager Navigation { get; set; } = null!;
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
private Post? _post;
// Set when the content source could not be reached or read. The markup then
// shows a "temporarily unavailable" note instead of a not-found page, matching
// the 503 this sets on the response.
private bool _unavailable;
// The post body rendered from Markdown to HTML, ready to emit as a
// MarkupString in the markup.
private MarkupString Body => (MarkupString)Markdown.ToHtml(_post?.Body);
@@ -36,24 +45,23 @@ public partial class PostDetail
{
try
{
var posts = await PocketBase.GetPostsAsync();
var posts = await PocketBase.GetPostsAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
_post = posts.FirstOrDefault(
p => string.Equals(p.Slug, Slug, StringComparison.OrdinalIgnoreCase));
post => string.Equals(post.Slug, Slug, StringComparison.OrdinalIgnoreCase));
}
catch (HttpRequestException ex)
catch (PocketBaseUnavailableException exception)
{
// Source unreachable -> treat as "not found" rather than a 500. The
// 404 branch below serves the friendly /not-found page.
LogLoadFailed(Logger, Slug, ex);
_post = null;
// The site works, its data store is down: 503, not 404.
LogSourceUnavailable(Logger, Slug, exception);
_unavailable = true;
SourceUnavailable.SetStatus(HttpContext);
return;
}
// Unknown slug (or unreachable source) -> 404, so
// UseStatusCodePagesWithReExecute serves the /not-found page instead of an
// empty 200 response.
if (_post is null && HttpContext is not null)
if (_post is null)
{
HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
// The source answered, but there is no post with this slug: a genuine 404.
Navigation.NotFound();
}
}
}
@@ -4,7 +4,11 @@
<h1>Beiträge</h1>
@if (_posts.Count == 0)
@if (_unavailable)
{
<p>Die Beiträge sind gerade nicht erreichbar. Bitte später erneut versuchen.</p>
}
else if (_posts.Count == 0)
{
<p>Zurzeit gibt es keine Beiträge.</p>
}
@@ -15,8 +19,8 @@ else
{
<li>
<a href="@($"/posts/{post.Slug}")">@post.Title</a>
<time datetime="@post.Date.ToString("yyyy-MM-dd")">
@post.Date.ToString("d. MMMM yyyy", German)
<time datetime="@post.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)">
@post.Date.ToString("d. MMMM yyyy", Cultures.German)
</time>
</li>
}
@@ -1,36 +1,48 @@
using System.Globalization;
using Elternbeirat.Contracts;
using Elternbeirat.PocketBase;
using Elternbeirat.Web.Shared;
using Microsoft.AspNetCore.Components;
namespace Elternbeirat.Web.Features.Posts;
public partial class PostList
{
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load posts from PocketBase.")]
private static partial void LogLoadFailed(ILogger logger, Exception exception);
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
[LoggerMessage(
Level = LogLevel.Error,
Message = "Could not load posts from PocketBase; content source is unavailable.")]
private static partial void LogSourceUnavailable(
ILogger logger,
Exception exception);
[Inject]
private PocketBaseClient PocketBase { get; set; } = default!;
private PocketBaseClient PocketBase { get; set; } = null!;
[Inject]
private ILogger<PostList> Logger { get; set; } = default!;
private ILogger<PostList> Logger { get; set; } = null!;
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
private IReadOnlyList<Post> _posts = [];
// Set when the content source could not be reached or read. The markup then
// shows a "temporarily unavailable" note instead of "no posts", matching the
// 503 this sets on the response.
private bool _unavailable;
protected override async Task OnInitializedAsync()
{
try
{
_posts = await PocketBase.GetPostsAsync();
_posts = await PocketBase.GetPostsAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
}
catch (HttpRequestException ex)
catch (PocketBaseUnavailableException exception)
{
// Source unreachable -> show an empty list instead of a 500. The page
// stays up; the "keine Beiträge" note is rendered.
LogLoadFailed(Logger, ex);
// An empty list would claim there are no posts. The site works, its
// data store is down: 503 and an honest note.
LogSourceUnavailable(Logger, exception);
_unavailable = true;
SourceUnavailable.SetStatus(HttpContext);
}
}
}
+16 -13
View File
@@ -13,7 +13,7 @@ builder.Services.AddRazorComponents();
// comes from configuration: appsettings for local dev, the PocketBase__BaseUrl
// env var on the server (see compose.yaml).
var pocketBaseUrl = builder.Configuration["PocketBase:BaseUrl"]
?? throw new InvalidOperationException("PocketBase:BaseUrl is not configured.");
?? throw new InvalidOperationException("PocketBase:BaseUrl is not configured.");
builder.Services.AddHttpClient<PocketBaseClient>(client =>
client.BaseAddress = new Uri(pocketBaseUrl));
@@ -24,23 +24,26 @@ var app = builder.Build();
// as HTTP and with the proxy IP instead of the client IP.
// KnownNetworks/KnownProxies are deliberately empty because only NPM reaches
// the container.
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
KnownIPNetworks = { },
KnownProxies = { }
});
app.UseForwardedHeaders(
new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
if (app.Environment.IsDevelopment() is false)
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// No UseHsts() and no UseHttpsRedirection(): NPM sets HSTS and terminates
// TLS. Both here would create a redirect loop behind the proxy.
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
// No UseStatusCodePagesWithReExecute: the Router renders the NotFoundPage
// (Pages.NotFound) in process for both an unmatched route and an explicit
// NavigationManager.NotFound() from a component (see Routes.razor). Re-executing
// every error code to /not-found would also turn a 503 (content source down) into
// a "not found" page; leaving it out lets those components keep their own
// "temporarily unavailable" markup and 503 status.
app.UseAntiforgery();
app.MapStaticAssets();
@@ -49,14 +52,14 @@ app.MapRazorComponents<App>();
// Subscribable calendar feed of all events. A minimal API endpoint rather than
// a Razor page because it returns text/calendar, not HTML. Reads from PocketBase
// per request; an unreachable source yields an empty calendar, not a 500.
app.MapGet("/events.ics", async (PocketBaseClient pocketBase) =>
app.MapGet("/events.ics", async (PocketBaseClient pocketBase, CancellationToken token) =>
{
IReadOnlyList<Event> events;
try
{
events = await pocketBase.GetEventsAsync();
events = await pocketBase.GetEventsAsync(token);
}
catch (HttpRequestException)
catch (PocketBaseUnavailableException)
{
events = [];
}
+21
View File
@@ -0,0 +1,21 @@
using System.Globalization;
namespace Elternbeirat.Web.Shared;
/// <summary>
/// Shared <see cref="CultureInfo"/> instances used to format visitor-facing
/// text.
/// </summary>
/// <remarks>
/// Kept in one place so every component renders month and weekday names the
/// same way, rather than each holding its own <c>de-DE</c> lookup. This is only
/// for display text; machine-readable output (e.g. an HTML <c>datetime</c>
/// attribute) uses <see cref="CultureInfo.InvariantCulture"/> instead.
/// </remarks>
internal static class Cultures
{
/// <summary>
/// German culture, for the month and weekday names visitors read.
/// </summary>
public static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
}
+3 -9
View File
@@ -1,4 +1,3 @@
using System.Globalization;
using Elternbeirat.Contracts;
namespace Elternbeirat.Web.Shared;
@@ -22,11 +21,6 @@ public static class EventFormat
/// </summary>
private const string ShortDate = "d. MMMM yyyy";
/// <summary>
/// The culture used for month and weekday names.
/// </summary>
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
/// <summary>
/// Formats the date range of an event.
/// </summary>
@@ -54,7 +48,7 @@ public static class EventFormat
(var start, null, var hasTime)
=> Stamp(start, LongDate, hasTime),
(var start, { } end, true) when end.Date == start.Date
=> $"{start.ToString(LongDate, German)}, {start.ToString("HH:mm", German)}–{end.ToString("HH:mm", German)} Uhr",
=> $"{start.ToString(LongDate, Cultures.German)}, {start.ToString("HH:mm", Cultures.German)}–{end.ToString("HH:mm", Cultures.German)} Uhr",
(var start, { } end, false) when end.Date == start.Date
=> Stamp(start, LongDate, withTime: false),
(var start, { } end, var hasTime)
@@ -78,6 +72,6 @@ public static class EventFormat
/// </returns>
private static string Stamp(DateTime value, string dateFormat, bool withTime)
=> withTime
? value.ToString(dateFormat + ", HH:mm", German) + " Uhr"
: value.ToString(dateFormat, German);
? value.ToString(dateFormat + ", HH:mm", Cultures.German) + " Uhr"
: value.ToString(dateFormat, Cultures.German);
}
@@ -0,0 +1,30 @@
namespace Elternbeirat.Web.Shared;
/// <summary>
/// Marks the current response as HTTP 503 when the content source is down.
/// </summary>
/// <remarks>
/// Several components handle a <see cref="PocketBase.PocketBaseUnavailableException"/>
/// the same way: the site works but PocketBase does not, so the response is a
/// 503 and the component renders a "temporarily unavailable" note instead of
/// empty content that would read as 200 "there is nothing here". This puts the
/// status-setting in one place so those components do not each repeat it.
/// </remarks>
internal static class SourceUnavailable
{
/// <summary>
/// Sets the response status to 503 Service Unavailable, if there is a
/// response to set it on.
/// </summary>
/// <param name="context">
/// The current HTTP context, or <see langword="null"/> when the component
/// renders outside a request (in which case there is nothing to do).
/// </param>
public static void SetStatus(HttpContext? context)
{
if (context is not null)
{
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
}
}
}
+1
View File
@@ -1,3 +1,4 @@
@using System.Globalization
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms