Skip to content

Commit

Permalink
ZIO 2: Latest changes from main (#858)
Browse files Browse the repository at this point in the history
* Doc: Add outline (#815)

* doc: add categories

* refactor: doc structure refactored

* fix: package-lock.json removed

* refactor: create outline sub-directories

* refactor: rename test to testing

* Docs: Update Basic Examples (#814)

* doc(Getting started): updated examples

* docs: updated basic examples

* docs: update advanced examples (#816)

* maintenance: semanticdb revision usage (#832)

* maintenance: workflow scala version (#833)

* Fix: HasHeader bug (#835)

* #834 - fix and test for the bug.

* applied suggested change

* refactor: fix naming for Http operators (#839)

* Update sbt-bloop to 1.4.12 (#810)

* Update sbt-bloop to 1.4.12

* Update sbt-bloop to 1.4.12

* Update scala-library to 2.13.8 (#801)

* Update scala-library to 2.13.8

* Regenerate workflow with sbt-github-actions

* Add configuration builder methods to zhttp.service.Server (#768)

* Add configuration builder methods to zhttp.service.Server

* Update zio-http/src/main/scala/zhttp/service/Server.scala

Co-authored-by: Tushar Mathur <tusharmath@gmail.com>

* Update zio-http/src/main/scala/zhttp/service/Server.scala

Co-authored-by: Tushar Mathur <tusharmath@gmail.com>

* Update zio-http/src/main/scala/zhttp/service/Server.scala

Co-authored-by: Tushar Mathur <tusharmath@gmail.com>

* Change some server with* builder methods (enable parameter)

* Server withAcceptContinue(enabled)

Co-authored-by: Tushar Mathur <tusharmath@gmail.com>

* maintenance: html template for internal server error string (#851)

Closes #842

* Performance: Improve benchmarking code (#731)

* wip: try server codec without validation

* wip: remove flush consolidator

* wip: use wrapped buffer

* wip: add flush consolidator

* perf: make response encoding checks faster

* use encoder and decoder (#733)

* wip: remove Request creation

* use encoder and decoder

Co-authored-by: Tushar Mathur <tusharmath@gmail.com>

* disable object aggregator

* disable object aggregator

* revert disable object aggregator

* doc: update scala doc

* perf: freeze the HttpResponse

Co-authored-by: Amit Kumar Singh <amit.singh@dream11.com>
Co-authored-by: amitsingh <amitksingh1490@gmail.com>

* Refactor: Support middlewares on Http (#773)

* refactor: remove type-params from Response

* chore: self review

* refactor: rename Middleware to HttpMiddleware

* refactor: add `@@@` to Http as an alternative to `@@`.

* feature: add new Middleware API

* feature: add `flatten` and `ifThenElse`

* feature: add `ifThenElseZIO`

* refactor: fix type params for `identity`

* feature: add `when`

* feature: add `make` constructor

* refactor: make middleware methods final

* refactor: git remains

* refactor: implement HttpMiddleware as Middleware

* scala3 fix

* Refactor CORS middleware (#788)

* Refactor/merge middleware and http middleware (#790)

* Refactor move cors and timeout

* move some httpMiddlewares to Middleware

* move some AuthMiddleware to Middleware

* move remaining AuthMiddleware to Middleware

* move Middlewares to middleware package

* scaladoc

* codec example

* move Middleware to http package

* named alias for `@@`

* rename Auth to AuthMiddlewares

* rename CORSMiddleware to CorsMiddlewares

* rename CSRF to CsrfMiddlewares

* make primitives private

* rename MiddlewareExtensions to HttpMiddlewares

* rename operators in HttpMiddlewares

* scalaDoc

* arg rename

* doc update and general refactor

* simplify cors middleware

* rename CorsConfig

* renames

* Make middlewares package private MiddlewareRequest

* Introduce MiddlewareRequest (#798)

* Introduce MiddlewareRequest

* PR review comments

* Refactor move runAfter to Middleware

* refactor: add `UMiddleware`

* feature: add `contramapZIO`

* refactor: move cors config to Cors file

* refactor: rename files

* refactor: remove AuthSpec from WebSpec

* refactor: fix naming for Http operators

* refactor: add partial type suport for contraMapZIO

* Refactor: Codec (#841)

* Add Run Before (#840)

* Add Run Before

* Add Run Before and After

* use renamed operator

* refactor: add partial type suport for contraMap

* Implement missing operators in Middleware (#807)

* Implement missing operators in Middleware

* fix as operator

* headers Middleware changes

* sign cookie

* extend with HeaderExtensions

* rename suite

* PR comments

* refactor: use `Request` instead of `MiddlewareRequest`

* refactor: rename methods

* refactor: resolve fix me issue

Co-authored-by: amitsingh <amitksingh1490@gmail.com>
Co-authored-by: Amit Kumar Singh <amit.singh@dream11.com>

* ZIO 2 support (#809)

* upgrade to zio 2.0.0-RC1

* bump timeout for failing test

* other fixes

* increase timeout

* rejigger broken test

* try, try again

* get compiling & tests passing

Co-authored-by: Kit Langton <kit.langton@gmail.com>

* Delete commented websocket tests (#826)

* Backmerge main 14 jan 2021 (#831)

* Doc: Add outline (#815)

* doc: add categories

* refactor: doc structure refactored

* fix: package-lock.json removed

* refactor: create outline sub-directories

* refactor: rename test to testing

* Update netty-all to 4.1.73.Final (#811)

* Feature: API to modify headers (#824)

* feat(Headers):added new api to update headers

* renamed api

* Feature: Signed Cookie (#751)

* feat(cookie): added secret in cookie

* feat(cookie): added signcookie middleware

* feat(cookie): scalafmt

* fix(cookie): sign cookie while encoding

* scalafmt

* fix(Cookie): added unsign method for cookie

* fix(cookie): minor changes

* fix(signCookieMiddleware: simplified signCookies

* fix(cookie): removed try catch from signContent

* cookie: throw error in verify

* cookie: throw error in verify

* verify method changes

* fixed test cases

* fix: removed decodeResponseSignedCookie

* fix: middlewareSpec

* added modifyheaders in middleware

* removed unwanted changes

* scalafmt

* refactoring

* refactoring

* build fix

* build fix

* fix: decodeResponseCookie

* added modify

* Update sbt-scalafix to 0.9.34 (#805)

* Fix: Echo streaming (#828)

* Failing test

* Fix echo streaming

* Pr Comments

* ZIO 2 support (#809)

* upgrade to zio 2.0.0-RC1

* bump timeout for failing test

* other fixes

* increase timeout

* rejigger broken test

* try, try again

* get compiling & tests passing

Co-authored-by: Kit Langton <kit.langton@gmail.com>

* ZIO2 changes

* scalafmt

* renamed

Co-authored-by: Shubham Girdhar <girdharshubham@hotmail.com>
Co-authored-by: Shruti Verma <62893271+ShrutiVerma97@users.noreply.github.com>
Co-authored-by: John A. De Goes <john@degoes.net>
Co-authored-by: Kit Langton <kit.langton@gmail.com>

* Merge

Co-authored-by: Shubham Girdhar <girdharshubham@hotmail.com>
Co-authored-by: Shruti Verma <62893271+ShrutiVerma97@users.noreply.github.com>
Co-authored-by: Gabriel Ciuloaica <95849448+gciuloaica@users.noreply.github.com>
Co-authored-by: Tushar Mathur <tushar@dream11.com>
Co-authored-by: Amit Kumar Singh <amit.singh@dream11.com>
Co-authored-by: Javier Goday <jgoday@gmail.com>
Co-authored-by: Tushar Mathur <tusharmath@gmail.com>
Co-authored-by: amitsingh <amitksingh1490@gmail.com>
Co-authored-by: Kit Langton <kit.langton@gmail.com>
  • Loading branch information
10 people authored Jan 19, 2022
1 parent fcff083 commit 49a4e52
Show file tree
Hide file tree
Showing 52 changed files with 1,525 additions and 1,163 deletions.
22 changes: 11 additions & 11 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest]
scala: [2.12.15, 2.13.7, 3.1.0]
scala: [2.12.15, 2.13.8, 3.1.0]
java: [graal_21.1.0@11, temurin@8]
runs-on: ${{ matrix.os }}
steps:
Expand Down Expand Up @@ -60,7 +60,7 @@ jobs:
key: ${{ runner.os }}-sbt-cache-v2-${{ hashFiles('**/*.sbt') }}-${{ hashFiles('project/build.properties') }}

- name: Check formatting
run: sbt ++2.13.7 fmtCheck
run: sbt ++2.13.8 fmtCheck

- name: Check that workflows are up to date
run: sbt ++${{ matrix.scala }} githubWorkflowCheck
Expand All @@ -70,7 +70,7 @@ jobs:

- name: Check doc generation
if: ${{ github.event_name == 'pull_request' }}
run: sbt ++2.13.7 doc
run: sbt ++2.13.8 doc

- name: Compress target directories
run: tar cf targets.tar target zio-http-test/target zio-http/target zio-http-benchmarks/target example/target project/target
Expand All @@ -88,7 +88,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest]
scala: [2.13.7]
scala: [2.13.8]
java: [graal_21.1.0@11]
runs-on: ${{ matrix.os }}
steps:
Expand Down Expand Up @@ -133,12 +133,12 @@ jobs:
tar xf targets.tar
rm targets.tar
- name: Download target directories (2.13.7)
- name: Download target directories (2.13.8)
uses: actions/download-artifact@v2
with:
name: target-${{ matrix.os }}-2.13.7-${{ matrix.java }}
name: target-${{ matrix.os }}-2.13.8-${{ matrix.java }}

- name: Inflate target directories (2.13.7)
- name: Inflate target directories (2.13.8)
run: |
tar xf targets.tar
rm targets.tar
Expand Down Expand Up @@ -201,7 +201,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest]
scala: [2.13.6]
scala: [2.13.8]
java: [temurin@11]
runs-on: ${{ matrix.os }}
steps:
Expand All @@ -212,7 +212,7 @@ jobs:

- name: Add Scoverage
id: add_plugin
run: sed -i -e '$aaddSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.2")' project/plugins.sbt
run: sed -i -e '$aaddSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.3")' project/plugins.sbt

- name: Update Build Definition
id: update_build_definition
Expand All @@ -222,7 +222,7 @@ jobs:
- name: Run Coverage
id: run_coverage
run: sbt ++2.13.7 coverage 'project zhttp;test' coverageReport
run: sbt ++${{ matrix.scala }} 'coverage; project zhttp; test; coverageReport'

- name: Push Codecov
id: push_codecov
Expand All @@ -234,7 +234,7 @@ jobs:
strategy:
matrix:
os: [centos]
scala: [2.13.6]
scala: [2.13.8]
java: [temurin@11]
runs-on: [ "${{ matrix.os }}", zio-http ]
steps:
Expand Down
31 changes: 14 additions & 17 deletions docs/website/docs/examples/advanced-examples/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

```scala
import pdi.jwt.{Jwt, JwtAlgorithm, JwtClaim}
import zhttp.http.{Method, _}
import zhttp.http._
import zhttp.service.Server
import zio._

Expand All @@ -27,36 +27,33 @@ object Authentication extends ZIOAppDefault {
}

// Authentication middleware
// Takes in a Failing HttpApp and a Succeed HttpApp which are
// called based on Authentication success or failure
// Takes in a Failing HttpApp and a Succeed HttpApp which are called based on Authentication success or failure
// For each request tries to read the `X-ACCESS-TOKEN` header
// Validates JWT Claim
def authenticate[R, E](fail: HttpApp[R, E], success: JwtClaim => HttpApp[R, E]): HttpApp[R, E] =
Http.flatten {
Http.fromFunction[Request] {
def authenticate[R, E](fail: HttpApp[R, E], success: JwtClaim => HttpApp[R, E]): HttpApp[R, E] =
Http
.fromFunction[Request] {
_.getHeader("X-ACCESS-TOKEN")
.flatMap(header => jwtDecode(header.value.toString))
.fold[HttpApp[R, E]](fail)(success)
}
}
.flatMap(header => jwtDecode(header._2.toString))
.fold[HttpApp[R, E]](fail)(success)
}
.flatten

// Http app that requires a JWT claim
def user(claim: JwtClaim): UHttpApp = Http.collect {
case Method.GET -> !! / "user" / name / "greet" =>
Response.text(s"Welcome to the ZIO party! ${name}")
case Method.GET -> !! / "user" / "expiration" =>
Response.text(s"Expires in: ${claim.expiration.getOrElse(-1L)}")
def user(claim: JwtClaim): UHttpApp = Http.collect[Request] {
case Method.GET -> !! / "user" / name / "greet" => Response.text(s"Welcome to the ZIO party! ${name}")
case Method.GET -> !! / "user" / "expiration" => Response.text(s"Expires in: ${claim.expiration.getOrElse(-1L)}")
}

// App that let's the user login
// Login is successful only if the password is the reverse of the username
def login: UHttpApp = Http.collect { case Method.GET -> !! / "login" / username / password =>
def login: UHttpApp = Http.collect[Request] { case Method.GET -> !! / "login" / username / password =>
if (password.reverse == username) Response.text(jwtEncode(username))
else Response.fromHttpError(HttpError.Unauthorized("Invalid username of password\n"))
}

// Composing all the HttpApps together
val app: UHttpApp = login +++ authenticate(Http.forbidden("Not allowed!"), user)
val app: UHttpApp = login ++ authenticate(Http.forbidden("Not allowed!"), user)

// Run it like any simple app
val run =
Expand Down
13 changes: 6 additions & 7 deletions docs/website/docs/examples/advanced-examples/concrete-entity.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,21 @@ import zio._
* Example to build app on concrete entity
*/
object ConcreteEntity extends ZIOAppDefault {
//Request
// Request
case class CreateUser(name: String)

//Response
// Response
case class UserCreated(id: Long)

val user: Http[Any, Nothing, CreateUser, UserCreated] =
Http.collect[CreateUser] { case CreateUser(_) =>
UserCreated(2)
}

val app: Http[Any, Nothing, Request, Response[Any, Nothing]] = user
.contramap[Request](req => CreateUser(req.endpoint._2.toString))
//Http[Any, Nothing, Request, UserCreated]
.map(userCreated => Response.text(userCreated.id.toString))
//Http[Any, Nothing, Request, Response]
val app: HttpApp[Any, Nothing] =
user
.contramap[Request](req => CreateUser(req.path.toString)) // Http[Any, Nothing, Request, UserCreated]
.map(userCreated => Response.text(userCreated.id.toString)) // Http[Any, Nothing, Request, Response]

// Run it like any simple app
val run =
Expand Down
22 changes: 0 additions & 22 deletions docs/website/docs/examples/advanced-examples/cors.md

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,37 +10,38 @@ import scala.util.Try

object HelloWorldAdvanced extends ZIOAppDefault {
// Set a port
private val PORT = 8090
private val PORT = 0

private val fooBar: HttpApp[Any, Nothing] = Http.collect[Request] {
case Method.GET -> !! / "foo" => Response.text("bar")
case Method.GET -> !! / "bar" => Response.text("foo")
}

private val app = Http.collectM[Request] {
case Method.GET -> !! / "random" => random.nextString(10).map(Response.text)
private val app = Http.collectZIO[Request] {
case Method.GET -> !! / "random" => random.nextString(10).map(Response.text(_))
case Method.GET -> !! / "utc" => clock.currentDateTime.map(s => Response.text(s.toString))
}

private val server =
Server.port(PORT) ++ // Setup port
Server.paranoidLeakDetection ++ // Paranoid leak detection (affects performance)
Server.app(fooBar +++ app) // Setup the Http app
Server.app(fooBar ++ app) // Setup the Http app

override val run = {
// Configure thread count using CLI
val nThreads: Int = args.headOption.flatMap(x => Try(x.toInt).toOption).getOrElse(0)

// Create a new server
server.make
.use(_ =>
.use(start =>
// Waiting for the server to start
console.putStrLn(s"Server started on port $PORT")
console.putStrLn(s"Server started on port ${start.port}")

// Ensures the server doesn't die after printing
*> ZIO.never,
)
.provideCustomLayer(ServerChannelFactory.auto ++ EventLoopGroup.auto(nThreads))
}
}

```
48 changes: 0 additions & 48 deletions docs/website/docs/examples/advanced-examples/sticky-threads.md

This file was deleted.

27 changes: 0 additions & 27 deletions docs/website/docs/examples/advanced-examples/stream-file.md

This file was deleted.

22 changes: 8 additions & 14 deletions docs/website/docs/examples/advanced-examples/stream-response.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@
```scala
import zhttp.http._
import zhttp.service.Server
import zio._
import zio.stream.ZStream
import zio._

/**
* Example to encode content using a ZStream
*/
object StreamingResponse extends ZIOAppDefault {
// Create a message as a Chunk[Byte]
val message = Chunk.fromArray("Hello world !\r\n".getBytes(HTTP_CHARSET))
// Starting the server (for more advanced startup configuration checkout `HelloWorldAdvanced`)
override def run = Server.start(8090, app.silent)

// Create a message as a Chunk[Byte]
val message = Chunk.fromArray("Hello world !\r\n".getBytes(HTTP_CHARSET))
// Use `Http.collect` to match on route
val app: HttpApp[Any, Nothing] = Http.collect[Request] {

Expand All @@ -21,20 +23,12 @@ object StreamingResponse extends ZIOAppDefault {

// ZStream powered response
case Method.GET -> !! / "stream" =>
Response.http(
Response(
status = Status.OK,
headers = List(Header.contentLength(message.length.toLong)),
content = HttpData.fromStream(ZStream.fromChunk(message)),
// Encoding content using a ZStream
headers = Headers.contentLength(message.length.toLong),
data = HttpData.fromStream(ZStream.fromChunk(message)), // Encoding content using a ZStream
)

}
val run = {

// Starting the server (for more advanced startup
// configuration checkout `HelloWorldAdvanced`)
Server.start(8090, app.silent)
}
}

```
Loading

0 comments on commit 49a4e52

Please sign in to comment.