Skip to content

Commit

Permalink
Use http4s.Uri in Http4sClient
Browse files Browse the repository at this point in the history
This is to avoid conversion between ElasticNodeEndpoint to http4s.Uri
for every request. Which'll save us some allocation, hence more
performance. This also allows users to pass http4s.Uri directly to
Http4sClient.
  • Loading branch information
lenguyenthanh committed Nov 17, 2024
1 parent 91f3793 commit 9b855fc
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,49 @@ object Http4sClient {
override def run[A](fa: IO[A], cb: Either[Throwable, A] => Unit): Unit = fa.unsafeRunAsync(cb)
}

Http4sClient(
client = client,
endpoint = endpoint,
runner = ioRunner
)
}

def usingIO(
client: http4s.client.Client[IO],
endpoint: http4s.Uri,
)(implicit runtime: IORuntime): Http4sClient[IO] = {
val ioRunner = new CallbackRunner[IO] {
override def run[A](fa: IO[A], cb: Either[Throwable, A] => Unit): Unit = fa.unsafeRunAsync(cb)
}

new Http4sClient(
client = client,
endpoint = endpoint,
runner = ioRunner
)
}

def apply[F[_] : Async : Files](
client: http4s.client.Client[F],
endpoint: ElasticNodeEndpoint,
runner: CallbackRunner[F],
): Http4sClient[F] = {
val uri = http4s.Uri(
scheme = Some(http4s.Uri.Scheme.http),
authority = Some(http4s.Uri.Authority(host = http4s.Uri.RegName(endpoint.host), port = Some(endpoint.port))),
)
new Http4sClient(
client = client,
endpoint = uri,
runner = runner
)
}

}

class Http4sClient[F[_] : Async : Files](
client: http4s.client.Client[F],
endpoint: ElasticNodeEndpoint,
endpoint: http4s.Uri,
runner: CallbackRunner[F],
) extends elastic4s.HttpClient with RequestResponseConverters {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package com.sksamuel.elastic4s.http4s
import cats.effect.Async
import cats.syntax.all._
import com.sksamuel.elastic4s
import com.sksamuel.elastic4s.ElasticNodeEndpoint
import fs2.io.file.Files
import org.http4s

Expand All @@ -12,15 +11,11 @@ import scala.language.higherKinds
trait RequestResponseConverters extends Elastic4sEntityEncoders {

def elasticRequestToHttp4sRequest[F[_] : Async : Files](
endpoint: ElasticNodeEndpoint,
endpoint: http4s.Uri,
request: elastic4s.ElasticRequest,
): http4s.Request[F] = {
val uri = http4s.Uri(
scheme = http4s.Uri.Scheme.fromString(endpoint.protocol).toOption,
authority = http4s.Uri.Authority(
host = http4s.Uri.RegName(endpoint.host),
port = endpoint.port.some
).some,
val uri =
endpoint.copy(
path = http4s.Uri.Path(request.endpoint.stripPrefix("/").split('/').map(http4s.Uri.Path.Segment(_)).toVector),
query = http4s.Query.fromPairs(request.params.toList: _*)
)
Expand Down

0 comments on commit 9b855fc

Please sign in to comment.