package dregarnuhr import ( "errors" "time" ) // CanStart retains a single background worker under foreground load, avoiding // starvation by long-lived requests while protecting foreground capacity. func CanStart(s Settings, active int64, foreground bool) bool { return !s.Paused && active < int64(s.Concurrency) && (!foreground || active == 0) } // RetryDelay doubles per completed attempt and saturates without overflowing. func RetryDelay(baseSeconds, attempt int) time.Duration { if baseSeconds < 1 { baseSeconds = 1 } if baseSeconds >= 86400 { return 24 * time.Hour } delay := time.Duration(baseSeconds) * time.Second for i := 1; i < attempt; i++ { if delay >= 12*time.Hour { return 24 * time.Hour } delay *= 2 } return delay } type Completion struct { Status, Message, Level string RetryAt time.Time } // Complete is independent of DB access. The repository persists this decision. func Complete(job Job, runErr error, baseSeconds int, now time.Time) Completion { out := Completion{Status: "succeeded", Level: "info"} if runErr == nil { return out } out.Message = runErr.Error() switch { case errors.Is(runErr, ErrSkipped): out.Status = "skipped" case job.CancelRequested: out.Status = "cancelled" case job.Attempts < job.MaxAttempts: out.Status = "queued" out.Level = "warning" out.RetryAt = now.Add(RetryDelay(baseSeconds, job.Attempts)) default: out.Status = "failed" out.Level = "error" } return out }