scala.concurrent.duration.DurationLong Scala Examples

The following examples show how to use scala.concurrent.duration.DurationLong. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: NotificationChannel.scala    From eventuate   with Apache License 2.0 5 votes vote down vote up
package com.rbmhtechnology.eventuate.log

import java.util.concurrent.TimeUnit

import akka.actor.Actor
import akka.actor.ActorRef
import com.rbmhtechnology.eventuate._
import com.rbmhtechnology.eventuate.ReplicationProtocol._
import com.typesafe.config.Config

import scala.collection.immutable.Seq
import scala.concurrent.duration.DurationLong
import scala.concurrent.duration.FiniteDuration

class NotificationChannelSettings(config: Config) {
  val registrationExpirationDuration: FiniteDuration =
    config.getDuration("eventuate.log.replication.retry-delay", TimeUnit.MILLISECONDS).millis
}

object NotificationChannel {
  case class Updated(events: Seq[DurableEvent])

  private case class Registration(replicator: ActorRef, currentTargetVersionVector: VectorTime, filter: ReplicationFilter, registrationTime: Long)

  private object Registration {
    def apply(read: ReplicationRead): Registration =
      new Registration(read.replicator, read.currentTargetVersionVector, read.filter, System.nanoTime())
  }
}


class NotificationChannel(logId: String) extends Actor {
  import NotificationChannel._

  private val settings = new NotificationChannelSettings(context.system.settings.config)

  // targetLogId -> subscription
  private var registry: Map[String, Registration] = Map.empty

  // targetLogIds for which a read operation is in progress
  private var reading: Set[String] = Set.empty

  def receive = {
    case Updated(events) =>
      val currentTime = System.nanoTime()
      registry.foreach {
        case (targetLogId, reg) =>
          if (!reading.contains(targetLogId)
            && events.exists(_.replicable(reg.currentTargetVersionVector, reg.filter))
            && currentTime - reg.registrationTime <= settings.registrationExpirationDuration.toNanos)
            reg.replicator ! ReplicationDue
      }
    case r: ReplicationRead =>
      registry += (r.targetLogId -> Registration(r))
      reading += r.targetLogId
    case r: ReplicationReadSuccess =>
      reading -= r.targetLogId
    case r: ReplicationReadFailure =>
      reading -= r.targetLogId
    case w: ReplicationWrite =>
      for {
        id <- w.sourceLogIds
        rr <- registry.get(id)
      } registry += (id -> rr.copy(currentTargetVersionVector = w.metadata(id).currentVersionVector))
  }
} 
Example 2
Source File: ProgressActor.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie
package balancer

import akka.NotUsed
import akka.actor.{Actor, ActorRef}
import akka.stream.scaladsl.Source
import com.olegych.scastie.api._
import com.olegych.scastie.util.GraphStageForwarder

import scala.collection.mutable.{Map => MMap, Queue => MQueue}
import scala.concurrent.duration.DurationLong

case class SubscribeProgress(snippetId: SnippetId)
private case class Cleanup(snippetId: SnippetId)

class ProgressActor extends Actor {
  type ProgressSource = Source[SnippetProgress, NotUsed]

  private val subscribers = MMap.empty[SnippetId, (ProgressSource, Option[ActorRef])]

  private val queuedMessages = MMap.empty[SnippetId, MQueue[SnippetProgress]]

  override def receive: Receive = {
    case SubscribeProgress(snippetId) =>
      val (source, _) = getOrCreateNewSubscriberInfo(snippetId, self)
      sender ! source

    case snippetProgress: SnippetProgress =>
      snippetProgress.snippetId.foreach { snippetId =>
        getOrCreateNewSubscriberInfo(snippetId, self)
        queuedMessages.getOrElseUpdate(snippetId, MQueue()).enqueue(snippetProgress)
        sendQueuedMessages(snippetId, self)
      }

    case (snippedId: SnippetId, graphStageForwarderActor: ActorRef) =>
      subscribers.get(snippedId).foreach(s => subscribers.update(snippedId, s.copy(_2 = Some(graphStageForwarderActor))))
      sendQueuedMessages(snippedId, self)

    case Cleanup(snippetId) =>
      subscribers.remove(snippetId)
      queuedMessages.remove(snippetId)
  }

  private def getOrCreateNewSubscriberInfo(snippetId: SnippetId, self: ActorRef): (ProgressSource, Option[ActorRef]) = {
    subscribers.getOrElseUpdate(
      snippetId,
      Source.fromGraph(new GraphStageForwarder("outlet-graph-" + snippetId, self, snippetId)) -> None
    )
  }

  private def sendQueuedMessages(snippetId: SnippetId, self: ActorRef): Unit =
    for {
      messageQueue <- queuedMessages.get(snippetId).toSeq
      (_, Some(graphStageForwarderActor)) <- subscribers.get(snippetId).toSeq
      message <- messageQueue.dequeueAll(_ => true)
    } yield {
      graphStageForwarderActor ! message
      if (message.isDone) context.system.scheduler.scheduleOnce(3.seconds, self, Cleanup(snippetId))(context.dispatcher)
    }
} 
Example 3
Source File: ABTestingSimulation.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package experiments

import java.util.concurrent.atomic.AtomicLong

import io.gatling.core.Predef._
import io.gatling.http.Predef._

import scala.concurrent.duration.DurationLong

class ABTestingSimulation extends Simulation {
  val sentHeaders = Map(HttpHeaderNames.ContentType -> "application/json")

  val userEmailFeeder = Iterator.from(0).map(i => Map("email" -> s"[email protected]"))

  val counter = new AtomicLong(0)
  def nextMail() = {
    val count = counter.incrementAndGet()
    s"[email protected]"
  }

  private val headers = Map(
    "Izanami-Client-Id"     -> "xxxx",
    "Izanami-Client-Secret" -> "xxxx"
  )

  private val experimentId = "project:experiments:name"

  private val host = "http://localhost:9000"

  val httpConf = http
    .baseUrl(host)
    .acceptHeader("application/json")
    .headers(headers)
    .acceptEncodingHeader("gzip, deflate")
    .acceptLanguageHeader("en-US,en;q=0.5")

  val scn = scenario("A/B test")
    .repeat(100, "n") {
      randomSwitch(
        50d ->
        exec(
          http("Displayed A request ")
            .post(s"/api/experiments/$experimentId/displayed?id=A&clientId=user-$${n}@maif.fr")
            .body(StringBody("{}"))
            .headers(sentHeaders)
        ).pause(1.second)
          .randomSwitch(
            30d -> exec(
              http("Won A request")
                .post(s"/api/experiments/$experimentId/won?id=A&clientId=user-$${n}@maif.fr")
                .body(StringBody("{}"))
                .headers(sentHeaders)
            ).pause(1.second)
          ),
        30d ->
        exec(
          http("Displayed B request")
            .post(s"/api/experiments/$experimentId/displayed?id=B&clientId=user-$${n}@maif.fr")
            .body(StringBody("{}"))
            .headers(sentHeaders)
        ).pause(1.second)
          .randomSwitch(
            70d -> exec(
              http("Won B request")
                .post(s"/api/experiments/$experimentId/won?id=B&clientId=user-$${n}@gmail.com")
                .body(StringBody("{}"))
                .headers(sentHeaders)
            ).pause(1.second)
          ),
        20d ->
        exec(
          http("Displayed C request")
            .post(s"/api/experiments/$experimentId/displayed?id=C&clientId=user-$${n}@maif.fr")
            .body(StringBody("{}"))
            .headers(sentHeaders)
        ).pause(1.second)
          .randomSwitch(
            70d -> exec(
              http("Won C request")
                .post(s"/api/experiments/$experimentId/won?id=C&clientId=user-$${n}@gmail.com")
                .body(StringBody("{}"))
                .headers(sentHeaders)
            ).pause(1.second)
          )
      )
    }

  setUp(scn.inject(atOnceUsers(2)).protocols(httpConf))

} 
Example 4
Source File: ExperimentVariantEventMongoServiceTest.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package specs.mongo.abtesting

import domains.abtesting.events.impl.ExperimentVariantEventMongoService
import domains.abtesting.AbstractExperimentServiceTest
import domains.abtesting.events.ExperimentVariantEventService
import env.{DbDomainConfig, DbDomainConfigDetails, Mongo}
import org.scalactic.source.Position
import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll}
import play.api.Configuration
import play.modules.reactivemongo.DefaultReactiveMongoApi
import reactivemongo.api.MongoConnection
import test.FakeApplicationLifecycle

import scala.concurrent.duration.DurationLong
import scala.concurrent.Await
import scala.util.Random

class ExperimentVariantEventMongoServiceTest
    extends AbstractExperimentServiceTest("Mongo")
    with BeforeAndAfter
    with BeforeAndAfterAll {

  import zio.interop.catz._

  val mongoApi = new DefaultReactiveMongoApi(
    Await.result(MongoConnection.fromString("mongodb://localhost:27017"), 5.seconds),
    s"dbtest-${Random.nextInt(50)}",
    false,
    Configuration.empty,
    new FakeApplicationLifecycle()
  )

  override def dataStore(name: String): ExperimentVariantEventService.Service = ExperimentVariantEventMongoService(
    DbDomainConfig(Mongo, DbDomainConfigDetails(name, None), None),
    mongoApi
  )

  override protected def before(fun: => Any)(implicit pos: Position): Unit = {
    super.before(fun)
    deleteAllData
  }

  override protected def afterAll(): Unit = {
    super.afterAll()

    deleteAllData
  }

  private def deleteAllData =
    Await.result(mongoApi.database.flatMap { _.drop() }, 30.seconds)

} 
Example 5
Source File: MongoJsonDataStoreTest.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package specs.mongo.store

import env.{DbDomainConfig, DbDomainConfigDetails, Mongo}
import org.scalactic.source.Position
import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll}
import play.api.Configuration
import play.modules.reactivemongo.DefaultReactiveMongoApi
import reactivemongo.api.MongoConnection
import store.AbstractJsonDataStoreTest
import test.FakeApplicationLifecycle

import scala.concurrent.duration.DurationLong
import scala.concurrent.Await
import scala.util.Random
import store.mongo.MongoJsonDataStore

class MongoJsonDataStoreTest extends AbstractJsonDataStoreTest("Mongo") with BeforeAndAfter with BeforeAndAfterAll {

  val mongoApi = new DefaultReactiveMongoApi(
    Await.result(MongoConnection.fromString("mongodb://localhost:27017"), 5.seconds),
    s"dbtest-${Random.nextInt(50)}",
    false,
    Configuration.empty,
    new FakeApplicationLifecycle()
  )

  override def dataStore(name: String): MongoJsonDataStore = MongoJsonDataStore(
    mongoApi,
    DbDomainConfig(Mongo, DbDomainConfigDetails(name, None), None)
  )

  override protected def before(fun: => Any)(implicit pos: Position): Unit = {
    super.before(fun)
    deleteAllData
  }

  override protected def afterAll(): Unit = {
    super.afterAll()

    deleteAllData
  }

  private def deleteAllData =
    Await.result(mongoApi.database.flatMap { _.drop() }, 30.seconds)

}