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:
- Migrate creates the schema, and NewClient returns the Client.
- Args is a task: a struct with a kind.
- Client.EnqueueTx adds a task in the caller's transaction.
- Handler runs the tasks of one kind, registered with AddHandler.
- Worker fetches tasks and runs their handlers, as its WorkerConfig says.
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)
}
}
Output:
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 ¶
- Constants
- Variables
- func AddBatchHandler[A Args](hs *Handlers, h BatchHandler[A], opts *HandlerOptions)
- func AddHandler[A Args](hs *Handlers, h Handler[A], opts *HandlerOptions)
- func Migrate(ctx context.Context, pool *pgxpool.Pool, cfg *MigrateConfig) error
- func Permanent(err error) error
- func Snooze(d time.Duration) error
- type Activity
- type ActivityParams
- type Args
- type ArgsWithDefaults
- type AttemptError
- type BatchHandler
- type BatchHandlerFunc
- type BulkParams
- type BulkResult
- type Client
- func (c *Client) Activity(ctx context.Context, params *ActivityParams) ([]Activity, error)
- func (c *Client) Cancel(ctx context.Context, id int64) error
- func (c *Client) CancelMatching(ctx context.Context, params *BulkParams) (BulkResult, error)
- func (c *Client) CancelTx(ctx context.Context, tx Executor, id int64) error
- func (c *Client) Close()
- func (c *Client) Count(ctx context.Context, params *CountParams) (*CountResult, error)
- func (c *Client) Delete(ctx context.Context, id int64) error
- func (c *Client) DeleteMatching(ctx context.Context, params *BulkParams) (BulkResult, error)
- func (c *Client) Enqueue(ctx context.Context, args Args, opts *EnqueueOptions) (EnqueueResult, error)
- func (c *Client) EnqueueMany(ctx context.Context, params []EnqueueParams) ([]EnqueueResult, error)
- func (c *Client) EnqueueManyTx(ctx context.Context, tx Executor, params []EnqueueParams) ([]EnqueueResult, error)
- func (c *Client) EnqueueTx(ctx context.Context, tx Executor, args Args, opts *EnqueueOptions) (EnqueueResult, error)
- func (c *Client) Get(ctx context.Context, id int64) (*TaskInfo, error)
- func (c *Client) Groups(ctx context.Context, params *GroupParams) (*GroupsResult, error)
- func (c *Client) List(ctx context.Context, params *ListParams) (*ListResult, error)
- func (c *Client) PauseQueue(ctx context.Context, name string) error
- func (c *Client) PauseSchedule(ctx context.Context, name string) error
- func (c *Client) Queues(ctx context.Context) ([]QueueInfo, error)
- func (c *Client) ResumeQueue(ctx context.Context, name string) error
- func (c *Client) ResumeSchedule(ctx context.Context, name string) error
- func (c *Client) Retry(ctx context.Context, id int64) error
- func (c *Client) RetryMatching(ctx context.Context, params *BulkParams) (BulkResult, error)
- func (c *Client) RunSchedule(ctx context.Context, name string) error
- func (c *Client) Schedules(ctx context.Context) ([]ScheduleInfo, error)
- func (c *Client) Settings(ctx context.Context) (*Settings, error)
- func (c *Client) UpdateQueue(ctx context.Context, name string, update func(*QueueSettings)) error
- func (c *Client) UpdateSettings(ctx context.Context, update func(*Settings)) error
- func (c *Client) Workers(ctx context.Context) ([]WorkerInfo, error)
- type ClientConfig
- type CountParams
- type CountResult
- type EnqueueMiddleware
- type EnqueueOptions
- type EnqueueParams
- type EnqueueResult
- type EnqueueTask
- type ErrorCode
- type Executor
- type ExponentialBackoff
- type GroupInfo
- type GroupParams
- type GroupsResult
- type Handler
- type HandlerFunc
- type HandlerOptions
- type Handlers
- type ListParams
- type ListResult
- type Middleware
- type MigrateConfig
- type Migration
- type PermanentError
- type PgxQuerier
- type Priority
- type QueueInfo
- type QueueOptions
- type QueueSettings
- type RetryPolicy
- type SQLQuerier
- type Schedule
- type ScheduleInfo
- type Settings
- type SnoozeError
- type State
- type Task
- type TaskCount
- type TaskFilter
- type TaskInfo
- type Worker
- type WorkerConfig
- type WorkerInfo
- type WorkerStats
Examples ¶
- Package
- Package (Errors)
- AddBatchHandler
- AddHandler
- ArgsWithDefaults
- Client.Cancel
- Client.Enqueue
- Client.Enqueue (Deduplicated)
- Client.EnqueueMany
- Client.EnqueueTx
- Client.Get
- Client.List
- Client.PauseQueue
- Client.Queues
- Client.RetryMatching
- Client.UpdateQueue
- EnqueueMiddleware
- EnqueueOptions
- EnqueueOptions (FifoGroup)
- HandlerFunc
- Middleware
- Migrate
- Migrations
- NewClient
- NewWorker
- Permanent
- RetryPolicy
- SQL
- Schedule
- Snooze
- State.CanRetry
- Task.CompleteTx
- TaskInfo.ScheduledFor
- Worker.Health
- Worker.Run
- Worker.RunTask
- WorkerConfig
Constants ¶
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.
const DefaultQueue = "default"
DefaultQueue is the queue that tasks go to when neither the enqueue call nor the kind's defaults name one.
Variables ¶
var ( // ErrNotFound means the task or schedule does not exist, or no longer // exists: 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") // ErrBlockingMigration means that [Migrate] refused a pending migration // that would block the writes to a large table while it builds an // index: see [MigrateConfig.MaxBlockingIndexRows]. Migrate changed // nothing, and trying again does not help: a person runs it at a quiet // time, with the limit raised. ErrBlockingMigration = classError("taskmill: a migration would block writes to a large table", "blocking_migration") // 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") // ErrStoredWithoutIDs means that an enqueue outside a transaction stored // its tasks, and then failed while it looked for the tasks that hold the // dedupe keys of its duplicates: see [EnqueueResult.ID]. The tasks // without a dedupe key are stored, so do not enqueue them again. Those // with a dedupe key may be enqueued again, to learn their IDs. On an // executor that runs in a transaction that taskmill cannot see as one, // as [Executor] lists, stored means stored in that transaction, which // can rarely commit after this error: roll it back, and the call stored // nothing. ErrStoredWithoutIDs = classError("taskmill: the tasks are stored, but the IDs of their duplicates are unknown", "stored_without_ids") // 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. A handler that has // not returned 5 seconds later is abandoned, and the task becomes // canceled: see [HandlerOptions.Timeout]. 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. A handler that has not returned 5 seconds later is // abandoned, and the attempt fails with that code all the same. 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", "blocking_migration", "conflict", "stored_without_ids", "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
}
Output:
func AddHandler ¶
func AddHandler[A Args](hs *Handlers, h Handler[A], opts *HandlerOptions)
AddHandler registers h for the kind of A. opts may be nil. Mistakes, such as registering a kind twice, are reported by NewWorker.
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}
}
Output:
func Migrate ¶
Migrate creates or upgrades taskmill's schema, and prepares the next week's history partitions. It is safe to run from several processes at 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.
Migrate fills an existing schema only if it trusts the role that owns the schema, which can drop or replace every table in it, and the role that owns its migrations table, which could have created objects there first: their objects would run with the rights of the role that the pool connects as. It trusts a superuser, and a role that has the rights of the pool's role, such as that role itself. pg_database_owner, which owns the schema public, stands for the database's owner. A role set on the connection, with SET ROLE, SET SESSION AUTHORIZATION or the role parameter, does not count, since code that runs as that role can switch back, and must be trusted too, since it would own what Migrate creates. Otherwise Migrate fails with PostgreSQL's insufficient_privilege, before it changes anything. Of a schema that is up to date, it only reads the migrations table: a superuser, or a member of one, only one whose owners it trusts, and other roles one of a role that they trust or of the schema's owner, so that roles that own nothing can call it too. So run Migrate connected as the role that owns taskmill's tables, and give the CREATE privilege on the database only to roles that you trust: one could create taskmill's schema first, and fill it.
A migration that builds an index does so online, without blocking writes, which can take minutes on a large table. Meanwhile Migrate keeps a second connection of the pool, so the pool needs at least 2, and its connections may have no lock_timeout, statement_timeout, or transaction_timeout, which would cancel the build. Otherwise Migrate fails before the build, with an error that wraps ErrInvalidArgument. An older migration that blocks writes while it builds an index is applied only on tables that MigrateConfig.MaxBlockingIndexRows allows.
The setup guide says when to call Migrate, and with which role.
Example ¶
This example migrates the schema "taskmill", which NewClient checks.
package main
import (
"context"
"log"
"os"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/code19m/taskmill"
)
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
// Several processes may migrate at the same time: one applies the
// migrations while the others wait.
if err := taskmill.Migrate(ctx, pool, nil); err != nil {
log.Fatal(err)
}
pool.Close()
}
Output:
func Permanent ¶
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 ¶
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. If a write's commit outlasts its
// 10 seconds, as when a synchronous standby lags that long, its counts
// can be added twice: the worker cannot tell it from a write that
// failed, and keeps the counts rather than lose 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.
// Maximum: 100 names.
Queues []string
// Since is when the period starts, a time that PostgreSQL can store,
// from 4713 BC to 294276 AD. 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 WorkerConfig.NoHandlerWait, an hour by default.
An enqueue returns an error that wraps ErrInvalidArgument for nil Args, also a nil pointer of an Args type, and 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)
}
}
Output:
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 ¶
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. More errors than tasks fail every task: no error can be matched to its task, as when append added the errors after the nils that make put in the slice.
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. A task's Task.CancelRequested reports a cancel request, so that the batch can skip that task's work. 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. A task whose lease ended before the batch began, as on a slow link to the database, is left out of it.
Register a batch handler with AddBatchHandler. The batch guide shows one, and says when a batch is worth it.
type BatchHandlerFunc ¶ added in v0.16.0
BatchHandlerFunc adapts a function to the BatchHandler interface.
func (BatchHandlerFunc[A]) HandleBatch ¶ added in v0.16.0
func (f BatchHandlerFunc[A]) HandleBatch(ctx context.Context, tasks []*Task[A]) []error
HandleBatch calls f(ctx, tasks).
type BulkParams ¶ added in v0.2.0
type BulkParams struct {
// Filter selects the tasks. Required: it must set Queues, States, Kinds,
// or GroupKeys, since a range of times alone does not say which tasks
// to change. The action goes through the tasks in ID order, also in a
// range of times.
Filter TaskFilter
// Cursor continues an action that stopped early, from its
// [BulkResult.Next], with the filter that it came from. Empty means from
// the oldest task.
Cursor string
}
BulkParams selects the tasks of a bulk action, such as Client.RetryMatching. Nil params, a filter that sets none of Queues, States, Kinds, and GroupKeys, 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. The call that continues goes through the
// tasks after Next again, so Skipped and Conflicts count none of those:
// the results of the calls that continue one another add up.
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, and Client.Close it when it is no longer needed. 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:
- Enqueue: Client.Enqueue and Client.EnqueueMany, and in the caller's transaction Client.EnqueueTx and Client.EnqueueManyTx.
- Read: Client.Get, Client.List, Client.Count, Client.Groups, Client.Queues, Client.Schedules, Client.Workers, Client.Activity, and Client.Settings.
- Change one task: Client.Cancel, Client.CancelTx, Client.Retry, and Client.Delete.
- Change every task that a filter matches: Client.RetryMatching, Client.CancelMatching, and Client.DeleteMatching.
- Change a queue or a schedule: Client.PauseQueue, Client.ResumeQueue, Client.UpdateQueue, Client.PauseSchedule, Client.ResumeSchedule, and Client.RunSchedule.
- Change what the installation keeps: Client.UpdateSettings.
The reads are bounded, so that a dashboard or a script cannot overload the database. The operations guide shows them at work.
func NewClient ¶
NewClient returns a client that uses pool for its own statements. cfg may be nil. It fails with ErrSchemaOutdated if the schema was not migrated.
taskmill's statements rely on the READ COMMITTED isolation level, so NewClient fails 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.
Example ¶
This example creates a client that logs through the application's logger.
package main
import (
"context"
"errors"
"log"
"log/slog"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/code19m/taskmill"
)
func main() {
ctx := context.Background()
var pool *pgxpool.Pool // the application's pool, of a migrated database
client, err := taskmill.NewClient(ctx, pool, &taskmill.ClientConfig{Logger: slog.Default()})
if errors.Is(err, taskmill.ErrSchemaOutdated) {
log.Fatal("run taskmill.Migrate first")
}
if err != nil {
log.Fatal(err)
}
_ = client // share it: it is safe for concurrent use
}
Output:
func (*Client) Activity ¶
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 ¶
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 keeps running, and its handler sees the request with Task.CancelRequested: the task becomes canceled when its batch ends, unless the batch completed it. Cancel frees the task's dedupe key right away. Client.Retry of the canceled task takes it back, and so does a running task that completes all the same, if no other task took the key meanwhile. 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)
}
}
Output:
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 params select, 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 ¶
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) Close ¶ added in v0.15.0
func (c *Client) Close()
Close stops the client's background work: it sends the notifications that the client held back to wake workers less often, bounded by 5 seconds, and waits for those being sent. Nothing of the client runs on the pool afterwards, so call Close before the pool's Close. The client's methods still work after Close, but hold back no notification any more: each sends its own before it returns. Close may be called more than once.
func (*Client) Count ¶ added in v0.2.0
func (c *Client) Count(ctx context.Context, params *CountParams) (*CountResult, error)
Count counts the tasks that params select. params may be nil, which counts every task. It counts at most 10,000 tasks per state. Like Client.List, the query is canceled after 5 seconds.
func (*Client) Delete ¶
Delete deletes a task that is not running, including a completed task in history, and frees its dedupe key. Deleting the dead task that halts its FIFO group resumes the group. It returns 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 params select, 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.
The ClientConfig.EnqueueMiddleware runs around the enqueue. Once the task is committed, the client notifies the workers of a task that may start now, so a worker with a free slot usually starts it within milliseconds. The client sends its notifications together, once per 50 ms, so while it enqueues more, a task can wait up to 50 ms for its own.
It returns an error that wraps ErrInvalidArgument for nil args, also a nil pointer, 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 with the defaults: in the default queue, to start right away.
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
res, err := client.Enqueue(ctx, SendReceipt{OrderID: 7, Email: "a@example.com"}, nil)
if err != nil {
log.Fatal(err) // such as ErrInvalidArgument for a payload that cannot be stored
}
log.Printf("enqueued task %d", res.ID)
}
Output:
Example (Deduplicated) ¶
This example deduplicates an enqueue: enqueueing the same key again within the window reports the existing task instead of creating another.
package main
import (
"context"
"log"
"time"
"github.com/code19m/taskmill"
)
// SendReceipt is the payload of an example task.
type SendReceipt struct {
OrderID int64 `json:"order_id"`
Email string `json:"email"`
}
// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }
func main() {
ctx := context.Background()
var client *taskmill.Client // from taskmill.NewClient
res, err := client.Enqueue(ctx, SendReceipt{OrderID: 7}, &taskmill.EnqueueOptions{
DedupeKey: "receipt-7",
DedupeWindow: 24 * time.Hour,
})
if err != nil {
log.Fatal(err)
}
if res.Duplicate {
log.Printf("already enqueued as task %d", res.ID)
}
}
Output:
func (*Client) EnqueueMany ¶
func (c *Client) EnqueueMany(ctx context.Context, params []EnqueueParams) ([]EnqueueResult, error)
EnqueueMany enqueues several tasks with one statement, in one round trip: all of them, or none if it returns an error. Only when another transaction takes a dedupe key of the call at the same moment does the call run more statements, and an error that wraps ErrStoredWithoutIDs then means that its tasks are stored: see EnqueueResult.ID. 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)
}
Output:
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, also one that wraps a nil pointer such as a nil *sql.Tx, 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)
}
}
Output:
func (*Client) Get ¶
Get returns a task by ID, whether it is unfinished, finished, or in history. It returns ErrNotFound if no such task exists.
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)
}
}
Output:
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, or keys without queues, that match 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 three orders:
- A list with a range of creation times, TaskFilter.CreatedSince or TaskFilter.CreatedBefore, is ordered by when the tasks were created, the latest first: by TaskInfo.CreatedAt, and by ID, the highest first, among tasks created at the same time.
- Without such a range, a list of only dead tasks, only canceled tasks, or both is ordered by when the tasks finished, the latest first: by TaskInfo.FinishedAt, and then by ID in the same way.
- Every other list is ordered by ID, the newest task first.
IDs follow creation times only roughly. A task's creation time is the start of the transaction that enqueued it, and its ID is as new as the moment of its insert: a task that a long transaction enqueues at its end has an older creation time than tasks with lower IDs. So a list with a range of creation times is in the order of that time, in which a page reads an index, and not in ID order.
A task's finish time is the start of the transaction that finished it. So tasks show up neither in the order of their creation times nor in that of their finish times: a walk through the pages of a list in either order can miss a task that is enqueued, or finishes, meanwhile. A walk in finish order can return a task twice, if the task is retried and finishes again meanwhile. So a list of dead tasks is not a log: to read the tasks that died since your last look, read from the first page to a little before the latest finish time that you saw, and drop the IDs that you have.
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 page reads about the tasks that it returns, except in these lists:
- A list in ID order whose tasks no index holds in that order reads every newer task, of any queue and state, until its page is full. Indexes hold every task, the completed tasks of one queue or of all, and the pending tasks of one queue's FIFO group, in ID order. They do not hold, for example, one waiting state, or dead tasks mixed with other states. A list of only running tasks reads every running task of its queues instead, and sorts them.
- A list in creation or finish order with no queue named reads up to a page of each queue that holds such tasks: with hundreds of queues, name the queue.
- A list in finish order reads every task that shares a finish time with the first or the last task of its page. The tasks that one transaction finished share one: up to 1,000 for a batch of a bulk action, and with no limit for the Client.CancelTx calls of one transaction.
- A list in finish order with a kind or a FIFO group in its filter reads the dead or canceled tasks of each queue until its page is full.
The reasons are in https://github.com/code19m/taskmill/blob/main/docs/design/schema-lists.md.
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
}
}
Output:
func (*Client) PauseQueue ¶
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)
}
}
Output:
func (*Client) PauseSchedule ¶
PauseSchedule stops a schedule from enqueueing runs until it is resumed. It returns ErrNotFound for an unknown schedule.
func (*Client) Queues ¶
Queues returns every known queue, 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)
}
}
Output:
func (*Client) ResumeQueue ¶
ResumeQueue undoes Client.PauseQueue. Workers apply it as fast as a pause, and like PauseQueue it never returns ErrNotFound. A queue that it leaves with its default settings is no longer stored, as with Client.UpdateQueue.
func (*Client) ResumeSchedule ¶
ResumeSchedule undoes Client.PauseSchedule. Runs missed while paused collapse into one run. It returns ErrNotFound for an unknown schedule.
func (*Client) Retry ¶
Retry makes a dead or canceled task available again, with a fresh set of attempts. Retrying the dead task that halts its FIFO group resumes the group; another task of a group waits 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 params select, as Client.Retry retries each one: those that match its filter. The filter must set Queues, States, Kinds, or GroupKeys: 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. A task that dies meanwhile is retried if the action has not yet read past it, and a read of a range of finish times looks up to 50 batches ahead: a later run retries the others. 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)
}
Output:
func (*Client) RunSchedule ¶
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) UpdateQueue ¶
UpdateQueue changes a queue's installation-wide settings for every worker, and stores them for a queue that had none. A queue whose settings are back to their defaults, and that is not paused, is no longer stored: Client.Queues lists it only while it holds tasks or workers read it. 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)
}
}
Output:
func (*Client) UpdateSettings ¶
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. A nil entry is an error that
// wraps [ErrInvalidArgument]. 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 CountParams ¶ added in v0.14.0
type CountParams struct {
// Filter selects the tasks. Empty means every task. With the filter of
// a bulk action, the counts say what that action would change.
Filter TaskFilter
}
CountParams selects the tasks that Client.Count counts. A field outside its limits is an error that wraps ErrInvalidArgument.
type CountResult ¶ added in v0.17.0
type CountResult 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
}
CountResult counts the tasks that match a filter.
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)
}
}
Output:
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. [Client.Retry] of the canceled task takes it
// back, and so does a running task that completes after its cancel was
// requested, if no other task took the key meanwhile. 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 ¶
This example enqueues a task that starts in 10 minutes at the earliest. Then it starts before the waiting tasks of its queue whose priority is lower, and after those of higher priority, and of the same priority that were due before it.
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
_, 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
}
}
Output:
Example (FifoGroup) ¶
This example runs tasks of one FIFO group one at a time, in order.
package main
import (
"context"
"log"
"github.com/code19m/taskmill"
)
// SendReceipt is the payload of an example task.
type SendReceipt struct {
OrderID int64 `json:"order_id"`
Email string `json:"email"`
}
// Kind implements taskmill.Args.
func (SendReceipt) Kind() string { return "email.send_receipt" }
func main() {
ctx := context.Background()
var client *taskmill.Client // from taskmill.NewClient
for _, entry := range []int64{1, 2, 3} {
_, err := client.Enqueue(ctx, SendReceipt{OrderID: entry}, &taskmill.EnqueueOptions{GroupKey: "customer-7"})
if err != nil {
log.Fatal(err)
}
}
}
Output:
type EnqueueParams ¶
type EnqueueParams struct {
// Args 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 for a duplicate the one that
// holds the key. It is never 0.
//
// Another transaction may take the key while the enqueue runs, and
// commit after the enqueue's statement began, which then cannot see the
// task. At READ COMMITTED, the enqueue reads the key again in a second
// statement. If that task was canceled or deleted meanwhile, the key is
// free, and the enqueue stores the task after all, in a statement of its
// own: in a FIFO group, it then comes after the call's other tasks. An
// enqueue outside a transaction has committed its other tasks by then,
// so the end of its context does not stop this. If the database fails
// first, it returns an error that wraps [ErrStoredWithoutIDs]. At
// REPEATABLE READ or SERIALIZABLE, the enqueue fails with PostgreSQL's
// serialization failure (SQLSTATE 40001) instead: run the caller's
// transaction again.
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. 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 [WorkerConfig.NoHandlerWait] of its [CodeNoHandler] note, // an hour by default, 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 the worker's // [WorkerConfig.NoHandlerWait], 1 hour by default, the task becomes // dead, with the code [CodeUnknownKind]. The wait 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 that wraps one with its Commit and Rollback methods, such as *sqlx.Tx. They return ErrInvalidArgument for anything else. An enqueue counts every other executor as outside a transaction, also a connection on which the caller ran BEGIN, and a type that wraps a transaction without its Commit and Rollback methods. There, a failed second read of a dedupe key returns an error that wraps ErrStoredWithoutIDs (see EnqueueResult.ID), and an EnqueueMiddleware that fails after next has its error logged, not returned.
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()
}
Output:
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
// Keys limits the result to the groups with these keys, exactly as
// [GroupInfo.Key] holds them. With Queues, a page reads only the
// groups it names. Maximum: 100 keys. Empty means all groups.
Keys []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 ¶
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. A task whose lease ended before its attempt began, as on a slow link to the database, reaches neither Handle nor the middleware.
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 ¶
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 }
Output:
type HandlerOptions ¶
type HandlerOptions struct {
// Timeout bounds each attempt, or each batch: the handler's context is
// canceled with [ErrAttemptTimeout] then. A handler that has not returned
// 5 seconds after its context was canceled, by this timeout, a cancel of
// its task, or a lost lease, is abandoned: its attempt ends as the cause
// says, its task is retried or canceled, and its result is ignored. Its
// goroutine keeps its slot until it returns, and it may still finish its
// work, while the task already runs again. The context of a batch
// handler ends only with this timeout, so a batch is abandoned only
// after it: each of its tasks fails with [CodeTimeout]. In a queue with
// a [QueueSettings.MaxRunning] limit, only an attempt that lost its lease
// is abandoned, since its task may run again anyway. Any other task there
// stays running until the handler returns, and the worker logs a
// warning: a task that ran again would break the limit. 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 rescued by the maintainer, the worker that leads maintenance:
// it is retried with this policy if that worker has a handler for the
// kind, and with the default otherwise. 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. A worker runs up to its queue's Concurrency batches, and
// each task of a batch holds its payload twice in memory: as stored,
// and decoded.
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
// 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 that it came from: each of the
// three orders of [Client.List] has cursors of its own, and a cursor of
// another 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 ¶
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)
}
}
Output:
type MigrateConfig ¶
type MigrateConfig struct {
// Schema is the PostgreSQL schema to migrate. It must match
// ^[a-z_][a-z0-9_]{0,62}$. Default: "taskmill".
Schema string
// Logger receives one log line per applied migration, and a warning if
// partitions cannot be prepared. Default: logs are discarded.
Logger *slog.Logger
// MaxBlockingIndexRows is the most rows, by PostgreSQL's estimate, that
// a pending migration may read while it builds an index that blocks
// writes to the table: migration 3 on groups, 7 on tasks and the
// history, and 9 on tasks. Writes wait about half a second for each
// million rows that migration 7 reads. Over the limit, Migrate fails
// before it changes anything, with an error that wraps
// [ErrBlockingMigration]: run it as a job of its own, at a quiet time,
// with the limit raised. A negative value removes the limit. Default:
// 1,000,000, which keeps the wait well under the 5 seconds for which a
// migration may wait for a lock. Later migrations build their indexes
// online, which blocks no writes.
MaxBlockingIndexRows int64
}
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
// Online reports a migration that builds or drops indexes with
// CONCURRENTLY, which blocks no writes. PostgreSQL runs such a statement
// only outside a transaction, alone: a query that holds several
// statements runs them in one transaction, and fails. So apply each of
// [Migration.Statements] in a query of its own, outside a transaction,
// and record the migration once every statement succeeded. A build that
// fails leaves the index that its statement names invalid: drop it with
// DROP INDEX CONCURRENTLY before you try again. Tools such as goose,
// Atlas, and Flyway split SQL into statements themselves.
Online bool
}
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. The bootstrap refuses what Migrate refuses, with PostgreSQL's insufficient_privilege: a schema or a migrations table whose owner it does not trust, or a role set on the connection that it does not trust. Apply them in order, each in a transaction unless it is Online, and record every version above 0, so that NewClient finds the schema up to date:
INSERT INTO <schema>.migrations (version, name) VALUES (<Version>, '<Name>')
func Migrations ¶
Migrations returns every migration for schema, in order. Teams that use their own migration tools apply these instead of calling Migrate. Their bootstrap refuses the schemas that Migrate refuses: see Migration. 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 0007_created_order 0008_worker_schedules 0009_group_heads
func (Migration) Statements ¶ added in v0.16.0
Statements returns the statements of an Online migration, in order and without comments, for a runner that applies them one at a time. It returns nil for any other migration, whose SQL runs whole, in a transaction.
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 have the Commit and Rollback methods of 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.
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. A
// handler that ignores its context keeps its task running, and counting,
// until it returns: it is not abandoned, as in a queue without a limit
// (see [HandlerOptions.Timeout]). 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. The maintainer calls it too, in the transaction that rescues the tasks whose workers lost their leases. 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)})
}
Output:
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. It compares them with those of the other workers, by name and by definition, once a minute. It logs an error when they have differed for 10 minutes, longer than a rolling deploy takes, again at most once an hour while they differ, and a line when they match again. A definition is all that decides when a run happens and which task it enqueues, except the metadata, so args that hold a value of each process, such as the time that the worker started, count as a difference. 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.
The maintainer enqueues each run within about a second of its time. 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)
}
}
Output:
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
CanCancel reports whether tasks in state s can be canceled: unfinished tasks.
func (State) CanDelete ¶ added in v0.2.0
CanDelete reports whether tasks in state s can be deleted: all but running tasks.
func (State) CanRetry ¶ added in v0.2.0
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
type Task ¶
Task is a task being run by a handler, with its decoded Args.
func (*Task[A]) CancelRequested ¶ added in v0.15.0
CancelRequested reports whether the task's cancellation was requested while its attempt runs, as with Client.Cancel. A Handler also learns it from its context, which ends with the cause ErrTaskCanceled. A BatchHandler, whose context a cancel does not end, learns it only here, and can skip the task's work: an error returned for the task then cancels it, and nil completes it. The worker learns of a request from a notification, within moments, or else at its next check-in, every third of WorkerConfig.LeaseDuration. It is false for a task that no worker runs, such as one that a test builds.
func (*Task[A]) CompleteTx ¶
CompleteTx completes the task inside the caller's transaction, so that the handler's own writes and the completion commit together or not at all. It returns ErrLeaseLost if another attempt took the task over; return that error, so that the transaction rolls back. If a cancel of the task was requested while it ran, CompleteTx also takes back the dedupe key that the cancel freed, unless another task took it, and like an enqueue of the key, it waits for a transaction that claims it. It claims the key before it takes the row of the task's FIFO group, as an enqueue and Client.Retry do. So a transaction of the caller that takes the group's row first, with an enqueue into the group, and then enqueues the key, can wait for it while it waits for that transaction: PostgreSQL then ends one of the two with a deadlock error (SQLSTATE 40P01). The transaction that got the error can be run again.
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)
}
Output:
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 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
// CreatedSince limits the tasks to those created at this time or later:
// those whose [TaskInfo.CreatedAt] is not before it. Zero means no lower
// bound. Any filter takes it, whatever its states, and it puts a list in
// creation order: see [Client.List]. A bulk action still goes through
// its tasks in ID order. Together with a range of finish times it is an
// error that wraps [ErrInvalidArgument]: a list has one order.
//
// 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 CreatedBefore if both are set.
CreatedSince time.Time
// CreatedBefore limits the tasks to those created before this time,
// under the rules of CreatedSince. Zero means no upper bound. A task
// created at this very time is left out, so two ranges that meet at a
// time share no task.
CreatedBefore time.Time
// FinishedSince limits the tasks to those that finished at this time or
// later: those whose [TaskInfo.FinishedAt] is not before it. Zero means
// no lower bound. Only a filter of only dead tasks, only canceled tasks,
// or both takes it, without a range of creation times: it lists them in
// finish order, see [Client.List]. With any other filter it is an error
// that wraps [ErrInvalidArgument].
//
// The time is an instant, under the rules of CreatedSince, and it must
// be before FinishedBefore if both are set.
FinishedSince time.Time
// FinishedBefore limits the tasks to those 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
}
TaskFilter selects tasks by what they are, by queue, state, kind, and FIFO group, and by when they were created or finished, for Client.List, Client.Count, and the bulk actions: a task matches if it matches every field that is set. Each filter takes at most 100 values. 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, a filter with too many values, or a range of times that breaks its rules, 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].
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
FinishedAt 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
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, such as one enqueued by hand: 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. While Run runs, if the pool has at least the worker's total Concurrency plus 5 connections, the worker keeps one of them idle in reserve: a renewal of leases that finds every other connection in use, as when handlers that share the pool hold them, runs on it, so that leases do not run out. Through a pooler in transaction mode, the reserve is only a connection to the pooler, whose own pool must leave room for it: see the docs on connection poolers. The worker also has 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.
Example ¶
This example creates a worker that runs the tasks of one kind, in the kind's default queue.
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 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 {
return deliverReceipt(ctx, t.Args.Email, t.Args.OrderID)
},
), nil)
worker, err := taskmill.NewWorker(client, &taskmill.WorkerConfig{Handlers: &handlers})
if err != nil {
log.Fatal(err) // ErrInvalidArgument, such as for a kind registered twice
}
_ = worker // run it with Run
}
Output:
func (*Worker) Health ¶ added in v0.2.0
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. And it is an error while handlers that did not return 5 seconds after their context ended, by their Timeout, a cancel, or a lost lease, hold every slot of the worker's queues: the worker can start no task until one of them returns, and WorkerStats.SlotsStuck counts them. 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
}
}
Output:
func (*Worker) Run ¶
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, at most about DrainTimeout plus 10 seconds after ctx ended, even when the database does not answer: see WorkerConfig.DrainTimeout. 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.
Example ¶
This example runs a worker until the process is told to stop. Run then waits for the running tasks, up to DrainTimeout, and returns.
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/code19m/taskmill"
)
func main() {
var worker *taskmill.Worker // from taskmill.NewWorker
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := worker.Run(ctx); err != nil {
log.Print(err) // it could not start: it could not register, or it runs already
}
}
Output:
func (*Worker) RunTask ¶
RunTask runs one task now, in the calling goroutine, the way Worker.Run runs tasks: it leases the task, runs the middleware and the handler of its kind while renewing the lease, and records the outcome. It ignores the task's run time, queue pauses, and 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. So does a task whose handler ends the goroutine with runtime.Goexit, as t.Fatal in a test does.
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.
A task whose lease ended on its way, as when its row took longer than the lease to arrive, may run on another worker already: RunTask runs nothing then, and returns the task, which stays running until the maintainer rescues it.
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)
}
Output:
func (*Worker) Stats ¶ added in v0.15.0
func (w *Worker) Stats() WorkerStats
Stats returns what the worker did since NewWorker created it, and how busy its slots are now. It reads only memory, so a metrics system may call it at every collection. The otel module exports it with Instrumentation.ObserveWorker.
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. While
// renewals fail, it tries them again every thirtieth of it. A lease
// starts when the task is taken, by the database's clock, not when the
// fetch began, so the time that its row takes to reach the worker counts
// against it. If no renewal of a task's lease succeeds for a whole
// LeaseDuration, as when the worker cannot reach the database, the
// worker cancels the task's handler with [ErrLeaseLost]: from then on,
// the maintainer may rescue the task, and another worker run it. Keep
// it above 30 round trips to the database: a thirtieth of it bounds the
// ping of an idle connection. 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, ±10%, so that workers poll
// apart. 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. Run then has 5 seconds more at most to record the
// results that are left, release those tasks, give up the maintainer's
// role, and unregister. What it cannot record by then, as when the
// database does not answer, is rescued once its lease runs out, and the
// task runs again. So Run returns at most about DrainTimeout plus 10
// seconds after its context is canceled. Keep
// DrainTimeout at least 10 seconds below the time the platform gives a
// stopping process. It must not be negative. Default: 20 seconds.
DrainTimeout time.Duration
// NoHandlerWait is how long a task of a kind that this worker has no
// handler for waits for a worker that has one, before this worker makes
// it dead with [CodeUnknownKind]. Meanwhile the worker snoozes the task 1
// minute at a time, without using its attempts. The wait counts from
// the first time a worker met the task without a handler: see
// [CodeNoHandler]. In a rolling deploy that adds a kind, the workers of
// the old release meet its tasks, so their wait is the one that counts:
// give them, a release ahead, a wait longer than the whole rollout,
// canary included. Minimum: 1 minute. Maximum: 7 days. Default: 1 hour.
NoHandlerWait time.Duration
// Middleware wraps every attempt, in order: the first is the outermost.
// A nil entry is an error that wraps [ErrInvalidArgument]. Default: none.
Middleware []Middleware
// Schedules are recurring tasks that the maintainer enqueues. Each name
// may appear once. Every worker that takes part in the maintainer
// election must define the same schedules: see [Schedule]. Default: none.
Schedules []Schedule
// NoMaintainer keeps this worker out of the maintainer election. At least
// one worker of an installation must take part. Set it on a worker that
// does not define the schedules of the others.
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)
}
}
Output:
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
// Schedules are the names of the worker's schedules, sorted, if it is a
// Candidate: see [WorkerConfig.Schedules]. It is empty for any other
// worker.
Schedules []string
// 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
// Candidate reports that the worker takes part in the maintainer
// election, so its Schedules count: the maintainer logs an error when
// the schedules of the candidates keep differing, see [Schedule]. It is
// false for a worker with [WorkerConfig.NoMaintainer], for one that is
// stopping, which no longer takes part, and for a worker of a release
// before v0.13.0, which does not say.
Candidate bool
// 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.
type WorkerStats ¶ added in v0.15.0
type WorkerStats struct {
// AttemptsStarted counts the attempts whose handler the worker started,
// in Run and in RunTask. A task that the worker ends without a handler,
// as one of a kind that it has no handler for, does not count.
AttemptsStarted int64
// AttemptsSucceeded counts the attempts whose success was recorded: their
// tasks completed, also those that the handler completed with
// [Task.CompleteTx].
AttemptsSucceeded int64
// AttemptsFailed counts the attempts whose failure was recorded: their
// tasks wait to be retried, or are dead. An attempt whose task the
// maintainer rescued after its worker lost the lease counts in
// LeasesLost, on that worker, if it still runs.
AttemptsFailed int64
// LeasesLost counts the attempts that lost their leases: the worker
// could not renew a lease in time, or fetched a task again whose older
// attempt still ran. Their results are discarded, and their tasks may
// run twice.
LeasesLost int64
// HandlersAbandoned counts the attempts whose handler did not return 5
// seconds after its context ended, by its Timeout, a cancel, a lost
// lease, or Run's shutdown, so that the worker abandoned it: see
// [HandlerOptions.Timeout]. The handler's goroutine keeps its slot until
// it returns.
HandlersAbandoned int64
// CompletionsBlocked counts the successful attempts whose completion
// waited longer than LeaseDuration for a row that another transaction
// held: the task's, or its FIFO group's.
CompletionsBlocked int64
// PoolWaits counts the times that a statement of the worker found every
// connection of the pool in use, and waited for one. Those statements
// are fetches, completions in Run, the records of other outcomes, such
// as failures and snoozes, renewals of leases, check-ins, and the takes
// of the worker's reserve. A connection that is still opening is not in
// use. Handlers that share the pool hold the connections, or the pool
// is too small, or statements wait for an answer, as behind a pooler
// whose own pool is full. A renewal or a check-in waits a thirtieth of
// the lease at most, and then uses the reserve, if the worker keeps
// one: see [Worker]. Without one, it counts twice.
PoolWaits int64
// Slots is the sum of the Concurrency of the worker's queues.
Slots int
// SlotsBusy is how many slots running attempts and batches hold now.
SlotsBusy int
// SlotsStuck is how many of those are held by handlers that did not
// return 5 seconds after their context ended. While they hold every
// slot, [Worker.Health] fails.
SlotsStuck int
}
WorkerStats are counts of what a Worker did since NewWorker created it, and how busy its slots are now: Worker.Stats returns them. The counts only grow, so a metrics system reads them as counters, and their rates say how often each thing happens. Each task of a batch counts as one attempt.
The monitoring page says which of them to alert on.
Source Files
¶
- activity.go
- args.go
- attempt.go
- bulk.go
- client.go
- complete.go
- doc.go
- enqueue.go
- errors.go
- executor.go
- fetch.go
- group.go
- handler.go
- history.go
- lease.go
- list.go
- listen.go
- log.go
- maintainer.go
- middleware.go
- migrate.go
- notify.go
- payload.go
- queues.go
- record.go
- runtask.go
- schedule.go
- schedule_compare.go
- settings.go
- sql.go
- sql_attempts.go
- sql_enqueue.go
- sql_groups.go
- sql_lists.go
- sql_maintenance.go
- sql_operations.go
- sql_session.go
- sql_stats.go
- task.go
- validate.go
- worker.go
- workers.go
- workerstats.go
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
|
|
|
enqueue-over-http
command
Command enqueue-over-http is the program of the recipe "Work with other languages", docs/recipes/work-with-other-languages.md: a Go service whose tasks programs in other languages enqueue over HTTP.
|
Command enqueue-over-http is the program of the recipe "Work with other languages", docs/recipes/work-with-other-languages.md: a Go service whose tasks programs in other languages enqueue over HTTP. |
|
internal/readme
Package readme holds the code of the quick look in README.md, so that it compiles.
|
Package readme holds the code of the quick look in README.md, so that it compiles. |
|
modules
command
Command modules is the program of the recipe "Organize tasks by module", docs/recipes/organize-tasks-by-module.md: one binary of two modules, orders and billing, which share one taskmill schema.
|
Command modules is the program of the recipe "Organize tasks by module", docs/recipes/organize-tasks-by-module.md: one binary of two modules, orders and billing, which share one taskmill schema. |
|
modules/internal/billing
Package billing is the billing module of the example: it creates invoices.
|
Package billing is the billing module of the example: it creates invoices. |
|
modules/internal/billing/billingtasks
Package billingtasks holds the tasks of the billing module: the types that other modules enqueue, and nothing else.
|
Package billingtasks holds the tasks of the billing module: the types that other modules enqueue, and nothing else. |
|
modules/internal/orders
Package orders is the orders module of the example: it takes orders.
|
Package orders is the orders module of the example: it takes orders. |
|
modules/internal/orders/ordertasks
Package ordertasks holds the tasks of the orders module: the types that other modules enqueue, and nothing else.
|
Package ordertasks holds the tasks of the orders module: the types that other modules enqueue, and nothing else. |
|
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. |
|
services/billing
command
Command billing is the billing service of the recipe "Split work across services", docs/recipes/split-across-services.md.
|
Command billing is the billing service of the recipe "Split work across services", docs/recipes/split-across-services.md. |
|
services/internal/billingtasks
Package billingtasks is the contract of the billing service's tasks: their kinds, their JSON fields, and their defaults.
|
Package billingtasks is the contract of the billing service's tasks: their kinds, their JSON fields, and their defaults. |
|
services/orders
command
Command orders is the orders service of the recipe "Split work across services", docs/recipes/split-across-services.md.
|
Command orders is the orders service of the recipe "Split work across services", docs/recipes/split-across-services.md. |
|
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. |
|
buildinfo
Package buildinfo reads taskmill's version from the build information of the binary.
|
Package buildinfo reads taskmill's version from the build information of the binary. |
|
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. |
|
internal/twins
Package twins holds the cases that the dashboard's server and its script must word alike.
|
Package twins holds the cases that the dashboard's server and its script must word alike. |