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 all 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
7 changes: 3 additions & 4 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.{Handler, HttpRuntime, Server, ServerResponseWriter}
import zio._
import zio.blocking.{Blocking, effectBlocking}
import zio.clock.Clock
Expand Down Expand Up @@ -638,11 +637,11 @@ object Http {
private[zhttp] def compile[R1 <: R](
zExec: HttpRuntime[R1],
settings: Server.Config[R1, Throwable],
serverTimeGenerator: ServerTime,
resWriter: ServerResponseWriter[R1],
)(implicit
evE: E <:< Throwable,
): ChannelHandler =
Handler(http.asInstanceOf[HttpApp[R1, Throwable]], zExec, settings, serverTimeGenerator)
Handler(http.asInstanceOf[HttpApp[R1, Throwable]], zExec, settings, resWriter)

/**
* Patches the response produced by the app
Expand Down
41 changes: 21 additions & 20 deletions zio-http/src/main/scala/zhttp/service/Handler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ 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}
Expand All @@ -15,10 +14,9 @@ private[zhttp] final case class Handler[R](
app: HttpApp[R, Throwable],
runtime: HttpRuntime[R],
config: Server.Config[R, Throwable],
serverTimeGenerator: ServerTime,
resWriter: 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 = {

Expand Down Expand Up @@ -56,7 +54,7 @@ private[zhttp] final case class Handler[R](
)
catch {
case throwable: Throwable =>
writeResponse(
resWriter.write(
Response
.fromHttpError(HttpError.InternalServerError(cause = Some(throwable)))
.withConnection(HeaderValues.close),
Expand Down Expand Up @@ -100,7 +98,7 @@ private[zhttp] final case class Handler[R](
)
catch {
case throwable: Throwable =>
writeResponse(
resWriter.write(
Response
.fromHttpError(HttpError.InternalServerError(cause = Some(throwable)))
.withConnection(HeaderValues.close),
Expand Down Expand Up @@ -139,20 +137,20 @@ private[zhttp] final case class Handler[R](
cause.failureOrCause match {
case Left(Some(cause)) =>
UIO {
writeResponse(
resWriter.write(
Response.fromHttpError(HttpError.InternalServerError(cause = Some(cause))),
jReq,
)
}
case Left(None) =>
UIO {
writeResponse(Response.status(Status.NotFound), jReq)
resWriter.write(Response.status(Status.NotFound), jReq)
}
case Right(other) =>
other.dieOption match {
case Some(defect) =>
UIO {
writeResponse(
resWriter.write(
Response.fromHttpError(HttpError.InternalServerError(cause = Some(defect))),
jReq,
)
Expand All @@ -166,7 +164,7 @@ private[zhttp] final case class Handler[R](
else {
for {
_ <- ZIO {
writeResponse(res, jReq)
resWriter.write(res, jReq)
}
} yield ()
},
Expand All @@ -177,17 +175,23 @@ private[zhttp] final case class Handler[R](
if (self.isWebSocket(res)) {
self.upgradeToWebSocket(jReq, res)
} else {
writeResponse(res, jReq): Unit
resWriter.write(res, jReq): Unit
}

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

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

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

}
}
Expand All @@ -196,15 +200,12 @@ private[zhttp] final case class Handler[R](
* Executes program
*/
private def unsafeRunZIO(program: ZIO[R, Throwable, Any])(implicit ctx: Ctx): Unit =
rt.unsafeRun(ctx) {
runtime.unsafeRun(ctx) {
program
}

override def serverTime: ServerTime = serverTimeGenerator

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)))
}

}
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 = new ServerResponseWriter(zExec, settings, ServerTime.make)
reqHandler = settings.app.compile(zExec, settings, 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,22 @@
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] {
type Ctx = ChannelHandlerContext
val rt: HttpRuntime[R]
val config: Server.Config[R, Throwable]
private[zhttp] final class ServerResponseWriter[R](
runtime: HttpRuntime[R],
config: Server.Config[R, Throwable],
serverTime: ServerTime,
) {

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 @@ -104,7 +102,7 @@ private[zhttp] trait ServerResponseHandler[R] {
case HttpData.Empty => flushReleaseAndRead(jReq)

case HttpData.BinaryStream(stream) =>
rt.unsafeRun(ctx) {
runtime.unsafeRun(ctx) {
writeStreamContent(stream).ensuring(UIO(releaseAndRead(jReq)))
}

Expand Down
10 changes: 9 additions & 1 deletion zio-http/src/main/scala/zhttp/service/package.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package zhttp

import io.netty.channel.{Channel, ChannelFactory => JChannelFactory, EventLoopGroup => JEventLoopGroup, ServerChannel}
import io.netty.channel.{
Channel,
ChannelFactory => JChannelFactory,
ChannelHandlerContext,
EventLoopGroup => JEventLoopGroup,
ServerChannel,
}
import zio.Has

package object service {
Expand All @@ -27,4 +33,6 @@ package object service {
type EventLoopGroup = Has[JEventLoopGroup]
type ServerChannelFactory = Has[JChannelFactory[ServerChannel]]
type UServer = Server[Any, Nothing]
private[zhttp] type Ctx = ChannelHandlerContext
tusharmath marked this conversation as resolved.
Show resolved Hide resolved

}