Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions node/src/main/scala/com/wavesplatform/metrics/package.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.wavesplatform

import java.util.concurrent.TimeUnit
import kamon.Kamon
import kamon.metric.Timer

package object metrics {
Expand All @@ -13,11 +15,16 @@ package object metrics {
def measureOptional[T](f: => Option[T]): Option[T] =
measureWithFilter(f)(_.isDefined)

private def measureWithFilter[T](f: => T)(filter: T => Boolean): T = {
val startedTimer = timer.start()
val result = f
if (filter(result)) startedTimer.stop()
result
}
private def measureWithFilter[T](f: => T)(filter: T => Boolean): T =
if (!Kamon.enabled()) f
else {
val start = System.nanoTime()
val result = f
val elapsed = System.nanoTime() - start
if (elapsed > 0 && filter(result)) {
timer.record(elapsed, TimeUnit.NANOSECONDS)
}
result
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.wavesplatform.metrics

import kamon.Kamon
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

class TimerExtSpec extends AnyFreeSpec with Matchers {
"TimerExt" - {
"measure executes function and returns result" in {
val timer = Kamon.timer("test.timer.measure").withoutTags()
val result = timer.measure {
42
}
result shouldBe 42
}

"measureSuccessful records only on Right results" in {
val timer = Kamon.timer("test.timer.successful").withoutTags()
val rightResult = timer.measureSuccessful {
Right("ok")
}
rightResult shouldBe Right("ok")

val leftResult = timer.measureSuccessful {
Left("error")
}
leftResult shouldBe Left("error")
}

"measureOptional records only on Some results" in {
val timer = Kamon.timer("test.timer.optional").withoutTags()
val someResult = timer.measureOptional {
Some("value")
}
someResult shouldBe Some("value")

val noneResult = timer.measureOptional {
None
}
noneResult shouldBe None
}
}
}