tasks

package
v1.36.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 8 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	QueueActionPause         = "pause"
	QueueActionUnpause       = "unpause"
	QueueActionRetry         = "retry"
	QueueActionArchiveRetry  = "archive-retry"
	QueueActionRetryArchived = "retry-archived"
	QueueActionPurgeArchived = "purge-archived"
)

Variables

View Source
var (
	ErrNilHandler       = fmt.Errorf("tasks: handler is nil")
	ErrNilManager       = fmt.Errorf("tasks: manager is nil")
	ErrRedisURLRequired = fmt.Errorf("tasks: redis_url is required")
	ErrTaskTypeRequired = fmt.Errorf("tasks: task type is required")
)

Functions

func DecodeJSONPayload

func DecodeJSONPayload(task Task, dst any) error

DecodeJSONPayload unmarshals a generic JSON task payload into dst.

func MustRegisterProvider added in v1.34.0

func MustRegisterProvider(name string, p Provider)

MustRegisterProvider is RegisterProvider for use in an init(), where there is no caller to hand an error back to.

func NormalizeQueueAction

func NormalizeQueueAction(raw string) (string, bool)

func RegisterProvider added in v1.34.0

func RegisterProvider(name string, p Provider) error

RegisterProvider records the Provider selected by `jobs_provider: name`.

It returns an error rather than panicking on a duplicate so that a package linked twice through different paths fails loudly at init in the provider's own code, where the import that caused it is visible.

func RegisteredProviders added in v1.34.0

func RegisteredProviders() []string

RegisteredProviders returns the names registered through RegisterProvider, sorted. It is what an error message uses to tell an operator what IS linked in; the built-in memory and sql providers are not listed because they are always there.

func SupportedQueueActions

func SupportedQueueActions() []string

Types

type Config

type Config struct {
	RedisURL       string         // Used if Provider needs Redis (e.g. Asynq)
	Concurrency    int            // Number of concurrent workers
	Queues         map[string]int // Queue names and their priority weights
	StrictPriority bool           // If true, strict priority ordering is enforced
}

Config configures task enqueueing and worker runtime.

type EnqueuePolicy

type EnqueuePolicy struct {
	Queue     string
	MaxRetry  int
	Timeout   time.Duration
	ProcessIn time.Duration
	Retention time.Duration

	// BackoffBase and BackoffMax describe the wait between attempts: the
	// first retry waits BackoffBase, each one after that doubles, and none
	// waits longer than BackoffMax. Zero means "the provider's own curve",
	// which is what every job used to get whether it suited the work or not —
	// a webhook that should back off for minutes and a thumbnail that should
	// be retried in a second took the same one.
	//
	// A provider that cannot express a curve per job ignores these, and says
	// so in its documentation rather than pretending:
	// the memory provider keeps its fixed curve, and asynq applies its
	// server-wide RetryDelayFunc.
	BackoffBase time.Duration
	BackoffMax  time.Duration

	// UniqueKey collapses jobs that mean the same thing. While a job with
	// this key is waiting or running, enqueueing another with the same key
	// returns the id of the one already there instead of adding a second —
	// so a double-clicked button, a webhook delivered twice or a retry loop
	// upstream does not become duplicated work.
	//
	// The key is the application's to choose, and it is scoped to the queue:
	// "invoice:42" or "sync:tenant-7". It stops being reserved when the job
	// finishes, so the same key can be enqueued again afterwards.
	//
	// A provider that cannot express uniqueness ignores it and says so in its
	// documentation rather than pretending: only the SQL provider honours it
	// today.
	UniqueKey string
}

EnqueuePolicy describes the supported explicit enqueue-policy subset. MaxRetry uses -1 to keep provider defaults; 0 disables retries.

func DefaultEnqueuePolicy

func DefaultEnqueuePolicy() EnqueuePolicy

type EnqueueRecord added in v1.31.0

type EnqueueRecord struct {
	ID         string
	Type       string
	Payload    []byte
	Queue      string
	EnqueuedAt time.Time
}

Inspector defines an interface for queue introspection and operations. EnqueueRecord is one enqueue as a provider saw it: what a test asserts on when it wants to know that a handler enqueued the right task, without caring whether a worker has run it yet.

type EnqueueRecorder added in v1.31.0

type EnqueueRecorder interface {
	Enqueued() []EnqueueRecord
	ResetEnqueued()
}

EnqueueRecorder is the optional interface a Manager implements when it keeps a record of every enqueue. The in-process provider does; a test kit asks for it with a type assertion, the way TaskInspectorSource is asked.

type HandlerFunc

type HandlerFunc func(ctx context.Context, task Task) error

HandlerFunc is a function that processes a Task.

type Inspector

type Inspector interface {
	InspectRuntime() RuntimeSnapshot
	OperateQueue(queue, action string) (QueueActionResult, error)
}

type Manager

type Manager interface {
	// Worker methods
	HandleFunc(taskType string, handler HandlerFunc) error
	Run(ctx context.Context) error
	Close() error

	// Client methods
	EnqueueJSON(taskType string, payload any) (string, error)
	EnqueueJSONCtx(ctx context.Context, taskType string, payload any) (string, error)
	EnqueueJSONWithPolicy(taskType string, payload any, policy EnqueuePolicy) (string, error)
	EnqueueJSONCtxWithPolicy(ctx context.Context, taskType string, payload any, policy EnqueuePolicy) (string, error)
}

Manager is the unified interface for a Task Queue Provider.

type Provider added in v1.34.0

type Provider interface {
	// Open builds the manager, scheduler and inspector the framework drives
	// for one application. The provider owns the choices its configuration
	// expresses — SchedulerLock, for one — and logs them through
	// opts.Logger, so the boot log says what the provider is doing.
	Open(opts ProviderOptions) (ProviderRuntime, error)

	// Inspect reports the state of the deployment the options name, without
	// starting a worker. It never panics: a backend that cannot be reached
	// is a snapshot with Enabled false and the Reason filled in.
	Inspect(opts ProviderOptions) RuntimeSnapshot
}

Provider is the contract a jobs provider implements to be selected with `jobs_provider`. The memory and sql providers are part of the framework and need no registration; every other provider registers itself by name from its init(), the way a storage backend registers with pkg/storage — and the framework then resolves `jobs_provider: <name>` through LookupProvider. An application that names a provider nothing registered fails at boot with the names that ARE registered.

Today the asynq provider is registered by the in-tree package pkg/tasks/providers/asynq, which the framework links, so `jobs_provider: asynq` keeps working with no import on the application's side. At v2.0.0 the provider moves to its own module, providers/tasks-asynq, and this registry is what makes that move a packaging change rather than a behaviour change (DEP-2026-020): the module registers under the same name, and a blank import of it is the whole wiring.

A Provider is consulted by two callers: the module-jobs runtime, which opens it once per application, and `nucleus doctor --check tasks`, which inspects a deployment without opening a worker.

func LookupProvider added in v1.34.0

func LookupProvider(name string) (Provider, bool)

LookupProvider returns the Provider registered under name.

type ProviderOptions added in v1.34.0

type ProviderOptions struct {
	// Config carries the broker URL (`jobs_redis_url`), the worker
	// concurrency (`jobs_concurrency`) and the queue weights.
	Config Config
	// SchedulerLock is `jobs_scheduler_lock`: whether the scheduler runs
	// under leader election, so that with several replicas exactly one
	// ticks the cron entries. A provider that cannot elect a leader
	// ignores it and says so in its documentation.
	SchedulerLock bool
	// Logger is the application's logger; nil means slog.Default().
	Logger *slog.Logger
}

ProviderOptions is what the framework hands a Provider: the task configuration derived from the `jobs_*` keys, and the logger the application runs on.

type ProviderRuntime added in v1.34.0

type ProviderRuntime struct {
	Manager   Manager
	Scheduler Scheduler
	Inspector Inspector
}

ProviderRuntime is what a Provider builds: the three handles the module-jobs runtime drives. Manager and Scheduler are required; Inspector may be nil for a provider with nothing to inspect.

type QueueActionResult

type QueueActionResult struct {
	Enabled     bool   `json:"enabled"`
	GeneratedAt string `json:"generated_at"`
	Queue       string `json:"queue"`
	Action      string `json:"action"`
	Applied     bool   `json:"applied"`
	Affected    int    `json:"affected,omitempty"`
	Message     string `json:"message,omitempty"`
}

QueueActionResult is the result of one operational queue action.

type RuntimeQueueSnapshot

type RuntimeQueueSnapshot struct {
	Name           string `json:"name"`
	Paused         bool   `json:"paused"`
	LatencyMS      int64  `json:"latency_ms"`
	Size           int    `json:"size"`
	Pending        int    `json:"pending"`
	Active         int    `json:"active"`
	Scheduled      int    `json:"scheduled"`
	Retry          int    `json:"retry"`
	Archived       int    `json:"archived"`
	Completed      int    `json:"completed"`
	Aggregating    int    `json:"aggregating"`
	ProcessedToday int    `json:"processed_today"`
	FailedToday    int    `json:"failed_today"`
	ProcessedAll   int    `json:"processed_all"`
	FailedAll      int    `json:"failed_all"`
}

RuntimeQueueSnapshot holds one queue aggregate.

type RuntimeScheduleSnapshot

type RuntimeScheduleSnapshot struct {
	ID            string `json:"id"`
	Spec          string `json:"spec"`
	TaskType      string `json:"task_type"`
	NextEnqueueAt string `json:"next_enqueue_at,omitempty"`
	PrevEnqueueAt string `json:"prev_enqueue_at,omitempty"`
}

RuntimeScheduleSnapshot holds one registered periodic task entry.

type RuntimeServerSnapshot

type RuntimeServerSnapshot struct {
	ID             string         `json:"id"`
	Host           string         `json:"host"`
	PID            int            `json:"pid"`
	Status         string         `json:"status"`
	StartedAt      string         `json:"started_at,omitempty"`
	Concurrency    int            `json:"concurrency"`
	StrictPriority bool           `json:"strict_priority"`
	Queues         map[string]int `json:"queues"`
	ActiveWorkers  int            `json:"active_workers"`
}

RuntimeServerSnapshot holds one server aggregate.

type RuntimeSnapshot

type RuntimeSnapshot struct {
	Enabled           bool                      `json:"enabled"`
	GeneratedAt       string                    `json:"generated_at"`
	Reason            string                    `json:"reason,omitempty"`
	Queues            []RuntimeQueueSnapshot    `json:"queues"`
	Schedules         []RuntimeScheduleSnapshot `json:"schedules"`
	Servers           []RuntimeServerSnapshot   `json:"servers"`
	Workers           []RuntimeWorkerSnapshot   `json:"workers"`
	TotalSchedules    int                       `json:"total_schedules"`
	TotalQueues       int                       `json:"total_queues"`
	TotalServers      int                       `json:"total_servers"`
	TotalWorkers      int                       `json:"total_workers"`
	TotalSize         int                       `json:"total_size"`
	TotalPending      int                       `json:"total_pending"`
	TotalActive       int                       `json:"total_active"`
	TotalScheduled    int                       `json:"total_scheduled"`
	TotalRetry        int                       `json:"total_retry"`
	TotalArchived     int                       `json:"total_archived"`
	TotalCompleted    int                       `json:"total_completed"`
	TotalAggregating  int                       `json:"total_aggregating"`
	TotalProcessed    int                       `json:"total_processed_today"`
	TotalFailed       int                       `json:"total_failed_today"`
	TotalProcessedAll int                       `json:"total_processed_all"`
	TotalFailedAll    int                       `json:"total_failed_all"`
}

RuntimeSnapshot describes queue/worker state discoverable from the provider runtime.

type RuntimeWorkerSnapshot

type RuntimeWorkerSnapshot struct {
	ServerID  string `json:"server_id"`
	Host      string `json:"host"`
	PID       int    `json:"pid"`
	Queue     string `json:"queue"`
	TaskID    string `json:"task_id"`
	TaskType  string `json:"task_type"`
	StartedAt string `json:"started_at,omitempty"`
	Deadline  string `json:"deadline,omitempty"`
}

RuntimeWorkerSnapshot describes one active worker task.

type Scheduler

type Scheduler interface {
	RegisterJSON(spec, taskType string, payload any, policy EnqueuePolicy) (string, error)
	Unregister(entryID string) error
	Start() error
	Close() error
}

Scheduler provides an interface for periodic background tasks.

type Task

type Task interface {
	Type() string
	Payload() []byte
}

Task represents a generic unit of work.

Directories

Path Synopsis
providers
asynq
Package tasks provides background job enqueueing and worker runtime backed by Asynq.
Package tasks provides background job enqueueing and worker runtime backed by Asynq.
sql
Package sqlprovider is a durable job queue on the database the application already has — no broker, no Redis.
Package sqlprovider is a durable job queue on the database the application already has — no broker, no Redis.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL