Files
junhong_cmp_fiber/internal/task/integration_archive.go
2026-08-20 12:03:17 +08:00

70 lines
2.2 KiB
Go

package task
import (
"context"
"fmt"
"time"
"github.com/bytedance/sonic"
"github.com/hibiken/asynq"
"go.uber.org/zap"
"github.com/break/junhong_cmp_fiber/internal/application/auditarchive"
"github.com/break/junhong_cmp_fiber/pkg/constants"
)
// IntegrationDailyArchivePayload 是人工补档时可选的任务载荷。
type IntegrationDailyArchivePayload struct {
ArchiveDate string `json:"archive_date"`
}
// IntegrationArchiveHandler 处理 Integration Log 每日归档。
type IntegrationArchiveHandler struct {
service *auditarchive.Service
logger *zap.Logger
}
// NewIntegrationArchiveHandler 创建 Integration Log 归档任务处理器。
func NewIntegrationArchiveHandler(service *auditarchive.Service, logger *zap.Logger) *IntegrationArchiveHandler {
return &IntegrationArchiveHandler{service: service, logger: logger}
}
// HandleDaily 执行前一完整自然日归档,或按任务载荷补档指定自然日。
func (h *IntegrationArchiveHandler) HandleDaily(ctx context.Context, task *asynq.Task) error {
if h.service == nil {
return fmt.Errorf("Integration Log 归档服务未配置")
}
var err error
if len(task.Payload()) == 0 {
err = h.service.ArchivePreviousIntegrationDay(ctx)
} else {
var payload IntegrationDailyArchivePayload
if unmarshalErr := sonic.Unmarshal(task.Payload(), &payload); unmarshalErr != nil {
return fmt.Errorf("解析 Integration Log 每日归档任务载荷失败: %w", unmarshalErr)
}
date, parseErr := parseArchiveDate(payload.ArchiveDate)
if parseErr != nil {
return parseErr
}
err = h.service.ArchiveIntegrationDate(ctx, date)
}
if err != nil {
h.logger.Error("Integration Log 每日冷归档失败", zap.Error(err))
return err
}
h.logger.Info("Integration Log 每日冷归档完成")
return nil
}
func parseArchiveDate(value string) (time.Time, error) {
location, err := time.LoadLocation(constants.AuditArchiveTimezone)
if err != nil {
return time.Time{}, fmt.Errorf("加载 Integration Log 归档时区失败: %w", err)
}
date, err := time.ParseInLocation(time.DateOnly, value, location)
if err != nil {
return time.Time{}, fmt.Errorf("解析 Integration Log 归档日期失败: %w", err)
}
return date, nil
}