zio.console.Console Scala Examples

The following examples show how to use zio.console.Console. 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: ExampleApp.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.play

import caliban.{ ExampleApi, ExampleService, PlayRouter }
import caliban.ExampleData.sampleCharacters
import caliban.ExampleService.ExampleService
import play.api.Mode
import play.api.mvc.DefaultControllerComponents
import play.core.server.{ AkkaHttpServer, ServerConfig }
import zio.clock.Clock
import zio.console.Console
import zio.internal.Platform
import zio.Runtime
import scala.io.StdIn.readLine

object ExampleApp extends App {

  implicit val runtime: Runtime[ExampleService with Console with Clock] =
    Runtime.unsafeFromLayer(ExampleService.make(sampleCharacters) ++ Console.live ++ Clock.live, Platform.default)

  val interpreter = runtime.unsafeRun(ExampleApi.api.interpreter)

  val server = AkkaHttpServer.fromRouterWithComponents(
    ServerConfig(
      mode = Mode.Dev,
      port = Some(8088),
      address = "127.0.0.1"
    )
  ) { components =>
    PlayRouter(
      interpreter,
      DefaultControllerComponents(
        components.defaultActionBuilder,
        components.playBodyParsers,
        components.messagesApi,
        components.langs,
        components.fileMimeTypes,
        components.executionContext
      )
    )(runtime, components.materializer).routes
  }

  println("Server online at http://localhost:8088/\nPress RETURN to stop...")
  readLine()
  server.stop()

} 
Example 2
Source File: TransportSpec.scala    From zio-keeper   with Apache License 2.0 5 votes vote down vote up
package zio.keeper.transport

import zio._
import zio.console.{ Console, _ }
import zio.duration._
import zio.keeper.TransportError
import zio.logging.Logging
import zio.nio.core.SocketAddress
import zio.test.Assertion._
import zio.test._
import zio.test.environment.TestEnvironment

object TransportSpec extends DefaultRunnableSpec {

  private val udpEnv =
    (TestEnvironment.live ++ Logging.ignore) >>> udp.live(128)

  def bindAndWaitForValue(
    addr: SocketAddress,
    startServer: Promise[Nothing, SocketAddress],
    handler: Channel => UIO[Unit] = _ => ZIO.unit
  ): ZIO[ConnectionLessTransport, TransportError, Chunk[Byte]] =
    for {
      q <- Queue.bounded[Chunk[Byte]](10)
      h = (out: Channel) => {
        for {
          _    <- handler(out)
          data <- out.read
          _    <- q.offer(data)
        } yield ()
      }.catchAll(ex => putStrLn("error in server: " + ex).provideLayer(Console.live))
      p <- bind(addr)(h).use { bind =>
            for {
              address <- bind.localAddress
              _       <- startServer.succeed(address)
              chunk   <- q.take
            } yield chunk
          }
    } yield p

  def spec =
    suite("transport")(
      suite("udp")(
        testM("can send and receive messages") {
          checkM(Gen.listOf(Gen.anyByte)) { bytes =>
            val payload = Chunk.fromIterable(bytes)
            for {
              addr        <- SocketAddress.inetSocketAddress(0)
              startServer <- Promise.make[Nothing, SocketAddress]
              chunk       <- bindAndWaitForValue(addr, startServer).fork
              address     <- startServer.await
              _           <- connect(address).use(_.send(payload).retry(Schedule.spaced(10.milliseconds)))
              result      <- chunk.join
            } yield assert(result)(equalTo(payload))
          }
        }
      ).provideCustomLayer(udpEnv)
    )
} 
Example 3
Source File: Aggregate.scala    From elastiknn   with Apache License 2.0 5 votes vote down vote up
package com.klibisz.elastiknn.benchmarks

import java.io.File

import kantan.csv._
import kantan.csv.ops._
import kantan.csv.generic._
import zio._
import zio.blocking.Blocking
import zio.console.Console
import zio.logging.log
import zio.logging.slf4j.Slf4jLogger
import zio.stream.ZSink


object Aggregate extends App {

  final case class Params(resultsBucket: String = "",
                          resultsPrefix: String = "",
                          aggregateBucket: String = "",
                          aggregateKey: String = "",
                          s3Minio: Boolean = false)

  private val parser = new scopt.OptionParser[Params]("Aggregate results into a single file") {
    override def showUsageOnError: Option[Boolean] = Some(true)
    help("help")
    opt[String]("resultsBucket").action((x, c) => c.copy(resultsBucket = x))
    opt[String]("resultsPrefix").action((x, c) => c.copy(resultsPrefix = x))
    opt[String]("aggregateBucket").action((x, c) => c.copy(aggregateBucket = x))
    opt[String]("aggregateKey").action((x, c) => c.copy(aggregateKey = x))
    opt[Boolean]("s3Minio").action((x, c) => c.copy(s3Minio = x))
  }

  def apply(params: Params): ZIO[Any, Throwable, Unit] = {
    val s3Client = if (params.s3Minio) S3Utils.minioClient() else S3Utils.defaultClient()
    val layer =
      (Blocking.live ++ ZLayer.succeed(s3Client)) >>>
        Slf4jLogger.make((_, s) => s, Some(getClass.getSimpleName)) ++
          ResultClient.s3(params.resultsBucket, params.resultsPrefix) ++
          Blocking.live

    val logic = for {
      // Stream results from S3.
      resultClient <- ZIO.access[ResultClient](_.get)
      results = resultClient.all()

      // Transform them to rows.
      aggStream = results
        .mapMPar(10) { res =>
          val agg = AggregateResult(res)
          log.info(agg.toString).map(_ => agg)
        }

      rows <- aggStream.run(ZSink.collectAll).map(_.sortBy(a => (a.dataset, a.similarity, a.algorithm)))

      // Write the rows to a temporary file
      csvFile = File.createTempFile("tmp", ".csv")
      writer = csvFile.asCsvWriter[AggregateResult](rfc.withHeader(AggregateResult.header: _*))
      _ = rows.foreach(writer.write)
      _ <- log.info(s"Wrote ${rows.length} rows to csv file.")
      _ = writer.close()

      // Upload the file.
      blocking <- ZIO.access[Blocking](_.get)
      _ <- blocking.effectBlocking(s3Client.putObject(params.aggregateBucket, params.aggregateKey, csvFile))

    } yield ()

    logic.provideLayer(layer)
  }

  override def run(args: List[String]): URIO[Any with Console, ExitCode] = parser.parse(args, Params()) match {
    case Some(params) => apply(params).exitCode
    case None         => sys.exit(1)
  }
} 
Example 4
Source File: ContinuousBenchmark.scala    From elastiknn   with Apache License 2.0 5 votes vote down vote up
package com.klibisz.elastiknn.benchmarks

import com.klibisz.elastiknn.api.{Mapping, NearestNeighborsQuery, Similarity, Vec}
import zio._
import zio.console.Console


object ContinuousBenchmark extends App {

  private val randomDenseFloats = Dataset.RandomDenseFloat(1000, 50000, 1000)
  private val randomSparseBools = Dataset.RandomSparseBool(3000, 50000, 1000)
  private val field = "vec"
  private val bucket = s"elastiknn-benchmarks"
  private val k = 100

  private val experiments = Seq(
    // L2 exact, LSH
    Experiment(
      randomDenseFloats,
      Mapping.DenseFloat(randomDenseFloats.dims),
      NearestNeighborsQuery.Exact(field, Similarity.L2),
      Mapping.L2Lsh(randomDenseFloats.dims, 400, 1, 3),
      Seq(
        Query(NearestNeighborsQuery.L2Lsh(field, 1000), k)
      )
    ),
    // Angular exact, LSH
    Experiment(
      randomDenseFloats,
      Mapping.DenseFloat(randomDenseFloats.dims),
      NearestNeighborsQuery.Exact(field, Similarity.Angular),
      Mapping.AngularLsh(randomDenseFloats.dims, 400, 1),
      Seq(
        Query(NearestNeighborsQuery.AngularLsh(field, 1000), k)
      )
    ),
    // Jaccard exact, sparse indexed, LSH
    Experiment(
      randomSparseBools,
      Mapping.SparseBool(randomSparseBools.dims),
      NearestNeighborsQuery.Exact(field, Similarity.Jaccard),
      Mapping.JaccardLsh(randomSparseBools.dims, 400, 1),
      Seq(
        Query(NearestNeighborsQuery.JaccardLsh(field, 1000), k)
      )
    )
  )

  override def run(args: List[String]): URIO[Console, ExitCode] = {
    val s3Client = S3Utils.minioClient()
    val experimentEffects = experiments.map { exp =>
      for {
        _ <- ZIO(s3Client.putObject(bucket, s"experiments/${exp.md5sum}.json", codecs.experimentCodec(exp).noSpaces))
        params = Execute.Params(
          experimentHash = exp.md5sum,
          experimentsBucket = bucket,
          experimentsPrefix = "experiments",
          datasetsBucket = bucket,
          datasetsPrefix = "data/processed",
          resultsBucket = bucket,
          resultsPrefix = "results",
          parallelism = 2,
          s3Minio = true,
          recompute = true
        )
        _ <- Execute(params)
      } yield ()
    }
    val pipeline = for {
      bucketExists <- ZIO(s3Client.doesBucketExistV2(bucket))
      _ <- if (!bucketExists) ZIO(s3Client.createBucket(bucket)) else ZIO.succeed(())
      _ <- ZIO.collectAll(experimentEffects)
      _ <- Aggregate(Aggregate.Params(bucket, "results", bucket, "results/aggregate/aggregate.csv", s3Minio = true))
    } yield ()
    pipeline.exitCode
  }

} 
Example 5
Source File: WebsocketZio.scala    From sttp   with Apache License 2.0 5 votes vote down vote up
package sttp.client.examples

import sttp.client._
import sttp.client.asynchttpclient.zio._
import sttp.client.ws.WebSocket
import sttp.model.ws.WebSocketFrame
import zio._
import zio.console.Console

object WebsocketZio extends App {
  def useWebsocket(ws: WebSocket[Task]): ZIO[Console, Throwable, Unit] = {
    def send(i: Int) = ws.send(WebSocketFrame.text(s"Hello $i!"))
    val receive = ws.receiveText().flatMap(t => console.putStrLn(s"RECEIVED: $t"))
    send(1) *> send(2) *> receive *> receive *> ws.close
  }

  // create a description of a program, which requires two dependencies in the environment:
  // the SttpClient, and the Console
  val sendAndPrint: ZIO[Console with SttpClient, Throwable, Unit] = for {
    response <- SttpClient.openWebsocket(basicRequest.get(uri"wss://echo.websocket.org"))
    _ <- useWebsocket(response.result)
  } yield ()

  override def run(args: List[String]): ZIO[ZEnv, Nothing, ExitCode] = {
    // provide an implementation for the SttpClient dependency; other dependencies are
    // provided by Zio
    sendAndPrint
      .provideCustomLayer(AsyncHttpClientZioBackend.layer())
      .fold(_ => ExitCode.failure, _ => ExitCode.success)
  }
} 
Example 6
Source File: ZIOSpec.scala    From polynote   with Apache License 2.0 5 votes vote down vote up
package polynote.testing

import polynote.config.PolynoteConfig
import polynote.env.ops.Enrich
import polynote.kernel.Kernel.Factory
import polynote.kernel.{BaseEnv, CellEnv, GlobalEnv, Kernel, ResultValue, interpreter}
import polynote.kernel.environment.{Config, Env, NotebookUpdates}
import interpreter.Interpreter
import org.scalatest.{BeforeAndAfterAll, Suite}
import polynote.kernel.logging.Logging
import zio.blocking.Blocking
import zio.clock.Clock
import zio.console.Console
import zio.internal.Platform
import zio.random.Random
import zio.system.System
import zio.{Has, RIO, Runtime, Tagged, ZIO, ZLayer}

abstract class TestRuntime
object TestRuntime {
  val runtime: Runtime.Managed[zio.ZEnv with Logging] = ZIOSpecBase.runtime
  def fiberDump(): List[zio.Fiber.Dump] = runtime.unsafeRun(zio.Fiber.dumpAll).toList
}

trait ZIOSpecBase[Env <: Has[_]] {
  import ZIOSpecBase.BaseEnv
  type Environment = Env
  val baseLayer: ZLayer[Any, Nothing, BaseEnv] = ZIOSpecBase.baseLayer
  def envLayer: ZLayer[zio.ZEnv with Logging, Nothing, Env]
  val runtime: Runtime.Managed[BaseEnv] = ZIOSpecBase.runtime

  // TODO: should test platform behave differently? Isolate per suite?
  implicit class IORunOps[A](val self: ZIO[BaseEnv, Throwable, A]) {
    def runIO(): A = ZIOSpecBase.this.runIO(self)
  }

  implicit class IORunWithOps[R <: Has[_], A](val self: ZIO[R, Throwable, A]) {
    def runWith[R1](env: R1)(implicit ev: Env with Has[R1] <:< R, ev1: Tagged[R1], ev2: Tagged[Has[R1]], ev3: Tagged[Env]): A =
      ZIOSpecBase.this.runIO(self.provideSomeLayer[Env](ZLayer.succeed(env)).provideSomeLayer[BaseEnv](envLayer))
  }

  def runIO[A](io: ZIO[BaseEnv, Throwable, A]): A = runtime.unsafeRunSync(io).getOrElse {
    c => throw c.squash
  }


}

object ZIOSpecBase {

  type BaseEnv = zio.ZEnv with Logging
  val baseLayer: ZLayer[Any, Nothing, zio.ZEnv with Logging] = Clock.live ++ Console.live ++ System.live ++ Random.live ++ Blocking.live ++ (Blocking.live >>> Logging.live)
  val platform: Platform = Platform.default
    .withReportFailure(_ => ()) // suppress printing error stack traces by default
  val runtime: Runtime.Managed[zio.ZEnv with Logging] = Runtime.unsafeFromLayer(baseLayer, platform)
}

trait ZIOSpec extends ZIOSpecBase[Clock with Console with System with Random with Blocking with Logging] {
  override lazy val envLayer: ZLayer[zio.ZEnv, Nothing, Environment] = baseLayer
  implicit class ConfigIORunOps[A](val self: ZIO[Environment with Config, Throwable, A]) {
    def runWithConfig(config: PolynoteConfig): A = ZIOSpec.this.runIO(self.provideSomeLayer[Environment](ZLayer.succeed(config)))
  }
}

trait ConfiguredZIOSpec extends ZIOSpecBase[BaseEnv with Config] { this: Suite =>
  def config: PolynoteConfig = PolynoteConfig()
  override lazy val envLayer: ZLayer[zio.ZEnv, Nothing, BaseEnv with Config] =
    baseLayer ++ ZLayer.succeed(config)
}

trait ExtConfiguredZIOSpec[Env <: Has[_]] extends ZIOSpecBase[BaseEnv with Config with Env] {
  def tagged: Tagged[Env]
  def configuredEnvLayer: ZLayer[zio.ZEnv with Config, Nothing, Env]

  private implicit def _tagged: Tagged[Env] = tagged

  def config: PolynoteConfig = PolynoteConfig()
  lazy val configLayer: ZLayer[Any, Nothing, Config] = ZLayer.succeed(config)
  override final lazy val envLayer: ZLayer[zio.ZEnv, Nothing, BaseEnv with Config with Env] = baseLayer ++ Logging.live ++ ((baseLayer ++ configLayer) >>> configuredEnvLayer) ++ configLayer
}

object ValueMap {
  def unapply(values: List[ResultValue]): Option[Map[String, Any]] = Some(apply(values))
  def apply(values: List[ResultValue]): Map[String, Any] = values.map(v => v.name -> v.value).toMap
} 
Example 7
Source File: InterpreterSpec.scala    From polynote   with Apache License 2.0 5 votes vote down vote up
package polynote.testing

import java.io.File

import cats.data.StateT
import cats.syntax.traverse._
import cats.instances.list._
import org.scalatest.Suite
import polynote.config.PolynoteConfig
import polynote.kernel.environment.Config
import polynote.kernel.{Output, Result, ScalaCompiler}
import polynote.kernel.interpreter.{Interpreter, State}
import polynote.kernel.logging.Logging
import polynote.testing.kernel.MockEnv
import zio.{RIO, ZIO}
import zio.blocking.Blocking
import zio.clock.Clock
import zio.console.Console
import zio.random.Random
import zio.system.System
import zio.interop.catz._

import scala.reflect.internal.util.AbstractFileClassLoader
import scala.reflect.io.VirtualDirectory
import scala.tools.nsc.Settings
import scala.tools.nsc.io.AbstractFile

trait InterpreterSpec extends ZIOSpec {
  import runtime.{unsafeRun, unsafeRunSync}
  val classpath: List[File] = sys.props("java.class.path").split(File.pathSeparator).toList.map(new File(_))
  val settings: Settings = ScalaCompiler.defaultSettings(new Settings(), classpath)

  def outDir: AbstractFile = new VirtualDirectory("(memory)", None)
  settings.outputDirs.setSingleOutput(outDir)

  val classLoader: AbstractFileClassLoader = unsafeRun(ScalaCompiler.makeClassLoader(settings, Nil).provide(Config.of(PolynoteConfig())))
  val compiler: ScalaCompiler = ScalaCompiler(settings, classLoader).runIO()

  def interpreter: Interpreter

  lazy val initialState: State = unsafeRun(interpreter.init(State.Root).provideSomeLayer[Environment](MockEnv.layer(State.Root.id + 1)))
  def cellState: State = State.id(1, initialState)

  def assertOutput(code: String)(assertion: (Map[String, Any], Seq[Result]) => Unit): Unit =
    assertOutput(List(code))(assertion)

  def assertOutput(code: Seq[String])(assertion: (Map[String, Any], Seq[Result]) => Unit): Unit= {
    val (finalState, interpResults) = code.toList.map(interp).sequence.run(cellState).runIO()
    val terminalResults = interpResults.foldLeft((Map.empty[String, Any], List.empty[Result])) {
      case ((vars, results), next) =>
        val nextVars = vars ++ next.state.values.map(v => v.name -> v.value).toMap
        val nextOutputs = results ++ next.env.publishResult.toList.runIO()
        (nextVars, nextOutputs)
    }
    assertion.tupled(terminalResults)
  }

  case class InterpResult(state: State, env: MockEnv)

  type ITask[A] = RIO[Clock with Console with System with Random with Blocking with Logging, A]

  def interp(code: String): StateT[ITask, State, InterpResult] = StateT[ITask, State, InterpResult] {
    state => MockEnv(state.id).flatMap {
      env => interpreter.run(code, state).map {
        newState => State.id(newState.id + 1, newState) -> InterpResult(newState, env)
      }.provideSomeLayer[Environment](env.toCellEnv(classLoader))
    }
  }

  def interp1(code: String): InterpResult = unsafeRun {
    MockEnv(cellState.id).flatMap {
      env =>
        interpreter.run(code, cellState).provideSomeLayer(env.toCellEnv(getClass.getClassLoader)).map {
          state => InterpResult(state, env)
        }
    }
  }

  def stdOut(results: Seq[Result]): String = results.foldLeft("") {
    case (accum, Output("text/plain; rel=stdout", next)) => accum + next.mkString
    case (accum, _) => accum
  }

} 
Example 8
Source File: ExampleApp.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.akkahttp

import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import caliban.ExampleData.sampleCharacters
import caliban.ExampleService.ExampleService
import caliban.interop.circe.AkkaHttpCirceAdapter
import caliban.{ ExampleApi, ExampleService }
import zio.clock.Clock
import zio.console.Console
import zio.internal.Platform
import zio.Runtime


  val route =
    path("api" / "graphql") {
      adapter.makeHttpService(interpreter)
    } ~ path("ws" / "graphql") {
      adapter.makeWebSocketService(interpreter)
    } ~ path("graphiql") {
      getFromResource("graphiql.html")
    }

  val bindingFuture = Http().bindAndHandle(route, "localhost", 8088)
  println(s"Server online at http://localhost:8088/\nPress RETURN to stop...")
  StdIn.readLine()
  bindingFuture
    .flatMap(_.unbind())
    .onComplete(_ => system.terminate())

} 
Example 9
Source File: ExampleApp.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.finch

import caliban.ExampleData.sampleCharacters
import caliban.ExampleService.ExampleService
import caliban.{ ExampleApi, ExampleService, FinchAdapter }
import com.twitter.io.{ Buf, BufReader, Reader }
import com.twitter.util.Await
import io.finch.Endpoint
import zio.clock.Clock
import zio.console.Console
import zio.internal.Platform
import zio.interop.catz._
import zio.{ Runtime, Task }

object ExampleApp extends App with Endpoint.Module[Task] {

  implicit val runtime: Runtime[ExampleService with Console with Clock] =
    Runtime.unsafeFromLayer(ExampleService.make(sampleCharacters) ++ Console.live ++ Clock.live, Platform.default)

  val interpreter = runtime.unsafeRun(ExampleApi.api.interpreter)

  
  import com.twitter.finagle.Http
  import io.finch._
  import io.finch.circe._

  val endpoint = "api" :: "graphql" :: FinchAdapter.makeHttpService(interpreter)

  val graphiqlBuf = {
    val stream = getClass.getResourceAsStream("/graphiql.html")
    BufReader.readAll(Reader.fromStream(stream))
  }

  val grapihql: Endpoint[Task, Buf] = get("graphiql") {
    graphiqlBuf.map(Ok)
  }

  val services = Bootstrap.serve[Application.Json](endpoint).serve[Text.Html](grapihql).toService

  val server = Http.server.serve(":8088", services)

  println(s"Server online at http://localhost:8088/\nPress RETURN to stop...")
  Await.ready(server)

} 
Example 10
Source File: ExampleApp.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.client

import caliban.client.Client._
import sttp.client._
import sttp.client.asynchttpclient.zio.{ AsyncHttpClientZioBackend, SttpClient }
import zio.console.{ putStrLn, Console }
import zio.{ App, ExitCode, RIO, ZIO }

object ExampleApp extends App {

  sealed trait Role
  object Role {
    case class Captain(shipName: String)  extends Role
    case class Pilot(shipName: String)    extends Role
    case class Engineer(shipName: String) extends Role
    case class Mechanic(shipName: String) extends Role
  }

  case class Character(name: String, nicknames: List[String], origin: Origin, role: Option[Role])

  override def run(args: List[String]): ZIO[zio.ZEnv, Nothing, ExitCode] = {
    val character = {
      import caliban.client.Client.Character._
      (name ~
        nicknames ~
        origin ~
        role(
          Captain.shipName.map(Role.Captain),
          Engineer.shipName.map(Role.Engineer),
          Mechanic.shipName.map(Role.Mechanic),
          Pilot.shipName.map(Role.Pilot)
        )).mapN(Character)
    }
    val query =
      Queries.characters(None) {
        character
      } ~
        Queries.character("Amos Burton") {
          character
        } ~
        Queries.character("Naomi Nagata") {
          character
        }
    val mutation = Mutations.deleteCharacter("James Holden")

    def send[T](req: Request[Either[CalibanClientError, T], Nothing]): RIO[Console with SttpClient, T] =
      SttpClient.send(req).map(_.body).absolve.tap(res => putStrLn(s"Result: $res"))

    val uri   = uri"http://localhost:8088/api/graphql"
    val call1 = send(mutation.toRequest(uri))
    val call2 = send(query.toRequest(uri, useVariables = true))

    (call1 *> call2)
      .provideCustomLayer(AsyncHttpClientZioBackend.layer())
      .exitCode
  }
} 
Example 11
Source File: UdpServer.scala    From zio-keeper   with Apache License 2.0 5 votes vote down vote up
package zio.keeper.example

import zio.{ Chunk, Schedule }
import zio.clock.Clock
import zio.console.{ Console, putStrLn }
import zio.keeper.transport.Channel
import zio.logging.Logging
import zio.nio.core.{ InetAddress, SocketAddress }

object UdpServer extends zio.App {
  import zio._
  import zio.keeper.transport._

  val logging = Logging.console((_, msg) => msg)

  val transport = (Clock.live ++ logging) >>> udp.live(128)

  val localEnvironment = Console.live ++ transport

  override def run(args: List[String]) =
    (for {
      localHost <- InetAddress.localHost.orDie
      publicAddress <- SocketAddress
                        .inetSocketAddress(localHost, 8010)
                        .orDie
      console <- ZIO.environment[Console]
      handler = (channel: Channel) => {
        for {
          data <- channel.read
          _    <- putStrLn(new String(data.toArray))
          _    <- channel.send(data)
        } yield ()
      }.catchAll(ex => putStrLn("error: " + ex.msg))
        .provide(console)

      _ <- putStrLn("public address: " + publicAddress.toString())
      _ <- bind(publicAddress)(handler)
            .use(ch => ZIO.never.ensuring(ch.close.ignore))

    } yield ()).ignore.as(0).provideLayer(localEnvironment)
}

object UdpClient extends zio.App {
  import zio.keeper.transport._

  val logging = Logging.console((_, msg) => msg)

  val transport = (Clock.live ++ logging) >>> udp.live(128)

  val localEnvironment = Console.live ++ transport

  override def run(args: List[String]) =
    (for {
      localHost <- InetAddress.localHost.orDie
      publicAddress <- SocketAddress
                        .inetSocketAddress(localHost, 5557)
                        .orDie
      _ <- putStrLn("connect to address: " + publicAddress.toString())
      _ <- connect(publicAddress)
            .use(_.send(Chunk.fromArray("message from client".getBytes)).repeat(Schedule.recurs(100)))
    } yield ()).ignore.as(0).provideLayer(localEnvironment)
} 
Example 12
Source File: NaiveTest.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.optimizations

import caliban.optimizations.CommonData._
import caliban.schema.{ GenericSchema, Schema }
import caliban.{ GraphQL, RootResolver }
import zio.console.{ putStrLn, Console }
import zio.{ App, ExitCode, ZIO }


object NaiveTest extends App with GenericSchema[Console] {

  type MyIO[A] = ZIO[Console, Nothing, A]

  case class Queries(user: UserArgs => MyIO[User])

  case class User(
    fullName: String,
    username: String,
    picture: SizeArgs => String,
    upcomingEvents: FirstArgs => MyIO[List[Event]]
  )

  case class Event(
    id: Int,
    name: String,
    date: String,
    startTime: String,
    endTime: String,
    viewerRsvp: MyIO[ViewerMetadata],
    tags: MyIO[List[Tag]],
    venue: MyIO[Venue],
    attendingFriendsOfViewer: FirstArgs => MyIO[List[User]]
  )

  def getUpcomingEventIdsForUser(id: Int, first: Int): MyIO[List[Int]] =
    putStrLn("getUpcomingEventIdsForUser").as((1 to first).toList)

  def getViewerMetadataForEvent(id: Int): MyIO[ViewerMetadata] =
    putStrLn("getViewerMetadataForEvent").as(ViewerMetadata(""))

  def getVenue(id: Int): MyIO[Venue] = putStrLn("getVenue").as(Venue("venue"))

  def getTags(ids: List[Int]): MyIO[List[Tag]] = putStrLn("getTags").as(ids.map(id => Tag(id.toString)))

  def getViewerFriendIdsAttendingEvent(id: Int, first: Int): MyIO[List[Int]] =
    putStrLn("getViewerFriendIdsAttendingEvent").as((1 to first).toList)

  def getEvent(id: Int): MyIO[Event] =
    putStrLn("getEvent").as(
      Event(
        id,
        "name",
        "date",
        "start",
        "end",
        getViewerMetadataForEvent(id),
        getTags(List(1, 2, 3, 4, 5)),
        getVenue(id),
        args => getViewerFriendIdsAttendingEvent(id, args.first).flatMap(ZIO.foreach(_)(getUser))
      )
    )

  def getUser(id: Int): MyIO[User] =
    putStrLn("getUser").as(
      User(
        "name",
        "name",
        args => s"picture of size ${args.size}",
        args => getUpcomingEventIdsForUser(id, args.first).flatMap(ZIO.foreach(_)(getEvent))
      )
    )

  implicit val viewerMetadataSchema: Schema[Any, ViewerMetadata] = Schema.gen[ViewerMetadata]
  implicit val tagSchema: Schema[Any, Tag]                       = Schema.gen[Tag]
  implicit val venueSchema: Schema[Any, Venue]                   = Schema.gen[Venue]
  implicit val userArgsSchema: Schema[Any, UserArgs]             = Schema.gen[UserArgs]
  implicit val sizeArgsSchema: Schema[Any, SizeArgs]             = Schema.gen[SizeArgs]
  implicit val firstArgsSchema: Schema[Any, FirstArgs]           = Schema.gen[FirstArgs]
  implicit lazy val user: Schema[Console, User]                  = gen[User]

  val resolver = Queries(args => getUser(args.id))
  val api      = GraphQL.graphQL(RootResolver(resolver))

  override def run(args: List[String]): ZIO[zio.ZEnv, Nothing, ExitCode] =
    api.interpreter
      .flatMap(_.execute(query).map(res => ExitCode(res.errors.length)))
      .exitCode
} 
Example 13
Source File: ExampleApi.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban

import scala.language.postfixOps
import caliban.ExampleData._
import caliban.ExampleService.ExampleService
import caliban.GraphQL.graphQL
import caliban.schema.Annotations.{ GQLDeprecated, GQLDescription }
import caliban.schema.GenericSchema
import caliban.wrappers.ApolloTracing.apolloTracing
import caliban.wrappers.Wrappers.{ maxDepth, maxFields, printSlowQueries, timeout }
import zio.URIO
import zio.clock.Clock
import zio.console.Console
import zio.duration._
import zio.stream.ZStream

object ExampleApi extends GenericSchema[ExampleService] {

  case class Queries(
    @GQLDescription("Return all characters from a given origin")
    characters: CharactersArgs => URIO[ExampleService, List[Character]],
    @GQLDeprecated("Use `characters`")
    character: CharacterArgs => URIO[ExampleService, Option[Character]]
  )
  case class Mutations(deleteCharacter: CharacterArgs => URIO[ExampleService, Boolean])
  case class Subscriptions(characterDeleted: ZStream[ExampleService, Nothing, String])

  implicit val roleSchema           = gen[Role]
  implicit val characterSchema      = gen[Character]
  implicit val characterArgsSchema  = gen[CharacterArgs]
  implicit val charactersArgsSchema = gen[CharactersArgs]

  val api: GraphQL[Console with Clock with ExampleService] =
    graphQL(
      RootResolver(
        Queries(
          args => ExampleService.getCharacters(args.origin),
          args => ExampleService.findCharacter(args.name)
        ),
        Mutations(args => ExampleService.deleteCharacter(args.name)),
        Subscriptions(ExampleService.deletedEvents)
      )
    ) @@
      maxFields(200) @@               // query analyzer that limit query fields
      maxDepth(30) @@                 // query analyzer that limit query depth
      timeout(3 seconds) @@           // wrapper that fails slow queries
      printSlowQueries(500 millis) @@ // wrapper that logs slow queries
      apolloTracing // wrapper for https://github.com/apollographql/apollo-tracing

} 
Example 14
Source File: CodegenPlugin.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.codegen

import caliban.parsing.adt.Document
import caliban.tools._
import sbt.Keys.commands
import sbt.{ AutoPlugin, Command, State }
import zio.console.{ putStrLn, Console }
import zio.{ RIO, Runtime }

object CodegenPlugin extends AutoPlugin {
  override lazy val projectSettings = Seq(commands ++= Seq(genSchemaCommand, genClientCommand))
  lazy val genSchemaCommand         = genCommand("calibanGenSchema", genSchemaHelpMsg, SchemaWriter.write)
  lazy val genClientCommand         = genCommand("calibanGenClient", genClientHelpMsg, ClientWriter.write)

  def genCommand(name: String, helpMsg: String, writer: (Document, String, Option[String], String) => String): Command =
    Command.args(name, helpMsg) { (state: State, args: Seq[String]) =>
      Runtime.default.unsafeRun(
        execGenCommand(helpMsg, args.toList, writer)
          .catchAll(reason => putStrLn(reason.toString) *> putStrLn(reason.getStackTrace.mkString("\n")))
          .as(1)
      )
      state
    }

  private val commonHelp =
    """
      |The generated code will be formatted with Scalafmt using the configuration defined by
      |`--scalafmtPath` option (default: ".scalafmt.conf").
      |
      |If you provide a URL for `schemaPath`, you can provide request headers with
      |`--headers` option.
      |
      |The package of the generated code is derived from the folder of `outputPath`.
      |This can be overridden by providing an alternative package with the `--packageName`
      |option.
  """.stripMargin

  private val genSchemaHelpMsg =
    s"""
       |calibanGenSchema schemaPath outputPath [--scalafmtPath path] [--headers name:value,name2:value2] [--packageName name] [--effect fqdn.Effect]
       |
       |This command will create a Scala file in `outputPath` containing all the types
       |defined in the provided GraphQL schema defined at `schemaPath`. Instead of a path,
       |you can provide a URL and introspection will be used to gather the schema.
       |
       |$commonHelp
       |
       |By default, each Query and Mutation will be wrapped into a `zio.UIO` effect. 
       |This can be overridden by providing an alternative effect with the `--effect` option.
       |""".stripMargin

  private val genClientHelpMsg =
    s"""
       |calibanGenClient schemaPath outputPath [--scalafmtPath path] [--headers name:value,name2:value2] [--packageName name]
       |
       |This command will create a Scala file in `outputPath` containing client code for all the
       |typed defined in the provided GraphQL schema defined at `schemaPath`. Instead of a path,
       |you can provide a URL and introspection will be used to gather the schema.
       |
       |$commonHelp
       |""".stripMargin

  def execGenCommand(
    helpMsg: String,
    args: List[String],
    writer: (Document, String, Option[String], String) => String
  ): RIO[Console, Unit] =
    Options.fromArgs(args) match {
      case Some(arguments) =>
        for {
          _ <- putStrLn(s"Generating code for ${arguments.schemaPath}")
          _ <- Codegen.generate(arguments, writer)
          _ <- putStrLn(s"Code generation done")
        } yield ()
      case None => putStrLn(helpMsg)
    }
} 
Example 15
Source File: Wrappers.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban.wrappers

import caliban.CalibanError.{ ExecutionError, ValidationError }
import caliban.{ GraphQLRequest, GraphQLResponse }
import caliban.Value.NullValue
import caliban.execution.Field
import caliban.parsing.adt.Document
import caliban.wrappers.Wrapper.{ OverallWrapper, ValidationWrapper }
import zio.clock.Clock
import zio.console.{ putStrLn, Console }
import zio.duration.Duration
import zio.{ IO, UIO, URIO, ZIO }

object Wrappers {

  
  def maxFields(maxFields: Int): ValidationWrapper[Any] =
    ValidationWrapper { process => (doc: Document) =>
      for {
        req    <- process(doc)
        fields <- countFields(req.field)
        _ <- IO.when(fields > maxFields)(
              IO.fail(ValidationError(s"Query has too many fields: $fields. Max fields: $maxFields.", ""))
            )
      } yield req
    }

  private def countFields(field: Field): UIO[Int] =
    for {
      inner <- innerFields(field.fields)
      conditional <- IO.foreach(field.conditionalFields.values)(innerFields).map {
                      case Nil  => 0
                      case list => list.max
                    }
    } yield inner + conditional

  private def innerFields(fields: List[Field]): UIO[Int] =
    IO.foreach(fields)(countFields).map(_.sum + fields.length)

} 
Example 16
Source File: JavaPropertiesExample.scala    From zio-config   with Apache License 2.0 5 votes vote down vote up
package zio.config.examples

import zio.config.Config
import zio.config.ConfigDescriptor._
import zio.console.Console
import zio.{ config, console, App, ExitCode, ZEnv, ZIO, ZLayer }


final case class ApplicationConfig(bridgeIp: String, userName: String)

object ApplicationConfig {
  val configuration =
    ((string("bridgeIp")) |@| string("username"))(ApplicationConfig.apply, ApplicationConfig.unapply)
}

// The main App
object JavaPropertiesExample extends App {

  val properties = new java.util.Properties()
  properties.put("bridgeIp", "10.0.0.1")
  properties.put("username", "afs")

  override def run(args: List[String]): ZIO[ZEnv, Nothing, ExitCode] = {
    val configLayer =
      Config.fromProperties(properties, ApplicationConfig.configuration, "constant")

    val pgm =
      SimpleExample.finalExecution.provideLayer(configLayer ++ ZLayer.requires[Console])

    pgm.foldM(
      throwable => console.putStr(throwable.getMessage).as(ExitCode.failure),
      _ => console.putStrLn("hurray !! Application ran successfully..").as(ExitCode.success)
    )
  }
}

// The core application functions
object SimpleExample {

  val printConfigs: ZIO[Console with Config[ApplicationConfig], Nothing, Unit] =
    for {
      appConfig <- config.config[ApplicationConfig]
      _         <- console.putStrLn(appConfig.bridgeIp)
      _         <- console.putStrLn(appConfig.userName)
    } yield ()

  val finalExecution: ZIO[Console with Config[ApplicationConfig], Nothing, Unit] =
    for {
      _ <- printConfigs
      _ <- console.putStrLn(s"processing data......")
    } yield ()
}
// A note that, with magnolia module (which is still experimental), you can skip writing the {{ configuration }} in ApplicationConfig object
// import zio.config.magnolia.DeriveConfigDescriptor_, 
Example 17
Source File: SimpleReadConfigExample.scala    From zio-config   with Apache License 2.0 5 votes vote down vote up
package zio.config.examples

import zio.config._
import ConfigDescriptor._
import zio.console.Console
import zio.config.Config
import zio.config.config
import zio.{ App, ExitCode, ZEnv, ZIO }

case class Prod(ldap: String, port: Int, dburl: Option[String])

object Prod {
  val prodConfig: ConfigDescriptor[Prod] =
    (string("LDAP") |@| int("PORT") |@|
      string("DB_URL").optional)(Prod.apply, Prod.unapply)

  val myAppLogic: ZIO[Config[Prod], Throwable, (String, Option[String])] =
    for {
      prod <- config[Prod]
    } yield (prod.ldap, prod.dburl)
}

object ReadConfig extends App {

  override def run(args: List[String]): ZIO[ZEnv, Nothing, ExitCode] =
    for {
      console <- ZIO.environment[Console].map(_.get)
      configLayer = Config.fromMap(
        Map("LDAP" -> "ldap", "PORT" -> "1999", "DB_URL" -> "ddd"),
        Prod.prodConfig,
        "constant"
      )
      out <- Prod.myAppLogic
              .provideLayer(configLayer)
              .foldM(
                failure => console.putStrLn(failure.toString).as(ExitCode.failure),
                _ => ZIO.succeed(ExitCode.success)
              )
    } yield out
} 
Example 18
Source File: catzSpecBase.scala    From interop-cats   with Apache License 2.0 5 votes vote down vote up
package zio.interop

import cats.Eq
import cats.effect.laws.util.{ TestContext, TestInstances }
import cats.implicits._
import org.scalacheck.Arbitrary
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.prop.Configuration
import org.typelevel.discipline.Laws
import org.typelevel.discipline.scalatest.FunSuiteDiscipline
import zio.clock.Clock
import zio.console.Console
import zio.internal.{ Executor, Platform, Tracing }
import zio.interop.catz.taskEffectInstance
import zio.random.Random
import zio.system.System
import zio.{ =!=, Cause, IO, Runtime, Task, UIO, ZIO, ZManaged }

private[zio] trait catzSpecBase
    extends AnyFunSuite
    with FunSuiteDiscipline
    with Configuration
    with TestInstances
    with catzSpecBaseLowPriority {

  type Env = Clock with Console with System with Random

  implicit def rts(implicit tc: TestContext): Runtime[Unit] = Runtime(
    (),
    Platform
      .fromExecutor(Executor.fromExecutionContext(Int.MaxValue)(tc))
      .withTracing(Tracing.disabled)
      .withReportFailure(_ => ())
  )

  implicit val zioEqCauseNothing: Eq[Cause[Nothing]] = Eq.fromUniversalEquals

  implicit def zioEqIO[E: Eq, A: Eq](implicit rts: Runtime[Any], tc: TestContext): Eq[IO[E, A]] =
    Eq.by(_.either)

  implicit def zioEqTask[A: Eq](implicit rts: Runtime[Any], tc: TestContext): Eq[Task[A]] =
    Eq.by(_.either)

  implicit def zioEqUIO[A: Eq](implicit rts: Runtime[Any], tc: TestContext): Eq[UIO[A]] =
    Eq.by(uio => taskEffectInstance.toIO(uio.sandbox.either))

  implicit def zioEqZManaged[E: Eq, A: Eq](implicit rts: Runtime[Any], tc: TestContext): Eq[ZManaged[Any, E, A]] =
    Eq.by(
      zm => ZManaged.ReleaseMap.make.flatMap(releaseMap => zm.zio.provideSome[Any]((_, releaseMap)).map(_._2).either)
    )

  def checkAllAsync(name: String, f: TestContext => Laws#RuleSet): Unit =
    checkAll(name, f(TestContext()))

}

private[interop] sealed trait catzSpecBaseLowPriority { this: catzSpecBase =>

  implicit def zioEq[R: Arbitrary, E: Eq, A: Eq](implicit rts: Runtime[Any], tc: TestContext): Eq[ZIO[R, E, A]] = {
    def run(r: R, zio: ZIO[R, E, A]) = taskEffectInstance.toIO(zio.provide(r).either)
    Eq.instance((io1, io2) => Arbitrary.arbitrary[R].sample.fold(false)(r => catsSyntaxEq(run(r, io1)) eqv run(r, io2)))
  }

  // 'R =!= Any' evidence fixes the 'diverging implicit expansion for type Arbitrary' error reproducible on scala 2.12 and 2.11.
  implicit def zmanagedEq[R: * =!= Any: Arbitrary, E: Eq, A: Eq](
    implicit rts: Runtime[Any],
    tc: TestContext
  ): Eq[ZManaged[R, E, A]] = {
    def run(r: R, zm: ZManaged[R, E, A]) =
      taskEffectInstance.toIO(
        ZManaged.ReleaseMap.make.flatMap(releaseMap => zm.zio.provide((r, releaseMap)).map(_._2).either)
      )
    Eq.instance((io1, io2) => Arbitrary.arbitrary[R].sample.fold(false)(r => catsSyntaxEq(run(r, io1)) eqv run(r, io2)))
  }

} 
Example 19
Source File: ZioExampleHttp4sServer.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.examples

import org.http4s._
import org.http4s.server.Router
import org.http4s.server.blaze.BlazeServerBuilder
import org.http4s.syntax.kleisli._
import zio.interop.catz._
import zio.interop.catz.implicits._
import zio.{Has, IO, Runtime, Task, UIO, ZIO, ZLayer, ZEnv}
import sttp.tapir.ztapir._
import sttp.tapir.server.http4s.ztapir._
import sttp.tapir.swagger.http4s.SwaggerHttp4s
import cats.implicits._
import UserLayer.UserService
import sttp.tapir.examples.ZioExampleHttp4sServer.Pet
import zio.console.Console

object ZioExampleHttp4sServer extends App {
  case class Pet(species: String, url: String)

  import io.circe.generic.auto._
  import sttp.tapir.json.circe._

  // Sample endpoint, with the logic implemented directly using .toRoutes
  val petEndpoint: ZEndpoint[Int, String, Pet] =
    endpoint.get.in("pet" / path[Int]("petId")).errorOut(stringBody).out(jsonBody[Pet])

  val petRoutes: HttpRoutes[Task] = petEndpoint.toRoutes { petId =>
    if (petId == 35) {
      UIO(Pet("Tapirus terrestris", "https://en.wikipedia.org/wiki/Tapir"))
    } else {
      IO.fail("Unknown pet id")
    }
  }

  // Same endpoint as above, but using a custom application layer
  val pet2Endpoint: ZEndpoint[Int, String, Pet] =
    endpoint.get.in("pet2" / path[Int]("petId")).errorOut(stringBody).out(jsonBody[Pet])

  val pet2Routes: HttpRoutes[Task] = pet2Endpoint.toRoutes(petId => UserService.hello(petId).provideLayer(UserLayer.liveEnv))

  // Final service is just a conjunction of different Routes
  implicit val runtime: Runtime[ZEnv] = Runtime.default
  val service: HttpRoutes[Task] = petRoutes <+> pet2Routes

  //
  // Same as above, but combining endpoint description with server logic:
  //

  val petServerEndpoint = petEndpoint.zServerLogic { petId =>
    if (petId == 35) {
      UIO(Pet("Tapirus terrestris", "https://en.wikipedia.org/wiki/Tapir"))
    } else {
      IO.fail("Unknown pet id")
    }
  }
  val petServerRoutes: HttpRoutes[Task] = petServerEndpoint.toRoutes

  val pet2ServerEndpoint = pet2Endpoint.zServerLogic { petId => UserService.hello(petId).provideLayer(UserLayer.liveEnv) }
  val pet2ServerRoutes: HttpRoutes[Task] = petServerEndpoint.toRoutes

  import sttp.tapir.docs.openapi._
  import sttp.tapir.openapi.circe.yaml._
  val yaml = List(petEndpoint).toOpenAPI("Our pets", "1.0").toYaml

  val serve = BlazeServerBuilder[Task](runtime.platform.executor.asEC)
    .bindHttp(8080, "localhost")
    .withHttpApp(Router("/" -> (service <+> new SwaggerHttp4s(yaml).routes[Task])).orNotFound)
    .serve
    .compile
    .drain

  runtime.unsafeRun(serve)
}

object UserLayer {
  type UserService = Has[UserService.Service]

  object UserService {
    trait Service {
      def hello(id: Int): ZIO[Any, String, Pet]
    }

    val live: ZLayer[Console, Nothing, Has[Service]] = ZLayer.fromFunction { console: Console => (id: Int) =>
      {
        console.get.putStrLn(s"Got Pet request for $id") >>
          ZIO.succeed(Pet(id.toString, "https://zio.dev"))
      }
    }

    def hello(id: Int): ZIO[UserService, String, Pet] = ZIO.accessM(_.get.hello(id))
  }

  val liveEnv: ZLayer[Any, Nothing, Has[UserService.Service]] = Console.live >>> UserService.live
} 
Example 20
Source File: MockConsole.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio.test.mock

import java.io.IOException

import zio.console.Console
import zio.{ Has, IO, UIO, URLayer, ZLayer }

object MockConsole extends Mock[Console] {

  object PutStr   extends Effect[String, Nothing, Unit]
  object PutStrLn extends Effect[String, Nothing, Unit]
  object GetStrLn extends Effect[Unit, IOException, String]

  val compose: URLayer[Has[Proxy], Console] =
    ZLayer.fromService(proxy =>
      new Console.Service {
        def putStr(line: String): UIO[Unit]   = proxy(PutStr, line)
        def putStrLn(line: String): UIO[Unit] = proxy(PutStrLn, line)
        val getStrLn: IO[IOException, String] = proxy(GetStrLn)
      }
    )
} 
Example 21
Source File: ResultNotifier.scala    From zorechka-bot   with MIT License 5 votes vote down vote up
package com.wix.zorechka.service

import java.nio.file.{Files, Path}

import com.wix.zorechka.Dep
import com.wix.zorechka.clients.{BuildozerClient, GithubClient}
import zio.console.Console
import zio.{RIO, ZIO}

import collection.JavaConverters._

trait ResultNotifier {
  val notifier: ResultNotifier.Service
}

object ResultNotifier {

  trait Service {
    def notify(forkDir: Path, updatedDeps: List[Dep], unusedDeps: List[PackageDeps]): RIO[GithubClient with BuildozerClient with Console, Unit]
  }

  trait CreatePullRequest extends ResultNotifier {
    override val notifier: Service = new Service {
      def notify(forkDir: Path, updatedDeps: List[Dep], unusedDeps: List[PackageDeps]): ZIO[GithubClient with BuildozerClient with Console, Throwable, Unit] = {
        val (depsDesc, branch) = branchName(updatedDeps)

        for {
          _ <- GithubClient.createBranch(forkDir, branch)
          _ <- ZIO.effect(applyDepUpdates(forkDir, updatedDeps))
          _ <- applyUnusedDeps(forkDir, unusedDeps)
          _ <- GithubClient.stageAllChanges(forkDir)
          _ <- GithubClient.commit(forkDir, s"zorechka found new versions for deps: $depsDesc #pr")
          _ <- GithubClient.push(forkDir, branch)
        } yield ()
      }
    }

    private def applyUnusedDeps(repoDir: Path, unusedDeps: List[PackageDeps]): RIO[BuildozerClient, List[Unit]] = {
      ZIO.collectAll {
        unusedDeps.flatMap { unusedDep =>
          unusedDep.deps.map { dep =>
            BuildozerClient.deleteDep(repoDir, dep.target, dep.dep)
          }
        }
      }
    }

    private def applyDepUpdates(repoDir: Path, deps: List[Dep]): Unit = {
      val regex = """artifact = "(.+)",""".r
      deps.foreach { dep =>
        val file = repoDir
          .resolve("third_party")
          .resolve(dep.groupId.replaceAll("\\.", "_") + ".bzl")

        if (file.toFile.exists()) {
          println(s"Rewriting deps for ${file.toAbsolutePath} to $dep")

          val lines = Files.readAllLines(file)
          val result = lines.asScala.map { line =>
            regex.findFirstMatchIn(line) match {
              case Some(m) if line.contains(s"${dep.groupId}:${dep.artifactId}:") =>
                line.replace(m.group(1), s"${dep.groupId}:${dep.artifactId}:${dep.version}")
              case _ => line
            }
          }
          Files.write(file, result.asJava)
        }
      }
    }


    private def branchName(deps: List[Dep]) = {
      val depsSample = deps.map(_.branchKey()).take(3).mkString("_")
      val depsDesc = (if (depsSample.length > 90) depsSample.substring(0, 90) else depsSample) + (if (deps.size > 3) s"_and_${deps.size - 3}_more" else "")
      (depsDesc, s"feature/update-deps-$depsDesc")
    }
  }

  trait PrintPullRequestInfo extends ResultNotifier {
    override val notifier: Service = new Service {
      override def notify(forkDir: Path, updatedDeps: List[Dep], unusedDeps: List[PackageDeps]): RIO[GithubClient with BuildozerClient with Console, Unit] = {
        ZIO.accessM[Console](_.console.putStrLn(
          s"""
             |Going to update:
             |${updatedDeps.mkString("\n")}
             |
             |Going to remove:
             |${unusedDeps.mkString("\n")}
             |""".stripMargin))
      }
    }
  }

  def notify(forkDir: Path, updatedDeps: List[Dep], unusedDeps: List[PackageDeps]): ZIO[ResultNotifier with GithubClient with BuildozerClient with Console, Throwable, Unit] =
    ZIO.accessM[ResultNotifier with GithubClient with BuildozerClient  with Console](_.notifier.notify(forkDir, updatedDeps, unusedDeps))

} 
Example 22
Source File: ThirdPartyDepsAnalyzer.scala    From zorechka-bot   with MIT License 5 votes vote down vote up
package com.wix.zorechka.service

import com.wix.zorechka.{Dep, ForkData}
import com.wix.zorechka.clients.{BazelClient, MavenCentralClient}
import zio.{RIO, ZIO}
import zio.console.{Console, putStrLn}

trait ThirdPartyDepsAnalyzer {
  val analyzer: ThirdPartyDepsAnalyzer.Service
}

object ThirdPartyDepsAnalyzer {
  trait Service {
    def findLatest(forkData: ForkData): ZIO[MavenCentralClient with BazelClient with Console, Throwable, List[Dep]]
  }

  trait Live extends ThirdPartyDepsAnalyzer {
    override val analyzer: Service = new Service {
      override def findLatest(forkData: ForkData): ZIO[MavenCentralClient with BazelClient with Console, Throwable, List[Dep]] = {
        for {
          deps <- BazelClient.foundDeps(forkData.forkDir)
          _ <- putStrLn(s"Found ${deps.size} in ${forkData.repo}")
          latestVersions <- latestVersions(deps)
          updatedDeps = latestVersions.filter {
            latestDep => deps
              .find(_.mapKey() == latestDep.mapKey())
              .exists(current => isNewer(latestDep, current))
          }
        } yield updatedDeps
      }

      private def latestVersions(deps: Seq[Dep]): ZIO[MavenCentralClient, Throwable, List[Dep]] = {
        ZIO.foreach(deps)(dep => ZIO.accessM[MavenCentralClient] {
          _.client.allVersions(dep).map(listOfDeps => if (listOfDeps.isEmpty) dep else listOfDeps.max)
        })
      }

      private def isNewer(latest: Dep, current: Dep): Boolean = Ordering[Dep].gt(latest, current)
    }
  }

  def findLatest(forkData: ForkData): RIO[ThirdPartyDepsAnalyzer with MavenCentralClient with BazelClient with Console, List[Dep]] = {
    ZIO.accessM[ThirdPartyDepsAnalyzer with MavenCentralClient with BazelClient with Console](_.analyzer.findLatest(forkData))
  }
} 
Example 23
Source File: UnusedDepsAnalyser.scala    From zorechka-bot   with MIT License 5 votes vote down vote up
package com.wix.zorechka.service

import com.wix.zorechka.ForkData
import com.wix.zorechka.clients.{BazelClient, BuildPackage, BuildTarget, BuildozerClient}
import com.wix.zorechka.repos.UnusedDepCache
import zio.{RIO, ZIO}
import zio.console.Console
import zio.console._

case class TargetDep(target: BuildTarget, dep: String)

case class PackageDeps(buildPackage: BuildPackage, deps: List[TargetDep])

trait UnusedDepsAnalyser {
  val unusedDepsAnalyser: UnusedDepsAnalyser.Service
}

object UnusedDepsAnalyser {

  trait Service {
    def findUnused(forkData: ForkData): RIO[BuildozerClient with BazelClient with BuildozerClient with Console with UnusedDepCache, List[PackageDeps]]
  }

  trait Live extends UnusedDepsAnalyser {
    override val unusedDepsAnalyser: Service = new Service {
      def findUnused(forkData: ForkData): RIO[BuildozerClient with BazelClient with Console with UnusedDepCache, List[PackageDeps]] = for {
        targets <- BazelClient.allBuildTargets(forkData.forkDir)
        _ <- putStrLn(s"Found ${targets.length} build targets")
        unusedDeps <- ZIO.collectAll(targets.take(5).map(target => checkPackage(forkData, target)))
      } yield unusedDeps
    }

    private def checkPackage(forkData: ForkData, buildPackage: BuildPackage): RIO[BuildozerClient with BazelClient with Console with UnusedDepCache, PackageDeps] = for {
      targets <- BuildozerClient.packageDeps(forkData.forkDir, buildPackage)
      _ <- putStrLn(s"Found ${targets.length} targets in build package: $buildPackage")

      targetWithCacheStatus <- ZIO.foreach(targets) { target =>
        UnusedDepCache.isCached(forkData.repo.url, buildPackage.value, buildPackage.buildFileHash).map(_ -> target)
      }
      uncachedTargets = targetWithCacheStatus.filter(!_._1).map(_._2)

      depsWithUsage <- ZIO.collectAll {
        for {
          target <- uncachedTargets
          dep <- target.deps
        } yield {
          for {
            _ <- BuildozerClient.deleteDep(forkData.forkDir, target, dep)
            isUnused <- BazelClient.buildTarget(forkData.forkDir, target).foldM(
              _ => BuildozerClient.addDep(forkData.forkDir, target, dep) *> ZIO.succeed(false),
              _ => BuildozerClient.addDep(forkData.forkDir, target, dep) *> ZIO.succeed(true)
            )
            _ <- UnusedDepCache.cache(forkData.repo.url, buildPackage.value, buildPackage.buildFileHash)
          } yield isUnused -> TargetDep(target, dep)
        }
      }
    } yield PackageDeps(buildPackage, depsWithUsage.filter(_._1).map(_._2))
  }

  def findUnused(forkData: ForkData): RIO[UnusedDepsAnalyser with BuildozerClient with BazelClient with Console with UnusedDepCache, List[PackageDeps]] =
    ZIO.accessM[UnusedDepsAnalyser with BuildozerClient with BazelClient with Console with UnusedDepCache](_.unusedDepsAnalyser.findUnused(forkData))
} 
Example 24
Source File: Server.scala    From zio-metrics   with Apache License 2.0 5 votes vote down vote up
package zio.metrics.dropwizard

import scala.util.Properties.envOrNone

import cats.data.Kleisli
import org.http4s.server.blaze._
import org.http4s.{ Request, Response }

import zio.{ RIO, ZIO }
import zio.system.System
import zio.clock.Clock
import zio.console.Console
import zio.random.Random
import zio.blocking.Blocking
import zio.interop.catz._
import io.circe.Json
import org.http4s.circe._
import org.http4s.dsl.impl.Root
import org.http4s.dsl.io._
import org.http4s.{ HttpRoutes, Response }
import zio.RIO
import zio.interop.catz._
import zio.metrics.dropwizard.typeclasses._
import zio.metrics.dropwizard.DropwizardExtractor._
import cats.instances.list._
import com.codahale.metrics.MetricRegistry

object Server {
  val port: Int = envOrNone("HTTP_PORT").fold(9090)(_.toInt)

  type HttpEnvironment = Clock with Console with System with Random with Blocking
  type HttpTask[A]     = RIO[HttpEnvironment, A]

  type KleisliApp = Kleisli[HttpTask, Request[HttpTask], Response[HttpTask]]

  //type HttpApp[R <: Registry] = R => KleisliApp

  def builder[Ctx]: KleisliApp => HttpTask[Unit] =
    (app: KleisliApp) =>
      ZIO
        .runtime[HttpEnvironment]
        .flatMap { implicit rts =>
          BlazeServerBuilder[HttpTask]
            .bindHttp(port)
            .withHttpApp(app)
            .serve
            .compile
            .drain
        }

  def serveMetrics: MetricRegistry => HttpRoutes[Server.HttpTask] =
    registry =>
      HttpRoutes.of[Server.HttpTask] {
        case GET -> Root / filter => {
          println(s"filter: $filter")
          val optFilter = if (filter == "ALL") None else Some(filter)
          RegistryPrinter
            .report[List, Json](registry, optFilter)(
              (k: String, v: Json) => Json.obj((k, v))
            )
            .map(m => Response[Server.HttpTask](Ok).withEntity(m))
        }
      }
} 
Example 25
Source File: ExportersTest.scala    From zio-metrics   with Apache License 2.0 5 votes vote down vote up
package zio.metrics

import zio.{ RIO, Runtime }
import zio.console.putStrLn
import zio.metrics.prometheus._
import zio.metrics.prometheus.helpers._
import zio.metrics.prometheus.exporters.Exporters
import io.prometheus.client.exporter.HTTPServer
import zio.console.Console

object ExportersTest {

  val rt = Runtime.unsafeFromLayer(Registry.live ++ Exporters.live ++ Console.live)

  val exporterTest: RIO[
    Registry with Exporters with Console,
    HTTPServer
  ] =
    for {
      r  <- getCurrentRegistry()
      _  <- initializeDefaultExports(r)
      hs <- http(r, 9090)
      c  <- Counter("ExportersTest", Array("exporter"))
      _  <- c.inc(Array("counter"))
      _  <- c.inc(2.0, Array("counter"))
      h  <- histogram.register("export_histogram", Array("exporter", "method"))
      _  <- h.time(() => Thread.sleep(2000), Array("histogram", "get"))
      s  <- write004(r)
      _  <- putStrLn(s)
    } yield hs

  val program = exporterTest >>= (server => putStrLn(s"Server port: ${server.getPort()}"))

  def main(args: Array[String]): Unit =
    rt.unsafeRun(program)
} 
Example 26
Source File: Logging.scala    From zio-logging   with Apache License 2.0 5 votes vote down vote up
package zio.logging

import zio._
import zio.clock.Clock
import zio.console.Console

object Logging {

  def console(
    format: (LogContext, => String) => String = (_, s) => s,
    rootLoggerName: Option[String] = None
  ): ZLayer[Console with Clock, Nothing, Logging] =
    make(
      LogWriter.ColoredLogWriter(format),
      rootLoggerName
    )

  val context: URIO[Logging, LogContext] =
    ZIO.accessM[Logging](_.get.logContext)

  def debug(line: => String): ZIO[Logging, Nothing, Unit] =
    ZIO.accessM[Logging](_.get.debug(line))

  def error(line: => String): ZIO[Logging, Nothing, Unit] =
    ZIO.accessM[Logging](_.get.error(line))

  def error(line: => String, cause: Cause[Any]): ZIO[Logging, Nothing, Unit] =
    ZIO.accessM[Logging](_.get.error(line, cause))

  val ignore: Layer[Nothing, Logging] =
    make((_, _) => ZIO.unit)

  def info(line: => String): ZIO[Logging, Nothing, Unit] =
    ZIO.accessM[Logging](_.get.info(line))

  def log(level: LogLevel)(line: => String): ZIO[Logging, Nothing, Unit] =
    ZIO.accessM[Logging](_.get.log(level)(line))

  def locally[A, R <: Logging, E, A1](fn: LogContext => LogContext)(zio: ZIO[R, E, A1]): ZIO[Logging with R, E, A1] =
    ZIO.accessM(_.get.locally(fn)(zio))

  def locallyM[A, R <: Logging, E, A1](
    fn: LogContext => URIO[R, LogContext]
  )(zio: ZIO[R, E, A1]): ZIO[Logging with R, E, A1] =
    ZIO.accessM(_.get.locallyM(fn)(zio))

  def make[R](
    logger: LogWriter[R],
    rootLoggerName: Option[String] = None
  ): ZLayer[R, Nothing, Logging] =
    ZLayer.fromEffect(
      ZIO
        .environment[R]
        .flatMap(env =>
          FiberRef
            .make(LogContext.empty)
            .tap(_.getAndUpdateSome {
              case ctx if rootLoggerName.isDefined =>
                ctx.annotate(LogAnnotation.Name, rootLoggerName.toList)
            })
            .map { ref =>
              new Logger[String] {
                def locally[R1, E, A](f: LogContext => LogContext)(zio: ZIO[R1, E, A]): ZIO[R1, E, A] =
                  ref.get.flatMap(context => ref.locally(f(context))(zio))

                def log(line: => String): UIO[Unit] =
                  ref.get.flatMap(context => logger.writeLog(context, line).provide(env))

                def logContext: UIO[LogContext] = ref.get
              }
            }
        )
    )

  def throwable(line: => String, t: Throwable): ZIO[Logging, Nothing, Unit] =
    ZIO.accessM[Logging](_.get.throwable(line, t))

  def trace(line: => String): ZIO[Logging, Nothing, Unit] =
    ZIO.accessM[Logging](_.get.trace(line))

  def warn(line: => String): ZIO[Logging, Nothing, Unit] =
    ZIO.accessM[Logging](_.get.warn(line))
} 
Example 27
Source File: LogWriter.scala    From zio-logging   with Apache License 2.0 5 votes vote down vote up
package zio.logging

import java.time.OffsetDateTime

import zio.{ Cause, URIO }
import zio.clock.{ currentDateTime, Clock }
import zio.console.{ putStrLn, Console }
import zio.logging.LogDatetimeFormatter.humanReadableDateTimeFormatter
import zio.logging.LogLevel._

import scala.io.AnsiColor._

trait LogWriter[R] {
  def writeLog(context: LogContext, line: => String): URIO[R, Unit]
}

object LogWriter {

  private val NL = System.lineSeparator()

  type LineFormatter = (LogContext, => String) => String

  case class SimpleConsoleLogWriter(format: LineFormatter = (_, s) => s) extends LogWriter[Console with Clock] {
    override def writeLog(context: LogContext, line: => String): URIO[Console with Clock, Unit] =
      for {
        date      <- currentDateTime.orDie
        level      = context(LogAnnotation.Level)
        loggerName = context(LogAnnotation.Name)
        maybeError = context
                       .get(LogAnnotation.Throwable)
                       .map(Cause.fail)
                       .orElse(context.get(LogAnnotation.Cause))
                       .map(cause => NL + cause.prettyPrint)
                       .getOrElse("")
        _         <- putStrLn(
                       humanReadableDateTimeFormatter
                         .format(date) + " " + level + " " + loggerName + " " + format(context, line) + " " + maybeError
                     )
      } yield ()
  }

  case class ColoredLogWriter(lineFormat: LineFormatter = (_, s) => s) extends LogWriter[Console with Clock] {
    private def withColor(color: String, s: String): String = s"$color$s$RESET"

    private def highlightLog(level: LogLevel, message: String): String = {
      val color = level match {
        case Error => RED
        case Warn  => YELLOW
        case Info  => CYAN
        case Debug => GREEN
        case Trace => MAGENTA
        case _     => RESET
      }
      withColor(color, message)
    }

    private def format(
      line: => String,
      time: OffsetDateTime,
      level: LogLevel,
      loggerName: String,
      maybeError: Option[String]
    ): String = {
      val logTag  = highlightLog(level, level.render)
      val logTime = withColor(BLUE, humanReadableDateTimeFormatter.format(time))
      val logMsg  =
        f"$logTime $logTag%14s [${withColor(WHITE, loggerName)}] ${highlightLog(level, line)}"
      maybeError.fold(logMsg)(err => s"$logMsg$NL${highlightLog(level, err)}")
    }

    override def writeLog(context: LogContext, line: => String): URIO[Console with Clock, Unit] =
      for {
        date      <- currentDateTime.orDie
        level      = context.get(LogAnnotation.Level)
        loggerName = context(LogAnnotation.Name)
        maybeError = context
                       .get(LogAnnotation.Throwable)
                       .map(Cause.fail)
                       .orElse(context.get(LogAnnotation.Cause))
                       .map(_.prettyPrint)
        _         <- putStrLn(format(lineFormat(context, line), date, level, loggerName, maybeError))
      } yield ()
  }
} 
Example 28
Source File: AccessibleMacroExample.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio.examples.macros

import zio.console.Console
import zio.macros.accessible
import zio.random.Random
import zio.stream.{ZSink, ZStream}
import zio.{Chunk, Has, IO, RIO, UIO, URIO, ZIO, ZLayer, random}

@accessible
object AccessibleMacroExample {

  type AccessibleMacroExample = Has[AccessibleMacroExample.Service]

  trait Foo { val value: String }
  case class Bar(value: String) extends Foo
  case class Wrapped[T](value: T)

  trait Service {

    val foo: UIO[Unit]
    def bar(n: Int): UIO[Unit]
    def baz(x: Int, y: Int): IO[String, Int]
    def poly[A](a: A): IO[Long, A]
    def poly2[A <: Foo](a: Wrapped[A]): IO[String, List[A]]
    def dependent(n: Int): ZIO[Random, Long, Int]
    val value: String
    def function(n: Int): String
    def stream(n: Int): ZStream[Any, String, Int]
    def sink(n: Int): ZSink[Any, Nothing, Int, Nothing, Chunk[Int]]
  }

  val live: ZLayer[Console, Nothing, Has[Service]] =
    ZLayer.fromService(console =>
      new Service {
        val foo: UIO[Unit]                                      = UIO.unit
        def bar(n: Int): UIO[Unit]                              = console.putStrLn(s"bar $n")
        def baz(x: Int, y: Int): IO[String, Int]                = UIO.succeed(x + y)
        def poly[A](a: A): IO[Long, A]                          = UIO.succeed(a)
        def poly2[A <: Foo](a: Wrapped[A]): IO[String, List[A]] = UIO.succeed(List(a.value))
        def dependent(n: Int): ZIO[Random, Long, Int]           = random.nextIntBounded(n)
        val value: String                                       = "foo"
        def function(n: Int): String                            = s"foo $n"
        def stream(n: Int): ZStream[Any, String, Int]           = ZStream.fromIterable(List(1, 2, 3))
        def sink(n: Int): ZSink[Any, Nothing, Int, Nothing, Chunk[Int]]  = ZSink.collectAll
      }
    )

  // can use accessors even in the same compilation unit
  val program: URIO[AccessibleMacroExample with Random, (Int, String, Long, List[Foo], Int, String, String, ZStream[Any, String, Int], ZSink[Any, Nothing, Int, Nothing, Chunk[Int]])] =
    for {
      _  <- AccessibleMacroExample.foo
      _  <- AccessibleMacroExample.bar(1)
      v1 <- AccessibleMacroExample.baz(2, 3).orDieWith(_ => new Exception)
      v2 <- AccessibleMacroExample.poly("foo").orDieWith(_ => new Exception)
      v3 <- AccessibleMacroExample.poly(4L).orDieWith(_ => new Exception)
      v4 <- AccessibleMacroExample.poly2(Wrapped(Bar("bar"))).orDieWith(_ => new Exception)
      v5 <- AccessibleMacroExample.dependent(5).orDieWith(_ => new Exception)
      v6 <- AccessibleMacroExample.value.orDie
      v7 <- AccessibleMacroExample.function(6).orDie
      v8 <- AccessibleMacroExample.stream(7)
      v9 <- AccessibleMacroExample.sink(8)
    } yield (v1, v2, v3, v4, v5, v6, v7, v8, v9)

  // sanity check
  val _foo                            : URIO[AccessibleMacroExample, Unit]                                         = AccessibleMacroExample.foo
  def _bar(n: Int)                    : URIO[AccessibleMacroExample, Unit]                                         = AccessibleMacroExample.bar(n)
  def _baz(x: Int, y: Int)            : ZIO[AccessibleMacroExample, String, Int]                                   = AccessibleMacroExample.baz(x, y)
  def _poly[A](a: A)                  : ZIO[AccessibleMacroExample, Long, A]                                       = AccessibleMacroExample.poly(a)
  def _poly2[A <: Foo](a: Wrapped[A]) : ZIO[AccessibleMacroExample, String, List[A]]                               = AccessibleMacroExample.poly2(a)
  def _dependent(n: Int)              : ZIO[AccessibleMacroExample with Random, Long, Int]                         = AccessibleMacroExample.dependent(n)
  def _value                          : RIO[AccessibleMacroExample, String]                                        = AccessibleMacroExample.value
  def _function(n: Int)               : RIO[AccessibleMacroExample, String]                                        = AccessibleMacroExample.function(n)
  def _stream(n: Int)                 : ZIO[AccessibleMacroExample, Nothing, ZStream[Any, String, Int]]            = AccessibleMacroExample.stream(n)
  def _sink(n: Int)                   : ZIO[AccessibleMacroExample, Nothing, ZSink[Any, Nothing, Int, Nothing, Chunk[Int]]] = AccessibleMacroExample.sink(n)

  // macro autogenerates accessors for `foo`, `bar`, `baz`, `poly`, `poly2`, `value` and `function` below
} 
Example 29
Source File: FlywayMigrator.scala    From zorechka-bot   with MIT License 5 votes vote down vote up
package com.wix.zorechka.repos

import com.zaxxer.hikari.HikariDataSource
import doobie.hikari.HikariTransactor
import org.flywaydb.core.Flyway
import zio.console.{Console, putStrLn}
import zio.{Task, ZIO}

trait FlywayMigrator {
  val flywayMigrator: FlywayMigrator.Service
}

object FlywayMigrator {

  trait Service {
    def migrate(dbTransactor: HikariTransactor[Task]): ZIO[Console, Throwable, Unit]
  }

  trait Live extends FlywayMigrator {

    val flywayMigrator: Service = new Service {
      override def migrate(dbTransactor: HikariTransactor[Task]): ZIO[Console, Throwable, Unit] = for {
        _ <- putStrLn("Starting Flyway migration")
        _ <- dbTransactor.configure(dataSource => loadFlyWayAndMigrate(dataSource))
        _ <- putStrLn("Finished Flyway migration")
      } yield ()
    }

    private def loadFlyWayAndMigrate(dataSource: HikariDataSource) = ZIO.effect {
      Flyway.configure()
        .dataSource(dataSource)
        .load()
        .migrate()
    }
  }

  def migrate(dbTransactor: HikariTransactor[Task]): ZIO[FlywayMigrator with Console, Throwable, Unit] =
    ZIO.accessM[FlywayMigrator with Console](_.flywayMigrator.migrate(dbTransactor))
} 
Example 30
Source File: ComposedMockSpec.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio.test.mock

import zio.clock.Clock
import zio.console.Console
import zio.duration._
import zio.random.Random
import zio.system.System
import zio.test.{ assertM, suite, testM, Assertion, ZIOBaseSpec }
import zio.{ clock, console, random, system, Has, Tag, ULayer, ZIO }

object ComposedMockSpec extends ZIOBaseSpec {

  import Assertion._
  import Expectation._

  private def testValueComposed[R1 <: Has[_]: Tag, E, A](name: String)(
    mock: ULayer[R1],
    app: ZIO[R1, E, A],
    check: Assertion[A]
  ) = testM(name) {
    val result = mock.build.use[R1, E, A](app.provide _)
    assertM(result)(check)
  }

  def spec = suite("ComposedMockSpec")(
    suite("mocking composed environments")(
      {
        val cmd1     = MockClock.NanoTime(value(42L))
        val cmd2     = MockConsole.PutStrLn(equalTo("42"))
        val composed = (cmd1 ++ cmd2)

        val program =
          for {
            time <- clock.nanoTime
            _    <- console.putStrLn(time.toString)
          } yield ()

        testValueComposed[Clock with Console, Nothing, Unit]("Console with Clock")(composed, program, isUnit)
      }, {
        val cmd1 = MockRandom.NextInt(value(42))
        val cmd2 = MockClock.Sleep(equalTo(42.seconds))
        val cmd3 = MockSystem.Property(equalTo("foo"), value(None))
        val cmd4 = MockConsole.PutStrLn(equalTo("None"))

        val composed = (cmd1 ++ cmd2 ++ cmd3 ++ cmd4)

        val program =
          for {
            n <- random.nextInt
            _ <- clock.sleep(n.seconds)
            v <- system.property("foo")
            _ <- console.putStrLn(v.toString)
          } yield ()

        testValueComposed[Random with Clock with System with Console, Throwable, Unit](
          "Random with Clock with System with Console"
        )(composed, program, isUnit)
      }
    )
  )
} 
Example 31
Source File: PlatformSpecific.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio

import zio.blocking.Blocking
import zio.clock.Clock
import zio.console.Console
import zio.random.Random
import zio.system.System

private[zio] trait PlatformSpecific {
  type ZEnv = Clock with Console with System with Random with Blocking

  object ZEnv {

    private[zio] object Services {
      val live: ZEnv =
        Has.allOf[Clock.Service, Console.Service, System.Service, Random.Service, Blocking.Service](
          Clock.Service.live,
          Console.Service.live,
          System.Service.live,
          Random.Service.live,
          Blocking.Service.live
        )
    }

    val any: ZLayer[ZEnv, Nothing, ZEnv] =
      ZLayer.requires[ZEnv]

    val live: Layer[Nothing, ZEnv] =
      Clock.live ++ Console.live ++ System.live ++ Random.live ++ Blocking.live
  }
} 
Example 32
Source File: PlatformSpecific.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio

import zio.clock.Clock
import zio.console.Console
import zio.random.Random
import zio.system.System

private[zio] trait PlatformSpecific {
  type ZEnv = Clock with Console with System with Random

  object ZEnv {

    private[zio] object Services {
      val live: ZEnv =
        Has.allOf[Clock.Service, Console.Service, System.Service, Random.Service](
          Clock.Service.live,
          Console.Service.live,
          System.Service.live,
          Random.Service.live
        )
    }

    val any: ZLayer[ZEnv, Nothing, ZEnv] =
      ZLayer.requires[ZEnv]

    val live: Layer[Nothing, ZEnv] =
      Clock.live ++ Console.live ++ System.live ++ Random.live
  }
} 
Example 33
Source File: PlatformSpecific.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio

import zio.clock.Clock
import zio.console.Console
import zio.random.Random
import zio.system.System

private[zio] trait PlatformSpecific {
  type ZEnv = Clock with Console with System with Random

  object ZEnv {

    object Services { 
      val live: ZEnv =
        Has.allOf[Clock.Service, Console.Service, System.Service, Random.Service](Clock.Service.live, Console.Service.live, System.Service.live, Random.Service.live)
      }

    val any: ZLayer[ZEnv, Nothing, ZEnv] =
      ZLayer.requires[ZEnv]

    val live: Layer[Nothing, ZEnv] =
      Clock.live ++ Console.live ++ System.live ++ Random.live
  }
} 
Example 34
Source File: Logger.scala    From ZparkIO   with MIT License 5 votes vote down vote up
package com.leobenkel.zparkio.Services

import zio.console.Console
import zio.{Has, Task, ZIO, ZLayer}

object Logger {
  type Logger = Has[Logger.Service]

  trait Service {
    def info(txt:  => String): Task[Unit]
    def error(txt: => String): Task[Unit]
    def debug(txt: => String): Task[Unit]
  }

  trait Factory {
    protected def makeLogger(
      console: zio.console.Console.Service
    ): ZIO[Any, Throwable, Logger.Service]

    private[zparkio] def assembleLogger: ZLayer[Console, Throwable, Logger] =
      ZLayer.fromServiceM(makeLogger)
  }

  object Factory {
    def apply(make: Console.Service => Service): Factory = new Factory {
      override protected def makeLogger(console: Console.Service): ZIO[Any, Throwable, Service] = {
        Task(make(console))
      }
    }
  }

  def displayAllErrors(ex: Throwable): ZIO[Logger, Throwable, Unit] = {
    for {
      _ <- Logger.error(s"!!! Error: ${ex.toString}:")
      _ <- ZIO.foreach(ex.getStackTrace)(st => Logger.error(s"  -   $st"))
      _ <- Option(ex.getCause)
        .fold[ZIO[Logger, Throwable, Unit]](Task(()))(displayAllErrors)
    } yield {
      ()
    }
  }

  val Live: ZLayer[Console, Nothing, Logger] = ZLayer.fromService { console =>
    new Logger.Service {
      override def info(txt:  => String): Task[Unit] = console.putStrLn(s"[INFO] $txt")
      override def error(txt: => String): Task[Unit] = console.putStrLn(s"[ERROR] $txt")
      override def debug(txt: => String): Task[Unit] = console.putStrLn(s"[DEBUG] $txt")
    }
  }

  def info(txt: => String): ZIO[Logger, Throwable, Unit] = ZIO.accessM[Logger](_.get.info(txt))

  def error(txt: => String): ZIO[Logger, Throwable, Unit] = ZIO.accessM[Logger](_.get.error(txt))

  def debug(txt: => String): ZIO[Logger, Throwable, Unit] = ZIO.accessM[Logger](_.get.debug(txt))
} 
Example 35
Source File: ZLogsSuite.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu.logging.zlogs

import ch.qos.logback.classic.Logger
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.read.ListAppender
import derevo.derive
import io.circe.JsonObject
import io.circe.syntax._
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.slf4j.LoggerFactory
import tofu.logging.LogTree
import tofu.logging.derivation.loggable
import tofu.logging.impl.ContextMarker
import tofu.syntax.logging._
import zio.blocking.Blocking
import zio.clock.Clock
import zio.console.Console
import zio.{Has, Runtime, URIO, URLayer, ZLayer}

import scala.jdk.CollectionConverters._

class ZLogsSuite extends AnyFlatSpec with Matchers {
  import ZLogsSuite.MyLogging

  val expr = debug"hello" *> info"world"

  "ZLogs" should "log the context" in {
    val appender = ZLogsSuite.attachList()
    Runtime.default.unsafeRun(expr.provideLayer(ZLogsSuite.fullLayer))
    val items    = appender.list.asScala

    val expected = JsonObject("foo" -> "kojima".asJson, "bar" -> 2.asJson).asJson

    items.map(_.getMarker).collect {
      case ContextMarker(ctx, _) => LogTree(ctx)
    } should ===(List.fill(2)(expected))
  }
}

object ZLogsSuite {
  val Name = "zio logs suite"

  @derive(loggable)
  case class FooService(foo: String)

  val fooLayer = ZLayer.succeed(FooService("kojima"))

  @derive(loggable)
  case class BarService(bar: Int)

  val barLayer = ZLayer.succeed(BarService(2))

  type Foo = Has[FooService]
  type Bar = Has[BarService]

  type LogEnv    = Foo with Bar
  type SystemEnv = Blocking with Clock with Console
  type MyEnv     = SystemEnv with LogEnv with ZLog[LogEnv]
  type TIO[+A]   = URIO[MyEnv, A]

  val logs: ZLogs[Foo with Bar] = ZLogs.build.of[Foo].of[Bar].make

  implicit val MyLogging: ZLogging[MyEnv] = ZLogs.access[MyEnv, LogEnv]

  implicitly[ZioHasBuilder.UnHas[Foo]](ZioHasBuilder.UnHas.unHas[FooService])
  val fullLayer: URLayer[Blocking with Console with Clock, MyEnv] =
    ZLayer.identity[SystemEnv] ++ fooLayer ++ barLayer ++ ZLogs.named(logs, Name)

  def attachList() = {
    val logger   = LoggerFactory.getLogger(Name).asInstanceOf[Logger]
    val appender = new ListAppender[ILoggingEvent]
    appender.start()
    logger.addAppender(appender)
    appender
  }
} 
Example 36
Source File: implicits.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu.zioInstances
import java.io.IOException

import tofu.optics.{Contains, Extract}
import zio.clock.Clock
import zio.console.Console
import zio.random.Random
import zio.{Has, Tag}

object implicits extends ZioTofuImplicits1

private[zioInstances] class ZioTofuImplicits1 extends ZioTofuImplicits2 {
  @inline final implicit def rioTofuImplicit[R]: RioTofuInstance[R] = rioTofuInstance

  @inline final implicit def zioTofuErrorsToImplicit[R, E]: ZioTofuErrorsToInstance[R, E, Nothing] =
    zioTofuErrorsToInstance

  @inline final implicit def zioTofuErrorsExtractToImplicit[R, E, E1: * Extract E]: ZioTofuErrorsToInstance[R, E, E1] =
    zioTofuExtractErrorsInstance

  @inline final implicit def zioTofuTimeoutImplicit[R <: Clock, E]: ZioTofuTimeoutInstance[R, E] =
    zioTofuTimeoutInstance

  @inline final implicit def zioTofuConcurrentImplicit[R1, E1, R, E]: ZioTofuConcurrentInstance[R1, E1, R, E] =
    zioTofuConcurrentInstance

  @inline final implicit def zioTofuConsoleImplicit[R <: Console, E >: IOException]: ZioTofuConsoleInstance[R, E] =
    zioTofuConsoleInstance

  @inline final implicit def zioTofuRandomImplicit[R <: Random, E]: ZioTofuRandomInstance[R, E] = zioTofuRandomInstance

  @inline final implicit def zioTofuContainsUnliftImplicit[R1, R2: * Contains R1, E]
      : ZioTofuContainsUnliftInstance[R1, R2, E] =
    zioTofuContainsUnliftInstance[R1, R2, E]

  @inline final implicit def rioTofuUnliftIOImplicit[R]: RioTofuUnliftIOInstance[R] = rioTofuUnliftIOInstance

}
private[zioInstances] trait ZioTofuImplicits2 extends ZioTofuImplicits3 {
  @inline final implicit def zioTofuImplicit[R, E]: ZioTofuInstance[R, E]               = zioTofuInstance
  @inline final implicit def zioTofuWithRunImplicit[R, E]: ZioTofuWithRunInstance[R, E] = zioTofuWithRunInstance
}

private[zioInstances] trait ZioTofuImplicits3 {
  @inline final implicit def zioTofuUnliftHasImplicit[R <: Has[_], E, C: Tag]: ZioTofuUnliftHasInstance[R, E, C] =
    zioTofuUnliftHasInstance
} 
Example 37
Source File: ZioInstances.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu
package zioInstances

import java.io.IOException
import tofu.optics.functions.extractSubtype
import tofu.optics.{Contains, Extract}
import zio.clock.Clock
import zio.console.Console
import zio.random.Random
import zio.{Has, Tag}

private[zioInstances] class ZioInstances {
  private[this] val rioTofuInstanceAny: RioTofuInstance[Any] = new RioTofuInstance
  final def rioTofuInstance[R]: RioTofuInstance[R]           = rioTofuInstanceAny.asInstanceOf[RioTofuInstance[R]]

  private[this] val zioErrorsToInstanceAny: ZioTofuErrorsToInstance[Any, Any, Nothing]             =
    new ZioTofuErrorsToInstance[Any, Any, Nothing]()(extractSubtype[Nothing, Any])
  final def zioTofuErrorsToInstance[R, E]: ZioTofuErrorsToInstance[R, E, Nothing]                  =
    zioErrorsToInstanceAny.asInstanceOf[ZioTofuErrorsToInstance[R, E, Nothing]]
  final def zioTofuExtractErrorsInstance[R, E, E1: * Extract E]: ZioTofuErrorsToInstance[R, E, E1] =
    new ZioTofuErrorsToInstance

  private[this] val zioTofuTimeoutInstanceAny: ZioTofuTimeoutInstance[Clock, Any] = new ZioTofuTimeoutInstance
  final def zioTofuTimeoutInstance[R <: Clock, E]: ZioTofuTimeoutInstance[R, E]   =
    zioTofuTimeoutInstanceAny.asInstanceOf[ZioTofuTimeoutInstance[R, E]]

  private[this] val zioTofuConcurrentInstanceAny: ZioTofuConcurrentInstance[Any, Nothing, Any, Nothing] =
    new ZioTofuConcurrentInstanceUIO

  final def zioTofuConcurrentInstance[R1, E1, R, E]: ZioTofuConcurrentInstance[R1, E1, R, E] =
    zioTofuConcurrentInstanceAny.asInstanceOf[ZioTofuConcurrentInstance[R1, E1, R, E]]

  private[this] val zioTofuConsoleInstanceAny: ZioTofuConsoleInstance[Console, IOException] = new ZioTofuConsoleInstance

  final def zioTofuConsoleInstance[R <: Console, E >: IOException]: ZioTofuConsoleInstance[R, E] =
    zioTofuConsoleInstanceAny.asInstanceOf[ZioTofuConsoleInstance[R, E]]

  private[this] val zioTofuRandomInstanceAny: ZioTofuRandomInstance[Random, Nothing] = new ZioTofuRandomInstance

  final def zioTofuRandomInstance[R <: Random, E]: ZioTofuRandomInstance[R, E] =
    zioTofuRandomInstanceAny.asInstanceOf[ZioTofuRandomInstance[R, E]]

  final def zioTofuContainsUnliftInstance[R1, R2: * Contains R1, E]: ZioTofuContainsUnliftInstance[R1, R2, E] =
    new ZioTofuContainsUnliftInstance[R1, R2, E]

  private[this] val rioTofuUnliftIOInstanceAny: RioTofuUnliftIOInstance[Any] = new RioTofuUnliftIOInstance
  final def rioTofuUnliftIOInstance[R]: RioTofuUnliftIOInstance[R]           =
    rioTofuUnliftIOInstanceAny.asInstanceOf[RioTofuUnliftIOInstance[R]]

  private[this] val rioTofuUnsafeExecFutureInstanceAny: RioTofuUnsafeExecFutureInstance[Any] =
    new RioTofuUnsafeExecFutureInstance
  final def rioTofuUnsafeExecFutureInstance[R]: RioTofuUnsafeExecFutureInstance[R]           =
    rioTofuUnsafeExecFutureInstanceAny.asInstanceOf[RioTofuUnsafeExecFutureInstance[R]]

  private[this] val zioTofuInstanceAny: ZioTofuInstance[Any, Any] = new ZioTofuInstance
  final def zioTofuInstance[R, E]: ZioTofuInstance[R, E]          = zioTofuInstanceAny.asInstanceOf[ZioTofuInstance[R, E]]

  private[this] val zioTofuWithRunInstanceAny                          = new ZioTofuWithRunInstance[Any, Any]
  final def zioTofuWithRunInstance[R, E]: ZioTofuWithRunInstance[R, E] =
    zioTofuWithRunInstanceAny.asInstanceOf[ZioTofuWithRunInstance[R, E]]

  final def zioTofuUnliftHasInstance[R <: Has[_], E, C: Tag]: ZioTofuUnliftHasInstance[R, E, C] =
    new ZioTofuUnliftHasInstance
}