forked from fun-stack/local-env
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevServer.scala
More file actions
234 lines (207 loc) · 9.4 KB
/
DevServer.scala
File metadata and controls
234 lines (207 loc) · 9.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package funstack.local.http
import cats.effect.IO
import cats.effect.std.Semaphore
import cats.effect.unsafe.implicits.{global => unsafeIORuntimeGlobal}
import cats.implicits._
import funstack.local.helper.{AccessToken, Base64Codec}
import funstack.local.ws.WebsocketConnections
import net.exoego.facade.aws_lambda
import net.exoego.facade.aws_lambda.{APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2}
import org.scalajs.dom.Fetch
import typings.node.httpMod.{createServer, IncomingMessage, Server, ServerResponse}
import typings.node.{Buffer => JsBuffer}
import java.net.URI
import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.util.{Failure, Success}
object DevServer {
type FunctionType =
js.Function2[APIGatewayProxyEventV2, aws_lambda.Context, js.Promise[APIGatewayProxyStructuredResultV2]]
var lambdaHandler: Option[FunctionType] = None
var lambdaHandlerUnderscore: Option[FunctionType] = None
val semaphore = Semaphore[IO](1).unsafeToFuture()
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
def start(port: Int): Server = {
val requestListener = { (req: IncomingMessage, res: ServerResponse) =>
val body = new StringBuilder
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Request-Method", "*");
res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE, HEAD, TRACE, CONNECT");
res.setHeader("Access-Control-Allow-Headers", "*");
req.on(
"data",
chunk => {
val buffer = chunk.asInstanceOf[JsBuffer];
body ++= buffer.toString()
()
},
)
req.on(
"end",
_ =>
if (req.method.exists(_ == "OPTIONS")) { // catch preflight requests
res.end()
}
else if (req.url.toOption.exists(_.startsWith("/__/"))) {
req.url.toOption match {
case Some("/__/send/event") =>
try {
val bodyStr = body.result()
val request = js.JSON.parse(bodyStr)
val subscribeUrl = request.SubscribeURL.asInstanceOf[js.UndefOr[String]].toOption
val result = subscribeUrl match {
case Some(url) =>
Fetch.fetch(url).toFuture.flatMap { response =>
if (response.ok) Future.successful(())
else Future.failed(new Exception(s"Unexpected status code from subscribe url: ${response.status}"))
}
case None =>
val subscriptionKey = request.MessageAttributes.subscription_key.Value.asInstanceOf[String]
val message = request.Message.asInstanceOf[String]
WebsocketConnections.sendSubscription(subscriptionKey, message)
Future.successful(())
}
result.onComplete {
case Success(()) =>
res.statusCode = 200
res.end()
case Failure(error) =>
println(s"Failed to handle send event: ${error.getMessage}")
res.statusCode = 500
res.end()
}
}
catch {
case error: Throwable =>
res.statusCode = 500 // internal server error
println(s"Http> Error sending subscription: ${error}")
res.end()
}
case _ =>
res.statusCode = 404 // not found
res.end()
}
}
else {
val bodyStr = body.result()
val (gatewayEvent, lambdaContext) = transform(s"http://localhost:$port", req, bodyStr)
val handler = req.url.toOption match {
case Some(url) if url.startsWith("/_/") => lambdaHandlerUnderscore
case _ => lambdaHandler
}
handler match {
case Some(handler) =>
for {
semaphore <- semaphore
_ <- semaphore.acquire.unsafeToFuture()
result <- handler(gatewayEvent, lambdaContext).toFuture.attempt
_ <- semaphore.release.unsafeToFuture()
} result match {
case Right(result) =>
result.headers.foreach { headers =>
headers.foreach { case (key, value) =>
// ignore content-length header. the content-length we
// get here can be wrong when it comes from, e.g.,
// tapir-based lambda functions and using umlauts in
// the payload. The node-http-server will add a correct
// one anyhow if it is not added.
if (key != "Content-Length") {
res.setHeader(key, value.toString)
}
}
}
result.statusCode.foreach(res.statusCode = _)
val body = result.body.map { body =>
if (result.isBase64Encoded.getOrElse(false)) Base64Codec.decode(body) else body
}
res.end(body)
case Left(error) =>
res.statusCode = 500 // internal server error
print("Http> ")
error.printStackTrace()
res.end()
}
case None =>
res.statusCode = 404 // not found
res.end()
}
()
},
)
()
}
val server = createServer(requestListener)
server.listen(port.toDouble)
server
}
def transform(baseUrl: String, req: IncomingMessage, body: String): (APIGatewayProxyEventV2, aws_lambda.Context) = {
val url = new URI(s"$baseUrl${req.url.getOrElse("")}")
val queryParameters = Option(url.getQuery)
.fold(Map.empty[String, String])(
_.split("&|=")
.grouped(2)
.map(a => a(0) -> a(1))
.toMap,
)
// https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html#apigateway-example-event
// example json: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/nodejs-apig/event-v2.json
// more examples: https://github.com/search?l=JSON&q=pathparameters+requestContext+isbase64encoded&type=Code
val routeKey = "ANY /nodejs-apig-function-1G3XMPLZXVXYI"
val now = new js.Date
val host = Option(url.getHost()).getOrElse("") // TODO: includes port number, but it shouldn't?
val path = s"/latest${url.getPath()}" // TODO: why latest?
val authHeader = req.headers.asInstanceOf[js.Dictionary[String]].get("authorization")
val accessToken = authHeader.map(_.split(" ")).collect { case Array("Bearer", token) => token }
val authorizerDict = AccessToken.toAuthorizer(accessToken)
val randomRequestId = util.Random.alphanumeric.take(20).mkString
val gateWayEvent = APIGatewayProxyEventV2(
version = "2.0",
routeKey = routeKey,
rawPath = path,
rawQueryString = Option(url.getQuery()).getOrElse(""),
cookies = req.headers.cookie.fold(js.Array[String]())(_.split(";").toJSArray),
// TODO: multi valued headers
// TODO: include cookies in headers?
headers = req.headers.asInstanceOf[js.Dictionary[String]],
requestContext = APIGatewayProxyEventV2.RequestContext(
accountId = "123456789012",
apiId = "r3pmxmplak",
authorizer = js.Dictionary("lambda" -> authorizerDict),
domainName = host,
domainPrefix = host.split(".").headOption.getOrElse(url.getHost()),
http = APIGatewayProxyEventV2.RequestContext.Http(
method = req.method.getOrElse(""),
path = path,
protocol = "HTTP/1.1",
sourceIp = "127.0.0.1",
userAgent = req.headers.`user-agent`.getOrElse(""),
), // RequestContext.Http
requestId = randomRequestId,
routeKey = routeKey,
stage = "$default",
time = now.toISOString(), // TODO: ISO 8601 maybe not correct. Examples have "21/Nov/2020:20:39:08 +0000" which is a different format,
timeEpoch = now.getUTCMilliseconds(),
),
isBase64Encoded = false,
body = body,
pathParameters = js.undefined, // TODO: js.Dictionary for /{id}/ in URL
queryStringParameters = queryParameters.toJSDictionary, // js.Dictionary[String](),
)
val lambdaContext = js.Dynamic
.literal(
callbackWaitsForEmptyEventLoop = true,
functionName = "function",
functionVersion = "$LATEST",
invokedFunctionArn = "arn:aws:lambda:ap-southeast-2:[AWS_ACCOUNT_ID]:function:restapi",
memoryLimitInMB = "128",
awsRequestId = "1d9ccf1c-0f09-427e-b2f8-ffc961d25904",
logGroupName = "",
logStreamName = s"/aws/lambda/function",
// var identity: js.UndefOr[aws_lambda.CognitoIdentity] = js.undefined
// var clientContext: js.UndefOr[aws_lambda.ClientContext] = js.undefined
)
.asInstanceOf[aws_lambda.Context]
(gateWayEvent, lambdaContext)
}
}