hammock icon indicating copy to clipboard operation
hammock copied to clipboard

Reduce allocation overhead by removing Kleisli layer

Open rlecomte opened this issue 6 years ago • 2 comments

Hammock Interpreter have HttpClient as constructor parameter. So why use Kleisli[F, HttpClient, ?] in the internal machinery?

We could just use Async effect without any other layer.

rlecomte avatar May 21 '18 19:05 rlecomte

Hi @rlecomte!

Yeah, you're right that receiving it as a constructor param and using it in the transK method is a bit repetitive.

However, since the interface we need to follow is the one from InterpTrans, we need it in both places, as for now, since the transK method is being used in other projects.

I've however thought of changing the InterpTrans more than once, that meaning that since for all implementations of the interpreter we'd need a value of the target's http client (apache's HttpClient, Akka's HttpExt...), I'd delete the trans method from the typeclass and only use the transK method.

trait InterpTrans[F[_], Client] {
  def transK(implicit S: Sync[F]): HttpF ~> Kleisli[F, Client, ?]
}

And we'd create instances of the like this:

implicit object AkkaInterpreter extends InterpTrans[F, HttpExt] {
  def transK...
}

What do you think about it? if we end up creating interpreters like so, we'd end up not needing the constructor parameter.

pepegar avatar May 23 '18 07:05 pepegar

I'm not sure to understand the whole picture but here is my 2 cents :

/*
  Keep interpreter signature as simple as possible. Just a F type without any behavior.
 */
trait InterpTrans[F[_]] {
  def trans: HttpF ~> F
}
/*
 Just an alias for Kleisli interpreter
*/
trait KleisliInterTrans[F[_], Client] extends InterpTrans[Kleisli[F, Client, ?]]
/*
 Here is the trick : deal with legacy by using client in context to execute kleisli interpreter
*/
trait LegacyTrans[F, Client] extends InterpTrans[F[_]] {
  val client: Client
  val kleisliTrans: KleisliInterTrans[F, Client, ?]

  def trans: HttpF ~> F = kleisliTrans.transK andThen λ[Kleisli[F, Client, ?] ~> F](_.run(client))

  def transK: HttpF ~> Kleisli[F, Client, ?] = kleisliTrans.trans
}
/*
An implementation for apache http client
*/
case class ApacheHttpClientTrans[F[_]](client: HttpClient) extends LegacyTrans[F, HttpClient] {
  val kleisliTrans = ApacheHttpClientKleisliTrans
}

object ApacheHttpClientKleisliTrans extends KleisliInterTrans[F, HttpClient] {
   //implementation
}

In this way, we don't introduce any breaking change and keep InterpTrans as simple as possible. This allow to implement any interpreter we want.

rlecomte avatar May 24 '18 16:05 rlecomte