Class AbstractMicronautLambdaRuntime<RequestType,ResponseType,HandlerRequestType,HandlerResponseType>
java.lang.Object
io.micronaut.function.aws.runtime.AbstractMicronautLambdaRuntime<RequestType,ResponseType,HandlerRequestType,HandlerResponseType>
- Type Parameters:
RequestType
- The expected request object. This is the model class that the event JSON is de-serialized toResponseType
- The expected Lambda function response object. Responses will be written to this model objectHandlerRequestType
- The request type forRequestHandler
.HandlerResponseType
- The response type for theRequestHandler
.
- All Implemented Interfaces:
io.micronaut.context.ApplicationContextProvider
,AwsLambdaRuntimeApi
- Direct Known Subclasses:
AbstractRequestStreamHandlerMicronautLambdaRuntime
,APIGatewayV2HTTPEventMicronautLambdaRuntime
,ApplicationLoadBalancerMicronautLambdaRuntime
,MicronautLambdaRuntime
public abstract class AbstractMicronautLambdaRuntime<RequestType,ResponseType,HandlerRequestType,HandlerResponseType>
extends Object
implements io.micronaut.context.ApplicationContextProvider, AwsLambdaRuntimeApi
Class that can be used as a entry point for a AWS Lambda custom runtime.
- Since:
- 2.0.0
- Author:
- sdelamo
- See Also:
-
Field Summary
Modifier and TypeFieldDescriptionprotected Object
protected final Class<HandlerRequestType>
protected final Class<HandlerResponseType>
protected final Class<RequestType>
protected final Class<ResponseType>
protected @Nullable String
Fields inherited from interface io.micronaut.function.aws.runtime.AwsLambdaRuntimeApi
ERROR_TEMPLATE, INIT_ERROR_URI, INVOCATION_TEMPLATE, LAMBDA_RUNTIME_FUNCTION_ERROR_TYPE, NEXT_INVOCATION_URI, PATH_REQUEST_ID
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionio.micronaut.context.ApplicationContextBuilder
protected @Nullable Object
protected @Nullable Object
createHandler
(String... args) protected HandlerRequestType
createHandlerRequest
(RequestType request) protected <T> @NonNull io.micronaut.http.MutableHttpRequest<T>
createNextInvocationHttpRequest
(@Nullable UserAgentProvider userAgentProvider) Creates a GET request for the "/2018-06-01/runtime/invocation/next" endpoint.protected @Nullable com.amazonaws.services.lambda.runtime.RequestHandler<HandlerRequestType,
HandlerResponseType> createRequestHandler
(String... args) protected @Nullable com.amazonaws.services.lambda.runtime.RequestStreamHandler
createRequestStreamHandler
(String... args) protected ResponseType
createResponse
(HandlerResponseType handlerResponse) protected com.amazonaws.services.lambda.runtime.Context
createRuntimeContext
(io.micronaut.http.HttpResponse<?> response) protected io.micronaut.http.HttpRequest
decorateWithUserAgent
(io.micronaut.http.HttpRequest<?> request) If the request isMutableHttpRequest
anduserAgent
is not null, it adds an HTTP Header User-Agent.io.micronaut.context.ApplicationContext
protected String
protected io.micronaut.logging.LogLevel
protected void
handleInvocationException
(@NonNull io.micronaut.http.client.BlockingHttpClient blockingHttpClient, @NonNull String requestId, @NonNull Exception exception) protected void
handleInvocationForRequestHandler
(@NonNull io.micronaut.http.client.BlockingHttpClient blockingHttpClient, @NonNull io.micronaut.http.MutableHttpRequest<?> nextInvocationHttpRequest) It handles an invocation event with a handler of typeRequestHandler
.protected void
handleInvocationForRequestStreamHandler
(@NonNull io.micronaut.http.client.BlockingHttpClient blockingHttpClient, io.micronaut.http.MutableHttpRequest<?> nextInvocationHttpRequest) It handles an invocation event with a handler of typeRequestStreamHandler
.protected void
protected void
protected void
Log with a line break.parseHandlerClass
(@NonNull String handler) protected void
UsesUserAgentProvider
to populateuserAgent
.protected void
propagateTraceId
(io.micronaut.http.HttpHeaders headers) Get the X-Ray tracing header from the Lambda-Runtime-Trace-Id header in the API response.protected void
reportInitializationError
(URL runtimeApiURL, Throwable e) Reports Initialization error to the Runtime API.protected com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent
void
Starts the runtime API event loop.protected @io.micronaut.core.annotation.Nullable byte[]
serializeAsByteArray
(Object value) protected boolean
shouldLog
(io.micronaut.logging.LogLevel level) protected void
startRuntimeApiEventLoop
(@NonNull URL runtimeApiURL, @NonNull Predicate<URL> loopUntil, String... args) Starts the runtime API event loop.protected void
protected <T> T
valueFromContent
(String content, Class<T> valueType) Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface io.micronaut.function.aws.runtime.AwsLambdaRuntimeApi
errorUri, initializationErrorRequest, invocationErrorRequest, invocationResponseRequest, responseUri
-
Field Details
-
userAgent
-
handler
-
requestType
-
responseType
-
handlerRequestType
-
handlerResponseType
-
-
Constructor Details
-
AbstractMicronautLambdaRuntime
public AbstractMicronautLambdaRuntime()Constructor.
-
-
Method Details
-
run
Starts the runtime API event loop.- Parameters:
args
- Command line arguments- Throws:
MalformedURLException
- if the lambda endpoint URL is malformed
-
populateUserAgent
protected void populateUserAgent()UsesUserAgentProvider
to populateuserAgent
. -
validateHandler
protected void validateHandler() throws io.micronaut.context.exceptions.ConfigurationException- Throws:
io.micronaut.context.exceptions.ConfigurationException
- if the handler is not of type RequestHandler or RequestStreamHandler
-
getApplicationContext
public io.micronaut.context.ApplicationContext getApplicationContext()- Specified by:
getApplicationContext
in interfaceio.micronaut.context.ApplicationContextProvider
-
createApplicationContextBuilderWithArgs
public io.micronaut.context.ApplicationContextBuilder createApplicationContextBuilderWithArgs(String... args) - Parameters:
args
- command line arguments- Returns:
- An
ApplicationContextBuilder
with the command line arguments as a property source and the environment set to lambda
-
createRequestHandler
@Nullable protected @Nullable com.amazonaws.services.lambda.runtime.RequestHandler<HandlerRequestType,HandlerResponseType> createRequestHandler(String... args) - Parameters:
args
- Command Line Args- Returns:
- a
RequestHandler
ornull
.
-
createRequestStreamHandler
@Nullable protected @Nullable com.amazonaws.services.lambda.runtime.RequestStreamHandler createRequestStreamHandler(String... args) - Parameters:
args
- Command Line Args- Returns:
- a
RequestStreamHandler
ornull
.
-
createHandler
- Parameters:
args
- Command Line Args- Returns:
- if
createHandler(String...)
orcreateRequestStreamHandler(String...)
are implemented, it returns the handler returned by those methods. If they are not, it attempts to instantiate the class referenced by the environment variableReservedRuntimeEnvironmentVariables.HANDLER
via Introspection. Otherwise, it returnsnull
.
-
createEnvironmentHandler
- Returns:
- A Handler by instantiating the class referenced by the environment variable
ReservedRuntimeEnvironmentVariables.HANDLER
via Introspection. Otherwise, it returnsnull
.
-
parseHandlerClass
- Parameters:
handler
- handler in format file.method, where file is the name of the file without an extension, and method is the name of a method or function that's defined in the file.- Returns:
- Empty or an Optional with the referenced class.
-
createResponse
- Parameters:
handlerResponse
- Handler response object- Returns:
- If the handlerResponseType and the responseType are identical just returns the supplied object. However,
if the response type is of type
APIGatewayProxyResponseEvent
it attempts to serialized the handler response as a JSON String and set it in the response body. If the object cannot be serialized, a 400 response is returned
-
respond
protected com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent respond(io.micronaut.http.HttpStatus status, byte[] body, String contentType) - Parameters:
status
- HTTP Status of the responsebody
- Body of the responsecontentType
- HTTP Header Content-Type value- Returns:
- a
APIGatewayProxyResponseEvent
populated with the supplied status, body and content type
-
createHandlerRequest
- Parameters:
request
- Request obtained from the Runtime API- Returns:
- if the request and the handler type are the same, just return the request, if the request is of type
APIGatewayProxyRequestEvent
it attempts to build an object of type HandlerRequestType with the body of the request, else returnsnull
- Throws:
IOException
- if underlying request body contains invalid content expected for result type (or has other mismatch issues)
-
createNextInvocationHttpRequest
@NonNull protected <T> @NonNull io.micronaut.http.MutableHttpRequest<T> createNextInvocationHttpRequest(@Nullable @Nullable UserAgentProvider userAgentProvider) Creates a GET request for the "/2018-06-01/runtime/invocation/next" endpoint. If a bean of typeUserAgentProvider
exists, it adds an HTTP Header User-Agent to the request.- Type Parameters:
T
- The Http request type- Parameters:
userAgentProvider
- UseAgent Provider- Returns:
- a Mutable HTTP Request to the "/2018-06-01/runtime/invocation/next" endpoint.
-
startRuntimeApiEventLoop
protected void startRuntimeApiEventLoop(@NonNull @NonNull URL runtimeApiURL, @NonNull @NonNull Predicate<URL> loopUntil, String... args) Starts the runtime API event loop.- Parameters:
runtimeApiURL
- The runtime API URL.loopUntil
- A predicate that allows controlling when the event loop should exitargs
- Command Line arguments
-
handleInvocationForRequestHandler
protected void handleInvocationForRequestHandler(@NonNull @NonNull io.micronaut.http.client.BlockingHttpClient blockingHttpClient, @NonNull @NonNull io.micronaut.http.MutableHttpRequest<?> nextInvocationHttpRequest) throws IOException It handles an invocation event with a handler of typeRequestHandler
.- Parameters:
blockingHttpClient
- Blocking HTTP ClientnextInvocationHttpRequest
- Next Invocation HTTP Request- Throws:
IOException
- Exception thrown while invoking the handler
-
handleInvocationException
protected void handleInvocationException(@NonNull @NonNull io.micronaut.http.client.BlockingHttpClient blockingHttpClient, @NonNull @NonNull String requestId, @NonNull @NonNull Exception exception) - Parameters:
blockingHttpClient
- Blocking HTTP ClientrequestId
- AWS Request ID retried viaContext.getAwsRequestId()
exception
- Execption thrown invoking the handler
-
createRuntimeContext
protected com.amazonaws.services.lambda.runtime.Context createRuntimeContext(io.micronaut.http.HttpResponse<?> response) - Parameters:
response
- Next Invocation Response- Returns:
- a new
Context
backed by aRuntimeContext
populated with the HTTP Headers of the Invocation Response.
-
handleInvocationForRequestStreamHandler
protected void handleInvocationForRequestStreamHandler(@NonNull @NonNull io.micronaut.http.client.BlockingHttpClient blockingHttpClient, io.micronaut.http.MutableHttpRequest<?> nextInvocationHttpRequest) It handles an invocation event with a handler of typeRequestStreamHandler
.- Parameters:
blockingHttpClient
- Blocking HTTP ClientnextInvocationHttpRequest
- Next Invocation HTTP Request
-
decorateWithUserAgent
protected io.micronaut.http.HttpRequest decorateWithUserAgent(io.micronaut.http.HttpRequest<?> request) If the request isMutableHttpRequest
anduserAgent
is not null, it adds an HTTP Header User-Agent.- Parameters:
request
- HTTP Request- Returns:
- The HTTP Request decorated
-
propagateTraceId
protected void propagateTraceId(io.micronaut.http.HttpHeaders headers) Get the X-Ray tracing header from the Lambda-Runtime-Trace-Id header in the API response. Set the _X_AMZN_TRACE_ID environment variable with the same value for the X-Ray SDK to use.- Parameters:
headers
- next API Response HTTP Headers
-
reportInitializationError
Reports Initialization error to the Runtime API.- Parameters:
runtimeApiURL
- Runtime API URLe
- Exception thrown
-
serializeAsByteArray
@Nullable protected @io.micronaut.core.annotation.Nullable byte[] serializeAsByteArray(Object value) throws IOException - Parameters:
value
- Object to be serialized- Returns:
- A JSON String of the supplied object
- Throws:
IOException
-
valueFromContent
- Type Parameters:
T
- Type to be read into- Parameters:
content
- JSON StringvalueType
- Class Type to be read into- Returns:
- a new Class build from the JSON String
- Throws:
IOException
- if underlying input contains invalid content expected for result type (or has other mismatch issues)
-
getEnv
- Parameters:
name
- the name of the environment variable- Returns:
- the string value of the variable, or
null
if the variable is not defined
-
log
- Parameters:
level
- Log Levelmsg
- Message to log
-
getLogLevel
protected io.micronaut.logging.LogLevel getLogLevel()- Returns:
LogLevel
for the custom runtime.
-
logn
Log with a line break.- Parameters:
logLevel
- Log levelmsg
- Message to log
-
logn
- Parameters:
level
- Log LevelmessageParts
- One or more message parts to concatenate and log if enabled
-
shouldLog
protected boolean shouldLog(io.micronaut.logging.LogLevel level) - Parameters:
level
- Log level- Returns:
- where it should log or not
-