Documentation
¶
Overview ¶
Package store defines Tasklane's storage contract. The service layer depends only on this package: pgstore implements it on PostgreSQL in v1, and a Raft-backed store will implement it in phase 2.
Index ¶
Constants ¶
const MaxErrorBytes = 4096
MaxErrorBytes caps a job's last_error. Longer messages are truncated, not rejected: refusing a Nack over its message would only leave the job to the reaper.
const StatsWindow = 10 * time.Second
StatsWindow is how far back QueueStats counts completed jobs. Completed jobs pile up until they are pruned, so counting all of them would get slower as the table grows; a recent window costs what the recent throughput costs, whatever the table size.
Variables ¶
var ( // ErrNotFound means the queue or job does not exist. ErrNotFound = errors.New("tasklane: not found") // ErrLeaseLost means the job exists but the caller's lease token is stale: the lease expired, was reaped or the job is no longer leased. ErrLeaseLost = errors.New("tasklane: lease lost") // ErrInvalid means an argument failed validation. ErrInvalid = errors.New("tasklane: invalid argument") // ErrAlreadyExists means the resource, such as a queue, already exists. ErrAlreadyExists = errors.New("tasklane: already exists") // ErrWrongState means the job exists but its state doesn't allow the // operation, such as cancelling a job that is already leased. ErrWrongState = errors.New("tasklane: wrong job state") )
Functions ¶
func TruncateUTF8 ¶
TruncateUTF8 cuts s to at most n bytes without splitting a character.
Types ¶
type AckResult ¶
AckResult is what an Ack did. Repeated is true when the job was already completed with the same token (a retry after a lost response): success, but nothing changed.
type DeadCursor ¶
DeadCursor marks where a page of dead jobs ended: the last job's FinishedAt and ID. The next page starts after it.
type EnqueueResult ¶
type Job ¶
type Job struct {
ID int64
Queue string
Kind string
Payload json.RawMessage
Priority Priority
State JobState
RunAt time.Time
Attempts int
MaxAttempts int
LastError string
LeaseToken uuid.UUID // the current lease's token; on a completed job, the token that completed it; otherwise uuid.Nil
LeaseExpiresAt time.Time // zero unless leased
IdempotencyKey string
TraceContext string
CreatedAt time.Time
FinishedAt time.Time // zero until completed, dead or cancelled
LeasedAt time.Time // set only on jobs returned by Lease: the database time the lease was taken
}
type NackResult ¶
NackResult is what a Nack did: the job went back to available, or to dead when it had used all its attempts.
type NewJob ¶
type NewJob struct {
Queue string
Kind string
Payload json.RawMessage // empty means {}
Priority Priority // PriorityUnspecified means PriorityDefault
RunAt time.Time // zero means now
MaxAttempts int // zero means the queue's default
IdempotencyKey string // empty means no deduplication
TraceContext string // W3C traceparent, passed through to the worker
}
type Priority ¶
type Priority int
Priority orders leasing: lower values run first. The zero value means "unspecified", which Enqueue stores as PriorityDefault (the protobuf enum convention, so an unset field never silently becomes critical).
type Queue ¶
type Queue struct {
Name string
MaxDepth int64
VisibilityTimeout time.Duration
MaxAttempts int
Paused bool
}
func (Queue) WithDefaults ¶
WithDefaults fills zero-valued settings with the queue defaults.
type QueueDepth ¶
type QueueDepth struct {
Queue string
MaxDepth int64
Available int64 // delayed jobs and jobs waiting to retry included
Leased int64
// OldestReady is how long the oldest available job whose run_at has
// passed has been ready; 0 when there is none or the queue is paused.
OldestReady time.Duration
}
QueueDepth is a queue's backpressure and monitoring input.
func (QueueDepth) Depth ¶
func (d QueueDepth) Depth() int64
Depth is what max_depth limits: available plus leased jobs.
type QueueStats ¶
type QueueStats struct {
Available int64
Leased int64
Dead int64
RecentlyCompleted int64 // completed within the last StatsWindow
}
QueueStats are a queue's live job counts.
type ReapedJob ¶
ReapedJob is one expired lease the reaper handled: retried, or dead when the job had used all its attempts.
type Store ¶
type Store interface {
// CreateQueue returns ErrAlreadyExists if the name is taken, and
// ErrInvalid for an empty or unsafe name (1-128 characters from
// [A-Za-z0-9._-]), negative settings or a visibility timeout that is
// positive but under 1 ms.
CreateQueue(ctx context.Context, q Queue) error
// GetQueue returns ErrNotFound for an unknown queue.
GetQueue(ctx context.Context, name string) (Queue, error)
// QueueStats counts the queue's available, leased and dead jobs and the
// jobs completed within the last StatsWindow. It returns ErrNotFound for
// an unknown queue.
QueueStats(ctx context.Context, queue string) (QueueStats, error)
// QueueDepths returns every queue's available and leased counts,
// max_depth and oldest ready age in one statement, for the API's
// backpressure cache and the depth gauges.
QueueDepths(ctx context.Context) ([]QueueDepth, error)
// Enqueue inserts 1 to 1000 jobs atomically and returns one result per
// job, in the caller's order. A job whose idempotency key already exists
// in its queue returns the existing ID with Created=false. Jobs with keys
// are inserted first, sorted by (queue, key), so concurrent batches lock
// keys in the same order and cannot deadlock. The commit wakes long-polling
// leases on every queue in the batch.
Enqueue(ctx context.Context, jobs []NewJob) ([]EnqueueResult, error)
// Lease takes up to n runnable jobs, highest priority first. A ttl <= 0
// uses the queue's visibility timeout. A paused queue returns no jobs and
// no error; an unknown queue returns ErrNotFound.
Lease(ctx context.Context, queue string, n int, ttl time.Duration) ([]Job, error)
// Ack marks the leased job completed and keeps its token, so repeating
// the Ack with the same token succeeds (a retry after a lost response).
// The result carries the job's queue and says whether this call changed
// anything (Repeated is true when it did not).
Ack(ctx context.Context, id int64, token uuid.UUID) (AckResult, error)
// Nack fails the current attempt. A job whose attempts have reached
// max_attempts moves to StateDead; otherwise it becomes available again at
// retryAt, or after the store's backoff delay when retryAt is nil. The
// result carries the job's queue and whether it went to StateDead; on an
// error it is the zero value.
Nack(ctx context.Context, id int64, token uuid.UUID, errMsg string, retryAt *time.Time) (NackResult, error)
// Heartbeat extends the lease and returns the new expiry. A ttl <= 0 uses
// the queue's visibility timeout.
Heartbeat(ctx context.Context, id int64, token uuid.UUID, ttl time.Duration) (time.Time, error)
// ReapExpired treats up to limit expired leases as failed attempts and
// returns one ReapedJob per lease it processed (nil on an error or when
// nothing had expired). Like Nack, a job whose attempts have reached
// max_attempts moves to StateDead instead of being retried.
ReapExpired(ctx context.Context, limit int) ([]ReapedJob, error)
// PruneFinished deletes up to limit completed and cancelled jobs that
// finished more than age ago and returns how many it deleted. Like the
// reaper, it is safe to run on every server at once.
PruneFinished(ctx context.Context, age time.Duration, limit int) (int, error)
// PruneDead does the same for dead jobs.
PruneDead(ctx context.Context, age time.Duration, limit int) (int, error)
// GetJob returns ErrNotFound for an unknown job.
GetJob(ctx context.Context, id int64) (Job, error)
// CancelJob moves an available job to StateCancelled and returns it.
// Cancelling a cancelled job returns it unchanged, so a retry is
// harmless. A job in any other state returns ErrWrongState; an unknown
// job, ErrNotFound. Cancelling never makes a job runnable, so it wakes
// no leases. cancelled is true when this call cancelled the job and false
// when it was already cancelled.
CancelJob(ctx context.Context, id int64) (job Job, cancelled bool, err error)
// ListDeadJobs returns up to limit dead jobs of the queue, newest first
// (finished_at, then id, both descending), starting after the cursor; a
// nil cursor starts at the newest. It returns ErrNotFound for an unknown
// queue and ErrInvalid for a limit below 1.
ListDeadJobs(ctx context.Context, queue string, after *DeadCursor, limit int) ([]Job, error)
// RedriveDead makes up to limit dead jobs of the queue available again,
// with attempts reset to 0, run_at now and finished_at cleared, in one
// transaction whose commit wakes long-polling leases. With ids, only
// those jobs are considered and any that aren't dead jobs of this queue
// are ignored; with nil ids, any dead job of the queue. It returns how
// many jobs it redrove. last_error is kept. It returns ErrNotFound for an
// unknown queue and ErrInvalid for a limit below 1.
RedriveDead(ctx context.Context, queue string, ids []int64, limit int) (int, error)
}