eventsource

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package eventsource is the Go side of Powertools for AWS Lambda (Python)'s event source data classes: the event types aws-lambda-go lacks, the members its partial types leave out, and the helpers Powertools adds on top of them.

github.com/aws/aws-lambda-go/events already has a struct for most event sources, and a handler receives it typed. This package does not redeclare any of them. It adds:

  • the events aws-lambda-go has no type for: AppSync resolvers and AppSync Events, Bedrock agents, CloudWatch alarm actions and dashboard custom widgets, CodeDeploy lifecycle hooks, Cognito custom senders, the IoT Core registry events, S3 notifications through EventBridge, Transfer Family authorizers and VPC Lattice (payload versions 1 and 2);
  • extensions of the aws-lambda-go types that miss members Powertools reads (ActiveMQ, API Gateway REST and REQUEST authorizers, CloudWatch Logs, CloudFormation, CodePipeline, Cognito, Config, Connect, EventBridge, Firehose responses, S3 Object Lambda, SES, Kinesis and DynamoDB tumbling windows);
  • helpers: request bodies and headers of every HTTP source, cookies, the API Gateway authorizer policy builder, DynamoDB attribute values to Go values, S3 key decoding, SQS queue URLs and nested S3 and SNS events, gzip and zlib payloads, CodePipeline artifacts (subpackage eventsource/codepipeline), Transfer Family and S3 Batch Operations responses, AppSync scalars.

Extended types

An extension embeds the aws-lambda-go type and declares the missing members next to it, shadowing the embedded member that must change type:

type APIGatewayProxyRequest struct {
	events.APIGatewayProxyRequest

	Version        string                        `json:"version,omitempty"`
	RequestContext APIGatewayProxyRequestContext `json:"requestContext"`
}

encoding/json (v1, used by lambda.Start) and encoding/json/v2 both decode the shadowing member and ignore the embedded one, so read the context as e.RequestContext; e.APIGatewayProxyRequest.RequestContext stays empty. Every other member is promoted, and Go 1.27 composite literals can set promoted members directly. When the container of an extended element would have to change too (SES records, the CodePipeline job), the container is redeclared, still embedding what it can.

Kafka events belong to the kafka package.

HTTP events

Body, JSONBody, Header, HeaderValues, QueryParameter, QueryParameterValues, Cookies, Path and Method accept any HTTP event (the HTTPRequest type set: API Gateway REST, HTTP and WebSocket APIs, ALB, Function URLs, VPC Lattice):

func handle(ctx context.Context, event events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
	token, _ := eventsource.Header(event, "authorization")
	order, err := eventsource.JSONBody[Order](event)
	...
}

Header names match case-insensitively, query string parameters exactly. Body decodes base64 bodies. Cookies parses as leniently as Powertools Python. Path strips the HTTP API stage from the raw path.

Decoding is lenient

As in aws-lambda-go, unknown members are ignored and missing ones stay zero; nothing is validated. Members Powertools treats as optional are pointers or carry omitempty. A few members accept more than one JSON shape because AWS sends more than one: VPC Lattice v2 headers (StringValues), its timeEpoch (EpochMicros), the AppSync prev object. For typed payloads with validation, see the parser package.

Differences from Python

  • No dictionary wrapper: the types are plain structs, decoded once; the Python properties that only read a member are the struct fields.
  • Helpers return errors instead of raising KeyError or IndexError, and compute on each call instead of caching.
  • JSON helpers (json_body, decoded_user_parameters, reason_data_decoded, rule_parameters) are generic and decode into a type of your choice.
  • DynamoDB numbers are Number values that keep every digit, binary values are bytes (Python keeps the base64 text), sets are slices.
  • The deprecated get_header_value, the advancing iterators of Kafka and ActiveMQ events and the event_source decorator are not ported: Go handlers are typed already and slices are iterated with range.
  • AppSync identities are one struct whose Authorization method tells Cognito, OIDC, IAM and Lambda identities apart (Python only tells Cognito from IAM). AppSync Events with no events are not given a placeholder event.
  • The ALB query parameter decoding switch and the response header serializers belong to the event handler.

Upstream bugs fixed: the authorizer policy writes Condition as the object IAM expects (Python writes a list) and keeps the ARN partition; SQSQueueURL uses the partition's DNS suffix; the HTTP API path is only stripped of a stage it starts with; the EFS Transfer Family response carries the uid (Python writes the gid twice); VPC Lattice v2 headers and parameters with several values are kept as lists; IoT timestamps are UTC; the version-id of an S3 EventBridge object is optional; CloudWatch Logs payloads may be zlib as well as gzip; Kinesis and DynamoDB tumbling window state may hold any JSON value.

Index

Examples

Constants

View Source
const (
	AppSyncEventsPublish   = "PUBLISH"
	AppSyncEventsSubscribe = "SUBSCRIBE"
)

The AppSync Events operations.

View Source
const (
	CloudWatchAlarmStateOK               = "OK"
	CloudWatchAlarmStateAlarm            = "ALARM"
	CloudWatchAlarmStateInsufficientData = "INSUFFICIENT_DATA"
)

The values of an alarm state.

View Source
const (
	ConfigConfigurationItemChangeNotification          = "ConfigurationItemChangeNotification"
	ConfigOversizedConfigurationItemChangeNotification = "OversizedConfigurationItemChangeNotification"
	ConfigScheduledNotification                        = "ScheduledNotification"
)

The message types of an AWS Config invoking event.

View Source
const (
	ConnectChannelVoice = "VOICE"
	ConnectChannelChat  = "CHAT"
)

The channels of a contact.

View Source
const (
	ConnectInitiationInbound  = "INBOUND"
	ConnectInitiationOutbound = "OUTBOUND"
	ConnectInitiationTransfer = "TRANSFER"
	ConnectInitiationCallback = "CALLBACK"
	ConnectInitiationAPI      = "API"
)

The ways a contact can be initiated.

View Source
const (
	IoTThingEvent                = "THING_EVENT"
	IoTThingTypeEvent            = "THING_TYPE_EVENT"
	IoTThingTypeAssociationEvent = "THING_TYPE_ASSOCIATION_EVENT"
	IoTThingGroupEvent           = "THING_GROUP_EVENT"
	IoTThingGroupMembershipEvent = "THING_GROUP_MEMBERSHIP_EVENT"
	IoTThingGroupHierarchyEvent  = "THING_GROUP_HIERARCHY_EVENT"
)

The event types of the IoT Core registry events.

View Source
const (
	IoTOperationCreated = "CREATED"
	IoTOperationUpdated = "UPDATED"
	IoTOperationDeleted = "DELETED"
	IoTOperationAdded   = "ADDED"
	IoTOperationRemoved = "REMOVED"
)

The operations of the IoT Core registry events.

View Source
const (
	S3BatchSucceeded        = "Succeeded"
	S3BatchTemporaryFailure = "TemporaryFailure"
	S3BatchPermanentFailure = "PermanentFailure"
)

The result codes of an S3 Batch Operations task.

View Source
const (
	SQSAttributeAWSTraceHeader                   = "AWSTraceHeader"
	SQSAttributeApproximateReceiveCount          = "ApproximateReceiveCount"
	SQSAttributeSentTimestamp                    = "SentTimestamp"
	SQSAttributeSenderID                         = "SenderId"
	SQSAttributeApproximateFirstReceiveTimestamp = "ApproximateFirstReceiveTimestamp"
	SQSAttributeSequenceNumber                   = "SequenceNumber"
	SQSAttributeMessageGroupID                   = "MessageGroupId"
	SQSAttributeMessageDeduplicationID           = "MessageDeduplicationId"
	SQSAttributeDeadLetterQueueSourceARN         = "DeadLetterQueueSourceArn"
)

The names of the SQS system attributes a message carries.

View Source
const (
	TransferFamilyHomeDirectoryPath    = "PATH"
	TransferFamilyHomeDirectoryLogical = "LOGICAL"
)

The home directory types of a Transfer Family user.

View Source
const ConnectEndpointTelephoneNumber = "TELEPHONE_NUMBER"

ConnectEndpointTelephoneNumber is the type of a telephone endpoint.

View Source
const MaxDecompressedSize = 128 << 20

MaxDecompressedSize bounds what Decompress inflates, so that a small malicious payload cannot exhaust the function's memory.

View Source
const ResourcePathPattern = `^[/.a-zA-Z0-9\-_\*\{\}\+]+$`

ResourcePathPattern is what a resource path of an authorizer policy must match, as in Powertools Python.

Variables

View Source
var (
	// ErrInvalidRouteARN reports a method or route ARN that is not an API
	// Gateway execute-api ARN.
	ErrInvalidRouteARN = errors.New("invalid API Gateway route ARN")
	// ErrInvalidHTTPVerb reports a route whose method is not an HTTPVerb.
	ErrInvalidHTTPVerb = errors.New("invalid HTTP verb")
	// ErrInvalidResourcePath reports a route whose resource does not match
	// ResourcePathPattern.
	ErrInvalidResourcePath = errors.New("invalid resource path")
	// ErrNoStatements reports a policy built without any route.
	ErrNoStatements = errors.New("no statements defined for the policy")
)

Errors of the API Gateway authorizer helpers.

View Source
var (
	// ErrEmptyResponse reports a response with no record, which Firehose
	// and S3 Batch Operations reject.
	ErrEmptyResponse = errors.New("response has no record")
	// ErrInvalidResult reports a result or result code the service does not
	// know.
	ErrInvalidResult = errors.New("invalid result")
)

Errors of the response helpers.

View Source
var (
	// ErrTooLarge reports compressed data that inflates beyond
	// MaxDecompressedSize.
	ErrTooLarge = errors.New("decompressed data is too large")
	// ErrNotCompressed reports data that is neither gzip nor zlib.
	ErrNotCompressed = errors.New("data is neither gzip nor zlib compressed")
)

Errors of the decompression helpers.

View Source
var ErrInvalidHomeDirectory = errors.New("invalid home directory")

ErrInvalidHomeDirectory reports a Transfer Family response without the home directory its type needs.

View Source
var ErrInvalidNumber = errors.New("invalid DynamoDB number")

ErrInvalidNumber reports a DynamoDB number that is not a decimal number.

View Source
var ErrInvalidQueueARN = errors.New("invalid SQS queue ARN")

ErrInvalidQueueARN reports an event source ARN that is not an SQS queue ARN.

Functions

func AWSDate

func AWSDate(offsetHours int) string

AWSDate returns today's date as an AppSync AWSDate scalar, in UTC shifted by offsetHours, with the zone suffix Powertools Python writes ("Z" or "+05:00:00").

func AWSDateTime

func AWSDateTime(offsetHours int) string

AWSDateTime returns the current instant as an AppSync AWSDateTime scalar, with millisecond precision, shifted by offsetHours.

func AWSTime

func AWSTime(offsetHours int) string

AWSTime returns the current time as an AppSync AWSTime scalar, with millisecond precision, shifted by offsetHours.

func AWSTimestamp

func AWSTimestamp() int64

AWSTimestamp returns the current time as an AppSync AWSTimestamp scalar: whole seconds since the Unix epoch.

func Body

func Body[E HTTPRequest](e E) ([]byte, error)

Body returns the request body, base64-decoded when the event says it is encoded. A body that is not text (an upload) stays intact: it is returned as bytes, not forced through UTF-8.

func Cookies

func Cookies[E HTTPRequest](e E) map[string]string

Cookies returns the request cookies by name. HTTP API and Function URL events carry them in their cookies list; the other sources in the Cookie header (single or multi-value). Parsing is as lenient as Powertools Python's: segments without "=" are skipped, values are not unquoted, a later duplicate wins.

func DecodeBody

func DecodeBody(body string, isBase64Encoded bool) ([]byte, error)

DecodeBody decodes a request body that may be base64 encoded.

func DecodeDynamoDBImage

func DecodeDynamoDBImage[T any](image map[string]events.DynamoDBAttributeValue) (T, error)

DecodeDynamoDBImage decodes a stream record image into a T through its JSON rendering (DynamoDBImageJSON): fields match the attribute names with their json tags.

Example
package main

import (
	"fmt"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventsource"
)

func main() {
	type item struct {
		ID    string  `json:"pk"`
		Total float64 `json:"total"`
	}
	image := map[string]events.DynamoDBAttributeValue{
		"pk":    events.NewStringAttribute("order#1"),
		"total": events.NewNumberAttribute("12.50"),
	}

	got, err := eventsource.DecodeDynamoDBImage[item](image)
	if err != nil {
		panic(err)
	}
	fmt.Println(got.ID, got.Total)
}
Output:
order#1 12.5

func DecodeMQData

func DecodeMQData(data string) ([]byte, error)

DecodeMQData decodes the base64 body of an Amazon MQ message, ActiveMQ or RabbitMQ (events.RabbitMQMessage.Data).

func Decompress

func Decompress(data []byte) ([]byte, error)

Decompress inflates gzip or zlib data, recognizing the format from its header as Python's zlib.decompress(data, MAX_WBITS | 32) does. CloudWatch Logs subscriptions, and producers that compress Kinesis records, use it.

func DynamoDBImage

func DynamoDBImage(image map[string]events.DynamoDBAttributeValue) (map[string]any, error)

DynamoDBImage converts a stream record image (Keys, NewImage, OldImage) into a map of Go values; see DynamoDBValue. A nil image gives an empty map, as Powertools Python gives an empty dict.

func DynamoDBImageJSON

func DynamoDBImageJSON(image map[string]events.DynamoDBAttributeValue) (jsontext.Value, error)

DynamoDBImageJSON renders a stream record image as a JSON object: numbers as JSON numbers with every digit, binary values as base64 strings, sets as arrays. It is the bridge to typed structs.

func DynamoDBValue

func DynamoDBValue(av events.DynamoDBAttributeValue) (any, error)

DynamoDBValue converts an attribute value of a stream record into a Go value, the way Powertools Python's TypeDeserializer does: NULL is nil, BOOL a bool, N a Number, S a string, B a []byte, SS a []string, NS a []Number, BS a [][]byte, L a []any and M a map[string]any.

Two differences from Python: binary values are bytes (Python keeps the base64 text) and sets are slices (Python builds a set).

func Header[E HTTPRequest](e E, name string) (string, bool)

Header returns the value of the named header, matched case-insensitively. Sources that only fill the multi-value map (an ALB target group with multi-value headers on) answer from it, with the last value, which is what API Gateway puts in the single-value map. VPC Lattice v2 headers with several values come back joined with commas.

Example
package main

import (
	"fmt"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventsource"
)

func main() {
	event := events.APIGatewayProxyRequest{
		Headers: map[string]string{"Content-Type": "application/json", "Cookie": "session=abc; theme=dark"},
		Body:    `{"id":"o-1"}`,
	}

	contentType, _ := eventsource.Header(event, "content-type")
	fmt.Println(contentType)
	fmt.Println(eventsource.Cookies(event)["session"])
}
Output:
application/json
abc

func HeaderValues

func HeaderValues[E HTTPRequest](e E, name string) []string

HeaderValues returns every value of the named header, matched case-insensitively: the multi-value map when the source has one, otherwise the single value. Like Powertools Python's resolved_headers_field, the sources that fold repeated headers into one value (HTTP API, Function URL, VPC Lattice v1) have it split on commas.

func JSONBody

func JSONBody[T any, E HTTPRequest](e E) (T, error)

JSONBody decodes the request body, base64-decoded first when needed, as JSON into a T. An empty body gives the zero T, as Powertools Python's json_body gives None. Decoding is lenient (unknown members are ignored); the parser package adds validation.

Example
package main

import (
	"fmt"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventsource"
)

func main() {
	type order struct {
		ID string `json:"id"`
	}
	event := events.APIGatewayV2HTTPRequest{Body: "eyJpZCI6Im8tMSJ9", IsBase64Encoded: true}

	o, err := eventsource.JSONBody[order](event)
	if err != nil {
		panic(err)
	}
	fmt.Println(o.ID)
}
Output:
o-1

func LookupHeader

func LookupHeader(headers map[string]string, name string) (string, bool)

LookupHeader looks name up in a header map case-insensitively, the way Powertools Python's CaseInsensitiveDict does. An exact match wins over a case-folded one.

func MakeID

func MakeID() string

MakeID returns a new random identifier for an AppSync ID scalar.

func Method

func Method[E HTTPRequest](e E) string

Method returns the HTTP method of the request.

func NestedS3Event

func NestedS3Event(m events.SQSMessage) (events.S3Event, error)

NestedS3Event decodes the S3 event notification an S3 bucket sent to the queue, which is the message body.

func NestedSNSMessage

func NestedSNSMessage(m events.SQSMessage) (events.SNSEntity, error)

NestedSNSMessage decodes the SNS notification an SNS topic delivered to the queue (without raw message delivery), which is the message body. SNS spells two members differently there (SigningCertURL, UnsubscribeURL) than in the events it sends to Lambda; both spellings decode.

Example
package main

import (
	"fmt"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventsource"
)

func main() {
	message := events.SQSMessage{
		Body: `{"Type":"Notification","Message":"hello","UnsubscribeURL":"https://sns.example.com/unsubscribe"}`,
	}

	notification, err := eventsource.NestedSNSMessage(message)
	if err != nil {
		panic(err)
	}
	fmt.Println(notification.Message, notification.UnsubscribeURL)
}
Output:
hello https://sns.example.com/unsubscribe

func NewS3BatchJobResponse

func NewS3BatchJobResponse(invocationSchemaVersion, invocationID string, results ...events.S3BatchJobResult) events.S3BatchJobResponse

NewS3BatchJobResponse returns the response to an S3 Batch Operations invocation, with treatMissingKeysAs Succeeded as Powertools Python defaults it. S3 Batch Operations sends one task per invocation, so results should hold exactly one result; Validate checks it.

func ParseCloudWatchTime

func ParseCloudWatchTime(value string) (time.Time, error)

ParseCloudWatchTime parses a CloudWatch alarm time such as 2024-02-17T11:53:08.431+0000. RFC 3339 times are accepted too.

func ParseCookies

func ParseCookies(header string) map[string]string

ParseCookies parses a Cookie header value into a map of cookie names to values. It follows Powertools Python's lenient parser rather than net/http's strict one: a malformed segment is skipped, not an error.

func Path

func Path[E HTTPRequest](e E) string

Path returns the request path. For HTTP API events it is the raw path without the stage prefix (unless the stage is $default), as Powertools Python routes it.

func QueryParameter

func QueryParameter[E HTTPRequest](e E, name string) (string, bool)

QueryParameter returns the value of the named query string parameter. The name matches exactly, as query strings are case-sensitive. A parameter present only in the multi-value map answers with its last value; VPC Lattice v2 parameters with several values come back joined with commas.

func QueryParameterValues

func QueryParameterValues[E HTTPRequest](e E, name string) []string

QueryParameterValues returns every value of the named query string parameter, the way Powertools Python resolves them for validation: the multi-value map wins when it has the parameter, otherwise the single value is split on commas.

func S3BatchTaskBucket

func S3BatchTaskBucket[T S3BatchTask](task T) string

S3BatchTaskBucket returns the bucket of a task: S3Bucket in schema 2.0, the name in S3BucketARN in schema 1.0.

func S3BatchTaskKey

func S3BatchTaskKey[T S3BatchTask](task T) string

S3BatchTaskKey returns the object key of a task, URL-decoded as UnquoteS3Key does.

func S3BucketFromARN

func S3BucketFromARN(arn string) string

S3BucketFromARN returns the bucket name of an S3 bucket ARN (arn:aws:s3:::bucket), or the argument itself when it is not an ARN.

func SNSMessageAttributes

func SNSMessageAttributes(entity events.SNSEntity) (map[string]SNSMessageAttribute, error)

SNSMessageAttributes returns the typed message attributes of a notification; events.SNSEntity keeps them as untyped maps.

func SQSQueueURL

func SQSQueueURL(arn string) (string, error)

SQSQueueURL returns the URL of the queue an event source ARN names (arn:aws:sqs:us-east-1:123456789012:orders). Unlike Powertools Python's queue_url, which always writes amazonaws.com, it uses the DNS suffix of the ARN's partition, so that China and isolated regions work.

func UnquoteS3Key

func UnquoteS3Key(key string) string

UnquoteS3Key decodes an object key as S3 event notifications encode it, the way Python's urllib.parse.unquote_plus does: "+" is a space and %XX escapes are decoded, while a malformed escape is kept as it is instead of failing (url.QueryUnescape fails).

func ValidateS3BatchJobResponse

func ValidateS3BatchJobResponse(r events.S3BatchJobResponse) error

ValidateS3BatchJobResponse reports what S3 Batch Operations would reject: a number of results other than one, or an unknown result code.

Types

type APIGatewayCustomAuthorizerRequestContext

type APIGatewayCustomAuthorizerRequestContext struct {
	events.APIGatewayCustomAuthorizerRequestTypeRequestContext

	DomainName        string                    `json:"domainName,omitempty"`
	DomainPrefix      string                    `json:"domainPrefix,omitempty"`
	ExtendedRequestID string                    `json:"extendedRequestId,omitempty"`
	Protocol          string                    `json:"protocol,omitempty"`
	RequestTime       string                    `json:"requestTime,omitempty"`
	RequestTimeEpoch  int64                     `json:"requestTimeEpoch,omitempty"`
	Identity          APIGatewayRequestIdentity `json:"identity"`
	ConnectedAt       int64                     `json:"connectedAt,omitempty"`
	ConnectionID      string                    `json:"connectionId,omitempty"`
	EventType         string                    `json:"eventType,omitempty"`
	MessageDirection  string                    `json:"messageDirection,omitempty"`
	RouteKey          string                    `json:"routeKey,omitempty"`
}

APIGatewayCustomAuthorizerRequestContext is the request context of a REQUEST authorizer event, complete: the members of a REST proxy request context plus, for WebSocket APIs, those of the connection.

type APIGatewayCustomAuthorizerRequestTypeRequest

type APIGatewayCustomAuthorizerRequestTypeRequest struct {
	events.APIGatewayCustomAuthorizerRequestTypeRequest

	Version            string                                   `json:"version,omitempty"`
	IdentitySource     string                                   `json:"identitySource,omitempty"`
	AuthorizationToken string                                   `json:"authorizationToken,omitempty"`
	RequestContext     APIGatewayCustomAuthorizerRequestContext `json:"requestContext"`
}

APIGatewayCustomAuthorizerRequestTypeRequest is the event of an API Gateway REQUEST authorizer: events.APIGatewayCustomAuthorizerRequestTypeRequest with the members aws-lambda-go leaves out (payload version, identity source, token) and the complete request context. The same type decodes the REQUEST authorizer events of REST APIs, of WebSocket APIs (which add the connection to the context) and of HTTP APIs with payload version 1.0.

type APIGatewayProxyRequest

type APIGatewayProxyRequest struct {
	events.APIGatewayProxyRequest

	Version        string                        `json:"version,omitempty"`
	RequestContext APIGatewayProxyRequestContext `json:"requestContext"`
}

APIGatewayProxyRequest is events.APIGatewayProxyRequest (an API Gateway REST API proxy request, payload version 1.0) with the members it lacks: the payload version and the caller's organization id.

The embedded aws-lambda-go request keeps every other field; RequestContext shadows its own, so read the context through e.RequestContext, not e.APIGatewayProxyRequest.RequestContext (which stays empty).

type APIGatewayProxyRequestContext

type APIGatewayProxyRequestContext struct {
	events.APIGatewayProxyRequestContext

	Identity APIGatewayRequestIdentity `json:"identity"`
}

APIGatewayProxyRequestContext is events.APIGatewayProxyRequestContext with the complete caller identity.

type APIGatewayRequestIdentity

type APIGatewayRequestIdentity struct {
	events.APIGatewayRequestIdentity

	PrincipalOrgID string `json:"principalOrgId,omitempty"`
}

APIGatewayRequestIdentity is events.APIGatewayRequestIdentity with the caller's AWS Organizations id.

type ActiveMQEvent

type ActiveMQEvent struct {
	events.ActiveMQEvent

	Messages []ActiveMQMessage `json:"messages"`
}

ActiveMQEvent is events.ActiveMQEvent whose messages carry the members aws-lambda-go leaves out.

type ActiveMQMessage

type ActiveMQMessage struct {
	events.ActiveMQMessage

	ConnectionID string `json:"connectionId,omitempty"`
	Persistent   bool   `json:"persistent,omitempty"`
}

ActiveMQMessage is events.ActiveMQMessage with the JMS connection id and the persistence flag.

func (ActiveMQMessage) DecodedData

func (m ActiveMQMessage) DecodedData() ([]byte, error)

DecodedData returns the message body, base64-decoded.

type AppSyncAuthorization

type AppSyncAuthorization string

AppSyncAuthorization is how the caller of an AppSync request was authorized.

const (
	AppSyncAuthorizationIAM     AppSyncAuthorization = "AWS_IAM"
	AppSyncAuthorizationCognito AppSyncAuthorization = "AMAZON_COGNITO_USER_POOLS"
	AppSyncAuthorizationOIDC    AppSyncAuthorization = "OPENID_CONNECT"
	AppSyncAuthorizationLambda  AppSyncAuthorization = "AWS_LAMBDA"
)

The authorization modes, as AppSyncIdentity.Authorization tells them apart. An API key request has no identity at all.

type AppSyncChannel

type AppSyncChannel struct {
	Path     string   `json:"path"`
	Segments []string `json:"segments"`
}

AppSyncChannel is the channel of an operation.

type AppSyncChannelNamespace

type AppSyncChannelNamespace struct {
	Name string `json:"name"`
}

AppSyncChannelNamespace is the namespace of the channel.

type AppSyncEvent

type AppSyncEvent struct {
	ID      string `json:"id"`
	Payload any    `json:"payload"`
}

AppSyncEvent is one published event.

type AppSyncEventsEvent

type AppSyncEventsEvent struct {
	Identity  *AppSyncIdentity  `json:"identity"`
	Request   AppSyncRequest    `json:"request"`
	Info      AppSyncEventsInfo `json:"info"`
	Prev      *AppSyncPrev      `json:"prev"`
	Stash     map[string]any    `json:"stash"`
	Events    []AppSyncEvent    `json:"events"`
	OutErrors []any             `json:"outErrors"`
}

AppSyncEventsEvent is what AppSync Events sends to a Lambda handler of a channel namespace, for a publish or a subscribe.

type AppSyncEventsInfo

type AppSyncEventsInfo struct {
	Channel          AppSyncChannel          `json:"channel"`
	ChannelNamespace AppSyncChannelNamespace `json:"channelNamespace"`
	// Operation is PUBLISH or SUBSCRIBE.
	Operation string `json:"operation"`
}

AppSyncEventsInfo describes the operation and its channel.

type AppSyncIdentity

type AppSyncIdentity struct {
	events.AppSyncIAMIdentity

	// Sub, Issuer, Claims: Cognito user pools and OpenID Connect.
	Sub    string         `json:"sub,omitempty"`
	Issuer string         `json:"issuer,omitempty"`
	Claims map[string]any `json:"claims,omitempty"`
	// DefaultAuthStrategy and Groups: Cognito user pools only.
	DefaultAuthStrategy string   `json:"defaultAuthStrategy,omitempty"`
	Groups              []string `json:"groups,omitempty"`
	// ResolverContext: Lambda authorization, what the authorizer returned.
	ResolverContext map[string]any `json:"resolverContext,omitempty"`
}

AppSyncIdentity is the caller of an AppSync request. AppSync sends a different shape per authorization mode; this struct holds them all and Authorization tells which one arrived. The IAM members come from the embedded events.AppSyncIAMIdentity.

func (AppSyncIdentity) Authorization

func (i AppSyncIdentity) Authorization() AppSyncAuthorization

Authorization tells how the caller was authorized. Powertools Python only tells Cognito (any identity with a sub) from IAM; this also recognizes OpenID Connect and Lambda identities.

func (*AppSyncIdentity) UnmarshalJSON

func (i *AppSyncIdentity) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the identity. An identity that is not an object (the string "None" some AppSync payloads carry for an API key request) is left empty rather than failing the whole event, as AppSyncPrev does.

type AppSyncInfo

type AppSyncInfo struct {
	FieldName           string         `json:"fieldName"`
	ParentTypeName      string         `json:"parentTypeName"`
	Variables           map[string]any `json:"variables"`
	SelectionSetList    []string       `json:"selectionSetList"`
	SelectionSetGraphQL string         `json:"selectionSetGraphQL,omitempty"`
}

AppSyncInfo describes the GraphQL request being resolved.

type AppSyncPrev

type AppSyncPrev struct {
	Result any `json:"result"`
}

AppSyncPrev holds the result of the previous function of a pipeline resolver.

func (*AppSyncPrev) UnmarshalJSON

func (p *AppSyncPrev) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the prev object. A prev that is not an object (some AppSync Events payloads carry a placeholder string) is left empty rather than failing the whole event.

type AppSyncRequest

type AppSyncRequest struct {
	// Headers are lower-cased by AppSync; LookupHeader matches them
	// case-insensitively anyway.
	Headers    map[string]string `json:"headers"`
	DomainName string            `json:"domainName,omitempty"`
}

AppSyncRequest is the HTTP request AppSync received.

type AppSyncResolverEvent

type AppSyncResolverEvent struct {
	Arguments map[string]any   `json:"arguments"`
	Identity  *AppSyncIdentity `json:"identity"`
	Source    map[string]any   `json:"source"`
	Request   AppSyncRequest   `json:"request"`
	Prev      *AppSyncPrev     `json:"prev"`
	Info      AppSyncInfo      `json:"info"`
	Stash     map[string]any   `json:"stash"`

	// FieldName, ParentTypeName and TypeName are where Amplify GraphQL
	// Transformer payloads, which have no info, name the field; read them
	// through Field and ParentType.
	FieldName      string `json:"fieldName,omitempty"`
	ParentTypeName string `json:"parentTypeName,omitempty"`
	TypeName       string `json:"typeName,omitempty"`
}

AppSyncResolverEvent is what AppSync sends to a direct Lambda resolver (and to the Amplify GraphQL Transformer @function directive).

func (AppSyncResolverEvent) Field

func (e AppSyncResolverEvent) Field() string

Field returns the name of the field being resolved, from info or, for Amplify payloads, from the top-level fieldName.

func (AppSyncResolverEvent) ParentType

func (e AppSyncResolverEvent) ParentType() string

ParentType returns the name of the type the field belongs to, from info or, for Amplify payloads, from parentTypeName or typeName.

type AuthorizerOption

type AuthorizerOption func(*policy)

AuthorizerOption configures an authorizer response.

func WithAuthorizerContext

func WithAuthorizerContext(context map[string]any) AuthorizerOption

WithAuthorizerContext sets the context API Gateway passes to the integration ($context.authorizer).

func WithUsageIdentifierKey

func WithUsageIdentifierKey(key string) AuthorizerOption

WithUsageIdentifierKey sets the API key of a usage plan.

type AuthorizerPolicyResponse

type AuthorizerPolicyResponse struct {
	PrincipalID        string         `json:"principalId"`
	PolicyDocument     PolicyDocument `json:"policyDocument"`
	Context            map[string]any `json:"context,omitempty"`
	UsageIdentifierKey string         `json:"usageIdentifierKey,omitempty"`
}

AuthorizerPolicyResponse is the response of a REST or WebSocket API Lambda authorizer: the principal, its policy, and what API Gateway passes on to the integration.

func DenyAllResponse

func DenyAllResponse() AuthorizerPolicyResponse

DenyAllResponse returns the response that denies every route to an unknown principal, Powertools Python's DENY_ALL_RESPONSE.

type AuthorizerResponse

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

AuthorizerResponse builds the IAM policy a REST API Lambda authorizer returns, Powertools Python's APIGatewayAuthorizerResponse. Create it with NewAuthorizerResponse, add routes, then Build.

func NewAuthorizerResponse

func NewAuthorizerResponse(principalID string, target RouteARN, opts ...AuthorizerOption) *AuthorizerResponse

NewAuthorizerResponse starts the response for principalID. The target gives the partition, region, account, API and stage of the routes; it is usually the parsed methodArn of the event:

arn, err := eventsource.ParseRouteARN(event.MethodArn)
response := eventsource.NewAuthorizerResponse("user-1", arn)

Unlike Powertools Python's from_route_arn, the partition of the ARN is kept, so that policies work in China and GovCloud regions.

Example
package main

import (
	"fmt"

	"github.com/alessandrolattao/powertools-lambda-go/eventsource"
)

func main() {
	arn, err := eventsource.ParseRouteARN("arn:aws:execute-api:us-east-1:123456789012:api1/prod/GET/orders")
	if err != nil {
		panic(err)
	}

	response := eventsource.NewAuthorizerResponse("user-1", arn)
	if routeErr := response.AllowRoute(eventsource.HTTPVerbGet, "/orders/*"); routeErr != nil {
		panic(routeErr)
	}
	policy, err := response.Build()
	if err != nil {
		panic(err)
	}
	fmt.Println(policy.PolicyDocument.Statement[0].Effect, policy.PolicyDocument.Statement[0].Resource[0])
}
Output:
Allow arn:aws:execute-api:us-east-1:123456789012:api1/prod/GET/orders/*

func (*AuthorizerResponse) AllowAllRoutes

func (r *AuthorizerResponse) AllowAllRoutes()

AllowAllRoutes allows every method on every resource.

func (*AuthorizerResponse) AllowRoute

func (r *AuthorizerResponse) AllowRoute(method HTTPVerb, resource string, conditions ...Condition) error

AllowRoute allows method on resource ("*" for every resource), optionally only under conditions.

func (*AuthorizerResponse) Build

Build returns the response, with the Allow statements first. It fails with ErrNoStatements when no route was added.

func (*AuthorizerResponse) DenyAllRoutes

func (r *AuthorizerResponse) DenyAllRoutes()

DenyAllRoutes denies every method on every resource.

func (*AuthorizerResponse) DenyRoute

func (r *AuthorizerResponse) DenyRoute(method HTTPVerb, resource string, conditions ...Condition) error

DenyRoute denies method on resource, optionally only under conditions.

type BedrockAgentEvent

type BedrockAgentEvent struct {
	MessageVersion          string                   `json:"messageVersion"`
	InputText               string                   `json:"inputText"`
	SessionID               string                   `json:"sessionId"`
	ActionGroup             string                   `json:"actionGroup"`
	APIPath                 string                   `json:"apiPath"`
	HTTPMethod              string                   `json:"httpMethod"`
	Parameters              []BedrockAgentProperty   `json:"parameters"`
	RequestBody             *BedrockAgentRequestBody `json:"requestBody,omitempty"`
	Agent                   BedrockAgentInfo         `json:"agent"`
	SessionAttributes       map[string]string        `json:"sessionAttributes"`
	PromptSessionAttributes map[string]string        `json:"promptSessionAttributes"`
}

BedrockAgentEvent is what an Amazon Bedrock agent sends to the Lambda function of an action group defined with an OpenAPI schema.

func (BedrockAgentEvent) BodyProperties

func (e BedrockAgentEvent) BodyProperties() (map[string]string, bool)

BodyProperties returns the application/json body properties by name, the equivalent of Powertools Python's json_body for Bedrock agents. It reports false when the request has no JSON body.

func (BedrockAgentEvent) QueryParameters

func (e BedrockAgentEvent) QueryParameters() map[string]string

QueryParameters returns the parameters by name, Powertools Python's query_string_parameters for Bedrock agents.

type BedrockAgentFunctionEvent

type BedrockAgentFunctionEvent struct {
	MessageVersion          string                 `json:"messageVersion"`
	InputText               string                 `json:"inputText"`
	SessionID               string                 `json:"sessionId"`
	ActionGroup             string                 `json:"actionGroup"`
	Function                string                 `json:"function"`
	Parameters              []BedrockAgentProperty `json:"parameters"`
	Agent                   BedrockAgentInfo       `json:"agent"`
	SessionAttributes       map[string]string      `json:"sessionAttributes"`
	PromptSessionAttributes map[string]string      `json:"promptSessionAttributes"`
}

BedrockAgentFunctionEvent is what an Amazon Bedrock agent sends to the Lambda function of an action group defined with function details.

type BedrockAgentInfo

type BedrockAgentInfo struct {
	Name    string `json:"name"`
	ID      string `json:"id"`
	Alias   string `json:"alias"`
	Version string `json:"version"`
}

BedrockAgentInfo identifies the agent.

type BedrockAgentMediaType

type BedrockAgentMediaType struct {
	Properties []BedrockAgentProperty `json:"properties"`
}

BedrockAgentMediaType holds the properties of the body for one media type.

type BedrockAgentProperty

type BedrockAgentProperty struct {
	Name  string `json:"name"`
	Type  string `json:"type"`
	Value string `json:"value"`
}

BedrockAgentProperty is a parameter or a body property the agent extracted from the conversation. Values are always strings; Type says what they hold (string, number, integer, boolean, array).

type BedrockAgentRequestBody

type BedrockAgentRequestBody struct {
	Content map[string]BedrockAgentMediaType `json:"content"`
}

BedrockAgentRequestBody is the request body, by media type.

type CloudFormationCustomResourceEvent

type CloudFormationCustomResourceEvent struct {
	cfn.Event

	ServiceToken string `json:"ServiceToken"`
}

CloudFormationCustomResourceEvent is cfn.Event (a CloudFormation custom resource request) with the service token, the ARN the template invokes. Respond with cfn.NewResponse and Response.Send, or wrap the handler with cfn.LambdaWrap.

type CloudWatchAlarmConfiguration

type CloudWatchAlarmConfiguration struct {
	Description string                  `json:"description,omitempty"`
	AlarmRule   string                  `json:"alarmRule,omitempty"`
	Metrics     []CloudWatchAlarmMetric `json:"metrics,omitempty"`
	// ActionsSuppressor and its periods (seconds) configure the action
	// suppression of a composite alarm.
	ActionsSuppressor                string `json:"actionsSuppressor,omitempty"`
	ActionsSuppressorWaitPeriod      int64  `json:"actionsSuppressorWaitPeriod,omitempty"`
	ActionsSuppressorExtensionPeriod int64  `json:"actionsSuppressorExtensionPeriod,omitempty"`
}

CloudWatchAlarmConfiguration is the configuration of the alarm: metrics for a metric alarm, a rule for a composite alarm.

type CloudWatchAlarmData

type CloudWatchAlarmData struct {
	AlarmName     string                       `json:"alarmName"`
	State         CloudWatchAlarmState         `json:"state"`
	PreviousState CloudWatchAlarmState         `json:"previousState"`
	Configuration CloudWatchAlarmConfiguration `json:"configuration"`
}

CloudWatchAlarmData describes the alarm and its state change.

type CloudWatchAlarmEvent

type CloudWatchAlarmEvent struct {
	Source    string `json:"source"`
	AlarmARN  string `json:"alarmArn"`
	Region    string `json:"region"`
	AccountID string `json:"accountId"`
	// Time is when the alarm changed state, in the CloudWatch format
	// (2024-02-17T11:53:08.431+0000); ParseCloudWatchTime reads it.
	Time      string              `json:"time"`
	AlarmData CloudWatchAlarmData `json:"alarmData"`
}

CloudWatchAlarmEvent is what a CloudWatch alarm sends when it invokes a Lambda function directly (alarm action). Alarms delivered through SNS use events.CloudWatchAlarmSNSPayload instead.

type CloudWatchAlarmMetric

type CloudWatchAlarmMetric struct {
	ID         string                     `json:"id"`
	Expression string                     `json:"expression,omitempty"`
	Label      string                     `json:"label,omitempty"`
	ReturnData bool                       `json:"returnData"`
	MetricStat *CloudWatchAlarmMetricStat `json:"metricStat,omitempty"`
}

CloudWatchAlarmMetric is a metric or a metric math expression of the alarm.

type CloudWatchAlarmMetricStat

type CloudWatchAlarmMetricStat struct {
	Metric CloudWatchMetric `json:"metric"`
	// Period is in seconds.
	Period int64  `json:"period,omitempty"`
	Stat   string `json:"stat,omitempty"`
	Unit   string `json:"unit,omitempty"`
}

CloudWatchAlarmMetricStat is the metric and statistic a metric of the alarm evaluates.

type CloudWatchAlarmState

type CloudWatchAlarmState struct {
	// Value is OK, ALARM or INSUFFICIENT_DATA.
	Value  string `json:"value"`
	Reason string `json:"reason"`
	// ReasonData is a JSON document about the evaluation;
	// DecodeReasonData decodes it.
	ReasonData string `json:"reasonData,omitempty"`
	// Timestamp is in the CloudWatch format; ParseCloudWatchTime reads it.
	Timestamp string `json:"timestamp"`
	// ActionsSuppressedBy is Alarm, ExtensionPeriod or WaitPeriod when a
	// composite alarm's actions were suppressed.
	ActionsSuppressedBy     string `json:"actionsSuppressedBy,omitempty"`
	ActionsSuppressedReason string `json:"actionsSuppressedReason,omitempty"`
}

CloudWatchAlarmState is a state of the alarm.

func (CloudWatchAlarmState) DecodeReasonData

func (s CloudWatchAlarmState) DecodeReasonData[T any]() (T, error)

DecodeReasonData decodes the reason data into a T. Empty reason data gives the zero T, as Powertools Python's reason_data_decoded gives None.

type CloudWatchDashboardCustomWidgetEvent

type CloudWatchDashboardCustomWidgetEvent struct {
	// Describe asks for the widget's documentation instead of its content.
	Describe      bool                     `json:"describe,omitempty"`
	WidgetContext *CloudWatchWidgetContext `json:"widgetContext,omitempty"`
	// Params holds the other members of the event: the parameters the
	// widget definition passes to the function. It is filled when the event
	// is decoded with encoding/json/v2 (the parser package does).
	Params jsontext.Value `json:",embed"` //nolint:revive // "embed" is an encoding/json/v2 option revive does not know
}

CloudWatchDashboardCustomWidgetEvent is what a CloudWatch dashboard custom widget sends to its Lambda function.

type CloudWatchForms

type CloudWatchForms struct {
	All map[string]any `json:"all"`
}

CloudWatchForms holds the values of the forms in the widget.

type CloudWatchLogsData

type CloudWatchLogsData struct {
	events.CloudwatchLogsData

	PolicyLevel string                   `json:"policyLevel,omitempty"`
	LogEvents   []CloudWatchLogsLogEvent `json:"logEvents"`
}

CloudWatchLogsData is events.CloudwatchLogsData with the members it lacks: the policy level of account-level subscriptions and the extracted fields of each log event.

func ExtractCloudWatchLogs

func ExtractCloudWatchLogs(e events.KinesisEvent) ([]CloudWatchLogsData, error)

ExtractCloudWatchLogs decodes the CloudWatch Logs subscription payloads a Kinesis stream delivered, one per record, in order.

func ExtractCloudWatchLogsFromRecord

func ExtractCloudWatchLogsFromRecord(record events.KinesisEventRecord) (CloudWatchLogsData, error)

ExtractCloudWatchLogsFromRecord decodes the CloudWatch Logs subscription payload of one Kinesis record: its data is gzip-compressed JSON (the base64 layer is already gone, aws-lambda-go decodes it).

func ParseCloudWatchLogs

func ParseCloudWatchLogs(raw events.CloudwatchLogsRawData) (CloudWatchLogsData, error)

ParseCloudWatchLogs decodes the payload of a CloudWatch Logs subscription event: base64, then gzip or zlib, then JSON. Unlike events.CloudwatchLogsRawData.Parse it accepts zlib streams and keeps the policy level and extracted fields.

type CloudWatchLogsLogEvent

type CloudWatchLogsLogEvent struct {
	events.CloudwatchLogsLogEvent

	ExtractedFields map[string]string `json:"extractedFields,omitempty"`
}

CloudWatchLogsLogEvent is events.CloudwatchLogsLogEvent with the fields a subscription filter pattern extracted.

type CloudWatchMetric

type CloudWatchMetric struct {
	Namespace  string            `json:"namespace"`
	Name       string            `json:"name"`
	Dimensions map[string]string `json:"dimensions"`
}

CloudWatchMetric identifies a metric.

type CloudWatchTimeRange

type CloudWatchTimeRange struct {
	Mode          string              `json:"mode"`
	Start         int64               `json:"start"`
	End           int64               `json:"end"`
	RelativeStart int64               `json:"relativeStart,omitempty"`
	Zoom          *CloudWatchTimeZoom `json:"zoom,omitempty"`
}

CloudWatchTimeRange is the time range the dashboard displays, in milliseconds since the Unix epoch.

type CloudWatchTimeZoom

type CloudWatchTimeZoom struct {
	Start int64 `json:"start"`
	End   int64 `json:"end"`
}

CloudWatchTimeZoom is the zoomed part of the time range.

type CloudWatchTimezone

type CloudWatchTimezone struct {
	Label           string `json:"label"`
	OffsetISO       string `json:"offsetISO"`
	OffsetInMinutes int64  `json:"offsetInMinutes"`
}

CloudWatchTimezone is the time zone the dashboard displays.

type CloudWatchWidgetContext

type CloudWatchWidgetContext struct {
	DashboardName string              `json:"dashboardName"`
	WidgetID      string              `json:"widgetId"`
	Domain        string              `json:"domain"`
	AccountID     string              `json:"accountId"`
	Locale        string              `json:"locale"`
	Timezone      CloudWatchTimezone  `json:"timezone"`
	Period        int64               `json:"period"`
	IsAutoPeriod  bool                `json:"isAutoPeriod"`
	TimeRange     CloudWatchTimeRange `json:"timeRange"`
	Theme         string              `json:"theme"`
	LinkCharts    bool                `json:"linkCharts"`
	Title         string              `json:"title"`
	Forms         CloudWatchForms     `json:"forms"`
	Params        map[string]any      `json:"params"`
	Width         int64               `json:"width"`
	Height        int64               `json:"height"`
}

CloudWatchWidgetContext describes the dashboard and the widget.

type CodeDeployLifecycleHookEvent

type CodeDeployLifecycleHookEvent struct {
	DeploymentID                  string `json:"DeploymentId"`
	LifecycleEventHookExecutionID string `json:"LifecycleEventHookExecutionId"`
}

CodeDeployLifecycleHookEvent is what CodeDeploy sends to a lifecycle event hook function (BeforeAllowTraffic, AfterAllowTraffic, ...). The function reports the outcome with the CodeDeploy PutLifecycleEventHookExecutionStatus API.

type CodePipelineArtifactCredentials

type CodePipelineArtifactCredentials struct {
	events.CodePipelineArtifactCredentials

	// ExpirationTime is in milliseconds since the Unix epoch.
	ExpirationTime int64 `json:"expirationTime,omitempty"`
}

CodePipelineArtifactCredentials is events.CodePipelineArtifactCredentials with their expiration. The secret members never reach logs: the type formats and logs them as [SENSITIVE], as Powertools Python prints them.

func (CodePipelineArtifactCredentials) GoString

GoString hides the secrets from %#v too.

func (CodePipelineArtifactCredentials) LogValue

LogValue hides the secrets from log/slog.

func (CodePipelineArtifactCredentials) String

String hides the secret access key and the session token.

type CodePipelineData

type CodePipelineData struct {
	events.CodePipelineData

	ArtifactCredentials CodePipelineArtifactCredentials `json:"artifactCredentials"`
	// EncryptionKey is nil when the artifact store uses the default key.
	EncryptionKey *CodePipelineEncryptionKey `json:"encryptionKey,omitempty"`
}

CodePipelineData is events.CodePipelineData with the encryption key of the artifact store and the complete artifact credentials.

type CodePipelineEncryptionKey

type CodePipelineEncryptionKey struct {
	ID string `json:"id"`
	// Type is KMS.
	Type string `json:"type"`
}

CodePipelineEncryptionKey is the key the artifact store encrypts with.

type CodePipelineJob

type CodePipelineJob struct {
	events.CodePipelineJob

	Data CodePipelineData `json:"data"`
}

CodePipelineJob is events.CodePipelineJob with the complete job data.

type CodePipelineJobEvent

type CodePipelineJobEvent struct {
	CodePipelineJob CodePipelineJob `json:"CodePipeline.job"`
}

CodePipelineJobEvent is events.CodePipelineJobEvent (a CodePipeline Lambda invoke action) whose job data has the artifact encryption key and the expiration of the artifact credentials. The subpackage eventsource/codepipeline reads and writes the job's artifacts.

func (CodePipelineJobEvent) DecodeUserParameters

func (e CodePipelineJobEvent) DecodeUserParameters[T any]() (T, error)

DecodeUserParameters decodes the user parameters, JSON, into a T. Missing parameters give the zero T, as Powertools Python gives an empty dict.

func (CodePipelineJobEvent) FindInputArtifact

func (e CodePipelineJobEvent) FindInputArtifact(name string) (events.CodePipelineInputArtifact, bool)

FindInputArtifact returns the input artifact called name.

func (CodePipelineJobEvent) FindOutputArtifact

func (e CodePipelineJobEvent) FindOutputArtifact(name string) (events.CodePipelineOutputArtifact, bool)

FindOutputArtifact returns the output artifact called name.

func (CodePipelineJobEvent) InputBucketName

func (e CodePipelineJobEvent) InputBucketName() string

InputBucketName returns the bucket of the first input artifact, or "".

func (CodePipelineJobEvent) InputObjectKey

func (e CodePipelineJobEvent) InputObjectKey() string

InputObjectKey returns the URL-decoded object key of the first input artifact, or "".

func (CodePipelineJobEvent) UserParameters

func (e CodePipelineJobEvent) UserParameters() string

UserParameters returns the user parameters of the action configuration.

type CognitoEventUserPoolsCustomEmailSender

type CognitoEventUserPoolsCustomEmailSender = CognitoEventUserPoolsCustomSender

CognitoEventUserPoolsCustomEmailSender is the event of the custom email sender trigger.

type CognitoEventUserPoolsCustomMessage

type CognitoEventUserPoolsCustomMessage struct {
	events.CognitoEventUserPoolsCustomMessage

	Request CognitoEventUserPoolsCustomMessageRequest `json:"request"`
}

CognitoEventUserPoolsCustomMessage is events.CognitoEventUserPoolsCustomMessage whose request carries the link parameter.

type CognitoEventUserPoolsCustomMessageRequest

type CognitoEventUserPoolsCustomMessageRequest struct {
	events.CognitoEventUserPoolsCustomMessageRequest

	LinkParameter string `json:"linkParameter,omitempty"`
}

CognitoEventUserPoolsCustomMessageRequest is events.CognitoEventUserPoolsCustomMessageRequest with the placeholder for the verification link.

type CognitoEventUserPoolsCustomSMSSender

type CognitoEventUserPoolsCustomSMSSender = CognitoEventUserPoolsCustomSender

CognitoEventUserPoolsCustomSMSSender is the event of the custom SMS sender trigger.

type CognitoEventUserPoolsCustomSender

type CognitoEventUserPoolsCustomSender struct {
	events.CognitoEventUserPoolsHeader

	Request CognitoEventUserPoolsCustomSenderRequest `json:"request"`
}

CognitoEventUserPoolsCustomSender is the event of the Cognito custom email sender and custom SMS sender triggers: the message Cognito wants sent, with the code encrypted with the pool's KMS key (decrypt it with the AWS Encryption SDK before sending it).

type CognitoEventUserPoolsCustomSenderRequest

type CognitoEventUserPoolsCustomSenderRequest struct {
	// Type is the request version, customEmailSenderRequestV1 or
	// customSMSSenderRequestV1.
	Type string `json:"type"`
	// Code is the encrypted code, empty for some trigger sources.
	Code           string            `json:"code"`
	UserAttributes map[string]any    `json:"userAttributes"`
	ClientMetadata map[string]string `json:"clientMetadata,omitempty"`
}

CognitoEventUserPoolsCustomSenderRequest is the request of a custom sender trigger.

type CognitoEventUserPoolsMigrateUser

type CognitoEventUserPoolsMigrateUser struct {
	events.CognitoEventUserPoolsMigrateUser

	Response CognitoEventUserPoolsMigrateUserResponse `json:"response"`
}

CognitoEventUserPoolsMigrateUser is events.CognitoEventUserPoolsMigrateUser whose response can turn SMS multi-factor authentication on.

type CognitoEventUserPoolsMigrateUserResponse

type CognitoEventUserPoolsMigrateUserResponse struct {
	events.CognitoEventUserPoolsMigrateUserResponse

	EnableSMSMFA bool `json:"enableSMSMFA,omitempty"`
}

CognitoEventUserPoolsMigrateUserResponse is events.CognitoEventUserPoolsMigrateUserResponse with enableSMSMFA.

type Condition

type Condition map[string]map[string]any

Condition is the Condition block of an IAM policy statement: condition operators to condition keys to values, for example

eventsource.Condition{"IpAddress": {"aws:SourceIp": []string{"203.0.113.0/24"}}}

type ConfigConfigurationChanged

type ConfigConfigurationChanged struct {
	ConfigurationItemDiff    map[string]any          `json:"configurationItemDiff"`
	ConfigurationItem        ConfigConfigurationItem `json:"configurationItem"`
	NotificationCreationTime string                  `json:"notificationCreationTime"`
	Type                     string                  `json:"messageType"`
	RecordVersion            string                  `json:"recordVersion"`
}

ConfigConfigurationChanged is the invoking event of a configuration change: the resource's configuration item and what changed.

func (*ConfigConfigurationChanged) MessageType

func (e *ConfigConfigurationChanged) MessageType() string

MessageType returns ConfigConfigurationItemChangeNotification.

type ConfigConfigurationItem

type ConfigConfigurationItem struct {
	RelatedEvents                []any          `json:"relatedEvents"`
	Relationships                []any          `json:"relationships"`
	Configuration                map[string]any `json:"configuration"`
	SupplementaryConfiguration   map[string]any `json:"supplementaryConfiguration"`
	Tags                         map[string]any `json:"tags"`
	ConfigurationItemVersion     string         `json:"configurationItemVersion"`
	ConfigurationItemCaptureTime string         `json:"configurationItemCaptureTime"`
	ConfigurationStateID         int64          `json:"configurationStateId"`
	AWSAccountID                 string         `json:"awsAccountId"`
	ConfigurationItemStatus      string         `json:"configurationItemStatus"`
	ResourceType                 string         `json:"resourceType"`
	ResourceID                   string         `json:"resourceId"`
	ResourceName                 string         `json:"resourceName"`
	ARN                          string         `json:"ARN"`
	AWSRegion                    string         `json:"awsRegion"`
	AvailabilityZone             string         `json:"availabilityZone"`
	ConfigurationStateMD5Hash    string         `json:"configurationStateMd5Hash"`
	ResourceCreationTime         string         `json:"resourceCreationTime"`
}

ConfigConfigurationItem is the configuration of a resource as AWS Config recorded it.

type ConfigConfigurationItemSummary

type ConfigConfigurationItemSummary struct {
	ChangeType                   string `json:"changeType"`
	ConfigurationItemVersion     string `json:"configurationItemVersion"`
	ConfigurationItemCaptureTime string `json:"configurationItemCaptureTime"`
	ConfigurationStateID         int64  `json:"configurationStateId"`
	AWSAccountID                 string `json:"awsAccountId"`
	ConfigurationItemStatus      string `json:"configurationItemStatus"`
	ResourceType                 string `json:"resourceType"`
	ResourceID                   string `json:"resourceId"`
	ResourceName                 string `json:"resourceName"`
	ARN                          string `json:"ARN"`
	AWSRegion                    string `json:"awsRegion"`
	AvailabilityZone             string `json:"availabilityZone"`
	ConfigurationStateMD5Hash    string `json:"configurationStateMd5Hash"`
	ResourceCreationTime         string `json:"resourceCreationTime"`
}

ConfigConfigurationItemSummary summarizes an oversized configuration item.

type ConfigEvent

type ConfigEvent struct {
	events.ConfigEvent

	// EvaluationMode is DETECTIVE or PROACTIVE.
	EvaluationMode string `json:"evaluationMode,omitempty"`
}

ConfigEvent is events.ConfigEvent (an AWS Config custom rule evaluation) with the evaluation mode, and helpers that decode its JSON-encoded members.

func (ConfigEvent) DecodeInvokingEvent

func (e ConfigEvent) DecodeInvokingEvent() (ConfigInvokingEvent, error)

DecodeInvokingEvent decodes the invoking event by its message type. Any type other than the scheduled and oversized notifications decodes as a configuration change, as Powertools Python does.

Example
package main

import (
	"fmt"

	"github.com/alessandrolattao/powertools-lambda-go/eventsource"
)

func main() {
	event := eventsource.ConfigEvent{
		InvokingEvent: `{"messageType":"ScheduledNotification","awsAccountId":"123456789012"}`,
	}

	invoking, err := event.DecodeInvokingEvent()
	if err != nil {
		panic(err)
	}
	switch e := invoking.(type) {
	case *eventsource.ConfigScheduled:
		fmt.Println("scheduled evaluation of", e.AWSAccountID)
	case *eventsource.ConfigConfigurationChanged:
		fmt.Println("change of", e.ConfigurationItem.ResourceID)
	case *eventsource.ConfigOversizedConfiguration:
		fmt.Println("oversized change of", e.ConfigurationItemSummary.ResourceID)
	}
}
Output:
scheduled evaluation of 123456789012

func (ConfigEvent) DecodeRuleParameters

func (e ConfigEvent) DecodeRuleParameters[T any]() (T, error)

DecodeRuleParameters decodes the rule parameters into a T. Missing parameters give the zero T.

type ConfigInvokingEvent

type ConfigInvokingEvent interface {
	// MessageType returns the message type of the invoking event.
	MessageType() string
	// contains filtered or unexported methods
}

ConfigInvokingEvent is what triggered an AWS Config rule evaluation: a *ConfigConfigurationChanged, a *ConfigOversizedConfiguration or a *ConfigScheduled. Tell them apart with a type switch.

type ConfigOversizedConfiguration

type ConfigOversizedConfiguration struct {
	ConfigurationItemSummary ConfigConfigurationItemSummary `json:"configurationItemSummary"`
	NotificationCreationTime string                         `json:"notificationCreationTime"`
	Type                     string                         `json:"messageType"`
	RecordVersion            string                         `json:"recordVersion"`
}

ConfigOversizedConfiguration is the invoking event of a configuration change too large for the event: a summary of the configuration item.

func (*ConfigOversizedConfiguration) MessageType

func (e *ConfigOversizedConfiguration) MessageType() string

MessageType returns ConfigOversizedConfigurationItemChangeNotification.

type ConfigScheduled

type ConfigScheduled struct {
	AWSAccountID             string `json:"awsAccountId"`
	NotificationCreationTime string `json:"notificationCreationTime"`
	Type                     string `json:"messageType"`
	RecordVersion            string `json:"recordVersion"`
}

ConfigScheduled is the invoking event of a periodic evaluation.

func (*ConfigScheduled) MessageType

func (e *ConfigScheduled) MessageType() string

MessageType returns ConfigScheduledNotification.

type ConnectAudioStream

type ConnectAudioStream struct {
	StartFragmentNumber string `json:"StartFragmentNumber,omitempty"`
	StartTimestamp      string `json:"StartTimestamp,omitempty"`
	StreamARN           string `json:"StreamARN,omitempty"`
}

ConnectAudioStream is a Kinesis Video Streams audio stream. The values are absent until streaming starts.

type ConnectContactData

type ConnectContactData struct {
	events.ConnectContactData

	CustomerEndpoint *events.ConnectEndpoint `json:"CustomerEndpoint"`
	Queue            *events.ConnectQueue    `json:"Queue"`
	SystemEndpoint   *events.ConnectEndpoint `json:"SystemEndpoint"`
	MediaStreams     ConnectMediaStreams     `json:"MediaStreams"`
}

ConnectContactData is events.ConnectContactData with the media streams. The customer endpoint, the queue and the system endpoint are nil when the contact has none, as Powertools Python returns None.

type ConnectCustomerMediaStream

type ConnectCustomerMediaStream struct {
	Audio ConnectAudioStream `json:"Audio"`
}

ConnectCustomerMediaStream is the customer's media stream.

type ConnectDetails

type ConnectDetails struct {
	events.ConnectDetails

	ContactData ConnectContactData `json:"ContactData"`
}

ConnectDetails is events.ConnectDetails with the complete contact data.

type ConnectEvent

type ConnectEvent struct {
	events.ConnectEvent

	Details ConnectDetails `json:"Details"`
}

ConnectEvent is events.ConnectEvent (an Amazon Connect contact flow invocation) whose contact data has the media streams and tells absent endpoints and queues from empty ones.

type ConnectMediaStreams

type ConnectMediaStreams struct {
	Customer ConnectCustomerMediaStream `json:"Customer"`
}

ConnectMediaStreams describes the live media streams of the contact.

type DynamoDBTimeWindowEvent

type DynamoDBTimeWindowEvent struct {
	events.DynamoDBTimeWindowEvent

	State map[string]any `json:"state"`
}

DynamoDBTimeWindowEvent is events.DynamoDBTimeWindowEvent whose state can hold any JSON value.

type DynamoDBTimeWindowEventResponse

type DynamoDBTimeWindowEventResponse struct {
	events.DynamoDBTimeWindowEventResponse

	State map[string]any `json:"state"`
}

DynamoDBTimeWindowEventResponse is events.DynamoDBTimeWindowEventResponse whose state can hold any JSON value.

type EpochMicros

type EpochMicros int64

EpochMicros is a time in microseconds since the Unix epoch that decodes from a JSON number or from a string holding one.

func (EpochMicros) Time

func (e EpochMicros) Time() time.Time

Time returns the instant as a time.Time in UTC.

func (*EpochMicros) UnmarshalJSON

func (e *EpochMicros) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a number, a string holding a number, or null.

type EventBridgeEvent

type EventBridgeEvent struct {
	events.EventBridgeEvent

	ReplayName string `json:"replay-name,omitempty"`
}

EventBridgeEvent is events.EventBridgeEvent with the name of the replay that sent it, when it comes from an archive replay. For a typed detail, see the parser package.

type HTTPRequest

HTTPRequest is the set of events that carry an HTTP request: API Gateway REST, HTTP and WebSocket APIs, Application Load Balancer, Lambda Function URL and VPC Lattice. The generic helpers below (Body, Header, Cookies...) accept any of them, so that a function reads every HTTP source the same way, as Powertools Python's BaseProxyEvent does.

type HTTPVerb

type HTTPVerb string

HTTPVerb is the method part of an API Gateway route ARN.

const (
	HTTPVerbGet     HTTPVerb = "GET"
	HTTPVerbPost    HTTPVerb = "POST"
	HTTPVerbPut     HTTPVerb = "PUT"
	HTTPVerbPatch   HTTPVerb = "PATCH"
	HTTPVerbHead    HTTPVerb = "HEAD"
	HTTPVerbDelete  HTTPVerb = "DELETE"
	HTTPVerbOptions HTTPVerb = "OPTIONS"
	HTTPVerbAll     HTTPVerb = "*"
)

The methods an authorizer policy can allow or deny. HTTPVerbAll matches every method.

type IoTCoreAddOrDeleteFromThingGroupEvent

type IoTCoreAddOrDeleteFromThingGroupEvent struct {
	IoTRegistryEvent

	AccountID      string `json:"accountId"`
	ThingGroupID   string `json:"thingGroupId"`
	ThingGroupName string `json:"thingGroupName"`
	ChildGroupID   string `json:"childGroupId"`
	ChildGroupName string `json:"childGroupName"`
}

IoTCoreAddOrDeleteFromThingGroupEvent reports a child thing group added to or removed from a parent group.

type IoTCoreAddOrRemoveFromThingGroupEvent

type IoTCoreAddOrRemoveFromThingGroupEvent struct {
	IoTRegistryEvent

	AccountID    string `json:"accountId"`
	GroupARN     string `json:"groupArn"`
	GroupID      string `json:"groupId"`
	ThingARN     string `json:"thingArn"`
	ThingID      string `json:"thingId"`
	MembershipID string `json:"membershipId"`
}

IoTCoreAddOrRemoveFromThingGroupEvent reports a thing added to or removed from a thing group.

type IoTCoreThingEvent

type IoTCoreThingEvent struct {
	IoTRegistryEvent

	AccountID     string         `json:"accountId"`
	ThingID       string         `json:"thingId"`
	ThingName     string         `json:"thingName"`
	VersionNumber int64          `json:"versionNumber"`
	ThingTypeName string         `json:"thingTypeName,omitempty"`
	Attributes    map[string]any `json:"attributes"`
}

IoTCoreThingEvent reports a thing created, updated or deleted.

type IoTCoreThingGroupEvent

type IoTCoreThingGroupEvent struct {
	IoTRegistryEvent

	AccountID               string              `json:"accountId"`
	ThingGroupID            string              `json:"thingGroupId"`
	ThingGroupName          string              `json:"thingGroupName"`
	VersionNumber           int64               `json:"versionNumber"`
	ParentGroupName         string              `json:"parentGroupName,omitempty"`
	ParentGroupID           string              `json:"parentGroupId,omitempty"`
	Description             string              `json:"description"`
	RootToParentThingGroups []map[string]string `json:"rootToParentThingGroups"`
	Attributes              map[string]any      `json:"attributes"`
	DynamicGroupMappingID   string              `json:"dynamicGroupMappingId,omitempty"`
}

IoTCoreThingGroupEvent reports a thing group created, updated or deleted.

type IoTCoreThingTypeAssociationEvent

type IoTCoreThingTypeAssociationEvent struct {
	IoTRegistryEvent

	ThingID       string `json:"thingId"`
	ThingName     string `json:"thingName"`
	ThingTypeName string `json:"thingTypeName"`
}

IoTCoreThingTypeAssociationEvent reports a thing associated with or dissociated from a thing type.

type IoTCoreThingTypeEvent

type IoTCoreThingTypeEvent struct {
	IoTRegistryEvent

	AccountID     string `json:"accountId"`
	ThingTypeID   string `json:"thingTypeId"`
	ThingTypeName string `json:"thingTypeName"`
	IsDeprecated  bool   `json:"isDeprecated"`
	// DeprecationDate is an ISO 8601 time, empty unless deprecated.
	DeprecationDate       string              `json:"deprecationDate,omitempty"`
	SearchableAttributes  []string            `json:"searchableAttributes"`
	PropagatingAttributes []map[string]string `json:"propagatingAttributes"`
	Description           string              `json:"description"`
}

IoTCoreThingTypeEvent reports a thing type created, updated, deprecated, undeprecated or deleted.

type IoTRegistryEvent

type IoTRegistryEvent struct {
	EventID   string `json:"eventId"`
	EventType string `json:"eventType"`
	// Timestamp is in milliseconds (seconds in some older events); Time
	// reads either.
	Timestamp int64  `json:"timestamp"`
	Operation string `json:"operation"`
}

IoTRegistryEvent holds what every AWS IoT Core registry event has.

func (IoTRegistryEvent) Time

func (e IoTRegistryEvent) Time() time.Time

Time returns the timestamp as a time.Time in UTC: a value above 10^10 is taken as milliseconds, a smaller one as seconds, as Powertools Python does (which returns local time instead).

type KinesisFirehoseResponse

type KinesisFirehoseResponse struct {
	Records []KinesisFirehoseResponseRecord `json:"records"`
}

KinesisFirehoseResponse is the response of an Amazon Data Firehose transformation function. Unlike events.KinesisFirehoseResponse, a record without metadata leaves it out, as Powertools Python does, instead of sending empty partition keys and on-the-fly metadata.

func (*KinesisFirehoseResponse) Add

Add appends records to the response.

func (*KinesisFirehoseResponse) Validate

func (r *KinesisFirehoseResponse) Validate() error

Validate reports what Firehose would reject: no record, or a result other than Ok, Dropped and ProcessingFailed. Powertools Python raises on the first and only warns on the second.

type KinesisFirehoseResponseRecord

type KinesisFirehoseResponseRecord struct {
	events.KinesisFirehoseResponseRecord

	Metadata *KinesisFirehoseResponseRecordMetadata `json:"metadata,omitempty"`
}

KinesisFirehoseResponseRecord is a transformed record: events.KinesisFirehoseResponseRecord with optional metadata. Result is events.KinesisFirehoseTransformedStateOk, Dropped or ProcessingFailed; Data is the transformed data, which the JSON encoder base64-encodes:

eventsource.KinesisFirehoseResponseRecord{
	RecordID: record.RecordID,
	Result:   events.KinesisFirehoseTransformedStateOk,
	Data:     transformed,
}

type KinesisFirehoseResponseRecordMetadata

type KinesisFirehoseResponseRecordMetadata struct {
	PartitionKeys map[string]string                                `json:"partitionKeys,omitempty"`
	OTFMetadata   *events.KinesisFirehoseResponseRecordOTFMetadata `json:"otfMetadata,omitempty"`
}

KinesisFirehoseResponseRecordMetadata is the metadata of a transformed record: the partition keys of dynamic partitioning, and the routing of an Apache Iceberg destination.

type KinesisTimeWindowEvent

type KinesisTimeWindowEvent struct {
	events.KinesisTimeWindowEvent

	State map[string]any `json:"state"`
}

KinesisTimeWindowEvent is events.KinesisTimeWindowEvent whose state can hold any JSON value, as the state a function returns can: aws-lambda-go only accepts strings, so an event carrying numbers (the AWS documentation example) fails to decode.

type KinesisTimeWindowEventResponse

type KinesisTimeWindowEventResponse struct {
	events.KinesisTimeWindowEventResponse

	State map[string]any `json:"state"`
}

KinesisTimeWindowEventResponse is events.KinesisTimeWindowEventResponse whose state can hold any JSON value.

type Number

type Number string

Number is a DynamoDB number kept as its decimal text, so that the 38 digits DynamoDB stores survive: Powertools Python returns a Decimal, float64 would round. It marshals to JSON as a number.

func (Number) Float64

func (n Number) Float64() (float64, error)

Float64 returns the number as a float64, rounded to the nearest one.

func (Number) Int64

func (n Number) Int64() (int64, error)

Int64 returns the number as an int64; it fails on a fraction or an overflow.

func (Number) MarshalJSON

func (n Number) MarshalJSON() ([]byte, error)

MarshalJSON writes the number as a JSON number, exactly.

func (Number) String

func (n Number) String() string

String returns the decimal text.

func (*Number) UnmarshalJSON

func (n *Number) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a JSON number, or a string holding one.

type PolicyDocument

type PolicyDocument struct {
	Version   string            `json:"Version"`
	Statement []PolicyStatement `json:"Statement"`
}

PolicyDocument is the IAM policy an authorizer returns.

type PolicyStatement

type PolicyStatement struct {
	Action    string    `json:"Action"`
	Effect    string    `json:"Effect"`
	Resource  []string  `json:"Resource"`
	Condition Condition `json:"Condition,omitempty"`
}

PolicyStatement is a statement of an authorizer policy. Unlike events.IAMPolicyStatement it carries a Condition.

type RouteARN

type RouteARN struct {
	Partition string
	Region    string
	AccountID string
	APIID     string
	Stage     string
	// Method is empty for WebSocket routes.
	Method HTTPVerb
	// Resource has no leading slash.
	Resource  string
	WebSocket bool
}

RouteARN is an API Gateway method or route ARN, as an authorizer receives it (methodArn, routeArn) and as a policy names the routes it allows:

arn:<partition>:execute-api:<region>:<account>:<api>/<stage>/<method>/<resource>

WebSocket routes have no method: arn:...:<api>/<stage>/<route>.

func ParseRouteARN

func ParseRouteARN(arn string) (RouteARN, error)

ParseRouteARN parses the ARN of a REST or HTTP API route. Unlike Powertools Python, a malformed ARN is an error, not a panic.

func ParseWebSocketRouteARN

func ParseWebSocketRouteARN(arn string) (RouteARN, error)

ParseWebSocketRouteARN parses the ARN of a WebSocket API route.

func (RouteARN) String

func (r RouteARN) String() string

String renders the ARN.

type S3BatchTask

type S3BatchTask interface {
	events.S3BatchJobTask | events.S3BatchJobTaskV2
}

S3BatchTask is a task of an S3 Batch Operations event, schema 1.0 or 2.0.

type S3EventBridgeNotificationBucket

type S3EventBridgeNotificationBucket struct {
	Name string `json:"name"`
}

S3EventBridgeNotificationBucket is the bucket of the event.

type S3EventBridgeNotificationDetail

type S3EventBridgeNotificationDetail struct {
	Version   string                          `json:"version"`
	Bucket    S3EventBridgeNotificationBucket `json:"bucket"`
	Object    S3EventBridgeNotificationObject `json:"object"`
	RequestID string                          `json:"request-id"`
	Requester string                          `json:"requester"`

	SourceIPAddress         string `json:"source-ip-address,omitempty"`
	Reason                  string `json:"reason,omitempty"`
	DeletionType            string `json:"deletion-type,omitempty"`
	RestoreExpiryTime       string `json:"restore-expiry-time,omitempty"`
	SourceStorageClass      string `json:"source-storage-class,omitempty"`
	DestinationStorageClass string `json:"destination-storage-class,omitempty"`
	DestinationAccessTier   string `json:"destination-access-tier,omitempty"`
}

S3EventBridgeNotificationDetail is the detail of an S3 event delivered through EventBridge. Which of the optional members are present depends on the detail type.

type S3EventBridgeNotificationEvent

type S3EventBridgeNotificationEvent struct {
	EventBridgeEvent

	Detail S3EventBridgeNotificationDetail `json:"detail"`
}

S3EventBridgeNotificationEvent is an Amazon S3 event delivered through EventBridge (Object Created, Object Deleted, Object Restore Completed...).

type S3EventBridgeNotificationObject

type S3EventBridgeNotificationObject struct {
	// Key is URL-encoded as S3 sends it; URLDecodedKey decodes it.
	Key  string `json:"key"`
	Size int64  `json:"size,omitempty"`
	// ETag is empty for deletions.
	ETag string `json:"etag,omitempty"`
	// VersionID is empty for buckets without versioning (Powertools Python
	// wrongly requires it).
	VersionID string `json:"version-id,omitempty"`
	Sequencer string `json:"sequencer"`
}

S3EventBridgeNotificationObject is the object of the event.

func (S3EventBridgeNotificationObject) URLDecodedKey

func (o S3EventBridgeNotificationObject) URLDecodedKey() string

URLDecodedKey returns the object key decoded the way Python's urllib.parse.unquote_plus does: "+" is a space, %XX escapes are decoded, malformed escapes are left as they are.

type S3ObjectLambdaEvent

type S3ObjectLambdaEvent struct {
	events.S3ObjectLambdaEvent

	UserIdentity S3ObjectLambdaUserIdentity `json:"userIdentity"`
}

S3ObjectLambdaEvent is events.S3ObjectLambdaEvent whose user identity has the IAM user name.

type S3ObjectLambdaUserIdentity

type S3ObjectLambdaUserIdentity struct {
	events.S3ObjectLambdaUserIdentity

	UserName string `json:"userName,omitempty"`
}

S3ObjectLambdaUserIdentity is events.S3ObjectLambdaUserIdentity with the IAM user name.

type SNSMessageAttribute

type SNSMessageAttribute struct {
	// Type is String, String.Array, Number or Binary.
	Type string `json:"Type"`
	// Value is the attribute value; base64 for Binary.
	Value string `json:"Value"`
}

SNSMessageAttribute is a message attribute of an SNS notification.

type SQSSystemAttributes

type SQSSystemAttributes struct {
	AWSTraceHeader                   string
	ApproximateReceiveCount          int
	SentTimestamp                    time.Time
	SenderID                         string
	ApproximateFirstReceiveTimestamp time.Time
	SequenceNumber                   string
	MessageGroupID                   string
	MessageDeduplicationID           string
	// DeadLetterQueueSourceARN is set when the function reads a dead-letter
	// queue: the queue the message was moved from.
	DeadLetterQueueSourceARN string
}

SQSSystemAttributes are the system attributes of an SQS message, parsed. FIFO members are empty for standard queues.

func ParseSQSAttributes

func ParseSQSAttributes(m events.SQSMessage) (SQSSystemAttributes, error)

ParseSQSAttributes parses the system attributes of a message: the counts as integers, the timestamps (milliseconds since the epoch) as times.

type SimpleEmailCommonHeaders

type SimpleEmailCommonHeaders struct {
	events.SimpleEmailCommonHeaders

	Bcc     []string `json:"bcc,omitempty"`
	Sender  []string `json:"sender,omitempty"`
	ReplyTo []string `json:"replyTo,omitempty"`
}

SimpleEmailCommonHeaders is events.SimpleEmailCommonHeaders with the headers aws-lambda-go leaves out.

type SimpleEmailEvent

type SimpleEmailEvent struct {
	Records []SimpleEmailRecord `json:"Records"`
}

SimpleEmailEvent is events.SimpleEmailEvent (an Amazon SES receipt rule invocation) whose common headers have the Bcc, Sender and Reply-To addresses.

type SimpleEmailMessage

type SimpleEmailMessage struct {
	events.SimpleEmailMessage

	CommonHeaders SimpleEmailCommonHeaders `json:"commonHeaders"`
}

SimpleEmailMessage is events.SimpleEmailMessage with the complete common headers.

type SimpleEmailRecord

type SimpleEmailRecord struct {
	events.SimpleEmailRecord

	SES SimpleEmailService `json:"ses"`
}

SimpleEmailRecord is events.SimpleEmailRecord with the complete message.

type SimpleEmailService

type SimpleEmailService struct {
	events.SimpleEmailService

	Mail SimpleEmailMessage `json:"mail"`
}

SimpleEmailService is events.SimpleEmailService with the complete message.

type StringValues

type StringValues []string

StringValues holds the values of a header or a query string parameter. It decodes from a JSON array of strings or from a single string, because VPC Lattice documents arrays while some payloads carry plain strings.

func (*StringValues) UnmarshalJSON

func (s *StringValues) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes an array of strings, a string or null.

type TransferFamilyAuthorizerEvent

type TransferFamilyAuthorizerEvent struct {
	Username string `json:"username"`
	// Password is nil for SSH public key authentication.
	Password *string `json:"password"`
	// Protocol is SFTP, FTP, FTPS or AS2.
	Protocol string `json:"protocol"`
	ServerID string `json:"serverId"`
	SourceIP string `json:"sourceIp"`
}

TransferFamilyAuthorizerEvent is what AWS Transfer Family sends to a custom identity provider function.

type TransferFamilyAuthorizerResponse

type TransferFamilyAuthorizerResponse struct {
	Role              string `json:"Role"`
	HomeDirectoryType string `json:"HomeDirectoryType"`
	HomeDirectory     string `json:"HomeDirectory,omitempty"`
	// HomeDirectoryDetails is the JSON-encoded list of logical directory
	// mappings, as Transfer Family expects it.
	HomeDirectoryDetails string                      `json:"HomeDirectoryDetails,omitempty"`
	PosixProfile         *TransferFamilyPosixProfile `json:"PosixProfile,omitempty"`
	Policy               string                      `json:"Policy,omitempty"`
	PublicKeys           []string                    `json:"PublicKeys,omitempty"`
}

TransferFamilyAuthorizerResponse is what a custom identity provider function returns to authenticate a user. An empty response denies access.

func NewTransferFamilyEFSResponse

func NewTransferFamilyEFSResponse(role string, uid, gid int64, opts ...TransferFamilyOption) (TransferFamilyAuthorizerResponse, error)

NewTransferFamilyEFSResponse authenticates a user of an Amazon EFS server with role and the POSIX identity uid:gid. A home directory option is required. Powertools Python writes the gid as the uid; this does not.

func NewTransferFamilyS3Response

func NewTransferFamilyS3Response(role string, opts ...TransferFamilyOption) (TransferFamilyAuthorizerResponse, error)

NewTransferFamilyS3Response authenticates a user of an Amazon S3 server with role. A home directory option is required.

Example
package main

import (
	"encoding/json/v2"
	"fmt"

	"github.com/alessandrolattao/powertools-lambda-go/eventsource"
)

func main() {
	response, err := eventsource.NewTransferFamilyS3Response("arn:aws:iam::123456789012:role/sftp-user",
		eventsource.WithHomeDirectory("/my-bucket/home/alice"))
	if err != nil {
		panic(err)
	}
	out, err := json.Marshal(response)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(out))
}
Output:
{"Role":"arn:aws:iam::123456789012:role/sftp-user","HomeDirectoryType":"PATH","HomeDirectory":"/my-bucket/home/alice"}

type TransferFamilyDirectoryMapping

type TransferFamilyDirectoryMapping struct {
	Entry  string `json:"Entry"`
	Target string `json:"Target"`
}

TransferFamilyDirectoryMapping maps a path the user sees (Entry) to a path in the bucket or file system (Target).

type TransferFamilyOption

type TransferFamilyOption func(*transferFamilyResponse)

TransferFamilyOption configures a Transfer Family response.

func WithHomeDirectory

func WithHomeDirectory(path string) TransferFamilyOption

WithHomeDirectory gives the user a PATH home directory.

func WithLogicalHomeDirectory

func WithLogicalHomeDirectory(mappings ...TransferFamilyDirectoryMapping) TransferFamilyOption

WithLogicalHomeDirectory gives the user a LOGICAL home directory made of mappings.

func WithPublicKeys

func WithPublicKeys(keys ...string) TransferFamilyOption

WithPublicKeys lists the SSH public keys the user may authenticate with.

func WithSessionPolicy

func WithSessionPolicy(policy string) TransferFamilyOption

WithSessionPolicy scopes the user's role down with a session policy (a JSON IAM policy document).

type TransferFamilyPosixProfile

type TransferFamilyPosixProfile struct {
	UID int64 `json:"Uid"`
	GID int64 `json:"Gid"`
}

TransferFamilyPosixProfile is the POSIX identity of an Amazon EFS user.

type VPCLatticeEvent

type VPCLatticeEvent struct {
	RawPath               string            `json:"raw_path"`
	Method                string            `json:"method"`
	Headers               map[string]string `json:"headers"`
	QueryStringParameters map[string]string `json:"query_string_parameters"`
	Body                  string            `json:"body"`
	IsBase64Encoded       bool              `json:"is_base64_encoded"`
}

VPCLatticeEvent is the request a VPC Lattice target group sends to a function with event structure version 1. Its keys are snake_case.

type VPCLatticeEventV2

type VPCLatticeEventV2 struct {
	Version string `json:"version"`
	Path    string `json:"path"`
	Method  string `json:"method"`
	// Headers holds every value of each header. VPC Lattice sends them as
	// arrays; a plain string value decodes as a single value.
	Headers map[string]StringValues `json:"headers"`
	// QueryStringParameters holds every value of each parameter, as Headers.
	QueryStringParameters map[string]StringValues  `json:"queryStringParameters,omitempty"`
	Body                  string                   `json:"body,omitempty"`
	IsBase64Encoded       bool                     `json:"isBase64Encoded"`
	RequestContext        VPCLatticeRequestContext `json:"requestContext"`
}

VPCLatticeEventV2 is the request a VPC Lattice target group sends to a function with event structure version 2.

Example
package main

import (
	"encoding/json/v2"
	"fmt"

	"github.com/alessandrolattao/powertools-lambda-go/eventsource"
)

func main() {
	raw := []byte(`{"version":"2.0","path":"/orders","method":"GET",
		"headers":{"accept":["application/json"]},"queryStringParameters":{"id":["1","2"]},
		"requestContext":{"timeEpoch":"1696331543569073"}}`)

	var event eventsource.VPCLatticeEventV2
	if err := json.Unmarshal(raw, &event); err != nil {
		panic(err)
	}
	fmt.Println(eventsource.Path(event), eventsource.QueryParameterValues(event, "id"))
	fmt.Println(event.RequestContext.TimeEpoch.Time().Format("2006-01-02"))
}
Output:
/orders [1 2]
2023-10-03

type VPCLatticeRequestContext

type VPCLatticeRequestContext struct {
	ServiceNetworkARN string                    `json:"serviceNetworkArn"`
	ServiceARN        string                    `json:"serviceArn"`
	TargetGroupARN    string                    `json:"targetGroupArn"`
	Identity          VPCLatticeRequestIdentity `json:"identity"`
	Region            string                    `json:"region"`
	// TimeEpoch is the request time in microseconds since the Unix epoch.
	// VPC Lattice sends it as a string; a number decodes too.
	TimeEpoch EpochMicros `json:"timeEpoch"`
}

VPCLatticeRequestContext describes where a version 2 request comes from.

type VPCLatticeRequestIdentity

type VPCLatticeRequestIdentity struct {
	SourceVPCARN   string `json:"sourceVpcArn,omitempty"`
	Type           string `json:"type,omitempty"`
	Principal      string `json:"principal,omitempty"`
	PrincipalOrgID string `json:"principalOrgID,omitempty"`
	SessionName    string `json:"sessionName,omitempty"`
	X509SubjectCN  string `json:"X509SubjectCn,omitempty"`
	X509IssuerOU   string `json:"X509IssuerOu,omitempty"`
	X509SANDNS     string `json:"x509SanDns,omitempty"`
	X509SANURI     string `json:"X509SanUri,omitempty"`
	X509SANNameCN  string `json:"X509SanNameCn,omitempty"`
}

VPCLatticeRequestIdentity is the caller of a version 2 request, as far as VPC Lattice authenticated it.

type WebSocketAuthorizerResponse

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

WebSocketAuthorizerResponse builds the IAM policy a WebSocket API Lambda authorizer returns, Powertools Python's APIGatewayAuthorizerResponseWebSocket: routes have no method.

func NewWebSocketAuthorizerResponse

func NewWebSocketAuthorizerResponse(principalID string, target RouteARN, opts ...AuthorizerOption) *WebSocketAuthorizerResponse

NewWebSocketAuthorizerResponse starts the response for principalID, for the API and stage of target (usually the parsed methodArn of the $connect event).

func (*WebSocketAuthorizerResponse) AllowAllRoutes

func (r *WebSocketAuthorizerResponse) AllowAllRoutes()

AllowAllRoutes allows every route.

func (*WebSocketAuthorizerResponse) AllowRoute

func (r *WebSocketAuthorizerResponse) AllowRoute(routeKey string, conditions ...Condition)

AllowRoute allows the route, optionally only under conditions.

func (*WebSocketAuthorizerResponse) Build

Build returns the response, with the Allow statements first. It fails with ErrNoStatements when no route was added.

func (*WebSocketAuthorizerResponse) DenyAllRoutes

func (r *WebSocketAuthorizerResponse) DenyAllRoutes()

DenyAllRoutes denies every route.

func (*WebSocketAuthorizerResponse) DenyRoute

func (r *WebSocketAuthorizerResponse) DenyRoute(routeKey string, conditions ...Condition)

DenyRoute denies the route, optionally only under conditions.

Directories

Path Synopsis
Package codepipeline reads and writes the artifacts of a CodePipeline job, the S3 half of Powertools Python's CodePipelineJobEvent (setup_s3_client, get_artifact, put_artifact).
Package codepipeline reads and writes the artifacts of a CodePipeline job, the S3 half of Powertools Python's CodePipelineJobEvent (setup_s3_client, get_artifact, put_artifact).

Jump to

Keyboard shortcuts

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