-
Notifications
You must be signed in to change notification settings - Fork 1
/
retriever.go
58 lines (52 loc) · 1.83 KB
/
retriever.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
package formigo
import (
"context"
"errors"
"fmt"
"github.com/francescopepe/formigo/internal/client"
"github.com/francescopepe/formigo/internal/messages"
)
// retriever will get messages from SQS until the given context gets canceled.
// Any error will be sent to the controller.
func retriever(ctx context.Context, receiver client.MessageReceiver, ctrl *controller, messageCh chan<- messages.Message) {
for {
select {
case <-ctx.Done():
return
default:
msgs, err := receiver.ReceiveMessages(ctx)
if err != nil {
if errors.Is(err, context.Canceled) && errors.Is(ctx.Err(), context.Canceled) {
// The worker's context was canceled. We can exit.
return
}
// Report the error to the controller and continue.
ctrl.reportError(fmt.Errorf("unable to receive message: %w", err))
continue
}
// All the messages retrieved must be processed.
// This means that the retriever won't listen for context cancellation
// at this stage.
func() {
for _, msg := range msgs {
select {
case <-msg.Ctx.Done():
// If consumers don't pick up the messages within the messages' timeout we raise
// an error.
// This could be due to one or more of the following reasons:
// - message timeout too small.
// - consumer too slow. Increasing the number of consumers may help, especially if
// the handler performs many I/O operations.
//
// Note that we won't process all messages retrieved by the API calls. This is because
// the visibility timeout is the same for all the messages returned by the call.
ctrl.reportError(errors.New("message didn't get picked up by any consumer within its timeout"))
return // Avoid publishing all the messages downstream
case messageCh <- msg:
// Message pushed to the channel
}
}
}()
}
}
}