Skip to content

Commit 5f230dd

Browse files
authored
fix: fixing event latency recording (#123)
1 parent 5c761f2 commit 5f230dd

1 file changed

Lines changed: 14 additions & 11 deletions

File tree

src/main/kotlin/at/ac/uibk/dps/cirrina/execution/object/StateMachine.kt

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import dagger.assisted.AssistedFactory
1212
import dagger.assisted.AssistedInject
1313
import java.util.concurrent.TimeUnit
1414
import kotlin.properties.Delegates
15+
import kotlin.time.Clock
1516
import kotlinx.coroutines.*
1617
import kotlinx.coroutines.channels.Channel
1718
import kotlinx.coroutines.channels.onFailure
@@ -155,7 +156,13 @@ internal constructor(
155156
private fun processEvent(event: Event) {
156157
if (isTerminated()) return
157158

158-
recordLatency(event)
159+
if (event.channel == EventChannel.EXTERNAL) {
160+
val now = Clock.System.now()
161+
val nowNanos = (now.epochSeconds * 1_000_000_000L) + now.nanosecondsOfSecond
162+
val deltaNanos = (nowNanos - event.emittedTime).coerceAtLeast(0L)
163+
164+
eventTimer.update(deltaNanos, TimeUnit.NANOSECONDS)
165+
}
159166

160167
handleEvent(event)?.let { transition -> step(transition) }
161168

@@ -284,19 +291,15 @@ internal constructor(
284291

285292
private fun stopTimeout(name: String) = timeoutActionManager.stop(name)
286293

287-
private fun recordLatency(event: Event) {
288-
if (event.source == name) return
289-
if (event.target != name) return
290-
if (event.emittedTime == 0L) return
291-
292-
eventTimer.update((System.currentTimeMillis() - event.emittedTime), TimeUnit.MILLISECONDS)
293-
}
294-
295294
override fun toString() = "StateMachine(name='$name')"
296295

297296
inner class StateMachineEventHandler(val eventHandler: EventHandler) {
298-
fun emit(event: Event) =
299-
eventHandler.emit(event.copy(source = name, emittedTime = System.currentTimeMillis()))
297+
fun emit(event: Event) {
298+
val now = Clock.System.now()
299+
val epochNanos = (now.epochSeconds * 1_000_000_000L) + now.nanosecondsOfSecond
300+
301+
eventHandler.emit(event.copy(source = name, emittedTime = epochNanos))
302+
}
300303

301304
fun propagateToParent(event: Event) {
302305
parent?.stateMachineEventHandler?.propagateToParent(event) ?: pushEvent(event)

0 commit comments

Comments
 (0)