cats.arrow.FunctionK Scala Examples

The following examples show how to use cats.arrow.FunctionK. 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: MainecoonTestSuite.scala    From mainecoon   with Apache License 2.0 5 votes vote down vote up
package mainecoon.tests

import cats.arrow.FunctionK
import cats.instances.AllInstances
import cats.kernel.Eq
import mainecoon.syntax.AllSyntax
import org.scalacheck.{Arbitrary, Gen}
import org.scalatest.{FunSuite, Matchers}
import org.typelevel.discipline.scalatest.Discipline

import scala.util.Try

class MainecoonTestSuite extends FunSuite with Matchers with Discipline with TestInstances with AllInstances with AllSyntax with cats.syntax.AllSyntax


trait TestInstances {
  implicit val catsDataArbitraryOptionList: Arbitrary[FunctionK[Option, List]] = Arbitrary(Gen.const(λ[FunctionK[Option, List]](_.toList)))
  implicit val catsDataArbitraryListOption: Arbitrary[FunctionK[List, Option]] = Arbitrary(Gen.const(λ[FunctionK[List, Option]](_.headOption)))
  implicit val catsDataArbitraryTryOption: Arbitrary[FunctionK[Try, Option]] = Arbitrary(Gen.const(λ[FunctionK[Try, Option]](_.toOption)))
  implicit val catsDataArbitraryOptionTry: Arbitrary[FunctionK[Option, Try]] = Arbitrary(Gen.const(λ[FunctionK[Option, Try]](o => Try(o.get))))
  implicit val catsDataArbitraryListVector: Arbitrary[FunctionK[List, Vector]] = Arbitrary(Gen.const(λ[FunctionK[List, Vector]](_.toVector)))
  implicit val catsDataArbitraryVectorList: Arbitrary[FunctionK[Vector, List]] = Arbitrary(Gen.const(λ[FunctionK[Vector, List]](_.toList)))

  implicit val eqThrow: Eq[Throwable] = Eq.allEqual
} 
Example 2
Source File: IoAdapt.scala    From http4s-poc-api   with MIT License 5 votes vote down vote up
package external
package library

import cats.arrow.FunctionK
import cats.effect.{Concurrent, ContextShift, IO}
import external.library.IoAdapt.-->
import zio.{Task, ZIO}

import scala.concurrent.Future


  def apply[A]: (=>F[A]) => G[A]

  def functionK: FunctionK[F, G] =
    λ[FunctionK[F, G]](apply(_))
}

private[library] sealed trait IoAdaptInstances {
  implicit def catsIoToZioTask(implicit cc: Concurrent[Task]): IO --> Task =
    new IoAdapt[IO, Task] {
      def apply[A]: (=>IO[A]) => Task[A] =
        io => cc.liftIO(io)
    }

  implicit val futureToZioTask: Future --> Task =
    new IoAdapt[Future, Task] {
      def apply[A]: (=>Future[A]) => Task[A] =
        ft => ZIO.fromFuture(ec => ft.map(identity)(ec))
    }

  implicit def futureToIo(implicit cs: ContextShift[IO]): Future --> IO =
    new IoAdapt[Future, IO] {
      def apply[A]: (=>Future[A]) => IO[A] =
        IO.fromFuture[A] _ compose IO.delay
    }
}

object IoAdapt extends IoAdaptInstances {
  type -->[F[_], G[_]] = IoAdapt[F, G]
} 
Example 3
Source File: FreeMonad.scala    From advanced-scala-code   with Apache License 2.0 5 votes vote down vote up
import scala.io.StdIn
import scalaz.concurrent.Task


trait ActionA[A]
case class ReadAction() extends ActionA[String]
case class WriteAction(output: String) extends ActionA[Unit]

object FreeMonad {
  def main(args: Array[String]) {

    import cats.free.Free
    type ActionF[A] = Free[ActionA, A]

    import cats.free.Free.liftF
    def read(): ActionF[String] = liftF[ActionA, String](ReadAction())
    def write(output: String): ActionF[Unit] = liftF[ActionA, Unit](WriteAction(output))

    val result = for {
      _ <- write("Write your name: ")
      name <- read()
      res <- write(s"Hello $name")
    } yield res
    // result: Free[ActionA, Unit]

    import cats.arrow.FunctionK
    import cats.{Id, Monad}


    val idInterpreter: FunctionK[ActionA, Id] =
      new FunctionK[ActionA, Id] {
      override def apply[A](fa: ActionA[A]): Id[A] = fa match {
        case ReadAction() =>
          val input = StdIn.readLine()
          input
        case WriteAction(output) =>
          println(output)
      }
    }

    def taskInterpreter: FunctionK[ActionA, Task] =
      new FunctionK[ActionA, Task] {
      def apply[A](fa: ActionA[A]): Task[A] = (fa match {
        case ReadAction() => Task.delay {
          val input = StdIn.readLine()
          input
        }
        case WriteAction(output) => Task.delay {
          println(output)
        }
      }).asInstanceOf[Task[A]]
    }

    implicit val taskMonad = new Monad[Task] {
      override def tailRecM[A,B](a: A)(f: A => Task[Either[A,B]]): Task[B] =
        Task.suspend(f(a)).flatMap {
          case Left(continueA) => tailRecM(continueA)(f)
          case Right(b) => Task.now(b)
        }
      override def flatMap[A, B](fa: Task[A])(f: (A) => Task[B]):
        Task[B] = fa.flatMap(f)
      override def pure[A](x: A): Task[A] = Task.now(x)
    }

    result.foldMap(taskInterpreter).unsafePerformSync

  }
} 
Example 4
Source File: Unlift.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu
package lift

import cats.arrow.FunctionK
import cats.data.ReaderT
import cats.{Applicative, Functor, Monad, ~>}
import syntax.funk._
import tofu.syntax.monadic._

trait Lift[F[_], G[_]] {
  def lift[A](fa: F[A]): G[A]

  def liftF: FunctionK[F, G] = funK(lift(_))
}

object Lift {
  def apply[F[_], G[_]](implicit lift: Lift[F, G]): Lift[F, G] = lift
  def trans[F[_], G[_]](implicit lift: Lift[F, G]): F ~> G     = lift.liftF

  private val liftIdentityAny: Lift[AnyK, AnyK] = new Lift[AnyK, AnyK] {
    def lift[A](fa: Any): Any = fa
  }
  implicit def liftIdentity[F[_]]: Lift[F, F]   = liftIdentityAny.asInstanceOf[Lift[F, F]]

  private val liftReaderTAny: Lift[AnyK, ReaderT[AnyK, Any, *]] = {
    type RT[a] = ReaderT[AnyK, Any, a]
    new Lift[AnyK, RT] {
      def lift[A](fa: Any): RT[A] = ReaderT.liftF(fa)
    }
  }
  implicit def liftReaderT[F[_], R]: Lift[F, ReaderT[F, R, *]] = liftReaderTAny.asInstanceOf[Lift[F, ReaderT[F, R, *]]]

  def byIso[F[_], G[_]](iso: IsoK[F, G]): Lift[F, G] =
    new Lift[F, G] {
      def lift[A](fa: F[A]): G[A] = iso.to(fa)
    }
}


trait Unlift[F[_], G[_]] extends Lift[F, G] {
  self =>
  def lift[A](fa: F[A]): G[A]
  def unlift: G[G ~> F]

  def subIso(implicit G: Functor[G]): G[IsoK[F, G]] =
    unlift.map(gf =>
      new IsoK[F, G] {
        def to[A](fa: F[A]): G[A]   = self.lift(fa)
        def from[A](ga: G[A]): F[A] = gf(ga)
      }
    )

  def andThen[H[_]: Monad](ugh: Unlift[G, H]): Unlift[F, H] =
    new Unlift[F, H] {
      def lift[A](fa: F[A]): H[A] = ugh.lift(self.lift(fa))
      def unlift: H[H ~> F]       =
        for {
          tfg <- ugh.lift(self.unlift)
          tgh <- ugh.unlift
        } yield tfg compose tgh
    }
}

object Unlift {
  def apply[F[_], G[_]](implicit unlift: Unlift[F, G]): Unlift[F, G] = unlift

  implicit def unliftIdentity[F[_]: Applicative]: Unlift[F, F] = new Unlift[F, F] {
    def lift[A](fa: F[A]): F[A] = fa
    def unlift: F[F ~> F]       = FunctionK.id[F].pure[F]
  }

  implicit def unliftReaderT[F[_]: Applicative, R]: Unlift[F, ReaderT[F, R, *]] = {
    type RT[a] = ReaderT[F, R, a]
    new Unlift[F, RT] {
      def lift[A](fa: F[A]): RT[A] = ReaderT.liftF(fa)
      def unlift: RT[RT ~> F]      = ReaderT(r => funK[RT, F](_.run(r)).pure[F])
    }
  }

  def byIso[F[_], G[_]: Applicative](iso: IsoK[F, G]): Unlift[F, G] =
    new Unlift[F, G] {
      def lift[A](fa: F[A]): G[A] = iso.to(fa)
      def unlift: G[G ~> F]       = iso.fromF.pure[G]
    }
} 
Example 5
Source File: EnvInstances.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu.env

import cats.arrow.{ArrowChoice, FunctionK, Profunctor}
import cats.effect.IO
import cats.{Applicative, Monad, Parallel, ~>}
import monix.eval.{Task, TaskLift}
import monix.execution.Scheduler
import tofu.lift.{UnliftIO, UnsafeExecFuture}
import tofu.optics.Contains
import tofu.syntax.funk._

import scala.concurrent.Future

private[env] trait EnvInstances {
  self: Env.type =>

  private object anyEnvInstance extends EnvFunctorstance[Any]

  final implicit def envInstance[E]: EnvFunctorstance[E] = anyEnvInstance.asInstanceOf[EnvFunctorstance[E]]

  private object envParallelInstance extends Applicative[Env[Any, *]] {
    override def pure[A](x: A): Env[Any, A]                                                   = Env.pure(x)
    override def ap[A, B](ff: Env[Any, A => B])(fa: Env[Any, A]): Env[Any, B]                 =
      Env.parMap2(ff, fa)(_.apply(_))
    override def map2[A, B, Z](fa: Env[Any, A], fb: Env[Any, B])(f: (A, B) => Z): Env[Any, Z] =
      Env.parMap2(fa, fb)(f)
    override val unit: Env[Any, Unit]                                                         = Env.unit
    override def map[A, B](fa: Env[Any, A])(f: A => B): Env[Any, B]                           = fa.map(f)
    override def replicateA[A](n: Int, fa: Env[Any, A]): Env[Any, List[A]]                    =
      fa.mapTask(t => Task.parSequence(Iterable.fill(n)(t)).map(_.toList))
  }

  private object anyEnvParallelInstance extends Parallel[Env[Any, *]] {
    type F[a] = Env[Any, a]
    override def applicative: Applicative[Env[Any, *]]    = envParallelInstance
    override def monad: Monad[Env[Any, *]]                = anyEnvInstance
    override val sequential: ~>[Env[Any, *], Env[Any, *]] = FunctionK.id
    override val parallel: ~>[Env[Any, *], Env[Any, *]]   = FunctionK.id
  }

  final implicit def envParallelInstance[E]: Parallel[Env[E, *]] =
    anyEnvParallelInstance.asInstanceOf[Parallel[Env[E, *]]]

  final implicit val envProfuctorInstance: Profunctor[Env] with ArrowChoice[Env] =
    new Profunctor[Env] with ArrowChoice[Env] {
      override def choose[A, B, C, D](f: Env[A, C])(g: Env[B, D]): Env[Either[A, B], Either[C, D]] =
        Env {
          case Left(a)  => f.run(a).map(Left(_))
          case Right(b) => g.run(b).map(Right(_))
        }

      override def lift[A, B](f: A => B): Env[A, B]                                   = Env(a => Task.pure(f(a)))
      override def first[A, B, C](fa: Env[A, B]): Env[(A, C), (B, C)]                 =
        fa.first[C]
      override def second[A, B, C](fa: Env[A, B]): Env[(C, A), (C, B)]                =
        fa.second[C]
      override def compose[A, B, C](f: Env[B, C], g: Env[A, B]): Env[A, C]            =
        f.compose(g)
      override def rmap[A, B, C](fab: Env[A, B])(f: B => C): Env[A, C]                =
        fab.map(f)
      override def lmap[A, B, C](fab: Env[A, B])(f: C => A): Env[C, B]                =
        fab.localP(f)
      override def id[A]: Env[A, A]                                                   = Env.context
      override def dimap[A, B, C, D](fab: Env[A, B])(f: C => A)(g: B => D): Env[C, D] = fab.dimap(f)(g)
      override def split[A, B, C, D](f: Env[A, B], g: Env[C, D]): Env[(A, C), (B, D)] =
        f.split(g)
      override def left[A, B, C](fab: Env[A, B]): Env[Either[A, C], Either[B, C]]     = fab.left[C]
      override def right[A, B, C](fab: Env[A, B]): Env[Either[C, A], Either[C, B]]    = fab.right[C]
      override def choice[A, B, C](f: Env[A, C], g: Env[B, C]): Env[Either[A, B], C]  =
        f.choice(g)
      override def merge[A, B, C](f: Env[A, B], g: Env[A, C]): Env[A, (B, C)]         =
        Env.parZip2(f, g)
    }

  final implicit def envUnliftSubContext[E, E1: E Contains *]: EnvUnliftSubContext[E, E1] = new EnvUnliftSubContext

  def envUnsafeExecFuture[E](implicit sc: Scheduler): UnsafeExecFuture[Env[E, *]] =
    new UnsafeExecFuture[Env[E, *]] {
      def lift[A](fa: Future[A]): Env[E, A]   = Env.fromFuture(fa)
      def unlift: Env[E, Env[E, *] ~> Future] = Env.fromFunc(r => makeFunctionK(_.run(r).runToFuture))
    }

  implicit def envUnliftIO[E](implicit toIO: TaskLift[IO]): UnliftIO[Env[E, *]] = new UnliftIO[Env[E, *]] {
    def lift[A](fa: IO[A]): Env[E, A]   = Env.fromIO(fa)
    def unlift: Env[E, Env[E, *] ~> IO] = Env.fromFunc(r => funK(_.run(r).to[IO]))
  }
} 
Example 6
Source File: data.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu

import cats.Functor
import cats.arrow.FunctionK
import scala.annotation.unchecked.{uncheckedVariance => uv}
import tofu.compat.uv212

package object data {
  type PArray[+A]                   = PArray.Type[A]
  type ICalc[-R, S, +E, +A]         = Calc[R, S, S, E, A]
  type Embedded[+F[+_], +G[+_], +A] = Embedded.T[F, G, A]
  type ∘[+F[+_], +G[+_], +A]        = Embedded.T[F, G, A]
  type Flux[+F[_], +G[_], +A]       = Flux.FluxRepr[F, G, A]
  type Identity[+A]                 = A
  type Nothing1 <: Nothing
  type NothingT[+A]                 = Nothing

  val CalcM: tofu.data.calc.CalcM.type = tofu.data.calc.CalcM
  val CalcT: tofu.data.calc.CalcT.type = tofu.data.calc.CalcT

  type CalcM[+F[+_, +_], -R, -SI, +SO, +E, +A] = tofu.data.calc.CalcM[F, R, SI, SO, E, A]
  type ICalcM[+F[+_, +_], -R, S, +E, +A]       = CalcM[F, R, S, S, E, A]

  type UnaryM[+F[+_], +E, +A]              = F[A]
  type CalcT[+F[+_], -R, -SI, +SO, +E, +A] = CalcM[Lambda[(`+x`, `+y`) => F[y]], R, SI, SO, E, A]
  type ICalcT[+F[+_], -R, S, +E, +A]       = CalcT[F, R, S, S, E, A]

  implicit val nothingFunctor: Functor[Nothing] = new Functor[Nothing] {
    def map[A, B](fa: Nothing)(f: A => B): Nothing = fa
  }

  type FunK[-F[_], +G[_]] = FunctionK[F @uv, G @uv]
} 
Example 7
Source File: HikariDataSourceTransactor.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.master.store

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

import cats.arrow.FunctionK
import cats.effect._
import com.zaxxer.hikari.{HikariConfig, HikariDataSource}
import doobie.util.transactor.Transactor
import doobie.util.transactor.Transactor.Aux
import io.hydrosphere.mist.utils.Logger

import scala.concurrent.ExecutionContext



  def shutdown(): Unit = {
    if (!ds.isClosed) {
      logger.info("Closing Hikari data source")
      ds.close()
    } else {
      logger.warn("Hikari datasource had not been properly initialized before closing")
    }

    shutdownExecutorService(awaitShutdown, ce, "connections EC")
    shutdownExecutorService(awaitShutdown, te, "tx EC")
  }
} 
Example 8
Source File: ContextualLoggerSpec.scala    From odin   with Apache License 2.0 5 votes vote down vote up
package io.odin.loggers

import cats.arrow.FunctionK
import cats.data.{ReaderT, WriterT}
import cats.effect.{Clock, IO, Timer}
import cats.instances.list._
import cats.mtl.instances.all._
import io.odin.syntax._
import io.odin.{LoggerMessage, OdinSpec}

import scala.concurrent.duration.{FiniteDuration, TimeUnit}

class ContextualLoggerSpec extends OdinSpec {
  type W[A] = WriterT[IO, List[LoggerMessage], A]
  type F[A] = ReaderT[W, Map[String, String], A]

  implicit val hasContext: HasContext[Map[String, String]] = (env: Map[String, String]) => env
  implicit val timer: Timer[IO] = new Timer[IO] {
    def clock: Clock[IO] = new Clock[IO] {
      def realTime(unit: TimeUnit): IO[Long] = IO.pure(0)

      def monotonic(unit: TimeUnit): IO[Long] = IO.pure(0)
    }

    def sleep(duration: FiniteDuration): IO[Unit] = ???
  }

  private val logger = new WriterTLogger[IO].mapK(λ[FunctionK[W, F]](ReaderT.liftF(_))).withContext

  checkAll("ContContextLogger", LoggerTests[F](logger, reader => reader.run(Map()).written.unsafeRunSync()).all)

  it should "pick up context from F[_]" in {
    forAll { (loggerMessage: LoggerMessage, ctx: Map[String, String]) =>
      val List(written) = logger.log(loggerMessage).apply(ctx).written.unsafeRunSync()
      written.context shouldBe loggerMessage.context ++ ctx
    }
  }

  it should "embed context in all messages" in {
    forAll { (msgs: List[LoggerMessage], ctx: Map[String, String]) =>
      val written = logger.log(msgs).apply(ctx).written.unsafeRunSync()
      written.map(_.context) shouldBe msgs.map(_.context ++ ctx)
    }
  }
} 
Example 9
Source File: package.scala    From odin   with Apache License 2.0 5 votes vote down vote up
package io.odin

import _root_.zio._
import _root_.zio.interop.catz._
import _root_.zio.interop.catz.implicits._
import cats.arrow.FunctionK
import cats.~>
import io.odin.formatter.Formatter

import scala.concurrent.duration._

package object zio {

  
  def asyncFileLogger(
      fileName: String,
      formatter: Formatter = Formatter.default,
      timeWindow: FiniteDuration = 1.second,
      maxBufferSize: Option[Int] = None,
      minLevel: Level = Level.Trace
  ): Managed[LoggerError, Logger[IO[LoggerError, *]]] =
    ZManaged
      .fromEffect(Task.concurrentEffect)
      .flatMap { implicit F =>
        io.odin.asyncFileLogger[Task](fileName, formatter, timeWindow, maxBufferSize, minLevel).toManaged
      }
      .mapError(LoggerError.apply)
      .map(_.mapK(fromTask))

  private[odin] val fromTask: Task ~> IO[LoggerError, *] =
    λ[FunctionK[Task, IO[LoggerError, *]]](_.mapError(LoggerError.apply))
} 
Example 10
Source File: CatsTaglessInstances.scala    From sup   with Apache License 2.0 5 votes vote down vote up
package sup

import cats.Eq
import cats.arrow.FunctionK
import org.scalacheck.{Arbitrary, Gen}

import scala.util.Try

object CatsTaglessInstances {

  implicit val catsDataArbitraryOptionList: Arbitrary[FunctionK[Option, List]] = Arbitrary(
    Gen.const(λ[FunctionK[Option, List]](_.toList))
  )

  implicit val catsDataArbitraryListOption: Arbitrary[FunctionK[List, Option]] = Arbitrary(
    Gen.const(λ[FunctionK[List, Option]](_.headOption))
  )

  implicit val catsDataArbitraryTryOption: Arbitrary[FunctionK[Try, Option]] = Arbitrary(
    Gen.const(λ[FunctionK[Try, Option]](_.toOption))
  )

  implicit val catsDataArbitraryOptionTry: Arbitrary[FunctionK[Option, Try]] = Arbitrary(
    Gen.const(λ[FunctionK[Option, Try]](o => Try(o.get)))
  )

  implicit val catsDataArbitraryListVector: Arbitrary[FunctionK[List, Vector]] = Arbitrary(
    Gen.const(λ[FunctionK[List, Vector]](_.toVector))
  )

  implicit val catsDataArbitraryVectorList: Arbitrary[FunctionK[Vector, List]] = Arbitrary(
    Gen.const(λ[FunctionK[Vector, List]](_.toList))
  )

  implicit val eqThrow: Eq[Throwable] = Eq.fromUniversalEquals
} 
Example 11
Source File: FunctorKLaws.scala    From mainecoon   with Apache License 2.0 5 votes vote down vote up
package mainecoon
package laws

import cats.arrow.FunctionK
import cats.laws._
import syntax.all._
import cats.~>

trait FunctorKLaws[F[_[_]]] extends InvariantKLaws[F]{
  implicit def F: FunctorK[F]

  def covariantIdentity[A[_]](fg: F[A]): IsEq[F[A]] =
    fg.mapK(FunctionK.id[A]) <-> fg

  def covariantComposition[A[_], B[_], C[_]](fa: F[A], f: A ~> B, g: B ~> C): IsEq[F[C]] =
    fa.mapK(f).mapK(g) <-> fa.mapK(f andThen g)

}

object FunctorKLaws {
  def apply[F[_[_]]](implicit ev: FunctorK[F]): FunctorKLaws[F] =
    new FunctorKLaws[F] { def F: FunctorK[F] = ev }
} 
Example 12
Source File: ContravariantKLaws.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless.laws

import cats.arrow.FunctionK
import cats.laws._
import cats.tagless.ContravariantK
import cats.tagless.syntax.contravariantK._
import cats.~>

trait ContravariantKLaws[F[_[_]]] extends InvariantKLaws[F]{
  implicit def F: ContravariantK[F]

  def contravariantIdentity[A[_]](fg: F[A]): IsEq[F[A]] =
    fg.contramapK(FunctionK.id[A]) <-> fg

  def contravariantComposition[A[_], B[_], C[_]](fa: F[A], f: B ~> A, g: C ~> B): IsEq[F[C]] =
    fa.contramapK(f).contramapK(g) <-> fa.contramapK(f compose g)
}

object ContravariantKLaws {
  def apply[F[_[_]]](implicit ev: ContravariantK[F]): ContravariantKLaws[F] =
    new ContravariantKLaws[F] { def F = ev }
} 
Example 13
Source File: FunctorKLaws.scala    From cats-tagless   with Apache License 2.0 5 votes vote down vote up
package cats.tagless
package laws

import cats.arrow.FunctionK
import cats.laws._
import syntax.all._
import cats.~>

trait FunctorKLaws[F[_[_]]] extends InvariantKLaws[F]{
  implicit def F: FunctorK[F]

  def covariantIdentity[A[_]](fg: F[A]): IsEq[F[A]] =
    fg.mapK(FunctionK.id[A]) <-> fg

  def covariantComposition[A[_], B[_], C[_]](fa: F[A], f: A ~> B, g: B ~> C): IsEq[F[C]] =
    fa.mapK(f).mapK(g) <-> fa.mapK(f andThen g)

}

object FunctorKLaws {
  def apply[F[_[_]]](implicit ev: FunctorK[F]): FunctorKLaws[F] =
    new FunctorKLaws[F] { def F: FunctorK[F] = ev }
} 
Example 14
Source File: ActorSystemRefTest.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package akka.persistence.kafka.journal

import cats.arrow.FunctionK
import cats.effect.{IO, Sync}
import cats.implicits._
import com.evolutiongaming.kafka.journal.ActorSuite
import com.evolutiongaming.kafka.journal.IOSuite._
import org.scalatest.funsuite.AsyncFunSuite
import org.scalatest.matchers.should.Matchers

class ActorSystemRefTest extends AsyncFunSuite with ActorSuite with Matchers {
  import ActorSystemRefTest._

  test("Extension") {
    val result = for {
      ref <- Sync[IO].delay { Extension(actorSystem) }
      ref <- ref.fromFuture[IO].mapK(FunctionK.id).pure[IO]
      a   <- ref.get.start
      _   <- ref.set(0)
      a   <- a.join
      _    = a shouldEqual 0
      a   <- ref.get
      _    = a shouldEqual 0
      a   <- ref.set(0).attempt
      _    = a.isLeft shouldEqual true
    } yield {}
    result.run()
  }
}

object ActorSystemRefTest {
  object Extension extends ActorSystemRef.ExtensionId[Int]
} 
Example 15
Source File: CassandraSync.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal.eventual.cassandra

import cats.arrow.FunctionK
import cats.effect.concurrent.Semaphore
import cats.effect.{Concurrent, Sync, Timer}
import cats.implicits._
import cats.~>
import com.evolutiongaming.cassandra
import com.evolutiongaming.cassandra.sync.AutoCreate
import com.evolutiongaming.kafka.journal.Origin

trait CassandraSync[F[_]] {
  def apply[A](fa: F[A]): F[A]
}

object CassandraSync {

  def empty[F[_]]: CassandraSync[F] = new CassandraSync[F] {
    def apply[A](fa: F[A]) = fa
  }


  def apply[F[_]](implicit F: CassandraSync[F]): CassandraSync[F] = F


  def apply[F[_] : Sync : Timer : CassandraSession](
    config: SchemaConfig,
    origin: Option[Origin],
  ): CassandraSync[F] = {

    val keyspace = config.keyspace
    val autoCreate = if (keyspace.autoCreate) AutoCreate.Table else AutoCreate.None
    apply(
      keyspace = keyspace.name,
      table = config.locksTable,
      autoCreate = autoCreate,
      metadata = origin.map(_.value))
  }

  def apply[F[_] : Sync : Timer : CassandraSession](
    keyspace: String,
    table: String,
    autoCreate: AutoCreate,
    metadata: Option[String],
  ): CassandraSync[F] = {

    new CassandraSync[F] {

      def apply[A](fa: F[A]) = {

        val cassandraSync = cassandra.sync.CassandraSync.of[F](
          session = CassandraSession[F].unsafe,
          keyspace = keyspace,
          table = table,
          autoCreate = autoCreate)

        for {
          cassandraSync <- cassandraSync
          result        <- cassandraSync(id = "kafka-journal", metadata = metadata)(fa)
        } yield result
      }
    }
  }

  def of[F[_] : Concurrent : Timer : CassandraSession](
    config: SchemaConfig,
    origin: Option[Origin]
  ): F[CassandraSync[F]] = {

    for {
      semaphore <- Semaphore[F](1)
    } yield {
      val cassandraSync = apply[F](config, origin)
      val serial = new (F ~> F) {
        def apply[A](fa: F[A]) = semaphore.withPermit(fa)
      }
      cassandraSync.mapK(serial, FunctionK.id)
    }
  }


  implicit class CassandraSyncOps[F[_]](val self: CassandraSync[F]) extends AnyVal {

    def mapK[G[_]](fg: F ~> G, gf: G ~> F): CassandraSync[G] = new CassandraSync[G] {

      def apply[A](fa: G[A]) = fg(self(gf(fa)))
    }
  }
} 
Example 16
Source File: InjK.scala    From freestyle   with Apache License 2.0 5 votes vote down vote up
package freestyle
package free

import cats.arrow.FunctionK
import cats.{~>, InjectK}
import iota._


sealed trait InjK[F[_], G[_]] {
  def inj: FunctionK[F, G]
  def prj: FunctionK[G, λ[α => Option[F[α]]]]
  final def apply[A](fa: F[A]): G[A]           = inj(fa)
  final def unapply[A](ga: G[A]): Option[F[A]] = prj(ga)
}

object InjK extends InjKInstances0

private[freestyle] sealed trait InjKInstances0 extends InjKInstances1 {
  implicit def injKReflexive[F[_]]: InjK[F, F] = new InjK[F, F] {
    def inj = FunctionK.id
    def prj = λ[F ~> λ[α => Option[F[α]]]](Some(_))
  }
}

private[freestyle] sealed trait InjKInstances1 {
  implicit def injKFromCatsInjectK[F[_], G[_]](
      implicit ev: InjectK[F, G]
  ): InjK[F, G] = new InjK[F, G] {
    def inj = λ[F ~> G](ev.inj(_))
    def prj = λ[G ~> λ[α => Option[F[α]]]](ev.prj(_))
  }

  implicit def injKfromIotaCopKInjectL[F[_], L <: TListK](
      implicit ev: CopK.InjectL[F, L]
  ): InjK[F, CopK[L, ?]] = new InjK[F, CopK[L, ?]] {
    def inj = λ[F ~> CopK[L, ?]](ev.inj(_))
    def prj = λ[CopK[L, ?] ~> λ[α => Option[F[α]]]](ev.proj(_))
  }
} 
Example 17
Source File: TestUtil.scala    From freestyle   with Apache License 2.0 5 votes vote down vote up
package freestyle.free.cache.redis

import cats.arrow.FunctionK
import cats.instances.future
import scala.concurrent.{ExecutionContext, Future}
import freestyle.free.cache.redis.rediscala._

object TestUtil {

  def redisMap(implicit ec: ExecutionContext): MapWrapper[Future, String, Int] =
    new MapWrapper()(
      formatKey = Format((key: String) => key),
      parseKey = Parser((str: String) => Some(str)),
      formatVal = Format((age: Int) => age.toString),
      parseVal = Parser((str: String) => scala.util.Try(Integer.parseInt(str)).toOption),
      toM = FunctionK.id[Future],
      funcM = future.catsStdInstancesForFuture(ec)
    )

}