scala.concurrent.TimeoutException Scala Examples
The following examples show how to use scala.concurrent.TimeoutException.
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: KustoTestUtils.scala From azure-kusto-spark with Apache License 2.0 | 5 votes |
package com.microsoft.kusto.spark import java.security.InvalidParameterException import com.microsoft.azure.kusto.data.Client import com.microsoft.kusto.spark.utils.CslCommandsGenerator._ import com.microsoft.kusto.spark.utils.{KustoDataSourceUtils => KDSU} import scala.collection.JavaConverters._ import scala.concurrent.TimeoutException private [kusto] object KustoTestUtils { private val myName = this.getClass.getSimpleName private val loggingLevel: Option[String] = Option(System.getProperty("logLevel")) if (loggingLevel.isDefined) KDSU.setLoggingLevel(loggingLevel.get) def validateResultsAndCleanup( kustoAdminClient: Client, table: String, database: String, expectedNumberOfRows: Int, // Set a negative value to skip validation timeoutMs: Int, cleanupAllTables: Boolean = true, tableCleanupPrefix: String = "") : Unit = { var rowCount = 0 var timeElapsedMs = 0 val sleepPeriodMs = timeoutMs / 10 val query = s"$table | count" while (rowCount < expectedNumberOfRows && timeElapsedMs < timeoutMs) { val result = kustoAdminClient.execute(database, query).getPrimaryResults result.next() rowCount = result.getInt(0) Thread.sleep(sleepPeriodMs) timeElapsedMs += sleepPeriodMs } if (cleanupAllTables) { if (tableCleanupPrefix.isEmpty) throw new InvalidParameterException("Tables cleanup prefix must be set if 'cleanupAllTables' is 'true'") tryDropAllTablesByPrefix(kustoAdminClient, database, tableCleanupPrefix) } else { kustoAdminClient.execute(database, generateDropTablesCommand(table)) } if (expectedNumberOfRows >= 0) { if (rowCount == expectedNumberOfRows) { KDSU.logInfo(myName, s"KustoSinkStreamingE2E: Ingestion results validated for table '$table'") } else { throw new TimeoutException(s"KustoSinkStreamingE2E: Timed out waiting for ingest. $rowCount rows found in database '$database' table '$table', expected: $expectedNumberOfRows. Elapsed time:$timeElapsedMs") } } } def tryDropAllTablesByPrefix(kustoAdminClient: Client, database: String, tablePrefix: String): Unit = { try{ val res = kustoAdminClient.execute(database, generateFindCurrentTempTablesCommand(tablePrefix)) val tablesToCleanup = res.getPrimaryResults.getData.asScala.map(row => row.get(0)) if (tablesToCleanup.nonEmpty) { kustoAdminClient.execute(database, generateDropTablesCommand(tablesToCleanup.mkString(","))) } }catch { case exception: Exception => KDSU.logWarn(myName, s"Failed to delete temporary tables with exception: ${exception.getMessage}") } } }
Example 2
Source File: GitFetcher.scala From sbt-git-versioning with MIT License | 5 votes |
package com.rallyhealth.sbt.versioning import sbt.util.Logger import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.Duration import scala.concurrent.{Await, Future, TimeoutException} import scala.util.control.NonFatal import scala.sys.process.Process def fetchRemotes(remotes: Seq[String], timeout: Duration)(implicit logger: Logger): Seq[FetchResult] = { val outputLogger = new BufferingProcessLogger val processResult = Process("git remote") ! outputLogger processResult match { case 0 => logger.debug("Fetching remote sources...") val remotes = outputLogger.stdout val tagsToFetch = remotes.filter(remotes.contains) if (tagsToFetch.nonEmpty) { logger.info("Fetching tags from: " + tagsToFetch.mkString(", ")) tagsToFetch.flatMap(remote => fetchTagsFromRemote(remote, timeout)) } else { logger.debug("No tags to fetch") Seq.empty[FetchResult] } case exitCode => logger.error(s"Fetching remotes failed enumerating remotes [git exitCode=$exitCode]") Seq.empty[FetchResult] } } private def fetchTagsFromRemote(remote: String, timeout: Duration)(implicit logger: Logger): Seq[FetchResult] = { val outputLogger = new BufferingProcessLogger val process = Process(s"git fetch $remote --tags").run(outputLogger) val resultFuture = Future { if (process.exitValue() == 0) { outputLogger.stderr.filter(_.contains("[new tag]")).flatMap { case tagResultRegex(tag) => logger.debug(s"Fetched from remote=$remote tag=$tag") Some(FetchResult(remote, tag)) case line => logger.warn(s"Unable to parse git result=$line, skipping") None } } else { logger.error(s"Fetching remote=$remote failed [git exitCode=${process.exitValue()}]") Seq.empty[FetchResult] } } try { val result = Await.result(resultFuture, timeout) logger.debug(s"Successfully fetched $remote") result } catch { case _: TimeoutException => process.destroy() logger.error(s"Fetching remote=$remote timed out [git exitCode=${process.exitValue()}]") Seq.empty case NonFatal(exc) => logger.error(s"Fetching remote=$remote failed [git exitCode=${process.exitValue()}]") logger.trace(exc) Seq.empty } } }
Example 3
Source File: PromiseMapper.scala From laserdisc with MIT License | 5 votes |
package laserdisc package fs2 import cats.effect.concurrent.Deferred import cats.effect.syntax.concurrent._ import cats.effect.{Concurrent, Timer} import cats.syntax.flatMap._ import cats.syntax.monadError._ import shapeless.Poly1 import scala.concurrent.TimeoutException object PromiseMapper extends Poly1 { private[this] final def mapper[F[_]: Concurrent: Timer, A](protocol: Protocol.Aux[A]): Env[F] => F[Maybe[A]] = { case (queue, duration) => Deferred[F, Maybe[A]] >>= { promise => queue.enqueue1(Request(protocol, promise.complete)) >> { promise.get .timeout(duration) .adaptError { case _: TimeoutException => RequestTimedOut(protocol) } } } } implicit def mkOne[F[_]: Timer: Concurrent, A]: Case.Aux[Protocol.Aux[A], Env[F] => F[Maybe[A]]] = at[Protocol.Aux[A]](mapper(_)) }
Example 4
Source File: ProcessMutantRunner.scala From stryker4s with Apache License 2.0 | 5 votes |
package stryker4s.command.runner import java.nio.file.Path import better.files.File import stryker4s.config.Config import stryker4s.model._ import stryker4s.mutants.findmutants.SourceCollector import stryker4s.report.Reporter import stryker4s.run.MutantRunner import stryker4s.run.process.{Command, ProcessRunner} import scala.concurrent.TimeoutException import scala.util.{Failure, Success} class ProcessMutantRunner( command: Command, processRunner: ProcessRunner, sourceCollector: SourceCollector, reporter: Reporter )(implicit config: Config) extends MutantRunner(sourceCollector, reporter) { type Context = CommandRunnerContext override def runMutant(mutant: Mutant, context: Context): Path => MutantRunResult = { val id = mutant.id processRunner(command, context.tmpDir, ("ACTIVE_MUTATION", id.toString)) match { case Success(0) => Survived(mutant, _) case Success(exitCode) if exitCode != 0 => Killed(mutant, _) case Failure(_: TimeoutException) => TimedOut(mutant, _) case _ => Error(mutant, _) } } override def runInitialTest(context: Context): Boolean = { processRunner(command, context.tmpDir, ("ACTIVE_MUTATION", "None")) match { case Success(0) => true case Success(exitCode) if exitCode != 0 => false case Failure(_: TimeoutException) => false } } override def initializeTestContext(tmpDir: File): Context = CommandRunnerContext(tmpDir) }
Example 5
Source File: PollingUtils.scala From sttp with Apache License 2.0 | 5 votes |
import java.io.FileNotFoundException import java.net.{ConnectException, URL} import scala.concurrent.TimeoutException import scala.concurrent.duration._ object PollingUtils { def waitUntilServerAvailable(url: URL): Unit = { val connected = poll(5.seconds, 250.milliseconds)({ urlConnectionAvailable(url) }) if (!connected) { throw new TimeoutException(s"Failed to connect to $url") } } def poll(timeout: FiniteDuration, interval: FiniteDuration)(poll: => Boolean): Boolean = { val start = System.nanoTime() def go(): Boolean = { if (poll) { true } else if ((System.nanoTime() - start) > timeout.toNanos) { false } else { Thread.sleep(interval.toMillis) go() } } go() } def urlConnectionAvailable(url: URL): Boolean = { try { url.openConnection() .getInputStream .close() true } catch { case _: ConnectException => false case _: FileNotFoundException => true // on 404 } } }
Example 6
Source File: GenericAPIHandlers.scala From marvin-engine-executor with Apache License 2.0 | 5 votes |
package org.marvin.executor.api import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.{ExceptionHandler, MissingQueryParamRejection, RejectionHandler} import grizzled.slf4j.Logger import org.marvin.exception.MarvinEExecutorException import spray.json.DefaultJsonProtocol._ import scala.concurrent.TimeoutException case class ErrorResponse(errorMessage: String) object GenericAPIHandlers { lazy val logger = Logger[this.type] implicit val errorFormatter = jsonFormat1(ErrorResponse) val exceptions: ExceptionHandler = ExceptionHandler { case ex: IllegalArgumentException => { logger.debug("Endpoint thrown illegal argument exception.", ex) val error = ErrorResponse(errorMessage = ex.getMessage) complete(HttpResponse(StatusCodes.BadRequest, entity = toResponseEntityJson(error))) } case ex: TimeoutException => { logger.debug("Endpoint thrown timeout exception", ex) val error = ErrorResponse(errorMessage = "The engine was not able to provide a response within the specified timeout.") complete(HttpResponse(StatusCodes.InternalServerError, entity = toResponseEntityJson(error))) } case ex: MarvinEExecutorException => { logger.debug("Endpoint thrown Marvin EExecutor Exception", ex) val error = ErrorResponse(errorMessage = ex.getMessage()) complete(HttpResponse(StatusCodes.ServiceUnavailable, entity = toResponseEntityJson(error))) } case _ => { val error = ErrorResponse(errorMessage = "Unexpected error.") complete(HttpResponse(StatusCodes.InternalServerError, entity = toResponseEntityJson(error))) } } val rejections: RejectionHandler = RejectionHandler.newBuilder().handle { case rj: MissingQueryParamRejection => { logger.debug("Missing query parameters.") val error = ErrorResponse(errorMessage = s"Missing query parameter. [${rj.parameterName}]") complete(HttpResponse(StatusCodes.BadRequest, entity = toResponseEntityJson(error))) } }.result() def toResponseEntityJson(error: ErrorResponse): ResponseEntity = { HttpEntity(ContentTypes.`application/json`, errorFormatter.write(error).toString()) } }
Example 7
Source File: TimedOut.scala From ticket-booking-aecor with Apache License 2.0 | 5 votes |
package ru.pavkin.booking.common.effect import cats.effect.{Concurrent, Timer} import cats.~> import scala.concurrent.TimeoutException import scala.concurrent.duration.FiniteDuration object TimedOut { def apply[F[_]](timeout: FiniteDuration)(implicit timer: Timer[F], F: Concurrent[F]): F ~> F = new (F ~> F) { def apply[A](fa: F[A]): F[A] = Concurrent.timeoutTo( fa, timeout, F.raiseError(new TimeoutException(s"Call timed out after $timeout")) ) } }
Example 8
Source File: ExecutorProxy.scala From ncdbg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.programmaticallyspeaking.ncd.infra import java.lang.reflect.{InvocationHandler, InvocationTargetException, Method} import java.util.concurrent.Executor import java.util.concurrent.atomic.AtomicInteger import org.slf4s.Logging import scala.concurrent.duration._ import scala.concurrent.{Await, Future, Promise, TimeoutException} import scala.reflect.ClassTag import scala.util.{Failure, Success, Try} class ExecutorProxy(executor: Executor) { import scala.collection.JavaConverters._ def createFor[A <: AnyRef : ClassTag](instance: A): A = { val clazz = implicitly[ClassTag[A]].runtimeClass java.lang.reflect.Proxy.newProxyInstance(clazz.getClassLoader, Array(clazz), new Handler(instance)).asInstanceOf[A] } class Handler(instance: AnyRef) extends InvocationHandler with Logging { import scala.concurrent.ExecutionContext.Implicits._ private val className = instance.getClass.getName private val idGen = new AtomicInteger(0) private var awaitingCalls = Map[Int, String]() override def invoke(proxy: scala.Any, method: Method, args: Array[AnyRef]): AnyRef = { val resultPromise = Promise[AnyRef]() val before = System.nanoTime() val id = idGen.getAndIncrement() val argss = Option(args).getOrElse(Array.empty) val desc = s"$method(${argss.mkString(", ")})[$id]" log.trace(s"Waiting to execute: $desc") // Snapshot of waiting calls prior to submitting to the executor val waitingCallsAtEntry = awaitingCalls executor.execute(() => { log.trace(s"Execute: $id") Try(method.invoke(instance, args: _*)) match { case Success(f: Future[_]) => resultPromise.completeWith(f.asInstanceOf[Future[AnyRef]]) case Success(result) => resultPromise.success(result) case Failure(t: InvocationTargetException) => resultPromise.failure(t.getCause) case Failure(t) => resultPromise.failure(t) } }) resultPromise.future.onComplete { _ => val methodName = method.getName val millis = (System.nanoTime() - before).nanos.toMillis log.trace(s"Elapsed time for $className.$methodName = $millis ms") } if (classOf[Future[_]].isAssignableFrom(method.getReturnType)) resultPromise.future else { // Update with this call awaitingCalls += (id -> desc) //TODO: Configurable timeout try Await.result(resultPromise.future, 30.seconds) catch { case _: TimeoutException => val other = waitingCallsAtEntry.values val sb = new StringBuilder(s"Timed out waiting for '$desc' to complete. Calls at entry: ${other.mkString("'", "', '", "'")}. Stack:\n") appendStackTraces(sb) log.debug(sb.toString()) throw new TimeoutException(s"Timed out waiting for '$desc' to complete.") } finally { // Done with this call awaitingCalls -= id log.trace(s"Done: $id") } } } private def appendStackTraces(sb: StringBuilder): Unit = { Thread.getAllStackTraces.asScala.foreach { tup => sb.append("\n> THREAD ").append(tup._1.getName).append("\n") tup._2.foreach(ste => sb.append(" ").append(ste).append("\n")) } } } }
Example 9
Source File: TimeoutScheduler.scala From subsearch with GNU General Public License v2.0 | 5 votes |
package com.gilazaria.subsearch.utils import java.util.concurrent.TimeUnit import org.jboss.netty.util.{Timeout, TimerTask, HashedWheelTimer} import scala.concurrent.{TimeoutException, Promise, Future} import scala.concurrent.duration.Duration object TimeoutScheduler { val timer = new HashedWheelTimer(10, TimeUnit.MILLISECONDS) def scheduleTimeout(promise:Promise[_], after:Duration) = { timer.newTimeout(new TimerTask { def run(timeout:Timeout){ promise.failure(new TimeoutException("Operation timed out after " + after.toMillis + " millis")) } }, after.toNanos, TimeUnit.NANOSECONDS) } } object TimeoutFuture { implicit class FutureWithTimeout[T](f: Future[T]) { import scala.concurrent.ExecutionContext def withTimeout(after: Duration)(implicit ec: ExecutionContext) = { val prom = Promise[T]() val timeout = TimeoutScheduler.scheduleTimeout(prom, after) val combinedFut = Future.firstCompletedOf(List(f, prom.future)) f onComplete { case result => timeout.cancel() } combinedFut } } }
Example 10
Source File: ClusterBootstrap.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.management.cluster.bootstrap import java.util.concurrent.atomic.AtomicReference import akka.AkkaVersion import scala.concurrent.{ Future, Promise, TimeoutException } import scala.concurrent.duration._ import akka.actor.ActorSystem import akka.actor.ClassicActorSystemProvider import akka.actor.ExtendedActorSystem import akka.actor.Extension import akka.actor.ExtensionId import akka.actor.ExtensionIdProvider import akka.annotation.InternalApi import akka.cluster.Cluster import akka.discovery.{ Discovery, ServiceDiscovery } import akka.event.Logging import akka.http.scaladsl.model.Uri import akka.http.scaladsl.server.Route import akka.management.cluster.bootstrap.contactpoint.HttpClusterBootstrapRoutes import akka.management.cluster.bootstrap.internal.BootstrapCoordinator import akka.management.scaladsl.ManagementRouteProviderSettings import akka.management.scaladsl.ManagementRouteProvider final class ClusterBootstrap(implicit system: ExtendedActorSystem) extends Extension with ManagementRouteProvider { import ClusterBootstrap.Internal._ import system.dispatcher private val log = Logging(system, classOf[ClusterBootstrap]) private final val bootstrapStep = new AtomicReference[BootstrapStep](NotRunning) AkkaVersion.require("cluster-bootstrap", "2.5.27") val settings: ClusterBootstrapSettings = ClusterBootstrapSettings(system.settings.config, log) // used for initial discovery of contact points lazy val discovery: ServiceDiscovery = settings.contactPointDiscovery.discoveryMethod match { case "akka.discovery" => val discovery = Discovery(system).discovery log.info("Bootstrap using default `akka.discovery` method: {}", Logging.simpleName(discovery)) discovery case otherDiscoveryMechanism => log.info("Bootstrap using `akka.discovery` method: {}", otherDiscoveryMechanism) Discovery(system).loadServiceDiscovery(otherDiscoveryMechanism) } private val joinDecider: JoinDecider = { system.dynamicAccess .createInstanceFor[JoinDecider]( settings.joinDecider.implClass, List((classOf[ActorSystem], system), (classOf[ClusterBootstrapSettings], settings)) ) .get } private[this] val _selfContactPointUri: Promise[Uri] = Promise() override def routes(routeProviderSettings: ManagementRouteProviderSettings): Route = { log.info(s"Using self contact point address: ${routeProviderSettings.selfBaseUri}") this.setSelfContactPoint(routeProviderSettings.selfBaseUri) new HttpClusterBootstrapRoutes(settings).routes } def start(): Unit = if (Cluster(system).settings.SeedNodes.nonEmpty) { log.warning( "Application is configured with specific `akka.cluster.seed-nodes`: {}, bailing out of the bootstrap process! " + "If you want to use the automatic bootstrap mechanism, make sure to NOT set explicit seed nodes in the configuration. " + "This node will attempt to join the configured seed nodes.", Cluster(system).settings.SeedNodes.mkString("[", ", ", "]") ) } else if (bootstrapStep.compareAndSet(NotRunning, Initializing)) { log.info("Initiating bootstrap procedure using {} method...", settings.contactPointDiscovery.discoveryMethod) ensureSelfContactPoint() val bootstrapProps = BootstrapCoordinator.props(discovery, joinDecider, settings) val bootstrap = system.systemActorOf(bootstrapProps, "bootstrapCoordinator") // Bootstrap already logs in several other execution points when it can't form a cluster, and why. selfContactPoint.foreach { uri => bootstrap ! BootstrapCoordinator.Protocol.InitiateBootstrapping(uri) } } else log.warning("Bootstrap already initiated, yet start() method was called again. Ignoring.") private[bootstrap] object Internal { sealed trait BootstrapStep case object NotRunning extends BootstrapStep case object Initializing extends BootstrapStep } }
Example 11
Source File: Utils.scala From incubator-livy with Apache License 2.0 | 5 votes |
package org.apache.livy import java.io.{Closeable, File, InputStreamReader} import java.net.URL import java.nio.charset.StandardCharsets.UTF_8 import java.security.SecureRandom import java.util.Properties import scala.annotation.tailrec import scala.collection.JavaConverters._ import scala.concurrent.TimeoutException import scala.concurrent.duration.Duration import org.apache.commons.codec.binary.Base64 object Utils { def getPropertiesFromFile(file: File): Map[String, String] = { loadProperties(file.toURI().toURL()) } def loadProperties(url: URL): Map[String, String] = { val inReader = new InputStreamReader(url.openStream(), UTF_8) try { val properties = new Properties() properties.load(inReader) properties.stringPropertyNames().asScala.map { k => (k, properties.getProperty(k).trim()) }.toMap } finally { inReader.close() } } def isProcessAlive(process: Process): Boolean = { try { process.exitValue() false } catch { case _: IllegalThreadStateException => true } } def startDaemonThread(name: String)(f: => Unit): Thread = { val thread = new Thread(name) { override def run(): Unit = f } thread.setDaemon(true) thread.start() thread } def usingResource[A <: Closeable, B](resource: A)(f: A => B): B = { try { f(resource) } finally { resource.close() } } def createSecret(secretBitLength: Int): String = { val rnd = new SecureRandom() val secretBytes = new Array[Byte](secretBitLength / java.lang.Byte.SIZE) rnd.nextBytes(secretBytes) Base64.encodeBase64String(secretBytes) } }
Example 12
Source File: process.scala From scala-steward with Apache License 2.0 | 5 votes |
package org.scalasteward.core.io import cats.effect._ import cats.implicits._ import fs2.Stream import java.io.{File, IOException, InputStream} import org.scalasteward.core.util._ import scala.collection.mutable.ListBuffer import scala.concurrent.TimeoutException import scala.concurrent.duration.FiniteDuration object process { def slurp[F[_]]( cmd: Nel[String], cwd: Option[File], extraEnv: Map[String, String], timeout: FiniteDuration, log: String => F[Unit], blocker: Blocker )(implicit contextShift: ContextShift[F], timer: Timer[F], F: Concurrent[F]): F[List[String]] = createProcess(cmd, cwd, extraEnv).flatMap { process => F.delay(new ListBuffer[String]).flatMap { buffer => val readOut = { val out = readInputStream[F](process.getInputStream, blocker) out.evalMap(line => F.delay(appendBounded(buffer, line, 4096)) >> log(line)).compile.drain } val showCmd = (extraEnv.map { case (k, v) => s"$k=$v" }.toList ++ cmd.toList).mkString_(" ") val result = readOut >> F.delay(process.waitFor()) >>= { exitValue => if (exitValue === 0) F.pure(buffer.toList) else { val msg = s"'$showCmd' exited with code $exitValue" F.raiseError[List[String]](new IOException(makeMessage(msg, buffer.toList))) } } val fallback = F.delay(process.destroyForcibly()) >> { val msg = s"'$showCmd' timed out after ${timeout.toString}" F.raiseError[List[String]](new TimeoutException(makeMessage(msg, buffer.toList))) } Concurrent.timeoutTo(result, timeout, fallback) } } private def createProcess[F[_]]( cmd: Nel[String], cwd: Option[File], extraEnv: Map[String, String] )(implicit F: Sync[F]): F[Process] = F.delay { val pb = new ProcessBuilder(cmd.toList: _*) val env = pb.environment() cwd.foreach(pb.directory) extraEnv.foreach { case (key, value) => env.put(key, value) } pb.redirectErrorStream(true) pb.start() } private def readInputStream[F[_]](is: InputStream, blocker: Blocker)(implicit F: Sync[F], cs: ContextShift[F] ): Stream[F, String] = fs2.io .readInputStream(F.pure(is), chunkSize = 4096, blocker) .through(fs2.text.utf8Decode) .through(fs2.text.lines) private def makeMessage(prefix: String, output: List[String]): String = (prefix :: output).mkString("\n") }
Example 13
Source File: FutureTimeouts.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.platform.akkastreams import akka.actor.ActorSystem import com.daml.dec.DirectExecutionContext import org.scalatest.{Assertion, AsyncWordSpec} import scala.concurrent.{Future, Promise, TimeoutException} import scala.concurrent.duration.FiniteDuration import scala.util.Try import scala.util.control.NoStackTrace trait FutureTimeouts { self: AsyncWordSpec => protected def system: ActorSystem protected def expectTimeout(f: Future[Any], duration: FiniteDuration): Future[Assertion] = { val promise: Promise[Any] = Promise[Any]() val cancellable = system.scheduler.scheduleOnce(duration, { () => promise.failure( new TimeoutException(s"Future timed out after $duration as expected.") with NoStackTrace) () })(system.dispatcher) f.onComplete((_: Try[Any]) => cancellable.cancel())(DirectExecutionContext) recoverToSucceededIf[TimeoutException]( Future.firstCompletedOf[Any](List[Future[Any]](f, promise.future))(DirectExecutionContext)) } }
Example 14
Source File: SingletonMemorySink.scala From milan with Apache License 2.0 | 5 votes |
package com.amazon.milan.application.sinks import java.time.{Duration, Instant} import java.util.concurrent.{ConcurrentHashMap, ConcurrentLinkedQueue} import java.util.function import com.amazon.milan.Id import com.amazon.milan.application.DataSink import com.amazon.milan.typeutil.TypeDescriptor import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.databind.annotation.{JsonDeserialize, JsonSerialize} import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import scala.concurrent.TimeoutException object SingletonMemorySink { private val values = new ConcurrentHashMap[String, ArrayBuffer[MemorySinkRecord[_]]]() private val nextSeqNum = new mutable.HashMap[String, Int]() private val locks = new ConcurrentHashMap[String, Object]() private def makeCreateBufferFunction[T]: java.util.function.Function[String, ArrayBuffer[MemorySinkRecord[_]]] = new function.Function[String, ArrayBuffer[MemorySinkRecord[_]]] { override def apply(t: String): ArrayBuffer[MemorySinkRecord[_]] = (new ArrayBuffer[MemorySinkRecord[T]]()).asInstanceOf[ArrayBuffer[MemorySinkRecord[_]]] } private val createLocker = new java.util.function.Function[String, Object] { override def apply(t: String): AnyRef = new Object() } @JsonIgnore def getRecordCount: Int = SingletonMemorySink.getBuffer(this.sinkId).size @JsonIgnore def getValues: List[T] = { SingletonMemorySink.getBuffer[T](this.sinkId).map(_.value).toList } @JsonIgnore def getRecords: List[MemorySinkRecord[T]] = { SingletonMemorySink.getBuffer[T](this.sinkId).toList } def waitForItems(itemCount: Int, timeout: Duration = null): Unit = { val endTime = if (timeout == null) Instant.MAX else Instant.now().plus(timeout) while (SingletonMemorySink.getBuffer(this.sinkId).size < itemCount) { if (Instant.now().isAfter(endTime)) { throw new TimeoutException() } Thread.sleep(1) } } override def equals(obj: Any): Boolean = { obj match { case o: SingletonMemorySink[_] => this.sinkId.equals(o.sinkId) case _ => false } } } class MemorySinkRecord[T](val seqNum: String, val createdTime: Instant, val value: T) extends Serializable
Example 15
Source File: ControlJVMOnlyTest.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.control import wvlet.airspec.AirSpec import scala.concurrent.TimeoutException class ControlJVMOnlyTest extends AirSpec { test("support failure rate health checker") { val cb = CircuitBreaker.withFailureRate(0.01, timeWindowMillis = 1000) val e = new TimeoutException() cb.isConnected shouldBe true // 1/1 cb.recordSuccess cb.isConnected shouldBe true // 1/2 Thread.sleep(200) cb.recordFailure(e) cb.isConnected shouldBe false // 1/3 Thread.sleep(200) cb.recordFailure(e) cb.isConnected shouldBe false // Force probing cb.halfOpen // The state should be recovered after the successful request cb.recordSuccess cb.isConnected shouldBe true } }
Example 16
Source File: Control_02_Jitter.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.examples.control import scala.concurrent.TimeoutException object Control_02_Jitter extends App { import wvlet.airframe.control.Retry Retry .withJitter(maxRetry = 3) // It will wait nextWaitMillis * rand() upon retry .retryOn { case e: TimeoutException => Retry.retryableFailure(e) } .run { // body } }
Example 17
Source File: Control_01_Retry.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.examples.control import scala.concurrent.TimeoutException object Control_01_Retry extends App { import wvlet.airframe.control.Retry Retry .withBackOff(maxRetry = 3) .retryOn { case e: TimeoutException => Retry.retryableFailure(e) } .run { // body } }
Example 18
Source File: RichFutureSuite.scala From mango with Apache License 2.0 | 5 votes |
package com.kakao.mango.concurrent import com.kakao.mango.MangoFunSuite import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ import scala.concurrent.{Future, TimeoutException} import scala.util.Try class RichFutureSuite extends MangoFunSuite { test("Blocking on Future should not time out when finished within timeout") { val duration = 3.seconds val start = System.currentTimeMillis() val tryBlock = Try { Future { Thread.sleep(1000) }.block(duration) } tryBlock.isSuccess shouldBe true } test("Should block on the Future until it finishes") { val duration = 1000.milliseconds val start = System.currentTimeMillis() futureOfThreadSleep(duration).await(duration * 2) val elapsedTime = System.currentTimeMillis() - start (elapsedTime - duration.toMillis) should be >= -(duration.toMillis / 10) } test("Awaiting on a Future shorter than it finishes should throw a TimeoutException") { val duration = 1000.milliseconds assertThrows[TimeoutException] { val start = System.currentTimeMillis() futureOfThreadSleep(duration*2).await(duration) } } def futureOfThreadSleep(d: Duration): Future[Long] = { Future { Thread.sleep(d.toMillis) d.toMillis } } }
Example 19
Source File: AskActorSpec.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.actors import akka.actor.ActorRef import akka.testkit.TestProbe import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits import com.wavesplatform.dex.time.SystemTime import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.should.Matchers import scala.concurrent.duration.DurationInt import scala.concurrent.{Await, Future, TimeoutException} class AskActorSpec extends AnyFreeSpec with Matchers with SystemTime with MatcherSpecLike with DiffMatcherWithImplicits { private val defaultTimeout = 5.seconds private val defaultResponse = "foo" "AskActor" - { "happy path" in test { (ref, future) => ref ! defaultResponse val actual = Await.result(future, defaultTimeout) actual should matchTo(defaultResponse) } "timeout" in test { (_, future) => Await.result(future.failed, defaultTimeout) shouldBe a[TimeoutException] } "unexpected response type" in test { (ref, future) => ref ! 100500 Await.result(future.failed, defaultTimeout) shouldBe a[IllegalArgumentException] } } private def test(f: (ActorRef, Future[String]) => Unit): Unit = { val (ref, future) = AskActor.mk[String](100.millis) val p = TestProbe() p.watch(ref) f(ref, future) p.expectTerminated(ref, defaultTimeout) } override protected def actorSystemName: String = "AskActorSpec" }
Example 20
Source File: AskActor.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.actors import akka.actor.{Actor, ActorRef, ActorSystem, Props, Status} import scala.concurrent.duration.FiniteDuration import scala.concurrent.{Future, Promise, TimeoutException} import scala.reflect.ClassTag class AskActor[T](p: Promise[T], timeout: FiniteDuration)(implicit ct: ClassTag[T]) extends Actor { import context.dispatcher private val timeoutCancelable = context.system.scheduler.scheduleOnce(timeout, self, AskActor.timeoutMessage) override val receive: Receive = { case x => // Fix in Scala 2.13 timeoutCancelable.cancel() context.stop(self) x match { case x: T if x.getClass == ct.runtimeClass => p.trySuccess(x) case e: Status.Failure => p.tryFailure(e.cause) case _ => p.tryFailure(new IllegalArgumentException(s"Expected ${ct.runtimeClass.getName}, but got $x")) } } } object AskActor { private val timeoutMessage = { val reason = new TimeoutException("Typed ask is timed out!") reason.setStackTrace(Array.empty) Status.Failure(reason) } def props[T](p: Promise[T], timeout: FiniteDuration)(implicit ct: ClassTag[T]) = Props(new AskActor(p, timeout)) def mk[T](timeout: FiniteDuration)(implicit ct: ClassTag[T], system: ActorSystem): (ActorRef, Future[T]) = { val p = Promise[T]() val ref = system.actorOf(props(p, timeout)) (ref, p.future) } }
Example 21
Source File: ScalaUtilIT.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.ledger.client.binding.util import java.util.concurrent.{Executors, ScheduledExecutorService} import com.daml.ledger.client.binding.util.ScalaUtil.FutureOps import org.scalatest.concurrent.AsyncTimeLimitedTests import org.scalatest.time.Span import org.scalatest.time.SpanSugar._ import org.scalatest.{AsyncWordSpec, BeforeAndAfterAll, Matchers} import scala.concurrent.{Future, Promise, TimeoutException} class ScalaUtilIT extends AsyncWordSpec with AsyncTimeLimitedTests with Matchers with BeforeAndAfterAll { implicit val scheduler: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor() override def afterAll(): Unit = { scheduler.shutdownNow() super.afterAll() } "FutureOps" can { "future with timeout" should { "fail Future with TimoutException after specified duration" in { val promise = Promise[Unit]() // never completes val future = promise.future.timeout("name", 1000.millis, 100.millis) recoverToSucceededIf[TimeoutException](future) } "be able to complete within specified duration" in { val future = Future { "result" }.timeoutWithDefaultWarn("name", 1.second) future.map(_ shouldBe "result") } } } override lazy val timeLimit: Span = 10.seconds }
Example 22
Source File: ScalaUtil.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.ledger.client.binding.util import java.util.concurrent.{ScheduledExecutorService, ScheduledFuture, TimeUnit} import com.typesafe.scalalogging.LazyLogging import scala.concurrent.duration._ import scala.concurrent.{ExecutionContext, Future, Promise, TimeoutException} object ScalaUtil { implicit class FutureOps[T](val future: Future[T]) extends LazyLogging { def timeout( name: String, failTimeout: FiniteDuration = 1.minute, warnTimeout: FiniteDuration = 30.seconds)( implicit ec: ExecutionContext, scheduler: ScheduledExecutorService): Future[T] = { val promise = Promise[T] @SuppressWarnings(Array("org.wartremover.warts.JavaSerializable")) val warningTask = schedule(warnTimeout) { logger.warn("Function {} takes more than {}", name, warnTimeout) } val errorTask = schedule(failTimeout) { val error = new TimeoutException(s"Function call $name took more than $failTimeout") promise.tryFailure(error) () } future.onComplete { outcome => warningTask.cancel(false) errorTask.cancel(false) promise.tryComplete(outcome) } promise.future } private def schedule(timeout: FiniteDuration)(f: => Unit)( implicit scheduler: ScheduledExecutorService): ScheduledFuture[_] = { val runnable = new Runnable { override def run(): Unit = f } scheduler.schedule(runnable, timeout.toMillis, TimeUnit.MILLISECONDS) } def timeoutWithDefaultWarn(name: String, failTimeout: FiniteDuration)( implicit ec: ExecutionContext, scheduler: ScheduledExecutorService): Future[T] = timeout(name, failTimeout, 10.seconds) } }
Example 23
Source File: MultiFixtureBase.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.ledger.api.testing.utils import java.util.concurrent.{Executors, ScheduledExecutorService, TimeUnit} import com.daml.dec.DirectExecutionContext import org.scalatest._ import org.scalatest.concurrent.{AsyncTimeLimitedTests, ScaledTimeSpans} import org.scalatest.exceptions.TestCanceledException import org.scalatest.time.Span import scala.collection.immutable.Iterable import scala.concurrent.duration.DurationInt import scala.concurrent.{Future, Promise, TimeoutException} import scala.util.control.{NoStackTrace, NonFatal} trait MultiFixtureBase[FixtureId, TestContext] extends Assertions with BeforeAndAfterAll with ScaledTimeSpans with AsyncTimeLimitedTests { self: AsyncTestSuite => private var es: ScheduledExecutorService = _ override protected def beforeAll(): Unit = { super.beforeAll() es = Executors.newScheduledThreadPool(1) } override protected def afterAll(): Unit = { es.shutdownNow() super.afterAll() } protected class TestFixture(val id: FixtureId, createContext: () => TestContext) { def context(): TestContext = createContext() } def timeLimit: Span = scaled(30.seconds) object TestFixture { def apply(id: FixtureId, createContext: () => TestContext): TestFixture = new TestFixture(id, createContext) def unapply(testFixture: TestFixture): Option[(FixtureId, TestContext)] = Some((testFixture.id, testFixture.context())) } protected def fixtures: Iterable[TestFixture] protected def allFixtures(runTest: TestContext => Future[Assertion]): Future[Assertion] = forAllFixtures(fixture => runTest(fixture.context)) protected def forAllFixtures(runTest: TestFixture => Future[Assertion]): Future[Assertion] = { forAllMatchingFixtures { case f => runTest(f) } } protected def forAllMatchingFixtures( runTest: PartialFunction[TestFixture, Future[Assertion]]): Future[Assertion] = { if (parallelExecution) { val results = fixtures.map( fixture => if (runTest.isDefinedAt(fixture)) runTestAgainstFixture(fixture, runTest) else Future.successful(succeed)) Future.sequence(results).map(foldAssertions) } else { fixtures.foldLeft(Future.successful(succeed)) { case (resultSoFar, thisFixture) => resultSoFar.flatMap { case Succeeded => runTestAgainstFixture(thisFixture, runTest) case other => Future.successful(other) } } } } }