-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
gorm_lock.go
109 lines (88 loc) · 2.3 KB
/
gorm_lock.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package gormlock
import (
"context"
"fmt"
"sync/atomic"
"time"
"github.com/go-co-op/gocron"
"gorm.io/gorm"
)
var (
defaultPrecision = time.Second
defaultJobIdentifier = func(precision time.Duration) func(ctx context.Context, key string) string {
return func(ctx context.Context, key string) string {
return time.Now().Truncate(precision).Format("2006-01-02 15:04:05.000")
}
}
StatusRunning = "RUNNING"
StatusFinished = "FINISHED"
defaultTTL = 24 * time.Hour
defaultCleanInterval = 5 * time.Second
)
func NewGormLocker(db *gorm.DB, worker string, options ...LockOption) (*GormLocker, error) {
if db == nil {
return nil, fmt.Errorf("gorm db definition can't be null")
}
if worker == "" {
return nil, fmt.Errorf("worker name can't be null")
}
gl := &GormLocker{
db: db,
worker: worker,
ttl: defaultTTL,
interval: defaultCleanInterval,
}
gl.jobIdentifier = defaultJobIdentifier(defaultPrecision)
for _, option := range options {
option(gl)
}
go func() {
ticker := time.NewTicker(gl.interval)
defer ticker.Stop()
for range ticker.C {
if gl.closed.Load() {
return
}
gl.cleanExpiredRecords()
}
}()
return gl, nil
}
var _ gocron.Locker = (*GormLocker)(nil)
type GormLocker struct {
db *gorm.DB
worker string
ttl time.Duration
interval time.Duration
jobIdentifier func(ctx context.Context, key string) string
closed atomic.Bool
}
func (g *GormLocker) cleanExpiredRecords() {
g.db.Where("updated_at < ? and status = ?", time.Now().Add(-g.ttl), StatusFinished).Delete(&CronJobLock{})
}
func (g *GormLocker) Close() {
g.closed.Store(true)
}
func (g *GormLocker) Lock(ctx context.Context, key string) (gocron.Lock, error) {
ji := g.jobIdentifier(ctx, key)
// I would like that people can "pass" their own implementation,
cjb := &CronJobLock{
JobName: key,
JobIdentifier: ji,
Worker: g.worker,
Status: StatusRunning,
}
tx := g.db.Create(cjb)
if tx.Error != nil {
return nil, tx.Error
}
return &gormLock{db: g.db, id: cjb.GetID()}, nil
}
var _ gocron.Lock = (*gormLock)(nil)
type gormLock struct {
db *gorm.DB
id int
}
func (g *gormLock) Unlock(_ context.Context) error {
return g.db.Model(&CronJobLock{ID: g.id}).Updates(&CronJobLock{Status: StatusFinished}).Error
}