Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Improve http4s lambda #99

Merged
merged 6 commits into from
Dec 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jvmopts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-Xms1G
-Xmx4G
-XX:+UseG1GC
6 changes: 4 additions & 2 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ val fs2Version = "3.2.3"
val http4sVersion = "0.23.7"
val natchezVersion = "0.1.5"
val munitVersion = "0.7.29"
val munitCEVersion = "1.0.7"

lazy val root =
project
Expand Down Expand Up @@ -132,10 +133,11 @@ lazy val lambdaHttp4s = crossProject(JSPlatform, JVMPlatform)
.settings(
name := "feral-lambda-http4s",
libraryDependencies ++= Seq(
"org.http4s" %%% "http4s-server" % http4sVersion
"org.http4s" %%% "http4s-server" % http4sVersion,
"org.typelevel" %%% "munit-cats-effect-3" % "1.0.7" % Test
)
)
.dependsOn(lambda)
.dependsOn(lambda % "compile->compile;test->test")

lazy val lambdaCloudFormationCustomResource = crossProject(JSPlatform, JVMPlatform)
.crossType(CrossType.Pure)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,22 @@
*/

package feral.lambda
package http4s

import cats.effect.kernel.Concurrent
import cats.syntax.all._
import feral.lambda.events.ApiGatewayProxyEventV2
import feral.lambda.events.ApiGatewayProxyStructuredResultV2
import fs2.Stream
import org.http4s.Charset
import org.http4s.Header
import org.http4s.Headers
import org.http4s.HttpRoutes
import org.http4s.Method
import org.http4s.Request
import org.http4s.Response
import org.http4s.Uri
import org.http4s.headers.Cookie
import org.http4s.headers.`Set-Cookie`

object ApiGatewayProxyHandler {

Expand All @@ -38,8 +40,11 @@ object ApiGatewayProxyHandler {
for {
event <- env.event
method <- Method.fromString(event.requestContext.http.method).liftTo[F]
uri <- Uri.fromString(event.rawPath).liftTo[F]
headers = Headers(event.headers.toList)
uri <- Uri.fromString(event.rawPath + "?" + event.rawQueryString).liftTo[F]
cookies = Some(event.cookies)
.filter(_.nonEmpty)
.map(Cookie.name.toString -> _.mkString("; "))
headers = Headers(cookies.toList ::: event.headers.toList)
readBody =
if (event.isBase64Encoded)
fs2.text.base64.decode[F]
Expand All @@ -56,20 +61,39 @@ object ApiGatewayProxyHandler {
response.body.through(fs2.text.base64.encode)
else
response.body.through(fs2.text.utf8.decode)).compile.foldMonoid
} yield Some(
ApiGatewayProxyStructuredResultV2(
response.status.code,
response
.headers
.headers
.map {
case Header.Raw(name, value) =>
name.toString -> value
}
.toMap,
responseBody,
isBase64Encoded
} yield {
val headers = response.headers.headers.groupMap(_.name)(_.value)
Some(
ApiGatewayProxyStructuredResultV2(
response.status.code,
(headers - `Set-Cookie`.name).map {
case (name, values) =>
name.toString -> values.mkString(",")
},
responseBody,
isBase64Encoded,
headers.getOrElse(`Set-Cookie`.name, Nil)
)
)
)
}

private[http4s] def decodeEvent[F[_]: Concurrent](
event: ApiGatewayProxyEventV2): F[Request[F]] = for {
method <- Method.fromString(event.requestContext.http.method).liftTo[F]
uri <- Uri.fromString(event.rawPath + "?" + event.rawQueryString).liftTo[F]
cookies = Some(event.cookies)
.filter(_.nonEmpty)
.map(Cookie.name.toString -> _.mkString("; "))
headers = Headers(cookies.toList ::: event.headers.toList)
readBody =
if (event.isBase64Encoded)
fs2.text.base64.decode[F]
else
fs2.text.utf8.encode[F]
} yield Request(
method,
uri,
headers = headers,
body = Stream.fromOption[F](event.body).through(readBody)
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright 2021 Typelevel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package feral.lambda.http4s

import cats.effect.IO
import cats.syntax.all._
import feral.lambda.events.ApiGatewayProxyEventV2
import feral.lambda.events.ApiGatewayProxyEventV2Suite
import munit.CatsEffectSuite
import org.http4s.Method
import org.http4s.syntax.all._
import org.http4s.Headers

class ApiGatewayProxyHandlerSuite extends CatsEffectSuite {

import ApiGatewayProxyEventV2Suite._

test("decode event") {
for {
event <- event.as[ApiGatewayProxyEventV2].liftTo[IO]
request <- ApiGatewayProxyHandler.decodeEvent[IO](event)
_ <- IO(assertEquals(request.method, Method.GET))
_ <- IO(assertEquals(request.uri, uri"/default/nodejs-apig-function-1G3XMPLZXVXYI?"))
_ <- IO(assertEquals(request.headers, expectedHeaders))
_ <- request.body.compile.count.assertEquals(0L)
} yield ()
}

def expectedHeaders = Headers(
("cookie", "s_fid=7AABXMPL1AFD9BBF-0643XMPL09956DE2; regStatus=pre-register"),
("x-forwarded-port", "443"),
(
"accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"),
("sec-fetch-site", "cross-site"),
("x-amzn-trace-id", "Root=1-5e6722a7-cc56xmpl46db7ae02d4da47e"),
("sec-fetch-mode", "navigate"),
("sec-fetch-user", "?1"),
("accept-encoding", "gzip, deflate, br"),
("x-forwarded-for", "205.255.255.176"),
("upgrade-insecure-requests", "1"),
(
"user-agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"),
("accept-language", "en-US,en;q=0.9"),
("x-forwarded-proto", "https"),
("host", "r3pmxmplak.execute-api.us-east-2.amazonaws.com"),
("content-length", "0"),
("sec-fetch-dest", "document")
)

}
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,21 @@ object RequestContext {
Decoder.forProduct1("http")(RequestContext.apply)
}

// TODO Just the bare minimum for proof-of-concept
final case class ApiGatewayProxyEventV2(
rawPath: String,
rawQueryString: String,
cookies: List[String],
headers: Map[String, String],
requestContext: RequestContext,
body: Option[String],
isBase64Encoded: Boolean
)

object ApiGatewayProxyEventV2 {
implicit def decoder: Decoder[ApiGatewayProxyEventV2] = Decoder.forProduct6(
implicit def decoder: Decoder[ApiGatewayProxyEventV2] = Decoder.forProduct7(
"rawPath",
"rawQueryString",
"cookies",
"headers",
"requestContext",
"body",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,16 @@ final case class ApiGatewayProxyStructuredResultV2(
statusCode: Int,
headers: Map[String, String],
body: String,
isBase64Encoded: Boolean
isBase64Encoded: Boolean,
cookies: List[String]
) extends ApiGatewayProxyResultV2

object ApiGatewayProxyStructuredResultV2 {
implicit def encoder: Encoder[ApiGatewayProxyStructuredResultV2] = Encoder.forProduct4(
implicit def encoder: Encoder[ApiGatewayProxyStructuredResultV2] = Encoder.forProduct5(
"statusCode",
"headers",
"body",
"isBase64Encoded"
)(r => (r.statusCode, r.headers, r.body, r.isBase64Encoded))
"isBase64Encoded",
"cookies"
)(r => (r.statusCode, r.headers, r.body, r.isBase64Encoded, r.cookies))
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,16 @@ import munit.FunSuite

class ApiGatewayProxyEventV2Suite extends FunSuite {

import ApiGatewayProxyEventV2Suite._

test("decoder") {
event.as[ApiGatewayProxyEventV2].toTry.get
}

}

object ApiGatewayProxyEventV2Suite {

def event = json"""
{
"version": "2.0",
Expand Down