-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotator.go
101 lines (80 loc) · 2.03 KB
/
rotator.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
package main
import (
"context"
"time"
"github.com/Aldiwildan77/dfs/entity"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
)
type rotator interface {
StartRotator(ctx context.Context, tick time.Duration)
RotateFile(ctx context.Context, file entity.FileMetadata) (string, error)
}
type Rotator struct {
cfg Config
db *gorm.DB
discord discord
}
func NewRotator(cfg Config, db *gorm.DB, discord discord) rotator {
return &Rotator{
cfg: cfg,
db: db,
discord: discord,
}
}
func (r *Rotator) StartRotator(ctx context.Context, tick time.Duration) {
ticker := time.NewTicker(tick)
defer ticker.Stop()
for range ticker.C {
log.Info().Msg("Rotating expiring files...")
r.rotateExpiringFiles(ctx)
}
}
func (r *Rotator) rotateExpiringFiles(ctx context.Context) {
var files []entity.FileMetadata
now := time.Now()
expiryThreshold := now.Add(time.Duration(r.cfg.RotatorThreshold) * time.Hour)
if err := r.db.Where("last_rotated_at <= ?", expiryThreshold).Find(&files).Error; err != nil {
log.Error().Err(err).Msg("Failed to fetch expiring files")
return
}
for _, file := range files {
_, err := r.RotateFile(ctx, file)
if err != nil {
log.Error().Err(err).Msg("Failed to rotate file")
}
}
}
func (r *Rotator) RotateFile(ctx context.Context, file entity.FileMetadata) (string, error) {
now := time.Now()
req := &FetchFileRequest{
GuildID: file.GuildID,
ChannelID: file.ChannelID,
MessageID: file.MessageID,
}
newURL, err := r.discord.FetchFile(ctx, req)
if err != nil {
return "", err
}
file.ExpiredAt, err = GetExURL(newURL)
if err != nil {
return "", err
}
file.IssuedAt, err = GetIsURL(newURL)
if err != nil {
return "", err
}
file.Hash, err = GetHashURL(newURL)
if err != nil {
return "", err
}
file.URL = newURL
file.LastRotatedAt = &now
if err := r.db.Save(&file).Error; err != nil {
// Allow the rotator to retry on the next tick
log.Error().Err(err).Msg("Failed to save rotated file")
return "", err
}
log.Info().Msgf("Rotated file %s", file.Filename)
return newURL, nil
}