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
FieldsModifier and TypeFieldDescriptionprotected Objectprotected final Class<HandlerRequestType>protected final Class<HandlerResponseType>protected final Class<RequestType>protected final Class<ResponseType>protected @Nullable StringFields 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
Constructors -
Method Summary
Modifier and TypeMethodDescriptionio.micronaut.context.ApplicationContextBuilderprotected @Nullable Objectprotected @Nullable ObjectcreateHandler(String... args) protected HandlerRequestTypecreateHandlerRequest(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.RequestStreamHandlercreateRequestStreamHandler(String... args) protected ResponseTypecreateResponse(HandlerResponseType handlerResponse) protected com.amazonaws.services.lambda.runtime.ContextcreateRuntimeContext(io.micronaut.http.HttpResponse<?> response) protected io.micronaut.http.HttpRequestdecorateWithUserAgent(io.micronaut.http.HttpRequest<?> request) If the request isMutableHttpRequestanduserAgentis not null, it adds an HTTP Header User-Agent.io.micronaut.context.ApplicationContextprotected Stringprotected io.micronaut.logging.LogLevelprotected voidhandleInvocationException(@NonNull io.micronaut.http.client.BlockingHttpClient blockingHttpClient, @NonNull String requestId, @NonNull Exception exception) protected voidhandleInvocationForRequestHandler(@NonNull io.micronaut.http.client.BlockingHttpClient blockingHttpClient, @NonNull io.micronaut.http.MutableHttpRequest<?> nextInvocationHttpRequest) It handles an invocation event with a handler of typeRequestHandler.protected voidhandleInvocationForRequestStreamHandler(@NonNull io.micronaut.http.client.BlockingHttpClient blockingHttpClient, io.micronaut.http.MutableHttpRequest<?> nextInvocationHttpRequest) It handles an invocation event with a handler of typeRequestStreamHandler.protected voidprotected voidprotected voidLog with a line break.parseHandlerClass(@NonNull String handler) protected voidUsesUserAgentProviderto populateuserAgent.protected voidpropagateTraceId(io.micronaut.http.HttpHeaders headers) Get the X-Ray tracing header from the Lambda-Runtime-Trace-Id header in the API response.protected voidreportInitializationError(URL runtimeApiURL, Throwable e) Reports Initialization error to the Runtime API.protected com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEventvoidStarts the runtime API event loop.protected @io.micronaut.core.annotation.Nullable byte[]serializeAsByteArray(Object value) protected booleanshouldLog(io.micronaut.logging.LogLevel level) protected voidstartRuntimeApiEventLoop(@NonNull URL runtimeApiURL, @NonNull Predicate<URL> loopUntil, String... args) Starts the runtime API event loop.protected voidprotected <T> TvalueFromContent(String content, Class<T> valueType) Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods 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()UsesUserAgentProviderto 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:
getApplicationContextin interfaceio.micronaut.context.ApplicationContextProvider
-
createApplicationContextBuilderWithArgs
public io.micronaut.context.ApplicationContextBuilder createApplicationContextBuilderWithArgs(String... args) - Parameters:
args- command line arguments- Returns:
- An
ApplicationContextBuilderwith 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
RequestHandlerornull.
-
createRequestStreamHandler
@Nullable protected @Nullable com.amazonaws.services.lambda.runtime.RequestStreamHandler createRequestStreamHandler(String... args) - Parameters:
args- Command Line Args- Returns:
- a
RequestStreamHandlerornull.
-
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.HANDLERvia Introspection. Otherwise, it returnsnull.
-
createEnvironmentHandler
- Returns:
- A Handler by instantiating the class referenced by the environment variable
ReservedRuntimeEnvironmentVariables.HANDLERvia 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
APIGatewayProxyResponseEventit 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
APIGatewayProxyResponseEventpopulated 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
APIGatewayProxyRequestEventit 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 typeUserAgentProviderexists, 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
Contextbacked by aRuntimeContextpopulated 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 isMutableHttpRequestanduserAgentis 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
nullif the variable is not defined
-
log
- Parameters:
level- Log Levelmsg- Message to log
-
getLogLevel
protected io.micronaut.logging.LogLevel getLogLevel()- Returns:
LogLevelfor 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
-