Behaviour for Lambda function handlers.
defmodule MyApp.Handler do
use Mayfly.Handler
@impl true
def init(_opts) do
# cold-start work: read config, open a pool, warm a cache
{:ok, %{table: System.fetch_env!("TABLE_NAME")}}
end
@impl true
def handle(event, %Mayfly.Context{} = ctx, state) do
{:ok, %{table: state.table, request_id: ctx.request_id, event: event}}
end
endSet the Lambda Handler (_HANDLER) to the module name: MyApp.Handler.
Callbacks
init/1– optional, runs once per execution environment before the first/nextpoll. Return{:ok, state}or{:error, reason}; an error is reported asRuntime.InitErrorand the function fails to start. The default returns{:ok, nil}.handle/3– called for every invocation with the decoded event, theMayfly.Contextand the state frominit/1. Return{:ok, response}or{:error, reason}. SeeMayfly.Responsefor whatresponsemay be.
On Lambda Managed Instances handle/3 runs concurrently in separate
processes (up to AWS_LAMBDA_MAX_CONCURRENCY); state is shared read-only.
Legacy Module.function handlers
_HANDLER=MyApp.Legacy.handle still works: a public function of arity 1
(handle(event)) or 2 (handle(event, context)) is wrapped automatically.
The Elixir. prefix is accepted in both forms.
Summary
Functions
Invokes a resolved handler, converting exceptions, exits and throws into error payloads.
Resolves the _HANDLER string and runs init/1.
Types
@type resolved() :: %{ module: module(), fun: (term(), Mayfly.Context.t(), state() -> result()), state: state() }
A resolved, ready-to-call handler.
@type result() :: {:ok, Mayfly.Response.t() | term()} | {:error, term()}
@type state() :: term()
Callbacks
Functions
@spec invoke(resolved(), term(), Mayfly.Context.t()) :: {:ok, Mayfly.Response.t()} | {:error, Mayfly.ErrorPayload.t()}
Invokes a resolved handler, converting exceptions, exits and throws into error payloads.
@spec resolve(String.t() | nil, keyword()) :: {:ok, resolved()} | {:error, Mayfly.ErrorPayload.t()}
Resolves the _HANDLER string and runs init/1.
Returns {:error, %{errorType: "Runtime.NoSuchHandler" | "Runtime.InitError", ...}}
on failure so callers can post it to /runtime/init/error directly.