From 0caceca728550cf36a96a87c9df955983c525dbf Mon Sep 17 00:00:00 2001 From: Sadeq Abu-Hattem Date: Mon, 16 Nov 2026 19:32:13 +0200 Subject: [PATCH 1/5] Record media changes in the audit trail where people look for them MediaAuditParticipant, a DotNetBoost.Media write participant, records each media change as an audit entry enlisted in the media store's own save: attach, detach and reorder as an Updated entry on the owner (so a product's trail shows its images), upload, edit and delete on ("Media", ). IgnoreEntity() and IgnoreEntity() keep the raw rows out of the trail. Tests cover a product image's life in the product and file trails, and a media write that fails after its entry was enlisted leaving nothing behind. Docs and documented counts updated. Needs DotNetBoost.Media's write participants, which arrive in the release after 1.0.0-preview.2; until then this builds only against local source. Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE-SLICES.md | 4 +- README.md | 66 +++++-- src/DotNetBoostSample.Api/Program.cs | 3 +- .../DependencyInjection.cs | 19 +- .../Persistence/AppDbContext.cs | 9 +- .../Persistence/MediaAuditParticipant.cs | 165 ++++++++++++++++++ .../Integration/AuditTrailTests.cs | 104 ++++++++++- .../Integration/SampleApp.cs | 43 ++++- 8 files changed, 382 insertions(+), 31 deletions(-) create mode 100644 src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs diff --git a/ARCHITECTURE-SLICES.md b/ARCHITECTURE-SLICES.md index b78d58f..5db02f4 100644 --- a/ARCHITECTURE-SLICES.md +++ b/ARCHITECTURE-SLICES.md @@ -5,7 +5,7 @@ the two disagreed the code won — §10 lists what changed on contact with the c written while the work sat on `feat/vertical-slices-cqrs` and still argues with itself about whether to merge it; §11.3 says how that ended. -The solution builds clean on `net8.0` and `net10.0` with `TreatWarningsAsErrors`, and all 172 tests +The solution builds clean on `net8.0` and `net10.0` with `TreatWarningsAsErrors`, and all 176 tests pass, including the integration suite that boots the real `Program.cs` against a throwaway PostgreSQL and drives every route over HTTP. No endpoint's URL, status code or JSON shape changed. @@ -56,7 +56,7 @@ compile against DotNetBoost's own `net8.0` TFM. This repo was **1,788 lines of C# in 13 files** when this was written, and the README's thesis is that the integration between three independent libraries is *five files, none of them large*. A -fourth library has since been installed, and that count is now nine files — see the README; the +fourth library has since been installed, and that count is now ten files — see the README; the reasoning below is unaffected. The one new file it would have changed its mind about, `Composition/CreationTrail.cs` — a creation's audit entry, written by hand in a scope of its own — is gone again: DotNetBoost.Auditing 1.0.0-preview.2 added `IgnoreEntity()`, its capture is now diff --git a/README.md b/README.md index 7592236..b11754d 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ What it demonstrates is as much what is *absent* as what is present: - no integration package pairing any two libraries Each library is installed and configured on its own. Everything that joins them is this -application's code, in nine files, [listed below](#where-the-composition-happens). `tests/` asserts +application's code, in ten files, [listed below](#where-the-composition-happens). `tests/` asserts that no library references another, so the claim cannot quietly stop being true. **Auditing was added last, to a solution the other three were already in** — the one measure of @@ -190,9 +190,9 @@ are `npm run lint`, `npm run typecheck`, `npm test` and `npm run test:e2e`. ## Where the composition happens -Nine files of this application's own code. Each is a place where it says two libraries are talking +Ten files of this application's own code. Each is a place where it says two libraries are talking about the same thing — the only way they ever find out, since none references another — or, for the -last three, where one library's data has no place in another's in the shape it is stored in: +last four, where one library's data has no place in another's in the shape it is stored in: | | File | Joins | What it says | |---|---|---|---| @@ -204,9 +204,10 @@ last three, where one library's data has no place in another's in the shape it i | 6 | `Infrastructure/DependencyInjection.cs` — one line | Auditing → MultiLingual | MultiLingual's translation row is not in the trail: `.IgnoreEntity()` | | 7 | `Domain/Catalog/Category.cs` and `Product.cs` | MultiLingual → Auditing | a translated property is not in the trail: `[AuditIgnore]` beside `[MultiLingual]` | | 8 | `Infrastructure/Persistence/SettingGroupAuditParticipant.cs` | Settings → Auditing | a settings save is one entry for the group, not one per row, committed with it | +| 9 | `Infrastructure/Persistence/MediaAuditParticipant.cs` | Media → Auditing | attaching a file is a change to the product it is attached to, and is recorded there, committed with it | -Nine files in eight entries, because the seventh is one sentence said once per entity. It was five -before Auditing arrived. Three of these exist because two libraries **disagree**, which is a worse +Ten files in nine entries, because the seventh is one sentence said once per entity. It was five +before Auditing arrived. Four of these exist because two libraries **disagree**, which is a worse kind of glue than "these two tables are about one thing" — and the reason the count is kept honest rather than tidy. @@ -217,9 +218,9 @@ it to Media is the string `"MediaFile"`, not a type. A join is an identity asser string, an attribute or a type both sides must agree on, which is why `BrandingOwnerTests`, `KeyFormatAgreementTests` and `AuditRuleTests` exist. -**Six of the nine name only `DotNetBoost.*.Core`**, so they live in the application and domain -layers beside the code that uses them. Only `AppDbContext`, the `IgnoreEntity` line and -`SettingGroupAuditParticipant` are infrastructure, and all three are there because four libraries share +**Six of the ten name only `DotNetBoost.*.Core`**, so they live in the application and domain +layers beside the code that uses them. Only `AppDbContext`, the `IgnoreEntity` lines, +`SettingGroupAuditParticipant` and `MediaAuditParticipant` are infrastructure, and all four are there because four libraries share **one `DbContext`**. Joining two libraries is not a persistence concern; joining them in one database is. @@ -513,6 +514,46 @@ Up to Settings `1.0.0-preview.2` this was an `ISettingWriteObserver`, which runs and whose failures the library logs and swallows. This was then the one entry that did not commit with its change. +### 9. A media change is recorded where people look for it — `src/.../Infrastructure/Persistence/MediaAuditParticipant.cs` + +DotNetBoost.Media stores a file as a `MediaFile` row and each use of it as a `MediaAttachment` row, +so the interceptor alone recorded attaching a photo to a product as a `MediaAttachment` entry +addressed by the link's own GUID, and a soft delete as a `MediaFile` change to `DeletedAt`. Product +42's own history said nothing. The media library knows what each write means, and lets code take +part in it through `IMediaWriteParticipant`, which runs inside the write, before the store saves: + +```csharp +// Media block +.UseWriteParticipant() + +// Auditing block +.IgnoreEntity() +.IgnoreEntity(); +``` + +The participant files each change where a reader would look for it: + +| Media change | Entry | +|---|---| +| attach, detach, reorder | `Updated` on the **owner** — `("Product", "42")` — with a `media.{role}` change naming the file | +| upload, edit, delete | `Created`, `Updated`, `Deleted` on `("Media", )`, with the file's name, type, size, category and tags | + +An attach can be filed under the product because Media's owner address and Auditing's entity +address are the same `(entityName, entityId)` — Entity Addressing v1, which +`KeyFormatAgreementTests` pins. A delete is one entry under the file plus a detach under each owner +that still used it, with one correlation id; so is a product delete's `DeleteAllAsync`. The file +entries are filed as `"Media"` rather than `"MediaFile"` with `MediaFileInfo` as their type, +because Auditing honours `IgnoreEntity()` by name when an entry has no type. + +**It commits with the change**, exactly as the settings participant does: Media's EF Core store, +Auditing's and the participant share the request's `AppDbContext`, the entry and its change rows +are enlisted with `EfCoreMediaWriteScope.Add`, and the media store's own save carries them. A +participant that throws aborts the media write and everything enlisted is detached again. +`AuditTrailTests` checks both halves, the second with a test-only participant that fails the write +after the entry is enlisted. + +Needs DotNetBoost.Media's write participants, which arrive in the release after `1.0.0-preview.2`. + --- ## Two places a language can live @@ -580,7 +621,7 @@ as `""` where the default mode answers `null`, because the column is a non-nulla `dotnet test` boots the sample twice, in two hosts against two schemas. -**The whole integration suite runs in both modes**: sixty-two tests against each, the same +**The whole integration suite runs in both modes**: sixty-four tests against each, the same assertions, unchanged — and between them they call **every one of the API's 48 published routes**. `OpenApiShapeTests` asserts that inventory by name, so a route added by this application or a new library version fails the suite rather than going uncalled. @@ -674,10 +715,10 @@ abstract class holds the assertions and two sealed subclasses bind it to each fi - **`SchemaUpgradeTests`** — a database from the HiLo builds, of either kind, gets identity keys back, counting past its existing rows. - **`BaseLanguageTests`** — what only base-language mode can be asked. - Sixteen tests, beside the sixty-two the suite runs in each mode. + Sixteen tests, beside the sixty-four the suite runs in each mode. **Without a container runtime these skip rather than fail** — `dotnet test` still runs the 30 fast -tests and reports the other 142 as skipped, with the reason. +tests and reports the other 146 as skipped, with the reason. ### And the dashboard's own @@ -795,7 +836,7 @@ A duplicate slug or SKU never reaches a handler: the unique index refuses it, an `409`. Reading a `PostgresException` cannot happen in `Application` and `IExceptionHandler` cannot happen in `Infrastructure`, so the translator is an interface implemented on the provider's side. -### Why four projects for 47 files +### Why four projects for 48 files It is more structure than 1,800 lines of behaviour needs, deliberately: the dependency rules above are enforced by the build, not by a comment. The cost is that a route no longer shows what it does — @@ -823,6 +864,7 @@ src/DotNetBoostSample.Infrastructure/ Persistence/Configurations/ one per entity: tables and unique indexes Persistence/DatabaseInitialiser.cs schema and seed on first run, and upgrades for old volumes Persistence/SettingGroupAuditParticipant.cs + Persistence/MediaAuditParticipant.cs Persistence/PostgresErrorTranslator.cs DependencyInjection.cs AddInfrastructure(): four independent blocks src/DotNetBoostSample.Api/ diff --git a/src/DotNetBoostSample.Api/Program.cs b/src/DotNetBoostSample.Api/Program.cs index 546a866..3d282c5 100644 --- a/src/DotNetBoostSample.Api/Program.cs +++ b/src/DotNetBoostSample.Api/Program.cs @@ -24,12 +24,13 @@ // kernel and no integration package, and tests/ZeroCouplingTests.cs fails the build if that // changes. // -// What joins them is nine files of this application's own code. The README's "Where the +// What joins them is ten files of this application's own code. The README's "Where the // composition happens" says what each one does and why: // // Infrastructure/Persistence/AppDbContext.cs — all four: one Apply* call each // Infrastructure/DependencyInjection.cs — .IgnoreEntity() // Infrastructure/Persistence/SettingGroupAuditParticipant.cs — one audit entry per settings save +// Infrastructure/Persistence/MediaAuditParticipant.cs — media changes, in the owner's trail // Application/Composition/MediaText.cs — a file's per-language alt text // Application/Composition/MediaTextCleanup.cs — deleted with the file // Application/Composition/MultiLingualSchemaContributor.cs — `translated` in settings schemas diff --git a/src/DotNetBoostSample.Infrastructure/DependencyInjection.cs b/src/DotNetBoostSample.Infrastructure/DependencyInjection.cs index 9f5d67a..3ea16d0 100644 --- a/src/DotNetBoostSample.Infrastructure/DependencyInjection.cs +++ b/src/DotNetBoostSample.Infrastructure/DependencyInjection.cs @@ -1,5 +1,6 @@ using DotNetBoost.Auditing.Core; using DotNetBoost.Media.Core.Interfaces; +using DotNetBoost.Media.Core.Models; using DotNetBoost.MultiLingual.Core; using DotNetBoost.MultiLingual.Core.Models; using DotNetBoost.Settings.Core.Interfaces; @@ -126,6 +127,10 @@ public static IServiceCollection AddInfrastructure( // A deleted file's alt text goes with it, whoever deleted it — including Media's own // DELETE /api/media/{id}. Only files actually deleted, not ones merely detached. .OnFilesDeleted() + // An audit entry per upload, attach, detach, reorder, edit and delete — the attaches + // filed under the product they were attached to — enlisted in the media store's own + // save, so each entry commits with its change or not at all. + .UseWriteParticipant() .Build(); // ── DotNetBoost.MultiLingual ───────────────────────────────────────── @@ -173,8 +178,14 @@ public static IServiceCollection AddInfrastructure( // for the group instead — enlisted in the settings store's own save, so it commits // atomically with its change like every other entry. // - // Every other mapped entity is captured, because that is the library's default — MediaFile, - // MediaAttachment and Language as well as the catalogue. + // 4. Media. A file is a MediaFile row and each use of it a MediaAttachment row, so the + // interceptor alone recorded an attach under the link's own GUID and nothing under the + // product. IgnoreEntity() and IgnoreEntity() keep the rows + // out, and MediaAuditParticipant records each change instead — an attach under the + // product, a delete under the file — enlisted in the media store's own save. + // + // Every other mapped entity is captured, because that is the library's default — Language + // as well as the catalogue. var auditing = services .AddAuditing() // In AppDbContext, which is what makes a change and its entry commit together: the @@ -184,7 +195,9 @@ public static IServiceCollection AddInfrastructure( // finds types carrying the library's attributes and these two carry none. .DeclareEntities(typeof(Category), typeof(Product)) .IgnoreEntity() - .IgnoreEntity(); + .IgnoreEntity() + .IgnoreEntity() + .IgnoreEntity(); // No o.Retention: retention is the runtime-editable `auditing` settings group, applied by // the host's AuditRetentionService. An option here is read once, at Build(), and could not diff --git a/src/DotNetBoostSample.Infrastructure/Persistence/AppDbContext.cs b/src/DotNetBoostSample.Infrastructure/Persistence/AppDbContext.cs index ad38572..6a65448 100644 --- a/src/DotNetBoostSample.Infrastructure/Persistence/AppDbContext.cs +++ b/src/DotNetBoostSample.Infrastructure/Persistence/AppDbContext.cs @@ -31,15 +31,16 @@ namespace DotNetBoostSample.Infrastructure.Persistence; /// which both libraries' 1.0.0-preview.3 made it. That file has both. /// /// -/// It is also one of only three of the nine composition files that are infrastructure; the -/// others are that one line in DependencyInjection.cs and +/// It is also one of only four of the ten composition files that are infrastructure; the +/// others are the IgnoreEntity lines in DependencyInjection.cs, /// SettingGroupAuditParticipant, which enlists its entry in the settings store's save on this -/// context. The remaining six — +/// context, and MediaAuditParticipant, which does the same in the media store's. The +/// remaining six — /// MediaText, MediaTextCleanup, MultiLingualSchemaContributor, /// BrandingProjector and the two entities' attributes — depend on DotNetBoost.*.Core /// and nothing else, so they live in the application and domain layers beside the code that uses /// them. Joining two libraries turns out not to be a persistence concern; joining them in one -/// database is, and all three infrastructure files are about exactly that. +/// database is, and all four infrastructure files are about exactly that. /// /// /// is the application layer's view of it: the two DbSets and diff --git a/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs b/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs new file mode 100644 index 0000000..2e1cf6e --- /dev/null +++ b/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs @@ -0,0 +1,165 @@ +using System.Globalization; +using DotNetBoost.Auditing.Core.Interfaces; +using DotNetBoost.Auditing.Core.Models; +using DotNetBoost.Media.Core.Interfaces; +using DotNetBoost.Media.Core.Models; +using DotNetBoost.Media.EntityFrameworkCore; + +namespace DotNetBoostSample.Infrastructure.Persistence; + +/// +/// Records what happens to media as entries people can read — "Product 42's gallery gained +/// desk.png", "desk.png was deleted" — in the same transaction as the media rows. +/// +/// Why not the interceptor. DotNetBoost.Media stores a file as a MediaFile row +/// and each use of it as a MediaAttachment row, and the interceptor sees rows. So attaching a +/// photo to a product wrote a MediaAttachment Created entry addressed by the link's +/// own GUID, and a soft delete wrote a MediaFile Updated entry whose only change was +/// DeletedAt. Product 42's own history said nothing at all. The media library knows what +/// each write means — it calls once per change, with the file, +/// the owner and the role — so both row types are ignored by the capture and this writes the +/// entries instead. +/// +/// Where each change is filed. An attach, a detach and a reorder are changes to the +/// owner: they are filed under the owner's (entityName, entityId), as an +/// Updated entry with a media.{role} change, so they show up in the product's own +/// trail beside its price changes. That works because Media's owner address and Auditing's entity +/// address are the same thing, Entity Addressing v1 (KeyFormatAgreementTests pins it). An +/// upload, an edit and a delete are about the file, and are filed under +/// and the file's id. A delete is one entry under the file plus a detach +/// under each owner that still used it — all three with one correlation id. +/// +/// Why the file entries are not called MediaFile. IgnoreEntity<MediaFile>() +/// keeps the rows out, and Auditing honours an ignore by name when a write has no type — so an entry +/// addressed as "MediaFile" would be dropped. They are filed as "Media" with +/// as their type: the record Media describes a file with, which is what +/// the entry is about, and which is not ignored. A typed write also keeps Auditing from logging, on +/// every upload, that it recorded an undeclared entity with no model rules. +/// +/// Why it commits with the change. Exactly as for : +/// this runs inside the media write, before the store saves; Media's EF Core store, Auditing's +/// EF Core store and this class all resolve the request's one , so +/// IAuditManager.RecordAsync tracks the entry on the context the media store is about to +/// save. It goes out in that save or not at all, and anything this throws aborts the media write. +/// The entry and each change row are enlisted with , so a write +/// that does not commit takes all of them back off the context. +/// +/// No actor is passed: Media has no notion of one, and a null actor falls back to the +/// request's caller, which is who made the change. +/// +public sealed class MediaAuditParticipant(IAuditManager audit, EfCoreMediaWriteScope mediaWrite) + : IMediaWriteParticipant +{ + /// The entity name a file's own entries are stored under. + public const string FileEntityName = "Media"; + + /// + public async Task OnWritingAsync(MediaChange change, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(change); + + var entry = await audit.RecordAsync(Describe(change), ct); + + // Null when Auditing chose not to record it — recording switched off, or an edit that + // changed nothing it keeps. Nothing to enlist. + if (entry is null) return; + + // The whole graph, so a write that does not commit takes all of it back. + mediaWrite.Add(entry); + foreach (var row in entry.Changes) + mediaWrite.Add(row); + } + + private static AuditWrite Describe(MediaChange change) => change.Kind switch + { + MediaChangeKind.Attached => OnOwner(change, $"media.{change.Role}", null, Name(change)), + MediaChangeKind.Detached => OnOwner(change, $"media.{change.Role}", Name(change), null), + MediaChangeKind.Reordered => OnOwner(change, $"media.{change.Role}.position", + $"{Name(change)} #{change.PreviousSortOrder}", + $"{Name(change)} #{change.SortOrder}"), + + MediaChangeKind.Uploaded => OnFile(change, AuditAction.Created, Values(change.File)), + MediaChangeKind.Updated => OnFile(change, AuditAction.Updated, Values(change.File, before: change.Previous)), + MediaChangeKind.Deleted => OnFile(change, AuditAction.Deleted, Values(change.File, deleted: true)), + + _ => throw new InvalidOperationException( + $"DotNetBoost.Media reported a {change.Kind} change, which this participant does not know how " + + "to record. Refusing the write rather than leaving it out of the trail.") + }; + + /// A change to which files an entity uses, filed under that entity. + private static AuditWrite OnOwner(MediaChange change, string property, string? oldValue, string? newValue) + { + var owner = change.Owner + ?? throw new InvalidOperationException($"A {change.Kind} media change arrived without its owner."); + + return new AuditWrite + { + EntityName = owner.EntityName, + EntityId = owner.EntityId, + Action = AuditAction.Updated, + Changes = [new AuditChange(property, oldValue, newValue)], + CorrelationId = change.CorrelationId, + }; + } + + /// A change to the file itself, filed under . + private static AuditWrite OnFile(MediaChange change, AuditAction action, IReadOnlyList changes) => new() + { + EntityName = FileEntityName, + EntityId = change.MediaFileId.ToString("D"), + EntityType = typeof(MediaFileInfo), + Action = action, + Changes = changes, + CorrelationId = change.CorrelationId, + }; + + /// + /// The file's recorded properties as changes. An upload reports each as a new value and a + /// delete each as an old one — the file as it was, which after the delete is the only copy of + /// its name. An edit reports only what moved, from to + /// . + /// + private static List Values(MediaFileInfo? file, MediaFileInfo? before = null, bool deleted = false) + { + if (file is null) return []; + + var edit = before is not null; + var changes = new List(); + + void Add(string name, string? value, string? previous = null) + { + if (deleted) + changes.Add(new AuditChange(name, value, null)); + else if (!edit || !string.Equals(value, previous, StringComparison.Ordinal)) + changes.Add(new AuditChange(name, previous, value)); + } + + Add(nameof(MediaFileInfo.FileName), file.FileName, before?.FileName); + Add(nameof(MediaFileInfo.Category), file.Category, before?.Category); + Add(nameof(MediaFileInfo.Tags), Join(file.Tags), before is null ? null : Join(before.Tags)); + Add(nameof(MediaFileInfo.Metadata), Join(file.Metadata), before is null ? null : Join(before.Metadata)); + + // Fixed at upload, so never part of an edit. + if (!edit) + { + Add(nameof(MediaFileInfo.ContentType), file.ContentType); + Add(nameof(MediaFileInfo.Size), file.Size.ToString(CultureInfo.InvariantCulture)); + } + + return changes; + } + + private static string? Join(IReadOnlyList tags) => tags.Count == 0 ? null : string.Join(",", tags); + + private static string? Join(IReadOnlyDictionary metadata) => + metadata.Count == 0 + ? null + : string.Join(";", metadata.OrderBy(p => p.Key, StringComparer.Ordinal).Select(p => $"{p.Key}={p.Value}")); + + /// How an entry names a file: its name and its id, since names repeat. + private static string Name(MediaChange change) => + change.File is { } file + ? $"{file.FileName} ({change.MediaFileId:D})" + : change.MediaFileId.ToString("D"); +} diff --git a/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs b/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs index 025cd15..cf843c6 100644 --- a/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs +++ b/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs @@ -1,4 +1,5 @@ using DotNetBoost.Auditing.Core.Models; +using DotNetBoost.Media.Core.Interfaces; using DotNetBoost.Settings.Core.Interfaces; using DotNetBoostSample.Api.Authentication; using DotNetBoostSample.Application.Settings; @@ -339,6 +340,96 @@ await Assert.ThrowsAsync(() => Assert.Equal(before.Int("pageSize"), (await client.GetJsonAsync("/api/settings/catalog")).Int("pageSize")); } + /// + /// A product image's whole life, in the trails people actually read: the upload under the file, + /// the attach and — when the product is deleted — the detach under the product, and the + /// delete under the file. None of DotNetBoost.Media's own rows are in the trail. + /// + /// The interceptor alone recorded this as a MediaAttachment entry addressed by the + /// link's own GUID, and a soft delete as a MediaFile Updated entry about + /// DeletedAt; the product's trail said nothing. IgnoreEntity<MediaFile>() + /// and IgnoreEntity<MediaAttachment>() keep the rows out, and + /// records each change as DotNetBoost.Media reports it — + /// under the product, because Media's owner address and Auditing's entity address are the same + /// (entityName, entityId). + /// + [RequiresDockerFact] + public async Task A_product_images_life_is_in_the_product_and_file_trails() + { + var client = app.Client.AsActor("media.editor@example.com"); + var id = await client.CreateProductAsync(app.SeededCategoryId, "Has a photo"); + + var upload = await client.UploadAsync($"/api/products/{id}/images?role=gallery", "lamp.png"); + var fileId = upload.Str("id"); + var named = $"lamp.png ({fileId})"; + + // The attach, in the product's own trail, by whoever made it. + var attached = (await Trail(client, "Product", id)).Single(e => Changes(e).ContainsKey("media.gallery")); + Assert.Equal("Updated", attached.Str("action")); + Assert.Equal("media.editor@example.com", attached.Str("actor")); + Assert.Equal(named, Changes(attached)["media.gallery"].Str("newValue")); + + // The upload, under the file — and the attach shares its correlation id: one call. + var uploaded = Assert.Single(await FileTrail(client, fileId)); + Assert.Equal("Created", uploaded.Str("action")); + Assert.Equal("lamp.png", Changes(uploaded)["FileName"].Str("newValue")); + Assert.Equal(uploaded.Str("correlationId"), attached.Str("correlationId")); + + // Deleting the product deletes the image only it held: detached from the product, then + // deleted, both recorded. + await client.SendJsonCheckedAsync(HttpMethod.Delete, $"/api/products/{id}"); + + var productTrail = await Trail(client, "Product", id); + var detached = productTrail.Single(e => + Changes(e).TryGetValue("media.gallery", out var c) && c.Str("oldValue") == named); + Assert.Contains(productTrail, e => e.Str("action") == "Deleted"); + + var fileTrail = await FileTrail(client, fileId); + Assert.Equal(["Created", "Deleted"], fileTrail.Select(e => e.Str("action")).Order()); + + var deleted = fileTrail.Single(e => e.Str("action") == "Deleted"); + Assert.Equal("lamp.png", Changes(deleted)["FileName"].Str("oldValue")); + Assert.Equal(deleted.Str("correlationId"), detached.Str("correlationId")); + + // And not one of the media library's rows, from this test or any other. + Assert.Equal("0", await app.ScalarAsync( + "SELECT COUNT(*) FROM \"AuditEntries\" WHERE \"EntityName\" IN ('MediaFile', 'MediaAttachment')")); + } + + /// + /// A media write that fails after its entry was recorded leaves the file unattached, no entry in + /// the trail, and nothing pending on the caller's context. + /// + /// The media counterpart of the settings test above. runs + /// after , so the entry and its change row are enlisted when + /// it throws, and DotNetBoost.Media has to take them back. The last save is the trap: an entry + /// left Added would be inserted by the context's next unrelated save. + /// + [RequiresDockerFact] + public async Task A_media_write_that_fails_leaves_the_link_and_the_trail_as_they_were() + { + var client = app.Client.AsActor(); + var id = await client.CreateProductAsync(app.SeededCategoryId, "Refuses a photo"); + var fileId = Guid.Parse((await client.UploadAsync("/api/media", "refused.png")).Str("id")); + var before = (await Trail(client, "Product", id)).Count; + + await app.WithScopeAsync(async services => + { + var db = services.GetRequiredService(); + services.GetRequiredService().Armed = true; + + await Assert.ThrowsAsync(() => + services.GetRequiredService().For("Product", id.ToString()).AddAsync(fileId, "gallery")); + + Assert.False(db.ChangeTracker.HasChanges()); + Assert.Equal(0, await db.SaveChangesAsync()); + }); + + Assert.Equal(before, (await Trail(client, "Product", id)).Count); + Assert.Equal("0", await app.ScalarAsync( + $"SELECT COUNT(*) FROM \"MediaAttachments\" WHERE \"MediaFileId\" = '{fileId}'")); + } + /// /// GET /api/audit/{id} — one entry, read by the id the page carries, with its changes. /// @@ -509,9 +600,11 @@ public async Task A_caller_who_names_nobody_is_the_default_sample_user() /// /// Declared is not the same as recorded, and this is where the difference shows. The /// list is what DeclareEntities named, so it is the application's own two; the trail is - /// wider — MediaFile and the rest are recorded too, by the interceptor, and a settings - /// group by its participant, as shows. And Translation is - /// neither: ignored, so it cannot be declared, which Build() enforces. + /// wider — Language is recorded too, by the interceptor, a settings group by its + /// participant, as shows, and a media + /// file under Media by its. And Translation, MediaFile and + /// MediaAttachment are neither: ignored, so they cannot be declared, which Build() + /// enforces. /// /// It also publishes maxPageSize, so a client can stop asking for more than it /// will ever be given rather than discovering the clamp by comparing take with what it @@ -732,6 +825,11 @@ private static async Task> GroupTrail(HttpClient client) => $"/api/audit?entityName={SettingGroupAuditParticipant.EntityName}&entityId={nameof(CatalogSettings)}")) .GetProperty("entries").EnumerateArray()]; + /// A media file's own entries, newest first. + private static async Task> FileTrail(HttpClient client, string fileId) => + [.. (await client.GetJsonAsync($"/api/audit?entityName={MediaAuditParticipant.FileEntityName}&entityId={fileId}")) + .GetProperty("entries").EnumerateArray()]; + /// One entity's entries, newest first. private static async Task> Trail(HttpClient client, string entityName, int entityId) => [.. (await client.GetJsonAsync($"/api/audit?entityName={entityName}&entityId={entityId}")) diff --git a/tests/DotNetBoostSample.Tests/Integration/SampleApp.cs b/tests/DotNetBoostSample.Tests/Integration/SampleApp.cs index 5561d8f..d134bc1 100644 --- a/tests/DotNetBoostSample.Tests/Integration/SampleApp.cs +++ b/tests/DotNetBoostSample.Tests/Integration/SampleApp.cs @@ -1,4 +1,6 @@ using DotNetBoostSample.Infrastructure.Persistence; +using DotNetBoost.Media.Core.Interfaces; +using DotNetBoost.Media.Core.Models; using DotNetBoost.Settings.Core.Interfaces; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; @@ -29,10 +31,11 @@ namespace DotNetBoostSample.Tests.Integration; /// /// Two things are overridden, both infrastructure rather than composition: the /// connection string, so the run gets a throwaway database, and Media:Root, so uploaded -/// bytes land in a temporary directory instead of the repository's media folder. One thing is -/// added: , a settings write participant that does nothing -/// until a test arms it in its own scope — the one way to make a settings write fail after the -/// application's own participant has enlisted its audit entry. +/// bytes land in a temporary directory instead of the repository's media folder. Two things are +/// added: and , write +/// participants that do nothing until a test arms one in its own scope — the one way to make a +/// settings or media write fail after the application's own participant has enlisted its audit +/// entry. /// /// Postgres comes from Testcontainers. The README already asks for a container runtime to /// run the sample at all, so this adds no prerequisite — and where there is no Docker the tests @@ -212,8 +215,9 @@ public WebApplicationFactory Boot(string connectionString) => /// /// What a test can switch on in a scope of its own, and nothing else can: see - /// . Added after the application's registrations, so the - /// sabotage runs after SettingGroupAuditParticipant has enlisted its entry. + /// and . Added after the + /// application's registrations, so each sabotage runs after SettingGroupAuditParticipant + /// or MediaAuditParticipant has enlisted its entry. /// /// And Auditing:OnLostAtomicity set to Throw: a save whose audit entries /// can no longer commit with it fails the test that made it, rather than logging an error @@ -227,6 +231,9 @@ private static void UseTestHooks(IWebHostBuilder builder) { services.AddScoped(); services.AddScoped(sp => sp.GetRequiredService()); + + services.AddScoped(); + services.AddScoped(sp => sp.GetRequiredService()); }); } @@ -293,3 +300,27 @@ public Task OnWritingAsync(SettingWrite write, CancellationToken cancellationTok /// What throws, so a test can tell it from a real failure. public sealed class SettingsWriteSabotagedException(string group) : Exception($"The test failed the write to settings group '{group}' on purpose."); + +/// +/// The media counterpart of : a media write participant that +/// fails the write, but only in a scope where a test has set . +/// +/// Registered after the application's own participant, so when it throws, +/// MediaAuditParticipant has already recorded and enlisted the entry — and DotNetBoost.Media +/// has to take it back off the request's context. +/// +public sealed class MediaWriteSabotage : IMediaWriteParticipant +{ + /// Set by a test, in its own scope, to fail that scope's next media write. + public bool Armed { get; set; } + + /// + public Task OnWritingAsync(MediaChange change, CancellationToken ct) => + Armed + ? throw new MediaWriteSabotagedException(change.Kind) + : Task.CompletedTask; +} + +/// What throws, so a test can tell it from a real failure. +public sealed class MediaWriteSabotagedException(MediaChangeKind kind) + : Exception($"The test failed a media {kind} write on purpose."); From 5ff17f1283080cf33fa4a4893df05c60bb1a9d12 Mon Sep 17 00:00:00 2001 From: Sadeq Abu-Hattem Date: Tue, 17 Nov 2026 20:54:56 +0200 Subject: [PATCH 2/5] Record media changes on the owner with the operation in metadata MediaAuditParticipant now writes one Updated entry on the product or category per media operation: the role as the row (Banner, Gallery), file names as the values, and the operation in Metadata as JSON ({"media":"Attach|Detach|Replace|Reorder","fileId":...}). A replace is one entry (old file -> new file), a reorder one entry with the whole order before and after, and a file delete adds a detach on each owner marked "reason":"FileDeleted". Upload, edit and delete stay on ("Media", id), without rows for properties the file never had. Built on DotNetBoost.Media's one-change-per-operation reporting; needs the Media release after 1.0.0-preview.2. Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE-SLICES.md | 2 +- README.md | 34 ++-- .../Persistence/MediaAuditParticipant.cs | 191 ++++++++++++------ .../Integration/AuditTrailTests.cs | 79 ++++++-- 4 files changed, 222 insertions(+), 84 deletions(-) diff --git a/ARCHITECTURE-SLICES.md b/ARCHITECTURE-SLICES.md index 5db02f4..a456b84 100644 --- a/ARCHITECTURE-SLICES.md +++ b/ARCHITECTURE-SLICES.md @@ -5,7 +5,7 @@ the two disagreed the code won — §10 lists what changed on contact with the c written while the work sat on `feat/vertical-slices-cqrs` and still argues with itself about whether to merge it; §11.3 says how that ended. -The solution builds clean on `net8.0` and `net10.0` with `TreatWarningsAsErrors`, and all 176 tests +The solution builds clean on `net8.0` and `net10.0` with `TreatWarningsAsErrors`, and all 178 tests pass, including the integration suite that boots the real `Program.cs` against a throwaway PostgreSQL and drives every route over HTTP. No endpoint's URL, status code or JSON shape changed. diff --git a/README.md b/README.md index b11754d..d0d6050 100644 --- a/README.md +++ b/README.md @@ -531,19 +531,29 @@ part in it through `IMediaWriteParticipant`, which runs inside the write, before .IgnoreEntity(); ``` -The participant files each change where a reader would look for it: +Media reports each operation once — an attach, a detach, a replacement, a reorder, a delete — and +the participant files it where a reader would look for it. A change to which files an entity uses +is an `Updated` entry **on that entity**, with one row named after the role, file names as its +values, and the operation in the entry's `Metadata`: -| Media change | Entry | -|---|---| -| attach, detach, reorder | `Updated` on the **owner** — `("Product", "42")` — with a `media.{role}` change naming the file | -| upload, edit, delete | `Created`, `Updated`, `Deleted` on `("Media", )`, with the file's name, type, size, category and tags | +| Operation | Entry | Row | Metadata | +|---|---|---|---| +| attach | Category 4 | `Banner: — → photo.png` | `{"media":"Attach","fileId":"…"}` | +| detach | Category 4 | `Banner: photo.png → —` | `{"media":"Detach","fileId":"…"}` | +| replace | Category 4 | `Banner: photo.png → new.png` | `{"media":"Replace","fileId":"…","previousFileId":"…"}` | +| reorder | Product 42 | `Gallery: a.png, b.png → b.png, a.png` | `{"media":"Reorder"}` | + +An upload, an edit and a delete are about the file itself: `Created`, `Updated` and `Deleted` on +`("Media", )`, with its name, type, size, category and tags. A delete also writes a detach +on every entity that still used the file, marked `"reason":"FileDeleted"`, so a product's history +says why its image went; all of them share one correlation id. An attach can be filed under the product because Media's owner address and Auditing's entity address are the same `(entityName, entityId)` — Entity Addressing v1, which -`KeyFormatAgreementTests` pins. A delete is one entry under the file plus a detach under each owner -that still used it, with one correlation id; so is a product delete's `DeleteAllAsync`. The file -entries are filed as `"Media"` rather than `"MediaFile"` with `MediaFileInfo` as their type, -because Auditing honours `IgnoreEntity()` by name when an entry has no type. +`KeyFormatAgreementTests` pins. The file's id is in the metadata rather than the row, which keeps +the row readable and still tells two files with the same name apart. The file entries are filed as +`"Media"` rather than `"MediaFile"` with `MediaFileInfo` as their type, because Auditing honours +`IgnoreEntity()` by name when an entry has no type. **It commits with the change**, exactly as the settings participant does: Media's EF Core store, Auditing's and the participant share the request's `AppDbContext`, the entry and its change rows @@ -621,7 +631,7 @@ as `""` where the default mode answers `null`, because the column is a non-nulla `dotnet test` boots the sample twice, in two hosts against two schemas. -**The whole integration suite runs in both modes**: sixty-four tests against each, the same +**The whole integration suite runs in both modes**: sixty-five tests against each, the same assertions, unchanged — and between them they call **every one of the API's 48 published routes**. `OpenApiShapeTests` asserts that inventory by name, so a route added by this application or a new library version fails the suite rather than going uncalled. @@ -715,10 +725,10 @@ abstract class holds the assertions and two sealed subclasses bind it to each fi - **`SchemaUpgradeTests`** — a database from the HiLo builds, of either kind, gets identity keys back, counting past its existing rows. - **`BaseLanguageTests`** — what only base-language mode can be asked. - Sixteen tests, beside the sixty-four the suite runs in each mode. + Sixteen tests, beside the sixty-five the suite runs in each mode. **Without a container runtime these skip rather than fail** — `dotnet test` still runs the 30 fast -tests and reports the other 146 as skipped, with the reason. +tests and reports the other 148 as skipped, with the reason. ### And the dashboard's own diff --git a/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs b/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs index 2e1cf6e..319e783 100644 --- a/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs +++ b/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Text.Json; using DotNetBoost.Auditing.Core.Interfaces; using DotNetBoost.Auditing.Core.Models; using DotNetBoost.Media.Core.Interfaces; @@ -9,25 +10,37 @@ namespace DotNetBoostSample.Infrastructure.Persistence; /// /// Records what happens to media as entries people can read — "Product 42's gallery gained -/// desk.png", "desk.png was deleted" — in the same transaction as the media rows. +/// desk.png", "Category 4's banner went from old.png to new.png" — in the same transaction as the +/// media rows. /// /// Why not the interceptor. DotNetBoost.Media stores a file as a MediaFile row /// and each use of it as a MediaAttachment row, and the interceptor sees rows. So attaching a /// photo to a product wrote a MediaAttachment Created entry addressed by the link's /// own GUID, and a soft delete wrote a MediaFile Updated entry whose only change was -/// DeletedAt. Product 42's own history said nothing at all. The media library knows what -/// each write means — it calls once per change, with the file, -/// the owner and the role — so both row types are ignored by the capture and this writes the -/// entries instead. +/// DeletedAt. Product 42's own history said nothing at all. The media library tells an +/// about each operation — one change per attach, detach, +/// replacement, reorder or delete — so both row types are ignored by the capture and this writes +/// the entries instead. /// -/// Where each change is filed. An attach, a detach and a reorder are changes to the -/// owner: they are filed under the owner's (entityName, entityId), as an -/// Updated entry with a media.{role} change, so they show up in the product's own -/// trail beside its price changes. That works because Media's owner address and Auditing's entity -/// address are the same thing, Entity Addressing v1 (KeyFormatAgreementTests pins it). An -/// upload, an edit and a delete are about the file, and are filed under -/// and the file's id. A delete is one entry under the file plus a detach -/// under each owner that still used it — all three with one correlation id. +/// The format. A change to which files an entity uses is an Updated entry on +/// that entity, with one row named after the role and the file names as its values, and the +/// operation in Metadata: +/// +/// AttachBanner | — | photo.png, {"media":"Attach","fileId":…} +/// DetachBanner | photo.png | —, {"media":"Detach","fileId":…} +/// ReplaceBanner | photo.png | new.png, {"media":"Replace","fileId":…,"previousFileId":…} +/// ReorderGallery | a.png, b.png | b.png, a.png, {"media":"Reorder"} +/// +/// The entity is the owner Media reports, filed under its own (entityName, entityId), +/// so the change shows up in the product's history beside its price changes. That works because +/// Media's owner address and Auditing's entity address are the same thing, Entity Addressing v1 +/// (KeyFormatAgreementTests pins it). The file's id goes in Metadata rather than the +/// row, which keeps the row readable and still tells two files with the same name apart. +/// +/// An upload, an edit and a delete are about the file, and are filed under +/// and the file's id. A delete also writes a detach on every entity the +/// file was still attached to — Media lists them on the one delete change — marked +/// "reason":"FileDeleted", so a product's history says why its image went. /// /// Why the file entries are not called MediaFile. IgnoreEntity<MediaFile>() /// keeps the rows out, and Auditing honours an ignore by name when a write has no type — so an entry @@ -39,9 +52,9 @@ namespace DotNetBoostSample.Infrastructure.Persistence; /// Why it commits with the change. Exactly as for : /// this runs inside the media write, before the store saves; Media's EF Core store, Auditing's /// EF Core store and this class all resolve the request's one , so -/// IAuditManager.RecordAsync tracks the entry on the context the media store is about to -/// save. It goes out in that save or not at all, and anything this throws aborts the media write. -/// The entry and each change row are enlisted with , so a write +/// IAuditManager.RecordAsync tracks each entry on the context the media store is about to +/// save. They go out in that save or not at all, and anything this throws aborts the media write. +/// Each entry and its change rows are enlisted with , so a write /// that does not commit takes all of them back off the context. /// /// No actor is passed: Media has no notion of one, and a null actor falls back to the @@ -58,62 +71,122 @@ public async Task OnWritingAsync(MediaChange change, CancellationToken ct) { ArgumentNullException.ThrowIfNull(change); - var entry = await audit.RecordAsync(Describe(change), ct); + foreach (var write in Describe(change)) + { + var entry = await audit.RecordAsync(write, ct); - // Null when Auditing chose not to record it — recording switched off, or an edit that - // changed nothing it keeps. Nothing to enlist. - if (entry is null) return; + // Null when Auditing chose not to record it — recording switched off, or an edit that + // changed nothing it keeps. Nothing to enlist. + if (entry is null) continue; - // The whole graph, so a write that does not commit takes all of it back. - mediaWrite.Add(entry); - foreach (var row in entry.Changes) - mediaWrite.Add(row); + // The whole graph, so a write that does not commit takes all of it back. + mediaWrite.Add(entry); + foreach (var row in entry.Changes) + mediaWrite.Add(row); + } } - private static AuditWrite Describe(MediaChange change) => change.Kind switch + private static IEnumerable Describe(MediaChange change) { - MediaChangeKind.Attached => OnOwner(change, $"media.{change.Role}", null, Name(change)), - MediaChangeKind.Detached => OnOwner(change, $"media.{change.Role}", Name(change), null), - MediaChangeKind.Reordered => OnOwner(change, $"media.{change.Role}.position", - $"{Name(change)} #{change.PreviousSortOrder}", - $"{Name(change)} #{change.SortOrder}"), - - MediaChangeKind.Uploaded => OnFile(change, AuditAction.Created, Values(change.File)), - MediaChangeKind.Updated => OnFile(change, AuditAction.Updated, Values(change.File, before: change.Previous)), - MediaChangeKind.Deleted => OnFile(change, AuditAction.Deleted, Values(change.File, deleted: true)), - - _ => throw new InvalidOperationException( - $"DotNetBoost.Media reported a {change.Kind} change, which this participant does not know how " + - "to record. Refusing the write rather than leaving it out of the trail.") - }; + switch (change.Kind) + { + case MediaChangeKind.Attached: + yield return OnOwner(change, Owner(change), change.Role, null, FileName(change.File, change.MediaFileId), + new { media = "Attach", fileId = change.MediaFileId }); + break; + + case MediaChangeKind.Detached: + yield return OnOwner(change, Owner(change), change.Role, FileName(change.File, change.MediaFileId), null, + new { media = "Detach", fileId = change.MediaFileId }); + break; + + case MediaChangeKind.Replaced: + yield return OnOwner(change, Owner(change), change.Role, + Names(change.Displaced.Select(d => d.File)), FileName(change.File, change.MediaFileId), + change.Displaced.Count == 1 + ? new { media = "Replace", fileId = change.MediaFileId, previousFileId = change.Displaced[0].File.Id } + : (object)new { media = "Replace", fileId = change.MediaFileId, previousFileIds = change.Displaced.Select(d => d.File.Id) }); + break; + + case MediaChangeKind.Reordered: + yield return OnOwner(change, Owner(change), change.Role, + Names(change.PreviousOrder), Names(change.Order), + new { media = "Reorder" }); + break; + + case MediaChangeKind.Uploaded: + yield return OnFile(change, AuditAction.Created, Values(change.File)); + break; + + case MediaChangeKind.Updated: + yield return OnFile(change, AuditAction.Updated, Values(change.File, before: change.Previous)); + break; + + case MediaChangeKind.Deleted: + // Every entity it was still attached to loses it, and says why. + foreach (var link in change.Attachments) + { + yield return OnOwner(change, link.Owner, link.Role, FileName(change.File, change.MediaFileId), null, + new { media = "Detach", fileId = change.MediaFileId, reason = "FileDeleted" }); + } + + yield return OnFile(change, AuditAction.Deleted, Values(change.File, deleted: true)); + break; + + default: + throw new InvalidOperationException( + $"DotNetBoost.Media reported a {change.Kind} change, which this participant does not know how " + + "to record. Refusing the write rather than leaving it out of the trail."); + } + } /// A change to which files an entity uses, filed under that entity. - private static AuditWrite OnOwner(MediaChange change, string property, string? oldValue, string? newValue) + private static AuditWrite OnOwner( + MediaChange change, MediaOwner owner, string? role, string? oldValue, string? newValue, object metadata) => new() { - var owner = change.Owner - ?? throw new InvalidOperationException($"A {change.Kind} media change arrived without its owner."); - - return new AuditWrite - { - EntityName = owner.EntityName, - EntityId = owner.EntityId, - Action = AuditAction.Updated, - Changes = [new AuditChange(property, oldValue, newValue)], - CorrelationId = change.CorrelationId, - }; - } + EntityName = owner.EntityName, + EntityId = owner.EntityId, + Action = AuditAction.Updated, + Changes = [new AuditChange(Label(role), oldValue, newValue)], + CorrelationId = change.CorrelationId, + Metadata = JsonSerializer.Serialize(metadata), + }; /// A change to the file itself, filed under . private static AuditWrite OnFile(MediaChange change, AuditAction action, IReadOnlyList changes) => new() { EntityName = FileEntityName, - EntityId = change.MediaFileId.ToString("D"), + EntityId = (change.MediaFileId ?? throw new InvalidOperationException( + $"A {change.Kind} media change arrived without its file.")).ToString("D"), EntityType = typeof(MediaFileInfo), Action = action, Changes = changes, CorrelationId = change.CorrelationId, }; + private static MediaOwner Owner(MediaChange change) => + change.Owner ?? throw new InvalidOperationException($"A {change.Kind} media change arrived without its owner."); + + /// + /// A role as a row name: banner reads as Banner. Media stores roles lower-cased, + /// so this is presentation only — the role itself is unchanged. + /// + private static string Label(string? role) => + string.IsNullOrEmpty(role) + ? "Media" + : char.ToUpperInvariant(role[0]) + role[1..]; + + /// How a row names a file. Its id is in the entry's metadata. + private static string FileName(MediaFileInfo? file, Guid? id) => + file?.FileName ?? id?.ToString("D") ?? "(unknown file)"; + + /// Several files, in order, as one value; null for none. + private static string? Names(IEnumerable files) + { + var names = string.Join(", ", files.Select(f => f.FileName)); + return names.Length == 0 ? null : names; + } + /// /// The file's recorded properties as changes. An upload reports each as a new value and a /// delete each as an old one — the file as it was, which after the delete is the only copy of @@ -129,6 +202,12 @@ private static List Values(MediaFileInfo? file, MediaFileInfo? befo void Add(string name, string? value, string? previous = null) { + // An upload or a delete records what the file had; a property it never had — no tags, + // no category — is not a row. An edit records every property that moved, including + // one cleared to nothing. + if (!edit && value is null) + return; + if (deleted) changes.Add(new AuditChange(name, value, null)); else if (!edit || !string.Equals(value, previous, StringComparison.Ordinal)) @@ -156,10 +235,4 @@ void Add(string name, string? value, string? previous = null) metadata.Count == 0 ? null : string.Join(";", metadata.OrderBy(p => p.Key, StringComparer.Ordinal).Select(p => $"{p.Key}={p.Value}")); - - /// How an entry names a file: its name and its id, since names repeat. - private static string Name(MediaChange change) => - change.File is { } file - ? $"{file.FileName} ({change.MediaFileId:D})" - : change.MediaFileId.ToString("D"); } diff --git a/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs b/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs index cf843c6..f85ef6f 100644 --- a/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs +++ b/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs @@ -342,14 +342,15 @@ await Assert.ThrowsAsync(() => /// /// A product image's whole life, in the trails people actually read: the upload under the file, - /// the attach and — when the product is deleted — the detach under the product, and the + /// the attach in the product's own history — Gallery: — → lamp.png, the operation in the + /// entry's metadata — and, when the product is deleted, the detach on the product and the /// delete under the file. None of DotNetBoost.Media's own rows are in the trail. /// /// The interceptor alone recorded this as a MediaAttachment entry addressed by the /// link's own GUID, and a soft delete as a MediaFile Updated entry about /// DeletedAt; the product's trail said nothing. IgnoreEntity<MediaFile>() /// and IgnoreEntity<MediaAttachment>() keep the rows out, and - /// records each change as DotNetBoost.Media reports it — + /// records each operation as DotNetBoost.Media reports it — /// under the product, because Media's owner address and Auditing's entity address are the same /// (entityName, entityId). /// @@ -361,28 +362,28 @@ public async Task A_product_images_life_is_in_the_product_and_file_trails() var upload = await client.UploadAsync($"/api/products/{id}/images?role=gallery", "lamp.png"); var fileId = upload.Str("id"); - var named = $"lamp.png ({fileId})"; - // The attach, in the product's own trail, by whoever made it. - var attached = (await Trail(client, "Product", id)).Single(e => Changes(e).ContainsKey("media.gallery")); + // The attach, in the product's own history, by whoever made it. + var attached = Assert.Single(await MediaTrail(client, "Product", id)); Assert.Equal("Updated", attached.Str("action")); Assert.Equal("media.editor@example.com", attached.Str("actor")); - Assert.Equal(named, Changes(attached)["media.gallery"].Str("newValue")); + Assert.Equal(("Gallery", null, "lamp.png"), Row(attached)); + Assert.Equal(("Attach", fileId), (Operation(attached).Str("media"), Operation(attached).Str("fileId"))); // The upload, under the file — and the attach shares its correlation id: one call. var uploaded = Assert.Single(await FileTrail(client, fileId)); Assert.Equal("Created", uploaded.Str("action")); Assert.Equal("lamp.png", Changes(uploaded)["FileName"].Str("newValue")); + Assert.DoesNotContain("Tags", Changes(uploaded).Keys); // no tags, so no empty row Assert.Equal(uploaded.Str("correlationId"), attached.Str("correlationId")); - // Deleting the product deletes the image only it held: detached from the product, then - // deleted, both recorded. + // Deleting the product deletes the image only it held: one delete under the file, and a + // detach on the product that says why. await client.SendJsonCheckedAsync(HttpMethod.Delete, $"/api/products/{id}"); - var productTrail = await Trail(client, "Product", id); - var detached = productTrail.Single(e => - Changes(e).TryGetValue("media.gallery", out var c) && c.Str("oldValue") == named); - Assert.Contains(productTrail, e => e.Str("action") == "Deleted"); + var detached = (await MediaTrail(client, "Product", id)).Single(e => Operation(e).Str("media") == "Detach"); + Assert.Equal(("Gallery", "lamp.png", null), Row(detached)); + Assert.Equal("FileDeleted", Operation(detached).Str("reason")); var fileTrail = await FileTrail(client, fileId); Assert.Equal(["Created", "Deleted"], fileTrail.Select(e => e.Str("action")).Order()); @@ -396,6 +397,42 @@ public async Task A_product_images_life_is_in_the_product_and_file_trails() "SELECT COUNT(*) FROM \"AuditEntries\" WHERE \"EntityName\" IN ('MediaFile', 'MediaAttachment')")); } + /// + /// Replacing a single-valued role and reordering a gallery are one entry each in the product's + /// history: Primary: first.png → second.png, and Gallery with the whole order before + /// and after — not a detach and an attach, and not one entry per image that moved. + /// + [RequiresDockerFact] + public async Task A_replacement_and_a_reorder_are_one_entry_each() + { + var client = app.Client.AsActor(); + var id = await client.CreateProductAsync(app.SeededCategoryId, "Rearranged"); + + var first = (await client.UploadAsync($"/api/products/{id}/images?role=primary", "first.png")).Str("id"); + var a = (await client.UploadAsync($"/api/products/{id}/images?role=gallery", "a.png")).Str("id"); + var b = (await client.UploadAsync($"/api/products/{id}/images?role=gallery", "b.png")).Str("id"); + var second = Guid.Parse((await client.UploadAsync("/api/media", "second.png")).Str("id")); + + await app.WithScopeAsync(async services => + { + var media = services.GetRequiredService().For("Product", id.ToString()); + + await media.SetAsync("primary", second); + await media.ReorderAsync("gallery", [Guid.Parse(b), Guid.Parse(a)]); + }); + + var trail = await MediaTrail(client, "Product", id); + + var replaced = Assert.Single(trail, e => Operation(e).Str("media") == "Replace"); + Assert.Equal(("Primary", "first.png", "second.png"), Row(replaced)); + Assert.Equal( + (second.ToString("D"), first), + (Operation(replaced).Str("fileId"), Operation(replaced).Str("previousFileId"))); + + var reordered = Assert.Single(trail, e => Operation(e).Str("media") == "Reorder"); + Assert.Equal(("Gallery", "a.png, b.png", "b.png, a.png"), Row(reordered)); + } + /// /// A media write that fails after its entry was recorded leaves the file unattached, no entry in /// the trail, and nothing pending on the caller's context. @@ -825,6 +862,24 @@ private static async Task> GroupTrail(HttpClient client) => $"/api/audit?entityName={SettingGroupAuditParticipant.EntityName}&entityId={nameof(CatalogSettings)}")) .GetProperty("entries").EnumerateArray()]; + /// An entity's media entries — the ones carrying an operation in their metadata — newest first. + private static async Task> MediaTrail(HttpClient client, string entityName, int entityId) => + [.. (await Trail(client, entityName, entityId)).Where(e => e.TryGetProperty("metadata", out var m) + && m.ValueKind == JsonValueKind.String)]; + + /// The operation a media entry records, from its metadata. + private static JsonElement Operation(JsonElement entry) => + JsonDocument.Parse(entry.Str("metadata")).RootElement; + + /// A media entry's one row, as (property, old, new). + private static (string, string?, string?) Row(JsonElement entry) + { + var change = Assert.Single(entry.GetProperty("changes").EnumerateArray()); + return (change.Str("propertyName"), + change.GetProperty("oldValue").GetString(), + change.GetProperty("newValue").GetString()); + } + /// A media file's own entries, newest first. private static async Task> FileTrail(HttpClient client, string fileId) => [.. (await client.GetJsonAsync($"/api/audit?entityName={MediaAuditParticipant.FileEntityName}&entityId={fileId}")) From 3237cb41f2ecdcc037e8638970964a48f3217aa0 Mon Sep 17 00:00:00 2001 From: Sadeq Abu-Hattem Date: Tue, 17 Nov 2026 21:09:47 +0200 Subject: [PATCH 3/5] List a deleted file's attachments on its own delete entry The Deleted entry under ("Media", id) gains one Attachments row naming every entity the file was still attached to ("Category 4 as banner, Product 42 as gallery"), so the file's history is complete on its own. Each owner still gets its detach entry marked "reason":"FileDeleted", so its history stays accurate too. The row is left out for a file attached to nothing. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +++++--- .../Persistence/MediaAuditParticipant.cs | 18 +++++++++++++++--- .../Integration/AuditTrailTests.cs | 1 + 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index d0d6050..e3201a4 100644 --- a/README.md +++ b/README.md @@ -544,9 +544,11 @@ values, and the operation in the entry's `Metadata`: | reorder | Product 42 | `Gallery: a.png, b.png → b.png, a.png` | `{"media":"Reorder"}` | An upload, an edit and a delete are about the file itself: `Created`, `Updated` and `Deleted` on -`("Media", )`, with its name, type, size, category and tags. A delete also writes a detach -on every entity that still used the file, marked `"reason":"FileDeleted"`, so a product's history -says why its image went; all of them share one correlation id. +`("Media", )`, with its name, type, size, category and tags — only the ones it has. A +delete also writes a detach on every entity that still used the file, marked +`"reason":"FileDeleted"`, so a product's history says why its image went, and lists those entities +on the file's own entry as one `Attachments` row (`Category 4 as banner, Product 42 as gallery`), +so the file's history is complete on its own. All of them share one correlation id. An attach can be filed under the product because Media's owner address and Auditing's entity address are the same `(entityName, entityId)` — Entity Addressing v1, which diff --git a/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs b/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs index 319e783..4464e1c 100644 --- a/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs +++ b/src/DotNetBoostSample.Infrastructure/Persistence/MediaAuditParticipant.cs @@ -130,7 +130,7 @@ private static IEnumerable Describe(MediaChange change) new { media = "Detach", fileId = change.MediaFileId, reason = "FileDeleted" }); } - yield return OnFile(change, AuditAction.Deleted, Values(change.File, deleted: true)); + yield return OnFile(change, AuditAction.Deleted, Values(change.File, deleted: true, attachments: change.Attachments)); break; default: @@ -191,9 +191,15 @@ private static string FileName(MediaFileInfo? file, Guid? id) => /// The file's recorded properties as changes. An upload reports each as a new value and a /// delete each as an old one — the file as it was, which after the delete is the only copy of /// its name. An edit reports only what moved, from to - /// . + /// . A delete also records where the file was still in use, as one + /// Attachments row — the same links each owner's own detach entry records, gathered on + /// the file so its history is complete on its own. /// - private static List Values(MediaFileInfo? file, MediaFileInfo? before = null, bool deleted = false) + private static List Values( + MediaFileInfo? file, + MediaFileInfo? before = null, + bool deleted = false, + IReadOnlyList? attachments = null) { if (file is null) return []; @@ -226,6 +232,12 @@ void Add(string name, string? value, string? previous = null) Add(nameof(MediaFileInfo.Size), file.Size.ToString(CultureInfo.InvariantCulture)); } + if (attachments is { Count: > 0 }) + { + Add("Attachments", string.Join(", ", attachments.Select(a => + $"{a.Owner.EntityName} {a.Owner.EntityId} as {a.Role}"))); + } + return changes; } diff --git a/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs b/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs index f85ef6f..63cd3a8 100644 --- a/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs +++ b/tests/DotNetBoostSample.Tests/Integration/AuditTrailTests.cs @@ -390,6 +390,7 @@ public async Task A_product_images_life_is_in_the_product_and_file_trails() var deleted = fileTrail.Single(e => e.Str("action") == "Deleted"); Assert.Equal("lamp.png", Changes(deleted)["FileName"].Str("oldValue")); + Assert.Equal($"Product {id} as gallery", Changes(deleted)["Attachments"].Str("oldValue")); Assert.Equal(deleted.Str("correlationId"), detached.Str("correlationId")); // And not one of the media library's rows, from this test or any other. From 5882a74af35eff7b6e27a32682dfc307c7b2fd42 Mon Sep 17 00:00:00 2001 From: Sadeq Abu-Hattem Date: Tue, 17 Nov 2026 21:28:29 +0200 Subject: [PATCH 4/5] Show the media operation as a badge in the audit trail Media changes are all Updated entries on their owner, with the operation in the entry's metadata ({"media":"Attach|Detach|Replace|Reorder"}). The audit page now reads that convention and draws a badge beside the action - Attached, Detached, Replaced, Reordered - in the trail table and in the entry's details. A detach caused by a file delete shows "Detached" with its own icon in the table and "Detached, file deleted" on hover and in the details. Entries without that metadata are drawn as before. Long metadata now wraps instead of running off the row. Strings in en, ar and fr; a unit test for reading the metadata and an e2e check for the badge. Co-Authored-By: Claude Opus 5.5 --- .../app/components/audit/EntryChanges.vue | 14 +++- .../components/audit/MediaOperationBadge.vue | 32 ++++++++ .../app/components/audit/TrailTable.vue | 5 +- .../app/composables/useMediaOperations.ts | 78 +++++++++++++++++++ clients/dashboard/i18n/locales/ar.json | 10 ++- clients/dashboard/i18n/locales/en.json | 10 ++- clients/dashboard/i18n/locales/fr.json | 10 ++- clients/dashboard/test/e2e/api.ts | 11 ++- clients/dashboard/test/e2e/smoke.e2e.ts | 9 +++ .../test/nuxt/mediaOperation.spec.ts | 33 ++++++++ 10 files changed, 204 insertions(+), 8 deletions(-) create mode 100644 clients/dashboard/app/components/audit/MediaOperationBadge.vue create mode 100644 clients/dashboard/app/composables/useMediaOperations.ts create mode 100644 clients/dashboard/test/nuxt/mediaOperation.spec.ts diff --git a/clients/dashboard/app/components/audit/EntryChanges.vue b/clients/dashboard/app/components/audit/EntryChanges.vue index 8ab230c..5e00df2 100644 --- a/clients/dashboard/app/components/audit/EntryChanges.vue +++ b/clients/dashboard/app/components/audit/EntryChanges.vue @@ -113,11 +113,21 @@ const showNew = computed(() => props.entry.action !== 'Deleted') + +
+
{{ $t('audit.entry.mediaOperation') }}
+
+ +
+
+ -
+
{{ $t('audit.entry.metadata') }}
-
+ +
{{ entry.metadata }}
diff --git a/clients/dashboard/app/components/audit/MediaOperationBadge.vue b/clients/dashboard/app/components/audit/MediaOperationBadge.vue new file mode 100644 index 0000000..e252841 --- /dev/null +++ b/clients/dashboard/app/components/audit/MediaOperationBadge.vue @@ -0,0 +1,32 @@ + + + diff --git a/clients/dashboard/app/components/audit/TrailTable.vue b/clients/dashboard/app/components/audit/TrailTable.vue index 159edeb..d37dd63 100644 --- a/clients/dashboard/app/components/audit/TrailTable.vue +++ b/clients/dashboard/app/components/audit/TrailTable.vue @@ -275,7 +275,10 @@ function showEdit(correlationId: string) { - +
+ + +