taskmill

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 32 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

A PostgreSQL-backed task queue and transactional outbox for Go.

If your service already runs on PostgreSQL, your background tasks can live there too: one less system to operate, and tasks that commit or roll back together with your data.

  • Transactional. Enqueue inside your own transaction, with pgx or database/sql. If it rolls back, the task never existed.
  • Reliable. Every task runs at least once, with leases, heartbeats, and retries with backoff. Dead tasks are kept for inspection and retry. A crashed worker never loses a task.
  • Ordered when you need it. FIFO groups run tasks one at a time per key, for any number of keys, and halt on a dead task instead of skipping it.
  • Complete. Priorities, delays, deduplication, cron schedules, concurrency limits across all workers, batch handlers, cancellation, and pausing.
  • An outbox, too. Publish to Kafka, NATS, or RabbitMQ with the same transactional guarantee, in order per key.
  • Operable. A live web dashboard that you mount in your application, embed in your admin panel, or run on its own; an operations API, with bulk actions on every task that matches a filter; structured logs through log/slog; and OpenTelemetry traces and metrics from an optional module.
  • Small and fast. One direct dependency, pgx. One worker drained a backlog at over 31,000 tasks per second, and one relay published over 26,000 outbox messages per second. This was on an Apple M5 laptop with PostgreSQL 18 in Docker; see the benchmarks.

The dashboard, here showing the shop example.

Status: taskmill is new, with no known production users yet. Before v1.0.0, minor releases may change the API, and the changelog says how to migrate. See Upgrading.

Why taskmill?

taskmill is closest to River. Both keep tasks in PostgreSQL, use pgx, and enqueue in your own transaction. taskmill also includes FIFO ordering per key, concurrency limits across all workers, batch handlers, a transactional outbox, and a web interface, in one MIT-licensed module. River offers several of these only in its paid River Pro. Choose River if you need workflows, a command-line tool, or a long production record.

What taskmill is not

  • A workflow engine. Tasks do not depend on each other.
  • A message broker. The outbox hands messages to your broker.
  • Exactly-once across systems. Delivery is at least once, and consumers deduplicate.
  • For other databases. It runs on PostgreSQL only.

The design overview lists the rest.

Install

go get github.com/code19m/taskmill

taskmill needs Go 1.26 or newer and PostgreSQL 15 or newer (supported versions).

Quick start

// A task is a struct with a kind.
type SendReceipt struct {
    OrderID int64  `json:"order_id"`
    Email   string `json:"email"`
}

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

func main() {
    ctx := context.Background()
    pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
    if err != nil {
        log.Fatal(err)
    }

    // Create or upgrade the schema. Safe to run from every process.
    if err := taskmill.Migrate(ctx, pool, nil); err != nil {
        log.Fatal(err)
    }
    client, err := taskmill.NewClient(ctx, pool, nil)
    if err != nil {
        log.Fatal(err)
    }

    // Enqueue inside your own transaction: the order and its receipt commit
    // together, or not at all.
    err = pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
        // ... insert the order ...
        _, err := client.EnqueueTx(ctx, taskmill.Pgx(tx), SendReceipt{OrderID: 42, Email: "a@example.com"}, nil)
        return err
    })
    if err != nil {
        log.Fatal(err)
    }

    // Handle tasks of that kind.
    var handlers taskmill.Handlers
    taskmill.AddHandler(&handlers, taskmill.HandlerFunc[SendReceipt](
        func(ctx context.Context, t *taskmill.Task[SendReceipt]) error {
            return sendEmail(ctx, t.Args.Email, t.Args.OrderID)
        }), nil)

    worker, err := taskmill.NewWorker(client, &taskmill.WorkerConfig{Handlers: &handlers})
    if err != nil {
        log.Fatal(err)
    }

    // Run until SIGTERM, then drain running tasks.
    ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
    defer stop()
    if err := worker.Run(ctx); err != nil {
        log.Fatal(err)
    }
}

A runnable version is Example in example_test.go. For a whole application with its dashboard, run the shop example: make db, then go run ./examples/shop. A handler that returns an error is retried with backoff, by default for about 13 hours, and then the task becomes dead. taskmill.Permanent(err) makes it dead at once, and taskmill.Snooze(d) runs it again later without using an attempt.

Documentation

  • Guide: how to use every feature, test your code, and run in production, also on Kubernetes.
  • API reference on pkg.go.dev.
  • Design: the task lifecycle and its guarantees, and the storage schema.
  • Shop example: a small shop that uses most features, with its dashboard.
  • Benchmarks: performance targets and measured results.
  • Decisions: why taskmill is built the way it is.
Package What it is
taskmill The client, workers, schedules, and the operations API
taskmill/outbox The transactional outbox for message brokers
taskmill/ui The web interface, as an http.Handler
taskmill/cmd/taskmill-ui The web interface as a dashboard 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

Contributing

Contributions are welcome. Please read CONTRIBUTING.md before opening a pull request, and report security issues privately as described in SECURITY.md.

License

taskmill is released under the MIT License.

Documentation

Overview

Package taskmill is a PostgreSQL-backed task queue for Go.

Tasks are rows in PostgreSQL. An enqueue commits or rolls back with the application's own writes, and a worker that crashes never loses a task. Every task runs at least once: handlers must be idempotent, so that running a task twice has the same effect as running it once.

The guide at https://github.com/code19m/taskmill/blob/main/docs/guide.md covers every feature, testing, and running in production.

Defining tasks

A task is a struct that implements Args: its Kind names the handler that runs it, and its fields are stored as JSON. Implement ArgsWithDefaults to give a kind default EnqueueOptions, such as its queue.

Enqueueing

Client.Enqueue enqueues a task in its own transaction, and Client.EnqueueTx in the caller's, through a Pgx or SQL executor, so that the task exists only if the caller's transaction commits. Options delay a task, prioritize it, deduplicate it with a key, or put it in a FIFO group, whose tasks run one at a time, in order.

Handling tasks

Register a Handler or a BatchHandler for each kind with AddHandler or AddBatchHandler, and run them with a Worker. Returning nil completes a task. An error retries it with backoff, 25 attempts by default, after which it is dead: kept for an operator to inspect and Client.Retry. Permanent makes it dead at once, and Snooze runs it again later without using an attempt. Task.CompleteTx completes a task in the handler's own transaction, so its effects apply exactly once.

Operating

The Client lists, cancels, retries, and deletes tasks, pauses queues, and limits how many of a queue's tasks run at once. Package github.com/code19m/taskmill/ui serves these operations, except the limits, as a web interface, and package github.com/code19m/taskmill/outbox publishes messages to a broker with the transactional outbox pattern.

Testing

Package github.com/code19m/taskmill/taskmilltest runs tests against a real database, each in a schema of its own: it checks what code enqueues, and runs handlers the way a worker does.

Example

This example enqueues a task in the same transaction as the business data it belongs to, and runs a worker until the process is told to stop.

package main

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

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

	"github.com/code19m/taskmill"
)

// SendReceipt is the payload of an example task.
type SendReceipt struct {
	OrderID int64  `json:"order_id"`
	Email   string `json:"email"`
}

// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }

func deliverReceipt(context.Context, string, int64) error { return nil }

func main() {
	ctx := context.Background()
	pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	if err := taskmill.Migrate(ctx, pool, nil); err != nil {
		log.Fatal(err)
	}
	client, err := taskmill.NewClient(ctx, pool, nil)
	if err != nil {
		log.Fatal(err)
	}

	err = pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
		// ... insert the order in tx ...
		_, err := client.EnqueueTx(ctx, taskmill.Pgx(tx), SendReceipt{OrderID: 42, Email: "a@example.com"}, nil)
		return err
	})
	if err != nil {
		log.Fatal(err)
	}

	var handlers taskmill.Handlers
	taskmill.AddHandler(&handlers, taskmill.HandlerFunc[SendReceipt](
		func(ctx context.Context, t *taskmill.Task[SendReceipt]) error {
			return deliverReceipt(ctx, t.Args.Email, t.Args.OrderID)
		},
	), nil)

	// The worker serves the queues of its handlers' kinds: here the default
	// queue.
	worker, err := taskmill.NewWorker(client, &taskmill.WorkerConfig{Handlers: &handlers})
	if err != nil {
		log.Fatal(err)
	}
	ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
	defer stop()
	if err := worker.Run(ctx); err != nil {
		log.Print(err)
	}
}

Index

Examples

Constants

View Source
const DefaultQueue = "default"

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

Variables

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

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

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

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

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

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

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

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

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

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

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

Functions

func AddBatchHandler

func AddBatchHandler[A Args](hs *Handlers, h BatchHandler[A], opts *HandlerOptions)

AddBatchHandler registers h for the kind of A. opts may be nil. Mistakes, such as registering a kind twice, are reported by NewWorker.

Example

This example runs receipts in batches of up to 50.

package main

import (
	"context"

	"github.com/code19m/taskmill"
)

// SendReceipt is the payload of an example task.
type SendReceipt struct {
	OrderID int64  `json:"order_id"`
	Email   string `json:"email"`
}

// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }

func deliverReceipt(context.Context, string, int64) error { return nil }

// receiptMailer sends receipts in bulk.
type receiptMailer struct{}

func (receiptMailer) HandleBatch(ctx context.Context, tasks []*taskmill.Task[SendReceipt]) []error {
	errs := make([]error, len(tasks))
	for i, t := range tasks {
		errs[i] = deliverReceipt(ctx, t.Args.Email, t.Args.OrderID)
	}
	return errs
}

func main() {
	var handlers taskmill.Handlers
	taskmill.AddBatchHandler[SendReceipt](&handlers, receiptMailer{}, &taskmill.HandlerOptions{BatchSize: 50})
	_ = taskmill.WorkerConfig{Handlers: &handlers} // serves the kind's default queue
}

func AddHandler

func AddHandler[A Args](hs *Handlers, h Handler[A], opts *HandlerOptions)

AddHandler registers h for the kind of A. opts may be nil. Mistakes, such as registering a kind twice, are reported by NewWorker.

func Migrate

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

Migrate creates or upgrades taskmill's schema, and prepares the next week's history partitions. It is safe to run from several processes at once: one applies the migrations while the others wait. A schema that is up to date is left as it is, so Migrate then needs no privilege to change it, and a failure to prepare partitions is only logged. cfg may be nil.

func Permanent

func Permanent(err error) error

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

func Snooze

func Snooze(d time.Duration) error

Snooze returns an error that reschedules the task to run after d, without using an attempt. Use it when the task cannot proceed yet, for example while waiting for a rate limit to reset. A delay of zero or less makes the task available at once. A task that always snoozes never becomes dead.

Types

type Activity

type Activity struct {
	// At is when the step starts.
	At time.Time

	// Counts holds the most tasks counted in each state during the step,
	// except completed: the maintainer counts them every 10 seconds, with the
	// caps of [QueueInfo.Counts]. It is nil if no maintainer counted them, for
	// example while no worker ran.
	Counts map[State]int64

	// Completed and Failed are the attempts that succeeded and failed during
	// the step. Failed counts every failed attempt, whether its task is
	// retried or dead, including attempts whose workers lost their leases.
	// Workers write their counts every 10 seconds; a worker that crashes
	// loses its last few seconds of them.
	Completed, Failed int64
}

Activity is what happened during one step of time.

type ActivityParams

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

	// Since is when the period starts. Default: an hour ago. Activity is
	// kept for 24 hours.
	Since time.Time

	// Step is how much time each point covers, in whole minutes. Default: a
	// minute. Maximum: a day.
	Step time.Duration
}

ActivityParams selects the activity that Client.Activity returns.

type Args

type Args interface {
	// Kind returns the task kind, such as "email.send". It must not depend
	// on the value's fields: handler registration reads it from a zero value.
	Kind() string
}

Args is the payload of a task. Its kind selects the handler that runs it, and it is stored as JSON with encoding/json, at most 1 MiB.

Implement Kind on a value receiver and return a constant: producers and consumers agree on the kind. If a kind is renamed, tasks enqueued under the old name find no handler, and become dead after an hour.

type ArgsWithDefaults

type ArgsWithDefaults interface {
	Args

	// EnqueueDefaults returns the default options for this kind.
	EnqueueDefaults() EnqueueOptions
}

ArgsWithDefaults is implemented by Args that set default enqueue options for their kind. Options passed to an enqueue call override these defaults field by field, 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 serve it when WorkerConfig.Queues is empty.

type AttemptError

type AttemptError struct {
	Attempt int       `json:"attempt"`
	At      time.Time `json:"at"`

	// Message is the error's text, truncated to 4 KiB.
	Message string `json:"message"`

	// Code classifies the entries that taskmill itself recorded, and marks a
	// handler's error returned after its attempt timed out as [CodeTimeout].
	// It is empty for other errors returned by a handler.
	Code ErrorCode `json:"code,omitempty"`
}

AttemptError is one entry of a task's error history: why an attempt failed, or a note that taskmill recorded.

type BatchHandler

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

BatchHandler runs tasks of one kind in batches, for work that is cheaper in bulk, such as publishing messages to a broker. It returns one error per task, in the same order: nil completes that task, and an error fails it as a Handler's error would. Returning a shorter slice fails the tasks without an entry.

A batch takes one slot of its queue's concurrency. When a worker fetches a task of a batch kind, it fills that task's batch with more available tasks of the kind, so a batch kind can share a queue with other kinds.

ctx is canceled when the batch times out or the worker shuts down, with the cause ErrAttemptTimeout or ErrShutdown, but not when one of its tasks is canceled or loses its lease: the batch runs to the end, and then that task becomes canceled, or its result is discarded.

type BulkParams added in v0.2.0

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

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

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

type BulkResult added in v0.2.0

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

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

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

BulkResult reports what a bulk action did.

type Client

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

Client enqueues and manages tasks. It is safe for concurrent use, and an application typically creates one per installation and shares it.

func NewClient

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

NewClient returns a client that uses pool for its own statements. cfg may be nil. It fails with ErrSchemaOutdated if the schema was not migrated.

taskmill's statements rely on the READ COMMITTED isolation level, so NewClient fails with ErrInvalidArgument if the pool's default_transaction_isolation is another level; set it in the pool's ConnConfig.RuntimeParams. Transactions that callers pass to the Tx methods may use any level.

func (*Client) Activity

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

Activity returns the activity of the selected queues, one point per step, oldest first. A step in which nothing was recorded has no point, so a gap between points means that no worker ran. The query is canceled after 5 seconds, like Client.List.

func (*Client) Cancel

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

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

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.

func (*Client) Count added in v0.2.0

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

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

func (*Client) Delete

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

Delete deletes a task that is not running, including a completed task in history, and frees its dedupe key. Deleting the dead task that halts its FIFO group resumes the group. It returns ErrNotFound if no task has the ID, and ErrInvalidState for a running task; cancel it first.

func (*Client) DeleteMatching added in v0.2.0

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

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

func (*Client) Enqueue

func (c *Client) Enqueue(ctx context.Context, args Args, opts *EnqueueOptions) (EnqueueResult, error)

Enqueue enqueues one task in its own transaction. opts may be nil.

Example (Deduplicated)

This example deduplicates an enqueue: enqueueing the same key again within the window reports the existing task instead of creating another.

package main

import (
	"context"
	"log"
	"time"

	"github.com/code19m/taskmill"
)

// SendReceipt is the payload of an example task.
type SendReceipt struct {
	OrderID int64  `json:"order_id"`
	Email   string `json:"email"`
}

// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }

func main() {
	ctx := context.Background()
	var client *taskmill.Client // from taskmill.NewClient
	res, err := client.Enqueue(ctx, SendReceipt{OrderID: 7}, &taskmill.EnqueueOptions{
		DedupeKey:    "receipt-7",
		DedupeWindow: 24 * time.Hour,
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.Duplicate {
		log.Printf("already enqueued as task %d", res.ID)
	}
}

func (*Client) EnqueueMany

func (c *Client) EnqueueMany(ctx context.Context, params []EnqueueParams) ([]EnqueueResult, error)

EnqueueMany enqueues several tasks in one round trip and one transaction. Results are in the same order as params. One call takes at most 10,000 tasks, with at most 64 MiB of payload and metadata in all.

func (*Client) EnqueueManyTx

func (c *Client) EnqueueManyTx(ctx context.Context, tx Executor, params []EnqueueParams) ([]EnqueueResult, error)

EnqueueManyTx is Client.EnqueueMany in the caller's transaction.

func (*Client) EnqueueTx

func (c *Client) EnqueueTx(ctx context.Context, tx Executor, args Args, opts *EnqueueOptions) (EnqueueResult, error)

EnqueueTx enqueues one task in the caller's transaction: the task exists only if that transaction commits. opts may be nil.

func (*Client) Get

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

Get returns a task by ID, whether it is unfinished, finished, or in history. It returns ErrNotFound if no such task exists.

func (*Client) Groups

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

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

func (*Client) List

func (c *Client) List(ctx context.Context, params *ListParams) (*ListResult, error)

List returns tasks that match params, newest first, one page at a time. Each page's query is canceled after 5 seconds, so listing cannot overload the database; on a very large table, a filter that matches few tasks can reach that limit and return an error.

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.

func (*Client) PauseSchedule

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

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

func (*Client) Queues

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

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

func (*Client) ResumeQueue

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

ResumeQueue undoes Client.PauseQueue.

func (*Client) ResumeSchedule

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

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

func (*Client) Retry

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

Retry makes a dead or canceled task available again, with a fresh set of attempts. Retrying the dead task that halts its FIFO group resumes the group; another task of a group waits until the group's current head finishes, and then runs before the group's tasks that were enqueued after it. It returns ErrNotFound if no task has the ID, and ErrInvalidState for tasks in other states.

func (*Client) RetryMatching added in v0.2.0

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

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

It goes through the tasks enqueued before it started, oldest first, in batches of 1,000, each in a short transaction of its own. It reads each task once, so it retries a task at most once, even if the task fails again meanwhile, and it ends however fast new tasks arrive. It skips the tasks, the FIFO groups, and the dedupe keys that other transactions hold at that moment, never waiting while it holds rows. If ctx ends first, it finishes the batch it is in, for at most 5 seconds, and returns what it did, with an error and BulkResult.Next to go on; each batch commits whole or not at all.

Example

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

package main

import (
	"context"
	"log"

	"github.com/code19m/taskmill"
)

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

func (*Client) RunSchedule

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

RunSchedule runs a schedule once now, in addition to its timetable. The maintainer enqueues the run within about a second, if it defines the schedule, with the schedule's options, and the task's RunAt is the time of the request. The next regular run stays as it was. It returns ErrNotFound for an unknown schedule, and ErrInvalidState for a paused one.

func (*Client) Schedules

func (c *Client) Schedules(ctx context.Context) ([]ScheduleInfo, error)

Schedules returns every schedule stored in the database.

func (*Client) Settings

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

Settings returns the installation-wide settings.

func (*Client) UpdateQueue

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

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

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

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

func (*Client) UpdateSettings

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

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

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

func (*Client) Workers

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

Workers returns the registered worker processes. A worker that stopped without unregistering disappears after 5 minutes without heartbeats.

type ClientConfig

type ClientConfig struct {
	// Schema is the PostgreSQL schema that holds taskmill's tables. It must
	// match ^[a-z_][a-z0-9_]{0,62}$. Default: "taskmill".
	Schema string

	// Logger receives the logs of the client and of its workers.
	// Default: logs are discarded.
	Logger *slog.Logger

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

ClientConfig configures a Client. The zero value is valid.

type EnqueueMiddleware added in v0.2.0

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

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

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

Example

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

package main

import (
	"context"
	"log"

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

	"github.com/code19m/taskmill"
)

type requestIDKey struct{}

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

type EnqueueOptions

type EnqueueOptions struct {
	// Queue is the queue to enqueue into, at most 128 characters.
	// Default: [DefaultQueue].
	Queue string

	// Priority orders tasks within the queue. Default: [PriorityNormal].
	Priority Priority

	// RunAt is the earliest time the task may start. Default: now.
	RunAt time.Time

	// MaxAttempts is how many times the task may run, from 1 to 10,000.
	// Default: 25, which with the default backoff spans about 13 hours.
	MaxAttempts int

	// GroupKey puts the task in a FIFO group: tasks with the same key in the
	// same queue run one at a time, in enqueue order. A group's dead task
	// halts it until an operator retries or deletes that task. At most 256
	// characters. Default: none.
	GroupKey string

	// DedupeKey makes the enqueue idempotent: while the key's window lasts,
	// enqueueing the same kind with the same key in the same queue creates no
	// new task, and reports the existing one. Canceling or deleting the task
	// frees the key at once. Default: none.
	DedupeKey string

	// DedupeWindow is how long DedupeKey blocks duplicates. Default: 24 hours.
	DedupeWindow time.Duration

	// Metadata is stored with the task and passed to its handler, for
	// example for tracing. Encoded as JSON, it may take at most 64 KiB,
	// including what [EnqueueMiddleware] adds. Default: none.
	Metadata map[string]string
}

EnqueueOptions control how a task is enqueued. Zero values mean "not set": a field set in the call wins over the kind's defaults (see ArgsWithDefaults), which win over taskmill's defaults. Metadata merges key by key instead: the call's keys win over the same keys of the defaults, and the other keys of both are kept.

Example (FifoGroup)

This example runs tasks of one FIFO group one at a time, in order.

package main

import (
	"context"
	"log"

	"github.com/code19m/taskmill"
)

// SendReceipt is the payload of an example task.
type SendReceipt struct {
	OrderID int64  `json:"order_id"`
	Email   string `json:"email"`
}

// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }

func main() {
	ctx := context.Background()
	var client *taskmill.Client // from taskmill.NewClient
	for _, entry := range []int64{1, 2, 3} {
		_, err := client.Enqueue(ctx, SendReceipt{OrderID: entry}, &taskmill.EnqueueOptions{GroupKey: "customer-7"})
		if err != nil {
			log.Fatal(err)
		}
	}
}

type EnqueueParams

type EnqueueParams struct {
	Args    Args
	Options *EnqueueOptions
}

EnqueueParams is one task in a batch enqueue. Options may be nil.

type EnqueueResult

type EnqueueResult struct {
	// ID identifies the task: the new one, or the existing one for a
	// duplicate.
	ID int64

	// Duplicate reports that the DedupeKey was already taken, so no task was
	// created.
	Duplicate bool
}

EnqueueResult reports the outcome of enqueueing one task.

type EnqueueTask added in v0.2.0

type EnqueueTask struct {
	Queue string
	Kind  string

	// Metadata holds the task's metadata, from [EnqueueOptions.Metadata]. It
	// is never nil, and middleware may change it before calling next.
	Metadata map[string]string

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

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

type ErrorCode

type ErrorCode string

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

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

	// CodePanic means the handler panicked.
	CodePanic ErrorCode = "panic"

	// CodeTimeout means the attempt ran longer than [HandlerOptions.Timeout].
	CodeTimeout ErrorCode = "timeout"

	// CodeInvalidPayload means the payload did not decode into the kind's
	// Args, so the task became dead at once.
	CodeInvalidPayload ErrorCode = "invalid_payload"

	// CodeUnknownKind means no worker with a handler for the kind appeared
	// within an hour, so the task became dead.
	CodeUnknownKind ErrorCode = "unknown_kind"

	// CodeNoHandler marks a note, not a failure: a worker met the task
	// without a handler for its kind, and the task began to wait for one,
	// without using attempts.
	CodeNoHandler ErrorCode = "no_handler"
)

Error codes.

type Executor

type Executor interface {
	// contains filtered or unexported methods
}

Executor runs taskmill's statements on a transaction or connection that the caller owns, so that they commit or roll back with the caller's own work. Create one with Pgx or SQL.

The enqueue methods accept a transaction, a connection, or a pool. Client.CancelTx and Task.CompleteTx run several statements that must commit together, so they need a transaction: a pgx.Tx, a *sql.Tx, or a type with Commit and Rollback methods, such as *sqlx.Tx. They return ErrInvalidArgument for anything else.

Executor is sealed: only this package implements it, which lets its methods change without breaking callers.

func Pgx

func Pgx(q PgxQuerier) Executor

Pgx returns an Executor that runs statements on q, typically a pgx.Tx.

func SQL

func SQL(q SQLQuerier) Executor

SQL returns an Executor that runs statements on q, typically a *sql.Tx.

Libraries built on database/sql work through their underlying transaction: with bun, pass tx.Tx, because bun rewrites query placeholders itself.

Example

This example enqueues through database/sql, as bun, sqlx, and plain database/sql code do.

package main

import (
	"context"
	"database/sql"
	"log"
	"os"

	"github.com/code19m/taskmill"
)

// SendReceipt is the payload of an example task.
type SendReceipt struct {
	OrderID int64  `json:"order_id"`
	Email   string `json:"email"`
}

// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }

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

	// The "pgx" driver comes from: import _ "github.com/jackc/pgx/v5/stdlib"
	db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	if err := enqueueWithSQL(ctx, db, client); err != nil {
		log.Fatal(err)
	}
}

func enqueueWithSQL(ctx context.Context, db *sql.DB, client *taskmill.Client) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback() }()

	if _, err := client.EnqueueTx(ctx, taskmill.SQL(tx), SendReceipt{OrderID: 7}, nil); err != nil {
		return err
	}
	return tx.Commit()
}

type ExponentialBackoff

type ExponentialBackoff struct {
	Base time.Duration
	Max  time.Duration
}

ExponentialBackoff doubles the delay after each failed attempt, from Base up to Max, and spreads retries out with ±10% random jitter, so a delay can reach 10% above Max. The zero value uses a base of 1 second and a maximum of 1 hour.

func (ExponentialBackoff) Backoff

func (b ExponentialBackoff) Backoff(attempt int) time.Duration

Backoff implements RetryPolicy.

type GroupInfo

type GroupInfo struct {
	Queue string
	Key   string

	// Tasks is how many tasks the group counts: its unfinished tasks, and
	// the dead task that halts it, if any. A group halted by its only task
	// counts 1.
	Tasks int

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

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

type GroupParams

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

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

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

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

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

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

type GroupsResult added in v0.3.0

type GroupsResult struct {
	Groups []GroupInfo

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

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

type Handler

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

Handler runs tasks of one kind.

Returning nil completes the task. Returning an error fails the attempt: the task is retried with backoff until it runs out of attempts. Wrap the error with Permanent to make the task dead at once, or return Snooze to run it again later without using an attempt.

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

type HandlerFunc

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

HandlerFunc adapts a function to the Handler interface.

Example

This example shows the errors a handler returns to control retries.

package main

import (
	"context"
	"errors"
	"time"

	"github.com/code19m/taskmill"
)

// SendReceipt is the payload of an example task.
type SendReceipt struct {
	OrderID int64  `json:"order_id"`
	Email   string `json:"email"`
}

// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }

func deliverReceipt(context.Context, string, int64) error { return nil }

func main() {
	handler := taskmill.HandlerFunc[SendReceipt](func(ctx context.Context, t *taskmill.Task[SendReceipt]) error {
		if t.Args.Email == "" {
			return taskmill.Permanent(errors.New("no email address")) // dead at once
		}
		if rateLimited() {
			return taskmill.Snooze(time.Minute) // later, without using an attempt
		}
		return deliverReceipt(ctx, t.Args.Email, t.Args.OrderID) // retried with backoff on error
	})
	var handlers taskmill.Handlers
	taskmill.AddHandler(&handlers, handler, &taskmill.HandlerOptions{Timeout: 30 * time.Second})
}

func rateLimited() bool { return false }

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. Default: 1 minute.
	Timeout time.Duration

	// Retry decides the delay before each retry. A task whose worker lost its
	// lease is retried with the default instead, because the maintainer that
	// rescues it knows no handler's options. Default: [ExponentialBackoff]{}.
	Retry RetryPolicy

	// BatchSize is the most tasks a [BatchHandler] receives at once.
	// Default: 100. Maximum: 1,000. Ignored for other handlers.
	BatchSize int

	// DiscardCompleted deletes completed tasks of the kind at once, instead
	// of keeping them in history, for high-volume kinds whose history nobody
	// reads.
	DiscardCompleted bool
}

HandlerOptions configure how a worker runs one kind.

type Handlers

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

Handlers maps task kinds to their handlers. Register handlers with AddHandler or AddBatchHandler before passing Handlers to NewWorker. The zero value is an empty set; it is not safe for concurrent use.

type ListParams

type ListParams struct {
	// Filter selects the tasks. Its zero value selects every task.
	Filter TaskFilter

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

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

ListParams filters and pages Client.List.

type ListResult

type ListResult struct {
	Tasks []TaskInfo

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

ListResult is one page of tasks, newest first.

type Middleware

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

Middleware wraps the execution of an attempt, for logging, metrics, or tracing. It must call next at most once, and must not modify task. Returning without calling next fails the attempt with the returned error, or with an error that says so if it returns nil: the task is retried with backoff, as after a handler's error, and the middleware outside sees that error from its next. A handler's panic reaches middleware as an error. For a batch handler, middleware runs once per task, but the context it passes to next does not reach the handler.

Example

This example logs every attempt with its duration, as tracing and metrics middleware would measure it.

package main

import (
	"context"
	"log"
	"time"

	"github.com/code19m/taskmill"
)

func main() {
	logAttempts := taskmill.Middleware(func(ctx context.Context, task *taskmill.TaskInfo, next func(context.Context) error) error {
		start := time.Now()
		err := next(ctx)
		log.Printf("task %d (%s), attempt %d: %v after %s", task.ID, task.Kind, task.Attempt, err, time.Since(start))
		return err
	})
	var client *taskmill.Client // from taskmill.NewClient
	var handlers taskmill.Handlers
	_, err := taskmill.NewWorker(client, &taskmill.WorkerConfig{
		Handlers:   &handlers,
		Middleware: []taskmill.Middleware{logAttempts},
	})
	if err != nil {
		log.Fatal(err)
	}
}

type MigrateConfig

type MigrateConfig struct {
	// Schema is the PostgreSQL schema to migrate. It must match
	// ^[a-z_][a-z0-9_]{0,62}$. Default: "taskmill".
	Schema string

	// Logger receives one log line per applied migration, and a warning if
	// partitions cannot be prepared. Default: logs are discarded.
	Logger *slog.Logger
}

MigrateConfig configures Migrate. The zero value is valid.

type Migration

type Migration struct {
	Version int
	Name    string
	SQL     string
}

Migration is one versioned schema change, for teams that apply migrations with their own tools. Migrations returns them in order: first the bootstrap, version 0, which creates the schema and the migrations table, then every versioned migration. Apply them in order, each in a transaction, and record every version above 0, so that NewClient finds the schema up to date:

INSERT INTO <schema>.migrations (version, name) VALUES (<Version>, '<Name>')

func Migrations

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

Migrations returns every migration for schema, in order. Teams that use their own migration tools apply these instead of calling Migrate. The maintainer then creates the daily history partitions when workers start, which needs the workers' role to own the taskmill tables.

Example

This example prints the migrations, for teams that apply them with their own migration tool.

package main

import (
	"fmt"
	"log"

	"github.com/code19m/taskmill"
)

func main() {
	ms, err := taskmill.Migrations("taskmill")
	if err != nil {
		log.Fatal(err)
	}
	for _, m := range ms {
		fmt.Printf("%04d_%s\n", m.Version, m.Name)
	}
}
Output:
0000_bootstrap
0001_initial
0002_queue_lag
0003_halted_groups

type PermanentError

type PermanentError struct {
	Err error
}

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

func (*PermanentError) Error

func (e *PermanentError) Error() string

Error implements the error interface.

func (*PermanentError) Unwrap

func (e *PermanentError) Unwrap() error

Unwrap returns the wrapped error.

type PgxQuerier

type PgxQuerier interface {
	Exec(ctx context.Context, query string, args ...any) (pgconn.CommandTag, error)
	Query(ctx context.Context, query string, args ...any) (pgx.Rows, error)
	QueryRow(ctx context.Context, query string, args ...any) pgx.Row
}

PgxQuerier is the part of pgx that taskmill uses. pgx.Tx, *pgx.Conn, and *pgxpool.Pool implement it.

type Priority

type Priority int16

Priority orders tasks within a queue: higher priorities start first. The zero value means "not set" and resolves to PriorityNormal.

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   bool

	// Workers counts the workers registered to serve the queue. A worker
	// that stopped without unregistering, such as after a crash, counts
	// until it is removed, 5 minutes after its last heartbeat.
	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
	// read high: a task that finished since still counts.
	Lag time.Duration
}

QueueInfo describes a queue: its settings, its workers, and its latest statistics, which the maintainer refreshes every 10 seconds.

type QueueOptions

type QueueOptions struct {
	// Concurrency is how many of the queue's tasks this process runs at once.
	// A batch counts as one. Default: 10.
	Concurrency int
}

QueueOptions configure how one worker process serves one queue. Installation-wide settings, such as a concurrency limit, are QueueSettings.

type QueueSettings

type QueueSettings struct {
	// MaxRunning caps the tasks of the queue running at once across all
	// workers of the installation. Zero means no limit.
	MaxRunning int
}

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

type RetryPolicy

type RetryPolicy interface {
	// Backoff returns the delay before the retry that follows the given
	// failed attempt, counting from 1.
	Backoff(attempt int) time.Duration
}

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

type SQLQuerier

type SQLQuerier interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

SQLQuerier is the part of database/sql that taskmill uses. *sql.Tx, *sql.Conn, and *sql.DB implement it. The connection must use pgx's database/sql driver, github.com/jackc/pgx/v5/stdlib.

type Schedule

type Schedule struct {
	// Name identifies the schedule. Schedules are kept in the database by
	// name, so renaming one creates a new schedule.
	Name string

	// Cron is a five-field cron expression, such as "0 3 * * *", or one of
	// the macros @yearly, @annually, @monthly, @weekly, @daily, @midnight,
	// and @hourly.
	Cron string

	// Location is the time zone the expression is read in. Default: UTC.
	Location *time.Location

	// Args and Options describe the task to enqueue; Options may be nil.
	// The schedule sets the run time and the dedupe key itself, to enqueue
	// each run once, so [NewWorker] rejects Options that set RunAt,
	// DedupeKey, or DedupeWindow.
	Args    Args
	Options *EnqueueOptions
}

Schedule enqueues a task on a cron schedule, once per scheduled time across all workers. Define the same schedules on every worker that takes part in the maintainer election: the elected maintainer runs its own definitions. If it defines any, it also deletes the stored schedules that it does not define once they have not run or changed for a day.

Runs that are missed while no maintainer runs, or while the schedule is paused, collapse into one run. The expression is read on the wall clock of Location, so daylight saving time behaves as in classic cron. The task's RunAt is the time it was scheduled for.

Example

This example runs a task every night at 03:00 Berlin time.

package main

import (
	"context"
	"log"
	"time"

	"github.com/code19m/taskmill"
)

// SendReceipt is the payload of an example task.
type SendReceipt struct {
	OrderID int64  `json:"order_id"`
	Email   string `json:"email"`
}

// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }

func deliverReceipt(context.Context, string, int64) error { return nil }

func main() {
	var client *taskmill.Client // from taskmill.NewClient
	var handlers taskmill.Handlers
	taskmill.AddHandler(&handlers, taskmill.HandlerFunc[SendReceipt](
		func(ctx context.Context, t *taskmill.Task[SendReceipt]) error {
			// t.RunAt is the night the run is for.
			return deliverReceipt(ctx, t.Args.Email, t.Args.OrderID)
		},
	), nil)
	berlin, err := time.LoadLocation("Europe/Berlin")
	if err != nil {
		log.Fatal(err)
	}
	_, err = taskmill.NewWorker(client, &taskmill.WorkerConfig{
		Handlers: &handlers,
		Schedules: []taskmill.Schedule{
			{Name: "nightly-receipts", Cron: "0 3 * * *", Location: berlin, Args: SendReceipt{}},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
}

type ScheduleInfo

type ScheduleInfo struct {
	Name      string
	Queue     string
	Kind      string
	Cron      string
	Location  string
	NextRunAt time.Time
	LastRunAt time.Time // zero if it never ran
	Paused    bool
}

ScheduleInfo describes a schedule and its state.

type Settings

type Settings struct {
	// HistoryRetention is how long completed tasks stay in history, at
	// least: history is dropped a whole UTC day at a time, so a task stays
	// up to a day longer. Minimum: 1 hour. Default: 7 days.
	HistoryRetention time.Duration

	// DeadRetention is how long dead and canceled tasks are kept for
	// operators to inspect and retry. A dead task that halts its FIFO group
	// is kept until it is retried or deleted. Minimum: 1 hour. Default: 30
	// days.
	DeadRetention time.Duration
}

Settings are the installation-wide settings, stored in the database and applied by the maintainer. Zero fields mean their defaults.

type SnoozeError

type SnoozeError struct {
	Delay time.Duration
}

SnoozeError asks taskmill to run the task again after a delay, without counting the current attempt.

func (*SnoozeError) Error

func (e *SnoozeError) Error() string

Error implements the error interface.

type State

type State string

State is the lifecycle state of a task. The lifecycle and its guarantees are described in https://github.com/code19m/taskmill/blob/main/docs/design/task-lifecycle.md.

const (
	StateScheduled State = "scheduled" // waiting for its run time
	StatePending   State = "pending"   // waiting behind the head of its FIFO group
	StateAvailable State = "available" // ready, waiting for a worker
	StateRunning   State = "running"   // leased by an attempt
	StateRetryable State = "retryable" // failed, waiting for its backoff
	StateCompleted State = "completed" // its handler succeeded
	StateDead      State = "dead"      // will not run again unless an operator retries it
	StateCanceled  State = "canceled"  // canceled on request
)

Task states.

func (State) CanCancel added in v0.2.0

func (s State) CanCancel() bool

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

func (State) CanDelete added in v0.2.0

func (s State) CanDelete() bool

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

func (State) CanRetry added in v0.2.0

func (s State) CanRetry() bool

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

func (State) Finished

func (s State) Finished() bool

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

type Task

type Task[A Args] struct {
	TaskInfo

	Args A
	// contains filtered or unexported fields
}

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

func (*Task[A]) CompleteTx

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

CompleteTx completes the task inside the caller's transaction, so that the handler's own writes and the completion commit together or not at all. It returns ErrLeaseLost if another attempt took the task over; return that error, so that the transaction rolls back.

After CompleteTx, the handler should commit and return nil. If the handler returns an error after its transaction committed, the task stays completed and the error is only logged; if the transaction rolled back, the error fails the attempt as usual. Returning nil after a rollback records nothing: once the task's lease expires, the maintainer rescues it as a failed attempt, with the code lease_lost.

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.

type TaskInfo

type TaskInfo struct {
	ID       int64
	Queue    string
	Kind     string
	State    State
	Priority Priority

	// Attempt is the number of attempts used. In a handler, it is the
	// current attempt, counting from 1. A snooze gives its attempt back, and
	// [Client.Retry] starts over from 0.
	Attempt     int
	MaxAttempts int

	GroupKey string

	// Metadata holds the tags from [EnqueueOptions.Metadata] and
	// [EnqueueMiddleware].
	Metadata map[string]string

	// Payload is the task's Args as stored, in JSON.
	Payload json.RawMessage

	// Errors is the task's error history, oldest first: at most the 20 most
	// recent entries.
	Errors []AttemptError

	CreatedAt time.Time

	// RunAt is the earliest time the task may start: for a retryable or
	// snoozed task, when it runs again, and for a task that a [Schedule]
	// enqueued, the time it was scheduled for.
	RunAt time.Time

	AttemptedAt time.Time // zero if never attempted
	FinalizedAt time.Time // zero until completed, dead, or canceled
}

TaskInfo describes a task: where it is in its lifecycle and what happened to its attempts.

type Worker

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

Worker fetches tasks from its queues and runs their handlers. One worker per process is typical; it also takes part in electing the maintainer, which promotes due tasks, rescues expired leases, runs schedules, and applies retention.

func NewWorker

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

NewWorker returns a worker that uses client to reach the database. It reports invalid configuration, 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 heartbeat succeeded within LeaseDuration, and otherwise an error that says why. A worker out of touch for that long can no longer keep its tasks' leases. Health reads only memory, so a readiness probe may call it often. It fails while the database is out of reach, which restarting the worker does not fix: do not base a liveness probe on it.

func (*Worker) Run

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

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

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 concurrency limits, but not FIFO order. It does not need Run to be running, which makes it the tool for tests. If ctx is canceled before the handler returns, the handler's context is canceled too, and the task goes back to its queue without using an attempt.

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.

type WorkerConfig

type WorkerConfig struct {
	// Handlers runs the tasks this worker fetches.
	Handlers *Handlers

	// Queues lists the queues to fetch from, with per-process options.
	// Default: the default queue of every registered kind, from
	// [ArgsWithDefaults] or else [DefaultQueue], with default options. If
	// Queues leaves out a registered kind's default queue, Run logs a warning
	// when it starts: tasks enqueued with the kind's defaults would wait for
	// another worker.
	Queues map[string]QueueOptions

	// LeaseDuration is how long a fetched task stays owned without a
	// heartbeat. Heartbeats are sent every third of it. Minimum: 100
	// milliseconds. Default: 30 seconds.
	LeaseDuration time.Duration

	// PollInterval is how often idle queues are checked while the
	// maintainer's heartbeats do not reach the worker: until the first one,
	// within 5 seconds of the start, once none came for 15 seconds, and
	// while no maintainer of this version or later runs. While they arrive,
	// every 5 seconds, notifications wake the worker, and the maintainer
	// wakes each queue whose next task waited more than a second, so idle
	// queues are checked only once a minute. So a task whose notification
	// came too early or was lost starts within about 2 seconds while
	// heartbeats arrive, within about 16 seconds if the maintainer or the
	// notification connection fails without a word, and within PollInterval
	// while no maintainer of this version runs. Default: 1 second.
	PollInterval time.Duration

	// DrainTimeout is how long Run waits for running tasks after its context
	// is canceled, before canceling their contexts and, 5 seconds later,
	// releasing them. Keep it at least 10 seconds below the time the platform
	// gives a stopping process. Default: 20 seconds.
	DrainTimeout time.Duration

	// Middleware wraps every attempt, in order: the first is the outermost.
	Middleware []Middleware

	// Schedules are recurring tasks that the maintainer enqueues.
	Schedules []Schedule

	// NoMaintainer keeps this worker out of the maintainer election. At least
	// one worker of an installation must take part.
	NoMaintainer bool

	// ListenConfig is the connection that receives notifications. Set it to
	// a direct connection when the pool goes through a transaction-pooling
	// proxy, which cannot deliver them: without it, the worker finds that
	// out when it starts, logs an error, and polls every PollInterval.
	// Create it with [pgx.ParseConfig]. Default: the pool's configuration.
	ListenConfig *pgx.ConnConfig
}

WorkerConfig configures a Worker. The zero value is valid: a worker without handlers only takes part in maintenance.

type WorkerInfo

type WorkerInfo struct {
	ID          string
	Hostname    string
	Version     string // taskmill's version in the worker's binary
	Queues      []string
	Kinds       []string // the kinds it has handlers for
	StartedAt   time.Time
	HeartbeatAt time.Time
	Maintainer  bool // the worker is the elected maintainer
}

WorkerInfo describes a worker process.

Directories

Path Synopsis
cmd
taskmill-ui command
Command taskmill-ui serves taskmill's web interface on its own: a dashboard for an installation, run apart from the applications that use it.
Command taskmill-ui serves taskmill's web interface on its own: a dashboard for an installation, run apart from the applications that use it.
examples
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.
internal
argkind
Package argkind reads what a zero value of an Args type says about it.
Package argkind reads what a zero value of an Args type says about it.
cmd/bench command
Command bench measures taskmill against the targets in docs/benchmarks.md, and checks its reliability under faults.
Command bench measures taskmill against the targets in docs/benchmarks.md, and checks its reliability under faults.
cmd/compat command
Command compat is the current code's half of the rolling-deploy check in internal/compat.
Command compat is the current code's half of the rolling-deploy check in internal/compat.
cron
Package cron parses standard five-field cron expressions and computes their next run times.
Package cron parses standard five-field cron expressions and computes their next run times.
migrations
Package migrations holds taskmill's versioned schema migrations.
Package migrations holds taskmill's versioned schema migrations.
testdb
Package testdb connects integration tests to PostgreSQL.
Package testdb connects integration tests to PostgreSQL.
uuid
Package uuid generates version 7 UUIDs (RFC 9562): a millisecond timestamp followed by random bits, so IDs are unique and roughly ordered by time.
Package uuid generates version 7 UUIDs (RFC 9562): a millisecond timestamp followed by random bits, so IDs are unique and roughly ordered by time.
otel module
Package outbox publishes messages to a message broker reliably, with the transactional outbox pattern.
Package outbox publishes messages to a message broker reliably, with the transactional outbox pattern.
Package taskmilltest helps test code that uses taskmill.
Package taskmilltest helps test code that uses taskmill.
Package ui serves taskmill's web interface: a dashboard of queues, tasks, schedules, and workers, with actions to pause and resume queues and schedules, run a schedule now, and retry, cancel, and delete tasks, one at a time or all that match the task list's filters.
Package ui serves taskmill's web interface: a dashboard of queues, tasks, schedules, and workers, with actions to pause and resume queues and schedules, run a schedule now, and retry, cancel, and delete tasks, one at a time or all that match the task list's filters.

Jump to

Keyboard shortcuts

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