taskmill

package module
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 35 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 task queue and transactional outbox for Go, on PostgreSQL.

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.

Where to start

Most programs take five steps, and the package's example shows them together:

These comments are the reference: the comment of each identifier states its contract, its defaults, its limits, and its errors. The docs teach how to use them, from a quickstart to running in production. They ship with the module, in its docs directory, at the version in use, and llms.txt in the module's root lists every page in one line.

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. Client.EnqueueMany enqueues thousands of tasks in one round trip. EnqueueOptions 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, with HandlerOptions such as a timeout. 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.

Running workers

A Worker runs the handlers until its context ends, then stops cleanly. Its WorkerConfig names its queues, each with a QueueOptions, its Middleware, and its Schedule values, which enqueue tasks on a cron timetable. One worker of an installation is elected maintainer, and does the shared work: delayed tasks, retries, lost leases, schedules, and retention. Worker.Health answers a readiness probe.

Operating

The Client lists, cancels, retries, and deletes tasks, one at a time or all that match a TaskFilter. It pauses queues, limits how many of a queue's tasks run at the same time with QueueSettings, and sets retention with Settings. Client.Queues reports each queue's counts and lag.

Other packages

  • github.com/code19m/taskmill/outbox publishes messages to a broker with the transactional outbox pattern.
  • github.com/code19m/taskmill/ui serves a dashboard of the queues and tasks, as a net/http.Handler.
  • github.com/code19m/taskmill/cmd/taskmill-ui is that dashboard as a program of its own.
  • github.com/code19m/taskmill/taskmilltest runs tests against a real database, each in a schema of its own.
  • github.com/code19m/taskmill/otel, a module of its own, adds OpenTelemetry traces and metrics.
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)
	}
}
Example (Errors)

This example tests one of taskmill's errors with errors.Is. The message says what is wrong, but it may change in any release: never compare messages.

package main

import (
	"errors"
	"fmt"

	"github.com/code19m/taskmill"
)

func main() {
	_, err := taskmill.Migrations("My Schema")
	fmt.Println(errors.Is(err, taskmill.ErrInvalidArgument))
	fmt.Println(err)
}
Output:
true
taskmill: invalid argument: schema "My Schema" must match ^[a-z_][a-z0-9_]{0,62}$

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: a task was deleted, or retention removed it. Treat it as gone.
	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.
	// [Task.CompleteTx] returns it: return it from the handler, so that the
	// handler's transaction rolls back.
	//
	// It is also the cause of the context of a handler whose attempt lost its
	// lease. Either the worker could not renew the lease in time, so the task
	// may already run on another worker. Or this worker fetched the task
	// again after a rescue: then the older of its two attempts gets this
	// cause. The result of the attempt is discarded: the maintainer rescues
	// a task whose lease ran out as a failed attempt, with the code
	// [CodeLeaseLost], so the task is retried.
	ErrLeaseLost = classError("taskmill: lease lost", "lease_lost")

	// ErrInvalidState means the operation does not fit the state of its
	// target: a retry of a task that is not dead or canceled, a cancel of a
	// finished task, a delete of a running one, a run of a paused schedule,
	// or [Worker.Run] on a worker that already runs. To check a task first,
	// use [State.CanRetry], [State.CanCancel], or [State.CanDelete].
	ErrInvalidState = classError("taskmill: invalid state", "invalid_state")

	// ErrInvalidArgument means an argument, an option, or a configuration is
	// invalid: out of range, too long, or text that PostgreSQL cannot store,
	// such as a NUL character. Every call that takes arguments can return it.
	// The message says what is wrong, and the same call fails again until
	// the caller fixes it.
	ErrInvalidArgument = classError("taskmill: invalid argument", "invalid_argument")

	// ErrSchemaOutdated means the database schema is missing or older than
	// this version of taskmill. [NewClient] returns it. Run [Migrate], or
	// apply [Migrations] with the application's own tool, before the new
	// version of the application starts.
	ErrSchemaOutdated = classError("taskmill: database schema is missing or outdated", "schema_outdated")

	// ErrConflict means that other work stands in the way of the call.
	// [Client.UpdateQueue] and [Client.UpdateSettings] return it when they
	// lost to concurrent updates of the same settings each of the 10 times
	// they tried: try again a little later. [Client.Retry] returns it when
	// another task holds the dedupe key that the canceled task had: that
	// task stands for the same work, so trying again helps only once it
	// gave the key away.
	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, never with == and never by their message: taskmill wraps them with details, such as the task's ID, and a message may change in any release. Test for the cause of a handler's canceled context with context.Cause. The packages outbox, ui, and otel return the same errors.

A database or network error is none of these, and has no class. taskmill wraps it with what it was doing, so errors.As still finds pgx's error types in it.

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". Failures that taskmill classifies itself have a class, but no error value: "panic" for a handler or an outbox publisher that panicked, "invalid_payload" for a payload that did not decode into the kind's Args, and "middleware" for middleware that returned nil without calling its next. A minor release may add a class: treat one that is not named here like any other failure.

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.

Example

This example registers a handler that is a struct with its dependencies, and gives its kind a timeout of its own.

package main

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

// mailer is the part of a mail service that the receipt handler uses.
type mailer interface {
	Send(ctx context.Context, to, subject string) error
}

// receiptHandler sends receipts. A handler that is a struct holds what it
// needs, such as the client of another service.
type receiptHandler struct {
	mail mailer
}

// Handle implements taskmill.Handler.
func (h receiptHandler) Handle(ctx context.Context, t *taskmill.Task[SendReceipt]) error {
	return h.mail.Send(ctx, t.Args.Email, fmt.Sprintf("Your receipt for order %d", t.Args.OrderID))
}

func main() {
	var mail mailer // the application's mail service
	var handlers taskmill.Handlers
	taskmill.AddHandler[SendReceipt](&handlers, receiptHandler{mail: mail}, &taskmill.HandlerOptions{
		Timeout: 30 * time.Second,
	})
	// NewWorker reports a mistake in the registrations, such as a kind
	// registered twice.
	_ = taskmill.WorkerConfig{Handlers: &handlers}
}

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.

The setup guide says when to call Migrate, and with which role.

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.

Example

This example shows what Permanent returns: an error that keeps its cause, and nil for a nil error.

package main

import (
	"errors"
	"fmt"

	"github.com/code19m/taskmill"
)

func main() {
	errNoEmail := errors.New("no email address")
	err := taskmill.Permanent(errNoEmail)
	fmt.Println(err)

	_, ok := errors.AsType[*taskmill.PermanentError](err)
	fmt.Println("a *PermanentError:", ok)
	fmt.Println("still the cause:", errors.Is(err, errNoEmail))
	fmt.Println("nil for nil:", taskmill.Permanent(nil) == nil)
}
Output:
permanent: no email address
a *PermanentError: true
still the cause: true
nil for nil: true

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. After a longer delay, the task becomes available within about a second of its new run time, while a maintainer runs. A task that always snoozes never becomes dead.

Example

This example shows what Snooze returns: an error that holds the delay.

package main

import (
	"errors"
	"fmt"
	"time"

	"github.com/code19m/taskmill"
)

func main() {
	err := taskmill.Snooze(90 * time.Second)
	fmt.Println(err)

	if snooze, ok := errors.AsType[*taskmill.SnoozeError](err); ok {
		fmt.Println("delay:", snooze.Delay)
	}
}
Output:
snooze for 1m30s
delay: 1m30s

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, and a worker drops the counts
	// that it could not write for 1 hour.
	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, in points of one minute.
	Since time.Time

	// Step is how much time each point covers, in whole minutes. Default: a
	// minute. Maximum: a day. Steps are counted from midnight UTC on 1
	// January 2000, whatever the time zone: a step of an hour starts on the
	// hour in UTC, and a step of a day at midnight UTC.
	Step time.Duration
}

ActivityParams selects the activity that Client.Activity returns. A field outside its limits is an error that wraps ErrInvalidArgument.

type Args

type Args interface {
	// Kind returns the task kind, such as "email.send", in 1 to 128
	// characters of valid UTF-8, with no NUL character. 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).

The guide to defining tasks says what to put in a payload, and how to change one later.

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 is the attempt that failed, counting from 1. For a note, it is
	// the number of attempts used so far, which may be 0.
	Attempt int

	// At is when the entry was recorded, by the database's clock.
	At time.Time

	// Message is the error's text, truncated to 4 KiB.
	Message string

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

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.

A task without a result fails, as after an error: HandleBatch returned nil, or fewer errors than tasks. So a handler that returns early completes no task that it did not run, and one that did all its work returns make([]error, len(tasks)), never nil.

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.

Register a batch handler with AddBatchHandler. The batch guide shows one, and says when a batch is worth it.

type BulkParams added in v0.2.0

type BulkParams struct {
	// Filter selects the tasks. Required: it must set at least one field.
	Filter TaskFilter

	// Cursor continues an action that stopped early, from its
	// [BulkResult.Next]. Empty means from the oldest task.
	Cursor string
}

BulkParams selects the tasks of a bulk action, such as Client.RetryMatching. Nil params, an empty filter, and a cursor that is not valid are errors that wrap ErrInvalidArgument.

type BulkResult added in v0.2.0

type BulkResult struct {
	// Changed is how many tasks it changed. If the action returns an error,
	// the batch it was in may have committed all the same, and is not
	// counted: at most 1,000 tasks more.
	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

	// Conflicts is how many canceled tasks a retry left as they were,
	// because another task holds their dedupe key: see [Client.Retry]. A
	// later run leaves them again while that task holds the key. Zero for
	// the other actions.
	Conflicts 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. Create one with NewClient. It is safe for concurrent use, and an application typically creates one per installation and shares it. It uses the pool it was given and never closes it.

Its methods, by what the caller wants to do:

The reads are bounded, so that a dashboard or a script cannot overload the database. The operations guide shows them at work.

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. params may be nil, for the last hour of every queue, in steps of a minute. 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 right away, and Client.Retry of the canceled task takes it back. It returns ErrNotFound if no task has the ID, and ErrInvalidState if the task already finished.

Cancel runs again by itself, up to 5 times in all, when another transaction changes the task under its locks, or when PostgreSQL ends its transaction to end a deadlock (SQLSTATE 40P01). So it returns that error only if the fifth try meets it too.

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. Like Client.Cancel, it runs again by itself, up to 5 times in all, when it loses to another transaction.

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, and returns the task's ID. opts may be nil: EnqueueOptions has the options and their defaults. If the options set a DedupeKey that is taken, Enqueue creates no task: the result holds the ID of the existing task, and its Duplicate is true. In a rare race that ID is 0: see EnqueueResult.ID.

The ClientConfig.EnqueueMiddleware runs around the enqueue. The enqueue notifies the workers of a task that may start now, so a worker with a free slot usually starts it within milliseconds.

It returns an error that wraps ErrInvalidArgument for nil args, for an option outside its limits, and for a payload that cannot be stored: Args and EnqueueOptions have the rules. To enqueue in the same transaction as the application's own writes, use Client.EnqueueTx.

If PostgreSQL ends the transaction to end a deadlock, which other transactions can open around a FIFO group's row or a dedupe key (SQLSTATE 40P01), Enqueue runs again by itself, up to 5 times in all: nothing of the try before was saved. Client.EnqueueTx cannot do that in the caller's transaction, and returns the error.

Example

This example enqueues a task that starts in 10 minutes at the earliest, and then before the other waiting tasks of its queue.

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, Email: "a@example.com"}, &taskmill.EnqueueOptions{
		RunAt:    time.Now().Add(10 * time.Minute),
		Priority: taskmill.PriorityHigh,
	})
	if err != nil {
		log.Fatal(err) // such as ErrInvalidArgument for an option outside its limits
	}
	log.Printf("enqueued task %d", res.ID)
}
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: all of them, or none if it returns an error. 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.

A call over these limits, or with a task that is not valid, is an error that wraps ErrInvalidArgument; for a task, the error says which one. A call with no params does nothing, and returns nil.

Like Client.Enqueue, it runs again by itself after a deadlock.

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. tx may be a transaction, a connection, or a pool, as for Client.EnqueueTx.

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, and workers see it from then on. opts may be nil. In all else it works like Client.Enqueue, and returns the same errors.

tx may be a transaction, a connection, or a pool: see Executor. A nil executor is an error that wraps ErrInvalidArgument. An option or a payload that fails taskmill's checks fails before any statement runs, so the transaction stays usable.

Example

This example enqueues a task in the transaction that saves its order: the task exists only if the order does.

package main

import (
	"context"
	"log"

	"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 main() {
	ctx := context.Background()
	var pool *pgxpool.Pool      // the application's pool
	var client *taskmill.Client // from taskmill.NewClient

	err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
		var orderID int64
		err := tx.QueryRow(ctx, "INSERT INTO orders (email) VALUES ($1) RETURNING id", "a@example.com").Scan(&orderID)
		if err != nil {
			return err
		}
		// If the enqueue fails, the order rolls back too.
		_, err = client.EnqueueTx(ctx, taskmill.Pgx(tx), SendReceipt{OrderID: orderID, Email: "a@example.com"}, nil)
		return err
	})
	if err != nil {
		log.Fatal(err)
	}
}

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.

Example

This example reads one task: where it is, and why its attempts failed.

package main

import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/code19m/taskmill"
)

func main() {
	ctx := context.Background()
	var client *taskmill.Client // from taskmill.NewClient
	var id int64                // from EnqueueResult.ID
	task, err := client.Get(ctx, id)
	if errors.Is(err, taskmill.ErrNotFound) {
		log.Print("the task is gone: deleted, or past its retention")
		return
	}
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("task %d (%s) is %s after %d of %d attempts", task.ID, task.Kind, task.State, task.Attempt, task.MaxAttempts)
	// The history holds the latest errors, oldest first. Code is empty for
	// an error that the handler returned in time.
	for _, e := range task.Errors {
		log.Printf("attempt %d at %s: %s %s", e.Attempt, e.At.Format(time.RFC3339), e.Code, e.Message)
	}
}

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. params may be nil, for the first page of every group. 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 the tasks that match params, one page at a time. params may be nil, for the first page of every task. A page holds every task in full, payloads included, unless ListParams.Summary is set.

A list is in one of two orders, which TaskFilter.States chooses:

  • A list of only dead tasks, only canceled tasks, or both is ordered by when the tasks finished, the latest first: by TaskInfo.FinalizedAt, and by ID, the highest first, among tasks that finished at the same time. A finish time that is infinite, as only an UPDATE by hand writes it, reads as the zero time, and comes before or after all others.
  • Every other list is ordered by ID, the newest task first.

A task's finish time is the start of the transaction that finished it, so tasks do not show up in the order of their finish times. A walk through the pages of a list in finish order can miss a task that finishes meanwhile. It can return a task twice, if the task is retried and finishes again meanwhile.

Each page's query is canceled after 5 seconds, so listing cannot load the database for longer: a list that needs more returns an error.

A list of dead or canceled tasks reads about the tasks it returns, however many tasks of other states the table holds. Two things make it read more. A page reads every task that shares a finish time with the task where it starts, or with the task where it ends. One bulk action, or one rescue by the maintainer, gives up to 1,000 tasks one finish time, so a page can read two such batches, and a transaction of the application that cancels more gives one finish time to all of them. And with no queue named, a page reads up to a page of each queue that holds such tasks: with hundreds of queues, name the queue. A filter by kind or FIFO group reads a queue's dead or canceled tasks until it has a page.

ListParams.FinishedSince and ListParams.FinishedBefore limit a list of dead or canceled tasks to those that finished in a range of time, which reaches a past period without the pages before it. A page then reads no task outside the range, so a filter by kind or FIFO group reads at most the tasks of the range.

A list in ID order reads about the tasks it returns where an index holds them newest first: with no filter, for the completed tasks of one queue or of all, and for the pending tasks of one queue's FIFO group. Other lists in ID order, such as one of a single unfinished state, or one that mixes dead tasks with other states, are as fast when their tasks are among the newest, or when the database expects few of them. Otherwise they read the newer tasks of every queue and state first, which on a very large table can reach the limit.

Example

This example prints the dead tasks of one queue with their last errors, the task that died last 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. Workers apply the pause within 10 seconds, and right away if they receive notifications. It never returns ErrNotFound: it creates the queue's settings if the queue has none.

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, ordered by name: 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. Workers apply it as fast as a pause, and like PauseQueue it never returns ErrNotFound.

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. It returns ErrNotFound for an unknown schedule.

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.

A canceled task takes back the dedupe key that its cancel freed, for the rest of the key's window, so that an enqueue of the key is a duplicate again. If another task took the key meanwhile and still holds it, Retry changes nothing and returns ErrConflict: the two would stand for the same work. A task whose window has ended takes no key, like any task that outlives its window.

It returns ErrNotFound if no task has the ID, and ErrInvalidState for tasks in other states. Like Client.Cancel, it runs again by itself, up to 5 times in all, when it loses to another transaction.

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. Like Client.Retry, it gives a canceled task its dedupe key back, and leaves a task whose key another task holds: it counts those in BulkResult.Conflicts, and returns no error for them. 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.

A call that returns an error may have done one batch more than it reports: if the commit of its last batch does not answer in those 5 seconds, or the connection breaks, the database may still commit it. Running the action again, or continuing from Next, is safe: the tasks that it changed no longer match.

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, ordered by name.

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 random pause of at most 50 milliseconds, 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 MaxRunning outside its limits 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, ordered by ID. A worker that stopped without unregistering is stale once it made no check-in for its LeaseDuration: see WorkerInfo.Stale. It disappears once it made none for 5 minutes, or for twice its LeaseDuration if that is longer: the maintainer removes it.

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. Default: none.
	EnqueueMiddleware []EnqueueMiddleware
}

ClientConfig configures a Client. The zero value is valid. NewClient reports a Schema that is not valid as an error that wraps ErrInvalidArgument.

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.

Add enqueue middleware in ClientConfig.EnqueueMiddleware. The middleware guide shows one that tags every task.

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, from [PriorityLow] to
	// [PriorityCritical]. Default: [PriorityNormal].
	Priority Priority

	// RunAt is the earliest time the task may start. Default: now. A task
	// with a later RunAt becomes available within about a second of that
	// time, while a maintainer runs. 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, and [Client.Retry] of the canceled task
	// takes it back. 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.

An enqueue returns an error that wraps ErrInvalidArgument for a field outside its limits. The queue and the group key must also be valid UTF-8, and neither they nor the metadata may hold a NUL character.

The enqueue guide shows each option at work.

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 is the task. Required.
	Args Args

	// Options are the task's options, as in [Client.Enqueue]. It may be nil.
	Options *EnqueueOptions
}

EnqueueParams is one task in a batch enqueue.

type EnqueueResult

type EnqueueResult struct {
	// ID identifies the task: the new one, or the existing one for a
	// duplicate.
	//
	// It is 0 for a duplicate whose existing task could not be read. That
	// can happen only when another transaction took the key while the
	// enqueue ran: the enqueue then reads the key a second time. The ID is 0
	// if the task that took the key was canceled or deleted meanwhile, or if
	// that read failed. [Client.Enqueue] and [Client.EnqueueMany] have
	// committed by then, so they log a failed read and return no error. In
	// the caller's transaction, the enqueue returns the error of a failed
	// read, so that the caller can roll back.
	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. The codes are part of the API and do not change. A minor release may add a code: treat one that is not named here like any other failure.

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 of the application that
	// the worker ran after the handler returned: a method of the handler's
	// error, such as Error on a nil pointer, or [RetryPolicy.Backoff]. After
	// a panic in that later code, the task is retried with the default
	// backoff, not with the kind's policy. The entry's Message holds the
	// panic's value and the stack trace.
	CodePanic ErrorCode = "panic"

	// CodeTimeout means the attempt ran longer than [HandlerOptions.Timeout],
	// and the handler then returned an error.
	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 took the
	// task within an hour of its [CodeNoHandler] note, so the task became
	// dead.
	CodeUnknownKind ErrorCode = "unknown_kind"

	// CodeInvalidRow means the task's row holds a value that taskmill never
	// writes, so the task became dead right away: metadata that is not a
	// JSON object of strings, a time of creation or a run time that is
	// infinite, or a lease token at its largest value. Neither the handler
	// nor the middleware ran. Another database role wrote such a row, or an
	// UPDATE by hand; only the lease token gets there by itself, after two
	// billion fetches of one task. A retry of the task ends the same way
	// until the row is corrected.
	CodeInvalidRow ErrorCode = "invalid_row"

	// CodeNoHandler marks a note, not a failure: a worker fetched the task
	// without a handler for its kind, and the task began to wait for one,
	// without using attempts. Such a worker snoozes the task 1 minute at a
	// time. If no worker with a handler takes it within 1 hour, the task
	// becomes dead, with the code [CodeUnknownKind]. The hour counts only
	// while this note is the last entry of the task's errors. 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.

The transactions guide shows an enqueue, a completion, and a cancel in the caller's transaction.

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: the delays are 1, 2, 4, and 8 seconds, and so on, and 1 hour from the 13th failed attempt on.

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 describes a FIFO group 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. It must not be negative. Default: 100.
	// Maximum: 1,000.
	Limit int

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

GroupParams selects and pages the FIFO groups that Client.Groups returns. A field outside its limits is an error that wraps ErrInvalidArgument.

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.

Register a handler with AddHandler. The guide to handling tasks says what a handler should return, and what happens on a panic or a timeout.

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. It
	// must not be negative. 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. Pass them to AddHandler or AddBatchHandler. The zero value keeps the defaults. NewWorker reports a value outside its limits, as an error that wraps ErrInvalidArgument.

The guide to handling tasks shows the options at work.

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. Empty means every task.
	Filter TaskFilter

	// FinishedSince limits the list to the tasks that finished at this time
	// or later: those whose [TaskInfo.FinalizedAt] is not before it. Zero
	// means no lower bound. Only a list in finish order takes it, which is a
	// list of only dead tasks, only canceled tasks, or both: see
	// [Client.List]. On any other list it is an error that wraps
	// [ErrInvalidArgument].
	//
	// The time is an instant: its location does not matter, and neither
	// does the time zone of the database or of the process. It must be a
	// time that PostgreSQL can store, from 4713 BC to 294276 AD, and it
	// must be before FinishedBefore if both are set.
	FinishedSince time.Time

	// FinishedBefore limits the list to the tasks that finished before this
	// time, under the rules of FinishedSince. Zero means no upper bound. A
	// task that finished at this very time is left out, so two ranges that
	// meet at a time share no task.
	FinishedBefore time.Time

	// Limit is the page size. It must not be negative. Default: 100.
	// Maximum: 1,000.
	Limit int

	// Cursor continues from a previous page's [ListResult.Next]. Empty means
	// the first page. Pass it with the filter and the range of finish times
	// that it came from: each of the two orders of [Client.List] has cursors
	// of its own, and a cursor of the other order, like any text that is not
	// a cursor, is an error that wraps [ErrInvalidArgument].
	Cursor string

	// Summary leaves out what makes a task large, for a list that shows one
	// line per task: each [TaskInfo] comes with a nil Payload, a nil
	// Metadata, and only the newest entry of its Errors. The database does
	// not read or send what is left out, so a page costs about the same
	// whatever its tasks hold. [TaskInfo.ScheduledFor] reads the metadata,
	// so it returns the zero time for such a task. Default: false, which
	// returns every field, as [Client.Get] does.
	Summary bool
}

ListParams filters and pages Client.List. A field outside its limits is an error that wraps ErrInvalidArgument.

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, in the order of its list: see Client.List.

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. Middleware does not run for a task that the worker ends without a handler: one of a kind that it has no handler for, or one whose row is invalid, which becomes dead with CodeInvalidRow.

Add middleware in WorkerConfig.Middleware. The middleware guide has examples.

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. Migrate reports a Schema that is not valid as an error that wraps ErrInvalidArgument.

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. An empty schema means "taskmill". A name that does not match the pattern of MigrateConfig.Schema is an error that wraps ErrInvalidArgument.

The recipe for migration tools shows the steps with goose, Atlas, and Flyway.

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
0005_worker_leases_and_freed_keys
0006_refused_rows

type PermanentError

type PermanentError struct {
	// Err is the handler's error. [errors.Is] and [errors.As] still find it.
	Err error
}

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

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

PgxQuerier is the part of pgx that taskmill uses: these two methods, and no other. pgx.Tx, *pgx.Conn, and *pgxpool.Pool implement it. An application's own type that wraps one of them, for example to trace statements, needs only these two methods to enqueue. For Client.CancelTx and Task.CompleteTx, it must also be a pgx.Tx, as Executor says.

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 the maintainer removes it: 5 minutes after its last check-in,
	// or twice its LeaseDuration after it if that is longer.
	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 stops at the longest [time.Duration], about 292 years.
	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. Read it with Client.Queues.

The monitoring page says which of these numbers to alert on, and at which values.

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. Each task of a batch counts. It must
	// not be negative, and is at most 2,147,483,647. Zero means no limit.
	MaxRunning int
}

QueueSettings are a queue's installation-wide settings, stored in the database. Change them with Client.UpdateQueue. 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. A delay of zero or less makes the
	// task due right away: the maintainer makes it available within about a
	// second. If Backoff 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. Set one for a kind in HandlerOptions.Retry. The default is the zero value of ExponentialBackoff.

The worker calls the policy each time a failed attempt leads to a retry, before it records the failure. So Backoff must return fast, with no I/O.

The guide to retries shows how to change the wait, and what happens to a task with no attempts left.

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

SQLQuerier is the part of database/sql that taskmill uses: these two methods, and no other. *sql.Tx, *sql.Conn, and *sql.DB implement it. An application's own type that wraps one of them needs only these two methods to enqueue. For Client.CancelTx and Task.CompleteTx, it must also have Commit and Rollback methods, as Executor says. 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.
	// Required.
	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. Required.
	Cron string

	// Location is the time zone the expression is read in. Default: UTC.
	// The time zones of the database and of the worker's process play no
	// part, except with time.Local: it is the zone of each worker's own
	// process, so workers in different zones read different timetables.
	Location *time.Location

	// Args is the task to enqueue, with the limits of any payload: see
	// [Args]. Required.
	Args Args

	// Options are the task's options. It 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.
	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 no maintainer has defined them for about a day. Until then a stored schedule keeps its state, such as a pause: a rolling deploy or a rollback in which some workers do not define it loses nothing.

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.

Set a worker's schedules in WorkerConfig.Schedules. NewWorker reports a schedule that is not valid as an error that wraps ErrInvalidArgument. The schedules guide shows a schedule from its timetable to its handler.

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()
			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 is the queue of the task that the schedule enqueues.
	Queue string

	// Kind is the kind of that task.
	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. Read them with Client.Settings, and change them with Client.UpdateSettings. Zero fields mean their defaults. A period shorter than its minimum is an error that wraps ErrInvalidArgument. A period is stored in whole microseconds, and the longest time.Duration, about 292 years, keeps tasks for good. The database refuses a period below the minimum or above 300 years, so SQL cannot store one either.

type SnoozeError

type SnoozeError struct {
	// Delay is how long the task waits before it runs again. Zero or less
	// means right away.
	Delay time.Duration
}

SnoozeError asks taskmill to run the task again after a delay, without counting the current attempt. Create one with Snooze. A snooze is not a failure, so it has no error class.

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.

Example

This example prints what each state allows: the task lifecycle as a table.

package main

import (
	"fmt"

	"github.com/code19m/taskmill"
)

func main() {
	states := []taskmill.State{
		taskmill.StateScheduled, taskmill.StatePending, taskmill.StateAvailable, taskmill.StateRunning,
		taskmill.StateRetryable, taskmill.StateCompleted, taskmill.StateDead, taskmill.StateCanceled,
	}
	fmt.Println("state      finished  retry  cancel  delete")
	for _, s := range states {
		fmt.Printf("%-10s %-9t %-6t %-7t %t\n", s, s.Finished(), s.CanRetry(), s.CanCancel(), s.CanDelete())
	}
}
Output:
state      finished  retry  cancel  delete
scheduled  false     false  true    true
pending    false     false  true    true
available  false     false  true    true
running    false     false  true    false
retryable  false     false  true    true
completed  true      false  false   true
dead       true      true   false   true
canceled   true      true   false   true

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 is how many times the task may run before it is dead, as
	// [EnqueueOptions.MaxAttempts] set it.
	MaxAttempts int

	// GroupKey is the key of the task's FIFO group. It is empty for a task
	// in no group.
	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]. It is
	// empty for a task whose row holds metadata that taskmill did not write
	// and cannot read: see [CodeInvalidRow].
	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. It also returns the zero time for a task of a list in summary, which comes without its metadata: see ListParams.Summary.

Example

This example reads the time that a schedule's run is for. A task that no schedule enqueued has none: a handler can fall back to RunAt then.

package main

import (
	"fmt"
	"time"

	"github.com/code19m/taskmill"
)

func main() {
	run := taskmill.TaskInfo{Metadata: map[string]string{
		taskmill.MetadataSchedule:     "nightly-receipts",
		taskmill.MetadataScheduledFor: "2026-11-16T03:00:00+01:00", // 03:00 in Berlin
	}}
	fmt.Println(run.ScheduledFor().Format(time.RFC3339))

	var other taskmill.TaskInfo // enqueued by the application, not by a schedule
	fmt.Println(other.ScheduledFor().IsZero())
}
Output:
2026-11-16T03:00:00+01:00
true

type Worker

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

Worker fetches tasks from its queues and runs their handlers. Create one with NewWorker, and run it with Worker.Run. 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.

A worker uses the pool of its Client, plus one connection of its own for notifications. Run may be called again after it returned, but not while it runs.

The guide to workers and queues shows how to choose the queues, limit how many tasks run, and stop a worker cleanly.

func NewWorker

func NewWorker(client *Client, cfg *WorkerConfig) (*Worker, error)

NewWorker returns a worker that uses client to reach the database. cfg may be nil: the zero WorkerConfig is valid. It reports a nil client, and 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. It is also an error until Run has read the settings of the worker's queues, which it does when it starts: the worker fetches no task before that. 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. The error wraps none of taskmill's error values.

The Kubernetes page has a probe and manifests to copy.

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.

Run fetches from no queue before it has read the queues' settings, so a paused queue stays paused and a QueueSettings.MaxRunning limit holds from the first fetch. If that read fails, Run logs it and reads again: 100 milliseconds later, then waiting twice as long each time, up to 10 seconds. Each read is given up after 10 seconds.

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. Default: none, so the
	// worker only takes part in maintenance. Required when Queues is set.
	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, 10 seconds by
	// default, and renews the leases of its running tasks then. A lease
	// starts when the task is taken, by the database's clock, not when the
	// fetch began. Minimum: 100 milliseconds. Default: 30 seconds.
	//
	// The worker stores it when it registers, and the installation judges
	// by it how long the worker may make no check-in. After one
	// LeaseDuration, [Client.Workers] and the dashboard show the worker as
	// stale. After two, but not before 5 minutes, the maintainer removes it
	// from the list of workers. If it still runs, it registers again at its
	// next check-in.
	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, ±10%, 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. When one of its own tasks ends, the worker fetches right
	// away.
	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.
	// Default: none.
	Middleware []Middleware

	// Schedules are recurring tasks that the maintainer enqueues. Each name
	// may appear once. Default: none.
	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.
	// The setup for each pooler is in
	// https://github.com/code19m/taskmill/blob/main/docs/production/connection-poolers.md.
	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, as it does for a field outside its limits.

The guide to workers and queues says which setting to use for which limit.

Example

This example runs a worker that reads two queues: 20 emails and 2 reports at the same time. When it stops, running tasks get 50 seconds to finish.

package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/code19m/taskmill"
)

func main() {
	var client *taskmill.Client    // from taskmill.NewClient
	var handlers taskmill.Handlers // with a handler for each kind of both queues
	worker, err := taskmill.NewWorker(client, &taskmill.WorkerConfig{
		Handlers: &handlers,
		Queues: map[string]taskmill.QueueOptions{
			"emails":  {Concurrency: 20},
			"reports": {Concurrency: 2},
		},
		// At least 10 seconds below the time that the platform gives a
		// stopping process: here, 60 seconds.
		DrainTimeout: 50 * time.Second,
	})
	if err != nil {
		log.Fatal(err) // ErrInvalidArgument: the configuration is not valid
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	if err := worker.Run(ctx); err != nil {
		log.Print(err)
	}
}

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

	// Stale reports that the worker made no check-in for its whole
	// [WorkerConfig.LeaseDuration], by the database's clock. It stopped
	// without unregistering, or it cannot reach the database: the leases of
	// its tasks have run out, and its [Worker.Health] fails. A worker of a
	// release that does not store its LeaseDuration is stale after 30
	// seconds without a check-in.
	Stale bool
}

WorkerInfo describes a worker process.

Directories

Path Synopsis
cmd
taskmill-ui command
Command taskmill-ui serves taskmill's dashboard as a program of its own, apart from the applications that use the installation.
Command taskmill-ui serves taskmill's dashboard as a program of its own, apart from the applications that use the installation.
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.
recovered
Package recovered formats the values of recovered panics.
Package recovered formats the values of recovered panics.
teardown
Package teardown drops the schema that a test or a benchmark worked in.
Package teardown drops the schema that a test or a benchmark worked in.
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 as an HTTP handler.
Package ui serves taskmill's dashboard as an HTTP handler.

Jump to

Keyboard shortcuts

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