-
Notifications
You must be signed in to change notification settings - Fork 414
/
audit.go
80 lines (70 loc) · 1.52 KB
/
audit.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
package api
import (
"context"
"time"
"github.com/go-gorp/gorp"
"github.com/rockbears/log"
)
const (
maxVersion = 10
delay = 1
)
func auditCleanerRoutine(ctx context.Context, DBFunc func() *gorp.DbMap) {
tick := time.NewTicker(delay * time.Minute).C
for {
select {
case <-ctx.Done():
if ctx.Err() != nil {
log.Error(ctx, "Exiting auditCleanerRoutine: %v", ctx.Err())
}
return
case <-tick:
db := DBFunc()
if db != nil {
err := actionAuditCleaner(DBFunc())
if err != nil {
log.Warn(ctx, "AuditCleanerRoutine> Action clean failed: %s", err)
}
}
}
}
}
func actionAuditCleaner(db *gorp.DbMap) error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback() // nolint
// Load all action and the number of version in database
query := `SELECT action_id, COUNT(versionned) FROM action_audit GROUP BY action_id`
rows, err := tx.Query(query)
if err != nil {
return err
}
defer rows.Close() // nolint
var toDel []int64
var actionID, count int64
for rows.Next() {
err = rows.Scan(&actionID, &count)
if err != nil {
return err
}
if count > maxVersion {
toDel = append(toDel, actionID)
}
}
// Now delete older version to keep only 20
query = `DELETE FROM action_audit
WHERE action_id = $1 AND versionned IN
( SELECT versionned FROM action_audit
WHERE action_id = $1
ORDER BY versionned DESC
OFFSET $2
)`
for _, id := range toDel {
if _, err := tx.Exec(query, id, maxVersion); err != nil {
return err
}
}
return tx.Commit()
}