Skip to content

Commit

Permalink
Making sure that event metadata is applied before aggregation side ef…
Browse files Browse the repository at this point in the history
…fects are applied. Closes GH-3580
  • Loading branch information
jeremydmiller committed Dec 9, 2024
1 parent 960fcf5 commit 05a5f39
Showing 1 changed file with 18 additions and 16 deletions.
34 changes: 18 additions & 16 deletions src/Marten/Events/Aggregation/AggregationRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,7 @@ public async ValueTask ApplyChangesAsync(DocumentSessionBase session,
}
}

if (aggregate != null)
{
Storage.SetIdentity(aggregate, slice.Id);
}
var lastEvent = tryApplyMetadata(slice, aggregate);

if (session is ProjectionDocumentSession pds && pds.Mode == ShardExecutionMode.Continuous)
{
Expand All @@ -155,18 +152,6 @@ public async ValueTask ApplyChangesAsync(DocumentSessionBase session,
await processPossibleSideEffects(session, slice).ConfigureAwait(false);
}

var lastEvent = slice.Events().LastOrDefault();
if (aggregate != null)
{
Versioning.TrySetVersion(aggregate, lastEvent);

foreach (var @event in slice.Events())
{
Projection.ApplyMetadata(aggregate, @event);
}

}

// Delete the aggregate *if* it existed prior to these events
if (aggregate == null)
{
Expand All @@ -189,6 +174,23 @@ public async ValueTask ApplyChangesAsync(DocumentSessionBase session,
session.QueueOperation(storageOperation);
}

private IEvent? tryApplyMetadata(EventSlice<TDoc, TId> slice, TDoc? aggregate)
{
var lastEvent = slice.Events().LastOrDefault();
if (aggregate != null)
{
Storage.SetIdentity(aggregate, slice.Id);
Versioning.TrySetVersion(aggregate, lastEvent);

foreach (var @event in slice.Events())
{
Projection.ApplyMetadata(aggregate, @event);
}
}

return lastEvent;
}

private async Task processPossibleSideEffects(DocumentSessionBase session, EventSlice<TDoc, TId> slice)
{
if (Projection is IAggregateProjectionWithSideEffects<TDoc> sideEffects)
Expand Down

0 comments on commit 05a5f39

Please sign in to comment.