feat(cron): implement IP ban maintenance tasks

Add IPBanManager to handle periodic background jobs including:
- Expiring outdated bans
- Syncing hit counts from Redis to DB
- Performing full Redis state synchronization

Additionally, update the service expiration logic to use system time
and add unit tests for CIDR normalization and overlap checking.
This commit is contained in:
zenfun
2026-01-04 01:28:43 +08:00
parent 63d43db39d
commit 830c6fa6e7
3 changed files with 217 additions and 1 deletions

View File

@@ -7,6 +7,7 @@ import (
"log/slog"
"net"
"strings"
"time"
"github.com/ez-api/ez-api/internal/model"
"github.com/redis/go-redis/v9"
@@ -288,12 +289,14 @@ func (s *IPBanService) SyncAllToRedis(ctx context.Context) error {
// ExpireOutdatedBans marks expired bans and removes them from Redis.
func (s *IPBanService) ExpireOutdatedBans(ctx context.Context) (int64, error) {
now := time.Now().Unix()
// Find active bans that have expired
var expiredBans []model.IPBan
if err := s.db.WithContext(ctx).
Where("status = ? AND expires_at IS NOT NULL AND expires_at <= ?",
model.IPBanStatusActive,
ctx.Value("now")). // This should be time.Now().Unix() in caller
now).
Find(&expiredBans).Error; err != nil {
return 0, err
}