Documentation
¶
Overview ¶
Package taskmill is a PostgreSQL-backed task queue for Go.
Tasks are rows in PostgreSQL. An enqueue commits or rolls back with the application's own writes, and a worker that crashes never loses a task. Every task runs at least once: handlers must be idempotent, so that running a task twice has the same effect as running it once.
The guide at https://github.com/code19m/taskmill/blob/main/docs/guide.md covers every feature, testing, and running in production.
Defining tasks ¶
A task is a struct that implements Args: its Kind names the handler that runs it, and its fields are stored as JSON. Implement ArgsWithDefaults to give a kind default EnqueueOptions, such as its queue.
Enqueueing ¶
Client.Enqueue enqueues a task in its own transaction, and Client.EnqueueTx in the caller's, through a Pgx or SQL executor, so that the task exists only if the caller's transaction commits. Options delay a task, prioritize it, deduplicate it with a key, or put it in a FIFO group, whose tasks run one at a time, in order.
Handling tasks ¶
Register a Handler or a BatchHandler for each kind with AddHandler or AddBatchHandler, and run them with a Worker. Returning nil completes a task. An error retries it with backoff, 25 attempts by default, after which it is dead: kept for an operator to inspect and Client.Retry. Permanent makes it dead at once, and Snooze runs it again later without using an attempt. Task.CompleteTx completes a task in the handler's own transaction, so its effects apply exactly once.
Operating ¶
The Client lists, cancels, retries, and deletes tasks, pauses queues, and limits how many of a queue's tasks run at once. Package github.com/code19m/taskmill/ui serves the same operations as a web interface, and package github.com/code19m/taskmill/outbox publishes messages to a broker with the transactional outbox pattern.
Testing ¶
Package github.com/code19m/taskmill/taskmilltest runs tests against a real database, each in a schema of its own: it checks what code enqueues, and runs handlers the way a worker does.
Example ¶
This example enqueues a task in the same transaction as the business data it belongs to, and runs a worker until the process is told to stop.
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/code19m/taskmill"
)
// SendReceipt is the payload of an example task.
type SendReceipt struct {
OrderID int64 `json:"order_id"`
Email string `json:"email"`
}
// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }
func deliverReceipt(context.Context, string, int64) error { return nil }
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
if err := taskmill.Migrate(ctx, pool, nil); err != nil {
log.Fatal(err)
}
client, err := taskmill.NewClient(ctx, pool, nil)
if err != nil {
log.Fatal(err)
}
err = pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
// ... insert the order in tx ...
_, err := client.EnqueueTx(ctx, taskmill.Pgx(tx), SendReceipt{OrderID: 42, Email: "a@example.com"}, nil)
return err
})
if err != nil {
log.Fatal(err)
}
var handlers taskmill.Handlers
taskmill.AddHandler(&handlers, taskmill.HandlerFunc[SendReceipt](
func(ctx context.Context, t *taskmill.Task[SendReceipt]) error {
return deliverReceipt(ctx, t.Args.Email, t.Args.OrderID)
},
), nil)
// The worker serves the queues of its handlers' kinds: here the default
// queue.
worker, err := taskmill.NewWorker(client, &taskmill.WorkerConfig{Handlers: &handlers})
if err != nil {
log.Fatal(err)
}
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
if err := worker.Run(ctx); err != nil {
log.Print(err)
}
}
Output:
Index ¶
- Constants
- Variables
- func AddBatchHandler[A Args](hs *Handlers, h BatchHandler[A], opts *HandlerOptions)
- func AddHandler[A Args](hs *Handlers, h Handler[A], opts *HandlerOptions)
- func Migrate(ctx context.Context, pool *pgxpool.Pool, cfg *MigrateConfig) error
- func Permanent(err error) error
- func Snooze(d time.Duration) error
- type Activity
- type ActivityParams
- type Args
- type ArgsWithDefaults
- type AttemptError
- type BatchHandler
- type Client
- func (c *Client) Activity(ctx context.Context, params *ActivityParams) ([]Activity, error)
- func (c *Client) Cancel(ctx context.Context, id int64) error
- func (c *Client) CancelTx(ctx context.Context, tx Executor, id int64) error
- func (c *Client) Delete(ctx context.Context, id int64) error
- func (c *Client) Enqueue(ctx context.Context, args Args, opts *EnqueueOptions) (EnqueueResult, error)
- func (c *Client) EnqueueMany(ctx context.Context, params []EnqueueParams) ([]EnqueueResult, error)
- func (c *Client) EnqueueManyTx(ctx context.Context, tx Executor, params []EnqueueParams) ([]EnqueueResult, error)
- func (c *Client) EnqueueTx(ctx context.Context, tx Executor, args Args, opts *EnqueueOptions) (EnqueueResult, error)
- func (c *Client) Get(ctx context.Context, id int64) (*TaskInfo, error)
- func (c *Client) Groups(ctx context.Context, params *GroupParams) ([]GroupInfo, error)
- func (c *Client) List(ctx context.Context, params *ListParams) (*ListResult, error)
- func (c *Client) PauseQueue(ctx context.Context, name string) error
- func (c *Client) PauseSchedule(ctx context.Context, name string) error
- func (c *Client) Queues(ctx context.Context) ([]QueueInfo, error)
- func (c *Client) ResumeQueue(ctx context.Context, name string) error
- func (c *Client) ResumeSchedule(ctx context.Context, name string) error
- func (c *Client) Retry(ctx context.Context, id int64) error
- func (c *Client) RunSchedule(ctx context.Context, name string) error
- func (c *Client) Schedules(ctx context.Context) ([]ScheduleInfo, error)
- func (c *Client) Settings(ctx context.Context) (*Settings, error)
- func (c *Client) UpdateQueue(ctx context.Context, name string, settings *QueueSettings) error
- func (c *Client) UpdateSettings(ctx context.Context, settings *Settings) error
- func (c *Client) Workers(ctx context.Context) ([]WorkerInfo, error)
- type ClientConfig
- type EnqueueOptions
- type EnqueueParams
- type EnqueueResult
- type ErrorCode
- type Executor
- type ExponentialBackoff
- type GroupInfo
- type GroupParams
- type Handler
- type HandlerFunc
- type HandlerOptions
- type Handlers
- type ListParams
- type ListResult
- type Middleware
- type MigrateConfig
- type Migration
- type PermanentError
- type PgxQuerier
- type Priority
- type QueueInfo
- type QueueOptions
- type QueueSettings
- type RetryPolicy
- type SQLQuerier
- type Schedule
- type ScheduleInfo
- type Settings
- type SnoozeError
- type State
- type Task
- type TaskInfo
- type Worker
- type WorkerConfig
- type WorkerInfo
Examples ¶
Constants ¶
const DefaultQueue = "default"
DefaultQueue is the queue that tasks go to when neither the enqueue call nor the kind's defaults name one.
Variables ¶
var ( // ErrNotFound means the task or schedule does not exist, or no longer // exists. ErrNotFound = errors.New("taskmill: not found") // ErrLeaseLost means the attempt no longer owns its task: its lease // expired and the task was rescued, canceled, or fetched again. ErrLeaseLost = errors.New("taskmill: lease lost") // ErrInvalidState means the operation does not apply to the task's // current state, such as retrying a running task. ErrInvalidState = errors.New("taskmill: invalid state") // ErrInvalidArgument means an argument or option is invalid: out of // range, too long, or holding a NUL character. ErrInvalidArgument = errors.New("taskmill: invalid argument") // ErrSchemaOutdated means the database schema is missing or older than // this version of taskmill. Run [Migrate]. ErrSchemaOutdated = errors.New("taskmill: database schema is missing or outdated") )
Errors returned by taskmill. Test for them with errors.Is.
Functions ¶
func AddBatchHandler ¶
func AddBatchHandler[A Args](hs *Handlers, h BatchHandler[A], opts *HandlerOptions)
AddBatchHandler registers h for the kind of A. opts may be nil. Mistakes, such as registering a kind twice, are reported by NewWorker.
Example ¶
This example runs receipts in batches of up to 50.
package main
import (
"context"
"github.com/code19m/taskmill"
)
// SendReceipt is the payload of an example task.
type SendReceipt struct {
OrderID int64 `json:"order_id"`
Email string `json:"email"`
}
// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }
func deliverReceipt(context.Context, string, int64) error { return nil }
// receiptMailer sends receipts in bulk.
type receiptMailer struct{}
func (receiptMailer) HandleBatch(ctx context.Context, tasks []*taskmill.Task[SendReceipt]) []error {
errs := make([]error, len(tasks))
for i, t := range tasks {
errs[i] = deliverReceipt(ctx, t.Args.Email, t.Args.OrderID)
}
return errs
}
func main() {
var handlers taskmill.Handlers
taskmill.AddBatchHandler[SendReceipt](&handlers, receiptMailer{}, &taskmill.HandlerOptions{BatchSize: 50})
_ = taskmill.WorkerConfig{Handlers: &handlers} // serves the kind's default queue
}
Output:
func AddHandler ¶
func AddHandler[A Args](hs *Handlers, h Handler[A], opts *HandlerOptions)
AddHandler registers h for the kind of A. opts may be nil. Mistakes, such as registering a kind twice, are reported by NewWorker.
func Migrate ¶
Migrate creates or upgrades taskmill's schema, and prepares the next week's history partitions. It is safe to run from several processes at once: one applies the migrations while the others wait. A schema that is up to date is left as it is, so Migrate then needs no privilege to change it, and a failure to prepare partitions is only logged. cfg may be nil.
func Permanent ¶
Permanent wraps err so that the task becomes dead without retrying, for example when its payload fails validation. Permanent(nil) returns nil.
func Snooze ¶
Snooze returns an error that reschedules the task to run after d, without using an attempt. Use it when the task cannot proceed yet, for example while waiting for a rate limit to reset. A delay of zero or less makes the task available at once. A task that always snoozes never becomes dead.
Types ¶
type Activity ¶
type Activity struct {
// At is when the step starts.
At time.Time
// Counts holds the most tasks counted in each state during the step,
// except completed: the maintainer counts them every 10 seconds, with the
// caps of [QueueInfo.Counts]. It is nil if no maintainer counted them, for
// example while no worker ran.
Counts map[State]int64
// Completed and Failed are the attempts that succeeded and failed during
// the step. Failed counts every failed attempt, whether its task is
// retried or dead, including attempts whose workers lost their leases.
// Workers write their counts every 10 seconds; a worker that crashes
// loses its last few seconds of them.
Completed, Failed int64
}
Activity is what happened during one step of time.
type ActivityParams ¶
type ActivityParams struct {
// Queues limits the activity to these queues. Empty means all queues.
Queues []string
// Since is when the period starts. Default: an hour ago. Activity is
// kept for 24 hours.
Since time.Time
// Step is how much time each point covers, in whole minutes. Default: a
// minute. Maximum: a day.
Step time.Duration
}
ActivityParams selects the activity that Client.Activity returns.
type Args ¶
type Args interface {
// Kind returns the task kind, such as "email.send". It must not depend
// on the value's fields: handler registration reads it from a zero value.
Kind() string
}
Args is the payload of a task. Its kind selects the handler that runs it, and it is stored as JSON with encoding/json, at most 1 MiB.
Implement Kind on a value receiver and return a constant: producers and consumers agree on the kind. If a kind is renamed, tasks enqueued under the old name find no handler, and become dead after an hour.
type ArgsWithDefaults ¶
type ArgsWithDefaults interface {
Args
// EnqueueDefaults returns the default options for this kind.
EnqueueDefaults() EnqueueOptions
}
ArgsWithDefaults is implemented by Args that set default enqueue options for their kind. Options passed to an enqueue call override these defaults field by field. A worker reads the default queue from a zero value, to serve it when WorkerConfig.Queues is empty.
type AttemptError ¶
type AttemptError struct {
Attempt int `json:"attempt"`
At time.Time `json:"at"`
// Message is the error's text, truncated to 4 KiB.
Message string `json:"message"`
// Code classifies the entries that taskmill itself recorded. It is empty
// for an error returned by a handler.
Code ErrorCode `json:"code,omitempty"`
}
AttemptError is one entry of a task's error history: why an attempt failed, or a note that taskmill recorded.
type BatchHandler ¶
BatchHandler runs tasks of one kind in batches, for work that is cheaper in bulk, such as publishing messages to a broker. It returns one error per task, in the same order: nil completes that task, and an error fails it as a Handler's error would. Returning a shorter slice fails the tasks without an entry.
A batch takes one slot of its queue's concurrency. When a worker fetches a task of a batch kind, it fills that task's batch with more available tasks of the kind, so a batch kind can share a queue with other kinds.
ctx is canceled when the batch times out or the worker shuts down, but not when one of its tasks is canceled or loses its lease: the batch runs to the end, and then that task becomes canceled, or its result is discarded.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client enqueues and manages tasks. It is safe for concurrent use, and an application typically creates one per installation and shares it.
func NewClient ¶
NewClient returns a client that uses pool for its own statements. cfg may be nil. It fails with ErrSchemaOutdated if the schema was not migrated.
taskmill's statements rely on the READ COMMITTED isolation level, so NewClient fails if the pool's default_transaction_isolation is another level; set it in the pool's ConnConfig.RuntimeParams. Transactions that callers pass to the Tx methods may use any level.
func (*Client) Activity ¶
Activity returns the activity of the selected queues, one point per step, oldest first. A step in which nothing was recorded has no point, so a gap between points means that no worker ran. The query is canceled after 5 seconds, like Client.List.
func (*Client) Cancel ¶
Cancel cancels a task. A waiting task is canceled at once; a running task's context is canceled, and the task becomes canceled when its attempt ends, unless the handler completed it. A task of a batch is canceled when its batch ends. Cancel frees the task's dedupe key. It returns ErrInvalidState if the task already finished.
func (*Client) CancelTx ¶
CancelTx is Client.Cancel in the caller's transaction.
func (*Client) Delete ¶
Delete deletes a task that is not running, including a completed task in history, and frees its dedupe key. Deleting the dead task that halts its FIFO group resumes the group. It returns ErrInvalidState for a running task; cancel it first.
func (*Client) Enqueue ¶
func (c *Client) Enqueue(ctx context.Context, args Args, opts *EnqueueOptions) (EnqueueResult, error)
Enqueue enqueues one task in its own transaction. opts may be nil.
Example (Deduplicated) ¶
This example deduplicates an enqueue: enqueueing the same key again within the window reports the existing task instead of creating another.
package main
import (
"context"
"log"
"time"
"github.com/code19m/taskmill"
)
// SendReceipt is the payload of an example task.
type SendReceipt struct {
OrderID int64 `json:"order_id"`
Email string `json:"email"`
}
// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }
func main() {
ctx := context.Background()
var client *taskmill.Client // from taskmill.NewClient
res, err := client.Enqueue(ctx, SendReceipt{OrderID: 7}, &taskmill.EnqueueOptions{
DedupeKey: "receipt-7",
DedupeWindow: 24 * time.Hour,
})
if err != nil {
log.Fatal(err)
}
if res.Duplicate {
log.Printf("already enqueued as task %d", res.ID)
}
}
Output:
func (*Client) EnqueueMany ¶
func (c *Client) EnqueueMany(ctx context.Context, params []EnqueueParams) ([]EnqueueResult, error)
EnqueueMany enqueues several tasks in one round trip and one transaction. Results are in the same order as params.
func (*Client) EnqueueManyTx ¶
func (c *Client) EnqueueManyTx(ctx context.Context, tx Executor, params []EnqueueParams) ([]EnqueueResult, error)
EnqueueManyTx is Client.EnqueueMany in the caller's transaction.
func (*Client) EnqueueTx ¶
func (c *Client) EnqueueTx(ctx context.Context, tx Executor, args Args, opts *EnqueueOptions) (EnqueueResult, error)
EnqueueTx enqueues one task in the caller's transaction: the task exists only if that transaction commits. opts may be nil.
func (*Client) Get ¶
Get returns a task by ID, whether it is unfinished, finished, or in history. It returns ErrNotFound if no such task exists.
func (*Client) Groups ¶
Groups returns the FIFO groups that have unfinished tasks, ordered by queue and key. Like Client.List, the query is canceled after 5 seconds.
func (*Client) List ¶
func (c *Client) List(ctx context.Context, params *ListParams) (*ListResult, error)
List returns tasks that match params, newest first, one page at a time. Each page's query is canceled after 5 seconds, so listing cannot overload the database; on a very large table, a filter that matches few tasks can reach that limit and return an error.
func (*Client) PauseQueue ¶
PauseQueue stops workers from fetching the queue's tasks. Tasks already running finish normally.
func (*Client) PauseSchedule ¶
PauseSchedule stops a schedule from enqueueing runs until it is resumed. It returns ErrNotFound for an unknown schedule.
func (*Client) Queues ¶
Queues returns every known queue: those with settings, those that workers serve, and those that hold tasks, as of the latest statistics.
func (*Client) ResumeQueue ¶
ResumeQueue undoes Client.PauseQueue.
func (*Client) ResumeSchedule ¶
ResumeSchedule undoes Client.PauseSchedule. Runs missed while paused collapse into one run.
func (*Client) Retry ¶
Retry makes a dead or canceled task available again, with a fresh set of attempts. Retrying the dead task that halts its FIFO group resumes the group; another task of a group waits behind the group's unfinished tasks. It returns ErrInvalidState for tasks in other states.
Example ¶
This example retries every dead task of one queue, once the cause of their failures is fixed.
package main
import (
"context"
"errors"
"log"
"github.com/code19m/taskmill"
)
func main() {
ctx := context.Background()
var client *taskmill.Client // from taskmill.NewClient
params := &taskmill.ListParams{Queues: []string{"emails"}, States: []taskmill.State{taskmill.StateDead}, Limit: 1000}
for {
page, err := client.List(ctx, params)
if err != nil {
log.Fatal(err)
}
for _, t := range page.Tasks {
// An operator may have retried or deleted it meanwhile.
if err := client.Retry(ctx, t.ID); err != nil && !errors.Is(err, taskmill.ErrInvalidState) &&
!errors.Is(err, taskmill.ErrNotFound) {
log.Fatal(err)
}
}
if page.Next == "" {
break
}
params.Cursor = page.Next
}
}
Output:
func (*Client) RunSchedule ¶
RunSchedule runs a schedule once now, in addition to its timetable. The maintainer enqueues the run within about a second, with the schedule's options, and the task's RunAt is the time of the request. The next regular run stays as it was. It returns ErrNotFound for an unknown schedule, and ErrInvalidState for a paused one.
func (*Client) Schedules ¶
func (c *Client) Schedules(ctx context.Context) ([]ScheduleInfo, error)
Schedules returns every schedule stored in the database.
func (*Client) UpdateQueue ¶
UpdateQueue sets a queue's installation-wide settings for every worker, and creates the queue if needed. Passing nil, or a zero MaxRunning, removes the limit. Workers apply the change within 10 seconds, and at once if they receive notifications.
func (*Client) UpdateSettings ¶
UpdateSettings changes the installation-wide settings. Zero fields reset to their defaults.
type ClientConfig ¶
type ClientConfig struct {
// Schema is the PostgreSQL schema that holds taskmill's tables. It must
// match ^[a-z_][a-z0-9_]{0,62}$. Default: "taskmill".
Schema string
// Logger receives the logs of the client and of its workers.
// Default: logs are discarded.
Logger *slog.Logger
// ContextMetadata, if set, is called on every enqueue and its result is
// added to the task's metadata, for example to carry a trace context from
// the producer to the handler. Metadata set in [EnqueueOptions] wins.
ContextMetadata func(ctx context.Context) map[string]string
}
ClientConfig configures a Client. The zero value is valid.
type EnqueueOptions ¶
type EnqueueOptions struct {
// Queue is the queue to enqueue into, at most 128 characters.
// Default: [DefaultQueue].
Queue string
// Priority orders tasks within the queue. Default: [PriorityNormal].
Priority Priority
// RunAt is the earliest time the task may start. Default: now.
RunAt time.Time
// MaxAttempts is how many times the task may run, from 1 to 10,000.
// Default: 25, which with the default backoff spans about 13 hours.
MaxAttempts int
// GroupKey puts the task in a FIFO group: tasks with the same key in the
// same queue run one at a time, in enqueue order. A group's dead task
// halts it until an operator retries or deletes that task. At most 256
// characters. Default: none.
GroupKey string
// DedupeKey makes the enqueue idempotent: while the key's window lasts,
// enqueueing the same kind with the same key in the same queue creates no
// new task, and reports the existing one. Canceling or deleting the task
// frees the key at once. Default: none.
DedupeKey string
// DedupeWindow is how long DedupeKey blocks duplicates. Default: 24 hours.
DedupeWindow time.Duration
// Metadata is stored with the task and passed to its handler, for
// example for tracing. Default: none.
Metadata map[string]string
}
EnqueueOptions control how a task is enqueued. Zero values mean "not set": a field set in the call wins over the kind's defaults (see ArgsWithDefaults), which win over taskmill's defaults.
Example (FifoGroup) ¶
This example runs tasks of one FIFO group one at a time, in order.
package main
import (
"context"
"log"
"github.com/code19m/taskmill"
)
// SendReceipt is the payload of an example task.
type SendReceipt struct {
OrderID int64 `json:"order_id"`
Email string `json:"email"`
}
// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }
func main() {
ctx := context.Background()
var client *taskmill.Client // from taskmill.NewClient
for _, entry := range []int64{1, 2, 3} {
_, err := client.Enqueue(ctx, SendReceipt{OrderID: entry}, &taskmill.EnqueueOptions{GroupKey: "customer-7"})
if err != nil {
log.Fatal(err)
}
}
}
Output:
type EnqueueParams ¶
type EnqueueParams struct {
Args Args
Options *EnqueueOptions
}
EnqueueParams is one task in a batch enqueue. Options may be nil.
type EnqueueResult ¶
type EnqueueResult struct {
// ID identifies the task: the new one, or the existing one for a
// duplicate.
ID int64
// Duplicate reports that the DedupeKey was already taken, so no task was
// created.
Duplicate bool
}
EnqueueResult reports the outcome of enqueueing one task.
type ErrorCode ¶
type ErrorCode string
ErrorCode classifies an entry of a task's error history that taskmill itself recorded.
const ( // CodeLeaseExpired means the worker lost the attempt's lease: it crashed, // stopped, or lost the database. CodeLeaseExpired ErrorCode = "lease_expired" // CodePanic means the handler panicked. CodePanic ErrorCode = "panic" // CodeTimeout means the attempt ran longer than [HandlerOptions.Timeout]. CodeTimeout ErrorCode = "timeout" // CodeInvalidPayload means the payload did not decode into the kind's // Args, so the task became dead at once. CodeInvalidPayload ErrorCode = "invalid_payload" // CodeUnknownKind means no worker with a handler for the kind appeared // within an hour, so the task became dead. CodeUnknownKind ErrorCode = "unknown_kind" // CodeNoHandler marks a note, not a failure: a worker met the task // without a handler for its kind, and the task began to wait for one, // without using attempts. CodeNoHandler ErrorCode = "no_handler" )
Error codes.
type Executor ¶
type Executor interface {
// contains filtered or unexported methods
}
Executor runs taskmill's statements on a transaction or connection that the caller owns, so that they commit or roll back with the caller's own work. Create one with Pgx or SQL.
The enqueue methods accept a transaction, a connection, or a pool. Client.CancelTx and Task.CompleteTx run several statements that must commit together, so they need a transaction: a pgx.Tx, a *sql.Tx, or a type with Commit and Rollback methods, such as *sqlx.Tx. They return ErrInvalidArgument for anything else.
Executor is sealed: only this package implements it, which lets its methods change without breaking callers.
func Pgx ¶
func Pgx(q PgxQuerier) Executor
Pgx returns an Executor that runs statements on q, typically a pgx.Tx.
func SQL ¶
func SQL(q SQLQuerier) Executor
SQL returns an Executor that runs statements on q, typically a *sql.Tx.
Libraries built on database/sql work through their underlying transaction: with bun, pass tx.Tx, because bun rewrites query placeholders itself.
Example ¶
This example enqueues through database/sql, as bun, sqlx, and plain database/sql code do.
package main
import (
"context"
"database/sql"
"log"
"os"
"github.com/code19m/taskmill"
)
// SendReceipt is the payload of an example task.
type SendReceipt struct {
OrderID int64 `json:"order_id"`
Email string `json:"email"`
}
// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }
func main() {
ctx := context.Background()
var client *taskmill.Client // from taskmill.NewClient
// The "pgx" driver comes from: import _ "github.com/jackc/pgx/v5/stdlib"
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
if err := enqueueWithSQL(ctx, db, client); err != nil {
log.Fatal(err)
}
}
func enqueueWithSQL(ctx context.Context, db *sql.DB, client *taskmill.Client) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if _, err := client.EnqueueTx(ctx, taskmill.SQL(tx), SendReceipt{OrderID: 7}, nil); err != nil {
return err
}
return tx.Commit()
}
Output:
type ExponentialBackoff ¶
ExponentialBackoff doubles the delay after each failed attempt, from Base up to Max, and spreads retries out with ±10% random jitter, so a delay can reach 10% above Max. The zero value uses a base of 1 second and a maximum of 1 hour.
func (ExponentialBackoff) Backoff ¶
func (b ExponentialBackoff) Backoff(attempt int) time.Duration
Backoff implements RetryPolicy.
type GroupInfo ¶
type GroupInfo struct {
Queue string
Key string
Tasks int // unfinished tasks in the group
// HaltedBy is the dead task that halts the group, or 0 if it runs.
HaltedBy int64
}
GroupInfo is a FIFO group that has unfinished tasks.
type GroupParams ¶
type GroupParams struct {
// Queues limits the result to groups of these queues. Empty means all
// queues.
Queues []string
// Search limits the result to groups whose keys contain it, ignoring
// case. Empty means all groups.
Search string
// Limit is the most groups returned. Default: 100. Maximum: 1,000.
Limit int
}
GroupParams selects the FIFO groups that Client.Groups returns.
type Handler ¶
Handler runs tasks of one kind.
Returning nil completes the task. Returning an error fails the attempt: the task is retried with backoff until it runs out of attempts. Wrap the error with Permanent to make the task dead at once, or return Snooze to run it again later without using an attempt.
Handle must return promptly once ctx is canceled: that means the task was canceled, its lease was lost, its attempt timed out, or the worker is shutting down.
type HandlerFunc ¶
HandlerFunc adapts a function to the Handler interface.
Example ¶
This example shows the errors a handler returns to control retries.
package main
import (
"context"
"errors"
"time"
"github.com/code19m/taskmill"
)
// SendReceipt is the payload of an example task.
type SendReceipt struct {
OrderID int64 `json:"order_id"`
Email string `json:"email"`
}
// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }
func deliverReceipt(context.Context, string, int64) error { return nil }
func main() {
handler := taskmill.HandlerFunc[SendReceipt](func(ctx context.Context, t *taskmill.Task[SendReceipt]) error {
if t.Args.Email == "" {
return taskmill.Permanent(errors.New("no email address")) // dead at once
}
if rateLimited() {
return taskmill.Snooze(time.Minute) // later, without using an attempt
}
return deliverReceipt(ctx, t.Args.Email, t.Args.OrderID) // retried with backoff on error
})
var handlers taskmill.Handlers
taskmill.AddHandler(&handlers, handler, &taskmill.HandlerOptions{Timeout: 30 * time.Second})
}
func rateLimited() bool { return false }
Output:
type HandlerOptions ¶
type HandlerOptions struct {
// Timeout bounds each attempt, or each batch. Default: 1 minute.
Timeout time.Duration
// Retry decides the delay before each retry. A task whose worker lost its
// lease is retried with the default instead, because the maintainer that
// rescues it knows no handler's options. Default: [ExponentialBackoff]{}.
Retry RetryPolicy
// BatchSize is the most tasks a [BatchHandler] receives at once.
// Default: 100. Maximum: 1,000. Ignored for other handlers.
BatchSize int
// DiscardCompleted deletes completed tasks of the kind at once, instead
// of keeping them in history, for high-volume kinds whose history nobody
// reads.
DiscardCompleted bool
}
HandlerOptions configure how a worker runs one kind.
type Handlers ¶
type Handlers struct {
// contains filtered or unexported fields
}
Handlers maps task kinds to their handlers. Register handlers with AddHandler or AddBatchHandler before passing Handlers to NewWorker. The zero value is an empty set; it is not safe for concurrent use.
type ListParams ¶
type ListParams struct {
// Queues limits the result to tasks of these queues. Empty means all
// queues.
Queues []string
// States limits the result to tasks in these states. Empty means all.
States []State
// Kinds limits the result to tasks of these kinds. Empty means all
// kinds.
Kinds []string
// GroupKeys limits the result to the tasks of these FIFO groups. Empty
// means all tasks.
GroupKeys []string
// Limit is the page size. Default: 100. Maximum: 1,000.
Limit int
// Cursor continues from a previous page's [ListResult.Next].
Cursor string
}
ListParams filters and pages Client.List.
type ListResult ¶
type ListResult struct {
Tasks []TaskInfo
// Next is the cursor for the next page, or empty on the last page.
Next string
}
ListResult is one page of tasks, newest first.
type Middleware ¶
Middleware wraps the execution of an attempt, for logging, metrics, or tracing. It must call next at most once, and must not modify task. Returning without calling next fails the attempt with the returned error. A handler's panic reaches middleware as an error. For a batch handler, middleware runs once per task, but the context it passes to next does not reach the handler.
Example ¶
This example logs every attempt with its duration, as tracing and metrics middleware would measure it.
package main
import (
"context"
"log"
"time"
"github.com/code19m/taskmill"
)
func main() {
logAttempts := taskmill.Middleware(func(ctx context.Context, task *taskmill.TaskInfo, next func(context.Context) error) error {
start := time.Now()
err := next(ctx)
log.Printf("task %d (%s), attempt %d: %v after %s", task.ID, task.Kind, task.Attempt, err, time.Since(start))
return err
})
var client *taskmill.Client // from taskmill.NewClient
var handlers taskmill.Handlers
_, err := taskmill.NewWorker(client, &taskmill.WorkerConfig{
Handlers: &handlers,
Middleware: []taskmill.Middleware{logAttempts},
})
if err != nil {
log.Fatal(err)
}
}
Output:
type MigrateConfig ¶
type MigrateConfig struct {
// Schema is the PostgreSQL schema to migrate. It must match
// ^[a-z_][a-z0-9_]{0,62}$. Default: "taskmill".
Schema string
// Logger receives one log line per applied migration, and a warning if
// partitions cannot be prepared. Default: logs are discarded.
Logger *slog.Logger
}
MigrateConfig configures Migrate. The zero value is valid.
type Migration ¶
Migration is one versioned schema change, for teams that apply migrations with their own tools. Migrations returns them in order: first the bootstrap, version 0, which creates the schema and the migrations table, then every versioned migration. Apply them in order, each in a transaction, and record every version above 0, so that NewClient finds the schema up to date:
INSERT INTO <schema>.migrations (version, name) VALUES (<Version>, '<Name>')
func Migrations ¶
Migrations returns every migration for schema, in order. Teams that use their own migration tools apply these instead of calling Migrate. The maintainer then creates the daily history partitions when workers start, which needs the workers' role to own the taskmill tables.
Example ¶
This example prints the migrations, for teams that apply them with their own migration tool.
package main
import (
"fmt"
"log"
"github.com/code19m/taskmill"
)
func main() {
ms, err := taskmill.Migrations("taskmill")
if err != nil {
log.Fatal(err)
}
for _, m := range ms {
fmt.Printf("%04d_%s\n", m.Version, m.Name)
}
}
Output: 0000_bootstrap 0001_initial
type PermanentError ¶
type PermanentError struct {
Err error
}
PermanentError marks a handler error that retrying cannot fix. The task becomes dead at once, keeping its remaining attempts unused.
func (*PermanentError) Error ¶
func (e *PermanentError) Error() string
Error implements the error interface.
func (*PermanentError) Unwrap ¶
func (e *PermanentError) Unwrap() error
Unwrap returns the wrapped error.
type PgxQuerier ¶
type PgxQuerier interface {
Exec(ctx context.Context, query string, args ...any) (pgconn.CommandTag, error)
Query(ctx context.Context, query string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, query string, args ...any) pgx.Row
}
PgxQuerier is the part of pgx that taskmill uses. pgx.Tx, *pgx.Conn, and *pgxpool.Pool implement it.
type Priority ¶
type Priority int16
Priority orders tasks within a queue: higher priorities start first. The zero value means "not set" and resolves to PriorityNormal.
type QueueInfo ¶
type QueueInfo struct {
Name string
Settings QueueSettings
Paused bool
Workers int // live workers that serve the queue
// Counts holds the number of tasks per state, except completed tasks.
// Counting stops at 10,000 tasks per state, and at 100,000 scheduled
// and retryable tasks across all queues; Capped reports that a count
// stopped early and is a lower bound.
Counts map[State]int64
Capped bool
RefreshedAt time.Time // zero until the maintainer first counts the queue
}
QueueInfo describes a queue: its settings, its workers, and its latest statistics, which the maintainer refreshes every 10 seconds.
type QueueOptions ¶
type QueueOptions struct {
// Concurrency is how many of the queue's tasks this process runs at once.
// A batch counts as one. Default: 10.
Concurrency int
}
QueueOptions configure how one worker process serves one queue. Installation-wide settings, such as a concurrency limit, are QueueSettings.
type QueueSettings ¶
type QueueSettings struct {
// MaxRunning caps the tasks of the queue running at once across all
// workers of the installation. Zero means no limit.
MaxRunning int
}
QueueSettings are a queue's installation-wide settings, stored in the database. The zero value means no concurrency limit.
type RetryPolicy ¶
type RetryPolicy interface {
// Backoff returns the delay before the retry that follows the given
// failed attempt, counting from 1.
Backoff(attempt int) time.Duration
}
RetryPolicy decides how long to wait before retrying a failed attempt.
type SQLQuerier ¶
type SQLQuerier interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
SQLQuerier is the part of database/sql that taskmill uses. *sql.Tx, *sql.Conn, and *sql.DB implement it. The connection must use pgx's database/sql driver, github.com/jackc/pgx/v5/stdlib.
type Schedule ¶
type Schedule struct {
// Name identifies the schedule. Schedules are kept in the database by
// name, so renaming one creates a new schedule.
Name string
// Cron is a five-field cron expression, such as "0 3 * * *", or one of
// the macros @yearly, @annually, @monthly, @weekly, @daily, @midnight,
// and @hourly.
Cron string
// Location is the time zone the expression is read in. Default: UTC.
Location *time.Location
// Args and Options describe the task to enqueue; Options may be nil.
// The schedule sets the run time and the dedupe key itself, to enqueue
// each run once.
Args Args
Options *EnqueueOptions
}
Schedule enqueues a task on a cron schedule, once per scheduled time across all workers. Define the same schedules on every worker that takes part in the maintainer election: the elected maintainer runs its own definitions. If it defines any, it also deletes the stored schedules that it does not define once they have not run or changed for a day.
Runs that are missed while no maintainer runs, or while the schedule is paused, collapse into one run. The expression is read on the wall clock of Location, so daylight saving time behaves as in classic cron. The task's RunAt is the time it was scheduled for.
Example ¶
This example runs a task every night at 03:00 Berlin time.
package main
import (
"context"
"log"
"time"
"github.com/code19m/taskmill"
)
// SendReceipt is the payload of an example task.
type SendReceipt struct {
OrderID int64 `json:"order_id"`
Email string `json:"email"`
}
// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }
func deliverReceipt(context.Context, string, int64) error { return nil }
func main() {
var client *taskmill.Client // from taskmill.NewClient
var handlers taskmill.Handlers
taskmill.AddHandler(&handlers, taskmill.HandlerFunc[SendReceipt](
func(ctx context.Context, t *taskmill.Task[SendReceipt]) error {
// t.RunAt is the night the run is for.
return deliverReceipt(ctx, t.Args.Email, t.Args.OrderID)
},
), nil)
berlin, err := time.LoadLocation("Europe/Berlin")
if err != nil {
log.Fatal(err)
}
_, err = taskmill.NewWorker(client, &taskmill.WorkerConfig{
Handlers: &handlers,
Schedules: []taskmill.Schedule{
{Name: "nightly-receipts", Cron: "0 3 * * *", Location: berlin, Args: SendReceipt{}},
},
})
if err != nil {
log.Fatal(err)
}
}
Output:
type ScheduleInfo ¶
type ScheduleInfo struct {
Name string
Queue string
Kind string
Cron string
Location string
NextRunAt time.Time
LastRunAt time.Time // zero if it never ran
Paused bool
}
ScheduleInfo describes a schedule and its state.
type Settings ¶
type Settings struct {
// HistoryRetention is how long completed tasks stay in history.
// Minimum: 1 hour. Default: 7 days.
HistoryRetention time.Duration
// DeadRetention is how long dead and canceled tasks are kept for
// operators to inspect and retry. Minimum: 1 hour. Default: 30 days.
DeadRetention time.Duration
}
Settings are the installation-wide settings, stored in the database and applied by the maintainer. Zero fields mean their defaults.
type SnoozeError ¶
SnoozeError asks taskmill to run the task again after a delay, without counting the current attempt.
func (*SnoozeError) Error ¶
func (e *SnoozeError) Error() string
Error implements the error interface.
type State ¶
type State string
State is the lifecycle state of a task. The lifecycle and its guarantees are described in https://github.com/code19m/taskmill/blob/main/docs/design/task-lifecycle.md.
const ( StateScheduled State = "scheduled" // waiting for its run time StatePending State = "pending" // waiting behind the head of its FIFO group StateAvailable State = "available" // ready, waiting for a worker StateRunning State = "running" // leased by an attempt StateRetryable State = "retryable" // failed, waiting for its backoff StateCompleted State = "completed" // its handler succeeded StateDead State = "dead" // will not run again unless an operator retries it StateCanceled State = "canceled" // canceled on request )
Task states.
type Task ¶
Task is a task being run by a handler, with its decoded Args.
func (*Task[A]) CompleteTx ¶
CompleteTx completes the task inside the caller's transaction, so that the handler's own writes and the completion commit together or not at all. It returns ErrLeaseLost if another attempt took the task over; return that error, so that the transaction rolls back.
After CompleteTx, the handler should commit and return nil. If the handler returns an error after its transaction committed, the task stays completed and the error is only logged; if the transaction rolled back, the error fails the attempt as usual.
Example ¶
This example completes a task in the handler's own transaction, so the balance update happens exactly once even if the task runs again.
package main
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/code19m/taskmill"
)
// ApplyPayment is the payload of an example task whose effects live in the
// same database.
type ApplyPayment struct {
AccountID int64 `json:"account_id"`
Cents int64 `json:"cents"`
}
// Kind implements taskmill.Args.
func (ApplyPayment) Kind() string { return "billing.apply_payment" }
func main() {
var pool *pgxpool.Pool // the application's pool
handler := func(ctx context.Context, t *taskmill.Task[ApplyPayment]) error {
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, "UPDATE accounts SET balance = balance + $1 WHERE id = $2", t.Args.Cents, t.Args.AccountID)
if err != nil {
return err
}
return t.CompleteTx(ctx, taskmill.Pgx(tx))
})
}
var handlers taskmill.Handlers
taskmill.AddHandler(&handlers, taskmill.HandlerFunc[ApplyPayment](handler), nil)
}
Output:
type TaskInfo ¶
type TaskInfo struct {
ID int64
Queue string
Kind string
State State
Priority Priority
// Attempt is the number of attempts used. In a handler, it is the
// current attempt, counting from 1. A snooze gives its attempt back, and
// [Client.Retry] starts over from 0.
Attempt int
MaxAttempts int
GroupKey string
// Metadata holds the tags from [EnqueueOptions.Metadata] and
// [ClientConfig.ContextMetadata].
Metadata map[string]string
// Payload is the task's Args as stored, in JSON.
Payload json.RawMessage
// Errors is the task's error history, oldest first: at most the 20 most
// recent entries.
Errors []AttemptError
CreatedAt time.Time
// RunAt is the earliest time the task may start: for a retryable or
// snoozed task, when it runs again, and for a task that a [Schedule]
// enqueued, the time it was scheduled for.
RunAt time.Time
AttemptedAt time.Time // zero if never attempted
FinalizedAt time.Time // zero until completed, dead, or canceled
}
TaskInfo describes a task: where it is in its lifecycle and what happened to its attempts.
type Worker ¶
type Worker struct {
// contains filtered or unexported fields
}
Worker fetches tasks from its queues and runs their handlers. One worker per process is typical; it also takes part in electing the maintainer, which promotes due tasks, rescues expired leases, runs schedules, and applies retention.
func NewWorker ¶
func NewWorker(client *Client, cfg *WorkerConfig) (*Worker, error)
NewWorker returns a worker that uses client to reach the database. It reports invalid configuration and handler registration errors.
func (*Worker) Run ¶
Run fetches and runs tasks until ctx is canceled. It then stops fetching, waits up to DrainTimeout for running tasks, cancels and releases those still running, and returns nil. It returns an error only if the worker cannot start: it is already running, or cannot register in the database.
func (*Worker) RunTask ¶
RunTask runs one task now, in the calling goroutine, the way Worker.Run runs tasks: it leases the task, runs the middleware and the handler of its kind while renewing the lease, and records the outcome. It ignores the task's run time, queue pauses, and concurrency limits, but not FIFO order. It does not need Run to be running, which makes it the tool for tests. If ctx is canceled before the handler returns, the handler's context is canceled too, and the task goes back to its queue without using an attempt.
It returns the task afterwards. It returns ErrNotFound if no task has the ID, and ErrInvalidState if the task is running, waits behind its FIFO group, or has finished.
type WorkerConfig ¶
type WorkerConfig struct {
// Handlers runs the tasks this worker fetches.
Handlers *Handlers
// Queues lists the queues to fetch from, with per-process options.
// Default: the default queue of every registered kind, from
// [ArgsWithDefaults] or else [DefaultQueue], with default options. If
// Queues leaves out a registered kind's default queue, Run logs a warning
// when it starts: tasks enqueued with the kind's defaults would wait for
// another worker.
Queues map[string]QueueOptions
// LeaseDuration is how long a fetched task stays owned without a
// heartbeat. Heartbeats are sent every third of it. Default: 30 seconds.
LeaseDuration time.Duration
// PollInterval is how often idle queues are checked when no notification
// arrives. Default: 1 second.
PollInterval time.Duration
// DrainTimeout is how long Run waits for running tasks after its context
// is canceled, before canceling their contexts and, 5 seconds later,
// releasing them. Keep it at least 10 seconds below the time the platform
// gives a stopping process. Default: 20 seconds.
DrainTimeout time.Duration
// Middleware wraps every attempt, in order: the first is the outermost.
Middleware []Middleware
// Schedules are recurring tasks that the maintainer enqueues.
Schedules []Schedule
// NoMaintainer keeps this worker out of the maintainer election. At least
// one worker of an installation must take part.
NoMaintainer bool
// ListenConfig is the connection that receives notifications. Set it to
// a direct connection when the pool goes through a transaction-pooling
// proxy, which cannot deliver them. Create it with [pgx.ParseConfig].
// Default: the pool's configuration.
ListenConfig *pgx.ConnConfig
}
WorkerConfig configures a Worker. The zero value is valid: a worker without handlers only takes part in maintenance.
type WorkerInfo ¶
type WorkerInfo struct {
ID string
Hostname string
Version string // taskmill's version in the worker's binary
Queues []string
Kinds []string // the kinds it has handlers for
StartedAt time.Time
HeartbeatAt time.Time
Maintainer bool // the worker is the elected maintainer
}
WorkerInfo describes a worker process.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
taskmill-ui
command
Command taskmill-ui serves taskmill's web interface on its own: a dashboard for an installation, run apart from the applications that use it.
|
Command taskmill-ui serves taskmill's web interface on its own: a dashboard for an installation, run apart from the applications that use it. |
|
internal
|
|
|
argkind
Package argkind reads what a zero value of an Args type says about it.
|
Package argkind reads what a zero value of an Args type says about it. |
|
cmd/bench
command
Command bench measures taskmill against the targets in docs/benchmarks.md, and checks its reliability under faults.
|
Command bench measures taskmill against the targets in docs/benchmarks.md, and checks its reliability under faults. |
|
cron
Package cron parses standard five-field cron expressions and computes their next run times.
|
Package cron parses standard five-field cron expressions and computes their next run times. |
|
migrations
Package migrations holds taskmill's versioned schema migrations.
|
Package migrations holds taskmill's versioned schema migrations. |
|
testdb
Package testdb connects integration tests to PostgreSQL.
|
Package testdb connects integration tests to PostgreSQL. |
|
uuid
Package uuid generates version 7 UUIDs (RFC 9562): a millisecond timestamp followed by random bits, so IDs are unique and roughly ordered by time.
|
Package uuid generates version 7 UUIDs (RFC 9562): a millisecond timestamp followed by random bits, so IDs are unique and roughly ordered by time. |
|
otel
module
|
|
|
Package outbox publishes messages to a message broker reliably, with the transactional outbox pattern.
|
Package outbox publishes messages to a message broker reliably, with the transactional outbox pattern. |
|
Package taskmilltest helps test code that uses taskmill.
|
Package taskmilltest helps test code that uses taskmill. |
|
Package ui serves taskmill's web interface: a dashboard of queues, tasks, schedules, and workers, with actions to pause and resume queues and schedules, run a schedule now, and retry, cancel, and delete tasks.
|
Package ui serves taskmill's web interface: a dashboard of queues, tasks, schedules, and workers, with actions to pause and resume queues and schedules, run a schedule now, and retry, cancel, and delete tasks. |