framework

package
v0.0.0-...-4391913 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 48 Imported by: 0

Documentation

Overview

Package framework runs AWS Lambda handlers with their dependencies wired in, on Powertools for AWS Lambda (Go): its logger, tracer and metrics, its Event Handler router, the AWS SDK clients, a database pool (Postgres, or Aurora DSQL through the AWS connector), and one place where every failure is reported.

A Lambda builds one Container at start-up, in main, and registers its business handlers. An API Gateway HTTP API registers typed operations, whose input the router binds and validates from the request:

func main() {
	c := framework.New()
	c.Get("/orders/{id}", getOrder)
	lambda.Start(c.HTTP())
}

type orderID struct {
	ID uuid.UUID `path:"id" format:"uuid"`
}

func getOrder(ctx context.Context, c *framework.Container, in orderID) (Order, error) {
	c.Logger.InfoContext(ctx, "reading order", "orderId", in.ID)
	...
}

The same routes serve an API Gateway REST API with a Lambda proxy integration: lambda.Start(c.REST()) instead of lambda.Start(c.HTTP()). A REST API endpoint that streams its response, server-sent events for one, is a Lambda of its own, whose handler writes through an http.ResponseWriter:

lambda.Start(c.Stream(watchOrder))

Any other event source hands its handler to Handle (for handlers that answer with a result) or Consume (for handlers that only succeed or fail):

lambda.Start(c.Consume(handleOrderPlaced))

Every invocation runs through the Powertools decorators (the logger's InjectContext, the tracer's CaptureLambdaHandler, the metrics' LogMetrics when metrics are configured). The AWS clients and the database pool are created on the first invocation and reused by every warm one. What belongs to one invocation (its request id, the client's address, its metric set) lives in the context: log with the Context methods (InfoContext, ErrorContext) so that records carry it, also when the execution environment runs several invocations at once (Lambda Managed Instances).

A handler reports a failure by returning it, and writes nothing itself: the framework logs it once, at Error, and that record is what error tracking reads. A handler that refuses an event on purpose (a Cognito trigger turning down a sign-up) returns Reject(err): the caller gets the same error, and the record is at Warn, except for an API Gateway request, whose expected failures are the 4xx of package response. An HTTP API or a REST API answers every failure with the error envelope of package response, the router's own (404, validation) included, instead of API Gateway's generic 500; so does a stream that fails before its first byte. With WithCORSOrigins (or CORS_ALLOW_ORIGINS) the API responses, error envelopes included, allow the listed origins.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Reject

func Reject(err error) error

Reject marks err as an expected rejection, for a handler that refuses an event on purpose: a Cognito pre-sign-up trigger turning down a disposable email, a failed anti-robot check.

return nil, framework.Reject(errors.New("disposable email"))

The caller receives it as it would receive err: the same message, the same errorType in Lambda, and errors.Is and errors.As reach err through it. Only the record changes: the framework writes it at Warn, as "handler rejected the event", instead of at Error, so that alerting on the error logs does not fire for a refusal the handler meant; its exception_name is still err's type. A rejection wrapped further (fmt.Errorf("check sign-up: %w", rejection)) is still one.

It is for Handle and Consume on events that are not API Gateway requests. A consumer's rejection still fails the event: Lambda retries it, and it may reach the DLQ. A route, a stream and any other handler of an API Gateway request answer an expected failure with a 4xx of package response instead: a Reject they return answers the 500 envelope and is written at Error, a failure like any other.

Reject(nil) is nil.

Types

type Consumer

type Consumer[E any] struct {
	// contains filtered or unexported fields
}

Consumer is what Consume returns: a Handler without a result.

func (Consumer[E]) Call

func (h Consumer[E]) Call(ctx context.Context, event E) error

Call runs one invocation with an event that is already decoded.

func (Consumer[E]) Invoke

func (h Consumer[E]) Invoke(ctx context.Context, payload []byte) ([]byte, error)

Invoke implements lambda.Handler.

type Container

type Container struct {
	Logger      *logging.Logger
	Tracer      *tracing.Tracer
	Metrics     *metrics.Metrics
	S3          *s3.Client
	EventBridge EventBridgeClient
	SFN         SFNClient
	Dynamo      *dynamodb.Client
	Websocket   *apigatewaymanagementapi.Client
	DB          *pgxpool.Pool
	// contains filtered or unexported fields
}

Container holds the dependencies a business handler works with: the Powertools logger, tracer and metrics, the AWS SDK clients and the database pool, to Postgres or to Aurora DSQL.

A Container built by New creates the clients it is missing and the database pool on the first invocation, once per cold start; a client already in a field (a test fake) is kept. A Container assembled by hand is used exactly as it is; a nil Logger, Tracer or Metrics is simply not used.

func New

func New(opts ...Option) *Container

New returns a Container with the Powertools logger and tracer ready, and the metrics when they are configured (see WithMetrics). The AWS clients and the database pool follow on the first invocation (see Handle), or on an explicit InitDB / InitEventBridge outside the Lambda lifecycle.

The utilities read their usual POWERTOOLS_* environment variables; the options above come first. New also routes the standard log package, which aws-lambda-go writes through, into the logger as structured records (runtimeLog), and OpenTelemetry's own errors to the logger at Warn: they are tracing trouble, not a failed invocation.

The tracer registers its provider and the X-Ray propagator as the global OpenTelemetry ones, as the AWS migration guide does in main: that state is per process, so build one Container per process.

func (*Container) ClientIP

func (c *Container) ClientIP(ctx context.Context) string

ClientIP returns the address of the client that called the API, looking past the trusted proxies set with WithTrustedProxies, for the request ctx belongs to (a routed request or a streaming one); "" outside an API Gateway request (HTTP API or REST API).

func (*Container) Close

func (c *Container) Close(ctx context.Context) error

Close releases what the container holds open: the database pool, and the tracer provider the tracer built, after exporting the spans it still holds (one passed with WithTracerProvider belongs to the caller). A Lambda never needs it, since every invocation flushes its spans and the environment is frozen and discarded as a whole; a task or CLI calls it before exiting.

func (*Container) Consume

func (c *Container) Consume[E any](h func(context.Context, *Container, E) error) Consumer[E]

Consume is Handle for business handlers that only succeed or fail, such as EventBridge, SQS, S3 and CloudWatch Logs consumers:

lambda.Start(c.Consume(HandleEvent))

The handler returns an error so a failure is a failure: Lambda retries the event and, when the retries run out, it lands in the DLQ. A consumer that swallowed its errors would turn "the event started nothing" into silence.

Example
package main

import (
	"context"
	"fmt"
	"io"

	"github.com/alessandrolattao/powertools-lambda-go/logging"
	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/lambda-framework-go/framework"
)

// handleOrderPlaced is a consumer: it only succeeds or fails.
func handleOrderPlaced(ctx context.Context, c *framework.Container, e events.EventBridgeEvent) error {
	c.Logger.InfoContext(ctx, "order placed", "detail", string(e.Detail))
	return nil
}

func main() {
	c := framework.New(framework.WithLogging(logging.WithWriter(io.Discard)))
	h := c.Consume(handleOrderPlaced) // in main: lambda.Start(h)

	err := h.Call(context.Background(), events.EventBridgeEvent{DetailType: "OrderPlaced", Detail: []byte(`{}`)})
	fmt.Println(err)
}
Output:
<nil>

func (*Container) Delete

func (c *Container) Delete[In, Out any](path string, op func(context.Context, *Container, In) (Out, error), opts ...eventhandler.RouteOption)

Delete registers a typed operation for DELETE path; see Get.

func (*Container) Get

func (c *Container) Get[In, Out any](path string, op func(context.Context, *Container, In) (Out, error), opts ...eventhandler.RouteOption)

Get registers a typed operation for GET path on the container's router: the Event Handler binds and validates In from the request (path, query, header and cookie fields, the body), and op receives the container, with its clients, next to it. Its result is the JSON response; a *response.Error is the error envelope.

func (*Container) HTTP

HTTP returns the Lambda handler serving the container's router to an API Gateway HTTP API (payload format 2.0):

c.Get("/orders/{id}", getOrder)
lambda.Start(c.HTTP())

The router runs inside Handle, so every request gets what every invocation gets (the Powertools decorators, initialization, failure reporting) plus what an API request gets: the "API request completed" record, the request described on the invocation's span, and the 500 envelope for a failure no error handler answered.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"uuid"

	"github.com/alessandrolattao/powertools-lambda-go/logging"
	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/lambda-framework-go/framework"
	"github.com/alessandrolattao/lambda-framework-go/response"
)

// getOrderInput is what GET /orders/{id} reads from the request; the router
// binds and validates it.
type getOrderInput struct {
	ID uuid.UUID `path:"id" format:"uuid"`
}

type order struct {
	ID string `json:"id"`
}

// getOrder is a business handler: its input is bound, its clients come with
// the container.
func getOrder(ctx context.Context, c *framework.Container, in getOrderInput) (order, error) {
	c.Logger.InfoContext(ctx, "reading order", "orderId", in.ID)
	if in.ID == uuid.Nil() {
		return order{}, response.NotFound("orderNotFound", "no order with this id", nil)
	}
	return order{ID: in.ID.String()}, nil
}

func main() {
	c := framework.New(framework.WithLogging(logging.WithWriter(io.Discard)))
	c.Get("/orders/{id}", getOrder)
	h := c.HTTP() // in main: lambda.Start(h)

	for _, path := range []string{"/orders/0b6f5c1e-4b8e-4f2a-9c3d-2a1b0c9d8e7f", "/orders/42", "/invoices"} {
		resp, err := h.Call(context.Background(), events.APIGatewayV2HTTPRequest{
			RawPath:        path,
			RequestContext: events.APIGatewayV2HTTPRequestContext{HTTP: events.APIGatewayV2HTTPRequestContextHTTPDescription{Method: "GET"}},
		})
		fmt.Println(resp.StatusCode, err)
	}
}
Output:
200 <nil>
422 <nil>
404 <nil>

func (*Container) Handle

func (c *Container) Handle[E, R any](h func(context.Context, *Container, E) (R, error)) Handler[E, R]

Handle adapts h, a business handler that answers with a result, into the handler lambda.Start expects:

lambda.Start(c.Handle(HandleRequest))

E and R are whatever event and response types h declares: API Gateway, Cognito triggers, a jsontext.Value carrying the raw payload of a direct invocation.

Every invocation runs through the Powertools decorators, as Powertools recommends stacking them: the logger's InjectContext (invocation keys, correlation id, sampling, buffering), the tracer's CaptureLambdaHandler (the invocation span, ColdStart and Service annotations) and the metrics' LogMetrics (one metric set per invocation, flushed at its end). Inside them the container is initialized (once per cold start), the business handler runs in a "## businessLogic" span, and a returned error or a panic is reported through the logger.

func (*Container) InitDB

func (c *Container) InitDB(ctx context.Context) error

InitDB opens the database pool: to the Aurora DSQL cluster when a DSQL endpoint is set (WithDSQLEndpoint, or DSQL_ENDPOINT), to Postgres when a connection string is (WithDatabaseURL, or DATABASE_URL). A Lambda gets it on its first invocation; code that runs outside the handler lifecycle (e.g. a Fargate task CLI) calls it directly. With neither there is no pool and no error; with both, an error. Idempotent: an existing pool is kept.

func (*Container) InitDBWithHost

func (c *Container) InitDBWithHost(ctx context.Context, host, port string) error

InitDBWithHost is like InitDB but connects to an overridden host/port, e.g. to reach the database through a tunnel on localhost. Postgres keeps the credentials and database name of the connection string; DSQL keeps the IAM token and the TLS verification of the endpoint. Empty overrides keep the original values.

func (*Container) InitEventBridge

func (c *Container) InitEventBridge(ctx context.Context) error

InitEventBridge mounts the EventBridge client for code that runs outside the Lambda lifecycle (e.g. a Fargate task CLI), which never invokes a handler. It loads the AWS config on demand since a bare New has none. Idempotent: an already-mounted client (including a test fake) is left untouched, mirroring InitDB.

func (*Container) Patch

func (c *Container) Patch[In, Out any](path string, op func(context.Context, *Container, In) (Out, error), opts ...eventhandler.RouteOption)

Patch registers a typed operation for PATCH path; see Get.

func (*Container) Post

func (c *Container) Post[In, Out any](path string, op func(context.Context, *Container, In) (Out, error), opts ...eventhandler.RouteOption)

Post registers a typed operation for POST path; see Get.

func (*Container) Put

func (c *Container) Put[In, Out any](path string, op func(context.Context, *Container, In) (Out, error), opts ...eventhandler.RouteOption)

Put registers a typed operation for PUT path; see Get.

func (*Container) REST

REST returns the Lambda handler serving the container's router to an API Gateway REST API with a Lambda proxy integration (payload format 1.0): the same routes as HTTP, so moving a Lambda from an HTTP API to a REST API changes only the line that starts it:

c.Get("/orders/{id}", getOrder)
lambda.Start(c.REST())

A REST API request gets what an HTTP API request gets: the "API request received" and "API request completed" records, the request described on the invocation's span, client_ip and ClientIP, and the 500 envelope for a failure no error handler answered. The claim functions of package request read the claims of a Cognito user pool authorizer.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"uuid"

	"github.com/alessandrolattao/powertools-lambda-go/logging"
	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/lambda-framework-go/framework"
	"github.com/alessandrolattao/lambda-framework-go/response"
)

// getOrderInput is what GET /orders/{id} reads from the request; the router
// binds and validates it.
type getOrderInput struct {
	ID uuid.UUID `path:"id" format:"uuid"`
}

type order struct {
	ID string `json:"id"`
}

// getOrder is a business handler: its input is bound, its clients come with
// the container.
func getOrder(ctx context.Context, c *framework.Container, in getOrderInput) (order, error) {
	c.Logger.InfoContext(ctx, "reading order", "orderId", in.ID)
	if in.ID == uuid.Nil() {
		return order{}, response.NotFound("orderNotFound", "no order with this id", nil)
	}
	return order{ID: in.ID.String()}, nil
}

func main() {
	c := framework.New(framework.WithLogging(logging.WithWriter(io.Discard)))
	c.Get("/orders/{id}", getOrder) // the same routes as behind an HTTP API
	h := c.REST()                   // in main: lambda.Start(h)

	for _, path := range []string{"/orders/0b6f5c1e-4b8e-4f2a-9c3d-2a1b0c9d8e7f", "/orders/42", "/invoices"} {
		resp, err := h.Call(context.Background(), events.APIGatewayProxyRequest{HTTPMethod: "GET", Path: path})
		fmt.Println(resp.StatusCode, err)
	}
}
Output:
200 <nil>
422 <nil>
404 <nil>

func (*Container) Router

func (c *Container) Router() *eventhandler.Router

Router returns the container's Event Handler router, for what the route methods below do not cover: plain http.Handler routes, middlewares, sub-routers, error handlers, the OpenAPI document. Register routes in main, before serving: the router is built on first use, and registering is not safe during requests.

func (*Container) Stream

Stream returns the Lambda handler of one API Gateway REST API endpoint that streams its response, server-sent events for one:

lambda.Start(c.Stream(watch))

func watch(ctx context.Context, c *framework.Container, req events.APIGatewayProxyRequest, w http.ResponseWriter) error {
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-store")
	for price := range prices(ctx) {
		if err := response.SSE(w, "price", price); err != nil {
			return err
		}
	}
	return nil
}

op writes the response through w, a plain http.ResponseWriter that is also an http.Flusher. Header and WriteHeader set the headers and the status (200 unless op sets one); the first Write or Flush sends them, and from then on whatever op writes reaches the client as it is written, Flush (or http.NewResponseController(w).Flush()) included. A Set-Cookie header goes out as the cookies of the response, a header with several values as its multiValueHeaders.

API Gateway streams a response only from an integration whose responseTransferMode is STREAM, which invokes the function through the response-streaming-invocations URI: a streaming endpoint is a Lambda of its own, and the router does not serve it. The metadata (status and headers) must stay within 16 KB.

The invocation gets what Handle gives an API request: the Powertools decorators, initialization, the "API request received" record, op in the "## businessLogic" span, and the "API request completed" record when the stream closes, with the status sent and the time the stream stayed open. In op, ClientIP and the claim functions of package request read the request as in a typed operation.

An error op returns before anything has gone out answers as a typed operation's does: a *response.Error with its status and envelope (reported when it is a 5xx), any other error with the 500 envelope, reported. After the first byte the status is gone: an error or a panic is reported, and the stream ends there.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/alessandrolattao/powertools-lambda-go/logging"
	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/lambda-framework-go/framework"
	"github.com/alessandrolattao/lambda-framework-go/response"
)

// watchPrices is a streaming handler: each price reaches the client as a
// server-sent event as soon as it is written.
func watchPrices(_ context.Context, _ *framework.Container, _ events.APIGatewayProxyRequest, w http.ResponseWriter) error {
	w.Header().Set("Content-Type", "text/event-stream")
	for _, price := range []string{`{"amount":41}`, `{"amount":42}`} {
		if err := response.SSE(w, "price", price); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	c := framework.New(framework.WithLogging(logging.WithWriter(io.Discard)))
	h := c.Stream(watchPrices) // in main: lambda.Start(h)

	r, err := h(context.Background(), events.APIGatewayProxyRequest{HTTPMethod: "GET", Resource: "/prices", Path: "/prices"})
	if err != nil {
		fmt.Println(err)
		return
	}
	stream, err := io.ReadAll(r)
	if err != nil {
		fmt.Println(err)
		return
	}
	// What Lambda hands API Gateway: the metadata, 8 null bytes, the body.
	metadata, body, _ := strings.Cut(string(stream), strings.Repeat("\x00", 8))
	fmt.Println(metadata)
	fmt.Print(body)
}
Output:
{"statusCode":200,"headers":{"Content-Type":"text/event-stream"}}
event: price
data: {"amount":41}

event: price
data: {"amount":42}

type EventBridgeClient

type EventBridgeClient interface {
	PutEvents(ctx context.Context, params *eventbridge.PutEventsInput, optFns ...func(*eventbridge.Options)) (*eventbridge.PutEventsOutput, error)
}

EventBridgeClient is the part of *eventbridge.Client handlers use. Using an interface allows tests to inject a fake without hitting AWS.

type Handler

type Handler[E, R any] struct {
	// contains filtered or unexported fields
}

Handler is what Handle returns. lambda.Start takes it as a lambda.Handler: it decodes the payload into E, runs the business handler and encodes the result, with encoding/json/v2 both ways. Call runs it with an event that is already decoded, which is what a test wants.

Because the JSON is done here, the JSON options of aws-lambda-go (WithSetEscapeHTML, WithUseNumber, WithDisallowUnknownFields, ...) do not apply to it; its runtime options (WithContext, WithEnableSIGTERM) do.

func (Handler[E, R]) Call

func (h Handler[E, R]) Call(ctx context.Context, event E) (R, error)

Call runs one invocation with an event that is already decoded, through the same Powertools decorators as Invoke.

func (Handler[E, R]) Invoke

func (h Handler[E, R]) Invoke(ctx context.Context, payload []byte) ([]byte, error)

Invoke implements lambda.Handler. A payload that does not decode and a result that does not encode are failures like any other: reported, and returned to the runtime.

type Option

type Option func(*Container)

Option configures a Container built by New.

func WithCORSOrigins

func WithCORSOrigins(origins ...string) Option

WithCORSOrigins sets the origins a browser may call the API from, as the browser sends them in the Origin header (https://app.example.com: scheme, host and a port other than the default). Without it New reads CORS_ALLOW_ORIGINS, the origins separated by commas; with neither, CORS is off and no response changes.

A request whose Origin is one of them gets Access-Control-Allow-Origin with that origin, in place of any the response already had, and Origin in Vary; any other request gets no CORS header. The rule covers every response HTTP, REST and Stream answer, the error envelopes included, and the response of any Handle handler that answers with an API Gateway response (events.APIGatewayV2HTTPResponse, events.APIGatewayProxyResponse). The preflight OPTIONS request and the responses API Gateway writes itself belong to the API's own configuration. Use it or the router's CORS (WithRouter(eventhandler.WithCORS(...))), not both.

func WithDSQLEndpoint

func WithDSQLEndpoint(endpoint string) Option

WithDSQLEndpoint sets the endpoint of the Aurora DSQL cluster the pool connects to, <cluster id>.dsql.<region>.on.aws, in the region in AWS_REGION. Without it New reads DSQL_ENDPOINT.

DSQL has no password: the pool connects as the database user admin with an IAM token, which the AWS connector signs for every new connection with the function's credentials. The function's role needs dsql:DbConnectAdmin on the cluster; an SST link to the cluster grants it.

A container gets one database: a DSQL endpoint together with a Postgres connection string (WithDatabaseURL or DATABASE_URL) fails the initialization.

func WithDatabaseURL

func WithDatabaseURL(url string) Option

WithDatabaseURL sets the Postgres connection string, in URL (postgres://user:pass@host:5432/db?sslmode=require) or keyword/value form. Without it New reads DATABASE_URL; with neither, and no DSQL endpoint, the container has no pool.

An application deployed with SST reads the linked database resource in its main and passes the string here: the password then stays in the encrypted bundle SST ships, instead of a plaintext environment variable.

func WithLogging

func WithLogging(opts ...logging.Option) Option

WithLogging passes options to the Powertools logger (level, sampling, buffering, output format).

func WithMetrics

func WithMetrics(opts ...metrics.Option) Option

WithMetrics turns the Powertools metrics on and passes them options (namespace, default dimensions, a Datadog provider). Metrics are also on when POWERTOOLS_METRICS_NAMESPACE is set; otherwise the container has no Metrics, and no invocation flushes an empty metric set.

func WithRouter

func WithRouter(opts ...eventhandler.Option) Option

WithRouter passes options to the container's Event Handler router: CORS, debug mode, strip prefixes, OpenAPI metadata.

func WithService

func WithService(name string) Option

WithService names the service the function belongs to, for the logger (the service key), the tracer (the X-Ray service and the Service annotation) and the metrics (the service dimension). The default is POWERTOOLS_SERVICE_NAME, else the function's name, which reads better in X-Ray and CloudWatch than Powertools' own "service_undefined".

func WithTracerProvider

func WithTracerProvider(tp trace.TracerProvider) Option

WithTracerProvider replaces the tracer provider the Powertools tracer builds for Lambda (X-Ray UDP exporter), e.g. with one that exports over OTLP to a collector outside Lambda, or with one that records spans in a test.

func WithTracing

func WithTracing(opts ...tracing.Option) Option

WithTracing passes options to the Powertools tracer.

func WithTrustedProxies

func WithTrustedProxies(n int) Option

WithTrustedProxies tells the container how many proxies of yours sit in front of API Gateway (CloudFront is one), so that ClientIP and the logs find the caller's address behind them. The default, 0, trusts nothing but the address API Gateway itself saw.

type SFNClient

type SFNClient interface {
	StartExecution(ctx context.Context, params *sfn.StartExecutionInput, optFns ...func(*sfn.Options)) (*sfn.StartExecutionOutput, error)
}

SFNClient is the part of *sfn.Client handlers use. Using an interface allows tests to inject a fake without hitting AWS.

Jump to

Keyboard shortcuts

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