-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreceive.go
91 lines (73 loc) · 1.77 KB
/
receive.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"context"
"errors"
"fmt"
"os"
)
const (
maxNumberOfMessages = 10
)
var (
outputDelimiter = []byte("\n")
)
type outFunc func(string) error
func defaultHandler(body string) error {
if _, err := os.Stdout.WriteString(body); err != nil {
return fmt.Errorf("WriteString() failed: %w", err)
}
if _, err := os.Stdout.Write(outputDelimiter); err != nil {
return fmt.Errorf("Write() failed: %w", err)
}
return nil
}
func poll(ctx context.Context, sqsClient sqsClient, fn outFunc, shouldDelete bool) error {
for {
_, err := pollCommon(ctx, sqsClient, fn, maxNumberOfMessages, shouldDelete)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil
}
return err
}
}
}
func pollWithLimit(ctx context.Context, sqsClient sqsClient, fn outFunc, limit int, shouldDelete bool) error {
for limit > 0 {
batchSize := maxNumberOfMessages
if limit < batchSize {
batchSize = limit
}
count, err := pollCommon(ctx, sqsClient, fn, batchSize, shouldDelete)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil
}
return err
}
limit -= count
}
return nil
}
func pollCommon(ctx context.Context, sqsClient sqsClient, fn outFunc, batchSize int, shouldDelete bool) (int, error) {
select {
case <-ctx.Done():
return 0, nil
default:
messages, err := sqsClient.ReceiveMessages(ctx, batchSize)
if err != nil {
return 0, err
}
for _, msg := range messages {
if err := fn(*msg.Body); err != nil {
return len(messages), err
}
}
if shouldDelete {
if err := sqsClient.DeleteMessages(context.Background(), messages); err != nil {
return len(messages), err
}
}
return len(messages), nil
}
}