Buuuug fix
This commit is contained in:
1 parent
eb7f8b2ba5
commit
52d64fc810
4 files changed
+118
-85
No files matched your search
@@ -22,14 +22,24 @@ open class EventDispatcher(val eventStore: EventStore, private val lifecycleStor
|
|||||||
open fun dispatch(referenceId: UUID, history: List<Event>, newEvents: List<Event>) {
|
open fun dispatch(referenceId: UUID, history: List<Event>, newEvents: List<Event>) {
|
||||||
val deletedEventIds = history.filterIsInstance<DeleteEvent>().map { it.deletedEventId }
|
val deletedEventIds = history.filterIsInstance<DeleteEvent>().map { it.deletedEventId }
|
||||||
|
|
||||||
val candidates = newEvents
|
var candidates = newEvents
|
||||||
.validEvents(deletedEventIds)
|
.validEvents(deletedEventIds)
|
||||||
.replayCandidates()
|
.replayCandidates()
|
||||||
|
|
||||||
|
// ⭐ Fallback: kun når ALLE nye events er signaler
|
||||||
|
if (candidates.isEmpty() && newEvents.all { it is SignalEvent }) {
|
||||||
|
candidates = history
|
||||||
|
.validEvents(deletedEventIds)
|
||||||
|
.replayCandidates()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
val effectiveHistory = history
|
val effectiveHistory = history
|
||||||
.validEvents(deletedEventIds)
|
.validEvents(deletedEventIds)
|
||||||
.filterNot { it is DeleteEvent }
|
.filterNot { it is DeleteEvent }
|
||||||
|
|
||||||
|
//val producedEvents: MutableList<Event> = mutableListOf()
|
||||||
|
|
||||||
EventListenerRegistry.getListeners().forEach { listener ->
|
EventListenerRegistry.getListeners().forEach { listener ->
|
||||||
for (candidate in candidates) {
|
for (candidate in candidates) {
|
||||||
//log.debug("Evaluating candidate: ${candidate::class.simpleName} for listener ${listener::class.simpleName}")
|
//log.debug("Evaluating candidate: ${candidate::class.simpleName} for listener ${listener::class.simpleName}")
|
||||||
@@ -40,6 +50,7 @@ open class EventDispatcher(val eventStore: EventStore, private val lifecycleStor
|
|||||||
validateReferenceId(result, listener)
|
validateReferenceId(result, listener)
|
||||||
validateDerivation(result, candidate, effectiveHistory, listener)
|
validateDerivation(result, candidate, effectiveHistory, listener)
|
||||||
eventStore.persist(result)
|
eventStore.persist(result)
|
||||||
|
//producedEvents.add(result)
|
||||||
lifecycleStore.add(
|
lifecycleStore.add(
|
||||||
ListenerResult(
|
ListenerResult(
|
||||||
timestamp = MyTime.utcNow(),
|
timestamp = MyTime.utcNow(),
|
||||||
@@ -115,6 +126,8 @@ open class EventDispatcher(val eventStore: EventStore, private val lifecycleStor
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// producedEvents.forEach { eventStore.persist(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun UUID.short(): String = this.toString().substring(0, 8)
|
private fun UUID.short(): String = this.toString().substring(0, 8)
|
||||||
|
|||||||
@@ -154,7 +154,7 @@ abstract class EventPollerImplementation(
|
|||||||
|
|
||||||
val newForRef = eventsForRef.filter { ev ->
|
val newForRef = eventsForRef.filter { ev ->
|
||||||
ev.persistedAt > refSeenAt ||
|
ev.persistedAt > refSeenAt ||
|
||||||
(ev.persistedAt == refSeenAt && ev.id >= refSeenId)
|
(ev.persistedAt == refSeenAt && ev.id > refSeenId)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (newForRef.isEmpty()) {
|
if (newForRef.isEmpty()) {
|
||||||
@@ -182,55 +182,24 @@ abstract class EventPollerImplementation(
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Domain-events (kandidater)
|
// ⭐ Send ALLE nye events (domain + signal) til dispatch
|
||||||
val newDomainEvents = newForRef
|
val newEvents = newForRef.mapNotNull { it.toEvent() }
|
||||||
.mapNotNull { it.toEvent() }
|
dispatchQueue.dispatch(ref, history, newEvents, dispatcher)
|
||||||
.filterNot { it is SignalEvent }
|
|
||||||
|
|
||||||
// ⭐ CASE 1: Kun signaler → trigge dispatch av siste domain-event
|
// ⭐ Flytt watermark KUN basert på domain-events
|
||||||
if (newDomainEvents.isEmpty()) {
|
val lastDomainPersisted = newForRef
|
||||||
|
|
||||||
val lastDomain = history
|
|
||||||
.filterNot { it is SignalEvent }
|
|
||||||
.maxByOrNull { it.metadata.created }
|
|
||||||
|
|
||||||
if (lastDomain == null) {
|
|
||||||
lifecycleStore.add(
|
|
||||||
RefDispatchSkipped(
|
|
||||||
timestamp = MyTime.utcNow(),
|
|
||||||
ref = ref,
|
|
||||||
reason = "Only signals present and no domain history"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
dispatchQueue.dispatch(
|
|
||||||
ref,
|
|
||||||
history = history,
|
|
||||||
newEvents = listOf(lastDomain),
|
|
||||||
dispatcher = dispatcher
|
|
||||||
)
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ⭐ CASE 2: Vanlige domain-events → normal dispatch
|
|
||||||
dispatchQueue.dispatch(ref, history, newDomainEvents, dispatcher)
|
|
||||||
|
|
||||||
// Flytt watermark basert på domain-events
|
|
||||||
val maxDomainEvent = fullLog
|
|
||||||
.filter { it.toEvent() !is SignalEvent }
|
.filter { it.toEvent() !is SignalEvent }
|
||||||
.maxWithOrNull(compareBy({ it.persistedAt }, { it.id }))
|
.maxWithOrNull(compareBy({ it.persistedAt }, { it.id }))
|
||||||
|
|
||||||
if (maxDomainEvent != null) {
|
if (lastDomainPersisted != null) {
|
||||||
updateWatermark(ref, maxDomainEvent.persistedAt to maxDomainEvent.id)
|
updateWatermark(ref, lastDomainPersisted.persistedAt to lastDomainPersisted.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Oppdaterer global scan hint basert på per-ref watermarks.
|
* Oppdaterer global scan hint basert på per-ref watermarks.
|
||||||
* Global watermark = min(persistedAt over alle refs).
|
* Global watermark = min(persistedAt over alle refs).
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package no.iktdev.eventi.events
|
package no.iktdev.eventi.events
|
||||||
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.CoroutineStart
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
@@ -17,6 +18,7 @@ import no.iktdev.eventi.lifecycle.LifecycleStore
|
|||||||
import no.iktdev.eventi.lifecycle.RefDispatchCompleted
|
import no.iktdev.eventi.lifecycle.RefDispatchCompleted
|
||||||
import no.iktdev.eventi.lifecycle.RefDispatchStarted
|
import no.iktdev.eventi.lifecycle.RefDispatchStarted
|
||||||
import no.iktdev.eventi.models.Event
|
import no.iktdev.eventi.models.Event
|
||||||
|
import org.jetbrains.annotations.VisibleForTesting
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
@@ -30,7 +32,8 @@ open class SequenceDispatchQueue(
|
|||||||
|
|
||||||
fun activeRefs(): Set<UUID> = active.toSet()
|
fun activeRefs(): Set<UUID> = active.toSet()
|
||||||
|
|
||||||
fun _scope(): CoroutineScope {
|
@VisibleForTesting
|
||||||
|
internal fun scope(): CoroutineScope {
|
||||||
return scope
|
return scope
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,7 +65,7 @@ open class SequenceDispatchQueue(
|
|||||||
)
|
)
|
||||||
log.debug {"▶️ Starting dispatch for $referenceId with ${history.size} events"}
|
log.debug {"▶️ Starting dispatch for $referenceId with ${history.size} events"}
|
||||||
|
|
||||||
return scope.launch {
|
return scope.launch(start = CoroutineStart.UNDISPATCHED) {
|
||||||
try {
|
try {
|
||||||
// Venter på semaphore
|
// Venter på semaphore
|
||||||
lifecycleStore.add(
|
lifecycleStore.add(
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import kotlinx.coroutines.test.runTest
|
|||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import kotlinx.coroutines.withTimeout
|
import kotlinx.coroutines.withTimeout
|
||||||
import kotlinx.coroutines.awaitAll
|
import kotlinx.coroutines.awaitAll
|
||||||
|
import kotlinx.coroutines.job
|
||||||
import kotlinx.coroutines.test.advanceUntilIdle
|
import kotlinx.coroutines.test.advanceUntilIdle
|
||||||
import no.iktdev.eventi.EventDispatcherTest
|
import no.iktdev.eventi.EventDispatcherTest
|
||||||
import no.iktdev.eventi.EventDispatcherTest.DerivedEvent
|
import no.iktdev.eventi.EventDispatcherTest.DerivedEvent
|
||||||
@@ -21,6 +22,7 @@ import no.iktdev.eventi.registry.EventListenerRegistry
|
|||||||
import no.iktdev.eventi.registry.EventTypeRegistry
|
import no.iktdev.eventi.registry.EventTypeRegistry
|
||||||
import no.iktdev.eventi.testUtil.TestSequenceDispatchQueue
|
import no.iktdev.eventi.testUtil.TestSequenceDispatchQueue
|
||||||
import no.iktdev.eventi.testUtil.wipe
|
import no.iktdev.eventi.testUtil.wipe
|
||||||
|
import org.assertj.core.api.Assertions.assertThat
|
||||||
import org.junit.jupiter.api.Assertions.assertEquals
|
import org.junit.jupiter.api.Assertions.assertEquals
|
||||||
import org.junit.jupiter.api.Assertions.assertFalse
|
import org.junit.jupiter.api.Assertions.assertFalse
|
||||||
import org.junit.jupiter.api.Assertions.assertTrue
|
import org.junit.jupiter.api.Assertions.assertTrue
|
||||||
@@ -415,78 +417,124 @@ class EventPollerImplementationTest : TestBase() {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("""
|
@DisplayName("""
|
||||||
Når kun SignalEvent ankommer etter et domain-event
|
Når kun SignalEvent ankommer etter et domain-event
|
||||||
Hvis pollOnce kjøres
|
Hvis pollOnce kjøres
|
||||||
Så skal polleren trigge dispatch av siste domain-event (ikke signalet)
|
Så skal polleren trigge dispatch av siste domain-event (ikke signalet)
|
||||||
""")
|
""")
|
||||||
fun pollerTriggersLastDomainEventWhenOnlySignalsArrive() = runTest {
|
fun pollerTriggersLastDomainEventWhenOnlySignalsArrive() = runTest {
|
||||||
|
|
||||||
val testDispatcher = StandardTestDispatcher(testScheduler)
|
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||||
val queue = TestSequenceDispatchQueue(maxConcurrency = 1, dispatcher = testDispatcher, lifecycleStore)
|
val queue = TestSequenceDispatchQueue(maxConcurrency = 1, dispatcher = testDispatcher, lifecycleStore)
|
||||||
|
|
||||||
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {}
|
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {}
|
||||||
|
|
||||||
EventTypeRegistry.wipe()
|
EventTypeRegistry.wipe()
|
||||||
EventListenerRegistry.wipe()
|
EventListenerRegistry.wipe()
|
||||||
eventStore.clear()
|
eventStore.clear()
|
||||||
|
|
||||||
// Registrer domain + signal
|
|
||||||
EventTypeRegistry.register(
|
EventTypeRegistry.register(
|
||||||
listOf(
|
listOf(
|
||||||
TriggerEvent::class.java, // domain-event
|
TriggerEvent::class.java,
|
||||||
EventDispatcherTest.OnHoldSignalEvent::class.java // signal-event
|
EventDispatcherTest.OnHoldSignalEvent::class.java
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
val refId = UUID.randomUUID()
|
val refId = UUID.randomUUID()
|
||||||
|
|
||||||
val dispatched = mutableListOf<Event>()
|
val dispatched = mutableListOf<Event>()
|
||||||
val done = CompletableDeferred<Unit>()
|
|
||||||
|
|
||||||
// Lytter som registrerer hva som faktisk blir dispatch'et
|
// auto-registrert lytter
|
||||||
EventListenerRegistry.registerListener(
|
object : EventListener() {
|
||||||
object : EventListener() {
|
override fun onEvent(event: Event, history: List<Event>): Event? {
|
||||||
override fun onEvent(event: Event, history: List<Event>): Event? {
|
dispatched += event
|
||||||
dispatched += event
|
return null
|
||||||
done.complete(Unit)
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
)
|
}
|
||||||
|
|
||||||
// Først: et domain-event
|
// Første domain-event
|
||||||
val domain = TriggerEvent().usingReferenceId(refId)
|
eventStore.persist(TriggerEvent().usingReferenceId(refId))
|
||||||
eventStore.persist(domain)
|
|
||||||
|
|
||||||
// Første poll → dispatch domain-event
|
|
||||||
poller.pollOnce()
|
poller.pollOnce()
|
||||||
advanceUntilIdle()
|
queue.awaitIdle()
|
||||||
|
|
||||||
// Tøm listen for å isolere neste dispatch
|
|
||||||
dispatched.clear()
|
|
||||||
|
|
||||||
// Deretter: et signal-event (skal ikke være kandidat)
|
// Signal-event
|
||||||
val signal = EventDispatcherTest.OnHoldSignalEvent().usingReferenceId(refId)
|
eventStore.persist(EventDispatcherTest.OnHoldSignalEvent().usingReferenceId(refId))
|
||||||
eventStore.persist(signal)
|
|
||||||
|
|
||||||
// Andre poll → signal skal trigge dispatch av *domain*, ikke seg selv
|
|
||||||
poller.pollOnce()
|
poller.pollOnce()
|
||||||
advanceUntilIdle()
|
queue.awaitIdle()
|
||||||
|
|
||||||
done.await()
|
assertEquals(2, dispatched.size)
|
||||||
|
assertTrue(dispatched.all { it is TriggerEvent })
|
||||||
assertEquals(
|
|
||||||
2,
|
|
||||||
dispatched.size,
|
|
||||||
"SignalEvent skal trigge dispatch av siste domain-event, ikke seg selv"
|
|
||||||
)
|
|
||||||
|
|
||||||
assertTrue(
|
|
||||||
dispatched.all { it is TriggerEvent },
|
|
||||||
"SignalEvent skal ikke være kandidat — kun siste domain-event skal dispatch'es"
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
suspend fun SequenceDispatchQueue.awaitIdle() {
|
||||||
|
while (true) {
|
||||||
|
val jobs = scope().coroutineContext.job.children.toList()
|
||||||
|
if (jobs.isEmpty()) return
|
||||||
|
jobs.forEach { it.join() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("""
|
||||||
|
Når flere events har identisk persistedAt
|
||||||
|
Hvis polleren kjøres to ganger
|
||||||
|
Så skal polleren ikke redispatch'e siste event (ingen double-dispatch)
|
||||||
|
""")
|
||||||
|
fun pollerDoesNotDoubleDispatchLastEventWithIdenticalTimestamps() = runTest {
|
||||||
|
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||||
|
val queue = TestSequenceDispatchQueue(maxConcurrency = 1, dispatcher = testDispatcher, lifecycleStore)
|
||||||
|
|
||||||
|
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {
|
||||||
|
public override fun updateWatermark(ref: UUID, value: Pair<Instant, Long>) {
|
||||||
|
super.updateWatermark(ref, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
EventTypeRegistry.wipe()
|
||||||
|
EventListenerRegistry.wipe()
|
||||||
|
eventStore.clear()
|
||||||
|
|
||||||
|
EventTypeRegistry.register(listOf(TriggerEvent::class.java))
|
||||||
|
|
||||||
|
|
||||||
|
val refId = UUID.randomUUID()
|
||||||
|
val dispatched = mutableListOf<UUID>()
|
||||||
|
|
||||||
|
val listener = object : EventListener() {
|
||||||
|
override fun onEvent(event: Event, history: List<Event>): Event? {
|
||||||
|
dispatched += event.eventId
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val ts = MyTime.utcNow()
|
||||||
|
|
||||||
|
// Tre events med IDENTISK timestamp (samme som i produksjon)
|
||||||
|
repeat(3) {
|
||||||
|
eventStore.persistAt(TriggerEvent().usingReferenceId(refId), ts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Første poll: alle tre dispatches
|
||||||
|
poller.pollOnce()
|
||||||
|
advanceUntilIdle()
|
||||||
|
|
||||||
|
assertEquals(3, dispatched.size, "Første poll skal dispatch'e alle tre events")
|
||||||
|
|
||||||
|
// Andre poll: watermark + id > skal hindre redispatch
|
||||||
|
poller.pollOnce()
|
||||||
|
advanceUntilIdle()
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
3,
|
||||||
|
dispatched.size,
|
||||||
|
"Polleren skal ikke redispatch'e siste event når persistedAt er identisk"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user