All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.http4k.serverless.InvocationLambdaFunction.kt Maven / Gradle / Ivy

There is a newer version: 5.45.1.0
Show newest version
package org.http4k.serverless

import com.amazonaws.services.lambda.runtime.Context
import org.http4k.core.HttpHandler
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.RequestContexts
import org.http4k.core.Response
import org.http4k.core.then
import org.http4k.filter.ServerFilters.CatchAll
import org.http4k.filter.ServerFilters.InitialiseRequestContext
import java.io.InputStream

/**
 * Function loader for Invocation Lambdas
 */
class InvocationFnLoader(private val appLoader: AppLoaderWithContexts) : FnLoader {
    constructor(input: AppLoader) : this(AppLoaderWithContexts { env, _ -> input(env) })
    constructor(input: HttpHandler) : this(AppLoader { input })

    private val contexts = RequestContexts("lambda")

    override operator fun invoke(env: Map): FnHandler {
        val app = appLoader(env, contexts)
        return FnHandler { inputStream, ctx ->
            val request = Request(POST, "/2015-03-31/functions/${ctx.functionName}/invocations")
                .header("X-Amz-Invocation-Type", "RequestResponse")
                .header("X-Amz-Log-Type", "Tail").body(inputStream)
            CatchAll()
                .then(InitialiseRequestContext(contexts))
                .then(AddLambdaContextAndRequest(ctx, inputStream, contexts))
                .then(app)(request)
                .body.stream
        }
    }
}

/**
 * This is the main entry point for lambda invocations using the direct invocations.
 * It uses the local environment to instantiate the HttpHandler which can be used
 * for further invocations.
 */
abstract class InvocationLambdaFunction(appLoader: AppLoaderWithContexts) :
    AwsLambdaEventFunction(InvocationFnLoader(appLoader)) {
    constructor(input: AppLoader) : this(AppLoaderWithContexts { env, _ -> input(env) })
    constructor(input: HttpHandler) : this(AppLoader { input })
}

object InvocationLambdaAwsHttpAdapter : AwsHttpAdapter {
    override fun invoke(req: InputStream, ctx: Context) = runCatching {
        Request(POST, "/2015-03-31/functions/${ctx.functionName}/invocations")
            .header("X-Amz-Invocation-Type", "RequestResponse")
            .header("X-Amz-Log-Type", "Tail").body(req)
    }

    override fun invoke(resp: Response) = resp.body.stream
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy