Skip to content

Commit

Permalink
zio2 support
Browse files Browse the repository at this point in the history
  • Loading branch information
amitksingh1490 committed Feb 9, 2022
1 parent f1e182a commit 9f4acc5
Show file tree
Hide file tree
Showing 26 changed files with 159 additions and 227 deletions.
2 changes: 1 addition & 1 deletion docs/website/docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ import zhttp.http._
object Spec extends DefaultRunnableSpec {

def spec = suite("http")(
testM("should be ok") {
test("should be ok") {
val app = Http.ok
val req = Request()
assertM(app(req))(equalTo(Response.ok)) // an apply method is added via `zhttp.test` package
Expand Down
2 changes: 1 addition & 1 deletion docs/website/docs/v1.x/dsl/http/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ The below snippet tests an app that takes `Int` as input and responds by adding
object Spec extends DefaultRunnableSpec {

def spec = suite("http")(
testM("1 + 1 = 2") {
test("1 + 1 = 2") {
val app: Http[Any, Nothing, Int, Int] = Http.fromFunction[Int](_ + 1)
assertM(app(1))(equalTo(2))
}
Expand Down
2 changes: 1 addition & 1 deletion docs/website/docs/v1.x/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ import zhttp.http._
object Spec extends DefaultRunnableSpec {

def spec = suite("http")(
testM("should be ok") {
test("should be ok") {
val app = Http.ok
val req = Request()
assertM(app(req))(equalTo(Response.ok))
Expand Down
1 change: 0 additions & 1 deletion example/src/main/scala/example/WebSocketEcho.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import zhttp.service.Server
import zhttp.socket.{Socket, WebSocketFrame}
import zio._
import zio.stream.ZStream
import zio.{App, ExitCode, Schedule, UIO, URIO}

object WebSocketEcho extends ZIOAppDefault {
private val socket =
Expand Down
7 changes: 3 additions & 4 deletions example/src/main/scala/example/WebSocketSimpleClient.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import zhttp.socket.{Socket, WebSocketFrame}
import zio._
import zio.stream.ZStream

object WebSocketSimpleClient extends zio.App {
object WebSocketSimpleClient extends ZIOAppDefault {

// Setup client envs
val env = EventLoopGroup.auto() ++ ChannelFactory.auto
Expand All @@ -20,7 +20,6 @@ object WebSocketSimpleClient extends zio.App {
.toSocketApp
.connect(url)

override def run(args: List[String]): URIO[ZEnv, ExitCode] = {
app.exitCode.provideCustomLayer(env)
}
val run = app.exitCode.provideCustomLayer(env)

}
2 changes: 0 additions & 2 deletions zio-http/src/main/scala/zhttp/http/Headers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ final case class Headers(toChunk: Chunk[Header]) extends HeaderExtension[Headers

def toList: List[(String, String)] = toChunk.map { case (name, value) => (name.toString, value.toString) }.toList

def modify(f: Header => Header): Headers = Headers(toChunk.map(f(_)))

override def updateHeaders(update: Headers => Headers): Headers = update(self)

def when(cond: Boolean): Headers = if (cond) self else Headers.empty
Expand Down
5 changes: 0 additions & 5 deletions zio-http/src/main/scala/zhttp/http/Http.scala
Original file line number Diff line number Diff line change
Expand Up @@ -567,11 +567,6 @@ object Http {
*/
def fromZIO[R, E, B](effect: ZIO[R, E, B]): Http[R, E, Any, B] = Http.fromFunctionZIO(_ => effect)

/**
* Converts a ZIO to an Http type
*/
def fromZIO[R, E, B](effect: ZIO[R, E, B]): Http[R, E, Any, B] = Http.fromFunctionZIO(_ => effect)

/**
* Creates an HTTP app which always responds with the provided Html page.
*/
Expand Down
20 changes: 1 addition & 19 deletions zio-http/src/main/scala/zhttp/http/Middleware.scala
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package zhttp.http

import io.netty.util.AsciiString.contentEqualsIgnoreCase
import zhttp.http.middleware.Web
import zio.clock.Clock
import zio.duration.Duration
import zio.{UIO, ZIO}
import zio._

/**
* Middlewares are essentially transformations that one can apply on any Http to
Expand Down Expand Up @@ -122,12 +119,6 @@ trait Middleware[-R, +E, +AIn, -BIn, -AOut, +BOut] { self =>
final def map[BOut0](f: BOut => BOut0): Middleware[R, E, AIn, BIn, AOut, BOut0] =
self.flatMap(b => Middleware.succeed(f(b)))

/**
* Modifies the provided list of headers to the updated list of headers
*/
def modifyHeaders(f: PartialFunction[Header, Header]): Middleware[Any, Nothing] =
patch((_, _) => Patch.updateHeaders(_.modify(f)))

/**
* Transforms the output type of the current middleware using effect function.
*/
Expand Down Expand Up @@ -199,15 +190,6 @@ object Middleware extends Web {
*/
def collect[A]: PartialCollect[A] = new PartialCollect[A](())

/**
* Creates a middleware for signing cookies
*/
def signCookies(secret: String): Middleware[Any, Nothing] =
modifyHeaders {
case h if contentEqualsIgnoreCase(h._1, HeaderNames.setCookie) =>
(HeaderNames.setCookie, Cookie.decodeResponseCookie(h._2.toString).get.sign(secret).encode)
}

/**
* Creates a middleware using specified effect function
*/
Expand Down
13 changes: 5 additions & 8 deletions zio-http/src/main/scala/zhttp/http/middleware/Web.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@ package zhttp.http.middleware
import zhttp.http._
import zhttp.http.headers.HeaderModifier
import zhttp.http.middleware.Web.{PartialInterceptPatch, PartialInterceptZIOPatch}
import zio.clock.Clock
import zio.console.Console
import zio.duration.Duration
import zio.{UIO, ZIO, clock, console}
import zio._

import java.io.IOException

Expand Down Expand Up @@ -35,12 +32,12 @@ private[zhttp] trait Web extends Cors with Csrf with Auth with HeaderModifier[Ht
* Add log status, method, url and time taken from req to res
*/
final def debug: HttpMiddleware[Console with Clock, IOException] =
interceptZIOPatch(req => zio.clock.nanoTime.map(start => (req.method, req.url, start))) {
interceptZIOPatch(req => Clock.nanoTime.map(start => (req.method, req.url, start))) {
case (response, (method, url, start)) =>
for {
end <- clock.nanoTime
_ <- console
.putStrLn(s"${response.status.asJava.code()} ${method} ${url.encode} ${(end - start) / 1000000}ms")
end <- Clock.nanoTime
_ <- Console
.printLine(s"${response.status.asJava.code()} ${method} ${url.encode} ${(end - start) / 1000000}ms")
.mapError(Option(_))
} yield Patch.empty
}
Expand Down
10 changes: 5 additions & 5 deletions zio-http/src/main/scala/zhttp/service/Client.scala
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ final case class Client[R](rtm: HttpRuntime[R], cf: JChannelFactory[Channel], el
url,
Method.GET,
headers,
attribute = Client.Attribute(socketApp = Some(socketApp.provide(env)), ssl = Some(sslOptions)),
attribute = Client.Attribute(socketApp = Some(socketApp.provideEnvironment(env)), ssl = Some(sslOptions)),
),
)
} yield res
Expand Down Expand Up @@ -125,10 +125,10 @@ final case class Client[R](rtm: HttpRuntime[R], cf: JChannelFactory[Channel], el
}

object Client {
def make: ZIO[EventLoopGroup with ChannelFactory, Nothing, Client] = for {
cf <- ZIO.service[ChannelFactory]
el <- ZIO.service[EventLoopGroup]
zx <- HttpRuntime.default[Any]
def make[R]: ZIO[R with EventLoopGroup with ChannelFactory, Nothing, Client[R]] = for {
cf <- ZIO.service[JChannelFactory[Channel]]
el <- ZIO.service[JEventLoopGroup]
zx <- HttpRuntime.default[R]
} yield service.Client(zx, cf, el)

def request(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ final class WebSocketAppHandler[R](
private def writeAndFlush(ctx: ChannelHandlerContext, stream: ZStream[R, Throwable, WebSocketFrame]): Unit =
zExec.unsafeRun(ctx)(
stream
.mapM(frame => ChannelFuture.unit(ctx.writeAndFlush(frame.toWebSocketFrame)))
.mapZIO(frame => ChannelFuture.unit(ctx.writeAndFlush(frame.toWebSocketFrame)))
.runDrain,
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,6 @@ private[zhttp] case class ServerResponseHandler[R](
}
}

/**
* Releases the FullHttpRequest safely.
*/
private def releaseRequest(jReq: FullHttpRequest): Unit = {
if (jReq.refCnt() > 0) {
jReq.release(jReq.refCnt()): Unit
}
}

/**
* Checks if an encoded version of the response exists, uses it if it does.
* Otherwise, it will return a fresh response. It will also set the server
Expand Down
38 changes: 19 additions & 19 deletions zio-http/src/test/scala/zhttp/http/EncodeClientRequestSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package zhttp.http
import io.netty.handler.codec.http.HttpHeaderNames
import zhttp.internal.HttpGen
import zhttp.service.{Client, EncodeClientRequest}
import zio.random.Random
import zio._
import zio.test.Assertion._
import zio.test._

Expand All @@ -30,63 +30,63 @@ object EncodeClientRequestSpec extends DefaultRunnableSpec with EncodeClientRequ
)

def spec = suite("EncodeClientParams") {
testM("method") {
checkM(anyClientParam) { params =>
test("method") {
check(anyClientParam) { params =>
val req = encode(params).map(_.method())
assertM(req)(equalTo(params.method.toJava))
}
} +
testM("method on HttpData.File") {
checkM(HttpGen.clientParamsForFileHttpData()) { params =>
test("method on HttpData.File") {
check(HttpGen.clientParamsForFileHttpData()) { params =>
val req = encode(params).map(_.method())
assertM(req)(equalTo(params.method.toJava))
}
} +
suite("uri") {
testM("uri") {
checkM(anyClientParam) { params =>
test("uri") {
check(anyClientParam) { params =>
val req = encode(params).map(_.uri())
assertM(req)(equalTo(params.url.relative.encode))
}
} +
testM("uri on HttpData.File") {
checkM(HttpGen.clientParamsForFileHttpData()) { params =>
test("uri on HttpData.File") {
check(HttpGen.clientParamsForFileHttpData()) { params =>
val req = encode(params).map(_.uri())
assertM(req)(equalTo(params.url.relative.encode))
}
}
} +
testM("content-length") {
checkM(clientParamWithFiniteData(5)) { params =>
test("content-length") {
check(clientParamWithFiniteData(5)) { params =>
val req = encode(params).map(
_.headers().getInt(HttpHeaderNames.CONTENT_LENGTH).toLong,
)
assertM(req)(equalTo(5L))
}
} +
testM("host header") {
checkM(anyClientParam) { params =>
test("host header") {
check(anyClientParam) { params =>
val req =
encode(params).map(i => Option(i.headers().get(HttpHeaderNames.HOST)))
assertM(req)(equalTo(params.url.host))
}
} +
testM("host header when absolute url") {
checkM(clientParamWithAbsoluteUrl) { params =>
test("host header when absolute url") {
check(clientParamWithAbsoluteUrl) { params =>
val req = encode(params)
.map(i => Option(i.headers().get(HttpHeaderNames.HOST)))
assertM(req)(equalTo(params.url.host))
}
} +
testM("only one host header exists") {
checkM(clientParamWithAbsoluteUrl) { params =>
test("only one host header exists") {
check(clientParamWithAbsoluteUrl) { params =>
val req = encode(params)
.map(_.headers().getAll(HttpHeaderNames.HOST).size)
assertM(req)(equalTo(1))
}
} +
testM("http version") {
checkM(anyClientParam) { params =>
test("http version") {
check(anyClientParam) { params =>
val req = encode(params).map(i => i.protocolVersion())
assertM(req)(equalTo(params.version.toJava))
}
Expand Down
6 changes: 3 additions & 3 deletions zio-http/src/test/scala/zhttp/http/GetBodyAsStringSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ object GetBodyAsStringSpec extends DefaultRunnableSpec {
Gen.fromIterable(List(UTF_8, UTF_16, UTF_16BE, UTF_16LE, US_ASCII, ISO_8859_1))

suite("binary chunk") {
testM("should map bytes according to charset given") {
test("should map bytes according to charset given") {

checkM(charsetGen) { charset =>
check(charsetGen) { charset =>
val request = Client
.ClientRequest(
URL(!!),
Expand All @@ -30,7 +30,7 @@ object GetBodyAsStringSpec extends DefaultRunnableSpec {
assertM(encoded)(equalTo(expected))
}
} +
testM("should map bytes to default utf-8 if no charset given") {
test("should map bytes to default utf-8 if no charset given") {
val request = Client.ClientRequest(URL(!!), data = HttpData.BinaryChunk(Chunk.fromArray("abc".getBytes())))
val encoded = request.bodyAsString
val expected = new String(Chunk.fromArray("abc".getBytes()).toArray, HTTP_CHARSET)
Expand Down
Loading

0 comments on commit 9f4acc5

Please sign in to comment.