refactor(admin): decouple system cleanup with event bus and enforce single owner principle

This commit is contained in:
ryan
2026-09-03 08:50:37 +08:00
parent 1e19d8114a
commit 6b28adfacf
14 changed files with 419 additions and 50 deletions
@@ -255,3 +255,13 @@ func CreatePushHistoryRecord(ctx context.Context, history *entity.PushHistory) e
func PushHistoryQuery(ctx context.Context) *gorm.DB {
return GetDB(ctx).Model(&entity.PushHistory{})
}
// DeletePushHistoriesBeforeRecord deletes push history records created before cutoff time.
func DeletePushHistoriesBeforeRecord(ctx context.Context, cutoff time.Time) (int64, error) {
db := GetDB(ctx)
if db == nil {
return 0, nil
}
result := db.Where("created_at < ?", cutoff).Delete(&entity.PushHistory{})
return result.RowsAffected, result.Error
}
@@ -10,6 +10,7 @@ import (
"Wavelet/plugins/domain/msg_gateway/model/entity"
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -94,3 +95,51 @@ func TestPushEventDAO_CRUD(t *testing.T) {
_, err = dao.GetPushEventByIDRecord(ctx, ev.ID)
assert.Error(t, err)
}
func TestPushHistoryDAO_Cleanup(t *testing.T) {
_ = idgen.Init(1)
db, _, cleanup := testhelper.SetupTestEnvironment(t)
defer cleanup()
require.NoError(t, db.AutoMigrate(&entity.PushHistory{}))
dao.SetDBServiceForTest(stubDBService{db: db})
t.Cleanup(func() { dao.SetDBServiceForTest(nil) })
ctx := context.Background()
now := time.Now()
oldTime := now.Add(-40 * 24 * time.Hour)
recentTime := now.Add(-5 * 24 * time.Hour)
oldHistory := entity.PushHistory{
EventKey: "login",
Channel: "telegram",
Target: "123",
Title: "Old login",
Content: "Old content",
Level: "info",
Status: "success",
CreatedAt: oldTime,
}
recentHistory := entity.PushHistory{
EventKey: "login",
Channel: "telegram",
Target: "123",
Title: "Recent login",
Content: "Recent content",
Level: "info",
Status: "success",
CreatedAt: recentTime,
}
require.NoError(t, db.Create(&oldHistory).Error)
require.NoError(t, db.Create(&recentHistory).Error)
cutoff := now.Add(-30 * 24 * time.Hour)
deleted, err := dao.DeletePushHistoriesBeforeRecord(ctx, cutoff)
require.NoError(t, err)
assert.Equal(t, int64(1), deleted)
var count int64
db.Model(&entity.PushHistory{}).Count(&count)
assert.Equal(t, int64(1), count)
}
@@ -21,6 +21,7 @@ import (
"context"
"embed"
"reflect"
"time"
"github.com/gin-gonic/gin"
)
@@ -204,6 +205,13 @@ func (p *Plugin) Apply(ctx *core.Context) error {
return nil
})
// 8.1 Register system cleanup event listener
ctx.Events().On(contracts.EventTopicSystemCleanup, func(c context.Context, _ contracts.SystemCleanupEvent) error {
const defaultPushHistoryRetention = 30 * 24 * time.Hour
_, err := service.CleanupPushHistories(c, defaultPushHistoryRetention)
return err
})
// 9. Register built-in domain events and provide PushRegistry
service.RegisterCustomEvents()
core.Provide[contracts.PushRegistry](ctx, service.PushRegistryAdapter{})
@@ -15,6 +15,7 @@ import (
"encoding/json"
"errors"
"fmt"
"time"
)
const (
@@ -174,3 +175,15 @@ func RecordPushHistory(ctx context.Context, req do.SendPayload, status, errMsg s
func ListPushHistories(ctx context.Context, filter do.PushHistoryListFilter) (int64, []entity.PushHistory, error) {
return dao.ListPushHistoriesRecord(ctx, filter)
}
// CleanupPushHistories removes push delivery audit records older than the retention duration.
func CleanupPushHistories(ctx context.Context, retention time.Duration) (int64, error) {
cutoff := time.Now().Add(-retention)
deleted, err := dao.DeletePushHistoriesBeforeRecord(ctx, cutoff)
if err != nil {
logger.WarnF(ctx, "[Push] 清理历史推送日志失败: %v", err)
return 0, err
}
logger.InfoF(ctx, "[Push] 已清理 %s 前推送历史日志,共 %d 条", cutoff.Format(time.RFC3339), deleted)
return deleted, nil
}