package controlplane import ( "encoding/json" "fmt" "strings" "time" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/scheduling" ) const SchedulesKind = "schedules" func scheduleDefinition() Definition { return Definition{ Kind: SchedulesKind, Title: "Schedules", Document: []scheduling.JobSpec{}, ApplyMode: "live", Seed: func(config.Config) any { return []scheduling.JobSpec{} }, Validate: func(input []byte) error { return validateAs(input, validateSchedules) }, Normalize: normalizeSchedules, } } func validateSchedules(jobs []scheduling.JobSpec) error { seen := make(map[string]struct{}, len(jobs)) for _, job := range jobs { if err := scheduling.RefuseDangerousJob(job); err != nil { return err } if strings.TrimSpace(job.ID) == "" { return fmt.Errorf("schedule ID is required") } if _, exists := seen[job.ID]; exists { return fmt.Errorf("duplicate schedule %q", job.ID) } seen[job.ID] = struct{}{} switch job.Kind { case scheduling.KindWorkflow: case scheduling.KindChat: if job.Target.Channel == "" || job.Target.ChatID == "" || strings.TrimSpace(job.Payload.Text) == "" { return fmt.Errorf("chat schedule %q needs a channel, chat ID and message", job.ID) } default: return fmt.Errorf("schedule %q has unsupported kind %q", job.ID, job.Kind) } if err := job.Schedule.Validate(); err != nil { return err } if err := scheduling.Pool(job.Pool).Validate(); err != nil { return err } } return nil } func normalizeSchedules(input []byte) ([]byte, error) { var jobs []scheduling.JobSpec if err := json.Unmarshal(input, &jobs); err != nil { return nil, err } now := time.Now().UTC() for i := range jobs { jobs[i].Schedule = jobs[i].Schedule.Resolved() if jobs[i].NextRun.IsZero() { next, err := jobs[i].Schedule.FirstRun(now) if err != nil { return nil, err } jobs[i].NextRun = next.UTC() } if jobs[i].Created.IsZero() { jobs[i].Created = now } jobs[i].Updated = now } return json.Marshal(jobs) }