- {t('hero.slides.processing')}
+
+ {image.failed ? null : }
+ {image.failed ? t('hero.slides.failed') : t('hero.slides.processing')}
) : image ? (
})
diff --git a/frontend/src/features/hero/services/hooks.ts b/frontend/src/features/hero/services/hooks.ts
index 1f9edf6..302ba60 100644
--- a/frontend/src/features/hero/services/hooks.ts
+++ b/frontend/src/features/hero/services/hooks.ts
@@ -40,3 +40,12 @@ export function useDeleteHeroImage() {
mutationFn: (imageId) => api.delete
(`/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({
+ mutationFn: (imageId) => api.post(`/api/v1/hero/images/${imageId}/retry`, {}),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: HERO_KEY }),
+ });
+}
diff --git a/frontend/src/features/hero/services/types.ts b/frontend/src/features/hero/services/types.ts
index 57b25df..eb6cb41 100644
--- a/frontend/src/features/hero/services/types.ts
+++ b/frontend/src/features/hero/services/types.ts
@@ -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 {
diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json
index 425ed31..a81589d 100644
--- a/frontend/src/i18n/locales/en/translation.json
+++ b/frontend/src/i18n/locales/en/translation.json
@@ -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",
diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json
index 4847396..ec94397 100644
--- a/frontend/src/i18n/locales/nl/translation.json
+++ b/frontend/src/i18n/locales/nl/translation.json
@@ -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",
diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json
index 1898795..20a147d 100644
--- a/openapi/slpsoftware.v1.json
+++ b/openapi/slpsoftware.v1.json
@@ -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": {
diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroFocusSaveTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroFocusSaveTests.cs
index cc3a9f7..8788732 100644
--- a/src/SlpModularCms.Modules.Hero.Tests/HeroFocusSaveTests.cs
+++ b/src/SlpModularCms.Modules.Hero.Tests/HeroFocusSaveTests.cs
@@ -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();
+ }
}
diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroTestRig.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroTestRig.cs
index b104c27..b82592f 100644
--- a/src/SlpModularCms.Modules.Hero.Tests/HeroTestRig.cs
+++ b/src/SlpModularCms.Modules.Hero.Tests/HeroTestRig.cs
@@ -32,6 +32,7 @@ public sealed class HeroTestRig : IDisposable
public MagickImageProcessor Processor { get; }
public MediaStatus Status { get; } = new();
public IIndexHtmlCache IndexCache { get; } = Substitute.For();
+ 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.Instance, Time, IndexCache);
+ Images = new HeroImageService(guard, Processor, Store, gate, Repository, mediaOptions, NullLogger.Instance, Time, IndexCache, Signal);
Service = new HeroService(Repository, Images, Options.Create(HeroOptions), NullLogger.Instance, Time, IndexCache);
Public = new PublicHeroService(Repository, Options.Create(HeroOptions), Time);
Cleanup = new HeroMediaCleanup(Repository, Store, mediaOptions, NullLogger.Instance, Time);
diff --git a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs
index 4349f2e..21a0c0b 100644
--- a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs
+++ b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs
@@ -95,6 +95,23 @@ public class HeroImagesController(IHeroImageService service, IOptionsLets the background renderer try an image it gave up on again.
+ [HttpPost("{id:guid}/retry")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task 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)]
diff --git a/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs b/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs
index 847a597..75a98a0 100644
--- a/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs
+++ b/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs
@@ -24,7 +24,8 @@ public record HeroImageDto(
FocusDto? TallFocus,
string Src,
IReadOnlyList Variants,
- bool Processing = false);
+ bool Processing = false,
+ bool Failed = false);
public record HeroButtonDto(string Label, string Target);
diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs
index 2f708f4..be6076c 100644
--- a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs
+++ b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs
@@ -40,6 +40,13 @@ public interface IHeroImageService
///
void ApplyFocus(HeroImage image, HeroFocusRequest request);
+ /// True when the background renderer gave up on the image after a few failed tries (until a retry or a restart).
+ bool IsRenderFailed(Guid imageId);
+
+ /// Lets the background renderer try an image it gave up on again.
+ /// There is no such image.
+ Task RetryRenderAsync(Guid imageId, CancellationToken cancellationToken);
+
/// Wakes the background renderer: there is an image whose set is missing or does not match its focus.
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 RenderNextPendingAsync(IReadOnlySet skip, CancellationToken cancellationToken)
{
var image = (await repository.GetImagesNeedingRenderAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id));
diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroRenderService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroRenderService.cs
index b5fde55..b28f88b 100644
--- a/src/SlpModularCms.Modules.Hero/Services/HeroRenderService.cs
+++ b/src/SlpModularCms.Modules.Hero/Services/HeroRenderService.cs
@@ -21,6 +21,20 @@ public sealed class HeroRenderSignal
}
}
+ /// How often the renderer may try an image before it gives up on it (until a retry or a restart).
+ public const int MaxAttempts = 3;
+
+ private readonly System.Collections.Concurrent.ConcurrentDictionary _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 GivenUp() => _failures.Where(f => f.Value >= MaxAttempts).Select(f => f.Key).ToHashSet();
+
+ /// Forgets the failures of an image (after a success, a retry or a new upload of the same photo).
+ public void Reset(Guid imageId) => _failures.TryRemove(imageId, out _);
+
/// Waits for a signal or for the timeout, whichever comes first.
public Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken) => _signal.WaitAsync(timeout, cancellationToken);
}
@@ -33,8 +47,6 @@ public sealed class HeroRenderSignal
///
public sealed class HeroRenderService(IServiceScopeFactory scopes, HeroRenderSignal signal, ILogger logger) : BackgroundService
{
- private const int MaxAttempts = 3;
- private readonly Dictionary _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);
}
}
}
diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroService.cs
index 22946ff..40294d5 100644
--- a/src/SlpModularCms.Modules.Hero/Services/HeroService.cs
+++ b/src/SlpModularCms.Modules.Hero/Services/HeroService.cs
@@ -36,7 +36,16 @@ public class HeroService(
private readonly ITextCatalog _texts = texts ?? TextCatalog.Default;
public async Task 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));
+
+ /// Marks the images the background renderer gave up on (that state lives in memory, not in the database).
+ 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 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)