github.com/mweagle/Sparta@v1.15.0/archetype/sns.go (about)

     1  package archetype
     2  
     3  import (
     4  	"context"
     5  	"reflect"
     6  	"runtime"
     7  
     8  	awsLambdaEvents "github.com/aws/aws-lambda-go/events"
     9  	sparta "github.com/mweagle/Sparta"
    10  	gocf "github.com/mweagle/go-cloudformation"
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  // SNSReactor represents a lambda function that responds to typical SNS events
    15  type SNSReactor interface {
    16  	// OnSNSEvent when an SNS event occurs. Check the snsEvent field
    17  	// for the specific event
    18  	OnSNSEvent(ctx context.Context, snsEvent awsLambdaEvents.SNSEvent) (interface{}, error)
    19  }
    20  
    21  // SNSReactorFunc is a free function that adapts a SNSReactor
    22  // compliant signature into a function that exposes an OnEvent
    23  // function
    24  type SNSReactorFunc func(ctx context.Context,
    25  	snsEvent awsLambdaEvents.SNSEvent) (interface{}, error)
    26  
    27  // OnSNSEvent satisfies the SNSReactor interface
    28  func (reactorFunc SNSReactorFunc) OnSNSEvent(ctx context.Context,
    29  	snsEvent awsLambdaEvents.SNSEvent) (interface{}, error) {
    30  	return reactorFunc(ctx, snsEvent)
    31  }
    32  
    33  // ReactorName provides the name of the reactor func
    34  func (reactorFunc SNSReactorFunc) ReactorName() string {
    35  	return runtime.FuncForPC(reflect.ValueOf(reactorFunc).Pointer()).Name()
    36  }
    37  
    38  // NewSNSReactor returns an SNS reactor lambda function
    39  func NewSNSReactor(reactor SNSReactor,
    40  	snsTopic gocf.Stringable,
    41  	additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
    42  
    43  	reactorLambda := func(ctx context.Context, snsEvent awsLambdaEvents.SNSEvent) (interface{}, error) {
    44  		return reactor.OnSNSEvent(ctx, snsEvent)
    45  	}
    46  
    47  	lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
    48  		reactorLambda,
    49  		sparta.IAMRoleDefinition{})
    50  	if lambdaFnErr != nil {
    51  		return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
    52  	}
    53  
    54  	lambdaFn.Permissions = append(lambdaFn.Permissions, sparta.SNSPermission{
    55  		BasePermission: sparta.BasePermission{
    56  			SourceArn: snsTopic,
    57  		},
    58  	})
    59  	if len(additionalLambdaPermissions) != 0 {
    60  		lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions
    61  	}
    62  	return lambdaFn, nil
    63  }