Skip to content

Commit

Permalink
Backmerge main 14 jan 2021 (#831)
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

* 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>
  • Loading branch information
5 people authored and amitksingh1490 committed Feb 9, 2022
1 parent 7660b9c commit bbcffb6
Show file tree
Hide file tree
Showing 61 changed files with 115 additions and 408 deletions.
4 changes: 4 additions & 0 deletions docs/website/docs/client/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Client",
"position": 4
}
1 change: 1 addition & 0 deletions docs/website/docs/client/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "DSL",
"position": 3
}
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/cookies/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Cookies",
"position": 6
}
1 change: 1 addition & 0 deletions docs/website/docs/dsl/cookies/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/headers/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Headers",
"position": 5
}
1 change: 1 addition & 0 deletions docs/website/docs/dsl/headers/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/http-data/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "HttpData",
"position": 4
}
1 change: 1 addition & 0 deletions docs/website/docs/dsl/http-data/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/http-endpoint/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Endpoint",
"position": 7
}
1 change: 1 addition & 0 deletions docs/website/docs/dsl/http-endpoint/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/http/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Http",
"position": 1
}
1 change: 1 addition & 0 deletions docs/website/docs/dsl/http/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/middleware/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Middleware",
"position": 9
}
1 change: 1 addition & 0 deletions docs/website/docs/dsl/middleware/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/request/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Request",
"position": 2
}
1 change: 1 addition & 0 deletions docs/website/docs/dsl/request/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/response/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Response",
"position": 3
}
1 change: 1 addition & 0 deletions docs/website/docs/dsl/response/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/server/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Server",
"position": 8
}
3 changes: 3 additions & 0 deletions docs/website/docs/dsl/server/config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Config

Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/dsl/socket/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Socket",
"position": 10
}
1 change: 1 addition & 0 deletions docs/website/docs/dsl/socket/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/examples/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Examples",
"position": 7
}
File renamed without changes.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
4 changes: 4 additions & 0 deletions docs/website/docs/integrations/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Integrations",
"position": 6
}
1 change: 1 addition & 0 deletions docs/website/docs/integrations/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
4 changes: 4 additions & 0 deletions docs/website/docs/testing/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Testing",
"position": 5
}
1 change: 1 addition & 0 deletions docs/website/docs/testing/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Work in progress
Original file line number Diff line number Diff line change
@@ -1,4 +0,0 @@
{
"label": "Advanced Examples",
"position": 2
}
Original file line number Diff line number Diff line change
@@ -1,63 +0,0 @@
# Authentication

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

import java.time.Clock

object Authentication extends ZIOAppDefault {
// Secret Authentication key
val SECRET_KEY = "secretKey"

implicit val clock: Clock = Clock.systemUTC

// Helper to encode the JWT token
def jwtEncode(username: String): String = {
val json = s"""{"user": "${username}"}"""
val claim = JwtClaim { json }.issuedNow.expiresIn(60)
Jwt.encode(claim, SECRET_KEY, JwtAlgorithm.HS512)
}

// Helper to decode the JWT token
def jwtDecode(token: String): Option[JwtClaim] = {
Jwt.decode(token, SECRET_KEY, Seq(JwtAlgorithm.HS512)).toOption
}

// Authentication middleware
// 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
.fromFunction[Request] {
_.getHeader("X-ACCESS-TOKEN")
.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[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[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)

// Run it like any simple app
val run =
Server.start(8090, app)
}

```
Original file line number Diff line number Diff line change
@@ -1,33 +0,0 @@
# Concrete Enity
```scala
import zhttp.http._
import zhttp.service.Server
import zio._

/**
* Example to build app on concrete entity
*/
object ConcreteEntity extends ZIOAppDefault {
//Request
case class CreateUser(name: String)

//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]

// Run it like any simple app
val run =
Server.start(8090, app)
}

```
Original file line number Diff line number Diff line change
@@ -1,47 +0,0 @@
# Advanced Server

```scala
import zhttp.http._
import zhttp.service._
import zhttp.service.server.ServerChannelFactory
import zio._

import scala.util.Try

object HelloWorldAdvanced extends ZIOAppDefault {
// Set a port
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.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

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(start =>
// Waiting for the server to start
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))
}
}

```
Original file line number Diff line number Diff line change
@@ -1,41 +0,0 @@
# Streaming Response

```scala
import zhttp.http._
import zhttp.service.Server
import zio.stream.ZStream
import zio._

/**
* Example to encode content using a ZStream
*/
object StreamingResponse extends ZIOAppDefault {
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] = {

// Starting the server (for more advanced startup configuration checkout `HelloWorldAdvanced`)
Server.start(8090, app.silent).exitCode
}
// 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] {

// Simple (non-stream) based route
case Method.GET -> !! / "health" => Response.ok

// ZStream powered response
case Method.GET -> !! / "stream" =>
Response(
status = Status.OK,
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)
}
}
```
Original file line number Diff line number Diff line change
@@ -1,60 +0,0 @@
# Web Socket Server
```scala
import zhttp.http._
import zhttp.service.Server
import zhttp.socket._
import zio._
import zio.duration._
import zio.stream.ZStream

object WebSocketAdvanced extends ZIOAppDefault {
// Message Handlers
private val open = Socket.succeed(WebSocketFrame.text("Greetings!"))

private val echo = Socket.collect[WebSocketFrame] { case WebSocketFrame.Text(text) =>
ZStream.repeat(WebSocketFrame.text(s"Received: $text")).schedule(Schedule.spaced(1 second)).take(3)
}

private val fooBar = Socket.collect[WebSocketFrame] {
case WebSocketFrame.Text("FOO") => ZStream.succeed(WebSocketFrame.text("BAR"))
case WebSocketFrame.Text("BAR") => ZStream.succeed(WebSocketFrame.text("FOO"))
}

// Setup protocol settings
private val protocol = SocketProtocol.subProtocol("json")

// Setup decoder settings
private val decoder = SocketDecoder.allowExtensions

// Combine all channel handlers together
private val socketApp = {

SocketApp(echo merge fooBar) // Called after each message being received on the channel

// Called after the request is successfully upgraded to websocket
.onOpen(open)

// Called after the connection is closed
.onClose(_ => console.putStrLn("Closed!").ignore)

// Called whenever there is an error on the socket channel
.onError(_ => console.putStrLn("Error!").ignore)

// Setup websocket decoder config
.withDecoder(decoder)

// Setup websocket protocol config
.withProtocol(protocol)
}

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

val run =
Server.start(8090, app)
}

```
Original file line number Diff line number Diff line change
@@ -1,4 +0,0 @@
{
"label": "Basic Examples",
"position": 1
}
Loading

0 comments on commit bbcffb6

Please sign in to comment.