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

+38 -10
View File
@@ -38,14 +38,11 @@ public sealed class PocketBaseClient(HttpClient httpClient)
/// <returns> /// <returns>
/// The public pages, or an empty list if there are none. /// The public pages, or an empty list if there are none.
/// </returns> /// </returns>
/// <exception cref="HttpRequestException"> /// <exception cref="PocketBaseUnavailableException">
/// PocketBase could not be reached or returned a non-success status code. /// PocketBase could not be reached, timed out, or returned an unreadable response.
/// </exception>
/// <exception cref="JsonException">
/// The response could not be deserialized.
/// </exception> /// </exception>
/// <exception cref="OperationCanceledException"> /// <exception cref="OperationCanceledException">
/// <paramref name="token"/> was canceled or the request timed out. /// <paramref name="token"/> was canceled by the caller.
/// </exception> /// </exception>
public Task<IReadOnlyList<Page>> GetPagesAsync(CancellationToken token = default) public Task<IReadOnlyList<Page>> GetPagesAsync(CancellationToken token = default)
=> GetRecordsAsync<Page>("pages", "order", token); => GetRecordsAsync<Page>("pages", "order", token);
@@ -73,15 +70,22 @@ public sealed class PocketBaseClient(HttpClient httpClient)
=> GetRecordsAsync<Event>("events", "start", token); => GetRecordsAsync<Event>("events", "start", token);
/// <summary> /// <summary>
/// Gets all public FAQ entries, ordered by <see cref="Faq.Topic"/>. /// Gets all public FAQ entries, ordered by <see cref="Faq.Topic"/>, then by
/// <see cref="Faq.Question"/>.
/// </summary> /// </summary>
/// <remarks>
/// The second sort key makes the order total: sorting by topic alone leaves
/// entries within a topic in an undefined order, so the same content could
/// render differently between requests. Adding the question as a tie-breaker
/// keeps the FAQ list and any teaser drawn from it stable.
/// </remarks>
/// <inheritdoc cref="GetPagesAsync" path="/param"/> /// <inheritdoc cref="GetPagesAsync" path="/param"/>
/// <returns> /// <returns>
/// The public FAQ entries, or an empty list if there are none. /// The public FAQ entries, or an empty list if there are none.
/// </returns> /// </returns>
/// <inheritdoc cref="GetPagesAsync" path="/exception"/> /// <inheritdoc cref="GetPagesAsync" path="/exception"/>
public Task<IReadOnlyList<Faq>> GetFaqsAsync(CancellationToken token = default) public Task<IReadOnlyList<Faq>> GetFaqsAsync(CancellationToken token = default)
=> GetRecordsAsync<Faq>("faqs", "topic", token); => GetRecordsAsync<Faq>("faqs", "topic,question", token);
/// <summary> /// <summary>
/// Gets all public records of a collection in a single request. /// Gets all public records of a collection in a single request.
@@ -101,6 +105,12 @@ public sealed class PocketBaseClient(HttpClient httpClient)
/// <returns> /// <returns>
/// The public records, or an empty list if there are none. /// The public records, or an empty list if there are none.
/// </returns> /// </returns>
/// <exception cref="PocketBaseUnavailableException">
/// PocketBase could not be reached, timed out, or returned an unreadable response.
/// </exception>
/// <exception cref="OperationCanceledException">
/// <paramref name="token"/> was canceled by the caller.
/// </exception>
private async Task<IReadOnlyList<T>> GetRecordsAsync<T>( private async Task<IReadOnlyList<T>> GetRecordsAsync<T>(
string collection, string collection,
string sort, string sort,
@@ -112,7 +122,25 @@ public sealed class PocketBaseClient(HttpClient httpClient)
+ $"?perPage=500&filter={Uri.EscapeDataString("public=true")}" + $"?perPage=500&filter={Uri.EscapeDataString("public=true")}"
+ $"&sort={Uri.EscapeDataString(sort)}"; + $"&sort={Uri.EscapeDataString(sort)}";
var result = await httpClient.GetFromJsonAsync<RecordList<T>>(url, token); try
return result?.Items ?? []; {
var result = await httpClient.GetFromJsonAsync<RecordList<T>>(url, token);
return result?.Items ?? [];
}
// These three mean PocketBase itself failed: it was unreachable
// (HttpRequestException), the request to it timed out (a TaskCanceledException
// whose inner exception is a TimeoutException, which is how HttpClient surfaces
// its own timeout), or it answered with something we could not read
// (JsonException). A plain TaskCanceledException with no inner TimeoutException
// is the caller's own cancellation via token and is deliberately not caught --
// it propagates as OperationCanceledException so an aborted request stays an
// abort, not a fault.
catch (Exception exception) when (
exception is HttpRequestException
or JsonException
or TaskCanceledException { InnerException: TimeoutException })
{
throw new PocketBaseUnavailableException($"Could not read collection '{collection}'.", exception);
}
} }
} }
@@ -0,0 +1,49 @@
namespace Elternbeirat.PocketBase;
/// <summary>
/// Thrown when PocketBase could not be reached, timed out, or returned a
/// response that could not be read.
/// </summary>
/// <remarks>
/// This is the one failure the content pages need to distinguish: the site is
/// up but its data store is not, which is an HTTP 503, not a 404. Which
/// low-level exceptions mean that (a transport error, a timeout, unreadable
/// JSON) is <see cref="PocketBaseClient"/>'s concern; callers catch only this
/// type and need not know how the client talks to PocketBase.
/// </remarks>
public sealed class PocketBaseUnavailableException : Exception
{
/// <summary>
/// Initializes a new instance with a default message.
/// </summary>
public PocketBaseUnavailableException()
: base("PocketBase is unavailable.")
{
}
/// <summary>
/// Initializes a new instance with the given message.
/// </summary>
/// <param name="message">
/// The message that describes the error.
/// </param>
public PocketBaseUnavailableException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance with the given message and the underlying
/// failure that caused it.
/// </summary>
/// <param name="message">
/// The message that describes the error.
/// </param>
/// <param name="innerException">
/// The transport, timeout, or deserialization exception that was caught.
/// </param>
public PocketBaseUnavailableException(string message, Exception innerException)
: base(message, innerException)
{
}
}
@@ -6,14 +6,19 @@ namespace Elternbeirat.Web.Components.Layout;
public partial class MainLayout public partial class MainLayout
{ {
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load navigation pages from PocketBase.")] [LoggerMessage(
private static partial void LogLoadFailed(ILogger logger, Exception exception); 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] [Inject]
private PocketBaseClient PocketBase { get; set; } = default!; private PocketBaseClient PocketBase { get; set; } = null!;
[Inject] [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> _header = [];
private IReadOnlyList<NavLinkItem> _footer = []; private IReadOnlyList<NavLinkItem> _footer = [];
@@ -22,15 +27,15 @@ public partial class MainLayout
{ {
try try
{ {
var pages = await PocketBase.GetPagesAsync(); var pages = await PocketBase.GetPagesAsync(HttpContext?.RequestAborted ?? default);
_header = NavBuilder.Header(pages); _header = NavBuilder.Header(pages);
_footer = NavBuilder.Footer(pages); _footer = NavBuilder.Footer(pages);
} }
catch (HttpRequestException ex) catch (PocketBaseUnavailableException ex)
{ {
// Source unreachable -> render the chrome with an empty menu instead of // Only the menu fails: render the chrome with an empty menu instead of a
// a 500. The brand link still leads home. // 500, so every page stays reachable. The brand link still leads home.
LogLoadFailed(Logger, ex); LogSourceUnavailable(Logger, ex);
} }
} }
} }
@@ -1,12 +1,7 @@
<section class="embed embed-events"> @if (_upcoming.Count > 0)
<h2>Kommende Termine</h2> {
<section class="embed embed-events">
@if (_upcoming.Count == 0) <h2>Kommende Termine</h2>
{
<p>Zurzeit sind keine Termine geplant.</p>
}
else
{
<ul class="event-list"> <ul class="event-list">
@foreach (var ev in _upcoming) @foreach (var ev in _upcoming)
{ {
@@ -21,5 +16,5 @@
} }
</ul> </ul>
<p class="embed-more"><a href="/events">Alle Termine <span aria-hidden="true">&rarr;</span></a></p> <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 public partial class EventsEmbed
{ {
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load events for an embed from PocketBase.")] // Number of upcoming events shown in the teaser; the full list is one link away.
private static partial void LogLoadFailed(ILogger logger, Exception exception); 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] [Inject]
private PocketBaseClient PocketBase { get; set; } = default!; private PocketBaseClient PocketBase { get; set; } = null!;
[Inject] [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 = []; private IReadOnlyList<Event> _upcoming = [];
@@ -22,22 +32,25 @@ public partial class EventsEmbed
IReadOnlyList<Event> events; IReadOnlyList<Event> events;
try 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. // Only part of the page fails: omit the teaser, keep the page (and its
LogLoadFailed(Logger, ex); // 200) intact. A missing teaser is degraded, not broken.
LogSourceUnavailable(Logger, exception);
return; return;
} }
// Teaser: the three soonest upcoming events, earliest first. An event // Teaser: the soonest upcoming events, earliest first. An event earlier
// earlier today still counts as upcoming. // today still counts as upcoming.
var today = DateOnly.FromDateTime(DateTime.Today); var today = DateOnly.FromDateTime(DateTime.Today);
_upcoming = events _upcoming =
.Where(e => DateOnly.FromDateTime(e.Start) >= today) [
.OrderBy(e => e.Start) .. events
.Take(3) .Where(@event => DateOnly.FromDateTime(@event.Start) >= today)
.ToList(); .OrderBy(@event => @event.Start)
.Take(TeaserCount)
];
} }
} }
@@ -1,12 +1,7 @@
<section class="embed embed-faqs"> @if (_faqs.Count > 0)
<h2>Häufige Fragen</h2> {
<section class="embed embed-faqs">
@if (_faqs.Count == 0) <h2>Häufige Fragen</h2>
{
<p>Zurzeit gibt es keine Fragen.</p>
}
else
{
@foreach (var faq in _faqs) @foreach (var faq in _faqs)
{ {
<details class="faq-item"> <details class="faq-item">
@@ -17,5 +12,5 @@
</details> </details>
} }
<p class="embed-more"><a href="/faqs">Alle Fragen <span aria-hidden="true">&rarr;</span></a></p> <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 public partial class FaqsEmbed
{ {
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load FAQs for an embed from PocketBase.")] // Number of questions shown in the teaser; the full hub is one link away.
private static partial void LogLoadFailed(ILogger logger, Exception exception); 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] [Inject]
private PocketBaseClient PocketBase { get; set; } = default!; private PocketBaseClient PocketBase { get; set; } = null!;
[Inject] [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 = []; private IReadOnlyList<Faq> _faqs = [];
@@ -21,14 +31,16 @@ public partial class FaqsEmbed
{ {
try try
{ {
// Teaser: the first three questions, with a link to the full hub. // GetFaqsAsync is ordered by topic, then question, so the first entries
var faqs = await PocketBase.GetFaqsAsync(); // the teaser takes are stable across requests.
_faqs = [.. faqs.Take(3)]; 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. // Only part of the page fails: omit the teaser, keep the page (and its
LogLoadFailed(Logger, ex); // 200) intact. A missing teaser is degraded, not broken.
LogSourceUnavailable(Logger, exception);
} }
} }
} }
@@ -1,23 +1,18 @@
<section class="embed embed-posts"> @if (_latest.Count > 0)
<h2>Aktuelle Beiträge</h2> {
<section class="embed embed-posts">
@if (_latest.Count == 0) <h2>Aktuelle Beiträge</h2>
{
<p>Zurzeit gibt es keine Beiträge.</p>
}
else
{
<ul class="post-list"> <ul class="post-list">
@foreach (var post in _latest) @foreach (var post in _latest)
{ {
<li> <li>
<a href="@($"/posts/{post.Slug}")">@post.Title</a> <a href="@($"/posts/{post.Slug}")">@post.Title</a>
<time datetime="@post.Date.ToString("yyyy-MM-dd")"> <time datetime="@post.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)">
@post.Date.ToString("d. MMMM yyyy", German) @post.Date.ToString("d. MMMM yyyy", Cultures.German)
</time> </time>
</li> </li>
} }
</ul> </ul>
<p class="embed-more"><a href="/posts">Alle Beiträge <span aria-hidden="true">&rarr;</span></a></p> <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.Contracts;
using Elternbeirat.PocketBase; using Elternbeirat.PocketBase;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
@@ -7,16 +6,24 @@ namespace Elternbeirat.Web.Features.Embeds;
public partial class PostsEmbed 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.")] [LoggerMessage(
private static partial void LogLoadFailed(ILogger logger, Exception exception); 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] [Inject]
private PocketBaseClient PocketBase { get; set; } = default!; private PocketBaseClient PocketBase { get; set; } = null!;
[Inject] [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 = []; private IReadOnlyList<Post> _latest = [];
@@ -24,14 +31,15 @@ public partial class PostsEmbed
{ {
try try
{ {
// Teaser: the three most recent posts, with a link to the full list. // GetPostsAsync returns newest first, so the first entries are the latest.
var posts = await PocketBase.GetPostsAsync(); var posts = await PocketBase.GetPostsAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
_latest = [.. posts.Take(3)]; _latest = [.. posts.Take(TeaserCount)];
} }
catch (HttpRequestException ex) catch (PocketBaseUnavailableException exception)
{ {
// Source unreachable -> show no teaser instead of a 500. // Only part of the page fails: omit the teaser, keep the page (and its
LogLoadFailed(Logger, ex); // 200) intact. A missing teaser is degraded, not broken.
LogSourceUnavailable(Logger, exception);
} }
} }
} }
@@ -4,53 +4,60 @@
<h1>Termine</h1> <h1>Termine</h1>
<p class="intro"> @if (_unavailable)
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)
{ {
<p>Zurzeit sind keine Termine geplant.</p> <p>Die Termine sind gerade nicht erreichbar. Bitte später erneut versuchen.</p>
} }
else else
{ {
<ul class="event-list"> <p class="intro">
@foreach (var ev in _upcoming) 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
<li> aktuell halten.
<time datetime="@ev.Start.ToString("s")">@EventFormat.Range(ev)</time> </p>
<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>Kommende Termine</h2>
{
<h2>Vergangene Termine</h2> @if (_upcoming.Count == 0)
<ul class="event-list event-list-past"> {
@foreach (var ev in _past) <p>Zurzeit sind keine Termine geplant.</p>
{ }
<li> else
<time datetime="@ev.Start.ToString("s")">@EventFormat.Range(ev)</time> {
<span class="event-title">@ev.Title</span> <ul class="event-list">
@if (!string.IsNullOrWhiteSpace(ev.Location)) @foreach (var ev in _upcoming)
{ {
<span class="event-location">@ev.Location</span> <li>
} <time datetime="@ev.Start.ToString("s")">@EventFormat.Range(ev)</time>
</li> <span class="event-title">@ev.Title</span>
} @if (!string.IsNullOrWhiteSpace(ev.Location))
</ul> {
<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.Contracts;
using Elternbeirat.PocketBase; using Elternbeirat.PocketBase;
using Elternbeirat.Web.Shared;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
namespace Elternbeirat.Web.Features.Events; namespace Elternbeirat.Web.Features.Events;
public partial class EventList public partial class EventList
{ {
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load events from PocketBase.")] [LoggerMessage(
private static partial void LogLoadFailed(ILogger logger, Exception exception); Level = LogLevel.Error,
Message = "Could not load events from PocketBase; content source is unavailable.")]
private static partial void LogSourceUnavailable(
ILogger logger,
Exception exception);
[Inject] [Inject]
private PocketBaseClient PocketBase { get; set; } = default!; private PocketBaseClient PocketBase { get; set; } = null!;
[Inject] [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> _upcoming = [];
private IReadOnlyList<Event> _past = []; 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() protected override async Task OnInitializedAsync()
{ {
IReadOnlyList<Event> events; IReadOnlyList<Event> events;
try 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 // Empty sections would claim there are no events. The site works, its
// stays up; the "keine Termine" note is rendered. // data store is down: 503 and an honest note.
LogLoadFailed(Logger, ex); LogSourceUnavailable(Logger, exception);
_unavailable = true;
SourceUnavailable.SetStatus(HttpContext);
return; return;
} }
// Split into upcoming and past by date, so an event earlier today still // Split into upcoming and past by date, so an event earlier today still
// counts as upcoming. Upcoming earliest first, past most recent first. // counts as upcoming. Upcoming earliest first, past most recent first.
var today = DateOnly.FromDateTime(DateTime.Today); var today = DateOnly.FromDateTime(DateTime.Today);
_upcoming = events _upcoming =
.Where(e => DateOnly.FromDateTime(e.Start) >= today) [
.OrderBy(e => e.Start) .. events
.ToList(); .Where(@event => DateOnly.FromDateTime(@event.Start) >= today)
_past = events .OrderBy(@event => @event.Start)
.Where(e => DateOnly.FromDateTime(e.Start) < today) ];
.OrderByDescending(e => e.Start) _past =
.ToList(); [
.. 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> <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> <p>Zurzeit gibt es keine Fragen.</p>
} }
+26 -11
View File
@@ -1,13 +1,18 @@
using Elternbeirat.Contracts; using Elternbeirat.Contracts;
using Elternbeirat.PocketBase; using Elternbeirat.PocketBase;
using Elternbeirat.Web.Shared;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
namespace Elternbeirat.Web.Features.Faqs; namespace Elternbeirat.Web.Features.Faqs;
public partial class FaqList public partial class FaqList
{ {
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load FAQs from PocketBase.")] [LoggerMessage(
private static partial void LogLoadFailed(ILogger logger, Exception exception); 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 // 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. // topic in PocketBase still shows up rather than being silently dropped.
@@ -21,28 +26,38 @@ public partial class FaqList
}; };
[Inject] [Inject]
private PocketBaseClient PocketBase { get; set; } = default!; private PocketBaseClient PocketBase { get; set; } = null!;
[Inject] [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 = []; 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() protected override async Task OnInitializedAsync()
{ {
try try
{ {
var faqs = await PocketBase.GetFaqsAsync(); var faqs = await PocketBase.GetFaqsAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
_groups = [.. faqs.GroupBy(faq => faq.Topic)]; _groups = [.. faqs.GroupBy(faq => faq.Topic)];
} }
catch (HttpRequestException ex) catch (PocketBaseUnavailableException exception)
{ {
// Source unreachable -> show an empty page instead of a 500. The page // An empty page would claim there are no questions. The site works, its
// stays up; the "keine Fragen" note is rendered. // data store is down: 503 and an honest note.
LogLoadFailed(Logger, ex); LogSourceUnavailable(Logger, exception);
_unavailable = true;
SourceUnavailable.SetStatus(HttpContext);
} }
} }
private static string TopicLabel(string topic) => private static string TopicLabel(string topic)
TopicLabels.TryGetValue(topic, out var label) ? label : topic; => TopicLabels.GetValueOrDefault(topic, topic);
} }
+10 -6
View File
@@ -8,8 +8,8 @@ public partial class Home
{ {
[LoggerMessage( [LoggerMessage(
Level = LogLevel.Warning, Level = LogLevel.Warning,
Message = "Could not load the home page from PocketBase.")] Message = "Could not load the home page from PocketBase; embeds are omitted.")]
private static partial void LogLoadFailed( private static partial void LogSourceUnavailable(
ILogger logger, ILogger logger,
Exception exception); Exception exception);
@@ -19,6 +19,9 @@ public partial class Home
[Inject] [Inject]
private ILogger<Home> Logger { get; set; } = null!; 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 // 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. // "home" page's embed field in PocketBase, not from hard-coded markup.
private IReadOnlyList<string> _embed = []; private IReadOnlyList<string> _embed = [];
@@ -27,14 +30,15 @@ public partial class Home
{ {
try try
{ {
var pages = await PocketBase.GetPagesAsync(); var pages = await PocketBase.GetPagesAsync(HttpContext?.RequestAborted ?? default);
var home = pages.FirstOrDefault(page => Page.IsHomeSlug(page.Slug)); var home = pages.FirstOrDefault(page => Page.IsHomeSlug(page.Slug));
_embed = home?.Embed ?? []; _embed = home?.Embed ?? [];
} }
catch (HttpRequestException exception) catch (PocketBaseUnavailableException exception)
{ {
// Source unreachable -> render the intro without embeds instead of a 500. // Only the embeds fail: render the static intro without them instead of a
LogLoadFailed(Logger, exception); // 500. The home page's own text is markup, so it stays intact.
LogSourceUnavailable(Logger, exception);
} }
} }
} }
@@ -1,14 +1,18 @@
@page "/{Slug}" @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> <PageTitle>@_page.Title</PageTitle>
<article> <article>
<h1>@_page.Title</h1>
@Body @Body
</article> </article>
<PageEmbeds Embed="_page.Embed" /> <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 public partial class ContentPage
{ {
[LoggerMessage( [LoggerMessage(
Level = LogLevel.Warning, Level = LogLevel.Error,
Message = "Could not load page '{slug}' from PocketBase.")] Message = "Could not load page '{Slug}' from PocketBase; content source is unavailable.")]
private static partial void LogLoadFailed( private static partial void LogSourceUnavailable(
ILogger logger, ILogger logger,
string slug, string slug,
Exception exception); Exception exception);
@@ -24,11 +24,19 @@ public partial class ContentPage
[Inject] [Inject]
private ILogger<ContentPage> Logger { get; set; } = null!; private ILogger<ContentPage> Logger { get; set; } = null!;
[Inject]
private NavigationManager Navigation { get; set; } = null!;
[CascadingParameter] [CascadingParameter]
private HttpContext? HttpContext { get; set; } private HttpContext? HttpContext { get; set; }
private Page? _page; 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 // The page body rendered from Markdown to HTML, ready to emit as a
// MarkupString in the markup. // MarkupString in the markup.
private MarkupString Body => (MarkupString)Markdown.ToHtml(_page?.Body); private MarkupString Body => (MarkupString)Markdown.ToHtml(_page?.Body);
@@ -37,24 +45,23 @@ public partial class ContentPage
{ {
try try
{ {
var pages = await PocketBase.GetPagesAsync(); var pages = await PocketBase.GetPagesAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
_page = pages.FirstOrDefault( _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 // The site works, its data store is down: 503, not 404.
// 404 branch below serves the friendly /not-found page. LogSourceUnavailable(Logger, Slug, exception);
LogLoadFailed(Logger, Slug, ex); _unavailable = true;
_page = null; SourceUnavailable.SetStatus(HttpContext);
return;
} }
// Unknown slug (or unreachable source) -> 404, so if (_page is null)
// UseStatusCodePagesWithReExecute serves the /not-found page instead of an
// empty 200 response.
if (_page is null && HttpContext is not 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}" @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> <PageTitle>@_post.Title</PageTitle>
<nav>
<a href="/posts">&larr; Alle Beiträge</a>
</nav>
<article> <article>
<p class="post-meta"> <header>
<a href="/posts">&larr; Alle Beiträge</a> <h1>@_post.Title</h1>
<time datetime="@_post.Date.ToString("yyyy-MM-dd")"> <time class="post-meta" datetime="@_post.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)">
@_post.Date.ToString("d. MMMM yyyy", German) @_post.Date.ToString("d. MMMM yyyy", Cultures.German)
</time> </time>
</p> </header>
@Body @Body
</article> </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.Contracts;
using Elternbeirat.PocketBase; using Elternbeirat.PocketBase;
using Elternbeirat.Web.Shared; using Elternbeirat.Web.Shared;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
namespace Elternbeirat.Web.Features.Posts; namespace Elternbeirat.Web.Features.Posts;
public partial class PostDetail public partial class PostDetail
{ {
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE"); [LoggerMessage(
Level = LogLevel.Error,
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load post '{slug}' from PocketBase.")] Message = "Could not load post '{Slug}' from PocketBase; content source is unavailable.")]
private static partial void LogLoadFailed(ILogger logger, string slug, Exception exception); private static partial void LogSourceUnavailable(
ILogger logger,
string slug,
Exception exception);
[Parameter] [Parameter]
public string Slug { get; set; } = string.Empty; public string Slug { get; set; } = string.Empty;
[Inject] [Inject]
private PocketBaseClient PocketBase { get; set; } = default!; private PocketBaseClient PocketBase { get; set; } = null!;
[Inject] [Inject]
private ILogger<PostDetail> Logger { get; set; } = default!; private ILogger<PostDetail> Logger { get; set; } = null!;
[Inject]
private NavigationManager Navigation { get; set; } = null!;
[CascadingParameter] [CascadingParameter]
private HttpContext? HttpContext { get; set; } private HttpContext? HttpContext { get; set; }
private Post? _post; 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 // The post body rendered from Markdown to HTML, ready to emit as a
// MarkupString in the markup. // MarkupString in the markup.
private MarkupString Body => (MarkupString)Markdown.ToHtml(_post?.Body); private MarkupString Body => (MarkupString)Markdown.ToHtml(_post?.Body);
@@ -36,24 +45,23 @@ public partial class PostDetail
{ {
try try
{ {
var posts = await PocketBase.GetPostsAsync(); var posts = await PocketBase.GetPostsAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
_post = posts.FirstOrDefault( _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 // The site works, its data store is down: 503, not 404.
// 404 branch below serves the friendly /not-found page. LogSourceUnavailable(Logger, Slug, exception);
LogLoadFailed(Logger, Slug, ex); _unavailable = true;
_post = null; SourceUnavailable.SetStatus(HttpContext);
return;
} }
// Unknown slug (or unreachable source) -> 404, so if (_post is null)
// UseStatusCodePagesWithReExecute serves the /not-found page instead of an
// empty 200 response.
if (_post is null && HttpContext is not 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> <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> <p>Zurzeit gibt es keine Beiträge.</p>
} }
@@ -15,8 +19,8 @@ else
{ {
<li> <li>
<a href="@($"/posts/{post.Slug}")">@post.Title</a> <a href="@($"/posts/{post.Slug}")">@post.Title</a>
<time datetime="@post.Date.ToString("yyyy-MM-dd")"> <time datetime="@post.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)">
@post.Date.ToString("d. MMMM yyyy", German) @post.Date.ToString("d. MMMM yyyy", Cultures.German)
</time> </time>
</li> </li>
} }
@@ -1,36 +1,48 @@
using System.Globalization;
using Elternbeirat.Contracts; using Elternbeirat.Contracts;
using Elternbeirat.PocketBase; using Elternbeirat.PocketBase;
using Elternbeirat.Web.Shared;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
namespace Elternbeirat.Web.Features.Posts; namespace Elternbeirat.Web.Features.Posts;
public partial class PostList public partial class PostList
{ {
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not load posts from PocketBase.")] [LoggerMessage(
private static partial void LogLoadFailed(ILogger logger, Exception exception); Level = LogLevel.Error,
Message = "Could not load posts from PocketBase; content source is unavailable.")]
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE"); private static partial void LogSourceUnavailable(
ILogger logger,
Exception exception);
[Inject] [Inject]
private PocketBaseClient PocketBase { get; set; } = default!; private PocketBaseClient PocketBase { get; set; } = null!;
[Inject] [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 = []; 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() protected override async Task OnInitializedAsync()
{ {
try 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 // An empty list would claim there are no posts. The site works, its
// stays up; the "keine Beiträge" note is rendered. // data store is down: 503 and an honest note.
LogLoadFailed(Logger, ex); 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 // comes from configuration: appsettings for local dev, the PocketBase__BaseUrl
// env var on the server (see compose.yaml). // env var on the server (see compose.yaml).
var pocketBaseUrl = builder.Configuration["PocketBase:BaseUrl"] 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 => builder.Services.AddHttpClient<PocketBaseClient>(client =>
client.BaseAddress = new Uri(pocketBaseUrl)); 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. // as HTTP and with the proxy IP instead of the client IP.
// KnownNetworks/KnownProxies are deliberately empty because only NPM reaches // KnownNetworks/KnownProxies are deliberately empty because only NPM reaches
// the container. // the container.
app.UseForwardedHeaders(new ForwardedHeadersOptions app.UseForwardedHeaders(
{ new ForwardedHeadersOptions
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto, {
KnownIPNetworks = { }, ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
KnownProxies = { } });
});
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment() is false)
{ {
app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseExceptionHandler("/Error", createScopeForErrors: true);
// No UseHsts() and no UseHttpsRedirection(): NPM sets HSTS and terminates // No UseHsts() and no UseHttpsRedirection(): NPM sets HSTS and terminates
// TLS. Both here would create a redirect loop behind the proxy. // 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.UseAntiforgery();
app.MapStaticAssets(); app.MapStaticAssets();
@@ -49,14 +52,14 @@ app.MapRazorComponents<App>();
// Subscribable calendar feed of all events. A minimal API endpoint rather than // 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 // 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. // 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; IReadOnlyList<Event> events;
try try
{ {
events = await pocketBase.GetEventsAsync(); events = await pocketBase.GetEventsAsync(token);
} }
catch (HttpRequestException) catch (PocketBaseUnavailableException)
{ {
events = []; 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; using Elternbeirat.Contracts;
namespace Elternbeirat.Web.Shared; namespace Elternbeirat.Web.Shared;
@@ -22,11 +21,6 @@ public static class EventFormat
/// </summary> /// </summary>
private const string ShortDate = "d. MMMM yyyy"; 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> /// <summary>
/// Formats the date range of an event. /// Formats the date range of an event.
/// </summary> /// </summary>
@@ -54,7 +48,7 @@ public static class EventFormat
(var start, null, var hasTime) (var start, null, var hasTime)
=> Stamp(start, LongDate, hasTime), => Stamp(start, LongDate, hasTime),
(var start, { } end, true) when end.Date == start.Date (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 (var start, { } end, false) when end.Date == start.Date
=> Stamp(start, LongDate, withTime: false), => Stamp(start, LongDate, withTime: false),
(var start, { } end, var hasTime) (var start, { } end, var hasTime)
@@ -78,6 +72,6 @@ public static class EventFormat
/// </returns> /// </returns>
private static string Stamp(DateTime value, string dateFormat, bool withTime) private static string Stamp(DateTime value, string dateFormat, bool withTime)
=> withTime => withTime
? value.ToString(dateFormat + ", HH:mm", German) + " Uhr" ? value.ToString(dateFormat + ", HH:mm", Cultures.German) + " Uhr"
: value.ToString(dateFormat, German); : 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
@using System.Net.Http.Json @using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Forms