SlideShare una empresa de Scribd logo
1 de 64
Descargar para leer sin conexión
ZIO ACTORSGITHUB.COM/MTSOKOL
TWITTER: @MT_SOKOL
AGENDA
AGENDA
> Actors outline
AGENDA
> Actors outline
> Akka recall
AGENDA
> Actors outline
> Akka recall
> ZIO Actors by example
AGENDA
> Actors outline
> Akka recall
> ZIO Actors by example
> Problems faced
ACTORS
ACTORS SHOULD
ACTORS SHOULD
> have a defined messages type
ACTORS SHOULD
> have a defined messages type
> form supervision trees
ACTORS SHOULD
> have a defined messages type
> form supervision trees
> be location-transparent
AKKA ACTORS
class ClassicActor extends Actor {
def receive = {
case "Hello" => println("Hello!")
case _ => println("Hello anyway.")
}
}
object TypedActor {
def act(): Behavior[Msg] = Behaviors.receive {
(ctx, message) =>
//computations...
Behaviors.same
}
}
object Main extends App {
val system = ActorSystem("HelloSystem")
val helloActor = system.actorOf(Props[ClassicActor], name = "actor1")
helloActor ! "Hello"
helloActor ! "Hi"
}
class ClassicActor extends Actor {
def receive = {
case "Hello" => println("Hello!")
case _ => println("Hello anyway.")
}
}
object TypedActor {
def act(): Behavior[Msg] = Behaviors.receive {
(ctx, message) =>
//computations...
Behaviors.same
}
}
object Main extends App {
val system = ActorSystem("HelloSystem")
val helloActor = system.actorOf(Props[ClassicActor], name = "actor1")
helloActor ! "Hello"
helloActor ! "Hi"
}
class ClassicActor extends Actor {
def receive = {
case "Hello" => println("Hello!")
case _ => println("Hello anyway.")
}
}
object TypedActor {
def act(): Behavior[Msg] = Behaviors.receive {
(ctx, message) =>
//computations...
Behaviors.same
}
}
object Main extends App {
val system = ActorSystem("HelloSystem")
val helloActor = system.actorOf(Props[ClassicActor], name = "actor1")
helloActor ! "Hello"
helloActor ! "Hi"
}
ZIO ACTORS
ZIO[R, E, A]
ALIASES
UIO[A] => ZIO[Any, Nothing, A]
URIO[R, A] => ZIO[R, Nothing, A]
Task[A] => ZIO[Any, Throwable, A]
IO[E, A] => ZIO[Any, E, A]
object ActorSystem {
def apply(name: String, configFile: Option[File]): Task[ActorSystem]
}
final class ActorSystem() {
def make[R, S, F[+_]](
actorName: String,
sup: Supervisor[R],
init: S,
stateful: Stateful[R, S, F]
): RIO[R, ActorRef[E, F]]
def select[F[+_]](path: String): Task[ActorRef[F]]
def shutdown: Task[List[_]]
}
object ActorSystem {
def apply(name: String, configFile: Option[File]): Task[ActorSystem]
}
final class ActorSystem() {
def make[R, S, F[+_]](
actorName: String,
sup: Supervisor[R],
init: S,
stateful: Stateful[R, S, F]
): RIO[R, ActorRef[E, F]]
def select[F[+_]](path: String): Task[ActorRef[F]]
def shutdown: Task[List[_]]
}
trait Stateful[-R, S, -F[+_]] {
def receive[A](
state: S,
msg: F[A],
context: Context
): RIO[R, (S, A)]
}
sealed trait ActorRef[-F[+_]] {
def ?[A](fa: F[A]): Task[A]
def !(fa: F[_]): Task[Unit]
val path: UIO[String]
}
TYPED
sealed trait Message[+_]
case object Reset extends Message[Unit]
case object Increase extends Message[Unit]
case object Get extends Message[Int]
val handler =
new Stateful[Any, Int, Message] {
override def receive[A](state: Int, msg: Message[A], context: Context) =
msg match {
case Reset => UIO((0, ()))
case Increase => UIO((state + 1, ()))
case Get => UIO((state, state))
}
}
sealed trait Message[+_]
case object Reset extends Message[Unit]
case object Increase extends Message[Unit]
case object Get extends Message[Int]
val handler =
new Stateful[Any, Int, Message] {
override def receive[A](state: Int, msg: Message[A], context: Context) =
msg match {
case Reset => UIO((0, ()))
case Increase => UIO((state + 1, ()))
case Get => UIO((state, state))
}
}
for {
system <- ActorSystem("test1")
actor <- system.make("actor1", Supervisor.none, 0, handler)
_ <- actor ! Increase
_ <- actor ! Increase
c1 <- actor ? Get
_ <- actor ! Reset
c2 <- actor ? Get
} yield assert(c1, equalTo(2)) && assert(c2, equalTo(0))
for {
system <- ActorSystem("test1")
actor <- system.make("actor1", Supervisor.none, 0, handler)
_ <- actor ! Increase
_ <- actor ! Increase
c1 <- actor ? Get
_ <- actor ! Reset
c2 <- actor ? Get
} yield assert(c1, equalTo(2)) && assert(c2, equalTo(0))
FSM
sealed trait Command[+A]
case object Open extends Command[Unit]
case object Close extends Command[Unit]
case object Sell extends Command[String]
sealed trait State
case object Opened extends State
case object Closed extends State
case class SaleException(msg: String) extends Throwable
sealed trait Command[+A]
case object Open extends Command[Unit]
case object Close extends Command[Unit]
case object Sell extends Command[String]
sealed trait State
case object Opened extends State
case object Closed extends State
case class SaleException(msg: String) extends Throwable
new Stateful[Console, State, Command] {
override def receive[A](
state: State,
msg: Command[A],
context: Context
): ZIO[Console, SaleException, (State, A)] = /*...*/
}
state match {
case Opened =>
msg match {
case Open => UIO((Opened, ()))
case Close => putStrLn("Closing...") *> UIO((Closed, ()))
case Sell => UIO((Opened, "Selling..."))
}
case Closed =>
msg match {
case Open => putStrLn("Opening...") *> UIO((Opened, ()))
case Close => UIO((Closed, ()))
case Sell => IO.fail(SaleException("Shop is closed"))
}
}
SUPERVISION
for {
system <- ActorSystem("sys1")
schedule = Schedule.recurs(10)
policy = Supervisor.retry(schedule)
actor <- system.make("actor1", policy, (), handler)
_ <- actor ! MightFail
} yield ()
val s1 = Schedule.exponential(10.milliseconds)
val s2 = Schedule.exponential(1.second) && Schedule.recurs(10)
for {
system <- ActorSystem("sys1")
schedule = Schedule.recurs(10)
policy = Supervisor.retry(schedule)
actor <- system.make("actor1", policy, (), handler)
_ <- actor ! MightFail
} yield ()
val s1 = Schedule.exponential(10.milliseconds)
val s2 = Schedule.exponential(1.second) && Schedule.recurs(10)
REMOTING SUPPORT
CONFIGURATION
made with zio-config
# application.conf
testSystem1.zio.actors.remoting {
hostname = ${HOST}
port = ${PORT}
}
for {
sys1 <- ActorSystem("testSystem1")
_ <- sys1.make("actorOne", Supervisor.none, 0, handler)
} yield ()
//============ OTHER NODE ==============
for {
sys2 <- ActorSystem("testSystem2")
actor <- sys2.select[MyErrorDomain, Message](
s"zio://testSystem1@127.0.0.1:$port1/actorOne"
)
result <- actor ? Str("ZIO-Actor response... ")
} yield assert(result, equalTo("ZIO-Actor... received 1"))
for {
sys1 <- ActorSystem("testSystem1")
_ <- sys1.make("actorOne", Supervisor.none, 0, handler)
} yield ()
//============ OTHER NODE ==============
for {
sys2 <- ActorSystem("testSystem2")
actor <- sys2.select[MyErrorDomain, Message](
s"zio://testSystem1@127.0.0.1:$port1/actorOne"
)
result <- actor ? Str("ZIO-Actor response... ")
} yield assert(result, equalTo("ZIO-Actor... received 1"))
PERSISTENCE
class EventSourcedStateful[R, S, -F[+_], Ev](id: PersId) {
def receive[A](
state: S,
msg: F[A],
context: Context
): RIO[R, (Command[Ev], S => A)]
def sourceEvent(state: S, event: Ev): S
}
object CounterUtils {
sealed trait Message[+_]
case object Reset extends Message[Unit]
case object Increase extends Message[String]
case object Get extends Message[Int]
sealed trait CounterEvent
case object ResetEvent extends CounterEvent
case object IncreaseEvent extends CounterEvent
}
new EventSourcedStateful[Any, Int, Message, CounterEvent](id) {
override def receive[A](
state: Int,
msg: Message[A],
context: Context
): UIO[(Command[CounterEvent], Int => A)] =
msg match {
case Reset => UIO((Comm.persist(ResetEvent), _ => ()))
case Increase => UIO((Comm.persist(IncreaseEvent), s => s"updated to $s"))
case Get => UIO((Comm.ignore, _ => state))
}
override def sourceEvent(state: Int, event: CounterEvent): Int =
event match {
case ResetEvent => 0
case IncreaseEvent => state + 1
}
}
new EventSourcedStateful[Any, Int, Message, CounterEvent](id) {
override def receive[A](
state: Int,
msg: Message[A],
context: Context
): UIO[(Command[CounterEvent], Int => A)] =
msg match {
case Reset => UIO((Comm.persist(ResetEvent), _ => ()))
case Increase => UIO((Comm.persist(IncreaseEvent), s => s"updated to $s"))
case Get => UIO((Comm.ignore, _ => state))
}
override def sourceEvent(state: Int, event: CounterEvent): Int =
event match {
case ResetEvent => 0
case IncreaseEvent => state + 1
}
}
new EventSourcedStateful[Any, Int, Message, CounterEvent](id) {
override def receive[A](
state: Int,
msg: Message[A],
context: Context
): UIO[(Command[CounterEvent], Int => A)] =
msg match {
case Reset => UIO((Comm.persist(ResetEvent), _ => ()))
case Increase => UIO((Comm.persist(IncreaseEvent), s => s"updated to $s"))
case Get => UIO((Comm.ignore, _ => state))
}
override def sourceEvent(state: Int, event: CounterEvent): Int =
event match {
case ResetEvent => 0
case IncreaseEvent => state + 1
}
}
PEEK INTO INTERNALS
PROBLEMS FACED
SERIALIZATION
@throws[IOException]
protected def writeObject1(out: ObjectOutputStream): Unit =
out.writeObject(actorPath)
@throws[ObjectStreamException]
protected def readResolve1(): Object = {
val remoteRef = for {
resolved <- resolvePath(actorPath)
(_, addr, port, _) = resolved
address <- InetAddress.byName(addr)
.flatMap(iAddr =>
SocketAddress.inetSocketAddress(iAddr, port)
)
} yield ActorRefRemote[F](actorPath, address)
ActorRefSerial.runtimeForResolve.unsafeRun(remoteRef)
}
@throws[IOException]
protected def writeObject1(out: ObjectOutputStream): Unit =
out.writeObject(actorPath)
@throws[ObjectStreamException]
protected def readResolve1(): Object = {
val remoteRef = for {
resolved <- resolvePath(actorPath)
(_, addr, port, _) = resolved
address <- InetAddress.byName(addr)
.flatMap(iAddr =>
SocketAddress.inetSocketAddress(iAddr, port)
)
} yield ActorRefRemote[F](actorPath, address)
ActorRefSerial.runtimeForResolve.unsafeRun(remoteRef)
}
SOCKET HANDLING
ZIO NIO
GOALS FOR 2020
GOALS FOR 2020
> Persistence (WIP)
GOALS FOR 2020
> Persistence (WIP)
> Serialization
GOALS FOR 2020
> Persistence (WIP)
> Serialization
> Monitoring
GOALS FOR 2020
> Persistence (WIP)
> Serialization
> Monitoring
> Clustering (zio-keeper )
THANK YOU!GITHUB.COM/MTSOKOL
TWITTER: @MT_SOKOL

Más contenido relacionado

La actualidad más candente

Programa simulacion de ventas de aeropuerto
Programa simulacion de ventas de aeropuertoPrograma simulacion de ventas de aeropuerto
Programa simulacion de ventas de aeropuertoAnel Sosa
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of TransductionDavid Stockton
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Leonardo Soto
 
Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.Basel Issmail
 
To Be Continued - multithreading with Project Loom and Kotlin's Coroutines
To Be Continued - multithreading with Project Loom and Kotlin's CoroutinesTo Be Continued - multithreading with Project Loom and Kotlin's Coroutines
To Be Continued - multithreading with Project Loom and Kotlin's CoroutinesArtur Skowroński
 
The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212Mahmoud Samir Fayed
 
Ciąg dalszy nastąpi - o wielowątkowości, Projekcie Loom i kotlinowych Korutynach
Ciąg dalszy nastąpi - o wielowątkowości, Projekcie Loom i kotlinowych KorutynachCiąg dalszy nastąpi - o wielowątkowości, Projekcie Loom i kotlinowych Korutynach
Ciąg dalszy nastąpi - o wielowątkowości, Projekcie Loom i kotlinowych KorutynachArtur Skowroński
 
To be Continued - multithreading with Project Loom and Kotlin's Coroutines
To be Continued - multithreading with Project Loom and Kotlin's CoroutinesTo be Continued - multithreading with Project Loom and Kotlin's Coroutines
To be Continued - multithreading with Project Loom and Kotlin's CoroutinesArtur Skowroński
 
The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 32 of 84
The Ring programming language version 1.2 book - Part 32 of 84The Ring programming language version 1.2 book - Part 32 of 84
The Ring programming language version 1.2 book - Part 32 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184Mahmoud Samir Fayed
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)진성 오
 
Syntactic sugar in postgre sql
Syntactic sugar in postgre sqlSyntactic sugar in postgre sql
Syntactic sugar in postgre sqlAntony Abramchenko
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOJorge Vásquez
 
Syntactic sugar in Postgre SQL
Syntactic sugar in Postgre SQLSyntactic sugar in Postgre SQL
Syntactic sugar in Postgre SQLAntony Abramchenko
 
Refactoring 메소드 호출의 단순화
Refactoring 메소드 호출의 단순화Refactoring 메소드 호출의 단순화
Refactoring 메소드 호출의 단순화HyeonSeok Choi
 
jQuery1.2.cheatsheet.v1.0
jQuery1.2.cheatsheet.v1.0jQuery1.2.cheatsheet.v1.0
jQuery1.2.cheatsheet.v1.0guest644d1d
 

La actualidad más candente (18)

Programa simulacion de ventas de aeropuerto
Programa simulacion de ventas de aeropuertoPrograma simulacion de ventas de aeropuerto
Programa simulacion de ventas de aeropuerto
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of Transduction
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
 
Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.
 
To Be Continued - multithreading with Project Loom and Kotlin's Coroutines
To Be Continued - multithreading with Project Loom and Kotlin's CoroutinesTo Be Continued - multithreading with Project Loom and Kotlin's Coroutines
To Be Continued - multithreading with Project Loom and Kotlin's Coroutines
 
The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212
 
Ciąg dalszy nastąpi - o wielowątkowości, Projekcie Loom i kotlinowych Korutynach
Ciąg dalszy nastąpi - o wielowątkowości, Projekcie Loom i kotlinowych KorutynachCiąg dalszy nastąpi - o wielowątkowości, Projekcie Loom i kotlinowych Korutynach
Ciąg dalszy nastąpi - o wielowątkowości, Projekcie Loom i kotlinowych Korutynach
 
To be Continued - multithreading with Project Loom and Kotlin's Coroutines
To be Continued - multithreading with Project Loom and Kotlin's CoroutinesTo be Continued - multithreading with Project Loom and Kotlin's Coroutines
To be Continued - multithreading with Project Loom and Kotlin's Coroutines
 
The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189
 
The Ring programming language version 1.2 book - Part 32 of 84
The Ring programming language version 1.2 book - Part 32 of 84The Ring programming language version 1.2 book - Part 32 of 84
The Ring programming language version 1.2 book - Part 32 of 84
 
The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
Syntactic sugar in postgre sql
Syntactic sugar in postgre sqlSyntactic sugar in postgre sql
Syntactic sugar in postgre sql
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
 
Syntactic sugar in Postgre SQL
Syntactic sugar in Postgre SQLSyntactic sugar in Postgre SQL
Syntactic sugar in Postgre SQL
 
Refactoring 메소드 호출의 단순화
Refactoring 메소드 호출의 단순화Refactoring 메소드 호출의 단순화
Refactoring 메소드 호출의 단순화
 
jQuery1.2.cheatsheet.v1.0
jQuery1.2.cheatsheet.v1.0jQuery1.2.cheatsheet.v1.0
jQuery1.2.cheatsheet.v1.0
 

Similar a ZIO actors by Mateusz Sokół Scalac

Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsJohn De Goes
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Mobx Performance and Sanity
Mobx Performance and SanityMobx Performance and Sanity
Mobx Performance and Sanity500Tech
 
Improving Correctness with Types Kats Conf
Improving Correctness with Types Kats ConfImproving Correctness with Types Kats Conf
Improving Correctness with Types Kats ConfIain Hull
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using ScalaSiarhiej Siemianchuk
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator PatternEric Torreborre
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingSergey Shishkin
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency명신 김
 
Taming Distribution: Formal Protocols for Akka Typed
Taming Distribution: Formal Protocols for Akka TypedTaming Distribution: Formal Protocols for Akka Typed
Taming Distribution: Formal Protocols for Akka TypedRoland Kuhn
 
aming distribution: formal protocols for Akka Typed
aming distribution: formal protocols for Akka Typedaming distribution: formal protocols for Akka Typed
aming distribution: formal protocols for Akka TypedJ On The Beach
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)Eric Torreborre
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wildJoe Morgan
 
Data in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data EfficientlyData in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data EfficientlyMartin Zapletal
 

Similar a ZIO actors by Mateusz Sokół Scalac (20)

Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Mobx Performance and Sanity
Mobx Performance and SanityMobx Performance and Sanity
Mobx Performance and Sanity
 
Improving Correctness with Types Kats Conf
Improving Correctness with Types Kats ConfImproving Correctness with Types Kats Conf
Improving Correctness with Types Kats Conf
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using Scala
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional Programming
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
 
Taming Distribution: Formal Protocols for Akka Typed
Taming Distribution: Formal Protocols for Akka TypedTaming Distribution: Formal Protocols for Akka Typed
Taming Distribution: Formal Protocols for Akka Typed
 
aming distribution: formal protocols for Akka Typed
aming distribution: formal protocols for Akka Typedaming distribution: formal protocols for Akka Typed
aming distribution: formal protocols for Akka Typed
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
Scala on Your Phone
Scala on Your PhoneScala on Your Phone
Scala on Your Phone
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Data in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data EfficientlyData in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data Efficiently
 
Serverless stateful
Serverless statefulServerless stateful
Serverless stateful
 
Akka tips
Akka tipsAkka tips
Akka tips
 
Lambdaconf2019 talk
Lambdaconf2019 talkLambdaconf2019 talk
Lambdaconf2019 talk
 

Más de Scalac

Applicative functors by Łukasz Marchewka
Applicative functors by Łukasz MarchewkaApplicative functors by Łukasz Marchewka
Applicative functors by Łukasz MarchewkaScalac
 
AWS Api Gateway by Łukasz Marchewka Scalacc
AWS Api Gateway by Łukasz Marchewka ScalaccAWS Api Gateway by Łukasz Marchewka Scalacc
AWS Api Gateway by Łukasz Marchewka ScalaccScalac
 
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...Scalac
 
React Hooks by Oleksandr Oleksiv Scalac
React Hooks by Oleksandr Oleksiv ScalacReact Hooks by Oleksandr Oleksiv Scalac
React Hooks by Oleksandr Oleksiv ScalacScalac
 
Introduction to Scala by Piotr Wiśniowski Scalac
Introduction to Scala by Piotr Wiśniowski ScalacIntroduction to Scala by Piotr Wiśniowski Scalac
Introduction to Scala by Piotr Wiśniowski ScalacScalac
 
Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Scalac
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Scalac
 
How to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
How to write automated tests and don’t lose your mind by Dorian Sarnowski ScalacHow to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
How to write automated tests and don’t lose your mind by Dorian Sarnowski ScalacScalac
 
Do you have that Spark in your ECTL? by Piotr Sych Scalac
Do you have that Spark in your ECTL? by Piotr Sych ScalacDo you have that Spark in your ECTL? by Piotr Sych Scalac
Do you have that Spark in your ECTL? by Piotr Sych ScalacScalac
 
Can we automate the process of backlog prioritizing? by Adam Gadomski Scalac
Can we automate the process of backlog prioritizing? by Adam Gadomski ScalacCan we automate the process of backlog prioritizing? by Adam Gadomski Scalac
Can we automate the process of backlog prioritizing? by Adam Gadomski ScalacScalac
 
How to create the right sales funnel for your business? by Maciej Greń
How to create the right sales funnel for your business? by Maciej GreńHow to create the right sales funnel for your business? by Maciej Greń
How to create the right sales funnel for your business? by Maciej GreńScalac
 
ActorRef[Typed] by Andrzej Kopeć
ActorRef[Typed] by Andrzej KopećActorRef[Typed] by Andrzej Kopeć
ActorRef[Typed] by Andrzej KopećScalac
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011Scalac
 
Liftweb
LiftwebLiftweb
LiftwebScalac
 
Scala == Effective Java
Scala == Effective JavaScala == Effective Java
Scala == Effective JavaScalac
 
Scala and Lift presentation
Scala and Lift presentationScala and Lift presentation
Scala and Lift presentationScalac
 

Más de Scalac (16)

Applicative functors by Łukasz Marchewka
Applicative functors by Łukasz MarchewkaApplicative functors by Łukasz Marchewka
Applicative functors by Łukasz Marchewka
 
AWS Api Gateway by Łukasz Marchewka Scalacc
AWS Api Gateway by Łukasz Marchewka ScalaccAWS Api Gateway by Łukasz Marchewka Scalacc
AWS Api Gateway by Łukasz Marchewka Scalacc
 
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
 
React Hooks by Oleksandr Oleksiv Scalac
React Hooks by Oleksandr Oleksiv ScalacReact Hooks by Oleksandr Oleksiv Scalac
React Hooks by Oleksandr Oleksiv Scalac
 
Introduction to Scala by Piotr Wiśniowski Scalac
Introduction to Scala by Piotr Wiśniowski ScalacIntroduction to Scala by Piotr Wiśniowski Scalac
Introduction to Scala by Piotr Wiśniowski Scalac
 
Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 
How to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
How to write automated tests and don’t lose your mind by Dorian Sarnowski ScalacHow to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
How to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
 
Do you have that Spark in your ECTL? by Piotr Sych Scalac
Do you have that Spark in your ECTL? by Piotr Sych ScalacDo you have that Spark in your ECTL? by Piotr Sych Scalac
Do you have that Spark in your ECTL? by Piotr Sych Scalac
 
Can we automate the process of backlog prioritizing? by Adam Gadomski Scalac
Can we automate the process of backlog prioritizing? by Adam Gadomski ScalacCan we automate the process of backlog prioritizing? by Adam Gadomski Scalac
Can we automate the process of backlog prioritizing? by Adam Gadomski Scalac
 
How to create the right sales funnel for your business? by Maciej Greń
How to create the right sales funnel for your business? by Maciej GreńHow to create the right sales funnel for your business? by Maciej Greń
How to create the right sales funnel for your business? by Maciej Greń
 
ActorRef[Typed] by Andrzej Kopeć
ActorRef[Typed] by Andrzej KopećActorRef[Typed] by Andrzej Kopeć
ActorRef[Typed] by Andrzej Kopeć
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011
 
Liftweb
LiftwebLiftweb
Liftweb
 
Scala == Effective Java
Scala == Effective JavaScala == Effective Java
Scala == Effective Java
 
Scala and Lift presentation
Scala and Lift presentationScala and Lift presentation
Scala and Lift presentation
 

Último

Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Data modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainData modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainAbdul Ahad
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 

Último (20)

Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Data modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainData modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software Domain
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 

ZIO actors by Mateusz Sokół Scalac

  • 5. AGENDA > Actors outline > Akka recall > ZIO Actors by example
  • 6. AGENDA > Actors outline > Akka recall > ZIO Actors by example > Problems faced
  • 8.
  • 9.
  • 11. ACTORS SHOULD > have a defined messages type
  • 12. ACTORS SHOULD > have a defined messages type > form supervision trees
  • 13. ACTORS SHOULD > have a defined messages type > form supervision trees > be location-transparent
  • 15. class ClassicActor extends Actor { def receive = { case "Hello" => println("Hello!") case _ => println("Hello anyway.") } } object TypedActor { def act(): Behavior[Msg] = Behaviors.receive { (ctx, message) => //computations... Behaviors.same } } object Main extends App { val system = ActorSystem("HelloSystem") val helloActor = system.actorOf(Props[ClassicActor], name = "actor1") helloActor ! "Hello" helloActor ! "Hi" }
  • 16. class ClassicActor extends Actor { def receive = { case "Hello" => println("Hello!") case _ => println("Hello anyway.") } } object TypedActor { def act(): Behavior[Msg] = Behaviors.receive { (ctx, message) => //computations... Behaviors.same } } object Main extends App { val system = ActorSystem("HelloSystem") val helloActor = system.actorOf(Props[ClassicActor], name = "actor1") helloActor ! "Hello" helloActor ! "Hi" }
  • 17. class ClassicActor extends Actor { def receive = { case "Hello" => println("Hello!") case _ => println("Hello anyway.") } } object TypedActor { def act(): Behavior[Msg] = Behaviors.receive { (ctx, message) => //computations... Behaviors.same } } object Main extends App { val system = ActorSystem("HelloSystem") val helloActor = system.actorOf(Props[ClassicActor], name = "actor1") helloActor ! "Hello" helloActor ! "Hi" }
  • 20. ALIASES UIO[A] => ZIO[Any, Nothing, A] URIO[R, A] => ZIO[R, Nothing, A] Task[A] => ZIO[Any, Throwable, A] IO[E, A] => ZIO[Any, E, A]
  • 21. object ActorSystem { def apply(name: String, configFile: Option[File]): Task[ActorSystem] } final class ActorSystem() { def make[R, S, F[+_]]( actorName: String, sup: Supervisor[R], init: S, stateful: Stateful[R, S, F] ): RIO[R, ActorRef[E, F]] def select[F[+_]](path: String): Task[ActorRef[F]] def shutdown: Task[List[_]] }
  • 22. object ActorSystem { def apply(name: String, configFile: Option[File]): Task[ActorSystem] } final class ActorSystem() { def make[R, S, F[+_]]( actorName: String, sup: Supervisor[R], init: S, stateful: Stateful[R, S, F] ): RIO[R, ActorRef[E, F]] def select[F[+_]](path: String): Task[ActorRef[F]] def shutdown: Task[List[_]] }
  • 23. trait Stateful[-R, S, -F[+_]] { def receive[A]( state: S, msg: F[A], context: Context ): RIO[R, (S, A)] }
  • 24. sealed trait ActorRef[-F[+_]] { def ?[A](fa: F[A]): Task[A] def !(fa: F[_]): Task[Unit] val path: UIO[String] }
  • 25. TYPED
  • 26. sealed trait Message[+_] case object Reset extends Message[Unit] case object Increase extends Message[Unit] case object Get extends Message[Int] val handler = new Stateful[Any, Int, Message] { override def receive[A](state: Int, msg: Message[A], context: Context) = msg match { case Reset => UIO((0, ())) case Increase => UIO((state + 1, ())) case Get => UIO((state, state)) } }
  • 27. sealed trait Message[+_] case object Reset extends Message[Unit] case object Increase extends Message[Unit] case object Get extends Message[Int] val handler = new Stateful[Any, Int, Message] { override def receive[A](state: Int, msg: Message[A], context: Context) = msg match { case Reset => UIO((0, ())) case Increase => UIO((state + 1, ())) case Get => UIO((state, state)) } }
  • 28. for { system <- ActorSystem("test1") actor <- system.make("actor1", Supervisor.none, 0, handler) _ <- actor ! Increase _ <- actor ! Increase c1 <- actor ? Get _ <- actor ! Reset c2 <- actor ? Get } yield assert(c1, equalTo(2)) && assert(c2, equalTo(0))
  • 29. for { system <- ActorSystem("test1") actor <- system.make("actor1", Supervisor.none, 0, handler) _ <- actor ! Increase _ <- actor ! Increase c1 <- actor ? Get _ <- actor ! Reset c2 <- actor ? Get } yield assert(c1, equalTo(2)) && assert(c2, equalTo(0))
  • 30. FSM
  • 31.
  • 32. sealed trait Command[+A] case object Open extends Command[Unit] case object Close extends Command[Unit] case object Sell extends Command[String] sealed trait State case object Opened extends State case object Closed extends State case class SaleException(msg: String) extends Throwable
  • 33. sealed trait Command[+A] case object Open extends Command[Unit] case object Close extends Command[Unit] case object Sell extends Command[String] sealed trait State case object Opened extends State case object Closed extends State case class SaleException(msg: String) extends Throwable
  • 34. new Stateful[Console, State, Command] { override def receive[A]( state: State, msg: Command[A], context: Context ): ZIO[Console, SaleException, (State, A)] = /*...*/ }
  • 35. state match { case Opened => msg match { case Open => UIO((Opened, ())) case Close => putStrLn("Closing...") *> UIO((Closed, ())) case Sell => UIO((Opened, "Selling...")) } case Closed => msg match { case Open => putStrLn("Opening...") *> UIO((Opened, ())) case Close => UIO((Closed, ())) case Sell => IO.fail(SaleException("Shop is closed")) } }
  • 37. for { system <- ActorSystem("sys1") schedule = Schedule.recurs(10) policy = Supervisor.retry(schedule) actor <- system.make("actor1", policy, (), handler) _ <- actor ! MightFail } yield () val s1 = Schedule.exponential(10.milliseconds) val s2 = Schedule.exponential(1.second) && Schedule.recurs(10)
  • 38. for { system <- ActorSystem("sys1") schedule = Schedule.recurs(10) policy = Supervisor.retry(schedule) actor <- system.make("actor1", policy, (), handler) _ <- actor ! MightFail } yield () val s1 = Schedule.exponential(10.milliseconds) val s2 = Schedule.exponential(1.second) && Schedule.recurs(10)
  • 40. CONFIGURATION made with zio-config # application.conf testSystem1.zio.actors.remoting { hostname = ${HOST} port = ${PORT} }
  • 41. for { sys1 <- ActorSystem("testSystem1") _ <- sys1.make("actorOne", Supervisor.none, 0, handler) } yield () //============ OTHER NODE ============== for { sys2 <- ActorSystem("testSystem2") actor <- sys2.select[MyErrorDomain, Message]( s"zio://testSystem1@127.0.0.1:$port1/actorOne" ) result <- actor ? Str("ZIO-Actor response... ") } yield assert(result, equalTo("ZIO-Actor... received 1"))
  • 42. for { sys1 <- ActorSystem("testSystem1") _ <- sys1.make("actorOne", Supervisor.none, 0, handler) } yield () //============ OTHER NODE ============== for { sys2 <- ActorSystem("testSystem2") actor <- sys2.select[MyErrorDomain, Message]( s"zio://testSystem1@127.0.0.1:$port1/actorOne" ) result <- actor ? Str("ZIO-Actor response... ") } yield assert(result, equalTo("ZIO-Actor... received 1"))
  • 44. class EventSourcedStateful[R, S, -F[+_], Ev](id: PersId) { def receive[A]( state: S, msg: F[A], context: Context ): RIO[R, (Command[Ev], S => A)] def sourceEvent(state: S, event: Ev): S }
  • 45. object CounterUtils { sealed trait Message[+_] case object Reset extends Message[Unit] case object Increase extends Message[String] case object Get extends Message[Int] sealed trait CounterEvent case object ResetEvent extends CounterEvent case object IncreaseEvent extends CounterEvent }
  • 46. new EventSourcedStateful[Any, Int, Message, CounterEvent](id) { override def receive[A]( state: Int, msg: Message[A], context: Context ): UIO[(Command[CounterEvent], Int => A)] = msg match { case Reset => UIO((Comm.persist(ResetEvent), _ => ())) case Increase => UIO((Comm.persist(IncreaseEvent), s => s"updated to $s")) case Get => UIO((Comm.ignore, _ => state)) } override def sourceEvent(state: Int, event: CounterEvent): Int = event match { case ResetEvent => 0 case IncreaseEvent => state + 1 } }
  • 47. new EventSourcedStateful[Any, Int, Message, CounterEvent](id) { override def receive[A]( state: Int, msg: Message[A], context: Context ): UIO[(Command[CounterEvent], Int => A)] = msg match { case Reset => UIO((Comm.persist(ResetEvent), _ => ())) case Increase => UIO((Comm.persist(IncreaseEvent), s => s"updated to $s")) case Get => UIO((Comm.ignore, _ => state)) } override def sourceEvent(state: Int, event: CounterEvent): Int = event match { case ResetEvent => 0 case IncreaseEvent => state + 1 } }
  • 48. new EventSourcedStateful[Any, Int, Message, CounterEvent](id) { override def receive[A]( state: Int, msg: Message[A], context: Context ): UIO[(Command[CounterEvent], Int => A)] = msg match { case Reset => UIO((Comm.persist(ResetEvent), _ => ())) case Increase => UIO((Comm.persist(IncreaseEvent), s => s"updated to $s")) case Get => UIO((Comm.ignore, _ => state)) } override def sourceEvent(state: Int, event: CounterEvent): Int = event match { case ResetEvent => 0 case IncreaseEvent => state + 1 } }
  • 50.
  • 52.
  • 53. @throws[IOException] protected def writeObject1(out: ObjectOutputStream): Unit = out.writeObject(actorPath) @throws[ObjectStreamException] protected def readResolve1(): Object = { val remoteRef = for { resolved <- resolvePath(actorPath) (_, addr, port, _) = resolved address <- InetAddress.byName(addr) .flatMap(iAddr => SocketAddress.inetSocketAddress(iAddr, port) ) } yield ActorRefRemote[F](actorPath, address) ActorRefSerial.runtimeForResolve.unsafeRun(remoteRef) }
  • 54. @throws[IOException] protected def writeObject1(out: ObjectOutputStream): Unit = out.writeObject(actorPath) @throws[ObjectStreamException] protected def readResolve1(): Object = { val remoteRef = for { resolved <- resolvePath(actorPath) (_, addr, port, _) = resolved address <- InetAddress.byName(addr) .flatMap(iAddr => SocketAddress.inetSocketAddress(iAddr, port) ) } yield ActorRefRemote[F](actorPath, address) ActorRefSerial.runtimeForResolve.unsafeRun(remoteRef) }
  • 55.
  • 57.
  • 60. GOALS FOR 2020 > Persistence (WIP)
  • 61. GOALS FOR 2020 > Persistence (WIP) > Serialization
  • 62. GOALS FOR 2020 > Persistence (WIP) > Serialization > Monitoring
  • 63. GOALS FOR 2020 > Persistence (WIP) > Serialization > Monitoring > Clustering (zio-keeper )