Hero-module: Application Design (componenten, methoden, services, afhankelijkheden); antwoorden van Bryan verwerkt
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
# Application Design: hero-module (consolidated)
|
||||
|
||||
Details: [components.md](components.md), [component-methods.md](component-methods.md), [services.md](services.md), [component-dependency.md](component-dependency.md). Inputs: `requirements.md`, `site-contract-agreed-with-asf.md`, answers to `application-design-plan.md` (2026-11-16).
|
||||
|
||||
## Decisions
|
||||
|
||||
| # | Decision | Source |
|
||||
|---|---|---|
|
||||
| D1 | One module `SlpModularCms.Modules.Hero` (own DbContext, migrations, texts); on or off per site | Q14 (requirements) |
|
||||
| D2 | A general media service in `Core.Media`: storage interface, image processor interface, upload guard, pure `FocusMath` and `VariantPlanner`, address scheme, media endpoint. Usable later for a gallery | Design Q4 = B |
|
||||
| D3 | Images are stored in a **directory outside the release** behind `IMediaStore`; a database store can follow if the hosting requires it. Risk R1 recorded; Bryan tests write access on the ASF hosting and is asked again if it fails | Design Q1 = B |
|
||||
| D4 | Input formats: as many as the library can decode (jpg/jpeg, png, webp always; gif, bmp, tiff, heic/avif where possible), real-signature check, metadata stripped, animation reduced to the first frame; output chosen by the system per platform (WebP required, AVIF when possible) | Design Q2 |
|
||||
| D5 | `#cms-data` is composed by a Core `CmsDataBlockTransform` from `ICmsDataBlockContributor`s; Offerings becomes a contributor with byte-identical output; the Hero adds `hero` | Design Q3 = A |
|
||||
| D6 | Crop model B: the host cuts `wide` (3:2) and `tall` (4:5) variants around the focus point and zoom. The focus defaults to the centre for all ratios; a separate focus (and zoom) per ratio is optional and falls back on the general one | Design Q6, contract |
|
||||
| D7 | The admin focus editor is an own light component (draggable point, zoom, live `wide` and `tall` previews using a TypeScript twin of `FocusMath` with shared test vectors) | Design Q5 = A |
|
||||
| D8 | Public contract: `GET /api/v1/hero` (204 = none), the same shape under `hero` in `#cms-data`; markers `CMS:HERO-HTML` (region with the first slide as `<picture>`) and `CMS:HERO-PRELOAD` (one or two preload links with `media`, byte-equal to the `<source>`/`<img>` attributes); addresses `/media/hero/<setHash>/<ratio>-<width>.<ext>`, immutable | Contract with ASF |
|
||||
| D9 | One renderer (`HeroPictureRenderer`) produces both the region attributes and the preload attributes; one read model (`PublicHeroService`) feeds the API, the region, the preload and the data block | LCP requirement |
|
||||
| D10 | Fail-open for page injection, fail-closed for uploads | Requirements, SECURITY-15 |
|
||||
| D11 | Language: the hero row carries a `Language` (default `nl`, unique), so adding a language needs no migration of existing rows; only one is exposed and edited now | Q9 |
|
||||
|
||||
## Architecture overview
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Admin["Admin (Hero screen)"] --> Hero["Modules.Hero"]
|
||||
Hero --> Media["Core.Media<br/>(store, processor, guard, endpoint)"]
|
||||
Hero --> Inj["Core.Hosting.Website<br/>(transforms, data block, cache)"]
|
||||
Off["Modules.Offerings"] --> Inj
|
||||
Inj --> Pages["Website pages (SLS, ASF)"]
|
||||
Media --> Pages
|
||||
Dir[("Media directory<br/>outside the release")] --- Media
|
||||
Db[("MariaDB")] --- Hero
|
||||
classDef new fill:#FFA726,stroke:#E65100,color:#000;
|
||||
classDef chg fill:#BBDEFB,stroke:#1565C0,color:#000;
|
||||
classDef ext fill:#C8E6C9,stroke:#2E7D32,color:#000;
|
||||
class Hero,Media new;
|
||||
class Inj,Off,Admin chg;
|
||||
class Pages,Dir,Db ext;
|
||||
```
|
||||
|
||||
Text alternative: the new Hero module and Core.Media (orange) work with the changed injection layer and Offerings (blue); media files live in a directory outside the release and metadata in the database; pages get the hero injected.
|
||||
|
||||
## Open items carried to the next stages
|
||||
|
||||
| Item | Stage |
|
||||
|---|---|
|
||||
| Choice and proof of the image library (win-x64, linux-arm64, formats, AVIF, licence), limits (pixels, memory, parallelism, timeouts), budgets for LCP and weight, maximum slides, grace period for old sets | NFR Requirements and NFR Design |
|
||||
| Whether deleting an image used by a slide refuses or detaches; exact validation messages; byte-exact HTML of the region | Functional Design |
|
||||
| Write permission of the directory on MijnHostingPartner (IIS) and the backup of the directory | Bryan with ASF; Infrastructure Design (storage is a directory, so this stage now executes for the media unit) |
|
||||
| Golden files for `<picture>` and the preload; focus estimates for the 8 photos | ASF session |
|
||||
| SLS rendering of the three-line title and its screen-reader text | SLS session |
|
||||
|
||||
## Units (confirmed from the execution plan, adjusted)
|
||||
|
||||
H0 (done, PR #16 merged, 0824bfa) · H1 image pipeline (`Core.Media` processor, guard, `FocusMath`, `VariantPlanner`) · H2 Hero module backend · H3 media store, endpoint, address scheme · H4 injection (data block contributor and Offerings change, region, preload, golden files) · H5 admin frontend · H6 seed, docs, smoke test. Infrastructure Design is now needed for H3 (directory storage).
|
||||
@@ -0,0 +1,70 @@
|
||||
# Component dependencies: hero-module
|
||||
|
||||
## Dependency matrix
|
||||
|
||||
Rows depend on columns (X = direct use).
|
||||
|
||||
| | Core.Media | Core.Hosting.Website | Core.Texts | Modules.Hero | Modules.Offerings | Frontend admin |
|
||||
|---|---|---|---|---|---|---|
|
||||
| **Modules.Hero** | X (store, processor, guard, paths, math) | X (`IHtmlPageTransform`, `IIndexHtmlMarkerProvider`, `ICmsDataBlockContributor`, `IIndexHtmlCache`) | X | n/a | none | none |
|
||||
| **Modules.Offerings** | none | X (adds `OfferingsDataContributor`; loses the data block write) | X | none | n/a | none |
|
||||
| **Core.Media** | n/a | none (endpoint is mapped by the host) | none | none (knows no module) | none | none |
|
||||
| **Core.Hosting.Website** | none | n/a | none | none | none | none |
|
||||
| **Frontend admin** | none | none | none | HTTP only (OpenAPI) | HTTP only | n/a |
|
||||
| **Api / site projects** | X (host registers the media endpoint and options) | X | X | X (project reference) | X | n/a |
|
||||
|
||||
Rules: Core never references a module; the Hero module never references the Offerings module (the data block is composed through the Core contributor interface, so no module knows another).
|
||||
|
||||
## Data flow
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Admin["Admin browser<br/>(HeroPage, FocusEditor)"] -->|"multipart upload, JSON"| HeroCtl["Hero controllers"]
|
||||
HeroCtl --> HeroSvc["HeroService / HeroImageService"]
|
||||
HeroSvc --> Guard["MediaUploadGuard"]
|
||||
HeroSvc --> Proc["ImageProcessor (library)"]
|
||||
HeroSvc --> Store["MediaStore (directory)"]
|
||||
HeroSvc --> Db[("Hero tables<br/>MariaDB")]
|
||||
HeroSvc --> Cache["IIndexHtmlCache"]
|
||||
Db --> PubSvc["PublicHeroService"]
|
||||
PubSvc --> PubApi["GET /api/v1/hero"]
|
||||
PubSvc --> Tr["Hero transform, preload, data contributor"]
|
||||
Tr --> Inj["HtmlMarkerInjector"]
|
||||
Inj --> Page["Website page<br/>(first HTML)"]
|
||||
Store --> MediaEp["GET /media/..."]
|
||||
Page -->|"img, picture, preload"| MediaEp
|
||||
Site["Website (SLS, ASF)"] -->|"refresh after load"| PubApi
|
||||
Page --> Site
|
||||
classDef user fill:#f6e05e,stroke:#c05621,color:#000;
|
||||
classDef host fill:#63b3ed,stroke:#2b6cb0,color:#000;
|
||||
classDef data fill:#9ae6b4,stroke:#2f855a,color:#000;
|
||||
classDef ext fill:#CE93D8,stroke:#6A1B9A,color:#000;
|
||||
class Admin user;
|
||||
class HeroCtl,HeroSvc,Guard,Proc,PubSvc,PubApi,Tr,Inj,MediaEp,Cache host;
|
||||
class Store,Db data;
|
||||
class Page,Site ext;
|
||||
```
|
||||
|
||||
Text alternative: the admin uploads through the Hero services into the media directory and the database; the public read model feeds the public endpoint and the page injection; the browser loads images from the media endpoint and the site refreshes from the public endpoint.
|
||||
|
||||
## Communication patterns
|
||||
|
||||
| From to | Pattern |
|
||||
|---|---|
|
||||
| Admin to host | REST over HTTPS, cookie/JWT as the other admin screens; multipart for the image |
|
||||
| Host internal | Dependency injection; services scoped, `IMediaStore` and `IImageProcessor` singletons (stateless, thread-safe) |
|
||||
| Page build | The injector (singleton with scoped providers) asks transforms in registration order; the data block contributor order fixes the key order |
|
||||
| Site to host | Anonymous GET of `/api/v1/hero` and `/media/...`; ETag and 304 for pages and media |
|
||||
| Change notification | Direct call `IIndexHtmlCache.Invalidate()` after commit |
|
||||
|
||||
## Risks and consequences of the design choices
|
||||
|
||||
| # | Risk or consequence | Mitigation |
|
||||
|---|---|---|
|
||||
| R1 | **Storage in a directory** (Bryan's choice): the directory must survive a deploy, be in the backup and be writable. Pi: place it in the `shared` directory next to `releases/current` and set `Media__Directory`; IIS (MijnHostingPartner, ASF production): write permission is unknown | The store sits behind `IMediaStore`, so a database store can be added without touching the Hero module. Bryan tests directory write access with ASF; if it fails Bryan is asked again. Startup check: the host logs an error and the hero admin upload is refused (public reads unaffected) when the directory is not writable. Backup: add the directory to the host's back-up script and to the release checklist |
|
||||
| R2 | Image library: AVIF encoder and native binaries on win-x64 and linux-arm64, licence | Proof in NFR Requirements; processing behind `IImageProcessor`; WebP is the required output, AVIF optional |
|
||||
| R3 | Wide input list (gif, bmp, tiff, heic/avif) enlarges the attack surface and the library requirements | Allow-list by real signature; decode only through the library inside the guard (pixel, memory and time limits); formats the platform cannot decode are reported as unsupported in the admin; animated input is reduced to the first frame |
|
||||
| R4 | Two writers of `#cms-data` would conflict | Solved by the Core contributor; the Offerings output stays byte-identical (golden files prove it) |
|
||||
| R5 | Variant addresses change when the focus changes; an old page cached by a site may point to removed files | Old set kept for a grace period after a change; sites refresh from the API after load |
|
||||
| R6 | LCP regression if preload and `<picture>` differ | One renderer for both, golden-tested with the ASF files |
|
||||
| R7 | Two preload links (portrait, landscape) double the first request when a browser ignores `media` on preload | Verified in the LCP measurement on both test hosts |
|
||||
@@ -0,0 +1,125 @@
|
||||
# Component methods: hero-module
|
||||
|
||||
Signatures and purposes only; business rules are detailed in Functional Design per unit. Types are C# sketches.
|
||||
|
||||
## Core.Media
|
||||
|
||||
```csharp
|
||||
public interface IMediaStore
|
||||
{
|
||||
Task PutAsync(string key, Stream content, string contentType, CancellationToken ct);
|
||||
Task<MediaFile?> OpenReadAsync(string key, CancellationToken ct); // null = not found; MediaFile has Stream, ContentType, Length, LastWriteTime
|
||||
Task<bool> ExistsAsync(string key, CancellationToken ct);
|
||||
Task DeleteAsync(string key, CancellationToken ct);
|
||||
Task DeletePrefixAsync(string prefix, CancellationToken ct); // removes every file below an area/hash directory
|
||||
}
|
||||
|
||||
public interface IImageProcessor
|
||||
{
|
||||
// Real format, pixel size and frame count; throws ImageRejectedException (reason code) for anything unsafe or unsupported.
|
||||
Task<ImageInfo> InspectAsync(Stream source, CancellationToken ct);
|
||||
|
||||
// Decode (orientation applied), crop around the focus for a ratio, resize without upscaling, strip metadata, encode.
|
||||
Task<RenderedImage> RenderAsync(Stream source, RenderRequest request, CancellationToken ct);
|
||||
|
||||
IReadOnlySet<ImageFormat> SupportedInput { get; }
|
||||
IReadOnlySet<ImageFormat> SupportedOutput { get; } // WebP always; AVIF when the platform can
|
||||
}
|
||||
|
||||
public sealed record RenderRequest(Ratio Ratio, int Width, ImageFormat Format, int Quality, FocusSetting Focus);
|
||||
public sealed record FocusSetting(double X, double Y, double Zoom); // 0..1, 0..1, >= 1; default (0.5, 0.5, 1)
|
||||
public sealed record Ratio(string Name, int Numerator, int Denominator); // wide 3:2, tall 4:5
|
||||
|
||||
public interface IMediaUploadGuard
|
||||
{
|
||||
// Size, real format, pixel/memory bounds, timeout and parallel gate; returns ImageInfo or throws ImageRejectedException.
|
||||
Task<GuardedUpload> AdmitAsync(Stream upload, long declaredLength, CancellationToken ct);
|
||||
}
|
||||
|
||||
public static class FocusMath // pure, property-tested
|
||||
{
|
||||
public static CropRect CropFor(int imageWidth, int imageHeight, Ratio ratio, FocusSetting focus);
|
||||
public static FocusSetting Normalize(FocusSetting focus); // clamps to valid ranges
|
||||
}
|
||||
|
||||
public static class VariantPlanner // pure, property-tested
|
||||
{
|
||||
public static IReadOnlyList<VariantSpec> Plan(int sourceWidth, int sourceHeight, IReadOnlyList<RatioPlan> ratios, IReadOnlySet<ImageFormat> outputs);
|
||||
}
|
||||
|
||||
public static class MediaPaths // pure
|
||||
{
|
||||
public static string SetHash(string originalSha256, IEnumerable<(string Ratio, FocusSetting Focus)> crops);
|
||||
public static string Url(string area, string setHash, string name); // "/media/hero/<setHash>/wide-1600.webp"
|
||||
public static bool TryParse(string path, out MediaAddress address); // strict allow-list of characters
|
||||
}
|
||||
```
|
||||
|
||||
`MediaEndpoint` is a minimal-API/endpoint mapping `GET|HEAD /media/{**path}`: parse, open from the store, answer with the immutable headers and `304` on a matching `If-None-Match`; any failure is a plain 404.
|
||||
|
||||
## Core.Hosting.Website
|
||||
|
||||
```csharp
|
||||
public interface ICmsDataBlockContributor
|
||||
{
|
||||
string Key { get; } // "offerings", "banners", "hero"
|
||||
int Order { get; } // 100 Offerings, 200 Hero: fixes the key order in the block
|
||||
Task<object?> GetAsync(HtmlTransformContext context, CancellationToken ct); // null is written as JSON null
|
||||
}
|
||||
|
||||
public sealed class CmsDataBlockTransform(IEnumerable<ICmsDataBlockContributor> contributors) : IHtmlPageTransform
|
||||
{
|
||||
public bool Wants(string html); // page contains <!--CMS:DATA-->
|
||||
public Task<string> ApplyAsync(string html, HtmlTransformContext context, CancellationToken ct);
|
||||
}
|
||||
```
|
||||
|
||||
## Modules.Hero
|
||||
|
||||
```csharp
|
||||
public interface IHeroService
|
||||
{
|
||||
Task<HeroAdminDto?> GetAsync(string language, CancellationToken ct); // management read incl. inactive
|
||||
Task<HeroAdminDto> SaveAsync(HeroSaveRequest request, string actor, CancellationToken ct);
|
||||
}
|
||||
|
||||
public interface IHeroImageService
|
||||
{
|
||||
Task<HeroImageDto> UploadAsync(Stream upload, long length, string actor, CancellationToken ct);
|
||||
Task<HeroImageDto> SetFocusAsync(Guid imageId, HeroFocusRequest request, string actor, CancellationToken ct); // general + optional per ratio
|
||||
Task DeleteAsync(Guid imageId, string actor, CancellationToken ct); // refuses while a slide uses it, or detaches (decided in Functional Design)
|
||||
Task RemoveOrphansAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
public interface IPublicHeroService
|
||||
{
|
||||
Task<PublicHeroDto?> GetActiveAsync(string language, DateTimeOffset now, CancellationToken ct); // null = 204
|
||||
}
|
||||
|
||||
public static class ButtonTargetValidator
|
||||
{
|
||||
public static ButtonTargetResult Validate(string? target); // Anchor | Path | Https | Invalid(reason)
|
||||
}
|
||||
|
||||
public static class HeroPictureRenderer
|
||||
{
|
||||
public static string RegionHtml(PublicHeroDto hero, ITextCatalog texts); // title, tagline, buttons, first slide <picture>
|
||||
public static string PreloadHtml(PublicHeroDto hero); // one or two <link rel="preload" as="image"> elements
|
||||
}
|
||||
```
|
||||
|
||||
DTO shape (public, `GET /api/v1/hero` and `hero` in `#cms-data`):
|
||||
|
||||
```json
|
||||
{ "display": "slideshow", "title": "…", "tagline": "…", "lead": null,
|
||||
"buttons": [ { "label": "…", "target": "/over-mij" } ],
|
||||
"slides": [ { "id": "guid", "alt": "…", "decorative": false,
|
||||
"image": { "width": 1600, "height": 1067, "focus": { "x": 0.5, "y": 0.5, "zoom": 1 },
|
||||
"src": "/media/hero/<set>/wide-1600.webp",
|
||||
"variants": [ { "ratio": "wide", "width": 1600, "type": "image/webp", "url": "…" },
|
||||
{ "ratio": "tall", "width": 960, "type": "image/webp", "url": "…" } ] } } ] }
|
||||
```
|
||||
|
||||
## Frontend
|
||||
|
||||
`heroApi.getHero()`, `saveHero()`, `uploadImage(file, onProgress)`, `setFocus(imageId, …)`, `deleteImage(imageId)`; `focusMath.cropFor(...)` (TypeScript twin of `FocusMath`, same test vectors).
|
||||
@@ -0,0 +1,76 @@
|
||||
# Components: hero-module
|
||||
|
||||
Namespaces follow the existing modules (`SlpModularCms.Core.*`, `SlpModularCms.Modules.Hero`). "New" = created in this feature, "Changed" = existing code that is adapted.
|
||||
|
||||
## C1. `SlpModularCms.Modules.Hero` (New, the module)
|
||||
|
||||
| Component | Purpose and responsibilities |
|
||||
|---|---|
|
||||
| `HeroModule` (`IModule`) | Registers services, DbContext, texts (`AddCmsTextsFrom`), the HTML transform, the preload marker provider and the data contributor; runs the module's migrations. Name `Hero`, switched on or off per site by the project references and committed defaults (like Offerings). |
|
||||
| `HeroDbContext` + entities | Tables `Heroes`, `HeroSlides`, `HeroImages` (see data model below). Own migrations, same style as the Offerings migrations (hand-written, MySQL). |
|
||||
| `IHeroRepository`, `IHeroImageRepository` | Persistence of the hero with its slides, and of the images with their variant lists. |
|
||||
| `IHeroService` | Management use cases: read and save the hero (texts, buttons, display, schedule, slide list and order), validation, change notification. |
|
||||
| `IHeroImageService` | Upload, replace and remove of an image: validates and processes through the media service, stores the files, writes the metadata, changes focus/zoom per ratio (regenerates the variants), removes orphans. |
|
||||
| `IPublicHeroService` | The read model for sites: the active hero (schedule and active slides applied) as `PublicHeroDto`, or null. Used by `GET /hero`, the HTML transform and the data contributor, so all three show exactly the same thing. |
|
||||
| `HeroController` | Public read `GET /api/v1/hero` (anonymous, `[PublicSiteEndpoint]`, `public, max-age=60`, rate-limit policy `hero-public`, 204 when there is no active hero); management `GET /api/v1/hero/all` (the full hero including inactive slides and the schedule) and `PUT /api/v1/hero` (policy `AdminOnly`). Same convention as `offerings` and `offerings/all`. |
|
||||
| `HeroImagesController` (admin) | `POST /api/v1/hero/images` (multipart upload, size limit), `PUT /api/v1/hero/images/{id}/focus`, `DELETE /api/v1/hero/images/{id}`. |
|
||||
| `ButtonTargetValidator` | Pure function: accepts `#anchor`, `/path`, `https://host/...`, rejects everything else. |
|
||||
| `HeroHtmlTransform` (`IHtmlPageTransform`) | Fills `<!--CMS:HERO-HTML-->` regions: title lines, tagline, buttons and the first active slide as `<picture>`. Fail-open. |
|
||||
| `HeroPreloadMarkerProvider` (`IIndexHtmlMarkerProvider`) | Writes the one or two `<link rel="preload" as="image">` elements at `<!--CMS:HERO-PRELOAD-->`; shares the `srcset`/`sizes`/`media` generator with the transform so they are byte-for-byte equal. |
|
||||
| `HeroPictureRenderer` | Pure: one place that produces the `<picture>`/`<img>` attributes and the preload attributes from a `PublicHeroDto`; golden-tested. |
|
||||
| `HeroDataContributor` (`ICmsDataBlockContributor`) | Adds the key `hero` (the `PublicHeroDto`, or null) to the data block. |
|
||||
| `HeroTexts` + `Texts/nl.json`, `en.json` | Backend texts (validation messages) per `docs/translation-files.md`. |
|
||||
|
||||
### Data model (sketch, detailed in Functional Design)
|
||||
|
||||
| Entity | Fields |
|
||||
|---|---|
|
||||
| `Hero` | `Id`, `Language` (default `nl`; unique per language so a language can be added later without migrating rows), `Title` (text with line breaks), `Tagline`, `Lead`, `Display` (`single`/`slideshow`), `Button1Label/Target`, `Button2Label/Target`, `StartsAt`, `EndsAt`, `IsActive`, `UpdatedAt`, `UpdatedBy` |
|
||||
| `HeroSlide` | `Id` (GUID, stable), `HeroId`, `ImageId`, `Alt`, `Decorative`, `SortOrder`, `IsActive` |
|
||||
| `HeroImage` | `Id`, `OriginalKey` (store key), `Sha256`, `SourceFormat`, `Width`, `Height`, `Bytes`, `Focus` (general, default centre: `X`, `Y`, `Zoom`), optional `WideFocus` and `TallFocus` (`X`, `Y`, `Zoom`, nullable), `VariantSetHash`, `VariantsJson` (list of `{ratio, width, type, key, bytes}`), `CreatedAt` |
|
||||
|
||||
## C2. `SlpModularCms.Core.Media` (New, general media service in Core)
|
||||
|
||||
| Component | Purpose and responsibilities |
|
||||
|---|---|
|
||||
| `IMediaStore` | The storage interface: `PutAsync(key, stream, contentType)`, `OpenReadAsync(key)`, `DeleteAsync(key)`, `DeletePrefixAsync(prefix)`, `ExistsAsync`. Keys are relative paths made by the code, never by a client file name. Behind this interface the store can move from a directory to the database if the hosting demands it (risk R1). |
|
||||
| `FileSystemMediaStore` | Implementation on a directory (`Media:Directory`) outside the release; atomic writes (temp file then move), path containment check (no `..`, no absolute paths, only a safe character set), no directory listing. |
|
||||
| `IImageProcessor` | The image library behind an interface: `InspectAsync(stream)` (real format, size, frame count, or a rejection), `RenderAsync(source, RenderRequest)` (decode, apply orientation, crop around focus/zoom to a ratio, resize without upscaling, strip metadata, encode to a format and quality). Implementation chosen in NFR Requirements after a proof on win-x64 and linux-arm64 (candidates ImageSharp, NetVips, Magick.NET, SkiaSharp). |
|
||||
| `ImageProcessingLimits` / `MediaOptions` | `Media:Directory`, maximum upload bytes (10 MB), maximum pixels, maximum parallel jobs, timeout, accepted input formats, output formats and quality per format. |
|
||||
| `FocusMath`, `VariantPlanner` | Pure, property-tested: the crop rectangle for a ratio from focus and zoom (always inside the image, as close to the focus as the image allows), and the widths per ratio from the source size (no upscaling, monotonic steps). |
|
||||
| `MediaPaths` | The address scheme `/media/<area>/<setHash>/<name>`; builds and parses addresses, computes the set hash from the content hash and the crop parameters, so a change of focus gives a new address. |
|
||||
| `MediaEndpoint` | `GET /media/{**path}`: anonymous, same origin; `Cache-Control: public, max-age=31536000, immutable`, `ETag`, `304`, `X-Content-Type-Options: nosniff`, content type from the stored file, `Content-Disposition` not set, rate-limit policy `media-public`; unknown or malformed path = 404 with no detail. Also `HEAD`. |
|
||||
| `IMediaUploadGuard` | The upload checks in one place (size, real format, pixel and memory bounds, decode timeout, parallelism gate), used by every module that accepts images. |
|
||||
|
||||
## C3. `SlpModularCms.Core.Hosting.Website` (Changed)
|
||||
|
||||
| Component | Change |
|
||||
|---|---|
|
||||
| `ICmsDataBlockContributor` (New) | `Key`, `Order`, `GetAsync(context, ct)` returning the value (object) for that key or "no value". |
|
||||
| `CmsDataBlockTransform` (New, `IHtmlPageTransform`) | Owns the `<!--CMS:DATA-->` marker: asks all contributors (ordered by `Order`) and writes `{"siteUrl": …, <key>: <value>, …}` into the data block. Wants = page contains the marker. Fail-open as every transform. If a contributor throws, the whole block is left as baked: a half-filled block would mislead the site (fail-open for the block as a whole). |
|
||||
| `OfferingsHtmlTransform` (Changed, module Offerings) | No longer writes the data block; its regions, JSON-LD and prices stay. A new `OfferingsDataContributor` (`Order` 100) supplies `offerings` and `banners`. The output of the block stays byte-identical (key order `siteUrl`, `offerings`, `banners`, then `hero`), so all existing golden files stay green. |
|
||||
| `HtmlMarkerEditor` | Unchanged API; the preload marker is written through the existing `IIndexHtmlMarkerProvider` (whole-comment replacement). |
|
||||
|
||||
## C4. Frontend admin (New feature folder `frontend/src/features/hero`)
|
||||
|
||||
| Component | Purpose |
|
||||
|---|---|
|
||||
| `HeroPage` | The Hero screen in the admin navigation (visible when the Hero module is on, via `/System/capabilities`), shows whether the hero is live (schedule, active slides). |
|
||||
| `HeroForm` | Title (multi-line), tagline, lead, display, up to two buttons with target validation messages, schedule. |
|
||||
| `SlideList` | Order (up/down), on/off, alt text or "decorative", remove, add. |
|
||||
| `ImageUploader` | Upload with progress, shows the accepted formats and the size limit, rejection messages. |
|
||||
| `FocusEditor` | Own light component: the image with a draggable focus point, a zoom control, live previews of `wide` (3:2) and `tall` (4:5) cut as the host will cut them (same pure maths, shared as a small TypeScript twin of `FocusMath` with the same test vectors), and optional per-ratio overrides with "use the general point" reset. |
|
||||
| `heroApi`, translations | React Query hooks and `nl/en` texts. |
|
||||
|
||||
## C5. Scripts, docs, CI
|
||||
|
||||
| Component | Purpose |
|
||||
|---|---|
|
||||
| `scripts/Seed-Hero.ps1` (+ data) | Seeds the SLP hero and the ASF hero with its 8 photos and the focus estimates of the ASF session, on test only; needs the owner's login like `Seed-Offerings.ps1`. |
|
||||
| `scripts/smoke-site.sh` (Changed) | Checks the public hero endpoint (200 or 204), a media address answers with the immutable header, and, for a site with markers, no unprocessed hero markers. |
|
||||
| `docs/hero-module.md` (New) | Contract, addresses, storage and the hosting risk, operation. |
|
||||
| CI H0 | Done (merged, 0824bfa). |
|
||||
|
||||
## Sites (outside this repository)
|
||||
|
||||
The SLP and ASF websites place the markers and render `<picture>`; contract in `site-contract-agreed-with-asf.md`.
|
||||
@@ -0,0 +1,98 @@
|
||||
# Services and orchestration: hero-module
|
||||
|
||||
## Services
|
||||
|
||||
| Service | Responsibility | Collaborators |
|
||||
|---|---|---|
|
||||
| `HeroService` (management) | Reads and saves the hero: validates fields (lengths, button targets via `ButtonTargetValidator`, schedule order, slide count and order), writes the hero and slides in one transaction, calls the cache invalidation. | `IHeroRepository`, `ITextCatalog`, `IIndexHtmlCache` |
|
||||
| `HeroImageService` | The upload pipeline and focus changes (below). Owns the rule that every stored file belongs to exactly one image set. | `IMediaUploadGuard`, `IImageProcessor`, `IMediaStore`, `IHeroImageRepository`, `IIndexHtmlCache` |
|
||||
| `PublicHeroService` | Builds the public read model from the stored hero: schedule and `IsActive` applied, inactive slides removed, variants that exist listed, the first-slide choice made once here. | `IHeroRepository`, `TimeProvider` |
|
||||
| Core `MediaEndpoint` | Serves stored variants; no knowledge of the Hero module. | `IMediaStore` |
|
||||
| Core `CmsDataBlockTransform` | Composes the `#cms-data` block from all contributors. | `ICmsDataBlockContributor` implementations |
|
||||
| `HeroHtmlTransform`, `HeroPreloadMarkerProvider` | Write the region and the preload from the same `PublicHeroDto` through `HeroPictureRenderer`. | `IPublicHeroService` |
|
||||
|
||||
## Orchestration
|
||||
|
||||
### Upload of an image
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
box rgba(246,224,94,0.4) Admin
|
||||
participant A as Admin browser
|
||||
end
|
||||
box rgba(99,179,237,0.4) Host
|
||||
participant C as HeroImagesController
|
||||
participant S as HeroImageService
|
||||
participant G as MediaUploadGuard
|
||||
participant P as ImageProcessor
|
||||
participant M as MediaStore
|
||||
participant R as Repository
|
||||
end
|
||||
A->>C: POST image (multipart)
|
||||
C->>S: UploadAsync(stream, length, actor)
|
||||
S->>G: AdmitAsync (size, real format, bounds, timeout, gate)
|
||||
G-->>S: ImageInfo or rejection
|
||||
S->>M: Put original (set directory)
|
||||
S->>P: Render variants per ratio and width
|
||||
P-->>S: encoded files, metadata stripped
|
||||
S->>M: Put variants
|
||||
S->>R: Save HeroImage (hash, size, variants)
|
||||
S-->>C: HeroImageDto
|
||||
C-->>A: 201 with the image and its variants
|
||||
```
|
||||
|
||||
Text alternative: the admin uploads; the service admits the file, stores the original, renders and stores the variants, saves the metadata, and returns the image with its variant addresses.
|
||||
|
||||
Rules of the pipeline:
|
||||
1. Reject early (size, real format, pixel count, frame count, timeout); a rejection is a clear 400 and nothing is stored.
|
||||
2. Write to a temporary location first; only a completely processed set is made visible (one move per set). A failure removes the partial files.
|
||||
3. The set hash is computed from the original's SHA-256 and the crop parameters; the variant addresses contain it.
|
||||
4. At most a few uploads are processed in parallel (gate); the rest wait or get 429.
|
||||
|
||||
### Change of focus
|
||||
|
||||
`SetFocusAsync` validates the numbers (ranges), recomputes the set hash, renders the affected ratios again into the new set directory, saves the new addresses, then removes the old set directory (after the commit). A site that still holds the old data block keeps working until its cache expires (the old files go after a grace period, decided in Functional Design).
|
||||
|
||||
### Publishing and live updates
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Save["PUT /hero or image change"] --> Repo["Repository (commit)"]
|
||||
Repo --> Inval["IIndexHtmlCache.Invalidate()"]
|
||||
Inval --> Cache["HtmlMarkerInjector cache dropped"]
|
||||
Req["Next page request"] --> Inj["HtmlMarkerInjector"]
|
||||
Inj --> T1["CmsDataBlockTransform<br/>(offerings, banners, hero)"]
|
||||
Inj --> T2["HeroHtmlTransform<br/>(region + first slide)"]
|
||||
Inj --> T3["HeroPreloadMarkerProvider<br/>(head)"]
|
||||
T1 --> Pub["PublicHeroService"]
|
||||
T2 --> Pub
|
||||
T3 --> Pub
|
||||
Api["GET /api/v1/hero"] --> Pub
|
||||
classDef act fill:#FFA726,stroke:#E65100,color:#000;
|
||||
classDef core fill:#BBDEFB,stroke:#1565C0,color:#000;
|
||||
classDef mod fill:#9ae6b4,stroke:#2f855a,color:#000;
|
||||
class Save,Req,Api act;
|
||||
class Inval,Cache,Inj,T1 core;
|
||||
class Repo,T2,T3,Pub mod;
|
||||
```
|
||||
|
||||
Text alternative: a save commits and invalidates the page cache; the next page request rebuilds the page through the data block, region and preload, all reading the one public read model, which the public endpoint also uses.
|
||||
|
||||
### Failure behaviour
|
||||
|
||||
| Where | Behaviour |
|
||||
|---|---|
|
||||
| Upload or processing fails | Fail closed: 4xx with a generic message, partial files removed, nothing published. |
|
||||
| `PublicHeroService` fails or finds no active hero | Region, preload and `hero` key are left as baked (data block: `hero` is `null`; the site keeps the baked hero). The page is served. |
|
||||
| A contributor fails | The data block is left as baked entirely. |
|
||||
| Media file missing or unreadable | 404 for that address; the data block lists only variants that were stored. |
|
||||
| Storage unwritable | Upload fails with a generic 503-style message and an error log; public reads are unaffected. |
|
||||
|
||||
## Cross-cutting
|
||||
|
||||
- **Texts**: validation and rejection messages go through `ITextCatalog` with `HeroTexts` keys (`hero.validation.*`, `hero.image.*`); the technical rejection reason codes stay English constants.
|
||||
- **Authorization**: management routes `AdminOnly`; public routes anonymous and marked `[PublicSiteEndpoint]` so they pass the availability gate.
|
||||
- **Rate limiting**: new policies `hero-public` (120 per 60 s like offerings), `media-public` (high, per client address, allows the page's images), `hero-upload` (low, per user).
|
||||
- **Logging**: structured, with the request id, actor and image id; never file contents or file names from the client.
|
||||
- **Auditing**: `UpdatedBy`/`UpdatedAt` on the hero and `CreatedAt` plus actor on images, plus a log line per change (who, what, when) for SECURITY-13.
|
||||
- **Cache keys**: the injector's per-file cache already keys by page; hero changes call `Invalidate()` like offerings and banners do.
|
||||
Reference in New Issue
Block a user