Skip to content

Commit

Permalink
Merge branch 'main' of github.com:dream11/zio-http into docs-headers
Browse files Browse the repository at this point in the history
  • Loading branch information
gciuloaica committed Jan 21, 2022
2 parents d39c2e3 + 3b9ea3a commit c4249bc
Show file tree
Hide file tree
Showing 66 changed files with 1,662 additions and 1,052 deletions.
28 changes: 14 additions & 14 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 All @@ -259,15 +259,15 @@ jobs:
run: |
cp ./zio-http/example/src/main/scala/example/PlainTextBenchmarkServer.scala ./FrameworkBenchMarks/frameworks/Scala/zio-http/src/main/scala/Main.scala
cd ./FrameworkBenchMarks
echo ${{github.event.pull_request.head.sha}}
sed -i "s/---COMMIT_SHA---/${{github.event.pull_request.head.sha}}/g" frameworks/Scala/zio-http/build.sbt
sed -i "s/---COMMIT_SHA---/${{github.event.pull_request.head.repo.owner.login}}\/zio-http.git#${{github.event.pull_request.head.sha}}/g" frameworks/Scala/zio-http/build.sbt
./tfb --test zio-http | tee result
RESULT_REQUEST=$(echo $(grep -B 1 -A 17 "Concurrency: 256 for plaintext" result) | grep -oiE "requests/sec: [0-9]+.[0-9]+")
RESULT_CONCURRENCY=$(echo $(grep -B 1 -A 17 "Concurrency: 256 for plaintext" result) | grep -oiE "concurrency: [0-9]+")
echo ::set-output name=request_result::$(echo $RESULT_REQUEST)
echo ::set-output name=concurrency_result::$(echo $RESULT_CONCURRENCY)
- uses: peter-evans/commit-comment@v1
- if: ${{github.event.pull_request.head.repo.full_name == 'dream11/zio-http'}}
uses: peter-evans/commit-comment@v1
with:
sha: ${{github.event.pull_request.head.sha}}
body: |
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 App {
}

// 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
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
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 App {
//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
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
Expand Down
26 changes: 14 additions & 12 deletions docs/website/docs/examples/advanced-examples/cors.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,19 @@ import zhttp.service.Server
import zio._

object HelloWorldWithCORS extends App {
// Create HTTP route with CORS enabled
val app: HttpApp[Any, Nothing] = CORS(
Http.collect[Request] {
case Method.GET -> !! / "text" => Response.text("Hello World!")
case Method.GET -> !! / "json" => Response.jsonString("""{"greetings": "Hello World!"}""")
},
config = CORSConfig(anyOrigin = true),
)

// Run it like any simple app
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
Server.start(8090, app.silent).exitCode
// Create CORS configuration
val config: CORSConfig =
CORSConfig(allowedOrigins = _ == "dev", allowedMethods = Some(Set(Method.PUT, Method.DELETE)))

// Create HTTP route with CORS enabled
val app: HttpApp[Any, Nothing] =
Http.collect[Request] {
case Method.GET -> !! / "text" => Response.text("Hello World!")
case Method.GET -> !! / "json" => Response.json("""{"greetings": "Hello World!"}""")
} @@ cors(config)

// Run it like any simple app
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
Server.start(8090, app.silent).exitCode
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,32 @@ import scala.util.Try

object HelloWorldAdvanced extends App {
// 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 def run(args: List[String]): URIO[zio.ZEnv, ExitCode] = {
// 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,
Expand All @@ -44,4 +44,5 @@ object HelloWorldAdvanced extends App {
.exitCode
}
}

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

This file was deleted.

24 changes: 15 additions & 9 deletions docs/website/docs/examples/advanced-examples/stream-file.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
# Streaming File
```scala
import zhttp.http._
import zhttp.service._
import zhttp.service.Server
import zio.stream.ZStream
import zio._
import zio.stream._

import java.io.File
import java.nio.file.Paths

object FileStreaming extends App {
// Read the file as ZStream
val content = HttpData.fromStream {
ZStream.fromFile(Paths.get("README.md"))
}

// Create HTTP route
val app = Http.collect[Request] {
case Method.GET -> !! / "health" => Response.ok
case Method.GET -> !! / "file" => Response.http(content = content)
val app = Http.collectHttp[Request] {
case Method.GET -> !! / "health" => Http.ok

// Read the file as ZStream
// Uses the blocking version of ZStream.fromFile
case Method.GET -> !! / "blocking" => Http.fromStream(ZStream.fromFile(Paths.get("README.md")))

// Uses netty's capability to write file content to the Channel
// Content-type response headers are automatically identified and added
// Does not use Chunked transfer encoding
case Method.GET -> !! / "video" => Http.fromFile(new File("src/main/resources/TestVideoFile.mp4"))
case Method.GET -> !! / "text" => Http.fromFile(new File("src/main/resources/TestFile.txt"))
}

// Run it like any simple app
Expand Down
Loading

0 comments on commit c4249bc

Please sign in to comment.