582 lines
20 KiB
Go
582 lines
20 KiB
Go
// Package jobrunner runs durable scheduled jobs when they fall due. Jobs are
|
|
// claimed under a lease, so they survive restarts and crashes, and each
|
|
// handler runs in the transaction that completes its job, so a
|
|
// database-only effect happens once even when several workers race.
|
|
package jobrunner
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"maps"
|
|
"runtime/debug"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
"unicode"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/inbound"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/worker/retry"
|
|
)
|
|
|
|
// Job outcome label values. Every claimed job ends a pass with exactly one.
|
|
const (
|
|
// OutcomeDone: the handler's effect and the completion committed.
|
|
OutcomeDone = "done"
|
|
// OutcomeRetry: the attempt failed and the job waits for its retry.
|
|
OutcomeRetry = "retry"
|
|
// OutcomeDead: the job failed finally and needs an operator.
|
|
OutcomeDead = "dead"
|
|
// OutcomeLeaseLost: the job was canceled or reclaimed by another worker
|
|
// before this attempt could finish; nothing of the attempt committed.
|
|
OutcomeLeaseLost = "lease_lost"
|
|
// OutcomeReleased: the worker gave the job back unfinished, at shutdown
|
|
// or after a database failure outside the handler, without counting
|
|
// the attempt.
|
|
OutcomeReleased = "released"
|
|
)
|
|
|
|
// Outcomes lists every outcome label value, for metrics that expose the
|
|
// series at zero.
|
|
var Outcomes = []string{OutcomeDone, OutcomeRetry, OutcomeDead, OutcomeLeaseLost, OutcomeReleased}
|
|
|
|
// maxReasonLength bounds the logged failure reason.
|
|
const maxReasonLength = 256
|
|
|
|
// errHandlerPanic replaces the value of a handler panic, which could quote
|
|
// the payload.
|
|
var errHandlerPanic = errors.New("handler panicked")
|
|
|
|
// Metrics records job outcomes and the backlog. Labels are kinds, which the
|
|
// code defines, and the outcome constants of this package.
|
|
type Metrics interface {
|
|
// PrepareScheduledJobKind exposes the series of kind at zero, so an
|
|
// alert on the first dead job sees an increase instead of a new series.
|
|
PrepareScheduledJobKind(kind string)
|
|
ObserveScheduledJob(kind, outcome string)
|
|
ObserveScheduledJobBacklog(backlog outbound.JobBacklog)
|
|
}
|
|
|
|
// Settings are the named worker limits; config validates their ranges.
|
|
type Settings struct {
|
|
// BatchSize bounds the jobs of one claim. The jobs of a batch run one
|
|
// after another under leases taken together, so the batch should finish
|
|
// well within one lease.
|
|
BatchSize int
|
|
// PollInterval is the wait after a pass that claimed less than a batch.
|
|
PollInterval time.Duration
|
|
// Lease is how long a claimed job belongs to this worker. It also bounds
|
|
// one handler attempt.
|
|
Lease time.Duration
|
|
// MaxAttempts bounds the attempts of jobs scheduled without their own
|
|
// limit.
|
|
MaxAttempts int
|
|
// Backoff is the wait before a failed job is retried and after a pass
|
|
// that failed in the database.
|
|
Backoff retry.Backoff
|
|
// ShutdownGrace is how long a job in progress may continue after Run's
|
|
// context ends. When it expires the attempt is canceled, its
|
|
// transaction rolls back, and the job is released.
|
|
ShutdownGrace time.Duration
|
|
// StoreTimeout bounds one claim, failure record, release, or backlog
|
|
// read.
|
|
StoreTimeout time.Duration
|
|
// BacklogInterval is the least time between two backlog reads for the
|
|
// metrics.
|
|
BacklogInterval time.Duration
|
|
}
|
|
|
|
func (settings Settings) validate() error {
|
|
if settings.BatchSize < 1 || settings.MaxAttempts < 1 || settings.MaxAttempts > domain.MaxScheduledJobAttempts {
|
|
return fmt.Errorf("jobrunner.New - batch size must be positive and max attempts between 1 and %d", domain.MaxScheduledJobAttempts)
|
|
}
|
|
if settings.PollInterval <= 0 || settings.Lease <= 0 || settings.ShutdownGrace <= 0 ||
|
|
settings.StoreTimeout <= 0 || settings.BacklogInterval <= 0 {
|
|
return errors.New("jobrunner.New - intervals, lease, grace, and timeouts must be positive")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Worker claims due jobs of its registered kinds and runs their handlers.
|
|
// Several workers may run against one database, in one process or many.
|
|
type Worker struct {
|
|
owner uuid.UUID
|
|
handlers map[string]inbound.JobHandler
|
|
kinds []string
|
|
store outbound.JobStore
|
|
metrics Metrics
|
|
logger *slog.Logger
|
|
settings Settings
|
|
clock func() time.Time
|
|
}
|
|
|
|
// New builds a worker for handlers, one per kind. clock is the application
|
|
// clock: every due and lease decision uses it, so tests move time with a
|
|
// fake one. Each worker gets a random lease owner ID.
|
|
func New(
|
|
handlers []inbound.JobHandler,
|
|
store outbound.JobStore,
|
|
metrics Metrics,
|
|
logger *slog.Logger,
|
|
settings Settings,
|
|
clock func() time.Time,
|
|
) (*Worker, error) {
|
|
if len(handlers) == 0 {
|
|
return nil, errors.New("jobrunner.New - at least one handler is required")
|
|
}
|
|
if err := settings.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
registry := make(map[string]inbound.JobHandler, len(handlers))
|
|
for _, handler := range handlers {
|
|
kind := handler.JobKind()
|
|
if err := domain.ValidateScheduledJobKind(kind); err != nil {
|
|
return nil, fmt.Errorf("jobrunner.New - handler kind: %w", err)
|
|
}
|
|
if _, exists := registry[kind]; exists {
|
|
return nil, fmt.Errorf("jobrunner.New - kind %s is registered twice", kind)
|
|
}
|
|
registry[kind] = handler
|
|
}
|
|
kinds := slices.Sorted(maps.Keys(registry))
|
|
for _, kind := range kinds {
|
|
metrics.PrepareScheduledJobKind(kind)
|
|
}
|
|
owner := uuid.New()
|
|
return &Worker{
|
|
owner: owner,
|
|
handlers: registry,
|
|
kinds: kinds,
|
|
store: store,
|
|
metrics: metrics,
|
|
logger: logger.With(slog.String("lease_owner", owner.String())),
|
|
settings: settings,
|
|
clock: clock,
|
|
}, nil
|
|
}
|
|
|
|
// Kinds returns the registered kinds in name order.
|
|
func (worker *Worker) Kinds() []string {
|
|
return slices.Clone(worker.kinds)
|
|
}
|
|
|
|
// PassResult counts the claimed jobs of one pass by outcome.
|
|
type PassResult struct {
|
|
Claimed int
|
|
Done int
|
|
Retried int
|
|
Dead int
|
|
LeaseLost int
|
|
Released int
|
|
}
|
|
|
|
func (result *PassResult) add(outcome string) {
|
|
switch outcome {
|
|
case OutcomeDone:
|
|
result.Done++
|
|
case OutcomeRetry:
|
|
result.Retried++
|
|
case OutcomeDead:
|
|
result.Dead++
|
|
case OutcomeLeaseLost:
|
|
result.LeaseLost++
|
|
case OutcomeReleased:
|
|
result.Released++
|
|
}
|
|
}
|
|
|
|
// RunDue runs one pass: it claims the jobs due at the clock's now and runs
|
|
// them in due order. Tests and harnesses call it to run due jobs
|
|
// deterministically; Run repeats it. An error reports a database failure
|
|
// outside the handlers; the jobs it left unfinished are released or wait for
|
|
// their leases to expire.
|
|
func (worker *Worker) RunDue(ctx context.Context) (PassResult, error) {
|
|
return worker.runPass(ctx, ctx)
|
|
}
|
|
|
|
// Run claims and runs due jobs until ctx ends. A pass that claimed a full
|
|
// batch is followed immediately by the next one; otherwise the worker waits
|
|
// PollInterval, and after a database failure Backoff, which grows across
|
|
// consecutive failures. Run stops claiming when ctx ends, lets the job in
|
|
// progress continue for ShutdownGrace, releases the claimed jobs it did not
|
|
// finish, and returns.
|
|
func (worker *Worker) Run(ctx context.Context) {
|
|
workCtx, stopWork := worker.workContext(ctx)
|
|
defer stopWork()
|
|
worker.logger.Info("scheduled job worker started",
|
|
slog.Any("kinds", worker.kinds),
|
|
slog.Int("batch_size", worker.settings.BatchSize),
|
|
slog.Duration("poll_interval", worker.settings.PollInterval),
|
|
slog.Duration("lease", worker.settings.Lease),
|
|
)
|
|
defer worker.logger.Info("scheduled job worker stopped")
|
|
|
|
backlog := backlogRefresher{worker: worker}
|
|
failures := 0
|
|
for ctx.Err() == nil {
|
|
result, err := worker.runPass(ctx, workCtx)
|
|
backlog.refresh(ctx)
|
|
var delay time.Duration
|
|
switch {
|
|
case err != nil && ctx.Err() == nil:
|
|
failures++
|
|
delay = worker.settings.Backoff.Delay(failures)
|
|
worker.logger.Warn("scheduled job pass failed in the database; unfinished jobs are released or wait for their leases",
|
|
slog.Int("claimed", result.Claimed),
|
|
slog.Int("consecutive_failures", failures),
|
|
slog.Duration("retry_in", delay),
|
|
slog.Any("error", err),
|
|
)
|
|
case result.Claimed >= worker.settings.BatchSize:
|
|
failures = 0
|
|
default:
|
|
failures = 0
|
|
delay = worker.settings.PollInterval
|
|
}
|
|
if !retry.Wait(ctx, delay) {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// runPass claims with ctx, so no claim starts after shutdown began, and
|
|
// runs handlers with workCtx, which outlives ctx by the shutdown grace.
|
|
func (worker *Worker) runPass(ctx, workCtx context.Context) (PassResult, error) {
|
|
var result PassResult
|
|
claimCtx, cancel := context.WithTimeout(ctx, worker.settings.StoreTimeout)
|
|
jobs, err := worker.store.Claim(claimCtx, outbound.JobClaim{
|
|
Owner: worker.owner,
|
|
Kinds: worker.kinds,
|
|
Now: worker.clock(),
|
|
Lease: worker.settings.Lease,
|
|
Limit: worker.settings.BatchSize,
|
|
DefaultMaxAttempts: worker.settings.MaxAttempts,
|
|
})
|
|
cancel()
|
|
if err != nil {
|
|
return result, fmt.Errorf("Worker.runPass - claim jobs: %w", err)
|
|
}
|
|
result.Claimed = len(jobs)
|
|
for index, job := range jobs {
|
|
select {
|
|
case <-ctx.Done():
|
|
// Jobs claimed but not started go back at once, so a deadline
|
|
// does not wait for the lease to expire.
|
|
worker.release(ctx, jobs[index:], &result)
|
|
return result, nil
|
|
default:
|
|
}
|
|
outcome, storeErr := worker.process(ctx, workCtx, job)
|
|
if outcome != "" {
|
|
result.add(outcome)
|
|
}
|
|
if storeErr != nil {
|
|
worker.release(ctx, jobs[index+1:], &result)
|
|
return result, storeErr
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// process runs one job and returns its outcome. storeErr reports a database
|
|
// failure outside the handler, after which the pass stops.
|
|
func (worker *Worker) process(ctx, workCtx context.Context, job outbound.ClaimedJob) (outcome string, storeErr error) {
|
|
logger := worker.logger.With(jobAttributes(job)...)
|
|
if job.Exhausted {
|
|
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeDead)
|
|
logger.Error("scheduled job is dead: its last allowed attempt stopped without finishing; it needs an operator",
|
|
slog.String("error_class", string(outbound.JobErrorLeaseExpired)))
|
|
return OutcomeDead, nil
|
|
}
|
|
handler, registered := worker.handlers[job.Kind]
|
|
if !registered {
|
|
return worker.releaseOne(ctx, job), nil
|
|
}
|
|
// The jobs of a batch share the lease of their claim, so each one renews
|
|
// it right before it starts. A job whose turn came after that lease
|
|
// expired is not started: it goes back without using up an attempt, or
|
|
// stays with the worker that already took it over.
|
|
startCtx, cancelStart := context.WithTimeout(ctx, worker.settings.StoreTimeout)
|
|
started, ok, err := worker.store.Start(startCtx, job, worker.clock(), worker.settings.Lease)
|
|
cancelStart()
|
|
if err != nil {
|
|
return worker.releaseOne(ctx, job), fmt.Errorf("Worker.process - start job: %w", err)
|
|
}
|
|
if !ok {
|
|
logger.Info("scheduled job lease expired or was taken over before its turn; not started")
|
|
return worker.releaseOne(ctx, job), nil
|
|
}
|
|
job = started
|
|
|
|
runCtx, cancel := context.WithTimeout(workCtx, job.LeaseExpiresAt.Sub(worker.clock()))
|
|
defer cancel()
|
|
handlerFailed := false
|
|
err = worker.store.Run(runCtx, job, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
err := worker.callHandler(ctx, unit, handler, job, logger)
|
|
handlerFailed = err != nil
|
|
return err
|
|
})
|
|
timedOut := errors.Is(runCtx.Err(), context.DeadlineExceeded) && workCtx.Err() == nil
|
|
switch {
|
|
case err == nil:
|
|
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeDone)
|
|
logger.Debug("scheduled job done")
|
|
return OutcomeDone, nil
|
|
case errors.Is(err, outbound.ErrJobLeaseLost):
|
|
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeLeaseLost)
|
|
logger.Info("scheduled job was canceled or reclaimed before this attempt ran; skipped")
|
|
return OutcomeLeaseLost, nil
|
|
}
|
|
class, attributable := failureClass(err, handlerFailed, timedOut)
|
|
switch {
|
|
case attributable && finalClass(class):
|
|
// A final failure is the job's own, also while stopping.
|
|
return worker.fail(ctx, job, class, err, logger)
|
|
case ctx.Err() != nil:
|
|
// Any other failure while stopping may be the shutdown itself, so
|
|
// it is not counted; the job is released and runs again later.
|
|
return worker.releaseOne(ctx, job), nil
|
|
case attributable:
|
|
return worker.fail(ctx, job, class, err, logger)
|
|
default:
|
|
return worker.releaseOne(ctx, job), fmt.Errorf("Worker.process - run job: %w", err)
|
|
}
|
|
}
|
|
|
|
// finalClass reports a class that ends the job at once: a retry cannot
|
|
// change the outcome.
|
|
func finalClass(class outbound.JobErrorClass) bool {
|
|
switch class {
|
|
case outbound.JobErrorHandlerPanic, outbound.JobErrorHandlerRejected, outbound.JobErrorCompletionConflict:
|
|
return true
|
|
case outbound.JobErrorHandlerFailed, outbound.JobErrorTimeout, outbound.JobErrorConflict,
|
|
outbound.JobErrorEffectRejected, outbound.JobErrorLeaseExpired:
|
|
return false
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// failureClass maps an attempt error to its class. attributable is false
|
|
// for a database failure that the job did not cause.
|
|
func failureClass(err error, handlerFailed, timedOut bool) (outbound.JobErrorClass, bool) {
|
|
switch {
|
|
case errors.Is(err, errHandlerPanic):
|
|
return outbound.JobErrorHandlerPanic, true
|
|
case errors.Is(err, inbound.ErrJobRejected):
|
|
return outbound.JobErrorHandlerRejected, true
|
|
case errors.Is(err, outbound.ErrJobCompletionConflict):
|
|
return outbound.JobErrorCompletionConflict, true
|
|
case timedOut:
|
|
return outbound.JobErrorTimeout, true
|
|
case errors.Is(err, outbound.ErrTransactionConflict):
|
|
return outbound.JobErrorConflict, true
|
|
case errors.Is(err, outbound.ErrJobEffectRejected):
|
|
return outbound.JobErrorEffectRejected, true
|
|
case handlerFailed:
|
|
return outbound.JobErrorHandlerFailed, true
|
|
default:
|
|
return "", false
|
|
}
|
|
}
|
|
|
|
// fail records a failed attempt: the job is retried after Backoff, or dead
|
|
// when the class is final or the attempts ran out.
|
|
func (worker *Worker) fail(
|
|
ctx context.Context,
|
|
job outbound.ClaimedJob,
|
|
class outbound.JobErrorClass,
|
|
cause error,
|
|
logger *slog.Logger,
|
|
) (string, error) {
|
|
final := finalClass(class) || job.Attempt >= job.MaxAttempts
|
|
delay := worker.settings.Backoff.Delay(job.Attempt)
|
|
failure := outbound.JobFailure{Class: class, Dead: final, RetryAt: worker.clock().Add(delay)}
|
|
// The record is written after shutdown began too, so a failure is not
|
|
// lost to a restart.
|
|
recordCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), worker.settings.StoreTimeout)
|
|
defer cancel()
|
|
recorded, err := worker.store.Fail(recordCtx, job, failure)
|
|
if err != nil {
|
|
logger.Warn("scheduled job failed and the failure could not be stored; the job runs again after its lease expires",
|
|
slog.String("error_class", string(class)),
|
|
slog.Any("error", err),
|
|
)
|
|
return "", fmt.Errorf("Worker.fail - record failure: %w", err)
|
|
}
|
|
if !recorded {
|
|
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeLeaseLost)
|
|
logger.Info("scheduled job failed after it was canceled or reclaimed; nothing recorded")
|
|
return OutcomeLeaseLost, nil
|
|
}
|
|
reason := sanitizeReason(cause)
|
|
if final {
|
|
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeDead)
|
|
logger.Error("scheduled job is dead; it needs an operator",
|
|
slog.String("error_class", string(class)),
|
|
slog.String("reason", reason),
|
|
)
|
|
return OutcomeDead, nil
|
|
}
|
|
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeRetry)
|
|
logger.Warn("scheduled job failed; retrying",
|
|
slog.String("error_class", string(class)),
|
|
slog.Duration("retry_in", delay),
|
|
slog.String("reason", reason),
|
|
)
|
|
return OutcomeRetry, nil
|
|
}
|
|
|
|
// releaseOne releases job and returns its outcome: OutcomeReleased,
|
|
// OutcomeLeaseLost when another worker or a cancel took it over meanwhile,
|
|
// or no outcome when the release failed and the job waits for its lease to
|
|
// expire.
|
|
func (worker *Worker) releaseOne(ctx context.Context, job outbound.ClaimedJob) string {
|
|
var result PassResult
|
|
worker.release(ctx, []outbound.ClaimedJob{job}, &result)
|
|
switch {
|
|
case result.Released > 0:
|
|
return OutcomeReleased
|
|
case result.LeaseLost > 0:
|
|
return OutcomeLeaseLost
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
// release gives unfinished jobs back and adds their outcomes to result: a
|
|
// job the guard skipped was taken over by another worker or canceled, so it
|
|
// counts as lost. A failed release is only logged: the leases expire and
|
|
// another claim takes the jobs then.
|
|
func (worker *Worker) release(ctx context.Context, jobs []outbound.ClaimedJob, result *PassResult) {
|
|
held := make([]outbound.ClaimedJob, 0, len(jobs))
|
|
for _, job := range jobs {
|
|
if !job.Exhausted {
|
|
held = append(held, job)
|
|
}
|
|
}
|
|
if len(held) == 0 {
|
|
return
|
|
}
|
|
releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), worker.settings.StoreTimeout)
|
|
defer cancel()
|
|
released, err := worker.store.Release(releaseCtx, held)
|
|
if err != nil {
|
|
worker.logger.Warn("scheduled jobs could not be released; they run again after their leases expire",
|
|
slog.Int("jobs", len(held)),
|
|
slog.Any("error", err),
|
|
)
|
|
return
|
|
}
|
|
for _, job := range held {
|
|
outcome := OutcomeLeaseLost
|
|
if slices.Contains(released, job.ID) {
|
|
outcome = OutcomeReleased
|
|
}
|
|
worker.metrics.ObserveScheduledJob(job.Kind, outcome)
|
|
result.add(outcome)
|
|
}
|
|
worker.logger.Info("scheduled jobs released unfinished",
|
|
slog.Int("jobs", len(held)),
|
|
slog.Int("released", len(released)),
|
|
)
|
|
}
|
|
|
|
// callHandler turns a panic into a final failure, so one job cannot crash
|
|
// the process on every attempt. The stack is logged; the panic value is
|
|
// not, because it could quote the payload.
|
|
func (worker *Worker) callHandler(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
handler inbound.JobHandler,
|
|
job outbound.ClaimedJob,
|
|
logger *slog.Logger,
|
|
) (err error) {
|
|
defer func() {
|
|
if recovered := recover(); recovered != nil {
|
|
logger.Error("scheduled job handler panicked", slog.String("stack", string(debug.Stack())))
|
|
err = errHandlerPanic
|
|
}
|
|
}()
|
|
return handler.Handle(ctx, unit, job)
|
|
}
|
|
|
|
// workContext returns a context for handler attempts that outlives ctx by at
|
|
// most ShutdownGrace. stop releases the watcher goroutine.
|
|
func (worker *Worker) workContext(ctx context.Context) (context.Context, func()) {
|
|
workCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
|
stopWatching := context.AfterFunc(ctx, func() {
|
|
timer := time.NewTimer(worker.settings.ShutdownGrace)
|
|
defer timer.Stop()
|
|
select {
|
|
case <-timer.C:
|
|
cancel()
|
|
case <-workCtx.Done():
|
|
}
|
|
})
|
|
return workCtx, func() {
|
|
stopWatching()
|
|
cancel()
|
|
}
|
|
}
|
|
|
|
// backlogRefresher reads the job backlog for the metrics at most once per
|
|
// BacklogInterval of real time; the due comparison uses the worker clock.
|
|
type backlogRefresher struct {
|
|
worker *Worker
|
|
last time.Time
|
|
}
|
|
|
|
func (refresher *backlogRefresher) refresh(ctx context.Context) {
|
|
settings := refresher.worker.settings
|
|
if !refresher.last.IsZero() && time.Since(refresher.last) < settings.BacklogInterval {
|
|
return
|
|
}
|
|
refresher.last = time.Now()
|
|
readCtx, cancel := context.WithTimeout(ctx, settings.StoreTimeout)
|
|
defer cancel()
|
|
backlog, err := refresher.worker.store.Backlog(readCtx, refresher.worker.clock())
|
|
if err != nil {
|
|
// A read interrupted by shutdown is not worth a warning.
|
|
if ctx.Err() == nil {
|
|
refresher.worker.logger.Warn("scheduled job worker could not read the backlog; its metrics are stale", slog.Any("error", err))
|
|
}
|
|
return
|
|
}
|
|
refresher.worker.metrics.ObserveScheduledJobBacklog(backlog)
|
|
}
|
|
|
|
// jobAttributes identifies a job in logs without its key or payload.
|
|
func jobAttributes(job outbound.ClaimedJob) []any {
|
|
return []any{
|
|
slog.Int64("job_id", job.ID),
|
|
slog.String("kind", job.Kind),
|
|
slog.Int("attempt", job.Attempt),
|
|
slog.Int("max_attempts", job.MaxAttempts),
|
|
}
|
|
}
|
|
|
|
// sanitizeReason keeps a short single-line cause. Handler errors must not
|
|
// carry personal data already; this also bounds what a mistake can expose.
|
|
func sanitizeReason(err error) string {
|
|
reason := strings.Map(func(character rune) rune {
|
|
if unicode.IsControl(character) || !unicode.IsPrint(character) {
|
|
return ' '
|
|
}
|
|
return character
|
|
}, err.Error())
|
|
reason = strings.TrimSpace(reason)
|
|
if runes := []rune(reason); len(runes) > maxReasonLength {
|
|
reason = string(runes[:maxReasonLength])
|
|
}
|
|
if reason == "" {
|
|
return "unspecified failure"
|
|
}
|
|
return reason
|
|
}
|