-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
40 lines (36 loc) · 1021 Bytes
/
middleware.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
package opinionatedevents
import (
"context"
"time"
)
type OnMessageMiddleware func(next OnMessageHandler) OnMessageHandler
func WithBackoff(backoff Backoff) OnMessageMiddleware {
return func(next OnMessageHandler) OnMessageHandler {
return func(ctx context.Context, delivery Delivery) error {
err := next(ctx, delivery)
// override the retry at time if an error was returned and it was not fatal
if err != nil && !IsFatal(err) {
return &retryError{
retryAt: time.Now().Add(backoff.DeliverAfter(delivery.GetAttempt() + 1)),
err: err,
}
}
return err
}
}
}
func WithLimit(limit int) OnMessageMiddleware {
return func(next OnMessageHandler) OnMessageHandler {
return func(ctx context.Context, delivery Delivery) error {
err := next(ctx, delivery)
// override the error with a fatal error if all attempts have been used
if err != nil && delivery.GetAttempt() >= limit {
if IsFatal(err) {
return err
}
return Fatal(err)
}
return err
}
}
}