scala.util.control.NoStackTrace Scala Examples

The following examples show how to use scala.util.control.NoStackTrace. 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: GrpcServerOwner.scala    From daml   with Apache License 2.0 6 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.apiserver

import java.io.IOException
import java.net.{BindException, InetAddress, InetSocketAddress}
import java.util.concurrent.TimeUnit.SECONDS

import com.daml.metrics.Metrics
import com.daml.platform.apiserver.GrpcServerOwner._
import com.daml.ports.Port
import com.daml.resources.{Resource, ResourceOwner}
import com.google.protobuf.Message
import io.grpc.netty.NettyServerBuilder
import io.grpc._
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.ssl.SslContext

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NoStackTrace

final class GrpcServerOwner(
    address: Option[String],
    desiredPort: Port,
    maxInboundMessageSize: Int,
    sslContext: Option[SslContext] = None,
    interceptors: List[ServerInterceptor] = List.empty,
    metrics: Metrics,
    eventLoopGroups: ServerEventLoopGroups,
    services: Iterable[BindableService],
) extends ResourceOwner[Server] {
  override def acquire()(implicit executionContext: ExecutionContext): Resource[Server] = {
    val host = address.map(InetAddress.getByName).getOrElse(InetAddress.getLoopbackAddress)
    Resource(Future {
      val builder = NettyServerBuilder.forAddress(new InetSocketAddress(host, desiredPort.value))
      builder.sslContext(sslContext.orNull)
      builder.channelType(classOf[NioServerSocketChannel])
      builder.permitKeepAliveTime(10, SECONDS)
      builder.permitKeepAliveWithoutCalls(true)
      builder.directExecutor()
      builder.maxInboundMessageSize(maxInboundMessageSize)
      interceptors.foreach(builder.intercept)
      builder.intercept(new MetricsInterceptor(metrics))
      eventLoopGroups.populate(builder)
      services.foreach { service =>
        builder.addService(service)
        toLegacyService(service).foreach(builder.addService)
      }
      val server = builder.build()
      try {
        server.start()
      } catch {
        case e: IOException if e.getCause != null && e.getCause.isInstanceOf[BindException] =>
          throw new UnableToBind(desiredPort, e.getCause)
      }
      server
    })(server => Future(server.shutdown().awaitTermination()))
  }

  // This exposes the existing services under com.daml also under com.digitalasset.
  // This is necessary to allow applications built with an earlier version of the SDK
  // to still work.
  // The "proxy" services will not show up on the reflection service, because of the way it
  // processes service definitions via protobuf file descriptors.
  private def toLegacyService(service: BindableService): Option[ServerServiceDefinition] = {
    val `com.daml` = "com.daml"
    val `com.digitalasset` = "com.digitalasset"

    val damlDef = service.bindService()
    val damlDesc = damlDef.getServiceDescriptor
    // Only add "proxy" services if it actually contains com.daml in the service name.
    // There are other services registered like the reflection service, that doesn't need the special treatment.
    if (damlDesc.getName.contains(`com.daml`)) {
      val digitalassetName = damlDesc.getName.replace(`com.daml`, `com.digitalasset`)
      val digitalassetDef = ServerServiceDefinition.builder(digitalassetName)
      damlDef.getMethods.forEach { methodDef =>
        val damlMethodDesc = methodDef.getMethodDescriptor
        val digitalassetMethodName =
          damlMethodDesc.getFullMethodName.replace(`com.daml`, `com.digitalasset`)
        val digitalassetMethodDesc =
          damlMethodDesc.toBuilder.setFullMethodName(digitalassetMethodName).build()
        val _ = digitalassetDef.addMethod(
          digitalassetMethodDesc.asInstanceOf[MethodDescriptor[Message, Message]],
          methodDef.getServerCallHandler.asInstanceOf[ServerCallHandler[Message, Message]]
        )
      }
      Option(digitalassetDef.build())
    } else None
  }
}

object GrpcServerOwner {

  final class UnableToBind(port: Port, cause: Throwable)
      extends RuntimeException(
        s"The API server was unable to bind to port $port. Terminate the process occupying the port, or choose a different one.",
        cause)
      with NoStackTrace

} 
Example 2
Source File: CommonTesting.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.testHelpers

import com.github.agourlay.cornichon.core._
import com.github.agourlay.cornichon.dsl.ProvidedInstances
import com.github.agourlay.cornichon.steps.cats.EffectStep
import com.github.agourlay.cornichon.steps.regular.DebugStep
import com.github.agourlay.cornichon.steps.regular.assertStep.{ AssertStep, Assertion }
import org.scalacheck.Gen

import scala.util.control.NoStackTrace

trait CommonTesting extends ProvidedInstances with TaskSpec {

  def integerGen(rc: RandomContext): ValueGenerator[Int] = ValueGenerator(
    name = "integer",
    gen = () => rc.nextInt(10000))

  def brokenIntGen(rc: RandomContext): ValueGenerator[Int] = ValueGenerator(
    name = "integer",
    gen = () => throw new RuntimeException(s"boom gen with initial seed ${rc.initialSeed}"))

  def stringGen(rc: RandomContext): ValueGenerator[String] = ValueGenerator(
    name = "integer",
    gen = () => rc.nextString(10))

  val identityEffectStep: Step = EffectStep.fromSync("identity effect step", _.session)
  val addValueToSessionEffectStep: Step = EffectStep.fromSyncE("add value to session effect step", _.session.addValue("my-key", "my-value"))
  val alwaysValidAssertStep: Step = AssertStep("valid", _ => Assertion.alwaysValid)
  val validDebugStep: Step = DebugStep("valid debug", _ => Right("debug!"))

  val validStepGen: Gen[Step] = Gen.oneOf(identityEffectStep, addValueToSessionEffectStep, alwaysValidAssertStep, validDebugStep)
  val validStepsGen: Gen[List[Step]] = Gen.nonEmptyListOf(validStepGen)

  def throwExceptionWithStackTrace() = throw new RuntimeException("boom!") with NoStackTrace

  val brokenEffectStep: Step = EffectStep.fromSyncE("always boom", _ => Left(CornichonError.fromString("boom!")))
  val exceptionEffectStep: Step = EffectStep.fromSync("throw exception effect step", _ => throwExceptionWithStackTrace())
  val neverValidAssertStep: Step = AssertStep("never valid assert step", _ => Assertion.failWith("never valid!"))
  val failedDebugStep: Step = DebugStep("bad debug", _ => throwExceptionWithStackTrace())

  val invalidStepGen: Gen[Step] = Gen.oneOf(brokenEffectStep, exceptionEffectStep, neverValidAssertStep, failedDebugStep)
  val invalidStepsGen: Gen[List[Step]] = Gen.nonEmptyListOf(invalidStepGen)

  // TODO generate wrapper steps with invalid and valid nested steps
} 
Example 3
Source File: ServiceLocatorSessionProvider.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.persistence.cassandra

import java.net.InetSocketAddress
import java.net.URI

import scala.collection.immutable
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.concurrent.Promise
import scala.concurrent.duration._
import scala.util.control.NoStackTrace

import akka.actor.ActorSystem
import akka.persistence.cassandra.ConfigSessionProvider
import com.typesafe.config.Config
import play.api.Logger


private[lagom] final class ServiceLocatorSessionProvider(system: ActorSystem, config: Config)
    extends ConfigSessionProvider(system, config) {
  private val log = Logger(getClass)

  override def lookupContactPoints(
      clusterId: String
  )(implicit ec: ExecutionContext): Future[immutable.Seq[InetSocketAddress]] = {
    ServiceLocatorHolder(system).serviceLocatorEventually.flatMap { serviceLocatorAdapter =>
      serviceLocatorAdapter.locateAll(clusterId).map {
        case Nil => throw new NoContactPointsException(s"No contact points for [$clusterId]")
        case uris =>
          log.debug(s"Found Cassandra contact points: $uris")

          // URIs must be all valid
          uris.foreach { uri =>
            require(uri.getHost != null, s"missing host in $uri for Cassandra contact points $clusterId")
            require(uri.getPort != -1, s"missing port in $uri for Cassandra contact points $clusterId")
          }

          uris.map { uri =>
            new InetSocketAddress(uri.getHost, uri.getPort)
          }
      }
    }
  }
}

private[lagom] final class NoContactPointsException(msg: String) extends RuntimeException(msg) with NoStackTrace 
Example 4
Source File: UnitSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package support

import org.scalatest.EitherValues
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import play.api.http.{HeaderNames, MimeTypes, Status}
import play.api.mvc.ControllerComponents
import play.api.test.Helpers.stubControllerComponents
import play.api.test.{DefaultAwaitTimeout, FutureAwaits, ResultExtractors}
import uk.gov.hmrc.http.HeaderCarrier

import scala.util.control.NoStackTrace

trait UnitSpec extends AnyWordSpecLike
  with EitherValues
  with Matchers
  with FutureAwaits
  with DefaultAwaitTimeout
  with ResultExtractors
  with HeaderNames
  with Status
  with MimeTypes {

  lazy val controllerComponents: ControllerComponents = stubControllerComponents()

  implicit val hc: HeaderCarrier = HeaderCarrier()

  val testException: Throwable = new NoStackTrace {
    override def getMessage: String = "A test exception was thrown"
  }
} 
Example 5
Source File: transactions.scala    From redis4cats   with Apache License 2.0 5 votes vote down vote up
package dev.profunktor.redis4cats

import cats.effect._
import cats.implicits._
import dev.profunktor.redis4cats.effect.Log
import dev.profunktor.redis4cats.hlist._
import scala.util.control.NoStackTrace

object transactions {

  sealed trait TransactionError extends NoStackTrace
  case object TransactionAborted extends TransactionError
  case object TransactionDiscarded extends TransactionError

  case class RedisTransaction[F[_]: Concurrent: Log: Timer, K, V](
      cmd: RedisCommands[F, K, V]
  ) {

    private val ops =
      Runner.Ops(
        name = "Transaction",
        mainCmd = cmd.multi,
        onComplete = (f: Runner.CancelFibers[F]) => cmd.exec.handleErrorWith(e => f(e) >> F.raiseError(e)),
        onError = cmd.discard,
        afterCompletion = F.unit,
        mkError = () => TransactionAborted
      )

    
    def exec[T <: HList, R <: HList](commands: T)(implicit w: Witness.Aux[T, R]): F[R] =
      Runner[F].exec(ops)(commands)

  }

} 
Example 6
Source File: pipeline.scala    From redis4cats   with Apache License 2.0 5 votes vote down vote up
package dev.profunktor.redis4cats

import cats.effect._
import dev.profunktor.redis4cats.effect.Log
import dev.profunktor.redis4cats.hlist._
import scala.util.control.NoStackTrace

object pipeline {

  case object PipelineError extends NoStackTrace

  case class RedisPipeline[F[_]: Concurrent: Log: Timer, K, V](
      cmd: RedisCommands[F, K, V]
  ) {

    private val ops =
      Runner.Ops(
        name = "Pipeline",
        mainCmd = cmd.disableAutoFlush,
        onComplete = (_: Runner.CancelFibers[F]) => cmd.flushCommands,
        onError = F.unit,
        afterCompletion = cmd.enableAutoFlush,
        mkError = () => PipelineError
      )

    
    def exec[T <: HList, R <: HList](commands: T)(implicit w: Witness.Aux[T, R]): F[R] =
      Runner[F].exec(ops)(commands)

  }

} 
Example 7
Source File: RedisConnection.scala    From redis4cats   with Apache License 2.0 5 votes vote down vote up
package dev.profunktor.redis4cats.connection

import cats.effect._
import cats.syntax.all._
import dev.profunktor.redis4cats.data.NodeId
import dev.profunktor.redis4cats.effect.JRFuture
import io.lettuce.core.api.StatefulRedisConnection
import io.lettuce.core.api.async.RedisAsyncCommands
import io.lettuce.core.api.sync.{ RedisCommands => RedisSyncCommands }
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection
import io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands
import io.lettuce.core.cluster.api.sync.{ RedisClusterCommands => RedisClusterSyncCommands }
import scala.util.control.NoStackTrace

case class OperationNotSupported(value: String) extends NoStackTrace {
  override def toString(): String = s"OperationNotSupported($value)"
}

private[redis4cats] trait RedisConnection[F[_], K, V] {
  def sync: F[RedisSyncCommands[K, V]]
  def clusterSync: F[RedisClusterSyncCommands[K, V]]
  def async: F[RedisAsyncCommands[K, V]]
  def clusterAsync: F[RedisClusterAsyncCommands[K, V]]
  def close: F[Unit]
  def byNode(nodeId: NodeId): F[RedisAsyncCommands[K, V]]
  def liftK[G[_]: Concurrent: ContextShift]: RedisConnection[G, K, V]
}

private[redis4cats] class RedisStatefulConnection[F[_]: Concurrent: ContextShift, K, V](
    conn: StatefulRedisConnection[K, V],
    blocker: Blocker
) extends RedisConnection[F, K, V] {
  def sync: F[RedisSyncCommands[K, V]] = F.delay(conn.sync())
  def clusterSync: F[RedisClusterSyncCommands[K, V]] =
    F.raiseError(OperationNotSupported("Running in a single node"))
  def async: F[RedisAsyncCommands[K, V]] = F.delay(conn.async())
  def clusterAsync: F[RedisClusterAsyncCommands[K, V]] =
    F.raiseError(OperationNotSupported("Running in a single node"))
  def close: F[Unit] = JRFuture.fromCompletableFuture(F.delay(conn.closeAsync()))(blocker).void
  def byNode(nodeId: NodeId): F[RedisAsyncCommands[K, V]] =
    F.raiseError(OperationNotSupported("Running in a single node"))
  def liftK[G[_]: Concurrent: ContextShift]: RedisConnection[G, K, V] =
    new RedisStatefulConnection[G, K, V](conn, blocker)
}

private[redis4cats] class RedisStatefulClusterConnection[F[_]: Concurrent: ContextShift, K, V](
    conn: StatefulRedisClusterConnection[K, V],
    blocker: Blocker
) extends RedisConnection[F, K, V] {
  def sync: F[RedisSyncCommands[K, V]] =
    F.raiseError(
      OperationNotSupported("Transactions are not supported in a cluster. You must select a single node.")
    )
  def async: F[RedisAsyncCommands[K, V]] =
    F.raiseError(
      OperationNotSupported("Transactions are not supported in a cluster. You must select a single node.")
    )
  def clusterAsync: F[RedisClusterAsyncCommands[K, V]] = F.delay(conn.async())
  def clusterSync: F[RedisClusterSyncCommands[K, V]]   = F.delay(conn.sync())
  def close: F[Unit] =
    JRFuture.fromCompletableFuture(F.delay(conn.closeAsync()))(blocker).void
  def byNode(nodeId: NodeId): F[RedisAsyncCommands[K, V]] =
    JRFuture.fromCompletableFuture(F.delay(conn.getConnectionAsync(nodeId.value)))(blocker).flatMap { stateful =>
      F.delay(stateful.async())
    }
  def liftK[G[_]: Concurrent: ContextShift]: RedisConnection[G, K, V] =
    new RedisStatefulClusterConnection[G, K, V](conn, blocker)
} 
Example 8
Source File: Contexts.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.javasupport.impl

import java.util.Optional

import io.cloudstate.javasupport.{ClientActionContext, Context, EffectContext, ServiceCall}

import scala.util.control.NoStackTrace
import com.google.protobuf.{Any => JavaPbAny}
import com.google.protobuf.any.{Any => ScalaPbAny}
import io.cloudstate.protocol.entity.{ClientAction, Failure, Forward, Reply, SideEffect}

private[impl] trait ActivatableContext extends Context {
  private final var active = true
  final def deactivate(): Unit = active = false
  final def checkActive(): Unit = if (!active) throw new IllegalStateException("Context no longer active!")
}

private[impl] trait AbstractEffectContext extends EffectContext {
  self: ActivatableContext =>

  private final var effects = List.empty[SideEffect]

  override final def effect(effect: ServiceCall, synchronous: Boolean): Unit = {
    checkActive()
    SideEffect(
      serviceName = effect.ref().method().getService.getFullName,
      commandName = effect.ref().method().getName,
      payload = Some(ScalaPbAny.fromJavaProto(effect.message())),
      synchronous = synchronous
    ) :: effects
  }

  final def sideEffects: List[SideEffect] = effects.reverse
}

private[impl] trait AbstractClientActionContext extends ClientActionContext {
  self: ActivatableContext =>

  def commandId: Long

  private final var error: Option[String] = None
  private final var forward: Option[Forward] = None

  override final def fail(errorMessage: String): RuntimeException = {
    checkActive()
    if (error.isEmpty) {
      error = Some(errorMessage)
      throw FailInvoked
    } else throw new IllegalStateException("fail(…) already previously invoked!")
  }

  override final def forward(to: ServiceCall): Unit = {
    checkActive()
    if (forward.isDefined) {
      throw new IllegalStateException("This context has already forwarded.")
    }
    forward = Some(
      Forward(
        serviceName = to.ref().method().getService.getFullName,
        commandName = to.ref().method().getName,
        payload = Some(ScalaPbAny.fromJavaProto(to.message()))
      )
    )
  }

  final def hasError: Boolean = error.isDefined

  final def createClientAction(reply: Optional[JavaPbAny], allowNoReply: Boolean): Option[ClientAction] =
    error match {
      case Some(msg) => Some(ClientAction(ClientAction.Action.Failure(Failure(commandId, msg))))
      case None =>
        if (reply.isPresent) {
          if (forward.isDefined) {
            throw new IllegalStateException(
              "Both a reply was returned, and a forward message was sent, choose one or the other."
            )
          }
          Some(ClientAction(ClientAction.Action.Reply(Reply(Some(ScalaPbAny.fromJavaProto(reply.get()))))))
        } else if (forward.isDefined) {
          Some(ClientAction(ClientAction.Action.Forward(forward.get)))
        } else if (allowNoReply) {
          None
        } else {
          throw new RuntimeException("No reply or forward returned by command handler!")
        }
    }
}

object FailInvoked extends Throwable with NoStackTrace {
  override def toString: String = "CommandContext.fail(…) invoked"
} 
Example 9
Source File: Contexts.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.javasupport.impl

import java.util.Optional

import io.cloudstate.javasupport.{ClientActionContext, Context, EffectContext, ServiceCall}

import scala.util.control.NoStackTrace
import com.google.protobuf.{Any => JavaPbAny}
import com.google.protobuf.any.{Any => ScalaPbAny}
import io.cloudstate.protocol.entity.{ClientAction, Failure, Forward, Reply, SideEffect}

private[impl] trait ActivatableContext extends Context {
  private final var active = true
  final def deactivate(): Unit = active = false
  final def checkActive(): Unit = if (!active) throw new IllegalStateException("Context no longer active!")
}

private[impl] trait AbstractEffectContext extends EffectContext {
  self: ActivatableContext =>

  private final var effects = List.empty[SideEffect]

  override final def effect(effect: ServiceCall, synchronous: Boolean): Unit = {
    checkActive()
    SideEffect(
      serviceName = effect.ref().method().getService.getFullName,
      commandName = effect.ref().method().getName,
      payload = Some(ScalaPbAny.fromJavaProto(effect.message())),
      synchronous = synchronous
    ) :: effects
  }

  final def sideEffects: List[SideEffect] = effects.reverse
}

private[impl] trait AbstractClientActionContext extends ClientActionContext {
  self: ActivatableContext =>

  def commandId: Long

  private final var error: Option[String] = None
  private final var forward: Option[Forward] = None

  override final def fail(errorMessage: String): RuntimeException = {
    checkActive()
    if (error.isEmpty) {
      error = Some(errorMessage)
      throw FailInvoked
    } else throw new IllegalStateException("fail(…) already previously invoked!")
  }

  override final def forward(to: ServiceCall): Unit = {
    checkActive()
    if (forward.isDefined) {
      throw new IllegalStateException("This context has already forwarded.")
    }
    forward = Some(
      Forward(
        serviceName = to.ref().method().getService.getFullName,
        commandName = to.ref().method().getName,
        payload = Some(ScalaPbAny.fromJavaProto(to.message()))
      )
    )
  }

  final def hasError: Boolean = error.isDefined

  final def createClientAction(reply: Optional[JavaPbAny], allowNoReply: Boolean): Option[ClientAction] =
    error match {
      case Some(msg) => Some(ClientAction(ClientAction.Action.Failure(Failure(commandId, msg))))
      case None =>
        if (reply.isPresent) {
          if (forward.isDefined) {
            throw new IllegalStateException(
              "Both a reply was returned, and a forward message was sent, choose one or the other."
            )
          }
          Some(ClientAction(ClientAction.Action.Reply(Reply(Some(ScalaPbAny.fromJavaProto(reply.get()))))))
        } else if (forward.isDefined) {
          Some(ClientAction(ClientAction.Action.Forward(forward.get)))
        } else if (allowNoReply) {
          None
        } else {
          throw new RuntimeException("No reply or forward returned by command handler!")
        }
    }
}

object FailInvoked extends Throwable with NoStackTrace {
  override def toString: String = "CommandContext.fail(…) invoked"
} 
Example 10
Source File: CornichonError.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.core

import java.io.{ PrintWriter, StringWriter }

import cats.data.EitherT
import cats.syntax.either._
import cats.instances.future._

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.control.NoStackTrace

trait CornichonError {
  def baseErrorMessage: String
  val causedBy: List[CornichonError] = Nil

  lazy val renderedMessage: String = {
    if (causedBy.isEmpty)
      baseErrorMessage
    else
      s"""$baseErrorMessage
      |caused by:
      |${causedBy.iterator.map(c => c.renderedMessage).mkString("\nand\n")}""".stripMargin
  }

  def toException = CornichonException(renderedMessage)
}

object CornichonError {
  def genStacktrace(exception: Throwable): String = {
    val sw = new StringWriter()
    val pw = new PrintWriter(sw)
    exception.printStackTrace(pw)
    sw.toString
  }

  def fromString(error: String): CornichonError =
    BasicError(error)

  def fromThrowable(exception: Throwable): CornichonError =
    StepExecutionError(exception)

  def catchThrowable[A](f: => A): Either[CornichonError, A] =
    Either.catchNonFatal(f).leftMap(fromThrowable)

  implicit class fromEither[A](e: Either[CornichonError, A]) {
    def valueUnsafe: A = e.fold(e => throw e.toException, identity)
    def futureEitherT(implicit ec: ExecutionContext): EitherT[Future, CornichonError, A] = EitherT.fromEither[Future](e)
  }
}

case class StepExecutionError(e: Throwable) extends CornichonError {
  lazy val baseErrorMessage = s"exception thrown ${CornichonError.genStacktrace(e)}"
}

case class BasicError(error: String) extends CornichonError {
  lazy val baseErrorMessage = error
}

case class CornichonException(m: String) extends Exception with NoStackTrace {
  override def getMessage = m
} 
Example 11
Source File: EffectStepSpec.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.steps.regular

import com.github.agourlay.cornichon.core.{ CornichonError, Scenario, ScenarioRunner, Session }
import com.github.agourlay.cornichon.steps.cats.{ EffectStep => CEffectStep }
import com.github.agourlay.cornichon.testHelpers.CommonTestSuite
import monix.eval.Task
import utest._

import scala.concurrent.Future
import scala.util.control.NoStackTrace

object EffectStepSpec extends TestSuite with CommonTestSuite {

  val tests = Tests {
    test("EffectStep Async - return error if an Effect step throw an exception") {
      val step = EffectStep(title = "buggy effect", _ => throwExceptionWithStackTrace())
      val s = Scenario("scenario with broken effect step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      scenarioFailsWithMessage(res) {
        """|Scenario 'scenario with broken effect step' failed:
           |
           |at step:
           |buggy effect
           |
           |with error(s):
           |exception thrown com.github.agourlay.cornichon.testHelpers.CommonTesting$$anon$1: boom!
           |
           |
           |seed for the run was '1'
           |""".stripMargin
      }
    }

    test("EffectStep Async - return error if an Effect step for Future.failed") {
      val step = EffectStep(title = "buggy effect", _ => Future.failed(new RuntimeException("boom")))
      val s = Scenario("scenario with broken effect step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      assert(!res.isSuccess)
    }

    test("EffectStep Sync - return error if an Effect step throw an exception") {
      val step = EffectStep.fromSync(title = "buggy effect", _ => throwExceptionWithStackTrace())
      val s = Scenario("scenario with broken effect step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      assert(!res.isSuccess)
    }

    test("EffectStep SyncE - valid if effect is an Either.Right") {
      val step = EffectStep.fromSyncE(title = "valid effect", sc => Right(sc.session))
      val s = Scenario("scenario with valid effect step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      assert(res.isSuccess)
    }

    test("EffectStep SyncE - invalid if effect is an Either.Left") {
      val step = EffectStep.fromSyncE(title = "valid effect", _ => Left(CornichonError.fromString("ohh nooes")))
      val s = Scenario("scenario with invalid effect step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      assert(!res.isSuccess)
    }

    test("CatsEffectStep Async - return error if an Effect step throw an exception") {
      val step = CEffectStep[Task](title = "buggy effect", _ => throwExceptionWithStackTrace())
      val s = Scenario("scenario with broken effect step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      assert(!res.isSuccess)
    }

    test("CatsEffectStep Async - return error if an Effect step for Task.raiseError") {
      val step = CEffectStep[Task](title = "buggy effect", _ => Task.raiseError(new RuntimeException("boom") with NoStackTrace))
      val s = Scenario("scenario with broken effect step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      assert(!res.isSuccess)
    }

    test("CatsEffectStep Sync - return error if an Effect step throw an exception") {
      val step = CEffectStep[Task](title = "buggy effect", _ => throwExceptionWithStackTrace())
      val s = Scenario("scenario with broken effect step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      assert(!res.isSuccess)
    }

    test("CatsEffectStep SyncE - valid if effect is an Either.Right") {
      val step = CEffectStep.fromSyncE(title = "valid effect", sc => Right(sc.session))
      val s = Scenario("scenario with valid effect step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      assert(res.isSuccess)
    }

    test("CatsEffectStep SyncE - invalid if effect is an Either.Left") {
      val step = CEffectStep.fromSyncE(title = "valid effect", _ => Left(CornichonError.fromString("ohh nooes")))
      val s = Scenario("scenario with invalid effect step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      assert(!res.isSuccess)
    }
  }
} 
Example 12
Source File: DebugStepSpec.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.steps.regular

import com.github.agourlay.cornichon.core.{ CornichonError, Scenario, ScenarioRunner, Session }
import com.github.agourlay.cornichon.testHelpers.CommonTestSuite

import utest._

import scala.util.control.NoStackTrace

object DebugStepSpec extends TestSuite with CommonTestSuite {

  val tests = Tests {
    test("fails scenario if a Debug step throws an exception") {
      val step = DebugStep("bad debug", _ => throw new RuntimeException("boom") with NoStackTrace)
      val s = Scenario("scenario with faulty debug step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      scenarioFailsWithMessage(res) {
        """Scenario 'scenario with faulty debug step' failed:
          |
          |at step:
          |bad debug
          |
          |with error(s):
          |exception thrown com.github.agourlay.cornichon.steps.regular.DebugStepSpec$$anon$1: boom
          |
          |
          |seed for the run was '1'
          |""".stripMargin
      }

      matchLogsWithoutDuration(res.logs) {
        """
          |   Scenario : scenario with faulty debug step
          |      main steps
          |      bad debug
          |      *** FAILED ***
          |      exception thrown com.github.agourlay.cornichon.steps.regular.DebugStepSpec$$anon$1: boom""".stripMargin
      }
    }

    test("fails scenario if a Debug step returns an Either.Left") {
      val step = DebugStep("invalid debug", _ => Left(CornichonError.fromString("debugging with println went wrong!")))
      val s = Scenario("scenario with faulty debug step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      scenarioFailsWithMessage(res) {
        """Scenario 'scenario with faulty debug step' failed:
          |
          |at step:
          |invalid debug
          |
          |with error(s):
          |debugging with println went wrong!
          |
          |seed for the run was '1'
          |""".stripMargin
      }

      matchLogsWithoutDuration(res.logs) {
        """
          |   Scenario : scenario with faulty debug step
          |      main steps
          |      invalid debug
          |      *** FAILED ***
          |      debugging with println went wrong!""".stripMargin
      }
    }

    test("debug info is present in the logs") {
      val step = DebugStep("debug info", _ => Right("debugging with println"))
      val s = Scenario("scenario with correct debug step", step :: Nil)
      val res = awaitTask(ScenarioRunner.runScenario(Session.newEmpty)(s))
      assert(res.isSuccess)
      matchLogsWithoutDuration(res.logs) {
        """
        |   Scenario : scenario with correct debug step
        |      main steps
        |      debugging with println""".stripMargin
      }
    }
  }
} 
Example 13
Source File: ResourceRegistrySpec.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal.util

import cats.effect._
import cats.effect.concurrent.{Deferred, Ref}
import cats.implicits._
import cats.{Applicative, Foldable}
import com.evolutiongaming.kafka.journal.IOSuite._
import org.scalatest.funsuite.AsyncFunSuite
import org.scalatest.matchers.should.Matchers

import scala.util.control.NoStackTrace

class ResourceRegistrySpec extends AsyncFunSuite with Matchers {

  val error: Throwable = new RuntimeException with NoStackTrace
  for {
    exitCase <- List(
      ExitCase.complete,
      ExitCase.error(error),
      ExitCase.canceled)
  } yield {

    test(s"ResRegistry releases resources, exitCase: $exitCase") {
      val result = exitCase match {
        case ExitCase.Completed    => testError(none)
        case ExitCase.Canceled     => testCancel
        case ExitCase.Error(error) => testError(error.some)
      }
      result.run()
    }
  }

  private def testError(error: Option[Throwable]) = {
    val n = 3

    def logic(release: IO[Unit]) = {
      ResourceRegistry.of[IO].use { registry =>
        val resource = Resource.make(().pure[IO]) { _ => release }
        val fa = registry.allocate(resource)
        implicit val monoidUnit = Applicative.monoid[IO, Unit]
        for {
          _ <- Foldable[List].fold(List.fill(n)(fa))
          _ <- error.fold(().pure[IO])(_.raiseError[IO, Unit])
        } yield {}
      }
    }

    for {
      ref      <- Ref.of[IO, Int](0)
      fa        = logic(ref.update(_ + 1))
      result   <- fa.redeem(_.some, _ => none)
      releases <- ref.get
    } yield {
      result shouldEqual result
      releases shouldEqual n
    }
  }

  private def testCancel = {
    for {
      released <- Ref.of[IO, Int](0)
      started  <- Deferred[IO, Unit]
      fiber    <- Concurrent[IO].start {
        ResourceRegistry.of[IO].use { registry =>
          val resource = Resource.make(().pure[IO]) { _ => released.update(_ + 1) }
          for {
            _ <- registry.allocate(resource)
            _ <- started.complete(())
            _ <- IO.never.as(())
          } yield {}
        }
      }
      _        <- started.get
      _        <- fiber.cancel
      released <- released.get
    } yield {
      released shouldEqual 1
    }
  }
} 
Example 14
Source File: ConsoleInput.scala    From akka-http-scala-js-websocket-chat   with MIT License 5 votes vote down vote up
package example.akkawschat.cli

import akka.stream.stage.{ OutHandler, GraphStageLogic, GraphStage }
import akka.stream._

import scala.annotation.tailrec
import scala.concurrent.{ Future, ExecutionContext }
import scala.util.control.NoStackTrace

class ConsoleInput(implicit ec: ExecutionContext) extends GraphStage[SourceShape[Char]] {
  val out = Outlet[Char]("consoleOut")
  val shape: SourceShape[Char] = SourceShape(out)

  def createLogic(inheritedAttributes: Attributes): GraphStageLogic =
    new GraphStageLogic(shape) {
      TTY.noEchoStty()

      @volatile var cancelled = false
      def getOne(): Unit = {
        val callback = getAsyncCallback[Char](push(out, _))

        Future {
          @tailrec def read(): Unit =
            if (cancelled) throw new Exception with NoStackTrace
            else if (System.in.available() > 0)
              callback.invoke(System.in.read().toChar)
            else {
              Thread.sleep(10)
              read()
            }

          read()
        }
      }

      setHandler(out, new OutHandler {
        def onPull(): Unit = getOne()

        override def onDownstreamFinish(cause: Throwable): Unit = {
          cancelled = true
          super.onDownstreamFinish(cause)
        }
      })

      override def postStop(): Unit =
        TTY.saneStty()
    }
} 
Example 15
Source File: StreamletLoader.scala    From cloudflow   with Apache License 2.0 5 votes vote down vote up
package cloudflow.streamlets

import scala.util.{ Failure, Try }
import scala.util.control.NoStackTrace

import com.typesafe.config.Config

case class LoadedStreamlet(streamlet: Streamlet[StreamletContext], config: StreamletDefinition)


trait StreamletLoader {

  def loadStreamlet(config: Config): Try[LoadedStreamlet] =
    for {
      streamletConfig ← StreamletDefinition.read(config)
      loadedStreamlet ← loadStreamlet(streamletConfig)
    } yield loadedStreamlet

  def loadStreamletClass(streamletClassName: String): Try[Streamlet[StreamletContext]] =
    for {
      instance ← ClassOps.instanceOf(streamletClassName).recoverWith {
        case _: ClassNotFoundException ⇒ Failure(new StreamletClassNotFound(streamletClassName))
        case _: InstantiationException ⇒ Failure(new NoArgsConstructorExpectedException(streamletClassName))
      }
      streamlet ← Try(instance.asInstanceOf[Streamlet[StreamletContext]]).recoverWith {
        case ex: ClassCastException ⇒ Failure(new InvalidStreamletClass(streamletClassName, ex))
      }
    } yield streamlet

  def loadStreamlet(streamletConfig: StreamletDefinition): Try[LoadedStreamlet] =
    loadStreamletClass(streamletConfig.streamletClass).map { streamlet ⇒
      LoadedStreamlet(streamlet, streamletConfig)
    }

  case class StreamletClassNotFound(className: String)
      extends Exception(s"The configured Streamlet class $className not found")
      with NoStackTrace

  case class InvalidStreamletClass(className: String, cause: Exception)
      extends Exception(s"The configured Streamlet class $className is invalid")
      with NoStackTrace

  case class NoArgsConstructorExpectedException(className: String)
      extends Exception(s"The configured Streamlet class $className must have an arg-less constructor")
      with NoStackTrace

} 
Example 16
Source File: JsonLifter.scala    From diffy   with GNU Affero General Public License v3.0 5 votes vote down vote up
package ai.diffy.lifter

import com.fasterxml.jackson.core.{JsonGenerator, JsonToken}
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper, SerializerProvider}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.twitter.util.Try

import scala.collection.JavaConversions._
import scala.language.postfixOps
import scala.reflect.runtime.universe.runtimeMirror
import scala.tools.reflect.ToolBox
import scala.util.control.NoStackTrace

object JsonLifter {
  @JsonSerialize(using = classOf[JsonNullSerializer])
  object JsonNull
  object JsonParseError extends Exception with NoStackTrace

  val toolbox = runtimeMirror(getClass.getClassLoader).mkToolBox()

  val Mapper = new ObjectMapper with ScalaObjectMapper
  Mapper.registerModule(DefaultScalaModule)
  def apply(obj: Any): JsonNode = Mapper.valueToTree(obj)

  def lift(node: JsonNode): Any = node.asToken match {
    case JsonToken.START_ARRAY        =>
      node.elements.toSeq.map {
        element => lift(element)
      }
    case JsonToken.START_OBJECT       => {
      val fields = node.fieldNames.toSet
      if (fields.exists{ field => Try(toolbox.parse(s"object ${field}123")).isThrow}) {
        node.fields map {field => (field.getKey -> lift(field.getValue))} toMap
      } else {
        FieldMap(
          node.fields map {field => (field.getKey -> lift(field.getValue))} toMap
        )
      }
    }
    case JsonToken.VALUE_FALSE        => false
    case JsonToken.VALUE_NULL         => JsonNull
    case JsonToken.VALUE_NUMBER_FLOAT => node.asDouble
    case JsonToken.VALUE_NUMBER_INT   => node.asLong
    case JsonToken.VALUE_TRUE         => true
    case JsonToken.VALUE_STRING       => node.textValue
    case _                            => throw JsonParseError
  }

  def decode(json: String): JsonNode = Mapper.readTree(json)
  def encode(item: Any): String = Mapper.writer.writeValueAsString(item)
}

class JsonNullSerializer(clazz: Class[Any]) extends StdSerializer[Any](clazz) {
  def this() {
    this(null)
  }

  override def serialize(t: Any, jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider): Unit = {
    jsonGenerator.writeNull()
  }
} 
Example 17
Source File: JsParser.scala    From scalaz-deriving   with GNU Lesser General Public License v3.0 5 votes vote down vote up
// Copyright: 2017 - 2020 Sam Halliday
// License: http://www.gnu.org/licenses/lgpl-3.0.en.html

package jsonformat

import scala.util.control.NoStackTrace
import org.typelevel.jawn._
import scalaz._, Scalaz._
import internal.FastToIList._

object JsParser extends SupportParser[JsValue] {

  // jawn uses exceptions for control flow (the error case), which is a huge DOS
  // security vulnerability, but we can't do anything about it.

  def apply(s: String): String \/ JsValue =
    Maybe.attempt(parseUnsafe(s)) \/> "invalid json"

  implicit val facade: Facade[JsValue] =
    new Facade.SimpleFacade[JsValue] {
      val jnull: JsNull.type = JsNull
      val jfalse: JsBoolean  = JsBoolean(false)
      val jtrue: JsBoolean   = JsBoolean(true)
      def jnum(cs: CharSequence, decIndex: Int, expIndex: Int): JsValue = {
        val s = cs.toString
        val n =
          if (decIndex == -1)
            s.parseLong.map(JsInteger(_))
          else if (s.endsWith(".0"))
            s.substring(0, s.length - 2).parseLong.map(JsInteger(_))
          else
            s.parseDouble.map(JsDouble(_))
        n.getOrElse(
          throw new IllegalArgumentException(s"bad number $s")
            with NoStackTrace // scalafix:ok
        )
      }

      def jstring(s: CharSequence): JsString          = JsString(s.toString)
      def jarray(vs: List[JsValue]): JsArray          = JsArray(vs.toIList)
      def jobject(vs: Map[String, JsValue]): JsObject = JsObject(vs.asIList)
    }
} 
Example 18
Source File: TxParseError.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.transaction

import scala.util.control.NoStackTrace

sealed trait TxParseError extends NoStackTrace

case class PBParsingError(underlying: Throwable) extends TxParseError {
  override val getMessage: String = s"Error while parsing protobuf transaction: ${underlying.getMessage}"
}

case class UnexpectedTransaction(expected: Byte, actual: Byte) extends TxParseError {
  override val getMessage: String = s"Unexpected transaction - required: $expected, actual: $actual"
}

case class UnknownType(typeId: Byte) extends TxParseError {
  override val getMessage: String = s"Unknown transaction type (old encoding): '$typeId'"
}

case class UnknownTypeAndVersion(typeId: Byte, version: Byte) extends TxParseError {
  override val getMessage: String = s"Unknown transaction type ($typeId) and version ($version) (modern encoding)"
}

case object BufferUnderflow extends TxParseError {
  override val getMessage: String = "Buffer underflow while parsing transaction"
} 
Example 19
Source File: http4stest.scala    From pfps-shopping-cart   with Apache License 2.0 5 votes vote down vote up
package suite

import cats.effect.IO
import io.circe._
import io.circe.syntax._
import org.http4s._
import org.http4s.circe._
import scala.util.control.NoStackTrace

trait HttpTestSuite extends PureTestSuite {

  case object DummyError extends NoStackTrace

  def assertHttp[A: Encoder](routes: HttpRoutes[IO], req: Request[IO])(
      expectedStatus: Status,
      expectedBody: A
  ) =
    routes.run(req).value.flatMap {
      case Some(resp) =>
        resp.asJson.map { json =>
          assert(resp.status === expectedStatus && json.dropNullValues === expectedBody.asJson.dropNullValues)
        }
      case None => fail("route nout found")
    }

  def assertHttpStatus(routes: HttpRoutes[IO], req: Request[IO])(expectedStatus: Status) =
    routes.run(req).value.map {
      case Some(resp) =>
        assert(resp.status === expectedStatus)
      case None => fail("route nout found")
    }

  def assertHttpFailure(routes: HttpRoutes[IO], req: Request[IO]) =
    routes.run(req).value.attempt.map {
      case Left(_)  => assert(true)
      case Right(_) => fail("expected a failure")
    }

} 
Example 20
Source File: order.scala    From pfps-shopping-cart   with Apache License 2.0 5 votes vote down vote up
package shop.domain

import io.estatico.newtype.macros.newtype
import java.util.UUID
import scala.util.control.NoStackTrace
import shop.domain.cart._
import shop.domain.item._
import squants.market.Money

object order {
  @newtype case class OrderId(value: UUID)
  @newtype case class PaymentId(value: UUID)

  case class Order(
      id: OrderId,
      paymentId: PaymentId,
      items: Map[ItemId, Quantity],
      total: Money
  )

  case object EmptyCartError extends NoStackTrace
  case class OrderError(cause: String) extends NoStackTrace
  case class PaymentError(cause: String) extends NoStackTrace
} 
Example 21
Source File: auth.scala    From pfps-shopping-cart   with Apache License 2.0 5 votes vote down vote up
package shop.domain

import eu.timepit.refined.types.string.NonEmptyString
import io.circe._
import io.estatico.newtype.macros.newtype
import java.util.UUID
import javax.crypto.Cipher
import scala.util.control.NoStackTrace

object auth {

  @newtype case class UserId(value: UUID)
  @newtype case class UserName(value: String)
  @newtype case class Password(value: String)

  @newtype case class EncryptedPassword(value: String)

  @newtype case class EncryptCipher(value: Cipher)
  @newtype case class DecryptCipher(value: Cipher)

  // --------- user registration -----------

  @newtype case class UserNameParam(value: NonEmptyString) {
    def toDomain: UserName = UserName(value.value.toLowerCase)
  }

  @newtype case class PasswordParam(value: NonEmptyString) {
    def toDomain: Password = Password(value.value)
  }

  case class CreateUser(
      username: UserNameParam,
      password: PasswordParam
  )

  case class UserNameInUse(username: UserName) extends NoStackTrace
  case class InvalidUserOrPassword(username: UserName) extends NoStackTrace
  case object UnsupportedOperation extends NoStackTrace

  case object TokenNotFound extends NoStackTrace

  // --------- user login -----------

  case class LoginUser(
      username: UserNameParam,
      password: PasswordParam
  )

  // --------- admin auth -----------

  @newtype case class ClaimContent(uuid: UUID)

  object ClaimContent {
    implicit val jsonDecoder: Decoder[ClaimContent] =
      Decoder.forProduct1("uuid")(ClaimContent.apply)
  }

} 
Example 22
Source File: brand.scala    From pfps-shopping-cart   with Apache License 2.0 5 votes vote down vote up
package shop.domain

import eu.timepit.refined.types.string.NonEmptyString
import io.estatico.newtype.macros.newtype
import java.util.UUID
import scala.util.control.NoStackTrace

object brand {
  @newtype case class BrandId(value: UUID)

  @newtype case class BrandName(value: String) {
    def toBrand(brandId: BrandId): Brand =
      Brand(brandId, this)
  }

  @newtype case class BrandParam(value: NonEmptyString) {
    def toDomain: BrandName = BrandName(value.value.toLowerCase.capitalize)
  }

  case class Brand(uuid: BrandId, name: BrandName)

  case class InvalidBrand(value: String) extends NoStackTrace
} 
Example 23
Source File: ScalafmtSbtReporter.scala    From sbt-scalafmt   with Apache License 2.0 5 votes vote down vote up
package org.scalafmt.sbt

import java.io.PrintWriter
import java.io.OutputStreamWriter
import java.nio.file.Path

import org.scalafmt.interfaces.ScalafmtReporter
import sbt.internal.util.MessageOnlyException
import sbt.util.Logger

import scala.util.control.NoStackTrace

class ScalafmtSbtReporter(log: Logger, out: OutputStreamWriter)
    extends ScalafmtReporter {
  override def error(file: Path, message: String): Unit = {
    throw new MessageOnlyException(s"$message: $file")
  }

  override def error(file: Path, e: Throwable): Unit = {
    if (e.getMessage != null) {
      error(file, e.getMessage)
    } else {
      throw new FailedToFormat(file.toString, e)
    }
  }

  override def error(file: Path, message: String, e: Throwable): Unit = {
    if (e.getMessage != null) {
      error(file, s"$message: ${e.getMessage()}")
    } else {
      throw new FailedToFormat(file.toString, e)
    }
  }

  override def excluded(file: Path): Unit =
    log.debug(s"file excluded: $file")

  override def parsedConfig(config: Path, scalafmtVersion: String): Unit =
    log.debug(s"parsed config (v$scalafmtVersion): $config")

  override def downloadWriter(): PrintWriter = new PrintWriter(out)
  override def downloadOutputStreamWriter(): OutputStreamWriter = out

  private class FailedToFormat(filename: String, cause: Throwable)
      extends Exception(filename, cause)
      with NoStackTrace
} 
Example 24
Source File: LoggingTestsJournal.scala    From freestyle   with Apache License 2.0 5 votes vote down vote up
package freestyle.tagless

import cats._
import cats.syntax.flatMap._
import cats.syntax.functor._
import freestyle.tagless._
import freestyle.tagless.algebras._
import freestyle.tagless.logging.LoggingM
import journal.Logger
import org.scalatest.{AsyncWordSpec, Matchers}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NoStackTrace

class LoggingTestsJournal extends AsyncWordSpec with Matchers {

  implicit override def executionContext = ExecutionContext.Implicits.global

  case object Cause extends Exception("kaboom") with NoStackTrace

  "Logging Freestyle tagless integration journal" should {

    import cats.instances.future._
    import freestyle.tagless.loggingJVM.journal.implicits._

    "allow a log message to be interleaved inside a program monadic flow" in {

      def program[F[_]: Monad](implicit app: App[F]) =
        for {
          a <- app.nonLogging.x
          _ <- app.loggingM.debug("Debug Message", sourceAndLineInfo = true)
          _ <- app.loggingM.debugWithCause("Debug Message", Cause)
          _ <- app.loggingM.error("Error Message")
          _ <- app.loggingM.errorWithCause("Error Message", Cause)
          _ <- app.loggingM.info("Info Message")
          _ <- app.loggingM.infoWithCause("Info Message", Cause)
          _ <- app.loggingM.warn("Warning Message")
          _ <- app.loggingM.warnWithCause("Warning Message", Cause)
          b <- Monad[F].pure(1)
        } yield a + b

      program[Future] map { _ shouldBe 2 }

    }

    "allow injecting a Logger instance" in {
      def program[F[_]: Monad](implicit app: App[F]) =
        for {
          a <- Monad[F].pure(1)
          _ <- app.loggingM.info("Info Message")
          _ <- app.loggingM.error("Error Message")
          b <- Monad[F].pure(1)
        } yield a + b

      implicit val logger: Logger = journal.Logger("Potatoes")

      program[Future] map { _ shouldBe 2 }
    }
  }
} 
Example 25
Source File: FutureTimeouts.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// 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 26
Source File: MultiFixtureBase.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// 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)
          }
      }
    }
  }

} 
Example 27
Source File: ProgramResource.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.resources

import java.util.concurrent.{Executors, TimeUnit}

import com.daml.logging.ContextualizedLogger
import com.daml.logging.LoggingContext.newLoggingContext
import com.daml.resources.ProgramResource._

import scala.concurrent.duration.{DurationInt, FiniteDuration}
import scala.concurrent.{Await, ExecutionContext}
import scala.util.Try
import scala.util.control.{NoStackTrace, NonFatal}

class ProgramResource[T](
    owner: => ResourceOwner[T],
    tearDownTimeout: FiniteDuration = 10.seconds,
) {
  private val logger = ContextualizedLogger.get(getClass)

  private val executorService = Executors.newCachedThreadPool()

  def run(): Unit = {
    newLoggingContext { implicit logCtx =>
      val resource = {
        implicit val executionContext: ExecutionContext =
          ExecutionContext.fromExecutor(executorService)
        Try(owner.acquire()).fold(Resource.failed, identity)
      }

      def stop(): Unit = {
        Await.result(resource.release(), tearDownTimeout)
        executorService.shutdown()
        executorService.awaitTermination(tearDownTimeout.toMillis, TimeUnit.MILLISECONDS)
        ()
      }

      sys.runtime.addShutdownHook(new Thread(() => {
        try {
          stop()
        } catch {
          case NonFatal(exception) =>
            logger.error("Failed to stop successfully.", exception)
        }
      }))

      // On failure, shut down immediately.
      resource.asFuture.failed.foreach { exception =>
        exception match {
          // The error is suppressed; we don't need to print anything more.
          case _: SuppressedStartupException =>
          case _: StartupException =>
            logger.error(
              s"Shutting down because of an initialization error.\n${exception.getMessage}")
          case NonFatal(_) =>
            logger.error("Shutting down because of an initialization error.", exception)
        }
        sys.exit(1) // `stop` will be triggered by the shutdown hook.
      }(ExecutionContext.global) // Run on the global execution context to avoid deadlock.
    }
  }
}

object ProgramResource {

  trait StartupException extends NoStackTrace {
    self: Exception =>
  }

  trait SuppressedStartupException {
    self: Exception =>
  }
} 
Example 28
Source File: BaseManager.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.core.peer

import java.net.InetSocketAddress

import cats.effect._
import cats.effect.concurrent.Ref
import cats.implicits._
import fs2.io.tcp.Socket
import jbok.codec.rlp.implicits._
import jbok.common.math.N
import jbok.core.config.FullConfig
import jbok.core.ledger.History
import jbok.core.messages.Status
import jbok.core.queue.Queue
import jbok.network.tcp.implicits._
import jbok.network.{Message, Request}

import scala.util.control.NoStackTrace

final case class Incompatible(local: Status, remote: Status) extends NoStackTrace {
  override def toString: String = s"peer incompatible chainId:${local.chainId}/${remote.chainId} genesis:${local.genesisHash.toHex}/${remote.genesisHash.toHex}"
}

abstract class BaseManager[F[_]](config: FullConfig, history: History[F])(implicit F: Concurrent[F]) {
  def inbound: Queue[F, Peer[F], Message[F]]

  val connected: Ref[F, Map[PeerUri, (Peer[F], Socket[F])]] = Ref.unsafe(Map.empty)

  def isConnected(uri: PeerUri): F[Boolean] = connected.get.map(_.get(uri).isDefined)

  def close(uri: PeerUri): F[Unit] =
    connected.get.map(_.get(uri)).flatMap {
      case Some((_, socket)) => socket.endOfOutput >> socket.close
      case _                 => F.unit
    }

  val localStatus: F[Status] =
    for {
      genesis <- history.genesisHeader
      number  <- history.getBestBlockNumber
      td      <- history.getTotalDifficultyByNumber(number).map(_.getOrElse(N(0)))
    } yield Status(history.chainId, genesis.hash, number, td, config.service.uri)

  def handshake(socket: Socket[F]): F[Peer[F]] =
    for {
      localStatus <- localStatus
      request = Request.binary[F, Status](Status.name, localStatus.encoded)
      _            <- socket.writeMessage(request)
      remoteStatus <- socket.readMessage.flatMap(_.as[Status])
      remote       <- socket.remoteAddress.map(_.asInstanceOf[InetSocketAddress])
      peer <- if (!localStatus.isCompatible(remoteStatus)) {
        F.raiseError(Incompatible(localStatus, remoteStatus))
      } else {
        Peer[F](PeerUri.fromTcpAddr(remote), remoteStatus)
      }
    } yield peer

  val seedDisconnects: F[List[PeerUri]] = config.peer.seedUris.filterA(uri => isConnected(uri).map(b => !b))

  val seedConnects: F[List[PeerUri]] = config.peer.seedUris.filterA(uri => isConnected(uri))
} 
Example 29
Source File: ApiMarshallers.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http

import akka.http.scaladsl.marshalling.{Marshaller, PredefinedToEntityMarshallers, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes.{`application/json`, `text/plain`}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, PredefinedFromEntityUnmarshallers, Unmarshaller}
import akka.util.ByteString
import com.wavesplatform.dex.api.http.json.CustomJson
import com.wavesplatform.dex.domain.transaction.ExchangeTransaction
import play.api.libs.json._

import scala.util.control.Exception.nonFatalCatch
import scala.util.control.NoStackTrace

case class PlayJsonException(cause: Option[Throwable] = None, errors: Seq[(JsPath, Seq[JsonValidationError])] = Seq.empty)
    extends IllegalArgumentException(s"JSON parsing errors:\n${errors.mkString("\n")}", cause.orNull)
    with NoStackTrace

trait ApiMarshallers {

  implicit lazy val ExchangeTransactionJsonWrites: Writes[ExchangeTransaction] = Writes(_.json())

  private[this] lazy val jsonStringUnmarshaller =
    Unmarshaller.byteStringUnmarshaller
      .forContentTypes(`application/json`)
      .mapWithCharset {
        case (ByteString.empty, _) => throw Unmarshaller.NoContentException
        case (data, charset)       => data.decodeString(charset.nioCharset.name)
      }

  private[this] lazy val jsonStringMarshaller = Marshaller.stringMarshaller(`application/json`)

  private[this] lazy val customJsonStringMarshaller = Marshaller.stringMarshaller(CustomJson.jsonWithNumbersAsStrings)

  implicit def playJsonUnmarshaller[A](implicit reads: Reads[A]): FromEntityUnmarshaller[A] =
    jsonStringUnmarshaller.map { data =>
      val json = nonFatalCatch.withApply(t => throw PlayJsonException(cause = Some(t)))(Json.parse(data))

      json.validate[A] match {
        case JsSuccess(value, _) => value
        case JsError(errors)     => throw PlayJsonException(errors = errors)
      }
    }

  // preserve support for extracting plain strings from requests
  implicit val stringUnmarshaller: FromEntityUnmarshaller[String] = PredefinedFromEntityUnmarshallers.stringUnmarshaller
  implicit val intUnmarshaller: FromEntityUnmarshaller[Int]       = stringUnmarshaller.map(_.toInt)

  implicit def playJsonMarshaller[A](implicit writes: Writes[A], jsValueToString: JsValue => String = Json.stringify): ToEntityMarshaller[A] =
    Marshaller.oneOf(
      jsonStringMarshaller
        .compose(jsValueToString)
        .compose(writes.writes),
      customJsonStringMarshaller
        .compose(CustomJson.writeValueAsString)
        .compose(writes.writes)
    )

  // preserve support for using plain strings as request entities
  implicit val stringMarshaller = PredefinedToEntityMarshallers.stringMarshaller(`text/plain`)
}

object ApiMarshallers extends ApiMarshallers 
Example 30
Source File: MatcherContext.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.grpc.integration.smart

import cats.{Eval, Id}
import com.wavesplatform.account.{Address, Alias}
import com.wavesplatform.block.Block.BlockId
import com.wavesplatform.block.{Block, BlockHeader}
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.lang.directives.values._
import com.wavesplatform.lang.script.Script
import com.wavesplatform.lang.v1.evaluator.ctx._
import com.wavesplatform.lang.v1.traits.Environment
import com.wavesplatform.lang.{ExecutionError, ValidationError}
import com.wavesplatform.settings.BlockchainSettings
import com.wavesplatform.state.reader.LeaseDetails
import com.wavesplatform.state.{AccountDataInfo, AssetDescription, BalanceSnapshot, Blockchain, DataEntry, InvokeScriptResult, LeaseBalance, Portfolio, TransactionId, VolumeAndFee}
import com.wavesplatform.transaction.assets.exchange.Order
import com.wavesplatform.transaction.lease.LeaseTransaction
import com.wavesplatform.transaction.smart.BlockchainContext
import com.wavesplatform.transaction.transfer.TransferTransaction
import com.wavesplatform.transaction.{Asset, Transaction}
import monix.eval.Coeval
import shapeless.Coproduct

import scala.util.control.NoStackTrace

// Used only for order validation
object MatcherContext {

  def build(version: StdLibVersion, nByte: Byte, inE: Eval[Order], isDApp: Boolean): Either[ExecutionError, EvaluationContext[Environment, Id]] = {
    val in: Coeval[Order] = Coeval.delay(inE.value)
    BlockchainContext
      .build(
        version,
        nByte,
        in.map(o => Coproduct[BlockchainContext.In](o)),
        Coeval.raiseError(new Denied("height")),
        deniedBlockchain,
        isTokenContext = false,
        isContract = isDApp,
        in.map(_.senderPublicKey.toAddress.bytes)
      )
  }

  private class Denied(methodName: String) extends SecurityException(s"An access to the blockchain.$methodName is denied on DEX") with NoStackTrace

  private def kill(methodName: String) = throw new Denied(methodName)

  private val deniedBlockchain = new Blockchain {

    override def settings: BlockchainSettings                                     = kill("settings")
    override def height: Int                                                      = kill("height")
    override def score: BigInt                                                    = kill("score")
    override def blockHeaderAndSize(height: Int): Option[(BlockHeader, Int)]      = kill("blockHeaderAndSize")
    override def blockHeaderAndSize(blockId: ByteStr): Option[(BlockHeader, Int)] = kill("blockHeaderAndSize")
    override def lastBlock: Option[Block]                                         = kill("lastBlock")
    override def carryFee: Long                                                   = kill("carryFee")
    override def blockBytes(height: Int): Option[Array[Byte]]                     = kill("blockBytes")
    override def blockBytes(blockId: ByteStr): Option[Array[Byte]]                = kill("blockBytes")
    override def heightOf(blockId: ByteStr): Option[Int]                          = kill("heightOf")

    
    override def blockReward(height: Int): Option[Long]   = kill("blockReward")
    override def lastBlockReward: Option[Long]            = kill("lastBlockReward")
    override def blockRewardVotes(height: Int): Seq[Long] = kill("blockRewardVotes")
    override def wavesAmount(height: Int): BigInt         = kill("wavesAmount")

    override def accountScriptWithComplexity(address: Address): Option[(Script, Long)]                               = kill("accountScriptWithComplexity")
    override def assetScriptWithComplexity(id: Asset.IssuedAsset): Option[(Script, Long)]                            = kill("assetScriptWithComplexity")
    override def collectActiveLeases(from: Int, to: Int)(filter: LeaseTransaction => Boolean): Seq[LeaseTransaction] = kill("collectActiveLeases")

    override def balanceOnlySnapshots(address: Address, height: Int, assetId: Asset): Option[(Int, Long)] = kill("balanceOnlySnapshots")
  }
} 
Example 31
Source File: Result.scala    From spatial   with MIT License 5 votes vote down vote up
package utils

import scala.util.control.NoStackTrace

case class BackendError(msg: String) extends Exception(msg) with NoStackTrace

sealed trait Result {
  def ==>(func: => Result): Result
  def orElse(result: => Result): Result
  def resolve(): Unit
  def continues: Boolean
}
object Result {
  type Result = utils.Result

  case object Pass extends Result {
    def ==>(func: => Result): Result = this orElse func
    def orElse(result: => Result): Result = this match {
      case Pass => Pass
      case _ => result
    }
    def resolve(): Unit = ()
    def continues: Boolean = true
  }

  case object Fail extends Exception("Test did not pass validation.") with Result with NoStackTrace {
    def ==>(func: => Result): Result = this
    def orElse(result: => Result): Result = this
    def resolve(): Unit = throw this
    def continues: Boolean = false
  }

  case object Unknown extends Exception("Test had no validation checks. (Indeterminate result)") with Result with NoStackTrace {
    def ==>(func: => Result): Result = this orElse func
    def orElse(result: => Result): Result = result
    def resolve(): Unit = throw this
    def continues: Boolean = true
  }

  case class CompileError(t: Throwable) extends Result {
    def ==>(func: => Result): Result = this
    def orElse(result: => Result): Result = this
    def resolve(): Unit = throw t
    def continues: Boolean = false
  }

  case class MakeError(msg: String) extends Exception(msg) with Result with NoStackTrace {
    def ==>(func: => Result): Result = this
    def orElse(result: => Result): Result = this
    def resolve(): Unit = throw this
    def continues: Boolean = false
  }

  case class RunError(msg: String) extends Exception(msg) with Result with NoStackTrace {
    def ==>(func: => Result): Result = this
    def orElse(result: => Result): Result = this
    def resolve(): Unit = throw this
    def continues: Boolean = false
  }


  case class ModelError(msg: String) extends Exception(msg) with Result with NoStackTrace {
    def ==>(func: => Result): Result = this
    def orElse(result: => Result): Result = this
    def resolve(): Unit = throw this
    def continues: Boolean = false
  }
} 
Example 32
Source File: Error.scala    From spatial   with MIT License 5 votes vote down vote up
package argon

import utils.plural

import scala.util.control.NoStackTrace

case class UnhandledException(t: Throwable)
   extends Exception(s"Uncaught exception ${t.getMessage} (${t.getCause})")

case class EarlyStop(stage: String)
   extends Exception(s"Stop after pass $stage was requested.")
      with NoStackTrace

case class CompilerErrors(stage: String, n: Int)
   extends Exception(s"$n compiler ${plural(n,"error")} during pass $stage")
      with NoStackTrace

case class CompilerBugs(stage: String, n: Int)
   extends Exception(s"$n ${plural(n,"bug")} found during $stage")
      with NoStackTrace

case class RequirementFailure(ctx: SrcCtx, msg: String)
   extends Exception("Requirement failure: " + msg)
      with NoStackTrace

case class MissingDataFolder()
   extends Exception("The TEST_DATA_HOME environment variable was required for this test but was unset.")
      with NoStackTrace

case class CompilerTimeout(time: String)
   extends Exception(s"DSL compilation timed out after $time. (Indeterminate result)")
      with NoStackTrace

case class BackendTimeout(pass: String, time: String)
   extends Exception(s"Backend $pass timed out after $time. (Indeterminate result)")
      with NoStackTrace 
Example 33
Source File: KafkaAdminAlgebra.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.kafka.algebras

import cats.effect.concurrent.Ref
import cats.effect.{Async, Concurrent, ContextShift, Resource, Sync}
import cats.implicits._
import fs2.kafka._
import hydra.core.protocol._
import hydra.kafka.util.KafkaUtils.TopicDetails
import org.apache.kafka.clients.admin.NewTopic
import org.apache.kafka.common.errors.UnknownTopicOrPartitionException

import scala.util.control.NoStackTrace


  def deleteTopic(name: String): F[Unit]
}

object KafkaAdminAlgebra {

  type TopicName = String
  final case class Topic(name: TopicName, numberPartitions: Int)

  def live[F[_]: Sync: Concurrent: ContextShift](
      bootstrapServers: String,
  ): F[KafkaAdminAlgebra[F]] = Sync[F].delay {
    new KafkaAdminAlgebra[F] {

      override def describeTopic(name: TopicName): F[Option[Topic]] = {
        getAdminClientResource
          .use(_.describeTopics(name :: Nil))
          .map(_.headOption.map(_._2).map { td =>
            Topic(td.name(), td.partitions().size())
          })
          .recover {
            case _: UnknownTopicOrPartitionException => None
          }
      }

      override def getTopicNames: F[List[TopicName]] =
        getAdminClientResource.use(_.listTopics.names.map(_.toList))

      override def createTopic(name: TopicName, d: TopicDetails): F[Unit] = {
        import scala.collection.JavaConverters._
        val newTopic = new NewTopic(name, d.numPartitions, d.replicationFactor)
          .configs(d.configs.asJava)
        getAdminClientResource.use(_.createTopic(newTopic))
      }

      override def deleteTopic(name: String): F[Unit] =
        getAdminClientResource.use(_.deleteTopic(name))

      private def getAdminClientResource: Resource[F, KafkaAdminClient[F]] = {
        adminClientResource(
          AdminClientSettings.apply.withBootstrapServers(bootstrapServers)
        )
      }
    }
  }

  def test[F[_]: Sync]: F[KafkaAdminAlgebra[F]] =
    Ref[F].of(Map[TopicName, Topic]()).flatMap(getTestKafkaClient[F])

  private[this] def getTestKafkaClient[F[_]: Sync](
      ref: Ref[F, Map[TopicName, Topic]]
  ): F[KafkaAdminAlgebra[F]] = Sync[F].delay {
    new KafkaAdminAlgebra[F] {
      override def describeTopic(name: TopicName): F[Option[Topic]] =
        ref.get.map(_.get(name))

      override def getTopicNames: F[List[TopicName]] =
        ref.get.map(_.keys.toList)

      override def createTopic(
          name: TopicName,
          details: TopicDetails
      ): F[Unit] = {
        val entry = name -> Topic(name, details.numPartitions)
        ref.update(old => old + entry)
      }

      override def deleteTopic(name: String): F[Unit] =
        ref.update(_ - name)
    }
  }

} 
Example 34
Source File: RestRequest.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash
package rest
package raw

import com.avsystem.commons._
import com.avsystem.commons.meta._
import com.avsystem.commons.misc.{AbstractValueEnum, AbstractValueEnumCompanion, EnumCtx}
import com.avsystem.commons.rpc._

import scala.util.control.NoStackTrace


final case class RestParameters(
  @multi @tagged[Path] path: List[PlainValue] = Nil,
  @multi @tagged[Header] headers: IMapping[PlainValue] = IMapping.empty,
  @multi @tagged[Query] query: Mapping[PlainValue] = Mapping.empty,
  @multi @tagged[Cookie] cookies: Mapping[PlainValue] = Mapping.empty
) {
  def append(method: RestMethodMetadata[_], otherParameters: RestParameters): RestParameters =
    RestParameters(
      path ::: method.applyPathParams(otherParameters.path),
      headers ++ otherParameters.headers,
      query ++ otherParameters.query,
      cookies ++ otherParameters.cookies
    )

  def path(values: String*): RestParameters =
    copy(path = path ++ values.iterator.map(PlainValue(_)))

  def header(name: String, value: String): RestParameters =
    copy(headers = headers.append(name, PlainValue(value)))

  def query(name: String, value: String): RestParameters =
    copy(query = query.append(name, PlainValue(value)))

  def cookie(name: String, value: String): RestParameters =
    copy(query = cookies.append(name, PlainValue(value)))
}
object RestParameters {
  final val Empty = RestParameters()
}

final case class HttpErrorException(code: Int, payload: OptArg[String] = OptArg.Empty, cause: Throwable = null)
  extends RuntimeException(s"HTTP ERROR $code${payload.fold("")(p => s": $p")}", cause) with NoStackTrace {
  def toResponse: RestResponse = RestResponse.plain(code, payload)
}

final case class RestRequest(method: HttpMethod, parameters: RestParameters, body: HttpBody) {
  def path(values: String*): RestRequest =
    copy(parameters = parameters.path(values: _*))

  def header(name: String, value: String): RestRequest =
    copy(parameters = parameters.header(name, value))

  def query(name: String, value: String): RestRequest =
    copy(parameters = parameters.query(name, value))

  def cookie(name: String, value: String): RestRequest =
    copy(parameters = parameters.cookie(name, value))
} 
Example 35
Source File: KafkaConfig.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.broker.kafka

import java.util.concurrent.TimeUnit

import akka.actor.ActorSystem
import akka.kafka.CommitterSettings
import com.typesafe.config.Config

import scala.concurrent.duration.FiniteDuration
import scala.concurrent.duration._
import scala.util.control.NoStackTrace

sealed trait KafkaConfig {

  
  def brokers: String
}

object KafkaConfig {
  def apply(conf: Config): KafkaConfig =
    new KafkaConfigImpl(conf.getConfig("lagom.broker.kafka"))

  private final class KafkaConfigImpl(conf: Config) extends KafkaConfig {
    override val brokers: String             = conf.getString("brokers")
    override val serviceName: Option[String] = Some(conf.getString("service-name")).filter(_.nonEmpty)
  }
}

sealed trait ClientConfig {
  def offsetTimeout: FiniteDuration
  def minBackoff: FiniteDuration
  def maxBackoff: FiniteDuration
  def randomBackoffFactor: Double
}

object ClientConfig {
  private[kafka] class ClientConfigImpl(conf: Config) extends ClientConfig {
    val offsetTimeout       = conf.getDuration("offset-timeout", TimeUnit.MILLISECONDS).millis
    val minBackoff          = conf.getDuration("failure-exponential-backoff.min", TimeUnit.MILLISECONDS).millis
    val maxBackoff          = conf.getDuration("failure-exponential-backoff.max", TimeUnit.MILLISECONDS).millis
    val randomBackoffFactor = conf.getDouble("failure-exponential-backoff.random-factor")
  }
}

sealed trait ProducerConfig extends ClientConfig {
  def role: Option[String]
}

object ProducerConfig {
  def apply(conf: Config): ProducerConfig =
    new ProducerConfigImpl(conf.getConfig("lagom.broker.kafka.client.producer"))

  private class ProducerConfigImpl(conf: Config) extends ClientConfig.ClientConfigImpl(conf) with ProducerConfig {
    val role = conf.getString("role") match {
      case ""    => None
      case other => Some(other)
    }
  }
}

sealed trait ConsumerConfig extends ClientConfig {
  def offsetBuffer: Int
  def committerSettings: CommitterSettings
}

object ConsumerConfig {
  val configPath = "lagom.broker.kafka.client.consumer"

  def apply(system: ActorSystem): ConsumerConfig =
    // reads Alpakka defaults from Alpakka Kafka's reference.conf and overwrites with Lagom's values
    new ConsumerConfigImpl(system.settings.config.getConfig(configPath), CommitterSettings(system))

  private final class ConsumerConfigImpl(conf: Config, alpakkaCommitterSettings: CommitterSettings)
      extends ClientConfig.ClientConfigImpl(conf)
      with ConsumerConfig {
    override val offsetBuffer: Int = conf.getInt("offset-buffer")

    override val committerSettings: CommitterSettings = alpakkaCommitterSettings
      .withMaxBatch(conf.getInt("batching-size"))
      .withMaxInterval(conf.getDuration("batching-interval"))
      .withParallelism(conf.getInt("batching-parallelism"))
  }
}

private[lagom] final class NoKafkaBrokersException(serviceName: String)
    extends RuntimeException(s"No Kafka brokers found in service locator for Kafka service name [$serviceName]")
    with NoStackTrace 
Example 36
Source File: LoggingTestsLog4s.scala    From freestyle   with Apache License 2.0 5 votes vote down vote up
package freestyle.tagless

import cats._
import cats.syntax.flatMap._
import cats.syntax.functor._
import freestyle.tagless._
import freestyle.tagless.algebras._
import freestyle.tagless.logging.LoggingM
import journal.Logger
import org.scalatest.{AsyncWordSpec, Matchers}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NoStackTrace

class LoggingTestsLog4s extends AsyncWordSpec with Matchers {

  implicit override def executionContext = ExecutionContext.Implicits.global

  case object Cause extends Exception("kaboom") with NoStackTrace

  "Logging Freestyle tagless integration log4s" should {

    import cats.instances.future._
    import freestyle.tagless.loggingJVM.log4s.implicits._

    "allow a log message to be interleaved inside a program monadic flow" in {

      def program[F[_]: Monad](implicit app: App[F]) =
        for {
          a <- app.nonLogging.x
          _ <- app.loggingM.debug("Debug Message", sourceAndLineInfo = true)
          _ <- app.loggingM.debugWithCause("Debug Message", Cause)
          _ <- app.loggingM.error("Error Message")
          _ <- app.loggingM.errorWithCause("Error Message", Cause)
          _ <- app.loggingM.info("Info Message")
          _ <- app.loggingM.infoWithCause("Info Message", Cause)
          _ <- app.loggingM.warn("Warning Message")
          _ <- app.loggingM.warnWithCause("Warning Message", Cause)
          b <- Monad[F].pure(1)
        } yield a + b

      program[Future] map { _ shouldBe 2 }

    }

    "allow injecting a Logger instance" in {
      def program[F[_]: Monad](implicit app: App[F]) =
        for {
          a <- Monad[F].pure(1)
          _ <- app.loggingM.info("Info Message")
          _ <- app.loggingM.error("Error Message")
          b <- Monad[F].pure(1)
        } yield a + b

      implicit val logger: Logger = journal.Logger("Potatoes")

      program[Future] map { _ shouldBe 2 }
    }
  }
} 
Example 37
Source File: LoggingTestsJournal.scala    From freestyle   with Apache License 2.0 5 votes vote down vote up
package freestyle.free

import cats.instances.future._
import cats.{Id, Monad}
import freestyle.free.implicits._
import freestyle.free.loggingJVM.implicits._
import org.scalatest.{AsyncWordSpec, Matchers}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NoStackTrace

class LoggingTestsJournal extends AsyncWordSpec with Matchers {

  implicit override def executionContext = ExecutionContext.Implicits.global

  import algebras._

  "Logging Freestyle free integration journal" should {

    case object Cause extends Exception("kaboom") with NoStackTrace

    "allow a log message to be interleaved inside a program monadic flow" in {
      val program = for {
        a <- app.nonLogging.x
        _ <- app.loggingM.debug("Debug Message", sourceAndLineInfo = true)
        _ <- app.loggingM.debugWithCause("Debug Message", Cause)
        _ <- app.loggingM.error("Error Message")
        _ <- app.loggingM.errorWithCause("Error Message", Cause)
        _ <- app.loggingM.info("Info Message")
        _ <- app.loggingM.infoWithCause("Info Message", Cause)
        _ <- app.loggingM.warn("Warning Message")
        _ <- app.loggingM.warnWithCause("Warning Message", Cause)
        b <- FreeS.pure(1)
      } yield a + b
      program.interpret[Future] map { _ shouldBe 2 }
    }

    "not depend on MonadError, thus allowing use of Monads without MonadError, like Id, for test algebras" in {
      val program = for {
        a <- app.nonLogging.x
        _ <- app.loggingM.info("Info Message")
        _ <- app.loggingM.infoWithCause("Info Message", Cause)
        b <- FreeS.pure(1)
      } yield a + b
      program.interpret[TestAlgebra].run("configHere") shouldBe 2
    }

    "allow injecting a Logger instance" in {
      val program = for {
        a <- FreeS.pure(1)
        _ <- app.loggingM.info("Info Message")
        _ <- app.loggingM.error("Error Message")
        b <- FreeS.pure(1)
      } yield a + b

      implicit val logger = journal.Logger("Potatoes")

      program
        .interpret[TestAlgebra]
        .run("configHere") shouldEqual 2
    }
  }
} 
Example 38
Source File: LoggingTestsLog4s.scala    From freestyle   with Apache License 2.0 5 votes vote down vote up
package freestyle.free

import cats.instances.future._
import cats.{Id, Monad}
import freestyle.free.implicits._
import freestyle.free.loggingJVM.implicits._
import org.scalatest.{AsyncWordSpec, Matchers}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NoStackTrace

class LoggingTestsLog4s extends AsyncWordSpec with Matchers {

  implicit override def executionContext = ExecutionContext.Implicits.global

  import algebras._

  "Logging Freestyle free integration log4s" should {

    case object Cause extends Exception("kaboom") with NoStackTrace

    "allow a log message to be interleaved inside a program monadic flow" in {
      val program = for {
        a <- app.nonLogging.x
        _ <- app.loggingM.debug("Debug Message", sourceAndLineInfo = true)
        _ <- app.loggingM.debugWithCause("Debug Message", Cause)
        _ <- app.loggingM.error("Error Message")
        _ <- app.loggingM.errorWithCause("Error Message", Cause)
        _ <- app.loggingM.info("Info Message")
        _ <- app.loggingM.infoWithCause("Info Message", Cause)
        _ <- app.loggingM.warn("Warning Message")
        _ <- app.loggingM.warnWithCause("Warning Message", Cause)
        b <- FreeS.pure(1)
      } yield a + b
      program.interpret[Future] map { _ shouldBe 2 }
    }

    "not depend on MonadError, thus allowing use of Monads without MonadError, like Id, for test algebras" in {
      val program = for {
        a <- app.nonLogging.x
        _ <- app.loggingM.info("Info Message")
        _ <- app.loggingM.infoWithCause("Info Message", Cause)
        b <- FreeS.pure(1)
      } yield a + b
      program.interpret[TestAlgebra].run("configHere") shouldBe 2
    }

    "allow injecting a Logger instance" in {
      val program = for {
        a <- FreeS.pure(1)
        _ <- app.loggingM.info("Info Message")
        _ <- app.loggingM.error("Error Message")
        b <- FreeS.pure(1)
      } yield a + b

      implicit val logger = journal.Logger("Potatoes")

      program
        .interpret[TestAlgebra]
        .run("configHere") shouldEqual 2
    }
  }
} 
Example 39
Source File: LoggingTests.scala    From freestyle   with Apache License 2.0 5 votes vote down vote up
package freestyle.tagless

import cats.{Applicative, Monad}
import cats.syntax.flatMap._
import cats.syntax.functor._
import freestyle.tagless.algebras._
import org.scalatest.{AsyncWordSpec, Matchers}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NoStackTrace

class LoggingTests extends AsyncWordSpec with Matchers {

  import slogging._

  LoggerConfig.factory = FilterLoggerFactory()
  LoggerConfig.level = LogLevel.TRACE

  FilterLogger.filter = {
    // use PrintLogger for all trace statements from sources starting with "foo.bar"
    case (LogLevel.TRACE, source) if source.startsWith("foo.bar") => PrintLogger
    // ignore all other trace statements
    case (LogLevel.TRACE, _) => NullLogger
    // log all other levels
    case _ => PrintLogger
  }

  implicit override def executionContext = ExecutionContext.Implicits.global

  case object Cause extends Exception("kaboom") with NoStackTrace

  "Logging Freestyle tagless integration" should {

    import cats.instances.future._
    import freestyle.tagless.loggingJS.implicits._

    "allow a log message to be interleaved inside a program monadic flow" in {
      def program[M[_]: Monad](implicit app: App[M]) =
        for {
          a <- app.nonLogging.x
          _ <- app.loggingM.debug("Debug Message", sourceAndLineInfo = true)
          _ <- app.loggingM.debugWithCause("Debug Message", Cause)
          _ <- app.loggingM.error("Error Message")
          _ <- app.loggingM.errorWithCause("Error Message", Cause)
          _ <- app.loggingM.info("Info Message")
          _ <- app.loggingM.infoWithCause("Info Message", Cause)
          _ <- app.loggingM.warn("Warning Message")
          _ <- app.loggingM.warnWithCause("Warning Message", Cause)
          b <- Applicative[M].pure(1)
        } yield a + b
      program[Future] map { _ shouldBe 2 }
    }

    "not depend on MonadError, thus allowing use of Monads without MonadError, like Id, for test algebras" in {
      def program[M[_]: Monad](implicit app: App[M]) =
        for {
          a <- app.nonLogging.x
          _ <- app.loggingM.info("Info Message")
          _ <- app.loggingM.infoWithCause("Info Message", Cause)
          b <- Applicative[M].pure(1)
        } yield a + b
      program[TestAlgebra].run("configHere") shouldBe 2
    }

  }
} 
Example 40
Source File: LoggingTests.scala    From freestyle   with Apache License 2.0 5 votes vote down vote up
package freestyle.free

import cats.instances.future._
import freestyle.free.implicits._
import freestyle.free.loggingJS.implicits._
import org.scalatest.{AsyncWordSpec, Matchers}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NoStackTrace

class LoggingTests extends AsyncWordSpec with Matchers {

  import slogging._

  LoggerConfig.factory = FilterLoggerFactory()
  LoggerConfig.level = LogLevel.TRACE

  FilterLogger.filter = {
    // use PrintLogger for all trace statements from sources starting with "foo.bar"
    case (LogLevel.TRACE, source) if source.startsWith("foo.bar") => PrintLogger
    // ignore all other trace statements
    case (LogLevel.TRACE, _) => NullLogger
    // log all other levels
    case _ => PrintLogger
  }

  implicit override def executionContext = ExecutionContext.Implicits.global

  import algebras._

  "Logging Freestyle free integration" should {

    case object Cause extends Exception("kaboom") with NoStackTrace

    "allow a log message to be interleaved inside a program monadic flow" in {
      val program = for {
        a <- app.nonLogging.x
        _ <- app.loggingM.debug("Debug Message", sourceAndLineInfo = true)
        _ <- app.loggingM.debugWithCause("Debug Message", Cause)
        _ <- app.loggingM.error("Error Message")
        _ <- app.loggingM.errorWithCause("Error Message", Cause)
        _ <- app.loggingM.info("Info Message")
        _ <- app.loggingM.infoWithCause("Info Message", Cause)
        _ <- app.loggingM.warn("Warning Message")
        _ <- app.loggingM.warnWithCause("Warning Message", Cause)
        b <- FreeS.pure(1)
      } yield a + b
      program.interpret[Future] map { _ shouldBe 2 }
    }

    "not depend on MonadError, thus allowing use of Monads without MonadError, like Id, for test algebras" in {
      val program = for {
        a <- app.nonLogging.x
        _ <- app.loggingM.info("Info Message")
        _ <- app.loggingM.infoWithCause("Info Message", Cause)
        b <- FreeS.pure(1)
      } yield a + b
      program.interpret[TestAlgebra].run("configHere") shouldBe 2
    }

  }
} 
Example 41
Source File: HttpJsonClient.scala    From scala-steward   with Apache License 2.0 5 votes vote down vote up
package org.scalasteward.core.util

import cats.effect.Sync
import cats.implicits._
import io.circe.{Decoder, Encoder}
import org.http4s.Method.{GET, POST}
import org.http4s.circe.{jsonEncoderOf, jsonOf}
import org.http4s.client.Client
import org.http4s._
import scala.util.control.NoStackTrace

final class HttpJsonClient[F[_]: Sync](implicit
    client: Client[F]
) {
  type ModReq = Request[F] => F[Request[F]]

  def get[A: Decoder](uri: Uri, modify: ModReq): F[A] =
    request[A](GET, uri, modify)

  def post[A: Decoder](uri: Uri, modify: ModReq): F[A] =
    request[A](POST, uri, modify)

  def postWithBody[A: Decoder, B: Encoder](uri: Uri, body: B, modify: ModReq): F[A] =
    post[A](uri, modify.compose(_.withEntity(body)(jsonEncoderOf[F, B])))

  private def request[A: Decoder](method: Method, uri: Uri, modify: ModReq): F[A] =
    client.expectOr[A](modify(Request[F](method, uri)))(resp =>
      toUnexpectedResponse(uri, method, resp)
    )(jsonOf[F, A].transform(_.leftMap(failure => JsonParseError(uri, method, failure))))

  private def toUnexpectedResponse(
      uri: Uri,
      method: Method,
      response: Response[F]
  ): F[Throwable] = {
    val body = response.body.through(fs2.text.utf8Decode).compile.string
    body.map(UnexpectedResponse(uri, method, response.headers, response.status, _))
  }
}

final case class JsonParseError(
    uri: Uri,
    method: Method,
    underlying: DecodeFailure
) extends DecodeFailure {
  val message = s"uri: $uri\nmethod: $method\nmessage: ${underlying.message}"
  override def cause: Option[Throwable] = underlying.some
  override def toHttpResponse[F[_]](httpVersion: HttpVersion): Response[F] =
    underlying.toHttpResponse(httpVersion)
}

final case class UnexpectedResponse(
    uri: Uri,
    method: Method,
    headers: Headers,
    status: Status,
    body: String
) extends RuntimeException
    with NoStackTrace {
  override def getMessage: String =
    s"uri: $uri\nmethod: $method\nstatus: $status\nheaders: $headers\nbody: $body"
} 
Example 42
Source File: ResultSetSpec.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal.eventual.cassandra

import cats.effect.concurrent.Ref
import cats.effect.{Concurrent, IO}
import cats.implicits._
import com.evolutiongaming.kafka.journal.IOSuite._
import org.scalatest.funsuite.AsyncFunSuite
import org.scalatest.matchers.should.Matchers

import scala.util.control.NoStackTrace


class ResultSetSpec extends AsyncFunSuite with Matchers {

  for {
    size      <- 0 to 5
    take      <- 1 to 5
    fetchSize <- 1 to 5
  } {
    test(s"size: $size, take: $take, fetchSize: $fetchSize") {
      testF[IO](size = size, take = take, fetchSize = fetchSize).run()
    }
  }

  private def testF[F[_] : Concurrent](size: Int, take: Int, fetchSize: Int) = {

    type Row = Int

    val all = (0 until size).toList

    for {
      fetches <- Ref[F].of(0)
      left    <- Ref[F].of(all)
      fetched <- Ref[F].of(List.empty[Row])
      next     = fetched.modify { rows => (List.empty, rows) }
      fetch    = for {
        _        <- fetches.update(_ + 1)
        toFetch1 <- left.get
        result   <- {
          if (toFetch1.isEmpty) ().pure[F]
          else for {
            taken <- left.modify { rows =>
              val fetched = rows.take(fetchSize)
              val left = rows.drop(fetchSize)
              (left, fetched)
            }
            _    <- fetched.set(taken)
          } yield {}
        }
      } yield result
      resultSet   = ResultSet[F, Row](fetch, left.get.map(_.isEmpty), next)
      rows       <- resultSet.take(take.toLong).toList
      fetches    <- fetches.get
    } yield {
      rows shouldEqual all.take(take)

      if (take >= size) {
        val expected = {
          val n = size / fetchSize
          if (size % fetchSize == 0) n else n + 1
        }
        fetches shouldEqual expected
      }
    }
  }

  case object NotImplemented extends RuntimeException with NoStackTrace
} 
Example 43
Source File: CassandraHealthCheckSpec.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal.eventual.cassandra

import cats.effect.{IO, Resource}
import cats.implicits._
import com.evolutiongaming.catshelper.Log
import com.evolutiongaming.kafka.journal.IOSuite._
import org.scalatest.funsuite.AsyncFunSuite
import org.scalatest.matchers.should.Matchers

import scala.concurrent.duration._
import scala.util.control.NoStackTrace

class CassandraHealthCheckSpec extends AsyncFunSuite with Matchers {

  test("CassandraHealthCheck") {
    val error = (new RuntimeException with NoStackTrace).raiseError[IO, Unit]
    val healthCheck = CassandraHealthCheck.of[IO](
      initial = 0.seconds,
      interval = 1.second,
      statement = Resource.pure[IO, IO[Unit]](error),
      log = Log.empty[IO])
    val result = for {
      error <- healthCheck.use { _.error.untilDefinedM }
    } yield {
      error shouldEqual error
    }
    result.run()
  }
} 
Example 44
Source File: ReplicatorSpec.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal.replicator

import cats.effect.{IO, Resource}
import cats.implicits._
import com.evolutiongaming.catshelper.LogOf
import com.evolutiongaming.kafka.journal.replicator.Replicator.Consumer
import com.evolutiongaming.kafka.journal.IOSuite._
import com.evolutiongaming.skafka.Topic
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AsyncWordSpec

import scala.concurrent.duration._
import scala.util.control.NoStackTrace

class ReplicatorSpec extends AsyncWordSpec with Matchers {

  "Replicator" should {

    "fail if any of replicators failed" in {

      implicit val logOf = LogOf.empty[IO]

      val error = new RuntimeException with NoStackTrace

      val consumer = new Consumer[IO] {
        def topics = Set("journal").pure[IO]
      }

      val start = (_: Topic) => Resource.pure[IO, IO[Unit]](error.raiseError[IO, Unit])
      val result = for {
        result <- Replicator.of(
          Replicator.Config(topicDiscoveryInterval = 0.millis),
          Resource.pure[IO, Consumer[IO]](consumer),
          start).use(identity).attempt
      } yield {
        result shouldEqual error.asLeft
      }

      result.run()
    }
  }
} 
Example 45
Source File: ResourceRef.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal.util

import cats.effect.concurrent.Ref
import cats.effect.implicits._
import cats.effect.{Resource, Sync}
import cats.implicits._

import scala.util.control.NoStackTrace

trait ResourceRef[F[_], A] {

  def get: F[A]

  def set(a: A, release: F[Unit]): F[Unit]

  def set(a: Resource[F, A]): F[Unit]
}

object ResourceRef {

  def of[F[_] : Sync, A](resource: Resource[F, A]): Resource[F, ResourceRef[F, A]] = {

    case class State(a: A, release: F[Unit])

    Resource
      .make {
        for {
          ab           <- resource.allocated
          (a, release)  = ab
          ref          <- Ref[F].of(State(a, release).some)
        } yield ref
      } { ref =>
        ref
          .getAndSet(none)
          .flatMap { _.foldMapM { _.release } }
      }
      .map { ref =>
        new ResourceRef[F, A] {

          def get = {
            ref
              .get
              .flatMap {
                case Some(state) => state.a.pure[F]
                case None        => ResourceReleasedError.raiseError[F, A]
              }
          }

          def set(a: A, release: F[Unit]) = {
            ref
              .modify {
                case Some(state) => (State(a, release).some, state.release )
                case None        => (none, ResourceReleasedError.raiseError[F, Unit])
              }
              .flatten
              .uncancelable
          }

          def set(a: Resource[F, A]) = {
            a
              .allocated
              .flatMap { case (a, release) => set(a, release) }
          }
        }
      }
  }
}

case object ResourceReleasedError extends RuntimeException("Resource released") with NoStackTrace