From 2f9cffe9c15ae56eb636363bdeec143676f03a89 Mon Sep 17 00:00:00 2001 From: Hossein Naderi Date: Thu, 12 Sep 2024 17:23:00 +0330 Subject: [PATCH] Fixed wrong snapshot usage --- .../eventsourcing/RepositoryReader.scala | 3 +- .../eventsourcing/RepositoryReaderSuite.scala | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/modules/backend/src/main/scala/eventsourcing/RepositoryReader.scala b/modules/backend/src/main/scala/eventsourcing/RepositoryReader.scala index 831e5318..09fb7c04 100644 --- a/modules/backend/src/main/scala/eventsourcing/RepositoryReader.scala +++ b/modules/backend/src/main/scala/eventsourcing/RepositoryReader.scala @@ -54,10 +54,11 @@ object RepositoryReader { .flatMap { case Some(last) => journal - .readStreamAfter(streamId, last.version) + .readStreamAfter(streamId, last.version - 1) .through(scanState(last)) .compile .lastOrError + case None => history(streamId).compile.lastOrError } diff --git a/modules/backend/src/test/scala/eventsourcing/RepositoryReaderSuite.scala b/modules/backend/src/test/scala/eventsourcing/RepositoryReaderSuite.scala index c75d06bb..61638e77 100644 --- a/modules/backend/src/test/scala/eventsourcing/RepositoryReaderSuite.scala +++ b/modules/backend/src/test/scala/eventsourcing/RepositoryReaderSuite.scala @@ -69,6 +69,41 @@ class RepositoryReaderSuite extends CatsEffectSuite { ) ) } + + test("Repository reader uses snapshot") { + val snapshot: SnapshotReader[IO, Long] = ConstantSnapshotStore(45, 9) + val journal: JournalReader[IO, Int] = JournalReaderStub(data) + + val r = RepositoryReader(journal, snapshot) + + r.get("sut").assertEquals(AggregateState.Valid(55, 10)) >> + r.history("sut") + .compile + .toList + .assertEquals( + data.scanLeft(initial)((s, e) => + AggregateState.Valid(s.state + e.payload, s.version + 1) + ) + ) + } + + test("Repository reader uses wrong snapshots too!") { + val snapshot: SnapshotReader[IO, Long] = ConstantSnapshotStore(100, 9) + val journal: JournalReader[IO, Int] = JournalReaderStub(data) + + val r = RepositoryReader(journal, snapshot) + + r.get("sut").assertEquals(AggregateState.Valid(110, 10)) >> + r.history("sut") + .compile + .toList + .assertEquals( + data.scanLeft(initial)((s, e) => + AggregateState.Valid(s.state + e.payload, s.version + 1) + ) + ) + } + } class JournalReaderStub[E](data: Stream[IO, EventMessage[E]])