lambda

package
v0.0.1-alpha.41 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2026 License: MIT Imports: 53 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	OpCreateFunction              = "CreateFunction"
	OpUpdateFunctionCode          = "UpdateFunctionCode"
	OpUpdateFunctionConfiguration = "UpdateFunctionConfiguration"
	OpCreateEventSourceMapping    = "CreateEventSourceMapping"
	OpUpdateEventSourceMapping    = "UpdateEventSourceMapping"
)

Lambda operation names used as keys by UnsupportedRequestMembers. They are the AWS operation names, so a caller can line them up with the API it is dispatching to.

Variables

This section is empty.

Functions

func UnsupportedRequestMembers

func UnsupportedRequestMembers() map[string][]string

UnsupportedRequestMembers reports the modeled request members each Lambda operation refuses with a 501, keyed by AWS operation name and sorted.

It exists so that another package can check itself against Lambda's real gate rather than a copy of it: a caller that forwards one of these members produces a request that can only ever fail. CloudFormation's provisioner is the caller that matters — see TestLambdaProvisionerForwardsOnlyReviewedGatedMembers.

Types

type AllowedPublishers

type AllowedPublishers struct {
	SigningProfileVersionArns []string `json:"SigningProfileVersionArns"`
}

AllowedPublishers lists the signing profiles whose signatures are accepted. AWS requires between 1 and 20.

type CodeFetcher

type CodeFetcher func(ctx context.Context, fn *Function) error

CodeFetcher populates fn.CodeZip with the stored deployment package. The package lives under its own store key (see lambdaStore.loadFunctionCode) so the invoke path never carries it; a cold start is the point where the bytes are actually needed.

type CodeSigningConfig

type CodeSigningConfig struct {
	CodeSigningConfigID  string               `json:"CodeSigningConfigId"`
	CodeSigningConfigArn string               `json:"CodeSigningConfigArn"`
	Description          string               `json:"Description,omitempty"`
	AllowedPublishers    AllowedPublishers    `json:"AllowedPublishers"`
	CodeSigningPolicies  *CodeSigningPolicies `json:"CodeSigningPolicies,omitempty"`
	LastModified         string               `json:"LastModified"`
}

CodeSigningConfig is the domain model for a code signing configuration. The JSON tags are the wire names, so it serialises straight into responses.

type CodeSigningPolicies

type CodeSigningPolicies struct {
	UntrustedArtifactOnDeployment string `json:"UntrustedArtifactOnDeployment,omitempty"`
}

CodeSigningPolicies decides what happens when a signature check fails at deploy time. Overcast never runs those checks, but the setting round-trips so configuration-as-code reads back what it wrote.

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,
	maxConcurrentStarts int,
	instances *serviceutil.InstanceDomain,
) *ContainerRuntime

NewContainerRuntime creates a ContainerRuntime. The Docker client and RuntimeAPIServer must already be initialised. maxConcurrentStarts bounds concurrent container creation/INIT bursts; the caller resolves it from LAMBDA_DOCKER_MAX_CONCURRENT_STARTS or the Docker host (see resolveRuntimeLimits).

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) AcquireProactive

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

AcquireProactive creates an environment ahead of any invocation, mirroring AWS's documented proactive initialization. Two deliberate differences from Acquire: cold-start capacity is try-acquired (errColdStartBusy instead of waiting — proactive work never queues ahead of real invocations), and the environment records no invoke-triggered init start, so its first REPORT line omits Init Duration — exactly what a proactively initialized environment looks like on AWS. AWS_LAMBDA_INITIALIZATION_TYPE stays "on-demand", also matching AWS.

func (*ContainerRuntime) AcquireProvisioned

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

AcquireProvisioned creates an environment for a provisioned concurrency reservation. Identical to Acquire except that the container reports AWS_LAMBDA_INITIALIZATION_TYPE=provisioned-concurrency, as it would on AWS.

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 every runtime the catalog maps to an official Lambda base image — activeRuntimes is derived from lambdaRuntimeCatalog in runtime_catalog.go — and for PackageType=Image functions (runtimeID "image").

func (*ContainerRuntime) InitVolumeProblems

func (cr *ContainerRuntime) InitVolumeProblems() []docker.VolumeOwnershipProblem

InitVolumeProblems returns every init volume this instance has reused that is labelled for a different instance, or not labelled with an owner at all — sorted by volume name for stable output. Read by the health/advisory machinery (see lambda.Service.InitVolumeProblems). Empty once every such volume is either pruned by its own owner or reseeded (and so reclaimed) by this one.

func (*ContainerRuntime) PrefillArtifacts

func (cr *ContainerRuntime) PrefillArtifacts(ctx context.Context, fn *Function)

PrefillArtifacts builds and caches fn's cold-start artifacts (code tar and layer tars) ahead of the next cold start. Called from the settle debounce after deploys — never on the invoke path — so the first cold start of a new code version skips the package fetch and conversion the same way later ones do. Best-effort: on any miss the cold start simply builds the artifact itself, as before.

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 in parallel so the first cold start of a 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.

Only runtimes AWS still supports are seeded. Overcast can execute every runtime AWS still lets you deploy, including ones already past their deprecation date, but pre-pulling all of them would cost several extra gigabytes for images almost nobody deploys. A deprecated runtime is still pulled on demand at its first cold start.

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) SetCodeFetcher

func (cr *ContainerRuntime) SetCodeFetcher(fetcher CodeFetcher)

SetCodeFetcher wires deployment-package retrieval for container cold starts.

func (*ContainerRuntime) SetEFSResolver

func (cr *ContainerRuntime) SetEFSResolver(r EFSVolumeResolver)

SetEFSResolver wires the EFS volume resolver for mounting file-system volumes declared in FileSystemConfigs.

func (*ContainerRuntime) SetImageResolver

func (cr *ContainerRuntime) SetImageResolver(r docker.ImageResolver)

SetImageResolver wires the registry resolver used when a function's image names a registry Overcast serves rather than a public one — a container image built and pushed by CDK, whose ImageUri points at real AWS. Implemented by the ECR service. Safe to call at any time; picked up by the next pull.

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) SetRuntimeAPIReachability

func (cr *ContainerRuntime) SetRuntimeAPIReachability(l containerendpoint.Listen, hintPath string)

SetRuntimeAPIReachability records how the Runtime API address was established, so an INIT failure can quote the verdict rather than leaving the reader to guess at the one number the runtime gives them.

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) TarCacheStats

func (cr *ContainerRuntime) TarCacheStats() (entries int, bytes, maxBytes int64)

TarCacheStats reports the artifact cache's entry count, resident bytes, and byte budget, for the lambda debug endpoint.

func (*ContainerRuntime) ThrottleInitBurst

func (cr *ContainerRuntime) ThrottleInitBurst(containerID string)

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

type CorsConfig

type CorsConfig struct {
	AllowCredentials *bool    `json:"allow_credentials,omitempty"`
	AllowHeaders     []string `json:"allow_headers,omitempty"`
	AllowMethods     []string `json:"allow_methods,omitempty"`
	AllowOrigins     []string `json:"allow_origins,omitempty"`
	ExposeHeaders    []string `json:"expose_headers,omitempty"`
	MaxAge           *int     `json:"max_age,omitempty"`
}

CorsConfig mirrors AWS's Cors shape for a function URL config. Overcast stores and returns it faithfully but does not enforce it — see docs/networking/host-routing.md's AuthType/CORS caveat.

type DestinationConfig

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

DestinationConfig specifies where to send records of an invocation's outcome. Mirrors the AWS Lambda DestinationConfig structure, which is one shape serving two features: an event source mapping's on-failure destination, and a function's asynchronous invocation destinations (see store_event_invoke.go).

An ESM only ever sets OnFailure — AWS gives a mapping no on-success destination — so OnSuccess is nil on that path and available on this one.

type EFSVolumeResolver

type EFSVolumeResolver interface {
	EFSVolumeForAccessPoint(ctx context.Context, accessPointARN string) (volume, subpath string, ok bool)
}

EFSVolumeResolver maps an EFS access-point ARN to the Docker volume backing its file system plus the access point's root directory as a volume subpath ("" for the volume root). Implemented by the EFS service; ok is false in mock mode, while Docker is unavailable, or for an unknown access point — callers then skip the mount and the function runs without shared storage.

type EventInvokeConfig

type EventInvokeConfig struct {
	FunctionName string `json:"function_name"`
	// Qualifier is "" for the unqualified function, otherwise a version number
	// or alias name. It is part of the key, not just data.
	Qualifier string `json:"qualifier,omitempty"`
	// FunctionArn is the qualified ARN when Qualifier is set, so a response
	// names the exact thing that was configured.
	FunctionArn              string             `json:"function_arn"`
	MaximumRetryAttempts     *int               `json:"maximum_retry_attempts,omitempty"`
	MaximumEventAgeInSeconds *int               `json:"maximum_event_age_in_seconds,omitempty"`
	DestinationConfig        *DestinationConfig `json:"destination_config,omitempty"`
	// LastModifiedUnix is Unix seconds, because that is what AWS returns for
	// this resource — unlike FunctionConfiguration.LastModified, which is an
	// RFC 3339 string. Storing it in the wire's own units keeps the conversion
	// out of the handler.
	LastModifiedUnix int64 `json:"last_modified_unix"`
}

EventInvokeConfig is the domain model behind Put/Get/Update/Delete/ListFunctionEventInvokeConfigs.

The two limits are pointers because "unset" and "zero" are different settings and AWS reports them differently: an absent MaximumRetryAttempts means the default of two, while an explicit 0 means do not retry at all. Collapsing them would silently turn "do not retry" into "retry twice", which is the opposite of what the caller asked for.

type EventSourceMapping

type EventSourceMapping struct {
	// UUID is the primary key assigned at creation time.
	UUID string `json:"UUID"`
	// EventSourceMappingArn is the full ARN assigned to the mapping.
	EventSourceMappingArn string `json:"EventSourceMappingArn"`
	// 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"`
	// BatchSizeExplicit records whether BatchSize was supplied by the caller.
	// AWS permits the omitted DynamoDB/Kinesis default of 100 with a zero-second
	// batching window, while an explicitly configured value above 10 requires a
	// nonzero window. This internal distinction is persisted but never returned.
	BatchSizeExplicit bool `json:"-"`
	// 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"`
	// FunctionResponseTypes opts the mapping into partial-batch failure
	// reporting. AWS models exactly one value, "ReportBatchItemFailures":
	// with it set, the poller reads the function's response and acknowledges
	// only the records the function did not report as failed. Poll-based
	// sources only — see esm_delivery.go.
	FunctionResponseTypes []string `json:"FunctionResponseTypes,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 FileSystemConfig

type FileSystemConfig struct {
	Arn            string `json:"Arn"`
	LocalMountPath string `json:"LocalMountPath"`
}

FileSystemConfig mirrors the AWS FileSystemConfig shape: an EFS access point mounted at a /mnt path inside the function's execution environment. https://docs.aws.amazon.com/lambda/latest/api/API_FileSystemConfig.html

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 is the deployment package. Only two writers are legitimate:
	// setCode when the package *changes* (it keeps CodeSize and CodeHash in
	// step — identity checks trust CodeHash, so a bare assignment would leave
	// warm containers serving stale code), and lambdaStore.loadFunctionCode
	// when materializing the already-stored package. The package is persisted
	// under its own store key, so records read on the invoke path carry no
	// bytes here — call loadFunctionCode before paths that need them.
	CodeZip  []byte `json:"code_zip,omitempty"` // base64-decoded zip
	CodeSize int64  `json:"code_size,omitempty"`
	// CodeHash is the hex SHA-256 of CodeZip, maintained by setCode. It is what
	// functionCodeIdentity and CodeSha256 responses read, so the invoke path
	// never rehashes the package. "" only on records persisted before the field
	// existed, where readers fall back to hashing CodeZip.
	CodeHash string `json:"code_hash,omitempty"`
	// CodeGeneration changes only for explicit code-source writes. Reactive
	// S3 refreshes preserve it so concurrent object events can be ordered while
	// every manual/inline update—including one with identical bytes—fences out
	// fetches that started against the previous generation.
	CodeGeneration string `json:"code_generation,omitempty"`
	CodeS3Bucket   string `json:"code_s3_bucket,omitempty"`
	CodeS3Key      string `json:"code_s3_key,omitempty"`
	// CodeS3ObjectVersion pins the deployment package to one immutable version
	// of CodeS3Key. Empty means "whatever is current", which is also what makes
	// the function eligible for reactive S3 code sync — a pinned function must
	// not be refreshed when a new version lands at its key.
	CodeS3ObjectVersion string   `json:"code_s3_object_version,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"
	// LastUpdateStatus is the outcome of the most recent update to the
	// function — "InProgress", "Successful" or "Failed" — and is what AWS's
	// FunctionUpdated waiter polls. Empty only while creation is still
	// running: AWS first sets it to Successful once the create completes. The
	// update-lifecycle block in handler_functions.go says which updates pass
	// through InProgress and which are already done when they answer.
	LastUpdateStatus string `json:"last_update_status,omitempty"`
	// LastUpdateStatusReason and LastUpdateStatusReasonCode explain a
	// LastUpdateStatus that is not Successful, the way StateReason and
	// StateReasonCode explain a State that is not Active. The code is one of
	// AWS's own — ImageAccessDenied, InvalidImage, InternalError.
	LastUpdateStatusReason     string `json:"last_update_status_reason,omitempty"`
	LastUpdateStatusReasonCode string `json:"last_update_status_reason_code,omitempty"`

	RevisionId          string             `json:"revision_id,omitempty"`
	CreationID          string             `json:"creation_id,omitempty"`
	LastModified        string             `json:"last_modified,omitempty"`
	LogGroup            string             `json:"log_group,omitempty"` // Custom log group; defaults to /aws/lambda/{name}
	LogFormat           string             `json:"log_format,omitempty"`
	ApplicationLogLevel string             `json:"application_log_level,omitempty"`
	SystemLogLevel      string             `json:"system_log_level,omitempty"`
	Layers              []LayerVersionLink `json:"layers,omitempty"` // Attached layer versions (empty until layers are implemented)
	// CodeSigningConfigArn is the code signing configuration associated with
	// the function, or "" when there is none — the usual case, since code
	// signing is opt-in. Stored and echoed back so SDKs and CDK read the
	// association they set; signature validation itself is deliberately not
	// emulated (Overcast is not a security boundary).
	CodeSigningConfigArn string `json:"code_signing_config_arn,omitempty"`
	// 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"`
	// FileSystemConfigs are the EFS access points mounted into the function.
	// Stored and echoed on the wire in every mode; when EFS live mode is
	// active, the container runtime binds each backing volume at
	// LocalMountPath so invocations share real file data.
	FileSystemConfigs []FileSystemConfig `json:"file_system_configs,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"`
	// TracingMode is the X-Ray tracing mode ("Active" or "PassThrough"), or ""
	// for a function that never set one. There is no X-Ray service in Overcast,
	// so the mode is recorded and echoed and changes nothing about execution —
	// accepting it claims nothing a caller can observe as false, and rejecting
	// it broke every CDK deploy with tracing enabled.
	TracingMode string `json:"tracing_mode,omitempty"`
	// EphemeralStorageSize is the configured /tmp size in MB, or 0 for a
	// function that never set one (AWS's default is 512). Recorded and echoed;
	// the container's /tmp is not actually capped to it.
	EphemeralStorageSize int `json:"ephemeral_storage_size,omitempty"`
	// KMSKeyArn is the customer managed key recorded for the function.
	// Environment variables are stored in plaintext regardless — Overcast is
	// not a security boundary — so this is association metadata only.
	KMSKeyArn string `json:"kms_key_arn,omitempty"`
	// DeadLetterTargetArn is the SQS queue or SNS topic an asynchronous
	// invocation is sent to once it has failed, or "" for a function with no
	// dead-letter queue. See dead_letter.go for what is delivered to it.
	DeadLetterTargetArn string `json:"dead_letter_target_arn,omitempty"`
}

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

func (*Function) GetTags

func (f *Function) GetTags() map[string]string

func (*Function) SetTags

func (f *Function) SetTags(t map[string]string)

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 FunctionURLConfig

type FunctionURLConfig struct {
	FunctionName     string      `json:"function_name"`
	FunctionArn      string      `json:"function_arn"`
	Qualifier        string      `json:"qualifier,omitempty"`
	AuthType         string      `json:"auth_type"` // "NONE" or "AWS_IAM" — accepted but never enforced, see docs.
	Cors             *CorsConfig `json:"cors,omitempty"`
	InvokeMode       string      `json:"invoke_mode"` // "BUFFERED" (only mode supported) or "RESPONSE_STREAM"
	UrlID            string      `json:"url_id"`
	Region           string      `json:"region"`
	CreationTime     string      `json:"creation_time"`
	LastModifiedTime string      `json:"last_modified_time"`
}

FunctionURLConfig is a Lambda function URL configuration (CreateFunctionUrlConfig).

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) AddPermission

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

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) CreateCodeSigningConfig

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

CreateCodeSigningConfig handles POST /2020-04-22/code-signing-configs/.

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) CreateFunctionUrlConfig

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

CreateFunctionUrlConfig handles POST /2021-10-31/functions/{name}/url.

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) DeleteCodeSigningConfig

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

DeleteCodeSigningConfig handles DELETE /2020-04-22/code-signing-configs/{arn}. A configuration still referenced by a function cannot be deleted — AWS answers ResourceConflictException, and deploy tooling relies on that to order teardown correctly.

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}[?Qualifier=].

AWS: "Deletes a Lambda function. To delete a specific function version, use the Qualifier parameter. Otherwise, all versions and aliases are deleted." (API_DeleteFunction.html). The qualifier may equally arrive as part of the NamespacedFunctionName path label — "my-function:1".

func (*Handler) DeleteFunctionCodeSigningConfig

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

DeleteFunctionCodeSigningConfig handles DELETE /2020-06-30/functions/{name}/code-signing-config. Returns 204 with an empty body, and is idempotent: removing an association that is not there is not an error.

func (*Handler) DeleteFunctionConcurrency

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

DeleteFunctionConcurrency handles DELETE /2017-10-31/functions/{name}/concurrency.

func (*Handler) DeleteFunctionEventInvokeConfig

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

DeleteFunctionEventInvokeConfig handles DELETE on the same path, answering 204 with no body.

func (*Handler) DeleteFunctionUrlConfig

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

DeleteFunctionUrlConfig handles DELETE /2021-10-31/functions/{name}/url.

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) DeleteProvisionedConcurrencyConfig

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

DeleteProvisionedConcurrencyConfig handles DELETE /2019-09-30/functions/{name}/provisioned-concurrency.

func (*Handler) DeleteResourcePolicy

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

DeleteResourcePolicy handles DELETE /2026-07-09/resource-policy/{ResourceArn}.

func (*Handler) DeleteTestEvent

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

DeleteTestEvent handles DELETE /_overcast/lambda/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) GetCodeSigningConfig

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

GetCodeSigningConfig handles GET /2020-04-22/code-signing-configs/{arn}.

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 /2020-06-30/functions/{name}/code-signing-config.

A function with no configuration returns ResourceNotFoundException rather than an empty success: CodeSigningConfigArn is a required member of the 200 response, so "no config" has no representation as a successful result, and ResourceNotFoundException is the only not-found error this operation declares (CodeSigningConfigNotFoundException is declared on the mutating operations, not this one).

func (*Handler) GetFunctionConcurrency

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

GetFunctionConcurrency handles GET /2019-09-30/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) GetFunctionEventInvokeConfig

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

GetFunctionEventInvokeConfig handles GET /2019-09-25/functions/{name}/event-invoke-config.

func (*Handler) GetFunctionMetrics

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

GetFunctionMetrics handles GET /_overcast/lambda/functions/{name}/metrics. ?range= is one of "1h" (default), "6h", "24h", "7d", "30d" — see metrics.ParseChartRange.

func (*Handler) GetFunctionSource

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

GetFunctionSource handles GET /_overcast/lambda/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) GetFunctionUrlConfig

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

GetFunctionUrlConfig handles GET /2021-10-31/functions/{name}/url.

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) GetLayerVersionMetadata

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

GetLayerVersionMetadata handles the emulator-only layer metadata endpoint used by the web UI.

func (*Handler) GetOrListProvisionedConcurrency

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

GetOrListProvisionedConcurrency handles GET /2019-09-30/functions/{name}/provisioned-concurrency. AWS overloads one path and method for two operations, told apart by the List query parameter, so the dispatch happens here rather than in the router.

func (*Handler) GetPolicy

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

func (*Handler) GetProvisionedConcurrencyConfig

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

GetProvisionedConcurrencyConfig handles GET /2019-09-30/functions/{name}/provisioned-concurrency.

func (*Handler) GetResourcePolicy

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

GetResourcePolicy handles GET /2026-07-09/resource-policy/{ResourceArn}.

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 /_overcast/lambda/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) InvokeFunctionURL

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

InvokeFunctionURL handles Host-routed Lambda function URL invocations — see the file doc above.

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) ListCodeSigningConfigs

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

ListCodeSigningConfigs handles GET /2020-04-22/code-signing-configs/.

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) ListFunctionEventInvokeConfigs

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

ListFunctionEventInvokeConfigs handles GET /2019-09-25/functions/{name}/event-invoke-config/list.

Pagination is a single page: MaxItems is validated so a caller that asks for an illegal one is told, but NextMarker is never returned, matching how the other list operations in this service behave at emulator scale.

func (*Handler) ListFunctionUrlConfigs

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

ListFunctionUrlConfigs handles GET /2021-10-31/functions/{name}/urls.

func (*Handler) ListFunctions

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

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

func (*Handler) ListFunctionsByCodeSigningConfig

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

ListFunctionsByCodeSigningConfig handles GET /2020-04-22/code-signing-configs/{arn}/functions.

func (*Handler) ListInstances

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

ListInstances handles GET /_overcast/lambda/instances. Returns all currently tracked instances (running + idle) across all functions, plus a snapshot of the cold-start artifact cache.

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) ListProvisionedConcurrencyConfigs

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

ListProvisionedConcurrencyConfigs handles GET /2019-09-30/functions/{name}/provisioned-concurrency?List=ALL.

func (*Handler) ListRuntimes

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

ListRuntimes handles GET /_overcast/lambda/runtimes (emulator-only). The catalog is the same table CreateFunction validates against, so what the web UI offers and what the API accepts cannot disagree.

func (*Handler) ListTestEvents

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

ListTestEvents handles GET /_overcast/lambda/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) PutFunctionCodeSigningConfig

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

PutFunctionCodeSigningConfig handles PUT /2020-06-30/functions/{name}/code-signing-config.

func (*Handler) PutFunctionConcurrency

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

PutFunctionConcurrency handles PUT /2017-10-31/functions/{name}/concurrency.

func (*Handler) PutFunctionEventInvokeConfig

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

PutFunctionEventInvokeConfig handles PUT /2019-09-25/functions/{name}/event-invoke-config.

func (*Handler) PutFunctionSource

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

PutFunctionSource handles PUT /_overcast/lambda/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 /2019-09-30/functions/{name}/provisioned-concurrency. The Qualifier query parameter is required (version number or alias name).

func (*Handler) PutResourcePolicy

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

PutResourcePolicy handles PUT /2026-07-09/resource-policy/{ResourceArn}.

func (*Handler) PutTestEvent

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

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

func (*Handler) RemovePermission

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

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.

It also closes the async path: startAsync refuses events from here on. That matters because Lambda is not the last service to stop — S3, Scheduler and the event bus all shut down after it, and any of them can still raise an event. Without the gate such an event would start a goroutine on a WaitGroup nobody is waiting on any more, against a pool and tracker this function is about to tear down.

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) UpdateCodeSigningConfig

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

UpdateCodeSigningConfig handles PUT /2020-04-22/code-signing-configs/{arn}. Every field is optional; omitted fields keep their stored value.

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.

func (*Handler) UpdateFunctionEventInvokeConfig

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

UpdateFunctionEventInvokeConfig handles POST on the same path. It merges rather than replaces.

func (*Handler) UpdateFunctionUrlConfig

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

UpdateFunctionUrlConfig handles PUT /2021-10-31/functions/{name}/url.

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 InstanceObserver

type InstanceObserver interface {
	// InstanceWarmed reports an environment created without an invocation —
	// proactive initialization or provisioned concurrency pre-warming.
	// containerID identifies the backing Docker container ("" when not
	// container-backed) so the tracker can sample its resource usage. origin
	// is one of the instanceOrigin* constants and records why the environment
	// was created, for the instances panel's origin badge.
	InstanceWarmed(functionName, instanceID, containerID, origin string)
	// InstanceLost reports an environment that no longer exists, for any
	// reason: idle sweep, reclaimed for capacity, retired after an update,
	// died in Docker, or its function was deleted. reason is one of the
	// evictReason* constants and records why, for the instances panel's
	// removal-reason display.
	InstanceLost(functionName, instanceID, reason string)
}

InstanceObserver is told about execution environments the pool creates or destroys outside an invocation, so a tracker of them can stay in step. Implemented by instanceTracker.

type InstancePool

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

InstancePool manages warm RuntimeInstances for every function.

func NewInstancePool

func NewInstancePool(rt Runtime, log *zap.Logger, clk clock.Clock, limits PoolLimits) *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 an instance for fn — reused from the warm set when one matches, cold started otherwise. Concurrent callers never share an instance.

It may block while the invocation queues behind an instance limit, and returns a TooManyRequestsException (see ThrottleError) when a concurrency limit refuses the invocation outright or ctx expires while queued.

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.

func (*InstancePool) CanHandle

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

CanHandle delegates to the underlying runtime.

func (*InstancePool) ClearProvisionedConcurrency

func (p *InstancePool) ClearProvisionedConcurrency(name string)

ClearProvisionedConcurrency removes the reservation for name. The environments it was holding open are not torn down — they lose their exemption from the idle sweep and age out like any other warm instance, matching AWS, which does not kill them the moment the config is deleted.

func (*InstancePool) EvictFunction

func (p *InstancePool) EvictFunction(name string)

EvictFunction closes and removes every warm instance for the named function, aborts the environments still being created for it, and forgets its provisioned-concurrency target. Called by DeleteFunction so containers do not linger after deletion.

An invocation still in flight is not interrupted — AWS does not either — and is destroyed on release instead, via the evicted marker.

func (*InstancePool) InvalidateFunction

func (p *InstancePool) InvalidateFunction(fn *Function) int

InvalidateFunction retires the execution environments for fn after its code or configuration changed.

  • Idle instances: closed immediately, so stale containers do not linger until the 15-minute idle sweep.
  • Instances serving an invocation: left running. AWS never interrupts an in-flight invocation to apply an update, so each finishes in the old environment and Release then destroys it instead of pooling it.
  • Identity unchanged (e.g. only the description was edited): the warm set is kept.

No on-demand replacement is started — the next invocation cold starts one. A function with provisioned concurrency is re-provisioned in the background against the new configuration, which is the point of having reserved it.

Returns the number of idle instances that were closed.

func (*InstancePool) ProactiveInit

func (p *InstancePool) ProactiveInit(fn *Function) proactiveOutcome

ProactiveInit creates one execution environment for fn ahead of traffic, mirroring AWS's documented proactive initialization. It is strictly best-effort: every budget a real invocation would consume (per-function slot, instance count, memory — including the high-water margin) is checked non-blockingly, and contention returns proactiveBusy instead of queueing, so proactive work can never delay a real invocation. The environment lands in the warm set as an ordinary on-demand instance: it is swept on idleness, retired on updates, and never counted toward provisioned reservations.

func (*InstancePool) ProvisionedStatus

func (p *InstancePool) ProvisionedStatus(name string) (requested, allocated, available int, ok bool)

ProvisionedStatus reports the reservation for name: how many environments are requested, how many exist (warm or serving an invocation), and how many are idle and immediately available. ok is false when name has no reservation.

func (*InstancePool) Release

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

Release returns inst to the warm set after an invocation. The instance is destroyed instead when it is unhealthy, when the function was updated while the invocation was in flight, or when the warm set is already full. Implements the Runtime interface — inst.FunctionName() is the pool key.

func (*InstancePool) SetProvisionedConcurrency

func (p *InstancePool) SetProvisionedConcurrency(fn *Function, target int)

SetProvisionedConcurrency reserves target execution environments for fn. They are created in the background, exempt from the idle sweep, and replenished whenever one is lost. target <= 0 clears the reservation, after which the environments become ordinary warm instances subject to the idle TTL — matching AWS, which does not tear them down instantly.

func (*InstancePool) Stop

func (p *InstancePool) Stop()

Stop shuts down the background sweeper and closes every warm instance. Idempotent for the same reason instanceTracker.Stop is: Service.Stop drives both, and is itself reachable more than once.

type InvokeOptions

type InvokeOptions struct {
	// LogTail asks for InvokeResult.LogResult to be populated. It costs invoke
	// latency: the container's stdout reaches the tail buffer through Docker's
	// log stream, which lands after the handler's response comes back over the
	// Runtime API, so producing a complete tail means waiting for it (see
	// containerInstance.waitForScannerIdle).
	//
	// Only two callers want it — InvokeFunction with X-Amz-Log-Type: Tail, and
	// the console's SSE invoke, which always renders the tail. Asynchronous
	// invokes, event-source mappings, function URLs and service-to-service
	// calls all discard LogResult, so they leave this false and pay nothing.
	LogTail bool
}

InvokeOptions carries per-invocation switches that change what the execution environment does around the handler call, as opposed to configuration that belongs to the function itself.

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
	// RequestID is the invocation's Lambda request ID — the one the runtime
	// handed the handler, and the one that appears in the function's own logs.
	// Empty for a runtime that never reached the Runtime API (the Docker-less
	// stub), and for a failure raised before the invocation was submitted.
	RequestID string

	// Duration is how long inst.Invoke's runtime round trip took — execution
	// time after function code begins, excluding cold-start/init (plan:
	// "Duration needs explicit start/end measurements in the execution
	// layer"). Zero when the function never ran (acquire/init failure,
	// throttle). Used only by recordInvocationOutcome; not part of any wire
	// response.
	Duration time.Duration
	// 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 is the layer zip. Persisted under its own key (nsLayerContent)
	// and stripped from the record by putLayerVersion; call loadLayerContent
	// before paths that need the bytes. Records persisted before the split
	// still carry it inline.
	Content []byte `json:"content,omitempty"`
	// CodeSize is the byte length of Content.
	CodeSize int64 `json:"code_size"`
	// CodeHash is the hex SHA-256 of Content, set at publish. Wire responses
	// report it in AWS's base64 form (Content.CodeSha256); "" on records
	// published before the field existed.
	CodeHash string `json:"code_hash,omitempty"`
}

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 the Node.js runtimes this stub answers for. It is deliberately narrower than the real runtime catalog (runtime_catalog.go): the stub exists only to keep the service usable while Docker is unavailable, so it mocks the current Node.js runtimes and nothing else. Which runtimes CreateFunction accepts is decided by the catalog, not here.

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 OnSuccess

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

OnSuccess specifies the destination for records of successful asynchronous invocations. AWS models it as its own shape rather than reusing OnFailure, so it is spelled out the same way here.

type PoolLimits

type PoolLimits struct {
	// MaxWarmPerFunction bounds the idle set for one function.
	MaxWarmPerFunction int
	// MaxInstances bounds containers across all functions.
	MaxInstances int
	// MaxInstancesPerFunction bounds concurrent containers for one function.
	MaxInstancesPerFunction int
	// MaxMemoryMB bounds Σ MemorySize over all live containers, in MB. Each
	// container is hard-capped at its function's MemorySize with swap disabled,
	// so this sum is a real bound on host memory, not an estimate. Zero means
	// unlimited.
	MaxMemoryMB int
}

PoolLimits bounds how many containers the pool will keep and run. Zero fields take their defaults.

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.

func (*RemoteLayerFetcher) ResolveLayerSize

func (f *RemoteLayerFetcher) ResolveLayerSize(ctx context.Context, layerVersionARN string) (int64, error)

ResolveLayerSize verifies a layer can be resolved from the documented cache paths or, when enabled, by remote fetch. It avoids reading cached zip bytes so invoke-time metadata checks stay cheap for pre-populated AWS-managed layers.

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, opts) // 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 moment that container's INIT phase ends. It is
	// told which environment reported it, not only which function: a function
	// can have several environments in INIT at once, and anything acting on
	// this (the INIT-burst throttle-down) acts on one container.
	OnFirstNext func(functionARN, containerID 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 NewRuntimeAPIServerFromListeners

func NewRuntimeAPIServerFromListeners(lns []net.Listener, containerAddr string, initTimeout time.Duration, logger *zap.Logger, clk clock.Clock) (*RuntimeAPIServer, error)

NewRuntimeAPIServerFromListeners fronts every listener with the one server, so a RIC is answered identically whichever address its request arrived on.

Several listeners rather than one wildcard is how the Runtime API stays off networks this machine merely happens to be attached to while remaining reachable from the containers that have to connect back to it: the address they dial, plus loopback. See containerendpoint.ResolveListen, which decides the set.

initTimeout is the budget an invocation gives a cold start (see lambdaInitTimeout); it bounds how long a Runtime API call waits for its container's registration, which must not outlive it.

func (*RuntimeAPIServer) AddContainerListener

func (s *RuntimeAPIServer) AddContainerListener() (*containerListener, error)

AddContainerListener binds a fresh port across the same local addresses the server already answers on, fronted by the same handler, for one execution environment's exclusive use.

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.

The invocation is also dropped from its function queue and marked cancelled. Without that it stayed queued after the caller gave up, and the next container to poll ran the handler for a request that had already been reported as timed out — real side effects, under a dead request ID, with the response then discarded because nothing was left in s.pending to route it to.

func (*RuntimeAPIServer) ContainerError

func (s *RuntimeAPIServer) ContainerError(containerIP string) (string, bool)

func (*RuntimeAPIServer) EnqueueExtensionShutdown

func (s *RuntimeAPIServer) EnqueueExtensionShutdown(containerIP, reason string, deadline time.Time) int

func (*RuntimeAPIServer) FirstNextAt

func (s *RuntimeAPIServer) FirstNextAt(containerIP string) (time.Time, bool)

FirstNextAt returns when the container's RIC issued its first GET /next — the moment the execution environment finished initialising. ok is false until that first poll arrives (or after the container is unregistered).

func (*RuntimeAPIServer) InvocationTraceID

func (s *RuntimeAPIServer) InvocationTraceID(reqID string) string

InvocationTraceID reports the X-Amzn-Trace-Id header a pending invocation's runtime receives, or "" once the invocation is no longer pending.

func (*RuntimeAPIServer) PrepareInvocation

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

PrepareInvocation registers an invocation — its ID, payload, deadline and result channel — without offering it to any execution environment. Until ReleaseInvocation, no GET /next can return it, so no log frame can carry its request ID yet. That gap is the point: the invoke path writes the invocation's START record between the two calls, which is what makes "the tail opens with START" a structural property rather than a race the invoke goroutine has to win — the handler cannot have printed a line for a request the runtime has not been handed.

func (*RuntimeAPIServer) PublishExtensionLog

func (s *RuntimeAPIServer) PublishExtensionLog(containerIP, typ, record string)

PublishExtensionLog publishes one log line — a "function" or "extension" record — to the subscribers of that type on this container.

What the record *is* depends on the subscriber. The Logs API and the oldest Telemetry schemaVersion embed the line as a string; from schemaVersion 2022-12-13 a JSON-format function's line is embedded as the JSON object it already is ("If the schema version you're using is older than the 2022-12-13 version, then the record is always rendered as a string even when your function's logging format is configured as JSON" — https://docs.aws.amazon.com/lambda/latest/dg/telemetry-schema-reference.html). A Text-format function's line stays a string for everyone, as does a line that is not itself a JSON object. Each shape is marshalled at most once, however many subscribers want it.

func (*RuntimeAPIServer) PublishInitPhaseRecord

func (s *RuntimeAPIServer) PublishInitPhaseRecord(containerIP, event string)

PublishInitPhaseRecord publishes one of the three init-phase platform events and remembers it for a subscription that has not been made yet — see RuntimeAPIServer.initRecords for why those three need that and no others.

func (*RuntimeAPIServer) PublishPlatformRecord

func (s *RuntimeAPIServer) PublishPlatformRecord(containerIP, event string)

PublishPlatformRecord publishes one platform event to the subscribers of the "platform" type. event is the complete Telemetry API event, already marshalled by the caller that owns the schema (see logging_json.go): the {"time","type","record"} envelope, whose type is the event's own — "platform.initStart", "platform.start", … — and whose record is an object. That is what AWS documents, and it is why this does not go through PublishExtensionLog, whose record is a string.

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) RegisterContainerConfig

func (s *RuntimeAPIServer) RegisterContainerConfig(containerIP string, cfg runtimeContainerConfig)

func (*RuntimeAPIServer) ReleaseInvocation

func (s *RuntimeAPIServer) ReleaseInvocation(reqID string)

ReleaseInvocation offers a prepared invocation to the function's execution environments: straight to a parked runtime when one is waiting, queued for the next GET /next otherwise. An invocation cancelled between the two calls is already gone from pending, so releasing it is a no-op.

func (*RuntimeAPIServer) Stop

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

Stop gracefully shuts down the Runtime API server. Idempotent.

func (*RuntimeAPIServer) SubmitInvocation

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

SubmitInvocation prepares an invocation and releases it in one call. It is the form for a caller with nothing to order in front of the hand-off; the invoke path uses the Prepare/Release pair so the START record is in the tail buffer before the runtime can start the handler — see PrepareInvocation.

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 reports that AWS has ended support for this runtime. AWS
	// still accepts it until CreateBlocked.
	Deprecated bool `json:"deprecated"`
	// CreateBlocked and UpdateBlocked report AWS's two later deprecation
	// phases: no new functions, then no updates to existing ones.
	CreateBlocked bool `json:"createBlocked"`
	UpdateBlocked bool `json:"updateBlocked"`
	// Supported indicates the emulator can actually execute this runtime.
	Supported bool `json:"supported"`
}

RuntimeInfo describes a Lambda runtime with its metadata. Built from lambdaRuntimeCatalog — see runtime_catalog.go.

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, opts InvokeOptions) (*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]<32-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

	// ConfigIdentity returns the fingerprint of the code and configuration this
	// instance was built from (see functionInstanceIdentity). Used by
	// InstancePool to detect instances made stale by a code or configuration
	// update.
	ConfigIdentity() string

	// ContainerID returns the Docker container backing this instance, or "" for
	// runtimes that are not container-backed. Used by InstancePool to drop a
	// pooled instance when the Docker watcher reports its container died.
	ContainerID() string

	// InstanceID returns a stable identifier for this execution environment,
	// assigned when it is created and preserved across warm reuse. It is what
	// the instance tracker keys its records by, so a function serving several
	// concurrent invocations reports one instance per environment.
	InstanceID() 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, versionID string) ([]byte, *protocol.AWSError)

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.

An empty versionID means the key's current version; a non-empty one is Code.S3ObjectVersion and selects exactly that version.

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) AddTriggerSource

func (s *Service) AddTriggerSource(src TriggerSource)

AddTriggerSource registers a service as proactive-init trigger evidence. Called by the router during cross-service wiring.

func (*Service) AuthorizeServiceInvoke

func (s *Service) AuthorizeServiceInvoke(ctx context.Context, functionRef, principal, sourceARN, sourceAccount string) *protocol.AWSError

AuthorizeServiceInvoke reports whether principal may invoke the function functionRef names, according to that function's resource-based policy. functionRef is a bare name or a function ARN, qualified or not; sourceARN and sourceAccount are the `aws:SourceArn` and `aws:SourceAccount` condition-key values the calling service contributes, either of which may be empty.

A nil return means the invocation is authorised. It is also what an unset OVERCAST_ENFORCE_LAMBDA_RESOURCE_POLICY returns, before any work at all: with the knob off this costs one field read, no store access and no allocation.

Satisfies events.FunctionInvokeAuthorizer. Callers translate a refusal into whatever their own service does when a permission is missing — S3 refuses the notification configuration, SNS dead-letters the delivery, API Gateway answers 500 — rather than surfacing this error verbatim.

func (*Service) HostRouteRewrite

func (s *Service) HostRouteRewrite(r *http.Request, m middleware.HostRouteMatch)

HostRouteRewrite adapts a Host-routed Lambda function URL invocation ({urlId}.lambda-url.{region}.{base}/...) to the emulator's internal invocation route (see handler_url_invoke.go).

This rewrite doesn't stamp a region onto the request context, but not because the region is unneeded: middleware.Region has already read it off the Host by the time this runs (regionFromHost parses the same hostRouteLabels grammar the router dispatched on). The region matters — getFunctionURLConfigByURLID scans every region, but the getFunction call right after it in InvokeFunctionURL is region-scoped, so without the hint a function URL created outside the default region resolves its config and then 404s on the function behind it.

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, 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) InitMetrics

func (s *Service) InitMetrics(m metricsRecorder)

InitMetrics wires the shared service-metrics recorder (docs/plans/service-metrics-platform.md) so every invocation path records AWS/Lambda's Invocations/Errors/Duration/Throttles/ConcurrentExecutions through recordInvocationOutcome (metrics_lambda.go). Called once from router.New, after metrics.NewRecorder — mirrors InitBus/InitLogWriter's "may run before or after Docker init completes" contract.

func (*Service) InitRouter

func (s *Service) InitRouter(router http.Handler)

InitRouter wires the root router so a dead-lettered failure can be delivered to the SQS queue or SNS topic its ARN names — a function's DeadLetterConfig.TargetArn, or an event-source mapping's DestinationConfig.OnFailure.Destination. 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 instance running the old code is retired.

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

func (*Service) InitVolumeProblems

func (s *Service) InitVolumeProblems() []docker.VolumeOwnershipProblem

InitVolumeProblems returns every Lambda init volume this instance has reused that turned out to be labelled for a different Overcast instance, or not labelled with an owner at all — see ContainerRuntime.InitVolumeProblems and issue #1573. Consumed by the router's debug/advisory endpoint (see debugLambdaProvider in internal/router/debug.go), which is why this returns docker.VolumeOwnershipProblem — a neutral type outside this package, mirroring how ec2.Service.NetworkProblems returns dataplane's type rather than one of its own — instead of a lambda-only type the router would have to import this package to read.

Empty before Docker has been probed (there is no ContainerRuntime yet to have reused anything), same as a genuinely clean instance.

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 lists every Lambda API version, so a router built with only a subset of services (test-only) answers these with a 501 rather than letting them fall through to S3's /{bucket}/* wildcard.

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) RuntimeAPIListenStatus

func (s *Service) RuntimeAPIListenStatus() (status listenstatus.Status, ok bool)

RuntimeAPIListenStatus reports how the shared Runtime API listener's bind went, for /_overcast/health. ok is false until a bind has been attempted.

func (*Service) RuntimeAPIReachability

func (s *Service) RuntimeAPIReachability() containerendpoint.Listen

RuntimeAPIReachability reports how the Runtime API address was established, for the console advisory and for the INIT-death diagnostic. The zero value means the Docker probe has not reported yet.

func (*Service) SetEFSResolver

func (s *Service) SetEFSResolver(r EFSVolumeResolver)

SetEFSResolver wires the EFS volume resolver so the container runtime can bind file-system volumes declared in FileSystemConfigs.

func (*Service) SetImageResolver

func (s *Service) SetImageResolver(r docker.ImageResolver)

SetImageResolver wires the registry resolver used when a PackageType=Image function's ImageUri names a registry Overcast serves rather than a public one — a container image built and pushed by CDK, whose reference points at real AWS. Implemented by the ECR service.

Callable before or after the Docker probe builds the container runtime: the resolver is recorded here and applied to every runtime built afterwards.

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 first Docker probe has reported (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, and returns as soon as the event is accepted or refused — never after the function has run.

Delivery problems are logged and swallowed: S3 notification configs, EventBridge targets and Scheduler targets all treat a misconfigured destination the way AWS does — the originating operation still succeeds. Callers that need the outcome use InvokeEvent instead.

func (*ServiceInvoker) InvokeEvent

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

InvokeEvent satisfies events.FunctionEventInvoker. It is safe to call from any goroutine.

It accepts or refuses the event and returns; it never waits for the function. A non-nil error means the event was refused and never queued, so the caller still owns it — SNS dead-letters it against the subscription's RedrivePolicy. The refusals are the ones an HTTP `InvocationType=Event` invoke answers before its 202: the function does not exist, or is not in an invokable state. Two more are Overcast's own, and are refusals rather than silent drops because a notification that vanishes is worse than one that fails loudly — a missing layer version, and a declared runtime the emulator cannot execute.

A throttle is deliberately *not* among them. AWS answered 202 before any concurrency was needed and retries internally; startAsync's acquireForAsync does the same. Handing it back would dead-letter an event AWS would have run.

Everything after acceptance — the cold start, the throttle retry, a handler that raises — is Lambda's, and is reported to the caller as a successful delivery. Overcast has no async retry or DeadLetterConfig yet, so a handler exception currently reaches nothing but the server logs; this seam is where that machinery will go.

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 TriggerSource

type TriggerSource interface {
	// ReferencesFunction reports whether any of the service's routing
	// configuration targets the given Lambda function ARN.
	ReferencesFunction(ctx context.Context, functionARN string) bool
}

TriggerSource is implemented by services that can attest a Lambda function is wired to receive traffic (an API Gateway integration, an AppSync data source, …). Used as proactive-initialization trigger evidence; called only when a function's configuration settles after a deploy, never on the invoke path, so implementations may scan their stored state.

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"`
	Ipv6AllowedForDualStack bool     `json:"Ipv6AllowedForDualStack,omitempty"`
	VpcId                   string   `json:"VpcId,omitempty"`
}

VpcConfig associates a Lambda function with a VPC.

Directories

Path Synopsis
Package initbin carries the in-container Lambda init binary, built for each Linux architecture Lambda offers and embedded in the Overcast binary.
Package initbin carries the in-container Lambda init binary, built for each Linux architecture Lambda offers and embedded in the Overcast binary.
Package initproto is the single definition of the contract between the Overcast host and the in-container Lambda init (cmd/lambda-init).
Package initproto is the single definition of the contract between the Overcast host and the in-container Lambda init (cmd/lambda-init).

Jump to

Keyboard shortcuts

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