taskmill

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 33 Imported by: 2 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.

README

taskmill

CI OpenSSF Scorecard Go Reference

Background tasks for Go, kept in your PostgreSQL database.

If your service already uses PostgreSQL, your tasks can live there too. You run one less system, and each task commits or rolls back with your data.

  • In your transaction. Add a task in the same transaction as your data, with pgx or database/sql. If the transaction rolls back, the task never existed.
  • Never loses a task. Every task runs at least once. When a worker crashes, another worker runs its tasks. A task that keeps failing is kept as a dead task, so that you can fix the cause and retry it.
  • In order when you need it. Tasks with the same key, such as one customer's, run one at a time, in order.
  • Outbox included. Publish events to Kafka, NATS, or RabbitMQ only if your transaction commits, in order per key.
  • Dashboard included. Watch queues and tasks, and retry, cancel, or delete them. Mount it in your app, or run it on its own.

Also: delays, priorities, cron schedules, deduplication, limits across all workers, batch handlers, logs through log/slog, and OpenTelemetry. One worker runs about 30,000 tasks per second on a laptop (performance), and the only direct dependency is pgx.

The dashboard, showing the shop example.

A quick look

// A task is a Go struct with a kind. taskmill stores it as JSON.
type SendReceipt struct {
	OrderID int64 `json:"order_id"`
}

func (SendReceipt) Kind() string { return "email.send_receipt" }

// placeOrder saves an order and its task in one transaction: both, or neither.
func placeOrder(ctx context.Context, pool *pgxpool.Pool, client *taskmill.Client, email string) error {
	return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
		var orderID int64
		err := tx.QueryRow(ctx, "INSERT INTO orders (email) VALUES ($1) RETURNING id", email).Scan(&orderID)
		if err != nil {
			return err
		}
		_, err = client.EnqueueTx(ctx, taskmill.Pgx(tx), SendReceipt{OrderID: orderID}, nil)
		return err
	})
}

// runWorker runs tasks until ctx ends. A handler returns nil when the work is
// done, or an error to try again later.
func runWorker(ctx context.Context, client *taskmill.Client) error {
	var handlers taskmill.Handlers
	taskmill.AddHandler(&handlers, taskmill.HandlerFunc[SendReceipt](
		func(ctx context.Context, t *taskmill.Task[SendReceipt]) error {
			slog.InfoContext(ctx, "sending the receipt", "order_id", t.Args.OrderID)
			return nil
		}), nil)
	worker, err := taskmill.NewWorker(client, &taskmill.WorkerConfig{Handlers: &handlers})
	if err != nil {
		return err
	}
	return worker.Run(ctx)
}

The quickstart runs this as a complete program, with the dashboard, in about 15 minutes. The tutorial builds it with you, step by step.

Install

go get github.com/code19m/taskmill

You need Go 1.26 or newer, and PostgreSQL 15 or newer.

Learn more

  • Quickstart: run your first task, and watch it in the dashboard.
  • Tutorial: build a small shop step by step, from one task to a program that is ready to ship.
  • Documentation: concepts, guides, and running in production.
  • How do I…?: the best way to do common things.
  • API reference on pkg.go.dev.
  • Shop example: a small shop that uses most features, with its dashboard.
Package What it is
taskmill The client, workers, schedules, and the operations API
taskmill/outbox The outbox, to publish to a message broker
taskmill/ui The dashboard, as an http.Handler
taskmill/cmd/taskmill-ui The dashboard as a program of its own
taskmill/taskmilltest Helpers to test your code against a real PostgreSQL
taskmill/otel OpenTelemetry traces and metrics, in a module of its own

Status

The API is final for v1.0.0, which is not tagged yet: it waits for more use in production. Compatibility says what each release promises.

Contributing

Contributions are welcome. Please read CONTRIBUTING.md before you open a pull request. Report security issues privately, as SECURITY.md describes.

License

taskmill is released under the MIT License.

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 docs at https://github.com/code19m/taskmill/blob/main/docs/README.md cover every feature, testing, and running in production. Start with the quickstart: https://github.com/code19m/taskmill/blob/main/docs/start/quickstart.md.

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 right away, 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 the same time. Package github.com/code19m/taskmill/ui serves the same, except the limits, as a dashboard. 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"
	"log/slog"
	"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)
	}
	// Without a logger, taskmill logs nothing, not even errors.
	client, err := taskmill.NewClient(ctx, pool, &taskmill.ClientConfig{Logger: slog.Default()})
	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)
	}
}

Index

Examples

Constants

View Source
const (
	// MetadataSchedule holds the name of the schedule that enqueued the
	// task.
	MetadataSchedule = "taskmill.schedule"

	// MetadataScheduledFor holds the time that the run is for, in the
	// format of RFC 3339. Read it with [TaskInfo.ScheduledFor].
	MetadataScheduledFor = "taskmill.scheduled_for"
)

Metadata keys that taskmill sets itself on every task that a Schedule enqueues. Their values never change, whatever happens to the task, so a handler reads the same on every attempt, and the dashboard shows which schedule made a task. taskmill sets its values over those that the schedule's Options, the kind's defaults, or an EnqueueMiddleware give the same keys.

Keys that start with "taskmill." belong to taskmill, and later releases may add more of them: do not use the prefix for keys of your own. A test of a handler may set these two, so that its task stands for a scheduled run.

View Source
const DefaultQueue = "default"

DefaultQueue is the queue that tasks go to when neither the enqueue call nor the kind's defaults name one.

Variables

View Source
var (
	// ErrNotFound means the task or schedule does not exist, or no longer
	// exists.
	ErrNotFound = classError("taskmill: not found", "not_found")

	// ErrLeaseLost means the attempt no longer owns its task: its lease
	// expired and the task was rescued, canceled, or fetched again. It is
	// also the cause of the context of a handler whose attempt lost its
	// lease.
	ErrLeaseLost = classError("taskmill: lease lost", "lease_lost")

	// ErrInvalidState means the operation does not apply to the task's
	// current state, such as retrying a running task.
	ErrInvalidState = classError("taskmill: invalid state", "invalid_state")

	// ErrInvalidArgument means an argument or option is invalid: out of
	// range, too long, or text that PostgreSQL cannot store, such as a NUL
	// character.
	ErrInvalidArgument = classError("taskmill: invalid argument", "invalid_argument")

	// ErrSchemaOutdated means the database schema is missing or older than
	// this version of taskmill. Run [Migrate].
	ErrSchemaOutdated = classError("taskmill: database schema is missing or outdated", "schema_outdated")

	// ErrConflict means an update lost to concurrent updates of the same
	// settings every time it tried. Try again.
	ErrConflict = classError("taskmill: conflict", "conflict")

	// ErrTaskCanceled is the cause of a handler's context when the task was
	// canceled while it ran. The task becomes canceled when the attempt ends,
	// unless the handler returns nil, which completes it.
	ErrTaskCanceled = classError("taskmill: task canceled", "canceled")

	// ErrAttemptTimeout is the cause of a handler's context when the attempt
	// ran longer than [HandlerOptions.Timeout]. A failure that the handler
	// then returns is recorded with the code [CodeTimeout]; returning nil
	// completes the task.
	ErrAttemptTimeout = classError("taskmill: attempt timed out", "timeout")

	// ErrShutdown is the cause of a handler's context when the worker is
	// shutting down and the attempt outlived [WorkerConfig.DrainTimeout], or
	// the context of [Worker.RunTask] ended. The task goes back to its queue
	// without using an attempt, unless the handler returns nil, which
	// completes it.
	ErrShutdown = classError("taskmill: worker shutting down", "shutdown")
)

Errors returned by taskmill. Test for them with errors.Is, and for the cause of a handler's canceled context with context.Cause.

Each error names its class through an ErrorType() string method, which OpenTelemetry's semconv.ErrorType reports as error.type. The classes are part of the API and do not change: "not_found", "lease_lost", "invalid_state", "invalid_argument", "schema_outdated", "conflict", "canceled", "timeout", and "shutdown", and for failures that taskmill classifies itself, "panic", "invalid_payload", and "middleware", for middleware that returned nil without calling its next.

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
}

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

func Migrate(ctx context.Context, pool *pgxpool.Pool, cfg *MigrateConfig) error

Migrate creates or upgrades taskmill's schema, and prepares the next week's history partitions. It is safe to run from several processes at the same time: 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

func Permanent(err error) error

Permanent wraps err so that the task becomes dead without retrying, for example when its payload fails validation. Permanent(nil) returns nil.

func Snooze

func Snooze(d time.Duration) error

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 right away. 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", in 1 to 128
	// characters. 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.

An enqueue returns an error that wraps ErrInvalidArgument for a payload that PostgreSQL cannot store, or that is too large:

  • The payload must not encode to null. It must be valid UTF-8, with no NUL character (\u0000).
  • Every number must fit PostgreSQL's numeric type: at most 131,072 digits before the decimal point, and 16,383 after it.
  • The limit of 1 MiB counts each number as PostgreSQL stores it, written in full: 1e6 counts as 7 bytes.
  • PostgreSQL can still reject a value that passes these checks, such as an unpaired surrogate escape (\ud800).

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, and Metadata key by key. The default Queue must not depend on the value's fields: a worker reads it from a zero value, to fetch from that queue when WorkerConfig.Queues is empty.

Example

This example gives a kind its own queue and number of attempts. An option set in the call wins over the kind's default, field by field.

package main

import (
	"context"
	"log"

	"github.com/code19m/taskmill"
)

// ResizeImage is the payload of an example task whose kind has defaults of
// its own.
type ResizeImage struct {
	ImageID int64 `json:"image_id"`
}

// Kind implements taskmill.Args.
func (ResizeImage) Kind() string { return "image.resize" }

// EnqueueDefaults implements taskmill.ArgsWithDefaults.
func (ResizeImage) EnqueueDefaults() taskmill.EnqueueOptions {
	return taskmill.EnqueueOptions{Queue: "images", MaxAttempts: 5}
}

func main() {
	ctx := context.Background()
	var client *taskmill.Client // from taskmill.NewClient

	// Goes to the queue "images", with at most 5 attempts.
	if _, err := client.Enqueue(ctx, ResizeImage{ImageID: 7}, nil); err != nil {
		log.Fatal(err)
	}
	// Still goes to "images" with 5 attempts, but with a high priority.
	_, err := client.Enqueue(ctx, ResizeImage{ImageID: 8}, &taskmill.EnqueueOptions{Priority: taskmill.PriorityHigh})
	if err != nil {
		log.Fatal(err)
	}
}

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, and marks a
	// handler's error returned after its attempt timed out as [CodeTimeout].
	// It is empty for other errors 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

type BatchHandler[A Args] interface {
	HandleBatch(ctx context.Context, tasks []*Task[A]) []error
}

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, with the cause ErrAttemptTimeout or ErrShutdown, but not when one of its tasks is canceled or loses its lease: the batch runs to the end. Then a canceled task becomes completed if the batch returned nil for it, because the work was done, and canceled otherwise; the result of a task that lost its lease is discarded.

type BulkParams added in v0.2.0

type BulkParams struct {
	// Filter selects the tasks. It must not be empty.
	Filter TaskFilter

	// Cursor continues an action that stopped early, from its
	// [BulkResult.Next].
	Cursor string
}

BulkParams selects the tasks of a bulk action, such as Client.RetryMatching.

type BulkResult added in v0.2.0

type BulkResult struct {
	// Changed is how many tasks it changed.
	Changed int64

	// Skipped is how many matching tasks it left as they were, because other
	// transactions held them, their FIFO groups, or their dedupe keys at
	// that moment. To keep a group in order, a retry also leaves the later
	// tasks of a group it left. Run the action again to act on them.
	Skipped int64

	// Next continues the action, as [BulkParams.Cursor], if it stopped
	// before it went through every task: at the first task it skipped, if it
	// skipped any, so that a group it left comes back in order. Empty if it
	// went through every task.
	Next string
}

BulkResult reports what a bulk action did.

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

func NewClient(ctx context.Context, pool *pgxpool.Pool, cfg *ClientConfig) (*Client, error)

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 with ErrInvalidArgument 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. At REPEATABLE READ or SERIALIZABLE, Task.CompleteTx must be the transaction's first statement, as its comment explains.

func (*Client) Activity

func (c *Client) Activity(ctx context.Context, params *ActivityParams) ([]Activity, error)

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

func (c *Client) Cancel(ctx context.Context, id int64) error

Cancel cancels a task. A waiting task is canceled right away; a running task's context is canceled, and the task becomes canceled when its attempt ends, unless the handler completed it. A batch handler does not see the request: a task of a batch becomes canceled when its batch ends, unless the batch completed it. Cancel frees the task's dedupe key. It returns ErrNotFound if no task has the ID, and ErrInvalidState if the task already finished.

Example

This example cancels a task, and tells apart the two reasons why a task cannot be canceled.

package main

import (
	"context"
	"errors"
	"log"

	"github.com/code19m/taskmill"
)

func main() {
	ctx := context.Background()
	var client *taskmill.Client // from taskmill.NewClient
	var id int64                // from EnqueueResult.ID
	err := client.Cancel(ctx, id)
	switch {
	case errors.Is(err, taskmill.ErrNotFound):
		log.Print("the task is gone: deleted, or past its retention")
	case errors.Is(err, taskmill.ErrInvalidState):
		log.Print("the task already finished")
	case err != nil:
		log.Fatal(err)
	}
}

func (*Client) CancelMatching added in v0.2.0

func (c *Client) CancelMatching(ctx context.Context, params *BulkParams) (BulkResult, error)

CancelMatching cancels the unfinished tasks that match the filter of params, as Client.Cancel cancels each one, counting running tasks, which become canceled when their attempts end. It skips running tasks already asked to stop, and otherwise works like Client.RetryMatching.

func (*Client) CancelTx

func (c *Client) CancelTx(ctx context.Context, tx Executor, id int64) error

CancelTx is Client.Cancel in the caller's transaction.

Unlike Cancel, it cannot take its locks again in another order: that would take a rollback, and the transaction is the caller's. So when another transaction changes the same task or its FIFO group at the same moment, the two may wait for each other: a retry of the task, the end of the group's head, which makes the task the next head, or the commit of the task's enqueue. PostgreSQL then ends one of them after a second with a deadlock error (SQLSTATE 40P01), which may hit the other transaction. The transaction that got the error can be run again.

func (*Client) Count added in v0.2.0

func (c *Client) Count(ctx context.Context, filter *TaskFilter) (*TaskCounts, error)

Count counts the tasks that match filter, which may be nil. It counts at most 10,000 tasks per state. Like Client.List, the query is canceled after 5 seconds.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, id int64) error

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 ErrNotFound if no task has the ID, and ErrInvalidState for a running task; cancel it first.

func (*Client) DeleteMatching added in v0.2.0

func (c *Client) DeleteMatching(ctx context.Context, params *BulkParams) (BulkResult, error)

DeleteMatching deletes the tasks that match the filter of params, except running ones, as Client.Delete deletes each one, completed tasks in history included. It works like Client.RetryMatching.

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)
	}
}

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. One call takes at most 10,000 tasks, with at most 64 MiB of payload and metadata in all.

Example

This example enqueues many tasks in one call: one round trip and one transaction, so all of them exist or none does.

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
	params := make([]taskmill.EnqueueParams, 0, 100)
	for orderID := int64(1); orderID <= 100; orderID++ {
		params = append(params, taskmill.EnqueueParams{Args: SendReceipt{OrderID: orderID}})
	}
	results, err := client.EnqueueMany(ctx, params)
	if err != nil {
		log.Fatal(err)
	}
	// The results are in the order of params.
	log.Printf("enqueued %d tasks; the first is task %d", len(results), results[0].ID)
}

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

func (c *Client) Get(ctx context.Context, id int64) (*TaskInfo, error)

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

func (c *Client) Groups(ctx context.Context, params *GroupParams) (*GroupsResult, error)

Groups returns the FIFO groups that have unfinished tasks or a dead task that halts them, one page at a time, ordered by queue and key. Each queue named in GroupParams.Queues reads up to a page, so it takes at most 100 names. Like Client.List, each page's query is canceled after 5 seconds; a search that matches few of very many groups can reach that limit and return an error.

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.

Example

This example prints the dead tasks of one queue with their last errors, newest first, one page at a time.

package main

import (
	"context"
	"log"

	"github.com/code19m/taskmill"
)

func main() {
	ctx := context.Background()
	var client *taskmill.Client // from taskmill.NewClient
	params := &taskmill.ListParams{Filter: taskmill.TaskFilter{
		Queues: []string{"emails"},
		States: []taskmill.State{taskmill.StateDead},
	}}
	for {
		page, err := client.List(ctx, params)
		if err != nil {
			log.Fatal(err)
		}
		for _, task := range page.Tasks {
			if n := len(task.Errors); n > 0 {
				log.Printf("task %d (%s): %s", task.ID, task.Kind, task.Errors[n-1].Message)
			}
		}
		if page.Next == "" {
			break
		}
		params.Cursor = page.Next
	}
}

func (*Client) PauseQueue

func (c *Client) PauseQueue(ctx context.Context, name string) error

PauseQueue stops workers from fetching the queue's tasks. Tasks already running finish normally.

Example

This example pauses a queue during an incident, and resumes it afterwards.

package main

import (
	"context"
	"log"

	"github.com/code19m/taskmill"
)

func main() {
	ctx := context.Background()
	var client *taskmill.Client // from taskmill.NewClient

	// Workers stop fetching the queue's tasks. Running tasks finish.
	if err := client.PauseQueue(ctx, "partner-api"); err != nil {
		log.Fatal(err)
	}
	// ... the partner's API works again ...
	if err := client.ResumeQueue(ctx, "partner-api"); err != nil {
		log.Fatal(err)
	}
}

func (*Client) PauseSchedule

func (c *Client) PauseSchedule(ctx context.Context, name string) error

PauseSchedule stops a schedule from enqueueing runs until it is resumed. It returns ErrNotFound for an unknown schedule.

func (*Client) Queues

func (c *Client) Queues(ctx context.Context) ([]QueueInfo, error)

Queues returns every known queue: those with settings, those that workers read, and those that hold tasks, as of the latest statistics.

Example

This example prints each queue's available tasks and its lag.

package main

import (
	"context"
	"log"

	"github.com/code19m/taskmill"
)

func main() {
	ctx := context.Background()
	var client *taskmill.Client // from taskmill.NewClient
	queues, err := client.Queues(ctx)
	if err != nil {
		log.Fatal(err)
	}
	for _, q := range queues {
		// Counting stops at a cap: Capped then says that N is a lower bound.
		// Lag has no cap.
		available := q.Counts[taskmill.StateAvailable]
		log.Printf("queue %s: %d available (capped: %t), the oldest has waited %s",
			q.Name, available.N, available.Capped, q.Lag)
	}
}

func (*Client) ResumeQueue

func (c *Client) ResumeQueue(ctx context.Context, name string) error

ResumeQueue undoes Client.PauseQueue.

func (*Client) ResumeSchedule

func (c *Client) ResumeSchedule(ctx context.Context, name string) error

ResumeSchedule undoes Client.PauseSchedule. Runs missed while paused collapse into one run.

func (*Client) Retry

func (c *Client) Retry(ctx context.Context, id int64) error

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 until the group's current head finishes, and then runs before the group's tasks that were enqueued after it. It returns ErrNotFound if no task has the ID, and ErrInvalidState for tasks in other states.

func (*Client) RetryMatching added in v0.2.0

func (c *Client) RetryMatching(ctx context.Context, params *BulkParams) (BulkResult, error)

RetryMatching retries the dead and canceled tasks that match the filter of params, as Client.Retry retries each one. The filter must not be empty: to retry every dead task, set its States.

It goes through the tasks enqueued before it started, oldest first, in batches of 1,000, each in a short transaction of its own. It reads each task once, so it retries a task at most once, even if the task fails again meanwhile, and it ends however fast new tasks arrive. If a batch cannot reach its tasks within a second, because too many tasks that do not match lie before them, the action continues in batches that read at most 100,000 tasks each, and so gets past those. It skips the tasks, the FIFO groups, and the dedupe keys that other transactions hold at that moment, never waiting while it holds rows. If ctx ends first, it finishes the batch it is in, for at most 5 seconds, and returns what it did, with an error and BulkResult.Next to continue; each batch commits whole or not at all.

Example

This example retries every dead task of one queue, once the cause of their failures is fixed.

package main

import (
	"context"
	"log"

	"github.com/code19m/taskmill"
)

func main() {
	ctx := context.Background()
	var client *taskmill.Client // from taskmill.NewClient
	res, err := client.RetryMatching(ctx, &taskmill.BulkParams{Filter: taskmill.TaskFilter{
		Queues: []string{"emails"},
		States: []taskmill.State{taskmill.StateDead},
	}})
	if err != nil {
		log.Fatal(err)
	}
	// Other transactions held the skipped tasks, their FIFO groups, or their
	// dedupe keys: run it again for them.
	log.Printf("retried %d tasks, skipped %d", res.Changed, res.Skipped)
}

func (*Client) RunSchedule

func (c *Client) RunSchedule(ctx context.Context, name string) error

RunSchedule runs a schedule once now, in addition to its timetable. The maintainer enqueues the run within about a second, if it defines the schedule, with the schedule's options, and the run is for the time of the request: its RunAt at first, and its TaskInfo.ScheduledFor. The regular runs stay as they were. A request adds no run while a run of the schedule is due and waits for the maintainer, whether a regular run or an earlier request: that run is the one that runs now. 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) Settings

func (c *Client) Settings(ctx context.Context) (*Settings, error)

Settings returns the installation-wide settings.

func (*Client) UpdateQueue

func (c *Client) UpdateQueue(ctx context.Context, name string, update func(*QueueSettings)) error

UpdateQueue changes a queue's installation-wide settings for every worker, and creates the queue if needed. update gets a copy of the current settings and changes the ones it means to, so that settings it does not know of, such as those of a later version, keep their values.

No lock is held while update runs. The settings are written back only if they did not change meanwhile; if they did, update runs again on the new settings, after a short random pause, up to 10 times before UpdateQueue gives up with an error that wraps ErrConflict. So concurrent updates never lose each other's changes, and update may run more than once: it must only change the settings it gets, with no I/O and no calls to the Client. Workers apply the change within 10 seconds, and right away if they receive notifications. A negative MaxRunning is an error that wraps ErrInvalidArgument.

err := client.UpdateQueue(ctx, "partner-api", func(s *taskmill.QueueSettings) { s.MaxRunning = 4 })
Example

This example lets at most 4 tasks of a queue run at the same time, across all workers. The setting is stored in the database, so one call is enough.

package main

import (
	"context"
	"log"

	"github.com/code19m/taskmill"
)

func main() {
	ctx := context.Background()
	var client *taskmill.Client // from taskmill.NewClient
	err := client.UpdateQueue(ctx, "partner-api", func(s *taskmill.QueueSettings) { s.MaxRunning = 4 })
	if err != nil {
		log.Fatal(err)
	}
}

func (*Client) UpdateSettings

func (c *Client) UpdateSettings(ctx context.Context, update func(*Settings)) error

UpdateSettings changes the installation-wide settings. update gets a copy of the current settings and changes the ones it means to, so that settings it does not know of, such as those of a later version, keep their values. A setting changed to zero goes back to its default. Like Client.UpdateQueue, it holds no lock while update runs, and runs update again if the settings changed meanwhile, up to 10 times before it fails with ErrConflict, so update must only change the settings it gets.

err := client.UpdateSettings(ctx, func(s *taskmill.Settings) { s.HistoryRetention = 48 * time.Hour })

func (*Client) Workers

func (c *Client) Workers(ctx context.Context) ([]WorkerInfo, error)

Workers returns the registered worker processes. A worker that stopped without unregistering disappears 5 minutes after its last check-in.

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

	// EnqueueMiddleware wraps every enqueue, in order: the first is the
	// outermost. It can add metadata to tasks, for example to carry a trace
	// context from the producer to the handler.
	EnqueueMiddleware []EnqueueMiddleware
}

ClientConfig configures a Client. The zero value is valid.

type EnqueueMiddleware added in v0.2.0

type EnqueueMiddleware func(ctx context.Context, tasks []*EnqueueTask, next func(context.Context) error) error

EnqueueMiddleware wraps every enqueue, for tracing or metrics, including the enqueues of schedules. It receives the tasks being enqueued, at least one, validated and with their options resolved, in the order of the call. It may change their metadata, for example to carry a trace context to the handler, and then calls next, which stores the tasks and sets their results. Inside the caller's transaction, next returns before the transaction commits, and the tasks exist only if it does.

Middleware must call next at most once, and return its error. Returning nil without calling next fails the call, stores nothing, and gives the middleware outside an error from its next. If middleware fails after next succeeded, an enqueue in the caller's transaction returns its error, so that the caller can roll back; any other enqueue has committed, so it returns the results and logs the error, and a retry does not duplicate the tasks.

Example

This example tags every task with the ID of the request that enqueued it, and logs the tasks that were enqueued.

package main

import (
	"context"
	"log"

	"github.com/jackc/pgx/v5/pgxpool"

	"github.com/code19m/taskmill"
)

type requestIDKey struct{}

func main() {
	tagRequests := taskmill.EnqueueMiddleware(func(ctx context.Context, tasks []*taskmill.EnqueueTask, next func(context.Context) error) error {
		if id, ok := ctx.Value(requestIDKey{}).(string); ok {
			for _, task := range tasks {
				task.Metadata["request_id"] = id
			}
		}
		if err := next(ctx); err != nil {
			return err
		}
		for _, task := range tasks {
			log.Printf("enqueued task %d (%s) in queue %s", task.Result.ID, task.Kind, task.Queue)
		}
		return nil
	})
	ctx := context.Background()
	var pool *pgxpool.Pool // from pgxpool.New
	_, err := taskmill.NewClient(ctx, pool, &taskmill.ClientConfig{
		EnqueueMiddleware: []taskmill.EnqueueMiddleware{tagRequests},
	})
	if err != nil {
		log.Fatal(err)
	}
}

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. It must
	// be a time that PostgreSQL can store, from 4713 BC to 294276 AD, so a
	// time that stands for "never", such as Go's largest, is rejected.
	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 right away. The key may have any length: taskmill stores
	// a SHA-256 hash of the queue, the kind, and the key. Default: none.
	DedupeKey string

	// DedupeWindow is how long DedupeKey blocks duplicates, counted from the
	// enqueue. It must not be negative. Default: 24 hours.
	DedupeWindow time.Duration

	// Metadata is stored with the task and passed to its handler, for
	// example for tracing. Encoded as JSON, it may take at most 64 KiB,
	// including what [EnqueueMiddleware] adds. Keys that start with
	// "taskmill." belong to taskmill, such as [MetadataSchedule], and later
	// releases may add more of them: do not use the prefix for keys of
	// your own. A test of a handler may set taskmill's keys, so that its
	// task stands for a scheduled run. 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. Metadata merges key by key instead: the call's keys win over the same keys of the defaults, and the other keys of both are kept.

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)
		}
	}
}

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 EnqueueTask added in v0.2.0

type EnqueueTask struct {
	Queue string
	Kind  string

	// Metadata holds the task's metadata, from [EnqueueOptions.Metadata]. It
	// is never nil, and middleware may change it before calling next. For a
	// schedule's run, it also holds taskmill's own keys, such as
	// [MetadataSchedule]: middleware can read them, but taskmill sets them
	// again after it, so it cannot change or remove them.
	Metadata map[string]string

	// Result is set once next returns nil.
	Result EnqueueResult
}

EnqueueTask is a task being enqueued, as EnqueueMiddleware sees it. Changes to fields other than Metadata are ignored.

type ErrorCode

type ErrorCode string

ErrorCode classifies an entry of a task's error history that taskmill itself recorded.

const (
	// CodeLeaseLost means the worker lost the attempt's lease: it crashed,
	// stopped, or lost the database. Entries that taskmill recorded before
	// v0.3.0 have the code "lease_expired" instead.
	CodeLeaseLost ErrorCode = "lease_lost"

	// CodePanic means the handler panicked, or code that the worker ran
	// after it returned: a method of its error, or its retry policy.
	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 right away.
	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. A worker with a handler that then snoozes the
	// task, or gives it back when it stops, removes the note, and so does a
	// retry of the task.
	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()
}

type ExponentialBackoff

type ExponentialBackoff struct {
	// Base is the delay after the first failed attempt. Zero or less means
	// the default, 1 second.
	Base time.Duration

	// Max is the longest delay, before jitter. Zero or less means the
	// default, 1 hour.
	Max time.Duration
}

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 is how many tasks the group counts: its unfinished tasks, and
	// the dead task that halts it, if any. A group halted by its only task
	// counts 1.
	Tasks int

	// HaltedBy is the dead task that halts the group, or 0 if it runs.
	HaltedBy int64
}

GroupInfo is a FIFO group that has a row: one that has unfinished tasks, or that a dead task halts.

type GroupParams

type GroupParams struct {
	// Queues limits the result to groups of these queues. Empty means all
	// queues. Maximum: 100 names.
	Queues []string

	// Search limits the result to groups whose keys contain it, ignoring
	// case. At most 256 characters. Empty means all groups.
	Search string

	// Halted limits the result to the groups that a dead task halts.
	Halted bool

	// Limit is the page size. Default: 100. Maximum: 1,000.
	Limit int

	// Cursor continues from a previous page's [GroupsResult.Next].
	Cursor string
}

GroupParams selects and pages the FIFO groups that Client.Groups returns.

type GroupsResult added in v0.3.0

type GroupsResult struct {
	Groups []GroupInfo

	// Next is the cursor for the next page, or empty on the last page.
	Next string
}

GroupsResult is one page of FIFO groups, ordered by queue and key.

type Handler

type Handler[A Args] interface {
	Handle(ctx context.Context, task *Task[A]) error
}

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 right away, or return Snooze to run it again later without using an attempt.

Handle must return promptly once ctx is canceled. context.Cause says why: ErrTaskCanceled, ErrLeaseLost, ErrAttemptTimeout, or ErrShutdown.

type HandlerFunc

type HandlerFunc[A Args] func(ctx context.Context, task *Task[A]) error

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 right away
		}
		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 }

func (HandlerFunc[A]) Handle

func (f HandlerFunc[A]) Handle(ctx context.Context, task *Task[A]) error

Handle calls f(ctx, task).

type HandlerOptions

type HandlerOptions struct {
	// Timeout bounds each attempt, or each batch. It must not be negative.
	// 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 in one call.
	// Default: 100. Maximum: 1,000. Ignored for other handlers.
	BatchSize int

	// DiscardCompleted deletes completed tasks of the kind right away,
	// 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 {
	// Filter selects the tasks. Its zero value selects every task.
	Filter TaskFilter

	// 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

type Middleware func(ctx context.Context, task *TaskInfo, next func(context.Context) error) error

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, or with an error that says so if it returns nil: the task is retried with backoff, as after a handler's error, and the middleware outside sees that error from its next. 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)
	}
}

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

type Migration struct {
	Version int
	Name    string
	SQL     string
}

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

func Migrations(schema string) ([]Migration, error)

Migrations returns every migration for schema, in order. Teams that use their own migration tools apply these instead of calling Migrate. They create no history partitions: each worker creates them when it starts, and the maintainer keeps them ready, 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
0002_queue_lag
0003_halted_groups
0004_stuck_work

type PermanentError

type PermanentError struct {
	Err error
}

PermanentError marks a handler error that retrying cannot fix. The task becomes dead right away, keeping its remaining attempts unused.

It names no error class of its own. OpenTelemetry's semconv.ErrorType reports the class of the first error in Err's chain that has an ErrorType() string method, and "*taskmill.PermanentError" if none has.

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.

const (
	PriorityLow      Priority = 1
	PriorityNormal   Priority = 2
	PriorityHigh     Priority = 3
	PriorityCritical Priority = 4
)

Task priorities, from lowest to highest.

func (Priority) String

func (p Priority) String() string

String returns the priority's name, such as "normal".

type QueueInfo

type QueueInfo struct {
	Name     string
	Settings QueueSettings

	// Paused reports that the queue is paused: workers fetch none of its
	// tasks until [Client.ResumeQueue].
	Paused bool

	// Workers counts the workers registered to read the queue. A worker
	// that stopped without unregistering, such as after a crash, counts
	// until it is removed, 5 minutes after its last check-in.
	Workers int

	// 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; a count's Capped reports that
	// it stopped with more tasks left, so it is a lower bound. Once the
	// shared cap is passed, every queue's scheduled and retryable counts are
	// capped, even at zero.
	Counts map[State]TaskCount

	// RefreshedAt is when the maintainer last counted the queue: zero until
	// it first does. It stops moving when no maintainer runs.
	RefreshedAt time.Time

	// Lag is how long the queue's oldest due task has waited since its run
	// time, by the database's clock at the call: an available task, or a
	// scheduled or retryable one whose run time has passed. It grows when
	// workers fall behind or stop, the queue is paused, or due tasks are not
	// promoted, and keeps growing when no maintainer runs. Tasks pending
	// behind their FIFO group wait by design and do not count. Zero when no
	// task was due at the last count. The maintainer finds the oldest task
	// when it counts, so for up to one refresh, about 10 seconds, Lag may
	// be too high: a task that finished since still counts. Work can be
	// stuck while Lag stays near zero: HaltedGroups and MostFailures show it.
	Lag time.Duration

	// HaltedGroups counts the queue's FIFO groups that a dead task halts.
	// Their later tasks wait as pending until an operator retries or
	// deletes the dead task, so they do not count in Lag. Counting stops at
	// 10,000.
	HaltedGroups int

	// MostFailures is the most times in a row that one task of the queue,
	// waiting to retry, has failed. It grows while a task keeps failing,
	// such as while a service that its handler calls is down, even though
	// Lag stays near zero: the task waits for its next attempt, not for a
	// worker. Zero when no task waits to retry. A task leaves it when it
	// completes, dies, or is canceled, and for as long as it runs its next
	// attempt.
	//
	// The maintainer reads the failures of the 10,000 retryable tasks in
	// all that retry last, and of each queue's task that retries last. A
	// task's wait before its retry grows with its failures, so the tasks
	// that failed most retry last. Once the waits reach their maximum, such
	// as 1 hour by default, they no longer tell the tasks apart: with more
	// than 10,000 tasks at that wait, MostFailures may be lower than the
	// most failures of any one task.
	MostFailures int
}

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 the
	// same time. A batch counts as one. It must not be negative. Default: 10.
	Concurrency int
}

QueueOptions configure how one worker process reads one queue. Installation-wide settings, such as a limit on running tasks, are QueueSettings.

type QueueSettings

type QueueSettings struct {
	// MaxRunning caps the tasks of the queue running at the same time across
	// all workers of the installation. It must not be negative. Zero means
	// no limit.
	MaxRunning int
}

QueueSettings are a queue's installation-wide settings, stored in the database. The zero value means no limit.

type RetryPolicy

type RetryPolicy interface {
	// Backoff returns the delay before the retry that follows the given
	// failed attempt, counting from 1. If it panics, the attempt fails with
	// the code [CodePanic] instead of the handler's error, and the task is
	// retried after the default backoff.
	Backoff(attempt int) time.Duration
}

RetryPolicy decides how long to wait before retrying a failed attempt.

Example

This example retries the tasks of one kind every 30 seconds, instead of with the default exponential backoff.

package main

import (
	"context"
	"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 }

// fixedDelay retries every failed attempt after the same wait.
type fixedDelay time.Duration

// Backoff implements taskmill.RetryPolicy.
func (d fixedDelay) Backoff(int) time.Duration { return time.Duration(d) }

func main() {
	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)
		},
	), &taskmill.HandlerOptions{Retry: fixedDelay(30 * time.Second)})
}

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, in 1 to 128 characters. Schedules are
	// kept in the database by name, so renaming one creates a new schedule.
	Name string

	// Cron is a cron expression of five fields separated by spaces, such as
	// "0 3 * * *": minute (0-59), hour (0-23), day of month (1-31), month
	// (1-12 or JAN-DEC), and day of week (0-7 or SUN-SAT, where 0 and 7 both
	// mean Sunday). A field is "*", a value, a range "a-b", or a list of
	// those separated by commas, and each of them may have a step "/n":
	// "*/15" in the first field means every 15 minutes. Names are read in
	// any letter case. If neither day field is "*", a day matches when
	// either field matches, as in classic cron.
	//
	// Cron can also be one of the macros @yearly, @annually, @monthly,
	// @weekly, @daily, @midnight, and @hourly. [NewWorker] rejects an
	// expression that matches no time in the next five years, such as
	// February 31.
	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, so [NewWorker] rejects Options that set RunAt,
	// DedupeKey, or DedupeWindow.
	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, for the first time that was missed. Each run's task carries the schedule's name and the time the run is for in its metadata; see MetadataSchedule. In a handler, read that time with TaskInfo.ScheduledFor: the task's RunAt is that time only until the first retry or snooze moves it.

The expression is read on the wall clock of Location, and each time on that clock that it names runs once. When clocks go forward, every time that they skip runs after the jump, as long after it as the time is into the skipped hour: 02:30 runs at 03:30. When clocks go back, a time in the repeated hour runs the first time the clock shows it, and not the second. So a schedule that runs several times an hour, such as "*/15 * * * *", makes no run during the second pass of that hour, where classic cron keeps it running.

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 {
			// The night the run is for, in Berlin time. It is the same on
			// every attempt, unlike t.RunAt, which a retry moves.
			night := t.ScheduledFor()
			if night.IsZero() {
				// No schedule enqueued the task, or a maintainer of an
				// older release did, which stored no such time.
				night = t.RunAt
			}
			log.Printf("sending the receipts of %s", night.Format(time.DateOnly))
			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)
	}
}

type ScheduleInfo

type ScheduleInfo struct {
	Name  string
	Queue string
	Kind  string
	Cron  string

	// Location is the name of the schedule's time zone, such as
	// "Europe/Berlin" or "UTC".
	Location string

	// NextRunAt is when the schedule's next run is due. A paused schedule
	// does not run then.
	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, at
	// least: history is dropped a whole UTC day at a time, so a task stays
	// up to a day longer. 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. A dead task that halts its FIFO group
	// is kept until it is retried or deleted. 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. A period is stored in whole microseconds, and the longest time.Duration, about 292 years, keeps tasks for good.

type SnoozeError

type SnoozeError struct {
	Delay time.Duration
}

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 states, and what moves a task from one to the next, are described in https://github.com/code19m/taskmill/blob/main/docs/concepts/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.

func (State) CanCancel added in v0.2.0

func (s State) CanCancel() bool

CanCancel reports whether tasks in state s can be canceled: unfinished tasks.

func (State) CanDelete added in v0.2.0

func (s State) CanDelete() bool

CanDelete reports whether tasks in state s can be deleted: all but running tasks.

func (State) CanRetry added in v0.2.0

func (s State) CanRetry() bool

CanRetry reports whether tasks in state s can be retried, one with Client.Retry or many with Client.RetryMatching: dead and canceled tasks.

func (State) Finished

func (s State) Finished() bool

Finished reports whether the state is final: completed, dead, or canceled.

type Task

type Task[A Args] struct {
	TaskInfo

	Args A
	// contains filtered or unexported fields
}

Task is a task being run by a handler, with its decoded Args.

func (*Task[A]) CompleteTx

func (t *Task[A]) CompleteTx(ctx context.Context, tx Executor) error

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. Returning nil after a rollback records nothing: once the task's lease expires, the maintainer rescues it as a failed attempt, with the code lease_lost.

At the REPEATABLE READ and SERIALIZABLE isolation levels, call CompleteTx as the first statement of the transaction. The worker's lease renewals change the task's row, and PostgreSQL fails CompleteTx with a serialization failure (SQLSTATE 40001) when a renewal commits after the transaction's first statement. The statements after CompleteTx still commit together with the completion.

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)
}

type TaskCount added in v0.2.0

type TaskCount struct {
	N int64

	// Capped reports that counting stopped at its cap with more tasks left,
	// so that N is a lower bound.
	Capped bool
}

TaskCount is a number of tasks, from a count that stops at a cap.

type TaskCounts added in v0.2.0

type TaskCounts struct {
	// States holds how many of them are in each state that the filter
	// selects.
	States map[State]TaskCount

	// Retry, Cancel, and Delete are how many of them [Client.RetryMatching],
	// [Client.CancelMatching], and [Client.DeleteMatching] would change.
	Retry, Cancel, Delete TaskCount
}

TaskCounts counts the tasks that match a filter.

type TaskFilter added in v0.2.0

type TaskFilter struct {
	// Queues limits the tasks to these queues. Empty means all queues.
	Queues []string

	// States limits the tasks to these states. Empty means all states.
	States []State

	// Kinds limits the tasks to these kinds. Empty means all kinds.
	Kinds []string

	// GroupKeys limits the tasks to those of these FIFO groups. Empty means
	// all tasks.
	GroupKeys []string
}

TaskFilter selects tasks by queue, state, kind, and FIFO group, for Client.List, Client.Count, and the bulk actions: a task matches if it matches every filter that is set. A queue name or kind has at most 128 characters, and a group key at most 256. An unknown state, like a value that is empty or too long, is an error that wraps ErrInvalidArgument.

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
	// [EnqueueMiddleware], and for a task that a [Schedule] enqueued,
	// taskmill's own: [MetadataSchedule] and [MetadataScheduledFor].
	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 is when the task was enqueued, by the database's clock.
	CreatedAt time.Time

	// RunAt is the earliest time the task may start. A retry, a snooze, and
	// a lost lease move it to when the task runs again. So for a task that a
	// [Schedule] enqueued, it is the time the run is for on the first
	// attempt only: [TaskInfo.ScheduledFor] returns that time on every
	// attempt.
	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.

func (*TaskInfo) ScheduledFor added in v0.6.0

func (t *TaskInfo) ScheduledFor() time.Time

ScheduledFor returns the time that the task's run is for, if a Schedule enqueued the task: the time of the timetable, or the time of the request for a run that Client.RunSchedule asked for. It is the same on every attempt, unlike RunAt, which a retry, a snooze, or a lost lease moves.

The time shows the clock of the schedule's Location, so its day and hour are those that the schedule's expression names. But it carries only the offset from UTC that this Location had at that moment, not the Location with its rules. So for arithmetic on the calendar that may cross a clock change, such as AddDate, first convert the time with In to the schedule's Location. For a Location whose offset is not a whole number of minutes, the time is in UTC.

It returns the zero time for a task that no schedule enqueued, and for a run that a maintainer of an older release enqueued, which stored no such time: a handler can fall back to RunAt then.

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, schedules, and handler registrations, such as a kind registered twice, as errors that wrap ErrInvalidArgument.

func (*Worker) Health added in v0.2.0

func (w *Worker) Health() error

Health reports whether the worker runs and is in touch with the database: nil while Run runs and its last check-in succeeded within LeaseDuration, and otherwise an error that says why. A worker out of touch for that long can no longer keep its tasks' leases. Health reads only memory, so a readiness probe may call it often. It fails while the database is out of reach, which restarting the worker does not fix: do not base a liveness probe on it.

Example

This example answers a readiness probe from a worker's health. Do not base a liveness probe on it: Health fails while the database is out of reach, which a restart does not fix.

package main

import (
	"log"

	"github.com/code19m/taskmill"
)

func main() {
	var worker *taskmill.Worker // from taskmill.NewWorker; its Run runs in another goroutine

	// Health is nil while Run runs and the worker's last check-in is at most
	// one LeaseDuration old. It reads only memory, so call it at every probe.
	if err := worker.Health(); err != nil {
		log.Printf("not ready: %v", err) // answer the probe with 503
	}
}

func (*Worker) Run

func (w *Worker) Run(ctx context.Context) error

Run fetches and runs tasks until ctx is canceled. It then stops fetching and, if it is the maintainer, resigns, so that another worker takes over right away. It waits up to DrainTimeout for running tasks, cancels and releases those still running, and returns nil. If ctx ends before the worker registered, it returns nil right away. It returns an error only if the worker cannot start: it is already running, which is ErrInvalidState, or it cannot register in the database.

Before it fetches, Run creates the history partitions that the next week lacks, as Migrate does, so that a schema applied with Migrations keeps the history of its first completed tasks. A failure is only logged: the maintainer tries again.

func (*Worker) RunTask

func (w *Worker) RunTask(ctx context.Context, id int64) (*TaskInfo, error)

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 MaxRunning 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.

A task of a kind that the worker has no handler for is snoozed, with a no_handler note in its errors, as Run does, and returned.

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.

Example

This example runs one task now, in the calling goroutine, as a test or an operator's tool does. Run does not need to be running.

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() {
	ctx := context.Background()
	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 {
			return deliverReceipt(ctx, t.Args.Email, t.Args.OrderID)
		},
	), nil)
	worker, err := taskmill.NewWorker(client, &taskmill.WorkerConfig{Handlers: &handlers, NoMaintainer: true})
	if err != nil {
		log.Fatal(err)
	}

	res, err := client.Enqueue(ctx, SendReceipt{OrderID: 7}, &taskmill.EnqueueOptions{RunAt: time.Now().Add(time.Hour)})
	if err != nil {
		log.Fatal(err)
	}
	// RunTask ignores the run time, so the task runs now.
	info, err := worker.RunTask(ctx, res.ID)
	if err != nil {
		log.Fatal(err) // such as ErrInvalidState for a task that is running or has finished
	}
	log.Printf("task %d is %s after attempt %d", info.ID, info.State, info.Attempt)
}

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. A
	// queue's name has 1 to 128 characters.
	// 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
	// renewal. The worker checks in every third of it, and renews the
	// leases of its running tasks then. Minimum: 100 milliseconds. Default:
	// 30 seconds.
	LeaseDuration time.Duration

	// PollInterval is how often the worker checks an idle queue while the
	// maintainer's heartbeats do not reach it. It must not be negative.
	// Default: 1 second.
	//
	// The maintainer sends a heartbeat every 5 seconds. While heartbeats
	// arrive, notifications wake the worker, and the maintainer wakes each
	// queue whose next task waited more than a second. So the worker checks
	// an idle queue only once a minute, or every PollInterval if that is
	// longer, and a task whose notification came too early or was lost
	// starts within about 2 seconds.
	//
	// The worker uses PollInterval from its start until the first heartbeat,
	// which a running maintainer sends within 5 seconds, and again once no
	// heartbeat came for 15 seconds. So if the maintainer or the
	// notification connection fails silently, such a task starts within
	// about 16 seconds, and then within PollInterval while no heartbeat
	// arrives.
	//
	// A queue that its [QueueSettings.MaxRunning] limit keeps from fetching
	// more tasks is checked every PollInterval too, whether heartbeats
	// arrive or not: no notification says when another worker's task of the
	// queue ends.
	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. It must not be negative. 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 pooler in transaction
	// mode, which cannot deliver them: without it, the worker finds that
	// out when it starts, logs an error, and polls every PollInterval.
	// 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. A config that sets Queues needs handlers too: without them, NewWorker returns an error that wraps ErrInvalidArgument.

type WorkerInfo

type WorkerInfo struct {
	// ID names the worker: its host name, its process ID, and a random
	// suffix, joined by dashes.
	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 is when the worker last registered: when its Run started,
	// or when it registered again after the maintainer removed it as stale.
	StartedAt   time.Time
	CheckedInAt time.Time // its last check-in, which it makes every third of its LeaseDuration
	Maintainer  bool      // the worker is the elected maintainer
}

WorkerInfo describes a worker process.

Directories

Path Synopsis
cmd
taskmill-ui command
Command taskmill-ui serves taskmill's dashboard of an installation on its own, apart from the applications that use it.
Command taskmill-ui serves taskmill's dashboard of an installation on its own, apart from the applications that use it.
examples
quickstart command
Command quickstart is the program of the quickstart, docs/start/quickstart.md: a tiny shop that emails a receipt for each order, as a background task, and shows the tasks in the dashboard.
Command quickstart is the program of the quickstart, docs/start/quickstart.md: a tiny shop that emails a receipt for each order, as a background task, and shows the tasks in the dashboard.
shop command
Command shop is a small online shop that shows taskmill at work, with its dashboard.
Command shop is a small online shop that shows taskmill at work, with its dashboard.
tutorial command
Command tutorial is the program that the reader of the tutorial, docs/tutorial, has built after part 7: the shop of the quickstart, grown into one binary with two roles.
Command tutorial is the program that the reader of the tutorial, docs/tutorial, has built after part 7: the shop of the quickstart, grown into one binary with two roles.
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/design/benchmarks.md, and checks its reliability under faults.
Command bench measures taskmill against the targets in docs/design/benchmarks.md, and checks its reliability under faults.
cmd/compat command
Command compat is the current code's half of the rolling-deploy check in internal/compat.
Command compat is the current code's half of the rolling-deploy check in internal/compat.
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 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, one at a time or all that match the task list's filters.
Package ui serves taskmill's 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, one at a time or all that match the task list's filters.

Jump to

Keyboard shortcuts

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