looplab / eventhorizon

Event Sourcing for Go!
Apache License 2.0
1.59k stars 195 forks source link

Version is not set when recreating Aggregate from SnapShot #414

Open totemcaf opened 10 months ago

totemcaf commented 10 months ago

Describe the bug

When an Aggregate is loaded by the AggregateStore, if the aggregate has Snapshots configured, after initializing the Aggregate with the Snapshot data, the Aggregate version is not modified and remains in 0.

The eventhorizon.Snapshot structure contains the Version field, but it is not set in the Aggregate.

If the Aggregate contains more events (not included in the Snapshot), the application of this events will set the Version correctly, and the error is hidden.

To Reproduce Steps to reproduce the behavior:

  1. Create an Aggregate
  2. Configure it to take a snapshot every 2 events
  3. Send a command that fires 2 events in the aggregate
  4. A Snapshot should be taken and persisted
  5. Send another command that fires one event
  6. The aggregate should be loaded from the Snapshot
  7. The aggregate will have version 0 (it should be 2)
  8. The new event will have version 1, instead of 3
  9. The persistence of events will fail

Expected behavior In step 6, when the aggregate is loaded from the Snapshot store, it should have Version 2 In step 8, the new event should have version 3, and it is correctly persisted

Screenshots N/A

Additional context Add any other context about the problem here.

func (r *AggregateStore) Load(ctx context.Context, aggregateType eh.AggregateType, id uuid.UUID) (eh.Aggregate, error) {
// ...
    fromVersion := 1

    if sa, ok := a.(eh.Snapshotable); ok && r.isSnapshotStore {
        snapshot, err := r.snapshotStore.LoadSnapshot(ctx, id)
        if err != nil {
            return nil, &eh.AggregateStoreError{
                Err:           err,
                Op:            eh.AggregateStoreOpLoad,
                AggregateType: aggregateType,
                AggregateID:   id,
            }
        }

        if snapshot != nil {
            sa.ApplySnapshot(snapshot)
            fromVersion = snapshot.Version + 1
            a.SetAggregateVersion(snapshot.Version) // <--- THIS IS THE MISSING LINE
        }
    }
// ...
totemcaf commented 10 months ago

I will provide a PR soon (hope, this week)