Path: redb/redb.Core/Interception/IRedbSaveInterceptor.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Interception/IRedbSaveInterceptor.cs ---- using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Security; namespace redb.Core.Interception; /// /// Save-pipeline interceptor (discussion #12, items 3-4), deliberately shaped after EF Core's /// ISaveChangesInterceptor so the behaviour is familiar: /// /// runs after the object graph is collected and BEFORE the /// transaction opens; an exception thrown here CANCELS the save and propagates to the caller — /// nothing has touched the database yet. /// runs after the transaction has committed; an exception /// propagates to the caller (exactly like EF), but the data IS saved — the save cannot be /// un-committed from here. /// /// Register any number via DI (services.AddSingleton<IRedbSaveInterceptor, ...>()); /// they run in registration order. Code that cannot reach that container (a module in its own /// AssemblyLoadContext) subscribes at run time through ; /// those run after the DI ones. With none registered and none subscribed the pipeline pays nothing — /// the change feed below is not even collected. /// /// Both hooks run INSIDE the SaveAsync call, and one scope is one save (the CT-4 guard): an /// interceptor that writes its journal as redb objects through the SAME service scope will trip /// that guard deterministically. Write through a separate scope (scoped IRedbService from a /// scope factory), or buffer and flush outside the save. /// /// /// Audit and impersonation live here by design: the application sees every object (and under /// ChangeTracking every value-level change) next to whatever pair of real/effective users it /// tracks, and writes its own journal - the framework does not prescribe one. /// /// /// Atomic audit (discussion #12 follow-up): by default the hooks do not share the save's /// transaction (Saving runs before BEGIN so a veto needs no rollback; Saved runs after COMMIT /// so a hook can never unwind it). When the audit row must be atomic with the write, wrap the /// call in your own transaction: /// /// await redb.Context.ExecuteAtomicAsync(async () => /// { /// await redb.SaveAsync(obj); // the whole pipeline, SavedAsync included, runs inside /// }); /// /// Inside that scope an insert from SavedAsync via redb.Context.ExecuteAsync(...) (a /// plain flat audit table is the recommended shape) joins the same transaction and commits or /// rolls back together with the save. The same works for DeleteAsync and DeletedAsync. /// /// public interface IRedbSaveInterceptor { Task SavingAsync(RedbSavingContext context, CancellationToken cancellationToken = default) => Task.CompletedTask; Task SavedAsync(RedbSavedContext context, CancellationToken cancellationToken = default) => Task.CompletedTask; /// /// Before a hard delete executes (owner decision: deletes are intercepted too). An exception /// cancels the delete - nothing has been removed yet. Fires for the intent: some of the ids /// may turn out not to exist. /// Task DeletingAsync(RedbDeletingContext context, CancellationToken cancellationToken = default) => Task.CompletedTask; /// /// After a hard delete committed. An exception propagates, but the rows are gone. /// Task DeletedAsync(RedbDeletedContext context, CancellationToken cancellationToken = default) => Task.CompletedTask; } /// What a hard delete is about to remove. public sealed class RedbDeletingContext { /// /// Ids the caller asked to delete (the intent). For DeleteSubtreeAsync: the start object and every descendant it /// collected. /// public required IReadOnlyList ObjectIds { get; init; } /// /// The object instances, when the caller had them (delete-by-object overloads); empty for /// delete-by-id. Database-side cascades (children) are not enumerated here. /// public required IReadOnlyList KnownObjects { get; init; } public required IRedbUser EffectiveUser { get; init; } } /// What a hard delete has removed. public sealed class RedbDeletedContext { public required IReadOnlyList ObjectIds { get; init; } public required IReadOnlyList KnownObjects { get; init; } public required IRedbUser EffectiveUser { get; init; } /// /// The objects of this call deleted (cascades not included); for DeleteSubtreeAsync, the /// objects of the subtree it deleted. /// public required int DeletedCount { get; init; } } /// What a save is about to do. Handed to . public sealed class RedbSavingContext { /// The objects the caller passed to SaveAsync. public required IReadOnlyList RootObjects { get; init; } /// The full collected graph: roots plus nested objects reached through Props. public required IReadOnlyList AllObjects { get; init; } /// The user the save is executed as (the effective user). public required IRedbUser EffectiveUser { get; init; } public required PropsSaveStrategy Strategy { get; init; } /// /// The objects this save CREATES - the ones that arrived without an id. At this point their /// Id is still 0 (EF temporary-key semantics: Saving runs before ids, hashes and the /// unchanged-set are computed, precisely so the interceptor MAY mutate Props and every /// derived artefact reflects the edit); the final ids arrive in /// . The exotic case of a hand-assigned id that /// does not exist in the database is inserted by the strategy but not listed here. /// public required IReadOnlyList NewObjects { get; init; } } /// What a save has done. Handed to . public sealed class RedbSavedContext { public required IReadOnlyList RootObjects { get; init; } public required IReadOnlyList AllObjects { get; init; } public required IRedbUser EffectiveUser { get; init; } public required PropsSaveStrategy Strategy { get; init; } /// Ids of the root objects, in the order the caller passed them. public required IReadOnlyList SavedIds { get; init; } /// Final ids of the objects this save created (). public required IReadOnlySet NewObjectIds { get; init; } /// /// Ids of existing objects the hash shortcut (F1) excluded from the value pipeline - their /// content was unchanged and no value-level work happened. Null when the shortcut found /// nothing or is inactive. Computed after Saving (so it reflects Saving-time edits), hence /// it lives here and not in the Saving context. /// public IReadOnlySet? UnchangedByHash { get; init; } /// /// Value-level changes the diff actually applied — ChangeTracking only (null under /// DeleteInsert, which rewrites everything and diffs nothing). The diff covers EXISTING /// objects: values of objects this save created go straight to insert and are not listed - /// read creations from and the objects themselves. The list holds /// the diff's own working rows: treat it as a read-only snapshot. /// public IReadOnlyList? Changes { get; init; } } public enum RedbValueChangeType { Insert, Update, Delete, } /// /// One value-level change from the ChangeTracking diff, flattened onto Core types (the tree /// machinery itself is a Pro internal). Old is null for an insert, New for a delete. /// public sealed class RedbValueChange { public required RedbValueChangeType Type { get; init; } /// /// The change in the model's terms: the property path as declared on Props — /// "Title", "Items[1].Price", "Meta[m0]". What an audit journal prints; /// the raw rows below are for consumers that need the storage-level detail. /// public required string PropertyPath { get; init; } public RedbValue? OldValue { get; init; } public RedbValue? NewValue { get; init; } public long ObjectId => (NewValue ?? OldValue)?.IdObject ?? 0; }