Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import akka.actor.typed.*
- import akka.actor.typed.scaladsl.AskPattern.*
- import akka.util.Timeout
- import cats.effect.*
- import cats.syntax.all.*
- import scala.annotation.targetName
- import scala.annotation.unchecked.uncheckedVariance
- import scala.concurrent.Future
- trait SummonerK[G[_[_]]] {
- def apply[F[_]: G]: G[F] = summon[G[F]]
- }
- trait FromFuture[F[_]] {
- def fromFuture[T](f: => Future[T]): F[T]
- }
- object FromFuture extends SummonerK[FromFuture] {
- given [F[_]: Async]: FromFuture[F] = new FromFuture[F] {
- override def fromFuture[T](f: => Future[T]): F[T] =
- Async[F].fromFuture {
- Async[F].delay {
- f
- }
- }
- }
- }
- trait Actor[F[_], -T] {
- @targetName("tell")
- def !(message: T): F[Unit]
- @targetName("ask")
- def ?[R](message: ActorRef[R] => T)(using timeout: Timeout, scheduler: Scheduler): F[R]
- def unsafe(): ActorRef[T @uncheckedVariance]
- }
- object Actor {
- private class Impl[F[_]: Async, -T](underlying: ActorRef[T]) extends Actor[F, T] {
- @targetName("tell")
- override def !(message: T): F[Unit] =
- Async[F].delay {
- underlying ! message
- }
- @targetName("ask")
- override def ?[R](message: ActorRef[R] => T)(using timeout: Timeout, scheduler: Scheduler): F[R] =
- FromFuture[F].fromFuture {
- underlying.ask[R](message)
- }
- override def unsafe(): ActorRef[T] = underlying
- }
- def apply[F[_]: Async, T](underlying: ActorRef[T]): Actor[F, T] = Impl[F, T](underlying)
- }
- trait SpawnActor[F[_]] {
- def actor[T](name: String, behavior: Behavior[T]): F[Actor[F, T]]
- }
- object SpawnActor extends SummonerK[SpawnActor] {
- given [F[_]: Async](using system: ActorSystem[SpawnProtocol.Command],
- timeout: Timeout): SpawnActor[F] =
- new SpawnActor[F] {
- override def actor[T](name: String, behavior: Behavior[T]): F[Actor[F, T]] =
- FromFuture[F].fromFuture {
- system.ask[ActorRef[T]] { replyTo =>
- SpawnProtocol.Spawn(
- behavior,
- name,
- Props.empty,
- replyTo,
- )
- }
- }.map(Actor.apply)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement