/
services.go
61 lines (52 loc) · 1.72 KB
/
services.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
package todos
import (
"time"
"github.com/jinzhu/gorm"
)
const (
tokenCleanupSvcInterval = 1 * time.Hour
)
// TokensCleanupService is a go routine that runs the TokenCleanup function every hour,
// logging the results to disk. It is run when it is first called, then every hour.
func (s *API) TokensCleanupService() {
logger.Printf("starting token cleanup service")
ticker := time.NewTicker(tokenCleanupSvcInterval)
for {
// Execute the tokens cleanup command and log the results
rows, err := TokensCleanup(s.db)
if err != nil {
logger.Printf("cleaned up %d rows from tokens before error: %s", rows, err)
} else if rows > 0 {
logger.Printf("cleaned up %d expired tokens from the database", rows)
} else {
// TODO: make this a lower log level when log leveling is a thing.
logger.Printf("no expired tokens to clean up")
}
// Block until the next scheduled service run
<-ticker.C
}
}
// TokensCleanup iterates through the database and finds any tokens that have expired,
// deleting them from the database. It returns the number of rows deleted and any
// errors that might have occurred during processing. Note that this function is run
// inside of a transaction in case it is long running.
func TokensCleanup(db *gorm.DB) (rows int, err error) {
err = db.Transaction(func(tx *gorm.DB) (err error) {
now := time.Now()
var tokens []Token
if err = tx.Where("refresh_by < ?", now).Find(&tokens).Error; err != nil {
return err
}
for _, token := range tokens {
// Secondary check is probably unnecessary
if token.RefreshBy.Before(now) {
if err = tx.Delete(&token).Error; err != nil {
return err
}
rows++
}
}
return nil // will commit the transaction
})
return rows, err
}