问题
Hypothetically I'm working on a system that uses "Event Sourcing" (storing the business events) that has purchase and selling of materials; at some point a report, with prices and costs information is generated.
Imagine that one of my clients call me and says, "The costs are wrong, for me, the rules from profit are this way".
I could add more handlers or change the rules to adjust to this particular case, and replay the events.
But my question is, this is the correct approach (or at least the better)?
回答1:
In an event sourced system, the events are immutable - the simple facts of what has happened. Rewriting the history of the events is a thing one simply does not do[1].
Changing the calculation logic that derives a result based on these events is absolutely a normal thing to do (it's one of the key things even sourcing enables).
Whether you actually change your code or provide an alternate algorithm alongside is a matter of choice - if the original was effectively a bug (sounds like your case), change the code. If not, write a new one.
In certain cases (not generally advised), one always works everything from the original events; if that's the case, all you have to do is change your derivation logic and you're done.
In the case where you've projected the events and denormalised into a persistent store, and have decided that the situation represents a bug, the normal approach is to:
- blow away the existing denormalised state
- replay the events to yield the intended alternate derivation
Note that this only comes into play if you have a non-ephemeral denormalised state store that retains values calculated on the basis now being superseded. (It's perfectly valid to project the denormalised state into an in-memory stash; in such a case the 'blowing away' is simpler).
Another scenario is where you've implemented snapshotting optimisations - in that case one would also re-project to denormalise differently.
[1] Yes there are exotic cases where it can be justified but that's a .001% case
来源:https://stackoverflow.com/questions/40547785/replay-events-for-adjustments