Skip to content

Commit

Permalink
Upgrade to ZIO 2.0.0-RC3 (#1174)
Browse files Browse the repository at this point in the history
* upgrade zio version

* fix implementation of use forever

* delete collect scoped

* Revert "delete collect scoped"

This reverts commit 7d74f66.

* switch order of intersection type

* cleanup

* rename

Co-authored-by: Adam Fraser <[email protected]>
  • Loading branch information
d11-amitsingh and adamgfraser authored Apr 1, 2022
1 parent f3c0db5 commit 9d2da98
Show file tree
Hide file tree
Showing 41 changed files with 205 additions and 203 deletions.
2 changes: 1 addition & 1 deletion example/src/main/scala/example/Endpoints.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ object Endpoints extends ZIOAppDefault {
}

def h3 = GET / "b" / *[Int] / "c" / *[Boolean] to { a =>
UIO(Response.text(a.params.toString))
ZIO.succeed(Response.text(a.params.toString))
}

// Run it like any simple app
Expand Down
4 changes: 2 additions & 2 deletions example/src/main/scala/example/HelloWorldAdvanced.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ object HelloWorldAdvanced extends ZIOAppDefault {

// Create a new server
server.make
.use(start =>
.flatMap(start =>
// Waiting for the server to start
Console.printLine(s"Server started on port ${start.port}")

// Ensures the server doesn't die after printing
*> ZIO.never,
)
.provideCustom(ServerChannelFactory.auto, EventLoopGroup.auto(nThreads))
.provideCustom(ServerChannelFactory.auto, EventLoopGroup.auto(nThreads), Scope.default)
}
}
4 changes: 2 additions & 2 deletions example/src/main/scala/example/HttpsHelloWorld.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ object HttpsHelloWorld extends ZIOAppDefault {
)

override val run =
server.make.useForever
.provide(ServerChannelFactory.auto, EventLoopGroup.auto(0))
(server.make *> ZIO.never)
.provide(ServerChannelFactory.auto, EventLoopGroup.auto(0), Scope.default)
}
6 changes: 3 additions & 3 deletions example/src/main/scala/example/PlainTextBenchmarkServer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import io.netty.util.AsciiString
import zhttp.http.{Http, _}
import zhttp.service.server.ServerChannelFactory
import zhttp.service.{EventLoopGroup, Server}
import zio.{ExitCode, UIO, URIO, ZIOAppDefault}
import zio._

/**
* This server is used to run plaintext benchmarks on CI.
Expand Down Expand Up @@ -42,8 +42,8 @@ object Main extends ZIOAppDefault {

val run: URIO[zio.ZEnv, ExitCode] =
app
.flatMap(server(_).make.useForever)
.provideCustomLayer(ServerChannelFactory.auto ++ EventLoopGroup.auto(8))
.flatMap(server(_).make *> ZIO.never)
.provideCustomLayer(ServerChannelFactory.auto ++ EventLoopGroup.auto(8) ++ Scope.default)
.exitCode

private def server(app: HttpApp[Any, Nothing]) =
Expand Down
2 changes: 1 addition & 1 deletion example/src/main/scala/example/WebSocketAdvanced.scala
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ object WebSocketAdvanced extends ZIOAppDefault {

private val app =
Http.collectZIO[Request] {
case Method.GET -> !! / "greet" / name => UIO(Response.text(s"Greetings ${name}!"))
case Method.GET -> !! / "greet" / name => ZIO.succeed(Response.text(s"Greetings ${name}!"))
case Method.GET -> !! / "subscriptions" => socketApp.toResponse
}

Expand Down
2 changes: 1 addition & 1 deletion example/src/main/scala/example/WebSocketEcho.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ object WebSocketEcho extends ZIOAppDefault {

private val app =
Http.collectZIO[Request] {
case Method.GET -> !! / "greet" / name => UIO(Response.text(s"Greetings {$name}!"))
case Method.GET -> !! / "greet" / name => ZIO.succeed(Response.text(s"Greetings {$name}!"))
case Method.GET -> !! / "subscriptions" => socket.toResponse
}

Expand Down
2 changes: 1 addition & 1 deletion project/Dependencies.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ object Dependencies {
val NettyVersion = "4.1.75.Final"
val NettyIncubatorVersion = "0.0.13.Final"
val ScalaCompactCollectionVersion = "2.7.0"
val ZioVersion = "2.0.0-RC2"
val ZioVersion = "2.0.0-RC3"
val SttpVersion = "3.3.18"

val `jwt-core` = "com.github.jwt-scala" %% "jwt-core" % JwtCoreVersion
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package zhttp.benchmarks

import org.openjdk.jmh.annotations._
import org.openjdk.jmh.annotations.{Scope => JScope, _}
import zhttp.http._
import zio._

import java.util.concurrent.TimeUnit

@State(Scope.Thread)
@State(JScope.Thread)
@BenchmarkMode(Array(Mode.Throughput))
@OutputTimeUnit(TimeUnit.SECONDS)
class HttpRouteTextPerf {
Expand All @@ -17,7 +17,7 @@ class HttpRouteTextPerf {
private val app = Http.succeed(res)
private val req: Request = Request(Version.`HTTP/1.1`, Method.GET, URL(!!))
private val httpProgram = ZIO.foreachDiscard(0 to 1000) { _ => app.execute(req).toZIO }
private val UIOProgram = ZIO.foreachDiscard(0 to 1000) { _ => UIO(res) }
private val UIOProgram = ZIO.foreachDiscard(0 to 1000) { _ => ZIO.succeed(res) }

@Benchmark
def benchmarkHttpProgram(): Unit = {
Expand Down
43 changes: 22 additions & 21 deletions zio-http/src/main/scala/zhttp/http/Http.scala
Original file line number Diff line number Diff line change
Expand Up @@ -182,13 +182,13 @@ sealed trait Http[-R, +E, -A, +B] extends (A => ZIO[R, Option[E], B]) { self =>
* Extracts body
*/
final def body(implicit eb: B <:< Response, ee: E <:< Throwable): Http[R, Throwable, A, Chunk[Byte]] =
self.bodyAsByteBuf.mapZIO(buf => Task(Chunk.fromArray(ByteBufUtil.getBytes(buf))))
self.bodyAsByteBuf.mapZIO(buf => ZIO.attempt(Chunk.fromArray(ByteBufUtil.getBytes(buf))))

/**
* Extracts body as a string
*/
final def bodyAsString(implicit eb: B <:< Response, ee: E <:< Throwable): Http[R, Throwable, A, String] =
self.bodyAsByteBuf.mapZIO(bytes => Task(bytes.toString(HTTP_CHARSET)))
self.bodyAsByteBuf.mapZIO(bytes => ZIO.attempt(bytes.toString(HTTP_CHARSET)))

/**
* Catches all the exceptions that the http app can fail with
Expand Down Expand Up @@ -256,10 +256,10 @@ sealed trait Http[-R, +E, -A, +B] extends (A => ZIO[R, Option[E], B]) { self =>
final def collect[R1 <: R, E1 >: E, A1 <: A, B1 >: B, C](pf: PartialFunction[B1, C]): Http[R1, E1, A1, C] =
self >>> Http.collect(pf)

final def collectManaged[R1 <: R, E1 >: E, A1 <: A, B1 >: B, C](
pf: PartialFunction[B1, ZManaged[R1, E1, C]],
final def collectScoped[R1 <: R, E1 >: E, A1 <: A, B1 >: B, C](
pf: PartialFunction[B1, ZIO[Scope with R1, E1, C]],
): Http[R1, E1, A1, C] =
self >>> Http.collectManaged(pf)
self >>> Http.collectScoped[B1][R1, E1, C](pf)

/**
* Collects some of the results of the http and effectfully converts it to
Expand Down Expand Up @@ -318,13 +318,14 @@ sealed trait Http[-R, +E, -A, +B] extends (A => ZIO[R, Option[E], B]) { self =>
/**
* Delays production of output B for the specified duration of time
*/
final def delayAfter(duration: Duration): Http[R with Clock, E, A, B] = self.mapZIO(b => UIO(b).delay(duration))
final def delayAfter(duration: Duration): Http[R with Clock, E, A, B] =
self.mapZIO(b => ZIO.succeed(b).delay(duration))

/**
* Delays consumption of input A for the specified duration of time
*/
final def delayBefore(duration: Duration): Http[R with Clock, E, A, B] =
self.contramapZIO(a => UIO(a).delay(duration))
self.contramapZIO(a => ZIO.succeed(a).delay(duration))

/**
* Returns an http app whose failure and success have been lifted into an
Expand Down Expand Up @@ -457,22 +458,22 @@ sealed trait Http[-R, +E, -A, +B] extends (A => ZIO[R, Option[E], B]) { self =>
/**
* Provides the environment to Http.
*/
final def provideEnvironment(r: ZEnvironment[R])(implicit ev: NeedsEnv[R]): Http[Any, E, A, B] =
final def provideEnvironment(r: ZEnvironment[R]): Http[Any, E, A, B] =
Http.fromOptionFunction[A](a => self(a).provideEnvironment(r))

/**
* Provides layer to Http.
*/
final def provideLayer[E1 >: E, R0](
layer: ZLayer[R0, E1, R],
)(implicit ev2: NeedsEnv[R]): Http[R0, E1, A, B] =
): Http[R0, E1, A, B] =
Http.fromOptionFunction[A](a => self(a).provideLayer(layer.mapError(Option(_))))

/**
* Provides some of the environment to Http.
*/
final def provideSomeEnvironment[R1](r: ZEnvironment[R1] => ZEnvironment[R])(implicit
ev: NeedsEnv[R],
final def provideSomeEnvironment[R1](
r: ZEnvironment[R1] => ZEnvironment[R],
): Http[R1, E, A, B] =
Http.fromOptionFunction[A](a => self(a).provideSomeEnvironment(r))

Expand Down Expand Up @@ -718,9 +719,9 @@ object Http {

/**
* Creates an Http app which accepts a request and produces response from a
* managed resource
* scoped resource
*/
def collectManaged[A]: Http.PartialCollectManaged[A] = Http.PartialCollectManaged(())
def collectScoped[A]: Http.PartialCollectScoped[A] = Http.PartialCollectScoped(())

/**
* Creates an HTTP app which accepts a request and produces response
Expand Down Expand Up @@ -803,7 +804,7 @@ object Http {
/**
* Creates an Http app from the contents of a file.
*/
def fromFile(file: => java.io.File): HttpApp[Any, Throwable] = Http.fromFileZIO(UIO(file))
def fromFile(file: => java.io.File): HttpApp[Any, Throwable] = Http.fromFileZIO(ZIO.succeed(file))

/**
* Creates an Http app from the contents of a file which is produced from an
Expand All @@ -813,7 +814,7 @@ object Http {
def fromFileZIO[R](fileZIO: ZIO[R, Throwable, java.io.File]): HttpApp[R, Throwable] = {
val response: ZIO[R, Throwable, HttpApp[R, Throwable]] =
fileZIO.flatMap { file =>
Task {
ZIO.attempt {
if (file.isFile) {
val length = Headers.contentLength(file.length())
val response = Response(headers = length, data = HttpData.fromFile(file))
Expand Down Expand Up @@ -999,9 +1000,9 @@ object Http {
Http.collect[A] { case a if pf.isDefinedAt(a) => Http.fromZIO(pf(a)) }.flatten
}

final case class PartialCollectManaged[A](unit: Unit) extends AnyVal {
def apply[R, E, B](pf: PartialFunction[A, ZManaged[R, E, B]]): Http[R, E, A, B] =
Http.collect[A] { case a if pf.isDefinedAt(a) => Http.fromZIO(pf(a).useNow) }.flatten
final case class PartialCollectScoped[A](unit: Unit) extends AnyVal {
def apply[R, E, B](pf: PartialFunction[A, ZIO[Scope with R, E, B]]): Http[R, E, A, B] =
Http.collect[A] { case a if pf.isDefinedAt(a) => Http.fromZIO(ZIO.scoped[R](pf(a))) }.flatten
}

final case class PartialCollect[A](unit: Unit) extends AnyVal {
Expand Down Expand Up @@ -1039,10 +1040,10 @@ object Http {
f(a)
.map(Http.succeed)
.catchAll {
case Some(error) => UIO(Http.fail(error))
case None => UIO(Http.empty)
case Some(error) => ZIO.succeed(Http.fail(error))
case None => ZIO.succeed(Http.empty)
}
.catchAllDefect(defect => UIO(Http.die(defect)))
.catchAllDefect(defect => ZIO.succeed(Http.die(defect)))
}
.flatten
}
Expand Down
23 changes: 12 additions & 11 deletions zio-http/src/main/scala/zhttp/http/HttpData.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import io.netty.handler.codec.http.{HttpContent, LastHttpContent}
import io.netty.util.AsciiString
import zhttp.http.HttpData.ByteBufConfig
import zio.stream.ZStream
import zio.{Chunk, Task, UIO, ZIO}
import zio.{Chunk, Task, ZIO}

import java.io.FileInputStream
import java.nio.charset.Charset
Expand Down Expand Up @@ -148,7 +148,7 @@ object HttpData {
val buffer = Unpooled.compositeBuffer()
msg => {
buffer.addComponent(true, msg.content)
if (msg.isLast) cb(UIO(buffer)) else ch.read()
if (msg.isLast) cb(ZIO.succeed(buffer)) else ch.read()
}
}),
)
Expand Down Expand Up @@ -178,7 +178,8 @@ object HttpData {
* Encodes the HttpData into a ByteBuf. Takes in ByteBufConfig to have a
* more fine grained control over the encoding.
*/
override def toByteBuf(config: ByteBufConfig): Task[ByteBuf] = Task(Unpooled.wrappedBuffer(asciiString.array()))
override def toByteBuf(config: ByteBufConfig): Task[ByteBuf] =
ZIO.attempt(Unpooled.wrappedBuffer(asciiString.array()))

/**
* Encodes the HttpData into a Stream of ByteBufs. Takes in ByteBufConfig to
Expand All @@ -202,7 +203,7 @@ object HttpData {
/**
* Encodes the HttpData into a ByteBuf.
*/
override def toByteBuf(config: ByteBufConfig): Task[ByteBuf] = UIO(encode)
override def toByteBuf(config: ByteBufConfig): Task[ByteBuf] = ZIO.succeed(encode)

/**
* Encodes the HttpData into a Stream of ByteBufs
Expand All @@ -218,7 +219,7 @@ object HttpData {
/**
* Encodes the HttpData into a ByteBuf.
*/
override def toByteBuf(config: ByteBufConfig): Task[ByteBuf] = Task(data)
override def toByteBuf(config: ByteBufConfig): Task[ByteBuf] = ZIO.attempt(data)

/**
* Encodes the HttpData into a Stream of ByteBufs
Expand Down Expand Up @@ -261,18 +262,18 @@ object HttpData {
override def toByteBufStream(config: ByteBufConfig): ZStream[Any, Throwable, ByteBuf] =
ZStream.unwrap {
for {
file <- Task(unsafeFile())
fs <- Task(new FileInputStream(file))
file <- ZIO.attempt(unsafeFile())
fs <- ZIO.attempt(new FileInputStream(file))
size = config.chunkSize(file.length())
buffer = new Array[Byte](size)
} yield ZStream
.repeatZIOOption[Any, Throwable, ByteBuf] {
for {
len <- Task(fs.read(buffer)).mapError(Some(_))
bytes <- if (len > 0) UIO(Unpooled.copiedBuffer(buffer, 0, len)) else ZIO.fail(None)
len <- ZIO.attempt(fs.read(buffer)).mapError(Some(_))
bytes <- if (len > 0) ZIO.succeed(Unpooled.copiedBuffer(buffer, 0, len)) else ZIO.fail(None)
} yield bytes
}
.ensuring(UIO(fs.close()))
.ensuring(ZIO.succeed(fs.close()))
}

override def toHttp(config: ByteBufConfig): Http[Any, Throwable, Any, ByteBuf] =
Expand All @@ -288,7 +289,7 @@ object HttpData {
/**
* Encodes the HttpData into a ByteBuf.
*/
override def toByteBuf(config: ByteBufConfig): Task[ByteBuf] = UIO(Unpooled.EMPTY_BUFFER)
override def toByteBuf(config: ByteBufConfig): Task[ByteBuf] = ZIO.succeed(Unpooled.EMPTY_BUFFER)

/**
* Encodes the HttpData into a Stream of ByteBufs
Expand Down
8 changes: 5 additions & 3 deletions zio-http/src/main/scala/zhttp/http/HttpDataExtension.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import io.netty.buffer.{ByteBuf, ByteBufUtil}
import io.netty.util.AsciiString
import zhttp.http.headers.HeaderExtension
import zio.stream.ZStream
import zio.{Chunk, Task, UIO, ZIO}
import zio.{Chunk, Task, ZIO}

private[zhttp] trait HttpDataExtension[+A] extends HeaderExtension[A] { self: A =>
private[zhttp] final def bodyAsByteBuf: Task[ByteBuf] = data.toByteBuf
Expand All @@ -18,7 +18,9 @@ private[zhttp] trait HttpDataExtension[+A] extends HeaderExtension[A] { self: A
bodyAsByteArray.map(Chunk.fromArray)

final def bodyAsByteArray: Task[Array[Byte]] =
bodyAsByteBuf.flatMap(buf => Task(ByteBufUtil.getBytes(buf)).ensuring(UIO(buf.release(buf.refCnt()))))
bodyAsByteBuf.flatMap(buf =>
ZIO.attempt(ByteBufUtil.getBytes(buf)).ensuring(ZIO.succeed(buf.release(buf.refCnt()))),
)

/**
* Decodes the content of request as CharSequence
Expand All @@ -31,7 +33,7 @@ private[zhttp] trait HttpDataExtension[+A] extends HeaderExtension[A] { self: A
*/
final def bodyAsStream: ZStream[Any, Throwable, Byte] = data.toByteBufStream
.mapZIO[Any, Throwable, Chunk[Byte]] { buf =>
Task {
ZIO.attempt {
val bytes = Chunk.fromArray(ByteBufUtil.getBytes(buf))
buf.release(buf.refCnt())
bytes
Expand Down
10 changes: 5 additions & 5 deletions zio-http/src/main/scala/zhttp/http/Middleware.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package zhttp.http

import zhttp.http.middleware.Web
import zio.{Clock, Duration, UIO, ZIO}
import zio.{Clock, Duration, ZIO}

/**
* Middlewares are essentially transformations that one can apply on any Http to
Expand Down Expand Up @@ -80,7 +80,7 @@ trait Middleware[-R, +E, +AIn, -BIn, -AOut, +BOut] { self =>
* Preprocesses the incoming value for the outgoing Http.
*/
final def contramap[AOut0](f: AOut0 => AOut): Middleware[R, E, AIn, BIn, AOut0, BOut] =
self.contramapZIO[AOut0](a => UIO(f(a)))
self.contramapZIO[AOut0](a => ZIO.succeed(f(a)))

/**
* Preprocesses the incoming value using a ZIO, for the outgoing Http.
Expand All @@ -92,7 +92,7 @@ trait Middleware[-R, +E, +AIn, -BIn, -AOut, +BOut] { self =>
* Delays the production of Http output for the specified duration
*/
final def delay(duration: Duration): Middleware[R with Clock, E, AIn, BIn, AOut, BOut] =
self.mapZIO(b => UIO(b).delay(duration))
self.mapZIO(b => ZIO.succeed(b).delay(duration))

/**
* Creates a new Middleware from another
Expand Down Expand Up @@ -158,7 +158,7 @@ trait Middleware[-R, +E, +AIn, -BIn, -AOut, +BOut] { self =>
* Applies Middleware based only if the condition function evaluates to true
*/
final def when[AOut0 <: AOut](cond: AOut0 => Boolean): Middleware[R, E, AIn, BIn, AOut0, BOut] =
whenZIO(a => UIO(cond(a)))
whenZIO(a => ZIO.succeed(cond(a)))

/**
* Applies Middleware based only if the condition effectful function evaluates
Expand Down Expand Up @@ -269,7 +269,7 @@ object Middleware extends Web {

final class PartialIntercept[A, B](val unit: Unit) extends AnyVal {
def apply[S, BOut](incoming: A => S)(outgoing: (B, S) => BOut): Middleware[Any, Nothing, A, B, A, BOut] =
interceptZIO[A, B](a => UIO(incoming(a)))((b, s) => UIO(outgoing(b, s)))
interceptZIO[A, B](a => ZIO.succeed(incoming(a)))((b, s) => ZIO.succeed(outgoing(b, s)))
}

final class PartialInterceptZIO[A, B](val unit: Unit) extends AnyVal {
Expand Down
2 changes: 1 addition & 1 deletion zio-http/src/main/scala/zhttp/http/Response.scala
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ final case class Response private (
* to be counter productive.
*/
def freeze: UIO[Response] =
UIO(self.copy(attribute = self.attribute.withEncodedResponse(unsafeEncode(), self)))
ZIO.succeed(self.copy(attribute = self.attribute.withEncodedResponse(unsafeEncode(), self)))

/**
* Sets the response attributes
Expand Down
Loading

0 comments on commit 9d2da98

Please sign in to comment.