Hero-admin: voortgangsindicator voor foto's die worden verwerkt, mislukt-melding met opnieuw proberen

Spinner per foto zonder varianten, totaal met voortgangsbalk (aria-valuenow/max), uitleg dat de hero al is opgeslagen, bij 3 mislukte pogingen een melding met 'Opnieuw proberen' (POST /hero/images/{id}/retry; foutstatus staat in het geheugen van de renderer). Test dat een refetch van 5 s onopgeslagen wijzigingen niet overschrijft.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 21:41:29 +01:00
co-authored by Claude Sonnet 5.5
parent 852a162bc3
commit 49302c3228
16 changed files with 323 additions and 15 deletions
@@ -0,0 +1,68 @@
import { Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { useRetryHeroImage } from '../services/hooks';
import type { HeroAdminDto } from '../services/types';
/** A spinner that stands still for people who asked for less motion. */
export function Spinner({ className = 'size-4' }: { className?: string }) {
return <Loader2 className={`${className} animate-spin motion-reduce:animate-none`} aria-hidden="true" />;
}
/**
* Shown above the form while photos of the saved hero are still being prepared in the background: how many are ready,
* what that means for the website, and a way to try again for a photo that failed.
*/
export function ProcessingStatus({ hero }: { hero: HeroAdminDto }) {
const { t } = useTranslation();
const retry = useRetryHeroImage();
const total = hero.slides.length;
const waiting = hero.slides.filter((s) => s.image.processing);
if (waiting.length === 0) return null;
const done = total - waiting.length;
const failed = waiting.filter((s) => s.image.failed);
const working = waiting.length - failed.length;
return (
<div className="space-y-3 rounded-md border bg-muted/40 p-4" data-testid="hero-processing">
{working > 0 && (
<div className="space-y-2" role="status">
<p className="flex items-center gap-2 text-sm font-medium">
<Spinner />
<span data-testid="hero-processing-count">{t('hero.processing.count', { done, total })}</span>
</p>
<div
role="progressbar"
aria-label={t('hero.processing.label')}
aria-valuemin={0}
aria-valuemax={total}
aria-valuenow={done}
aria-valuetext={t('hero.processing.count', { done, total })}
className="h-2 w-full overflow-hidden rounded bg-muted"
data-testid="hero-processing-bar"
>
<div className="h-full bg-primary transition-all" style={{ width: `${total === 0 ? 0 : (done / total) * 100}%` }} />
</div>
<p className="text-sm text-muted-foreground">{t('hero.processing.explain')}</p>
</div>
)}
{failed.length > 0 && (
<div className="space-y-2" role="alert" data-testid="hero-processing-failed">
<p className="text-sm font-medium text-destructive">{t('hero.processing.failed', { count: failed.length })}</p>
<p className="text-sm text-muted-foreground">{t('hero.processing.failedHint')}</p>
<Button
type="button"
variant="outline"
size="sm"
disabled={retry.isPending}
onClick={() => failed.forEach((s) => retry.mutate(s.imageId))}
data-testid="hero-processing-retry"
>
{t('hero.processing.retry')}
</Button>
</div>
)}
</div>
);
}
@@ -16,6 +16,7 @@ const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({
{ ratio: 'tall', width: 640, height: 800, type: 'image/webp', url: '/media/hero/0123456789abcdef/tall-640.webp' },
],
processing: false,
failed: false,
});
export const emptyHero = (): HeroAdminDto => ({
@@ -57,6 +58,7 @@ export const resetMockHero = (): void => {
saved = [];
uploads = 0;
uploadFailure = null;
retried = [];
};
export const setMockHero = (next: HeroAdminDto): void => {
@@ -64,6 +66,9 @@ export const setMockHero = (next: HeroAdminDto): void => {
images = Object.fromEntries(next.slides.map((s) => [s.imageId, s.image]));
};
let retried: string[] = [];
export const getRetriedImages = (): string[] => retried;
export const getSavedHeroRequests = (): HeroSaveRequest[] => saved;
export const failNextUpload = (failure: { status: number; error: string; message: string } | null): void => {
@@ -107,6 +112,11 @@ export const heroHandlers = [
return HttpResponse.json(hero);
}),
http.post(`${API_BASE}/api/v1/hero/images/:id/retry`, ({ params }) => {
retried.push(String(params.id));
return new HttpResponse(null, { status: 204 });
}),
http.post(`${API_BASE}/api/v1/hero/images`, () => {
if (uploadFailure) {
const { status, error, message } = uploadFailure;
@@ -5,7 +5,7 @@ import { http, HttpResponse } from 'msw';
import { server } from '@/mocks/server';
import { API_BASE } from '@/features/auth/mocks/fixtures';
import { renderApp, mockAuthenticated } from '@/test/utils';
import { emptyHero, failNextUpload, getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers';
import { emptyHero, failNextUpload, getRetriedImages, getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers';
import { _resetSetupStatusCache } from '@/router';
const T = { timeout: 10000 };
@@ -41,6 +41,59 @@ describe('Hero page', () => {
expect(screen.getByTestId('hero-slide-0-focus')).toBeDisabled();
});
it('shows how many photos are ready, with an accessible progress bar, and hides it when all are ready', async () => {
const waiting = (n: number) => ({ ...slide(n), image: { ...slide(n).image, variants: [], src: '', processing: true } });
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), waiting(2), waiting(3)] });
await openPage();
expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/1 van 3|1 of 3/);
const bar = screen.getByRole('progressbar');
expect(bar).toHaveAttribute('aria-valuenow', '1');
expect(bar).toHaveAttribute('aria-valuemax', '3');
});
it('keeps unsaved edits when the background refresh brings a finished photo', async () => {
const waiting = { ...slide(1), image: { ...slide(1).image, variants: [], src: '', processing: true } };
setMockHero({ ...emptyHero(), id: 'h1', title: 'Oude titel', slides: [waiting] });
await openPage();
expect(await screen.findByTestId('hero-slide-0-processing', {}, T)).toBeInTheDocument();
const title = screen.getByTestId('hero-title-input');
await userEvent.clear(title);
await userEvent.type(title, 'Nieuwe titel');
const alt = screen.getByTestId('hero-slide-0-alt');
await userEvent.clear(alt);
await userEvent.type(alt, 'Mijn eigen alt');
// The server finishes the photo; the page asks again by itself (every 5 seconds).
setMockHero({ ...emptyHero(), id: 'h1', title: 'Oude titel', slides: [slide(1)] });
await waitFor(() => expect(screen.queryByTestId('hero-slide-0-processing')).not.toBeInTheDocument(), { timeout: 12000 });
expect(screen.getByTestId('hero-title-input')).toHaveValue('Nieuwe titel');
expect(screen.getByTestId('hero-slide-0-alt')).toHaveValue('Mijn eigen alt');
expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled();
}, 20000);
it('does not show the progress panel when every photo is ready', async () => {
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
await openPage();
expect(screen.queryByTestId('hero-processing')).not.toBeInTheDocument();
});
it('shows a failed photo with a retry that asks the server to try again', async () => {
const failed = { ...slide(1), image: { ...slide(1).image, variants: [], src: '', processing: true, failed: true } };
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [failed] });
await openPage();
await userEvent.click(await screen.findByTestId('hero-processing-retry', {}, T));
await waitFor(() => expect(getRetriedImages()).toEqual([failed.imageId]), T);
expect(screen.getByTestId('hero-processing-failed')).toBeInTheDocument();
});
it('is reachable from the navigation for an administrator', async () => {
mockAuthenticated();
renderApp('/dashboard');
@@ -12,6 +12,7 @@ import { FieldError } from '@/components/ui/FieldError';
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
import { FocusDialog } from '../components/FocusDialog';
import { ProcessingStatus, Spinner } from '../components/ProcessingStatus';
import { mediaUrl } from '../lib/media';
import { fromLocalInput, heroFormSchema, toLocalInput, type HeroFormData } from '../schemas/hero';
import { useHero, useSaveHero, useUploadHeroImage } from '../services/hooks';
@@ -113,6 +114,7 @@ export function HeroPage() {
<Button variant="outline" onClick={() => void refetch()}>{t('common.retry')}</Button>
</div>
)}
{hero && <ProcessingStatus hero={hero} />}
{hero && <HeroEditor key={hero.id ?? 'new'} hero={hero} />}
</div>
);
@@ -300,8 +302,13 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
return (
<li key={field.id} className="flex flex-wrap items-start gap-3 rounded-md border p-3" data-testid={`hero-slide-${index}`}>
{image && image.variants.length === 0 ? (
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted p-1 text-center text-xs" title={t('hero.slides.processingHint')} data-testid={`hero-slide-${index}-processing`}>
{t('hero.slides.processing')}
<div
className={`flex h-20 w-28 flex-col items-center justify-center gap-1 rounded p-1 text-center text-xs ${image.failed ? 'bg-destructive/10 text-destructive' : 'bg-muted'}`}
title={t('hero.slides.processingHint')}
data-testid={`hero-slide-${index}-processing`}
>
{image.failed ? null : <Spinner />}
{image.failed ? t('hero.slides.failed') : t('hero.slides.processing')}
</div>
) : image ? (
<img src={thumbnail(image)} alt="" className="h-20 w-28 rounded object-cover" />
@@ -40,3 +40,12 @@ export function useDeleteHeroImage() {
mutationFn: (imageId) => api.delete<void>(`/api/v1/hero/images/${imageId}`),
});
}
/** Asks the server to try an image again that the background renderer gave up on. */
export function useRetryHeroImage() {
const queryClient = useQueryClient();
return useMutation<void, Error, string>({
mutationFn: (imageId) => api.post<void>(`/api/v1/hero/images/${imageId}/retry`, {}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: HERO_KEY }),
});
}
@@ -25,6 +25,8 @@ export interface HeroImageDto {
variants: HeroVariantDto[];
/** The variants of this image are still being cut in the background; it is not published yet. */
processing: boolean;
/** The background renderer gave up on this image after a few tries; it can be retried. */
failed: boolean;
}
export interface HeroButtonDto {
+11 -1
View File
@@ -657,7 +657,17 @@
"ceiling": "Only the first {{max}} images are shown on the website.",
"focusPending": "Focus changed, not saved yet.",
"processing": "Processing…",
"processingHint": "The image is being prepared in the background; it appears on the website as soon as it is ready."
"processingHint": "The image is being prepared in the background; it appears on the website as soon as it is ready.",
"failed": "Failed"
},
"processing": {
"count": "{{done}} of {{total}} photos processed",
"label": "Progress of processing the photos",
"explain": "The hero has been saved. The photos are prepared one by one in the background and go live as soon as they are ready. Until the first photo is ready the website keeps showing the baked hero. You do not have to keep this page open.",
"failed_one": "Processing {{count}} photo failed.",
"failed_other": "Processing {{count}} photos failed.",
"failedHint": "The server tried three times. Try again, or upload the photo once more (the same photo is the same image).",
"retry": "Try again"
},
"focus": {
"title": "Focus and crop",
+11 -1
View File
@@ -657,7 +657,17 @@
"ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website.",
"focusPending": "Focus gewijzigd, nog niet opgeslagen.",
"processing": "Wordt verwerkt…",
"processingHint": "De afbeelding wordt klaargezet op de achtergrond; hij verschijnt op de website zodra hij klaar is."
"processingHint": "De afbeelding wordt klaargezet op de achtergrond; hij verschijnt op de website zodra hij klaar is.",
"failed": "Mislukt"
},
"processing": {
"count": "{{done}} van {{total}} foto’s verwerkt",
"label": "Voortgang van het verwerken van de foto’s",
"explain": "De hero is al opgeslagen. De foto’s worden één voor één klaargezet op de achtergrond en gaan live zodra ze klaar zijn. Tot de eerste foto klaar is, toont de website de ingebakken hero. Je hoeft deze pagina niet open te houden.",
"failed_one": "Het verwerken van {{count}} foto is mislukt.",
"failed_other": "Het verwerken van {{count}} foto’s is mislukt.",
"failedHint": "De server heeft het drie keer geprobeerd. Probeer het opnieuw, of upload de foto nog een keer (dezelfde foto is dezelfde afbeelding).",
"retry": "Opnieuw proberen"
},
"focus": {
"title": "Focus en uitsnede",
+47
View File
@@ -680,6 +680,10 @@
},
"HeroImageDto": {
"properties": {
"failed": {
"default": false,
"type": "boolean"
},
"focus": {
"$ref": "#/components/schemas/FocusDto"
},
@@ -3063,6 +3067,49 @@
]
}
},
"/api/v1/hero/images/{id}/retry": {
"post": {
"parameters": [
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"format": "uuid",
"type": "string"
}
}
],
"responses": {
"204": {
"description": "No Content"
},
"404": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Not Found"
}
},
"tags": [
"HeroImages"
]
}
},
"/api/v1/offerings": {
"get": {
"responses": {
@@ -156,4 +156,37 @@ public class HeroFocusSaveTests
results.Should().BeEmpty();
}
[Fact]
public async Task AnImageTheRendererGaveUpOn_IsShownAsFailed_AndARetryClearsIt()
{
using var rig = new HeroTestRig();
var dto = await rig.UploadWithoutRendering(HeroTestRig.Photo());
var id = Guid.Parse(dto.Id);
await rig.Service.SaveAsync(Save(id, null), HeroTestRig.Admin, default);
for (var i = 0; i < HeroRenderSignal.MaxAttempts; i++)
{
rig.Signal.RecordFailure(id);
}
var failed = (await rig.Service.GetAsync(default)).Slides[0].Image;
failed.Processing.Should().BeTrue();
failed.Failed.Should().BeTrue();
await rig.Images.RetryRenderAsync(id, default);
(await rig.Service.GetAsync(default)).Slides[0].Image.Failed.Should().BeFalse();
(await rig.RenderPending()).Should().Be(1);
}
[Fact]
public async Task ARetryForAnUnknownImage_IsNotFound()
{
using var rig = new HeroTestRig();
var act = async () => await rig.Images.RetryRenderAsync(Guid.NewGuid(), default);
await act.Should().ThrowAsync<HeroImageNotFoundException>();
}
}
@@ -32,6 +32,7 @@ public sealed class HeroTestRig : IDisposable
public MagickImageProcessor Processor { get; }
public MediaStatus Status { get; } = new();
public IIndexHtmlCache IndexCache { get; } = Substitute.For<IIndexHtmlCache>();
public HeroRenderSignal Signal { get; } = new();
public HeroImageService Images { get; }
public HeroService Service { get; }
public PublicHeroService Public { get; }
@@ -51,7 +52,7 @@ public sealed class HeroTestRig : IDisposable
Status.SetDirectory(true);
var gate = new MediaProcessingGate(mediaOptions);
var guard = new MediaUploadGuard(Processor, gate, Status, mediaOptions);
Images = new HeroImageService(guard, Processor, Store, gate, Repository, mediaOptions, NullLogger<HeroImageService>.Instance, Time, IndexCache);
Images = new HeroImageService(guard, Processor, Store, gate, Repository, mediaOptions, NullLogger<HeroImageService>.Instance, Time, IndexCache, Signal);
Service = new HeroService(Repository, Images, Options.Create(HeroOptions), NullLogger<HeroService>.Instance, Time, IndexCache);
Public = new PublicHeroService(Repository, Options.Create(HeroOptions), Time);
Cleanup = new HeroMediaCleanup(Repository, Store, mediaOptions, NullLogger<HeroMediaCleanup>.Instance, Time);
@@ -95,6 +95,23 @@ public class HeroImagesController(IHeroImageService service, IOptions<MediaOptio
}
}
/// <summary>Lets the background renderer try an image it gave up on again.</summary>
[HttpPost("{id:guid}/retry")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Retry(Guid id, CancellationToken cancellationToken)
{
try
{
await service.RetryRenderAsync(id, cancellationToken);
return NoContent();
}
catch (HeroImageNotFoundException)
{
return NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) });
}
}
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
@@ -24,7 +24,8 @@ public record HeroImageDto(
FocusDto? TallFocus,
string Src,
IReadOnlyList<HeroVariantDto> Variants,
bool Processing = false);
bool Processing = false,
bool Failed = false);
public record HeroButtonDto(string Label, string Target);
@@ -40,6 +40,13 @@ public interface IHeroImageService
/// </summary>
void ApplyFocus(HeroImage image, HeroFocusRequest request);
/// <summary>True when the background renderer gave up on the image after a few failed tries (until a retry or a restart).</summary>
bool IsRenderFailed(Guid imageId);
/// <summary>Lets the background renderer try an image it gave up on again.</summary>
/// <exception cref="HeroImageNotFoundException">There is no such image.</exception>
Task RetryRenderAsync(Guid imageId, CancellationToken cancellationToken);
/// <summary>Wakes the background renderer: there is an image whose set is missing or does not match its focus.</summary>
void NotifyPending();
@@ -77,6 +84,9 @@ public class HeroImageService(
var existing = await repository.GetImageBySha256Async(sha, cancellationToken);
if (existing is not null && await FilesExistAsync(existing, cancellationToken))
{
// The same photo again also gives up the failed state: the renderer tries it again when it is still pending.
signal?.Reset(existing.Id);
signal?.Notify();
return HeroMapping.ToImageDto(existing);
}
@@ -148,6 +158,15 @@ public class HeroImageService(
public void NotifyPending() => signal?.Notify();
public bool IsRenderFailed(Guid imageId) => signal?.IsGivenUp(imageId) ?? false;
public async Task RetryRenderAsync(Guid imageId, CancellationToken cancellationToken)
{
_ = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
signal?.Reset(imageId);
signal?.Notify();
}
public async Task<Guid?> RenderNextPendingAsync(IReadOnlySet<Guid> skip, CancellationToken cancellationToken)
{
var image = (await repository.GetImagesNeedingRenderAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id));
@@ -21,6 +21,20 @@ public sealed class HeroRenderSignal
}
}
/// <summary>How often the renderer may try an image before it gives up on it (until a retry or a restart).</summary>
public const int MaxAttempts = 3;
private readonly System.Collections.Concurrent.ConcurrentDictionary<Guid, int> _failures = new();
public int RecordFailure(Guid imageId) => _failures.AddOrUpdate(imageId, 1, (_, n) => n + 1);
public bool IsGivenUp(Guid imageId) => _failures.TryGetValue(imageId, out var n) && n >= MaxAttempts;
public IReadOnlySet<Guid> GivenUp() => _failures.Where(f => f.Value >= MaxAttempts).Select(f => f.Key).ToHashSet();
/// <summary>Forgets the failures of an image (after a success, a retry or a new upload of the same photo).</summary>
public void Reset(Guid imageId) => _failures.TryRemove(imageId, out _);
/// <summary>Waits for a signal or for the timeout, whichever comes first.</summary>
public Task<bool> WaitAsync(TimeSpan timeout, CancellationToken cancellationToken) => _signal.WaitAsync(timeout, cancellationToken);
}
@@ -33,8 +47,6 @@ public sealed class HeroRenderSignal
/// </summary>
public sealed class HeroRenderService(IServiceScopeFactory scopes, HeroRenderSignal signal, ILogger<HeroRenderService> logger) : BackgroundService
{
private const int MaxAttempts = 3;
private readonly Dictionary<Guid, int> _failures = [];
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
@@ -58,7 +70,7 @@ public sealed class HeroRenderService(IServiceScopeFactory scopes, HeroRenderSig
{
while (!stoppingToken.IsCancellationRequested)
{
var skip = _failures.Where(f => f.Value >= MaxAttempts).Select(f => f.Key).ToHashSet();
var skip = signal.GivenUp();
Guid? handled = null;
try
{
@@ -67,8 +79,8 @@ public sealed class HeroRenderService(IServiceScopeFactory scopes, HeroRenderSig
}
catch (HeroImageRenderException failure)
{
var attempts = _failures[failure.ImageId] = _failures.GetValueOrDefault(failure.ImageId) + 1;
logger.LogError(failure.InnerException, "Cutting the variants of hero image {ImageId} failed (attempt {Attempt} of {Max}).", failure.ImageId, attempts, MaxAttempts);
var attempts = signal.RecordFailure(failure.ImageId);
logger.LogError(failure.InnerException, "Cutting the variants of hero image {ImageId} failed (attempt {Attempt} of {Max}).", failure.ImageId, attempts, HeroRenderSignal.MaxAttempts);
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
continue;
}
@@ -83,7 +95,7 @@ public sealed class HeroRenderService(IServiceScopeFactory scopes, HeroRenderSig
return;
}
_failures.Remove(handled.Value);
signal.Reset(handled.Value);
}
}
}
@@ -36,7 +36,16 @@ public class HeroService(
private readonly ITextCatalog _texts = texts ?? TextCatalog.Default;
public async Task<HeroAdminDto> GetAsync(CancellationToken cancellationToken)
=> HeroMapping.ToAdmin(await repository.GetReadOnlyAsync(HeroLanguages.Default, cancellationToken), _time.GetUtcNow(), options.Value.MaxPublishedSlides);
=> WithFailures(HeroMapping.ToAdmin(await repository.GetReadOnlyAsync(HeroLanguages.Default, cancellationToken), _time.GetUtcNow(), options.Value.MaxPublishedSlides));
/// <summary>Marks the images the background renderer gave up on (that state lives in memory, not in the database).</summary>
private HeroAdminDto WithFailures(HeroAdminDto dto)
=> dto with
{
Slides = dto.Slides
.Select(s => imageService.IsRenderFailed(Guid.Parse(s.ImageId)) ? s with { Image = s.Image with { Failed = true } } : s)
.ToList(),
};
public async Task<HeroAdminDto> SaveAsync(HeroSaveRequest request, Guid callerId, CancellationToken cancellationToken)
{
@@ -128,7 +137,7 @@ public class HeroService(
imageService.NotifyPending();
logger.LogInformation("Hero {HeroId} {Action} by user {LastModifiedByUserId} ({Slides} slides)", hero.Id, created ? "Created" : "Updated", callerId, keep.Count);
return HeroMapping.ToAdmin(hero, now, options.Value.MaxPublishedSlides);
return WithFailures(HeroMapping.ToAdmin(hero, now, options.Value.MaxPublishedSlides));
}
private static void Apply(HeroContent hero, HeroSaveRequest r, DateTimeOffset now, Guid callerId)