lambda

package
v0.0.1-alpha.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

Package lambda is a stub — handlers are implemented test-first.

Architecture uses the Strategy pattern for runtime execution:

Runtime interface ← NodeRuntime (v1) | PythonRuntime (future) | GoRuntime (future)

The Lambda handler never knows which runtime it's talking to. Adding a new runtime means implementing the Runtime interface and registering it in the RuntimeRegistry — nothing else changes.

Implementation order (TDD):

  1. CreateFunction / GetFunction / ListFunctions / DeleteFunction / UpdateFunctionCode
  2. Invoke (synchronous) — stub response mode
  3. Invoke (synchronous) — real Node.js execution via NodeRuntime
  4. InvokeAsync
  5. Event source mapping (SQS→Lambda)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ContainerRuntime

type ContainerRuntime struct {
	// contains filtered or unexported fields
}

ContainerRuntime implements Runtime by running Lambda functions in Docker containers using official AWS Lambda base images.

func NewContainerRuntime

func NewContainerRuntime(
	cfg *config.Config,
	clk clock.Clock,
	docker *docker.Client,
	gc *docker.GC,
	runtimeAPI *RuntimeAPIServer,
	logger *zap.Logger,
) *ContainerRuntime

NewContainerRuntime creates a ContainerRuntime. The Docker client and RuntimeAPIServer must already be initialised.

func (*ContainerRuntime) Acquire

func (cr *ContainerRuntime) Acquire(ctx context.Context, fn *Function) (RuntimeInstance, error)

Acquire creates and starts a Docker container for fn, then returns a containerInstance that can invoke the function via the Runtime API.

func (*ContainerRuntime) AcquireWithProgress

func (cr *ContainerRuntime) AcquireWithProgress(ctx context.Context, fn *Function, progress ProgressFunc) (RuntimeInstance, error)

AcquireWithProgress is like Acquire but calls progress at each lifecycle step so callers (e.g. the SSE invoke endpoint) can stream status to the UI.

func (*ContainerRuntime) CanHandle

func (cr *ContainerRuntime) CanHandle(runtimeID string) bool

CanHandle returns true for all active (non-deprecated) runtime IDs that have official ECR images, and for PackageType=Image functions (runtimeID "image").

func (*ContainerRuntime) PrewarmFunction

func (cr *ContainerRuntime) PrewarmFunction(fn *Function, onReady func(err error))

PrewarmFunction starts a background pull of fn's Docker image so the first Invoke doesn't pay the cold-pull cost on the request path. Safe to call from CreateFunction — if the image is already cached or in flight, the sync.Once inside ensureImage coalesces the work. onReady is invoked (on the background goroutine) after the pull completes; it can be nil. err passed to onReady is the pull result.

func (*ContainerRuntime) Release

func (cr *ContainerRuntime) Release(_ context.Context, _ RuntimeInstance, _ bool)

Release is a no-op for ContainerRuntime itself — InstancePool wraps it and handles warm-instance storage and eviction.

func (*ContainerRuntime) SeedImages

func (cr *ContainerRuntime) SeedImages()

SeedImages pre-pulls Docker images for all active runtimes (nodejs, python, java, dotnet, ruby, provided) in parallel so the first cold start of any runtime skips the image pull entirely. The seed runs in a background goroutine with a detached context — it does not block startup or callers. Call after the ContainerRuntime is fully wired (i.e. after initDockerRuntime).

Pre-pulling at startup is the single biggest lever for cold-start latency: the base images are 200–500 MB and pulling them on the first Invoke path can take minutes. By the time the user creates a function and invokes it the images are already cached locally.

func (*ContainerRuntime) SetBus

func (cr *ContainerRuntime) SetBus(b *events.Bus)

SetBus wires the event bus so image pull progress events are published. Safe to call at any time; picked up by the next ensureImage call.

func (*ContainerRuntime) SetLayerContentFetcher

func (cr *ContainerRuntime) SetLayerContentFetcher(fetcher LayerContentFetcher)

SetLayerContentFetcher wires layer content retrieval for runtime injection.

func (*ContainerRuntime) SetLogWriter

func (cr *ContainerRuntime) SetLogWriter(lw events.LogWriter)

SetLogWriter wires the CloudWatch Logs writer so container stdout/stderr is forwarded to CloudWatch. Safe to call at any time; the writer is picked up by the next Acquire call.

func (*ContainerRuntime) SetRemoteLayerFetcher

func (cr *ContainerRuntime) SetRemoteLayerFetcher(fetcher *RemoteLayerFetcher)

SetRemoteLayerFetcher wires the optional remote layer fetcher that downloads layers from real AWS when not available locally.

func (*ContainerRuntime) SetVPCResolver

func (cr *ContainerRuntime) SetVPCResolver(r VPCNetworkResolver)

SetVPCResolver wires the EC2 VPC resolver for connecting Lambda containers to VPC Docker networks.

func (*ContainerRuntime) ThrottleInitBurst

func (cr *ContainerRuntime) ThrottleInitBurst(functionARN string)

ThrottleInitBurst reduces a container's CPU allocation from the INIT burst level to the steady-state proportional allocation. Called when the RIC issues its first GET /next, signalling that the INIT phase is complete. Safe to call for functions that don't have a pending burst entry (no-op).

type DestinationConfig

type DestinationConfig struct {
	OnFailure *OnFailure `json:"OnFailure,omitempty"`
}

DestinationConfig specifies where to send records of invocations that fail after exhausting retries. Mirrors the AWS Lambda DestinationConfig structure.

type EventSourceMapping

type EventSourceMapping struct {
	// UUID is the primary key assigned at creation time.
	UUID string `json:"UUID"`
	// FunctionArn is the full ARN of the target Lambda function.
	FunctionArn string `json:"FunctionArn"`
	// EventSourceArn is the ARN of the SQS queue or DynamoDB stream.
	EventSourceArn string `json:"EventSourceArn"`
	// State is the lifecycle state (see esmState* constants).
	State string `json:"State"`
	// StateTransitionReason is a human-readable explanation of the last state change.
	StateTransitionReason string `json:"StateTransitionReason"`
	// BatchSize is the maximum number of records per invocation batch.
	BatchSize int `json:"BatchSize"`
	// StartingPosition is required for stream-based sources ("TRIM_HORIZON", "LATEST").
	StartingPosition string `json:"StartingPosition,omitempty"`
	// MaximumBatchingWindowInSeconds controls how long to accumulate records
	// before invoking (0 means invoke as soon as records arrive).
	MaximumBatchingWindowInSeconds int `json:"MaximumBatchingWindowInSeconds"`
	// FilterCriteria defines event-filtering patterns evaluated before invoking
	// the function. Only records matching at least one filter are processed.
	FilterCriteria *FilterCriteria `json:"FilterCriteria,omitempty"`
	// MaximumRecordAgeInSeconds is the maximum age (in seconds) of a record that
	// Lambda sends to the function. -1 disables the limit. Stream sources only.
	MaximumRecordAgeInSeconds *int `json:"MaximumRecordAgeInSeconds,omitempty"`
	// MaximumRetryAttempts is the max number of retries when the function returns
	// an error. -1 means unlimited. Stream sources only.
	MaximumRetryAttempts *int `json:"MaximumRetryAttempts,omitempty"`
	// TumblingWindowInSeconds groups stream records into fixed-duration processing
	// windows. 0 disables tumbling windows. Stream sources only.
	TumblingWindowInSeconds int `json:"TumblingWindowInSeconds,omitempty"`
	// BisectBatchOnFunctionError splits a failed batch into two and retries each
	// half separately. Stream sources only.
	BisectBatchOnFunctionError bool `json:"BisectBatchOnFunctionError,omitempty"`
	// DestinationConfig specifies where to send records of failed asynchronous
	// invocations. Only OnFailure.Destination is supported (SQS ARN).
	DestinationConfig *DestinationConfig `json:"DestinationConfig,omitempty"`
	// LastModified is the Unix timestamp (seconds, fractional) of the last update.
	LastModified float64 `json:"LastModified"`
	// LastProcessingResult describes the outcome of the most recent invocation
	// ("No records processed", "OK", "FunctionError", "Throttled", etc.).
	LastProcessingResult string `json:"LastProcessingResult,omitempty"`
	// ScalingConfig controls the maximum concurrent invocations for this ESM.
	// Only applicable to SQS sources. nil means unlimited.
	ScalingConfig *ScalingConfig `json:"ScalingConfig,omitempty"`
}

EventSourceMapping is the domain model for a Lambda event source mapping. Field names and JSON tags mirror the AWS Lambda wire format so they can be serialised directly in HTTP responses.

type Filter

type Filter struct {
	Pattern string `json:"Pattern"`
}

Filter is a single event-filter pattern in an EventSourceMapping.

type FilterCriteria

type FilterCriteria struct {
	Filters []Filter `json:"Filters"`
}

FilterCriteria defines event-filtering criteria for an EventSourceMapping.

type Function

type Function struct {
	Name            string             `json:"name"`
	ARN             string             `json:"arn"`
	Runtime         string             `json:"runtime"`
	Handler         string             `json:"handler"`
	Role            string             `json:"role"`
	Description     string             `json:"description,omitempty"`
	Timeout         int                `json:"timeout"`
	MemorySize      int                `json:"memory_size"`
	Environment     map[string]string  `json:"environment,omitempty"`
	CodeZip         []byte             `json:"code_zip,omitempty"` // base64-decoded zip
	CodeSize        int64              `json:"code_size,omitempty"`
	CodeS3Bucket    string             `json:"code_s3_bucket,omitempty"`
	CodeS3Key       string             `json:"code_s3_key,omitempty"`
	ImageUri        string             `json:"image_uri,omitempty"` // PackageType=Image only
	PackageType     string             `json:"package_type,omitempty"`
	Architectures   []string           `json:"architectures,omitempty"`
	State           string             `json:"state"` // "Active", "Pending", "Inactive", "Failed"
	StateReason     string             `json:"state_reason,omitempty"`
	StateReasonCode string             `json:"state_reason_code,omitempty"` // e.g. "Creating", "Idle", "ImagePullError"
	RevisionId      string             `json:"revision_id,omitempty"`
	LastModified    string             `json:"last_modified,omitempty"`
	LogGroup        string             `json:"log_group,omitempty"` // Custom log group; defaults to /aws/lambda/{name}
	Layers          []LayerVersionLink `json:"layers,omitempty"`    // Attached layer versions (empty until layers are implemented)
	// SourceCode and SourceFilename are emulator-internal: they hold the raw
	// handler source text authored in the web UI. Not exposed in AWS wire responses.
	SourceCode     string `json:"source_code,omitempty"`
	SourceFilename string `json:"source_filename,omitempty"`
	// VpcConfig optionally associates the function with an EC2 VPC. When set,
	// the Lambda container is connected to the VPC's Docker network in addition
	// to the default Lambda network, so the function can communicate with other
	// resources in the VPC.
	VpcConfig *VpcConfig `json:"vpc_config,omitempty"`
	// ImageConfig overrides the container image's EntryPoint, Command, and
	// WorkingDirectory. Only applicable when PackageType=Image.
	ImageConfig *ImageConfig      `json:"image_config,omitempty"`
	Tags        map[string]string `json:"tags,omitempty"`
	// ReservedConcurrency is the reserved concurrency limit. nil = unreserved,
	// 0 = throttled (no executions).
	ReservedConcurrency *int `json:"reserved_concurrency,omitempty"`
}

Function is the domain model for a stored Lambda function definition.

type FunctionAlias

type FunctionAlias struct {
	FunctionName    string `json:"function_name"`
	Name            string `json:"name"`
	FunctionVersion string `json:"function_version"` // e.g. "3" or "$LATEST"
	Description     string `json:"description,omitempty"`
	AliasARN        string `json:"alias_arn"`
	RevisionId      string `json:"revision_id"`
}

FunctionAlias is a named pointer to a specific function version.

type FunctionVersion

type FunctionVersion struct {
	// Embed the full function config — all fields are frozen at publish time.
	Function
	// Version is the numeric version identifier (1, 2, 3, …).
	Version int `json:"version"`
	// Description overrides the function description for this specific version.
	Description string `json:"version_description,omitempty"`
	// CodeSha256 is the SHA-256 of the deployment package at publish time.
	CodeSha256 string `json:"code_sha256,omitempty"`
}

FunctionVersion is an immutable snapshot of a function configuration published via PublishVersion. It mirrors the AWS FunctionConfiguration wire shape with the additional Version and CodeSha256 fields.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler holds Lambda handler dependencies.

func (*Handler) CreateAlias

func (h *Handler) CreateAlias(w http.ResponseWriter, r *http.Request)

CreateAlias handles POST /2015-03-31/functions/{name}/aliases. https://docs.aws.amazon.com/lambda/latest/api/API_CreateAlias.html

func (*Handler) CreateEventSourceMapping

func (h *Handler) CreateEventSourceMapping(w http.ResponseWriter, r *http.Request)

CreateEventSourceMapping handles POST /2015-03-31/event-source-mappings.

func (*Handler) CreateFunction

func (h *Handler) CreateFunction(w http.ResponseWriter, r *http.Request)

CreateFunction handles POST /2015-03-31/functions.

func (*Handler) DeleteAlias

func (h *Handler) DeleteAlias(w http.ResponseWriter, r *http.Request)

DeleteAlias handles DELETE /2015-03-31/functions/{name}/aliases/{aliasName}. https://docs.aws.amazon.com/lambda/latest/api/API_DeleteAlias.html

func (*Handler) DeleteEventSourceMapping

func (h *Handler) DeleteEventSourceMapping(w http.ResponseWriter, r *http.Request)

DeleteEventSourceMapping handles DELETE /2015-03-31/event-source-mappings/{uuid}.

func (*Handler) DeleteFunction

func (h *Handler) DeleteFunction(w http.ResponseWriter, r *http.Request)

DeleteFunction handles DELETE /2015-03-31/functions/{name}.

func (*Handler) DeleteFunctionConcurrency

func (h *Handler) DeleteFunctionConcurrency(w http.ResponseWriter, r *http.Request)

DeleteFunctionConcurrency handles DELETE /2015-03-31/functions/{name}/concurrency.

func (*Handler) DeleteLayerVersion

func (h *Handler) DeleteLayerVersion(w http.ResponseWriter, r *http.Request)

DeleteLayerVersion handles DELETE /2015-03-31/layers/{layerName}/versions/{versionNumber}. https://docs.aws.amazon.com/lambda/latest/api/API_DeleteLayerVersion.html

func (*Handler) DeleteTestEvent

func (h *Handler) DeleteTestEvent(w http.ResponseWriter, r *http.Request)

DeleteTestEvent handles DELETE /2015-03-31/functions/{name}/test-events/{eventName}. Emulator-only endpoint for removing saved test events.

func (*Handler) GetAlias

func (h *Handler) GetAlias(w http.ResponseWriter, r *http.Request)

GetAlias handles GET /2015-03-31/functions/{name}/aliases/{aliasName}. https://docs.aws.amazon.com/lambda/latest/api/API_GetAlias.html

func (*Handler) GetEventSourceMapping

func (h *Handler) GetEventSourceMapping(w http.ResponseWriter, r *http.Request)

GetEventSourceMapping handles GET /2015-03-31/event-source-mappings/{uuid}.

func (*Handler) GetFunction

func (h *Handler) GetFunction(w http.ResponseWriter, r *http.Request)

GetFunction handles GET /2015-03-31/functions/{name}. Returns FunctionConfiguration + Code location block.

func (*Handler) GetFunctionCodeSigningConfig

func (h *Handler) GetFunctionCodeSigningConfig(w http.ResponseWriter, r *http.Request)

GetFunctionCodeSigningConfig handles GET /2015-03-31/functions/{name}/code-signing-config. Code signing is not enforced by the emulator; functions never have a config associated, so this always returns ResourceNotFoundException once the function is confirmed to exist.

func (*Handler) GetFunctionConcurrency

func (h *Handler) GetFunctionConcurrency(w http.ResponseWriter, r *http.Request)

GetFunctionConcurrency handles GET /2015-03-31/functions/{name}/concurrency.

func (*Handler) GetFunctionConfiguration

func (h *Handler) GetFunctionConfiguration(w http.ResponseWriter, r *http.Request)

GetFunctionConfiguration handles GET /2015-03-31/functions/{name}/configuration. Returns FunctionConfiguration only (no Code block), matching AWS behaviour.

func (*Handler) GetFunctionSource

func (h *Handler) GetFunctionSource(w http.ResponseWriter, r *http.Request)

GetFunctionSource handles GET /2015-03-31/functions/{name}/source. Returns the stored plain-text source (or a default stub if none stored yet).

Query parameters:

?file=path — return content of a specific file inside the deployment zip.

func (*Handler) GetLayerVersion

func (h *Handler) GetLayerVersion(w http.ResponseWriter, r *http.Request)

GetLayerVersion handles GET /2015-03-31/layers/{layerName}/versions/{versionNumber}. https://docs.aws.amazon.com/lambda/latest/api/API_GetLayerVersion.html

func (*Handler) GetProvisionedConcurrencyConfig

func (h *Handler) GetProvisionedConcurrencyConfig(w http.ResponseWriter, r *http.Request)

GetProvisionedConcurrencyConfig handles GET /2015-03-31/functions/{name}/provisioned-concurrency.

func (*Handler) InvokeFunction

func (h *Handler) InvokeFunction(w http.ResponseWriter, r *http.Request)

InvokeFunction handles POST /2015-03-31/functions/{name}/invocations. https://docs.aws.amazon.com/lambda/latest/api/API_Invoke.html

func (*Handler) InvokeFunctionSSE

func (h *Handler) InvokeFunctionSSE(w http.ResponseWriter, r *http.Request)

InvokeFunctionSSE handles POST /2015-03-31/functions/{name}/invoke-with-progress. Emulator-only endpoint that streams lifecycle progress events as SSE, then sends the final invoke result. Used by the web UI Test tab.

func (*Handler) InvokeWithResponseStream

func (h *Handler) InvokeWithResponseStream(w http.ResponseWriter, r *http.Request)

InvokeWithResponseStream handles POST /2021-11-15/functions/{name}/response-streaming-invocations.

func (*Handler) ListAliases

func (h *Handler) ListAliases(w http.ResponseWriter, r *http.Request)

ListAliases handles GET /2015-03-31/functions/{name}/aliases. https://docs.aws.amazon.com/lambda/latest/api/API_ListAliases.html

func (*Handler) ListEventSourceMappings

func (h *Handler) ListEventSourceMappings(w http.ResponseWriter, r *http.Request)

ListEventSourceMappings handles GET /2015-03-31/event-source-mappings. This replaces the stub in handler_stubs.go.

func (*Handler) ListFunctions

func (h *Handler) ListFunctions(w http.ResponseWriter, r *http.Request)

ListFunctions handles GET /2015-03-31/functions.

func (*Handler) ListInstances

func (h *Handler) ListInstances(w http.ResponseWriter, r *http.Request)

ListInstances handles GET /_lambda/instances. Returns all currently tracked instances (running + idle) across all functions.

func (*Handler) ListLayerVersions

func (h *Handler) ListLayerVersions(w http.ResponseWriter, r *http.Request)

ListLayerVersions handles GET /2015-03-31/layers/{layerName}/versions. https://docs.aws.amazon.com/lambda/latest/api/API_ListLayerVersions.html AWS returns versions in descending order (newest first).

func (*Handler) ListLayers

func (h *Handler) ListLayers(w http.ResponseWriter, r *http.Request)

ListLayers handles GET /2015-03-31/layers. https://docs.aws.amazon.com/lambda/latest/api/API_ListLayers.html Returns one entry per distinct layer name, with its latest version.

func (*Handler) ListRuntimes

func (h *Handler) ListRuntimes(w http.ResponseWriter, _ *http.Request)

ListRuntimes handles GET /_lambda/runtimes (emulator-only). Fetches available runtimes from ECR Public on first call and caches the result.

func (*Handler) ListTestEvents

func (h *Handler) ListTestEvents(w http.ResponseWriter, r *http.Request)

ListTestEvents handles GET /2015-03-31/functions/{name}/test-events. Emulator-only endpoint for the web UI's Test tab.

func (*Handler) ListVersionsByFunction

func (h *Handler) ListVersionsByFunction(w http.ResponseWriter, r *http.Request)

ListVersionsByFunction handles GET /2015-03-31/functions/{name}/versions. https://docs.aws.amazon.com/lambda/latest/api/API_ListVersionsByFunction.html

func (*Handler) PublishLayerVersion

func (h *Handler) PublishLayerVersion(w http.ResponseWriter, r *http.Request)

PublishLayerVersion handles POST /2015-03-31/layers/{layerName}/versions. https://docs.aws.amazon.com/lambda/latest/api/API_PublishLayerVersion.html

func (*Handler) PublishVersion

func (h *Handler) PublishVersion(w http.ResponseWriter, r *http.Request)

PublishVersion handles POST /2015-03-31/functions/{name}/versions. https://docs.aws.amazon.com/lambda/latest/api/API_PublishVersion.html

func (*Handler) PutFunctionConcurrency

func (h *Handler) PutFunctionConcurrency(w http.ResponseWriter, r *http.Request)

PutFunctionConcurrency handles PUT /2015-03-31/functions/{name}/concurrency.

func (*Handler) PutFunctionSource

func (h *Handler) PutFunctionSource(w http.ResponseWriter, r *http.Request)

PutFunctionSource handles PUT /2015-03-31/functions/{name}/source. Stores the source text, packs it into a zip, and updates the function.

func (*Handler) PutProvisionedConcurrencyConfig

func (h *Handler) PutProvisionedConcurrencyConfig(w http.ResponseWriter, r *http.Request)

PutProvisionedConcurrencyConfig handles PUT /2015-03-31/functions/{name}/provisioned-concurrency. The Qualifier query parameter is required (version number or alias name).

func (*Handler) PutTestEvent

func (h *Handler) PutTestEvent(w http.ResponseWriter, r *http.Request)

PutTestEvent handles PUT /2015-03-31/functions/{name}/test-events/{eventName}. Emulator-only endpoint for creating or updating saved test events.

func (*Handler) StopAsync

func (h *Handler) StopAsync(ctx context.Context)

StopAsync waits for all in-flight async invocations to complete, with a timeout provided by ctx. This prevents goroutine leaks on shutdown.

func (*Handler) UpdateAlias

func (h *Handler) UpdateAlias(w http.ResponseWriter, r *http.Request)

UpdateAlias handles PUT /2015-03-31/functions/{name}/aliases/{aliasName}. https://docs.aws.amazon.com/lambda/latest/api/API_UpdateAlias.html

func (*Handler) UpdateEventSourceMapping

func (h *Handler) UpdateEventSourceMapping(w http.ResponseWriter, r *http.Request)

UpdateEventSourceMapping handles PUT /2015-03-31/event-source-mappings/{uuid}.

func (*Handler) UpdateFunctionCode

func (h *Handler) UpdateFunctionCode(w http.ResponseWriter, r *http.Request)

UpdateFunctionCode handles PUT /2015-03-31/functions/{name}/code.

func (*Handler) UpdateFunctionConfiguration

func (h *Handler) UpdateFunctionConfiguration(w http.ResponseWriter, r *http.Request)

UpdateFunctionConfiguration handles PUT /2015-03-31/functions/{name}/configuration.

type ImageConfig

type ImageConfig struct {
	EntryPoint       []string `json:"entry_point,omitempty"`
	Command          []string `json:"command,omitempty"`
	WorkingDirectory string   `json:"working_directory,omitempty"`
}

ImageConfig overrides for container image Lambda functions.

type InstancePool

type InstancePool struct {
	// contains filtered or unexported fields
}

InstancePool manages warm RuntimeInstances, one per function.

func NewInstancePool

func NewInstancePool(rt Runtime, log *zap.Logger, clk clock.Clock) *InstancePool

NewInstancePool creates an InstancePool backed by rt and starts the background sweeper. Call Stop() to shut it down.

func (*InstancePool) Acquire

func (p *InstancePool) Acquire(ctx context.Context, fn *Function) (RuntimeInstance, error)

Acquire returns a warm RuntimeInstance for fn.

  • Warm hit: existing instance with matching codeHash → reused.
  • Stale hit: existing instance with different codeHash (code was updated) → old instance closed, new cold start.
  • Miss: no entry → cold start via rt.Acquire.

func (*InstancePool) AcquireWithProgress

func (p *InstancePool) AcquireWithProgress(ctx context.Context, fn *Function, progress ProgressFunc) (RuntimeInstance, error)

AcquireWithProgress is like Acquire but reports lifecycle steps via progress. If a warm instance is available it is returned immediately; otherwise it delegates to the underlying ContainerRuntime.AcquireWithProgress for a cold start with progress reporting.

func (*InstancePool) CanHandle

func (p *InstancePool) CanHandle(runtimeID string) bool

CanHandle delegates to the underlying runtime.

func (*InstancePool) EvictFunction

func (p *InstancePool) EvictFunction(name string)

EvictFunction closes and removes the warm instance for the named function, if any. Called by DeleteFunction so the container does not linger after deletion.

func (*InstancePool) Release

func (p *InstancePool) Release(_ context.Context, inst RuntimeInstance, healthy bool)

Release returns inst to the pool after an invocation. If the instance is healthy it is stored for reuse; otherwise it is closed. Implements the Runtime interface — inst.FunctionName() is used as the pool key.

func (*InstancePool) Stop

func (p *InstancePool) Stop()

Stop shuts down the background sweeper. It does not close existing instances.

type InvokeResult

type InvokeResult struct {
	// StatusCode is the HTTP status code returned by the function handler.
	StatusCode int
	// Payload is the raw JSON response body.
	Payload []byte
	// FunctionError is non-empty if the function returned an error response
	// (i.e. X-Amz-Function-Error: Handled or Unhandled).
	FunctionError string
	// LogResult contains base64-encoded tail log output (last 4KB).
	LogResult string
	// LogGroupName is the CloudWatch log group for this function.
	LogGroupName string
	// LogStreamName is the specific log stream produced by this invocation.
	LogStreamName string
	// contains filtered or unexported fields
}

InvokeResult holds the outcome of a Lambda invocation.

type LayerContentFetcher

type LayerContentFetcher func(ctx context.Context, layerVersionARN string) ([]byte, error)

LayerContentFetcher returns layer zip bytes for a layer version ARN. The returned bytes should be an immutable copy owned by the caller.

type LayerVersion

type LayerVersion struct {
	LayerName               string   `json:"layer_name"`
	LayerARN                string   `json:"layer_arn"`
	LayerVersionARN         string   `json:"layer_version_arn"`
	Version                 int64    `json:"version"`
	Description             string   `json:"description,omitempty"`
	CreatedDate             string   `json:"created_date"`
	CompatibleRuntimes      []string `json:"compatible_runtimes,omitempty"`
	CompatibleArchitectures []string `json:"compatible_architectures,omitempty"`
	// Content stores the raw zip bytes.
	Content []byte `json:"content,omitempty"`
	// CodeSize is the byte length of Content.
	CodeSize int64 `json:"code_size"`
}

LayerVersion is the domain model for a published Lambda layer version.

type LayerVersionLink struct {
	ARN                      string `json:"Arn"`
	CodeSize                 int64  `json:"CodeSize"`
	SigningProfileVersionARN string `json:"SigningProfileVersionArn,omitempty"`
	SigningJobARN            string `json:"SigningJobArn,omitempty"`
}

LayerVersionLink is a reference to a specific layer version attached to a function. The struct mirrors the AWS FunctionConfiguration.Layers shape so it serialises directly into wire responses without a conversion step.

type NodeRuntime

type NodeRuntime struct {
	// contains filtered or unexported fields
}

NodeRuntime is a stub Runtime for Node.js functions.

func (*NodeRuntime) Acquire

func (rt *NodeRuntime) Acquire(_ context.Context, fn *Function) (RuntimeInstance, error)

Acquire returns a stub RuntimeInstance. The real implementation will start a container via the Docker daemon and wait for the Lambda Runtime API to be ready.

func (*NodeRuntime) CanHandle

func (rt *NodeRuntime) CanHandle(runtimeID string) bool

CanHandle returns true for all currently supported Node.js runtime identifiers. nodejs18.x is excluded — it reached end-of-life on 2025-04-30 and is no longer supported by AWS Lambda. Attempting to create a function with nodejs18.x will return an InvalidParameterValueException, matching AWS behaviour.

func (*NodeRuntime) Release

func (rt *NodeRuntime) Release(_ context.Context, _ RuntimeInstance, _ bool)

Release is a no-op for the stub. The real implementation will return the container to a warm pool (healthy=true) or stop/remove it (healthy=false).

type OnFailure

type OnFailure struct {
	Destination string `json:"Destination"`
}

OnFailure specifies the destination for records of failed invocations.

type ProgressFunc

type ProgressFunc func(step string)

ProgressFunc is called by AcquireWithProgress to report lifecycle steps to the caller (e.g. an SSE endpoint streaming progress to the UI).

type ProvisionedConcurrencyConfig

type ProvisionedConcurrencyConfig struct {
	FunctionName                             string `json:"function_name"`
	Qualifier                                string `json:"qualifier"`
	RequestedProvisionedConcurrentExecutions int    `json:"requested"`
	LastModified                             string `json:"last_modified"`
}

ProvisionedConcurrencyConfig is the domain model for a provisioned concurrency setting.

type RemoteLayerFetcher

type RemoteLayerFetcher struct {
	// contains filtered or unexported fields
}

RemoteLayerFetcher downloads Lambda layers from real AWS and caches them.

func NewRemoteLayerFetcher

func NewRemoteLayerFetcher(cfg *config.Config, logger *zap.Logger, clk clock.Clock) *RemoteLayerFetcher

NewRemoteLayerFetcher creates a fetcher configured from the app config.

func (*RemoteLayerFetcher) FetchLayer

func (f *RemoteLayerFetcher) FetchLayer(ctx context.Context, layerVersionARN string) ([]byte, error)

FetchLayer downloads the layer zip for the given ARN. It checks the disk cache first. Returns the raw zip bytes.

type Runtime

type Runtime interface {
	// CanHandle returns true if this runtime can execute functions with the
	// given runtime identifier (e.g. "nodejs20.x", "nodejs22.x").
	CanHandle(runtimeID string) bool

	// Acquire returns a warm RuntimeInstance ready to serve one invocation.
	// It may start a new container if no warm instance is available.
	Acquire(ctx context.Context, fn *Function) (RuntimeInstance, error)

	// Release returns the instance to the pool (healthy=true) or destroys it
	// (healthy=false, e.g. after a crash or timeout).
	Release(ctx context.Context, inst RuntimeInstance, healthy bool)
}

Runtime is the Strategy interface for Lambda execution environments. It follows a two-level lifecycle: the Runtime manages the pool of warm instances; a RuntimeInstance executes a single invocation.

Sequence:

inst, err := runtime.Acquire(ctx, fn)  // get or start a warm container
result, err := inst.Invoke(ctx, event) // run the handler
runtime.Release(ctx, inst, err == nil) // return or discard the instance

type RuntimeAPIServer

type RuntimeAPIServer struct {

	// OnFirstNext is called (in a goroutine) the first time a container's RIC
	// issues GET /next.  The argument is the function ARN.  Setting this lets
	// the instance tracker transition the instance from "initializing" to
	// "running".
	OnFirstNext func(functionARN string)
	// contains filtered or unexported fields
}

RuntimeAPIServer serves the Lambda Runtime API to containers.

func NewRuntimeAPIServer

func NewRuntimeAPIServer(listenAddr string, containerAddr string, logger *zap.Logger, clk clock.Clock) (*RuntimeAPIServer, error)

NewRuntimeAPIServer creates and starts the Runtime API server. listenAddr is the address to bind to (e.g. "0.0.0.0:9001"). containerAddr is the host:port that containers use to reach this server (may differ from listenAddr when Overcast runs inside Docker).

func NewRuntimeAPIServerFromListener

func NewRuntimeAPIServerFromListener(ln net.Listener, containerAddr string, logger *zap.Logger, clk clock.Clock) (*RuntimeAPIServer, error)

NewRuntimeAPIServerFromListener is like NewRuntimeAPIServer but accepts a pre-created listener. This allows the caller to bind first (e.g. to resolve port 0) and then derive containerAddr from the actual port.

func (*RuntimeAPIServer) Addr

func (s *RuntimeAPIServer) Addr() string

Addr returns the host:port that containers should use to reach this server.

func (*RuntimeAPIServer) CancelInvocation

func (s *RuntimeAPIServer) CancelInvocation(reqID string)

CancelInvocation removes a pending invocation from the map and closes its ResultCh so that any goroutine blocked on <-resultCh is unblocked. This must be called when the container crashes or the invoke times out to prevent goroutine leaks from drain goroutines that would otherwise block forever.

func (*RuntimeAPIServer) ReadyChan

func (s *RuntimeAPIServer) ReadyChan(containerIP string) <-chan struct{}

func (*RuntimeAPIServer) RegisterContainer

func (s *RuntimeAPIServer) RegisterContainer(containerIP, functionARN string)

RegisterContainer maps the container's IP address to a function ARN so that incoming GET /next requests from that container can be routed to the correct invocation queue. Call this as soon as Docker has assigned the container IP.

func (*RuntimeAPIServer) Stop

func (s *RuntimeAPIServer) Stop(ctx context.Context) error

Stop gracefully shuts down the Runtime API server.

func (*RuntimeAPIServer) SubmitInvocation

func (s *RuntimeAPIServer) SubmitInvocation(functionARN string, event []byte, deadline time.Time) (string, <-chan invokeResponse)

SubmitInvocation enqueues an invocation for a container to pick up. It returns the request ID and a channel that will receive the result.

func (*RuntimeAPIServer) UnregisterContainer

func (s *RuntimeAPIServer) UnregisterContainer(containerIP string)

UnregisterContainer removes the container IP from the registry.

type RuntimeInfo

type RuntimeInfo struct {
	ID             string `json:"id"`
	Name           string `json:"name"`
	Family         string `json:"family"`
	DefaultHandler string `json:"defaultHandler"`
	ImageURI       string `json:"imageUri,omitempty"`
	Deprecated     bool   `json:"deprecated"`
	// Supported indicates the emulator can actually execute this runtime.
	Supported bool `json:"supported"`
}

RuntimeInfo describes a Lambda runtime with its metadata.

type RuntimeInstance

type RuntimeInstance interface {
	// Invoke sends the event payload to the function handler and returns the
	// result. The instance is exclusive to the caller for the duration.
	Invoke(ctx context.Context, event []byte) (*InvokeResult, error)

	// LogStreamName returns the CloudWatch Logs stream name for this container
	// instance. The name is assigned when the instance starts and remains fixed
	// for its lifetime. Format: YYYY/MM/DD/[$LATEST]<26-char hex>
	LogStreamName() string

	// Healthy reports whether the instance is usable after the last invocation.
	Healthy() bool

	// FunctionName returns the name of the Lambda function this instance runs.
	// Used by InstancePool.Release to key the pool without requiring *Function.
	FunctionName() string

	// CodeHash returns the SHA-256 of the deployment package this instance was
	// built from. Used by InstancePool to detect stale instances after code updates.
	CodeHash() string

	// Close shuts down and removes the underlying container or process.
	Close() error
}

RuntimeInstance represents a single warm Lambda container (or process) that can execute exactly one invocation at a time.

type S3FetchFunc

type S3FetchFunc func(ctx context.Context, bucket, key string) ([]byte, error)

S3FetchFunc retrieves the raw bytes of an S3 object from the emulated S3 service. Provided by the router as a closure over the S3 service so that the lambda package does not import the s3 package directly.

type ScalingConfig

type ScalingConfig struct {
	// MaximumConcurrency caps the number of concurrent Lambda invocations driven
	// by this ESM. 0 means unlimited. SQS sources only (2–1000 in AWS).
	MaximumConcurrency int `json:"MaximumConcurrency"`
}

ScalingConfig controls the maximum concurrency for an SQS event source mapping. It mirrors the AWS Lambda ScalingConfig wire format.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service implements router.Service for Lambda.

func New

func New(cfg *config.Config, store state.Store, logger *zap.Logger, clk clock.Clock) *Service

New returns a configured Lambda Service with all supported runtimes registered. Docker availability is checked in the background — the service starts immediately using the stub NodeRuntime and upgrades to ContainerRuntime once Docker is confirmed reachable. Other services are never blocked.

func (*Service) InitBus

func (s *Service) InitBus(b *events.Bus)

InitBus wires the event bus so Lambda lifecycle events (FunctionCreated, FunctionDeleted, FunctionUpdated) are published for topology and UI consumers. Called by the router after all services are constructed.

func (*Service) InitESMDelivery

func (s *Service) InitESMDelivery(receiver events.MessageReceiver, enqueuer events.MessageEnqueuer, bus *events.Bus)

InitESMDelivery wires SQS→Lambda and DynamoDB Streams→Lambda event delivery. Called by the router after all services are constructed and the event bus is available. receiver may be nil when the SQS service is not loaded.

func (*Service) InitLogWriter

func (s *Service) InitLogWriter(lw events.LogWriter)

InitLogWriter wires the CloudWatch Logs writer so Lambda invocations can write START/log/END/REPORT lines without importing the logs package. Called by the router after all services are constructed.

func (*Service) InitS3Sync

func (s *Service) InitS3Sync(fetch S3FetchFunc)

InitS3Sync wires S3-reactive code sync. When an S3 object that matches a function's CodeS3Bucket/CodeS3Key is uploaded, the function's CodeZip is refreshed automatically and the warm pool is invalidated on the next invoke.

Must be called after InitBus; if the bus has not been set this is a no-op.

func (*Service) Invoker

func (s *Service) Invoker() *ServiceInvoker

Invoker returns the FunctionInvoker for this Lambda service. Used by other services (e.g. S3 notifications) to invoke Lambda functions without creating an import cycle.

func (*Service) Name

func (s *Service) Name() string

func (*Service) PathPrefixes

func (s *Service) PathPrefixes() []string

PathPrefixes implements router.PathPrefixService. When Lambda is disabled, the router registers a 503 ServiceDisabled handler at this prefix so requests don't fall through to S3's /{bucket}/* wildcard and return XML errors.

func (*Service) RegisterRoutes

func (s *Service) RegisterRoutes(r chi.Router)

RegisterRoutes mounts Lambda REST endpoints. Lambda uses versioned REST paths, not a single-dispatch target header.

func (*Service) SetVPCResolver

func (s *Service) SetVPCResolver(r VPCNetworkResolver)

SetVPCResolver wires the EC2 VPC resolver so Lambda can look up subnet→VPC mappings and connect containers to VPC Docker networks.

func (*Service) Stop

func (s *Service) Stop(ctx context.Context)

Stop shuts down the Runtime API server and any background resources.

func (*Service) SyncInvoker

func (s *Service) SyncInvoker() events.FunctionSyncInvoker

SyncInvoker returns the FunctionSyncInvoker for this Lambda service. Used by API Gateway to invoke Lambda functions synchronously and receive the response payload.

func (*Service) WaitReady

func (s *Service) WaitReady()

WaitReady blocks until the background Docker runtime initialisation has completed (successfully or not). Production callers should never need this; it exists so integration tests can ensure the ContainerRuntime is wired before invoking functions.

type ServiceInvoker

type ServiceInvoker struct {
	// contains filtered or unexported fields
}

ServiceInvoker implements events.FunctionInvoker for the Lambda service.

func (*ServiceInvoker) InitBus

func (inv *ServiceInvoker) InitBus(b *events.Bus, clk clock.Clock)

InitBus wires the event bus and clock so the invoker can publish ServiceError events for invocation failures that would otherwise only appear in server logs.

func (*ServiceInvoker) Invoke

func (inv *ServiceInvoker) Invoke(ctx context.Context, functionName string, payload []byte) (*events.InvokeOutcome, error)

Invoke executes the named function synchronously and returns the result. Satisfies events.FunctionSyncInvoker. If the function is not found, no runtime is available, or the container fails to start, (nil, nil) is returned and the issue is logged — consistent with InvokeAsync's fail-silent approach for missing configuration.

A non-nil *events.InvokeOutcome with FunctionError != "" means the function ran but returned a handled or unhandled error; the caller should decide whether to retry or discard the event.

func (*ServiceInvoker) InvokeAsync

func (inv *ServiceInvoker) InvokeAsync(ctx context.Context, functionARN string, payload []byte) error

InvokeAsync satisfies events.FunctionInvoker. It is safe to call from any goroutine.

type TestEvent

type TestEvent struct {
	Name         string `json:"name"`
	FunctionName string `json:"function_name"`
	Body         string `json:"body"` // JSON event payload
}

TestEvent is a saved test event payload associated with a Lambda function.

type VPCNetworkResolver

type VPCNetworkResolver interface {
	// VpcIDForSubnet returns the VPC ID that owns the given subnet.
	VpcIDForSubnet(ctx context.Context, subnetID string) string
	// VPCNetworkStatus returns the launchability status for the VPC.
	VPCNetworkStatus(ctx context.Context, vpcID string) string
	// DockerNetworkForVpc returns the Docker network ID for the given VPC.
	// Returns empty string if the VPC has no Docker network.
	DockerNetworkForVpc(ctx context.Context, vpcID string) string
}

VPCNetworkResolver resolves VPC configuration for Lambda functions. Implemented by the EC2 service; nil when EC2 is not enabled.

type VpcConfig

type VpcConfig struct {
	SubnetIds        []string `json:"SubnetIds,omitempty"`
	SecurityGroupIds []string `json:"SecurityGroupIds,omitempty"`
	VpcId            string   `json:"VpcId,omitempty"`
}

VpcConfig associates a Lambda function with a VPC.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL