Documentation
¶
Overview ¶
Package localrunner derives an HTTP surface from a synthesized AWS CDK cloud assembly and serves it from the app's real Lambda handlers running in the official AWS Lambda runtime images.
The cloud assembly is the only routing definition: functions, HTTP API v2 routes, REST API v1 resources and Function URLs are read from the templates the app already deploys. Nothing here calls AWS; every function container is started with static dummy credentials, closed DNS and endpoint overrides that point at the local profile.
Index ¶
- Constants
- Variables
- func BuildAuthorizerEvent(request InvokeRequest) ([]byte, error)
- func BuildCloudWatchLogsKinesisEvent(streamARN, logGroup, logStream string, subscriptionFilters []string, ...) ([]byte, error)
- func BuildDynamoDBStreamEvent(input DynamoDBStreamInput) ([]byte, error)
- func BuildEvent(request InvokeRequest) ([]byte, error)
- func BuildEventBridgeEvent(rule RuleSpec, detail json.RawMessage, source, detailType string, ...) ([]byte, error)
- func BuildImageArgv(options ImageBuildOptions) []string
- func BuildKinesisEvent(streamARN string, records []KinesisRecordInput, now time.Time) ([]byte, error)
- func BuildS3NotificationRecord(event S3ObjectEvent) ([]byte, error)
- func BuildS3TestEvent(bucket string, now time.Time) ([]byte, error)
- func BuildSQSEvent(queueARN string, messages []sqstypes.Message) ([]byte, error)
- func ContainerArgv(options ContainerOptions) []string
- func DeliveryCell(state DeliveryState) string
- func NewRequestID() string
- func RequestPath(request *http.Request) string
- func RouteTable(spec *Spec) []string
- func RuntimeClass(runtime string) (string, error)
- func SortNotifications(notifications []NotificationSpec)
- func SummarizeEndpoints(endpoints []Endpoint) string
- func Synth(ctx context.Context, options SynthOptions) error
- func ValidateEndpoint(endpoint Endpoint) error
- type APIClass
- type APISpec
- type AuthorizerKind
- type Clock
- type ClockMode
- type ClockState
- type CloudWatchLogEvent
- type CloudWatchLogsDeliverer
- type CodeBuildImagePin
- type CodeBuildProjectSpec
- type ContainerOptions
- type ContainerPin
- type DeliverFunc
- type Deliverer
- func NewCloudWatchLogsDeliverer(source DeliverySource) (Deliverer, error)
- func NewDynamoDBStreamDeliverer(source DeliverySource, tracker *ttlTracker) (Deliverer, error)
- func NewEventBridgeDeliverer(source DeliverySource, bus *eventBridgeBus) (Deliverer, error)
- func NewKinesisDeliverer(source DeliverySource) (Deliverer, error)
- func NewS3NotificationDeliverer(source DeliverySource, supervisor *s3NotificationSupervisor) (Deliverer, error)
- func NewSNSDeliverer(source DeliverySource, registry *snsHubRegistry) (Deliverer, error)
- func NewSQSDeliverer(source DeliverySource) (Deliverer, error)
- type DelivererEnv
- type DelivererFactory
- type DeliveryBackend
- type DeliveryEngine
- func (e *DeliveryEngine) Clock() Clock
- func (e *DeliveryEngine) Drain(ctx context.Context) error
- func (e *DeliveryEngine) Planned(spec *Spec) []DeliveryState
- func (e *DeliveryEngine) RegisterDeliverer(kind DeliveryKind, factory DelivererFactory)
- func (e *DeliveryEngine) Restart(ctx context.Context, spec *Spec) error
- func (e *DeliveryEngine) Start(ctx context.Context, spec *Spec) error
- func (e *DeliveryEngine) State() EngineState
- func (e *DeliveryEngine) Stop(ctx context.Context) error
- type DeliveryKind
- type DeliveryPhase
- type DeliveryReporter
- type DeliveryResolver
- type DeliverySource
- type DeliveryState
- type Docker
- func (d *Docker) Available(ctx context.Context) error
- func (d *Docker) BuildImage(ctx context.Context, options ImageBuildOptions) error
- func (d *Docker) ContainerIP(ctx context.Context, name, network string) (string, error)
- func (d *Docker) CreateNetwork(ctx context.Context, name string, labels map[string]string) error
- func (d *Docker) EnsureImage(ctx context.Context, image string) error
- func (d *Docker) ExitCode(ctx context.Context, name string) (int, error)
- func (d *Docker) FollowLogs(ctx context.Context, name string, since time.Time, onLine func(string)) error
- func (d *Docker) ImageEnv(ctx context.Context, image string) (map[string]string, error)
- func (d *Docker) ImageID(ctx context.Context, image string) (string, error)
- func (d *Docker) ListContainers(ctx context.Context, label string) ([]string, error)
- func (d *Docker) ListImages(ctx context.Context, label string) ([]string, error)
- func (d *Docker) ListNetworks(ctx context.Context, label string) ([]string, error)
- func (d *Docker) Logs(ctx context.Context, name string) string
- func (d *Docker) NetworkGateway(ctx context.Context, name string) (string, error)
- func (d *Docker) PublishedPort(ctx context.Context, name string, containerPort int) (int, error)
- func (d *Docker) RemoveContainer(ctx context.Context, name string)
- func (d *Docker) RemoveImage(ctx context.Context, tag string)
- func (d *Docker) RemoveImageIfUnused(ctx context.Context, image string)
- func (d *Docker) RemoveNetwork(ctx context.Context, name string)
- func (d *Docker) RunOnce(ctx context.Context, options ContainerOptions) (string, error)
- func (d *Docker) Running(ctx context.Context, name string) (bool, error)
- func (d *Docker) ServerArch(ctx context.Context) (string, error)
- func (d *Docker) StartContainer(ctx context.Context, options ContainerOptions) (string, error)
- func (d *Docker) TagImage(ctx context.Context, source, tag string) error
- type DockerImageAssetSpec
- type DynamoDBStreamDeliverer
- type DynamoDBStreamInput
- type Endpoint
- type EngineState
- type EventBridgeDeliverer
- type EventSourceSpec
- type FunctionProcess
- func (p *FunctionProcess) Invoke(ctx context.Context, payload []byte) ([]byte, error)
- func (p *FunctionProcess) InvokeStream(ctx context.Context, payload []byte, sink StreamSink) (InvokeStreamResult, error)
- func (p *FunctionProcess) RuntimeAPIURL() string
- func (p *FunctionProcess) StreamingIncremental() bool
- func (p *FunctionProcess) URL() string
- type FunctionSpec
- type FunctionURLSpec
- type HandlerError
- type HandlerSpec
- type ImageBuildOptions
- type ImagePin
- type InvokeRequest
- type InvokeResult
- type InvokeStreamResult
- type Invoker
- type KinesisDeliverer
- type KinesisRecordInput
- type LambdaResponse
- type LayerSpec
- type LocalSNSAttribute
- type LocalSNSMessage
- type MockResponse
- type NotificationFilterRule
- type NotificationSpec
- type Options
- type PlannedResource
- type PreflightResult
- type Profile
- func (p *Profile) CodeBuildAgent(arch string) (string, error)
- func (p *Profile) CodeBuildImage(arch, image string) (string, error)
- func (p *Profile) Container(name string) (ContainerPin, error)
- func (p *Profile) DynamoDBImage() (string, error)
- func (p *Profile) EndpointEnvNames(service string) []string
- func (p *Profile) EndpointsForContainer(name string) []Endpoint
- func (p *Profile) ImageFor(runtime string) (string, error)
- func (p *Profile) ImageForClass(class string) (string, error)
- func (p *Profile) Path() string
- type RealClock
- type ResourceSpec
- type Route
- type RuleInputTransformer
- type RuleRetryPolicy
- type RuleSpec
- type RuleTargetSpec
- type Runner
- func (r *Runner) CleanScratch()
- func (r *Runner) CurrentSpec() *Spec
- func (r *Runner) Down(ctx context.Context) (int, error)
- func (r *Runner) Plan(ctx context.Context) (*Spec, error)
- func (r *Runner) PlanJSON(spec *Spec) ([]byte, error)
- func (r *Runner) Preflight(ctx context.Context, network string, addHosts []string) (PreflightResult, error)
- func (r *Runner) PublishLocal(ctx context.Context, topicARN, message string) error
- func (r *Runner) PublishLocalMessage(ctx context.Context, topicARN string, message LocalSNSMessage) error
- func (r *Runner) ResolveDeliveryBackend(kind DeliveryKind) (DeliveryBackend, error)
- func (r *Runner) Run(ctx context.Context) error
- func (r *Runner) RunInvoke(ctx context.Context, functionID string, in io.Reader, out io.Writer) error
- func (r *Runner) RunSession(ctx context.Context, in io.Reader, out io.Writer) error
- func (r *Runner) RuntimeMode() string
- func (r *Runner) Scratch() string
- type RuntimeAPIError
- type S3NotificationDeliverer
- type S3ObjectEvent
- type SNSDeliverer
- type SQSDeliverer
- type Skipped
- type Spec
- func (s *Spec) CloudFrontEdgeFunctions() []string
- func (s *Spec) CloudFrontOriginFunctions() []string
- func (s *Spec) Function(logicalID string) (FunctionSpec, bool)
- func (s *Spec) FunctionURLsFor(function string) []FunctionURLSpec
- func (s *Spec) HTTPAPIs() []APISpec
- func (s *Spec) RuntimeFunctions() []string
- func (s *Spec) ServableCloudFront() []*localcloudfront.Distribution
- func (s *Spec) ServedFunctions() []string
- func (s *Spec) WebSocketAPIs() []WebSocketAPISpec
- type StreamSink
- type SubscriptionSpec
- type SynthOptions
- type TestClock
- type Transport
- type UnsupportedError
- type WebSocketAPISpec
- type WebSocketAuthorizerSpec
- type WebSocketRouteSpec
- type WebSocketServer
Constants ¶
const ( // LocalAccountID and LocalRegion are the fixed values every synthesized // event carries. They are syntactically valid AWS values, so handlers that // validate them behave as they would in a deployment. LocalAccountID = "123456789012" LocalRegion = "us-east-1" LocalPartition = "aws" // LocalStageName is the stage the local transport reports when an API has // no explicit stage resource. LocalStageName = "$default" // ClosedDNSServer points function containers at an address that answers no // DNS query. Anything the runner does not add to /etc/hosts fails to // resolve, so an SDK cannot reach a real AWS endpoint. ClosedDNSServer = "127.0.0.2" // ClosedEndpoint is the global endpoint used when no local backend is // configured. A connection to it is refused locally, which keeps a handler // that calls AWS from reaching real AWS. ClosedEndpoint = "http://127.0.0.1:1" // FunctionURLDomainSuffix keeps synthesized Function URL events // distinguishable from HTTP API v2 events, which the AppTheory runtime // discriminates by requestContext.domainName. FunctionURLDomainSuffix = ".lambda-url." + LocalRegion + ".on.aws" )
Variables ¶
var DefaultTestClockStart = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
DefaultTestClockStart is where `--clock test` starts when no instant is given. A fixed instant keeps every test run reproducible.
Functions ¶
func BuildAuthorizerEvent ¶
func BuildAuthorizerEvent(request InvokeRequest) ([]byte, error)
BuildAuthorizerEvent serializes the API Gateway v2 REQUEST authorizer event. It carries the same request the route handler will receive, plus the identity sources the authorizer declared, as an array in configured order.
func BuildCloudWatchLogsKinesisEvent ¶
func BuildCloudWatchLogsKinesisEvent(streamARN, logGroup, logStream string, subscriptionFilters []string, logEvents []CloudWatchLogEvent, now time.Time) ([]byte, error)
BuildCloudWatchLogsKinesisEvent encodes a CloudWatch Logs subscription payload as the gzip+base64 Kinesis record AWS delivers.
func BuildDynamoDBStreamEvent ¶
func BuildDynamoDBStreamEvent(input DynamoDBStreamInput) ([]byte, error)
BuildDynamoDBStreamEvent builds the DynamoDB stream record a stream mapping delivers. The images are the typed attribute values read from the local table, so the record is generated from the stored image rather than a literal.
func BuildEvent ¶
func BuildEvent(request InvokeRequest) ([]byte, error)
BuildEvent serializes the provider payload the handler receives: an HTTP API v2 event, a REST API v1 event or a Function URL event, matching the surface the request matched.
func BuildEventBridgeEvent ¶
func BuildEventBridgeEvent(rule RuleSpec, detail json.RawMessage, source, detailType string, now time.Time) ([]byte, error)
BuildEventBridgeEvent builds the event an EventBridge rule delivers. A scheduled rule gets the Scheduled Event envelope; a pattern rule gets the source and detail-type the template declares unless the caller supplies them.
func BuildImageArgv ¶
func BuildImageArgv(options ImageBuildOptions) []string
BuildImageArgv is the exact docker build argv for options, sorted so a test can pin what the runner asks Docker to do.
func BuildKinesisEvent ¶
func BuildKinesisEvent(streamARN string, records []KinesisRecordInput, now time.Time) ([]byte, error)
BuildKinesisEvent builds the Kinesis event a stream mapping delivers.
func BuildS3NotificationRecord ¶
func BuildS3NotificationRecord(event S3ObjectEvent) ([]byte, error)
BuildS3NotificationRecord builds the Records envelope a Lambda, SQS or SNS destination receives.
func BuildS3TestEvent ¶
BuildS3TestEvent builds the message S3 sends to an SQS queue or SNS topic when its notification configuration is applied. It is deliberately a different shape from a record event.
func BuildSQSEvent ¶
BuildSQSEvent builds the SQS event an event-source mapping delivers from messages a local ElasticMQ queue actually returned.
func ContainerArgv ¶
func ContainerArgv(options ContainerOptions) []string
ContainerArgv is the exact docker run argv for options, sorted so a test can pin what the runner asks Docker to do.
func DeliveryCell ¶
func DeliveryCell(state DeliveryState) string
DeliveryCell renders one state for the human plan output.
func NewRequestID ¶
func NewRequestID() string
NewRequestID returns a request id in the shape API Gateway uses.
func RequestPath ¶
RequestPath returns the decoded request path.
func RouteTable ¶
RouteTable renders the derived surface for the CLI's plan output.
func RuntimeClass ¶
RuntimeClass maps a Lambda runtime name to the image class the profile pins.
func SortNotifications ¶
func SortNotifications(notifications []NotificationSpec)
SortNotifications orders the derived configurations for stable output.
func SummarizeEndpoints ¶
SummarizeEndpoints renders the endpoints the runner injects, sorted.
func Synth ¶
func Synth(ctx context.Context, options SynthOptions) error
Synth runs `cdk synth` for the app with static dummy credentials and a fixed account/region. It never reads an operator's AWS configuration: every AWS_* and CDK_* variable is removed from the child environment first.
func ValidateEndpoint ¶
ValidateEndpoint fails closed on an endpoint that is malformed or that points at AWS.
Types ¶
type APIClass ¶
type APIClass string
APIClass names a supported HTTP surface kind.
const ( // APIHTTPV2 is AWS::ApiGatewayV2::Api with ProtocolType HTTP. APIHTTPV2 APIClass = "httpv2" // APIRESTV1 is AWS::ApiGateway::RestApi. APIRESTV1 APIClass = "restv1" // APIFunctionURL is AWS::Lambda::Url. APIFunctionURL APIClass = "fnurl" // APIWebSocket is AWS::ApiGatewayV2::Api with ProtocolType WEBSOCKET. APIWebSocket APIClass = "websocket" )
type APISpec ¶
type APISpec struct {
Class APIClass `json:"class"`
LogicalID string `json:"logicalId"`
Stack string `json:"stack"`
Name string `json:"name"`
Stage string `json:"stage"`
Routes []Route `json:"routes"`
Streaming bool `json:"streaming"`
}
APISpec is one supported HTTP surface.
type AuthorizerKind ¶
type AuthorizerKind string
AuthorizerKind names one authorizer implementation.
const ( // AuthorizerKindSimpleRequest is an HTTP API REQUEST authorizer with // EnableSimpleResponses. AuthorizerKindSimpleRequest AuthorizerKind = "http-request-simple" // AuthorizerKindJWT is an HTTP API JWT authorizer. AuthorizerKindJWT AuthorizerKind = "http-jwt" // AuthorizerKindLambdaRequest is a Lambda authorizer that returns an IAM // policy: a WebSocket $connect authorizer, or a REST TOKEN/REQUEST one. AuthorizerKindLambdaRequest AuthorizerKind = "lambda-request-policy" // AuthorizerKindCognito is a REST API COGNITO_USER_POOLS authorizer. AuthorizerKindCognito AuthorizerKind = "rest-cognito-user-pools" )
type Clock ¶
type Clock interface {
// Now is the current instant.
Now() time.Time
// After returns a channel that receives the instant d from now.
After(d time.Duration) <-chan time.Time
}
Clock is the run's time source. The delivery engine, the events a session builds and every future schedule, TTL expiry and visibility timeout take their time from it. Real time is the default; `--clock test[=<RFC3339>]` makes a run deterministic.
func ParseClockSpec ¶
ParseClockSpec parses the `--clock` value: real, test, or test=<RFC3339 start>. The empty value is the real clock.
type ClockState ¶
ClockState reports the run's clock mode and current instant.
type CloudWatchLogEvent ¶
type CloudWatchLogEvent struct {
ID string `json:"id"`
Timestamp int64 `json:"timestamp"`
Message string `json:"message"`
}
CloudWatchLogEvent is one log event in a CloudWatch Logs subscription payload.
type CloudWatchLogsDeliverer ¶
type CloudWatchLogsDeliverer struct {
// contains filtered or unexported fields
}
CloudWatchLogsDeliverer delivers one subscription filter.
func (*CloudWatchLogsDeliverer) Start ¶
func (d *CloudWatchLogsDeliverer) Start(ctx context.Context, env DelivererEnv) error
Start verifies the destination and polls the log group until the context ends.
type CodeBuildImagePin ¶
type CodeBuildImagePin struct {
Tag string `json:"tag"`
Digest string `json:"digest"`
Pinned string `json:"pinned"`
License string `json:"license,omitempty"`
CompressedBytes int64 `json:"compressedBytes,omitempty"`
}
CodeBuildImagePin is one digest-pinned CodeBuild image (the local agent or a curated build image). CompressedBytes is the public registry's compressed size, recorded so the docs can state the colima disk requirement without a pull.
type CodeBuildProjectSpec ¶
type CodeBuildProjectSpec struct {
LogicalID string `json:"logicalId"`
Stack string `json:"stack"`
// Name is the local physical project name. AWS generates a name when the
// template omits one; the runner uses resourceName's deterministic local
// name, which is also the Ref the state-change rule's event pattern uses.
Name string `json:"name"`
// Image is the project's Environment.Image, for example
// aws/codebuild/standard:7.0.
Image string `json:"image"`
// BuildSpec is the inline buildspec (JSON or YAML). BuildSpecPath is the
// source-relative path form.
BuildSpec string `json:"buildSpec,omitempty"`
BuildSpecPath string `json:"buildSpecPath,omitempty"`
// SourceType is the project's Source.Type, for example NO_SOURCE.
SourceType string `json:"sourceType,omitempty"`
// EnvironmentVariables are the project's literal Environment.Variables.
EnvironmentVariables map[string]string `json:"environmentVariables,omitempty"`
Privileged bool `json:"privileged,omitempty"`
TimeoutMinutes int `json:"timeoutMinutes,omitempty"`
// Deviations name project features the local agent does not reproduce.
Deviations []string `json:"deviations,omitempty"`
}
CodeBuildProjectSpec is one AWS::CodeBuild::Project the local runner serves. It carries the deployed image name and the buildspec; the profile maps the image to a digest-pinned local build image per architecture.
type ContainerOptions ¶
type ContainerOptions struct {
Name string
Network string
// Aliases are additional network names, so an emulator can answer on its
// service name while the container keeps the run's unique name.
Aliases []string
Image string
Command []string
Entrypoint string
Env map[string]string
AddHosts []string
MemoryMB int
Mounts []string
Publish int
Labels map[string]string
// Detach starts the container in the background (function containers).
Detach bool
}
ContainerOptions describes one function or probe container.
type ContainerPin ¶
type ContainerPin struct {
Image string `json:"image"`
Command []string `json:"command,omitempty"`
ContainerPort int `json:"containerPort"`
Environment map[string]string `json:"environment,omitempty"`
// Mounts are profile-declared bind mounts (host:container[:ro]).
Mounts []string `json:"mounts,omitempty"`
}
ContainerPin is one digest-pinned local emulator container.
type DeliverFunc ¶
DeliverFunc sends one provider event to one registered function.
type Deliverer ¶
type Deliverer interface {
Start(ctx context.Context, env DelivererEnv) error
}
Deliverer is one source kind's delivery loop. E1b–E6 implement it. Start blocks until ctx is canceled; it reports polling or armed through env.State as soon as it is delivering, and returns an error when it cannot deliver.
func NewCloudWatchLogsDeliverer ¶
func NewCloudWatchLogsDeliverer(source DeliverySource) (Deliverer, error)
NewCloudWatchLogsDeliverer builds the deliverer for one registered filter.
func NewDynamoDBStreamDeliverer ¶
func NewDynamoDBStreamDeliverer(source DeliverySource, tracker *ttlTracker) (Deliverer, error)
NewDynamoDBStreamDeliverer builds the deliverer for one registered mapping.
func NewEventBridgeDeliverer ¶
func NewEventBridgeDeliverer(source DeliverySource, bus *eventBridgeBus) (Deliverer, error)
NewEventBridgeDeliverer builds the deliverer for one registered rule.
func NewKinesisDeliverer ¶
func NewKinesisDeliverer(source DeliverySource) (Deliverer, error)
NewKinesisDeliverer builds the deliverer for one registered mapping.
func NewS3NotificationDeliverer ¶
func NewS3NotificationDeliverer(source DeliverySource, supervisor *s3NotificationSupervisor) (Deliverer, error)
NewS3NotificationDeliverer builds the deliverer for one notification entry.
func NewSNSDeliverer ¶
func NewSNSDeliverer(source DeliverySource, registry *snsHubRegistry) (Deliverer, error)
NewSNSDeliverer builds the SNS deliverer for one registered subscription.
func NewSQSDeliverer ¶
func NewSQSDeliverer(source DeliverySource) (Deliverer, error)
NewSQSDeliverer builds the SQS deliverer for one registered mapping.
type DelivererEnv ¶
type DelivererEnv struct {
// Source is the registered mapping, rule or subscription.
Source DeliverySource
// Clock is the run's time source. Schedules, TTL expiry and visibility
// timeouts must take their time from it, never from time.Now.
Clock Clock
// Backend is the resolved local backend client and endpoint.
Backend DeliveryBackend
// Invoke sends one event to the source's own function.
Invoke func(ctx context.Context, event []byte) (InvokeResult, error)
// InvokeTarget sends one event to a named function. A rule can target
// several functions.
InvokeTarget DeliverFunc
// State is the engine-owned reporting surface for this source.
State DeliveryReporter
// Concurrency is the engine's global invocation bound. A deliverer with
// its own per-mapping bound never exceeds it.
Concurrency int
// Logf writes one line to the run log.
Logf func(format string, args ...any)
}
DelivererEnv is everything a deliverer receives from the engine.
type DelivererFactory ¶
type DelivererFactory func(source DeliverySource) (Deliverer, error)
DelivererFactory builds the deliverer for one registered source.
type DeliveryBackend ¶
type DeliveryBackend struct {
Service string `json:"service"`
Endpoint string `json:"endpoint,omitempty"`
Client any `json:"-"`
// SQS is the host-side ElasticMQ client when the SQS backend is running.
SQS *sqs.Client `json:"-"`
// PublishSNS runs one message through the local SNS fan-out.
PublishSNS func(ctx context.Context, topicARN string, message LocalSNSMessage) error `json:"-"`
}
DeliveryBackend is the resolved local backend a deliverer talks to: the service name, its loopback endpoint and the host-side SDK client, when the service has one. SQS and PublishSNS are the auxiliary clients an event deliverer needs for its targets and on-failure destinations.
type DeliveryEngine ¶
type DeliveryEngine struct {
// contains filtered or unexported fields
}
DeliveryEngine owns the registry of deliverers, the registered sources, the bounded concurrency and the reported state.
func NewDeliveryEngine ¶
func NewDeliveryEngine(clock Clock, concurrency int, resolver DeliveryResolver, invoker DeliverFunc, logf func(format string, args ...any)) *DeliveryEngine
NewDeliveryEngine builds the engine for one run. A nil clock is the real clock; a concurrency of zero is the documented default; a nil resolver or invoker makes the corresponding operation fail closed.
func (*DeliveryEngine) Clock ¶
func (e *DeliveryEngine) Clock() Clock
Clock returns the engine's time source.
func (*DeliveryEngine) Drain ¶
func (e *DeliveryEngine) Drain(ctx context.Context) error
Drain stops accepting new deliveries and waits for in-flight invocations to finish. It is the graceful half of shutdown; Stop cancels the deliverers.
func (*DeliveryEngine) Planned ¶
func (e *DeliveryEngine) Planned(spec *Spec) []DeliveryState
Planned reports the state the engine would register for every derived source, without starting a run. It is what `plan` prints: a kind with a deliverer is registered; every other kind is not-delivered with the task that will implement it.
func (*DeliveryEngine) RegisterDeliverer ¶
func (e *DeliveryEngine) RegisterDeliverer(kind DeliveryKind, factory DelivererFactory)
RegisterDeliverer installs the deliverer implementation for one source kind. E1b–E6 call it once per kind.
func (*DeliveryEngine) Restart ¶
func (e *DeliveryEngine) Restart(ctx context.Context, spec *Spec) error
Restart re-derives every registered source after a watch reload. The running deliverers are canceled and drained, then the new Spec's sources are registered on a fresh engine context. Counters start from zero, which is the honest reading of a rebuilt local session.
func (*DeliveryEngine) Start ¶
func (e *DeliveryEngine) Start(ctx context.Context, spec *Spec) error
Start registers every derived source and starts one deliverer per source whose kind has one. A source kind without a deliverer is recorded as not-delivered; it never prevents the run from starting.
func (*DeliveryEngine) State ¶
func (e *DeliveryEngine) State() EngineState
State snapshots the live engine state for `session describe`.
type DeliveryKind ¶
type DeliveryKind string
DeliveryKind names one source kind the engine can deliver. The mapping kinds match EventSourceSpec.Type; rule kinds split scheduled rules from pattern rules, and cloudwatch-logs covers a log subscription filter.
const ( // DeliveryKindSQS is an SQS event source mapping. DeliveryKindSQS DeliveryKind = "sqs" // DeliveryKindDynamoDBStream is a DynamoDB Streams event source mapping. DeliveryKindDynamoDBStream DeliveryKind = "dynamodb" // DeliveryKindKinesis is a Kinesis event source mapping. DeliveryKindKinesis DeliveryKind = "kinesis" // DeliveryKindEventBridgeSchedule is an EventBridge scheduled rule. DeliveryKindEventBridgeSchedule DeliveryKind = "eventbridge-schedule" // DeliveryKindEventBridgeRule is an EventBridge pattern rule. DeliveryKindEventBridgeRule DeliveryKind = "eventbridge-rule" // DeliveryKindCloudWatchLogs is a CloudWatch Logs subscription filter. DeliveryKindCloudWatchLogs DeliveryKind = "cloudwatch-logs" // DeliveryKindSNS is an SNS topic subscription. DeliveryKindSNS DeliveryKind = "sns" // DeliveryKindS3Notification is one S3 bucket notification configuration // entry: a Lambda, SQS or SNS destination, or the bucket's EventBridge // configuration. DeliveryKindS3Notification DeliveryKind = "s3-notification" )
type DeliveryPhase ¶
type DeliveryPhase string
DeliveryPhase is one source's delivery state, the local counterpart of the event source mapping State field.
const ( // DeliveryPhaseRegistered is a source whose kind has a deliverer, before // the deliverer reports that it is polling or armed. DeliveryPhaseRegistered DeliveryPhase = "registered" // DeliveryPhasePolling is a deliverer actively polling a queue or stream. DeliveryPhasePolling DeliveryPhase = "polling" // DeliveryPhaseArmed is a deliverer waiting for the clock to reach the next // schedule or matching an event against a rule. DeliveryPhaseArmed DeliveryPhase = "armed" // DeliveryPhasePaused is a deliverer that is registered but not delivering. DeliveryPhasePaused DeliveryPhase = "paused" // DeliveryPhaseStopped is a deliverer that has stopped. DeliveryPhaseStopped DeliveryPhase = "stopped" // DeliveryPhaseFailed is a deliverer that could not start or deliver. DeliveryPhaseFailed DeliveryPhase = "failed" // DeliveryPhaseNotDelivered is a source kind with no deliverer yet. DeliveryPhaseNotDelivered DeliveryPhase = "not-delivered" )
type DeliveryReporter ¶
type DeliveryReporter interface {
// SetPhase reports the deliverer's current phase.
SetPhase(phase DeliveryPhase)
// Delivered records a completed handler invocation.
Delivered()
// Failed records a failed handler invocation.
Failed(err error)
// Filtered records a message a subscription filter did not match.
Filtered()
// SetPaused records whether delivery is paused.
SetPaused(paused bool)
// SetInflight records how many batches the deliverer is invoking now. The
// engine keeps the observed peak.
SetInflight(inflight int)
// Left records how many records the deliverer left for redelivery.
Left(count int)
// Discarded records how many stream records were sent to an on-failure
// destination.
Discarded(count int)
// Fired records one rule evaluation or schedule tick.
Fired()
// DeadLettered records one EventBridge event sent to a target DLQ.
DeadLettered()
}
DeliveryReporter is the engine-owned state a running deliverer updates.
type DeliveryResolver ¶
type DeliveryResolver func(kind DeliveryKind) (DeliveryBackend, error)
DeliveryResolver resolves the backend for one source kind. The runner implements it from the profile endpoints it started; tests can supply their own.
type DeliverySource ¶
type DeliverySource struct {
// ID is stable across plan and session: the qualified logical id.
ID string `json:"id"`
Kind DeliveryKind `json:"kind"`
Stack string `json:"stack"`
LogicalID string `json:"logicalId"`
// Function is the single function a mapping or subscription delivers to.
Function string `json:"function,omitempty"`
// Targets are the functions a rule invokes, in the declared order.
Targets []string `json:"targets,omitempty"`
Mapping *EventSourceSpec `json:"mapping,omitempty"`
Rule *RuleSpec `json:"rule,omitempty"`
Subscription *SubscriptionSpec `json:"subscription,omitempty"`
Notification *NotificationSpec `json:"notification,omitempty"`
}
DeliverySource is one derived mapping, rule or subscription the engine registers. Exactly one of Mapping, Rule or Subscription is set.
func DeliverySources ¶
func DeliverySources(spec *Spec) []DeliverySource
DeliverySources lists every derived mapping, rule and subscription in the order the engine registers them.
type DeliveryState ¶
type DeliveryState struct {
ID string `json:"id"`
Kind DeliveryKind `json:"kind"`
Function string `json:"function,omitempty"`
Targets []string `json:"targets,omitempty"`
State DeliveryPhase `json:"state"`
// Delivered and Failed count handler invocations the deliverer completed.
Delivered int64 `json:"delivered"`
Failed int64 `json:"failed"`
// Filtered counts messages a subscription filter policy did not match.
Filtered int64 `json:"filtered,omitempty"`
// Fired counts the rule evaluations or schedule ticks a rule produced.
Fired int64 `json:"fired,omitempty"`
// Discarded counts stream records sent to an on-failure destination, and
// DeadLettered counts EventBridge events sent to a target DLQ.
Discarded int64 `json:"discarded,omitempty"`
DeadLettered int64 `json:"deadLettered,omitempty"`
// Inflight is the number of batches the deliverer is invoking right now;
// PeakInflight is the highest observed value. They make a mapping's
// MaximumConcurrency observable from session describe.
Inflight int `json:"inflight"`
PeakInflight int `json:"peakInflight"`
// Left counts the records the deliverer left undeleted for redelivery, in
// total. A partial batch response or a failed invocation adds to it.
Left int64 `json:"left"`
// LastError is the last delivery error, empty after a success.
LastError string `json:"lastError,omitempty"`
Paused bool `json:"paused"`
// Task names the delivery task that implements the kind when the engine has
// no deliverer for it.
Task string `json:"task,omitempty"`
// Reason explains a state that is not delivering.
Reason string `json:"reason,omitempty"`
}
DeliveryState is one source's reported delivery state.
type Docker ¶
type Docker struct {
// contains filtered or unexported fields
}
Docker talks to the Docker CLI. The local runner never uses the SDK: every container, network and port operation is an explicit CLI call with a name and label the runner owns.
func NewDocker ¶
func NewDocker() *Docker
NewDocker returns a Docker client backed by the docker CLI on PATH.
func (*Docker) BuildImage ¶
func (d *Docker) BuildImage(ctx context.Context, options ImageBuildOptions) error
BuildImage builds one container image from the cloud assembly's Docker asset.
func (*Docker) ContainerIP ¶
ContainerIP returns a container's address on a Docker network.
func (*Docker) CreateNetwork ¶
CreateNetwork creates the run's private network.
func (*Docker) EnsureImage ¶
EnsureImage pulls a digest-pinned image when the local daemon does not have it. A digest reference is immutable, so an existing image is already the pinned content.
func (*Docker) FollowLogs ¶
func (d *Docker) FollowLogs(ctx context.Context, name string, since time.Time, onLine func(string)) error
FollowLogs streams a container's stdout and stderr until the context ends. Docker prefixes each line with an RFC3339 timestamp because the runner asks for --timestamps; the caller parses it. The command is killed with the context, so a stopped run leaves no follower behind.
func (*Docker) ImageEnv ¶
ImageEnv reads the environment the image itself declares, so the layer paths can be prepended to the image's own PATH and LD_LIBRARY_PATH.
func (*Docker) ImageID ¶
ImageID resolves an image reference to the daemon's immutable id. A watch reload records it before a rebuild can move the tag, and a rollback starts the previous container from that id, so the tag's new target cannot leak into the restored container.
func (*Docker) ListContainers ¶
ListContainers returns container ids carrying a label.
func (*Docker) ListImages ¶
ListImages lists the images carrying one label.
func (*Docker) ListNetworks ¶
ListNetworks returns network names carrying a label.
func (*Docker) NetworkGateway ¶
NetworkGateway returns a network's IPAM gateway address: the address a container on that network reaches the host at when the host's loopback is not forwarded to it (the Linux bridge case).
func (*Docker) PublishedPort ¶
PublishedPort returns the loopback host port Docker assigned to a container port, or zero while it is not published yet.
func (*Docker) RemoveContainer ¶
RemoveContainer force-removes one container.
func (*Docker) RemoveImage ¶
RemoveImage removes an image the run built. A missing image is not an error: cleanup runs after failures too.
func (*Docker) RemoveImageIfUnused ¶
RemoveImageIfUnused removes an image by id without forcing. Docker refuses when another tag or a container still references it, so an image shared with a running function survives a watch reload's cleanup.
func (*Docker) RemoveNetwork ¶
RemoveNetwork removes a network the runner created. A missing network is not an error: cleanup runs after failures too.
func (*Docker) RunOnce ¶
RunOnce runs one foreground container and returns its combined output. The probe uses it; function containers are detached instead.
func (*Docker) ServerArch ¶
ServerArch returns the Docker server architecture (arm64 or amd64).
func (*Docker) StartContainer ¶
StartContainer starts one container and returns its id.
type DockerImageAssetSpec ¶
type DockerImageAssetSpec struct {
// Hash is the content hash CDK put in the image URI.
Hash string `json:"hash"`
// Directory, DockerFile, BuildArgs and Target describe the local build.
Directory string `json:"-"`
DockerFile string `json:"dockerFile,omitempty"`
BuildArgs map[string]string `json:"buildArgs,omitempty"`
Target string `json:"target,omitempty"`
Platform string `json:"platform,omitempty"`
}
DockerImageAssetSpec is the CDK Docker image asset a container-image function's Code.ImageUri names. It comes from the function resource's aws:asset:* metadata, the same assembly the zip functions read.
type DynamoDBStreamDeliverer ¶
type DynamoDBStreamDeliverer struct {
// contains filtered or unexported fields
}
DynamoDBStreamDeliverer reads one table's stream on DynamoDB Local and invokes the mapping's function exactly as the Lambda poller documents.
https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html
func (*DynamoDBStreamDeliverer) Start ¶
func (d *DynamoDBStreamDeliverer) Start(ctx context.Context, env DelivererEnv) error
Start resolves the provisioned stream and polls its shards.
type DynamoDBStreamInput ¶
type DynamoDBStreamInput struct {
EventSourceARN string
EventName string
Keys map[string]types.AttributeValue
NewImage map[string]types.AttributeValue
OldImage map[string]types.AttributeValue
StreamViewType string
SequenceNumber string
Now time.Time
}
DynamoDBStreamInput is one stream record built from a real local write.
type Endpoint ¶
Endpoint is one local AWS emulator endpoint the runner injects into every function container. Service is the AWS service name the SDK override uses (dynamodb, sqs, s3, ...).
type EngineState ¶
type EngineState struct {
Running bool `json:"running"`
Clock ClockState `json:"clock"`
Concurrency int `json:"concurrency"`
Sources []DeliveryState `json:"sources"`
}
EngineState is the delivery engine's live state.
type EventBridgeDeliverer ¶
type EventBridgeDeliverer struct {
// contains filtered or unexported fields
}
EventBridgeDeliverer delivers one EventBridge rule.
func (*EventBridgeDeliverer) Start ¶
func (d *EventBridgeDeliverer) Start(ctx context.Context, env DelivererEnv) error
Start arms a schedule or registers a pattern rule on its bus.
type EventSourceSpec ¶
type EventSourceSpec struct {
LogicalID string `json:"logicalId"`
Stack string `json:"stack"`
Function string `json:"function"`
// Type is sqs, dynamodb or kinesis.
Type string `json:"type"`
// Source is the logical id of the queue, table or stream the mapping reads.
Source string `json:"source"`
// SourceName is the queue name, table name or stream name.
SourceName string `json:"sourceName"`
// SourceARN is the provider-shaped ARN the derived mapping reports. A
// session builds DynamoDB stream events from the provisioned table's real
// local stream ARN instead.
SourceARN string `json:"sourceArn"`
BatchSize int `json:"batchSize,omitempty"`
ReportBatchItemFailures bool `json:"reportBatchItemFailures,omitempty"`
Enabled bool `json:"enabled"`
StartingPosition string `json:"startingPosition,omitempty"`
// MaximumBatchingWindowInSeconds is how long the SQS poller gathers a batch
// before invoking the function. AWS documents 0 as the SQS default and 300
// as the maximum; a FIFO queue does not support a batching window.
MaximumBatchingWindowInSeconds int `json:"maximumBatchingWindowInSeconds,omitempty"`
// FilterCriteria is the mapping's FilterCriteria object, verbatim. AWS
// applies the patterns to the SQS record and its parsed body; a record that
// matches no filter is deleted without invoking the function.
FilterCriteria json.RawMessage `json:"filterCriteria,omitempty"`
// MaximumConcurrency is ScalingConfig.MaximumConcurrency for an SQS
// mapping: the per-mapping bound on concurrent batches (2..1000).
MaximumConcurrency int `json:"maximumConcurrency,omitempty"`
// FIFO, VisibilityTimeout and MaxReceiveCount describe the source queue. The
// deliverer reads the provisioned queue's attributes at start; these fields
// let plan and describe report the same configuration without a backend.
FIFO bool `json:"fifo,omitempty"`
VisibilityTimeout int `json:"visibilityTimeout,omitempty"`
MaxReceiveCount int `json:"maxReceiveCount,omitempty"`
// Stream mapping settings shared by DynamoDB Streams and Kinesis.
//
// https://docs.aws.amazon.com/lambda/latest/dg/API_EventSourceMappingConfiguration.html
BisectBatchOnFunctionError bool `json:"bisectBatchOnFunctionError,omitempty"`
// MaximumRetryAttempts is -1 for unlimited, which is the AWS default. The
// RetryAttemptsSet flag distinguishes an explicit 0 (no retries) from an
// omitted property.
MaximumRetryAttempts int `json:"maximumRetryAttempts,omitempty"`
RetryAttemptsSet bool `json:"-"`
// MaximumRecordAgeInSeconds is -1 or omitted for unlimited.
MaximumRecordAgeInSeconds int `json:"maximumRecordAgeInSeconds,omitempty"`
// ParallelizationFactor is 1..10.
ParallelizationFactor int `json:"parallelizationFactor,omitempty"`
// TumblingWindowInSeconds is refused: no example uses it.
TumblingWindowInSeconds int `json:"tumblingWindowInSeconds,omitempty"`
// StartingPositionTimestamp is the Kinesis AT_TIMESTAMP value, in epoch
// seconds.
StartingPositionTimestamp float64 `json:"startingPositionTimestamp,omitempty"`
// DestinationType, DestinationName and DestinationARN describe
// DestinationConfig.OnFailure: an SQS queue or an SNS topic.
DestinationType string `json:"destinationType,omitempty"`
DestinationName string `json:"destinationName,omitempty"`
DestinationARN string `json:"destinationArn,omitempty"`
// StreamViewType, PartitionKey and TTLAttribute describe the source table.
StreamViewType string `json:"streamViewType,omitempty"`
PartitionKey string `json:"partitionKey,omitempty"`
TTLAttribute string `json:"ttlAttribute,omitempty"`
// FunctionName is the target function's physical name, used in the
// on-failure invocation record.
FunctionName string `json:"functionName,omitempty"`
}
EventSourceSpec is one AWS::Lambda::EventSourceMapping the assembly declares. It is reported, and its function is started, so a local session can receive real messages and build the provider event the mapping would deliver.
type FunctionProcess ¶
type FunctionProcess struct {
Function FunctionSpec
Container string
Image string
// Port is the loopback port of the embedded Runtime Interface Emulator. It
// is set only in RIE mode.
Port int
// Started is when the container was started; the log follower replays from
// this instant.
Started time.Time
// contains filtered or unexported fields
}
FunctionProcess is one function container. In the default mode it serves the Lambda Runtime API and the container's own runtime interface client talks to it; in RIE mode it posts to the image's embedded Runtime Interface Emulator.
func (*FunctionProcess) Invoke ¶
Invoke runs one event and returns the response payload. A Lambda error (including a timeout, a crash or an initialization failure) is returned as the documented error JSON so existing callers decode it exactly as they decoded the emulator's response.
func (*FunctionProcess) InvokeStream ¶
func (p *FunctionProcess) InvokeStream(ctx context.Context, payload []byte, sink StreamSink) (InvokeStreamResult, error)
InvokeStream runs one event and forwards each response chunk to sink as it arrives. A nil sink buffers the response. The returned body is always the complete payload, which keeps the caller's decode path unchanged.
func (*FunctionProcess) RuntimeAPIURL ¶
func (p *FunctionProcess) RuntimeAPIURL() string
RuntimeAPIURL is the host address of this function's Runtime API.
func (*FunctionProcess) StreamingIncremental ¶
func (p *FunctionProcess) StreamingIncremental() bool
StreamingIncremental reports whether this process can forward chunks as the runtime writes them. The emulator buffers every response, so RIE mode cannot.
func (*FunctionProcess) URL ¶
func (p *FunctionProcess) URL() string
URL is the RIE invocation endpoint. It is empty outside RIE mode.
type FunctionSpec ¶
type FunctionSpec struct {
LogicalID string `json:"logicalId"`
Stack string `json:"stack"`
Runtime string `json:"runtime"`
Handler string `json:"handler"`
Architecture string `json:"architecture"`
MemoryMB int `json:"memoryMb"`
Timeout int `json:"timeout"`
LayerCount int `json:"layerCount"`
// Layers are the resolved Lambda layers, in the template's listed order.
// The runner extracts every layer into /opt in that order.
Layers []LayerSpec `json:"layers,omitempty"`
// LayerProblem names why the declared layers cannot be assembled locally.
// A served function with one fails closed.
LayerProblem string `json:"layerProblem,omitempty"`
// PackageType is Image for a container-image function.
PackageType string `json:"packageType,omitempty"`
// ImageAsset is the Docker image asset the function's Code.ImageUri names.
ImageAsset *DockerImageAssetSpec `json:"imageAsset,omitempty"`
Environment map[string]string `json:"environment,omitempty"`
// UnresolvedEnvironment lists environment names whose template value is a
// CloudFormation expression. The runner resolves the supported references
// before a function starts; one it cannot resolve fails closed.
UnresolvedEnvironment []string `json:"unresolvedEnvironment,omitempty"`
// EnvironmentExpressions holds the raw CloudFormation expression behind
// each unresolved name. It is internal: the runner resolves it to a local
// value and never prints it.
EnvironmentExpressions map[string]string `json:"-"`
// UnresolvedMemorySize and UnresolvedTimeout report that the template value
// is a CloudFormation expression. A served function with one of these fails
// closed instead of silently applying the AWS default.
UnresolvedMemorySize bool `json:"unresolvedMemorySize,omitempty"`
UnresolvedTimeout bool `json:"unresolvedTimeout,omitempty"`
// MemorySizeExpression and TimeoutExpression name the intrinsic (Ref,
// Fn::If, ...) behind an unresolved limit. They are display-only; the
// Unresolved* flags remain the fail-closed signals.
MemorySizeExpression string `json:"memorySizeExpression,omitempty"`
TimeoutExpression string `json:"timeoutExpression,omitempty"`
AssetDir string `json:"assetDir,omitempty"`
// OptDir is the merged /opt directory the run materializes from the
// function's layers. It is internal.
OptDir string `json:"-"`
InlineCode string `json:"-"`
InlineFile string `json:"inlineFile,omitempty"`
// CodeProblem is set when the function's code cannot be resolved locally.
// Only a served function fails the run because of it; an event-source
// function that the transport never invokes is reported, not blocking.
CodeProblem string `json:"codeProblem,omitempty"`
}
FunctionSpec is one Lambda function the assembly defines.
type FunctionURLSpec ¶
type FunctionURLSpec struct {
LogicalID string `json:"logicalId"`
Stack string `json:"stack"`
Function string `json:"function"`
Streaming bool `json:"streaming"`
}
FunctionURLSpec is one Lambda Function URL.
type HandlerError ¶
HandlerError reports a Lambda invocation that ended with a handler error instead of a proxy response.
func (*HandlerError) Error ¶
func (e *HandlerError) Error() string
type HandlerSpec ¶
type HandlerSpec struct {
CodeDir string
Runtime string
Handler string
Architecture string
MemoryMB int
Timeout int
Environment map[string]string
}
HandlerSpec describes one handler to run without a CDK definition. It is for examples that ship a Lambda handler but no CDK app: the caller supplies the built code directory and every request event. No routing is derived or invented.
type ImageBuildOptions ¶
type ImageBuildOptions struct {
Tag string
Directory string
DockerFile string
BuildArgs map[string]string
Target string
Platform string
Labels map[string]string
}
ImageBuildOptions describes one locally built container-image function.
type ImagePin ¶
type ImagePin struct {
Tag string `json:"tag"`
Digest string `json:"digest"`
Pinned string `json:"pinned"`
}
ImagePin is one digest-pinned Lambda runtime image in the local profile.
type InvokeRequest ¶
type InvokeRequest struct {
API APISpec
Route Route
FunctionURL *FunctionURLSpec
Params map[string]string
Method string
Path string
RawPath string
// StagePrefix is the "/{stage}" prefix the request used, or empty for a
// root (custom-domain) request. The REST v1 requestContext.path and the
// HTTP API v2 requestContext.http.path carry it; path and resource do not.
StagePrefix string
RawQuery string
Header http.Header
Body []byte
RemoteAddr string
RequestID string
Now time.Time
// AuthorizerContext is the context a CUSTOM authorizer returned for this
// request. It is carried as requestContext.authorizer.lambda, the same
// place API Gateway v2 puts a simple-response authorizer context.
AuthorizerContext map[string]any
// AuthorizerJWT is a JWT authorizer's validated claims; they are carried as
// requestContext.authorizer.jwt.claims with the token's scopes.
AuthorizerJWT map[string]any
// AuthorizerScopes are the scopes a JWT authorizer validated.
AuthorizerScopes []string
// AuthorizerClaims is a REST Cognito authorizer's claims; they are carried
// as requestContext.authorizer.claims.
AuthorizerClaims map[string]any
// AuthorizerPolicyContext is the context a Lambda authorizer that returns an
// IAM policy produced. It is stringified and carried as
// requestContext.authorizer for REST and HTTP API integrations.
AuthorizerPolicyContext map[string]any
}
InvokeRequest is one HTTP request translated into a provider event.
type InvokeResult ¶
type InvokeResult struct {
Proxy bool `json:"proxy"`
StatusCode int `json:"statusCode,omitempty"`
Headers map[string][]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
Streamed bool `json:"streamed,omitempty"`
Raw json.RawMessage `json:"raw,omitempty"`
RawText string `json:"rawText,omitempty"`
HandlerError string `json:"handlerError,omitempty"`
}
InvokeResult is one handler response. Proxy is true when the handler returned a Lambda proxy response (statusCode/headers/body); otherwise Raw carries the handler's JSON result unchanged.
type InvokeStreamResult ¶
type InvokeStreamResult struct {
Body []byte
// Streamed reports that the runtime sent a chunked response.
Streamed bool
// ContentType is the response Content-Type the runtime set.
ContentType string
// HandlerError is set when the runtime answered with an error instead of a
// response: an /error post, a timeout, a crash or an initialization
// failure. Body then carries the documented error JSON, so a sink can
// answer the invocation without waiting for a response that will never
// arrive.
HandlerError error
// ErrorType and ErrorBody are the midstream error trailers, when present.
ErrorType string
ErrorBody []byte
}
InvokeStreamResult is one invocation's outcome on the streaming path.
type KinesisDeliverer ¶
type KinesisDeliverer struct {
// contains filtered or unexported fields
}
KinesisDeliverer polls one Kinesis event source mapping.
func (*KinesisDeliverer) Start ¶
func (d *KinesisDeliverer) Start(ctx context.Context, env DelivererEnv) error
Start resolves the provisioned stream and polls its shards.
type KinesisRecordInput ¶
type KinesisRecordInput struct {
Data []byte
PartitionKey string
SequenceNumber string
// Arrival is the record's approximate arrival time. A zero value uses the
// batch time, which is what a hand-built session event does.
Arrival time.Time
}
KinesisRecordInput is one Kinesis record. Data is the raw payload the provider base64-encodes into the event.
type LambdaResponse ¶
type LambdaResponse struct {
StatusCode int
Headers map[string][]string
Cookies []string
Body []byte
// Streamed reports that the RIE returned a framed streaming response. The
// body is complete, not incremental.
Streamed bool
}
LambdaResponse is a decoded Lambda proxy response.
func DecodeResponse ¶
func DecodeResponse(raw []byte) (LambdaResponse, error)
DecodeResponse decodes a Runtime Interface Emulator response body. It accepts an ordinary proxy response, a base64 body, and the RIE's buffered streaming framing (metadata JSON, eight NUL bytes, body).
type LayerSpec ¶
type LayerSpec struct {
LogicalID string `json:"logicalId"`
// AssetDir is the layer content directory the cloud assembly holds.
AssetDir string `json:"-"`
}
LayerSpec is one Lambda layer a function declares.
type LocalSNSAttribute ¶
LocalSNSAttribute is one attribute a local publisher supplies.
type LocalSNSMessage ¶
type LocalSNSMessage struct {
Message string
Subject string
MessageAttributes map[string]LocalSNSAttribute
MessageGroupID string
MessageDeduplicationID string
}
LocalSNSMessage is one message the runner publishes through the local fan-out without going through moto. E3 and E4 use PublishLocal for rule and notification targets.
type MockResponse ¶
type MockResponse struct {
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers,omitempty"`
}
MockResponse is a REST API MOCK integration: the template declares the status and headers the transport returns instead of invoking a function. CDK uses it for CORS preflight.
type NotificationFilterRule ¶
NotificationFilterRule is one prefix or suffix rule of a notification's key filter.
type NotificationSpec ¶
type NotificationSpec struct {
// LogicalID is the qualified id plan and describe report. It is stable:
// <bucket>/notification/<index>.
LogicalID string `json:"logicalId"`
Stack string `json:"stack"`
Bucket string `json:"bucket"`
// BucketName is the physical bucket name the run provisioned.
BucketName string `json:"bucketName"`
// ConfigurationID is the id recorded in the notification's
// s3.configurationId. AWS assigns one when the configuration is applied.
ConfigurationID string `json:"configurationId"`
// DestinationType is function, queue, topic or eventbridge.
DestinationType string `json:"destinationType"`
// Destination is the qualified logical id of the target resource.
Destination string `json:"destination"`
// DestinationARN is the provider ARN the template declares for the target.
DestinationARN string `json:"destinationArn,omitempty"`
// DestinationName is the physical name delivery needs: a function name, a
// queue name or a topic ARN.
DestinationName string `json:"destinationName,omitempty"`
// Events are the declared event names with their s3: prefix, verbatim.
Events []string `json:"events,omitempty"`
// FilterRules are the prefix/suffix rules, in declared order.
FilterRules []NotificationFilterRule `json:"filterRules,omitempty"`
// EventBridge is true for the bucket's EventBridgeConfiguration.
EventBridge bool `json:"eventBridge,omitempty"`
}
NotificationSpec is one destination of a bucket's notification configuration. A bucket with two SQS entries and one Lambda entry produces three specs, so plan and describe report each destination separately.
type Options ¶
type Options struct {
// AppDir is the CDK app directory (the one containing cdk.json).
AppDir string
// Context is passed to `cdk synth` as -c key=value.
Context map[string]string
// AssemblyDir skips synthesis and reads an existing cloud assembly.
AssemblyDir string
// ScratchDir holds synthesis output and materialized inline code. It must
// live under $HOME or the checkout so Docker can bind-mount it.
ScratchDir string
// ProfilePath points at the checked-in local execution profile.
ProfilePath string
// Images overrides a profile pin per image class (go, node, python).
Images map[string]string
// Endpoints are the local AWS emulators every function container sees.
Endpoints []Endpoint
// AddHosts are extra --add-host entries for function containers.
AddHosts []string
// Backends are local emulators the runner starts on the run network from
// the profile (currently: dynamodb). Their endpoints and /etc/hosts entries
// are added automatically.
Backends []string
// PortBase pins the API listener ports; zero asks the OS for free ports.
PortBase int
// NamePrefix names containers, the network and built images. The default
// is derived from the app hash, so concurrent runs of one app share names
// unless a unique prefix is set.
NamePrefix string
// MaxConcurrency bounds in-flight invocations; never above 32.
MaxConcurrency int
// DeliveryConcurrency bounds concurrent handler invocations the delivery
// engine performs. Zero uses the documented default.
DeliveryConcurrency int
// Clock selects the run's time source: "real" (the default) or
// "test[=<RFC3339 start>]".
Clock string
// Stdout receives the runner's progress log.
Stdout io.Writer
// SynthTimeout bounds `cdk synth`.
SynthTimeout time.Duration
// Handler runs one handler from a built code directory instead of reading
// a CDK app. It is for examples that ship a Lambda handler but no CDK
// definition; the invoke caller supplies every request event.
Handler *HandlerSpec
// ExtraFunctions names additional CDK functions a session starts even
// though no route, event source or rule targets them. It exists for
// examples whose producer is invoked by a caller (the local session).
ExtraFunctions []string
// AllowNoSurface lets an invoke read an assembly whose functions have no
// HTTP route. Run and plan leave it false and refuse such an assembly.
AllowNoSurface bool
// Origins maps an external custom origin's domain to a loopback URL the
// local gateway may reach. An unmapped external origin is refused at plan
// time.
Origins map[string]string
// ViewerCountry is the run's resolved ISO 3166-1 alpha-2 viewer country for
// CloudFront geo restriction. An empty value is an undetermined location,
// which CloudFront serves.
ViewerCountry string
// RIEMode runs function containers under the image's embedded Runtime
// Interface Emulator instead of the runner's Runtime API. It exists to
// compare against the emulator and for an image whose entry script ignores
// AWS_LAMBDA_RUNTIME_API; it cannot stream incrementally.
RIEMode bool
// StreamChunks makes `invoke --stdio` write one chunk event per streamed
// response chunk before the result line. The default protocol stays one
// result line per event.
StreamChunks bool
// Watch re-synthesizes the app when its sources change, derives a new Spec
// and restarts only the functions whose execution inputs changed. The
// listeners and their URLs stay.
Watch bool
// DataDir keeps backend state across runs. An empty value keeps today's
// ephemeral behavior.
DataDir string
// Seed is a shell command that runs after provisioning and before the run
// reports ready. It is how a seed script drives the app through its own
// code paths.
Seed string
}
Options configure one local run.
type PlannedResource ¶
type PlannedResource struct {
LogicalID string `json:"logicalId"`
Stack string `json:"stack"`
Type string `json:"type"`
LocalID string `json:"localId"`
// Generated is true when the provider creates the identifier at run time
// (a KMS key id, a secret ARN suffix, a Cognito client id).
Generated bool `json:"generated,omitempty"`
}
PlannedResource is one resource the run provisions, with the local identifier the CDK definition determines before any backend starts.
type PreflightResult ¶
PreflightResult is what the in-container probe proved.
type Profile ¶
type Profile struct {
DynamoDBLocal struct {
Image string `json:"image"`
Port int `json:"port"`
} `json:"dynamodbLocal"`
// Containers are the digest-pinned local emulators the runner can start
// with --backend. dynamodbLocal remains the DynamoDB Local shortcut.
Containers map[string]ContainerPin `json:"containers"`
Lambda struct {
Images map[string]ImagePin `json:"images"`
} `json:"lambda"`
Endpoints map[string]struct {
Container string `json:"container"`
Env []string `json:"env"`
} `json:"endpoints"`
// CodeBuild pins the local agent and the curated build images. Images is
// keyed by the deployed Environment.Image and then by host architecture
// (aarch64 or x86_64), because AWS publishes different curated images per
// architecture.
CodeBuild struct {
Agent map[string]CodeBuildImagePin `json:"agent"`
Images map[string]map[string]CodeBuildImagePin `json:"images"`
} `json:"codeBuild"`
// contains filtered or unexported fields
}
Profile is the checked-in local execution profile the repo's harness and the local runner share. Only the sections the runner needs are read.
func LoadProfile ¶
LoadProfile reads a local execution profile.
func (*Profile) CodeBuildAgent ¶
CodeBuildAgent returns the digest-pinned local CodeBuild agent for an architecture. AWS publishes the x86_64 agent as :latest and the ARM agent as :aarch64.
func (*Profile) CodeBuildImage ¶
CodeBuildImage maps a project's Environment.Image to the profile's pinned local build image for the host architecture.
func (*Profile) Container ¶
func (p *Profile) Container(name string) (ContainerPin, error)
Container returns the digest-pinned emulator container a --backend name selects. "dynamodb-local" falls back to the legacy dynamodbLocal section so an A3a profile keeps working unchanged.
func (*Profile) DynamoDBImage ¶
DynamoDBImage returns the digest-pinned DynamoDB Local image.
func (*Profile) EndpointEnvNames ¶
EndpointEnvNames returns the environment variable names the profile binds to a service's endpoint. Without a profile the AWS-standard service override is used.
func (*Profile) EndpointsForContainer ¶
EndpointsForContainer returns the endpoints the profile binds to a container. The URL uses the container name, which resolves only inside the run network.
func (*Profile) ImageForClass ¶
ImageForClass returns the digest-pinned image for an image class (go, node or python).
type RealClock ¶
type RealClock struct{}
RealClock is the wall clock and the default.
type ResourceSpec ¶
type ResourceSpec struct {
Stack string `json:"stack"`
LogicalID string `json:"logicalId"`
Type string `json:"type"`
Properties json.RawMessage `json:"-"`
}
ResourceSpec is one template resource the runner can resolve a reference to.
type Route ¶
type Route struct {
Class APIClass `json:"class"`
Method string `json:"method"`
Path string `json:"path"`
Function string `json:"function,omitempty"`
// AuthorizerFunction is the Lambda function a CUSTOM HTTP API authorizer
// invokes before the route handler. The transport runs it; a route with an
// authorizer is never served without it.
AuthorizerFunction string `json:"authorizerFunction,omitempty"`
// AuthorizerIdentitySources lists the provider identity sources the
// authorizer event carries, in configured order, for example
// $request.header.Authorization. The transport refuses a request that does
// not carry every source before invoking the authorizer.
AuthorizerIdentitySources []string `json:"authorizerIdentitySources,omitempty"`
// AuthorizerKind is empty for a route with no authorizer, or one of the
// AuthorizerKind values: http-request-simple, http-jwt, lambda-request-policy,
// rest-cognito-user-pools.
AuthorizerKind AuthorizerKind `json:"authorizerKind,omitempty"`
// AuthorizerRESTType is the REST API authorizer Type (TOKEN or REQUEST) for
// a Lambda authorizer that returns an IAM policy.
AuthorizerRESTType string `json:"authorizerRestType,omitempty"`
// AuthorizerCacheTTLSeconds is AuthorizerResultTtlInSeconds on the run clock.
// Zero disables the authorizer result cache.
AuthorizerCacheTTLSeconds int `json:"authorizerCacheTtlSeconds,omitempty"`
// AuthorizerValidationExpression is a TOKEN authorizer's
// IdentityValidationExpression, applied to the token before the authorizer
// runs.
AuthorizerValidationExpression string `json:"authorizerValidationExpression,omitempty"`
// AuthorizerPayloadFormat is an HTTP API Lambda authorizer's payload format
// version (1.0 or 2.0).
AuthorizerPayloadFormat string `json:"authorizerPayloadFormat,omitempty"`
// JWTIssuer, JWTIssuerExpression and JWTAudience describe an HTTP API JWT
// authorizer. The expression is the raw template value until the run
// resolves it against the provisioned Cognito pool.
JWTIssuer string `json:"jwtIssuer,omitempty"`
JWTIssuerExpression string `json:"jwtIssuerExpression,omitempty"`
JWTJWTests []string `json:"-"`
JWTAudience []string `json:"jwtAudience,omitempty"`
JWTAudienceExpressions []string `json:"-"`
// JWKSURL and AcceptedIssuers are filled at run time, after the local
// issuer is known.
JWKSURL string `json:"jwksUrl,omitempty"`
AcceptedIssuers []string `json:"acceptedIssuers,omitempty"`
// CognitoPoolARNs are the pools a REST COGNITO_USER_POOLS authorizer names.
CognitoPoolARNs []string `json:"cognitoPoolArns,omitempty"`
// AuthorizationScopes are the scopes the route requires.
AuthorizationScopes []string `json:"authorizationScopes,omitempty"`
// Mock is set for a REST API MOCK integration. A mock route has no
// function and no invoker; the transport returns the declared response.
Mock *MockResponse `json:"mock,omitempty"`
Streaming bool `json:"streaming"`
// RouteKey is the API Gateway v2 route key, kept verbatim from the
// template. REST v1 and Function URL routes leave it empty.
RouteKey string `json:"routeKey,omitempty"`
}
Route is one HTTP route bound to a function.
func MatchRoute ¶
MatchRoute returns the route that should receive a request, or false when no route matches. Routes are ranked the way API Gateway ranks them: literal segments beat parameters, parameters beat greedy proxies, and the "$default" catch-all is last.
type RuleInputTransformer ¶
type RuleInputTransformer struct {
InputPathsMap map[string]string `json:"inputPathsMap,omitempty"`
InputTemplate string `json:"inputTemplate"`
}
RuleInputTransformer is a target's InputTransformer.
type RuleRetryPolicy ¶
type RuleRetryPolicy struct {
MaximumRetryAttempts int `json:"maximumRetryAttempts"`
MaximumEventAgeInSeconds int `json:"maximumEventAgeInSeconds"`
}
RuleRetryPolicy is a target's RetryPolicy.
type RuleSpec ¶
type RuleSpec struct {
LogicalID string `json:"logicalId"`
Stack string `json:"stack"`
Name string `json:"name"`
// BusName is the event bus the rule belongs to; "default" when omitted.
BusName string `json:"busName,omitempty"`
ARN string `json:"arn"`
Schedule string `json:"schedule,omitempty"`
// EventPattern is the rule's declared pattern, kept verbatim.
EventPattern json.RawMessage `json:"eventPattern,omitempty"`
// Targets lists the Lambda function targets, in declared order. It stays a
// function-only list so existing callers and the plan output keep their
// contract.
Targets []string `json:"targets,omitempty"`
// TargetSpecs is every deliverable target with its input shaping, retry
// policy and dead-letter configuration.
TargetSpecs []RuleTargetSpec `json:"targetSpecs,omitempty"`
Enabled bool `json:"enabled"`
}
RuleSpec is one AWS::Events::Rule. It is reported so a local session can build the event the rule would deliver, and it carries every target the runner can deliver.
type RuleTargetSpec ¶
type RuleTargetSpec struct {
ID string `json:"id,omitempty"`
Type string `json:"type"`
// Function, Queue and Topic are the qualified logical ids of the target.
Function string `json:"function,omitempty"`
Queue string `json:"queue,omitempty"`
Topic string `json:"topic,omitempty"`
// FunctionName, QueueName and TopicARN are the physical values delivery
// needs.
FunctionName string `json:"functionName,omitempty"`
QueueName string `json:"queueName,omitempty"`
TopicARN string `json:"topicArn,omitempty"`
// ARN is the target's provider ARN, used in the dead-letter attributes.
ARN string `json:"arn,omitempty"`
// Input, InputPath and InputTransformer are mutually exclusive shaping
// settings.
Input string `json:"input,omitempty"`
InputPath string `json:"inputPath,omitempty"`
InputTransformer *RuleInputTransformer `json:"inputTransformer,omitempty"`
// RetryPolicy governs the target attempts; a nil policy uses the AWS
// defaults (185 attempts, 86400 seconds).
RetryPolicy *RuleRetryPolicy `json:"retryPolicy,omitempty"`
// DeadLetterQueue and DeadLetterQueueName describe the target DLQ.
DeadLetterQueue string `json:"deadLetterQueue,omitempty"`
DeadLetterQueueName string `json:"deadLetterQueueName,omitempty"`
// SQSMessageGroupID is SqsParameters.MessageGroupId: a literal or a JSON
// path such as $.detail.group.
SQSMessageGroupID string `json:"sqsMessageGroupId,omitempty"`
}
RuleTargetSpec is one EventBridge rule target.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner owns one local run: the derived surface, the Docker network, the function containers and the HTTP listeners.
func NewRunner ¶
NewRunner validates the options and prepares the run. It contacts no Docker and synthesizes nothing yet.
func (*Runner) CleanScratch ¶
func (r *Runner) CleanScratch()
CleanScratch removes the run's scratch directory. It is safe to call more than once and never touches containers or the network.
func (*Runner) CurrentSpec ¶
CurrentSpec returns the surface the run is serving now. A watch reload replaces it under the same lock, so a session's describe reads the new definitions without racing the file watcher.
func (*Runner) Plan ¶
Plan synthesizes the app (unless an assembly was supplied) and derives the surface. It starts no containers.
func (*Runner) PlanJSON ¶
PlanJSON renders the derived surface for machines (the examples harness and future tooling).
func (*Runner) Preflight ¶
func (r *Runner) Preflight(ctx context.Context, network string, addHosts []string) (PreflightResult, error)
Preflight proves, from inside a function container, that the environment the runner is about to hand the app cannot reach real AWS: the credentials are the static dummy keys, every configured endpoint resolves and answers, the DynamoDB SDK resolves to the local endpoint, and a real AWS hostname does not resolve because the container has closed DNS.
func (*Runner) PublishLocal ¶
PublishLocal publishes one message to a local SNS topic through the same filter and fan-out path an observed SDK publish uses. E3 and E4 call it for their SNS rule and notification targets; it never goes through moto.
func (*Runner) PublishLocalMessage ¶
func (r *Runner) PublishLocalMessage(ctx context.Context, topicARN string, message LocalSNSMessage) error
PublishLocalMessage is PublishLocal with attributes, a subject and FIFO group/deduplication ids.
func (*Runner) ResolveDeliveryBackend ¶
func (r *Runner) ResolveDeliveryBackend(kind DeliveryKind) (DeliveryBackend, error)
ResolveDeliveryBackend resolves the local backend a source kind delivers from: the loopback endpoint the runner published and the host-side SDK client for the services that have one. EventBridge schedules and rules are served by the runner itself, so their backend is the engine; a kind whose emulator is not running fails closed before a deliverer starts.
func (*Runner) Run ¶
Run plans the app, starts the run's network, proves it cannot reach AWS, starts every function the CDK definition targets and serves the derived HTTP surface until the context is canceled.
func (*Runner) RunInvoke ¶
func (r *Runner) RunInvoke(ctx context.Context, functionID string, in io.Reader, out io.Writer) error
RunInvoke starts the target function once and sends newline-delimited JSON events read from in, writing one JSON result per event to out. The container stays warm for the whole stream, so session state persists across requests.
func (*Runner) RunSession ¶
RunSession is the automation interface behind `apptheory-local session`. It prepares the same run environment as Run, starts every function the CDK definition targets, serves any HTTP surface, and then reads one JSON command per line from in, writing one JSON response per line to out. It is how the examples harness receives real messages, writes real items and builds the event an event-source mapping would deliver.
func (*Runner) RuntimeMode ¶
RuntimeMode names the transport the run uses for its function containers.
type RuntimeAPIError ¶
RuntimeAPIError is one error the runtime reported, or one the runner synthesized in the documented Lambda error shape.
func (*RuntimeAPIError) Error ¶
func (e *RuntimeAPIError) Error() string
type S3NotificationDeliverer ¶
type S3NotificationDeliverer struct {
// contains filtered or unexported fields
}
S3NotificationDeliverer registers one destination configuration with the supervisor and keeps the source alive for the run.
func (*S3NotificationDeliverer) Start ¶
func (d *S3NotificationDeliverer) Start(ctx context.Context, env DelivererEnv) error
Start registers the configuration and waits until the run ends. The bucket watcher owns the poll loop.
type S3ObjectEvent ¶
type S3ObjectEvent struct {
Bucket string
BucketARN string
Key string
EventName string
ConfigurationID string
Size int64
ETag string
Sequencer string
Time time.Time
// Now is the observation instant; a delete has no object timestamp of its
// own, so its event time comes from the run clock.
Now time.Time
RequestID string
SourceIP string
// Reason is the S3 API the EventBridge detail names, for example PutObject.
Reason string
}
S3ObjectEvent is one observed object change the watcher turns into the provider's payload. The watcher observes real bucket state with ListObjectsV2; the event fields it cannot observe (request id, source IP) are derived the way S3 derives them for its own record.
type SNSDeliverer ¶
type SNSDeliverer struct {
// contains filtered or unexported fields
}
SNSDeliverer attaches one subscription to its topic's shared hub.
func (*SNSDeliverer) Start ¶
func (d *SNSDeliverer) Start(ctx context.Context, env DelivererEnv) error
Start attaches the subscription to the topic hub and reports armed. The hub owns the drain poller; every subscription of the topic shares it.
type SQSDeliverer ¶
type SQSDeliverer struct {
// contains filtered or unexported fields
}
SQSDeliverer polls one SQS event source mapping.
func (*SQSDeliverer) Start ¶
func (d *SQSDeliverer) Start(ctx context.Context, env DelivererEnv) error
Start resolves the queue, reports polling and runs the mapping's pollers until ctx is canceled.
type Skipped ¶
type Skipped struct {
LogicalID string `json:"logicalId"`
Kind string `json:"kind"`
Reason string `json:"reason"`
}
Skipped is a construct the assembly defines that the local transport does not serve. It is always reported, never silently dropped.
type Spec ¶
type Spec struct {
AssemblyDir string `json:"assemblyDir"`
Functions []FunctionSpec `json:"functions"`
APIs []APISpec `json:"apis"`
WebSockets []WebSocketAPISpec `json:"webSockets,omitempty"`
FunctionURLs []FunctionURLSpec `json:"functionUrls"`
EventSources []EventSourceSpec `json:"eventSources,omitempty"`
Rules []RuleSpec `json:"rules,omitempty"`
Subscriptions []SubscriptionSpec `json:"subscriptions,omitempty"`
// Notifications are the S3 bucket notification configurations. Each entry is
// one destination (function, queue, topic) or the bucket's EventBridge
// configuration, so plan and describe report them one by one.
Notifications []NotificationSpec `json:"notifications,omitempty"`
// CodeBuildProjects are the AWS::CodeBuild::Project resources the runner
// serves through AWS's local CodeBuild agent.
CodeBuildProjects []CodeBuildProjectSpec `json:"codeBuild,omitempty"`
Skipped []Skipped `json:"skipped"`
// Delivery is the state the engine would register for every source. Plan
// fills it; a live session reports the engine's own state instead.
Delivery []DeliveryState `json:"delivery,omitempty"`
// PlannedResources lists every resource the run provisions with the local
// identifier the CDK definition fixes before a backend starts.
PlannedResources []PlannedResource `json:"resources,omitempty"`
// CloudFront is the delivery topology read from the assembly. A refused
// distribution is also listed under Skipped with its reasons.
CloudFront []*localcloudfront.Distribution `json:"cloudFront,omitempty"`
CloudFrontFunctions []*localcloudfront.Function `json:"cloudFrontFunctions,omitempty"`
CloudFrontKeyGroups []*localcloudfront.KeyGroup `json:"cloudFrontKeyGroups,omitempty"`
CloudFrontPublicKeys []*localcloudfront.PublicKey `json:"cloudFrontPublicKeys,omitempty"`
CloudFrontKeyValueStores []*localcloudfront.KeyValueStore `json:"cloudFrontKeyValueStores,omitempty"`
// Resources is the assembly index used to resolve function environment
// references. It is internal and not part of the plan document.
Resources []ResourceSpec `json:"-"`
// Templates holds each stack's parameters, conditions and mappings for the
// intrinsic resolver. It never appears in plan output.
Templates map[string]templateContext `json:"-"`
// contains filtered or unexported fields
}
Spec is everything the local runner derived from the cloud assembly.
func (*Spec) CloudFrontEdgeFunctions ¶
CloudFrontEdgeFunctions returns the Lambda functions the served distributions associate through LambdaFunctionAssociations. They start with the rest of the run because no route or event source targets them.
func (*Spec) CloudFrontOriginFunctions ¶
CloudFrontOriginFunctions returns the functions the served distributions invoke as origins: every Function URL an origin or origin-group member targets. The gateway invokes the same container the runner starts for a standalone Function URL; an AWS_IAM URL is only reachable through the signed CloudFront origin path.
func (*Spec) Function ¶
func (s *Spec) Function(logicalID string) (FunctionSpec, bool)
Function returns the function spec for a logical id.
func (*Spec) FunctionURLsFor ¶
func (s *Spec) FunctionURLsFor(function string) []FunctionURLSpec
FunctionURLsFor returns the Function URL surfaces bound to one function.
func (*Spec) RuntimeFunctions ¶
RuntimeFunctions returns every function the runner must start: HTTP route and Function URL targets, HTTP API authorizers, enabled event-source consumers, enabled EventBridge rule targets and Lambda log-subscription destinations. It is the local run's function set.
func (*Spec) ServableCloudFront ¶
func (s *Spec) ServableCloudFront() []*localcloudfront.Distribution
ServableCloudFront returns the distributions the gateway can serve: no unsupported property refused it. The runner registers an origin implementation for every origin of such a distribution.
func (*Spec) ServedFunctions ¶
ServedFunctions returns the logical ids any HTTP surface targets, in sorted order. A function that only an event source mapping or EventBridge rule targets is not served over HTTP; use RuntimeFunctions for everything the runner must start.
func (*Spec) WebSocketAPIs ¶
func (s *Spec) WebSocketAPIs() []WebSocketAPISpec
WebSocketAPIs returns the WebSocket surfaces the runner serves.
type StreamSink ¶
type StreamSink interface {
// Start is called once before the first chunk with the response
// Content-Type. streamed is false when the runtime answered with a buffered
// response, which then arrives as a single chunk.
Start(contentType string, streamed bool) error
// Chunk is called for every chunk the runtime writes, in order.
Chunk(chunk []byte) error
// End is called after the last chunk with any midstream error trailers.
End(errorType string, errorBody []byte) error
}
StreamSink receives a response as the runtime writes it.
type SubscriptionSpec ¶
type SubscriptionSpec struct {
LogicalID string `json:"logicalId"`
Stack string `json:"stack"`
// Kind is cloudwatch-logs or sns.
Kind string `json:"kind"`
// LogGroup is the log group the filter reads.
LogGroup string `json:"logGroup,omitempty"`
// FilterName and FilterPattern are the declared filter.
FilterName string `json:"filterName,omitempty"`
FilterPattern string `json:"filterPattern,omitempty"`
// Distribution is the CloudWatch Logs distribution, when declared.
Distribution string `json:"distribution,omitempty"`
// Destination is the qualified logical id of the subscription target.
Destination string `json:"destination,omitempty"`
// DestinationType is function or stream.
DestinationType string `json:"destinationType,omitempty"`
// Function is set when the destination is a Lambda function.
Function string `json:"function,omitempty"`
// Stream and StreamName identify the Kinesis stream a CloudWatch Logs
// destination forwards to.
Stream string `json:"stream,omitempty"`
StreamName string `json:"streamName,omitempty"`
// Topic is the qualified logical id of the SNS topic the subscription
// targets. TopicARN is the provider ARN when it is literal or resolved from
// the assembly. ARN is the local subscription ARN the runner reports in
// the Lambda record, the HTTP headers and the UnsubscribeUrl.
Topic string `json:"topic,omitempty"`
TopicARN string `json:"topicArn,omitempty"`
ARN string `json:"arn,omitempty"`
// Protocol is lambda, sqs, http or https.
Protocol string `json:"protocol,omitempty"`
// Endpoint is the qualified Lambda function or SQS queue logical id, or the
// loopback URL of an HTTP(S) subscription.
Endpoint string `json:"endpoint,omitempty"`
// Queue is the qualified SQS queue for an sqs subscription.
Queue string `json:"queue,omitempty"`
// RawMessageDelivery is the subscription's raw message delivery setting.
RawMessageDelivery bool `json:"rawMessageDelivery,omitempty"`
// FilterPolicy is the declared subscription filter policy, verbatim.
FilterPolicy json.RawMessage `json:"filterPolicy,omitempty"`
// FilterPolicyScope is MessageAttributes (the default) or MessageBody.
FilterPolicyScope string `json:"filterPolicyScope,omitempty"`
}
SubscriptionSpec is one CloudWatch Logs subscription filter or SNS topic subscription. It is registered with the delivery engine and reported by plan and session describe. CloudWatch Logs delivery lands in E5; SNS delivery lands in E6.
type SynthOptions ¶
type SynthOptions struct {
AppDir string
OutputDir string
Context map[string]string
Stderr io.Writer
}
SynthOptions controls the CDK synthesis the runner performs before it reads the cloud assembly.
type TestClock ¶
type TestClock struct {
// contains filtered or unexported fields
}
TestClock is a deterministic clock. It never reads the wall clock; Advance moves it forward and fires every timer that is due, in scheduled order.
func NewTestClock ¶
NewTestClock builds a test clock at start.
func (*TestClock) Advance ¶
Advance moves the clock forward by d and fires every due timer with its scheduled instant. It reports how many timers fired.
type Transport ¶
type Transport struct {
API APISpec
Invokers map[string]Invoker
Semaphore chan struct{}
Now func() time.Time
// Clock is the run clock; a JWT's exp, nbf and iat are checked against it.
Clock Clock
Logf func(format string, args ...any)
// contains filtered or unexported fields
}
Transport serves one API surface and invokes the app's real handlers.
func NewTransport ¶
func NewTransport(api APISpec, invokers map[string]Invoker, semaphore chan struct{}, logf func(string, ...any)) *Transport
NewTransport builds a transport for an API surface.
type UnsupportedError ¶
UnsupportedError reports a construct the local runner refuses to guess about.
func (*UnsupportedError) Error ¶
func (e *UnsupportedError) Error() string
type WebSocketAPISpec ¶
type WebSocketAPISpec struct {
Class APIClass `json:"class"`
LogicalID string `json:"logicalId"`
Stack string `json:"stack"`
Name string `json:"name"`
Stage string `json:"stage"`
// RouteSelectionExpression is the API's expression, for example
// $request.body.action.
RouteSelectionExpression string `json:"routeSelectionExpression"`
Routes []WebSocketRouteSpec `json:"routes"`
// Authorizer is the $connect authorizer, when the API declares one.
Authorizer *WebSocketAuthorizerSpec `json:"authorizer,omitempty"`
// APIID is the id the events and the method ARN report. AWS assigns a
// ten-character id; the local run derives a stable one from the logical id.
APIID string `json:"apiId"`
}
WebSocketAPISpec is one WebSocket API the runner serves.
func (WebSocketAPISpec) Route ¶
func (api WebSocketAPISpec) Route(routeKey string) (WebSocketRouteSpec, bool)
Route returns the declared route for a key.
type WebSocketAuthorizerSpec ¶
type WebSocketAuthorizerSpec struct {
Function string `json:"function"`
IdentitySources []string `json:"identitySources,omitempty"`
// MethodARN is the $connect method ARN the returned policy is matched
// against: arn:aws:execute-api:<region>:<account>:<apiId>/<stage>/$connect
MethodARN string `json:"methodArn"`
}
WebSocketAuthorizerSpec is the $connect REQUEST authorizer.
type WebSocketRouteSpec ¶
type WebSocketRouteSpec struct {
RouteKey string `json:"routeKey"`
Function string `json:"function"`
// TwoWay is true for $default and custom routes: the integration's response
// is sent back to the client. $connect and $disconnect are one-way.
TwoWay bool `json:"twoWay"`
}
WebSocketRouteSpec is one route of a WebSocket API.
type WebSocketServer ¶
type WebSocketServer struct {
API WebSocketAPISpec
Invokers map[string]Invoker
Clock Clock
Semaphore chan struct{}
Management *webSocketManagement
Logf func(format string, args ...any)
Now func() time.Time
// DomainName is the host:port the event reports in requestContext; it is
// the management endpoint, so a handler that builds the management client
// from the request context reaches the local endpoint.
DomainName string
// contains filtered or unexported fields
}
WebSocketServer serves one WebSocket API.
func (*WebSocketServer) ServeHTTP ¶
func (s *WebSocketServer) ServeHTTP(writer http.ResponseWriter, request *http.Request)
ServeHTTP upgrades the connection and serves it until it closes.
func (*WebSocketServer) SetSurface ¶
func (s *WebSocketServer) SetSurface(api WebSocketAPISpec, invokers map[string]Invoker)
SetSurface swaps the route table and invoker set after a watch reload.
Source Files
¶
- assembly.go
- assembly_packaging.go
- authorizer_events.go
- authorizer_policy.go
- authorizers_runtime.go
- awsjson.go
- clients.go
- clock.go
- cloudfront_edge.go
- cloudfront_function.go
- cloudfront_origins.go
- cloudfront_r5a.go
- cloudfront_s3.go
- cloudwatch_filter.go
- cloudwatch_logs.go
- codebuild.go
- codebuild_api.go
- cognito_issuer.go
- control_listener.go
- data_dir.go
- delivery.go
- delivery_cloudwatch_logs.go
- delivery_dynamodb.go
- delivery_eventbridge.go
- delivery_kinesis.go
- delivery_runner.go
- delivery_s3.go
- delivery_sns.go
- delivery_sqs.go
- deploy.go
- derive_authorizers.go
- derive_events.go
- derive_http.go
- derive_s3.go
- derive_sns.go
- derive_websocket.go
- docker.go
- dynamodb_streams.go
- environment.go
- eventbridge_bus.go
- eventbridge_input.go
- eventbridge_schedule.go
- events.go
- eventsources.go
- function_logs.go
- function_runtime.go
- intrinsics.go
- invoke.go
- jwt.go
- model.go
- preflight.go
- process.go
- profile.go
- provision.go
- provision_services.go
- provision_sns.go
- readiness.go
- response.go
- routes.go
- runner.go
- runtime_api.go
- s3_notifications.go
- seed.go
- server.go
- session.go
- sns_filter.go
- sns_message.go
- sqs_filter.go
- stream.go
- stream_destination.go
- stream_poller.go
- synth.go
- ttl.go
- watch.go
- websocket.go
- websocket_management.go
- websocket_protocol.go