iniyanp
3/28/2017 - 9:41 PM

How to generalize timer?

How to generalize timer?


/**
 * Creates separate success and failure timers for Tasks
 *
 * @param label a label describing the operation that the task performs.
 * For example a label of `"cassandra/recordings/getOne"` will result in
 * timers named `"dvrsvc/cassandra/recordings/getOne/success"` and
 * `"dvrsvc/cassandra/recordings/getOne/failure"`.
 */

final class TaskMetrics(val label: String) {
  import TaskMetrics.currentNanoTime

  private val success = lapTimer(s"dvrsvc/$label/success")
  private val failure = lapTimer(s"dvrsvc/$label/failure")
  /** Captures the elapsed execution time for the provided `Task` */
  def apply[A](task: Task[A]): Task[A] = for {
    start <- currentNanoTime
    op    <- task.attempt
    stop  <- currentNanoTime
    _     <- delay(op.fold(_ => failure, _ => success).recordNanos(stop - start))
    res   <- Task.fromDisjunction(op)
  } yield res
}

object TaskMetrics {
  private val currentNanoTime: Task[Long] = delay(System.nanoTime())
}