rssh / cps-async-connect

Apache License 2.0
17 stars 3 forks source link

Any clue how to implement zio2 FiberRef? #4

Closed wiltonlazary closed 2 years ago

wiltonlazary commented 2 years ago

Expression type:

FiberRef[Map[String, Any]] Symbol signature:

def await[F[$1], T, G[$2]](f: F[T])(using am: CpsAwaitable[F], ctx: CpsMonadContext[G]): T Pseudofunction, which can be used inside async block, to 'await' (i.e. receive value of t:T from ft:F[T]).

Can't find cps.CpsMonadConversion[[A >: scala.Nothing <: scala.Any] => zio.ZIO[zio.Scope, scala.Nothing, A], zio.Task]: given instance zioToZio in package cps.monads.zio does not match type cps.CpsMonadConversion[[A] =>> zio.ZIO[zio.Scope, Nothing, A], zio.Task]sbt

wiltonlazary commented 2 years ago
import zio.{given, *}
import cps.monads.zio.{given, *}
import cps.{given, *}

object ctx:
  private val ref = zio.FiberRef.make(Map.empty[String, Any])

  def withCtx[R](body: => Task[R]) = async[Task] {
    val ctx = await(ref)
  }
rssh commented 2 years ago

Let-s try to deduce types by hand:

We have zioToZio with the next signature:

given zioToZio[R1,R2<:R1,E1,E2>:E1]: CpsMonadConversion[[T] =>> ZIO[R1,E1,T], [T]=>>ZIO[R2,E2,T]] 

Our failed conversion:

// zio[Scope,Nothing,A] => zio.Task[A]
//                                            zio[Any, Throwable, A]
// 
// .   R1 = Scope, E1 = Nothing
//     R2 = Any    E1 = Throwable
// .   R2 <: R1 = (Any <:  Scope) - false.  

So, resolution is correct - this should not be compiled, because environment of Task (Any) is not a subset of Scope.

For rechecking we can emulate same logic without async:

 def withCtxNoAwait[R](body:  => Task[R]):Task[Unit] = {
    ref.map(_ => ())
  }

To have Scope in the environment we should have something like:

  def withCtx[R](body: => Task[R]) = async[[T]=>>ZIO[Scope,Throwable,T]] {
    val ctx = ref
    body
  }

Btw, let's think, are R2<:R1 requirement is correct(?) R - is a set of requirements. Any - no requirements, buf FiberRef introduce Scope requirement, so I think it's necessory.

wiltonlazary commented 2 years ago

Great, thanks very much.