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 to
ResponseType - The expected Lambda function response object. Responses will be written to this model object
HandlerRequestType - The request type for RequestHandler.
HandlerResponseType - The response type for the RequestHandler.
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 Details

  • Constructor Details

    • AbstractMicronautLambdaRuntime

      public AbstractMicronautLambdaRuntime()
      Constructor.
  • Method Details

    • run

      public void run(String... args) throws MalformedURLException
      Starts the runtime API event loop.
      Parameters:
      args - Command line arguments
      Throws:
      MalformedURLException - if the lambda endpoint URL is malformed
    • populateUserAgent

      protected void populateUserAgent()
      Uses UserAgentProvider to populate userAgent.
    • 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 interface io.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 or null.
    • createRequestStreamHandler

      @Nullable protected @Nullable com.amazonaws.services.lambda.runtime.RequestStreamHandler createRequestStreamHandler(String... args)
      Parameters:
      args - Command Line Args
      Returns:
      a RequestStreamHandler or null.
    • createHandler

      @Nullable protected @Nullable Object createHandler(String... args)
      Parameters:
      args - Command Line Args
      Returns:
      if createHandler(String...) or createRequestStreamHandler(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 variable ReservedRuntimeEnvironmentVariables.HANDLER via Introspection. Otherwise, it returns null.
    • createEnvironmentHandler

      @Nullable protected @Nullable Object createEnvironmentHandler()
      Returns:
      A Handler by instantiating the class referenced by the environment variable ReservedRuntimeEnvironmentVariables.HANDLER via Introspection. Otherwise, it returns null.
    • parseHandlerClass

      protected Optional<Class<?>> parseHandlerClass(@NonNull @NonNull String handler)
      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

      @Nullable protected ResponseType createResponse(HandlerResponseType handlerResponse)
      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 response
      body - Body of the response
      contentType - HTTP Header Content-Type value
      Returns:
      a APIGatewayProxyResponseEvent populated with the supplied status, body and content type
    • createHandlerRequest

      @Nullable protected HandlerRequestType createHandlerRequest(RequestType request) throws IOException
      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 returns null
      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 type UserAgentProvider 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 exit
      args - 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 type RequestHandler.
      Parameters:
      blockingHttpClient - Blocking HTTP Client
      nextInvocationHttpRequest - 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 Client
      requestId - AWS Request ID retried via Context.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 a RuntimeContext 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 type RequestStreamHandler.
      Parameters:
      blockingHttpClient - Blocking HTTP Client
      nextInvocationHttpRequest - Next Invocation HTTP Request
    • decorateWithUserAgent

      protected io.micronaut.http.HttpRequest decorateWithUserAgent(io.micronaut.http.HttpRequest<?> request)
      If the request is MutableHttpRequest and userAgent 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

      protected void reportInitializationError(URL runtimeApiURL, Throwable e)
      Reports Initialization error to the Runtime API.
      Parameters:
      runtimeApiURL - Runtime API URL
      e - 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

      @Nullable protected <T> T valueFromContent(String content, Class<T> valueType) throws IOException
      Type Parameters:
      T - Type to be read into
      Parameters:
      content - JSON String
      valueType - 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

      protected String getEnv(String name)
      Parameters:
      name - the name of the environment variable
      Returns:
      the string value of the variable, or null if the variable is not defined
    • log

      protected void log(io.micronaut.logging.LogLevel level, String msg)
      Parameters:
      level - Log Level
      msg - Message to log
    • getLogLevel

      protected io.micronaut.logging.LogLevel getLogLevel()
      Returns:
      LogLevel for the custom runtime.
    • logn

      protected void logn(io.micronaut.logging.LogLevel logLevel, String msg)
      Log with a line break.
      Parameters:
      logLevel - Log level
      msg - Message to log
    • logn

      protected void logn(io.micronaut.logging.LogLevel level, Object... messageParts)
      Parameters:
      level - Log Level
      messageParts - 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