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>) {
|
||||
val deletedEventIds = history.filterIsInstance<DeleteEvent>().map { it.deletedEventId }
|
||||
|
||||
val candidates = newEvents
|
||||
var candidates = newEvents
|
||||
.validEvents(deletedEventIds)
|
||||
.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
|
||||
.validEvents(deletedEventIds)
|
||||
.filterNot { it is DeleteEvent }
|
||||
|
||||
//val producedEvents: MutableList<Event> = mutableListOf()
|
||||
|
||||
EventListenerRegistry.getListeners().forEach { listener ->
|
||||
for (candidate in candidates) {
|
||||
//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)
|
||||
validateDerivation(result, candidate, effectiveHistory, listener)
|
||||
eventStore.persist(result)
|
||||
//producedEvents.add(result)
|
||||
lifecycleStore.add(
|
||||
ListenerResult(
|
||||
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)
|
||||
|
||||
@@ -154,7 +154,7 @@ abstract class EventPollerImplementation(
|
||||
|
||||
val newForRef = eventsForRef.filter { ev ->
|
||||
ev.persistedAt > refSeenAt ||
|
||||
(ev.persistedAt == refSeenAt && ev.id >= refSeenId)
|
||||
(ev.persistedAt == refSeenAt && ev.id > refSeenId)
|
||||
}
|
||||
|
||||
if (newForRef.isEmpty()) {
|
||||
@@ -182,55 +182,24 @@ abstract class EventPollerImplementation(
|
||||
return false
|
||||
}
|
||||
|
||||
// Domain-events (kandidater)
|
||||
val newDomainEvents = newForRef
|
||||
.mapNotNull { it.toEvent() }
|
||||
.filterNot { it is SignalEvent }
|
||||
// ⭐ Send ALLE nye events (domain + signal) til dispatch
|
||||
val newEvents = newForRef.mapNotNull { it.toEvent() }
|
||||
dispatchQueue.dispatch(ref, history, newEvents, dispatcher)
|
||||
|
||||
// ⭐ CASE 1: Kun signaler → trigge dispatch av siste domain-event
|
||||
if (newDomainEvents.isEmpty()) {
|
||||
|
||||
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
|
||||
// ⭐ Flytt watermark KUN basert på domain-events
|
||||
val lastDomainPersisted = newForRef
|
||||
.filter { it.toEvent() !is SignalEvent }
|
||||
.maxWithOrNull(compareBy({ it.persistedAt }, { it.id }))
|
||||
|
||||
if (maxDomainEvent != null) {
|
||||
updateWatermark(ref, maxDomainEvent.persistedAt to maxDomainEvent.id)
|
||||
if (lastDomainPersisted != null) {
|
||||
updateWatermark(ref, lastDomainPersisted.persistedAt to lastDomainPersisted.id)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Oppdaterer global scan hint basert på per-ref watermarks.
|
||||
* Global watermark = min(persistedAt over alle refs).
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package no.iktdev.eventi.events
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
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.RefDispatchStarted
|
||||
import no.iktdev.eventi.models.Event
|
||||
import org.jetbrains.annotations.VisibleForTesting
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
@@ -30,7 +32,8 @@ open class SequenceDispatchQueue(
|
||||
|
||||
fun activeRefs(): Set<UUID> = active.toSet()
|
||||
|
||||
fun _scope(): CoroutineScope {
|
||||
@VisibleForTesting
|
||||
internal fun scope(): CoroutineScope {
|
||||
return scope
|
||||
}
|
||||
|
||||
@@ -62,7 +65,7 @@ open class SequenceDispatchQueue(
|
||||
)
|
||||
log.debug {"▶️ Starting dispatch for $referenceId with ${history.size} events"}
|
||||
|
||||
return scope.launch {
|
||||
return scope.launch(start = CoroutineStart.UNDISPATCHED) {
|
||||
try {
|
||||
// Venter på semaphore
|
||||
lifecycleStore.add(
|
||||
|
||||
@@ -8,6 +8,7 @@ import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.job
|
||||
import kotlinx.coroutines.test.advanceUntilIdle
|
||||
import no.iktdev.eventi.EventDispatcherTest
|
||||
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.testUtil.TestSequenceDispatchQueue
|
||||
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.assertFalse
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
@@ -415,78 +417,124 @@ class EventPollerImplementationTest : TestBase() {
|
||||
|
||||
@Test
|
||||
@DisplayName("""
|
||||
Når kun SignalEvent ankommer etter et domain-event
|
||||
Hvis pollOnce kjøres
|
||||
Så skal polleren trigge dispatch av siste domain-event (ikke signalet)
|
||||
Når kun SignalEvent ankommer etter et domain-event
|
||||
Hvis pollOnce kjøres
|
||||
Så skal polleren trigge dispatch av siste domain-event (ikke signalet)
|
||||
""")
|
||||
fun pollerTriggersLastDomainEventWhenOnlySignalsArrive() = runTest {
|
||||
|
||||
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||
val queue = TestSequenceDispatchQueue(maxConcurrency = 1, dispatcher = testDispatcher, lifecycleStore)
|
||||
|
||||
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {}
|
||||
|
||||
EventTypeRegistry.wipe()
|
||||
EventListenerRegistry.wipe()
|
||||
eventStore.clear()
|
||||
|
||||
// Registrer domain + signal
|
||||
EventTypeRegistry.register(
|
||||
listOf(
|
||||
TriggerEvent::class.java, // domain-event
|
||||
EventDispatcherTest.OnHoldSignalEvent::class.java // signal-event
|
||||
TriggerEvent::class.java,
|
||||
EventDispatcherTest.OnHoldSignalEvent::class.java
|
||||
)
|
||||
)
|
||||
|
||||
val refId = UUID.randomUUID()
|
||||
|
||||
val dispatched = mutableListOf<Event>()
|
||||
val done = CompletableDeferred<Unit>()
|
||||
|
||||
// Lytter som registrerer hva som faktisk blir dispatch'et
|
||||
EventListenerRegistry.registerListener(
|
||||
object : EventListener() {
|
||||
override fun onEvent(event: Event, history: List<Event>): Event? {
|
||||
dispatched += event
|
||||
done.complete(Unit)
|
||||
return null
|
||||
}
|
||||
// auto-registrert lytter
|
||||
object : EventListener() {
|
||||
override fun onEvent(event: Event, history: List<Event>): Event? {
|
||||
dispatched += event
|
||||
return null
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Først: et domain-event
|
||||
val domain = TriggerEvent().usingReferenceId(refId)
|
||||
eventStore.persist(domain)
|
||||
// Første domain-event
|
||||
eventStore.persist(TriggerEvent().usingReferenceId(refId))
|
||||
|
||||
// Første poll → dispatch domain-event
|
||||
poller.pollOnce()
|
||||
advanceUntilIdle()
|
||||
queue.awaitIdle()
|
||||
|
||||
// Tøm listen for å isolere neste dispatch
|
||||
dispatched.clear()
|
||||
|
||||
// Deretter: et signal-event (skal ikke være kandidat)
|
||||
val signal = EventDispatcherTest.OnHoldSignalEvent().usingReferenceId(refId)
|
||||
eventStore.persist(signal)
|
||||
// Signal-event
|
||||
eventStore.persist(EventDispatcherTest.OnHoldSignalEvent().usingReferenceId(refId))
|
||||
|
||||
// Andre poll → signal skal trigge dispatch av *domain*, ikke seg selv
|
||||
poller.pollOnce()
|
||||
advanceUntilIdle()
|
||||
queue.awaitIdle()
|
||||
|
||||
done.await()
|
||||
|
||||
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"
|
||||
)
|
||||
assertEquals(2, dispatched.size)
|
||||
assertTrue(dispatched.all { it is TriggerEvent })
|
||||
}
|
||||
|
||||
|
||||
|
||||
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