Skip to content

Commit d4dc81b

Browse files
committed
fix gc
1 parent 5d60775 commit d4dc81b

File tree

1 file changed

+37
-18
lines changed

1 file changed

+37
-18
lines changed

internal/gc/gc.go

+37-18
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ type Gc struct {
1818
}
1919

2020
func (g *Gc) Init() {
21+
g.cleanup()
2122
go func() {
2223
ticker := time.NewTicker(24 * time.Hour)
2324
defer ticker.Stop()
@@ -36,30 +37,48 @@ func (g *Gc) cleanup() {
3637
}
3738

3839
for _, file := range files {
39-
var post *models.Post
40-
r = g.database.Handler().
41-
Where("audio_id = ?", file.Id).
42-
Or("image_id = ?", file.Id).
43-
First(&post)
44-
if r.Error != nil && !errors.Is(r.Error, gorm.ErrRecordNotFound) {
45-
g.l.Error("gc: cannot fetch post", zap.Error(errors.WithStack(r.Error)))
40+
if g.IsUsedForUsers(file) {
41+
continue
42+
}
43+
if g.IsUsedForPosts(file) {
44+
continue
45+
}
46+
47+
if err := g.s3.Delete(file.Path); err != nil {
48+
g.l.Error("gc: cannot delete s3 file", zap.Error(errors.WithStack(err)))
4649
return
4750
}
48-
if post == nil || post.Id == 0 {
49-
if err := g.s3.Delete(file.Path); err != nil {
50-
g.l.Error("gc: cannot delete s3 file", zap.Error(errors.WithStack(err)))
51-
return
52-
}
53-
r = g.database.Handler().Delete(&file)
54-
if r.Error != nil {
55-
g.l.Error("gc: cannot delete db file", zap.Error(errors.WithStack(r.Error)))
56-
} else {
57-
g.l.Info("gc: cleaned", zap.Uint64("id", file.Id), zap.String("path", file.Path))
58-
}
51+
52+
r = g.database.Handler().Delete(&file)
53+
if r.Error != nil {
54+
g.l.Error("gc: cannot delete db file", zap.Error(errors.WithStack(r.Error)))
55+
} else {
56+
g.l.Info("gc: cleaned", zap.Uint64("id", file.Id), zap.String("path", file.Path))
5957
}
6058
}
6159
}
6260

61+
func (g *Gc) IsUsedForPosts(file *models.File) bool {
62+
var post models.Post
63+
r := g.database.Handler().
64+
Where("audio_id = ?", file.Id).
65+
Or("image_id = ?", file.Id).
66+
First(&post)
67+
if r.Error != nil && !errors.Is(r.Error, gorm.ErrRecordNotFound) {
68+
g.l.Error("gc: query failed", zap.Error(errors.WithStack(r.Error)))
69+
}
70+
return post.Id != 0
71+
}
72+
73+
func (g *Gc) IsUsedForUsers(file *models.File) bool {
74+
var user models.User
75+
r := g.database.Handler().Where("image_id = ?", file.Id).First(&user)
76+
if r.Error != nil && !errors.Is(r.Error, gorm.ErrRecordNotFound) {
77+
g.l.Error("gc: query failed", zap.Error(errors.WithStack(r.Error)))
78+
}
79+
return user.Id != 0
80+
}
81+
6382
func New(database *database.Database, s3 *s3.S3, l *logger.Logger) *Gc {
6483
return &Gc{database: database, s3: s3, l: l}
6584
}

0 commit comments

Comments
 (0)