Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: ServerResponseHandler #1198

Merged
merged 10 commits into from
Apr 19, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions zio-http/src/main/scala/zhttp/http/Http.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import io.netty.channel.ChannelHandler
import io.netty.handler.codec.http.HttpHeaderNames
import zhttp.html._
import zhttp.http.headers.HeaderModifier
import zhttp.service.server.ServerTime
import zhttp.service.{Handler, HttpRuntime, Server}
import zhttp.service._
import zio._
import zio.blocking.{Blocking, effectBlocking}
import zio.clock.Clock
Expand Down Expand Up @@ -636,13 +635,11 @@ object Http {
self =>

private[zhttp] def compile[R1 <: R](
zExec: HttpRuntime[R1],
settings: Server.Config[R1, Throwable],
serverTimeGenerator: ServerTime,
handler: ServerResponseWriter[R1],
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
handler: ServerResponseWriter[R1],
resWriter: ServerResponseWriter[R1],

)(implicit
evE: E <:< Throwable,
): ChannelHandler =
Handler(http.asInstanceOf[HttpApp[R1, Throwable]], zExec, settings, serverTimeGenerator)
Handler(http.asInstanceOf[HttpApp[R1, Throwable]], handler)

/**
* Patches the response produced by the app
Expand Down
52 changes: 26 additions & 26 deletions zio-http/src/main/scala/zhttp/service/Handler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,19 @@ import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelHandlerContext, SimpleChannelInboundHandler}
import io.netty.handler.codec.http._
import zhttp.http._
import zhttp.service.server.content.handlers.ServerResponseHandler
import zhttp.service.server.{ServerTime, WebSocketUpgrade}
import zhttp.service.server.WebSocketUpgrade
import zio.{UIO, ZIO}

import java.net.{InetAddress, InetSocketAddress}

@Sharable
private[zhttp] final case class Handler[R](
app: HttpApp[R, Throwable],
runtime: HttpRuntime[R],
config: Server.Config[R, Throwable],
serverTimeGenerator: ServerTime,
serverResponseWriter: ServerResponseWriter[R],
) extends SimpleChannelInboundHandler[HttpObject](false)
with WebSocketUpgrade[R]
with ServerResponseHandler[R] { self =>
with WebSocketUpgrade[R] { self =>

override def channelRead0(ctx: Ctx, msg: HttpObject): Unit = {
override def channelRead0(ctx: serverResponseWriter.Ctx, msg: HttpObject): Unit = {

implicit val iCtx: ChannelHandlerContext = ctx
msg match {
Expand Down Expand Up @@ -56,7 +52,7 @@ private[zhttp] final case class Handler[R](
)
catch {
case throwable: Throwable =>
writeResponse(
serverResponseWriter.write(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
serverResponseWriter.write(
resWriter.write(

This is more concise.

Response
.fromHttpError(HttpError.InternalServerError(cause = Some(throwable)))
.withConnection(HeaderValues.close),
Expand Down Expand Up @@ -100,7 +96,7 @@ private[zhttp] final case class Handler[R](
)
catch {
case throwable: Throwable =>
writeResponse(
serverResponseWriter.write(
Response
.fromHttpError(HttpError.InternalServerError(cause = Some(throwable)))
.withConnection(HeaderValues.close),
Expand Down Expand Up @@ -130,7 +126,7 @@ private[zhttp] final case class Handler[R](
jReq: HttpRequest,
http: Http[R, Throwable, A, Response],
a: A,
)(implicit ctx: Ctx): Unit = {
)(implicit ctx: serverResponseWriter.Ctx): Unit = {
http.execute(a) match {
case HExit.Effect(resM) =>
unsafeRunZIO {
Expand All @@ -139,20 +135,20 @@ private[zhttp] final case class Handler[R](
cause.failureOrCause match {
case Left(Some(cause)) =>
UIO {
writeResponse(
serverResponseWriter.write(
Response.fromHttpError(HttpError.InternalServerError(cause = Some(cause))),
jReq,
)
}
case Left(None) =>
UIO {
writeResponse(Response.status(Status.NotFound), jReq)
serverResponseWriter.write(Response.status(Status.NotFound), jReq)
}
case Right(other) =>
other.dieOption match {
case Some(defect) =>
UIO {
writeResponse(
serverResponseWriter.write(
Response.fromHttpError(HttpError.InternalServerError(cause = Some(defect))),
jReq,
)
Expand All @@ -166,7 +162,7 @@ private[zhttp] final case class Handler[R](
else {
for {
_ <- ZIO {
writeResponse(res, jReq)
serverResponseWriter.write(res, jReq)
}
} yield ()
},
Expand All @@ -177,34 +173,38 @@ private[zhttp] final case class Handler[R](
if (self.isWebSocket(res)) {
self.upgradeToWebSocket(jReq, res)
} else {
writeResponse(res, jReq): Unit
serverResponseWriter.write(res, jReq): Unit
}

case HExit.Failure(e) =>
writeResponse(Response.fromHttpError(HttpError.InternalServerError(cause = Some(e))), jReq): Unit
serverResponseWriter.write(
Response.fromHttpError(HttpError.InternalServerError(cause = Some(e))),
jReq,
): Unit

case HExit.Die(e) =>
writeResponse(Response.fromHttpError(HttpError.InternalServerError(cause = Some(e))), jReq): Unit
serverResponseWriter.write(
Response.fromHttpError(HttpError.InternalServerError(cause = Some(e))),
jReq,
): Unit

case HExit.Empty =>
writeResponse(Response.fromHttpError(HttpError.NotFound(Path(jReq.uri()))), jReq): Unit
serverResponseWriter.write(Response.fromHttpError(HttpError.NotFound(Path(jReq.uri()))), jReq): Unit

}
}

/**
* Executes program
*/
private def unsafeRunZIO(program: ZIO[R, Throwable, Any])(implicit ctx: Ctx): Unit =
rt.unsafeRun(ctx) {
private def unsafeRunZIO(program: ZIO[R, Throwable, Any])(implicit ctx: serverResponseWriter.Ctx): Unit =
serverResponseWriter.rt.unsafeRun(ctx) {
program
}

override def serverTime: ServerTime = serverTimeGenerator
override val runtime: HttpRuntime[R] = serverResponseWriter.rt

override val rt: HttpRuntime[R] = runtime

override def exceptionCaught(ctx: Ctx, cause: Throwable): Unit = {
config.error.fold(super.exceptionCaught(ctx, cause))(f => runtime.unsafeRun(ctx)(f(cause)))
override def exceptionCaught(ctx: serverResponseWriter.Ctx, cause: Throwable): Unit = {
serverResponseWriter.config.error.fold(super.exceptionCaught(ctx, cause))(f => runtime.unsafeRun(ctx)(f(cause)))
}
}
3 changes: 2 additions & 1 deletion zio-http/src/main/scala/zhttp/service/Server.scala
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,8 @@ object Server {
channelFactory <- ZManaged.access[ServerChannelFactory](_.get)
eventLoopGroup <- ZManaged.access[EventLoopGroup](_.get)
zExec <- HttpRuntime.sticky[R](eventLoopGroup).toManaged_
reqHandler = settings.app.compile(zExec, settings, ServerTime.make)
handler = ServerResponseWriter(zExec, settings, ServerTime.make)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
handler = ServerResponseWriter(zExec, settings, ServerTime.make)
resWriter = ServerResponseWriter(zExec, settings, ServerTime.make)

reqHandler = settings.app.compile(handler)
init = ServerChannelInitializer(zExec, settings, reqHandler)
serverBootstrap = new ServerBootstrap().channelFactory(channelFactory).group(eventLoopGroup)
chf <- ZManaged.effect(serverBootstrap.childHandler(init).bind(settings.address))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
package zhttp.service.server.content.handlers
package zhttp.service

import io.netty.buffer.ByteBuf
import io.netty.channel.{ChannelHandlerContext, DefaultFileRegion}
import io.netty.handler.codec.http._
import zhttp.http.{HttpData, Response}
import zhttp.service.server.ServerTime
import zhttp.service.{ChannelFuture, HttpRuntime, Server}
import zio.stream.ZStream
import zio.{UIO, ZIO}

import java.io.File

private[zhttp] trait ServerResponseHandler[R] {
private[zhttp] trait ServerResponseWriter[R] {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can convert it to a final class now.

type Ctx = ChannelHandlerContext
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can move Ctx to package.scala file in zhttp.service

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also keep it package private.

val rt: HttpRuntime[R]
val config: Server.Config[R, Throwable]

def serverTime: ServerTime

def writeResponse(msg: Response, jReq: HttpRequest)(implicit ctx: Ctx): Unit = {
def write(msg: Response, jReq: HttpRequest)(implicit ctx: Ctx): Unit = {
ctx.write(encodeResponse(msg))
writeData(msg.data.asInstanceOf[HttpData.Complete], jReq)
()
Expand Down Expand Up @@ -126,3 +125,12 @@ private[zhttp] trait ServerResponseHandler[R] {
} yield ()
}
}
object ServerResponseWriter {
def apply[R](runtime: HttpRuntime[R], conf: Server.Config[R, Throwable], st: ServerTime): ServerResponseWriter[R] =
new ServerResponseWriter[R]() {
override val rt: HttpRuntime[R] = runtime
override val config: Server.Config[R, Throwable] = conf

override def serverTime: ServerTime = st
}
}