-
Notifications
You must be signed in to change notification settings - Fork 13
/
otp_retry.go
92 lines (69 loc) · 2.24 KB
/
otp_retry.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
92
package consumers
import (
"fmt"
"log"
"time"
"github.com/latolukasz/beeorm"
"github.com/coretrix/hitrix/pkg/entity"
"github.com/coretrix/hitrix/pkg/queue/streams"
"github.com/coretrix/hitrix/service/component/otp"
)
type OTPRetryConsumer struct {
ormService *beeorm.Engine
maxRetries int
gatewayRegistry map[string]otp.IOTPSMSGateway
}
func NewOTPRetryConsumer(ormService *beeorm.Engine, maxRetries int, gatewayRegistry map[string]otp.IOTPSMSGateway) *OTPRetryConsumer {
return &OTPRetryConsumer{ormService: ormService, maxRetries: maxRetries, gatewayRegistry: gatewayRegistry}
}
func (c *OTPRetryConsumer) GetQueueName() string {
return streams.StreamMsgRetryOTP
}
func (c *OTPRetryConsumer) GetGroupName(suffix *string) string {
return streams.GetGroupName(c.GetQueueName(), suffix)
}
func (c *OTPRetryConsumer) Consume(_ *beeorm.Engine, event beeorm.Event) error {
log.Println(".")
ormService := c.ormService.Clone()
retryDTO := &otp.RetryDTO{}
event.Unserialize(retryDTO)
if retryDTO == nil || retryDTO.Gateway == "" {
return nil
}
otpTrackerEntity := &entity.OTPTrackerEntity{}
ormService.LoadByID(retryDTO.OTPTrackerEntityID, otpTrackerEntity)
RetryOTP(ormService, c.gatewayRegistry, retryDTO, otpTrackerEntity, c.maxRetries)
return nil
}
func RetryOTP(
ormService *beeorm.Engine,
gatewayRegistry map[string]otp.IOTPSMSGateway,
retryDTO *otp.RetryDTO,
otpTrackerEntity *entity.OTPTrackerEntity,
maxRetries int,
) {
retryAfter := time.Second / 2
retryCount := 1
for retryCount <= maxRetries {
retryCount++
gateway, ok := gatewayRegistry[retryDTO.Gateway]
if !ok {
panic(fmt.Sprintf("gateway %s not found in registry", retryDTO.Gateway))
}
var err error
otpTrackerEntity.GatewaySendRequest, otpTrackerEntity.GatewaySendResponse, err = gateway.SendOTP(retryDTO.Phone, retryDTO.Code)
if err == nil {
otpTrackerEntity.GatewaySendStatus = entity.OTPTrackerGatewaySendStatusSent
}
otpTrackerEntity.RetryCount = retryCount - 1
if retryCount == maxRetries {
otpTrackerEntity.MaxRetriesReached = true
}
ormService.Flush(otpTrackerEntity)
if otpTrackerEntity.GatewaySendStatus == entity.OTPTrackerGatewaySendStatusSent {
break
}
time.Sleep(retryAfter)
retryAfter = retryAfter * 2
}
}