-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcleanup.go
More file actions
75 lines (64 loc) · 1.39 KB
/
cleanup.go
File metadata and controls
75 lines (64 loc) · 1.39 KB
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
package smtp
import (
"context"
"os"
"path/filepath"
"strings"
"time"
"go.uber.org/zap"
)
// startCleanupRoutine starts background cleanup of temp files
func (p *Plugin) startCleanupRoutine(ctx context.Context) {
if p.cfg.AttachmentStorage.Mode != "tempfile" {
return
}
ticker := time.NewTicker(p.cfg.AttachmentStorage.CleanupAfter)
go func() {
for {
select {
case <-ctx.Done():
ticker.Stop()
return
case <-ticker.C:
p.cleanupTempFiles()
}
}
}()
}
// cleanupTempFiles removes old temp files
func (p *Plugin) cleanupTempFiles() {
dir := p.cfg.AttachmentStorage.TempDir
cutoff := time.Now().Add(-p.cfg.AttachmentStorage.CleanupAfter)
entries, err := os.ReadDir(dir)
if err != nil {
// Directory might not exist yet, which is fine
if !os.IsNotExist(err) {
p.log.Error("cleanup readdir error", zap.Error(err))
}
return
}
removed := 0
for _, entry := range entries {
if !strings.HasPrefix(entry.Name(), "smtp-att-") {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
if info.ModTime().Before(cutoff) {
path := filepath.Join(dir, entry.Name())
if err := os.Remove(path); err != nil {
p.log.Warn("failed to remove temp file",
zap.String("path", path),
zap.Error(err),
)
} else {
removed++
}
}
}
if removed > 0 {
p.log.Debug("temp file cleanup completed", zap.Int("removed", removed))
}
}