-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLambdaRuntime.scala
598 lines (511 loc) · 20.6 KB
/
LambdaRuntime.scala
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
package org.encalmo.lambda
import com.amazonaws.services.lambda.runtime.logging.LogLevel
import org.encalmo.lambda.AnsiColor.*
import java.io.PrintStream
import java.net.URI
import java.net.http.*
import java.net.http.HttpRequest.BodyPublishers
import java.net.http.HttpResponse.BodyHandlers
import java.time.ZoneId
import java.time.ZonedDateTime
import java.util.UUID
import java.util.concurrent.Semaphore
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import java.util.function.BinaryOperator
import scala.io.AnsiColor
import scala.jdk.CollectionConverters.*
import scala.jdk.OptionConverters.*
import scala.reflect.ClassTag
import scala.util.control.NonFatal
import java.io.InputStream
import java.io.OutputStream
import java.nio.charset.StandardCharsets
/** Simplified lambda runtime when no application context is required. */
trait SimpleLambdaRuntime extends LambdaRuntime {
type ApplicationContext = Unit
override def initialize(using LambdaEnvironment): Unit = ()
}
/** Custom lambda runtime base. (https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html)
*/
trait LambdaRuntime extends EventHandler, EventHandlerTag, com.amazonaws.services.lambda.runtime.RequestStreamHandler {
import LambdaEnvironment.Logger.*
/** Handle of the current lambda instance. */
private val instance: AtomicReference[Option[Instance]] =
new AtomicReference(None)
/** Handle of the current test environment instance. */
private val testLambdaEnvironment: AtomicReference[Option[LambdaEnvironment]] =
new AtomicReference(None)
/** Handle of the current test application context. */
private val testApplicationContext: AtomicReference[Option[ApplicationContext]] =
new AtomicReference(None)
val ZoneUTC = ZoneId.of("UTC")
private lazy val httpClient = HttpClient
.newBuilder()
.connectTimeout(java.time.Duration.ofSeconds(60))
.build()
/** Per-invocation debug mode reset each time to global isDebugMode */
private var lambdaInvocationDebugMode: Boolean = true
/** Switch off debug mode for the current lambda invocation. */
def switchOffDebugMode() = {
lambdaInvocationDebugMode = false
}
/** Lambda runtime instance interface. */
trait Instance {
val runtimeId: String
lazy val lambdaEnvironment: LambdaEnvironment
lazy val applicationContext: ApplicationContext
/** Start receiving events. */
def start(): Instance
/** Wait for lambda runtime to finish job (potentially never). */
def waitUntilInterrupted(): Instance
/** Temporaily stop receiving events. */
def pause(): Instance
/** Stop receiving events and shutdow the runtime. */
def shutdown(): Instance
}
/** Starts lambda runtime and blocks thread until finished. */
final inline def run(): Unit = {
initializeLambdaRuntime().start().waitUntilInterrupted()
}
/** Configure something with lambda environment provided. */
private def configure[T](f: LambdaEnvironment ?=> T): T =
instance.getAcquire() match {
case Some(i) =>
trace("Configuring lambda ...")(using i.lambdaEnvironment)
f(using i.lambdaEnvironment)
case None =>
testLambdaEnvironment.getAcquire() match {
case Some(le) =>
trace("Configuring lambda using test environment ...")(using le)
f(using le)
case None =>
throw new IllegalStateException(
"Lambda instance is not initialized yet at this point. Use `lazy val config = configure(...)` declaration."
)
}
}
/** Creates lambda runtime instance. */
final def initializeLambdaRuntime(
variablesOverrides: Map[String, String] = Map.empty
): Instance = {
instance.getAcquire().match {
case Some(i) => i // returns an existing instance if exists
case None =>
try {
// Create and initialize a new instance of the lambda runtime
val i = new Instance {
val runtimeId = UUID.randomUUID().toString().take(6)
given lambdaEnvironment: LambdaEnvironment =
new LambdaEnvironment(variablesOverrides)
lambdaEnvironment.setCustomOut()
val logPrefix =
if (lambdaEnvironment.shouldLogStructuredJson)
then s"""{"log":"INIT","lambda":"${lambdaEnvironment.getFunctionName()}","""
else s"[${lambdaEnvironment.getFunctionName()}] LAMBDA INIT "
val logSuffix =
if (lambdaEnvironment.shouldLogStructuredJson)
then s""","lambdaVersion":"${lambdaEnvironment.getFunctionVersion()}"}"""
else ""
lazy val applicationContext: ApplicationContext =
LambdaRuntime
.withLogCapture(
lambdaEnvironment,
logPrefix,
logSuffix,
true,
configure(initialize)
)
private val semaphore = new Semaphore(1)
semaphore.acquire() // pausing execution until started
private val active = new AtomicBoolean(true)
private val counter = new AtomicInteger()
private val mainLoop = new Runnable {
def run =
while (active.get()) {
val id = counter.incrementAndGet()
try {
semaphore.acquire()
lambdaInvocationDebugMode = lambdaEnvironment.isDebugMode
invokeHandleRequest(id)(using lambdaEnvironment, applicationContext)
trace(s"[$id] Done.")
} catch {
case e: InterruptedException =>
case e: HttpConnectTimeoutException =>
error(s"[$id] $e")
shutdown()
case e =>
if (active.get)
then
try {
reportError(LambdaRuntime.createErrorMessage(e), lambdaEnvironment.initErrorUrl)
} catch {
case e => error(LambdaRuntime.createErrorMessage(e))
}
} finally {
lambdaInvocationDebugMode = lambdaEnvironment.isDebugMode
Runtime.getRuntime().gc()
semaphore.release()
}
}
}
private val loopThread = Thread.ofVirtual
.name(
s"lambda-runtime-${lambdaEnvironment.getFunctionName()}-$runtimeId"
)
.start(mainLoop)
final override def start(): Instance = {
semaphore.release()
trace(s"[$runtimeId] LambdaRuntime started.")
this
}
final override def waitUntilInterrupted(): Instance = {
trace(s"Waiting ...")
try (loopThread.join())
catch {
case e: InterruptedException =>
trace(s"[$runtimeId] LambdaRuntime interrupted.")
instance.setRelease(None)
}
this
}
final override def pause(): Instance = {
semaphore.acquire()
trace(s"[$runtimeId] LambdaRuntime paused.")
this
}
final override def shutdown(): Instance = {
trace(s"[$runtimeId] LambdaRuntime shutdowns.")
active.set(false)
lambdaEnvironment.resetOut()
Thread.sleep(100)
loopThread.interrupt()
this
}
trace(s"[$runtimeId] LambdaRuntime initialized.")
}
instance.setRelease(Some(i))
i
} catch {
// Lambda runtime initilization has failed, report error to the AWS host
case NonFatal(e) =>
given le: LambdaEnvironment = new LambdaEnvironment()
try {
reportError(LambdaRuntime.createErrorMessage(e), le.initErrorUrl)
} catch {
case e => error(LambdaRuntime.createErrorMessage(e))
}
le.resetOut()
throw e
}
}
}
/* ----------------------------------------------------------
* THE ACTUAL LAMBDA BUSINESS METHOD INVOCATION HAPPENS HERE.
* ---------------------------------------------------------- */
private final def invokeHandleRequest(
id: Int
)(using lambdaEnvironment: LambdaEnvironment, applicationContext: ApplicationContext): Unit = {
lambdaEnvironment.setCustomOut()
val functionName = lambdaEnvironment.getFunctionName()
val functionVersion = lambdaEnvironment.getFunctionVersion()
val uri = lambdaEnvironment.nextEventUrl
trace(s"[$id] Requesting next event from $uri")
val event = httpClient
.send(lambdaEnvironment.nextEventRequest, BodyHandlers.ofString())
val requestId =
event.headers
.firstValue("Lambda-Runtime-Aws-Request-Id")
.toScala
.getOrElse(
throw new Exception(
s"[$id] Missing [Lambda-Runtime-Aws-Request-Id] header. Skipping lambda execution."
)
)
val tagOpt: Option[String] = getEventHandlerTag(event.body)
val tag: String = tagOpt.map(t => s" [$t]").getOrElse("")
val structuredLogIntro =
s""""lambda":"${functionName}"${tagOpt
.map(tag => s""","handler":"$tag"""")
.getOrElse("")},"id":$id"""
val structuredLogEnd =
s""""lambdaVersion":"${functionVersion}","lambdaRequestId":"$requestId""""
val isJsonRequest = {
val body = event.body.trim()
(body.startsWith("{") && body.endsWith("}")) || (body.startsWith("[") && body.endsWith("]"))
}
val t0 = System.currentTimeMillis()
debug(
if (lambdaEnvironment.shouldLogStructuredJson)
then
s"""{"log":"REQUEST",$structuredLogIntro,"request":${
if (isJsonRequest) then event.body else s"\"${event.body.replace("\"", "\\\"")}\""
},$structuredLogEnd,"timestamp":"${t0}","datetime":"${ZonedDateTime
.now(ZoneUTC)
.toString()}","maxMemory":${Runtime
.getRuntime()
.maxMemory()},"totalMemory":${Runtime
.getRuntime()
.totalMemory()},"freeMemory":${Runtime.getRuntime().freeMemory()}}"""
else {
s"[$id]$tag ${REQUEST}LAMBDA REQUEST ${AnsiColor.BOLD}${event.body}"
}
)
try {
val lambdaContext = LambdaContext(
requestId,
event.headers
.map()
.asScala
.map((key, values) => (key, values.getFirst()))
.toMap,
lambdaEnvironment,
switchOffDebugMode
)
event.headers
.firstValue("Lambda-Runtime-Aws-Request-Id")
.toScala
.foreach(xamazTraceId => System.setProperty("com.amazonaws.xray.traceHeader", xamazTraceId))
val input = event.body
val logPrefix =
if (lambdaEnvironment.shouldLogStructuredJson)
then s"""{"log":"LOGS",$structuredLogIntro,"""
else s"[${lambdaEnvironment.getFunctionName()}] [$id]$tag LAMBDA LOGS {"
val logSuffix =
if (lambdaEnvironment.shouldLogStructuredJson)
then s""",$structuredLogEnd}"""
else "}"
val result: Either[String, String] =
LambdaRuntime
.withLogCapture(
lambdaEnvironment,
logPrefix,
logSuffix,
lambdaInvocationDebugMode,
try {
Right(handleRequest(input)(using lambdaContext, applicationContext).trim())
} catch {
case NonFatal(e) =>
error(e.toString())
val stackTrace = e
.getStackTrace()
.filterNot { s =>
val n = s.getClassName()
n.startsWith("scala") || n.startsWith("java")
}
if (stackTrace.size > 30) then
stackTrace.take(15).foreach(println)
println("...")
stackTrace.takeRight(15).foreach(println)
else stackTrace.foreach(println)
Left(LambdaRuntime.createErrorMessage(e))
}
)
val t1 = System.currentTimeMillis()
val output = result.fold(identity, identity)
val isJsonReponse =
(output.startsWith("{") && output.endsWith("}"))
|| (output.startsWith("[") && output.endsWith("]"))
// https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html
val awsEmbededMetric =
s""""_aws":{"Timestamp":$t1,"CloudWatchMetrics":[{"Namespace":"lambda-${functionName}-metrics","Dimensions":[${
if (tagOpt.isDefined) then "[\"handler\",\"lambdaVersion\"]" else "[\"lambdaVersion\"]"
}],"Metrics":[${LambdaRuntime.durationMetric}]}]}"""
debug(
if (lambdaEnvironment.shouldLogStructuredJson)
then
s"""{"log":"RESPONSE",$structuredLogIntro,${
if (lambdaEnvironment.shouldLogResponseIncludeRequest)
then
s""""request":${if (isJsonRequest) then event.body else s"\"${event.body.replace("\"", "\\\"")}\""},"""
else ""
}${
if (lambdaInvocationDebugMode) then
s""""response":${if (isJsonReponse) then output else s"\"${output.replace("\"", "\\\"")}\""},"""
else ""
}$structuredLogEnd,"timestamp":"${t1}","datetime":"${ZonedDateTime
.now(ZoneUTC)
.toString()}","duration":${t1 - t0},"maxMemory":${Runtime
.getRuntime()
.maxMemory()},"totalMemory":${Runtime
.getRuntime()
.totalMemory()},"freeMemory":${Runtime.getRuntime().freeMemory()},$awsEmbededMetric}"""
else {
s"[$id]$tag ${RESPONSE}LAMBDA RESPONSE [${t1 - t0}ms] ${AnsiColor.BOLD}$output"
}
)
val responseResult =
if (result.isLeft)
then reportError(output, lambdaEnvironment.errorUrl(requestId))
else
httpClient
.send(lambdaEnvironment.responseRequest(requestId, output), BodyHandlers.ofString())
val success = responseResult.statusCode() >= 200 && responseResult.statusCode() < 300
if (!success) {
throw new Exception(
s"[$id]$tag Response rejected with status code ${responseResult.statusCode()}: ${responseResult.body}"
)
}
} catch {
case NonFatal(e) =>
val errorMessage = LambdaRuntime.createErrorMessage(e)
error(errorMessage)
try {
reportError(errorMessage, lambdaEnvironment.errorUrl(requestId))
} catch {
case e => error(LambdaRuntime.createErrorMessage(e))
}
}
}
// Lambda invocation for unit test purposes, does not interact with the AWS host, returns result directly. */
final def test(
input: String,
overrides: Map[String, String] = Map.empty
): String =
try {
val requestId = UUID.randomUUID().toString()
val tag: String = getEventHandlerTag(input).map(t => s"[$t]").getOrElse("")
given lambdaEnvironment: LambdaEnvironment =
new LambdaEnvironment(
Map(
"AWS_LAMBDA_RUNTIME_API" -> "none",
"AWS_LAMBDA_FUNCTION_NAME" -> "test",
"AWS_LAMBDA_FUNCTION_MEMORY_SIZE" -> "128",
"AWS_LAMBDA_FUNCTION_VERSION" -> "0",
"AWS_LAMBDA_LOG_GROUP_NAME" -> "none",
"AWS_LAMBDA_LOG_STREAM_NAME" -> "none",
"LAMBDA_RUNTIME_DEBUG_MODE" -> "ON",
"LAMBDA_RUNTIME_TRACE_MODE" -> "ON"
)
++ overrides
)
testLambdaEnvironment.setRelease(Some(lambdaEnvironment))
val applicationContext: ApplicationContext =
testApplicationContext
.accumulateAndGet(
None,
new BinaryOperator[Option[ApplicationContext]] {
override def apply(
existing: Option[ApplicationContext],
dummy: Option[ApplicationContext]
): Option[ApplicationContext] =
existing.orElse {
Some(configure(initialize))
}
}
)
.get
debug(
s"$tag ${REQUEST}LAMBDA REQUEST ${AnsiColor.BOLD}${input}"
)
val lambdaContext =
LambdaContext(requestId, Map.empty, lambdaEnvironment, switchOffDebugMode)
val output = handleRequest(input)(using lambdaContext, applicationContext)
debug(
s"$tag ${RESPONSE}LAMBDA RESPONSE ${AnsiColor.BOLD}$output"
)
output
} catch {
case NonFatal(e) =>
LambdaRuntime.createErrorMessage(e)
}
/** Report error back to the AWS lambda host. */
final inline def reportError(
errorMessage: String,
errorUrl: URI
)(using lambdaEnvironment: LambdaEnvironment): HttpResponse[String] =
httpClient
.send(
HttpRequest
.newBuilder(errorUrl)
.POST(BodyPublishers.ofString(errorMessage))
.setHeader("Lambda-Runtime-Function-Error-Type", "Runtime.UnknownReason")
.build(),
BodyHandlers.ofString()
)
private lazy val javaHandlerInitialize: (LambdaEnvironment, ApplicationContext) = {
given lambdaEnvironment: LambdaEnvironment = new LambdaEnvironment()
val applicationContext = initialize(using lambdaEnvironment)
(lambdaEnvironment, applicationContext)
}
/** [[com.amazonaws.services.lambda.runtime.RequestStreamHandler]] implementation for Java Runtime integration */
final override def handleRequest(
inputStream: InputStream,
outputStream: OutputStream,
context: com.amazonaws.services.lambda.runtime.Context
): Unit = {
val (lambdaEnvironment, applicationContext) = javaHandlerInitialize
val lambdaContext = LambdaContext(
context.getAwsRequestId(),
Map.empty,
lambdaEnvironment,
switchOffDebugMode
)
val bytes = inputStream.readAllBytes()
val input = new String(bytes, StandardCharsets.UTF_8)
val output = handleRequest(input)(using lambdaContext, applicationContext).trim()
outputStream.write(output.getBytes(StandardCharsets.UTF_8))
}
}
object LambdaRuntime {
inline def durationMetric = """{"Name":"duration","Unit":"Milliseconds","StorageResolution":60}"""
final def createErrorMessage(e: Throwable): String =
val stackTrace = e.getStackTrace().filterNot { s =>
val n = s.getClassName()
n.startsWith("scala") || n.startsWith("java")
}
s"{\"success\":false,\"errorMessage\":\"${e.getMessage()}\", \"error\":\"${e
.getClass()
.getName()}\", \"stackTrace\": [${(stackTrace.take(3).map(_.toString()) ++ Array("...") ++ stackTrace
.takeRight(3)
.map(_.toString())).map(s => s"\"$s\"").mkString(",")}]}"
final def withLogCapture[A](
lambdaEnvironment: LambdaEnvironment,
logPrefix: String,
logSuffix: String,
debugMode: Boolean,
body: => A
): A = {
val logPrinter: PrintStream | NoAnsiColorJsonArray | NoAnsiColorJsonString | NoAnsiColorsSingleLine =
if (debugMode) then {
if (lambdaEnvironment.shouldDisplayAnsiColors)
then LambdaEnvironment.originalOut
else if (lambdaEnvironment.shouldLogInJsonArrayFormat)
then new NoAnsiColorJsonArray(logPrefix, logSuffix, LambdaEnvironment.originalOut)
else if (lambdaEnvironment.shouldLogInJsonStringFormat)
then new NoAnsiColorJsonString(logPrefix, logSuffix, LambdaEnvironment.originalOut)
else new NoAnsiColorsSingleLine(logPrefix, logSuffix, LambdaEnvironment.originalOut)
} else NoOpPrinter.out
extension (
v: PrintStream | NoAnsiColorJsonArray | NoAnsiColorsSingleLine | NoAnsiColorJsonString
)
inline def out: PrintStream = v match {
case out: PrintStream => out
case ps: NoAnsiColorJsonArray => ps.out
case ps: NoAnsiColorJsonString => ps.out
case ps: NoAnsiColorsSingleLine => ps.out
}
inline def close(): Unit = v match {
case out: PrintStream => ()
case ps: NoAnsiColorJsonArray => ps.close()
case ps: NoAnsiColorJsonString => ps.close()
case ps: NoAnsiColorsSingleLine => ps.close()
}
val previousSystemOut = System.out
var isError = false
try {
System.setOut(logPrinter.out)
System.setErr(logPrinter.out)
Console.withOut(logPrinter.out) {
Console.withErr(logPrinter.out) {
body
}
}
} finally {
logPrinter.close()
System.setOut(previousSystemOut)
System.setErr(previousSystemOut)
}
}
}