package jobs import ( "context" "errors" "sort" "time" ) type Queue interface { Claim(ctx context.Context, workerID string, allowedTypes []string, now time.Time, leaseDuration time.Duration) (*Job, error) Complete(ctx context.Context, id, owner string, now time.Time) error Fail(ctx context.Context, id, owner, message, code string, now, retryAt time.Time) error Heartbeat(ctx context.Context, id, owner string, now time.Time, leaseDuration time.Duration) error } // TerminalFailer is an optional Queue extension (P6): a permanent failure goes // straight to the dead-letter state with a stable error code instead of // consuming the retry budget. type TerminalFailer interface { FailTerminal(ctx context.Context, id, owner, message, code string, now time.Time) error } type Handler func(context.Context, Job) error type WorkerConfig struct { Queue Queue WorkerID string LeaseDuration time.Duration HeartbeatInterval time.Duration RetryDelay time.Duration Now func() time.Time Handlers map[string]Handler OnError func(error) } type Worker struct { queue Queue workerID string leaseDuration time.Duration heartbeatInterval time.Duration retryDelay time.Duration now func() time.Time handlers map[string]Handler allowedTypes []string onError func(error) } func NewWorker(config WorkerConfig) (*Worker, error) { if config.Queue == nil { return nil, errors.New("queue is required") } if config.WorkerID == "" { return nil, errors.New("worker ID is required") } if config.LeaseDuration <= 0 { return nil, errors.New("lease duration must be positive") } if config.Now == nil { config.Now = time.Now } if config.RetryDelay <= 0 { config.RetryDelay = time.Second } if config.HeartbeatInterval <= 0 { config.HeartbeatInterval = config.LeaseDuration / 3 } if config.OnError == nil { config.OnError = func(error) {} } allowedTypes := make([]string, 0, len(config.Handlers)) for jobType := range config.Handlers { allowedTypes = append(allowedTypes, jobType) } sort.Strings(allowedTypes) return &Worker{ queue: config.Queue, workerID: config.WorkerID, leaseDuration: config.LeaseDuration, heartbeatInterval: config.HeartbeatInterval, retryDelay: config.RetryDelay, now: config.Now, handlers: config.Handlers, allowedTypes: allowedTypes, onError: config.OnError, }, nil } func (w *Worker) Run(ctx context.Context, pollInterval time.Duration) error { if pollInterval <= 0 { return errors.New("poll interval must be positive") } for { claimed, err := w.RunOnce(ctx) if err != nil { w.onError(err) } if claimed && err == nil { continue } timer := time.NewTimer(pollInterval) select { case <-ctx.Done(): if !timer.Stop() { <-timer.C } return nil case <-timer.C: } } } func (w *Worker) failJob(ctx context.Context, job Job, cause error, failedAt time.Time) error { code := "" if terminal, c := Terminal(cause); terminal { code = c if failer, ok := w.queue.(TerminalFailer); ok { return failer.FailTerminal(ctx, job.ID, w.workerID, cause.Error(), code, failedAt) } } return w.queue.Fail(ctx, job.ID, w.workerID, cause.Error(), code, failedAt, failedAt.Add(w.retryDelay)) } func (w *Worker) RunOnce(ctx context.Context) (bool, error) { claimedAt := w.now() job, err := w.queue.Claim(ctx, w.workerID, w.allowedTypes, claimedAt, w.leaseDuration) if err != nil { return false, err } if job == nil { return false, nil } handler := w.handlers[job.Type] if handler == nil { err := Permanent(ErrCodeNoHandler, errors.New("no handler registered for job type "+job.Type)) failedAt := w.now() if failErr := w.failJob(ctx, *job, err, failedAt); failErr != nil { return true, failErr } return true, err } heartbeatCtx, stopHeartbeat := context.WithCancel(ctx) heartbeatResult := make(chan error, 1) go func() { ticker := time.NewTicker(w.heartbeatInterval) defer ticker.Stop() for { select { case <-heartbeatCtx.Done(): heartbeatResult <- nil return case <-ticker.C: if err := w.queue.Heartbeat(ctx, job.ID, w.workerID, w.now(), w.leaseDuration); err != nil { heartbeatResult <- err return } } } }() handlerErr := handler(ctx, *job) stopHeartbeat() heartbeatErr := <-heartbeatResult if handlerErr == nil { handlerErr = heartbeatErr } if handlerErr != nil { failedAt := w.now() if failErr := w.failJob(ctx, *job, handlerErr, failedAt); failErr != nil { return true, failErr } return true, handlerErr } if err := w.queue.Complete(ctx, job.ID, w.workerID, w.now()); err != nil { return true, err } return true, nil }