Lifecycle
This commit is contained in:
1 parent
fbade21451
commit
2919e9731a
21 files changed
+1260
-80
No files matched your search
@@ -0,0 +1,47 @@
|
|||||||
|
package no.iktdev.eventi
|
||||||
|
|
||||||
|
import java.time.Instant
|
||||||
|
import java.util.UUID
|
||||||
|
import java.util.ArrayDeque
|
||||||
|
|
||||||
|
sealed interface PollerTraceEntry {
|
||||||
|
val timestamp: Instant
|
||||||
|
}
|
||||||
|
|
||||||
|
data class GlobalTrace(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val lastSeenBefore: Instant,
|
||||||
|
val lastSeenAfter: Instant,
|
||||||
|
val maxSeenThisRound: Instant?,
|
||||||
|
val refsProcessed: List<UUID>,
|
||||||
|
val refsDeferred: List<UUID>
|
||||||
|
) : PollerTraceEntry
|
||||||
|
|
||||||
|
data class RefTrace(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID,
|
||||||
|
val seen: List<Pair<Instant, Long>>,
|
||||||
|
val newForRef: List<Pair<Instant, Long>>,
|
||||||
|
val watermarkBefore: Pair<Instant, Long>,
|
||||||
|
val watermarkAfter: Pair<Instant, Long>?,
|
||||||
|
val busy: Boolean,
|
||||||
|
val dispatched: Boolean
|
||||||
|
) : PollerTraceEntry
|
||||||
|
|
||||||
|
class PollerTraceStore(private val capacity: Int = 500) {
|
||||||
|
|
||||||
|
private val buffer = ArrayDeque<PollerTraceEntry>(capacity)
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun add(entry: PollerTraceEntry) {
|
||||||
|
if (buffer.size >= capacity) buffer.removeFirst()
|
||||||
|
buffer.addLast(entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun getAll(): List<PollerTraceEntry> = buffer.toList()
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun getForRef(ref: UUID): List<RefTrace> =
|
||||||
|
buffer.filterIsInstance<RefTrace>().filter { it.ref == ref }
|
||||||
|
}
|
||||||
@@ -2,6 +2,10 @@ package no.iktdev.eventi.events
|
|||||||
|
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import mu.KotlinLogging
|
import mu.KotlinLogging
|
||||||
|
import no.iktdev.eventi.MyTime
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
|
import no.iktdev.eventi.lifecycle.ListenerFatalError
|
||||||
|
import no.iktdev.eventi.lifecycle.ListenerResult
|
||||||
import no.iktdev.eventi.models.DeleteEvent
|
import no.iktdev.eventi.models.DeleteEvent
|
||||||
import no.iktdev.eventi.models.DispatchResult
|
import no.iktdev.eventi.models.DispatchResult
|
||||||
import no.iktdev.eventi.models.Event
|
import no.iktdev.eventi.models.Event
|
||||||
@@ -10,7 +14,7 @@ import no.iktdev.eventi.registry.EventListenerRegistry
|
|||||||
import no.iktdev.eventi.stores.EventStore
|
import no.iktdev.eventi.stores.EventStore
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
open class EventDispatcher(val eventStore: EventStore) {
|
open class EventDispatcher(val eventStore: EventStore, private val lifecycleStore: LifecycleStore) {
|
||||||
|
|
||||||
private val log = KotlinLogging.logger {}
|
private val log = KotlinLogging.logger {}
|
||||||
|
|
||||||
@@ -35,17 +39,78 @@ open class EventDispatcher(val eventStore: EventStore) {
|
|||||||
validateReferenceId(result, listener)
|
validateReferenceId(result, listener)
|
||||||
validateDerivation(result, candidate, effectiveHistory, listener)
|
validateDerivation(result, candidate, effectiveHistory, listener)
|
||||||
eventStore.persist(result)
|
eventStore.persist(result)
|
||||||
|
lifecycleStore.add(
|
||||||
|
ListenerResult(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId,
|
||||||
|
listener = listener::class.java.simpleName,
|
||||||
|
result = "Accepted"
|
||||||
|
)
|
||||||
|
)
|
||||||
onDispatched(candidate, listener, DispatchResult.Accepted)
|
onDispatched(candidate, listener, DispatchResult.Accepted)
|
||||||
} else {
|
} else {
|
||||||
|
lifecycleStore.add(
|
||||||
|
ListenerResult(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId,
|
||||||
|
listener = listener::class.java.simpleName,
|
||||||
|
result = "NoResult"
|
||||||
|
)
|
||||||
|
)
|
||||||
onDispatched(candidate, listener, DispatchResult.NoResult)
|
onDispatched(candidate, listener, DispatchResult.NoResult)
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (e: SoftDispatchException.UnqualifiedEntryEventException) {
|
} catch (e: SoftDispatchException.UnqualifiedEntryEventException) {
|
||||||
|
lifecycleStore.add(
|
||||||
|
ListenerResult(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId,
|
||||||
|
listener = listener::class.java.simpleName,
|
||||||
|
result = "Rejected: ${e.message}"
|
||||||
|
)
|
||||||
|
)
|
||||||
onDispatched(candidate, listener, DispatchResult.Rejected, e.message)
|
onDispatched(candidate, listener, DispatchResult.Rejected, e.message)
|
||||||
} catch (e: SoftDispatchException.SkipListenerException) {
|
} catch (e: SoftDispatchException.SkipListenerException) {
|
||||||
|
lifecycleStore.add(
|
||||||
|
ListenerResult(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId,
|
||||||
|
listener = listener::class.java.simpleName,
|
||||||
|
result = "Skipped: ${e.message}"
|
||||||
|
)
|
||||||
|
)
|
||||||
onDispatched(candidate, listener, DispatchResult.Skipped, e.message)
|
onDispatched(candidate, listener, DispatchResult.Skipped, e.message)
|
||||||
} catch (e: SoftDispatchException) {
|
} catch (e: SoftDispatchException) {
|
||||||
|
lifecycleStore.add(
|
||||||
|
ListenerResult(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId,
|
||||||
|
listener = listener::class.java.simpleName,
|
||||||
|
result = "Error: ${e.message}"
|
||||||
|
)
|
||||||
|
)
|
||||||
onDispatched(candidate, listener, DispatchResult.Error, e.message)
|
onDispatched(candidate, listener, DispatchResult.Error, e.message)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
|
||||||
|
// ⭐ NYTT: Fatal exception
|
||||||
|
lifecycleStore.add(
|
||||||
|
ListenerFatalError(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId,
|
||||||
|
listener = listener::class.java.simpleName,
|
||||||
|
eventName = candidate::class.java.simpleName,
|
||||||
|
exception = "${e::class.java.simpleName}: ${e.message}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Du kan velge å logge dette hardt
|
||||||
|
log.error(e) { "Fatal exception in listener ${listener::class.java.simpleName}" }
|
||||||
|
|
||||||
|
// Og du kan velge hva du gjør videre:
|
||||||
|
// - rethrow (stopper dispatch)
|
||||||
|
// - swallow (fortsetter)
|
||||||
|
// - wrap i HardDispatchException
|
||||||
|
throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,36 @@
|
|||||||
package no.iktdev.eventi.events
|
package no.iktdev.eventi.events
|
||||||
|
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.time.delay
|
||||||
import mu.KotlinLogging
|
import mu.KotlinLogging
|
||||||
import no.iktdev.eventi.MyTime
|
import no.iktdev.eventi.MyTime
|
||||||
|
import no.iktdev.eventi.PollerTraceStore
|
||||||
|
import no.iktdev.eventi.lifecycle.CurrentState
|
||||||
|
import no.iktdev.eventi.lifecycle.EventState
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
|
import no.iktdev.eventi.lifecycle.PollerBackoff
|
||||||
|
import no.iktdev.eventi.lifecycle.PollerCycleStart
|
||||||
|
import no.iktdev.eventi.lifecycle.PollerFetched
|
||||||
|
import no.iktdev.eventi.lifecycle.PollerGrouped
|
||||||
|
import no.iktdev.eventi.lifecycle.PollerUpdatedLastSeen
|
||||||
|
import no.iktdev.eventi.lifecycle.RefState
|
||||||
import no.iktdev.eventi.models.store.PersistedEvent
|
import no.iktdev.eventi.models.store.PersistedEvent
|
||||||
import no.iktdev.eventi.serialization.ZDS.toEvent
|
import no.iktdev.eventi.serialization.ZDS.toEvent
|
||||||
import no.iktdev.eventi.stores.EventStore
|
import no.iktdev.eventi.stores.EventStore
|
||||||
import java.time.Duration
|
import java.time.Duration
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
import kotlin.text.compareTo
|
||||||
|
import kotlin.time.Duration.Companion.milliseconds
|
||||||
|
|
||||||
abstract class EventPollerImplementation(
|
abstract class EventPollerImplementation(
|
||||||
private val eventStore: EventStore,
|
private val eventStore: EventStore,
|
||||||
private val dispatchQueue: SequenceDispatchQueue,
|
private val dispatchQueue: SequenceDispatchQueue,
|
||||||
private val dispatcher: EventDispatcher
|
private val dispatcher: EventDispatcher,
|
||||||
|
private val lifecycleStore: LifecycleStore
|
||||||
) {
|
) {
|
||||||
private val log = KotlinLogging.logger {}
|
private val log = KotlinLogging.logger {}
|
||||||
|
|
||||||
/**
|
|
||||||
* Per-reference watermark:
|
|
||||||
* - first = last seen persistedAt
|
|
||||||
* * - second = last seen persistedId
|
|
||||||
*/
|
|
||||||
protected val refWatermark = mutableMapOf<UUID, Pair<Instant, Long>>()
|
protected val refWatermark = mutableMapOf<UUID, Pair<Instant, Long>>()
|
||||||
|
|
||||||
protected open fun updateWatermark(ref: UUID, value: Pair<Instant, Long>) {
|
protected open fun updateWatermark(ref: UUID, value: Pair<Instant, Long>) {
|
||||||
@@ -45,7 +54,7 @@ abstract class EventPollerImplementation(
|
|||||||
pollOnce()
|
pollOnce()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
log.error(e) { "Error in poller loop" }
|
log.error(e) { "Error in poller loop" }
|
||||||
delay(backoff.toMillis())
|
delay(backoff)
|
||||||
backoff = backoff.multipliedBy(2).coerceAtMost(maxBackoff)
|
backoff = backoff.multipliedBy(2).coerceAtMost(maxBackoff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -53,9 +62,26 @@ abstract class EventPollerImplementation(
|
|||||||
|
|
||||||
suspend fun pollOnce() {
|
suspend fun pollOnce() {
|
||||||
val pollStartedAt = MyTime.utcNow()
|
val pollStartedAt = MyTime.utcNow()
|
||||||
|
|
||||||
|
// Lifecycle: start av poll-syklus
|
||||||
|
lifecycleStore.add(
|
||||||
|
PollerCycleStart(
|
||||||
|
timestamp = pollStartedAt,
|
||||||
|
scanFrom = lastSeenTime
|
||||||
|
)
|
||||||
|
)
|
||||||
log.debug { "🔍 Polling for new events at $pollStartedAt (scanFrom=$lastSeenTime)" }
|
log.debug { "🔍 Polling for new events at $pollStartedAt (scanFrom=$lastSeenTime)" }
|
||||||
|
|
||||||
val newPersisted = fetchNewPersistedEvents(lastSeenTime)
|
val newPersisted = fetchNewPersistedEvents(lastSeenTime)
|
||||||
|
|
||||||
|
// Lifecycle: hvor mange events ble hentet
|
||||||
|
lifecycleStore.add(
|
||||||
|
PollerFetched(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
count = newPersisted.size
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
if (newPersisted.isEmpty()) {
|
if (newPersisted.isEmpty()) {
|
||||||
handleEmptyPoll()
|
handleEmptyPoll()
|
||||||
return
|
return
|
||||||
@@ -66,6 +92,14 @@ abstract class EventPollerImplementation(
|
|||||||
|
|
||||||
val grouped = newPersisted.groupBy { it.referenceId }
|
val grouped = newPersisted.groupBy { it.referenceId }
|
||||||
|
|
||||||
|
// Lifecycle: hvilke refs som var med i denne poll-runden
|
||||||
|
lifecycleStore.add(
|
||||||
|
PollerGrouped(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
refs = grouped.keys.toList()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
var anyProcessed = false
|
var anyProcessed = false
|
||||||
for ((ref, eventsForRef) in grouped) {
|
for ((ref, eventsForRef) in grouped) {
|
||||||
if (processReference(ref, eventsForRef)) {
|
if (processReference(ref, eventsForRef)) {
|
||||||
@@ -76,9 +110,18 @@ abstract class EventPollerImplementation(
|
|||||||
// Move global scan hint forward to avoid livelock
|
// Move global scan hint forward to avoid livelock
|
||||||
val maxSeenThisRound = newPersisted.maxOfOrNull { it.persistedAt }
|
val maxSeenThisRound = newPersisted.maxOfOrNull { it.persistedAt }
|
||||||
if (maxSeenThisRound != null && maxSeenThisRound > lastSeenTime) {
|
if (maxSeenThisRound != null && maxSeenThisRound > lastSeenTime) {
|
||||||
|
val before = lastSeenTime
|
||||||
lastSeenTime = maxSeenThisRound
|
lastSeenTime = maxSeenThisRound
|
||||||
}
|
|
||||||
|
|
||||||
|
// Lifecycle: global lastSeenTime flyttet
|
||||||
|
lifecycleStore.add(
|
||||||
|
PollerUpdatedLastSeen(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
before = before,
|
||||||
|
after = lastSeenTime
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
updateGlobalWatermark(anyProcessed)
|
updateGlobalWatermark(anyProcessed)
|
||||||
}
|
}
|
||||||
@@ -87,8 +130,16 @@ abstract class EventPollerImplementation(
|
|||||||
eventStore.getPersistedEventsAfter(scanFrom)
|
eventStore.getPersistedEventsAfter(scanFrom)
|
||||||
|
|
||||||
private suspend fun handleEmptyPoll() {
|
private suspend fun handleEmptyPoll() {
|
||||||
|
// Lifecycle: backoff når ingen events ble funnet
|
||||||
|
lifecycleStore.add(
|
||||||
|
PollerBackoff(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
backoffMillis = backoff.toMillis()
|
||||||
|
)
|
||||||
|
)
|
||||||
log.debug { "😴 No new events found. Backing off for $backoff" }
|
log.debug { "😴 No new events found. Backing off for $backoff" }
|
||||||
delay(backoff.toMillis())
|
|
||||||
|
delay(backoff)
|
||||||
backoff = backoff.multipliedBy(2).coerceAtMost(maxBackoff)
|
backoff = backoff.multipliedBy(2).coerceAtMost(maxBackoff)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,6 +152,7 @@ abstract class EventPollerImplementation(
|
|||||||
* Returnerer true hvis vi faktisk dispatch’et noe.
|
* Returnerer true hvis vi faktisk dispatch’et noe.
|
||||||
*/
|
*/
|
||||||
private fun processReference(ref: UUID, eventsForRef: List<PersistedEvent>): Boolean {
|
private fun processReference(ref: UUID, eventsForRef: List<PersistedEvent>): Boolean {
|
||||||
|
// (Neste steg: vi legger inn Lifecycle her også)
|
||||||
val (refSeenAt, refSeenId) = refWatermark[ref] ?: (Instant.EPOCH to 0L)
|
val (refSeenAt, refSeenId) = refWatermark[ref] ?: (Instant.EPOCH to 0L)
|
||||||
|
|
||||||
// Filter new events using (timestamp, id) ordering
|
// Filter new events using (timestamp, id) ordering
|
||||||
@@ -116,9 +168,6 @@ abstract class EventPollerImplementation(
|
|||||||
|
|
||||||
// If ref is busy, advance watermark but skip dispatch
|
// If ref is busy, advance watermark but skip dispatch
|
||||||
if (dispatchQueue.isProcessing(ref)) {
|
if (dispatchQueue.isProcessing(ref)) {
|
||||||
val maxEvent = newForRef.maxWith(
|
|
||||||
compareBy({ it.persistedAt }, { it.id })
|
|
||||||
)
|
|
||||||
log.debug {
|
log.debug {
|
||||||
log.debug { "⏳ $ref is busy — deferring ${newForRef.size} events" }
|
log.debug { "⏳ $ref is busy — deferring ${newForRef.size} events" }
|
||||||
}
|
}
|
||||||
@@ -159,4 +208,33 @@ abstract class EventPollerImplementation(
|
|||||||
log.debug { "🔁 No refs processed — keeping global scanFrom at $lastSeenTime" }
|
log.debug { "🔁 No refs processed — keeping global scanFrom at $lastSeenTime" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun eventState(): EventState {
|
||||||
|
val now = MyTime.utcNow()
|
||||||
|
|
||||||
|
val refStates = refWatermark.map { (ref, wm) ->
|
||||||
|
val fullLog = eventStore.getPersistedEventsFor(ref)
|
||||||
|
val lastEvent = fullLog.maxByOrNull { it.persistedAt }
|
||||||
|
|
||||||
|
val hasUnprocessed = lastEvent != null &&
|
||||||
|
(lastEvent.persistedAt > wm.first || lastEvent.id > wm.second)
|
||||||
|
|
||||||
|
RefState(
|
||||||
|
ref = ref,
|
||||||
|
watermark = wm,
|
||||||
|
isProcessing = dispatchQueue.isProcessing(ref),
|
||||||
|
hasUnprocessedEvents = hasUnprocessed,
|
||||||
|
lastEventAt = lastEvent?.persistedAt
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return EventState(
|
||||||
|
lastSeenTime = lastSeenTime,
|
||||||
|
backoffMillis = backoff.toMillis(),
|
||||||
|
nextPollExpectedAt = now.plusMillis(backoff.toMillis()),
|
||||||
|
activeRefs = dispatchQueue.activeRefs(),
|
||||||
|
refStates = refStates
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -7,17 +7,28 @@ import kotlinx.coroutines.SupervisorJob
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.sync.Semaphore
|
import kotlinx.coroutines.sync.Semaphore
|
||||||
import mu.KotlinLogging
|
import mu.KotlinLogging
|
||||||
|
import no.iktdev.eventi.MyTime
|
||||||
|
import no.iktdev.eventi.lifecycle.DispatchExceptionEntry
|
||||||
|
import no.iktdev.eventi.lifecycle.DispatchQueueAcquired
|
||||||
|
import no.iktdev.eventi.lifecycle.DispatchQueueReleased
|
||||||
|
import no.iktdev.eventi.lifecycle.DispatchQueueSkipped
|
||||||
|
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 no.iktdev.eventi.models.Event
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
open class SequenceDispatchQueue(
|
open class SequenceDispatchQueue(
|
||||||
private val maxConcurrency: Int = 8,
|
private val maxConcurrency: Int = 8,
|
||||||
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Default + SupervisorJob()),
|
||||||
|
private val lifecycleStore: LifecycleStore
|
||||||
) {
|
) {
|
||||||
private val semaphore = Semaphore(maxConcurrency)
|
private val semaphore = Semaphore(maxConcurrency)
|
||||||
private val active = ConcurrentHashMap.newKeySet<UUID>()
|
private val active = ConcurrentHashMap.newKeySet<UUID>()
|
||||||
|
|
||||||
|
fun activeRefs(): Set<UUID> = active.toSet()
|
||||||
|
|
||||||
fun _scope(): CoroutineScope {
|
fun _scope(): CoroutineScope {
|
||||||
return scope
|
return scope
|
||||||
}
|
}
|
||||||
@@ -29,13 +40,36 @@ open class SequenceDispatchQueue(
|
|||||||
|
|
||||||
open fun dispatch(referenceId: UUID, history: List<Event>, newEvents: List<Event>, dispatcher: EventDispatcher): Job? {
|
open fun dispatch(referenceId: UUID, history: List<Event>, newEvents: List<Event>, dispatcher: EventDispatcher): Job? {
|
||||||
if (!active.add(referenceId)) {
|
if (!active.add(referenceId)) {
|
||||||
|
lifecycleStore.add(
|
||||||
|
DispatchQueueSkipped(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId
|
||||||
|
)
|
||||||
|
)
|
||||||
log.debug {"⚠️ Already processing $referenceId, skipping dispatch"}
|
log.debug {"⚠️ Already processing $referenceId, skipping dispatch"}
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dispatch starter
|
||||||
|
lifecycleStore.add(
|
||||||
|
RefDispatchStarted(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId,
|
||||||
|
historyCount = history.size,
|
||||||
|
newCount = newEvents.size
|
||||||
|
)
|
||||||
|
)
|
||||||
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 {
|
||||||
try {
|
try {
|
||||||
|
// Venter på semaphore
|
||||||
|
lifecycleStore.add(
|
||||||
|
DispatchQueueAcquired(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId
|
||||||
|
)
|
||||||
|
)
|
||||||
log.debug {"⏳ Waiting for semaphore for $referenceId"}
|
log.debug {"⏳ Waiting for semaphore for $referenceId"}
|
||||||
semaphore.acquire()
|
semaphore.acquire()
|
||||||
log.debug {"🔓 Acquired semaphore for $referenceId"}
|
log.debug {"🔓 Acquired semaphore for $referenceId"}
|
||||||
@@ -45,12 +79,32 @@ open class SequenceDispatchQueue(
|
|||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
log.error("Dispatch failed for $referenceId: ${e.message}")
|
log.error("Dispatch failed for $referenceId: ${e.message}")
|
||||||
e.printStackTrace()
|
e.printStackTrace()
|
||||||
|
lifecycleStore.add(
|
||||||
|
DispatchExceptionEntry(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId,
|
||||||
|
exception = "${e::class.java.simpleName}: ${e.message}",
|
||||||
|
stacktrace = e.stackTraceToString()
|
||||||
|
)
|
||||||
|
)
|
||||||
} finally {
|
} finally {
|
||||||
semaphore.release()
|
semaphore.release()
|
||||||
|
lifecycleStore.add(
|
||||||
|
DispatchQueueReleased(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId
|
||||||
|
)
|
||||||
|
)
|
||||||
log.debug {"✅ Released semaphore for $referenceId"}
|
log.debug {"✅ Released semaphore for $referenceId"}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
active.remove(referenceId)
|
active.remove(referenceId)
|
||||||
|
lifecycleStore.add(
|
||||||
|
RefDispatchCompleted(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
ref = referenceId
|
||||||
|
)
|
||||||
|
)
|
||||||
log.debug {"🏁 Finished dispatch for $referenceId"}
|
log.debug {"🏁 Finished dispatch for $referenceId"}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
package no.iktdev.eventi.lifecycle
|
||||||
|
|
||||||
|
import no.iktdev.eventi.models.Progress
|
||||||
|
import java.time.Instant
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
sealed interface LifecycleEntry {
|
||||||
|
val timestamp: Instant
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------- POLLER ----------------------------- */
|
||||||
|
|
||||||
|
data class PollerCycleStart(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val scanFrom: Instant
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class PollerFetched(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val count: Int
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class PollerGrouped(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val refs: List<UUID>
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class PollerUpdatedLastSeen(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val before: Instant,
|
||||||
|
val after: Instant
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class PollerBackoff(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val backoffMillis: Long
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
/* ----------------------------- REF ----------------------------- */
|
||||||
|
|
||||||
|
data class RefFiltered(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID,
|
||||||
|
val seenCount: Int,
|
||||||
|
val newCount: Int,
|
||||||
|
val watermarkBefore: Pair<Instant, Long>
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class RefBusy(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID,
|
||||||
|
val deferredCount: Int
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class RefDispatchStarted(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID,
|
||||||
|
val historyCount: Int,
|
||||||
|
val newCount: Int
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class RefDispatchCompleted(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class RefWatermarkUpdated(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID,
|
||||||
|
val before: Pair<Instant, Long>,
|
||||||
|
val after: Pair<Instant, Long>
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
/* ----------------------------- DISPATCH QUEUE ----------------------------- */
|
||||||
|
|
||||||
|
data class DispatchQueueAcquired(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class DispatchQueueReleased(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class DispatchQueueSkipped(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class DispatchExceptionEntry(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID,
|
||||||
|
val exception: String,
|
||||||
|
val stacktrace: String
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
|
||||||
|
/* ----------------------------- DISPATCHER ----------------------------- */
|
||||||
|
|
||||||
|
data class ListenerInvoked(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID,
|
||||||
|
val listener: String,
|
||||||
|
val eventName: String
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class ListenerResult(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID,
|
||||||
|
val listener: String,
|
||||||
|
val result: String
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class ListenerFatalError(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val ref: UUID,
|
||||||
|
val listener: String,
|
||||||
|
val eventName: String,
|
||||||
|
val exception: String
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
/* ----------------------------- Tasks ----------------------------- */
|
||||||
|
|
||||||
|
data class TaskPollerCycleStart(
|
||||||
|
override val timestamp: Instant
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class TaskPollerFetched(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val count: Int
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class TaskPollerBackoff(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val backoffMillis: Long
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class TaskListenerInvoked(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val taskId: String,
|
||||||
|
val listener: String
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class TaskListenerResult(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val taskId: String,
|
||||||
|
val listener: String,
|
||||||
|
val result: String
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class TaskListenerFatalError(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val taskId: String,
|
||||||
|
val listener: String,
|
||||||
|
val exception: String,
|
||||||
|
val stacktrace: String
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class TaskClaimed(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val taskId: UUID,
|
||||||
|
val workerId: String
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class TaskProgress(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val taskId: UUID,
|
||||||
|
val progress: Progress
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class TaskCompleted(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val taskId: UUID
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class TaskFailed(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val taskId: UUID,
|
||||||
|
val referenceId: UUID
|
||||||
|
) : LifecycleEntry
|
||||||
|
|
||||||
|
data class TaskCancelled(
|
||||||
|
override val timestamp: Instant,
|
||||||
|
val taskId: UUID,
|
||||||
|
val referenceId: UUID
|
||||||
|
) : LifecycleEntry
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package no.iktdev.eventi.lifecycle
|
||||||
|
|
||||||
|
import java.time.Instant
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
data class EventState(
|
||||||
|
val lastSeenTime: Instant,
|
||||||
|
val backoffMillis: Long,
|
||||||
|
val nextPollExpectedAt: Instant,
|
||||||
|
val activeRefs: Set<UUID>,
|
||||||
|
val refStates: List<RefState>
|
||||||
|
)
|
||||||
|
|
||||||
|
data class TaskStateSummary(
|
||||||
|
val taskBackoffMillis: Long,
|
||||||
|
val nextTaskPollExpectedAt: Instant,
|
||||||
|
val pendingTasks: Int,
|
||||||
|
val taskStates: List<TaskState>
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
data class CurrentState(
|
||||||
|
// ----- EVENT POLLER -----
|
||||||
|
val lastSeenTime: Instant,
|
||||||
|
val backoffMillis: Long,
|
||||||
|
val nextPollExpectedAt: Instant,
|
||||||
|
val activeRefs: Set<UUID>,
|
||||||
|
val refStates: List<RefState>,
|
||||||
|
|
||||||
|
// ----- TASK POLLER -----
|
||||||
|
val taskBackoffMillis: Long,
|
||||||
|
val nextTaskPollExpectedAt: Instant,
|
||||||
|
val pendingTasks: Int,
|
||||||
|
val taskStates: List<TaskState>
|
||||||
|
)
|
||||||
|
|
||||||
|
data class RefState(
|
||||||
|
val ref: UUID,
|
||||||
|
val watermark: Pair<Instant, Long>,
|
||||||
|
val isProcessing: Boolean,
|
||||||
|
val hasUnprocessedEvents: Boolean,
|
||||||
|
val lastEventAt: Instant?
|
||||||
|
)
|
||||||
|
|
||||||
|
data class TaskState(
|
||||||
|
val taskId: String,
|
||||||
|
val type: String,
|
||||||
|
val listener: String?,
|
||||||
|
val status: TaskStatus
|
||||||
|
)
|
||||||
|
|
||||||
|
enum class TaskStatus {
|
||||||
|
PENDING,
|
||||||
|
ACCEPTED,
|
||||||
|
IGNORED,
|
||||||
|
FAILED
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package no.iktdev.eventi.lifecycle
|
||||||
|
|
||||||
|
import no.iktdev.eventi.MyTime
|
||||||
|
import no.iktdev.eventi.events.EventPollerImplementation
|
||||||
|
import no.iktdev.eventi.events.SequenceDispatchQueue
|
||||||
|
import no.iktdev.eventi.tasks.TaskPollerImplementation
|
||||||
|
import no.iktdev.eventi.stores.TaskStore
|
||||||
|
import java.time.Instant
|
||||||
|
|
||||||
|
class LifecycleStateBuilder(
|
||||||
|
private val eventPoller: EventPollerImplementation,
|
||||||
|
private val taskPoller: TaskPollerImplementation
|
||||||
|
) {
|
||||||
|
suspend fun build(): CurrentState {
|
||||||
|
val eventState = eventPoller.eventState()
|
||||||
|
val taskState = taskPoller.taskState()
|
||||||
|
|
||||||
|
return CurrentState(
|
||||||
|
lastSeenTime = eventState.lastSeenTime,
|
||||||
|
backoffMillis = eventState.backoffMillis,
|
||||||
|
nextPollExpectedAt = eventState.nextPollExpectedAt,
|
||||||
|
activeRefs = eventState.activeRefs,
|
||||||
|
refStates = eventState.refStates,
|
||||||
|
|
||||||
|
taskBackoffMillis = taskState.taskBackoffMillis,
|
||||||
|
nextTaskPollExpectedAt = taskState.nextTaskPollExpectedAt,
|
||||||
|
pendingTasks = taskState.pendingTasks,
|
||||||
|
taskStates = taskState.taskStates
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package no.iktdev.eventi.lifecycle
|
||||||
|
|
||||||
|
import java.util.ArrayDeque
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
class LifecycleStore(private val capacity: Int = 50_000) {
|
||||||
|
|
||||||
|
private val buffer = ArrayDeque<LifecycleEntry>(capacity)
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun add(entry: LifecycleEntry) {
|
||||||
|
if (buffer.size >= capacity) {
|
||||||
|
buffer.removeFirst()
|
||||||
|
}
|
||||||
|
buffer.addLast(entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun getAll(): List<LifecycleEntry> =
|
||||||
|
buffer.toList()
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun getForRef(ref: UUID): List<LifecycleEntry> =
|
||||||
|
buffer.filter {
|
||||||
|
when (it) {
|
||||||
|
is RefFiltered -> it.ref == ref
|
||||||
|
is RefBusy -> it.ref == ref
|
||||||
|
is RefDispatchStarted -> it.ref == ref
|
||||||
|
is RefDispatchCompleted -> it.ref == ref
|
||||||
|
is RefWatermarkUpdated -> it.ref == ref
|
||||||
|
is DispatchQueueAcquired -> it.ref == ref
|
||||||
|
is DispatchQueueReleased -> it.ref == ref
|
||||||
|
is DispatchQueueSkipped -> it.ref == ref
|
||||||
|
is ListenerInvoked -> it.ref == ref
|
||||||
|
is ListenerResult -> it.ref == ref
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package no.iktdev.eventi.lifecycle
|
||||||
|
|
||||||
|
import no.iktdev.eventi.MyTime
|
||||||
|
import no.iktdev.eventi.models.Event
|
||||||
|
import no.iktdev.eventi.models.Progress
|
||||||
|
import no.iktdev.eventi.tasks.Result
|
||||||
|
import no.iktdev.eventi.tasks.TaskReporter
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
class LifecycleTaskReporter(
|
||||||
|
private val delegate: TaskReporter,
|
||||||
|
private val lifecycleStore: LifecycleStore
|
||||||
|
) : TaskReporter {
|
||||||
|
override fun markClaimed(taskId: UUID, workerId: String): Result {
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskClaimed(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
taskId = taskId,
|
||||||
|
workerId = workerId
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return delegate.markClaimed(taskId, workerId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun updateLastSeen(taskId: UUID): Result {
|
||||||
|
return delegate.updateLastSeen(taskId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun markCompleted(taskId: UUID): Result {
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskCompleted(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
taskId = taskId
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return delegate.markCompleted(taskId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun markFailed(referenceId: UUID, taskId: UUID): Result {
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskFailed(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
taskId = taskId,
|
||||||
|
referenceId = referenceId
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return delegate.markFailed(referenceId, taskId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun markCancelled(referenceId: UUID, taskId: UUID): Result {
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskCancelled(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
taskId = taskId,
|
||||||
|
referenceId = referenceId
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return delegate.markCancelled(referenceId, taskId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun updateProgress(
|
||||||
|
referenceId: UUID,
|
||||||
|
taskId: UUID,
|
||||||
|
payload: Progress
|
||||||
|
): Result {
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskProgress(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
taskId = taskId,
|
||||||
|
progress = payload
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return delegate.updateProgress(referenceId, taskId, payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun log(taskId: UUID, message: String) {
|
||||||
|
delegate.log(taskId, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun publishEvent(event: Event): Result {
|
||||||
|
return delegate.publishEvent(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
package no.iktdev.eventi.lifecycle
|
||||||
|
|
||||||
|
import java.time.Instant
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
data class TimelineEntry(
|
||||||
|
val timestamp: Instant,
|
||||||
|
val ref: UUID?,
|
||||||
|
val category: TimelineCategory,
|
||||||
|
val description: String,
|
||||||
|
val raw: LifecycleEntry
|
||||||
|
)
|
||||||
|
|
||||||
|
enum class TimelineCategory {
|
||||||
|
POLLER,
|
||||||
|
REF,
|
||||||
|
DISPATCH_QUEUE,
|
||||||
|
DISPATCHER,
|
||||||
|
TASK,
|
||||||
|
ERROR
|
||||||
|
}
|
||||||
|
|
||||||
|
fun LifecycleStore.timeline(): List<TimelineEntry> =
|
||||||
|
getAll().map { it.toTimeline() }.sortedBy { it.timestamp }
|
||||||
|
|
||||||
|
fun LifecycleStore.timelineForRef(ref: UUID): List<TimelineEntry> =
|
||||||
|
getForRef(ref).map { it.toTimeline() }.sortedBy { it.timestamp }
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
fun LifecycleEntry.toTimeline(): TimelineEntry {
|
||||||
|
return when (this) {
|
||||||
|
|
||||||
|
/* -------------------- EVENT POLLER -------------------- */
|
||||||
|
|
||||||
|
is PollerCycleStart -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.POLLER,
|
||||||
|
"Poller cycle start (scanFrom=$scanFrom)", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is PollerFetched -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.POLLER,
|
||||||
|
"Fetched $count new events", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is PollerGrouped -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.POLLER,
|
||||||
|
"Grouped refs: ${refs.size}", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is PollerUpdatedLastSeen -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.POLLER,
|
||||||
|
"Updated lastSeenTime → $after", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is PollerBackoff -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.POLLER,
|
||||||
|
"Backoff for ${backoffMillis}ms", this
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
/* -------------------- EVENT REF -------------------- */
|
||||||
|
|
||||||
|
is RefFiltered -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.REF,
|
||||||
|
"Ref $ref filtered: ${newCount}/${seenCount} new events", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is RefBusy -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.REF,
|
||||||
|
"Ref $ref busy, deferred ${deferredCount} events", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is RefDispatchStarted -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.REF,
|
||||||
|
"Dispatch started (history=${historyCount}, new=${newCount})", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is RefDispatchCompleted -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.REF,
|
||||||
|
"Dispatch completed", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is RefWatermarkUpdated -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.REF,
|
||||||
|
"Watermark updated → ${after.first} / ${after.second}", this
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
/* -------------------- DISPATCH QUEUE -------------------- */
|
||||||
|
|
||||||
|
is DispatchQueueAcquired -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.DISPATCH_QUEUE,
|
||||||
|
"Semaphore acquired", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is DispatchQueueReleased -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.DISPATCH_QUEUE,
|
||||||
|
"Semaphore released", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is DispatchQueueSkipped -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.DISPATCH_QUEUE,
|
||||||
|
"Dispatch skipped (already active)", this
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
/* -------------------- EVENT DISPATCHER -------------------- */
|
||||||
|
|
||||||
|
is ListenerInvoked -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.DISPATCHER,
|
||||||
|
"Listener ${listener} invoked for $eventName", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is ListenerResult -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.DISPATCHER,
|
||||||
|
"Listener ${listener} result: $result", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is ListenerFatalError -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.ERROR,
|
||||||
|
"FATAL listener error in ${listener}: $exception", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is DispatchExceptionEntry -> TimelineEntry(
|
||||||
|
timestamp, ref, TimelineCategory.ERROR,
|
||||||
|
"FATAL dispatch error: $exception", this
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
/* -------------------- TASK POLLER -------------------- */
|
||||||
|
|
||||||
|
is TaskPollerCycleStart -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.TASK,
|
||||||
|
"Task poller cycle start", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is TaskPollerFetched -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.TASK,
|
||||||
|
"Fetched ${count} pending tasks", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is TaskPollerBackoff -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.TASK,
|
||||||
|
"Task poller backoff for ${backoffMillis}ms", this
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
/* -------------------- TASK DISPATCH -------------------- */
|
||||||
|
|
||||||
|
is TaskListenerInvoked -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.TASK,
|
||||||
|
"Task ${taskId}: listener ${listener} invoked", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is TaskListenerResult -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.TASK,
|
||||||
|
"Task ${taskId}: listener ${listener} → $result", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is TaskListenerFatalError -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.ERROR,
|
||||||
|
"FATAL task listener error for task ${taskId}: $exception", this
|
||||||
|
)
|
||||||
|
/* -------------------- TASK LIFECYCLE (REPORTER) -------------------- */
|
||||||
|
|
||||||
|
is TaskClaimed -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.TASK,
|
||||||
|
"Task ${taskId} claimed by ${workerId}", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is TaskProgress -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.TASK,
|
||||||
|
"Task ${taskId} progress: ${progress}", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is TaskCompleted -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.TASK,
|
||||||
|
"Task ${taskId} completed", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is TaskFailed -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.ERROR,
|
||||||
|
"Task ${taskId} failed (ref=$referenceId)", this
|
||||||
|
)
|
||||||
|
|
||||||
|
is TaskCancelled -> TimelineEntry(
|
||||||
|
timestamp, null, TimelineCategory.TASK,
|
||||||
|
"Task ${taskId} cancelled (ref=$referenceId)", this
|
||||||
|
)
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,20 @@
|
|||||||
package no.iktdev.eventi.tasks
|
package no.iktdev.eventi.tasks
|
||||||
|
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.time.delay
|
||||||
import mu.KotlinLogging
|
import mu.KotlinLogging
|
||||||
|
import no.iktdev.eventi.MyTime
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleTaskReporter
|
||||||
|
import no.iktdev.eventi.lifecycle.TaskListenerFatalError
|
||||||
|
import no.iktdev.eventi.lifecycle.TaskListenerInvoked
|
||||||
|
import no.iktdev.eventi.lifecycle.TaskListenerResult
|
||||||
|
import no.iktdev.eventi.lifecycle.TaskPollerBackoff
|
||||||
|
import no.iktdev.eventi.lifecycle.TaskPollerCycleStart
|
||||||
|
import no.iktdev.eventi.lifecycle.TaskPollerFetched
|
||||||
|
import no.iktdev.eventi.lifecycle.TaskState
|
||||||
|
import no.iktdev.eventi.lifecycle.TaskStateSummary
|
||||||
|
import no.iktdev.eventi.lifecycle.TaskStatus
|
||||||
import no.iktdev.eventi.serialization.ZDS.toTask
|
import no.iktdev.eventi.serialization.ZDS.toTask
|
||||||
import no.iktdev.eventi.models.Task
|
import no.iktdev.eventi.models.Task
|
||||||
import no.iktdev.eventi.registry.TaskListenerRegistry
|
import no.iktdev.eventi.registry.TaskListenerRegistry
|
||||||
@@ -10,7 +23,8 @@ import java.time.Duration
|
|||||||
|
|
||||||
abstract class TaskPollerImplementation(
|
abstract class TaskPollerImplementation(
|
||||||
private val taskStore: TaskStore,
|
private val taskStore: TaskStore,
|
||||||
private val reporterFactory: (Task) -> TaskReporter
|
private val lifecycleStore: LifecycleStore,
|
||||||
|
private val reporterFactory: (Task) -> TaskReporter,
|
||||||
) {
|
) {
|
||||||
private val log = KotlinLogging.logger {}
|
private val log = KotlinLogging.logger {}
|
||||||
|
|
||||||
@@ -35,19 +49,46 @@ abstract class TaskPollerImplementation(
|
|||||||
pollOnce()
|
pollOnce()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
log.error(e) { "Unhandled error in poll loop, backing off for $backoff" }
|
log.error(e) { "Unhandled error in poll loop, backing off for $backoff" }
|
||||||
delay(backoff.toMillis())
|
lifecycleStore.add(
|
||||||
|
TaskListenerFatalError(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
taskId = "N/A",
|
||||||
|
listener = "TaskPoller",
|
||||||
|
exception = "${e::class.java.simpleName}: ${e.message}",
|
||||||
|
stacktrace = e.stackTraceToString()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
delay(backoff)
|
||||||
backoff = backoff.multipliedBy(2).coerceAtMost(maxBackoff)
|
backoff = backoff.multipliedBy(2).coerceAtMost(maxBackoff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun pollOnce() {
|
suspend fun pollOnce() {
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskPollerCycleStart(
|
||||||
|
timestamp = MyTime.utcNow()
|
||||||
|
)
|
||||||
|
)
|
||||||
log.debug { "Polling for pending tasks…" }
|
log.debug { "Polling for pending tasks…" }
|
||||||
val newPersistedTasks = taskStore.getPendingTasks()
|
val newPersistedTasks = taskStore.getPendingTasks()
|
||||||
|
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskPollerFetched(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
count = newPersistedTasks.size
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
if (newPersistedTasks.isEmpty()) {
|
if (newPersistedTasks.isEmpty()) {
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskPollerBackoff(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
backoffMillis = backoff.toMillis()
|
||||||
|
)
|
||||||
|
)
|
||||||
log.debug { "No pending tasks found. Backing off for $backoff" }
|
log.debug { "No pending tasks found. Backing off for $backoff" }
|
||||||
delay(backoff.toMillis())
|
delay(backoff)
|
||||||
backoff = backoff.multipliedBy(2).coerceAtMost(maxBackoff)
|
backoff = backoff.multipliedBy(2).coerceAtMost(maxBackoff)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -73,6 +114,14 @@ abstract class TaskPollerImplementation(
|
|||||||
.filter { it.supports(task) && !it.isBusy }
|
.filter { it.supports(task) && !it.isBusy }
|
||||||
|
|
||||||
if (candidates.isEmpty()) {
|
if (candidates.isEmpty()) {
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskListenerResult(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
taskId = task.taskId.toString(),
|
||||||
|
listener = "NO_MATCHING_LISTENER",
|
||||||
|
result = "IGNORED"
|
||||||
|
)
|
||||||
|
)
|
||||||
results += PollResult(
|
results += PollResult(
|
||||||
taskId = task.taskId.toString(),
|
taskId = task.taskId.toString(),
|
||||||
type = task::class.simpleName.toString(),
|
type = task::class.simpleName.toString(),
|
||||||
@@ -86,17 +135,46 @@ abstract class TaskPollerImplementation(
|
|||||||
var accepted = false
|
var accepted = false
|
||||||
|
|
||||||
for (listener in candidates) {
|
for (listener in candidates) {
|
||||||
val reporter = reporterFactory(task)
|
val reporter = LifecycleTaskReporter(
|
||||||
|
delegate = reporterFactory(task),
|
||||||
|
lifecycleStore = lifecycleStore
|
||||||
|
)
|
||||||
|
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskListenerInvoked(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
taskId = task.taskId.toString(),
|
||||||
|
listener = listener.getWorkerId()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
val ok = try {
|
val ok = try {
|
||||||
listener.accept(task, reporter)
|
listener.accept(task, reporter)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskListenerFatalError(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
taskId = task.taskId.toString(),
|
||||||
|
listener = listener.getWorkerId(),
|
||||||
|
exception = "${e::class.java.simpleName}: ${e.message}",
|
||||||
|
stacktrace = e.stackTraceToString()
|
||||||
|
)
|
||||||
|
)
|
||||||
log.error(e) {
|
log.error(e) {
|
||||||
"Error while processing task ${task.taskId} by listener ${listener.getWorkerId()}"
|
"Error while processing task ${task.taskId} by listener ${listener.getWorkerId()}"
|
||||||
}
|
}
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskListenerResult(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
taskId = task.taskId.toString(),
|
||||||
|
listener = listener.getWorkerId(),
|
||||||
|
result = if (ok) "ACCEPTED" else "IGNORED"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
val (statusPlain, statusColored) = when {
|
val (statusPlain, statusColored) = when {
|
||||||
ok -> "[ACCEPTED]" to colorize("[ACCEPTED]", Color.GREEN)
|
ok -> "[ACCEPTED]" to colorize("[ACCEPTED]", Color.GREEN)
|
||||||
else -> "[IGNORED]" to colorize("[IGNORED]", Color.YELLOW)
|
else -> "[IGNORED]" to colorize("[IGNORED]", Color.YELLOW)
|
||||||
@@ -123,8 +201,14 @@ abstract class TaskPollerImplementation(
|
|||||||
log.debug { formatTaskReport(results) }
|
log.debug { formatTaskReport(results) }
|
||||||
|
|
||||||
if (!acceptedAny) {
|
if (!acceptedAny) {
|
||||||
|
lifecycleStore.add(
|
||||||
|
TaskPollerBackoff(
|
||||||
|
timestamp = MyTime.utcNow(),
|
||||||
|
backoffMillis = backoff.toMillis()
|
||||||
|
)
|
||||||
|
)
|
||||||
log.debug { "No tasks were accepted. Backing off for $backoff" }
|
log.debug { "No tasks were accepted. Backing off for $backoff" }
|
||||||
delay(backoff.toMillis())
|
delay(backoff)
|
||||||
backoff = backoff.multipliedBy(2).coerceAtMost(maxBackoff)
|
backoff = backoff.multipliedBy(2).coerceAtMost(maxBackoff)
|
||||||
} else {
|
} else {
|
||||||
log.debug { "At least one task accepted. Resetting backoff." }
|
log.debug { "At least one task accepted. Resetting backoff." }
|
||||||
@@ -178,4 +262,24 @@ abstract class TaskPollerImplementation(
|
|||||||
val statusColored: String,
|
val statusColored: String,
|
||||||
val listener: String
|
val listener: String
|
||||||
)
|
)
|
||||||
|
|
||||||
|
suspend fun taskState(): TaskStateSummary {
|
||||||
|
val now = MyTime.utcNow()
|
||||||
|
val pending = taskStore.getPendingTasks()
|
||||||
|
|
||||||
|
return TaskStateSummary(
|
||||||
|
taskBackoffMillis = backoff.toMillis(),
|
||||||
|
nextTaskPollExpectedAt = now.plusMillis(backoff.toMillis()),
|
||||||
|
pendingTasks = pending.size,
|
||||||
|
taskStates = pending.map {
|
||||||
|
TaskState(
|
||||||
|
taskId = it.taskId.toString(),
|
||||||
|
type = it.task,
|
||||||
|
listener = null,
|
||||||
|
status = TaskStatus.PENDING
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ import no.iktdev.eventi.serialization.ZDS.toPersisted
|
|||||||
import no.iktdev.eventi.events.EventDispatcher
|
import no.iktdev.eventi.events.EventDispatcher
|
||||||
import no.iktdev.eventi.events.EventListener
|
import no.iktdev.eventi.events.EventListener
|
||||||
import no.iktdev.eventi.events.HardDispatchException
|
import no.iktdev.eventi.events.HardDispatchException
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
import no.iktdev.eventi.registry.EventTypeRegistry
|
import no.iktdev.eventi.registry.EventTypeRegistry
|
||||||
import no.iktdev.eventi.models.DeleteEvent
|
import no.iktdev.eventi.models.DeleteEvent
|
||||||
import no.iktdev.eventi.models.Event
|
import no.iktdev.eventi.models.Event
|
||||||
@@ -28,8 +29,8 @@ Så skal dispatcheren håndtere filtrering, replays og historikk korrekt
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
class EventDispatcherTest : TestBase() {
|
class EventDispatcherTest : TestBase() {
|
||||||
|
val lifecycleStore = LifecycleStore()
|
||||||
val dispatcher = EventDispatcher(eventStore)
|
val dispatcher = EventDispatcher(eventStore, lifecycleStore)
|
||||||
|
|
||||||
class DerivedEvent : Event()
|
class DerivedEvent : Event()
|
||||||
class TriggerEvent : Event()
|
class TriggerEvent : Event()
|
||||||
@@ -147,7 +148,7 @@ class EventDispatcherTest : TestBase() {
|
|||||||
fun shouldNotDeliverDeletedEventsAsCandidates() {
|
fun shouldNotDeliverDeletedEventsAsCandidates() {
|
||||||
val referenceId = UUID.randomUUID()
|
val referenceId = UUID.randomUUID()
|
||||||
|
|
||||||
val dispatcher = EventDispatcher(eventStore)
|
val dispatcher = EventDispatcher(eventStore, lifecycleStore)
|
||||||
val received = mutableListOf<Event>()
|
val received = mutableListOf<Event>()
|
||||||
|
|
||||||
object : EventListener() {
|
object : EventListener() {
|
||||||
@@ -229,7 +230,7 @@ class EventDispatcherTest : TestBase() {
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
fun historyShouldExcludeDeletedEvents() {
|
fun historyShouldExcludeDeletedEvents() {
|
||||||
val dispatcher = EventDispatcher(eventStore)
|
val dispatcher = EventDispatcher(eventStore, lifecycleStore)
|
||||||
|
|
||||||
val original = TriggerEvent().newReferenceId()
|
val original = TriggerEvent().newReferenceId()
|
||||||
val deleted = object : DeleteEvent(original.eventId) {}.apply { usingReferenceId(original.referenceId) }
|
val deleted = object : DeleteEvent(original.eventId) {}.apply { usingReferenceId(original.referenceId) }
|
||||||
@@ -258,7 +259,7 @@ class EventDispatcherTest : TestBase() {
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
fun historyShouldKeepNonDeletedEvents() {
|
fun historyShouldKeepNonDeletedEvents() {
|
||||||
val dispatcher = EventDispatcher(eventStore)
|
val dispatcher = EventDispatcher(eventStore, lifecycleStore)
|
||||||
val referenceId = UUID.randomUUID()
|
val referenceId = UUID.randomUUID()
|
||||||
val e1 = TriggerEvent().usingReferenceId(referenceId)
|
val e1 = TriggerEvent().usingReferenceId(referenceId)
|
||||||
val e2 = OtherEvent().usingReferenceId(referenceId)
|
val e2 = OtherEvent().usingReferenceId(referenceId)
|
||||||
@@ -289,7 +290,7 @@ class EventDispatcherTest : TestBase() {
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
fun deleteEventShouldBeDeliveredButHistoryEmpty() {
|
fun deleteEventShouldBeDeliveredButHistoryEmpty() {
|
||||||
val dispatcher = EventDispatcher(eventStore)
|
val dispatcher = EventDispatcher(eventStore, lifecycleStore)
|
||||||
|
|
||||||
val original = TriggerEvent().newReferenceId()
|
val original = TriggerEvent().newReferenceId()
|
||||||
val deleted = object : DeleteEvent(original.eventId) {}.apply { newReferenceId() }
|
val deleted = object : DeleteEvent(original.eventId) {}.apply { newReferenceId() }
|
||||||
@@ -356,7 +357,7 @@ class EventDispatcherTest : TestBase() {
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
fun replayShouldSelectLastValidEventWhenLaterEventIsDeleted() {
|
fun replayShouldSelectLastValidEventWhenLaterEventIsDeleted() {
|
||||||
val dispatcher = EventDispatcher(eventStore)
|
val dispatcher = EventDispatcher(eventStore, lifecycleStore)
|
||||||
val referenceId = UUID.randomUUID()
|
val referenceId = UUID.randomUUID()
|
||||||
|
|
||||||
val received = mutableListOf<Event>()
|
val received = mutableListOf<Event>()
|
||||||
@@ -389,7 +390,7 @@ class EventDispatcherTest : TestBase() {
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
fun shouldThrowWhenDerivingFromHistoricalEventWithoutOptIn() {
|
fun shouldThrowWhenDerivingFromHistoricalEventWithoutOptIn() {
|
||||||
val dispatcher = EventDispatcher(eventStore)
|
val dispatcher = EventDispatcher(eventStore, lifecycleStore)
|
||||||
val referenceId = UUID.randomUUID()
|
val referenceId = UUID.randomUUID()
|
||||||
|
|
||||||
// Historikk
|
// Historikk
|
||||||
@@ -426,7 +427,7 @@ class EventDispatcherTest : TestBase() {
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
fun shouldAllowHistoricalDerivationWhenOptInIsEnabled() {
|
fun shouldAllowHistoricalDerivationWhenOptInIsEnabled() {
|
||||||
val dispatcher = EventDispatcher(eventStore)
|
val dispatcher = EventDispatcher(eventStore, lifecycleStore)
|
||||||
val referenceId = UUID.randomUUID()
|
val referenceId = UUID.randomUUID()
|
||||||
|
|
||||||
// Historikk
|
// Historikk
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import no.iktdev.eventi.EventDispatcherTest.OtherEvent
|
|||||||
import no.iktdev.eventi.EventDispatcherTest.TriggerEvent
|
import no.iktdev.eventi.EventDispatcherTest.TriggerEvent
|
||||||
import no.iktdev.eventi.MyTime
|
import no.iktdev.eventi.MyTime
|
||||||
import no.iktdev.eventi.TestBase
|
import no.iktdev.eventi.TestBase
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
import no.iktdev.eventi.models.Event
|
import no.iktdev.eventi.models.Event
|
||||||
import no.iktdev.eventi.registry.EventListenerRegistry
|
import no.iktdev.eventi.registry.EventListenerRegistry
|
||||||
import no.iktdev.eventi.registry.EventTypeRegistry
|
import no.iktdev.eventi.registry.EventTypeRegistry
|
||||||
@@ -39,7 +40,8 @@ Så skal polleren dispatch'e riktig, oppdatere lastSeenTime og unngå duplikater
|
|||||||
""")
|
""")
|
||||||
class EventPollerImplementationTest : TestBase() {
|
class EventPollerImplementationTest : TestBase() {
|
||||||
|
|
||||||
private val dispatcher = EventDispatcher(eventStore)
|
val lifecycleStore = LifecycleStore()
|
||||||
|
private val dispatcher = EventDispatcher(eventStore, lifecycleStore)
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
fun setup() {
|
fun setup() {
|
||||||
@@ -64,8 +66,8 @@ class EventPollerImplementationTest : TestBase() {
|
|||||||
""")
|
""")
|
||||||
fun pollOnceDispatchesAllNewReferenceIdsAndUpdatesLastSeenTime() = runTest {
|
fun pollOnceDispatchesAllNewReferenceIdsAndUpdatesLastSeenTime() = runTest {
|
||||||
val testDispatcher = StandardTestDispatcher(testScheduler)
|
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||||
val queue = TestSequenceDispatchQueue(maxConcurrency = 8, dispatcher = testDispatcher)
|
val queue = TestSequenceDispatchQueue(maxConcurrency = 8, dispatcher = testDispatcher, lifecycleStore)
|
||||||
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher) {}
|
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {}
|
||||||
|
|
||||||
val dispatched = ConcurrentHashMap.newKeySet<UUID>()
|
val dispatched = ConcurrentHashMap.newKeySet<UUID>()
|
||||||
val completionMap = mutableMapOf<UUID, CompletableDeferred<Unit>>()
|
val completionMap = mutableMapOf<UUID, CompletableDeferred<Unit>>()
|
||||||
@@ -102,9 +104,9 @@ class EventPollerImplementationTest : TestBase() {
|
|||||||
""")
|
""")
|
||||||
fun pollOnceIncreasesBackoffWhenNoEventsAndResetsWhenEventsArrive() = runTest {
|
fun pollOnceIncreasesBackoffWhenNoEventsAndResetsWhenEventsArrive() = runTest {
|
||||||
val testDispatcher = StandardTestDispatcher(testScheduler)
|
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||||
val queue = TestSequenceDispatchQueue(maxConcurrency = 8, dispatcher = testDispatcher)
|
val queue = TestSequenceDispatchQueue(maxConcurrency = 8, dispatcher = testDispatcher, lifecycleStore)
|
||||||
|
|
||||||
val testPoller = object : EventPollerImplementation(eventStore, queue, dispatcher) {
|
val testPoller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {
|
||||||
fun currentBackoff(): Duration = backoff
|
fun currentBackoff(): Duration = backoff
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,8 +135,8 @@ class EventPollerImplementationTest : TestBase() {
|
|||||||
""")
|
""")
|
||||||
fun pollOnceGroupsAndDispatchesExactlyThreeEventsForOneReferenceId() = runTest {
|
fun pollOnceGroupsAndDispatchesExactlyThreeEventsForOneReferenceId() = runTest {
|
||||||
val testDispatcher = StandardTestDispatcher(testScheduler)
|
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||||
val queue = TestSequenceDispatchQueue(maxConcurrency = 8, dispatcher = testDispatcher)
|
val queue = TestSequenceDispatchQueue(maxConcurrency = 8, dispatcher = testDispatcher, lifecycleStore)
|
||||||
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher) {}
|
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {}
|
||||||
|
|
||||||
val refId = UUID.randomUUID()
|
val refId = UUID.randomUUID()
|
||||||
val received = mutableListOf<Event>()
|
val received = mutableListOf<Event>()
|
||||||
@@ -173,9 +175,9 @@ class EventPollerImplementationTest : TestBase() {
|
|||||||
""")
|
""")
|
||||||
fun pollOnceIgnoresEventsBeforeLastSeenTime() = runTest {
|
fun pollOnceIgnoresEventsBeforeLastSeenTime() = runTest {
|
||||||
val testDispatcher = StandardTestDispatcher(testScheduler)
|
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||||
val queue = TestSequenceDispatchQueue(maxConcurrency = 8, dispatcher = testDispatcher)
|
val queue = TestSequenceDispatchQueue(maxConcurrency = 8, dispatcher = testDispatcher, lifecycleStore)
|
||||||
|
|
||||||
val testPoller = object : EventPollerImplementation(eventStore, queue, dispatcher) {
|
val testPoller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {
|
||||||
init {
|
init {
|
||||||
lastSeenTime = MyTime.utcNow().plusSeconds(1)
|
lastSeenTime = MyTime.utcNow().plusSeconds(1)
|
||||||
}
|
}
|
||||||
@@ -199,8 +201,8 @@ class EventPollerImplementationTest : TestBase() {
|
|||||||
""")
|
""")
|
||||||
fun pollerHandlesManuallyInjectedDuplicateEvent() = runTest {
|
fun pollerHandlesManuallyInjectedDuplicateEvent() = runTest {
|
||||||
val testDispatcher = StandardTestDispatcher(testScheduler)
|
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||||
val queue = TestSequenceDispatchQueue(maxConcurrency = 8, dispatcher = testDispatcher)
|
val queue = TestSequenceDispatchQueue(maxConcurrency = 8, dispatcher = testDispatcher, lifecycleStore)
|
||||||
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher) {}
|
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {}
|
||||||
|
|
||||||
EventTypeRegistry.register(listOf(MarcoEvent::class.java, EchoEvent::class.java))
|
EventTypeRegistry.register(listOf(MarcoEvent::class.java, EchoEvent::class.java))
|
||||||
|
|
||||||
@@ -251,9 +253,9 @@ class EventPollerImplementationTest : TestBase() {
|
|||||||
""")
|
""")
|
||||||
fun pollerDoesNotLoseEventsWithIdenticalTimestamps() = runTest {
|
fun pollerDoesNotLoseEventsWithIdenticalTimestamps() = runTest {
|
||||||
val testDispatcher = StandardTestDispatcher(testScheduler)
|
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||||
val queue = TestSequenceDispatchQueue(maxConcurrency = 1, dispatcher = testDispatcher)
|
val queue = TestSequenceDispatchQueue(maxConcurrency = 1, dispatcher = testDispatcher, lifecycleStore)
|
||||||
|
|
||||||
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher) {
|
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {
|
||||||
public override fun updateWatermark(ref: UUID, value: Pair<Instant, Long>) {
|
public override fun updateWatermark(ref: UUID, value: Pair<Instant, Long>) {
|
||||||
super.updateWatermark(ref, value)
|
super.updateWatermark(ref, value)
|
||||||
}
|
}
|
||||||
@@ -315,9 +317,9 @@ class EventPollerImplementationTest : TestBase() {
|
|||||||
""")
|
""")
|
||||||
fun pollerDoesNotRedispatchEventsWithIdenticalTimestamps() = runTest {
|
fun pollerDoesNotRedispatchEventsWithIdenticalTimestamps() = runTest {
|
||||||
val testDispatcher = StandardTestDispatcher(testScheduler)
|
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||||
val queue = TestSequenceDispatchQueue(maxConcurrency = 1, dispatcher = testDispatcher)
|
val queue = TestSequenceDispatchQueue(maxConcurrency = 1, dispatcher = testDispatcher, lifecycleStore)
|
||||||
|
|
||||||
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher) {
|
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {
|
||||||
public override fun updateWatermark(ref: UUID, value: Pair<Instant, Long>) {
|
public override fun updateWatermark(ref: UUID, value: Pair<Instant, Long>) {
|
||||||
super.updateWatermark(ref, value)
|
super.updateWatermark(ref, value)
|
||||||
}
|
}
|
||||||
@@ -368,9 +370,9 @@ class EventPollerImplementationTest : TestBase() {
|
|||||||
""")
|
""")
|
||||||
fun pollerDoesNotSkipOtherReferencesWithSameTimestamp() = runTest {
|
fun pollerDoesNotSkipOtherReferencesWithSameTimestamp() = runTest {
|
||||||
val testDispatcher = StandardTestDispatcher(testScheduler)
|
val testDispatcher = StandardTestDispatcher(testScheduler)
|
||||||
val queue = TestSequenceDispatchQueue(maxConcurrency = 1, dispatcher = testDispatcher)
|
val queue = TestSequenceDispatchQueue(maxConcurrency = 1, dispatcher = testDispatcher, lifecycleStore)
|
||||||
|
|
||||||
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher) {
|
val poller = object : EventPollerImplementation(eventStore, queue, dispatcher, lifecycleStore) {
|
||||||
public override fun updateWatermark(ref: UUID, value: Pair<Instant, Long>) {
|
public override fun updateWatermark(ref: UUID, value: Pair<Instant, Long>) {
|
||||||
super.updateWatermark(ref, value)
|
super.updateWatermark(ref, value)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ package no.iktdev.eventi.events
|
|||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
import kotlinx.coroutines.test.*
|
import kotlinx.coroutines.test.*
|
||||||
import no.iktdev.eventi.InMemoryEventStore
|
import no.iktdev.eventi.InMemoryEventStore
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
import org.assertj.core.api.Assertions.assertThat
|
import org.assertj.core.api.Assertions.assertThat
|
||||||
import org.junit.jupiter.api.BeforeEach
|
import org.junit.jupiter.api.BeforeEach
|
||||||
import org.junit.jupiter.api.Test
|
import org.junit.jupiter.api.Test
|
||||||
@@ -16,10 +17,10 @@ import org.junit.jupiter.api.DisplayName
|
|||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
|
|
||||||
class FakeDispatchQueue(
|
class FakeDispatchQueue(
|
||||||
private val scope: CoroutineScope
|
private val scope: CoroutineScope,
|
||||||
) : SequenceDispatchQueue(8, scope) {
|
private val lifecycleStore: LifecycleStore
|
||||||
|
) : SequenceDispatchQueue(8, scope, lifecycleStore) {
|
||||||
|
|
||||||
private val active = ConcurrentHashMap.newKeySet<UUID>()
|
private val active = ConcurrentHashMap.newKeySet<UUID>()
|
||||||
|
|
||||||
@@ -38,7 +39,7 @@ class FakeDispatchQueue(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class FakeDispatcher : EventDispatcher(InMemoryEventStore()) {
|
class FakeDispatcher(private val lifecycleStore: LifecycleStore) : EventDispatcher(InMemoryEventStore(), lifecycleStore) {
|
||||||
|
|
||||||
val dispatched = mutableListOf<Pair<UUID, List<Event>>>()
|
val dispatched = mutableListOf<Pair<UUID, List<Event>>>()
|
||||||
|
|
||||||
@@ -67,6 +68,8 @@ Så skal polleren oppdatere lastSeenTime, unngå duplikater og prosessere riktig
|
|||||||
""")
|
""")
|
||||||
class RunSimulationTestTest {
|
class RunSimulationTestTest {
|
||||||
|
|
||||||
|
val lifecycleStore = LifecycleStore()
|
||||||
|
|
||||||
private lateinit var store: InMemoryEventStore
|
private lateinit var store: InMemoryEventStore
|
||||||
private lateinit var dispatcher: FakeDispatcher
|
private lateinit var dispatcher: FakeDispatcher
|
||||||
private lateinit var testDispatcher: TestDispatcher
|
private lateinit var testDispatcher: TestDispatcher
|
||||||
@@ -77,12 +80,12 @@ class RunSimulationTestTest {
|
|||||||
@BeforeEach
|
@BeforeEach
|
||||||
fun setup() {
|
fun setup() {
|
||||||
store = InMemoryEventStore()
|
store = InMemoryEventStore()
|
||||||
dispatcher = FakeDispatcher()
|
dispatcher = FakeDispatcher(lifecycleStore)
|
||||||
testDispatcher = StandardTestDispatcher()
|
testDispatcher = StandardTestDispatcher()
|
||||||
scope = CoroutineScope(testDispatcher)
|
scope = CoroutineScope(testDispatcher)
|
||||||
queue = FakeDispatchQueue(scope)
|
queue = FakeDispatchQueue(scope, lifecycleStore)
|
||||||
EventTypeRegistry.register(TestEvent::class.java)
|
EventTypeRegistry.register(TestEvent::class.java)
|
||||||
poller = object : EventPollerImplementation(store, queue, dispatcher) {
|
poller = object : EventPollerImplementation(store, queue, dispatcher, lifecycleStore) {
|
||||||
override suspend fun start() = error("Do not call start() in tests")
|
override suspend fun start() = error("Do not call start() in tests")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -110,7 +113,7 @@ class RunSimulationTestTest {
|
|||||||
assertThat(dispatcher.dispatched).hasSize(1)
|
assertThat(dispatcher.dispatched).hasSize(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
class AlwaysBusyDispatchQueue : SequenceDispatchQueue(8, CoroutineScope(Dispatchers.Default)) {
|
class AlwaysBusyDispatchQueue(private val lifecycleStore: LifecycleStore) : SequenceDispatchQueue(8, CoroutineScope(Dispatchers.Default), lifecycleStore) {
|
||||||
override fun isProcessing(referenceId: UUID): Boolean = true
|
override fun isProcessing(referenceId: UUID): Boolean = true
|
||||||
override fun dispatch(referenceId: UUID, history: List<Event>, newEvents: List<Event>, dispatcher: EventDispatcher) = null
|
override fun dispatch(referenceId: UUID, history: List<Event>, newEvents: List<Event>, dispatcher: EventDispatcher) = null
|
||||||
}
|
}
|
||||||
@@ -127,8 +130,8 @@ class RunSimulationTestTest {
|
|||||||
|
|
||||||
store.persistAt(TestEvent().withReference(ref), t)
|
store.persistAt(TestEvent().withReference(ref), t)
|
||||||
|
|
||||||
val busyQueue = AlwaysBusyDispatchQueue()
|
val busyQueue = AlwaysBusyDispatchQueue(lifecycleStore)
|
||||||
val poller = object : EventPollerImplementation(store, busyQueue, dispatcher) {}
|
val poller = object : EventPollerImplementation(store, busyQueue, dispatcher, lifecycleStore) {}
|
||||||
|
|
||||||
poller.pollOnce()
|
poller.pollOnce()
|
||||||
advanceUntilIdle()
|
advanceUntilIdle()
|
||||||
@@ -211,8 +214,9 @@ class RunSimulationTestTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class ControlledDispatchQueue(
|
class ControlledDispatchQueue(
|
||||||
private val scope: CoroutineScope
|
private val scope: CoroutineScope,
|
||||||
) : SequenceDispatchQueue(8, scope) {
|
private val lifecycleStore: LifecycleStore
|
||||||
|
) : SequenceDispatchQueue(8, scope, lifecycleStore) {
|
||||||
|
|
||||||
val busyRefs = mutableSetOf<UUID>()
|
val busyRefs = mutableSetOf<UUID>()
|
||||||
|
|
||||||
@@ -237,10 +241,10 @@ class RunSimulationTestTest {
|
|||||||
|
|
||||||
persistEvent(ref)
|
persistEvent(ref)
|
||||||
|
|
||||||
val controlledQueue = ControlledDispatchQueue(scope)
|
val controlledQueue = ControlledDispatchQueue(scope, lifecycleStore)
|
||||||
controlledQueue.busyRefs += ref
|
controlledQueue.busyRefs += ref
|
||||||
|
|
||||||
val poller = object : EventPollerImplementation(store, controlledQueue, dispatcher) {}
|
val poller = object : EventPollerImplementation(store, controlledQueue, dispatcher, lifecycleStore) {}
|
||||||
|
|
||||||
// Poll #1: busy → no dispatch
|
// Poll #1: busy → no dispatch
|
||||||
poller.pollOnce()
|
poller.pollOnce()
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import no.iktdev.eventi.EventDispatcherTest.DerivedEvent
|
|||||||
import no.iktdev.eventi.EventDispatcherTest.OtherEvent
|
import no.iktdev.eventi.EventDispatcherTest.OtherEvent
|
||||||
import no.iktdev.eventi.EventDispatcherTest.TriggerEvent
|
import no.iktdev.eventi.EventDispatcherTest.TriggerEvent
|
||||||
import no.iktdev.eventi.TestBase
|
import no.iktdev.eventi.TestBase
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
import no.iktdev.eventi.models.Event
|
import no.iktdev.eventi.models.Event
|
||||||
import no.iktdev.eventi.registry.EventListenerRegistry
|
import no.iktdev.eventi.registry.EventListenerRegistry
|
||||||
import no.iktdev.eventi.registry.EventTypeRegistry
|
import no.iktdev.eventi.registry.EventTypeRegistry
|
||||||
@@ -24,6 +25,7 @@ Hvis køen har begrenset samtidighet
|
|||||||
Så skal alle events prosesseres uten tap
|
Så skal alle events prosesseres uten tap
|
||||||
""")
|
""")
|
||||||
class SequenceDispatchQueueTest : TestBase() {
|
class SequenceDispatchQueueTest : TestBase() {
|
||||||
|
private val lifecycleStore = LifecycleStore()
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
fun setup() {
|
fun setup() {
|
||||||
@@ -46,8 +48,8 @@ class SequenceDispatchQueueTest : TestBase() {
|
|||||||
Så skal alle referenceId-er bli prosessert nøyaktig én gang
|
Så skal alle referenceId-er bli prosessert nøyaktig én gang
|
||||||
""")
|
""")
|
||||||
fun shouldDispatchAllReferenceIdsWithLimitedConcurrency() = runTest {
|
fun shouldDispatchAllReferenceIdsWithLimitedConcurrency() = runTest {
|
||||||
val dispatcher = EventDispatcher(eventStore)
|
val dispatcher = EventDispatcher(eventStore, lifecycleStore)
|
||||||
val queue = SequenceDispatchQueue(maxConcurrency = 8)
|
val queue = SequenceDispatchQueue(maxConcurrency = 8, lifecycleStore = lifecycleStore)
|
||||||
|
|
||||||
val dispatched = ConcurrentHashMap.newKeySet<UUID>()
|
val dispatched = ConcurrentHashMap.newKeySet<UUID>()
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import no.iktdev.eventi.events.FakeDispatcher
|
|||||||
import no.iktdev.eventi.events.RunSimulationTestTest
|
import no.iktdev.eventi.events.RunSimulationTestTest
|
||||||
import no.iktdev.eventi.events.SequenceDispatchQueue
|
import no.iktdev.eventi.events.SequenceDispatchQueue
|
||||||
import no.iktdev.eventi.events.TestEvent
|
import no.iktdev.eventi.events.TestEvent
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
import no.iktdev.eventi.models.Event
|
import no.iktdev.eventi.models.Event
|
||||||
import no.iktdev.eventi.models.Metadata
|
import no.iktdev.eventi.models.Metadata
|
||||||
import no.iktdev.eventi.models.store.PersistedEvent
|
import no.iktdev.eventi.models.store.PersistedEvent
|
||||||
@@ -32,6 +33,7 @@ Hvis events ankommer, refs er busy eller watermark flytter seg
|
|||||||
Så skal polleren håndtere backoff, dispatch og livelock korrekt
|
Så skal polleren håndtere backoff, dispatch og livelock korrekt
|
||||||
""")
|
""")
|
||||||
class PollerStartLoopTest : TestBase() {
|
class PollerStartLoopTest : TestBase() {
|
||||||
|
private val lifecycleStore = LifecycleStore()
|
||||||
|
|
||||||
private lateinit var store: InMemoryEventStore
|
private lateinit var store: InMemoryEventStore
|
||||||
private lateinit var dispatcher: FakeDispatcher
|
private lateinit var dispatcher: FakeDispatcher
|
||||||
@@ -46,13 +48,13 @@ class PollerStartLoopTest : TestBase() {
|
|||||||
@BeforeEach
|
@BeforeEach
|
||||||
fun setup() {
|
fun setup() {
|
||||||
store = InMemoryEventStore()
|
store = InMemoryEventStore()
|
||||||
dispatcher = FakeDispatcher()
|
dispatcher = FakeDispatcher(lifecycleStore)
|
||||||
testDispatcher = StandardTestDispatcher()
|
testDispatcher = StandardTestDispatcher()
|
||||||
scope = TestScope(testDispatcher)
|
scope = TestScope(testDispatcher)
|
||||||
queue = RunSimulationTestTest.ControlledDispatchQueue(scope)
|
queue = RunSimulationTestTest.ControlledDispatchQueue(scope, lifecycleStore)
|
||||||
EventTypeRegistry.register(TestEvent::class.java)
|
EventTypeRegistry.register(TestEvent::class.java)
|
||||||
|
|
||||||
poller = TestablePoller(store, queue, dispatcher, scope)
|
poller = TestablePoller(store, queue, dispatcher, scope, lifecycleStore)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun persistAt(ref: UUID, time: Instant) {
|
private fun persistAt(ref: UUID, time: Instant) {
|
||||||
@@ -463,13 +465,13 @@ class PollerStartLoopTest : TestBase() {
|
|||||||
override fun persist(event: Event) = Unit
|
override fun persist(event: Event) = Unit
|
||||||
}
|
}
|
||||||
|
|
||||||
val queue = SequenceDispatchQueue()
|
val queue = SequenceDispatchQueue(lifecycleStore = lifecycleStore)
|
||||||
class NoopDispatcher : EventDispatcher(fakeStore) {
|
class NoopDispatcher(lifecycleStore: LifecycleStore) : EventDispatcher(fakeStore, lifecycleStore) {
|
||||||
override fun dispatch(referenceId: UUID, history: List<Event>, newEvents: List<Event>) {}
|
override fun dispatch(referenceId: UUID, history: List<Event>, newEvents: List<Event>) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
val dispatcher = NoopDispatcher()
|
val dispatcher = NoopDispatcher(lifecycleStore)
|
||||||
val poller = TestablePoller(fakeStore, queue, dispatcher, scope)
|
val poller = TestablePoller(fakeStore, queue, dispatcher, scope, lifecycleStore)
|
||||||
|
|
||||||
// Sett watermark høyt (polleren setter watermark selv i ekte drift,
|
// Sett watermark høyt (polleren setter watermark selv i ekte drift,
|
||||||
// men i denne testen må vi simulere det)
|
// men i denne testen må vi simulere det)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import kotlinx.coroutines.test.TestScope
|
|||||||
import no.iktdev.eventi.events.EventDispatcher
|
import no.iktdev.eventi.events.EventDispatcher
|
||||||
import no.iktdev.eventi.events.EventPollerImplementation
|
import no.iktdev.eventi.events.EventPollerImplementation
|
||||||
import no.iktdev.eventi.events.SequenceDispatchQueue
|
import no.iktdev.eventi.events.SequenceDispatchQueue
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
import no.iktdev.eventi.stores.EventStore
|
import no.iktdev.eventi.stores.EventStore
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
import java.util.*
|
import java.util.*
|
||||||
@@ -14,8 +15,9 @@ class TestablePoller(
|
|||||||
eventStore: EventStore,
|
eventStore: EventStore,
|
||||||
dispatchQueue: SequenceDispatchQueue,
|
dispatchQueue: SequenceDispatchQueue,
|
||||||
dispatcher: EventDispatcher,
|
dispatcher: EventDispatcher,
|
||||||
val scope: TestScope
|
val scope: TestScope,
|
||||||
) : EventPollerImplementation(eventStore, dispatchQueue, dispatcher), WatermarkDebugView {
|
private val lifecycleStore: LifecycleStore
|
||||||
|
) : EventPollerImplementation(eventStore, dispatchQueue, dispatcher, lifecycleStore), WatermarkDebugView {
|
||||||
|
|
||||||
suspend fun startFor(iterations: Int) {
|
suspend fun startFor(iterations: Int) {
|
||||||
repeat(iterations) {
|
repeat(iterations) {
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package no.iktdev.eventi.lifecycle
|
||||||
|
|
||||||
|
import no.iktdev.eventi.lifecycle.*
|
||||||
|
import org.junit.jupiter.api.Assertions.assertEquals
|
||||||
|
import org.junit.jupiter.api.Assertions.assertTrue
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
import org.junit.jupiter.api.assertDoesNotThrow
|
||||||
|
import java.time.Instant
|
||||||
|
|
||||||
|
class LifecycleStoreStressTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `lifecycle store handles millions of entries without OOM or overflow`() {
|
||||||
|
val capacity = 1000
|
||||||
|
val store = LifecycleStore(capacity)
|
||||||
|
|
||||||
|
assertDoesNotThrow {
|
||||||
|
repeat(5_000_000) { i ->
|
||||||
|
store.add(
|
||||||
|
TaskPollerCycleStart(
|
||||||
|
timestamp = Instant.ofEpochMilli(i.toLong()) // garantert unik
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// sjekk hver 100k
|
||||||
|
if (i % 100_000 == 0 && i > capacity) {
|
||||||
|
val all = store.getAll()
|
||||||
|
|
||||||
|
// bufferen skal være full
|
||||||
|
assertEquals(
|
||||||
|
capacity,
|
||||||
|
all.size,
|
||||||
|
"LifecycleStore did not fill to capacity"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// sluttverifisering
|
||||||
|
val final = store.getAll()
|
||||||
|
assertEquals(capacity, final.size)
|
||||||
|
assertTrue(final.first().timestamp.toEpochMilli() > 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
package no.iktdev.eventi.lifecycle
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Assertions.assertEquals
|
||||||
|
import org.junit.jupiter.api.Assertions.assertTrue
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
import org.junit.jupiter.api.assertDoesNotThrow
|
||||||
|
import java.time.Instant
|
||||||
|
import java.util.UUID
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class LifecycleStoreTest {
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------
|
||||||
|
1. BASIC CAPACITY TEST
|
||||||
|
--------------------------------------------------------- */
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `store should never exceed capacity`() {
|
||||||
|
val capacity = 1000
|
||||||
|
val store = LifecycleStore(capacity)
|
||||||
|
|
||||||
|
repeat(10_000) { i ->
|
||||||
|
store.add(
|
||||||
|
TaskPollerCycleStart(
|
||||||
|
timestamp = Instant.ofEpochMilli(i.toLong())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val all = store.getAll()
|
||||||
|
assertEquals(capacity, all.size, "Store exceeded capacity")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------
|
||||||
|
2. STRESS TEST (5 MILLION ENTRIES)
|
||||||
|
--------------------------------------------------------- */
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `store handles millions of entries without OOM or overflow`() {
|
||||||
|
val capacity = 2000
|
||||||
|
val store = LifecycleStore(capacity)
|
||||||
|
|
||||||
|
assertDoesNotThrow {
|
||||||
|
repeat(5_000_000) { i ->
|
||||||
|
store.add(
|
||||||
|
TaskPollerCycleStart(
|
||||||
|
timestamp = Instant.ofEpochMilli(i.toLong())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val all = store.getAll()
|
||||||
|
assertEquals(capacity, all.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------
|
||||||
|
3. CONCURRENCY TEST
|
||||||
|
--------------------------------------------------------- */
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `store handles concurrent writers`() {
|
||||||
|
val capacity = 5000
|
||||||
|
val store = LifecycleStore(capacity)
|
||||||
|
|
||||||
|
val pool = Executors.newFixedThreadPool(8)
|
||||||
|
|
||||||
|
repeat(1_000_000) { i ->
|
||||||
|
pool.submit {
|
||||||
|
store.add(
|
||||||
|
TaskPollerCycleStart(
|
||||||
|
timestamp = Instant.ofEpochMilli(i.toLong())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pool.shutdown()
|
||||||
|
pool.awaitTermination(30, TimeUnit.SECONDS)
|
||||||
|
|
||||||
|
val all = store.getAll()
|
||||||
|
assertEquals(capacity, all.size, "Concurrent writes exceeded capacity")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------
|
||||||
|
4. REF FILTER TEST
|
||||||
|
--------------------------------------------------------- */
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `getForRef returns only entries for that ref`() {
|
||||||
|
val store = LifecycleStore(1000)
|
||||||
|
|
||||||
|
val refA = UUID.randomUUID()
|
||||||
|
val refB = UUID.randomUUID()
|
||||||
|
|
||||||
|
repeat(500) {
|
||||||
|
store.add(
|
||||||
|
RefDispatchCompleted(
|
||||||
|
timestamp = Instant.now(),
|
||||||
|
ref = refA
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
repeat(300) {
|
||||||
|
store.add(
|
||||||
|
RefDispatchCompleted(
|
||||||
|
timestamp = Instant.now(),
|
||||||
|
ref = refB
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val aEntries = store.getForRef(refA)
|
||||||
|
val bEntries = store.getForRef(refB)
|
||||||
|
|
||||||
|
assertTrue(aEntries.all { it is RefDispatchCompleted && it.ref == refA })
|
||||||
|
assertTrue(bEntries.all { it is RefDispatchCompleted && it.ref == refB })
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------
|
||||||
|
5. TIMELINE ORDER TEST
|
||||||
|
--------------------------------------------------------- */
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `entries maintain correct chronological order`() {
|
||||||
|
val store = LifecycleStore(1000)
|
||||||
|
|
||||||
|
repeat(1000) { i ->
|
||||||
|
store.add(
|
||||||
|
TaskPollerCycleStart(
|
||||||
|
timestamp = Instant.ofEpochMilli(i.toLong())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val all = store.getAll()
|
||||||
|
val timestamps = all.map { it.timestamp.toEpochMilli() }
|
||||||
|
|
||||||
|
assertEquals(timestamps.sorted(), timestamps, "Timeline is not ordered")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------
|
||||||
|
6. LIGHT MEMORY PRESSURE TEST
|
||||||
|
--------------------------------------------------------- */
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `store does not leak memory`() {
|
||||||
|
val capacity = 2000
|
||||||
|
val store = LifecycleStore(capacity)
|
||||||
|
|
||||||
|
val before = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
|
||||||
|
|
||||||
|
repeat(2_000_000) { i ->
|
||||||
|
store.add(
|
||||||
|
TaskPollerCycleStart(
|
||||||
|
timestamp = Instant.ofEpochMilli(i.toLong())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
System.gc()
|
||||||
|
Thread.sleep(200)
|
||||||
|
|
||||||
|
val after = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
|
||||||
|
|
||||||
|
// Memory should not grow unbounded
|
||||||
|
assertTrue(after < before * 3, "Possible memory leak detected")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import kotlinx.coroutines.test.advanceUntilIdle
|
|||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import no.iktdev.eventi.InMemoryTaskStore
|
import no.iktdev.eventi.InMemoryTaskStore
|
||||||
import no.iktdev.eventi.TestBase
|
import no.iktdev.eventi.TestBase
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
import no.iktdev.eventi.registry.EventTypeRegistry
|
import no.iktdev.eventi.registry.EventTypeRegistry
|
||||||
import no.iktdev.eventi.models.Event
|
import no.iktdev.eventi.models.Event
|
||||||
import no.iktdev.eventi.models.Progress
|
import no.iktdev.eventi.models.Progress
|
||||||
@@ -34,6 +35,7 @@ Hvis lyttere, backoff og event-produksjon fungerer som forventet
|
|||||||
Så skal polleren håndtere alle scenarier korrekt
|
Så skal polleren håndtere alle scenarier korrekt
|
||||||
""")
|
""")
|
||||||
class TaskPollerImplementationTest : TestBase() {
|
class TaskPollerImplementationTest : TestBase() {
|
||||||
|
private val lifecycleStore = LifecycleStore()
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
fun setup() {
|
fun setup() {
|
||||||
@@ -65,8 +67,9 @@ class TaskPollerImplementationTest : TestBase() {
|
|||||||
|
|
||||||
class TaskPollerImplementationTest(
|
class TaskPollerImplementationTest(
|
||||||
taskStore: TaskStore,
|
taskStore: TaskStore,
|
||||||
reporterFactory: (Task) -> TaskReporter
|
reporterFactory: (Task) -> TaskReporter,
|
||||||
) : TaskPollerImplementation(taskStore, reporterFactory) {
|
private val lifecycleStore: LifecycleStore
|
||||||
|
) : TaskPollerImplementation(taskStore, lifecycleStore, reporterFactory) {
|
||||||
fun overrideSetBackoff(duration: java.time.Duration) {
|
fun overrideSetBackoff(duration: java.time.Duration) {
|
||||||
backoff = duration
|
backoff = duration
|
||||||
}
|
}
|
||||||
@@ -116,7 +119,7 @@ class TaskPollerImplementationTest : TestBase() {
|
|||||||
EventTypeRegistry.register(EchoEvent::class.java)
|
EventTypeRegistry.register(EchoEvent::class.java)
|
||||||
|
|
||||||
val listener = EchoListener()
|
val listener = EchoListener()
|
||||||
val poller = object : TaskPollerImplementation(taskStore, reporterFactory) {}
|
val poller = object : TaskPollerImplementation(taskStore, lifecycleStore, reporterFactory) {}
|
||||||
|
|
||||||
val task = EchoTask("Hello").newReferenceId().derivedOf(object : Event() {}.apply { newReferenceId() })
|
val task = EchoTask("Hello").newReferenceId().derivedOf(object : Event() {}.apply { newReferenceId() })
|
||||||
taskStore.persist(task)
|
taskStore.persist(task)
|
||||||
@@ -144,7 +147,7 @@ class TaskPollerImplementationTest : TestBase() {
|
|||||||
EventTypeRegistry.register(EchoEvent::class.java)
|
EventTypeRegistry.register(EchoEvent::class.java)
|
||||||
|
|
||||||
val listener = EchoListener()
|
val listener = EchoListener()
|
||||||
val poller = TaskPollerImplementationTest(taskStore, reporterFactory)
|
val poller = TaskPollerImplementationTest(taskStore, reporterFactory, lifecycleStore)
|
||||||
val initialBackoff = poller.backoff
|
val initialBackoff = poller.backoff
|
||||||
|
|
||||||
poller.overrideSetBackoff(Duration.ofSeconds(16))
|
poller.overrideSetBackoff(Duration.ofSeconds(16))
|
||||||
@@ -169,7 +172,7 @@ class TaskPollerImplementationTest : TestBase() {
|
|||||||
Så skal backoff dobles
|
Så skal backoff dobles
|
||||||
""")
|
""")
|
||||||
fun pollerIncreasesBackoffWhenNoTasks() = runTest {
|
fun pollerIncreasesBackoffWhenNoTasks() = runTest {
|
||||||
val poller = object : TaskPollerImplementation(taskStore, reporterFactory) {}
|
val poller = object : TaskPollerImplementation(taskStore, lifecycleStore, reporterFactory) {}
|
||||||
val initialBackoff = poller.backoff
|
val initialBackoff = poller.backoff
|
||||||
|
|
||||||
poller.pollOnce()
|
poller.pollOnce()
|
||||||
@@ -184,7 +187,7 @@ class TaskPollerImplementationTest : TestBase() {
|
|||||||
Så skal backoff dobles
|
Så skal backoff dobles
|
||||||
""")
|
""")
|
||||||
fun pollerIncreasesBackoffWhenNoListenerSupportsTask() = runTest {
|
fun pollerIncreasesBackoffWhenNoListenerSupportsTask() = runTest {
|
||||||
val poller = object : TaskPollerImplementation(taskStore, reporterFactory) {}
|
val poller = object : TaskPollerImplementation(taskStore, lifecycleStore, reporterFactory) {}
|
||||||
val initialBackoff = poller.backoff
|
val initialBackoff = poller.backoff
|
||||||
|
|
||||||
// as long as the task is not added to registry this will be unsupported
|
// as long as the task is not added to registry this will be unsupported
|
||||||
@@ -207,7 +210,7 @@ class TaskPollerImplementationTest : TestBase() {
|
|||||||
override val isBusy = true
|
override val isBusy = true
|
||||||
}
|
}
|
||||||
|
|
||||||
val poller = object : TaskPollerImplementation(taskStore, reporterFactory) {}
|
val poller = object : TaskPollerImplementation(taskStore, lifecycleStore, reporterFactory) {}
|
||||||
val initialBackoff = poller.backoff
|
val initialBackoff = poller.backoff
|
||||||
|
|
||||||
val task = EchoTask("Busy").newReferenceId()
|
val task = EchoTask("Busy").newReferenceId()
|
||||||
@@ -234,7 +237,7 @@ class TaskPollerImplementationTest : TestBase() {
|
|||||||
override fun claim(taskId: UUID, workerId: String) = false
|
override fun claim(taskId: UUID, workerId: String) = false
|
||||||
}
|
}
|
||||||
|
|
||||||
val poller = object : TaskPollerImplementation(failingStore, reporterFactory) {}
|
val poller = object : TaskPollerImplementation(failingStore, lifecycleStore, reporterFactory) {}
|
||||||
val initialBackoff = poller.backoff
|
val initialBackoff = poller.backoff
|
||||||
|
|
||||||
failingStore.persist(task)
|
failingStore.persist(task)
|
||||||
|
|||||||
@@ -4,11 +4,14 @@ import kotlinx.coroutines.CoroutineDispatcher
|
|||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import no.iktdev.eventi.events.SequenceDispatchQueue
|
import no.iktdev.eventi.events.SequenceDispatchQueue
|
||||||
|
import no.iktdev.eventi.lifecycle.LifecycleStore
|
||||||
|
|
||||||
class TestSequenceDispatchQueue(
|
class TestSequenceDispatchQueue(
|
||||||
maxConcurrency: Int,
|
maxConcurrency: Int,
|
||||||
dispatcher: CoroutineDispatcher
|
dispatcher: CoroutineDispatcher,
|
||||||
|
lifecycleStore: LifecycleStore
|
||||||
) : SequenceDispatchQueue(
|
) : SequenceDispatchQueue(
|
||||||
maxConcurrency,
|
maxConcurrency,
|
||||||
CoroutineScope(dispatcher + SupervisorJob())
|
CoroutineScope(dispatcher + SupervisorJob()),
|
||||||
|
lifecycleStore
|
||||||
)
|
)
|
||||||
Reference in new issue
Block a user