Fix/pocketbase date timezone #33

Merged
Tom merged 9 commits from fix/pocketbase-date-timezone into main 2026-09-24 14:50:11 +02:00
25 changed files with 434 additions and 195 deletions
Showing only changes of commit e242eaf79a - Show all commits

No files matched your search

+36 -8
View File
@@ -38,14 +38,11 @@ public sealed class PocketBaseClient(HttpClient httpClient)
/// <returns>
/// The public pages, or an empty list if there are none.
/// </returns>
/// <exception cref="HttpRequestException">
/// PocketBase could not be reached or returned a non-success status code.
/// </exception>
/// <exception cref="JsonException">
/// The response could not be deserialized.
/// <exception cref="PocketBaseUnavailableException">
/// PocketBase could not be reached, timed out, or returned an unreadable response.
/// </exception>
/// <exception cref="OperationCanceledException">
/// <paramref name="token"/> was canceled or the request timed out.
/// <paramref name="token"/> was canceled by the caller.
/// </exception>
public Task<IReadOnlyList<Page>> GetPagesAsync(CancellationToken token = default)
=> GetRecordsAsync<Page>("pages", "order", token);
@@ -73,15 +70,22 @@ public sealed class PocketBaseClient(HttpClient httpClient)
=> GetRecordsAsync<Event>("events", "start", token);
/// <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>
/// <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"/>
/// <returns>
/// The public FAQ entries, or an empty list if there are none.
/// </returns>
/// <inheritdoc cref="GetPagesAsync" path="/exception"/>
public Task<IReadOnlyList<Faq>> GetFaqsAsync(CancellationToken token = default)
=> GetRecordsAsync<Faq>("faqs", "topic", token);
=> GetRecordsAsync<Faq>("faqs", "topic,question", token);
/// <summary>
/// Gets all public records of a collection in a single request.
@@ -101,6 +105,12 @@ public sealed class PocketBaseClient(HttpClient httpClient)
/// <returns>
/// The public records, or an empty list if there are none.
/// </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>(
string collection,
string sort,
@@ -112,7 +122,25 @@ public sealed class PocketBaseClient(HttpClient httpClient)
+ $"?perPage=500&filter={Uri.EscapeDataString("public=true")}"
+ $"&sort={Uri.EscapeDataString(sort)}";
try
{
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
{
[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 @@
@if (_upcoming.Count > 0)
{
<section class="embed embed-events">
<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)
{
@@ -21,5 +16,5 @@
}
</ul>
<p class="embed-more"><a href="/events">Alle Termine <span aria-hidden="true">&rarr;</span></a></p>
}
</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 @@
@if (_faqs.Count > 0)
{
<section class="embed embed-faqs">
<h2>Häufige Fragen</h2>
@if (_faqs.Count == 0)
{
<p>Zurzeit gibt es keine Fragen.</p>
}
else
{
@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>
}
@@ -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 @@
@if (_latest.Count > 0)
{
<section class="embed embed-posts">
<h2>Aktuelle Beiträge</h2>
@if (_latest.Count == 0)
{
<p>Zurzeit gibt es keine Beiträge.</p>
}
else
{
<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>
}
@@ -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,6 +4,12 @@
<h1>Termine</h1>
@if (_unavailable)
{
<p>Die Termine sind gerade nicht erreichbar. Bitte später erneut versuchen.</p>
}
else
{
<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
@@ -54,3 +60,4 @@ else
}
</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>
<article>
<p class="post-meta">
<nav>
<a href="/posts">&larr; Alle Beiträge</a>
<time datetime="@_post.Date.ToString("yyyy-MM-dd")">
@_post.Date.ToString("d. MMMM yyyy", German)
</nav>
<article>
<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);
}
}
}
+13 -10
View File
@@ -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
app.UseForwardedHeaders(
new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
KnownIPNetworks = { },
KnownProxies = { }
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