queue

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 16 Imported by: ? modules, 0 packages

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

Overview

Package queue runs GoHead's background jobs (collection events, agent runs, webhook deliveries) behind one interface, with two drivers:

  • redis: asynq on Redis, for deployments with several processes or replicas (the default);
  • database: a jobs table in GoHead's own database, polled by in-process workers. No extra service: suited to a single process (gohead standalone) or a few, on small machines.

Index

Constants

View Source
const (
	StatusPending = "pending"
	StatusRunning = "running"
	StatusDone    = "done"
	StatusFailed  = "failed"
)

Job statuses of the database driver.

View Source
const (
	DriverRedis    = "redis"
	DriverDatabase = "database"
)

Driver names.

View Source
const (
	DefaultMaxRetry = 25
	DefaultTimeout  = 30 * time.Minute
)

Defaults shared by the drivers (asynq's).

Variables

View Source
var ErrDuplicateTask = errors.New("a task with this ID already exists")

ErrDuplicateTask is returned when a task with the same TaskID is queued, running, or kept for its retention period.

View Source
var FailedRetention = 7 * 24 * time.Hour

FailedRetention is how long the database driver keeps tasks that failed for good (asynq's archive keeps them 90 days; a small machine keeps less).

View Source
var SkipRetry = errors.New("skip retry")

SkipRetry, wrapped in a handler's error, fails the task without retrying.

Functions

func Backoff

func Backoff(n int) time.Duration

Backoff is the delay before retry n (1-based), asynq's default: n⁴ + 15 + rand(0..30)·(n+1) seconds.

func Counts

func Counts(ctx context.Context, db *gorm.DB) (map[string]int64, error)

Counts returns the number of tasks by status (for health and tests).

func GetRetryCount

func GetRetryCount(ctx context.Context) (int, bool)

GetRetryCount returns how many times the task was retried (0 on the first attempt).

func GetTaskID

func GetTaskID(ctx context.Context) (string, bool)

GetTaskID returns the ID of the task being processed.

func WithTaskInfo

func WithTaskInfo(ctx context.Context, id string, retry int) context.Context

WithTaskInfo is used by drivers to pass a task's ID and retry count to its handler.

Types

type Client

type Client interface {
	// Enqueue queues a task and returns its ID.
	Enqueue(ctx context.Context, taskType string, payload []byte, opts ...Option) (string, error)
	Close() error
}

Client enqueues tasks.

type DatabaseClient

type DatabaseClient struct {
	// contains filtered or unexported fields
}

DatabaseClient queues tasks in the jobs table.

func NewDatabaseClient

func NewDatabaseClient(db *gorm.DB) *DatabaseClient

NewDatabaseClient returns a client of the jobs table of db.

func (*DatabaseClient) Close

func (c *DatabaseClient) Close() error

Close implements Client.

func (*DatabaseClient) Enqueue

func (c *DatabaseClient) Enqueue(ctx context.Context, taskType string, payload []byte, opts ...Option) (string, error)

Enqueue implements Client.

type DatabaseServer

type DatabaseServer struct {
	// contains filtered or unexported fields
}

DatabaseServer processes tasks of the jobs table.

func NewDatabaseServer

func NewDatabaseServer(db *gorm.DB, cfg DatabaseServerConfig) *DatabaseServer

NewDatabaseServer returns a server of the jobs table of db.

func (*DatabaseServer) Run

func (s *DatabaseServer) Run(ctx context.Context, mux *Mux) error

Run implements Server.

type DatabaseServerConfig

type DatabaseServerConfig struct {
	ServerConfig
	// PollInterval is how often other processes' tasks and retries are
	// looked for (tasks queued by this process start at once). Default 1s.
	PollInterval time.Duration
	// ShutdownTimeout is how long running tasks may finish on shutdown
	// before they are cancelled and queued again. Default 8s.
	ShutdownTimeout time.Duration
}

DatabaseServerConfig tunes the database driver.

type HandlerFunc

type HandlerFunc func(ctx context.Context, payload []byte) error

HandlerFunc processes a task. Returning an error retries it later (with backoff) unless it wraps SkipRetry or the retries are exhausted.

type Job

type Job struct {
	ID             uint64  `gorm:"primaryKey"`
	TaskID         *string `gorm:"size:191;uniqueIndex"`
	Queue          string  `gorm:"size:64;not null;index:idx_jobs_claim,priority:2"`
	Type           string  `gorm:"size:128;not null"`
	Payload        []byte
	Status         string     `gorm:"size:16;not null;index:idx_jobs_claim,priority:1"`
	RunAt          time.Time  `gorm:"not null;index:idx_jobs_claim,priority:3"`
	Retried        int        `gorm:"not null;default:0"`
	MaxRetry       int        `gorm:"not null;default:0"`
	TimeoutMS      int64      `gorm:"column:timeout_ms;not null;default:0"`
	RetentionMS    int64      `gorm:"column:retention_ms;not null;default:0"`
	LockedBy       string     `gorm:"size:64"`
	LockedUntil    *time.Time `gorm:"index"`
	RetentionUntil *time.Time `gorm:"index"`
	LastError      string     `gorm:"type:text"`
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

Job is a task of the database driver (table jobs).

func (Job) TableName

func (Job) TableName() string

TableName implements gorm's Tabler.

type Mux

type Mux struct {
	// contains filtered or unexported fields
}

Mux maps task types to handlers.

func NewMux

func NewMux() *Mux

NewMux returns an empty Mux.

func (*Mux) Handle

func (m *Mux) Handle(taskType string, h HandlerFunc)

Handle registers the handler of a task type.

func (*Mux) Handler

func (m *Mux) Handler(taskType string) (HandlerFunc, bool)

Handler returns the handler of a task type.

func (*Mux) Types

func (m *Mux) Types() []string

Types lists the registered task types.

type Option

type Option func(*Options)

Option sets an Option.

func MaxRetry

func MaxRetry(n int) Option

func Queue

func Queue(name string) Option

func Retention

func Retention(d time.Duration) Option

func TaskID

func TaskID(id string) Option

func Timeout

func Timeout(d time.Duration) Option

type Options

type Options struct {
	Queue     string
	TaskID    string        // deduplication key; empty: none
	MaxRetry  int           // retries after the first attempt; <0: DefaultMaxRetry
	Timeout   time.Duration // per attempt; 0: DefaultTimeout
	Retention time.Duration // keep the finished task (and its ID) this long
}

Options of an enqueued task.

func Apply

func Apply(opts []Option) Options

Apply returns the options with defaults.

type RedisClient

type RedisClient struct {
	// contains filtered or unexported fields
}

RedisClient enqueues tasks on Redis with asynq.

func NewRedisClient

func NewRedisClient(opt asynq.RedisConnOpt) *RedisClient

NewRedisClient returns a client of the Redis described by opt.

func (*RedisClient) Close

func (r *RedisClient) Close() error

Close implements Client.

func (*RedisClient) Enqueue

func (r *RedisClient) Enqueue(ctx context.Context, taskType string, payload []byte, opts ...Option) (string, error)

Enqueue implements Client.

type RedisServer

type RedisServer struct {
	// contains filtered or unexported fields
}

RedisServer processes tasks from Redis with asynq.

func NewRedisServer

func NewRedisServer(opt asynq.RedisConnOpt, cfg ServerConfig) *RedisServer

NewRedisServer returns a server of the Redis described by opt.

func (*RedisServer) Run

func (r *RedisServer) Run(ctx context.Context, mux *Mux) error

Run implements Server.

type Server

type Server interface {
	Run(ctx context.Context, mux *Mux) error
}

Server processes tasks until its context ends.

type ServerConfig

type ServerConfig struct {
	// Concurrency is the number of tasks processed at once.
	Concurrency int
	// Queues to process, with their priority: queues are looked at in a
	// random order weighted by priority, so busy queues do not starve the
	// others.
	Queues map[string]int
	// StrictPriority always empties higher priority queues first.
	StrictPriority bool
}

ServerConfig configures a Server.

Jump to

Keyboard shortcuts

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