Skip to content

Commit 940c073

Browse files
committed
Fix scheduler
1 parent d604fe1 commit 940c073

1 file changed

Lines changed: 20 additions & 9 deletions

File tree

api/pkg/repositories/gorm_phone_notification_repository.go

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ package repositories
22

33
import (
44
"context"
5+
"errors"
56
"fmt"
6-
"math"
77
"time"
88

99
"github.com/cockroachdb/cockroach-go/v2/crdb/crdbgorm"
@@ -63,20 +63,24 @@ func (repository gormPhoneNotificationRepository) Schedule(ctx context.Context,
6363
}
6464

6565
err := crdbgorm.ExecuteTx(ctx, repository.db, nil, func(tx *gorm.DB) error {
66-
var messagesCount int64
66+
lastNotification := new(entities.PhoneNotification)
6767
err := tx.WithContext(ctx).
68-
Model(&entities.PhoneNotification{}).
6968
Where("phone_id = ?", notification.PhoneID).
70-
Where("status = ?", entities.PhoneNotificationStatusPending).
71-
Count(&messagesCount).
69+
Order("scheduled_at desc").
70+
First(lastNotification).
7271
Error
73-
if err != nil {
74-
msg := fmt.Sprintf("cannot count messages with phoneID [%s] and status [%s]", notification.PhoneID, entities.PhoneNotificationStatusPending)
72+
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
73+
msg := fmt.Sprintf("cannot fetch last notification with phone ID [%s]", notification.PhoneID)
7574
return stacktrace.Propagate(err, msg)
7675
}
7776

78-
timeout := int(math.Ceil(float64(messagesCount) / float64(messagesPerMinute))) // how many minutes to wait
79-
notification.ScheduledAt = time.Now().UTC().Add(time.Minute * time.Duration(timeout))
77+
notification.ScheduledAt = time.Now().UTC()
78+
if err == nil {
79+
notification.ScheduledAt = repository.maxTime(
80+
time.Now().UTC(),
81+
lastNotification.ScheduledAt.Add(time.Duration(60/messagesPerMinute)*time.Second),
82+
)
83+
}
8084

8185
if err = tx.WithContext(ctx).Create(notification).Error; err != nil {
8286
msg := fmt.Sprintf("cannot create new notification with id [%s] and schedule [%s]", notification.ID, notification.ScheduledAt.String())
@@ -92,6 +96,13 @@ func (repository gormPhoneNotificationRepository) Schedule(ctx context.Context,
9296
return nil
9397
}
9498

99+
func (repository *gormPhoneNotificationRepository) maxTime(a, b time.Time) time.Time {
100+
if a.Unix() > b.Unix() {
101+
return a
102+
}
103+
return b
104+
}
105+
95106
func (repository *gormPhoneNotificationRepository) insert(ctx context.Context, notification *entities.PhoneNotification) error {
96107
ctx, span := repository.tracer.Start(ctx)
97108
defer span.End()

0 commit comments

Comments
 (0)