zio.duration.Duration Scala Examples
The following examples show how to use zio.duration.Duration.
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: K8DnsDiscovery.scala From zio-keeper with Apache License 2.0 | 5 votes |
package zio.keeper.discovery import java.net.UnknownHostException import java.util import javax.naming.directory.InitialDirContext import javax.naming.{ Context, NamingException } import zio.duration.Duration import zio.keeper.{ Error, ServiceDiscoveryError } import zio.logging.Logger import zio.nio.core.{ InetAddress, InetSocketAddress, SocketAddress } import zio.{ IO, UIO, ZIO } private class K8DnsDiscovery( log: Logger[String], serviceDns: InetAddress, serviceDnsTimeout: Duration, servicePort: Int ) extends Discovery.Service { final override val discoverNodes: IO[Error, Set[InetSocketAddress]] = { for { _ <- log.info(s"k8s dns dicovery: $serviceDns, port: $servicePort, timeout: $serviceDnsTimeout") addresses <- lookup(serviceDns, serviceDnsTimeout) nodes <- IO.foreach(addresses)(addr => SocketAddress.inetSocketAddress(addr, servicePort)) } yield nodes.toSet[InetSocketAddress] }.catchAllCause { ex => log.error(s"discovery strategy ${this.getClass.getSimpleName} failed.", ex) *> IO.halt(ex.map(e => ServiceDiscoveryError(e.getMessage))) } private def lookup( serviceDns: InetAddress, serviceDnsTimeout: Duration ): IO[Exception, Set[InetAddress]] = { import scala.jdk.CollectionConverters._ val env = new util.Hashtable[String, String] env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory") env.put(Context.PROVIDER_URL, "dns:") env.put("com.sun.jndi.dns.timeout.initial", serviceDnsTimeout.toMillis.toString) for { dirContext <- IO.effect(new InitialDirContext(env)).refineToOrDie[NamingException] attributes <- UIO.effectTotal(dirContext.getAttributes(serviceDns.hostname, Array("SRV"))) srvAttribute = Option(attributes.get("srv")).toList.flatMap(_.getAll.asScala) addresses <- ZIO.foldLeft(srvAttribute)(Set.empty[InetAddress]) { case (acc, address: String) => extractHost(address) .flatMap(InetAddress.byName) .map(acc + _) .refineToOrDie[UnknownHostException] case (acc, _) => UIO.succeed(acc) } } yield addresses } private def extractHost(server: String): UIO[String] = log.debug(s"k8 dns on response: $server") *> UIO.effectTotal { val host = server.split(" ")(3) host.replaceAll("\\\\.$", "") } }
Example 2
Source File: Window.scala From zio-analytics with Apache License 2.0 | 5 votes |
package zio.analytics import zio.duration.Duration sealed abstract class WindowAssigner { def assign(timestamp: Long): List[Window] } object WindowAssigner { case class Fixed(size: Duration, step: Duration) extends WindowAssigner { def assign(timestamp: Long): List[Window] = { val sizeMillis = size.toMillis val firstStart = (timestamp / sizeMillis) * sizeMillis (firstStart until (firstStart + sizeMillis) by step.toMillis) .filter(bound => bound <= timestamp && bound + sizeMillis > timestamp) .map { lowerBound => Window(lowerBound, lowerBound + sizeMillis - 1) } .toList } } case class Dynamic(gap: Duration) extends WindowAssigner { // TODO def assign(timestamp: Long): List[Window] = ??? } def tumbling(size: Duration): WindowAssigner = Fixed(size, size) def sliding(size: Duration, step: Duration): WindowAssigner = Fixed(size, step) def session(gap: Duration): WindowAssigner = Dynamic(gap) } case class Window(lower: Long, upper: Long) case class Windowed[A](window: Window, value: A)
Example 3
Source File: Selector.scala From zio-nio with Apache License 2.0 | 5 votes |
package zio.nio.channels import java.io.IOException import java.nio.channels.{ ClosedSelectorException, Selector => JSelector, SelectionKey => JSelectionKey } import com.github.ghik.silencer.silent import zio.duration.Duration import zio.nio.channels.spi.SelectorProvider import zio.nio.core.channels.SelectionKey import zio.{ IO, Managed, UIO } import scala.jdk.CollectionConverters._ class Selector(private[nio] val selector: JSelector) { final val provider: UIO[SelectorProvider] = IO.effectTotal(selector.provider()).map(new SelectorProvider(_)) @silent final val keys: IO[ClosedSelectorException, Set[SelectionKey]] = IO.effect(selector.keys()) .map(_.asScala.toSet[JSelectionKey].map(new SelectionKey(_))) .refineToOrDie[ClosedSelectorException] @silent final val selectedKeys: IO[ClosedSelectorException, Set[SelectionKey]] = IO.effect(selector.selectedKeys()) .map(_.asScala.toSet[JSelectionKey].map(new SelectionKey(_))) .refineToOrDie[ClosedSelectorException] final def removeKey(key: SelectionKey): IO[ClosedSelectorException, Unit] = IO.effect(selector.selectedKeys().remove(key.selectionKey)) .unit .refineToOrDie[ClosedSelectorException] final val select: IO[Exception, Int] = IO.effect(selector.select()).refineToOrDie[IOException] final val wakeup: IO[Nothing, Selector] = IO.effectTotal(selector.wakeup()).map(new Selector(_)) final private[channels] val close: IO[IOException, Unit] = IO.effect(selector.close()).refineToOrDie[IOException].unit } object Selector { final val make: Managed[IOException, Selector] = { val open = IO.effect(new Selector(JSelector.open())).refineToOrDie[IOException] Managed.make(open)(_.close.orDie) } }
Example 4
Source File: Selector.scala From zio-nio with Apache License 2.0 | 5 votes |
package zio.nio.core.channels import java.io.IOException import java.nio.channels.{ ClosedSelectorException, Selector => JSelector, SelectionKey => JSelectionKey } import com.github.ghik.silencer.silent import zio.duration.Duration import zio.nio.core.channels.spi.SelectorProvider import zio.{ IO, UIO } import scala.jdk.CollectionConverters._ class Selector(private[nio] val selector: JSelector) { final val isOpen: UIO[Boolean] = IO.effectTotal(selector.isOpen) final val provider: UIO[SelectorProvider] = IO.effectTotal(selector.provider()).map(new SelectorProvider(_)) @silent final val keys: IO[ClosedSelectorException, Set[SelectionKey]] = IO.effect(selector.keys()) .map(_.asScala.toSet[JSelectionKey].map(new SelectionKey(_))) .refineToOrDie[ClosedSelectorException] @silent final val selectedKeys: IO[ClosedSelectorException, Set[SelectionKey]] = IO.effect(selector.selectedKeys()) .map(_.asScala.toSet[JSelectionKey].map(new SelectionKey(_))) .refineToOrDie[ClosedSelectorException] final def removeKey(key: SelectionKey): IO[ClosedSelectorException, Unit] = IO.effect(selector.selectedKeys().remove(key.selectionKey)) .unit .refineToOrDie[ClosedSelectorException] final val select: IO[Exception, Int] = IO.effect(selector.select()).refineToOrDie[IOException] final val wakeup: IO[Nothing, Selector] = IO.effectTotal(selector.wakeup()).map(new Selector(_)) final val close: IO[IOException, Unit] = IO.effect(selector.close()).refineToOrDie[IOException].unit } object Selector { final val make: IO[IOException, Selector] = IO.effect(new Selector(JSelector.open())).refineToOrDie[IOException] }
Example 5
Source File: AsynchronousChannelGroup.scala From zio-nio with Apache License 2.0 | 5 votes |
package zio.nio.core.channels import java.io.IOException import java.nio.channels.{ AsynchronousChannelGroup => JAsynchronousChannelGroup } import java.nio.channels.spi.{ AsynchronousChannelProvider => JAsynchronousChannelProvider } import java.util.concurrent.{ ThreadFactory => JThreadFactory } import java.util.concurrent.TimeUnit import zio.{ IO, UIO } import zio.duration.Duration import scala.concurrent.ExecutionContextExecutorService object AsynchronousChannelGroup { def apply(executor: ExecutionContextExecutorService, initialSize: Int): IO[Exception, AsynchronousChannelGroup] = IO.effect( new AsynchronousChannelGroup( JAsynchronousChannelGroup.withCachedThreadPool(executor, initialSize) ) ) .refineToOrDie[Exception] def apply( threadsNo: Int, threadsFactory: JThreadFactory ): IO[Exception, AsynchronousChannelGroup] = IO.effect( new AsynchronousChannelGroup( JAsynchronousChannelGroup.withFixedThreadPool(threadsNo, threadsFactory) ) ) .refineToOrDie[Exception] def apply(executor: ExecutionContextExecutorService): IO[Exception, AsynchronousChannelGroup] = IO.effect( new AsynchronousChannelGroup(JAsynchronousChannelGroup.withThreadPool(executor)) ) .refineToOrDie[Exception] } class AsynchronousChannelGroup(val channelGroup: JAsynchronousChannelGroup) { def awaitTermination(timeout: Duration): IO[Exception, Boolean] = IO.effect(channelGroup.awaitTermination(timeout.asJava.toMillis, TimeUnit.MILLISECONDS)) .refineToOrDie[Exception] val isShutdown: UIO[Boolean] = IO.effectTotal(channelGroup.isShutdown) val isTerminated: UIO[Boolean] = IO.effectTotal(channelGroup.isTerminated) val provider: UIO[JAsynchronousChannelProvider] = IO.effectTotal(channelGroup.provider()) val shutdown: UIO[Unit] = IO.effectTotal(channelGroup.shutdown()) val shutdownNow: IO[IOException, Unit] = IO.effect(channelGroup.shutdownNow()).refineToOrDie[IOException] }
Example 6
Source File: WatchService.scala From zio-nio with Apache License 2.0 | 5 votes |
package zio.nio.core.file import java.io.IOException import java.nio.file.{ ClosedWatchServiceException, WatchEvent, WatchKey => JWatchKey, WatchService => JWatchService, Watchable => JWatchable, Path => JPath } import java.util.concurrent.TimeUnit import zio.blocking.Blocking import zio.duration.Duration import scala.jdk.CollectionConverters._ import zio.{ IO, UIO, ZIO } trait Watchable { protected def javaWatchable: JWatchable final def register(watcher: WatchService, events: WatchEvent.Kind[_]*): IO[Exception, WatchKey] = IO.effect(new WatchKey(javaWatchable.register(watcher.javaWatchService, events: _*))).refineToOrDie[Exception] final def register( watcher: WatchService, events: Iterable[WatchEvent.Kind[_]], modifiers: WatchEvent.Modifier* ): IO[Exception, WatchKey] = IO.effect(new WatchKey(javaWatchable.register(watcher.javaWatchService, events.toArray, modifiers: _*))) .refineToOrDie[Exception] } object Watchable { def apply(jWatchable: JWatchable): Watchable = new Watchable { override protected val javaWatchable = jWatchable } } final class WatchKey private[file] (private val javaKey: JWatchKey) { def isValid: UIO[Boolean] = UIO.effectTotal(javaKey.isValid) def pollEvents: UIO[List[WatchEvent[_]]] = UIO.effectTotal(javaKey.pollEvents().asScala.toList) def reset: UIO[Boolean] = UIO.effectTotal(javaKey.reset()) def cancel: UIO[Unit] = UIO.effectTotal(javaKey.cancel()) def watchable: UIO[Watchable] = UIO.effectTotal(javaKey.watchable()).map { case javaPath: JPath => Path.fromJava(javaPath) case javaWatchable => Watchable(javaWatchable) } } final class WatchService private (private[file] val javaWatchService: JWatchService) { def close: IO[IOException, Unit] = IO.effect(javaWatchService.close()).refineToOrDie[IOException] def poll: IO[ClosedWatchServiceException, Option[WatchKey]] = IO.effect(Option(javaWatchService.poll()).map(new WatchKey(_))).refineToOrDie[ClosedWatchServiceException] def poll(timeout: Duration): IO[Exception, Option[WatchKey]] = IO.effect(Option(javaWatchService.poll(timeout.toNanos, TimeUnit.NANOSECONDS)).map(new WatchKey(_))) .refineToOrDie[Exception] def take: ZIO[Blocking, Exception, WatchKey] = ZIO .accessM[Blocking](_.get.effectBlocking(new WatchKey(javaWatchService.take()))) .refineToOrDie[Exception] } object WatchService { def forDefaultFileSystem: ZIO[Blocking, Exception, WatchService] = FileSystem.default.newWatchService def fromJava(javaWatchService: JWatchService): WatchService = new WatchService(javaWatchService) }
Example 7
Source File: Wrappers.scala From caliban with Apache License 2.0 | 5 votes |
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 8
Source File: PlayRouter.scala From caliban with Apache License 2.0 | 5 votes |
package caliban import akka.stream.Materializer import play.api.mvc.{ ActionBuilder, AnyContent, ControllerComponents, PlayBodyParsers, Request, Results } import play.api.routing.Router.Routes import play.api.routing.SimpleRouter import play.api.routing.sird._ import zio.Runtime import zio.duration.Duration import scala.concurrent.ExecutionContext case class PlayRouter[R, E]( interpreter: GraphQLInterpreter[R, E], controllerComponents: ControllerComponents, playground: Boolean = true, allowGETRequests: Boolean = true, subscriptions: Boolean = true, skipValidation: Boolean = false, enableIntrospection: Boolean = true, keepAliveTime: Option[Duration] = None )(implicit runtime: Runtime[R], materializer: Materializer) extends SimpleRouter with PlayAdapter { override val actionBuilder: ActionBuilder[Request, AnyContent] = controllerComponents.actionBuilder override val parse: PlayBodyParsers = controllerComponents.parsers implicit val ec: ExecutionContext = controllerComponents.executionContext override def routes: Routes = { case POST(p"/api/graphql") => makePostAction(interpreter, skipValidation, enableIntrospection) case GET( p"/api/graphql" ? q_o"query=$query" & q_o"variables=$variables" & q_o"operationName=$operation" & q_o"extensions=$extensions" ) if allowGETRequests => makeGetAction(interpreter, skipValidation, enableIntrospection)(query, variables, operation, extensions) case GET(p"/ws/graphql") if subscriptions => makeWebSocket(interpreter, skipValidation, enableIntrospection, keepAliveTime) case GET(p"/graphiql") if playground => actionBuilder( Results.Ok .sendResource("graphiql.html")(controllerComponents.executionContext, controllerComponents.fileMimeTypes) ) } }
Example 9
Source File: InProcessDeploy.scala From polynote with Apache License 2.0 | 5 votes |
package polynote.testing.kernel.remote import java.net.InetSocketAddress import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import polynote.kernel.{BaseEnv, GlobalEnv, Kernel} import polynote.kernel.environment.CurrentNotebook import polynote.kernel.logging.Logging import polynote.kernel.remote.{RemoteKernelClient, SocketTransport} import zio.{Fiber, RIO, Ref, ZIO} import zio.duration.Duration class InProcessDeploy(kernelFactory: Kernel.Factory.LocalService, clientRef: Ref[RemoteKernelClient]) extends SocketTransport.Deploy { def deployKernel(transport: SocketTransport, serverAddress: InetSocketAddress): RIO[BaseEnv with GlobalEnv with CurrentNotebook, SocketTransport.DeployedProcess] = { val connectClient = RemoteKernelClient.tapRunThrowable( RemoteKernelClient.Args( Some(serverAddress.getHostString), Some(serverAddress.getPort), Some(kernelFactory)), Some(clientRef)) connectClient.forkDaemon.map(new InProcessDeploy.Process(_)) } } object InProcessDeploy { class Process(fiber: Fiber[Throwable, Int]) extends SocketTransport.DeployedProcess { def exitStatus: RIO[BaseEnv, Option[Int]] = fiber.poll.flatMap { case Some(exit) => ZIO.fromEither(exit.toEither).map(Some(_)) case None => ZIO.succeed(None) } def awaitExit(timeout: Long, timeUnit: TimeUnit): RIO[BaseEnv, Option[Int]] = { fiber.join.disconnect.timeout(Duration(timeout, timeUnit)) } def kill(): RIO[BaseEnv, Unit] = fiber.interrupt.unit } }
Example 10
Source File: HttpClientHighLevelZioWebsocketTest.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.httpclient.zio import sttp.client._ import sttp.client.httpclient.WebSocketHandler import sttp.client.impl.zio.RIOMonadAsyncError import sttp.client.monad.MonadError import sttp.client.testing.ConvertToFuture import sttp.client.testing.HttpTest.wsEndpoint import sttp.client.testing.websocket.HighLevelWebsocketTest import sttp.client.ws.WebSocket import zio.blocking.Blocking import zio.stream.ZStream import sttp.client.impl.zio._ import zio.clock.Clock import zio.{Schedule, ZIO} import scala.concurrent.duration._ import zio.duration.Duration class HttpClientHighLevelZioWebsocketTest extends HighLevelWebsocketTest[BlockingTask, WebSocketHandler] { implicit val backend: SttpBackend[BlockingTask, ZStream[Blocking, Throwable, Byte], WebSocketHandler] = runtime.unsafeRun(HttpClientZioBackend()) implicit val convertToFuture: ConvertToFuture[BlockingTask] = convertZioBlockingTaskToFuture implicit val monad: MonadError[BlockingTask] = new RIOMonadAsyncError def createHandler: Option[Int] => BlockingTask[WebSocketHandler[WebSocket[BlockingTask]]] = _ => ZioWebSocketHandler() it should "handle backpressure correctly" in { new ConvertToFutureDecorator( basicRequest .get(uri"$wsEndpoint/ws/echo") .openWebsocketF(createHandler(None)) .flatMap { response => val ws = response.result send(ws, 1000).flatMap(_ => eventually(10.millis, 500) { ws.isOpen.map(_ shouldBe true) } ) } ).toFuture() } override def eventually[T](interval: FiniteDuration, attempts: Int)(f: => BlockingTask[T]): BlockingTask[T] = { (ZIO.sleep(Duration.fromScala(interval)) *> f.retry(Schedule.recurs(attempts))) .provideSomeLayer[Blocking](Clock.live) } }
Example 11
Source File: Message.scala From zio-keeper with Apache License 2.0 | 5 votes |
package zio.keeper.swim import zio.duration.Duration import zio.keeper.NodeAddress import zio.keeper.swim.Message.{ NoResponse, WithTimeout } import zio.{ IO, UIO, ZIO, keeper } sealed trait Message[+A] { self => final def transformM[B](fn: A => IO[keeper.Error, B]): IO[keeper.Error, Message[B]] = self match { case msg: Message.Direct[A] => fn(msg.message).map(b => msg.copy(message = b)) case msg: Message.Broadcast[A] => fn(msg.message).map(b => msg.copy(message = b)) case msg: Message.Batch[A] => for { m1 <- msg.first.transformM(fn) m2 <- msg.second.transformM(fn) rest <- ZIO.foreach(msg.rest)(_.transformM(fn)) } yield Message.Batch(m1, m2, rest: _*) case msg: WithTimeout[A] => msg.message .transformM(fn) .map(b => msg.copy(message = b, action = msg.action.flatMap(_.transformM(fn)))) case NoResponse => Message.noResponse } } object Message { final case class Direct[A](node: NodeAddress, conversationId: Long, message: A) extends Message[A] final case class Batch[A](first: Message[A], second: Message[A], rest: Message[A]*) extends Message[A] final case class Broadcast[A](message: A) extends Message[A] final case class WithTimeout[A](message: Message[A], action: IO[keeper.Error, Message[A]], timeout: Duration) extends Message[A] case object NoResponse extends Message[Nothing] def direct[A](node: NodeAddress, message: A): ZIO[ConversationId, Nothing, Direct[A]] = ConversationId.next.map(Direct(node, _, message)) def withTimeout[R, A]( message: Message[A], action: ZIO[R, keeper.Error, Message[A]], timeout: Duration ): ZIO[R, Nothing, WithTimeout[A]] = for { env <- ZIO.environment[R] } yield WithTimeout(message, action.provide(env), timeout) def withTimeoutM[R, R1, A]( message: ZIO[R1, keeper.Error, Message[A]], action: ZIO[R, keeper.Error, Message[A]], timeout: Duration ): ZIO[R1 with R, keeper.Error, WithTimeout[A]] = for { env <- ZIO.environment[R] msg <- message } yield WithTimeout(msg, action.provide(env), timeout) val noResponse: UIO[NoResponse.type] = ZIO.succeedNow(NoResponse) }
Example 12
Source File: SwimConfig.scala From zio-keeper with Apache License 2.0 | 5 votes |
package zio.keeper.swim import zio.Layer import zio.config.{ Config, ConfigDescriptor, ReadError } import zio.config.ConfigDescriptor._ import zio.duration.{ Duration, _ } case class SwimConfig( port: Int, protocolInterval: Duration, protocolTimeout: Duration, suspicionTimeout: Duration, messageSizeLimit: Int, broadcastResent: Int ) object SwimConfig { val description: ConfigDescriptor[SwimConfig] = (int("PORT").default(5557) |@| zioDuration("PROTOCOL_INTERVAL").default(3.seconds) |@| zioDuration("PROTOCOL_TIMEOUT").default(1.seconds) |@| zioDuration("SUSPICION_TIMEOUT").default(3.seconds) |@| int("MESSAGE_SIZE_LIMIT").default(64000) |@| int("BROADCAST_RESENT").default(10))(SwimConfig.apply, SwimConfig.unapply) val fromEnv: Layer[ReadError[String], Config[SwimConfig]] = Config.fromSystemEnv(description) }
Example 13
Source File: Suspicion.scala From zio-keeper with Apache License 2.0 | 5 votes |
package zio.keeper.swim.protocols import upickle.default.macroRW import zio.{ ZIO, keeper } import zio.duration.Duration import zio.keeper.swim.Nodes._ import zio.keeper.swim.{ ConversationId, Message, Nodes, Protocol } import zio.keeper.{ ByteCodec, NodeAddress } sealed trait Suspicion object Suspicion { final case class Suspect(from: NodeAddress, nodeId: NodeAddress) extends Suspicion final case class Alive(nodeId: NodeAddress) extends Suspicion final case class Dead(nodeId: NodeAddress) extends Suspicion implicit val suspectCodec: ByteCodec[Suspect] = ByteCodec.fromReadWriter(macroRW[Suspect]) implicit val aliveCodec: ByteCodec[Alive] = ByteCodec.fromReadWriter(macroRW[Alive]) implicit val deadCodec: ByteCodec[Dead] = ByteCodec.fromReadWriter(macroRW[Dead]) implicit val byteCodec: ByteCodec[Suspicion] = ByteCodec.tagged[Suspicion][ Suspect, Alive, Dead ] type Env = ConversationId with Nodes def protocol(local: NodeAddress, timeout: Duration): ZIO[Env, keeper.Error, Protocol[Suspicion]] = Protocol[Suspicion].make( { case Message.Direct(sender, _, Suspect(_, `local`)) => Message .direct(sender, Alive(local)) .map( Message.Batch( _, Message.Broadcast(Alive(local)) ) ) case Message.Direct(_, _, Suspect(_, node)) => nodeState(node) .orElseSucceed(NodeState.Dead) .flatMap { case NodeState.Dead | NodeState.Suspicion => Message.noResponse case _ => changeNodeState(node, NodeState.Suspicion).ignore *> Message.noResponse //it will trigger broadcast by events } case Message.Direct(sender, _, msg @ Dead(nodeAddress)) if sender == nodeAddress => changeNodeState(nodeAddress, NodeState.Left).ignore .as(Message.Broadcast(msg)) case Message.Direct(_, _, msg @ Dead(nodeAddress)) => nodeState(nodeAddress).orElseSucceed(NodeState.Dead).flatMap { case NodeState.Dead => Message.noResponse case _ => changeNodeState(nodeAddress, NodeState.Dead).ignore .as(Message.Broadcast(msg)) } case Message.Direct(_, _, msg @ Alive(nodeAddress)) => changeNodeState(nodeAddress, NodeState.Healthy).ignore .as(Message.Broadcast(msg)) }, internalEvents.collectM { case NodeStateChanged(node, _, NodeState.Suspicion) => Message.withTimeout( Message.Broadcast(Suspect(local, node)), ZIO.ifM(nodeState(node).map(_ == NodeState.Suspicion).orElseSucceed(false))( changeNodeState(node, NodeState.Dead) .as(Message.Broadcast(Dead(node))), Message.noResponse ), timeout ) } ) }
Example 14
Source File: ReportersTest.scala From zio-metrics with Apache License 2.0 | 5 votes |
package zio.metrics import zio.metrics.dropwizard._ import zio.metrics.dropwizard.helpers._ import zio.metrics.dropwizard.reporters._ import zio.{ App, RIO, Runtime } import java.util.concurrent.TimeUnit import scala.concurrent.duration._ import zio.console._ import zio.duration.Duration import com.codahale.metrics.MetricRegistry import zio.ExitCode object ReportersTest extends App { val rt = Runtime.unsafeFromLayer(Registry.live ++ Reporters.live) val tests: RIO[ Registry with Reporters, MetricRegistry ] = for { r <- getCurrentRegistry() _ <- jmx(r) _ <- console(r, 2, TimeUnit.SECONDS) c <- counter.register(Show.fixClassName(DropwizardTest.getClass()), Array("test", "counter")) _ <- c.inc() _ <- c.inc(2.0) t <- timer.register("DropwizardTimer", Array("test", "timer")) ctx <- t.start() _ <- RIO.foreach( List( Thread.sleep(1000L), Thread.sleep(1400L), Thread.sleep(1200L) ) )(_ => t.stop(ctx)) } yield r override def run(args: List[String]) = { println("Starting tests") val json = rt.unsafeRun(tests >>= (r => DropwizardExtractor.writeJson(r)(None))) RIO.sleep(Duration.fromScala(30.seconds)) putStrLn(json.spaces2).map(_ => ExitCode.success) } }
Example 15
Source File: Discovery.scala From zio-keeper with Apache License 2.0 | 5 votes |
package zio.keeper.discovery import zio.duration.Duration import zio.keeper.Error import zio.logging.{ Logger, Logging } import zio.nio.core.{ InetAddress, InetSocketAddress } import zio.{ IO, Layer, UIO, ZLayer } object Discovery { trait Service { def discoverNodes: IO[Error, Set[InetSocketAddress]] } def staticList(addresses: Set[InetSocketAddress]): Layer[Nothing, Discovery] = ZLayer.succeed { new Service { final override val discoverNodes: UIO[Set[InetSocketAddress]] = UIO.succeed(addresses) } } def k8Dns(address: InetAddress, timeout: Duration, port: Int): ZLayer[Logging, Nothing, Discovery] = ZLayer.fromFunction { logging => new K8DnsDiscovery(logging.get[Logger[String]], address, timeout, port) } }
Example 16
Source File: ShoppingCartSpec.scala From zio-actors with Apache License 2.0 | 5 votes |
package zio.actors.examples.persistence import java.io.File import java.util.concurrent.TimeUnit import zio.{ Cause, Has, Managed, Schedule, UIO, ZIO, ZLayer } import zio.actors.{ ActorSystem, Supervisor } import zio.duration.Duration import zio.test.Assertion._ import zio.test.{ assert, suite, testM, DefaultRunnableSpec, TestFailure } import ShoppingCart._ import Deps._ object Deps { val actorSystem: Managed[TestFailure[Throwable], ActorSystem] = Managed.make( ActorSystem("testSys", Some(new File("./src/test/resources/application.conf"))) .mapError(e => TestFailure.Runtime(Cause.die(e))) )(_.shutdown.catchAll(_ => UIO.unit)) val actorSystemLayer = ZLayer.fromManaged(actorSystem) val recoverPolicy = Supervisor.retry(Schedule.exponential(Duration(200, TimeUnit.MILLISECONDS))) } object ShoppingCartSpec extends DefaultRunnableSpec { def spec = suite("The Shopping Cart should")( testM("add item") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart1", recoverPolicy, State.empty, ShoppingCart("cart1")) conf <- cart ? AddItem("foo", 42) } yield assert(conf)(equalTo(Accepted(Summary(Map("foo" -> 42), checkedOut = false)))) }, testM("reject already added item") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart2", recoverPolicy, State.empty, ShoppingCart("cart2")) conf1 <- cart ? AddItem("foo", 42) conf2 <- cart ? AddItem("foo", 13) } yield assert(conf1)(isSubtype[Accepted](anything)) && assert(conf2)(isSubtype[Rejected](anything)) }, testM("remove item") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart3", recoverPolicy, State.empty, ShoppingCart("cart3")) conf1 <- cart ? AddItem("foo", 42) conf2 <- cart ? RemoveItem("foo") } yield assert(conf1)(isSubtype[Accepted](anything)) && assert(conf2)( equalTo(Accepted(Summary(Map.empty, checkedOut = false))) ) }, testM("adjust quantity") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart4", recoverPolicy, State.empty, ShoppingCart("cart4")) conf1 <- cart ? AddItem("foo", 42) conf2 <- cart ? AdjustItemQuantity("foo", 43) } yield assert(conf1)(isSubtype[Accepted](anything)) && assert(conf2)( equalTo(Accepted(Summary(Map("foo" -> 43), checkedOut = false))) ) }, testM("checkout") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart5", recoverPolicy, State.empty, ShoppingCart("cart5")) conf1 <- cart ? AddItem("foo", 42) conf2 <- cart ? Checkout } yield assert(conf1)(isSubtype[Accepted](anything)) && assert(conf2)( equalTo(Accepted(Summary(Map("foo" -> 42), checkedOut = true))) ) }, testM("keep its state") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart6", recoverPolicy, State.empty, ShoppingCart("cart6")) conf1 <- cart ? AddItem("foo", 42) _ <- cart.stop cart <- as.make("cart6", recoverPolicy, State.empty, ShoppingCart("cart6")) status <- cart ? Get } yield assert(conf1)(equalTo(Accepted(Summary(Map("foo" -> 42), checkedOut = false)))) && assert(status)(equalTo(Summary(Map("foo" -> 42), checkedOut = false))) } ).provideCustomLayer(actorSystemLayer) }
Example 17
Source File: AsynchronousChannelGroup.scala From scalaz-nio with Apache License 2.0 | 5 votes |
package zio.nio.channels import java.io.IOException import java.nio.channels.{ AsynchronousChannelGroup => JAsynchronousChannelGroup } import java.nio.channels.spi.{ AsynchronousChannelProvider => JAsynchronousChannelProvider } import java.util.concurrent.{ ExecutorService => JExecutorService, ThreadFactory => JThreadFactory } import java.util.concurrent.TimeUnit import zio.{ IO, UIO } import zio.duration.Duration object AsynchronousChannelGroup { def apply(executor: JExecutorService, initialSize: Int): IO[Exception, AsynchronousChannelGroup] = IO.effect( new AsynchronousChannelGroup( JAsynchronousChannelGroup.withCachedThreadPool(executor, initialSize) ) ) .refineToOrDie[Exception] def apply( threadsNo: Int, threadsFactory: JThreadFactory ): IO[Exception, AsynchronousChannelGroup] = IO.effect( new AsynchronousChannelGroup( JAsynchronousChannelGroup.withFixedThreadPool(threadsNo, threadsFactory) ) ) .refineToOrDie[Exception] def apply(executor: JExecutorService): IO[Exception, AsynchronousChannelGroup] = IO.effect( new AsynchronousChannelGroup(JAsynchronousChannelGroup.withThreadPool(executor)) ) .refineToOrDie[Exception] } class AsynchronousChannelGroup(private[channels] val channelGroup: JAsynchronousChannelGroup) { def awaitTermination(timeout: Duration): IO[Exception, Boolean] = IO.effect(channelGroup.awaitTermination(timeout.asJava.toMillis, TimeUnit.MILLISECONDS)) .refineToOrDie[Exception] val isShutdown: UIO[Boolean] = IO.effectTotal(channelGroup.isShutdown) val isTerminated: UIO[Boolean] = IO.effectTotal(channelGroup.isTerminated) val provider: UIO[JAsynchronousChannelProvider] = IO.effectTotal(channelGroup.provider()) val shutdown: UIO[Unit] = IO.effectTotal(channelGroup.shutdown()) val shutdownNow: IO[IOException, Unit] = IO.effect(channelGroup.shutdownNow()).refineToOrDie[IOException] }
Example 18
Source File: PlatformSpecific.scala From zio with Apache License 2.0 | 5 votes |
package zio.clock import zio.duration.Duration import zio.internal.Scheduler import scala.scalajs.js private[clock] trait PlatformSpecific { private[clock] val globalScheduler = new Scheduler { import Scheduler.CancelToken private[this] val ConstFalse = () => false override def schedule(task: Runnable, duration: Duration): CancelToken = duration match { case Duration.Infinity => ConstFalse case Duration.Zero => task.run() ConstFalse case duration: Duration.Finite => var completed = false val handle = js.timers.setTimeout(duration.toMillis.toDouble) { completed = true task.run() } () => { js.timers.clearTimeout(handle) !completed } } } }
Example 19
Source File: PlatformSpecific.scala From zio with Apache License 2.0 | 5 votes |
package zio.clock import scala.scalajs.js import zio.duration.Duration import zio.internal.Scheduler private[clock] trait PlatformSpecific { private[clock] val globalScheduler = new Scheduler { import Scheduler.CancelToken private[this] val ConstFalse = () => false override def schedule(task: Runnable, duration: Duration): CancelToken = duration match { case Duration.Infinity => ConstFalse case Duration.Zero => task.run() ConstFalse case duration: Duration.Finite => var completed = false val handle = js.timers.setTimeout(duration.toMillis.toDouble) { completed = true task.run() } () => { js.timers.clearTimeout(handle) !completed } } } }
Example 20
Source File: package.scala From zio with Apache License 2.0 | 5 votes |
package zio import java.time.{ DateTimeException, Instant, OffsetDateTime, ZoneId } import java.util.concurrent.TimeUnit import zio.duration.Duration package object clock { type Clock = Has[Clock.Service] object Clock extends PlatformSpecific with Serializable { trait Service extends Serializable { def currentTime(unit: TimeUnit): UIO[Long] def currentDateTime: IO[DateTimeException, OffsetDateTime] def nanoTime: UIO[Long] def sleep(duration: Duration): UIO[Unit] } object Service { val live: Service = new Service { def currentTime(unit: TimeUnit): UIO[Long] = IO.effectTotal(System.currentTimeMillis).map(l => unit.convert(l, TimeUnit.MILLISECONDS)) val nanoTime: UIO[Long] = IO.effectTotal(System.nanoTime) def sleep(duration: Duration): UIO[Unit] = UIO.effectAsyncInterrupt { cb => val canceler = globalScheduler.schedule(() => cb(UIO.unit), duration) Left(UIO.effectTotal(canceler())) } def currentDateTime: IO[DateTimeException, OffsetDateTime] = { val dateTime = for { millis <- currentTime(TimeUnit.MILLISECONDS) zone <- ZIO(ZoneId.systemDefault) instant <- ZIO(Instant.ofEpochMilli(millis)) offsetDateTime <- ZIO(OffsetDateTime.ofInstant(instant, zone)) } yield offsetDateTime dateTime.refineToOrDie[DateTimeException] } } } val any: ZLayer[Clock, Nothing, Clock] = ZLayer.requires[Clock] val live: Layer[Nothing, Clock] = ZLayer.succeed(Service.live) } def sleep(duration: => Duration): URIO[Clock, Unit] = ZIO.accessM(_.get.sleep(duration)) }
Example 21
Source File: Scheduler.scala From zio with Apache License 2.0 | 5 votes |
package zio.internal import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit import zio.duration.Duration import zio.internal.Scheduler.CancelToken private[zio] trait Scheduler { def schedule(task: Runnable, duration: Duration): CancelToken } private[zio] object Scheduler { type CancelToken = () => Boolean def fromScheduledExecutorService(service: ScheduledExecutorService): Scheduler = new Scheduler { val ConstFalse = () => false override def schedule(task: Runnable, duration: Duration): CancelToken = duration match { case Duration.Infinity => ConstFalse case Duration.Zero => task.run() ConstFalse case duration: Duration.Finite => val future = service.schedule(new Runnable { def run: Unit = task.run() }, duration.toNanos, TimeUnit.NANOSECONDS) () => future.cancel(true) } } }
Example 22
Source File: PlatformSpecific.scala From zio with Apache License 2.0 | 5 votes |
package zio.clock import java.util.concurrent._ import zio.duration.Duration import zio.internal.{ NamedThreadFactory, Scheduler } private[clock] trait PlatformSpecific { import Scheduler.CancelToken private[clock] val globalScheduler = new Scheduler { private[this] val service = Executors.newScheduledThreadPool(1, new NamedThreadFactory("zio-timer", true)) private[this] val ConstFalse = () => false override def schedule(task: Runnable, duration: Duration): CancelToken = duration match { case Duration.Infinity => ConstFalse case Duration.Zero => task.run() ConstFalse case duration: Duration.Finite => val future = service.schedule(new Runnable { def run: Unit = task.run() }, duration.toNanos, TimeUnit.NANOSECONDS) () => { val canceled = future.cancel(true) canceled } } } }
Example 23
Source File: MockClock.scala From zio with Apache License 2.0 | 5 votes |
package zio.test.mock import java.time.{ DateTimeException, OffsetDateTime } import java.util.concurrent.TimeUnit import zio.clock.Clock import zio.duration.Duration import zio.{ Has, IO, UIO, URLayer, ZLayer } object MockClock extends Mock[Clock] { object CurrentTime extends Effect[TimeUnit, Nothing, Long] object CurrentDateTime extends Effect[Unit, DateTimeException, OffsetDateTime] object NanoTime extends Effect[Unit, Nothing, Long] object Sleep extends Effect[Duration, Nothing, Unit] val compose: URLayer[Has[Proxy], Clock] = ZLayer.fromService(proxy => new Clock.Service { def currentTime(unit: TimeUnit): UIO[Long] = proxy(CurrentTime, unit) def currentDateTime: IO[DateTimeException, OffsetDateTime] = proxy(CurrentDateTime) val nanoTime: UIO[Long] = proxy(NanoTime) def sleep(duration: Duration): UIO[Unit] = proxy(Sleep, duration) } ) }
Example 24
Source File: DogStatsDClientTest.scala From zio-metrics with Apache License 2.0 | 5 votes |
package zio.metrics import zio.{ Queue, RIO, Runtime, Schedule } import zio.clock.Clock import zio.console._ import java.util.concurrent.TimeUnit import zio.duration.Duration import zio.metrics.dogstatsd._ import zio.metrics.encoders._ object DogStatsDClientTest { val rt = Runtime.unsafeFromLayer(Encoder.dogstatsd ++ Console.live ++ Clock.live) val schd = Schedule.recurs(10) val client = DogStatsDClient() def program(r: Long)(implicit queue: Queue[Metric]) = for { clock <- RIO.environment[Clock] _ <- client.listen t1 <- clock.get.currentTime(TimeUnit.MILLISECONDS) _ <- client.increment("zmetrics.dog.counter", 0.9) _ <- putStrLn(s"waiting for $r ms") *> clock.get.sleep(Duration(r, TimeUnit.MILLISECONDS)) t2 <- clock.get.currentTime(TimeUnit.MILLISECONDS) d = (t2 - t1).toDouble _ <- client.timer("zmetrics.dog.timer", d, 0.9) _ <- client.histogram("zmetrics.dog.hist", d) _ <- client.serviceCheck("zmetrics.dog.check", ServiceCheckOk) _ <- client.event("zmetrics.dog.event", "something amazing happened") } yield () def main(args: Array[String]): Unit = { val timeouts = Seq(34L, 76L, 52L) rt.unsafeRun( client.queue >>= ( q => RIO .foreach(timeouts)(l => program(l)(q)) .repeat(schd) ) ) Thread.sleep(10000) } }
Example 25
Source File: StatsDClientTest.scala From zio-metrics with Apache License 2.0 | 5 votes |
package zio.metrics import zio.{ Queue, RIO, Runtime, Schedule } import zio.clock.Clock import zio.console._ import zio.metrics.encoders._ import zio.metrics.statsd._ import zio.duration.Duration import java.util.concurrent.TimeUnit object StatsDClientTest { val rt = Runtime.unsafeFromLayer(Encoder.statsd ++ Console.live ++ Clock.live) val schd = Schedule.recurs(10) val client = StatsDClient() def program(r: Long)(implicit queue: Queue[Metric]) = for { clock <- RIO.environment[Clock] _ <- client.listen t1 <- clock.get.currentTime(TimeUnit.MILLISECONDS) _ <- client.increment("zmetrics.counter", 0.9) _ <- putStrLn(s"waiting for $r s") *> clock.get.sleep(Duration(r, TimeUnit.SECONDS)) t2 <- clock.get.currentTime(TimeUnit.MILLISECONDS) _ <- client.timer("zmetrics.timer", (t2 - t1).toDouble, 0.9) } yield () def main(args: Array[String]): Unit = { val timeouts = Seq(4L, 6L, 2L) rt.unsafeRun( client.queue >>= ( q => RIO .foreach(timeouts)(l => program(l)(q)) .repeat(schd) ) ) Thread.sleep(10000) } }