| 1 | package awsjob |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/aws/aws-sdk-go-v2/aws" |
| 10 | "github.com/aws/aws-sdk-go-v2/service/sns" |
| 11 | ) |
| 12 | |
| 13 | // SNSAPI is the part of the SNS client SNSPublisher calls. *sns.Client |
| 14 | // satisfies it. |
| 15 | type SNSAPI interface { |
| 16 | Publish(context.Context, *sns.PublishInput, ...func(*sns.Options)) (*sns.PublishOutput, error) |
| 17 | } |
| 18 | |
| 19 | // SNSPublisher sends operator alerts to an SNS topic. It knows nothing of |
| 20 | // the controller; the controller's command wraps it as its alerter. |
| 21 | type SNSPublisher struct { |
| 22 | TopicARN string |
| 23 | Client SNSAPI |
| 24 | } |
| 25 | |
| 26 | // maxSubject is the longest subject SNS takes for email endpoints. |
| 27 | const maxSubject = 100 |
| 28 | |
| 29 | // Publish sends one alert: kind in the subject and the message, detail in |
| 30 | // the message. |
| 31 | func (p SNSPublisher) Publish(ctx context.Context, kind, detail string) error { |
| 32 | if p.TopicARN == "" || p.Client == nil { |
| 33 | return errors.New("awsjob: SNS publisher needs a topic and a client") |
| 34 | } |
| 35 | _, err := p.Client.Publish(ctx, &sns.PublishInput{ |
| 36 | TopicArn: aws.String(p.TopicARN), |
| 37 | Subject: aws.String(subject("Equipo hosted alert: " + kind)), |
| 38 | Message: aws.String(kind + "\n\n" + detail), |
| 39 | }) |
| 40 | if err != nil { |
| 41 | return fmt.Errorf("awsjob: publish %s alert: %w", kind, err) |
| 42 | } |
| 43 | return nil |
| 44 | } |
| 45 | |
| 46 | // subject keeps s to what SNS takes in a subject: printable ASCII on one |
| 47 | // line, at most 100 characters. Anything else becomes '?'. |
| 48 | func subject(s string) string { |
| 49 | var b strings.Builder |
| 50 | for _, r := range s { |
| 51 | if b.Len() == maxSubject { |
| 52 | break |
| 53 | } |
| 54 | if r < 0x20 || r > 0x7e { |
| 55 | r = '?' |
| 56 | } |
| 57 | b.WriteRune(r) |
| 58 | } |
| 59 | return b.String() |
| 60 | } |
| 61 | |