Hero-module: hero beheren vanuit het CMS #17
@@ -28,3 +28,4 @@ Kept while Bryan was away (2026-11-16): no questions to him, a likely assumption
|
||||
| 22 | **Production seed**. | Not done; only the test hosts, with Bryan's password, after his go. | n/a | `scripts/Seed-Hero.ps1`, `docs/release-checklist-productie.md` section 4b |
|
||||
| 23 | What does the host write for a hero **without any slide** (SLP Software)? | A text-only region in the first HTML (so a CMS change is visible without JavaScript, LCP is the text): `h1.cms-hero-title` with an optional `span.cms-hero-tagline` and `span.cms-hero-title-lines` (title lines separated by `<br>`, no brand prefix), then `p.cms-hero-lead` (lead, line breaks as `<br>`) and `p.cms-hero-buttons` with `a.cms-hero-button`. Nothing to preload, and the preload region is left as built. A hero WITH slides but none usable stays empty (ASF unchanged). This is a per-site switch, `Hero:TextOnlyRegion`: on in the committed settings of the SLP site, off by default (so ASF keeps its baked hero when its CMS hero has no slide, as ASF asked). | A separate marker for the text region instead of a switch. | `HeroOptions.TextOnlyRegion`, `HeroPictureRenderer.Render` and `TextOnlyRegion`, `HeroHtmlTransform.ApplyAsync`, `Api.SlpSoftware/appsettings.json`, `HeroTextOnlyTests` |
|
||||
| 24 | Does the data block carry the hero when it has no slides? | Yes (intended): the site reads the hero from the data block, the baked block is `{}`. | n/a | `HeroPageModel`, `HeroDataContributor` |
|
||||
| 25 | **Variants are cut in the background**, not inside the upload or save request (2026-11-16, found on the ASF test host: saving 8 photos took 60 s+ on the Pi and the proxy cut it with a 504). | Upload and save return at once; `HeroRenderService` cuts one image at a time and switches an image to its new set when it is complete (old set stays live meanwhile); an image without a set is not published; a failing image is tried 3 times, then left until the next restart. Measured on a 20-core PC: upload 3.5-8.8 s and save of 8 changed focus points 39.6 s before, 0.1 s and 0.1 s after (the 37.5 s of cutting moved to the background, 4.7 s per photo). On the Pi: about 25-30 s per photo, 4 minutes for 8. | A longer proxy time-out is then not needed; if cutting should be faster, reduce the variant set or the AVIF effort. | `HeroImageService.RenderNextPendingAsync`, `HeroRenderService`, `HeroSaveTimingTests` |
|
||||
|
||||
+3
-2
@@ -10,7 +10,7 @@ Admin > **Hero** (Owner en Administrator, module `Hero`):
|
||||
- Maximaal twee knoppen met tekst en doel. Een doel is een `#anker`, een `/pad` of een `https://`-adres; andere waarden worden geweigerd.
|
||||
- Planning (aan of uit, van en tot). Buiten de planning, of uitgezet, toont de website zijn eigen ingebakken hero.
|
||||
- Slides: een afbeelding met verplichte beschrijving (alt-tekst) of de markering decoratief, volgorde, aan of uit per slide. Er is geen grens op het aantal slides; technisch publiceert de host er hoogstens `Hero:MaxPublishedSlides` (50).
|
||||
- Focus: per afbeelding een algemeen punt en zoom, en optioneel een eigen punt voor de liggende (`wide`, 3:2) en de staande (`tall`, 4:5) weergave. De host snijdt de varianten daaromheen uit. **Een wijziging van het focuspunt geldt pas als je de hero opslaat** (Bryan, 2026-11-16): het focus-venster houdt de wijziging lokaal in de admin (knop Toepassen, een markering bij de slide); bij Opslaan gaat ze mee in dezelfde aanvraag (`imageFocus`), de host snijdt dan de varianten opnieuw in nieuwe bestanden en bewaart hero en afbeeldingen in één keer. Verlaat je de pagina zonder op te slaan, dan vervalt de wijziging en is er niets aan de server veranderd. Mislukt een opslag nadat nieuwe bestanden zijn geschreven, dan verwijst niets ernaar en ruimt de opschoning ze na 7 dagen op; de oude bestanden blijven ook 7 dagen staan voor sites die nog oude data hebben.
|
||||
- Focus: per afbeelding een algemeen punt en zoom, en optioneel een eigen punt voor de liggende (`wide`, 3:2) en de staande (`tall`, 4:5) weergave. De host snijdt de varianten daaromheen uit. **Een wijziging van het focuspunt geldt pas als je de hero opslaat** (Bryan, 2026-11-16): het focus-venster houdt de wijziging lokaal in de admin (knop Toepassen, een markering bij de slide); bij Opslaan gaat ze mee in dezelfde aanvraag (`imageFocus`); de host bewaart hero en focus direct (onder een seconde) en snijdt de varianten daarna op de achtergrond in nieuwe bestanden. De afbeelding schakelt over naar de nieuwe set zodra die compleet is; tot die tijd blijft de oude set in beeld. Verlaat je de pagina zonder op te slaan, dan vervalt de wijziging en is er niets aan de server veranderd. Mislukt een opslag nadat nieuwe bestanden zijn geschreven, dan verwijst niets ernaar en ruimt de opschoning ze na 7 dagen op; de oude bestanden blijven ook 7 dagen staan voor sites die nog oude data hebben.
|
||||
|
||||
De admin toont alleen een badge Live of Niet live.
|
||||
|
||||
@@ -51,10 +51,11 @@ Een gegevensmap naast de site, buiten de webroot, waarin het account van de appl
|
||||
./scripts/Seed-Hero.ps1 -BaseUrl https://test.slpsoftware.nl -SeedFile ./scripts/hero-sls.json
|
||||
```
|
||||
|
||||
`hero-asf.json` bevat de 8 huidige foto's met alt-teksten en een eerste schatting van de focuspunten (door de ASF-sessie); Bryan past ze aan in de admin. `hero-sls.json` is de huidige SLP-hero (alleen tekst, twee knoppen). Het script uploadt eerst alle foto's (dezelfde foto is dezelfde afbeelding, dus een tweede run dupliceert niets) en slaat dan de hero in een keer op, met de focuspunten in dezelfde aanvraag (`imageFocus`): een focuspunt geldt pas bij het opslaan van de hero. Het slaat een CMS over dat al een hero heeft (`-Force` vervangt), vraagt het wachtwoord interactief (alleen voor een lokale host of testrun leest het `SEED_HERO_PASSWORD`) en gebruikt voor productie niets zonder Bryans go. Getest op PowerShell 7 en Windows PowerShell 5.1 tegen een lokale host, met de ASF-seed en `hero-sls.json`.
|
||||
`hero-asf.json` bevat de 8 huidige foto's met alt-teksten en een eerste schatting van de focuspunten (door de ASF-sessie); Bryan past ze aan in de admin. `hero-sls.json` is de huidige SLP-hero (alleen tekst, twee knoppen). Het script uploadt eerst alle foto's (de varianten worden daarna op de achtergrond gemaakt; het script wacht tot alles klaar is) (dezelfde foto is dezelfde afbeelding, dus een tweede run dupliceert niets) en slaat dan de hero in een keer op, met de focuspunten in dezelfde aanvraag (`imageFocus`): een focuspunt geldt pas bij het opslaan van de hero. Het slaat een CMS over dat al een hero heeft (`-Force` vervangt), vraagt het wachtwoord interactief (alleen voor een lokale host of testrun leest het `SEED_HERO_PASSWORD`) en gebruikt voor productie niets zonder Bryans go. Getest op PowerShell 7 en Windows PowerShell 5.1 tegen een lokale host, met de ASF-seed en `hero-sls.json`.
|
||||
|
||||
## Wat er achter de schermen gebeurt
|
||||
|
||||
- Verwerking op de achtergrond: een upload bewaart het origineel en geeft direct antwoord (`processing: true`, nog geen varianten, de afbeelding wordt niet gepubliceerd); `HeroRenderService` knipt de varianten, een afbeelding per keer (op een Raspberry Pi 4 ongeveer 25-30 s per foto), en pikt bij het opstarten en elke minuut werk op dat nog openstaat. Daardoor kapt de proxy-time-out (60 s) nooit een upload of een opslag af, en laat een afgebroken verzoek niets half bewaard achter (bestanden eerst, rij als laatste; een herhaling doet het gewoon opnieuw). De admin ververst zelf zolang er afbeeldingen worden verwerkt.
|
||||
- Upload: echt bestandstype aan de inhoud (geen SVG), grenzen op bytes, pixels, tijd en gelijktijdigheid; metadata (GPS) uit het opgeslagen origineel en alle varianten; varianten per verhouding rond het focuspunt, nooit groter dan de bron, in WebP (en AVIF waar het platform dat kan). Dezelfde foto nog een keer is hetzelfde plaatje (en herstelt verloren bestanden).
|
||||
- Oude bestanden (nieuwe focus, vervangen of ongebruikte foto) blijven 7 dagen en worden dan opgeschoond; een bestand dat nog gebruikt wordt, verdwijnt nooit.
|
||||
- Ondersteunde invoer: JPEG, PNG, WebP, GIF, BMP, TIFF en AVIF; HEIC alleen als aangegeven mogelijkheid van de bibliotheek (nog niet met een echt bestand getest).
|
||||
|
||||
@@ -15,6 +15,7 @@ const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({
|
||||
{ ratio: 'wide', width, height, type: 'image/webp', url: `/media/hero/0123456789abcdef/wide-${width}.webp` },
|
||||
{ ratio: 'tall', width: 640, height: 800, type: 'image/webp', url: '/media/hero/0123456789abcdef/tall-640.webp' },
|
||||
],
|
||||
processing: false,
|
||||
});
|
||||
|
||||
export const emptyHero = (): HeroAdminDto => ({
|
||||
|
||||
@@ -31,6 +31,16 @@ describe('Hero page', () => {
|
||||
expect(screen.getByTestId('hero-display-single')).toBeChecked();
|
||||
});
|
||||
|
||||
it('shows a placeholder, and no focus button, for an image whose variants are still being cut', async () => {
|
||||
const waiting = slide(1);
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [{ ...waiting, image: { ...waiting.image, variants: [], src: '', processing: true } }] });
|
||||
|
||||
await openPage();
|
||||
|
||||
expect(await screen.findByTestId('hero-slide-0-processing', {}, T)).toBeInTheDocument();
|
||||
expect(screen.getByTestId('hero-slide-0-focus')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('is reachable from the navigation for an administrator', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/dashboard');
|
||||
|
||||
@@ -299,7 +299,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
const decorative = watchedSlides[index]?.decorative ?? false;
|
||||
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 && 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>
|
||||
) : image ? (
|
||||
<img src={thumbnail(image)} alt="" className="h-20 w-28 rounded object-cover" />
|
||||
) : (
|
||||
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted text-xs">?</div>
|
||||
@@ -329,7 +333,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.down')} disabled={index === slides.fields.length - 1} onClick={() => slides.move(index, index + 1)} data-testid={`hero-slide-${index}-down`}>
|
||||
<ArrowDown className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button type="button" variant={focusEdits[field.imageId] ? 'default' : 'outline'} size="icon" aria-label={t('hero.slides.focus')} disabled={!image} onClick={() => setFocusImageId(field.imageId)} data-testid={`hero-slide-${index}-focus`}>
|
||||
<Button type="button" variant={focusEdits[field.imageId] ? 'default' : 'outline'} size="icon" aria-label={t('hero.slides.focus')} disabled={!image || image.variants.length === 0} onClick={() => setFocusImageId(field.imageId)} data-testid={`hero-slide-${index}-focus`}>
|
||||
<Crosshair className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="icon" aria-label={t('hero.slides.remove')} onClick={() => slides.remove(index)} data-testid={`hero-slide-${index}-remove`}>
|
||||
|
||||
@@ -9,6 +9,8 @@ export function useHero() {
|
||||
return useQuery<HeroAdminDto, Error>({
|
||||
queryKey: HERO_KEY,
|
||||
queryFn: () => api.get<HeroAdminDto>('/api/v1/hero/all'),
|
||||
// Images are cut in the background after an upload or a saved focus change: look again until they are all ready.
|
||||
refetchInterval: (query) => (query.state.data?.slides.some((s) => s.image.processing) ? 5000 : false),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface HeroImageDto {
|
||||
tallFocus: FocusDto | null;
|
||||
src: string;
|
||||
variants: HeroVariantDto[];
|
||||
/** The variants of this image are still being cut in the background; it is not published yet. */
|
||||
processing: boolean;
|
||||
}
|
||||
|
||||
export interface HeroButtonDto {
|
||||
|
||||
@@ -655,7 +655,9 @@
|
||||
"focus": "Set focus",
|
||||
"remove": "Remove from the hero",
|
||||
"ceiling": "Only the first {{max}} images are shown on the website.",
|
||||
"focusPending": "Focus changed, not saved yet."
|
||||
"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."
|
||||
},
|
||||
"focus": {
|
||||
"title": "Focus and crop",
|
||||
|
||||
@@ -655,7 +655,9 @@
|
||||
"focus": "Focus instellen",
|
||||
"remove": "Verwijderen uit de hero",
|
||||
"ceiling": "Alleen de eerste {{max}} afbeeldingen worden getoond op de website.",
|
||||
"focusPending": "Focus gewijzigd, nog niet opgeslagen."
|
||||
"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."
|
||||
},
|
||||
"focus": {
|
||||
"title": "Focus en uitsnede",
|
||||
|
||||
@@ -694,6 +694,10 @@
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"processing": {
|
||||
"default": false,
|
||||
"type": "boolean"
|
||||
},
|
||||
"src": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -156,6 +156,17 @@ $payload = [ordered]@{
|
||||
try {
|
||||
$saved = Invoke-RestMethod -Method Put -Uri "$api/hero" -Headers $headers -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($payload))
|
||||
Write-Host "saved hero $($saved.id) with $($saved.slides.Count) slide(s); live: $($saved.isLive)"
|
||||
# The variants of the photos are cut in the background (about half a minute per photo on a Raspberry Pi); a photo goes
|
||||
# live as soon as its set is ready. Wait for them so the script ends when the site shows everything (at most 15 minutes).
|
||||
$deadline = (Get-Date).AddMinutes(15)
|
||||
do {
|
||||
$state = Invoke-RestMethod -Method Get -Uri "$api/hero/all" -Headers $headers
|
||||
$waiting = @($state.slides | Where-Object { $_.image.processing }).Count
|
||||
if ($waiting -eq 0) { break }
|
||||
Write-Host "wait $waiting photo(s) are still being prepared in the background"
|
||||
Start-Sleep -Seconds 15
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
if ($waiting -eq 0) { Write-Host "ready all photos are prepared" } else { Write-Warning "$waiting photo(s) are still being prepared; they appear on the site by themselves." }
|
||||
}
|
||||
catch {
|
||||
Write-Error "Saving the hero failed: $($_.Exception.Message) $($_.ErrorDetails.Message)"
|
||||
|
||||
@@ -112,6 +112,16 @@ public class HeroAsfSiteE2ETests : IClassFixture<AsfSiteFactory>
|
||||
seed.GetProperty("buttons").EnumerateArray().Select(b => new HeroButtonRequest(b.GetProperty("label").GetString(), b.GetProperty("target").GetString())).ToList(),
|
||||
true, null, null, slides, focusEdits), caller, default));
|
||||
|
||||
await InScope(async sp =>
|
||||
{
|
||||
// The variants are cut by the background renderer in production; here it is run to the end at once.
|
||||
while (await sp.GetRequiredService<IHeroImageService>().RenderNextPendingAsync(new HashSet<Guid>(), default) is not null)
|
||||
{
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
var response = await client.GetAsync("/");
|
||||
var page = await response.Content.ReadAsStringAsync();
|
||||
var api = await client.GetStringAsync("/api/v1/hero");
|
||||
|
||||
@@ -133,6 +133,15 @@ public class HeroInjectionPipelineTests : IClassFixture<HeroInjectionFactory>
|
||||
await InScope(async sp => await sp.GetRequiredService<IHeroService>().SaveAsync(
|
||||
new HeroSaveRequest("Andrea Slop", "Lifestyle fotograaf · Huizen", null, "slideshow", [new HeroButtonRequest("Lees meer", "/over-mij")], true, null, null,
|
||||
[new HeroSlideRequest(null, Guid.Parse(image.Id), "Zwangerschapsfoto in de duinen")]), caller, default));
|
||||
await InScope(async sp =>
|
||||
{
|
||||
// The variants are cut by the background renderer in production; here it is run to the end at once.
|
||||
while (await sp.GetRequiredService<IHeroImageService>().RenderNextPendingAsync(new HashSet<Guid>(), default) is not null)
|
||||
{
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
var live = await client.GetAsync("/hero");
|
||||
var body = await live.Content.ReadAsStringAsync();
|
||||
|
||||
@@ -12,7 +12,7 @@ public class HeroFocusSaveTests
|
||||
=> new("Andrea Slop", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, imageId, "foto")], focus);
|
||||
|
||||
[Fact]
|
||||
public async Task TheLiveHero_KeepsItsAddresses_UntilTheHeroIsSavedWithTheNewFocus()
|
||||
public async Task TheLiveHero_KeepsItsOldSet_UntilTheNewSetIsCut_AndThenSwitchesToIt()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
@@ -20,19 +20,22 @@ public class HeroFocusSaveTests
|
||||
await rig.Service.SaveAsync(Save(id, null), HeroTestRig.Admin, default);
|
||||
var before = (await rig.Public.GetActiveAsync(default))!.Slides[0].Image.Src;
|
||||
|
||||
// Nothing but a save changes what is live: the focus travels with the save request.
|
||||
// The save returns without cutting anything: the old set stays live and the admin sees the image as processing.
|
||||
var saved = await rig.Service.SaveAsync(Save(id, [new HeroImageFocusRequest(id, new FocusDto(0.5, 0.5, 1), null, new FocusDto(1.0, 0.5, 1))]), HeroTestRig.Admin, default);
|
||||
(await rig.Public.GetActiveAsync(default))!.Slides[0].Image.Src.Should().Be(before);
|
||||
saved.Slides[0].Image.Processing.Should().BeTrue();
|
||||
|
||||
await rig.Service.SaveAsync(Save(id, [new HeroImageFocusRequest(id, new FocusDto(0.5, 0.5, 1), null, new FocusDto(1.0, 0.5, 1))]), HeroTestRig.Admin, default);
|
||||
(await rig.RenderPending()).Should().Be(1);
|
||||
var after = (await rig.Public.GetActiveAsync(default))!.Slides[0].Image;
|
||||
|
||||
var beforeSet = before.Split('/')[3];
|
||||
after.Variants.Should().OnlyContain(v => !v.Url.Contains(beforeSet), "a changed focus gives new addresses");
|
||||
after.FocusByRatio.Should().ContainKey("tall");
|
||||
(await rig.Service.GetAsync(default)).Slides[0].Image.Processing.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheOldFiles_StayOnDisk_AfterTheSave_UntilTheCleanUp()
|
||||
public async Task TheOldFiles_StayOnDisk_AfterTheSwitch_UntilTheCleanUp()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
@@ -41,11 +44,64 @@ public class HeroFocusSaveTests
|
||||
var oldVariant = image.Variants.First();
|
||||
|
||||
await rig.Service.SaveAsync(Save(id, [new HeroImageFocusRequest(id, new FocusDto(0.1, 0.1, 1.5))]), HeroTestRig.Admin, default);
|
||||
await rig.RenderPending();
|
||||
|
||||
(await rig.Store.ExistsAsync(oldVariant.Url["/media/".Length..], default)).Should().BeTrue("a site that still holds the old data keeps working for the retention time");
|
||||
rig.Db.HeroRetiredFiles.Should().ContainSingle(f => f.Kind == "set");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnUpload_ReturnsWithoutCuttingAnything_AndIsNotPublishedUntilItsSetExists()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var dto = await rig.UploadWithoutRendering(HeroTestRig.Photo());
|
||||
dto.Processing.Should().BeTrue();
|
||||
dto.Variants.Should().BeEmpty();
|
||||
await rig.Service.SaveAsync(Save(Guid.Parse(dto.Id), null), HeroTestRig.Admin, default);
|
||||
(await rig.Public.GetActiveAsync(default))!.Slides.Should().BeEmpty("a slide whose image is not ready is not published");
|
||||
|
||||
await rig.RenderPending();
|
||||
|
||||
(await rig.Public.GetActiveAsync(default))!.Slides.Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TwoFocusSaves_BeforeTheRenderRuns_AreCutOnce_AtTheLastFocus()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var id = Guid.Parse(image.Id);
|
||||
await rig.Service.SaveAsync(Save(id, [new HeroImageFocusRequest(id, new FocusDto(0.2, 0.2, 1))]), HeroTestRig.Admin, default);
|
||||
await rig.Service.SaveAsync(Save(id, [new HeroImageFocusRequest(id, new FocusDto(0.9, 0.9, 1))]), HeroTestRig.Admin, default);
|
||||
|
||||
(await rig.RenderPending()).Should().Be(1);
|
||||
|
||||
var done = rig.Db.HeroImages.Single();
|
||||
done.SetHash.Should().Be(HeroMapping.TargetSetHash(done));
|
||||
done.FocusX.Should().Be(0.9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ACancelledRenderOrSave_LeavesTheStoredHeroAlone_AndARepeatWorks()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var id = Guid.Parse(image.Id);
|
||||
await rig.Service.SaveAsync(Save(id, null), HeroTestRig.Admin, default);
|
||||
var live = rig.Db.HeroImages.Single().SetHash;
|
||||
await rig.Service.SaveAsync(Save(id, [new HeroImageFocusRequest(id, new FocusDto(0.9, 0.1, 1))]), HeroTestRig.Admin, default);
|
||||
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
await cancelled.CancelAsync();
|
||||
var act = async () => await rig.Images.RenderNextPendingAsync(new HashSet<Guid>(), cancelled.Token);
|
||||
await act.Should().ThrowAsync<OperationCanceledException>();
|
||||
|
||||
rig.Db.HeroImages.Single().SetHash.Should().Be(live, "nothing was switched");
|
||||
(await rig.RenderPending()).Should().Be(1);
|
||||
HeroMapping.NeedsRender(rig.Db.HeroImages.Single()).Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APreparedFocusThatIsNeverSaved_LeavesOnlyUnreferencedFiles_ThatTheCleanUpRemoves()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Diagnostics;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// A measurement, not a check: how long uploading and saving a hero with real photos takes. Runs only when
|
||||
/// HERO_TIMING_DIR points to a folder with hero-1.jpg .. hero-8.jpg (the ASF exports); otherwise it passes at once.
|
||||
/// </summary>
|
||||
public class HeroSaveTimingTests(ITestOutputHelper output)
|
||||
{
|
||||
[Fact]
|
||||
public async Task MeasureUploadAndSave_WithRealPhotos()
|
||||
{
|
||||
var dir = Environment.GetEnvironmentVariable("HERO_TIMING_DIR");
|
||||
if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using var rig = new HeroTestRig();
|
||||
var ids = new List<Guid>();
|
||||
var watch = Stopwatch.StartNew();
|
||||
for (var i = 1; i <= 8; i++)
|
||||
{
|
||||
watch.Restart();
|
||||
var image = await rig.UploadWithoutRendering(await File.ReadAllBytesAsync(Path.Combine(dir, $"hero-{i}.jpg")));
|
||||
ids.Add(Guid.Parse(image.Id));
|
||||
output.WriteLine($"upload request hero-{i}.jpg: {watch.ElapsedMilliseconds} ms, {image.Width}x{image.Height}");
|
||||
}
|
||||
|
||||
var slides = ids.Select(id => new HeroSlideRequest(null, id, "foto")).ToList();
|
||||
var focus = ids.Select(id => new HeroImageFocusRequest(id, new FocusDto(0.3, 0.4, 1), null, null)).ToList();
|
||||
watch.Restart();
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Andrea Slop", null, null, "slideshow", [], true, null, null, slides, focus), HeroTestRig.Admin, default);
|
||||
output.WriteLine($"save request with 8 slides and 8 changed focus points: {watch.ElapsedMilliseconds} ms");
|
||||
|
||||
watch.Restart();
|
||||
var cut = await rig.RenderPending();
|
||||
output.WriteLine($"background renderer: {cut} images in {watch.ElapsedMilliseconds} ms ({watch.ElapsedMilliseconds / Math.Max(1, cut)} ms per image)");
|
||||
|
||||
watch.Restart();
|
||||
var again = focus.Select(f => f with { Focus = new FocusDto(0.6, 0.4, 1) }).ToList();
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Andrea Slop", null, null, "slideshow", [], true, null, null, slides, again), HeroTestRig.Admin, default);
|
||||
output.WriteLine($"save request with 8 changed focus points again: {watch.ElapsedMilliseconds} ms");
|
||||
await rig.RenderPending();
|
||||
|
||||
watch.Restart();
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Andrea Slop", null, null, "slideshow", [], true, null, null, slides, null), HeroTestRig.Admin, default);
|
||||
output.WriteLine($"save without focus changes: {watch.ElapsedMilliseconds} ms");
|
||||
}
|
||||
}
|
||||
@@ -84,12 +84,38 @@ public sealed class HeroTestRig : IDisposable
|
||||
new SlpModularCms.Modules.Hero.Models.HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [],
|
||||
[new SlpModularCms.Modules.Hero.Models.HeroImageFocusRequest(imageId, request.Focus, request.Wide, request.Tall)]),
|
||||
Admin, CancellationToken.None);
|
||||
await RenderPending();
|
||||
return SlpModularCms.Modules.Hero.Services.HeroMapping.ToImageDto((await Repository.GetImageAsync(imageId, CancellationToken.None))!);
|
||||
}
|
||||
|
||||
public Task<SlpModularCms.Modules.Hero.Models.HeroImageDto> Upload(byte[] bytes)
|
||||
/// <summary>Uploads an image and lets the background renderer cut its variants (here: at once, the way the worker would).</summary>
|
||||
public async Task<SlpModularCms.Modules.Hero.Models.HeroImageDto> Upload(byte[] bytes)
|
||||
{
|
||||
var dto = await UploadWithoutRendering(bytes);
|
||||
await RenderPending();
|
||||
return SlpModularCms.Modules.Hero.Services.HeroMapping.ToImageDto((await Repository.GetImageAsync(Guid.Parse(dto.Id), CancellationToken.None))!);
|
||||
}
|
||||
|
||||
/// <summary>The upload request as such: the image is stored and its variants are still to be cut.</summary>
|
||||
public Task<SlpModularCms.Modules.Hero.Models.HeroImageDto> UploadWithoutRendering(byte[] bytes)
|
||||
=> Images.UploadAsync(new MemoryStream(bytes), bytes.Length, Admin, CancellationToken.None);
|
||||
|
||||
/// <summary>Does the work of the background renderer until nothing is pending.</summary>
|
||||
public async Task<int> RenderPending()
|
||||
{
|
||||
var count = 0;
|
||||
while (await Images.RenderNextPendingAsync(new HashSet<Guid>(), CancellationToken.None) is not null)
|
||||
{
|
||||
count++;
|
||||
if (count > 100)
|
||||
{
|
||||
throw new InvalidOperationException("The renderer does not settle.");
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Db.Dispose();
|
||||
|
||||
@@ -47,6 +47,8 @@ public class HeroModule : IModule
|
||||
services.AddScoped<IHeroPageModel, HeroPageModel>();
|
||||
services.AddScoped<IHtmlPageTransform, HeroHtmlTransform>();
|
||||
services.AddScoped<ICmsDataBlockContributor, HeroDataContributor>();
|
||||
services.AddSingleton<HeroRenderSignal>();
|
||||
services.AddHostedService<HeroRenderService>();
|
||||
services.AddScoped<HeroMediaCleanup>();
|
||||
services.AddHostedService<HeroMediaCleanupService>();
|
||||
}
|
||||
|
||||
@@ -23,7 +23,8 @@ public record HeroImageDto(
|
||||
FocusDto? WideFocus,
|
||||
FocusDto? TallFocus,
|
||||
string Src,
|
||||
IReadOnlyList<HeroVariantDto> Variants);
|
||||
IReadOnlyList<HeroVariantDto> Variants,
|
||||
bool Processing = false);
|
||||
|
||||
public record HeroButtonDto(string Label, string Target);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SlpModularCms.Modules.Hero.Data;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Repositories;
|
||||
|
||||
@@ -18,6 +19,12 @@ public interface IHeroRepository
|
||||
|
||||
Task<HeroImage?> GetImageAsync(Guid id, CancellationToken cancellationToken);
|
||||
Task<IReadOnlyList<HeroImage>> GetImagesAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken);
|
||||
/// <summary>Images whose set is missing or does not match their focus, oldest first (tracked).</summary>
|
||||
Task<IReadOnlyList<HeroImage>> GetImagesNeedingRenderAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The image as stored right now, not tracked.</summary>
|
||||
Task<HeroImage?> GetImageFreshAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
Task<HeroImage?> GetImageBySha256Async(string sha256, CancellationToken cancellationToken);
|
||||
void AddImage(HeroImage image);
|
||||
void RemoveImage(HeroImage image);
|
||||
@@ -62,6 +69,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
|
||||
return (await context.HeroImages.ToListAsync(cancellationToken)).Where(i => wanted.Contains(i.Id)).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetImagesNeedingRenderAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsRender).OrderBy(i => i.CreatedAt).ToList();
|
||||
|
||||
public Task<HeroImage?> GetImageFreshAsync(Guid id, CancellationToken cancellationToken)
|
||||
=> context.HeroImages.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
|
||||
|
||||
public Task<HeroImage?> GetImageBySha256Async(string sha256, CancellationToken cancellationToken)
|
||||
=> context.HeroImages.FirstOrDefaultAsync(i => i.OriginalSha256 == sha256, cancellationToken);
|
||||
|
||||
|
||||
@@ -12,6 +12,12 @@ namespace SlpModularCms.Modules.Hero.Services;
|
||||
/// <summary>The image is still used by a slide (the administrator gets a 409 and a message).</summary>
|
||||
public sealed class HeroImageInUseException() : Exception("The image is still used by a slide.");
|
||||
|
||||
/// <summary>Cutting the variants of one image failed; the id tells the background renderer which image to give up on after a few tries.</summary>
|
||||
public sealed class HeroImageRenderException(Guid imageId, Exception inner) : Exception("Cutting the variants of a hero image failed.", inner)
|
||||
{
|
||||
public Guid ImageId { get; } = imageId;
|
||||
}
|
||||
|
||||
public sealed class HeroImageNotFoundException() : Exception("The image does not exist.");
|
||||
|
||||
/// <summary>There is not enough room in the media directory for the image.</summary>
|
||||
@@ -19,18 +25,29 @@ public sealed class MediaStorageFullException() : Exception("The media directory
|
||||
|
||||
public interface IHeroImageService
|
||||
{
|
||||
/// <summary>Admits, stores and processes an uploaded image (all variants of the default focus). The same photo twice is one image.</summary>
|
||||
/// <summary>
|
||||
/// Admits and stores an uploaded image and returns at once: the variants are cut afterwards by the background renderer
|
||||
/// (<see cref="RenderNextPendingAsync"/>), so a slow machine never holds the request open. The same photo twice is one
|
||||
/// image. Until its set exists the image has no variants and is not published.
|
||||
/// </summary>
|
||||
/// <exception cref="ImageRejectedException">The upload is refused; see the code.</exception>
|
||||
Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Applies a changed focus (general and optionally per ratio) to a tracked image: when the set changes, the variants are
|
||||
/// cut again around the new point into a NEW set of files (new addresses, nothing live is touched) and the old set is
|
||||
/// noted as retired. Nothing is saved here: the caller saves it together with the hero, so a changed focus only becomes
|
||||
/// visible when the hero is saved. When the hero is not saved the new files are never referenced and the clean-up
|
||||
/// removes them after the retention time.
|
||||
/// Records a changed focus (general and optionally per ratio) on a tracked image. Nothing is cut here: the caller saves
|
||||
/// the image together with the hero and then calls <see cref="NotifyPending"/>; the background renderer cuts the new set
|
||||
/// into NEW files and only then switches the image to it (so the old set stays live until the new one is complete).
|
||||
/// </summary>
|
||||
Task StageFocusAsync(HeroImage image, HeroFocusRequest request, CancellationToken cancellationToken);
|
||||
void ApplyFocus(HeroImage image, HeroFocusRequest request);
|
||||
|
||||
/// <summary>Wakes the background renderer: there is an image whose set is missing or does not match its focus.</summary>
|
||||
void NotifyPending();
|
||||
|
||||
/// <summary>
|
||||
/// Cuts the set of the oldest image that needs one (new upload, repair or changed focus), skipping the given ids, and
|
||||
/// switches the image to it. Returns the id of the image handled, or null when nothing is pending.
|
||||
/// </summary>
|
||||
Task<Guid?> RenderNextPendingAsync(IReadOnlySet<Guid> skip, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Removes an image nothing uses; its files go after the retention time.</summary>
|
||||
Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
|
||||
@@ -45,7 +62,8 @@ public class HeroImageService(
|
||||
IOptions<MediaOptions> mediaOptions,
|
||||
ILogger<HeroImageService> logger,
|
||||
TimeProvider? time = null,
|
||||
IIndexHtmlCache? indexCache = null) : IHeroImageService
|
||||
IIndexHtmlCache? indexCache = null,
|
||||
HeroRenderSignal? signal = null) : IHeroImageService
|
||||
{
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
|
||||
@@ -83,18 +101,20 @@ public class HeroImageService(
|
||||
CreatedByUserId = callerId,
|
||||
};
|
||||
|
||||
var files = await RenderSetAsync(image, original, storedFormat, cancellationToken);
|
||||
|
||||
// The files first, the row last: an aborted request leaves at most an original nobody refers to (the clean-up
|
||||
// removes it) and a repeated upload simply does it again. The set is cut afterwards by the background renderer.
|
||||
await store.PutAsync(image.OriginalKey, original, cancellationToken);
|
||||
await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken);
|
||||
image.SetHash = string.Empty;
|
||||
image.Variants = [];
|
||||
if (existing is null)
|
||||
{
|
||||
repository.AddImage(image);
|
||||
}
|
||||
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
signal?.Notify();
|
||||
|
||||
logger.LogInformation("Hero image {ImageId} {Action} by user {UserId} ({Width}x{Height}, {Variants} variants)", image.Id, existing is null ? "uploaded" : "repaired", callerId, image.Width, image.Height, image.Variants.Count);
|
||||
logger.LogInformation("Hero image {ImageId} {Action} by user {UserId} ({Width}x{Height}); its variants are cut in the background", image.Id, existing is null ? "uploaded" : "repaired", callerId, image.Width, image.Height);
|
||||
return HeroMapping.ToImageDto(image);
|
||||
}
|
||||
|
||||
@@ -116,21 +136,46 @@ public class HeroImageService(
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task StageFocusAsync(HeroImage image, HeroFocusRequest request, CancellationToken cancellationToken)
|
||||
public void ApplyFocus(HeroImage image, HeroFocusRequest request)
|
||||
{
|
||||
var oldSet = image.SetHash;
|
||||
var general = request.Focus.ToSetting().Normalize();
|
||||
image.FocusX = general.X;
|
||||
image.FocusY = general.Y;
|
||||
image.Zoom = general.Zoom;
|
||||
Apply(request.Wide, v => (image.WideFocusX, image.WideFocusY, image.WideZoom) = v);
|
||||
Apply(request.Tall, v => (image.TallFocusX, image.TallFocusY, image.TallZoom) = v);
|
||||
}
|
||||
|
||||
var newSet = SetHashOf(image);
|
||||
if (newSet != oldSet)
|
||||
public void NotifyPending() => signal?.Notify();
|
||||
|
||||
public async Task<Guid?> RenderNextPendingAsync(IReadOnlySet<Guid> skip, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = (await repository.GetImagesNeedingRenderAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id));
|
||||
if (image is null)
|
||||
{
|
||||
using var slot = await gate.EnterAsync(cancellationToken);
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await RenderAsync(image, cancellationToken);
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
throw new HeroImageRenderException(image.Id, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Guid?> RenderAsync(HeroImage image, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
var target = HeroMapping.TargetSetHash(image);
|
||||
var oldSet = image.SetHash;
|
||||
Dictionary<string, byte[]> files;
|
||||
List<HeroVariant> variants;
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
using (await gate.EnterAsync(cancellationToken))
|
||||
{
|
||||
var file = await store.OpenReadAsync(image.OriginalKey, cancellationToken)
|
||||
?? throw new ImageRejectedException(ImageRejection.Unavailable, "The stored original is missing.");
|
||||
using var memory = new MemoryStream();
|
||||
@@ -140,12 +185,31 @@ public class HeroImageService(
|
||||
}
|
||||
|
||||
var storedFormat = ImageFormatExtensions.FromExtension(Path.GetExtension(image.OriginalKey).TrimStart('.'));
|
||||
|
||||
var files = await RenderSetAsync(image, memory.ToArray(), storedFormat, cancellationToken);
|
||||
await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken);
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() });
|
||||
logger.LogInformation("Hero image {ImageId}: variants cut again for a changed focus (saved with the hero)", image.Id);
|
||||
(files, variants) = await RenderSetAsync(image, memory.ToArray(), storedFormat, cancellationToken);
|
||||
}
|
||||
|
||||
await store.PutSetAsync(HeroMapping.Area, target, files, cancellationToken);
|
||||
|
||||
// The focus may have been changed while the set was being cut: then this set is not the one that is wanted and the
|
||||
// image stays pending (the next round cuts the right one; this set is cleaned up as an unreferenced set).
|
||||
var current = await repository.GetImageFreshAsync(image.Id, cancellationToken);
|
||||
if (current is null || HeroMapping.TargetSetHash(current) != target)
|
||||
{
|
||||
logger.LogInformation("Hero image {ImageId}: the focus changed while its variants were cut; cutting again.", image.Id);
|
||||
return image.Id;
|
||||
}
|
||||
|
||||
image.SetHash = target;
|
||||
image.Variants = variants;
|
||||
if (oldSet.Length > 0 && oldSet != target)
|
||||
{
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() });
|
||||
}
|
||||
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
indexCache?.Invalidate();
|
||||
logger.LogInformation("Hero image {ImageId}: {Variants} variants cut in {Seconds:0.0} s", image.Id, variants.Count, watch.Elapsed.TotalSeconds);
|
||||
return image.Id;
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
|
||||
@@ -177,11 +241,8 @@ public class HeroImageService(
|
||||
assign((f.X, f.Y, f.Zoom));
|
||||
}
|
||||
|
||||
private static string SetHashOf(HeroImage image)
|
||||
=> MediaPaths.SetHash(image.OriginalSha256, [("wide", image.FocusFor("wide")), ("tall", image.FocusFor("tall"))]);
|
||||
|
||||
/// <summary>Cuts and encodes every planned variant of the image and fills its set hash and variant list. Returns the files by name.</summary>
|
||||
private async Task<Dictionary<string, byte[]>> RenderSetAsync(HeroImage image, byte[] original, ImageFormat storedFormat, CancellationToken cancellationToken)
|
||||
/// <summary>Cuts and encodes every planned variant of the image at its current focus. Returns the files by name and the variant list.</summary>
|
||||
private async Task<(Dictionary<string, byte[]> Files, List<HeroVariant> Variants)> RenderSetAsync(HeroImage image, byte[] original, ImageFormat storedFormat, CancellationToken cancellationToken)
|
||||
{
|
||||
var ratios = new[] { Ratio.Wide, Ratio.Tall }
|
||||
.Select(r => new RatioPlan(r, image.FocusFor(r.Name), VariantPlanner.DefaultWidths(r)))
|
||||
@@ -198,9 +259,7 @@ public class HeroImageService(
|
||||
variants.Add(new HeroVariant(spec.Ratio.Name, rendered.Width, rendered.Height, spec.Format.MimeType(), name, rendered.Bytes.LongLength));
|
||||
}
|
||||
|
||||
image.SetHash = SetHashOf(image);
|
||||
image.Variants = variants;
|
||||
return files;
|
||||
return (files, variants);
|
||||
}
|
||||
|
||||
private async Task EnsureRoomAsync(long incomingBytes, CancellationToken cancellationToken)
|
||||
|
||||
@@ -33,6 +33,13 @@ public static class HeroMapping
|
||||
{
|
||||
public const string Area = "hero";
|
||||
|
||||
/// <summary>The set hash the image should have at its current focus.</summary>
|
||||
public static string TargetSetHash(HeroImage image)
|
||||
=> MediaPaths.SetHash(image.OriginalSha256, [("wide", image.FocusFor("wide")), ("tall", image.FocusFor("tall"))]);
|
||||
|
||||
/// <summary>True when the image has no set yet or its set was cut for another focus (the work of the background renderer).</summary>
|
||||
public static bool NeedsRender(HeroImage image) => image.Variants.Count == 0 || image.SetHash != TargetSetHash(image);
|
||||
|
||||
public static HeroVariantDto ToDto(HeroImage image, HeroVariant variant)
|
||||
=> new(variant.Ratio, variant.Width, variant.Height, variant.Type, MediaPaths.Url(Area, image.SetHash, variant.FileName));
|
||||
|
||||
@@ -55,7 +62,8 @@ public static class HeroMapping
|
||||
image.WideFocusX is null ? null : FocusDto.From(image.FocusFor("wide")),
|
||||
image.TallFocusX is null ? null : FocusDto.From(image.FocusFor("tall")),
|
||||
SrcFor(image),
|
||||
image.Variants.Select(v => ToDto(image, v)).ToList());
|
||||
image.Variants.Select(v => ToDto(image, v)).ToList(),
|
||||
NeedsRender(image));
|
||||
|
||||
public static bool IsLive(HeroContent hero, DateTimeOffset now)
|
||||
=> hero.IsActive
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
/// <summary>Wakes the background renderer after an upload or a save. A singleton shared by the request and the worker.</summary>
|
||||
public sealed class HeroRenderSignal
|
||||
{
|
||||
private readonly SemaphoreSlim _signal = new(0, 1);
|
||||
|
||||
public void Notify()
|
||||
{
|
||||
try
|
||||
{
|
||||
_signal.Release();
|
||||
}
|
||||
catch (SemaphoreFullException)
|
||||
{
|
||||
// Already signalled; the worker will look at everything that is pending.
|
||||
}
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cuts the variants of images that have none yet (upload) or whose set no longer matches their focus (a saved focus
|
||||
/// change), one image at a time, so an upload or a save never waits for the slow part. An image goes live (or switches to
|
||||
/// its new set) the moment its set is complete; until then the old set, or nothing, is published. Looks again when woken
|
||||
/// and at least every minute, and at start-up, so work interrupted by a restart is picked up.
|
||||
/// </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)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Let the start-up (migrations, health check) finish first.
|
||||
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await RunPassAsync(stoppingToken);
|
||||
await signal.WaitAsync(TimeSpan.FromMinutes(1), stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Shutting down.
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunPassAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
var skip = _failures.Where(f => f.Value >= MaxAttempts).Select(f => f.Key).ToHashSet();
|
||||
Guid? handled = null;
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
handled = await scope.ServiceProvider.GetRequiredService<IHeroImageService>().RenderNextPendingAsync(skip, stoppingToken);
|
||||
}
|
||||
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);
|
||||
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
|
||||
continue;
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(exception, "Looking for hero images to cut failed; trying again at the next wake-up.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (handled is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_failures.Remove(handled.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,16 +115,17 @@ public class HeroService(
|
||||
}
|
||||
}
|
||||
|
||||
// A changed focus is applied only now, together with the hero: the new variants are cut into new files first, then
|
||||
// the hero and the images are saved in one go, so nothing live changes before the hero is saved.
|
||||
// A changed focus is only recorded here: the new variants are cut in the background into new files and the image
|
||||
// switches to them when they are complete, so saving is quick and nothing live changes half-way.
|
||||
foreach (var edit in focusRequests)
|
||||
{
|
||||
await imageService.StageFocusAsync(images[edit.ImageId], new HeroFocusRequest(edit.Focus, edit.Wide, edit.Tall), cancellationToken);
|
||||
imageService.ApplyFocus(images[edit.ImageId], new HeroFocusRequest(edit.Focus, edit.Wide, edit.Tall));
|
||||
}
|
||||
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
indexCache?.Invalidate();
|
||||
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);
|
||||
|
||||
Reference in New Issue
Block a user