package awsjob import ( "context" "errors" "fmt" "strings" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" ) // SNSAPI is the part of the SNS client SNSPublisher calls. *sns.Client // satisfies it. type SNSAPI interface { Publish(context.Context, *sns.PublishInput, ...func(*sns.Options)) (*sns.PublishOutput, error) } // SNSPublisher sends operator alerts to an SNS topic. It knows nothing of // the controller; the controller's command wraps it as its alerter. type SNSPublisher struct { TopicARN string Client SNSAPI } // maxSubject is the longest subject SNS takes for email endpoints. const maxSubject = 100 // Publish sends one alert: kind in the subject and the message, detail in // the message. func (p SNSPublisher) Publish(ctx context.Context, kind, detail string) error { if p.TopicARN == "" || p.Client == nil { return errors.New("awsjob: SNS publisher needs a topic and a client") } _, err := p.Client.Publish(ctx, &sns.PublishInput{ TopicArn: aws.String(p.TopicARN), Subject: aws.String(subject("Equipo hosted alert: " + kind)), Message: aws.String(kind + "\n\n" + detail), }) if err != nil { return fmt.Errorf("awsjob: publish %s alert: %w", kind, err) } return nil } // subject keeps s to what SNS takes in a subject: printable ASCII on one // line, at most 100 characters. Anything else becomes '?'. func subject(s string) string { var b strings.Builder for _, r := range s { if b.Len() == maxSubject { break } if r < 0x20 || r > 0x7e { r = '?' } b.WriteRune(r) } return b.String() }