Database cleaner

This commit is contained in:
LittleSheep 2024-04-06 14:05:51 +08:00
parent f2f75269d5
commit b2719ae302
3 changed files with 51 additions and 7 deletions

View File

@ -1,6 +1,8 @@
package main package main
import ( import (
"git.solsynth.dev/hydrogen/messaging/pkg/services"
"github.com/robfig/cron/v3"
"os" "os"
"os/signal" "os/signal"
"syscall" "syscall"
@ -50,6 +52,11 @@ func main() {
server.NewServer() server.NewServer()
go server.Listen() go server.Listen()
// Configure timed tasks
quartz := cron.New(cron.WithLogger(cron.VerbosePrintfLogger(&log.Logger)))
quartz.AddFunc("@every 60m", services.DoAutoDatabaseCleanup)
quartz.Start()
// Messages // Messages
log.Info().Msgf("Messaging v%s is started...", messaging.AppVersion) log.Info().Msgf("Messaging v%s is started...", messaging.AppVersion)
@ -58,4 +65,6 @@ func main() {
<-quit <-quit
log.Info().Msgf("Messaging v%s is quitting...", messaging.AppVersion) log.Info().Msgf("Messaging v%s is quitting...", messaging.AppVersion)
quartz.Stop()
} }

View File

@ -5,14 +5,16 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
func RunMigration(source *gorm.DB) error { var DatabaseAutoActionRange = []any{
if err := source.AutoMigrate(
&models.Account{}, &models.Account{},
&models.Channel{}, &models.Channel{},
&models.ChannelMember{}, &models.ChannelMember{},
&models.Message{}, &models.Message{},
&models.Attachment{}, &models.Attachment{},
); err != nil { }
func RunMigration(source *gorm.DB) error {
if err := source.AutoMigrate(DatabaseAutoActionRange...); err != nil {
return err return err
} }

33
pkg/services/cleaner.go Normal file
View File

@ -0,0 +1,33 @@
package services
import (
"git.solsynth.dev/hydrogen/messaging/pkg/database"
"git.solsynth.dev/hydrogen/messaging/pkg/models"
"github.com/rs/zerolog/log"
"time"
)
func DoAutoDatabaseCleanup() {
deadline := time.Now().Add(60 * time.Minute)
log.Debug().Time("deadline", deadline).Msg("Now cleaning up entire database...")
// Deal soft-deletion
var count int64
for _, model := range database.DatabaseAutoActionRange {
tx := database.C.Unscoped().Delete(model, "deleted_at >= ?", deadline)
if tx.Error != nil {
log.Error().Err(tx.Error).Msg("An error occurred when running auth context cleanup...")
}
count += tx.RowsAffected
}
// Clean up outdated chat history
tx := database.C.Unscoped().Delete(&models.Message{}, "created_at < ?", time.Now().Add(30*24*time.Hour))
if tx.Error != nil {
log.Error().Err(tx.Error).Msg("An error occurred when running auth context cleanup...")
} else {
count += tx.RowsAffected
}
log.Debug().Int64("affected", count).Msg("Clean up entire database accomplished.")
}