package governance import ( "fmt" "regexp" "strings" "time" ) // 整库逻辑备份的定时计划(平台「系统设置 → 存储与备份」)。校验集中在领域层: // 非法值一律拒绝,绝不把半成品下发到数据面主机。 const ( BackupScheduleDefaultTime = "03:30" BackupScheduleMinDays = 1 BackupScheduleMaxDays = 365 BackupScheduleMinMonths = 0 BackupScheduleMaxMonths = 24 ) // backupScheduleTime 形如 03:30;cron 用 24 小时制,不接受 24:00 及秒位。 var backupScheduleTime = regexp.MustCompile(`^([01][0-9]|2[0-3]):[0-5][0-9]$`) // BackupSchedule 是一份可下发的备份计划(时间 + 保留策略)。 type BackupSchedule struct { ID string Enabled bool ScheduleTime string RetentionDays int RetentionMonths int LastAppliedAt *time.Time LastAppliedSummary string UpdatedBy string UpdatedAt time.Time } // Validate 校验时间格式与保留范围;返回的错误直接可展示给操作者。 func (schedule BackupSchedule) Validate() error { if !backupScheduleTime.MatchString(strings.TrimSpace(schedule.ScheduleTime)) { return fmt.Errorf("定时时间必须是 HH:MM(00:00~23:59),收到 %q", schedule.ScheduleTime) } if schedule.RetentionDays < BackupScheduleMinDays || schedule.RetentionDays > BackupScheduleMaxDays { return fmt.Errorf("储存天数需在 %d~%d 之间,收到 %d", BackupScheduleMinDays, BackupScheduleMaxDays, schedule.RetentionDays) } if schedule.RetentionMonths < BackupScheduleMinMonths || schedule.RetentionMonths > BackupScheduleMaxMonths { return fmt.Errorf("每月归档保留需在 %d~%d 之间,收到 %d", BackupScheduleMinMonths, BackupScheduleMaxMonths, schedule.RetentionMonths) } return nil } // Normalize 填默认值并去掉时间两侧空白,便于比较"是否变化"。 func (schedule BackupSchedule) Normalize() BackupSchedule { schedule.ScheduleTime = strings.TrimSpace(schedule.ScheduleTime) if schedule.ScheduleTime == "" { schedule.ScheduleTime = BackupScheduleDefaultTime } return schedule } // SameHostPlan 判断两份计划在数据面主机上是否等价(只看会写进 cron 的字段)。 func (schedule BackupSchedule) SameHostPlan(other BackupSchedule) bool { return schedule.Enabled == other.Enabled && schedule.ScheduleTime == other.ScheduleTime && schedule.RetentionDays == other.RetentionDays && schedule.RetentionMonths == other.RetentionMonths } // DescribesNextRunUtc 仅用于日志:给出下一次执行的 UTC 时刻(按当天算)。 func (schedule BackupSchedule) NextRunAfter(now time.Time) (time.Time, error) { if err := schedule.Validate(); err != nil { return time.Time{}, err } hour, minute := 0, 0 if _, err := fmt.Sscanf(schedule.ScheduleTime, "%d:%d", &hour, &minute); err != nil { return time.Time{}, err } next := time.Date(now.Year(), now.Month(), now.Day(), hour, minute, 0, 0, now.Location()) if !next.After(now) { next = next.Add(24 * time.Hour) } return next, nil }